From b012a83ee0697a889629007e6d1f1c606baf68b0 Mon Sep 17 00:00:00 2001 From: Andy Killorin <37423245+Speedy6451@users.noreply.github.com> Date: Mon, 3 Feb 2025 14:09:20 -0500 Subject: [PATCH] recv control input on northbridge --- common/src/lib.rs | 2 +- northbridge/src/main.rs | 28 +++++++++++++++++++++++++++- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/common/src/lib.rs b/common/src/lib.rs index f7004cd..3f726d7 100644 --- a/common/src/lib.rs +++ b/common/src/lib.rs @@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize}; pub const BAUDRATE: u32 = 115200; -#[derive(Serialize, Deserialize, Debug)] +#[derive(Serialize, Deserialize, Debug, Clone)] pub enum Command { /// Forward, clockwise Twist(f32,f32), diff --git a/northbridge/src/main.rs b/northbridge/src/main.rs index 62179dd..7ff8c6a 100644 --- a/northbridge/src/main.rs +++ b/northbridge/src/main.rs @@ -4,7 +4,7 @@ use anyhow::{Context, Result}; use common::{Command, Response, BAUDRATE}; use framed_codec::FramedCodec; use futures::{SinkExt, StreamExt}; -use tokio::sync::broadcast; +use tokio::{io::AsyncReadExt, net::{TcpListener, TcpSocket}, sync::{broadcast, watch::{self, Sender}}}; use tokio_serial::SerialPortBuilderExt; use tokio_util::codec::Framed; @@ -24,6 +24,10 @@ async fn main() -> Result<()> { Ok(postcard::from_bytes::(&data.ok().context("decode err")?)?) }); + let (send, commands) = watch::channel(Command::Stop); + + tokio::spawn(control(send)); + println!("starting"); write.send(Command::Enable).await?; @@ -41,7 +45,29 @@ async fn main() -> Result<()> { if let Some(data) = data.sensor_data { let _ = sensor_sender.send(data); } + + write.send(commands.borrow().clone()).await?; } Ok(()) } + +async fn control(sender: Sender) -> Result<()> { + let listener = TcpListener::bind("0.0.0.0:3322").await?; + + let (mut stream, addr) = listener.accept().await?; + + println!("connected to {addr:?}"); + + loop { + let len = stream.read_u32().await?; + let mut buf = vec![0; len as usize]; + stream.read_exact(&mut buf).await?; + + let cmd: Command = postcard::from_bytes(&buf)?; + + println!("recv {cmd:?}"); + + sender.send(cmd)?; + } +}