Add discovery and status into mqtt for floodlight tasks

This commit is contained in:
QuantumEntangledAndy committed 2023-10-26 09:35:25 +07:00
1 parent 484d16c262
commit 6653fc43ac
4 files changed
+129 -12

No files matched your search

+15 -7
View File
@@ -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<bool> {
let curr_state = self.get_flightlight_tasks().await?;
Ok(curr_state.enable == 1)
}
}
+16
View File
@@ -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<MqttDiscoveryConfig>,
}
@@ -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(),
}
}
+45
View File
@@ -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 {
+53 -5
View File
@@ -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::<bool>() {
let state = match message.to_lowercase().as_ref() {
"on" => Ok(true),
"off" => Ok(false),
n => match n.parse::<bool>() {
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)