diff --git a/crates/core/src/bc/model.rs b/crates/core/src/bc/model.rs index 6f1b8be..efd9ea3 100644 --- a/crates/core/src/bc/model.rs +++ b/crates/core/src/bc/model.rs @@ -16,6 +16,10 @@ pub const MSG_ID_TALKABILITY: u32 = 10; pub const MSG_ID_TALKRESET: u32 = 11; /// Reboot messages have this ID pub const MSG_ID_REBOOT: u32 = 23; +/// Request motion detection messages +pub const MSG_ID_MOTION_REQUEST: u32 = 31; +/// Motion detection messages +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 diff --git a/crates/core/src/bc/xml.rs b/crates/core/src/bc/xml.rs index 908bb41..2440d6e 100644 --- a/crates/core/src/bc/xml.rs +++ b/crates/core/src/bc/xml.rs @@ -69,6 +69,9 @@ pub struct BcXml { /// Revieced as part of the TalkAbility request #[yaserde(rename = "TalkAbility")] pub talk_ability: Option, + /// Received when motion is detected + #[yaserde(rename = "AlarmEventList")] + pub alarm_event_list: Option, } impl BcXml { @@ -412,6 +415,35 @@ pub struct AudioConfigList { pub audio_config: AudioConfig, } +/// An XML that desctibes a list of events such as motion detection +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct AlarmEventList { + /// XML Version + #[yaserde(attribute)] + pub version: String, + /// List of events + #[yaserde(rename = "AlarmEvent")] + pub alarm_events: Vec, +} + +/// An alarm event. Camera can send multiple per message as an array in AlarmEventList. +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct AlarmEvent { + /// XML Version + #[yaserde(attribute)] + pub version: String, + /// The channel the event occured on. Usually zero unless from an NVR + #[yaserde(rename = "channelId")] + pub channel_id: u8, + /// Motion status. Known values are `"MD"` or `"none"` + pub status: String, + /// The recording status. Known values `0` or `1` + pub recording: i32, + /// The timestamp associated with the recording. `0` if not recording + #[yaserde(rename = "timeStamp")] + pub timeStamp: i32, +} + /// 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 40e099b..24b9d30 100644 --- a/crates/core/src/bc_protocol.rs +++ b/crates/core/src/bc_protocol.rs @@ -11,6 +11,7 @@ mod errors; mod ledstate; mod login; mod logout; +mod motion; mod ping; mod pirstate; mod reboot; @@ -27,6 +28,7 @@ pub use errors::Error; pub use ledstate::LightState; pub use pirstate::PirState; pub use resolution::*; +pub use motion::{MotionOutput, MotionOutputError, MotionStatus}; pub use stream::{Stream, StreamOutput, StreamOutputError}; type Result = std::result::Result; diff --git a/crates/core/src/bc_protocol/connection/filesub.rs b/crates/core/src/bc_protocol/connection/filesub.rs index d27ec86..f5530b9 100644 --- a/crates/core/src/bc_protocol/connection/filesub.rs +++ b/crates/core/src/bc_protocol/connection/filesub.rs @@ -24,10 +24,7 @@ pub struct FileSubscriber { } impl FileSubscriber { - /// Creates a binary subsciber from a BcSubscrption. - /// When reading the next packet it will skip over multiple - /// Bc packets to fill the binary buffer so ensure you - /// only want binary packets when calling read + /// Creates a file subsciber from a list of files pub fn from_files>(paths: Vec

) -> FileSubscriber { FileSubscriber { files: paths diff --git a/crates/core/src/bc_protocol/ledstate.rs b/crates/core/src/bc_protocol/ledstate.rs index 6be34d8..333e35f 100644 --- a/crates/core/src/bc_protocol/ledstate.rs +++ b/crates/core/src/bc_protocol/ledstate.rs @@ -3,7 +3,7 @@ use crate::bc::{model::*, xml::*}; impl BcCamera { /// Get the [LedState] xml which contains the LED status of the camera - pub fn get_ledstate(&mut self) -> Result { + pub fn get_ledstate(&self) -> Result { let connection = self .connection .as_ref() @@ -49,7 +49,7 @@ impl BcCamera { } /// Set the led lights using the [LedState] xml - pub fn set_ledstate(&mut self, mut led_state: LedState) -> Result<()> { + pub fn set_ledstate(&self, mut led_state: LedState) -> Result<()> { let connection = self .connection .as_ref() @@ -100,7 +100,7 @@ impl BcCamera { /// /// This is for the RED IR lights that can come on automaitcally /// during low light. - pub fn irled_light_set(&mut self, state: LightState) -> Result<()> { + pub fn irled_light_set(&self, state: LightState) -> Result<()> { let mut led_state = self.get_ledstate()?; led_state.state = match state { LightState::On => "open".to_string(), @@ -115,7 +115,7 @@ impl BcCamera { /// True is on and false is off /// /// This is for the little blue on light of some camera - pub fn led_light_set(&mut self, state: bool) -> Result<()> { + pub fn led_light_set(&self, state: bool) -> Result<()> { let mut led_state = self.get_ledstate()?; led_state.light_state = match state { true => "open".to_string(), diff --git a/crates/core/src/bc_protocol/motion.rs b/crates/core/src/bc_protocol/motion.rs new file mode 100644 index 0000000..5a33690 --- /dev/null +++ b/crates/core/src/bc_protocol/motion.rs @@ -0,0 +1,132 @@ +use super::{BcCamera, Error, Result, RX_TIMEOUT}; +use crate::bc::{model::*, xml::*}; + +/// Motion Status that the callback can send +pub enum MotionStatus { + /// Sent when motion is first detected + Start, + /// Sent when motion stops + Stop, + /// Sent when an Alarm about something other than motion was received + NoChange, +} + +/// This is a conveince type for the error of the MotionOutput callback +pub type MotionOutputError = Result; + +/// Trait used as part of [`listen_on_motion`] to send motion messages +pub trait MotionOutput { + /// This is the callback used when motion is received + /// + /// If result is `Ok(true)` more messages will be sent + /// + /// If result if `Ok(false)` then message will be stopped + /// + /// If result is `Err(E)` then motion messages be stopped + /// and an error will be thrown + fn motion_recv(&mut self, motion_status: MotionStatus) -> MotionOutputError; +} + +impl BcCamera { + /// This message tells the camera to send the motion events to us + /// Which are the recieved on msgid 33 + fn start_motion_query(&self) -> Result<()> { + let connection = self + .connection + .as_ref() + .expect("Must be connected to listen to messages"); + + let sub = connection.subscribe(MSG_ID_MOTION_REQUEST)?; + let msg = Bc { + meta: BcMeta { + msg_id: MSG_ID_MOTION_REQUEST, + channel_id: self.channel_id, + msg_num: self.new_message_num(), + stream_type: 0, + response_code: 0, + class: 0x6414, + }, + body: BcBody::ModernMsg(ModernMsg { + ..Default::default() + }), + }; + + sub.send(msg)?; + + let msg = sub.rx.recv_timeout(RX_TIMEOUT)?; + + if let BcMeta { + response_code: 200, .. + } = msg.meta + { + Ok(()) + } else { + Err(Error::UnintelligibleReply { + reply: msg, + why: "The camera did not accept the request to start motion", + }) + } + } + + /// This requests that motion messages be listen to and sent to the + /// output struct. + /// + /// The output structure must implement the [`MotionCallback`] trait + pub fn listen_on_motion(&self, data_out: &mut T) -> Result<()> { + self.start_motion_query()?; + + let connection = self + .connection + .as_ref() + .expect("Must be connected to listen to messages"); + + // After start_motion_query (MSG_ID 31) the camera sends motion messages + // when whenever motion is detected. + let sub = connection.subscribe(MSG_ID_MOTION)?; + + loop { + // Mostly ignore when timout is reached because these messages are only + // sent when motion is detected which might means hours between messages + // being received + let msg = sub.rx.recv_timeout(RX_TIMEOUT); + let status = match msg { + Ok(motion_msg) => { + if let BcBody::ModernMsg(ModernMsg { + payload: + Some(BcPayloads::BcXml(BcXml { + alarm_event_list: Some(alarm_event_list), + .. + })), + .. + }) = motion_msg.body + { + let mut result = MotionStatus::NoChange; + for alarm_event in &alarm_event_list.alarm_events { + if alarm_event.channel_id == self.channel_id { + if alarm_event.status == "MD" { + result = MotionStatus::Start; + break; + } else if alarm_event.status == "none" { + result = MotionStatus::Stop; + break; + } + } + } + Ok(result) + } else { + Ok(MotionStatus::NoChange) + } + } + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => Ok(MotionStatus::NoChange), + // On connection drop we stop + Err(e @ std::sync::mpsc::RecvTimeoutError::Disconnected) => Err(e), + }?; + + match data_out.motion_recv(status) { + Ok(true) => {} + Ok(false) => return Ok(()), + Err(e) => return Err(e), + } + } + } +} diff --git a/crates/core/src/bc_protocol/reboot.rs b/crates/core/src/bc_protocol/reboot.rs index ce6fe47..4d5430a 100644 --- a/crates/core/src/bc_protocol/reboot.rs +++ b/crates/core/src/bc_protocol/reboot.rs @@ -32,7 +32,7 @@ impl BcCamera { } else { Err(Error::UnintelligibleReply { reply: msg, - why: "The camera did not except the TalkConfig xml", + why: "The camera did not accept the reboot command", }) } } diff --git a/crates/core/src/bc_protocol/stream.rs b/crates/core/src/bc_protocol/stream.rs index 0f5cd1d..6c0b24e 100644 --- a/crates/core/src/bc_protocol/stream.rs +++ b/crates/core/src/bc_protocol/stream.rs @@ -2,17 +2,23 @@ use super::{BcCamera, BinarySubscriber, Result}; use crate::{ bc::{model::*, xml::*}, bcmedia::model::*, - Never, }; /// Convience type for the error raised by the [StreamOutput] trait -pub type StreamOutputError = Result<()>; +pub type StreamOutputError = Result; /// The method [`BcCamera::start_video()`] requires a structure with this trait to pass the /// audio and video data back to pub trait StreamOutput { /// This is the callback raised a complete media packet is received - fn write(&mut self, media: BcMedia) -> StreamOutputError; + /// + /// If result is `Ok(true)` more messages will be sent + /// + /// If result if `Ok(false)` then message will be stopped + /// + /// If result is `Err(E)` then messages be stopped + /// and an error will be thrown + fn stream_recv(&mut self, media: BcMedia) -> StreamOutputError; } /// The stream names supported by BC @@ -46,7 +52,7 @@ impl BcCamera { /// /// This will block forever or return an error when the camera connection is dropped /// - pub fn start_video(&self, data_outs: &mut Outputs, stream: Stream) -> Result + pub fn start_video(&self, data_outs: &mut Outputs, stream: Stream) -> Result<()> where Outputs: StreamOutput, { @@ -119,7 +125,11 @@ impl BcCamera { loop { let bc_media = BcMedia::deserialize(&mut media_sub)?; // We now have a complete interesting packet. Send it to on the callback - data_outs.write(bc_media)?; + match data_outs.stream_recv(bc_media) { + Ok(true) => {} + Ok(false) => return Ok(()), + Err(e) => return Err(e), + }; } } } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index cbeca6c..6b725d4 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -33,11 +33,6 @@ pub mod bcmedia; /// Contains low level structures and formats for the udpstream pub mod bcudp; -#[derive(Debug)] -/// Certain method just as `start_video` will block forever or return an error -/// In such a case the return type is `Result` -pub enum Never {} - /// This is the top level error structure of the library /// /// Most commands will either return their `Ok(result)` or this `Err(Error)` diff --git a/src/rtsp/gst.rs b/src/rtsp/gst.rs index 2955c07..77a67a1 100644 --- a/src/rtsp/gst.rs +++ b/src/rtsp/gst.rs @@ -57,7 +57,7 @@ enum StreamFormat { } impl StreamOutput for GstOutputs { - fn write(&mut self, media: BcMedia) -> StreamOutputError { + fn stream_recv(&mut self, media: BcMedia) -> StreamOutputError { match media { BcMedia::Iframe(payload) => { let video_type = match payload.video_type { @@ -88,7 +88,7 @@ impl StreamOutput for GstOutputs { } } - Ok(()) + Ok(true) } } diff --git a/src/rtsp/mod.rs b/src/rtsp/mod.rs index 6c11129..0ce7859 100644 --- a/src/rtsp/mod.rs +++ b/src/rtsp/mod.rs @@ -31,7 +31,6 @@ use anyhow::{Context, Result}; use log::*; use neolink_core::bc_protocol::{BcCamera, Stream}; -use neolink_core::Never; use std::collections::HashSet; use std::sync::Arc; use std::time::Duration; @@ -120,36 +119,41 @@ fn camera_loop( stream_name: Stream, outputs: &mut GstOutputs, manage: bool, -) -> Result { +) -> Result<(), anyhow::Error> { let min_backoff = Duration::from_secs(1); let max_backoff = Duration::from_secs(15); let mut current_backoff = min_backoff; loop { - let cam_err = camera_main(camera_config, stream_name, outputs, manage).unwrap_err(); - outputs.vidsrc.on_stream_error(); - outputs.audsrc.on_stream_error(); - // Authentication failures are permanent; we retry everything else - if cam_err.connected { - current_backoff = min_backoff; - } - if cam_err.login_fail { - error!( - "Authentication failed to camera {}, not retrying", - camera_config.name - ); - return Err(cam_err.err); - } else { - error!( - "Error streaming from camera {}, will retry in {}s: {:?}", - camera_config.name, - current_backoff.as_secs(), - cam_err.err - ) - } + if let Err(cam_err) = camera_main(camera_config, stream_name, outputs, manage) { + outputs.vidsrc.on_stream_error(); + outputs.audsrc.on_stream_error(); + // Authentication failures are permanent; we retry everything else + if cam_err.connected { + current_backoff = min_backoff; + } + if cam_err.login_fail { + error!( + "Authentication failed to camera {}, not retrying", + camera_config.name + ); + return Err(cam_err.err); + } else { + error!( + "Error streaming from camera {}, will retry in {}s: {:?}", + camera_config.name, + current_backoff.as_secs(), + cam_err.err + ) + } - std::thread::sleep(current_backoff); - current_backoff = std::cmp::min(max_backoff, current_backoff * 2); + std::thread::sleep(current_backoff); + current_backoff = std::cmp::min(max_backoff, current_backoff * 2); + } else { + // Should not occur because we don't set the callback up + // in such a way that it requests graceful shutdown + return Ok(()); + } } } @@ -209,7 +213,7 @@ fn camera_main( stream_name: Stream, outputs: &mut GstOutputs, manage: bool, -) -> Result { +) -> Result<(), CameraErr> { let mut connected = false; let mut login_fail = false; (|| {