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)