From 72cf358b0c63b2f4a181c534ed87d65b7590b728 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Sun, 14 May 2023 08:46:22 +0700 Subject: [PATCH] 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(()) +}