From a33897ec2c725e350a14a285d058fa28ed0a9d9a Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Mon, 17 Jan 2022 21:02:48 +0700 Subject: [PATCH] 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)