From a17a826f3ce35a51a577916e927e0c8e29e03776 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Tue, 10 Aug 2021 11:24:43 +0700 Subject: [PATCH 1/5] Added motion to core and made streams abortable via their callback --- crates/core/src/bc/model.rs | 4 + crates/core/src/bc/xml.rs | 32 ++++++ crates/core/src/bc_protocol.rs | 2 + crates/core/src/bc_protocol/filesub.rs | 5 +- crates/core/src/bc_protocol/ledstate.rs | 8 +- crates/core/src/bc_protocol/motion.rs | 132 ++++++++++++++++++++++++ crates/core/src/bc_protocol/reboot.rs | 2 +- crates/core/src/bc_protocol/stream.rs | 20 +++- crates/core/src/lib.rs | 5 - src/rtsp/gst.rs | 4 +- src/rtsp/mod.rs | 54 +++++----- 11 files changed, 221 insertions(+), 47 deletions(-) create mode 100644 crates/core/src/bc_protocol/motion.rs diff --git a/crates/core/src/bc/model.rs b/crates/core/src/bc/model.rs index 588e282..d71babd 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; /// Ping messages have this ID diff --git a/crates/core/src/bc/xml.rs b/crates/core/src/bc/xml.rs index 1aea64a..193347c 100644 --- a/crates/core/src/bc/xml.rs +++ b/crates/core/src/bc/xml.rs @@ -66,6 +66,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 { @@ -388,6 +391,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 c6dda1c..03c6499 100644 --- a/crates/core/src/bc_protocol.rs +++ b/crates/core/src/bc_protocol.rs @@ -15,6 +15,7 @@ pub(crate) mod filesub; mod ledstate; mod login; mod logout; +mod motion; mod ping; mod reboot; mod stream; @@ -25,6 +26,7 @@ mod version; pub use binarysub::BinarySubscriber; pub use errors::Error; pub use ledstate::LightState; +pub use motion::{MotionOutput, MotionOutputError, MotionStatus}; pub use stream::{StreamOutput, StreamOutputError}; type Result = std::result::Result; diff --git a/crates/core/src/bc_protocol/filesub.rs b/crates/core/src/bc_protocol/filesub.rs index d27ec86..f5530b9 100644 --- a/crates/core/src/bc_protocol/filesub.rs +++ b/crates/core/src/bc_protocol/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..379f3eb 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 except the reboot", }) } } diff --git a/crates/core/src/bc_protocol/stream.rs b/crates/core/src/bc_protocol/stream.rs index ba4aebd..27c0c3d 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; } impl BcCamera { @@ -29,7 +35,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_name: &str) -> Result + pub fn start_video(&self, data_outs: &mut Outputs, stream_name: &str) -> Result<()> where Outputs: StreamOutput, { @@ -72,7 +78,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 4b6076a..01ce1b6 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -31,11 +31,6 @@ pub mod bc_protocol; /// Contains low level structures and formats for the media substream pub mod bcmedia; -#[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 120b614..b7d0fc3 100644 --- a/src/rtsp/mod.rs +++ b/src/rtsp/mod.rs @@ -30,7 +30,6 @@ /// use log::*; use neolink_core::bc_protocol::BcCamera; -use neolink_core::Never; use std::collections::HashSet; use std::fs; use std::sync::Arc; @@ -118,37 +117,40 @@ fn camera_loop( stream_name: &str, outputs: &mut GstOutputs, manage: bool, -) -> Result { +) -> Result<(), 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; - } - match cam_err.err { - neolink_core::Error::AuthFailed => { - error!( - "Authentication failed to camera {}, not retrying", - camera_config.name - ); - return Err(cam_err.err.into()); + 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; + } + match cam_err.err { + neolink_core::Error::AuthFailed => { + error!( + "Authentication failed to camera {}, not retrying", + camera_config.name + ); + return Err(cam_err.err.into()); + } + _ => error!( + "Error streaming from camera {}, will retry in {}s: {:?}", + camera_config.name, + current_backoff.as_secs(), + cam_err.err + ), } - _ => 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 { + return Ok(()); + } } } @@ -207,7 +209,7 @@ fn camera_main( stream_name: &str, outputs: &mut GstOutputs, manage: bool, -) -> Result { +) -> Result<(), CameraErr> { let mut connected = false; (|| { let mut camera = BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id)?; From 20601b897ef7ebcc0940d71bcb4eca0240a19b03 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Tue, 10 Aug 2021 11:25:01 +0700 Subject: [PATCH 2/5] Added mqtt command --- .github/workflows/build.yml | 1 + Cargo.lock | 303 ++++++++++++++++++++++++++++++++++-- Cargo.toml | 3 + src/cmdline.rs | 1 + src/errors.rs | 2 + src/main.rs | 4 + src/mqtt/app.rs | 35 +++++ src/mqtt/cmdline.rs | 10 ++ src/mqtt/config.rs | 65 ++++++++ src/mqtt/errors.rs | 41 +++++ src/mqtt/event_cam.rs | 243 +++++++++++++++++++++++++++++ src/mqtt/mod.rs | 171 ++++++++++++++++++++ src/mqtt/mqttc.rs | 246 +++++++++++++++++++++++++++++ 13 files changed, 1109 insertions(+), 16 deletions(-) create mode 100644 src/mqtt/app.rs create mode 100644 src/mqtt/cmdline.rs create mode 100644 src/mqtt/config.rs create mode 100644 src/mqtt/errors.rs create mode 100644 src/mqtt/event_cam.rs create mode 100644 src/mqtt/mod.rs create mode 100644 src/mqtt/mqttc.rs diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 8fcf811..f4ba852 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -94,6 +94,7 @@ jobs: apt-get install --assume-yes --no-install-recommends \ build-essential \ gcc-${{ matrix.gcc }} \ + g++-${{ matrix.gcc }} \ libgstrtspserver-1.0-dev:${{ matrix.arch }} \ libgstreamer1.0-dev:${{ matrix.arch }} \ libgtk2.0-dev:${{ matrix.arch }} \ diff --git a/Cargo.lock b/Cargo.lock index 73f3d64..43f0ff1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -63,6 +63,17 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "23b62fc65de8e4e7f52534fb52b0f3ed04746ae267519eef2a83941e8085068b" +[[package]] +name = "async-channel" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2114d64672151c0c5eaa5e131ec84a74f06e1e559830dabba01ca30605d66319" +dependencies = [ + "concurrent-queue", + "event-listener", + "futures-core", +] + [[package]] name = "atty" version = "0.2.14" @@ -86,6 +97,12 @@ version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a4521f3e3d031370679b3b140beb36dfe4801b09ac77e30c61941f97df3ef28b" +[[package]] +name = "base64" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd" + [[package]] name = "bitflags" version = "1.2.1" @@ -116,6 +133,24 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65c1bf4a04a88c54f589125563643d773f3254b5c38571395e2b591c693bbc81" +[[package]] +name = "bytes" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b700ce4376041dcd0a327fd0097c41095743c4c8af8887265942faf1100bd040" + +[[package]] +name = "cache-padded" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "631ae5198c9be5e753e5cc215e1bd73c2b466a3565173db433f52bb9d3e66dba" + +[[package]] +name = "cc" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e70cc2f62c6ce1868963827bd677764c62d07c3d9a3e1fb1177ee1a9ab199eb2" + [[package]] name = "cfb-mode" version = "0.6.0" @@ -170,6 +205,15 @@ dependencies = [ "vec_map", ] +[[package]] +name = "concurrent-queue" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30ed07550be01594c6026cff2a1d7fe9c8f683caa798e12b68694ac9e88286a3" +dependencies = [ + "cache-padded", +] + [[package]] name = "const_fn" version = "0.4.8" @@ -189,11 +233,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69323bff1fb41c635347b8ead484a5ca6c3f11914d784170b158d8449ab07f8e" dependencies = [ "cfg-if 0.1.10", - "crossbeam-channel", + "crossbeam-channel 0.4.4", "crossbeam-deque", "crossbeam-epoch", "crossbeam-queue", - "crossbeam-utils", + "crossbeam-utils 0.7.2", ] [[package]] @@ -202,10 +246,20 @@ version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b153fe7cbef478c567df0f972e02e6d736db11affe43dfc9c56a9374d1adfb87" dependencies = [ - "crossbeam-utils", + "crossbeam-utils 0.7.2", "maybe-uninit", ] +[[package]] +name = "crossbeam-channel" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06ed27e177f16d65f0f0c22a213e17c696ace5dd64b14258b52f9417ccb52db4" +dependencies = [ + "cfg-if 1.0.0", + "crossbeam-utils 0.8.5", +] + [[package]] name = "crossbeam-deque" version = "0.7.4" @@ -213,7 +267,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c20ff29ded3204c5106278a81a38f4b482636ed4fa1e6cfbeef193291beb29ed" dependencies = [ "crossbeam-epoch", - "crossbeam-utils", + "crossbeam-utils 0.7.2", "maybe-uninit", ] @@ -225,7 +279,7 @@ checksum = "058ed274caafc1f60c4997b5fc07bf7dc7cca454af7c6e81edffe5f33f70dace" dependencies = [ "autocfg", "cfg-if 0.1.10", - "crossbeam-utils", + "crossbeam-utils 0.7.2", "lazy_static", "maybe-uninit", "memoffset", @@ -239,7 +293,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "774ba60a54c213d409d5353bda12d49cd68d14e45036a285234c8d6f91f92570" dependencies = [ "cfg-if 0.1.10", - "crossbeam-utils", + "crossbeam-utils 0.7.2", "maybe-uninit", ] @@ -254,6 +308,16 @@ dependencies = [ "lazy_static", ] +[[package]] +name = "crossbeam-utils" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d82cfc11ce7f2c3faef78d8a684447b40d503d9681acebed6cb728d45940c4db" +dependencies = [ + "cfg-if 1.0.0", + "lazy_static", +] + [[package]] name = "discard" version = "1.0.4" @@ -293,6 +357,18 @@ dependencies = [ "synstructure", ] +[[package]] +name = "event-listener" +version = "2.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7531096570974c3a9dcf9e4b8e1cede1ec26cf5046219fb3b9d897503b9be59" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + [[package]] name = "form_urlencoded" version = "1.0.1" @@ -684,6 +760,17 @@ dependencies = [ "libc", ] +[[package]] +name = "http" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527e8c9ac747e28542699a951517aa9a6945af506cd1f2e1b53a576c17b6cc11" +dependencies = [ + "bytes", + "fnv", + "itoa", +] + [[package]] name = "humantime" version = "2.1.0" @@ -754,6 +841,15 @@ version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dd25036021b0de88a0aff6b850051563c6516d0bf53f8638938edbb9de732736" +[[package]] +name = "js-sys" +version = "0.3.52" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce791b7ca6638aae45be056e068fc756d871eb3b3b10b8efa62d1c9cec616752" +dependencies = [ + "wasm-bindgen", +] + [[package]] name = "lazy_static" version = "1.4.0" @@ -821,6 +917,37 @@ dependencies = [ "autocfg", ] +[[package]] +name = "mio" +version = "0.7.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c2bdb6314ec10835cd3293dd268473a835c02b7b352e788be788b3c6ca6bb16" +dependencies = [ + "libc", + "log", + "miow", + "ntapi", + "winapi", +] + +[[package]] +name = "miow" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9f1c5b025cda876f66ef43a113f91ebc9f4ccef34843000e0adf6ebbab84e21" +dependencies = [ + "winapi", +] + +[[package]] +name = "mqttbytes" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d710573f2144656d97b82b7ad85c464a1c35ae065278fbee545d40034ec1de5a" +dependencies = [ + "bytes", +] + [[package]] name = "muldiv" version = "1.0.0" @@ -836,6 +963,7 @@ dependencies = [ "cfb-mode", "cookie-factory", "crossbeam", + "crossbeam-channel 0.5.1", "env_logger", "err-derive", "gstreamer", @@ -849,10 +977,12 @@ dependencies = [ "neolink_core", "nom", "regex", + "rumqttc", "serde", "socket2", "structopt", "time", + "tokio", "toml", "validator", "validator_derive", @@ -894,6 +1024,15 @@ dependencies = [ "version_check", ] +[[package]] +name = "ntapi" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6bb902e437b6d86e03cce10a7e2af662292c5dfef23b65899ea3ac9354ad44" +dependencies = [ + "winapi", +] + [[package]] name = "num-integer" version = "0.1.44" @@ -966,6 +1105,12 @@ version = "0.3.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3831453b3449ceb48b6d9c7ad7c96d5ea673e9b470a1dc578c2ce6521230884c" +[[package]] +name = "pollster" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb20dcc30536a1508e75d47dd0e399bb2fe7354dcf35cda9127f2bf1ed92e30e" + [[package]] name = "pretty-hex" version = "0.2.1" @@ -1053,6 +1198,39 @@ version = "0.6.25" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f497285884f3fcff424ffc933e56d7cbca511def0c9831a7f9b5f6153e3cc89b" +[[package]] +name = "ring" +version = "0.16.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3053cf52e236a3ed746dfc745aa9cacf1b791d846bdaf412f60a8d7d6e17c8fc" +dependencies = [ + "cc", + "libc", + "once_cell", + "spin", + "untrusted", + "web-sys", + "winapi", +] + +[[package]] +name = "rumqttc" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd4cf48aa8588d907fc835c47fbc8ef01dc30552467fbf0123cd794f77fd2072" +dependencies = [ + "async-channel", + "bytes", + "http", + "log", + "mqttbytes", + "pollster", + "thiserror", + "tokio", + "tokio-rustls", + "webpki", +] + [[package]] name = "rustc_version" version = "0.2.3" @@ -1062,6 +1240,19 @@ dependencies = [ "semver", ] +[[package]] +name = "rustls" +version = "0.19.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35edb675feee39aec9c99fa5ff985081995a06d594114ae14cbe797ad7b7a6d7" +dependencies = [ + "base64", + "log", + "ring", + "sct", + "webpki", +] + [[package]] name = "rustversion" version = "1.0.5" @@ -1080,6 +1271,16 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" +[[package]] +name = "sct" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b362b83898e0e69f38515b82ee15aa80636befe47c3b6d3d89a911e78fc228ce" +dependencies = [ + "ring", + "untrusted", +] + [[package]] name = "semver" version = "0.9.0" @@ -1155,6 +1356,12 @@ dependencies = [ "winapi", ] +[[package]] +name = "spin" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" + [[package]] name = "standback" version = "0.2.17" @@ -1405,6 +1612,44 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c" +[[package]] +name = "tokio" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b7b349f11a7047e6d1276853e612d152f5e8a352c61917887cc2169e2366b4c" +dependencies = [ + "autocfg", + "bytes", + "libc", + "memchr", + "mio", + "pin-project-lite", + "tokio-macros", + "winapi", +] + +[[package]] +name = "tokio-macros" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54473be61f4ebe4efd09cec9bd5d16fa51d70ea0192213d754d2d500457db110" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tokio-rustls" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc6844de72e57df1980054b38be3a9f4702aba4858be64dd700181a8a6d0e1b6" +dependencies = [ + "rustls", + "tokio", + "webpki", +] + [[package]] name = "toml" version = "0.5.8" @@ -1462,6 +1707,12 @@ version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f14ee04d9415b52b3aeab06258a3f07093182b88ba0f9b8d203f211a7a7d41c7" +[[package]] +name = "untrusted" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" + [[package]] name = "url" version = "2.2.2" @@ -1524,9 +1775,9 @@ checksum = "5fecdca9a5291cc2b8dcf7dc02453fee791a280f3743cb0905f8822ae463b3fe" [[package]] name = "wasm-bindgen" -version = "0.2.74" +version = "0.2.75" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d54ee1d4ed486f78874278e63e4069fc1ab9f6a18ca492076ffb90c5eb2997fd" +checksum = "b608ecc8f4198fe8680e2ed18eccab5f0cd4caaf3d83516fa5fb2e927fda2586" dependencies = [ "cfg-if 1.0.0", "wasm-bindgen-macro", @@ -1534,9 +1785,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-backend" -version = "0.2.74" +version = "0.2.75" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b33f6a0694ccfea53d94db8b2ed1c3a8a4c86dd936b13b9f0a15ec4a451b900" +checksum = "580aa3a91a63d23aac5b6b267e2d13cb4f363e31dce6c352fca4752ae12e479f" dependencies = [ "bumpalo", "lazy_static", @@ -1549,9 +1800,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.74" +version = "0.2.75" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "088169ca61430fe1e58b8096c24975251700e7b1f6fd91cc9d59b04fb9b18bd4" +checksum = "171ebf0ed9e1458810dfcb31f2e766ad6b3a89dbda42d8901f2b268277e5f09c" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -1559,9 +1810,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.74" +version = "0.2.75" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be2241542ff3d9f241f5e2cb6dd09b37efe786df8851c54957683a49f0987a97" +checksum = "6c2657dd393f03aa2a659c25c6ae18a13a4048cebd220e147933ea837efc589f" dependencies = [ "proc-macro2", "quote", @@ -1572,9 +1823,29 @@ dependencies = [ [[package]] name = "wasm-bindgen-shared" -version = "0.2.74" +version = "0.2.75" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7cff876b8f18eed75a66cf49b65e7f967cb354a7aa16003fb55dbfd25b44b4f" +checksum = "2e0c4a743a309662d45f4ede961d7afa4ba4131a59a639f29b0069c3798bbcc2" + +[[package]] +name = "web-sys" +version = "0.3.52" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01c70a82d842c9979078c772d4a1344685045f1a5628f677c2b2eab4dd7d2696" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki" +version = "0.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e38c0608262c46d4a56202ebabdeb094cef7e560ca7a226c6bf055188aa4ea" +dependencies = [ + "ring", + "untrusted", +] [[package]] name = "winapi" diff --git a/Cargo.toml b/Cargo.toml index 3a5d3de..4b45c62 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,3 +39,6 @@ xml-rs = "0.8" validator = "0.10" validator_derive = "0.10" byte-slice-cast = "1.0.0" +rumqttc = "0.8.0" +tokio = { version = "1.0", features = ["rt", "macros", "io-util"] } +crossbeam-channel = "0.5.1" diff --git a/src/cmdline.rs b/src/cmdline.rs index 80a65a0..3c4bb22 100644 --- a/src/cmdline.rs +++ b/src/cmdline.rs @@ -14,4 +14,5 @@ pub enum Command { StatusLight(super::statusled::Opt), Reboot(super::reboot::Opt), Talk(super::talk::Opt), + Mqtt(super::mqtt::Opt), } diff --git a/src/errors.rs b/src/errors.rs index 009115e..09e2cee 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -11,4 +11,6 @@ pub enum Error { Reboot(#[error(source)] super::reboot::Error), #[error(display = "Talk Error")] Talk(#[error(source)] super::talk::Error), + #[error(display = "Talk Error")] + Mqtt(#[error(source)] super::mqtt::Error), } diff --git a/src/main.rs b/src/main.rs index 475475b..ceaf307 100644 --- a/src/main.rs +++ b/src/main.rs @@ -13,6 +13,7 @@ use structopt::StructOpt; mod cmdline; mod errors; +mod mqtt; mod reboot; mod rtsp; mod statusled; @@ -45,6 +46,9 @@ fn main() -> Result<(), Error> { Command::Talk(opts) => { talk::main(opts)?; } + Command::Mqtt(opts) => { + mqtt::main(opts)?; + } } Ok(()) diff --git a/src/mqtt/app.rs b/src/mqtt/app.rs new file mode 100644 index 0000000..d4030c8 --- /dev/null +++ b/src/mqtt/app.rs @@ -0,0 +1,35 @@ +use std::collections::HashSet; +use std::sync::{Arc, Mutex}; + +// Handles app wide things like aborting all connections +pub(crate) struct App { + aborters: Arc>>, +} + +impl App { + pub(crate) fn new() -> Self { + Self { + aborters: Default::default(), + } + } + + // Abort at a level + // e.g. about camera_event_loop + pub(crate) fn abort(&self, level: &str) { + let mut aborters = self.aborters.lock().unwrap(); + aborters.insert(level.to_string()); + } + + // Checks if any level has aborted + // e.g. app:camera_a::camera_event_loop + // will check if app, camera_a or camera_event_loop has been aborted + pub(crate) fn running(&self, levels: &str) -> bool { + let aborters = self.aborters.lock().unwrap(); + for level in levels.split(':') { + if aborters.contains(&level.to_string()) { + return true; + } + } + false + } +} diff --git a/src/mqtt/cmdline.rs b/src/mqtt/cmdline.rs new file mode 100644 index 0000000..f6e02a7 --- /dev/null +++ b/src/mqtt/cmdline.rs @@ -0,0 +1,10 @@ +use std::path::PathBuf; +use structopt::StructOpt; + +/// The reboot command will reboot the camera +#[derive(StructOpt, Debug)] +pub struct Opt { + /// The path to the config file + #[structopt(short, long, parse(from_os_str))] + pub config: PathBuf, +} diff --git a/src/mqtt/config.rs b/src/mqtt/config.rs new file mode 100644 index 0000000..86b2136 --- /dev/null +++ b/src/mqtt/config.rs @@ -0,0 +1,65 @@ +use serde::Deserialize; +use std::clone::Clone; +use validator::{Validate, ValidationError}; +use validator_derive::Validate; + +#[derive(Debug, Deserialize, Validate, Clone)] +pub(crate) struct Config { + #[validate] + pub(crate) cameras: Vec, +} + +#[derive(Debug, Deserialize, Validate, Clone)] +pub(crate) struct CameraConfig { + pub(crate) name: String, + + #[serde(rename = "address")] + pub(crate) camera_addr: String, + + pub(crate) username: String, + pub(crate) password: Option, + + #[validate(range(min = 0, max = 31, message = "Invalid channel", code = "channel_id"))] + #[serde(default = "default_channel_id")] + pub(crate) channel_id: u8, + + #[validate] + #[serde(default = "default_mqtt")] + pub(crate) mqtt: Option, +} + +#[derive(Debug, Deserialize, Clone, Validate)] +#[validate(schema(function = "validate_mqtt_config", skip_on_field_errors = true))] +pub(crate) struct MqttConfig { + #[serde(alias = "server")] + pub(crate) broker_addr: String, + + pub(crate) port: u16, + + #[serde(default)] + pub(crate) credentials: Option<(String, String)>, + + #[serde(default)] + pub(crate) ca: Option, + + #[serde(default)] + pub(crate) client_auth: Option<(std::path::PathBuf, std::path::PathBuf)>, +} + +fn validate_mqtt_config(config: &MqttConfig) -> Result<(), ValidationError> { + if config.ca.is_some() && config.client_auth.is_some() { + Err(ValidationError::new( + "Cannot have both ca and client_auth set", + )) + } else { + Ok(()) + } +} + +fn default_mqtt() -> Option { + None +} + +fn default_channel_id() -> u8 { + 0 +} diff --git a/src/mqtt/errors.rs b/src/mqtt/errors.rs new file mode 100644 index 0000000..6994eaa --- /dev/null +++ b/src/mqtt/errors.rs @@ -0,0 +1,41 @@ +use err_derive::Error; +use std::convert::From; +use std::sync::{MutexGuard, PoisonError}; + +/// The main error for the reboot subcommand +#[derive(Debug, Error)] +#[allow(clippy::large_enum_variant)] +pub enum Error { + /// Raised when the config file fails to deserlize + #[error(display = "Configuration parsing error")] + Config(#[error(source)] toml::de::Error), + /// Raised when `neolink_core` raises an error + #[error(display = "Communication error")] + Protocol(#[error(source)] neolink_core::Error), + /// Raised when there is an IO error such as unable to find + /// config file + #[error(display = "I/O error")] + Io(#[error(source)] std::io::Error), + /// Raised when the config file fails validataion + #[error(display = "Validation error")] + Validation(#[error(source)] validator::ValidationErrors), + /// Raised when crossbeam fails to recv + #[error(display = "Recv data error")] + CrossbeamRecv(#[error(source)] crossbeam_channel::RecvError), + #[error(display = "Send data error")] + CrossbeamSend, + #[error(display = "Unable to lock mutex")] + Lock, +} + +impl From> for Error { + fn from(_: crossbeam_channel::SendError) -> Self { + Error::CrossbeamSend + } +} + +impl<'a, M> From>> for Error { + fn from(_: PoisonError>) -> Self { + Error::Lock + } +} diff --git a/src/mqtt/event_cam.rs b/src/mqtt/event_cam.rs new file mode 100644 index 0000000..5255131 --- /dev/null +++ b/src/mqtt/event_cam.rs @@ -0,0 +1,243 @@ +use super::App; +use super::{config::CameraConfig, errors::Error}; +use crossbeam_channel::{unbounded, Receiver, Sender, TryRecvError}; +use log::*; +use neolink_core::bc_protocol::{ + BcCamera, Error as BcError, LightState, MotionOutput, MotionOutputError, MotionStatus, +}; +use std::sync::{Arc, Mutex}; + +pub(crate) enum Messages { + None, + Login, + MotionStop, + MotionStart, + Reboot, + StatusLedOn, + StatusLedOff, + IRLedOn, + IRLedOff, + IRLedAuto, +} + +pub(crate) struct EventCam<'a> { + config: &'a CameraConfig, + app: Arc, + channel_out: Arc>>>, + channel_in: Arc>>>, +} + +impl<'a> EventCam<'a> { + pub(crate) fn new(config: &'a CameraConfig, app: Arc) -> Self { + Self { + config, + app, + channel_out: Arc::new(Mutex::new(None)), + channel_in: Arc::new(Mutex::new(None)), + } + } + + pub(crate) fn poll(&self) -> Result { + if let Ok(ref mut channel_out) = self.channel_out.try_lock() { + if let Some(channel_out) = channel_out.as_mut() { + channel_out.recv().map_err(|e| e.into()) + } else { + Ok(Messages::None) + } + } else { + Ok(Messages::None) + } + } + + pub(crate) fn send_message(&self, msg: Messages) -> Result<(), Error> { + if let Ok(ref mut channel_in) = self.channel_in.lock() { + if let Some(channel_in) = channel_in.as_mut() { + channel_in.send(msg).map_err(|e| e.into()) + } else { + Err(Error::CrossbeamSend) + } + } else { + Err(Error::Lock) + } + } + + pub(crate) fn abort(&self) { + self.app.abort(&self.config.name); + } + + pub(crate) fn start_listening(&self) { + let loop_config = self.config; + + // Channels from the camera + let (tx, rx) = unbounded(); + let loop_tx = Arc::new(Mutex::new(tx)); + *self.channel_out.lock().unwrap() = Some(rx); + + // Channels to the camera + let (stx, srx) = unbounded(); + let loop_rx = Arc::new(Mutex::new(srx)); + *self.channel_in.lock().unwrap() = Some(stx); + + while self.app.running(&self.config.name) { + // Ignore errors and just loop + let _ = Self::cam_run( + &loop_config, + loop_tx.clone(), + loop_rx.clone(), + self.app.clone(), + ); + } + } + + fn cam_run( + camera_config: &CameraConfig, + tx: Arc>>, + rx: Arc>>, + app: Arc, + ) -> Result<(), Error> { + info!( + "{}: Connecting to camera at {}", + camera_config.name, camera_config.camera_addr + ); + + let mut camera = + BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id)?; + + info!("{}: Logging in", camera_config.name); + camera.login(&camera_config.username, camera_config.password.as_deref())?; + + (tx.lock()?).send(Messages::Login)?; + + // Shararble cameras + let arc_cam = Arc::new(camera); + let cam_motion = arc_cam.clone(); + let cam_mesg = arc_cam; + + let mut motion_callback = MotionCallback { + app: app.clone(), + tx, + name: camera_config.name.to_string(), + }; + + let mut message_handler = MessageHandler { + app: app.clone(), + rx, + camera: cam_mesg, + name: camera_config.name.to_string(), + }; + + let _ = crossbeam::scope(|s| { + s.spawn(|_| { + let _ = cam_motion.listen_on_motion(&mut motion_callback); + // If listen_on_motion returns then camera disconnect + app.abort(&camera_config.name); + }); + + s.spawn(|_| { + let _ = message_handler.listen(); + }); + }); + + Ok(()) + } +} + +struct MotionCallback { + app: Arc, + tx: Arc>>, + name: String, +} + +impl MotionOutput for MotionCallback { + fn motion_recv(&mut self, motion_status: MotionStatus) -> MotionOutputError { + if self.app.running(&format!("app:{}", self.name)) { + match motion_status { + MotionStatus::Start => { + (self + .tx + .lock() + .map_err(|_| BcError::Other("Failed to lock mutex"))?) + .send(Messages::MotionStart) + .map_err(|_| BcError::Other("Failed to send Message"))?; + } + MotionStatus::Stop => { + (self + .tx + .lock() + .map_err(|_| BcError::Other("Failed to lock mutex"))?) + .send(Messages::MotionStop) + .map_err(|_| BcError::Other("Failed to send Message"))?; + } + _ => {} + } + + Ok(true) + } else { + Ok(false) + } + } +} + +struct MessageHandler { + app: Arc, + rx: Arc>>, + camera: Arc, + name: String, +} + +impl MessageHandler { + fn listen(&mut self) { + if self.app.running(&format!("app:{}", self.name)) { + // Try and lock don't worry if not + if let Ok(ref mut channel_out) = self.rx.try_lock() { + match channel_out.try_recv() { + Ok(message) => match message { + Messages::Reboot => { + if self.camera.reboot().is_err() { + error!("Failed to reboot the camera"); + self.abort() + } + } + Messages::StatusLedOn => { + if self.camera.led_light_set(true).is_err() { + error!("Failed to turn on the status light"); + self.abort(); + } + } + Messages::StatusLedOff => { + if self.camera.led_light_set(false).is_err() { + error!("Failed to turn off the status light"); + self.abort(); + } + } + Messages::IRLedOn => { + if self.camera.irled_light_set(LightState::On).is_err() { + error!("Failed to turn on the status light"); + self.abort(); + } + } + Messages::IRLedOff => { + if self.camera.irled_light_set(LightState::Off).is_err() { + error!("Failed to turn on the status light"); + self.abort(); + } + } + Messages::IRLedAuto => { + if self.camera.irled_light_set(LightState::Auto).is_err() { + error!("Failed to turn on the status light"); + self.abort(); + } + } + _ => {} + }, + Err(TryRecvError::Empty) => (), + Err(TryRecvError::Disconnected) => self.abort(), + } + } + } + } + + fn abort(&self) { + self.app.abort(&self.name); + } +} diff --git a/src/mqtt/mod.rs b/src/mqtt/mod.rs new file mode 100644 index 0000000..ea29b2f --- /dev/null +++ b/src/mqtt/mod.rs @@ -0,0 +1,171 @@ +use log::*; +/// +/// # Neolink Reboot +/// +/// This module handles the reboot subcommand +/// +/// The subcommand attepts to reboot the camera. +/// +/// # Usage +/// +/// ```bash +/// neolink reboot --config=config.toml CameraName +/// ``` +/// +use std::fs; +use std::sync::Arc; +use validator::Validate; + +mod app; +mod cmdline; +mod config; +mod errors; +mod event_cam; +mod mqttc; + +pub(crate) use app::App; +pub(crate) use cmdline::Opt; +use config::{CameraConfig, Config, MqttConfig}; +pub(crate) use errors::Error; +use event_cam::EventCam; +pub(crate) use event_cam::Messages; +use mqttc::{Mqtt, MqttReplyRef}; + +/// Entry point for the reboot subcommand +/// +/// Opt is the command line options +pub fn main(opt: Opt) -> Result<(), Error> { + let config: Config = toml::from_str(&fs::read_to_string(opt.config)?)?; + + config.validate()?; + + let app = App::new(); + let arc_app = Arc::new(app); + + let _ = crossbeam::scope(|s| { + for camera_config in &config.cameras { + if let Some(mqtt_config) = camera_config.mqtt.as_ref() { + let loop_arc_app = arc_app.clone(); + s.spawn(move |_| { + while loop_arc_app.running("app") { + let _ = listen_on_camera(camera_config, mqtt_config, loop_arc_app.clone()); + } + }); + } + } + }); + + Ok(()) +} + +fn listen_on_camera( + cam_config: &CameraConfig, + mqtt_config: &MqttConfig, + app: Arc, +) -> Result<(), Error> { + // Camera thread + let event_cam = EventCam::new(cam_config, app.clone()); + let mqtt = Mqtt::new(mqtt_config, &cam_config.name, app.clone()); + + let _ = crossbeam::scope(|s| { + // Start listening to camera events + s.spawn(|_| { + event_cam.start_listening(); // Loop forever + event_cam.abort(); // Just to ensure everything aborts + }); + + // Start listening to mqtt events + s.spawn(|_| { + if mqtt.start().is_err() { + event_cam.abort(); + } + }); + + // Listen on camera messages and post on mqtt + s.spawn(|_| { + while app.running(&format!("app:{}", cam_config.name.to_string())) { + if let Ok(msg) = event_cam.poll() { + match msg { + Messages::Login => { + if mqtt.send_message("status", "connected", true).is_err() { + error!("Failed to post connect over MQTT for {}", cam_config.name); + } + } + Messages::MotionStop => { + if mqtt.send_message("status/motion", "on", true).is_err() { + error!("Failed to publish motion start for {}", cam_config.name); + } + } + Messages::MotionStart => { + if mqtt.send_message("status/motion", "off", true).is_err() { + error!("Failed to publish motion stop for {}", cam_config.name); + } + } + _ => {} + } + } + } + }); + + // Listen on mqtt messages and post on camera + s.spawn(|_| { + while app.running(&format!("app:{}", cam_config.name.to_string())) { + if let Ok(msg) = mqtt.poll() { + match msg.as_ref() { + MqttReplyRef { + topic: "control/led", + message: "on", + } => { + if event_cam.send_message(Messages::StatusLedOn).is_err() { + error!("Failed to set camera status light on"); + } + } + MqttReplyRef { + topic: "control/led", + message: "off", + } => { + if event_cam.send_message(Messages::StatusLedOff).is_err() { + error!("Failed to set camera status light off"); + } + } + MqttReplyRef { + topic: "control/ir", + message: "on", + } => { + if event_cam.send_message(Messages::IRLedOn).is_err() { + error!("Failed to set camera status light off"); + } + } + MqttReplyRef { + topic: "control/ir", + message: "off", + } => { + if event_cam.send_message(Messages::IRLedOff).is_err() { + error!("Failed to set camera status light off"); + } + } + MqttReplyRef { + topic: "control/ir", + message: "auto", + } => { + if event_cam.send_message(Messages::IRLedAuto).is_err() { + error!("Failed to set camera status light off"); + } + } + MqttReplyRef { + topic: "control/reboot", + .. + } => { + if event_cam.send_message(Messages::Reboot).is_err() { + error!("Failed to set camera status light off"); + } + } + _ => {} + } + } + } + }); + }); + + Ok(()) +} diff --git a/src/mqtt/mqttc.rs b/src/mqtt/mqttc.rs new file mode 100644 index 0000000..f563c8d --- /dev/null +++ b/src/mqtt/mqttc.rs @@ -0,0 +1,246 @@ +use super::{config::MqttConfig, errors::Error, App}; +use crossbeam_channel::{unbounded, Receiver, RecvError, Sender}; +use log::*; +use rumqttc::{ + Client, ClientError, ConnectReturnCode, Connection, Event, Incoming, Key, LastWill, + MqttOptions, Publish, QoS, TlsConfiguration, Transport, +}; +use std::sync::{Arc, Mutex}; + +pub(crate) struct Mqtt { + app: Arc, + client: Mutex, + connection: Mutex, + name: String, + incoming: (Sender, Receiver), + msg_channel: (Sender, Receiver), + drop_message: Mutex>, +} + +pub(crate) struct MqttReply { + pub(crate) topic: String, + pub(crate) message: String, +} + +impl MqttReply { + pub(crate) fn as_ref(&self) -> MqttReplyRef { + MqttReplyRef { + topic: &self.topic, + message: &self.message, + } + } +} + +pub(crate) struct MqttReplyRef<'a> { + pub(crate) topic: &'a str, + pub(crate) message: &'a str, +} + +impl Mqtt { + pub(crate) fn new(config: &MqttConfig, name: &str, app: Arc) -> Arc { + let incoming = unbounded::(); + let msg_channel = unbounded::(); + let mut mqttoptions = MqttOptions::new( + format!("Neolink-{}", name), + &config.broker_addr, + config.port, + ); + + // Use TLS if ca path is set + if let Some(ca_path) = &config.ca { + if let Ok(ca) = std::fs::read(ca_path) { + // Use client_auth if they have cert and key + let client_auth = if let Some((cert_path, key_path)) = &config.client_auth { + if let (Ok(cert_buf), Ok(key_buf)) = + (std::fs::read(cert_path), std::fs::read(key_path)) + { + Some((cert_buf, Key::RSA(key_buf))) + } else { + error!("Failed to set client tls"); + None + } + } else { + None + }; + + let transport = Transport::Tls(TlsConfiguration::Simple { + ca, + alpn: None, + client_auth, + }); + mqttoptions.set_transport(transport); + } else { + error!("Failed to set CA"); + } + }; + + if let Some((username, password)) = &config.credentials { + mqttoptions.set_credentials(username, password); + } + + mqttoptions.set_keep_alive(5); + + // On unclean disconnect send this + mqttoptions.set_last_will(LastWill::new( + format!("neolink/{}/status", name), + "offline", + QoS::AtLeastOnce, + true, + )); + + let (client, connection) = Client::new(mqttoptions, 10); + + let me = Self { + app: app.clone(), + client: Mutex::new(client), + connection: Mutex::new(connection), + name: name.to_string(), + incoming, + msg_channel, + // Send the drop message on clean disconnect + drop_message: Mutex::new(Some(MqttReply { + topic: "status".to_string(), + message: "offline".to_string(), + })), + }; + + let arc_me = Arc::new(me); + + // Start the mqtt server + let mqtt_running = arc_me.clone(); + let mqtt_app = app.clone(); + let mqtt_name = name.to_string(); + std::thread::spawn(move || { + let _ = (*mqtt_running).start(); + mqtt_app.abort(&mqtt_name) + }); + + // Start polling messages + let mqtt_read_app = app; + let mqtt_reading = arc_me.clone(); + let mqtt_read_name = name.to_string(); + std::thread::spawn(move || { + while mqtt_read_app.running(&format!("app:{}", mqtt_read_name)) { + if (*mqtt_reading).handle_message().is_err() { + error!( + "Failed to get messages from mqtt client {}", + (mqtt_read_name) + ); + } + } + }); + + arc_me + } + + #[allow(unused)] + pub(crate) fn set_drop_message(&mut self, topic: &str, message: &str) { + self.drop_message.lock().unwrap().replace(MqttReply { + topic: topic.to_string(), + message: message.to_string(), + }); + } + + fn subscribe(&self) -> Result<(), ClientError> { + let mut client = self.client.lock().unwrap(); + client.subscribe(format!("neolink/{}/#", self.name), QoS::AtMostOnce)?; + Ok(()) + } + + fn update_status(&self) -> Result<(), ClientError> { + self.send_message("status", "disconnected", true)?; + Ok(()) + } + + pub fn send_message( + &self, + sub_topic: &str, + message: &str, + retain: bool, + ) -> Result<(), ClientError> { + let mut client = self.client.lock().unwrap(); + client.publish( + format!("neolink/{}/{}", self.name, sub_topic), + QoS::AtLeastOnce, + retain, + message, + )?; + Ok(()) + } + + fn handle_message(&self) -> Result<(), RecvError> { + let (_, receiver) = &self.incoming; + let published_message = receiver.recv()?; + + if let Some(sub_topic) = published_message + .topic + .strip_prefix(&format!("neolink/{}/", &self.name)) + { + if self + .msg_channel + .0 + .send(MqttReply { + topic: sub_topic.to_string(), + message: String::from_utf8_lossy(published_message.payload.as_ref()) + .into_owned(), + }) + .is_err() + { + error!("Failed to send messages up the mqtt msg channel"); + } + } + + Ok(()) + } + + pub fn get_message_listener(&self) -> Receiver { + self.msg_channel.1.clone() + } + + pub(crate) fn poll(&self) -> Result { + self.get_message_listener().recv().map_err(|e| e.into()) + } + + pub(crate) fn start(&self) -> Result<(), ClientError> { + // This acts as an event loop + let mut connection = self.connection.lock().unwrap(); + let (sender, _) = &self.incoming; + info!("Starting MQTT Client for {}", self.name); + while self.app.running(&format!("app:{}", self.name)) { + for (_i, notification) in connection.iter().enumerate() { + if let Ok(notification) = notification { + match notification { + Event::Incoming(Incoming::ConnAck(connected)) => { + if ConnectReturnCode::Success == connected.code { + self.update_status()?; + // We succesfully logged in. Now ask for the cameras subscription. + self.subscribe()?; + } + } + Event::Incoming(Incoming::Publish(published_message)) => { + if sender.send(published_message).is_err() { + error!("Failed to publish motion message on mqtt"); + } + } + _ => {} + } + } + } + } + Ok(()) + } +} + +impl Drop for Mqtt { + fn drop(&mut self) { + let drop_message = self.drop_message.lock().unwrap(); + if let Some(drop_message) = drop_message.as_ref() { + if self + .send_message(&drop_message.topic, &drop_message.message, true) + .is_err() + { + error!("Failed to send offline message to mqtt"); + } + } + } +} From cc517588fe5dea7696cd9f686d797e92937180e2 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Tue, 10 Aug 2021 14:53:35 +0700 Subject: [PATCH 3/5] Make the loops in mqtt abort cleanly --- src/mqtt/app.rs | 4 ++-- src/mqtt/event_cam.rs | 4 +++- src/mqtt/mod.rs | 14 +++++++------- src/mqtt/mqttc.rs | 1 + 4 files changed, 13 insertions(+), 10 deletions(-) diff --git a/src/mqtt/app.rs b/src/mqtt/app.rs index d4030c8..18042df 100644 --- a/src/mqtt/app.rs +++ b/src/mqtt/app.rs @@ -27,9 +27,9 @@ impl App { let aborters = self.aborters.lock().unwrap(); for level in levels.split(':') { if aborters.contains(&level.to_string()) { - return true; + return false; } } - false + true } } diff --git a/src/mqtt/event_cam.rs b/src/mqtt/event_cam.rs index 5255131..58c3f80 100644 --- a/src/mqtt/event_cam.rs +++ b/src/mqtt/event_cam.rs @@ -105,6 +105,7 @@ impl<'a> EventCam<'a> { info!("{}: Logging in", camera_config.name); camera.login(&camera_config.username, camera_config.password.as_deref())?; + info!("{}: Connected and logged in", camera_config.name); (tx.lock()?).send(Messages::Login)?; @@ -127,12 +128,14 @@ impl<'a> EventCam<'a> { }; let _ = crossbeam::scope(|s| { + info!("{}: Listening to Camera Motion", camera_config.name); s.spawn(|_| { let _ = cam_motion.listen_on_motion(&mut motion_callback); // If listen_on_motion returns then camera disconnect app.abort(&camera_config.name); }); + info!("{}: Setting up camera actions", camera_config.name); s.spawn(|_| { let _ = message_handler.listen(); }); @@ -170,7 +173,6 @@ impl MotionOutput for MotionCallback { } _ => {} } - Ok(true) } else { Ok(false) diff --git a/src/mqtt/mod.rs b/src/mqtt/mod.rs index ea29b2f..205b4cc 100644 --- a/src/mqtt/mod.rs +++ b/src/mqtt/mod.rs @@ -46,6 +46,7 @@ pub fn main(opt: Opt) -> Result<(), Error> { for camera_config in &config.cameras { if let Some(mqtt_config) = camera_config.mqtt.as_ref() { let loop_arc_app = arc_app.clone(); + info!("{}: Setting up mqtt", camera_config.name); s.spawn(move |_| { while loop_arc_app.running("app") { let _ = listen_on_camera(camera_config, mqtt_config, loop_arc_app.clone()); @@ -76,9 +77,8 @@ fn listen_on_camera( // Start listening to mqtt events s.spawn(|_| { - if mqtt.start().is_err() { - event_cam.abort(); - } + let _ = mqtt.start().is_err(); + event_cam.abort(); }); // Listen on camera messages and post on mqtt @@ -92,13 +92,13 @@ fn listen_on_camera( } } Messages::MotionStop => { - if mqtt.send_message("status/motion", "on", true).is_err() { - error!("Failed to publish motion start for {}", cam_config.name); + if mqtt.send_message("status/motion", "off", true).is_err() { + error!("Failed to publish motion stop for {}", cam_config.name); } } Messages::MotionStart => { - if mqtt.send_message("status/motion", "off", true).is_err() { - error!("Failed to publish motion stop for {}", cam_config.name); + if mqtt.send_message("status/motion", "on", true).is_err() { + error!("Failed to publish motion start for {}", cam_config.name); } } _ => {} diff --git a/src/mqtt/mqttc.rs b/src/mqtt/mqttc.rs index f563c8d..6b95a93 100644 --- a/src/mqtt/mqttc.rs +++ b/src/mqtt/mqttc.rs @@ -116,6 +116,7 @@ impl Mqtt { }); // Start polling messages + info!("{}: Starting listening to mqtt", name); let mqtt_read_app = app; let mqtt_reading = arc_me.clone(); let mqtt_read_name = name.to_string(); From 81e7fd8ecf41f139bf09d4e7e570db524864c1e8 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Sun, 15 Aug 2021 16:14:39 +0700 Subject: [PATCH 4/5] Bug fix to event loop --- src/mqtt/event_cam.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/mqtt/event_cam.rs b/src/mqtt/event_cam.rs index 58c3f80..9e6bc11 100644 --- a/src/mqtt/event_cam.rs +++ b/src/mqtt/event_cam.rs @@ -189,7 +189,7 @@ struct MessageHandler { impl MessageHandler { fn listen(&mut self) { - if self.app.running(&format!("app:{}", self.name)) { + while self.app.running(&format!("app:{}", self.name)) { // Try and lock don't worry if not if let Ok(ref mut channel_out) = self.rx.try_lock() { match channel_out.try_recv() { From a33897ec2c725e350a14a285d058fa28ed0a9d9a Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Mon, 17 Jan 2022 21:02:48 +0700 Subject: [PATCH 5/5] Bug and clippy lint squashing --- Cargo.lock | 278 +++++++++++++++++- crates/core/src/bc/de.rs | 9 +- crates/core/src/bc/ser.rs | 2 +- crates/core/src/bc/xml.rs | 1 + .../connection/udpconn/discover.rs | 6 +- crates/core/src/bc_protocol/stream.rs | 2 +- crates/core/src/bcmedia/de.rs | 2 +- crates/core/src/bcudp/de.rs | 2 +- crates/core/src/bcudp/model.rs | 1 + crates/core/src/bcudp/xml_crypto.rs | 3 +- src/config.rs | 36 +++ src/main.rs | 4 +- src/mqtt/config.rs | 65 ---- src/mqtt/errors.rs | 41 --- src/mqtt/event_cam.rs | 44 ++- src/mqtt/mod.rs | 20 +- src/mqtt/mqttc.rs | 16 +- src/rtsp/gst.rs | 2 +- src/rtsp/mod.rs | 21 +- src/statusled/mod.rs | 2 +- 20 files changed, 375 insertions(+), 182 deletions(-) delete mode 100644 src/mqtt/config.rs delete mode 100644 src/mqtt/errors.rs diff --git a/Cargo.lock b/Cargo.lock index e828ff0..b0d6c31 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -69,6 +69,17 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b34d609dfbaf33d6889b2b7106d3ca345eacad44200913df5ba02bfd31d2ba9" +[[package]] +name = "async-channel" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2114d64672151c0c5eaa5e131ec84a74f06e1e559830dabba01ca30605d66319" +dependencies = [ + "concurrent-queue", + "event-listener", + "futures-core", +] + [[package]] name = "atty" version = "0.2.14" @@ -92,6 +103,12 @@ version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a4521f3e3d031370679b3b140beb36dfe4801b09ac77e30c61941f97df3ef28b" +[[package]] +name = "base64" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd" + [[package]] name = "bitflags" version = "1.2.1" @@ -128,12 +145,30 @@ version = "1.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" +[[package]] +name = "bytes" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4872d67bab6358e59559027aa3b9157c53d9358c51423c17554809a8858e0f8" + [[package]] name = "c_linked_list" version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4964518bd3b4a8190e832886cdc0da9794f12e8e6c1613a9e90ff331c4c8724b" +[[package]] +name = "cache-padded" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1db59621ec70f09c5e9b597b220c7a2b43611f4710dc03ceb8748637775692c" + +[[package]] +name = "cc" +version = "1.0.72" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22a9137b95ea06864e018375b72adfb7db6e6f68cfc8df5a04d00288050485ee" + [[package]] name = "cfb-mode" version = "0.6.0" @@ -188,6 +223,15 @@ dependencies = [ "vec_map", ] +[[package]] +name = "concurrent-queue" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30ed07550be01594c6026cff2a1d7fe9c8f683caa798e12b68694ac9e88286a3" +dependencies = [ + "cache-padded", +] + [[package]] name = "const-sha1" version = "0.2.0" @@ -346,6 +390,18 @@ dependencies = [ "synstructure", ] +[[package]] +name = "event-listener" +version = "2.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7531096570974c3a9dcf9e4b8e1cede1ec26cf5046219fb3b9d897503b9be59" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + [[package]] name = "form_urlencoded" version = "1.0.1" @@ -776,6 +832,17 @@ dependencies = [ "libc", ] +[[package]] +name = "http" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31f4c6746584866f0feabcc69893c5b51beef3831656a968ed7ae254cdc4fd03" +dependencies = [ + "bytes", + "fnv", + "itoa 1.0.1", +] + [[package]] name = "humantime" version = "2.1.0" @@ -846,6 +913,21 @@ version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dd25036021b0de88a0aff6b850051563c6516d0bf53f8638938edbb9de732736" +[[package]] +name = "itoa" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aab8fc367588b89dcee83ab0fd66b72b50b72fa1904d7095045ace2b0c81c35" + +[[package]] +name = "js-sys" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cc9ffccd38c451a86bf13657df244e9c3f37493cce8e5e21e940963777acc84" +dependencies = [ + "wasm-bindgen", +] + [[package]] name = "lazy_static" version = "1.4.0" @@ -932,6 +1014,37 @@ dependencies = [ "autocfg", ] +[[package]] +name = "mio" +version = "0.7.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8067b404fe97c70829f082dec8bcf4f71225d7eaea1d8645349cb76fa06205cc" +dependencies = [ + "libc", + "log", + "miow", + "ntapi", + "winapi 0.3.9", +] + +[[package]] +name = "miow" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9f1c5b025cda876f66ef43a113f91ebc9f4ccef34843000e0adf6ebbab84e21" +dependencies = [ + "winapi 0.3.9", +] + +[[package]] +name = "mqttbytes" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d710573f2144656d97b82b7ad85c464a1c35ae065278fbee545d40034ec1de5a" +dependencies = [ + "bytes", +] + [[package]] name = "muldiv" version = "1.0.0" @@ -958,6 +1071,7 @@ dependencies = [ "cfb-mode", "cookie-factory", "crossbeam", + "crossbeam-channel 0.5.1", "env_logger", "err-derive", "gstreamer", @@ -971,10 +1085,12 @@ dependencies = [ "neolink_core", "nom", "regex", + "rumqttc", "serde", "socket2", "structopt", "time", + "tokio", "toml", "validator", "validator_derive", @@ -1024,6 +1140,15 @@ dependencies = [ "version_check", ] +[[package]] +name = "ntapi" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6bb902e437b6d86e03cce10a7e2af662292c5dfef23b65899ea3ac9354ad44" +dependencies = [ + "winapi 0.3.9", +] + [[package]] name = "num-integer" version = "0.1.44" @@ -1096,6 +1221,12 @@ version = "0.3.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3831453b3449ceb48b6d9c7ad7c96d5ea673e9b470a1dc578c2ce6521230884c" +[[package]] +name = "pollster" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb20dcc30536a1508e75d47dd0e399bb2fe7354dcf35cda9127f2bf1ed92e30e" + [[package]] name = "ppv-lite86" version = "0.2.10" @@ -1229,6 +1360,39 @@ version = "0.6.25" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f497285884f3fcff424ffc933e56d7cbca511def0c9831a7f9b5f6153e3cc89b" +[[package]] +name = "ring" +version = "0.16.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3053cf52e236a3ed746dfc745aa9cacf1b791d846bdaf412f60a8d7d6e17c8fc" +dependencies = [ + "cc", + "libc", + "once_cell", + "spin", + "untrusted", + "web-sys", + "winapi 0.3.9", +] + +[[package]] +name = "rumqttc" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd4cf48aa8588d907fc835c47fbc8ef01dc30552467fbf0123cd794f77fd2072" +dependencies = [ + "async-channel", + "bytes", + "http", + "log", + "mqttbytes", + "pollster", + "thiserror", + "tokio", + "tokio-rustls", + "webpki", +] + [[package]] name = "rustc_version" version = "0.2.3" @@ -1238,6 +1402,19 @@ dependencies = [ "semver", ] +[[package]] +name = "rustls" +version = "0.19.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35edb675feee39aec9c99fa5ff985081995a06d594114ae14cbe797ad7b7a6d7" +dependencies = [ + "base64", + "log", + "ring", + "sct", + "webpki", +] + [[package]] name = "rustversion" version = "1.0.5" @@ -1256,6 +1433,16 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" +[[package]] +name = "sct" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b362b83898e0e69f38515b82ee15aa80636befe47c3b6d3d89a911e78fc228ce" +dependencies = [ + "ring", + "untrusted", +] + [[package]] name = "semver" version = "0.9.0" @@ -1297,7 +1484,7 @@ version = "1.0.66" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "336b10da19a12ad094b59d870ebde26a45402e5b470add4b5fd03c5048a32127" dependencies = [ - "itoa", + "itoa 0.4.7", "ryu", "serde", ] @@ -1331,6 +1518,12 @@ dependencies = [ "winapi 0.3.9", ] +[[package]] +name = "spin" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" + [[package]] name = "standback" version = "0.2.17" @@ -1581,6 +1774,43 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c" +[[package]] +name = "tokio" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbbf1c778ec206785635ce8ad57fe52b3009ae9e0c9f574a728f3049d3e55838" +dependencies = [ + "bytes", + "libc", + "memchr", + "mio", + "pin-project-lite", + "tokio-macros", + "winapi 0.3.9", +] + +[[package]] +name = "tokio-macros" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b557f72f448c511a979e2564e55d74e6c4432fc96ff4f6241bc6bded342643b7" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tokio-rustls" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc6844de72e57df1980054b38be3a9f4702aba4858be64dd700181a8a6d0e1b6" +dependencies = [ + "rustls", + "tokio", + "webpki", +] + [[package]] name = "toml" version = "0.5.8" @@ -1638,6 +1868,12 @@ version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f14ee04d9415b52b3aeab06258a3f07093182b88ba0f9b8d203f211a7a7d41c7" +[[package]] +name = "untrusted" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" + [[package]] name = "url" version = "2.2.2" @@ -1706,9 +1942,9 @@ checksum = "fd6fbd9a79829dd1ad0cc20627bf1ed606756a7f77edff7b66b7064f9cb327c6" [[package]] name = "wasm-bindgen" -version = "0.2.74" +version = "0.2.78" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d54ee1d4ed486f78874278e63e4069fc1ab9f6a18ca492076ffb90c5eb2997fd" +checksum = "632f73e236b219150ea279196e54e610f5dbafa5d61786303d4da54f84e47fce" dependencies = [ "cfg-if 1.0.0", "wasm-bindgen-macro", @@ -1716,9 +1952,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-backend" -version = "0.2.74" +version = "0.2.78" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b33f6a0694ccfea53d94db8b2ed1c3a8a4c86dd936b13b9f0a15ec4a451b900" +checksum = "a317bf8f9fba2476b4b2c85ef4c4af8ff39c3c7f0cdfeed4f82c34a880aa837b" dependencies = [ "bumpalo", "lazy_static", @@ -1731,9 +1967,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.74" +version = "0.2.78" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "088169ca61430fe1e58b8096c24975251700e7b1f6fd91cc9d59b04fb9b18bd4" +checksum = "d56146e7c495528bf6587663bea13a8eb588d39b36b679d83972e1a2dbbdacf9" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -1741,9 +1977,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.74" +version = "0.2.78" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be2241542ff3d9f241f5e2cb6dd09b37efe786df8851c54957683a49f0987a97" +checksum = "7803e0eea25835f8abdc585cd3021b3deb11543c6fe226dcd30b228857c5c5ab" dependencies = [ "proc-macro2", "quote", @@ -1754,9 +1990,29 @@ dependencies = [ [[package]] name = "wasm-bindgen-shared" -version = "0.2.74" +version = "0.2.78" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7cff876b8f18eed75a66cf49b65e7f967cb354a7aa16003fb55dbfd25b44b4f" +checksum = "0237232789cf037d5480773fe568aac745bfe2afbc11a863e97901780a6b47cc" + +[[package]] +name = "web-sys" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38eb105f1c59d9eaa6b5cdc92b859d85b926e82cb2e0945cd0c9259faa6fe9fb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki" +version = "0.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e38c0608262c46d4a56202ebabdeb094cef7e560ca7a226c6bf055188aa4ea" +dependencies = [ + "ring", + "untrusted", +] [[package]] name = "winapi" diff --git a/crates/core/src/bc/de.rs b/crates/core/src/bc/de.rs index 1943cfb..4b5ebc9 100644 --- a/crates/core/src/bc/de.rs +++ b/crates/core/src/bc/de.rs @@ -169,8 +169,7 @@ fn bc_modern_msg<'a, 'b>( }; // Now we'll take the buffer that Nom gave a ref to and parse it. - let extension; - if ext_len > 0 { + let extension = if ext_len > 0 { // Apply the XML parse function, but throw away the reference to decrypted in the Ok and // Err case. This error-error-error thing is the same idiom Nom uses internally. let parsed = Extension::try_parse(processed_ext_buf) @@ -182,10 +181,10 @@ fn bc_modern_msg<'a, 'b>( { context.in_bin_mode.insert(header.msg_num); } - extension = Some(parsed); + Some(parsed) } else { - extension = None; - } + None + }; // Now to handle the payload block // This block can either be xml or binary depending on what the message expects. diff --git a/crates/core/src/bc/ser.rs b/crates/core/src/bc/ser.rs index f2770ff..ee749cd 100644 --- a/crates/core/src/bc/ser.rs +++ b/crates/core/src/bc/ser.rs @@ -173,7 +173,7 @@ where /// A serializer combinator that does nothing with its input fn do_nothing() -> impl SerializeFn { - move |out: WriteContext| Ok(out) + Ok } #[test] diff --git a/crates/core/src/bc/xml.rs b/crates/core/src/bc/xml.rs index f4a216a..2df25ae 100644 --- a/crates/core/src/bc/xml.rs +++ b/crates/core/src/bc/xml.rs @@ -12,6 +12,7 @@ use indoc::indoc; /// There are two types of payloads xml and binary #[derive(PartialEq, Eq, Debug, YaDeserialize)] #[yaserde(flatten)] +#[allow(clippy::large_enum_variant)] pub enum BcPayloads { /// XML payloads are the more common ones and include payloads for camera controls #[yaserde(rename = "body")] diff --git a/crates/core/src/bc_protocol/connection/udpconn/discover.rs b/crates/core/src/bc_protocol/connection/udpconn/discover.rs index f17c805..aabb873 100644 --- a/crates/core/src/bc_protocol/connection/udpconn/discover.rs +++ b/crates/core/src/bc_protocol/connection/udpconn/discover.rs @@ -40,12 +40,11 @@ impl UdpDiscover { let addrs: Vec = addrs .iter() - .map(|a| { + .flat_map(|a| { a.to_socket_addrs() .ok() .and_then(|mut a_iter| a_iter.next()) }) - .flatten() .collect(); let mut bytes_send = 0; @@ -120,13 +119,12 @@ impl UdpDiscover { let ports: [u16; 2] = [2015, 2018]; let destinations: Vec<(Ipv4Addr, u16)> = broadcasts .iter() - .map(|&addr| { + .flat_map(|&addr| { ports .iter() .map(|&port| (addr, port)) .collect::>() }) - .flatten() .collect(); debug!("Broadcasting to: {:?}", destinations); diff --git a/crates/core/src/bc_protocol/stream.rs b/crates/core/src/bc_protocol/stream.rs index d7186b6..6c0b24e 100644 --- a/crates/core/src/bc_protocol/stream.rs +++ b/crates/core/src/bc_protocol/stream.rs @@ -52,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_name: Stream) -> Result<()> + pub fn start_video(&self, data_outs: &mut Outputs, stream: Stream) -> Result<()> where Outputs: StreamOutput, { diff --git a/crates/core/src/bcmedia/de.rs b/crates/core/src/bcmedia/de.rs index d58f00d..05531f7 100644 --- a/crates/core/src/bcmedia/de.rs +++ b/crates/core/src/bcmedia/de.rs @@ -86,7 +86,7 @@ where impl BcMedia { pub(crate) fn deserialize(r: R) -> Result { // Throw away the nom-specific return types - read_from_reader(|reader| bcmedia(reader), r) + read_from_reader(bcmedia, r) } } diff --git a/crates/core/src/bcudp/de.rs b/crates/core/src/bcudp/de.rs index ab4479c..a691f32 100644 --- a/crates/core/src/bcudp/de.rs +++ b/crates/core/src/bcudp/de.rs @@ -84,7 +84,7 @@ where impl BcUdp { pub(crate) fn deserialize(r: R) -> Result { // Throw away the nom-specific return types - read_from_reader(|reader| bcudp(reader), r) + read_from_reader(bcudp, r) } } diff --git a/crates/core/src/bcudp/model.rs b/crates/core/src/bcudp/model.rs index b82c2d5..ecdd6d5 100644 --- a/crates/core/src/bcudp/model.rs +++ b/crates/core/src/bcudp/model.rs @@ -5,6 +5,7 @@ use super::xml::*; /// Top level udp packet #[derive(Debug, PartialEq, Eq)] +#[allow(clippy::large_enum_variant)] pub enum BcUdp { /// Packet from the negotiate stage when connection info is exchanged Discovery(UdpDiscovery), diff --git a/crates/core/src/bcudp/xml_crypto.rs b/crates/core/src/bcudp/xml_crypto.rs index 147f575..e5e69ef 100644 --- a/crates/core/src/bcudp/xml_crypto.rs +++ b/crates/core/src/bcudp/xml_crypto.rs @@ -5,8 +5,7 @@ const XML_KEY: [u32; 8] = [ pub(crate) fn decrypt(offset: u32, buf: &[u8]) -> Vec { let key = XML_KEY .iter() - .map(|i| (i + offset).to_le_bytes()) - .flatten() + .flat_map(|i| (i + offset).to_le_bytes()) .cycle(); buf.iter().zip(key).map(|(byte, key)| key ^ byte).collect() } diff --git a/src/config.rs b/src/config.rs index 013c3de..7e6582e 100644 --- a/src/config.rs +++ b/src/config.rs @@ -73,6 +73,10 @@ pub(crate) struct CameraConfig { #[validate(range(min = 0, max = 31, message = "Invalid channel", code = "channel_id"))] #[serde(default = "default_channel_id")] pub(crate) channel_id: u8, + + #[validate] + #[serde(default = "default_mqtt")] + pub(crate) mqtt: Option, } #[derive(Debug, Deserialize, Validate, Clone)] @@ -85,6 +89,38 @@ pub(crate) struct UserConfig { pub(crate) pass: String, } +#[derive(Debug, Deserialize, Clone, Validate)] +#[validate(schema(function = "validate_mqtt_config", skip_on_field_errors = true))] +pub(crate) struct MqttConfig { + #[serde(alias = "server")] + pub(crate) broker_addr: String, + + pub(crate) port: u16, + + #[serde(default)] + pub(crate) credentials: Option<(String, String)>, + + #[serde(default)] + pub(crate) ca: Option, + + #[serde(default)] + pub(crate) client_auth: Option<(std::path::PathBuf, std::path::PathBuf)>, +} + +fn validate_mqtt_config(config: &MqttConfig) -> Result<(), ValidationError> { + if config.ca.is_some() && config.client_auth.is_some() { + Err(ValidationError::new( + "Cannot have both ca and client_auth set", + )) + } else { + Ok(()) + } +} + +fn default_mqtt() -> Option { + None +} + fn default_bind_addr() -> String { "0.0.0.0".to_string() } diff --git a/src/main.rs b/src/main.rs index d30b0ad..b78373e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -68,8 +68,8 @@ fn main() -> Result<()> { Some(Command::Talk(opts)) => { talk::main(opts, config)?; } - Command::Mqtt(opts) => { - mqtt::main(opts)?; + Some(Command::Mqtt(opts)) => { + mqtt::main(opts, config)?; } } diff --git a/src/mqtt/config.rs b/src/mqtt/config.rs deleted file mode 100644 index 86b2136..0000000 --- a/src/mqtt/config.rs +++ /dev/null @@ -1,65 +0,0 @@ -use serde::Deserialize; -use std::clone::Clone; -use validator::{Validate, ValidationError}; -use validator_derive::Validate; - -#[derive(Debug, Deserialize, Validate, Clone)] -pub(crate) struct Config { - #[validate] - pub(crate) cameras: Vec, -} - -#[derive(Debug, Deserialize, Validate, Clone)] -pub(crate) struct CameraConfig { - pub(crate) name: String, - - #[serde(rename = "address")] - pub(crate) camera_addr: String, - - pub(crate) username: String, - pub(crate) password: Option, - - #[validate(range(min = 0, max = 31, message = "Invalid channel", code = "channel_id"))] - #[serde(default = "default_channel_id")] - pub(crate) channel_id: u8, - - #[validate] - #[serde(default = "default_mqtt")] - pub(crate) mqtt: Option, -} - -#[derive(Debug, Deserialize, Clone, Validate)] -#[validate(schema(function = "validate_mqtt_config", skip_on_field_errors = true))] -pub(crate) struct MqttConfig { - #[serde(alias = "server")] - pub(crate) broker_addr: String, - - pub(crate) port: u16, - - #[serde(default)] - pub(crate) credentials: Option<(String, String)>, - - #[serde(default)] - pub(crate) ca: Option, - - #[serde(default)] - pub(crate) client_auth: Option<(std::path::PathBuf, std::path::PathBuf)>, -} - -fn validate_mqtt_config(config: &MqttConfig) -> Result<(), ValidationError> { - if config.ca.is_some() && config.client_auth.is_some() { - Err(ValidationError::new( - "Cannot have both ca and client_auth set", - )) - } else { - Ok(()) - } -} - -fn default_mqtt() -> Option { - None -} - -fn default_channel_id() -> u8 { - 0 -} diff --git a/src/mqtt/errors.rs b/src/mqtt/errors.rs deleted file mode 100644 index 6994eaa..0000000 --- a/src/mqtt/errors.rs +++ /dev/null @@ -1,41 +0,0 @@ -use err_derive::Error; -use std::convert::From; -use std::sync::{MutexGuard, PoisonError}; - -/// The main error for the reboot subcommand -#[derive(Debug, Error)] -#[allow(clippy::large_enum_variant)] -pub enum Error { - /// Raised when the config file fails to deserlize - #[error(display = "Configuration parsing error")] - Config(#[error(source)] toml::de::Error), - /// Raised when `neolink_core` raises an error - #[error(display = "Communication error")] - Protocol(#[error(source)] neolink_core::Error), - /// Raised when there is an IO error such as unable to find - /// config file - #[error(display = "I/O error")] - Io(#[error(source)] std::io::Error), - /// Raised when the config file fails validataion - #[error(display = "Validation error")] - Validation(#[error(source)] validator::ValidationErrors), - /// Raised when crossbeam fails to recv - #[error(display = "Recv data error")] - CrossbeamRecv(#[error(source)] crossbeam_channel::RecvError), - #[error(display = "Send data error")] - CrossbeamSend, - #[error(display = "Unable to lock mutex")] - Lock, -} - -impl From> for Error { - fn from(_: crossbeam_channel::SendError) -> Self { - Error::CrossbeamSend - } -} - -impl<'a, M> From>> for Error { - fn from(_: PoisonError>) -> Self { - Error::Lock - } -} diff --git a/src/mqtt/event_cam.rs b/src/mqtt/event_cam.rs index 9e6bc11..81e9851 100644 --- a/src/mqtt/event_cam.rs +++ b/src/mqtt/event_cam.rs @@ -1,5 +1,7 @@ use super::App; -use super::{config::CameraConfig, errors::Error}; +use crate::config::CameraConfig; +use crate::utils::AddressOrUid; +use anyhow::{anyhow, Context, Result}; use crossbeam_channel::{unbounded, Receiver, Sender, TryRecvError}; use log::*; use neolink_core::bc_protocol::{ @@ -37,10 +39,10 @@ impl<'a> EventCam<'a> { } } - pub(crate) fn poll(&self) -> Result { + pub(crate) fn poll(&self) -> Result { if let Ok(ref mut channel_out) = self.channel_out.try_lock() { if let Some(channel_out) = channel_out.as_mut() { - channel_out.recv().map_err(|e| e.into()) + channel_out.recv().context("Camera failed to poll") } else { Ok(Messages::None) } @@ -49,15 +51,17 @@ impl<'a> EventCam<'a> { } } - pub(crate) fn send_message(&self, msg: Messages) -> Result<(), Error> { + pub(crate) fn send_message(&self, msg: Messages) -> Result<()> { if let Ok(ref mut channel_in) = self.channel_in.lock() { if let Some(channel_in) = channel_in.as_mut() { - channel_in.send(msg).map_err(|e| e.into()) + channel_in + .send(msg) + .context("Failed to send message from camera") } else { - Err(Error::CrossbeamSend) + Err(anyhow!("Failed to send camera data over crossbeam")) } } else { - Err(Error::Lock) + Err(anyhow!("Failed to lock")) } } @@ -81,7 +85,7 @@ impl<'a> EventCam<'a> { while self.app.running(&self.config.name) { // Ignore errors and just loop let _ = Self::cam_run( - &loop_config, + loop_config, loop_tx.clone(), loop_rx.clone(), self.app.clone(), @@ -94,20 +98,30 @@ impl<'a> EventCam<'a> { tx: Arc>>, rx: Arc>>, app: Arc, - ) -> Result<(), Error> { + ) -> Result<()> { + let camera_addr = + AddressOrUid::new(&camera_config.camera_addr, &camera_config.camera_uid).unwrap(); + info!( "{}: Connecting to camera at {}", - camera_config.name, camera_config.camera_addr + camera_config.name, camera_addr ); - - let mut camera = - BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id)?; + let mut camera = camera_addr + .connect_camera(camera_config.channel_id) + .with_context(|| { + format!( + "Failed to connect to camera {} at {} on channel {}", + camera_config.name, camera_addr, camera_config.channel_id + ) + })?; info!("{}: Logging in", camera_config.name); - camera.login(&camera_config.username, camera_config.password.as_deref())?; + camera + .login(&camera_config.username, camera_config.password.as_deref()) + .context("Failed to login to the camera")?; info!("{}: Connected and logged in", camera_config.name); - (tx.lock()?).send(Messages::Login)?; + (tx.lock().map_err(|_| anyhow!("Failed to lock"))?).send(Messages::Login)?; // Shararble cameras let arc_cam = Arc::new(camera); diff --git a/src/mqtt/mod.rs b/src/mqtt/mod.rs index 205b4cc..453e491 100644 --- a/src/mqtt/mod.rs +++ b/src/mqtt/mod.rs @@ -12,21 +12,17 @@ use log::*; /// neolink reboot --config=config.toml CameraName /// ``` /// -use std::fs; use std::sync::Arc; -use validator::Validate; mod app; mod cmdline; -mod config; -mod errors; mod event_cam; mod mqttc; +use crate::config::{CameraConfig, Config, MqttConfig}; +use anyhow::Result; pub(crate) use app::App; pub(crate) use cmdline::Opt; -use config::{CameraConfig, Config, MqttConfig}; -pub(crate) use errors::Error; use event_cam::EventCam; pub(crate) use event_cam::Messages; use mqttc::{Mqtt, MqttReplyRef}; @@ -34,11 +30,7 @@ use mqttc::{Mqtt, MqttReplyRef}; /// Entry point for the reboot subcommand /// /// Opt is the command line options -pub fn main(opt: Opt) -> Result<(), Error> { - let config: Config = toml::from_str(&fs::read_to_string(opt.config)?)?; - - config.validate()?; - +pub(crate) fn main(_: Opt, config: Config) -> Result<()> { let app = App::new(); let arc_app = Arc::new(app); @@ -63,7 +55,7 @@ fn listen_on_camera( cam_config: &CameraConfig, mqtt_config: &MqttConfig, app: Arc, -) -> Result<(), Error> { +) -> Result<()> { // Camera thread let event_cam = EventCam::new(cam_config, app.clone()); let mqtt = Mqtt::new(mqtt_config, &cam_config.name, app.clone()); @@ -83,7 +75,7 @@ fn listen_on_camera( // Listen on camera messages and post on mqtt s.spawn(|_| { - while app.running(&format!("app:{}", cam_config.name.to_string())) { + while app.running(&format!("app: {}", cam_config.name)) { if let Ok(msg) = event_cam.poll() { match msg { Messages::Login => { @@ -109,7 +101,7 @@ fn listen_on_camera( // Listen on mqtt messages and post on camera s.spawn(|_| { - while app.running(&format!("app:{}", cam_config.name.to_string())) { + while app.running(&format!("app: {}", cam_config.name)) { if let Ok(msg) = mqtt.poll() { match msg.as_ref() { MqttReplyRef { diff --git a/src/mqtt/mqttc.rs b/src/mqtt/mqttc.rs index 6b95a93..b38abd8 100644 --- a/src/mqtt/mqttc.rs +++ b/src/mqtt/mqttc.rs @@ -1,4 +1,6 @@ -use super::{config::MqttConfig, errors::Error, App}; +use super::App; +use crate::config::MqttConfig; +use anyhow::{Context, Result}; use crossbeam_channel::{unbounded, Receiver, RecvError, Sender}; use log::*; use rumqttc::{ @@ -198,11 +200,13 @@ impl Mqtt { self.msg_channel.1.clone() } - pub(crate) fn poll(&self) -> Result { - self.get_message_listener().recv().map_err(|e| e.into()) + pub(crate) fn poll(&self) -> Result { + self.get_message_listener() + .recv() + .context("Mqtt Polling error") } - pub(crate) fn start(&self) -> Result<(), ClientError> { + pub(crate) fn start(&self) -> Result<()> { // This acts as an event loop let mut connection = self.connection.lock().unwrap(); let (sender, _) = &self.incoming; @@ -213,9 +217,9 @@ impl Mqtt { match notification { Event::Incoming(Incoming::ConnAck(connected)) => { if ConnectReturnCode::Success == connected.code { - self.update_status()?; + self.update_status().context("Failed to update status")?; // We succesfully logged in. Now ask for the cameras subscription. - self.subscribe()?; + self.subscribe().context("Failed to subscribe")?; } } Event::Incoming(Incoming::Publish(published_message)) => { diff --git a/src/rtsp/gst.rs b/src/rtsp/gst.rs index 77a67a1..a779341 100644 --- a/src/rtsp/gst.rs +++ b/src/rtsp/gst.rs @@ -347,7 +347,7 @@ mod maybe_app_src { /// owning the AppSrc directly. This function handles either case and returns the AppSrc, /// or None if the caller has not yet sent one. fn try_get_src(&mut self) -> Option<&AppSrc> { - while let Some(src) = self.rx.try_recv().ok() { + while let Ok(src) = self.rx.try_recv() { self.app_src = Some(src); } self.app_src.as_ref() diff --git a/src/rtsp/mod.rs b/src/rtsp/mod.rs index 68147c3..d35e927 100644 --- a/src/rtsp/mod.rs +++ b/src/rtsp/mod.rs @@ -119,7 +119,7 @@ fn camera_loop( stream_name: Stream, outputs: &mut GstOutputs, manage: bool, -) -> Result<(), Error> { +) -> Result<()> { let min_backoff = Duration::from_secs(1); let max_backoff = Duration::from_secs(15); let mut current_backoff = min_backoff; @@ -132,20 +132,19 @@ fn camera_loop( if cam_err.connected { current_backoff = min_backoff; } - match cam_err.err { - neolink_core::Error::AuthFailed => { - error!( - "Authentication failed to camera {}, not retrying", - camera_config.name - ); - return Err(cam_err.err.into()); - } - _ => error!( + 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); diff --git a/src/statusled/mod.rs b/src/statusled/mod.rs index ed50013..d1efd17 100644 --- a/src/statusled/mod.rs +++ b/src/statusled/mod.rs @@ -27,7 +27,7 @@ pub(crate) use cmdline::Opt; /// /// Opt is the command line options pub(crate) fn main(opt: Opt, config: Config) -> Result<()> { - let mut camera = find_and_connect(&config, &opt.camera)?; + let camera = find_and_connect(&config, &opt.camera)?; camera .led_light_set(opt.on)