diff --git a/Cargo.lock b/Cargo.lock index be48a93..080b54d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1266,6 +1266,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "json" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "078e285eafdfb6c4b434e0d31e8cfcb5115b651496faca5749b88fafd4f23bfd" + [[package]] name = "lazy_static" version = "1.4.0" @@ -1421,8 +1427,10 @@ dependencies = [ "gstreamer-app", "gstreamer-rtsp", "gstreamer-rtsp-server", + "heck", "is_sorted", "itertools", + "json", "lazy_static", "log", "neolink_core", diff --git a/Cargo.toml b/Cargo.toml index 1329791..f159b4d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,8 +23,10 @@ gstreamer = "0.20.3" gstreamer-app = "0.20.0" gstreamer-rtsp = "0.20.0" gstreamer-rtsp-server = { version = "0.20.3", features = ["v1_16"] } +heck = "0.4.1" is_sorted = "0.1.1" itertools = "0.10.5" +json = "0.12.4" lazy_static = "1.4.0" log = { version = "0.4.17", features = [ "release_max_level_debug" ] } neolink_core = { path = "crates/core", version = "0.5.12" } diff --git a/sample_config.toml b/sample_config.toml index da37fb6..1f8128f 100644 --- a/sample_config.toml +++ b/sample_config.toml @@ -38,6 +38,10 @@ address = "192.168.1.187:9000" # mqtt.broker_addr = "192.168.1.122" # mqtt.port = 1883 # mqtt.credentials = ["mqtt_user", "mqtt_password"] +# MQTT Discovery: https://www.home-assistant.io/integrations/mqtt/#mqtt-discovery +# mqtt.discovery.topic = homeassistant # Uncomment to enable +# If using discovery, _ characters are replaced with spaces in the name and title case is applied +# mqtt.discovery.features = ["floodlight"] # Uncomment if this camera has a spotlight/floodlight # If you use a battery camera: **Instead** of an `address` supply the uid # as follows diff --git a/src/config.rs b/src/config.rs index 2cfd870..842b774 100644 --- a/src/config.rs +++ b/src/config.rs @@ -146,6 +146,16 @@ pub(crate) struct MqttConfig { #[serde(default)] pub(crate) client_auth: Option<(std::path::PathBuf, std::path::PathBuf)>, + + #[serde(default)] + pub(crate) discovery: Option, +} + +#[derive(Debug, Deserialize, Clone, Validate)] +pub(crate) struct MqttDiscoveryConfig { + pub(crate) topic: String, + + pub(crate) features: Vec, } fn validate_mqtt_config(config: &MqttConfig) -> Result<(), ValidationError> { diff --git a/src/mqtt/mod.rs b/src/mqtt/mod.rs index d0b0056..80eedaf 100644 --- a/src/mqtt/mod.rs +++ b/src/mqtt/mod.rs @@ -9,6 +9,7 @@ /// /// Control messages: /// +/// - `/control/floodlight [on|off]` Turns floodlight (if equipped) on/off /// - `/control/led [on|off]` Turns status LED on/off /// - `/control/pir [on|off]` Turns PIR on/off /// - `/control/ir [on|off|auto]` Turn IR lights on/off or automatically via light detection @@ -60,11 +61,13 @@ mod cmdline; mod event_cam; mod mqttc; -use crate::config::{CameraConfig, Config, MqttConfig}; +use crate::config::{CameraConfig, Config, MqttConfig, MqttDiscoveryConfig}; use anyhow::{anyhow, Context, Error, Result}; pub(crate) use cmdline::Opt; use event_cam::EventCam; pub(crate) use event_cam::{Direction, Messages}; +use heck::ToTitleCase; +use json::{array, object}; use log::*; use mqttc::{Mqtt, MqttReplyRef}; @@ -167,6 +170,10 @@ async fn listen_on_camera(cam_config: Arc, mqtt_config: &MqttConfi .with_context(|| { format!("Failed to post connect over MQTT for {}", camera_name) })?; + + if let Some(discovery_config) = &mqtt_config.discovery { + enable_discovery(discovery_config, &mqtt_sender_cam, &cam_config).await?; + } } Messages::FloodlightOn => { mqtt_sender_cam @@ -174,7 +181,7 @@ async fn listen_on_camera(cam_config: Arc, mqtt_config: &MqttConfi .await .with_context(|| { format!( - "Failed to publish gloodlight on over MQTT for {}", + "Failed to publish floodlight on over MQTT for {}", camera_name ) })?; @@ -185,7 +192,7 @@ async fn listen_on_camera(cam_config: Arc, mqtt_config: &MqttConfi .await .with_context(|| { format!( - "Failed to publish gloodlight off over MQTT for {}", + "Failed to publish floodlight off over MQTT for {}", camera_name ) })?; @@ -219,6 +226,109 @@ async fn listen_on_camera(cam_config: Arc, mqtt_config: &MqttConfi Ok(()) } +/// Enables MQTT discovery for a camera. See docs at https://www.home-assistant.io/integrations/mqtt/#mqtt-discovery +async fn enable_discovery( + discovery_config: &MqttDiscoveryConfig, + mqtt_sender: &MqttSender, + cam_config: &Arc, +) -> Result<()> { + debug!("Enabling MQTT discovery for {}", cam_config.name); + + let mut connections = array![]; + if let Some(addr) = &cam_config.camera_addr { + connections + .push(array!["camera_addr", addr.clone()]) + .expect("Failed to add camera_addr to connections"); + } + if let Some(uid) = &cam_config.camera_uid { + connections + .push(array!["camera_uid", uid.clone()]) + .expect("Failed to add camera_uid to connections"); + } + + if connections.is_empty() { + error!( + "No connections found for camera {}, either addr or UID must be supplied", + cam_config.name + ); + return Ok(()); + } + + let friendly_name = cam_config.name.replace("_", " ").to_title_case(); + let device = object! { + connections: connections, + name: friendly_name.clone(), + identifiers: array![format!("neolink_{}", cam_config.name)], + manufacturer: "Reolink", + model: "Neolink", + sw_version: env!("CARGO_PKG_VERSION"), + }; + + let availability = object! { + topic: format!("neolink/{}/status", cam_config.name), + payload_available: "connected", + }; + + for feature in &discovery_config.features { + match feature.as_str() { + "floodlight" => { + let discovery_prefix = format!("{}/light", discovery_config.topic); + + let config_data = object! { + // Common across all potential features + device: device.clone(), + availability: availability.clone(), + + // Identifiers + name: format!("{} Floodlight", friendly_name.clone()), + unique_id: format!("neolink_{}_floodlight", cam_config.name), + // Match native home assistant integration: https://github.com/home-assistant/core/blob/dev/homeassistant/components/reolink/light.py#L49 + icon: "mdi:spotlight-beam", + + // State + state_topic: format!("neolink/{}/status/floodlight", cam_config.name), + state_value_template: "{{ value_json.state }}", + + // Control + command_topic: format!("neolink/{}/control/floodlight", cam_config.name), + // Lowercase payloads to match neolink convention + payload_on: "on", + payload_off: "off", + }; + + // Each feature needs to be individually registered + mqtt_sender + .send_message_with_root_topic( + &discovery_prefix, + "config", + &config_data.dump(), + true, + ) + .await + .with_context(|| { + format!( + "Failed to publish auto-discover data on over MQTT for {}", + cam_config.name + ) + })?; + } + _ => { + error!( + "Unsupported MQTT feature {} for {}", + feature, cam_config.name + ); + } + } + } + + info!( + "Enabled MQTT discovery for {} with friendly name {}", + cam_config.name, friendly_name + ); + + Ok(()) +} + async fn handle_mqtt_message( msg: &MqttReply, event_cam_sender: EventCamSender, diff --git a/src/mqtt/mqttc.rs b/src/mqtt/mqttc.rs index bbfedef..6dea40d 100644 --- a/src/mqtt/mqttc.rs +++ b/src/mqtt/mqttc.rs @@ -50,15 +50,16 @@ pub(crate) struct MqttSender { } impl MqttSender { - pub async fn send_message( + pub async fn send_message_with_root_topic( &self, + root_topic: &str, sub_topic: &str, message: &str, retain: bool, ) -> Result<(), ClientError> { self.client .publish( - format!("neolink/{}/{}", self.name, sub_topic), + format!("{}/{}/{}", root_topic, self.name, sub_topic), QoS::AtLeastOnce, retain, message, @@ -67,6 +68,17 @@ impl MqttSender { Ok(()) } + pub async fn send_message( + &self, + sub_topic: &str, + message: &str, + retain: bool, + ) -> Result<(), ClientError> { + self.send_message_with_root_topic("neolink", sub_topic, message, retain) + .await?; + Ok(()) + } + async fn subscribe(&self) -> Result<(), ClientError> { self.client .subscribe(format!("neolink/{}/#", self.name), QoS::AtMostOnce)