Compare commits

..

1 Commits

Author SHA1 Message Date
e02edbcd28
DeviceManager no longer handles subscribing and filtering topics, each device has to do this themselves now
All checks were successful
Build and deploy automation_rs / Build automation_rs (push) Successful in 6m15s
Build and deploy automation_rs / Build Docker image (push) Successful in 48s
Build and deploy automation_rs / Deploy Docker container (push) Has been skipped
2024-04-29 01:46:43 +02:00
21 changed files with 145 additions and 169 deletions

View File

@ -1,9 +1,30 @@
use proc_macro2::TokenStream;
use quote::quote;
use syn::DeriveInput;
use syn::{Data, DataStruct, DeriveInput, Fields, FieldsNamed};
pub fn impl_lua_device_macro(ast: &DeriveInput) -> TokenStream {
let name = &ast.ident;
// TODO: Handle errors properly
// This includes making sure one, and only one config is specified
let config = if let Data::Struct(DataStruct {
fields: Fields::Named(FieldsNamed { ref named, .. }),
..
}) = ast.data
{
named
.iter()
.find(|&field| {
field
.attrs
.iter()
.any(|attr| attr.path().is_ident("config"))
})
.map(|field| field.ty.clone())
.unwrap()
} else {
unimplemented!()
};
let gen = quote! {
impl #name {
pub fn register_with_lua(lua: &mlua::Lua) -> mlua::Result<()> {
@ -13,10 +34,8 @@ pub fn impl_lua_device_macro(ast: &DeriveInput) -> TokenStream {
impl mlua::UserData for #name {
fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) {
methods.add_async_function("new", |lua, config: mlua::Value| async {
let config = mlua::FromLua::from_lua(config, lua)?;
// TODO: Using crate:: could cause issues
let device: #name = crate::devices::LuaDeviceCreate::create(config).await.map_err(mlua::ExternalError::into_lua_err)?;
let config: #config = mlua::FromLua::from_lua(config, lua)?;
let device = #name::create(config).await.map_err(mlua::ExternalError::into_lua_err)?;
Ok(crate::device_manager::WrappedDevice::new(Box::new(device)))
});

View File

@ -13,15 +13,6 @@ local function mqtt_automation(topic)
return "automation/" .. topic
end
local mqtt_client = automation.create_mqtt_client({
host = debug and "olympus.lan.huizinga.dev" or "mosquitto",
port = 8883,
client_name = debug and "automation-debug" or "automation_rs",
username = "mqtt",
password = automation.util.get_env("MQTT_PASSWORD"),
tls = debug and true or false,
})
automation.device_manager:add(Ntfy.new({
topic = automation.util.get_env("NTFY_TOPIC"),
event_channel = automation.event_channel,
@ -29,14 +20,14 @@ automation.device_manager:add(Ntfy.new({
automation.device_manager:add(Presence.new({
topic = "automation_dev/presence/+/#",
client = mqtt_client,
client = automation.mqtt_client,
event_channel = automation.event_channel,
}))
automation.device_manager:add(DebugBridge.new({
identifier = "debug_bridge",
topic = mqtt_automation("debug"),
client = mqtt_client,
client = automation.mqtt_client,
}))
local hue_ip = "10.0.0.146"
@ -55,7 +46,7 @@ automation.device_manager:add(HueBridge.new({
automation.device_manager:add(LightSensor.new({
identifier = "living_light_sensor",
topic = mqtt_z2m("living/light"),
client = mqtt_client,
client = automation.mqtt_client,
min = 22000,
max = 23500,
event_channel = automation.event_channel,
@ -65,7 +56,7 @@ automation.device_manager:add(WakeOnLAN.new({
name = "Zeus",
room = "Living Room",
topic = mqtt_automation("appliance/living_room/zeus"),
client = mqtt_client,
client = automation.mqtt_client,
mac_address = "30:9c:23:60:9c:13",
broadcast_ip = "10.0.0.255",
}))
@ -78,7 +69,7 @@ automation.device_manager:add(living_speakers)
automation.device_manager:add(AudioSetup.new({
identifier = "living_audio",
topic = mqtt_z2m("living/remote"),
client = mqtt_client,
client = automation.mqtt_client,
mixer = living_mixer,
speakers = living_speakers,
}))
@ -88,7 +79,7 @@ automation.device_manager:add(IkeaOutlet.new({
name = "Kettle",
room = "Kitchen",
topic = mqtt_z2m("kitchen/kettle"),
client = mqtt_client,
client = automation.mqtt_client,
timeout = debug and 5 or 300,
remotes = {
{ topic = mqtt_z2m("bedroom/remote") },
@ -101,14 +92,14 @@ automation.device_manager:add(IkeaOutlet.new({
name = "Light",
room = "Bathroom",
topic = mqtt_z2m("batchroom/light"),
client = mqtt_client,
client = automation.mqtt_client,
timeout = debug and 60 or 45 * 60,
}))
automation.device_manager:add(Washer.new({
identifier = "bathroom_washer",
topic = mqtt_z2m("batchroom/washer"),
client = mqtt_client,
client = automation.mqtt_client,
threshold = 1,
event_channel = automation.event_channel,
}))
@ -118,7 +109,7 @@ automation.device_manager:add(IkeaOutlet.new({
name = "Charger",
room = "Workbench",
topic = mqtt_z2m("workbench/charger"),
client = mqtt_client,
client = automation.mqtt_client,
timeout = debug and 5 or 20 * 3600,
}))
@ -126,7 +117,7 @@ automation.device_manager:add(IkeaOutlet.new({
name = "Outlet",
room = "Workbench",
topic = mqtt_z2m("workbench/outlet"),
client = mqtt_client,
client = automation.mqtt_client,
}))
local hallway_lights = automation.device_manager:add(HueGroup.new({
@ -139,13 +130,13 @@ local hallway_lights = automation.device_manager:add(HueGroup.new({
remotes = {
{ topic = mqtt_z2m("hallway/remote") },
},
client = mqtt_client,
client = automation.mqtt_client,
}))
automation.device_manager:add(ContactSensor.new({
identifier = "hallway_frontdoor",
topic = mqtt_z2m("hallway/frontdoor"),
client = mqtt_client,
client = automation.mqtt_client,
presence = {
topic = mqtt_automation("presence/contact/frontdoor"),
timeout = debug and 10 or 15 * 60,
@ -160,7 +151,7 @@ local bedroom_air_filter = automation.device_manager:add(AirFilter.new({
name = "Air Filter",
room = "Bedroom",
topic = "pico/filter/bedroom",
client = mqtt_client,
client = automation.mqtt_client,
}))
-- TODO: Use the wrapped device bedroom_air_filter instead of the string

View File

@ -1,2 +1,9 @@
openid:
base_url: "https://login.huizinga.dev/api/oidc"
mqtt:
host: "mosquitto"
port: 8883
client_name: "automation_rs"
username: "mqtt"
password: "${MQTT_PASSWORD}"

View File

@ -1,2 +1,10 @@
openid:
base_url: "https://login.huizinga.dev/api/oidc"
mqtt:
host: "olympus.lan.huizinga.dev"
port: 8883
client_name: "automation-zeus"
username: "mqtt"
password: "${MQTT_PASSWORD}"
tls: true

View File

@ -4,7 +4,7 @@ use std::time::Duration;
use regex::{Captures, Regex};
use rumqttc::{MqttOptions, Transport};
use serde::Deserialize;
use serde::{Deserialize, Deserializer};
use tracing::debug;
use crate::auth::OpenIDConfig;
@ -13,6 +13,8 @@ use crate::error::{ConfigParseError, MissingEnv};
#[derive(Debug, Deserialize)]
pub struct Config {
pub openid: OpenIDConfig,
#[serde(deserialize_with = "deserialize_mqtt_options")]
pub mqtt: MqttOptions,
#[serde(default)]
pub fullfillment: FullfillmentConfig,
}
@ -42,6 +44,13 @@ impl From<MqttConfig> for MqttOptions {
}
}
fn deserialize_mqtt_options<'de, D>(deserializer: D) -> Result<MqttOptions, D::Error>
where
D: Deserializer<'de>,
{
Ok(MqttOptions::from(MqttConfig::deserialize(deserializer)?))
}
#[derive(Debug, Deserialize)]
pub struct FullfillmentConfig {
#[serde(default = "default_fullfillment_ip")]

View File

@ -8,9 +8,9 @@ use google_home::GoogleHomeDevice;
use rumqttc::Publish;
use tracing::{debug, error, trace, warn};
use super::LuaDeviceCreate;
use crate::config::{InfoConfig, MqttDeviceConfig};
use crate::devices::Device;
use crate::error::DeviceConfigError;
use crate::event::OnMqtt;
use crate::messages::{AirFilterFanState, AirFilterState, SetAirFilterFanState};
use crate::mqtt::WrappedAsyncClient;
@ -27,6 +27,7 @@ pub struct AirFilterConfig {
#[derive(Debug, LuaDevice)]
pub struct AirFilter {
#[config]
config: AirFilterConfig,
last_known_state: AirFilterState,
@ -41,7 +42,7 @@ impl AirFilter {
self.config
.client
.publish(
&topic,
topic.clone(),
rumqttc::QoS::AtLeastOnce,
false,
serde_json::to_string(&message).unwrap(),
@ -52,17 +53,13 @@ impl AirFilter {
}
}
#[async_trait]
impl LuaDeviceCreate for AirFilter {
type Config = AirFilterConfig;
type Error = rumqttc::ClientError;
async fn create(config: Self::Config) -> Result<Self, Self::Error> {
impl AirFilter {
async fn create(config: AirFilterConfig) -> Result<Self, DeviceConfigError> {
trace!(id = config.info.identifier(), "Setting up AirFilter");
config
.client
.subscribe(&config.mqtt.topic, rumqttc::QoS::AtLeastOnce)
.subscribe(config.mqtt.topic.clone(), rumqttc::QoS::AtLeastOnce)
.await?;
Ok(Self {

View File

@ -3,7 +3,7 @@ use automation_macro::{LuaDevice, LuaDeviceConfig};
use google_home::traits::OnOff;
use tracing::{debug, error, trace, warn};
use super::{Device, LuaDeviceCreate};
use super::Device;
use crate::config::MqttDeviceConfig;
use crate::device_manager::WrappedDevice;
use crate::devices::As;
@ -27,15 +27,12 @@ pub struct AudioSetupConfig {
#[derive(Debug, LuaDevice)]
pub struct AudioSetup {
#[config]
config: AudioSetupConfig,
}
#[async_trait]
impl LuaDeviceCreate for AudioSetup {
type Config = AudioSetupConfig;
type Error = DeviceConfigError;
async fn create(config: Self::Config) -> Result<Self, Self::Error> {
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();
@ -50,7 +47,7 @@ impl LuaDeviceCreate for AudioSetup {
config
.client
.subscribe(&config.mqtt.topic, rumqttc::QoS::AtLeastOnce)
.subscribe(config.mqtt.topic.clone(), rumqttc::QoS::AtLeastOnce)
.await?;
Ok(AudioSetup { config })

View File

@ -7,7 +7,7 @@ use mlua::FromLua;
use tokio::task::JoinHandle;
use tracing::{debug, error, trace, warn};
use super::{Device, LuaDeviceCreate};
use super::Device;
use crate::config::MqttDeviceConfig;
use crate::device_manager::WrappedDevice;
use crate::devices::{As, DEFAULT_PRESENCE};
@ -64,6 +64,7 @@ pub struct ContactSensorConfig {
#[derive(Debug, LuaDevice)]
pub struct ContactSensor {
#[config]
config: ContactSensorConfig,
overall_presence: bool,
@ -71,12 +72,8 @@ pub struct ContactSensor {
handle: Option<JoinHandle<()>>,
}
#[async_trait]
impl LuaDeviceCreate for ContactSensor {
type Config = ContactSensorConfig;
type Error = DeviceConfigError;
async fn create(config: Self::Config) -> Result<Self, Self::Error> {
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
@ -96,7 +93,7 @@ impl LuaDeviceCreate for ContactSensor {
config
.client
.subscribe(&config.mqtt.topic, rumqttc::QoS::AtLeastOnce)
.subscribe(config.mqtt.topic.clone(), rumqttc::QoS::AtLeastOnce)
.await?;
Ok(Self {
@ -195,7 +192,7 @@ impl OnMqtt for ContactSensor {
self.config
.client
.publish(
&presence.mqtt.topic,
presence.mqtt.topic.clone(),
rumqttc::QoS::AtLeastOnce,
false,
serde_json::to_string(&PresenceMessage::new(true)).unwrap(),
@ -220,7 +217,7 @@ impl OnMqtt for ContactSensor {
tokio::time::sleep(timeout).await;
debug!(id, "Removing door device!");
client
.publish(&topic, rumqttc::QoS::AtLeastOnce, false, "")
.publish(topic.clone(), rumqttc::QoS::AtLeastOnce, false, "")
.await
.map_err(|err| warn!("Failed to publish presence on {topic}: {err}"))
.ok();

View File

@ -1,12 +1,10 @@
use std::convert::Infallible;
use async_trait::async_trait;
use automation_macro::{LuaDevice, LuaDeviceConfig};
use tracing::{trace, warn};
use super::LuaDeviceCreate;
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;
@ -22,15 +20,12 @@ pub struct DebugBridgeConfig {
#[derive(Debug, LuaDevice)]
pub struct DebugBridge {
#[config]
config: DebugBridgeConfig,
}
#[async_trait]
impl LuaDeviceCreate for DebugBridge {
type Config = DebugBridgeConfig;
type Error = Infallible;
async fn create(config: Self::Config) -> Result<Self, Self::Error> {
impl DebugBridge {
async fn create(config: DebugBridgeConfig) -> Result<Self, DeviceConfigError> {
trace!(id = config.identifier, "Setting up DebugBridge");
Ok(Self { config })
}

View File

@ -1,4 +1,3 @@
use std::convert::Infallible;
use std::net::SocketAddr;
use async_trait::async_trait;
@ -6,8 +5,8 @@ use automation_macro::{LuaDevice, LuaDeviceConfig};
use serde::{Deserialize, Serialize};
use tracing::{error, trace, warn};
use super::LuaDeviceCreate;
use crate::devices::Device;
use crate::error::DeviceConfigError;
use crate::event::{OnDarkness, OnPresence};
#[derive(Debug)]
@ -33,6 +32,7 @@ pub struct HueBridgeConfig {
#[derive(Debug, LuaDevice)]
pub struct HueBridge {
#[config]
config: HueBridgeConfig,
}
@ -41,18 +41,12 @@ struct FlagMessage {
flag: bool,
}
#[async_trait]
impl LuaDeviceCreate for HueBridge {
type Config = HueBridgeConfig;
type Error = Infallible;
async fn create(config: Self::Config) -> Result<Self, Infallible> {
impl HueBridge {
async fn create(config: HueBridgeConfig) -> Result<Self, DeviceConfigError> {
trace!(id = config.identifier, "Setting up HueBridge");
Ok(Self { config })
}
}
impl HueBridge {
pub async fn set_flag(&self, flag: Flag, value: bool) {
let flag_id = match flag {
Flag::Presence => self.config.flags.presence,

View File

@ -9,8 +9,9 @@ use google_home::traits::OnOff;
use rumqttc::{Publish, SubscribeFilter};
use tracing::{debug, error, trace, warn};
use super::{Device, LuaDeviceCreate};
use super::Device;
use crate::config::MqttDeviceConfig;
use crate::error::DeviceConfigError;
use crate::event::OnMqtt;
use crate::messages::{RemoteAction, RemoteMessage};
use crate::mqtt::WrappedAsyncClient;
@ -33,16 +34,13 @@ pub struct HueGroupConfig {
#[derive(Debug, LuaDevice)]
pub struct HueGroup {
#[config]
config: HueGroupConfig,
}
// Couple of helper function to get the correct urls
#[async_trait]
impl LuaDeviceCreate for HueGroup {
type Config = HueGroupConfig;
type Error = rumqttc::ClientError;
async fn create(config: Self::Config) -> Result<Self, Self::Error> {
impl HueGroup {
async fn create(config: HueGroupConfig) -> Result<Self, DeviceConfigError> {
trace!(id = config.identifier, "Setting up AudioSetup");
if !config.remotes.is_empty() {
@ -57,9 +55,7 @@ impl LuaDeviceCreate for HueGroup {
Ok(Self { config })
}
}
impl HueGroup {
fn url_base(&self) -> String {
format!("http://{}/api/{}", self.config.addr, self.config.login)
}

View File

@ -12,9 +12,9 @@ use serde::Deserialize;
use tokio::task::JoinHandle;
use tracing::{debug, error, trace, warn};
use super::LuaDeviceCreate;
use crate::config::{InfoConfig, MqttDeviceConfig};
use crate::devices::Device;
use crate::error::DeviceConfigError;
use crate::event::{OnMqtt, OnPresence};
use crate::messages::{OnOffMessage, RemoteAction, RemoteMessage};
use crate::mqtt::WrappedAsyncClient;
@ -47,6 +47,7 @@ pub struct IkeaOutletConfig {
#[derive(Debug, LuaDevice)]
pub struct IkeaOutlet {
#[config]
config: IkeaOutletConfig,
last_known_state: bool,
@ -60,7 +61,7 @@ async fn set_on(client: WrappedAsyncClient, topic: &str, on: bool) {
// TODO: Handle potential errors here
client
.publish(
&topic,
topic.clone(),
rumqttc::QoS::AtLeastOnce,
false,
serde_json::to_string(&message).unwrap(),
@ -70,12 +71,8 @@ async fn set_on(client: WrappedAsyncClient, topic: &str, on: bool) {
.ok();
}
#[async_trait]
impl LuaDeviceCreate for IkeaOutlet {
type Config = IkeaOutletConfig;
type Error = rumqttc::ClientError;
async fn create(config: Self::Config) -> Result<Self, Self::Error> {
impl IkeaOutlet {
async fn create(config: IkeaOutletConfig) -> Result<Self, DeviceConfigError> {
trace!(id = config.info.identifier(), "Setting up IkeaOutlet");
if !config.remotes.is_empty() {
@ -88,11 +85,6 @@ impl LuaDeviceCreate for IkeaOutlet {
.await?;
}
config
.client
.subscribe(&config.mqtt.topic, rumqttc::QoS::AtLeastOnce)
.await?;
Ok(Self {
config,
last_known_state: false,

View File

@ -1,4 +1,3 @@
use std::convert::Infallible;
use std::net::SocketAddr;
use std::str::Utf8Error;
@ -13,7 +12,8 @@ use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use tracing::trace;
use super::{Device, LuaDeviceCreate};
use super::Device;
use crate::error::DeviceConfigError;
#[derive(Debug, Clone, LuaDeviceConfig)]
pub struct KasaOutletConfig {
@ -24,15 +24,12 @@ pub struct KasaOutletConfig {
#[derive(Debug, LuaDevice)]
pub struct KasaOutlet {
#[config]
config: KasaOutletConfig,
}
#[async_trait]
impl LuaDeviceCreate for KasaOutlet {
type Config = KasaOutletConfig;
type Error = Infallible;
async fn create(config: Self::Config) -> Result<Self, Self::Error> {
impl KasaOutlet {
async fn create(config: KasaOutletConfig) -> Result<Self, DeviceConfigError> {
trace!(id = config.identifier, "Setting up KasaOutlet");
Ok(Self { config })
}

View File

@ -3,9 +3,9 @@ use automation_macro::{LuaDevice, LuaDeviceConfig};
use rumqttc::Publish;
use tracing::{debug, trace, warn};
use super::LuaDeviceCreate;
use crate::config::MqttDeviceConfig;
use crate::devices::Device;
use crate::error::DeviceConfigError;
use crate::event::{self, Event, EventChannel, OnMqtt};
use crate::messages::BrightnessMessage;
use crate::mqtt::WrappedAsyncClient;
@ -27,22 +27,19 @@ pub const DEFAULT: bool = false;
#[derive(Debug, LuaDevice)]
pub struct LightSensor {
#[config]
config: LightSensorConfig,
is_dark: bool,
}
#[async_trait]
impl LuaDeviceCreate for LightSensor {
type Config = LightSensorConfig;
type Error = rumqttc::ClientError;
async fn create(config: Self::Config) -> Result<Self, Self::Error> {
impl LightSensor {
async fn create(config: LightSensorConfig) -> Result<Self, DeviceConfigError> {
trace!(id = config.identifier, "Setting up LightSensor");
config
.client
.subscribe(&config.mqtt.topic, rumqttc::QoS::AtLeastOnce)
.subscribe(config.mqtt.topic.clone(), rumqttc::QoS::AtLeastOnce)
.await?;
Ok(Self {

View File

@ -12,7 +12,6 @@ mod presence;
mod wake_on_lan;
mod washer;
use async_trait::async_trait;
use google_home::device::AsGoogleHomeDevice;
use google_home::traits::OnOff;
@ -32,16 +31,6 @@ pub use self::washer::*;
use crate::event::{OnDarkness, OnMqtt, OnNotification, OnPresence};
use crate::traits::Timeout;
#[async_trait]
pub trait LuaDeviceCreate {
type Config;
type Error;
async fn create(config: Self::Config) -> Result<Self, Self::Error>
where
Self: Sized;
}
#[impl_cast::device(As: OnMqtt + OnPresence + OnDarkness + OnNotification + OnOff + Timeout)]
pub trait Device: AsGoogleHomeDevice + std::fmt::Debug + Sync + Send {
fn get_id(&self) -> String;

View File

@ -1,5 +1,4 @@
use std::collections::HashMap;
use std::convert::Infallible;
use async_trait::async_trait;
use automation_macro::{LuaDevice, LuaDeviceConfig};
@ -7,8 +6,8 @@ use serde::Serialize;
use serde_repr::*;
use tracing::{error, trace, warn};
use super::LuaDeviceCreate;
use crate::devices::Device;
use crate::error::DeviceConfigError;
use crate::event::{self, Event, EventChannel, OnNotification, OnPresence};
#[derive(Debug, Serialize_repr, Clone, Copy)]
@ -122,15 +121,12 @@ pub struct NtfyConfig {
#[derive(Debug, LuaDevice)]
pub struct Ntfy {
#[config]
config: NtfyConfig,
}
#[async_trait]
impl LuaDeviceCreate for Ntfy {
type Config = NtfyConfig;
type Error = Infallible;
async fn create(config: Self::Config) -> Result<Self, Self::Error> {
impl Ntfy {
async fn create(config: NtfyConfig) -> Result<Self, DeviceConfigError> {
trace!(id = "ntfy", "Setting up Ntfy");
Ok(Self { config })
}

View File

@ -5,9 +5,9 @@ use automation_macro::{LuaDevice, LuaDeviceConfig};
use rumqttc::Publish;
use tracing::{debug, trace, warn};
use super::LuaDeviceCreate;
use crate::config::MqttDeviceConfig;
use crate::devices::Device;
use crate::error::DeviceConfigError;
use crate::event::{self, Event, EventChannel, OnMqtt};
use crate::messages::PresenceMessage;
use crate::mqtt::WrappedAsyncClient;
@ -26,22 +26,19 @@ pub const DEFAULT_PRESENCE: bool = false;
#[derive(Debug, LuaDevice)]
pub struct Presence {
#[config]
config: PresenceConfig,
devices: HashMap<String, bool>,
current_overall_presence: bool,
}
#[async_trait]
impl LuaDeviceCreate for Presence {
type Config = PresenceConfig;
type Error = rumqttc::ClientError;
async fn create(config: Self::Config) -> Result<Self, Self::Error> {
impl Presence {
async fn create(config: PresenceConfig) -> Result<Self, DeviceConfigError> {
trace!(id = "ntfy", "Setting up Presence");
config
.client
.subscribe(&config.mqtt.topic, rumqttc::QoS::AtLeastOnce)
.subscribe(config.mqtt.topic.clone(), rumqttc::QoS::AtLeastOnce)
.await?;
Ok(Self {

View File

@ -10,8 +10,9 @@ use google_home::{device, GoogleHomeDevice};
use rumqttc::Publish;
use tracing::{debug, error, trace};
use super::{Device, LuaDeviceCreate};
use super::Device;
use crate::config::{InfoConfig, MqttDeviceConfig};
use crate::error::DeviceConfigError;
use crate::event::OnMqtt;
use crate::messages::ActivateMessage;
use crate::mqtt::WrappedAsyncClient;
@ -31,20 +32,17 @@ pub struct WakeOnLANConfig {
#[derive(Debug, LuaDevice)]
pub struct WakeOnLAN {
#[config]
config: WakeOnLANConfig,
}
#[async_trait]
impl LuaDeviceCreate for WakeOnLAN {
type Config = WakeOnLANConfig;
type Error = rumqttc::ClientError;
async fn create(config: Self::Config) -> Result<Self, Self::Error> {
impl WakeOnLAN {
async fn create(config: WakeOnLANConfig) -> Result<Self, DeviceConfigError> {
trace!(id = config.info.identifier(), "Setting up WakeOnLAN");
config
.client
.subscribe(&config.mqtt.topic, rumqttc::QoS::AtLeastOnce)
.subscribe(config.mqtt.topic.clone(), rumqttc::QoS::AtLeastOnce)
.await?;
Ok(Self { config })

View File

@ -4,8 +4,9 @@ use rumqttc::Publish;
use tracing::{debug, error, trace, warn};
use super::ntfy::Priority;
use super::{Device, LuaDeviceCreate, Notification};
use super::{Device, Notification};
use crate::config::MqttDeviceConfig;
use crate::error::DeviceConfigError;
use crate::event::{self, Event, EventChannel, OnMqtt};
use crate::messages::PowerMessage;
use crate::mqtt::WrappedAsyncClient;
@ -26,22 +27,19 @@ pub struct WasherConfig {
// TODO: Add google home integration
#[derive(Debug, LuaDevice)]
pub struct Washer {
#[config]
config: WasherConfig,
running: isize,
}
#[async_trait]
impl LuaDeviceCreate for Washer {
type Config = WasherConfig;
type Error = rumqttc::ClientError;
async fn create(config: Self::Config) -> Result<Self, Self::Error> {
impl Washer {
async fn create(config: WasherConfig) -> Result<Self, DeviceConfigError> {
trace!(id = config.identifier, "Setting up Washer");
config
.client
.subscribe(&config.mqtt.topic, rumqttc::QoS::AtLeastOnce)
.subscribe(config.mqtt.topic.clone(), rumqttc::QoS::AtLeastOnce)
.await?;
Ok(Self { config, running: 0 })

View File

@ -92,9 +92,13 @@ impl MissingWildcard {
#[derive(Debug, Error)]
pub enum DeviceConfigError {
#[error("Child '{1}' of device '{0}' does not exist")]
MissingChild(String, String),
#[error("Device '{0}' does not implement expected trait '{1}'")]
MissingTrait(String, String),
#[error(transparent)]
MissingWildcard(#[from] MissingWildcard),
#[error(transparent)]
MqttClientError(#[from] rumqttc::ClientError),
}

View File

@ -2,7 +2,7 @@
use std::{fs, process};
use automation::auth::{OpenIDConfig, User};
use automation::config::{Config, MqttConfig};
use automation::config::Config;
use automation::device_manager::DeviceManager;
use automation::devices::{
AirFilter, AudioSetup, ContactSensor, DebugBridge, HueBridge, HueGroup, IkeaOutlet, KasaOutlet,
@ -17,7 +17,6 @@ use axum::routing::post;
use axum::{Json, Router};
use dotenvy::dotenv;
use google_home::{GoogleHome, Request};
use mlua::LuaSerdeExt;
use rumqttc::AsyncClient;
use tracing::{debug, error, info, warn};
@ -56,9 +55,15 @@ async fn app() -> anyhow::Result<()> {
std::env::var("AUTOMATION_CONFIG").unwrap_or("./config/config.yml".into());
let config = Config::parse_file(&config_filename)?;
// Create a mqtt client
// TODO: Since we wait with starting the eventloop we might fill the queue while setting up devices
let (client, eventloop) = AsyncClient::new(config.mqtt.clone(), 100);
// Setup the device handler
let device_manager = DeviceManager::new();
let event_channel = device_manager.event_channel();
// Lua testing
{
let lua = mlua::Lua::new();
@ -69,20 +74,9 @@ async fn app() -> anyhow::Result<()> {
});
let automation = lua.create_table()?;
let event_channel = device_manager.event_channel();
let create_mqtt_client = lua.create_function(move |lua, config: mlua::Value| {
let config: MqttConfig = lua.from_value(config)?;
// Create a mqtt client
// TODO: When starting up, the devices are not yet created, this could lead to a device being out of sync
let (client, eventloop) = AsyncClient::new(config.into(), 100);
mqtt::start(eventloop, &event_channel);
Ok(WrappedAsyncClient(client))
})?;
automation.set("create_mqtt_client", create_mqtt_client)?;
automation.set("device_manager", device_manager.clone())?;
automation.set("mqtt_client", WrappedAsyncClient(client.clone()))?;
automation.set("event_channel", device_manager.event_channel())?;
let util = lua.create_table()?;
@ -121,6 +115,10 @@ async fn app() -> anyhow::Result<()> {
}?;
}
// Wrap the mqtt eventloop and start listening for message
// NOTE: We wait until all the setup is done, as otherwise we might miss some messages
mqtt::start(eventloop, &event_channel);
// Create google home fullfillment route
let fullfillment = Router::new().route(
"/google_home",