From 1f8296dd01133e5e027254fdd7aba483eee77f3f Mon Sep 17 00:00:00 2001 From: Kevin David Date: Tue, 24 Jan 2023 22:38:00 -0500 Subject: [PATCH 01/10] WIP: Add support for floodlight control over MQTT --- .gitignore | 3 + .vscode/launch.json | 18 +++ crates/core/src/bc/model.rs | 5 + crates/core/src/bc/xml.rs | 49 ++++++++ crates/core/src/bc_protocol.rs | 1 + .../core/src/bc_protocol/floodlight_status.rs | 110 ++++++++++++++++++ src/mqtt/event_cam.rs | 20 ++++ src/mqtt/mod.rs | 16 +++ 8 files changed, 222 insertions(+) create mode 100644 .vscode/launch.json create mode 100644 crates/core/src/bc_protocol/floodlight_status.rs diff --git a/.gitignore b/.gitignore index 78aa81c..4780ea9 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,6 @@ # Committing IntelliJ project files is a violation of intergalactic law .idea/ + +# We prefer to keep .vscode files outside the repo +.vscode/ \ No newline at end of file diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..945cf95 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,18 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "type": "lldb", + "request": "launch", + "name": "Debug", + "program": "${workspaceRoot}/target/debug/${workspaceRootFolderName}", + "args": ["mqtt", "--config", "target/config.toml"], + "cwd": "${workspaceRoot}", + "sourceLanguages": [ + "rust" + ], + "env": { + "RUST_LOG": "debug" + } + } + ]} \ No newline at end of file diff --git a/crates/core/src/bc/model.rs b/crates/core/src/bc/model.rs index d7de246..584cfc5 100644 --- a/crates/core/src/bc/model.rs +++ b/crates/core/src/bc/model.rs @@ -46,6 +46,11 @@ pub const MSG_ID_GET_LED_STATUS: u32 = 208; pub const MSG_ID_SET_LED_STATUS: u32 = 209; /// UDP Keep alive pub const MSG_ID_UDP_KEEP_ALIVE: u32 = 234; +/// Manual Floodlight Control +pub const MSG_ID_FLOODLIGHT_MANUAL: u32 = 288; +/// Floodlight status report from the camera +pub const MSG_ID_FLOODLIGHT_STATUS_LIST: u32 = 291; + /// An empty password in legacy format pub const EMPTY_LEGACY_PASSWORD: &str = diff --git a/crates/core/src/bc/xml.rs b/crates/core/src/bc/xml.rs index cd12fa2..fe2e74f 100644 --- a/crates/core/src/bc/xml.rs +++ b/crates/core/src/bc/xml.rs @@ -76,6 +76,12 @@ pub struct BcXml { /// Sent to move the camera #[yaserde(rename = "PtzControl")] pub ptz_control: Option, + /// Sent to manually control the floodlight + #[yaserde(rename = "FloodlightManual")] + pub floodlight_manual: Option, + /// Received when the floodlight status is updated + #[yaserde(rename = "FloodlightStatusList")] + pub floodlight_status_list: Option, } impl BcXml { @@ -312,6 +318,49 @@ pub struct LedState { pub light_state: String, } + +/// FloodlightStatus xml +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct FloodlightStatus { + /// XML Version + #[yaserde(attribute)] + pub version: String, + /// Channel ID of floodlight + #[yaserde(rename = "channel")] + pub channel_id: u8, + /// On or off + #[yaserde(rename = "status")] + pub status: u8, +} + +/// FloodlightStatusList xml +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct FloodlightStatusList { + /// XML Version + #[yaserde(attribute)] + pub version: String, + /// List of events + #[yaserde(rename = "FloodlightStatusList")] + pub floodlight_status_list: Vec, +} + +/// FloodlightManual xml +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct FloodlightManual { + /// XML Version + #[yaserde(attribute)] + pub version: String, + /// Channel ID of floodlight + #[yaserde(rename = "channelId")] + pub channel_id: u8, + /// On or off + #[yaserde(rename = "status")] + pub status: u8, + /// How long the manual control should apply for + pub duration: u16, +} + + /// rfAlarmCfg xml #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] pub struct RfAlarmCfg { diff --git a/crates/core/src/bc_protocol.rs b/crates/core/src/bc_protocol.rs index d3e86ba..22f7e1e 100644 --- a/crates/core/src/bc_protocol.rs +++ b/crates/core/src/bc_protocol.rs @@ -11,6 +11,7 @@ use Md5Trunc::*; mod connection; mod errors; +mod floodlight_status; mod ledstate; mod login; mod logout; diff --git a/crates/core/src/bc_protocol/floodlight_status.rs b/crates/core/src/bc_protocol/floodlight_status.rs new file mode 100644 index 0000000..508ce4c --- /dev/null +++ b/crates/core/src/bc_protocol/floodlight_status.rs @@ -0,0 +1,110 @@ +use super::{BcCamera, Error, Result, RX_TIMEOUT}; +use crate::bc::{model::*, xml::*}; + +impl BcCamera { + /// Get the [FloodlightStatusList] xml which contains the Floodlist status of the camera + pub fn get_floodlight_status(&self) -> Result { + let connection = self.get_connection(); + let msg_num = self.new_message_num(); + let sub_get = connection.subscribe(msg_num)?; + let get = Bc { + meta: BcMeta { + msg_id: MSG_ID_FLOODLIGHT_STATUS_LIST, + channel_id: self.channel_id, + msg_num, + response_code: 0, + stream_type: 0, + class: 0x6414, + }, + body: BcBody::ModernMsg(ModernMsg { + extension: Some(Extension { + channel_id: Some(self.channel_id), + ..Default::default() + }), + payload: None, + }), + }; + + sub_get.send(get)?; + let msg = sub_get.rx.recv_timeout(RX_TIMEOUT)?; + if msg.meta.response_code != 200 { + return Err(Error::CameraServiceUnavaliable); + } + + if let BcBody::ModernMsg(ModernMsg { + payload: + Some(BcPayloads::BcXml(BcXml { + floodlight_status_list: Some(floodlight_status_list), + .. + })), + .. + }) = msg.body + { + Ok(floodlight_status_list) + } else { + Err(Error::UnintelligibleReply { + reply: Box::new(msg), + why: "Expected FloodlightStatusList xml but it was not recieved", + }) + } + } + + /// Set the floodlight status using the [FloodlightManual] xml + pub fn set_floodlight_manual(&self, floodlight_manual: FloodlightManual) -> Result<()> { + let connection = self.get_connection(); + + let msg_num = self.new_message_num(); + let sub_set = connection.subscribe(msg_num)?; + + let get = Bc { + meta: BcMeta { + msg_id: MSG_ID_FLOODLIGHT_MANUAL, + channel_id: self.channel_id, + msg_num, + response_code: 0, + stream_type: 0, + class: 0x6414, + }, + body: BcBody::ModernMsg(ModernMsg { + extension: Some(Extension { + channel_id: Some(self.channel_id), + ..Default::default() + }), + payload: Some(BcPayloads::BcXml(BcXml { + floodlight_manual: Some(floodlight_manual), + ..Default::default() + })), + }), + }; + + sub_set.send(get)?; + let msg = sub_set.rx.recv_timeout(RX_TIMEOUT)?; + + if let BcMeta { + response_code: 200, .. + } = msg.meta + { + Ok(()) + } else { + Err(Error::UnintelligibleReply { + reply: Box::new(msg), + why: "The camera did not accept the Floodlight manual state", + }) + } + } + + /// Set the floodlight status for a duration + pub fn floodlight_light_set(&self, state: bool, duration: u16) -> Result<()> { + let mut floodlight_state = self.get_floodlight_status()?; + for floodlight in floodlight_state.floodlight_status_list.iter_mut() { + if floodlight.channel_id == self.channel_id { + self.set_floodlight_manual(FloodlightManual { version: "1".to_string(), channel_id: floodlight.channel_id, status: match state { + true => 1, + false => 0, + } , duration: duration })?; + } + } + + Ok(()) + } +} diff --git a/src/mqtt/event_cam.rs b/src/mqtt/event_cam.rs index 05be67c..657095c 100644 --- a/src/mqtt/event_cam.rs +++ b/src/mqtt/event_cam.rs @@ -15,6 +15,8 @@ pub(crate) enum Messages { MotionStop, MotionStart, Reboot, + FloodlightOn, + FloodlightOff, StatusLedOn, StatusLedOff, IRLedOn, @@ -263,6 +265,24 @@ impl MessageHandler { "OK".to_string() } } + Messages::FloodlightOn => { + if self.camera.floodlight_light_set(true, 180).is_err() { + error!("Failed to turn on the floodlight light"); + self.abort(); + "FAIL".to_string() + } else { + "OK".to_string() + } + } + Messages::FloodlightOff => { + if self.camera.floodlight_light_set(false, 180).is_err() { + error!("Failed to turn off the floodlight light"); + self.abort(); + "FAIL".to_string() + } else { + "OK".to_string() + } + } Messages::StatusLedOn => { if self.camera.led_light_set(true).is_err() { error!("Failed to turn on the status light"); diff --git a/src/mqtt/mod.rs b/src/mqtt/mod.rs index dd3968f..c2d331f 100644 --- a/src/mqtt/mod.rs +++ b/src/mqtt/mod.rs @@ -148,6 +148,22 @@ fn listen_on_camera( while app.running(&format!("app: {}", cam_config.name)) { if let Ok(msg) = mqtt.poll() { match msg.as_ref() { + MqttReplyRef { + topic: "control/floodlight", + message: "on", + } => { + if event_cam.send_message(Messages::FloodlightOn).is_err() { + error!("Failed to set floodlight on"); + } + } + MqttReplyRef { + topic: "control/floodlight", + message: "off", + } => { + if event_cam.send_message(Messages::FloodlightOff).is_err() { + error!("Failed to set floodlight off"); + } + } MqttReplyRef { topic: "control/led", message: "on", From 8cbaf06cde3259cbd57720706ebaca99a1d4f6dd Mon Sep 17 00:00:00 2001 From: Kevin David Date: Tue, 24 Jan 2023 23:14:11 -0500 Subject: [PATCH 02/10] Satisify rustfmt --- crates/core/src/bc/model.rs | 1 - crates/core/src/bc/xml.rs | 2 -- crates/core/src/bc_protocol/floodlight_status.rs | 15 ++++++++++----- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/crates/core/src/bc/model.rs b/crates/core/src/bc/model.rs index 584cfc5..28b143c 100644 --- a/crates/core/src/bc/model.rs +++ b/crates/core/src/bc/model.rs @@ -51,7 +51,6 @@ pub const MSG_ID_FLOODLIGHT_MANUAL: u32 = 288; /// Floodlight status report from the camera pub const MSG_ID_FLOODLIGHT_STATUS_LIST: u32 = 291; - /// An empty password in legacy format pub const EMPTY_LEGACY_PASSWORD: &str = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"; diff --git a/crates/core/src/bc/xml.rs b/crates/core/src/bc/xml.rs index fe2e74f..a6e013a 100644 --- a/crates/core/src/bc/xml.rs +++ b/crates/core/src/bc/xml.rs @@ -318,7 +318,6 @@ pub struct LedState { pub light_state: String, } - /// FloodlightStatus xml #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] pub struct FloodlightStatus { @@ -360,7 +359,6 @@ pub struct FloodlightManual { pub duration: u16, } - /// rfAlarmCfg xml #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] pub struct RfAlarmCfg { diff --git a/crates/core/src/bc_protocol/floodlight_status.rs b/crates/core/src/bc_protocol/floodlight_status.rs index 508ce4c..13e1894 100644 --- a/crates/core/src/bc_protocol/floodlight_status.rs +++ b/crates/core/src/bc_protocol/floodlight_status.rs @@ -98,13 +98,18 @@ impl BcCamera { let mut floodlight_state = self.get_floodlight_status()?; for floodlight in floodlight_state.floodlight_status_list.iter_mut() { if floodlight.channel_id == self.channel_id { - self.set_floodlight_manual(FloodlightManual { version: "1".to_string(), channel_id: floodlight.channel_id, status: match state { - true => 1, - false => 0, - } , duration: duration })?; + self.set_floodlight_manual(FloodlightManual { + version: "1".to_string(), + channel_id: floodlight.channel_id, + status: match state { + true => 1, + false => 0, + }, + duration: duration, + })?; } } - + Ok(()) } } From 6be7ac2d1445da130d74767b29a68daed6bff892 Mon Sep 17 00:00:00 2001 From: Kevin David Date: Tue, 24 Jan 2023 23:46:40 -0500 Subject: [PATCH 03/10] Remove .vscode, improve logging --- .vscode/launch.json | 18 ------------------ src/mqtt/event_cam.rs | 10 ++++++---- src/mqtt/mod.rs | 10 ++++++---- 3 files changed, 12 insertions(+), 26 deletions(-) delete mode 100644 .vscode/launch.json diff --git a/.vscode/launch.json b/.vscode/launch.json deleted file mode 100644 index 945cf95..0000000 --- a/.vscode/launch.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "version": "0.2.0", - "configurations": [ - { - "type": "lldb", - "request": "launch", - "name": "Debug", - "program": "${workspaceRoot}/target/debug/${workspaceRootFolderName}", - "args": ["mqtt", "--config", "target/config.toml"], - "cwd": "${workspaceRoot}", - "sourceLanguages": [ - "rust" - ], - "env": { - "RUST_LOG": "debug" - } - } - ]} \ No newline at end of file diff --git a/src/mqtt/event_cam.rs b/src/mqtt/event_cam.rs index 657095c..ed24c90 100644 --- a/src/mqtt/event_cam.rs +++ b/src/mqtt/event_cam.rs @@ -266,8 +266,9 @@ impl MessageHandler { } } Messages::FloodlightOn => { - if self.camera.floodlight_light_set(true, 180).is_err() { - error!("Failed to turn on the floodlight light"); + let res = self.camera.floodlight_light_set(true, 180); + if res.is_err() { + error!("Failed to turn on the floodlight light: {:?}", res.err()); self.abort(); "FAIL".to_string() } else { @@ -275,8 +276,9 @@ impl MessageHandler { } } Messages::FloodlightOff => { - if self.camera.floodlight_light_set(false, 180).is_err() { - error!("Failed to turn off the floodlight light"); + let res = self.camera.floodlight_light_set(false, 180); + if res.is_err() { + error!("Failed to turn off the floodlight light: {:?}", res.err()); self.abort(); "FAIL".to_string() } else { diff --git a/src/mqtt/mod.rs b/src/mqtt/mod.rs index c2d331f..bb6d9b5 100644 --- a/src/mqtt/mod.rs +++ b/src/mqtt/mod.rs @@ -152,16 +152,18 @@ fn listen_on_camera( topic: "control/floodlight", message: "on", } => { - if event_cam.send_message(Messages::FloodlightOn).is_err() { - error!("Failed to set floodlight on"); + let res = event_cam.send_message(Messages::FloodlightOn); + if res.is_err() { + error!("Failed to set floodlight on: {:?}", res.err()); } } MqttReplyRef { topic: "control/floodlight", message: "off", } => { - if event_cam.send_message(Messages::FloodlightOff).is_err() { - error!("Failed to set floodlight off"); + let res = event_cam.send_message(Messages::FloodlightOff); + if res.is_err() { + error!("Failed to set floodlight off: {:?}", res.err()); } } MqttReplyRef { From 355cd4846ab4af8674492006d9073f58b86c9ecc Mon Sep 17 00:00:00 2001 From: Kevin David Date: Wed, 25 Jan 2023 22:52:45 -0500 Subject: [PATCH 04/10] Remove incorrect code for now --- .../core/src/bc_protocol/floodlight_status.rs | 78 +++---------------- src/mqtt/event_cam.rs | 4 +- 2 files changed, 12 insertions(+), 70 deletions(-) diff --git a/crates/core/src/bc_protocol/floodlight_status.rs b/crates/core/src/bc_protocol/floodlight_status.rs index 13e1894..4917e81 100644 --- a/crates/core/src/bc_protocol/floodlight_status.rs +++ b/crates/core/src/bc_protocol/floodlight_status.rs @@ -2,55 +2,8 @@ use super::{BcCamera, Error, Result, RX_TIMEOUT}; use crate::bc::{model::*, xml::*}; impl BcCamera { - /// Get the [FloodlightStatusList] xml which contains the Floodlist status of the camera - pub fn get_floodlight_status(&self) -> Result { - let connection = self.get_connection(); - let msg_num = self.new_message_num(); - let sub_get = connection.subscribe(msg_num)?; - let get = Bc { - meta: BcMeta { - msg_id: MSG_ID_FLOODLIGHT_STATUS_LIST, - channel_id: self.channel_id, - msg_num, - response_code: 0, - stream_type: 0, - class: 0x6414, - }, - body: BcBody::ModernMsg(ModernMsg { - extension: Some(Extension { - channel_id: Some(self.channel_id), - ..Default::default() - }), - payload: None, - }), - }; - - sub_get.send(get)?; - let msg = sub_get.rx.recv_timeout(RX_TIMEOUT)?; - if msg.meta.response_code != 200 { - return Err(Error::CameraServiceUnavaliable); - } - - if let BcBody::ModernMsg(ModernMsg { - payload: - Some(BcPayloads::BcXml(BcXml { - floodlight_status_list: Some(floodlight_status_list), - .. - })), - .. - }) = msg.body - { - Ok(floodlight_status_list) - } else { - Err(Error::UnintelligibleReply { - reply: Box::new(msg), - why: "Expected FloodlightStatusList xml but it was not recieved", - }) - } - } - /// Set the floodlight status using the [FloodlightManual] xml - pub fn set_floodlight_manual(&self, floodlight_manual: FloodlightManual) -> Result<()> { + pub fn set_floodlight_manual(&self, state: bool, duration: u16) -> Result<()> { let connection = self.get_connection(); let msg_num = self.new_message_num(); @@ -71,7 +24,15 @@ impl BcCamera { ..Default::default() }), payload: Some(BcPayloads::BcXml(BcXml { - floodlight_manual: Some(floodlight_manual), + floodlight_manual: Some(FloodlightManual { + version: "1".to_string(), + channel_id: self.channel_id, + status: match state { + true => 1, + false => 0, + }, + duration: duration, + }), ..Default::default() })), }), @@ -93,23 +54,4 @@ impl BcCamera { } } - /// Set the floodlight status for a duration - pub fn floodlight_light_set(&self, state: bool, duration: u16) -> Result<()> { - let mut floodlight_state = self.get_floodlight_status()?; - for floodlight in floodlight_state.floodlight_status_list.iter_mut() { - if floodlight.channel_id == self.channel_id { - self.set_floodlight_manual(FloodlightManual { - version: "1".to_string(), - channel_id: floodlight.channel_id, - status: match state { - true => 1, - false => 0, - }, - duration: duration, - })?; - } - } - - Ok(()) - } } diff --git a/src/mqtt/event_cam.rs b/src/mqtt/event_cam.rs index ed24c90..7d654e8 100644 --- a/src/mqtt/event_cam.rs +++ b/src/mqtt/event_cam.rs @@ -266,7 +266,7 @@ impl MessageHandler { } } Messages::FloodlightOn => { - let res = self.camera.floodlight_light_set(true, 180); + let res = self.camera.set_floodlight_manual(true, 180); if res.is_err() { error!("Failed to turn on the floodlight light: {:?}", res.err()); self.abort(); @@ -276,7 +276,7 @@ impl MessageHandler { } } Messages::FloodlightOff => { - let res = self.camera.floodlight_light_set(false, 180); + let res = self.camera.set_floodlight_manual(false, 180); if res.is_err() { error!("Failed to turn off the floodlight light: {:?}", res.err()); self.abort(); From be10aaeed5b12837f9fccdb763efd0126ba27518 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Fri, 19 May 2023 13:15:31 +0700 Subject: [PATCH 05/10] Add floodlight status and keep alive pings --- crates/core/src/bc/xml.rs | 15 +++- .../core/src/bc_protocol/floodlight_status.rs | 35 ++++++++ crates/core/src/bc_protocol/link.rs | 50 +++++++++++ src/mqtt/event_cam.rs | 82 ++++++++++++++++++- src/mqtt/mod.rs | 22 +++++ 5 files changed, 198 insertions(+), 6 deletions(-) create mode 100644 crates/core/src/bc_protocol/link.rs diff --git a/crates/core/src/bc/xml.rs b/crates/core/src/bc/xml.rs index 977551c..5e65cff 100644 --- a/crates/core/src/bc/xml.rs +++ b/crates/core/src/bc/xml.rs @@ -91,6 +91,9 @@ pub struct BcXml { /// Recieved on request for a users persmissions/capabilitoes #[yaserde(rename = "AbilityInfo")] pub ability_info: Option, + /// Recieved on request for a link type + #[yaserde(rename = "LinkType")] + pub link_type: Option, } impl BcXml { @@ -332,7 +335,7 @@ pub struct LedState { } /// FloodlightStatus xml -#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)] pub struct FloodlightStatus { /// XML Version #[yaserde(attribute)] @@ -346,7 +349,7 @@ pub struct FloodlightStatus { } /// FloodlightStatusList xml -#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)] pub struct FloodlightStatusList { /// XML Version #[yaserde(attribute)] @@ -661,6 +664,14 @@ pub struct AbilityInfoSubModule { pub ability_value: String, } +/// The Link Type contains the type of connection present +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct LinkType { + #[yaserde(rename = "type")] + /// Type of connection known values `"LAN"` + link_type: String, +} + /// Convience function to return the xml version used throughout the library pub fn xml_ver() -> String { "1.1".to_string() diff --git a/crates/core/src/bc_protocol/floodlight_status.rs b/crates/core/src/bc_protocol/floodlight_status.rs index 8ec4c0e..f95e399 100644 --- a/crates/core/src/bc_protocol/floodlight_status.rs +++ b/crates/core/src/bc_protocol/floodlight_status.rs @@ -1,7 +1,42 @@ +use tokio::sync::mpsc::{channel, Receiver}; + use super::{BcCamera, Error, Result}; use crate::bc::{model::*, xml::*}; impl BcCamera { + /// Listen on the flood light update messages and return their XMLs + pub async fn listen_on_flightlight(&self) -> Result> { + let (tx, rx) = channel(3); + let connection = self.get_connection(); + connection + .handle_msg(MSG_ID_FLOODLIGHT_STATUS_LIST, move |bc| { + if let Bc { + meta: + BcMeta { + msg_id: MSG_ID_FLOODLIGHT_STATUS_LIST, + .. + }, + body: + BcBody::ModernMsg(ModernMsg { + payload: + Some(BcPayloads::BcXml(BcXml { + floodlight_status_list: Some(list), + .. + })), + .. + }), + } = bc + { + let send_this: FloodlightStatusList = list.clone(); + let _ = tx.blocking_send(send_this); + } + None + }) + .await?; + + Ok(rx) + } + /// Set the floodlight status using the [FloodlightManual] xml pub async fn set_floodlight_manual(&self, state: bool, duration: u16) -> Result<()> { let connection = self.get_connection(); diff --git a/crates/core/src/bc_protocol/link.rs b/crates/core/src/bc_protocol/link.rs new file mode 100644 index 0000000..f37fdaa --- /dev/null +++ b/crates/core/src/bc_protocol/link.rs @@ -0,0 +1,50 @@ +use super::{BcCamera, Error, Result}; +use crate::bc::{model::*, xml::*}; + +impl BcCamera { + /// Get the [LinkType] xml which contains the connection status of the camera + /// + /// This is the same as `ping()` but with the return type + pub async fn get_linktype(&self) -> Result { + let connection = self.get_connection(); + let msg_num = self.new_message_num(); + let mut sub_get = connection.subscribe(msg_num).await?; + let get = Bc { + meta: BcMeta { + msg_id: MSG_ID_PING, + channel_id: self.channel_id, + msg_num, + response_code: 0, + stream_type: 0, + class: 0x6414, + }, + body: BcBody::ModernMsg(ModernMsg { + extension: None, + payload: None, + }), + }; + + sub_get.send(get).await?; + let msg = sub_get.recv().await?; + if msg.meta.response_code != 200 { + return Err(Error::CameraServiceUnavaliable); + } + + if let BcBody::ModernMsg(ModernMsg { + payload: + Some(BcPayloads::BcXml(BcXml { + link_type: Some(link_type), + .. + })), + .. + }) = msg.body + { + Ok(link_type) + } else { + Err(Error::UnintelligibleReply { + reply: std::sync::Arc::new(Box::new(msg)), + why: "Expected LinkType xml but it was not recieved", + }) + } + } +} diff --git a/src/mqtt/event_cam.rs b/src/mqtt/event_cam.rs index 37f9104..6e387ab 100644 --- a/src/mqtt/event_cam.rs +++ b/src/mqtt/event_cam.rs @@ -1,6 +1,7 @@ use crate::config::CameraConfig; use crate::utils::AddressOrUid; use anyhow::{anyhow, Context, Result}; +use futures::stream::StreamExt; use log::*; use neolink_core::bc_protocol::{ BcCamera, Direction as BcDirection, Error as BcError, LightState, MaxEncryption, MotionStatus, @@ -9,11 +10,9 @@ use std::sync::Arc; use tokio::{ sync::mpsc::{channel, Receiver, Sender}, task::JoinSet, - time::sleep, + time::{interval, sleep, Duration}, }; -use core::time::Duration; - #[derive(Debug, Copy, Clone)] pub(crate) enum Messages { Login, @@ -205,6 +204,15 @@ impl EventCamThread { camera: arc_cam.clone(), }; + let mut flight_thread = FloodlightThread { + tx: self.tx.clone(), + camera: arc_cam.clone(), + }; + + let mut keepalive_thread = KeepaliveThread { + camera: arc_cam.clone(), + }; + let mut message_handler = MessageHandler { rx: &mut self.rx, camera: arc_cam, @@ -223,6 +231,30 @@ impl EventCamThread { Ok(()) } }, + val = async { + debug!("{}: Starting Pings", camera_config.name); + keepalive_thread.run().await + } => { + if let Err(e) = val { + debug!("Ping thread aborted: {:?}", e); + Err(e) + } else { + debug!("Normal finish on Ping thread"); + Ok(()) + } + }, + val = async { + info!("{}: Listening to FloodLight Status", camera_config.name); + flight_thread.run().await + } => { + if let Err(e) = val { + error!("FloodLight thread aborted: {:?}", e); + Err(e) + } else { + debug!("Normal finish on FloodLight thread"); + Ok(()) + } + }, val = async { info!("{}: Setting up camera actions", camera_config.name); message_handler.listen().await @@ -274,6 +306,47 @@ impl MotionThread { } } +struct FloodlightThread { + tx: Sender, + camera: Arc, +} + +impl FloodlightThread { + async fn run(&mut self) -> Result<()> { + let mut reciever = + tokio_stream::wrappers::ReceiverStream::new(self.camera.listen_on_flightlight().await?); + while let Some(flights) = reciever.next().await { + for flight in flights.floodlight_status_list.iter() { + if flight.status == 0 { + self.tx.send(Messages::FloodlightOff).await?; + } else { + self.tx.send(Messages::FloodlightOn).await?; + } + } + } + Ok(()) + } +} + +struct KeepaliveThread { + camera: Arc, +} + +impl KeepaliveThread { + async fn run(&mut self) -> Result<()> { + let mut interval = + tokio_stream::wrappers::IntervalStream::new(interval(Duration::from_secs(5))); + while let Some(_update) = interval.next().await { + if self.camera.ping().await.is_err() { + break; + } + } + + futures::pending!(); // Never actually finish, has to be aborted + Ok(()) + } +} + struct MessageHandler<'a> { rx: &'a mut Receiver, camera: Arc, @@ -325,7 +398,8 @@ impl<'a> MessageHandler<'a> { } Messages::StatusLedOn => { if let Err(e) = self.camera.led_light_set(true).await { - error = Some(format!("Failed to turn on the status light: {:?}", e)); + error = + Some(format!("Failed to turn on the status light: {:?}", e)); "FAIL".to_string() } else { "OK".to_string() diff --git a/src/mqtt/mod.rs b/src/mqtt/mod.rs index 3b19b23..ab4328b 100644 --- a/src/mqtt/mod.rs +++ b/src/mqtt/mod.rs @@ -167,6 +167,28 @@ async fn listen_on_camera(cam_config: Arc, mqtt_config: &MqttConfi format!("Failed to post connect over MQTT for {}", camera_name) })?; } + Messages::FloodlightOn => { + mqtt_sender_cam + .send_message("status/floodlight", "on", true) + .await + .with_context(|| { + format!( + "Failed to publish gloodlight on over MQTT for {}", + camera_name + ) + })?; + } + Messages::FloodlightOff => { + mqtt_sender_cam + .send_message("status/floodlight", "off", true) + .await + .with_context(|| { + format!( + "Failed to publish gloodlight off over MQTT for {}", + camera_name + ) + })?; + } Messages::MotionStop => { mqtt_sender_cam .send_message("status/motion", "off", true) From 1824e061f42eb4b43e81c5c47fbaa1793839a165 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Fri, 19 May 2023 13:17:04 +0700 Subject: [PATCH 06/10] fmt --- crates/core/src/bc_protocol.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/core/src/bc_protocol.rs b/crates/core/src/bc_protocol.rs index 03be064..6bd5f01 100644 --- a/crates/core/src/bc_protocol.rs +++ b/crates/core/src/bc_protocol.rs @@ -16,8 +16,8 @@ mod battery; mod connection; mod credentials; mod errors; -mod keepalive; mod floodlight_status; +mod keepalive; mod ledstate; mod login; mod logout; From d90f0b1002725e0857ec4170ed3b3d032b62f068 Mon Sep 17 00:00:00 2001 From: Kevin David Date: Fri, 19 May 2023 23:48:10 -0400 Subject: [PATCH 07/10] Improve MQTT error message --- src/mqtt/mqttc.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/mqtt/mqttc.rs b/src/mqtt/mqttc.rs index 1cb2317..d490ea4 100644 --- a/src/mqtt/mqttc.rs +++ b/src/mqtt/mqttc.rs @@ -264,12 +264,12 @@ impl Mqtt { impl Drop for Mqtt { fn drop(&mut self) { if let Some(drop_message) = self.drop_message.as_ref() { - if self + let res = self .get_sender() - .try_send_message(&drop_message.topic, &drop_message.message, true) - .is_err() + .try_send_message(&drop_message.topic, &drop_message.message, true); + if res.is_err() { - error!("Failed to send offline message to mqtt"); + error!("Failed to send offline message to mqtt: {:?}. Is the MQTT topic name valid?", res.err().unwrap()); } } self.set.abort_all(); From 864f58d20e7066cd8b0857d5edd0ac072a22b24f Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Wed, 24 May 2023 12:26:27 +0700 Subject: [PATCH 08/10] Async handle_msg closures --- crates/core/src/bc_protocol/battery.rs | 86 ++++++++++--------- .../core/src/bc_protocol/connection/bcconn.rs | 15 ++-- .../core/src/bc_protocol/floodlight_status.rs | 45 +++++----- crates/core/src/bc_protocol/keepalive.rs | 26 +++--- 4 files changed, 91 insertions(+), 81 deletions(-) diff --git a/crates/core/src/bc_protocol/battery.rs b/crates/core/src/bc_protocol/battery.rs index 83697e8..ec4a91d 100644 --- a/crates/core/src/bc_protocol/battery.rs +++ b/crates/core/src/bc_protocol/battery.rs @@ -19,58 +19,60 @@ impl BcCamera { let connection = self.get_connection(); connection .handle_msg(MSG_ID_BATTERY_INFO_LIST, move |bc| { - if let Bc { - body: - BcBody::ModernMsg(ModernMsg { - payload: - Some(BcPayloads::BcXml(BcXml { - battery_list: Some(battery_list), - .. - })), - .. - }), - .. - } = bc - { - for battery in battery_list.battery_info.iter() { - match format { - PrintFormat::None => {} - PrintFormat::Human => { - println!( - "==Battery==\n\ + Box::pin(async move { + if let Bc { + body: + BcBody::ModernMsg(ModernMsg { + payload: + Some(BcPayloads::BcXml(BcXml { + battery_list: Some(battery_list), + .. + })), + .. + }), + .. + } = bc + { + for battery in battery_list.battery_info.iter() { + match format { + PrintFormat::None => {} + PrintFormat::Human => { + println!( + "==Battery==\n\ Charge: {}%,\n\ Temperature: {}°C,\n\ LowPower: {},\n\ Adapter: {},\n\ ChargeStatus: {},\n\ ", - battery.battery_percent, - battery.temperature, - if battery.low_power == 1 { - "true" - } else { - "false" - }, - battery.adapter_status, - battery.charge_status, - ); - } - PrintFormat::Xml => { - let bat_ser = String::from_utf8( - yaserde::ser::serialize_with_writer( - battery, - vec![], - &Default::default(), + battery.battery_percent, + battery.temperature, + if battery.low_power == 1 { + "true" + } else { + "false" + }, + battery.adapter_status, + battery.charge_status, + ); + } + PrintFormat::Xml => { + let bat_ser = String::from_utf8( + yaserde::ser::serialize_with_writer( + battery, + vec![], + &Default::default(), + ) + .expect("Should Ser the struct"), ) - .expect("Should Ser the struct"), - ) - .expect("Should be UTF8"); - println!("{}", bat_ser); + .expect("Should be UTF8"); + println!("{}", bat_ser); + } } } } - } - None + Option::::None + }) }) .await?; Ok(()) diff --git a/crates/core/src/bc_protocol/connection/bcconn.rs b/crates/core/src/bc_protocol/connection/bcconn.rs index b2038d7..bae0408 100644 --- a/crates/core/src/bc_protocol/connection/bcconn.rs +++ b/crates/core/src/bc_protocol/connection/bcconn.rs @@ -1,10 +1,12 @@ use super::BcSubscription; use crate::{bc::model::*, Error, Result}; +use futures::future::BoxFuture; use futures::sink::{Sink, SinkExt}; use futures::stream::{Stream, StreamExt}; use log::*; use std::collections::btree_map::Entry; use std::collections::BTreeMap; +use std::sync::Arc; use tokio::sync::mpsc::{channel, Sender}; use tokio::task::yield_now; use tokio_stream::wrappers::ReceiverStream; @@ -12,13 +14,14 @@ use tokio_util::sync::PollSender; use tokio::{sync::RwLock, task::JoinSet}; -type MsgHandler = Box Option + Send + Sync>; +type MsgHandler = dyn 'static + Send + Sync + for<'a> Fn(&'a Bc) -> BoxFuture<'a, Option>; + #[derive(Default)] struct Subscriber { /// Subscribers based on their Num num: BTreeMap>>, /// Subscribers based on their ID - id: BTreeMap, + id: BTreeMap>, } pub(crate) type BcConnSink = Box + Send + Sync + Unpin>; @@ -95,10 +98,10 @@ impl BcConnection { /// and return either None or Some(Bc) reply pub async fn handle_msg(&self, msg_id: u32, handler: T) -> Result<()> where - T: Fn(&Bc) -> Option + Send + Sync + 'static, + T: 'static + Send + Sync + for<'a> Fn(&'a Bc) -> BoxFuture<'a, Option>, { self.poll_commander - .send(PollCommand::AddHandler(msg_id, Box::new(handler))) + .send(PollCommand::AddHandler(msg_id, Arc::new(handler))) .await?; Ok(()) } @@ -133,7 +136,7 @@ impl BcConnection { enum PollCommand { Bc(Box>), - AddHandler(u32, MsgHandler), + AddHandler(u32, Arc), RemoveHandler(u32), AddSubscriber(u16, Sender>), } @@ -160,7 +163,7 @@ impl Poller { self.subscribers.num.get(&msg_num), ) { (Some(occ), _) => { - if let Some(reply) = occ(&response) { + if let Some(reply) = occ(&response).await { assert!(reply.meta.msg_num == response.meta.msg_num); self.sink.send(Ok(reply)).await?; } diff --git a/crates/core/src/bc_protocol/floodlight_status.rs b/crates/core/src/bc_protocol/floodlight_status.rs index f95e399..d682a40 100644 --- a/crates/core/src/bc_protocol/floodlight_status.rs +++ b/crates/core/src/bc_protocol/floodlight_status.rs @@ -10,27 +10,30 @@ impl BcCamera { let connection = self.get_connection(); connection .handle_msg(MSG_ID_FLOODLIGHT_STATUS_LIST, move |bc| { - if let Bc { - meta: - BcMeta { - msg_id: MSG_ID_FLOODLIGHT_STATUS_LIST, - .. - }, - body: - BcBody::ModernMsg(ModernMsg { - payload: - Some(BcPayloads::BcXml(BcXml { - floodlight_status_list: Some(list), - .. - })), - .. - }), - } = bc - { - let send_this: FloodlightStatusList = list.clone(); - let _ = tx.blocking_send(send_this); - } - None + let tx = tx.clone(); + Box::pin(async move { + if let Bc { + meta: + BcMeta { + msg_id: MSG_ID_FLOODLIGHT_STATUS_LIST, + .. + }, + body: + BcBody::ModernMsg(ModernMsg { + payload: + Some(BcPayloads::BcXml(BcXml { + floodlight_status_list: Some(list), + .. + })), + .. + }), + } = bc + { + let send_this: FloodlightStatusList = list.clone(); + let _ = tx.send(send_this).await; + } + None + }) }) .await?; diff --git a/crates/core/src/bc_protocol/keepalive.rs b/crates/core/src/bc_protocol/keepalive.rs index 89a9ca7..3de5cbc 100644 --- a/crates/core/src/bc_protocol/keepalive.rs +++ b/crates/core/src/bc_protocol/keepalive.rs @@ -10,18 +10,20 @@ impl BcCamera { let connection = self.get_connection(); connection .handle_msg(MSG_ID_UDP_KEEP_ALIVE, |bc| { - Some(Bc { - meta: BcMeta { - msg_id: MSG_ID_UDP_KEEP_ALIVE, - channel_id: bc.meta.channel_id, - msg_num: bc.meta.msg_num, - stream_type: bc.meta.stream_type, - response_code: 200, - class: 0x6414, - }, - body: BcBody::ModernMsg(ModernMsg { - ..Default::default() - }), + Box::pin(async move { + Some(Bc { + meta: BcMeta { + msg_id: MSG_ID_UDP_KEEP_ALIVE, + channel_id: bc.meta.channel_id, + msg_num: bc.meta.msg_num, + stream_type: bc.meta.stream_type, + response_code: 200, + class: 0x6414, + }, + body: BcBody::ModernMsg(ModernMsg { + ..Default::default() + }), + }) }) }) .await?; From f9975520abd3540fbcfce45d9dc2c974e0092452 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Wed, 24 May 2023 12:33:38 +0700 Subject: [PATCH 09/10] Fmt --- src/mqtt/mqttc.rs | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/src/mqtt/mqttc.rs b/src/mqtt/mqttc.rs index d490ea4..bbfedef 100644 --- a/src/mqtt/mqttc.rs +++ b/src/mqtt/mqttc.rs @@ -264,12 +264,16 @@ impl Mqtt { impl Drop for Mqtt { fn drop(&mut self) { if let Some(drop_message) = self.drop_message.as_ref() { - let res = self - .get_sender() - .try_send_message(&drop_message.topic, &drop_message.message, true); - if res.is_err() - { - error!("Failed to send offline message to mqtt: {:?}. Is the MQTT topic name valid?", res.err().unwrap()); + let res = self.get_sender().try_send_message( + &drop_message.topic, + &drop_message.message, + true, + ); + if res.is_err() { + error!( + "Failed to send offline message to mqtt: {:?}. Is the MQTT topic name valid?", + res.err().unwrap() + ); } } self.set.abort_all(); From 5f96b2e7f8807522f4c07376694d402a8dc01369 Mon Sep 17 00:00:00 2001 From: Kevin David Date: Wed, 24 May 2023 08:20:26 -0400 Subject: [PATCH 10/10] Fix XML deserialization of `FloodlightStatusList` The children are `FloodlightStatus`, so that's what we should `yaserde(rename)` to --- crates/core/src/bc/xml.rs | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/crates/core/src/bc/xml.rs b/crates/core/src/bc/xml.rs index 5e65cff..4659e47 100644 --- a/crates/core/src/bc/xml.rs +++ b/crates/core/src/bc/xml.rs @@ -337,14 +337,10 @@ pub struct LedState { /// FloodlightStatus xml #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)] pub struct FloodlightStatus { - /// XML Version - #[yaserde(attribute)] - pub version: String, /// Channel ID of floodlight #[yaserde(rename = "channel")] pub channel_id: u8, /// On or off - #[yaserde(rename = "status")] pub status: u8, } @@ -355,7 +351,7 @@ pub struct FloodlightStatusList { #[yaserde(attribute)] pub version: String, /// List of events - #[yaserde(rename = "FloodlightStatusList")] + #[yaserde(rename = "FloodlightStatus")] pub floodlight_status_list: Vec, } @@ -369,7 +365,6 @@ pub struct FloodlightManual { #[yaserde(rename = "channelId")] pub channel_id: u8, /// On or off - #[yaserde(rename = "status")] pub status: u8, /// How long the manual control should apply for pub duration: u16,