From 427046239c52b0fa048fb76594df49a63a4f0ffc Mon Sep 17 00:00:00 2001 From: Adrian Bates Date: Sat, 22 Apr 2023 11:13:59 -0400 Subject: [PATCH 1/8] Added stop command to PTZ --- crates/core/src/bc_protocol/ptz.rs | 7 +++++-- src/mqtt/event_cam.rs | 2 ++ src/mqtt/mod.rs | 1 + 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/crates/core/src/bc_protocol/ptz.rs b/crates/core/src/bc_protocol/ptz.rs index c06fee0..247ce3f 100644 --- a/crates/core/src/bc_protocol/ptz.rs +++ b/crates/core/src/bc_protocol/ptz.rs @@ -15,6 +15,8 @@ pub enum Direction { In, /// To zoom the camera Out (may be done with cropping depending on camera model) Out, + /// To stop currently active PTZ command + Stop } impl BcCamera { @@ -32,10 +34,11 @@ impl BcCamera { Direction::Right => "right", Direction::In => { todo!() - } + }, Direction::Out => { todo!() - } + }, + Direction::Stop => "stop" } .to_string(); let send = Bc { diff --git a/src/mqtt/event_cam.rs b/src/mqtt/event_cam.rs index fe0ae26..788f85f 100644 --- a/src/mqtt/event_cam.rs +++ b/src/mqtt/event_cam.rs @@ -37,6 +37,7 @@ pub(crate) enum Direction { Right(f32), In(f32), Out(f32), + Stop(f32) } #[derive(Debug)] @@ -415,6 +416,7 @@ impl<'a> MessageHandler<'a> { Direction::Right(amount) => (BcDirection::Right, amount), Direction::In(amount) => (BcDirection::In, amount), Direction::Out(amount) => (BcDirection::Out, amount), + Direction::Stop(amount) => (BcDirection::Stop, amount) }; if let Err(e) = self.camera.send_ptz(bc_direction, amount).await { error = Some(format!("Failed to send PTZ: {:?}", e)); diff --git a/src/mqtt/mod.rs b/src/mqtt/mod.rs index dcdb2ab..106f2fc 100644 --- a/src/mqtt/mod.rs +++ b/src/mqtt/mod.rs @@ -207,6 +207,7 @@ async fn listen_on_camera(cam_config: Arc, mqtt_config: &MqttConfi "right" => Direction::Right(amount), "in" => Direction::In(amount), "out" => Direction::Out(amount), + "stop" => Direction::Stop(amount), _ => { error!("Unrecongnized PTZ direction"); continue; From 29b47aa44edbae9dbb720979ea3e4cf217c863de Mon Sep 17 00:00:00 2001 From: Adrian Bates Date: Sat, 22 Apr 2023 11:41:45 -0400 Subject: [PATCH 2/8] Changed Unrecognized PTZ Direction error to include unrecognized command --- src/mqtt/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/mqtt/mod.rs b/src/mqtt/mod.rs index 106f2fc..5bd0fd3 100644 --- a/src/mqtt/mod.rs +++ b/src/mqtt/mod.rs @@ -209,7 +209,7 @@ async fn listen_on_camera(cam_config: Arc, mqtt_config: &MqttConfi "out" => Direction::Out(amount), "stop" => Direction::Stop(amount), _ => { - error!("Unrecongnized PTZ direction"); + error!("Unrecognized PTZ direction \"{}\"", direction_txt); continue; } }; From 5ccdc27d377823b3080f305d43a8580be54dc0d3 Mon Sep 17 00:00:00 2001 From: Adrian Bates Date: Tue, 25 Apr 2023 15:49:08 -0400 Subject: [PATCH 3/8] In mod.rs: Removed the ability to send "stop" PTZ command with MQTT Changed the signature of PTZ MQTT commands to (direction amount seconds), where seconds is currently checked and limited to the range 0.0 - 10.0 In event_cam.rs: stop has been removed from event_cam.Direction, and directions now take an additional f32 seconds parameter in Message::PTZ if the intial send_ptz is successful, will sleep for designated seconds and then issue a stop command --- src/mqtt/event_cam.rs | 42 ++++++++++++++++++++------------- src/mqtt/mod.rs | 54 +++++++++++++++++++++++++++---------------- 2 files changed, 60 insertions(+), 36 deletions(-) diff --git a/src/mqtt/event_cam.rs b/src/mqtt/event_cam.rs index 788f85f..80c9cf0 100644 --- a/src/mqtt/event_cam.rs +++ b/src/mqtt/event_cam.rs @@ -9,8 +9,11 @@ use std::sync::Arc; use tokio::{ sync::mpsc::{channel, Receiver, Sender}, task::JoinSet, + time::sleep }; +use core::time::Duration; + #[derive(Debug, Copy, Clone)] pub(crate) enum Messages { Login, @@ -31,13 +34,12 @@ pub(crate) enum Messages { #[derive(Debug, Copy, Clone)] pub(crate) enum Direction { - Up(f32), - Down(f32), - Left(f32), - Right(f32), - In(f32), - Out(f32), - Stop(f32) + Up(f32, f32), + Down(f32, f32), + Left(f32, f32), + Right(f32, f32), + In(f32, f32), + Out(f32, f32) } #[derive(Debug)] @@ -409,20 +411,28 @@ impl<'a> MessageHandler<'a> { } } Messages::Ptz(direction) => { - let (bc_direction, amount) = match direction { - Direction::Up(amount) => (BcDirection::Up, amount), - Direction::Down(amount) => (BcDirection::Down, amount), - Direction::Left(amount) => (BcDirection::Left, amount), - Direction::Right(amount) => (BcDirection::Right, amount), - Direction::In(amount) => (BcDirection::In, amount), - Direction::Out(amount) => (BcDirection::Out, amount), - Direction::Stop(amount) => (BcDirection::Stop, amount) + let (bc_direction, amount, seconds) = match direction { + Direction::Up(amount, seconds) => (BcDirection::Up, amount, seconds), + Direction::Down(amount, seconds) => (BcDirection::Down, amount, seconds), + Direction::Left(amount, seconds) => (BcDirection::Left, amount, seconds), + Direction::Right(amount, seconds) => (BcDirection::Right, amount, seconds), + Direction::In(amount, seconds) => (BcDirection::In, amount, seconds), + Direction::Out(amount, seconds) => (BcDirection::Out, amount, seconds), }; if let Err(e) = self.camera.send_ptz(bc_direction, amount).await { error = Some(format!("Failed to send PTZ: {:?}", e)); "FAIL".to_string() } else { - "OK".to_string() + // sleep for the designated seconds + sleep(Duration::from_secs_f32(seconds)).await; + + // note that amount is not used in the stop command + if let Err(e) = self.camera.send_ptz(BcDirection::Stop, amount).await { + error = Some(format!("Failed to send PTZ: {:?}", e)); + "FAIL".to_string() + } else { + "OK".to_string() + } } } _ => "UNKNOWN COMMAND".to_string(), diff --git a/src/mqtt/mod.rs b/src/mqtt/mod.rs index 5bd0fd3..300814d 100644 --- a/src/mqtt/mod.rs +++ b/src/mqtt/mod.rs @@ -199,28 +199,42 @@ async fn listen_on_camera(cam_config: Arc, mqtt_config: &MqttConfi let mut words = lowercase_message.split_whitespace(); if let Some(direction_txt) = words.next() { let amount = words.next().unwrap_or("32.0"); + let seconds = words.next().unwrap_or("1.0"); if let Ok(amount) = amount.parse::() { - let direction = match direction_txt { - "up" => Direction::Up(amount), - "down" => Direction::Down(amount), - "left" => Direction::Left(amount), - "right" => Direction::Right(amount), - "in" => Direction::In(amount), - "out" => Direction::Out(amount), - "stop" => Direction::Stop(amount), - _ => { - error!("Unrecognized PTZ direction \"{}\"", direction_txt); - continue; - } - }; - reply = Some( - event_cam_sender - .send_message_with_reply(Messages::Ptz(direction)) - .await - .with_context(|| "Failed to send PTZ")?, - ); + if let Ok(seconds) = seconds.parse::() { + + // range checking on seconds so that you can't sleep for 3.4E+38 seconds + match seconds { + x if (0.0..10.0).contains(&x) => seconds, + _ => { + error!("seconds was not a valid number (out of range)"); + continue; + } + }; + + let direction = match direction_txt { + "up" => Direction::Up(amount, seconds), + "down" => Direction::Down(amount, seconds), + "left" => Direction::Left(amount, seconds), + "right" => Direction::Right(amount, seconds), + "in" => Direction::In(amount, seconds), + "out" => Direction::Out(amount, seconds), + _ => { + error!("Unrecognized PTZ direction \"{}\"", direction_txt); + continue; + } + }; + reply = Some( + event_cam_sender + .send_message_with_reply(Messages::Ptz(direction)) + .await + .with_context(|| "Failed to send PTZ")?, + ); + } else { + error!("seconds was not a valid number"); + } } else { - error!("No PTZ direction speed was not a valid number"); + error!("No PTZ direction speed was not a valid number (unrecognized)"); } } else { error!("No PTZ Direction given. Please add up/down/left/right/in/out"); From 03a7e1473ab6cd8a4a2651f468ee9bc6a827f717 Mon Sep 17 00:00:00 2001 From: Adrian Bates Date: Tue, 25 Apr 2023 16:14:55 -0400 Subject: [PATCH 4/8] Fixed mistake in new error message --- src/mqtt/mod.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/mqtt/mod.rs b/src/mqtt/mod.rs index 300814d..b56dc24 100644 --- a/src/mqtt/mod.rs +++ b/src/mqtt/mod.rs @@ -231,10 +231,10 @@ async fn listen_on_camera(cam_config: Arc, mqtt_config: &MqttConfi .with_context(|| "Failed to send PTZ")?, ); } else { - error!("seconds was not a valid number"); + error!("seconds was not a valid number (unrecognized)"); } } else { - error!("No PTZ direction speed was not a valid number (unrecognized)"); + error!("No PTZ direction speed was not a valid number"); } } else { error!("No PTZ Direction given. Please add up/down/left/right/in/out"); From a81924855670053818d41256a02ce2d1fdee61b3 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Sat, 13 May 2023 20:03:08 +0700 Subject: [PATCH 5/8] Rework MQTT to allow async message handelling --- src/mqtt/mod.rs | 377 ++++++++++++++++++++++++---------------------- src/mqtt/mqttc.rs | 1 + 2 files changed, 202 insertions(+), 176 deletions(-) diff --git a/src/mqtt/mod.rs b/src/mqtt/mod.rs index b56dc24..579f198 100644 --- a/src/mqtt/mod.rs +++ b/src/mqtt/mod.rs @@ -118,190 +118,215 @@ async fn listen_on_camera(cam_config: Arc, mqtt_config: &MqttConfi // Listen on mqtt messages and post on camera let camera_name = cam_config.name.clone(); + // When one error is recieved we pass it up async + let (error_send, mut error_recv) = tokio::sync::mpsc::channel::(1); let mqtt_to_cam = async { - while let Ok(msg) = mqtt.poll().await { - tokio::task::yield_now().await; - let mut reply = None; - let mut reply_topic = None; - match msg.as_ref() { - MqttReplyRef { - topic: "control/led", - message: "on", - } => { - reply = Some( - event_cam_sender - .send_message_with_reply(Messages::StatusLedOn) - .await - .with_context(|| "Failed to set camera status light on")?, - ); - } - MqttReplyRef { - topic: "control/led", - message: "off", - } => { - reply = Some( - event_cam_sender - .send_message_with_reply(Messages::StatusLedOff) - .await - .with_context(|| "Failed to set camera status light off")?, - ); - } - MqttReplyRef { - topic: "control/ir", - message: "on", - } => { - reply = Some( - event_cam_sender - .send_message_with_reply(Messages::IRLedOn) - .await - .with_context(|| "Failed to set camera status light on")?, - ); - } - MqttReplyRef { - topic: "control/ir", - message: "off", - } => { - reply = Some( - event_cam_sender - .send_message_with_reply(Messages::IRLedOff) - .await - .with_context(|| "Failed to set camera status light off")?, - ); - } - MqttReplyRef { - topic: "control/ir", - message: "auto", - } => { - reply = Some( - event_cam_sender - .send_message_with_reply(Messages::IRLedAuto) - .await - .with_context(|| "Failed to set camera status light off")?, - ); - } - MqttReplyRef { - topic: "control/reboot", - .. - } => { - reply = Some( - event_cam_sender - .send_message_with_reply(Messages::Reboot) - .await - .with_context(|| "Failed to set camera status light off")?, - ); - } - MqttReplyRef { - topic: "control/ptz", - message, - } => { - let lowercase_message = message.to_lowercase(); - let mut words = lowercase_message.split_whitespace(); - if let Some(direction_txt) = words.next() { - let amount = words.next().unwrap_or("32.0"); - let seconds = words.next().unwrap_or("1.0"); - if let Ok(amount) = amount.parse::() { - if let Ok(seconds) = seconds.parse::() { + // Select to wait on an error (via the channel) or normal poll ops + tokio::select! { + v = async { + // Normal poll operations + while let Ok(msg) = mqtt.poll().await { + tokio::task::yield_now().await; + // Put the reply on it's own async thread so we can safely sleep + // and wait for it to reply in it's own time + let event_cam_sender = event_cam_sender.clone(); + let mqtt_sender_mqtt = mqtt_sender_mqtt.clone(); + let error_send = error_send.clone(); + tokio::task::spawn(async move { + // This is to let us grap the result of all the following (specifically its error) + let result: Result<()> = async { + let mut reply = None; + let mut reply_topic = None; + match msg.as_ref() { + MqttReplyRef { + topic: "control/led", + message: "on", + } => { + reply = Some( + event_cam_sender + .send_message_with_reply(Messages::StatusLedOn) + .await + .with_context(|| "Failed to set camera status light on")?, + ); + } + MqttReplyRef { + topic: "control/led", + message: "off", + } => { + reply = Some( + event_cam_sender + .send_message_with_reply(Messages::StatusLedOff) + .await + .with_context(|| "Failed to set camera status light off")?, + ); + } + MqttReplyRef { + topic: "control/ir", + message: "on", + } => { + reply = Some( + event_cam_sender + .send_message_with_reply(Messages::IRLedOn) + .await + .with_context(|| "Failed to set camera status light on")?, + ); + } + MqttReplyRef { + topic: "control/ir", + message: "off", + } => { + reply = Some( + event_cam_sender + .send_message_with_reply(Messages::IRLedOff) + .await + .with_context(|| "Failed to set camera status light off")?, + ); + } + MqttReplyRef { + topic: "control/ir", + message: "auto", + } => { + reply = Some( + event_cam_sender + .send_message_with_reply(Messages::IRLedAuto) + .await + .with_context(|| "Failed to set camera status light off")?, + ); + } + MqttReplyRef { + topic: "control/reboot", + .. + } => { + reply = Some( + event_cam_sender + .send_message_with_reply(Messages::Reboot) + .await + .with_context(|| "Failed to set camera status light off")?, + ); + } + MqttReplyRef { + topic: "control/ptz", + message, + } => { + let lowercase_message = message.to_lowercase(); + let mut words = lowercase_message.split_whitespace(); + if let Some(direction_txt) = words.next() { + // Target amount to move + let amount = words.next().unwrap_or("32.0"); + if let Ok(amount) = amount.parse::() { + let seconds = amount / 32f32; + // range checking on seconds so that you can't sleep for 3.4E+38 seconds + match seconds { + x if (0.0..10.0).contains(&x) => seconds, + _ => { + error!("seconds was not a valid number (out of range)"); + return Result::<(), Error>::Ok(()); + } + }; - // range checking on seconds so that you can't sleep for 3.4E+38 seconds - match seconds { - x if (0.0..10.0).contains(&x) => seconds, - _ => { - error!("seconds was not a valid number (out of range)"); - continue; + let direction = match direction_txt { + "up" => Direction::Up(amount, seconds), + "down" => Direction::Down(amount, seconds), + "left" => Direction::Left(amount, seconds), + "right" => Direction::Right(amount, seconds), + "in" => Direction::In(amount, seconds), + "out" => Direction::Out(amount, seconds), + "ok" | "fail" => { + return Ok(()); + } + _ => { + error!("Unrecognized PTZ direction \"{}\"", direction_txt); + return Ok(()); + } + }; + reply = Some( + event_cam_sender + .send_message_with_reply(Messages::Ptz(direction)) + .await + .with_context(|| "Failed to send PTZ")?, + ); + } else { + error!("No PTZ direction speed was not a valid number"); + } + } else { + error!("No PTZ Direction given. Please add up/down/left/right/in/out"); } - }; - - let direction = match direction_txt { - "up" => Direction::Up(amount, seconds), - "down" => Direction::Down(amount, seconds), - "left" => Direction::Left(amount, seconds), - "right" => Direction::Right(amount, seconds), - "in" => Direction::In(amount, seconds), - "out" => Direction::Out(amount, seconds), - _ => { - error!("Unrecognized PTZ direction \"{}\"", direction_txt); - continue; - } - }; - reply = Some( - event_cam_sender - .send_message_with_reply(Messages::Ptz(direction)) - .await - .with_context(|| "Failed to send PTZ")?, - ); - } else { - error!("seconds was not a valid number (unrecognized)"); + } + MqttReplyRef { + topic: "control/pir", + message: "on", + } => { + reply = Some( + event_cam_sender + .send_message_with_reply(Messages::PIROn) + .await + .with_context(|| "Failed to set pir on")?, + ); + } + MqttReplyRef { + topic: "control/pir", + message: "off", + } => { + reply = Some( + event_cam_sender + .send_message_with_reply(Messages::PIROff) + .await + .with_context(|| "Failed to set pir off")?, + ); + } + MqttReplyRef { + topic: "query/battery", + .. + } => { + reply = Some( + event_cam_sender + .send_message_with_reply(Messages::Battery) + .await + .with_context(|| "Failed to get battery status")?, + ); + reply_topic = Some("status/battery"); + } + MqttReplyRef { + topic: "query/pir", .. + } => { + reply = Some( + event_cam_sender + .send_message_with_reply(Messages::PIRQuery) + .await + .with_context(|| "Failed to get pir status")?, + ); + reply_topic = Some("status/pir"); + } + _ => {} } - } else { - error!("No PTZ direction speed was not a valid number"); + if let Some(reply) = reply { + if let Some(topic) = reply_topic { + mqtt_sender_mqtt + .send_message(topic, &reply, false) + .await + .with_context(|| "Failed to send Camera reply to Mqtt")?; + } else { + mqtt_sender_mqtt + .send_message(&msg.topic, &reply, false) + .await + .with_context(|| "Failed to send Camera reply to Mqtt")?; + } + } + Ok(()) + }.await; + // If there is an error we pass it to the channel + // this allows for async error handelling + if let Err(e) = result { + let _ = error_send.try_send(e); } - } else { - error!("No PTZ Direction given. Please add up/down/left/right/in/out"); - } + }); } - MqttReplyRef { - topic: "control/pir", - message: "on", - } => { - reply = Some( - event_cam_sender - .send_message_with_reply(Messages::PIROn) - .await - .with_context(|| "Failed to set pir on")?, - ); - } - MqttReplyRef { - topic: "control/pir", - message: "off", - } => { - reply = Some( - event_cam_sender - .send_message_with_reply(Messages::PIROff) - .await - .with_context(|| "Failed to set pir off")?, - ); - } - MqttReplyRef { - topic: "query/battery", - .. - } => { - reply = Some( - event_cam_sender - .send_message_with_reply(Messages::Battery) - .await - .with_context(|| "Failed to get battery status")?, - ); - reply_topic = Some("status/battery"); - } - MqttReplyRef { - topic: "query/pir", .. - } => { - reply = Some( - event_cam_sender - .send_message_with_reply(Messages::PIRQuery) - .await - .with_context(|| "Failed to get pir status")?, - ); - reply_topic = Some("status/pir"); - } - _ => {} - } - if let Some(reply) = reply { - if let Some(topic) = reply_topic { - mqtt_sender_mqtt - .send_message(topic, &reply, false) - .await - .with_context(|| "Failed to send Camera reply to Mqtt")?; - } else { - mqtt_sender_mqtt - .send_message(&msg.topic, &reply, false) - .await - .with_context(|| "Failed to send Camera reply to Mqtt")?; - } - } + Ok(()) + } => v, + // Wait on an error and if we get it we abort + v = error_recv.recv() => Err(v.unwrap()), } - Result::<(), Error>::Ok(()) }; let cam_to_mqtt = async { diff --git a/src/mqtt/mqttc.rs b/src/mqtt/mqttc.rs index 87e85b1..1cb2317 100644 --- a/src/mqtt/mqttc.rs +++ b/src/mqtt/mqttc.rs @@ -43,6 +43,7 @@ struct MqttReciever { name: String, } +#[derive(Clone)] pub(crate) struct MqttSender { client: Arc, name: String, From 72cf358b0c63b2f4a181c534ed87d65b7590b728 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Sun, 14 May 2023 08:46:22 +0700 Subject: [PATCH 6/8] Make mqtt messgae handler cleaner --- crates/core/src/bc_protocol/ptz.rs | 8 +- src/mqtt/event_cam.rs | 34 ++- src/mqtt/mod.rs | 377 +++++++++++++++-------------- 3 files changed, 222 insertions(+), 197 deletions(-) diff --git a/crates/core/src/bc_protocol/ptz.rs b/crates/core/src/bc_protocol/ptz.rs index 247ce3f..3c925d3 100644 --- a/crates/core/src/bc_protocol/ptz.rs +++ b/crates/core/src/bc_protocol/ptz.rs @@ -16,7 +16,7 @@ pub enum Direction { /// To zoom the camera Out (may be done with cropping depending on camera model) Out, /// To stop currently active PTZ command - Stop + Stop, } impl BcCamera { @@ -34,11 +34,11 @@ impl BcCamera { Direction::Right => "right", Direction::In => { todo!() - }, + } Direction::Out => { todo!() - }, - Direction::Stop => "stop" + } + Direction::Stop => "stop", } .to_string(); let send = Bc { diff --git a/src/mqtt/event_cam.rs b/src/mqtt/event_cam.rs index 80c9cf0..91fde9f 100644 --- a/src/mqtt/event_cam.rs +++ b/src/mqtt/event_cam.rs @@ -9,7 +9,7 @@ use std::sync::Arc; use tokio::{ sync::mpsc::{channel, Receiver, Sender}, task::JoinSet, - time::sleep + time::sleep, }; use core::time::Duration; @@ -39,7 +39,7 @@ pub(crate) enum Direction { Left(f32, f32), Right(f32, f32), In(f32, f32), - Out(f32, f32) + Out(f32, f32), } #[derive(Debug)] @@ -412,12 +412,24 @@ impl<'a> MessageHandler<'a> { } Messages::Ptz(direction) => { let (bc_direction, amount, seconds) = match direction { - Direction::Up(amount, seconds) => (BcDirection::Up, amount, seconds), - Direction::Down(amount, seconds) => (BcDirection::Down, amount, seconds), - Direction::Left(amount, seconds) => (BcDirection::Left, amount, seconds), - Direction::Right(amount, seconds) => (BcDirection::Right, amount, seconds), - Direction::In(amount, seconds) => (BcDirection::In, amount, seconds), - Direction::Out(amount, seconds) => (BcDirection::Out, amount, seconds), + Direction::Up(amount, seconds) => { + (BcDirection::Up, amount, seconds) + } + Direction::Down(amount, seconds) => { + (BcDirection::Down, amount, seconds) + } + Direction::Left(amount, seconds) => { + (BcDirection::Left, amount, seconds) + } + Direction::Right(amount, seconds) => { + (BcDirection::Right, amount, seconds) + } + Direction::In(amount, seconds) => { + (BcDirection::In, amount, seconds) + } + Direction::Out(amount, seconds) => { + (BcDirection::Out, amount, seconds) + } }; if let Err(e) = self.camera.send_ptz(bc_direction, amount).await { error = Some(format!("Failed to send PTZ: {:?}", e)); @@ -425,9 +437,11 @@ impl<'a> MessageHandler<'a> { } else { // sleep for the designated seconds sleep(Duration::from_secs_f32(seconds)).await; - + // note that amount is not used in the stop command - if let Err(e) = self.camera.send_ptz(BcDirection::Stop, amount).await { + if let Err(e) = + self.camera.send_ptz(BcDirection::Stop, amount).await + { error = Some(format!("Failed to send PTZ: {:?}", e)); "FAIL".to_string() } else { diff --git a/src/mqtt/mod.rs b/src/mqtt/mod.rs index 579f198..c2e2071 100644 --- a/src/mqtt/mod.rs +++ b/src/mqtt/mod.rs @@ -67,6 +67,11 @@ pub(crate) use event_cam::{Direction, Messages}; use log::*; use mqttc::{Mqtt, MqttReplyRef}; +use self::{ + event_cam::EventCamSender, + mqttc::{MqttReply, MqttSender}, +}; + /// Entry point for the mqtt subcommand /// /// Opt is the command line options @@ -134,187 +139,8 @@ async fn listen_on_camera(cam_config: Arc, mqtt_config: &MqttConfi let mqtt_sender_mqtt = mqtt_sender_mqtt.clone(); let error_send = error_send.clone(); tokio::task::spawn(async move { - // This is to let us grap the result of all the following (specifically its error) - let result: Result<()> = async { - let mut reply = None; - let mut reply_topic = None; - match msg.as_ref() { - MqttReplyRef { - topic: "control/led", - message: "on", - } => { - reply = Some( - event_cam_sender - .send_message_with_reply(Messages::StatusLedOn) - .await - .with_context(|| "Failed to set camera status light on")?, - ); - } - MqttReplyRef { - topic: "control/led", - message: "off", - } => { - reply = Some( - event_cam_sender - .send_message_with_reply(Messages::StatusLedOff) - .await - .with_context(|| "Failed to set camera status light off")?, - ); - } - MqttReplyRef { - topic: "control/ir", - message: "on", - } => { - reply = Some( - event_cam_sender - .send_message_with_reply(Messages::IRLedOn) - .await - .with_context(|| "Failed to set camera status light on")?, - ); - } - MqttReplyRef { - topic: "control/ir", - message: "off", - } => { - reply = Some( - event_cam_sender - .send_message_with_reply(Messages::IRLedOff) - .await - .with_context(|| "Failed to set camera status light off")?, - ); - } - MqttReplyRef { - topic: "control/ir", - message: "auto", - } => { - reply = Some( - event_cam_sender - .send_message_with_reply(Messages::IRLedAuto) - .await - .with_context(|| "Failed to set camera status light off")?, - ); - } - MqttReplyRef { - topic: "control/reboot", - .. - } => { - reply = Some( - event_cam_sender - .send_message_with_reply(Messages::Reboot) - .await - .with_context(|| "Failed to set camera status light off")?, - ); - } - MqttReplyRef { - topic: "control/ptz", - message, - } => { - let lowercase_message = message.to_lowercase(); - let mut words = lowercase_message.split_whitespace(); - if let Some(direction_txt) = words.next() { - // Target amount to move - let amount = words.next().unwrap_or("32.0"); - if let Ok(amount) = amount.parse::() { - let seconds = amount / 32f32; - // range checking on seconds so that you can't sleep for 3.4E+38 seconds - match seconds { - x if (0.0..10.0).contains(&x) => seconds, - _ => { - error!("seconds was not a valid number (out of range)"); - return Result::<(), Error>::Ok(()); - } - }; - - let direction = match direction_txt { - "up" => Direction::Up(amount, seconds), - "down" => Direction::Down(amount, seconds), - "left" => Direction::Left(amount, seconds), - "right" => Direction::Right(amount, seconds), - "in" => Direction::In(amount, seconds), - "out" => Direction::Out(amount, seconds), - "ok" | "fail" => { - return Ok(()); - } - _ => { - error!("Unrecognized PTZ direction \"{}\"", direction_txt); - return Ok(()); - } - }; - reply = Some( - event_cam_sender - .send_message_with_reply(Messages::Ptz(direction)) - .await - .with_context(|| "Failed to send PTZ")?, - ); - } else { - error!("No PTZ direction speed was not a valid number"); - } - } else { - error!("No PTZ Direction given. Please add up/down/left/right/in/out"); - } - } - MqttReplyRef { - topic: "control/pir", - message: "on", - } => { - reply = Some( - event_cam_sender - .send_message_with_reply(Messages::PIROn) - .await - .with_context(|| "Failed to set pir on")?, - ); - } - MqttReplyRef { - topic: "control/pir", - message: "off", - } => { - reply = Some( - event_cam_sender - .send_message_with_reply(Messages::PIROff) - .await - .with_context(|| "Failed to set pir off")?, - ); - } - MqttReplyRef { - topic: "query/battery", - .. - } => { - reply = Some( - event_cam_sender - .send_message_with_reply(Messages::Battery) - .await - .with_context(|| "Failed to get battery status")?, - ); - reply_topic = Some("status/battery"); - } - MqttReplyRef { - topic: "query/pir", .. - } => { - reply = Some( - event_cam_sender - .send_message_with_reply(Messages::PIRQuery) - .await - .with_context(|| "Failed to get pir status")?, - ); - reply_topic = Some("status/pir"); - } - _ => {} - } - if let Some(reply) = reply { - if let Some(topic) = reply_topic { - mqtt_sender_mqtt - .send_message(topic, &reply, false) - .await - .with_context(|| "Failed to send Camera reply to Mqtt")?; - } else { - mqtt_sender_mqtt - .send_message(&msg.topic, &reply, false) - .await - .with_context(|| "Failed to send Camera reply to Mqtt")?; - } - } - Ok(()) - }.await; + // Handle the message and wait for ok/error on this thread + let result: Result<()> = handle_mqtt_message(&msg, event_cam_sender, mqtt_sender_mqtt).await; // If there is an error we pass it to the channel // this allows for async error handelling if let Err(e) = result { @@ -324,8 +150,8 @@ async fn listen_on_camera(cam_config: Arc, mqtt_config: &MqttConfi } Ok(()) } => v, - // Wait on an error and if we get it we abort - v = error_recv.recv() => Err(v.unwrap()), + // Wait on any error from any of the error channels and if we get it we abort + v = error_recv.recv() => v.map(Err).unwrap_or_else(|| Err(anyhow!("Listen on camera error channel closed"))), } }; @@ -369,3 +195,188 @@ async fn listen_on_camera(cam_config: Arc, mqtt_config: &MqttConfi Ok(()) } + +async fn handle_mqtt_message( + msg: &MqttReply, + event_cam_sender: EventCamSender, + mqtt_sender_mqtt: MqttSender, +) -> Result<()> { + let mut reply = None; + let mut reply_topic = None; + match msg.as_ref() { + MqttReplyRef { + topic: "control/led", + message: "on", + } => { + reply = Some( + event_cam_sender + .send_message_with_reply(Messages::StatusLedOn) + .await + .with_context(|| "Failed to set camera status light on")?, + ); + } + MqttReplyRef { + topic: "control/led", + message: "off", + } => { + reply = Some( + event_cam_sender + .send_message_with_reply(Messages::StatusLedOff) + .await + .with_context(|| "Failed to set camera status light off")?, + ); + } + MqttReplyRef { + topic: "control/ir", + message: "on", + } => { + reply = Some( + event_cam_sender + .send_message_with_reply(Messages::IRLedOn) + .await + .with_context(|| "Failed to set camera status light on")?, + ); + } + MqttReplyRef { + topic: "control/ir", + message: "off", + } => { + reply = Some( + event_cam_sender + .send_message_with_reply(Messages::IRLedOff) + .await + .with_context(|| "Failed to set camera status light off")?, + ); + } + MqttReplyRef { + topic: "control/ir", + message: "auto", + } => { + reply = Some( + event_cam_sender + .send_message_with_reply(Messages::IRLedAuto) + .await + .with_context(|| "Failed to set camera status light off")?, + ); + } + MqttReplyRef { + topic: "control/reboot", + .. + } => { + reply = Some( + event_cam_sender + .send_message_with_reply(Messages::Reboot) + .await + .with_context(|| "Failed to set camera status light off")?, + ); + } + MqttReplyRef { + topic: "control/ptz", + message, + } => { + let lowercase_message = message.to_lowercase(); + let mut words = lowercase_message.split_whitespace(); + if let Some(direction_txt) = words.next() { + // Target amount to move + let amount = words.next().unwrap_or("32.0"); + if let Ok(amount) = amount.parse::() { + let seconds = amount / 32f32; + // range checking on seconds so that you can't sleep for 3.4E+38 seconds + match seconds { + x if (0.0..10.0).contains(&x) => seconds, + _ => { + error!("seconds was not a valid number (out of range)"); + return Ok(()); + } + }; + + let direction = match direction_txt { + "up" => Direction::Up(amount, seconds), + "down" => Direction::Down(amount, seconds), + "left" => Direction::Left(amount, seconds), + "right" => Direction::Right(amount, seconds), + "in" => Direction::In(amount, seconds), + "out" => Direction::Out(amount, seconds), + "ok" | "fail" => { + return Ok(()); + } + _ => { + error!("Unrecognized PTZ direction \"{}\"", direction_txt); + return Ok(()); + } + }; + reply = Some( + event_cam_sender + .send_message_with_reply(Messages::Ptz(direction)) + .await + .with_context(|| "Failed to send PTZ")?, + ); + } else { + error!("No PTZ direction speed was not a valid number"); + } + } else { + error!("No PTZ Direction given. Please add up/down/left/right/in/out"); + } + } + MqttReplyRef { + topic: "control/pir", + message: "on", + } => { + reply = Some( + event_cam_sender + .send_message_with_reply(Messages::PIROn) + .await + .with_context(|| "Failed to set pir on")?, + ); + } + MqttReplyRef { + topic: "control/pir", + message: "off", + } => { + reply = Some( + event_cam_sender + .send_message_with_reply(Messages::PIROff) + .await + .with_context(|| "Failed to set pir off")?, + ); + } + MqttReplyRef { + topic: "query/battery", + .. + } => { + reply = Some( + event_cam_sender + .send_message_with_reply(Messages::Battery) + .await + .with_context(|| "Failed to get battery status")?, + ); + reply_topic = Some("status/battery"); + } + MqttReplyRef { + topic: "query/pir", .. + } => { + reply = Some( + event_cam_sender + .send_message_with_reply(Messages::PIRQuery) + .await + .with_context(|| "Failed to get pir status")?, + ); + reply_topic = Some("status/pir"); + } + _ => {} + } + if let Some(reply) = reply { + if let Some(topic) = reply_topic { + mqtt_sender_mqtt + .send_message(topic, &reply, false) + .await + .with_context(|| "Failed to send Camera reply to Mqtt")?; + } else { + mqtt_sender_mqtt + .send_message(&msg.topic, &reply, false) + .await + .with_context(|| "Failed to send Camera reply to Mqtt")?; + } + } + Ok(()) +} From d9600d060798677ea3954e0214896716f48bb370 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Sun, 14 May 2023 10:40:46 +0700 Subject: [PATCH 7/8] Filter out OK/FAIL replies --- src/mqtt/mod.rs | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/mqtt/mod.rs b/src/mqtt/mod.rs index c2e2071..15e4ab0 100644 --- a/src/mqtt/mod.rs +++ b/src/mqtt/mod.rs @@ -204,6 +204,16 @@ async fn handle_mqtt_message( let mut reply = None; let mut reply_topic = None; match msg.as_ref() { + MqttReplyRef { + topic: _, + message: "OK", + } + | MqttReplyRef { + topic: _, + message: "FAIL", + } => { + // Do nothing for the success/fail replies + } MqttReplyRef { topic: "control/led", message: "on", @@ -297,9 +307,6 @@ async fn handle_mqtt_message( "right" => Direction::Right(amount, seconds), "in" => Direction::In(amount, seconds), "out" => Direction::Out(amount, seconds), - "ok" | "fail" => { - return Ok(()); - } _ => { error!("Unrecognized PTZ direction \"{}\"", direction_txt); return Ok(()); From 2d1ccf518a765b6328feadced536c67cb592c590 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Sun, 14 May 2023 10:45:34 +0700 Subject: [PATCH 8/8] Clippy fixes --- crates/core/src/bc_protocol/connection/udpsource.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/core/src/bc_protocol/connection/udpsource.rs b/crates/core/src/bc_protocol/connection/udpsource.rs index cb35b4b..d22c884 100644 --- a/crates/core/src/bc_protocol/connection/udpsource.rs +++ b/crates/core/src/bc_protocol/connection/udpsource.rs @@ -296,7 +296,7 @@ impl Stream for UdpPayloadSource { fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let camera_addr = self.inner.addr; - let mut this = self.get_mut(); + let this = self.get_mut(); match this.state { State::Normal => { // this.state = State::YieldNow; @@ -417,7 +417,7 @@ impl Sink> for UdpPayloadSource { } } fn start_send(self: Pin<&mut Self>, item: Vec) -> std::result::Result<(), Self::Error> { - let mut this = self.get_mut(); + let this = self.get_mut(); for chunk in item.chunks(MTU - UDPDATA_HEADER_SIZE) { let udp_data = UdpData { connection_id: this.camera_id, @@ -487,7 +487,7 @@ impl Sink> for UdpPayloadSource { self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll> { - let mut this = self.get_mut(); + let this = self.get_mut(); if let State::Closed = this.state { return Poll::Ready(Ok(())); }