diff --git a/.gitignore b/.gitignore index 98443d3..f85854a 100644 --- a/.gitignore +++ b/.gitignore @@ -15,6 +15,8 @@ # Committing IntelliJ project files is a violation of intergalactic law .idea/ +# We prefer to keep .vscode files outside the repo +.vscode/ # MacOS .DS_Store ._.DS_Store diff --git a/crates/core/src/bc/model.rs b/crates/core/src/bc/model.rs index 86a51e9..e633085 100644 --- a/crates/core/src/bc/model.rs +++ b/crates/core/src/bc/model.rs @@ -53,6 +53,10 @@ pub const MSG_ID_UDP_KEEP_ALIVE: u32 = 234; pub const MSG_ID_BATTERY_INFO_LIST: u32 = 252; /// Battery message initiaed by the client pub const MSG_ID_BATTERY_INFO: u32 = 253; +/// 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 f7aeafe..4659e47 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, /// Recieved on login/low battery events #[yaserde(rename = "BatteryList")] pub battery_list: Option, @@ -85,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 { @@ -325,6 +334,42 @@ pub struct LedState { pub light_state: String, } +/// FloodlightStatus xml +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)] +pub struct FloodlightStatus { + /// Channel ID of floodlight + #[yaserde(rename = "channel")] + pub channel_id: u8, + /// On or off + pub status: u8, +} + +/// FloodlightStatusList xml +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)] +pub struct FloodlightStatusList { + /// XML Version + #[yaserde(attribute)] + pub version: String, + /// List of events + #[yaserde(rename = "FloodlightStatus")] + 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 + 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 { @@ -614,6 +659,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.rs b/crates/core/src/bc_protocol.rs index 9b76be5..4b3b889 100644 --- a/crates/core/src/bc_protocol.rs +++ b/crates/core/src/bc_protocol.rs @@ -16,6 +16,7 @@ mod battery; mod connection; mod credentials; mod errors; +mod floodlight_status; mod keepalive; mod ledstate; mod login; 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 new file mode 100644 index 0000000..d682a40 --- /dev/null +++ b/crates/core/src/bc_protocol/floodlight_status.rs @@ -0,0 +1,94 @@ +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| { + 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?; + + 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(); + + let msg_num = self.new_message_num(); + let mut sub_set = connection.subscribe(msg_num).await?; + + 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(FloodlightManual { + version: "1".to_string(), + channel_id: self.channel_id, + status: match state { + true => 1, + false => 0, + }, + duration, + }), + ..Default::default() + })), + }), + }; + + sub_set.send(get).await?; + let msg = sub_set.recv().await?; + + if let BcMeta { + response_code: 200, .. + } = msg.meta + { + Ok(()) + } else { + Err(Error::UnintelligibleReply { + reply: std::sync::Arc::new(Box::new(msg)), + why: "The camera did not accept the Floodlight manual state", + }) + } + } +} 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?; 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 91fde9f..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,17 +10,17 @@ 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, MotionStop, MotionStart, Reboot, + FloodlightOn, + FloodlightOff, StatusLedOn, StatusLedOff, IRLedOn, @@ -203,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, @@ -221,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 @@ -272,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, @@ -297,6 +372,30 @@ impl<'a> MessageHandler<'a> { "OK".to_string() } } + Messages::FloodlightOn => { + let res = self.camera.set_floodlight_manual(true, 180).await; + if res.is_err() { + error = Some(format!( + "Failed to turn on the floodlight light: {:?}", + res.err() + )); + "FAIL".to_string() + } else { + "OK".to_string() + } + } + Messages::FloodlightOff => { + let res = self.camera.set_floodlight_manual(false, 180).await; + if res.is_err() { + error = Some(format!( + "Failed to turn off the floodlight light: {:?}", + res.err() + )); + "FAIL".to_string() + } else { + "OK".to_string() + } + } Messages::StatusLedOn => { if let Err(e) = self.camera.led_light_set(true).await { error = diff --git a/src/mqtt/mod.rs b/src/mqtt/mod.rs index 15e4ab0..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) @@ -214,6 +236,28 @@ async fn handle_mqtt_message( } => { // Do nothing for the success/fail replies } + MqttReplyRef { + topic: "control/floodlight", + message: "on", + } => { + reply = Some( + event_cam_sender + .send_message_with_reply(Messages::FloodlightOn) + .await + .with_context(|| "Failed to set camera status light on")?, + ); + } + MqttReplyRef { + topic: "control/floodlight", + message: "off", + } => { + reply = Some( + event_cam_sender + .send_message_with_reply(Messages::FloodlightOff) + .await + .with_context(|| "Failed to set camera status light off")?, + ); + } MqttReplyRef { topic: "control/led", message: "on", diff --git a/src/mqtt/mqttc.rs b/src/mqtt/mqttc.rs index 1cb2317..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() { - if self - .get_sender() - .try_send_message(&drop_message.topic, &drop_message.message, true) - .is_err() - { - error!("Failed to send offline message to mqtt"); + 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();