automation_rs/src/devices/debug_bridge.rs
Dreaded_X 9385f27125
All checks were successful
Build and deploy automation_rs / Build automation_rs (push) Successful in 5m30s
Build and deploy automation_rs / Build Docker image (push) Successful in 55s
Build and deploy automation_rs / Deploy Docker container (push) Has been skipped
Improved how devices are created, ntfy and presence are now treated like any other device
2024-04-27 02:55:53 +02:00

87 lines
2.3 KiB
Rust

use async_trait::async_trait;
use automation_macro::{LuaDevice, LuaDeviceConfig};
use tracing::{trace, warn};
use crate::config::MqttDeviceConfig;
use crate::devices::Device;
use crate::error::DeviceConfigError;
use crate::event::{OnDarkness, OnPresence};
use crate::messages::{DarknessMessage, PresenceMessage};
use crate::mqtt::WrappedAsyncClient;
#[derive(Debug, LuaDeviceConfig, Clone)]
pub struct DebugBridgeConfig {
identifier: String,
#[device_config(flatten)]
pub mqtt: MqttDeviceConfig,
#[device_config(from_lua)]
client: WrappedAsyncClient,
}
#[derive(Debug, LuaDevice)]
pub struct DebugBridge {
#[config]
config: DebugBridgeConfig,
}
impl DebugBridge {
async fn create(config: DebugBridgeConfig) -> Result<Self, DeviceConfigError> {
trace!(id = config.identifier, "Setting up DebugBridge");
Ok(Self { config })
}
}
impl Device for DebugBridge {
fn get_id(&self) -> String {
self.config.identifier.clone()
}
}
#[async_trait]
impl OnPresence for DebugBridge {
async fn on_presence(&mut self, presence: bool) {
let message = PresenceMessage::new(presence);
let topic = format!("{}/presence", self.config.mqtt.topic);
self.config
.client
.publish(
topic,
rumqttc::QoS::AtLeastOnce,
true,
serde_json::to_string(&message).expect("Serialization should not fail"),
)
.await
.map_err(|err| {
warn!(
"Failed to update presence on {}/presence: {err}",
self.config.mqtt.topic
)
})
.ok();
}
}
#[async_trait]
impl OnDarkness for DebugBridge {
async fn on_darkness(&mut self, dark: bool) {
let message = DarknessMessage::new(dark);
let topic = format!("{}/darkness", self.config.mqtt.topic);
self.config
.client
.publish(
topic,
rumqttc::QoS::AtLeastOnce,
true,
serde_json::to_string(&message).unwrap(),
)
.await
.map_err(|err| {
warn!(
"Failed to update presence on {}/presence: {err}",
self.config.mqtt.topic
)
})
.ok();
}
}