Feature/optional MQTT discovery

Adds config options to enable MQTT Discovery as documented here: https://www.home-assistant.io/integrations/mqtt/#mqtt-discovery

As discussed in https://github.com/QuantumEntangledAndy/neolink/pull/14#issuecomment-1561076262

Unfortinuately, the floodlight/spotlight doesn't show up in the `<AbilityInfo>` returned by the camera: https://github.com/QuantumEntangledAndy/neolink/pull/14#issuecomment-1563728970

Open to other suggestions on how to detect or enable these options.
This commit is contained in:
Kevin David committed 2023-06-03 12:55:01 -04:00
1 parent cf67a05dd1
commit fc8adf2a5c
6 files changed
+151 -5

No files matched your search

Generated
+8
View File
@@ -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",
+2
View File
@@ -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" }
+4
View File
@@ -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
+10
View File
@@ -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<MqttDiscoveryConfig>,
}
#[derive(Debug, Deserialize, Clone, Validate)]
pub(crate) struct MqttDiscoveryConfig {
pub(crate) topic: String,
pub(crate) features: Vec<String>,
}
fn validate_mqtt_config(config: &MqttConfig) -> Result<(), ValidationError> {
+113 -3
View File
@@ -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<CameraConfig>, 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<CameraConfig>, 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<CameraConfig>, 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<CameraConfig>, 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<CameraConfig>,
) -> 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,
+14 -2
View File
@@ -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)