From 6653fc43ac590fe11e59255def5da7a8dab468f7 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Thu, 26 Oct 2023 09:35:25 +0700 Subject: [PATCH] Add discovery and status into mqtt for floodlight tasks --- crates/core/src/bc_protocol/floodlight.rs | 22 ++++++--- src/config.rs | 16 +++++++ src/mqtt/discovery.rs | 45 ++++++++++++++++++ src/mqtt/mod.rs | 58 +++++++++++++++++++++-- 4 files changed, 129 insertions(+), 12 deletions(-) diff --git a/crates/core/src/bc_protocol/floodlight.rs b/crates/core/src/bc_protocol/floodlight.rs index ec2cf94..76b320f 100644 --- a/crates/core/src/bc_protocol/floodlight.rs +++ b/crates/core/src/bc_protocol/floodlight.rs @@ -187,15 +187,23 @@ impl BcCamera { Ok(()) } - /// Activate the Flood Light night mode + /// Convience function: Activate the Flood Light night mode pub async fn flightlight_tasks_enable(&self, state: bool) -> Result<()> { - let mut curr_state = self.get_flightlight_tasks().await?; // println!("{:?}", pir_state); - curr_state.enable = match state { - true => 1, - false => 0, - }; - self.set_flightlight_tasks(curr_state).await?; + if self.is_flightlight_tasks_enabled().await? != state { + let mut curr_state = self.get_flightlight_tasks().await?; + curr_state.enable = match state { + true => 1, + false => 0, + }; + self.set_flightlight_tasks(curr_state).await?; + } Ok(()) } + + /// Convience function: Check if Flood Light tasks are enbabled + pub async fn is_flightlight_tasks_enabled(&self) -> Result { + let curr_state = self.get_flightlight_tasks().await?; + Ok(curr_state.enable == 1) + } } diff --git a/src/config.rs b/src/config.rs index be9bf17..cfea560 100644 --- a/src/config.rs +++ b/src/config.rs @@ -247,6 +247,20 @@ pub(crate) struct MqttConfig { #[serde(default = "default_2000")] pub(crate) preview_update: u64, + /// Enable the flood light tasks status + /// Will not do anything if no floodlight + /// is detected + #[serde(default = "default_true")] + pub(crate) enable_floodlight: bool, + /// Update time in ms + #[validate(range( + min = 500, + message = "Update ms should be > 500", + code = "floodlight_update" + ))] + #[serde(default = "default_2000")] + pub(crate) floodlight_update: u64, + #[serde(default)] pub(crate) discovery: Option, } @@ -284,6 +298,8 @@ fn default_mqtt() -> MqttConfig { battery_update: 2000, enable_preview: true, preview_update: 2000, + enable_floodlight: true, + floodlight_update: 2000, discovery: Default::default(), } } diff --git a/src/mqtt/discovery.rs b/src/mqtt/discovery.rs index 9bedcc2..1790e1c 100644 --- a/src/mqtt/discovery.rs +++ b/src/mqtt/discovery.rs @@ -286,6 +286,51 @@ pub(crate) async fn enable_discovery( cam_config.name ) })?; + + let config_data = DiscoverySwitch { + // Common across all potential features + device: device.clone(), + availability: availability.clone(), + + // Identifiers + name: format!("{} FloodlightTasks", friendly_name.as_str()), + unique_id: format!("neolink_{}_floodlight_tasks", cam_config.name), + // Match native home assistant integration: https://github.com/home-assistant/core/blob/dev/homeassistant/components/reolink/light.py#L49 + icon: Some("mdi:spotlight-beam".to_string()), + + // State + state_topic: Some(format!( + "neolink/{}/status/floodlight_tasks", + cam_config.name + )), + state_on: Some("on".to_string()), + state_off: Some("off".to_string()), + + // Control + command_topic: format!("neolink/{}/control/floodlight_tasks", cam_config.name), + // Lowercase payloads to match neolink convention + payload_on: "on".to_string(), + payload_off: "off".to_string(), + }; + + // Each feature needs to be individually registered + mqtt.send_message_with_root_topic( + &format!( + "{}/switch/{}", + discovery_config.topic, &config_data.unique_id + ), + "config", + &serde_json::to_string(&config_data) + .with_context(|| "Cound not serialise discovery switch config into json")?, + true, + ) + .await + .with_context(|| { + format!( + "Failed to publish floodlight tasks auto-discover data on over MQTT for {}", + cam_config.name + ) + })?; } Discoveries::Camera => { let config_data = DiscoveryCamera { diff --git a/src/mqtt/mod.rs b/src/mqtt/mod.rs index dafca57..071c578 100644 --- a/src/mqtt/mod.rs +++ b/src/mqtt/mod.rs @@ -309,6 +309,9 @@ async fn listen_on_camera(camera: NeoInstance, mqtt_instance: MqttInstance) -> R let camera_battery = camera.clone(); let mqtt_battery = mqtt_instance.resubscribe().await?; + let camera_floodlight_tasks = camera.clone(); + let mqtt_floodlight_tasks = mqtt_instance.resubscribe().await?; + tokio::select! { _ = cancel.cancelled() => AnyResult::Ok(()), // Handles incomming requests @@ -560,6 +563,45 @@ async fn listen_on_camera(camera: NeoInstance, mqtt_instance: MqttInstance) -> R }?; } } => v, + // Handle the floodlight task activation + v = async { + let flt_status = camera_floodlight_tasks.run_task(|cam| Box::pin(async move { + Ok(cam.is_flightlight_tasks_enabled().await?) + })).await; + if flt_status.is_err() { + // Assume floodlight unsupported + futures::future::pending::<()>().await; + } + let flt_status = flt_status.unwrap(); + let flt_status_txt = match flt_status { + true => "on".to_string(), + false => "off".to_string(), + }; + mqtt_floodlight_tasks.send_message("status/floodlight_tasks", &flt_status_txt, true).await.with_context(|| { + format!("{}: Failed to publish floodlight task notification", camera_name) + })?; + + let mut wait = IntervalStream::new({ + let mut i = interval(Duration::from_millis(config.floodlight_update)); + i.set_missed_tick_behavior(MissedTickBehavior::Skip); + i + }); + while wait.next().await.is_some() { + let flt_status = camera_floodlight_tasks.run_passive_task(|cam| Box::pin(async move { + Ok(cam.is_flightlight_tasks_enabled().await?) + })).await; + if let Ok(flt_status) = flt_status { + let flt_status_txt = match flt_status { + true => "on".to_string(), + false => "off".to_string(), + }; + mqtt_floodlight_tasks.send_message("status/floodlight_tasks", &flt_status_txt, true).await.with_context(|| { + format!("{}: Failed to publish floodlight task notification", camera_name) + })?; + } + } + AnyResult::Ok(()) + }, if config.enable_floodlight => v, }?; AnyResult::Ok(()) } => v, @@ -1041,7 +1083,16 @@ async fn handle_mqtt_message( topic: "control/floodlight_tasks", message, } => { - let reply = match message.parse::() { + let state = match message.to_lowercase().as_ref() { + "on" => Ok(true), + "off" => Ok(false), + n => match n.parse::() { + Ok(state) => Ok(state), + Err(e) => AnyResult::Err(e.into()), + }, + }; + + let reply = match state { Ok(state) => { if let Err(e) = camera .run_task(|cam| { @@ -1057,10 +1108,7 @@ async fn handle_mqtt_message( "OK".to_string() } } - Err(e) => { - error!("Failed to parse message as bool: {:?}", e); - format!("FAIL: '{message}' => {e:?}") - } + Err(e) => format!("FAIL: Could not parse message to {e:?}"), }; mqtt.send_message("control/floodlight_tasks", &reply, false)