From 20601b897ef7ebcc0940d71bcb4eca0240a19b03 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Tue, 10 Aug 2021 11:25:01 +0700 Subject: [PATCH] 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"); + } + } + } +}