Improved how devices are created, ntfy and presence are now treated like any other device
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

This commit is contained in:
Dreaded_X 2024-04-27 02:55:53 +02:00
parent 8c327095fd
commit 9385f27125
Signed by: Dreaded_X
GPG Key ID: 5A0CBFE3C3377FAA
22 changed files with 409 additions and 519 deletions

View File

@ -33,10 +33,11 @@ pub fn impl_lua_device_macro(ast: &DeriveInput) -> TokenStream {
} }
impl mlua::UserData for #name { impl mlua::UserData for #name {
fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) { fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) {
methods.add_function("new", |lua, config: mlua::Value| { methods.add_async_function("new", |lua, config: mlua::Value| async {
let config: #config = mlua::FromLua::from_lua(config, lua)?; let config: #config = mlua::FromLua::from_lua(config, lua)?;
let config: Box<dyn crate::device_manager::DeviceConfig> = Box::new(config); let device = #name::create(config).await.map_err(mlua::ExternalError::into_lua_err)?;
Ok(config)
Ok(crate::device_manager::WrappedDevice::new(Box::new(device)))
}); });
} }
} }

View File

@ -13,65 +13,64 @@ local function mqtt_automation(topic)
return "automation/" .. topic return "automation/" .. topic
end end
automation.device_manager:create( automation.device_manager:add(Ntfy.new({
"debug_bridge", topic = automation.util.get_env("NTFY_TOPIC"),
DebugBridge.new({ event_channel = automation.event_channel,
}))
automation.device_manager:add(Presence.new({
topic = "automation_dev/presence/+/#",
event_channel = automation.event_channel,
}))
automation.device_manager:add(DebugBridge.new({
identifier = "debug_bridge",
topic = mqtt_automation("debug"), topic = mqtt_automation("debug"),
client = automation.mqtt_client, client = automation.mqtt_client,
}) }))
)
local hue_ip = "10.0.0.146" local hue_ip = "10.0.0.146"
local hue_token = automation.util.get_env("HUE_TOKEN") local hue_token = automation.util.get_env("HUE_TOKEN")
automation.device_manager:create( automation.device_manager:add(HueBridge.new({
"hue_bridge", identifier = "hue_bridge",
HueBridge.new({
ip = hue_ip, ip = hue_ip,
login = hue_token, login = hue_token,
flags = { flags = {
presence = 41, presence = 41,
darkness = 43, darkness = 43,
}, },
}) }))
)
automation.device_manager:create( automation.device_manager:add(LightSensor.new({
"living_light_sensor", identifier = "living_light_sensor",
LightSensor.new({
topic = mqtt_z2m("living/light"), topic = mqtt_z2m("living/light"),
min = 22000, min = 22000,
max = 23500, max = 23500,
event_channel = automation.event_channel, event_channel = automation.event_channel,
}) }))
)
automation.device_manager:create( automation.device_manager:add(WakeOnLAN.new({
"living_zeus",
WakeOnLAN.new({
name = "Zeus", name = "Zeus",
room = "Living Room", room = "Living Room",
topic = mqtt_automation("appliance/living_room/zeus"), topic = mqtt_automation("appliance/living_room/zeus"),
mac_address = "30:9c:23:60:9c:13", mac_address = "30:9c:23:60:9c:13",
broadcast_ip = "10.0.0.255", broadcast_ip = "10.0.0.255",
}) }))
)
local living_mixer = automation.device_manager:create("living_mixer", KasaOutlet.new({ ip = "10.0.0.49" })) local living_mixer = KasaOutlet.new({ identifier = "living_mixer", ip = "10.0.0.49" })
local living_speakers = automation.device_manager:create("living_speakers", KasaOutlet.new({ ip = "10.0.0.182" })) automation.device_manager:add(living_mixer)
local living_speakers = KasaOutlet.new({ identifier = "living_speakers", ip = "10.0.0.182" })
automation.device_manager:add(living_speakers)
automation.device_manager:create( automation.device_manager:add(AudioSetup.new({
"living_audio", identifier = "living_audio",
AudioSetup.new({
topic = mqtt_z2m("living/remote"), topic = mqtt_z2m("living/remote"),
mixer = living_mixer, mixer = living_mixer,
speakers = living_speakers, speakers = living_speakers,
}) }))
)
automation.device_manager:create( automation.device_manager:add(IkeaOutlet.new({
"kitchen_kettle",
IkeaOutlet.new({
outlet_type = "Kettle", outlet_type = "Kettle",
name = "Kettle", name = "Kettle",
room = "Kitchen", room = "Kitchen",
@ -82,55 +81,42 @@ automation.device_manager:create(
{ topic = mqtt_z2m("bedroom/remote") }, { topic = mqtt_z2m("bedroom/remote") },
{ topic = mqtt_z2m("kitchen/remote") }, { topic = mqtt_z2m("kitchen/remote") },
}, },
}) }))
)
automation.device_manager:create( automation.device_manager:add(IkeaOutlet.new({
"batchroom_light",
IkeaOutlet.new({
outlet_type = "Light", outlet_type = "Light",
name = "Light", name = "Light",
room = "Bathroom", room = "Bathroom",
topic = mqtt_z2m("batchroom/light"), topic = mqtt_z2m("batchroom/light"),
client = automation.mqtt_client, client = automation.mqtt_client,
timeout = debug and 60 or 45 * 60, timeout = debug and 60 or 45 * 60,
}) }))
)
automation.device_manager:create( automation.device_manager:add(Washer.new({
"bathroom_washer", identifier = "bathroom_washer",
Washer.new({
topic = mqtt_z2m("batchroom/washer"), topic = mqtt_z2m("batchroom/washer"),
threshold = 1, threshold = 1,
event_channel = automation.event_channel, event_channel = automation.event_channel,
}) }))
)
automation.device_manager:create( automation.device_manager:add(IkeaOutlet.new({
"workbench_charger",
IkeaOutlet.new({
outlet_type = "Charger", outlet_type = "Charger",
name = "Charger", name = "Charger",
room = "Workbench", room = "Workbench",
topic = mqtt_z2m("workbench/charger"), topic = mqtt_z2m("workbench/charger"),
client = automation.mqtt_client, client = automation.mqtt_client,
timeout = debug and 5 or 20 * 3600, timeout = debug and 5 or 20 * 3600,
}) }))
)
automation.device_manager:create( automation.device_manager:add(IkeaOutlet.new({
"workbench_outlet",
IkeaOutlet.new({
name = "Outlet", name = "Outlet",
room = "Workbench", room = "Workbench",
topic = mqtt_z2m("workbench/outlet"), topic = mqtt_z2m("workbench/outlet"),
client = automation.mqtt_client, client = automation.mqtt_client,
}) }))
)
local hallway_lights = automation.device_manager:create( local hallway_lights = automation.device_manager:add(HueGroup.new({
"hallway_lights", identifier = "hallway_lights",
HueGroup.new({
ip = hue_ip, ip = hue_ip,
login = hue_token, login = hue_token,
group_id = 81, group_id = 81,
@ -139,12 +125,10 @@ local hallway_lights = automation.device_manager:create(
remotes = { remotes = {
{ topic = mqtt_z2m("hallway/remote") }, { topic = mqtt_z2m("hallway/remote") },
}, },
}) }))
)
automation.device_manager:create( automation.device_manager:add(ContactSensor.new({
"hallway_frontdoor", identifier = "hallway_frontdoor",
ContactSensor.new({
topic = mqtt_z2m("hallway/frontdoor"), topic = mqtt_z2m("hallway/frontdoor"),
client = automation.mqtt_client, client = automation.mqtt_client,
presence = { presence = {
@ -155,18 +139,14 @@ automation.device_manager:create(
devices = { hallway_lights }, devices = { hallway_lights },
timeout = debug and 10 or 2 * 60, timeout = debug and 10 or 2 * 60,
}, },
}) }))
)
local bedroom_air_filter = automation.device_manager:create( local bedroom_air_filter = automation.device_manager:add(AirFilter.new({
"bedroom_air_filter",
AirFilter.new({
name = "Air Filter", name = "Air Filter",
room = "Bedroom", room = "Bedroom",
topic = "pico/filter/bedroom", topic = "pico/filter/bedroom",
client = automation.mqtt_client, client = automation.mqtt_client,
}) }))
)
-- TODO: Use the wrapped device bedroom_air_filter instead of the string -- TODO: Use the wrapped device bedroom_air_filter instead of the string
automation.device_manager:add_schedule({ automation.device_manager:add_schedule({

View File

@ -7,9 +7,3 @@ mqtt:
client_name: "automation_rs" client_name: "automation_rs"
username: "mqtt" username: "mqtt"
password: "${MQTT_PASSWORD}" password: "${MQTT_PASSWORD}"
ntfy:
topic: "${NTFY_TOPIC}"
presence:
topic: "automation/presence/+/#"

View File

@ -8,9 +8,3 @@ mqtt:
username: "mqtt" username: "mqtt"
password: "${MQTT_PASSWORD}" password: "${MQTT_PASSWORD}"
tls: true tls: true
ntfy:
topic: "${NTFY_TOPIC}"
presence:
topic: "automation_dev/presence/+/#"

View File

@ -46,7 +46,7 @@ where
pub trait GoogleHomeDevice: AsGoogleHomeDevice + Sync + Send + 'static { pub trait GoogleHomeDevice: AsGoogleHomeDevice + Sync + Send + 'static {
fn get_device_type(&self) -> Type; fn get_device_type(&self) -> Type;
fn get_device_name(&self) -> Name; fn get_device_name(&self) -> Name;
fn get_id(&self) -> &str; fn get_id(&self) -> String;
fn is_online(&self) -> bool; fn is_online(&self) -> bool;
// Default values that can optionally be overriden // Default values that can optionally be overriden
@ -63,7 +63,7 @@ pub trait GoogleHomeDevice: AsGoogleHomeDevice + Sync + Send + 'static {
async fn sync(&self) -> response::sync::Device { async fn sync(&self) -> response::sync::Device {
let name = self.get_device_name(); let name = self.get_device_name();
let mut device = let mut device =
response::sync::Device::new(self.get_id(), &name.name, self.get_device_type()); response::sync::Device::new(&self.get_id(), &name.name, self.get_device_type());
device.name = name; device.name = name;
device.will_report_state = self.will_report_state(); device.will_report_state = self.will_report_state();

View File

@ -8,7 +8,6 @@ use serde::{Deserialize, Deserializer};
use tracing::debug; use tracing::debug;
use crate::auth::OpenIDConfig; use crate::auth::OpenIDConfig;
use crate::devices::PresenceConfig;
use crate::error::{ConfigParseError, MissingEnv}; use crate::error::{ConfigParseError, MissingEnv};
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
@ -18,8 +17,6 @@ pub struct Config {
pub mqtt: MqttOptions, pub mqtt: MqttOptions,
#[serde(default)] #[serde(default)]
pub fullfillment: FullfillmentConfig, pub fullfillment: FullfillmentConfig,
pub ntfy: Option<NtfyConfig>,
pub presence: PresenceConfig,
} }
#[derive(Debug, Clone, Deserialize)] #[derive(Debug, Clone, Deserialize)]
@ -85,23 +82,22 @@ fn default_fullfillment_port() -> u16 {
7878 7878
} }
#[derive(Debug, Deserialize)]
pub struct NtfyConfig {
#[serde(default = "default_ntfy_url")]
pub url: String,
pub topic: String,
}
fn default_ntfy_url() -> String {
"https://ntfy.sh".into()
}
#[derive(Debug, Clone, Deserialize)] #[derive(Debug, Clone, Deserialize)]
pub struct InfoConfig { pub struct InfoConfig {
pub name: String, pub name: String,
pub room: Option<String>, pub room: Option<String>,
} }
impl InfoConfig {
pub fn identifier(&self) -> String {
(if let Some(room) = &self.room {
room.to_ascii_lowercase().replace(' ', "_") + "_"
} else {
String::new()
}) + &self.name.to_ascii_lowercase().replace(' ', "_")
}
}
#[derive(Debug, Clone, Deserialize)] #[derive(Debug, Clone, Deserialize)]
pub struct MqttDeviceConfig { pub struct MqttDeviceConfig {
pub topic: String, pub topic: String,

View File

@ -2,8 +2,6 @@ use std::collections::HashMap;
use std::ops::{Deref, DerefMut}; use std::ops::{Deref, DerefMut};
use std::sync::Arc; use std::sync::Arc;
use async_trait::async_trait;
use enum_dispatch::enum_dispatch;
use futures::future::join_all; use futures::future::join_all;
use google_home::traits::OnOff; use google_home::traits::OnOff;
use mlua::{FromLua, LuaSerdeExt}; use mlua::{FromLua, LuaSerdeExt};
@ -13,22 +11,14 @@ use tokio_cron_scheduler::{Job, JobScheduler};
use tracing::{debug, error, instrument, trace}; use tracing::{debug, error, instrument, trace};
use crate::devices::{As, Device}; use crate::devices::{As, Device};
use crate::error::DeviceConfigError;
use crate::event::{Event, EventChannel, OnDarkness, OnMqtt, OnNotification, OnPresence}; use crate::event::{Event, EventChannel, OnDarkness, OnMqtt, OnNotification, OnPresence};
use crate::schedule::{Action, Schedule}; use crate::schedule::{Action, Schedule};
#[async_trait]
#[enum_dispatch]
pub trait DeviceConfig {
async fn create(&self, identifier: &str) -> Result<Box<dyn Device>, DeviceConfigError>;
}
impl mlua::UserData for Box<dyn DeviceConfig> {}
#[derive(Debug, FromLua, Clone)] #[derive(Debug, FromLua, Clone)]
pub struct WrappedDevice(Arc<RwLock<Box<dyn Device>>>); pub struct WrappedDevice(Arc<RwLock<Box<dyn Device>>>);
impl WrappedDevice { impl WrappedDevice {
fn new(device: Box<dyn Device>) -> Self { pub fn new(device: Box<dyn Device>) -> Self {
Self(Arc::new(RwLock::new(device))) Self(Arc::new(RwLock::new(device)))
} }
} }
@ -132,13 +122,13 @@ impl DeviceManager {
sched.start().await.unwrap(); sched.start().await.unwrap();
} }
pub async fn add(&self, device: Box<dyn Device>) -> WrappedDevice { pub async fn add(&self, device: &WrappedDevice) {
let id = device.get_id().into(); let id = device.read().await.get_id();
debug!(id, "Adding device"); debug!(id, "Adding device");
// If the device listens to mqtt, subscribe to the topics // If the device listens to mqtt, subscribe to the topics
if let Some(device) = As::<dyn OnMqtt>::cast(device.as_ref()) { if let Some(device) = As::<dyn OnMqtt>::cast(device.read().await.as_ref()) {
for topic in device.topics() { for topic in device.topics() {
trace!(id, topic, "Subscribing to topic"); trace!(id, topic, "Subscribing to topic");
if let Err(err) = self.client.subscribe(topic, QoS::AtLeastOnce).await { if let Err(err) = self.client.subscribe(topic, QoS::AtLeastOnce).await {
@ -149,12 +139,7 @@ impl DeviceManager {
} }
} }
// Wrap the device
let device = WrappedDevice::new(device);
self.devices.write().await.insert(id, device.0.clone()); self.devices.write().await.insert(id, device.0.clone());
device
} }
pub fn event_channel(&self) -> EventChannel { pub fn event_channel(&self) -> EventChannel {
@ -193,6 +178,7 @@ impl DeviceManager {
if subscribed { if subscribed {
trace!(id, "Handling"); trace!(id, "Handling");
device.on_mqtt(message).await; device.on_mqtt(message).await;
trace!(id, "Done");
} }
} }
} }
@ -208,6 +194,7 @@ impl DeviceManager {
if let Some(device) = As::<dyn OnDarkness>::cast_mut(device) { if let Some(device) = As::<dyn OnDarkness>::cast_mut(device) {
trace!(id, "Handling"); trace!(id, "Handling");
device.on_darkness(dark).await; device.on_darkness(dark).await;
trace!(id, "Done");
} }
}); });
@ -221,6 +208,7 @@ impl DeviceManager {
if let Some(device) = As::<dyn OnPresence>::cast_mut(device) { if let Some(device) = As::<dyn OnPresence>::cast_mut(device) {
trace!(id, "Handling"); trace!(id, "Handling");
device.on_presence(presence).await; device.on_presence(presence).await;
trace!(id, "Done");
} }
}); });
@ -236,6 +224,7 @@ impl DeviceManager {
if let Some(device) = As::<dyn OnNotification>::cast_mut(device) { if let Some(device) = As::<dyn OnNotification>::cast_mut(device) {
trace!(id, "Handling"); trace!(id, "Handling");
device.on_notification(notification).await; device.on_notification(notification).await;
trace!(id, "Done");
} }
} }
}); });
@ -248,20 +237,11 @@ impl DeviceManager {
impl mlua::UserData for DeviceManager { impl mlua::UserData for DeviceManager {
fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) { fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) {
methods.add_async_method( methods.add_async_method("add", |_lua, this, device: WrappedDevice| async move {
"create", this.add(&device).await;
|_lua, this, (identifier, config): (String, mlua::Value)| async move {
// TODO: Handle the error here properly
let config: Box<dyn DeviceConfig> = config.as_userdata().unwrap().take()?;
let device = config Ok(())
.create(&identifier) });
.await
.map_err(mlua::ExternalError::into_lua_err)?;
Ok(this.add(device).await)
},
);
methods.add_async_method("add_schedule", |lua, this, schedule| async { methods.add_async_method("add_schedule", |lua, this, schedule| async {
let schedule = lua.from_value(schedule)?; let schedule = lua.from_value(schedule)?;

View File

@ -6,10 +6,9 @@ use google_home::traits::{AvailableSpeeds, FanSpeed, HumiditySetting, OnOff, Spe
use google_home::types::Type; use google_home::types::Type;
use google_home::GoogleHomeDevice; use google_home::GoogleHomeDevice;
use rumqttc::Publish; use rumqttc::Publish;
use tracing::{debug, error, warn}; use tracing::{debug, error, trace, warn};
use crate::config::{InfoConfig, MqttDeviceConfig}; use crate::config::{InfoConfig, MqttDeviceConfig};
use crate::device_manager::DeviceConfig;
use crate::devices::Device; use crate::devices::Device;
use crate::error::DeviceConfigError; use crate::error::DeviceConfigError;
use crate::event::OnMqtt; use crate::event::OnMqtt;
@ -26,25 +25,8 @@ pub struct AirFilterConfig {
client: WrappedAsyncClient, client: WrappedAsyncClient,
} }
#[async_trait]
impl DeviceConfig for AirFilterConfig {
async fn create(&self, identifier: &str) -> Result<Box<dyn Device>, DeviceConfigError> {
let device = AirFilter {
identifier: identifier.into(),
config: self.clone(),
last_known_state: AirFilterState {
state: AirFilterFanState::Off,
humidity: 0.0,
},
};
Ok(Box::new(device))
}
}
#[derive(Debug, LuaDevice)] #[derive(Debug, LuaDevice)]
pub struct AirFilter { pub struct AirFilter {
identifier: String,
#[config] #[config]
config: AirFilterConfig, config: AirFilterConfig,
@ -71,9 +53,22 @@ impl AirFilter {
} }
} }
impl AirFilter {
async fn create(config: AirFilterConfig) -> Result<Self, DeviceConfigError> {
trace!(id = config.info.identifier(), "Setting up AirFilter");
Ok(Self {
config,
last_known_state: AirFilterState {
state: AirFilterFanState::Off,
humidity: 0.0,
},
})
}
}
impl Device for AirFilter { impl Device for AirFilter {
fn get_id(&self) -> &str { fn get_id(&self) -> String {
&self.identifier self.config.info.identifier()
} }
} }
@ -87,7 +82,7 @@ impl OnMqtt for AirFilter {
let state = match AirFilterState::try_from(message) { let state = match AirFilterState::try_from(message) {
Ok(state) => state, Ok(state) => state,
Err(err) => { Err(err) => {
error!(id = self.identifier, "Failed to parse message: {err}"); error!(id = Device::get_id(self), "Failed to parse message: {err}");
return; return;
} }
}; };
@ -96,7 +91,7 @@ impl OnMqtt for AirFilter {
return; return;
} }
debug!(id = self.identifier, "Updating state to {state:?}"); debug!(id = Device::get_id(self), "Updating state to {state:?}");
self.last_known_state = state; self.last_known_state = state;
} }
@ -111,7 +106,7 @@ impl GoogleHomeDevice for AirFilter {
Name::new(&self.config.info.name) Name::new(&self.config.info.name)
} }
fn get_id(&self) -> &str { fn get_id(&self) -> String {
Device::get_id(self) Device::get_id(self)
} }

View File

@ -5,7 +5,7 @@ use tracing::{debug, error, trace, warn};
use super::Device; use super::Device;
use crate::config::MqttDeviceConfig; use crate::config::MqttDeviceConfig;
use crate::device_manager::{DeviceConfig, WrappedDevice}; use crate::device_manager::WrappedDevice;
use crate::devices::As; use crate::devices::As;
use crate::error::DeviceConfigError; use crate::error::DeviceConfigError;
use crate::event::{OnMqtt, OnPresence}; use crate::event::{OnMqtt, OnPresence};
@ -13,6 +13,7 @@ use crate::messages::{RemoteAction, RemoteMessage};
#[derive(Debug, Clone, LuaDeviceConfig)] #[derive(Debug, Clone, LuaDeviceConfig)]
pub struct AudioSetupConfig { pub struct AudioSetupConfig {
identifier: String,
#[device_config(flatten)] #[device_config(flatten)]
mqtt: MqttDeviceConfig, mqtt: MqttDeviceConfig,
#[device_config(from_lua)] #[device_config(from_lua)]
@ -21,41 +22,33 @@ pub struct AudioSetupConfig {
speakers: WrappedDevice, speakers: WrappedDevice,
} }
#[async_trait]
impl DeviceConfig for AudioSetupConfig {
async fn create(&self, identifier: &str) -> Result<Box<dyn Device>, DeviceConfigError> {
trace!(id = identifier, "Setting up AudioSetup");
let mixer_id = self.mixer.read().await.get_id().to_owned();
if !As::<dyn OnOff>::is(self.mixer.read().await.as_ref()) {
return Err(DeviceConfigError::MissingTrait(mixer_id, "OnOff".into()));
}
let speakers_id = self.speakers.read().await.get_id().to_owned();
if !As::<dyn OnOff>::is(self.speakers.read().await.as_ref()) {
return Err(DeviceConfigError::MissingTrait(speakers_id, "OnOff".into()));
}
let device = AudioSetup {
identifier: identifier.into(),
config: self.clone(),
};
Ok(Box::new(device))
}
}
// TODO: We need a better way to store the children devices
#[derive(Debug, LuaDevice)] #[derive(Debug, LuaDevice)]
pub struct AudioSetup { pub struct AudioSetup {
identifier: String,
#[config] #[config]
config: AudioSetupConfig, config: AudioSetupConfig,
} }
impl AudioSetup {
async fn create(config: AudioSetupConfig) -> Result<Self, DeviceConfigError> {
trace!(id = config.identifier, "Setting up AudioSetup");
let mixer_id = config.mixer.read().await.get_id().to_owned();
if !As::<dyn OnOff>::is(config.mixer.read().await.as_ref()) {
return Err(DeviceConfigError::MissingTrait(mixer_id, "OnOff".into()));
}
let speakers_id = config.speakers.read().await.get_id().to_owned();
if !As::<dyn OnOff>::is(config.speakers.read().await.as_ref()) {
return Err(DeviceConfigError::MissingTrait(speakers_id, "OnOff".into()));
}
Ok(AudioSetup { config })
}
}
impl Device for AudioSetup { impl Device for AudioSetup {
fn get_id(&self) -> &str { fn get_id(&self) -> String {
&self.identifier self.config.identifier.clone()
} }
} }
@ -69,7 +62,10 @@ impl OnMqtt for AudioSetup {
let action = match RemoteMessage::try_from(message) { let action = match RemoteMessage::try_from(message) {
Ok(message) => message.action(), Ok(message) => message.action(),
Err(err) => { Err(err) => {
error!(id = self.identifier, "Failed to parse message: {err}"); error!(
id = self.config.identifier,
"Failed to parse message: {err}"
);
return; return;
} }
}; };
@ -118,7 +114,7 @@ impl OnPresence for AudioSetup {
) { ) {
// Turn off the audio setup when we leave the house // Turn off the audio setup when we leave the house
if !presence { if !presence {
debug!(id = self.identifier, "Turning devices off"); debug!(id = self.config.identifier, "Turning devices off");
speakers.set_on(false).await.unwrap(); speakers.set_on(false).await.unwrap();
mixer.set_on(false).await.unwrap(); mixer.set_on(false).await.unwrap();
} }

View File

@ -9,7 +9,7 @@ use tracing::{debug, error, trace, warn};
use super::Device; use super::Device;
use crate::config::MqttDeviceConfig; use crate::config::MqttDeviceConfig;
use crate::device_manager::{DeviceConfig, WrappedDevice}; use crate::device_manager::WrappedDevice;
use crate::devices::{As, DEFAULT_PRESENCE}; use crate::devices::{As, DEFAULT_PRESENCE};
use crate::error::DeviceConfigError; use crate::error::DeviceConfigError;
use crate::event::{OnMqtt, OnPresence}; use crate::event::{OnMqtt, OnPresence};
@ -51,6 +51,7 @@ pub struct TriggerConfig {
#[derive(Debug, Clone, LuaDeviceConfig)] #[derive(Debug, Clone, LuaDeviceConfig)]
pub struct ContactSensorConfig { pub struct ContactSensorConfig {
identifier: String,
#[device_config(flatten)] #[device_config(flatten)]
mqtt: MqttDeviceConfig, mqtt: MqttDeviceConfig,
#[device_config(from_lua)] #[device_config(from_lua)]
@ -61,13 +62,22 @@ pub struct ContactSensorConfig {
client: WrappedAsyncClient, client: WrappedAsyncClient,
} }
#[async_trait] #[derive(Debug, LuaDevice)]
impl DeviceConfig for ContactSensorConfig { pub struct ContactSensor {
async fn create(&self, identifier: &str) -> Result<Box<dyn Device>, DeviceConfigError> { #[config]
trace!(id = identifier, "Setting up ContactSensor"); config: ContactSensorConfig,
overall_presence: bool,
is_closed: bool,
handle: Option<JoinHandle<()>>,
}
impl ContactSensor {
async fn create(config: ContactSensorConfig) -> Result<Self, DeviceConfigError> {
trace!(id = config.identifier, "Setting up ContactSensor");
// Make sure the devices implement the required traits // Make sure the devices implement the required traits
if let Some(trigger) = &self.trigger { if let Some(trigger) = &config.trigger {
for (device, _) in &trigger.devices { for (device, _) in &trigger.devices {
let id = device.read().await.get_id().to_owned(); let id = device.read().await.get_id().to_owned();
if !As::<dyn OnOff>::is(device.read().await.as_ref()) { if !As::<dyn OnOff>::is(device.read().await.as_ref()) {
@ -81,32 +91,18 @@ impl DeviceConfig for ContactSensorConfig {
} }
} }
let device = ContactSensor { Ok(Self {
identifier: identifier.into(), config: config.clone(),
config: self.clone(),
overall_presence: DEFAULT_PRESENCE, overall_presence: DEFAULT_PRESENCE,
is_closed: true, is_closed: true,
handle: None, handle: None,
}; })
Ok(Box::new(device))
} }
} }
#[derive(Debug, LuaDevice)]
pub struct ContactSensor {
identifier: String,
#[config]
config: ContactSensorConfig,
overall_presence: bool,
is_closed: bool,
handle: Option<JoinHandle<()>>,
}
impl Device for ContactSensor { impl Device for ContactSensor {
fn get_id(&self) -> &str { fn get_id(&self) -> String {
&self.identifier self.config.identifier.clone()
} }
} }
@ -127,7 +123,10 @@ impl OnMqtt for ContactSensor {
let is_closed = match ContactMessage::try_from(message) { let is_closed = match ContactMessage::try_from(message) {
Ok(state) => state.is_closed(), Ok(state) => state.is_closed(),
Err(err) => { Err(err) => {
error!(id = self.identifier, "Failed to parse message: {err}"); error!(
id = self.config.identifier,
"Failed to parse message: {err}"
);
return; return;
} }
}; };
@ -136,7 +135,7 @@ impl OnMqtt for ContactSensor {
return; return;
} }
debug!(id = self.identifier, "Updating state to {is_closed}"); debug!(id = self.config.identifier, "Updating state to {is_closed}");
self.is_closed = is_closed; self.is_closed = is_closed;
if let Some(trigger) = &mut self.config.trigger { if let Some(trigger) = &mut self.config.trigger {
@ -205,7 +204,7 @@ impl OnMqtt for ContactSensor {
} else { } else {
// Once the door is closed again we start a timeout for removing the presence // Once the door is closed again we start a timeout for removing the presence
let client = self.config.client.clone(); let client = self.config.client.clone();
let id = self.identifier.clone(); let id = self.config.identifier.clone();
let timeout = presence.timeout; let timeout = presence.timeout;
let topic = presence.mqtt.topic.clone(); let topic = presence.mqtt.topic.clone();
self.handle = Some(tokio::spawn(async move { self.handle = Some(tokio::spawn(async move {

View File

@ -1,9 +1,8 @@
use async_trait::async_trait; use async_trait::async_trait;
use automation_macro::{LuaDevice, LuaDeviceConfig}; use automation_macro::{LuaDevice, LuaDeviceConfig};
use tracing::warn; use tracing::{trace, warn};
use crate::config::MqttDeviceConfig; use crate::config::MqttDeviceConfig;
use crate::device_manager::DeviceConfig;
use crate::devices::Device; use crate::devices::Device;
use crate::error::DeviceConfigError; use crate::error::DeviceConfigError;
use crate::event::{OnDarkness, OnPresence}; use crate::event::{OnDarkness, OnPresence};
@ -12,34 +11,29 @@ use crate::mqtt::WrappedAsyncClient;
#[derive(Debug, LuaDeviceConfig, Clone)] #[derive(Debug, LuaDeviceConfig, Clone)]
pub struct DebugBridgeConfig { pub struct DebugBridgeConfig {
identifier: String,
#[device_config(flatten)] #[device_config(flatten)]
pub mqtt: MqttDeviceConfig, pub mqtt: MqttDeviceConfig,
#[device_config(from_lua)] #[device_config(from_lua)]
client: WrappedAsyncClient, client: WrappedAsyncClient,
} }
#[async_trait]
impl DeviceConfig for DebugBridgeConfig {
async fn create(&self, identifier: &str) -> Result<Box<dyn Device>, DeviceConfigError> {
let device = DebugBridge {
identifier: identifier.into(),
config: self.clone(),
};
Ok(Box::new(device))
}
}
#[derive(Debug, LuaDevice)] #[derive(Debug, LuaDevice)]
pub struct DebugBridge { pub struct DebugBridge {
identifier: String,
#[config] #[config]
config: DebugBridgeConfig, 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 { impl Device for DebugBridge {
fn get_id(&self) -> &str { fn get_id(&self) -> String {
&self.identifier self.config.identifier.clone()
} }
} }

View File

@ -5,7 +5,6 @@ use automation_macro::{LuaDevice, LuaDeviceConfig};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tracing::{error, trace, warn}; use tracing::{error, trace, warn};
use crate::device_manager::DeviceConfig;
use crate::devices::Device; use crate::devices::Device;
use crate::error::DeviceConfigError; use crate::error::DeviceConfigError;
use crate::event::{OnDarkness, OnPresence}; use crate::event::{OnDarkness, OnPresence};
@ -24,27 +23,15 @@ pub struct FlagIDs {
#[derive(Debug, LuaDeviceConfig, Clone)] #[derive(Debug, LuaDeviceConfig, Clone)]
pub struct HueBridgeConfig { pub struct HueBridgeConfig {
pub identifier: String,
#[device_config(rename("ip"), with(|ip| SocketAddr::new(ip, 80)))] #[device_config(rename("ip"), with(|ip| SocketAddr::new(ip, 80)))]
pub addr: SocketAddr, pub addr: SocketAddr,
pub login: String, pub login: String,
pub flags: FlagIDs, pub flags: FlagIDs,
} }
#[async_trait]
impl DeviceConfig for HueBridgeConfig {
async fn create(&self, identifier: &str) -> Result<Box<dyn Device>, DeviceConfigError> {
let device = HueBridge {
identifier: identifier.into(),
config: self.clone(),
};
Ok(Box::new(device))
}
}
#[derive(Debug, LuaDevice)] #[derive(Debug, LuaDevice)]
pub struct HueBridge { pub struct HueBridge {
identifier: String,
#[config] #[config]
config: HueBridgeConfig, config: HueBridgeConfig,
} }
@ -55,6 +42,11 @@ struct FlagMessage {
} }
impl HueBridge { impl HueBridge {
async fn create(config: HueBridgeConfig) -> Result<Self, DeviceConfigError> {
trace!(id = config.identifier, "Setting up HueBridge");
Ok(Self { config })
}
pub async fn set_flag(&self, flag: Flag, value: bool) { pub async fn set_flag(&self, flag: Flag, value: bool) {
let flag_id = match flag { let flag_id = match flag {
Flag::Presence => self.config.flags.presence, Flag::Presence => self.config.flags.presence,
@ -88,8 +80,8 @@ impl HueBridge {
} }
impl Device for HueBridge { impl Device for HueBridge {
fn get_id(&self) -> &str { fn get_id(&self) -> String {
&self.identifier self.config.identifier.clone()
} }
} }

View File

@ -7,11 +7,10 @@ use automation_macro::{LuaDevice, LuaDeviceConfig};
use google_home::errors::ErrorCode; use google_home::errors::ErrorCode;
use google_home::traits::OnOff; use google_home::traits::OnOff;
use rumqttc::Publish; use rumqttc::Publish;
use tracing::{debug, error, warn}; use tracing::{debug, error, trace, warn};
use super::Device; use super::Device;
use crate::config::MqttDeviceConfig; use crate::config::MqttDeviceConfig;
use crate::device_manager::DeviceConfig;
use crate::error::DeviceConfigError; use crate::error::DeviceConfigError;
use crate::event::OnMqtt; use crate::event::OnMqtt;
use crate::messages::{RemoteAction, RemoteMessage}; use crate::messages::{RemoteAction, RemoteMessage};
@ -19,6 +18,7 @@ use crate::traits::Timeout;
#[derive(Debug, Clone, LuaDeviceConfig)] #[derive(Debug, Clone, LuaDeviceConfig)]
pub struct HueGroupConfig { pub struct HueGroupConfig {
identifier: String,
#[device_config(rename("ip"), with(|ip| SocketAddr::new(ip, 80)))] #[device_config(rename("ip"), with(|ip| SocketAddr::new(ip, 80)))]
pub addr: SocketAddr, pub addr: SocketAddr,
pub login: String, pub login: String,
@ -29,27 +29,19 @@ pub struct HueGroupConfig {
pub remotes: Vec<MqttDeviceConfig>, pub remotes: Vec<MqttDeviceConfig>,
} }
#[async_trait]
impl DeviceConfig for HueGroupConfig {
async fn create(&self, identifier: &str) -> Result<Box<dyn Device>, DeviceConfigError> {
let device = HueGroup {
identifier: identifier.into(),
config: self.clone(),
};
Ok(Box::new(device))
}
}
#[derive(Debug, LuaDevice)] #[derive(Debug, LuaDevice)]
pub struct HueGroup { pub struct HueGroup {
identifier: String,
#[config] #[config]
config: HueGroupConfig, config: HueGroupConfig,
} }
// Couple of helper function to get the correct urls // Couple of helper function to get the correct urls
impl HueGroup { impl HueGroup {
async fn create(config: HueGroupConfig) -> Result<Self, DeviceConfigError> {
trace!(id = config.identifier, "Setting up AudioSetup");
Ok(Self { config })
}
fn url_base(&self) -> String { fn url_base(&self) -> String {
format!("http://{}/api/{}", self.config.addr, self.config.login) format!("http://{}/api/{}", self.config.addr, self.config.login)
} }
@ -68,8 +60,8 @@ impl HueGroup {
} }
impl Device for HueGroup { impl Device for HueGroup {
fn get_id(&self) -> &str { fn get_id(&self) -> String {
&self.identifier self.config.identifier.clone()
} }
} }
@ -87,7 +79,10 @@ impl OnMqtt for HueGroup {
let action = match RemoteMessage::try_from(message) { let action = match RemoteMessage::try_from(message) {
Ok(message) => message.action(), Ok(message) => message.action(),
Err(err) => { Err(err) => {
error!(id = self.identifier, "Failed to parse message: {err}"); error!(
id = self.config.identifier,
"Failed to parse message: {err}"
);
return; return;
} }
}; };
@ -126,10 +121,13 @@ impl OnOff for HueGroup {
Ok(res) => { Ok(res) => {
let status = res.status(); let status = res.status();
if !status.is_success() { if !status.is_success() {
warn!(id = self.identifier, "Status code is not success: {status}"); warn!(
id = self.config.identifier,
"Status code is not success: {status}"
);
} }
} }
Err(err) => error!(id = self.identifier, "Error: {err}"), Err(err) => error!(id = self.config.identifier, "Error: {err}"),
} }
Ok(()) Ok(())
@ -145,13 +143,19 @@ impl OnOff for HueGroup {
Ok(res) => { Ok(res) => {
let status = res.status(); let status = res.status();
if !status.is_success() { if !status.is_success() {
warn!(id = self.identifier, "Status code is not success: {status}"); warn!(
id = self.config.identifier,
"Status code is not success: {status}"
);
} }
let on = match res.json::<message::Info>().await { let on = match res.json::<message::Info>().await {
Ok(info) => info.any_on(), Ok(info) => info.any_on(),
Err(err) => { Err(err) => {
error!(id = self.identifier, "Failed to parse message: {err}"); error!(
id = self.config.identifier,
"Failed to parse message: {err}"
);
// TODO: Error code // TODO: Error code
return Ok(false); return Ok(false);
} }
@ -159,7 +163,7 @@ impl OnOff for HueGroup {
return Ok(on); return Ok(on);
} }
Err(err) => error!(id = self.identifier, "Error: {err}"), Err(err) => error!(id = self.config.identifier, "Error: {err}"),
} }
Ok(false) Ok(false)

View File

@ -13,7 +13,6 @@ use tokio::task::JoinHandle;
use tracing::{debug, error, trace, warn}; use tracing::{debug, error, trace, warn};
use crate::config::{InfoConfig, MqttDeviceConfig}; use crate::config::{InfoConfig, MqttDeviceConfig};
use crate::device_manager::DeviceConfig;
use crate::devices::Device; use crate::devices::Device;
use crate::error::DeviceConfigError; use crate::error::DeviceConfigError;
use crate::event::{OnMqtt, OnPresence}; use crate::event::{OnMqtt, OnPresence};
@ -46,30 +45,8 @@ pub struct IkeaOutletConfig {
client: WrappedAsyncClient, client: WrappedAsyncClient,
} }
#[async_trait]
impl DeviceConfig for IkeaOutletConfig {
async fn create(&self, identifier: &str) -> Result<Box<dyn Device>, DeviceConfigError> {
trace!(
id = identifier,
name = self.info.name,
room = self.info.room,
"Setting up IkeaOutlet"
);
let device = IkeaOutlet {
identifier: identifier.into(),
config: self.clone(),
last_known_state: false,
handle: None,
};
Ok(Box::new(device))
}
}
#[derive(Debug, LuaDevice)] #[derive(Debug, LuaDevice)]
pub struct IkeaOutlet { pub struct IkeaOutlet {
identifier: String,
#[config] #[config]
config: IkeaOutletConfig, config: IkeaOutletConfig,
@ -94,9 +71,21 @@ async fn set_on(client: WrappedAsyncClient, topic: &str, on: bool) {
.ok(); .ok();
} }
impl IkeaOutlet {
async fn create(config: IkeaOutletConfig) -> Result<Self, DeviceConfigError> {
trace!(id = config.info.identifier(), "Setting up IkeaOutlet");
Ok(Self {
config,
last_known_state: false,
handle: None,
})
}
}
impl Device for IkeaOutlet { impl Device for IkeaOutlet {
fn get_id(&self) -> &str { fn get_id(&self) -> String {
&self.identifier self.config.info.identifier()
} }
} }
@ -122,7 +111,7 @@ impl OnMqtt for IkeaOutlet {
let state = match OnOffMessage::try_from(message) { let state = match OnOffMessage::try_from(message) {
Ok(state) => state.state(), Ok(state) => state.state(),
Err(err) => { Err(err) => {
error!(id = self.identifier, "Failed to parse message: {err}"); error!(id = Device::get_id(self), "Failed to parse message: {err}");
return; return;
} }
}; };
@ -135,7 +124,7 @@ impl OnMqtt for IkeaOutlet {
// Abort any timer that is currently running // Abort any timer that is currently running
self.stop_timeout().await.unwrap(); self.stop_timeout().await.unwrap();
debug!(id = self.identifier, "Updating state to {state}"); debug!(id = Device::get_id(self), "Updating state to {state}");
self.last_known_state = state; self.last_known_state = state;
// If this is a kettle start a timeout for turning it of again // If this is a kettle start a timeout for turning it of again
@ -146,7 +135,7 @@ impl OnMqtt for IkeaOutlet {
let action = match RemoteMessage::try_from(message) { let action = match RemoteMessage::try_from(message) {
Ok(message) => message.action(), Ok(message) => message.action(),
Err(err) => { Err(err) => {
error!(id = self.identifier, "Failed to parse message: {err}"); error!(id = Device::get_id(self), "Failed to parse message: {err}");
return; return;
} }
}; };
@ -166,7 +155,7 @@ impl OnPresence for IkeaOutlet {
async fn on_presence(&mut self, presence: bool) { async fn on_presence(&mut self, presence: bool) {
// Turn off the outlet when we leave the house (Not if it is a battery charger) // Turn off the outlet when we leave the house (Not if it is a battery charger)
if !presence && self.config.outlet_type != OutletType::Charger { if !presence && self.config.outlet_type != OutletType::Charger {
debug!(id = self.identifier, "Turning device off"); debug!(id = Device::get_id(self), "Turning device off");
self.set_on(false).await.ok(); self.set_on(false).await.ok();
} }
} }
@ -186,7 +175,7 @@ impl GoogleHomeDevice for IkeaOutlet {
device::Name::new(&self.config.info.name) device::Name::new(&self.config.info.name)
} }
fn get_id(&self) -> &str { fn get_id(&self) -> String {
Device::get_id(self) Device::get_id(self)
} }
@ -228,7 +217,7 @@ impl crate::traits::Timeout for IkeaOutlet {
// get dropped // get dropped
let client = self.config.client.clone(); let client = self.config.client.clone();
let topic = self.config.mqtt.topic.clone(); let topic = self.config.mqtt.topic.clone();
let id = self.identifier.clone(); let id = Device::get_id(self).clone();
self.handle = Some(tokio::spawn(async move { self.handle = Some(tokio::spawn(async move {
debug!(id, "Starting timeout ({timeout:?})..."); debug!(id, "Starting timeout ({timeout:?})...");
tokio::time::sleep(timeout).await; tokio::time::sleep(timeout).await;

View File

@ -13,39 +13,31 @@ use tokio::net::TcpStream;
use tracing::trace; use tracing::trace;
use super::Device; use super::Device;
use crate::device_manager::DeviceConfig;
use crate::error::DeviceConfigError; use crate::error::DeviceConfigError;
#[derive(Debug, Clone, LuaDeviceConfig)] #[derive(Debug, Clone, LuaDeviceConfig)]
pub struct KasaOutletConfig { pub struct KasaOutletConfig {
identifier: String,
#[device_config(rename("ip"), with(|ip| SocketAddr::new(ip, 9999)))] #[device_config(rename("ip"), with(|ip| SocketAddr::new(ip, 9999)))]
addr: SocketAddr, addr: SocketAddr,
} }
#[async_trait]
impl DeviceConfig for KasaOutletConfig {
async fn create(&self, identifier: &str) -> Result<Box<dyn Device>, DeviceConfigError> {
trace!(id = identifier, "Setting up KasaOutlet");
let device = KasaOutlet {
identifier: identifier.into(),
config: self.clone(),
};
Ok(Box::new(device))
}
}
#[derive(Debug, LuaDevice)] #[derive(Debug, LuaDevice)]
pub struct KasaOutlet { pub struct KasaOutlet {
identifier: String,
#[config] #[config]
config: KasaOutletConfig, config: KasaOutletConfig,
} }
impl KasaOutlet {
async fn create(config: KasaOutletConfig) -> Result<Self, DeviceConfigError> {
trace!(id = config.identifier, "Setting up KasaOutlet");
Ok(Self { config })
}
}
impl Device for KasaOutlet { impl Device for KasaOutlet {
fn get_id(&self) -> &str { fn get_id(&self) -> String {
&self.identifier self.config.identifier.clone()
} }
} }

View File

@ -4,7 +4,6 @@ use rumqttc::Publish;
use tracing::{debug, trace, warn}; use tracing::{debug, trace, warn};
use crate::config::MqttDeviceConfig; use crate::config::MqttDeviceConfig;
use crate::device_manager::DeviceConfig;
use crate::devices::Device; use crate::devices::Device;
use crate::error::DeviceConfigError; use crate::error::DeviceConfigError;
use crate::event::{self, Event, EventChannel, OnMqtt}; use crate::event::{self, Event, EventChannel, OnMqtt};
@ -12,6 +11,7 @@ use crate::messages::BrightnessMessage;
#[derive(Debug, Clone, LuaDeviceConfig)] #[derive(Debug, Clone, LuaDeviceConfig)]
pub struct LightSensorConfig { pub struct LightSensorConfig {
identifier: String,
#[device_config(flatten)] #[device_config(flatten)]
pub mqtt: MqttDeviceConfig, pub mqtt: MqttDeviceConfig,
pub min: isize, pub min: isize,
@ -22,34 +22,27 @@ pub struct LightSensorConfig {
pub const DEFAULT: bool = false; pub const DEFAULT: bool = false;
// TODO: The light sensor should get a list of devices that it should inform
#[async_trait]
impl DeviceConfig for LightSensorConfig {
async fn create(&self, identifier: &str) -> Result<Box<dyn Device>, DeviceConfigError> {
let device = LightSensor {
identifier: identifier.into(),
// Add helper type that does this conversion for us
config: self.clone(),
is_dark: DEFAULT,
};
Ok(Box::new(device))
}
}
#[derive(Debug, LuaDevice)] #[derive(Debug, LuaDevice)]
pub struct LightSensor { pub struct LightSensor {
identifier: String,
#[config] #[config]
config: LightSensorConfig, config: LightSensorConfig,
is_dark: bool, is_dark: bool,
} }
impl LightSensor {
async fn create(config: LightSensorConfig) -> Result<Self, DeviceConfigError> {
trace!(id = config.identifier, "Setting up LightSensor");
Ok(Self {
config,
is_dark: DEFAULT,
})
}
}
impl Device for LightSensor { impl Device for LightSensor {
fn get_id(&self) -> &str { fn get_id(&self) -> String {
&self.identifier self.config.identifier.clone()
} }
} }

View File

@ -33,5 +33,5 @@ use crate::traits::Timeout;
#[impl_cast::device(As: OnMqtt + OnPresence + OnDarkness + OnNotification + OnOff + Timeout)] #[impl_cast::device(As: OnMqtt + OnPresence + OnDarkness + OnNotification + OnOff + Timeout)]
pub trait Device: AsGoogleHomeDevice + std::fmt::Debug + Sync + Send { pub trait Device: AsGoogleHomeDevice + std::fmt::Debug + Sync + Send {
fn get_id(&self) -> &str; fn get_id(&self) -> String;
} }

View File

@ -1,21 +1,15 @@
use std::collections::HashMap; use std::collections::HashMap;
use async_trait::async_trait; use async_trait::async_trait;
use automation_macro::{LuaDevice, LuaDeviceConfig};
use serde::Serialize; use serde::Serialize;
use serde_repr::*; use serde_repr::*;
use tracing::{debug, error, warn}; use tracing::{error, trace, warn};
use crate::config::NtfyConfig;
use crate::devices::Device; use crate::devices::Device;
use crate::error::DeviceConfigError;
use crate::event::{self, Event, EventChannel, OnNotification, OnPresence}; use crate::event::{self, Event, EventChannel, OnNotification, OnPresence};
#[derive(Debug)]
pub struct Ntfy {
base_url: String,
topic: String,
tx: event::Sender,
}
#[derive(Debug, Serialize_repr, Clone, Copy)] #[derive(Debug, Serialize_repr, Clone, Copy)]
#[repr(u8)] #[repr(u8)]
pub enum Priority { pub enum Priority {
@ -116,22 +110,41 @@ impl Default for Notification {
} }
} }
#[derive(Debug, LuaDeviceConfig)]
pub struct NtfyConfig {
#[device_config(default("https://ntfy.sh".into()))]
url: String,
topic: String,
#[device_config(rename("event_channel"), from_lua, with(|ec: EventChannel| ec.get_tx()))]
tx: event::Sender,
}
#[derive(Debug, LuaDevice)]
pub struct Ntfy {
#[config]
config: NtfyConfig,
}
impl Ntfy { impl Ntfy {
pub fn new(config: NtfyConfig, event_channel: &EventChannel) -> Self { async fn create(config: NtfyConfig) -> Result<Self, DeviceConfigError> {
Self { trace!(id = "ntfy", "Setting up Ntfy");
base_url: config.url, Ok(Self { config })
topic: config.topic,
tx: event_channel.get_tx(),
} }
} }
impl Device for Ntfy {
fn get_id(&self) -> String {
"ntfy".to_string()
}
}
impl Ntfy {
async fn send(&self, notification: Notification) { async fn send(&self, notification: Notification) {
let notification = notification.finalize(&self.topic); let notification = notification.finalize(&self.config.topic);
debug!("Sending notfication");
// Create the request // Create the request
let res = reqwest::Client::new() let res = reqwest::Client::new()
.post(self.base_url.clone()) .post(self.config.url.clone())
.json(&notification) .json(&notification)
.send() .send()
.await; .await;
@ -147,12 +160,6 @@ impl Ntfy {
} }
} }
impl Device for Ntfy {
fn get_id(&self) -> &str {
"ntfy"
}
}
#[async_trait] #[async_trait]
impl OnPresence for Ntfy { impl OnPresence for Ntfy {
async fn on_presence(&mut self, presence: bool) { async fn on_presence(&mut self, presence: bool) {
@ -177,7 +184,13 @@ impl OnPresence for Ntfy {
.add_action(action) .add_action(action)
.set_priority(Priority::Low); .set_priority(Priority::Low);
if self.tx.send(Event::Ntfy(notification)).await.is_err() { if self
.config
.tx
.send(Event::Ntfy(notification))
.await
.is_err()
{
warn!("There are no receivers on the event channel"); warn!("There are no receivers on the event channel");
} }
} }

View File

@ -1,60 +1,64 @@
use std::collections::HashMap; use std::collections::HashMap;
use async_trait::async_trait; use async_trait::async_trait;
use automation_macro::{LuaDevice, LuaDeviceConfig};
use rumqttc::Publish; use rumqttc::Publish;
use serde::Deserialize; use tracing::{debug, trace, warn};
use tracing::{debug, warn};
use crate::config::MqttDeviceConfig; use crate::config::MqttDeviceConfig;
use crate::devices::Device; use crate::devices::Device;
use crate::error::DeviceConfigError;
use crate::event::{self, Event, EventChannel, OnMqtt}; use crate::event::{self, Event, EventChannel, OnMqtt};
use crate::messages::PresenceMessage; use crate::messages::PresenceMessage;
#[derive(Debug, Deserialize)] #[derive(Debug, LuaDeviceConfig)]
pub struct PresenceConfig { pub struct PresenceConfig {
#[serde(flatten)] #[device_config(flatten)]
pub mqtt: MqttDeviceConfig, pub mqtt: MqttDeviceConfig,
#[device_config(from_lua, rename("event_channel"), with(|ec: EventChannel| ec.get_tx()))]
tx: event::Sender,
} }
pub const DEFAULT_PRESENCE: bool = false; pub const DEFAULT_PRESENCE: bool = false;
#[derive(Debug)] #[derive(Debug, LuaDevice)]
pub struct Presence { pub struct Presence {
tx: event::Sender, #[config]
mqtt: MqttDeviceConfig, config: PresenceConfig,
devices: HashMap<String, bool>, devices: HashMap<String, bool>,
current_overall_presence: bool, current_overall_presence: bool,
} }
impl Presence { impl Presence {
pub fn new(config: PresenceConfig, event_channel: &EventChannel) -> Self { async fn create(config: PresenceConfig) -> Result<Self, DeviceConfigError> {
Self { trace!(id = "ntfy", "Setting up Presence");
tx: event_channel.get_tx(), Ok(Self {
mqtt: config.mqtt, config,
devices: HashMap::new(), devices: HashMap::new(),
current_overall_presence: DEFAULT_PRESENCE, current_overall_presence: DEFAULT_PRESENCE,
} })
} }
} }
impl Device for Presence { impl Device for Presence {
fn get_id(&self) -> &str { fn get_id(&self) -> String {
"presence" "presence".to_string()
} }
} }
#[async_trait] #[async_trait]
impl OnMqtt for Presence { impl OnMqtt for Presence {
fn topics(&self) -> Vec<&str> { fn topics(&self) -> Vec<&str> {
vec![&self.mqtt.topic] vec![&self.config.mqtt.topic]
} }
async fn on_mqtt(&mut self, message: Publish) { async fn on_mqtt(&mut self, message: Publish) {
let offset = self let offset = self
.config
.mqtt .mqtt
.topic .topic
.find('+') .find('+')
.or(self.mqtt.topic.find('#')) .or(self.config.mqtt.topic.find('#'))
.expect("Presence::create fails if it does not contain wildcards"); .expect("Presence::create fails if it does not contain wildcards");
let device_name = message.topic[offset..].into(); let device_name = message.topic[offset..].into();
@ -81,6 +85,7 @@ impl OnMqtt for Presence {
self.current_overall_presence = overall_presence; self.current_overall_presence = overall_presence;
if self if self
.config
.tx .tx
.send(Event::Presence(overall_presence)) .send(Event::Presence(overall_presence))
.await .await

View File

@ -12,7 +12,6 @@ use tracing::{debug, error, trace};
use super::Device; use super::Device;
use crate::config::{InfoConfig, MqttDeviceConfig}; use crate::config::{InfoConfig, MqttDeviceConfig};
use crate::device_manager::DeviceConfig;
use crate::error::DeviceConfigError; use crate::error::DeviceConfigError;
use crate::event::OnMqtt; use crate::event::OnMqtt;
use crate::messages::ActivateMessage; use crate::messages::ActivateMessage;
@ -28,37 +27,23 @@ pub struct WakeOnLANConfig {
broadcast_ip: Ipv4Addr, broadcast_ip: Ipv4Addr,
} }
#[async_trait]
impl DeviceConfig for WakeOnLANConfig {
async fn create(&self, identifier: &str) -> Result<Box<dyn Device>, DeviceConfigError> {
trace!(
id = identifier,
name = self.info.name,
room = self.info.room,
"Setting up WakeOnLAN"
);
debug!("broadcast_ip = {}", self.broadcast_ip);
let device = WakeOnLAN {
identifier: identifier.into(),
config: self.clone(),
};
Ok(Box::new(device))
}
}
#[derive(Debug, LuaDevice)] #[derive(Debug, LuaDevice)]
pub struct WakeOnLAN { pub struct WakeOnLAN {
identifier: String,
#[config] #[config]
config: WakeOnLANConfig, config: WakeOnLANConfig,
} }
impl WakeOnLAN {
async fn create(config: WakeOnLANConfig) -> Result<Self, DeviceConfigError> {
trace!(id = config.info.identifier(), "Setting up WakeOnLAN");
Ok(Self { config })
}
}
impl Device for WakeOnLAN { impl Device for WakeOnLAN {
fn get_id(&self) -> &str { fn get_id(&self) -> String {
&self.identifier self.config.info.identifier()
} }
} }
@ -72,7 +57,7 @@ impl OnMqtt for WakeOnLAN {
let activate = match ActivateMessage::try_from(message) { let activate = match ActivateMessage::try_from(message) {
Ok(message) => message.activate(), Ok(message) => message.activate(),
Err(err) => { Err(err) => {
error!(id = self.identifier, "Failed to parse message: {err}"); error!(id = Device::get_id(self), "Failed to parse message: {err}");
return; return;
} }
}; };
@ -93,7 +78,7 @@ impl GoogleHomeDevice for WakeOnLAN {
name name
} }
fn get_id(&self) -> &str { fn get_id(&self) -> String {
Device::get_id(self) Device::get_id(self)
} }
@ -111,14 +96,14 @@ impl traits::Scene for WakeOnLAN {
async fn set_active(&self, activate: bool) -> Result<(), ErrorCode> { async fn set_active(&self, activate: bool) -> Result<(), ErrorCode> {
if activate { if activate {
debug!( debug!(
id = self.identifier, id = Device::get_id(self),
"Activating Computer: {} (Sending to {})", "Activating Computer: {} (Sending to {})",
self.config.mac_address, self.config.mac_address,
self.config.broadcast_ip self.config.broadcast_ip
); );
let wol = wakey::WolPacket::from_bytes(&self.config.mac_address.to_array()).map_err( let wol = wakey::WolPacket::from_bytes(&self.config.mac_address.to_array()).map_err(
|err| { |err| {
error!(id = self.identifier, "invalid mac address: {err}"); error!(id = Device::get_id(self), "invalid mac address: {err}");
google_home::errors::DeviceError::TransientError google_home::errors::DeviceError::TransientError
}, },
)?; )?;
@ -129,13 +114,16 @@ impl traits::Scene for WakeOnLAN {
) )
.await .await
.map_err(|err| { .map_err(|err| {
error!(id = self.identifier, "Failed to activate computer: {err}"); error!(
id = Device::get_id(self),
"Failed to activate computer: {err}"
);
google_home::errors::DeviceError::TransientError.into() google_home::errors::DeviceError::TransientError.into()
}) })
.map(|_| debug!(id = self.identifier, "Success!")) .map(|_| debug!(id = Device::get_id(self), "Success!"))
} else { } else {
debug!( debug!(
id = self.identifier, id = Device::get_id(self),
"Trying to deactivate computer, this is not currently supported" "Trying to deactivate computer, this is not currently supported"
); );
// We do not support deactivating this scene // We do not support deactivating this scene

View File

@ -1,18 +1,18 @@
use async_trait::async_trait; use async_trait::async_trait;
use automation_macro::{LuaDevice, LuaDeviceConfig}; use automation_macro::{LuaDevice, LuaDeviceConfig};
use rumqttc::Publish; use rumqttc::Publish;
use tracing::{debug, error, warn}; use tracing::{debug, error, trace, warn};
use super::ntfy::Priority; use super::ntfy::Priority;
use super::{Device, Notification}; use super::{Device, Notification};
use crate::config::MqttDeviceConfig; use crate::config::MqttDeviceConfig;
use crate::device_manager::DeviceConfig;
use crate::error::DeviceConfigError; use crate::error::DeviceConfigError;
use crate::event::{self, Event, EventChannel, OnMqtt}; use crate::event::{self, Event, EventChannel, OnMqtt};
use crate::messages::PowerMessage; use crate::messages::PowerMessage;
#[derive(Debug, Clone, LuaDeviceConfig)] #[derive(Debug, Clone, LuaDeviceConfig)]
pub struct WasherConfig { pub struct WasherConfig {
identifier: String,
#[device_config(flatten)] #[device_config(flatten)]
mqtt: MqttDeviceConfig, mqtt: MqttDeviceConfig,
// Power in Watt // Power in Watt
@ -21,33 +21,25 @@ pub struct WasherConfig {
pub tx: event::Sender, pub tx: event::Sender,
} }
#[async_trait]
impl DeviceConfig for WasherConfig {
async fn create(&self, identifier: &str) -> Result<Box<dyn Device>, DeviceConfigError> {
let device = Washer {
identifier: identifier.into(),
config: self.clone(),
running: 0,
};
Ok(Box::new(device))
}
}
// TODO: Add google home integration // TODO: Add google home integration
#[derive(Debug, LuaDevice)] #[derive(Debug, LuaDevice)]
pub struct Washer { pub struct Washer {
identifier: String,
#[config] #[config]
config: WasherConfig, config: WasherConfig,
running: isize, running: isize,
} }
impl Washer {
async fn create(config: WasherConfig) -> Result<Self, DeviceConfigError> {
trace!(id = config.identifier, "Setting up Washer");
Ok(Self { config, running: 0 })
}
}
impl Device for Washer { impl Device for Washer {
fn get_id(&self) -> &str { fn get_id(&self) -> String {
&self.identifier self.config.identifier.clone()
} }
} }
@ -66,7 +58,10 @@ impl OnMqtt for Washer {
let power = match PowerMessage::try_from(message) { let power = match PowerMessage::try_from(message) {
Ok(state) => state.power(), Ok(state) => state.power(),
Err(err) => { Err(err) => {
error!(id = self.identifier, "Failed to parse message: {err}"); error!(
id = self.config.identifier,
"Failed to parse message: {err}"
);
return; return;
} }
}; };
@ -76,7 +71,7 @@ impl OnMqtt for Washer {
if power < self.config.threshold && self.running >= HYSTERESIS { if power < self.config.threshold && self.running >= HYSTERESIS {
// The washer is done running // The washer is done running
debug!( debug!(
id = self.identifier, id = self.config.identifier,
power, power,
threshold = self.config.threshold, threshold = self.config.threshold,
"Washer is done" "Washer is done"
@ -104,7 +99,7 @@ impl OnMqtt for Washer {
} else if power >= self.config.threshold && self.running < HYSTERESIS { } else if power >= self.config.threshold && self.running < HYSTERESIS {
// Washer could be starting // Washer could be starting
debug!( debug!(
id = self.identifier, id = self.config.identifier,
power, power,
threshold = self.config.threshold, threshold = self.config.threshold,
"Washer is starting" "Washer is starting"

View File

@ -64,18 +64,6 @@ async fn app() -> anyhow::Result<()> {
let event_channel = device_manager.event_channel(); let event_channel = device_manager.event_channel();
// Create and add the presence system
{
let presence = Presence::new(config.presence, &event_channel);
device_manager.add(Box::new(presence)).await;
}
// Start the ntfy service if it is configured
if let Some(config) = config.ntfy {
let ntfy = Ntfy::new(config, &event_channel);
device_manager.add(Box::new(ntfy)).await;
}
// Lua testing // Lua testing
{ {
let lua = mlua::Lua::new(); let lua = mlua::Lua::new();
@ -101,6 +89,8 @@ async fn app() -> anyhow::Result<()> {
lua.globals().set("automation", automation)?; lua.globals().set("automation", automation)?;
// Register all the device types // Register all the device types
Ntfy::register_with_lua(&lua)?;
Presence::register_with_lua(&lua)?;
AirFilter::register_with_lua(&lua)?; AirFilter::register_with_lua(&lua)?;
AudioSetup::register_with_lua(&lua)?; AudioSetup::register_with_lua(&lua)?;
ContactSensor::register_with_lua(&lua)?; ContactSensor::register_with_lua(&lua)?;