diff --git a/README.md b/README.md index 872510b..5592771 100644 --- a/README.md +++ b/README.md @@ -130,10 +130,12 @@ Control messages: Status Messages: `/status offline` Sent when the neolink goes offline this is a LastWill message `/status disconnected` Sent when the camera goes offline -`/status/battery` Sent in reply to a `/query/battery` send an XML encoded version of the battery status +`/status/battery` Sent in reply to a `/query/battery` an XML encoded version of the battery status +`/status/pir` Sent in reply to a `/query/pir` an XML encoded version of the pir status Query Messages: `/query/battery` Request that the camera reports its battery level +`/query/pir` Request that the camera reports its pir status ### Pause diff --git a/crates/core/src/bc/model.rs b/crates/core/src/bc/model.rs index 141c84f..86a51e9 100644 --- a/crates/core/src/bc/model.rs +++ b/crates/core/src/bc/model.rs @@ -27,14 +27,12 @@ pub const MSG_ID_MOTION_REQUEST: u32 = 31; pub const MSG_ID_MOTION: u32 = 33; /// Version messages have this ID pub const MSG_ID_VERSION: u32 = 80; -/// Getting PIR status messages have this ID -pub const MSG_ID_GET_PIR_ALARM: u32 = 212; -/// Setting PIR status messages have this ID -pub const MSG_ID_START_PIR_ALARM: u32 = 213; /// Ping messages have this ID pub const MSG_ID_PING: u32 = 93; /// General system info messages have this ID pub const MSG_ID_GET_GENERAL: u32 = 104; +/// Used to get the abilities of a user +pub const MSG_ID_ABILITY_INFO: u32 = 151; /// Setting general system info (clock mostly) messages have this ID pub const MSG_ID_SET_GENERAL: u32 = 105; /// Will send the talk config for talk back data to follow this msg @@ -45,6 +43,10 @@ pub const MSG_ID_TALK: u32 = 202; pub const MSG_ID_GET_LED_STATUS: u32 = 208; /// Setting the LED status is done with this ID pub const MSG_ID_SET_LED_STATUS: u32 = 209; +/// Getting PIR status messages have this ID +pub const MSG_ID_GET_PIR_ALARM: u32 = 212; +/// Setting PIR status messages have this ID +pub const MSG_ID_START_PIR_ALARM: u32 = 213; /// UDP Keep alive pub const MSG_ID_UDP_KEEP_ALIVE: u32 = 234; /// Battery message initiaed by the camera diff --git a/crates/core/src/bc/xml.rs b/crates/core/src/bc/xml.rs index add10c2..97c8a5f 100644 --- a/crates/core/src/bc/xml.rs +++ b/crates/core/src/bc/xml.rs @@ -82,6 +82,9 @@ pub struct BcXml { /// Recieved on request for battery info #[yaserde(rename = "BatteryInfo")] pub battery_info: Option, + /// Recieved on request for a users persmissions/capabilitoes + #[yaserde(rename = "AbilityInfo")] + pub ability_info: Option, } impl BcXml { @@ -238,6 +241,9 @@ pub struct Extension { /// The channel ID. This is usually `0` unless using an NVR #[yaserde(rename = "channelId")] pub channel_id: Option, + /// The rfID used in the PIR + #[yaserde(rename = "rfId")] + pub rf_id: Option, } impl Default for Extension { @@ -248,6 +254,7 @@ impl Default for Extension { user_name: None, token: None, channel_id: None, + rf_id: None, } } } @@ -336,7 +343,54 @@ pub struct RfAlarmCfg { /// reduce False alarm boolean pub reduceFalseAlarm: u8, /// XML time block for all week days - pub timeBlockList: String, + #[yaserde(rename = "timeBlockList")] + pub time_block_list: TimeBlockList, + /// The alarm handle to attach to this Rf + #[yaserde(rename = "alarmHandle")] + pub alarm_handle: AlarmHandle, +} + +/// TimeBlockList XML +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +#[yaserde(rename = "timeBlockList")] +pub struct TimeBlockList { + /// List of time block entries which disable/enable the PIR at a time + #[yaserde(rename = "timeBlock")] + pub time_block: Vec, +} + +/// TimeBlock XML Used to set the time to enable/disable PIR dectection +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +#[yaserde(rename = "timeBlock")] +pub struct TimeBlock { + /// Whether to enable or disable for this time block + pub enable: u8, + /// The day of the week for this block + pub weekDay: String, + /// Time to start this block + #[yaserde(rename = "beginHour")] + pub begin_hour: u8, + /// Time to end this block + #[yaserde(rename = "endHour")] + pub end_hour: u8, +} + +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +/// AlarmHandle Xml +pub struct AlarmHandle { + /// Items in the alarm handle + pub item: Vec, +} + +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +/// An item in the alarm handle +#[yaserde(rename = "item")] +pub struct AlarmHandleItem { + /// The channel ID + pub channel: u8, + /// The handle type: Known values, comma seperated list of snap,rec,push + #[yaserde(rename = "handleType")] + pub handle_type: String, } /// TalkConfig xml @@ -510,6 +564,56 @@ pub struct BatteryInfo { pub battery_version: u32, } +/// The ability battery info +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct AbilityInfo { + /// Username with this ability + #[yaserde(rename = "userName")] + pub username: String, + /// System permissions + pub system: Option, + /// Network permissions + pub network: Option, + /// Alarm permissions + pub alarm: Option, + /// Image permissions + pub image: Option, + /// Video permissions + pub video: Option, + /// Secutiry permissions + pub security: Option, + /// Replay permissions + pub replay: Option, + /// PTZ permissions + #[yaserde(rename = "PTZ")] + pub ptz: Option, + /// IO permissions + #[yaserde(rename = "IO")] + pub io: Option, + /// Streaming permissions + pub streaming: Option, +} + +/// Ability info for system token +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct AbilityInfoToken { + /// Submodule for this ability info token + #[yaserde(rename = "subModule")] + pub sub_module: Vec, +} + +/// Token submodule infomation +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +#[yaserde(rename = "subModule")] +pub struct AbilityInfoSubModule { + /// The channel the for the camera usually 0 + #[yaserde(rename = "channelId")] + pub channel_id: Option, + /// The comma seperated list of permissions like this: `general_rw, norm_rw, version_ro` + #[yaserde(rename = "abilityValue")] + pub ability_value: 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 6d2d1d6..3699f7b 100644 --- a/crates/core/src/bc_protocol.rs +++ b/crates/core/src/bc_protocol.rs @@ -3,10 +3,15 @@ use futures::stream::StreamExt; use log::*; use serde::{Deserialize, Serialize}; use std::net::ToSocketAddrs; -use std::sync::atomic::{AtomicBool, AtomicU16, Ordering}; +use std::{ + collections::HashMap, + sync::atomic::{AtomicBool, AtomicU16, Ordering}, +}; +use tokio::sync::RwLock; use Md5Trunc::*; +mod abilityinfo; mod battery; mod connection; mod credentials; @@ -40,6 +45,13 @@ pub use stream::{StreamData, StreamKind}; pub(crate) type Result = std::result::Result; +#[derive(Clone, Copy)] +enum ReadKind { + ReadOnly, + ReadWrite, + None, +} + /// /// This is the primary struct of this library when interacting with the camera /// @@ -50,6 +62,7 @@ pub struct BcCamera { message_num: AtomicU16, // Certain commands such as logout require the username/pass in plain text.... why....??? credentials: Credentials, + abilities: RwLock>, } /// Used to choode the print format of various status messages like battery levels @@ -334,9 +347,12 @@ impl BcCamera { channel_id, logged_in: AtomicBool::new(false), credentials: Credentials::new(username, passwd), + abilities: Default::default(), }; me.keepalive().await?; - me.monitor_battery(aux_info_format).await?; + if let Err(e) = me.monitor_battery(aux_info_format).await { + warn!("Could not monitor battery: {:?}", e); + } Ok(me) } @@ -355,6 +371,42 @@ impl BcCamera { fn get_credentials(&self) -> &Credentials { &self.credentials } + + async fn has_ability>(&self, name: T) -> ReadKind { + let abilities = self.abilities.read().await; + if let Some(kind) = abilities.get(&name.into()).copied() { + kind + } else { + ReadKind::None + } + } + async fn has_ability_ro>(&self, name: T) -> Result<()> { + let s: String = name.into(); + match self.has_ability(&s).await { + ReadKind::ReadWrite | ReadKind::ReadOnly => Ok(()), + ReadKind::None => Err(Error::MissingAbility { + name: s.clone(), + requested: "read".to_string(), + actual: "none".to_string(), + }), + } + } + async fn has_ability_rw>(&self, name: T) -> Result<()> { + let s: String = name.into(); + match self.has_ability(&s).await { + ReadKind::ReadWrite => Ok(()), + ReadKind::ReadOnly => Err(Error::MissingAbility { + name: s.clone(), + requested: "write".to_string(), + actual: "read".to_string(), + }), + ReadKind::None => Err(Error::MissingAbility { + name: s.clone(), + requested: "write".to_string(), + actual: "none".to_string(), + }), + } + } } /// The Baichuan library has a very peculiar behavior where it always zeros the last byte. I diff --git a/crates/core/src/bc_protocol/abilityinfo.rs b/crates/core/src/bc_protocol/abilityinfo.rs new file mode 100644 index 0000000..6718584 --- /dev/null +++ b/crates/core/src/bc_protocol/abilityinfo.rs @@ -0,0 +1,104 @@ +use super::{BcCamera, Error, Result}; +use crate::bc::{model::*, xml::*}; + +impl BcCamera { + /// Get the ability info xml for the current user + pub async fn get_abilityinfo(&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_ABILITY_INFO, + channel_id: self.channel_id, + msg_num, + response_code: 0, + stream_type: 0, + class: 0x6414, + }, + body: BcBody::ModernMsg(ModernMsg { + extension: Some(Extension { + user_name: Some(self.get_credentials().username.clone()), + token: Some("system, streaming, PTZ, IO, security, replay, disk, network, alarm, record, video, image".to_string()), + ..Default::default() + }), + 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 { + ability_info: Some(ability_info), + .. + })), + .. + }) = msg.body + { + Ok(ability_info) + } else { + Err(Error::UnintelligibleReply { + reply: std::sync::Arc::new(Box::new(msg)), + why: "Expected AbilityInfo xml but it was not recieved", + }) + } + } + + /// Populate ability list of the camera + pub async fn polulate_abilities(&self) -> Result<()> { + let info = self.get_abilityinfo().await?; + let mut abilities: Vec = vec![]; + + let mut tokens: Vec> = vec![ + info.system.as_ref(), + info.network.as_ref(), + info.alarm.as_ref(), + info.image.as_ref(), + info.video.as_ref(), + info.security.as_ref(), + info.replay.as_ref(), + info.ptz.as_ref(), + info.io.as_ref(), + info.streaming.as_ref(), + ]; + for token in tokens.drain(..).flatten() { + for sub_module in token.sub_module.iter() { + abilities.extend( + sub_module + .ability_value + .replace(' ', "") + .split(',') + .map(|s| s.to_string()), + ); + } + } + + let mut locked_abilities = self.abilities.write().await; + for ability in abilities.iter() { + let mut abilities_ro = ability.split('_').map(|s| s.to_string()); + if let (Some(ability_name), Some(ability_kind)) = + (abilities_ro.next(), abilities_ro.next()) + { + match ability_kind.as_str() { + "rw" => { + locked_abilities.insert(ability_name, super::ReadKind::ReadWrite); + } + "ro" => { + locked_abilities.insert(ability_name, super::ReadKind::ReadOnly); + } + _ => { + continue; + } + } + } + } + + Ok(()) + } +} diff --git a/crates/core/src/bc_protocol/connection/discovery.rs b/crates/core/src/bc_protocol/connection/discovery.rs index 0019707..25c273a 100644 --- a/crates/core/src/bc_protocol/connection/discovery.rs +++ b/crates/core/src/bc_protocol/connection/discovery.rs @@ -938,7 +938,7 @@ fn generate_cid() -> i32 { } async fn connect() -> Result { - let mut ports: Vec = (53500..54000).into_iter().collect(); + let mut ports: Vec = (53500..54000).collect(); { let mut rng = thread_rng(); ports.shuffle(&mut rng); diff --git a/crates/core/src/bc_protocol/connection/udpsource.rs b/crates/core/src/bc_protocol/connection/udpsource.rs index 3bc0ddc..27b7252 100644 --- a/crates/core/src/bc_protocol/connection/udpsource.rs +++ b/crates/core/src/bc_protocol/connection/udpsource.rs @@ -253,12 +253,15 @@ impl UdpPayloadSource { fn handle_ack(&mut self, ack: UdpAck) { let start = ack.packet_id; - self.sent.retain(|&k, _| k > start); + // -1 is the special case of no messages recieved + if start != 0xFFFFFFFF { + self.sent.retain(|&k, _| k > start); - for (idx, &value) in ack.payload.iter().enumerate() { - let packet_id = (start + 1) + idx as u32; - if value > 0 { - self.sent.remove(&packet_id); + for (idx, &value) in ack.payload.iter().enumerate() { + let packet_id = (start + 1) + idx as u32; + if value > 0 { + self.sent.remove(&packet_id); + } } } } @@ -508,7 +511,7 @@ impl futures::AsyncWrite for UdpPayloadSource { /// Helper to create a TcpStream with a connect timeout async fn connect() -> Result { - let mut ports: Vec = (53500..54000).into_iter().collect(); + let mut ports: Vec = (53500..54000).collect(); let mut rng = thread_rng(); ports.shuffle(&mut rng); diff --git a/crates/core/src/bc_protocol/errors.rs b/crates/core/src/bc_protocol/errors.rs index e1c53bf..e616821 100644 --- a/crates/core/src/bc_protocol/errors.rs +++ b/crates/core/src/bc_protocol/errors.rs @@ -143,6 +143,22 @@ pub enum Error { #[error(display = "Nom Parsing error: {}", _0)] NomError(String), + /// Raised when a camera/user lacks an ability + #[error( + display = "Missing ability: {} with {} permission has only {}", + name, + requested, + actual + )] + MissingAbility { + /// Name of the ability + name: String, + /// Requested permission (read/write) + requested: String, + /// Actual permission (read/write/none) + actual: String, + }, + /// A generic catch all error #[error(display = "Other error: {}", _0)] Other(&'static str), diff --git a/crates/core/src/bc_protocol/ledstate.rs b/crates/core/src/bc_protocol/ledstate.rs index a15b5cf..472a8ea 100644 --- a/crates/core/src/bc_protocol/ledstate.rs +++ b/crates/core/src/bc_protocol/ledstate.rs @@ -4,6 +4,7 @@ use crate::bc::{model::*, xml::*}; impl BcCamera { /// Get the [LedState] xml which contains the LED status of the camera pub async fn get_ledstate(&self) -> Result { + self.has_ability_ro("ledState").await?; let connection = self.get_connection(); let msg_num = self.new_message_num(); let mut sub_get = connection.subscribe(msg_num).await?; @@ -51,6 +52,7 @@ impl BcCamera { /// Set the led lights using the [LedState] xml pub async fn set_ledstate(&self, mut led_state: LedState) -> Result<()> { + self.has_ability_rw("ledState").await?; let connection = self.get_connection(); let msg_num = self.new_message_num(); diff --git a/crates/core/src/bc_protocol/login.rs b/crates/core/src/bc_protocol/login.rs index 363d5aa..b6b9810 100644 --- a/crates/core/src/bc_protocol/login.rs +++ b/crates/core/src/bc_protocol/login.rs @@ -164,6 +164,9 @@ impl BcCamera { } } } + + // Populate the list of abilities this user has with the camera + self.polulate_abilities().await?; Ok(device_info) } } diff --git a/crates/core/src/bc_protocol/motion.rs b/crates/core/src/bc_protocol/motion.rs index b408ffe..9884bc0 100644 --- a/crates/core/src/bc_protocol/motion.rs +++ b/crates/core/src/bc_protocol/motion.rs @@ -86,6 +86,7 @@ impl BcCamera { /// This message tells the camera to send the motion events to us /// Which are the recieved on msgid 33 async fn start_motion_query(&self) -> Result { + self.has_ability_rw("motion").await?; let connection = self.get_connection(); let msg_num = self.new_message_num(); diff --git a/crates/core/src/bc_protocol/pirstate.rs b/crates/core/src/bc_protocol/pirstate.rs index 75a3a85..aa340e8 100644 --- a/crates/core/src/bc_protocol/pirstate.rs +++ b/crates/core/src/bc_protocol/pirstate.rs @@ -1,56 +1,73 @@ use super::{BcCamera, Error, Result}; use crate::bc::{model::*, xml::*}; +use tokio::time::{interval, Duration}; impl BcCamera { /// Get the [RfAlarmCfg] xml which contains the PIR status of the camera pub async fn get_pirstate(&self) -> Result { + self.has_ability_ro("rfAlarm").await?; 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_GET_PIR_ALARM, - 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() + let mut reties: usize = 0; + let mut retry_interval = interval(Duration::from_millis(500)); + loop { + retry_interval.tick().await; + 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_GET_PIR_ALARM, + channel_id: self.channel_id, + msg_num, + response_code: 0, + stream_type: 0, + class: 0x6414, + }, + body: BcBody::ModernMsg(ModernMsg { + extension: Some(Extension { + rf_id: Some(self.channel_id), + ..Default::default() + }), + payload: 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 { - rf_alarm_cfg: Some(pirstate), + sub_get.send(get).await?; + let msg = sub_get.recv().await?; + if msg.meta.response_code == 400 { + // Retryable + if reties < 5 { + reties += 1; + continue; + } else { + return Err(Error::CameraServiceUnavaliable); + } + } else if msg.meta.response_code != 200 { + return Err(Error::CameraServiceUnavaliable); + } else { + // Valid message with response_code == 200 + if let BcBody::ModernMsg(ModernMsg { + payload: + Some(BcPayloads::BcXml(BcXml { + rf_alarm_cfg: Some(pirstate), + .. + })), .. - })), - .. - }) = msg.body - { - Ok(pirstate) - } else { - Err(Error::UnintelligibleReply { - reply: std::sync::Arc::new(Box::new(msg)), - why: "Expected PirSate xml but it was not recieved", - }) + }) = msg.body + { + return Ok(pirstate); + } else { + return Err(Error::UnintelligibleReply { + reply: std::sync::Arc::new(Box::new(msg)), + why: "Expected PirSate xml but it was not recieved", + }); + } + } } } /// Set the PIR sensor using the [RfAlarmCfg] xml pub async fn set_pirstate(&self, rf_alarm_cfg: RfAlarmCfg) -> Result<()> { + self.has_ability_rw("rfAlarm").await?; let connection = self.get_connection(); let msg_num = self.new_message_num(); let mut sub_set = connection.subscribe(msg_num).await?; @@ -66,7 +83,7 @@ impl BcCamera { }, body: BcBody::ModernMsg(ModernMsg { extension: Some(Extension { - channel_id: Some(self.channel_id), + rf_id: Some(self.channel_id), ..Default::default() }), payload: Some(BcPayloads::BcXml(BcXml { diff --git a/crates/core/src/bc_protocol/ptz.rs b/crates/core/src/bc_protocol/ptz.rs index f7e8e26..c06fee0 100644 --- a/crates/core/src/bc_protocol/ptz.rs +++ b/crates/core/src/bc_protocol/ptz.rs @@ -20,6 +20,7 @@ pub enum Direction { impl BcCamera { /// Send a PTZ message to the camera pub async fn send_ptz(&self, direction: Direction, amount: f32) -> Result<()> { + self.has_ability_rw("control").await?; let connection = self.get_connection(); let msg_num = self.new_message_num(); let mut sub_set = connection.subscribe(msg_num).await?; diff --git a/crates/core/src/bc_protocol/reboot.rs b/crates/core/src/bc_protocol/reboot.rs index 2ad7566..4142679 100644 --- a/crates/core/src/bc_protocol/reboot.rs +++ b/crates/core/src/bc_protocol/reboot.rs @@ -4,6 +4,7 @@ use crate::bc::model::*; impl BcCamera { /// Reboot the camera pub async fn reboot(&self) -> Result<()> { + self.has_ability_rw("reboot").await?; let connection = self.get_connection(); let msg_num = self.new_message_num(); let mut sub = connection.subscribe(msg_num).await?; diff --git a/crates/core/src/bc_protocol/stream.rs b/crates/core/src/bc_protocol/stream.rs index 0cafc76..ef3f6df 100644 --- a/crates/core/src/bc_protocol/stream.rs +++ b/crates/core/src/bc_protocol/stream.rs @@ -74,6 +74,7 @@ impl BcCamera { mut buffer_size: usize, strict: bool, ) -> Result { + self.has_ability_rw("preview").await?; let connection = self.get_connection(); let msg_num = self.new_message_num(); @@ -208,6 +209,7 @@ impl BcCamera { /// Stop a camera from sending more stream data. pub async fn stop_video(&self, stream: StreamKind) -> Result<()> { + self.has_ability_rw("preview").await?; let connection = self.get_connection(); let msg_num = self.new_message_num(); let mut sub_video = connection.subscribe(msg_num).await?; diff --git a/crates/core/src/bc_protocol/time.rs b/crates/core/src/bc_protocol/time.rs index 7ff3bab..a99aec1 100644 --- a/crates/core/src/bc_protocol/time.rs +++ b/crates/core/src/bc_protocol/time.rs @@ -11,6 +11,7 @@ impl BcCamera { /// returns either an error or an option with the offsetted date time /// pub async fn get_time(&self) -> Result> { + self.has_ability_ro("general").await?; let connection = self.get_connection(); let msg_num = self.new_message_num(); let mut sub_get_general = connection.subscribe(msg_num).await?; @@ -95,6 +96,7 @@ impl BcCamera { /// returns Ok(()) or error /// pub async fn set_time(&self, timestamp: OffsetDateTime) -> Result<()> { + self.has_ability_rw("general").await?; let connection = self.get_connection(); let msg_num = self.new_message_num(); let mut sub_set_general = connection.subscribe(msg_num).await?; diff --git a/crates/core/src/bc_protocol/version.rs b/crates/core/src/bc_protocol/version.rs index e01bf26..b562f5a 100644 --- a/crates/core/src/bc_protocol/version.rs +++ b/crates/core/src/bc_protocol/version.rs @@ -4,6 +4,7 @@ use crate::bc::{model::*, xml::*}; impl BcCamera { /// Request the [VersionInfo] xml pub async fn version(&self) -> Result { + self.has_ability_ro("version").await?; let connection = self.get_connection(); let msg_num = self.new_message_num(); let mut sub_version = connection.subscribe(msg_num).await?; diff --git a/dissector/baichuan.lua b/dissector/baichuan.lua index 34259c5..d5b2079 100644 --- a/dissector/baichuan.lua +++ b/dissector/baichuan.lua @@ -166,6 +166,7 @@ local message_types = { [210]="", [211]=" (write)", [212]="", + [213]=" (write)", [216]=" (write)", [217]="", [218]=" (write)", @@ -179,6 +180,8 @@ local message_types = { [272]="", [273]="", [274]="", + [319]="", + [342]="", } local message_classes = { diff --git a/src/mqtt/event_cam.rs b/src/mqtt/event_cam.rs index 22d07e6..c2fa812 100644 --- a/src/mqtt/event_cam.rs +++ b/src/mqtt/event_cam.rs @@ -25,6 +25,9 @@ pub(crate) enum Messages { IRLedOff, IRLedAuto, Battery, + PIROn, + PIROff, + PIRQuery, Ptz(Direction), } @@ -349,6 +352,50 @@ impl MessageHandler { } } }, + Messages::PIRQuery => match self.camera.get_pirstate().await { + Err(_) => { + error!("Failed to get pir status"); + "FAIL".to_string() + } + Ok(pir_info) => { + let bytes_res = yaserde::ser::serialize_with_writer( + &pir_info, + vec![], + &Default::default(), + ); + match bytes_res { + Ok(bytes) => match String::from_utf8(bytes) { + Ok(str) => str, + Err(_) => { + error!("Failed to encode pir status"); + "FAIL".to_string() + } + }, + Err(_) => { + error!("Failed to serialise pir status"); + "FAIL".to_string() + } + } + } + }, + Messages::PIROn => { + if self.camera.pir_set(true).await.is_err() { + error!("Failed to turn on the pir"); + self.abort(); + "FAIL".to_string() + } else { + "OK".to_string() + } + } + Messages::PIROff => { + if self.camera.pir_set(false).await.is_err() { + error!("Failed to turn on the pir"); + self.abort(); + "FAIL".to_string() + } else { + "OK".to_string() + } + } Messages::Ptz(direction) => { let (bc_direction, amount) = match direction { Direction::Up(amount) => (BcDirection::Up, amount), diff --git a/src/mqtt/mod.rs b/src/mqtt/mod.rs index 32b3004..37d4faf 100644 --- a/src/mqtt/mod.rs +++ b/src/mqtt/mod.rs @@ -11,6 +11,7 @@ use log::*; /// Control messages: /// /// - `/control/led [on|off]` Turns status LED on/off +/// - `/control/pir [on|off]` Turns PIR on/off /// - `/control/ir [on|off|auto]` Turn IR lights on/off or automatically via light detection /// - `/control/reboot` Reboot the camera /// - `/control/ptz` [up|down|left|right|in|out] (amount) Control the PTZ movements, amount defaults to 32.0 @@ -20,10 +21,12 @@ use log::*; /// `/status offline` Sent when the neolink goes offline this is a LastWill message /// `/status disconnected` Sent when the camera goes offline /// `/status/battery` Sent in reply to a `/query/battery` +/// `/status/pir` Sent in reply to a `/query/pir` /// /// Query Messages: /// -/// `/query/battery` Request that the camera reports its battery level (Not Yet Implemented) +/// `/query/battery` Request that the camera reports its battery level +/// `/query/pir` Request that the camera reports its pir status /// /// /// # Usage @@ -193,7 +196,7 @@ async fn listen_on_camera( message: "on", } => { if event_cam.send_message(Messages::IRLedOn).await.is_err() { - error!("Failed to set camera status light off"); + error!("Failed to set camera status light on"); } } MqttReplyRef { @@ -255,6 +258,22 @@ async fn listen_on_camera( error!("No PTZ Direction given. Please add up/down/left/right/in/out"); } } + MqttReplyRef { + topic: "control/pir", + message: "on", + } => { + if event_cam.send_message(Messages::PIROn).await.is_err() { + error!("Failed to set pir on"); + } + } + MqttReplyRef { + topic: "control/pir", + message: "off", + } => { + if event_cam.send_message(Messages::PIROff).await.is_err() { + error!("Failed to set pir off"); + } + } MqttReplyRef { topic: "query/battery", .. @@ -264,7 +283,17 @@ async fn listen_on_camera( error!("Failed to send battery status reply"); } } - Err(_) => error!("Failed to set camera status light off"), + Err(_) => error!("Failed to get battery status"), + }, + MqttReplyRef { + topic: "query/pir", .. + } => match event_cam.send_message_with_reply(Messages::PIRQuery).await { + Ok(reply) => { + if mqtt.send_message("status/pir", &reply, false).is_err() { + error!("Failed to send pir status reply"); + } + } + Err(_) => error!("Failed to get pir status"), }, _ => {} } diff --git a/src/pir/cmdline.rs b/src/pir/cmdline.rs index 36d2ed4..0933c89 100644 --- a/src/pir/cmdline.rs +++ b/src/pir/cmdline.rs @@ -19,5 +19,5 @@ pub struct Opt { pub camera: String, /// Whether to turn the PIR ON or OFF #[structopt(parse(try_from_str = onoff_parse), name = "on|off")] - pub on: bool, + pub on: Option, } diff --git a/src/pir/mod.rs b/src/pir/mod.rs index 724e699..6a028de 100644 --- a/src/pir/mod.rs +++ b/src/pir/mod.rs @@ -27,9 +27,22 @@ pub(crate) use cmdline::Opt; pub(crate) async fn main(opt: Opt, config: Config) -> Result<()> { let camera = find_and_connect(&config, &opt.camera).await?; - camera - .pir_set(opt.on) - .await - .context("Unable to set camera PIR state")?; + if let Some(on) = opt.on { + camera + .pir_set(on) + .await + .context("Unable to set camera PIR state")?; + } else { + let pir_state = camera + .get_pirstate() + .await + .context("Unable to get camera PIR state")?; + let pir_ser = String::from_utf8( + yaserde::ser::serialize_with_writer(&pir_state, vec![], &Default::default()) + .expect("Should Ser the struct"), + ) + .expect("Should be UTF8"); + println!("{}", pir_ser); + } Ok(()) }