diff --git a/interface/src/main.rs b/interface/src/main.rs index 05ec97f..cc73fc2 100644 --- a/interface/src/main.rs +++ b/interface/src/main.rs @@ -1,12 +1,12 @@ #![feature(iter_collect_into)] -use std::{thread::sleep, time::Duration}; +use std::{result, thread::sleep, time::Duration}; use anyhow::{Context, Ok, Result}; use common::{ControlPacket, TelemetryPacket}; use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; use pitch_detection::{detector::{mcleod::McLeodDetector, PitchDetector}, utils}; use rust_music_theory::note::{Note, NoteLetter, Pitch, Tuning}; -use tokio::{io::{AsyncReadExt, AsyncWriteExt, BufWriter, WriteHalf}, net::{tcp::{OwnedReadHalf, OwnedWriteHalf}, TcpStream}, sync::mpsc}; +use tokio::{io::{AsyncReadExt, AsyncWriteExt, BufWriter, WriteHalf}, net::{tcp::{OwnedReadHalf, OwnedWriteHalf}, TcpStream}, sync::mpsc, time::timeout}; fn main() -> Result<()> { // assumes pulseaudio system with f32 samples and 2204 sample packets @@ -77,10 +77,17 @@ async fn telemetry_handler(mut telem: OwnedReadHalf) -> Result<()> { async fn controller(mut notes: mpsc::Receiver<(Option>, f32)>, controller: OwnedWriteHalf) -> Result<()> { let mut controller = BufWriter::new(controller); + send_packet(&mut controller, ControlPacket::Arm(true)).await?; + println!("armed flipper"); loop { let mut control = ControlPacket::Stop; - let (note,vol) = notes.recv().await.context("channel closed")?; + let result::Result::Ok(note) = timeout(Duration::from_millis(95), notes.recv()).await else { + send_packet(&mut controller, ControlPacket::Stop).await?; + continue; + }; + + let (note,vol) = note.context("channel closed")?; if let Some(note) = note { //dbg!(note.frequency); //dbg!(note.clarity); @@ -122,10 +129,15 @@ async fn controller(mut notes: mpsc::Receiver<(Option = postcard::to_vec(&control)?; - controller.write_u32(control.len() as u32).await?; - controller.write_all(&control).await?; - controller.flush().await?; + send_packet(&mut controller, control).await?; } } } + +async fn send_packet(controller: &mut BufWriter, control: ControlPacket) -> Result<(), anyhow::Error> { + let control: heapless::Vec = postcard::to_vec(&control)?; + controller.write_u32(control.len() as u32).await?; + controller.write_all(&control).await?; + controller.flush().await?; + Ok(()) +}