Compare commits

5 Commits

Author SHA1 Message Date
18f9e20633 Removed old notification system
All checks were successful
Build and deploy / build (push) Successful in 8m33s
Build and deploy / Deploy container (push) Successful in 25s
2025-08-31 00:56:42 +02:00
7237cac887 Converted presence notification into lua callback 2025-08-31 00:54:15 +02:00
5a8f2be99f Send laundy notification from lua 2025-08-31 00:53:42 +02:00
68a34b5fae Make it possible to send notifications from lua 2025-08-31 00:53:05 +02:00
461d24c0c2 Converted macro to derive macro 2025-08-31 00:38:58 +02:00
22 changed files with 186 additions and 192 deletions

View File

@@ -1,7 +1,7 @@
use async_trait::async_trait; use async_trait::async_trait;
use automation_lib::config::InfoConfig; use automation_lib::config::InfoConfig;
use automation_lib::device::{Device, LuaDeviceCreate}; use automation_lib::device::{Device, LuaDeviceCreate};
use automation_macro::{LuaDeviceConfig, impl_device}; use automation_macro::{LuaDevice, LuaDeviceConfig};
use google_home::device::Name; use google_home::device::Name;
use google_home::errors::ErrorCode; use google_home::errors::ErrorCode;
use google_home::traits::{ use google_home::traits::{
@@ -19,7 +19,8 @@ pub struct Config {
pub url: String, pub url: String,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone, LuaDevice)]
#[traits(OnOff)]
pub struct AirFilter { pub struct AirFilter {
config: Config, config: Config,
} }
@@ -62,7 +63,6 @@ impl AirFilter {
Ok(reqwest::get(url).await?.json().await?) Ok(reqwest::get(url).await?.json().await?)
} }
} }
impl_device!(AirFilter);
#[async_trait] #[async_trait]
impl LuaDeviceCreate for AirFilter { impl LuaDeviceCreate for AirFilter {

View File

@@ -10,7 +10,7 @@ use automation_lib::event::{OnMqtt, OnPresence};
use automation_lib::messages::{ContactMessage, PresenceMessage}; use automation_lib::messages::{ContactMessage, PresenceMessage};
use automation_lib::mqtt::WrappedAsyncClient; use automation_lib::mqtt::WrappedAsyncClient;
use automation_lib::presence::DEFAULT_PRESENCE; use automation_lib::presence::DEFAULT_PRESENCE;
use automation_macro::{LuaDeviceConfig, impl_device}; use automation_macro::{LuaDevice, LuaDeviceConfig};
use google_home::device; use google_home::device;
use google_home::errors::{DeviceError, ErrorCode}; use google_home::errors::{DeviceError, ErrorCode};
use google_home::traits::OpenClose; use google_home::traits::OpenClose;
@@ -61,12 +61,11 @@ struct State {
handle: Option<JoinHandle<()>>, handle: Option<JoinHandle<()>>,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone, LuaDevice)]
pub struct ContactSensor { pub struct ContactSensor {
config: Config, config: Config,
state: Arc<RwLock<State>>, state: Arc<RwLock<State>>,
} }
impl_device!(ContactSensor);
impl ContactSensor { impl ContactSensor {
async fn state(&self) -> RwLockReadGuard<'_, State> { async fn state(&self) -> RwLockReadGuard<'_, State> {

View File

@@ -6,7 +6,7 @@ use automation_lib::device::{Device, LuaDeviceCreate};
use automation_lib::event::{OnDarkness, OnPresence}; use automation_lib::event::{OnDarkness, OnPresence};
use automation_lib::messages::{DarknessMessage, PresenceMessage}; use automation_lib::messages::{DarknessMessage, PresenceMessage};
use automation_lib::mqtt::WrappedAsyncClient; use automation_lib::mqtt::WrappedAsyncClient;
use automation_macro::{LuaDeviceConfig, impl_device}; use automation_macro::{LuaDevice, LuaDeviceConfig};
use tracing::{trace, warn}; use tracing::{trace, warn};
#[derive(Debug, LuaDeviceConfig, Clone)] #[derive(Debug, LuaDeviceConfig, Clone)]
@@ -18,11 +18,10 @@ pub struct Config {
pub client: WrappedAsyncClient, pub client: WrappedAsyncClient,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone, LuaDevice)]
pub struct DebugBridge { pub struct DebugBridge {
config: Config, config: Config,
} }
impl_device!(DebugBridge);
#[async_trait] #[async_trait]
impl LuaDeviceCreate for DebugBridge { impl LuaDeviceCreate for DebugBridge {

View File

@@ -4,7 +4,7 @@ use std::net::SocketAddr;
use async_trait::async_trait; use async_trait::async_trait;
use automation_lib::device::{Device, LuaDeviceCreate}; use automation_lib::device::{Device, LuaDeviceCreate};
use automation_lib::event::{OnDarkness, OnPresence}; use automation_lib::event::{OnDarkness, OnPresence};
use automation_macro::{LuaDeviceConfig, impl_device}; use automation_macro::{LuaDevice, LuaDeviceConfig};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tracing::{error, trace, warn}; use tracing::{error, trace, warn};
@@ -29,11 +29,10 @@ pub struct Config {
pub flags: FlagIDs, pub flags: FlagIDs,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone, LuaDevice)]
pub struct HueBridge { pub struct HueBridge {
config: Config, config: Config,
} }
impl_device!(HueBridge);
#[derive(Debug, Serialize)] #[derive(Debug, Serialize)]
struct FlagMessage { struct FlagMessage {

View File

@@ -2,7 +2,7 @@ use std::net::SocketAddr;
use anyhow::Result; use anyhow::Result;
use async_trait::async_trait; use async_trait::async_trait;
use automation_macro::{LuaDeviceConfig, impl_device}; 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 tracing::{error, trace, warn}; use tracing::{error, trace, warn};
@@ -19,11 +19,11 @@ pub struct Config {
pub scene_id: String, pub scene_id: String,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone, LuaDevice)]
#[traits(OnOff)]
pub struct HueGroup { pub struct HueGroup {
config: Config, config: Config,
} }
impl_device!(HueGroup);
// Couple of helper function to get the correct urls // Couple of helper function to get the correct urls
#[async_trait] #[async_trait]

View File

@@ -4,7 +4,7 @@ use automation_lib::config::{InfoConfig, MqttDeviceConfig};
use automation_lib::device::{Device, LuaDeviceCreate}; use automation_lib::device::{Device, LuaDeviceCreate};
use automation_lib::event::OnMqtt; use automation_lib::event::OnMqtt;
use automation_lib::mqtt::WrappedAsyncClient; use automation_lib::mqtt::WrappedAsyncClient;
use automation_macro::{LuaDeviceConfig, impl_device}; use automation_macro::{LuaDevice, LuaDeviceConfig};
use rumqttc::{Publish, matches}; use rumqttc::{Publish, matches};
use serde::Deserialize; use serde::Deserialize;
use tracing::{debug, trace, warn}; use tracing::{debug, trace, warn};
@@ -51,11 +51,10 @@ struct State {
action: Action, action: Action,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone, LuaDevice)]
pub struct HueSwitch { pub struct HueSwitch {
config: Config, config: Config,
} }
impl_device!(HueSwitch);
impl Device for HueSwitch { impl Device for HueSwitch {
fn get_id(&self) -> String { fn get_id(&self) -> String {

View File

@@ -4,7 +4,7 @@ use automation_lib::device::{Device, LuaDeviceCreate};
use automation_lib::event::OnMqtt; use automation_lib::event::OnMqtt;
use automation_lib::messages::{RemoteAction, RemoteMessage}; use automation_lib::messages::{RemoteAction, RemoteMessage};
use automation_lib::mqtt::WrappedAsyncClient; use automation_lib::mqtt::WrappedAsyncClient;
use automation_macro::{LuaDeviceConfig, impl_device}; use automation_macro::{LuaDevice, LuaDeviceConfig};
use axum::async_trait; use axum::async_trait;
use rumqttc::{Publish, matches}; use rumqttc::{Publish, matches};
use tracing::{debug, error, trace}; use tracing::{debug, error, trace};
@@ -27,11 +27,10 @@ pub struct Config {
pub callback: ActionCallback<IkeaRemote, bool>, pub callback: ActionCallback<IkeaRemote, bool>,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone, LuaDevice)]
pub struct IkeaRemote { pub struct IkeaRemote {
config: Config, config: Config,
} }
impl_device!(IkeaRemote);
impl Device for IkeaRemote { impl Device for IkeaRemote {
fn get_id(&self) -> String { fn get_id(&self) -> String {

View File

@@ -5,7 +5,7 @@ use std::str::Utf8Error;
use async_trait::async_trait; use async_trait::async_trait;
use automation_lib::device::{Device, LuaDeviceCreate}; use automation_lib::device::{Device, LuaDeviceCreate};
use automation_lib::event::OnPresence; use automation_lib::event::OnPresence;
use automation_macro::{LuaDeviceConfig, impl_device}; use automation_macro::{LuaDevice, LuaDeviceConfig};
use bytes::{Buf, BufMut}; use bytes::{Buf, BufMut};
use google_home::errors::{self, DeviceError}; use google_home::errors::{self, DeviceError};
use google_home::traits::OnOff; use google_home::traits::OnOff;
@@ -22,11 +22,11 @@ pub struct Config {
pub addr: SocketAddr, pub addr: SocketAddr,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone, LuaDevice)]
#[traits(OnOff)]
pub struct KasaOutlet { pub struct KasaOutlet {
config: Config, config: Config,
} }
impl_device!(KasaOutlet);
#[async_trait] #[async_trait]
impl LuaDeviceCreate for KasaOutlet { impl LuaDeviceCreate for KasaOutlet {

View File

@@ -6,7 +6,7 @@ use automation_lib::device::{Device, LuaDeviceCreate};
use automation_lib::event::{self, Event, EventChannel, OnMqtt}; use automation_lib::event::{self, Event, EventChannel, OnMqtt};
use automation_lib::messages::BrightnessMessage; use automation_lib::messages::BrightnessMessage;
use automation_lib::mqtt::WrappedAsyncClient; use automation_lib::mqtt::WrappedAsyncClient;
use automation_macro::{LuaDeviceConfig, impl_device}; use automation_macro::{LuaDevice, LuaDeviceConfig};
use rumqttc::Publish; use rumqttc::Publish;
use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard}; use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use tracing::{debug, trace, warn}; use tracing::{debug, trace, warn};
@@ -31,12 +31,11 @@ pub struct State {
is_dark: bool, is_dark: bool,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone, LuaDevice)]
pub struct LightSensor { pub struct LightSensor {
config: Config, config: Config,
state: Arc<RwLock<State>>, state: Arc<RwLock<State>>,
} }
impl_device!(LightSensor);
impl LightSensor { impl LightSensor {
async fn state(&self) -> RwLockReadGuard<'_, State> { async fn state(&self) -> RwLockReadGuard<'_, State> {

View File

@@ -6,7 +6,7 @@ use automation_lib::device::{Device, LuaDeviceCreate};
use automation_lib::event::OnMqtt; use automation_lib::event::OnMqtt;
use automation_lib::messages::ActivateMessage; use automation_lib::messages::ActivateMessage;
use automation_lib::mqtt::WrappedAsyncClient; use automation_lib::mqtt::WrappedAsyncClient;
use automation_macro::{LuaDeviceConfig, impl_device}; use automation_macro::{LuaDevice, LuaDeviceConfig};
use eui48::MacAddress; use eui48::MacAddress;
use google_home::device; use google_home::device;
use google_home::errors::ErrorCode; use google_home::errors::ErrorCode;
@@ -28,11 +28,10 @@ pub struct Config {
pub client: WrappedAsyncClient, pub client: WrappedAsyncClient,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone, LuaDevice)]
pub struct WakeOnLAN { pub struct WakeOnLAN {
config: Config, config: Config,
} }
impl_device!(WakeOnLAN);
#[async_trait] #[async_trait]
impl LuaDeviceCreate for WakeOnLAN { impl LuaDeviceCreate for WakeOnLAN {

View File

@@ -1,16 +1,16 @@
use std::sync::Arc; use std::sync::Arc;
use async_trait::async_trait; use async_trait::async_trait;
use automation_lib::action_callback::ActionCallback;
use automation_lib::config::MqttDeviceConfig; use automation_lib::config::MqttDeviceConfig;
use automation_lib::device::{Device, LuaDeviceCreate}; use automation_lib::device::{Device, LuaDeviceCreate};
use automation_lib::event::{self, Event, EventChannel, OnMqtt}; use automation_lib::event::{self, EventChannel, OnMqtt};
use automation_lib::messages::PowerMessage; use automation_lib::messages::PowerMessage;
use automation_lib::mqtt::WrappedAsyncClient; use automation_lib::mqtt::WrappedAsyncClient;
use automation_lib::ntfy::{Notification, Priority}; use automation_macro::{LuaDevice, LuaDeviceConfig};
use automation_macro::{LuaDeviceConfig, impl_device};
use rumqttc::Publish; use rumqttc::Publish;
use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard}; use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use tracing::{debug, error, trace, warn}; use tracing::{debug, error, trace};
#[derive(Debug, Clone, LuaDeviceConfig)] #[derive(Debug, Clone, LuaDeviceConfig)]
pub struct Config { pub struct Config {
@@ -21,6 +21,10 @@ pub struct Config {
pub threshold: f32, pub threshold: f32,
#[device_config(rename("event_channel"), from_lua, with(|ec: EventChannel| ec.get_tx()))] #[device_config(rename("event_channel"), from_lua, with(|ec: EventChannel| ec.get_tx()))]
pub tx: event::Sender, pub tx: event::Sender,
#[device_config(from_lua, default)]
pub done_callback: ActionCallback<Washer, ()>,
#[device_config(from_lua)] #[device_config(from_lua)]
pub client: WrappedAsyncClient, pub client: WrappedAsyncClient,
} }
@@ -31,12 +35,11 @@ pub struct State {
} }
// TODO: Add google home integration // TODO: Add google home integration
#[derive(Debug, Clone)] #[derive(Debug, Clone, LuaDevice)]
pub struct Washer { pub struct Washer {
config: Config, config: Config,
state: Arc<RwLock<State>>, state: Arc<RwLock<State>>,
} }
impl_device!(Washer);
impl Washer { impl Washer {
async fn state(&self) -> RwLockReadGuard<'_, State> { async fn state(&self) -> RwLockReadGuard<'_, State> {
@@ -97,8 +100,6 @@ impl OnMqtt for Washer {
} }
}; };
// debug!(id = self.identifier, power, "Washer state update");
if power < self.config.threshold && self.state().await.running >= HYSTERESIS { if power < self.config.threshold && self.state().await.running >= HYSTERESIS {
// The washer is done running // The washer is done running
debug!( debug!(
@@ -109,21 +110,8 @@ impl OnMqtt for Washer {
); );
self.state_mut().await.running = 0; self.state_mut().await.running = 0;
let notification = Notification::new()
.set_title("Laundy is done")
.set_message("Don't forget to hang it!")
.add_tag("womans_clothes")
.set_priority(Priority::High);
if self self.config.done_callback.call(self, &()).await;
.config
.tx
.send(Event::Ntfy(notification))
.await
.is_err()
{
warn!("There are no receivers on the event channel");
}
} else if power < self.config.threshold { } else if power < self.config.threshold {
// Prevent false positives // Prevent false positives
self.state_mut().await.running = 0; self.state_mut().await.running = 0;

View File

@@ -10,7 +10,7 @@ use automation_lib::device::{Device, LuaDeviceCreate};
use automation_lib::event::{OnMqtt, OnPresence}; use automation_lib::event::{OnMqtt, OnPresence};
use automation_lib::helpers::serialization::state_deserializer; use automation_lib::helpers::serialization::state_deserializer;
use automation_lib::mqtt::WrappedAsyncClient; use automation_lib::mqtt::WrappedAsyncClient;
use automation_macro::{LuaDeviceConfig, impl_device}; use automation_macro::{LuaDevice, LuaDeviceConfig};
use google_home::device; use google_home::device;
use google_home::errors::ErrorCode; use google_home::errors::ErrorCode;
use google_home::traits::{Brightness, Color, ColorSetting, ColorTemperatureRange, OnOff}; use google_home::traits::{Brightness, Color, ColorSetting, ColorTemperatureRange, OnOff};
@@ -88,7 +88,10 @@ impl From<StateColorTemperature> for StateBrightness {
} }
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone, LuaDevice)]
#[traits(<StateOnOff>: OnOff)]
#[traits(<StateBrightness>: OnOff, Brightness)]
#[traits(<StateColorTemperature>: OnOff, Brightness, ColorSetting)]
pub struct Light<T: LightState> { pub struct Light<T: LightState> {
config: Config<T>, config: Config<T>,
@@ -96,11 +99,8 @@ pub struct Light<T: LightState> {
} }
pub type LightOnOff = Light<StateOnOff>; pub type LightOnOff = Light<StateOnOff>;
impl_device!(LightOnOff -> OnOff);
pub type LightBrightness = Light<StateBrightness>; pub type LightBrightness = Light<StateBrightness>;
impl_device!(LightBrightness -> OnOff, Brightness);
pub type LightColorTemperature = Light<StateColorTemperature>; pub type LightColorTemperature = Light<StateColorTemperature>;
impl_device!(LightColorTemperature -> OnOff, Brightness, ColorSetting);
impl<T: LightState> Light<T> { impl<T: LightState> Light<T> {
async fn state(&self) -> RwLockReadGuard<'_, T> { async fn state(&self) -> RwLockReadGuard<'_, T> {

View File

@@ -10,7 +10,7 @@ use automation_lib::device::{Device, LuaDeviceCreate};
use automation_lib::event::{OnMqtt, OnPresence}; use automation_lib::event::{OnMqtt, OnPresence};
use automation_lib::helpers::serialization::state_deserializer; use automation_lib::helpers::serialization::state_deserializer;
use automation_lib::mqtt::WrappedAsyncClient; use automation_lib::mqtt::WrappedAsyncClient;
use automation_macro::{LuaDeviceConfig, impl_device}; use automation_macro::{LuaDevice, LuaDeviceConfig};
use google_home::device; use google_home::device;
use google_home::errors::ErrorCode; use google_home::errors::ErrorCode;
use google_home::traits::OnOff; use google_home::traits::OnOff;
@@ -84,7 +84,9 @@ impl From<StatePower> for StateOnOff {
} }
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone, LuaDevice)]
#[traits(<StateOnOff>: OnOff)]
#[traits(<StatePower>: OnOff)]
pub struct Outlet<T: OutletState> { pub struct Outlet<T: OutletState> {
config: Config<T>, config: Config<T>,
@@ -92,9 +94,7 @@ pub struct Outlet<T: OutletState> {
} }
pub type OutletOnOff = Outlet<StateOnOff>; pub type OutletOnOff = Outlet<StateOnOff>;
impl_device!(OutletOnOff -> OnOff);
pub type OutletPower = Outlet<StatePower>; pub type OutletPower = Outlet<StatePower>;
impl_device!(OutletPower -> OnOff);
impl<T: OutletState> Outlet<T> { impl<T: OutletState> Outlet<T> {
async fn state(&self) -> RwLockReadGuard<'_, T> { async fn state(&self) -> RwLockReadGuard<'_, T> {

View File

@@ -5,7 +5,7 @@ use dyn_clone::DynClone;
use google_home::traits::OnOff; use google_home::traits::OnOff;
use mlua::ObjectLike; use mlua::ObjectLike;
use crate::event::{OnDarkness, OnMqtt, OnNotification, OnPresence}; use crate::event::{OnDarkness, OnMqtt, OnPresence};
#[async_trait::async_trait] #[async_trait::async_trait]
pub trait LuaDeviceCreate { pub trait LuaDeviceCreate {
@@ -26,7 +26,6 @@ pub trait Device:
+ Cast<dyn OnMqtt> + Cast<dyn OnMqtt>
+ Cast<dyn OnPresence> + Cast<dyn OnPresence>
+ Cast<dyn OnDarkness> + Cast<dyn OnDarkness>
+ Cast<dyn OnNotification>
+ Cast<dyn OnOff> + Cast<dyn OnOff>
{ {
fn get_id(&self) -> String; fn get_id(&self) -> String;

View File

@@ -9,7 +9,7 @@ use tokio_cron_scheduler::{Job, JobScheduler};
use tracing::{debug, instrument, trace}; use tracing::{debug, instrument, trace};
use crate::device::Device; use crate::device::Device;
use crate::event::{Event, EventChannel, OnDarkness, OnMqtt, OnNotification, OnPresence}; use crate::event::{Event, EventChannel, OnDarkness, OnMqtt, OnPresence};
pub type DeviceMap = HashMap<String, Box<dyn Device>>; pub type DeviceMap = HashMap<String, Box<dyn Device>>;
@@ -118,22 +118,6 @@ impl DeviceManager {
} }
}); });
join_all(iter).await;
}
Event::Ntfy(notification) => {
let devices = self.devices.read().await;
let iter = devices.iter().map(|(id, device)| {
let notification = notification.clone();
async move {
let device: Option<&dyn OnNotification> = device.cast();
if let Some(device) = device {
trace!(id, "Handling");
device.on_notification(notification).await;
trace!(id, "Done");
}
}
});
join_all(iter).await; join_all(iter).await;
} }
} }

View File

@@ -3,14 +3,11 @@ use mlua::FromLua;
use rumqttc::Publish; use rumqttc::Publish;
use tokio::sync::mpsc; use tokio::sync::mpsc;
use crate::ntfy::Notification;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum Event { pub enum Event {
MqttMessage(Publish), MqttMessage(Publish),
Darkness(bool), Darkness(bool),
Presence(bool), Presence(bool),
Ntfy(Notification),
} }
pub type Sender = mpsc::Sender<Event>; pub type Sender = mpsc::Sender<Event>;
@@ -48,8 +45,3 @@ pub trait OnPresence: Sync + Send {
pub trait OnDarkness: Sync + Send { pub trait OnDarkness: Sync + Send {
async fn on_darkness(&self, dark: bool); async fn on_darkness(&self, dark: bool);
} }
#[async_trait]
pub trait OnNotification: Sync + Send {
async fn on_notification(&self, notification: Notification);
}

View File

@@ -81,3 +81,9 @@ pub trait OpenClose {
} }
} }
impl<T> OpenClose for T where T: google_home::traits::OpenClose {} impl<T> OpenClose for T where T: google_home::traits::OpenClose {}
pub trait AddAdditionalMethods {
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M)
where
Self: Sized + 'static;
}

View File

@@ -2,16 +2,19 @@ use std::collections::HashMap;
use std::convert::Infallible; use std::convert::Infallible;
use async_trait::async_trait; use async_trait::async_trait;
use automation_macro::{LuaDeviceConfig, impl_device}; use automation_macro::{LuaDevice, LuaDeviceConfig};
use serde::Serialize; use mlua::LuaSerdeExt;
use serde::{Deserialize, Serialize};
use serde_repr::*; use serde_repr::*;
use tracing::{error, trace, warn}; use tracing::{error, trace, warn};
use crate::device::{Device, LuaDeviceCreate}; use crate::device::{Device, LuaDeviceCreate};
use crate::event::{self, Event, EventChannel, OnNotification, OnPresence}; use crate::event::{self, EventChannel};
use crate::lua::traits::AddAdditionalMethods;
#[derive(Debug, Serialize_repr, Clone, Copy)] #[derive(Debug, Serialize_repr, Deserialize, Clone, Copy)]
#[repr(u8)] #[repr(u8)]
#[serde(rename_all = "snake_case")]
pub enum Priority { pub enum Priority {
Min = 1, Min = 1,
Low, Low,
@@ -20,7 +23,7 @@ pub enum Priority {
Max, Max,
} }
#[derive(Debug, Serialize, Clone)] #[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "snake_case", tag = "action")] #[serde(rename_all = "snake_case", tag = "action")]
pub enum ActionType { pub enum ActionType {
Broadcast { Broadcast {
@@ -31,7 +34,7 @@ pub enum ActionType {
// Http // Http
} }
#[derive(Debug, Serialize, Clone)] #[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Action { pub struct Action {
#[serde(flatten)] #[serde(flatten)]
pub action: ActionType, pub action: ActionType,
@@ -39,24 +42,24 @@ pub struct Action {
pub clear: Option<bool>, pub clear: Option<bool>,
} }
#[derive(Serialize)] #[derive(Serialize, Deserialize)]
struct NotificationFinal { struct NotificationFinal {
topic: String, topic: String,
#[serde(flatten)] #[serde(flatten)]
inner: Notification, inner: Notification,
} }
#[derive(Debug, Serialize, Clone)] #[derive(Debug, Serialize, Clone, Deserialize)]
pub struct Notification { pub struct Notification {
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
title: Option<String>, title: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
message: Option<String>, message: Option<String>,
#[serde(skip_serializing_if = "Vec::is_empty")] #[serde(skip_serializing_if = "Vec::is_empty", default = "Default::default")]
tags: Vec<String>, tags: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
priority: Option<Priority>, priority: Option<Priority>,
#[serde(skip_serializing_if = "Vec::is_empty")] #[serde(skip_serializing_if = "Vec::is_empty", default = "Default::default")]
actions: Vec<Action>, actions: Vec<Action>,
} }
@@ -119,11 +122,11 @@ pub struct Config {
pub tx: event::Sender, pub tx: event::Sender,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone, LuaDevice)]
#[traits(crate::lua::traits::AddAdditionalMethods)]
pub struct Ntfy { pub struct Ntfy {
config: Config, config: Config,
} }
impl_device!(Ntfy);
#[async_trait] #[async_trait]
impl LuaDeviceCreate for Ntfy { impl LuaDeviceCreate for Ntfy {
@@ -164,45 +167,20 @@ impl Ntfy {
} }
} }
#[async_trait] impl AddAdditionalMethods for Ntfy {
impl OnPresence for Ntfy { fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M)
async fn on_presence(&self, presence: bool) { where
// Setup extras for the broadcast Self: Sized + 'static,
let extras = HashMap::from([
("cmd".into(), "presence".into()),
("state".into(), if presence { "0" } else { "1" }.into()),
]);
// Create broadcast action
let action = Action {
action: ActionType::Broadcast { extras },
label: if presence { "Set away" } else { "Set home" }.into(),
clear: Some(true),
};
// Create the notification
let notification = Notification::new()
.set_title("Presence")
.set_message(if presence { "Home" } else { "Away" })
.add_tag("house")
.add_action(action)
.set_priority(Priority::Low);
if self
.config
.tx
.send(Event::Ntfy(notification))
.await
.is_err()
{ {
warn!("There are no receivers on the event channel"); methods.add_async_method(
} "send_notification",
} |lua, this, notification: mlua::Value| async move {
} let notification: Notification = lua.from_value(notification)?;
#[async_trait] this.send(notification).await;
impl OnNotification for Ntfy {
async fn on_notification(&self, notification: Notification) { Ok(())
self.send(notification).await; },
);
} }
} }

View File

@@ -2,11 +2,12 @@ use std::collections::HashMap;
use std::sync::Arc; use std::sync::Arc;
use async_trait::async_trait; use async_trait::async_trait;
use automation_macro::{LuaDeviceConfig, impl_device}; use automation_macro::{LuaDevice, LuaDeviceConfig};
use rumqttc::Publish; use rumqttc::Publish;
use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard}; use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use tracing::{debug, trace, warn}; use tracing::{debug, trace, warn};
use crate::action_callback::ActionCallback;
use crate::config::MqttDeviceConfig; use crate::config::MqttDeviceConfig;
use crate::device::{Device, LuaDeviceCreate}; use crate::device::{Device, LuaDeviceCreate};
use crate::event::{self, Event, EventChannel, OnMqtt}; use crate::event::{self, Event, EventChannel, OnMqtt};
@@ -19,6 +20,10 @@ pub struct Config {
pub mqtt: MqttDeviceConfig, pub mqtt: MqttDeviceConfig,
#[device_config(from_lua, rename("event_channel"), with(|ec: EventChannel| ec.get_tx()))] #[device_config(from_lua, rename("event_channel"), with(|ec: EventChannel| ec.get_tx()))]
pub tx: event::Sender, pub tx: event::Sender,
#[device_config(from_lua, default)]
pub callback: ActionCallback<Presence, bool>,
#[device_config(from_lua)] #[device_config(from_lua)]
pub client: WrappedAsyncClient, pub client: WrappedAsyncClient,
} }
@@ -31,12 +36,11 @@ pub struct State {
current_overall_presence: bool, current_overall_presence: bool,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone, LuaDevice)]
pub struct Presence { pub struct Presence {
config: Config, config: Config,
state: Arc<RwLock<State>>, state: Arc<RwLock<State>>,
} }
impl_device!(Presence);
impl Presence { impl Presence {
async fn state(&self) -> RwLockReadGuard<'_, State> { async fn state(&self) -> RwLockReadGuard<'_, State> {
@@ -124,6 +128,8 @@ impl OnMqtt for Presence {
{ {
warn!("There are no receivers on the event channel"); warn!("There are no receivers on the event channel");
} }
self.config.callback.call(self, &overall_presence).await;
} }
} }
} }

View File

@@ -1,53 +1,52 @@
use proc_macro::TokenStream; use proc_macro2::TokenStream;
use quote::quote; use quote::{ToTokens, quote};
use syn::parse::Parse; use syn::parse::Parse;
use syn::punctuated::Punctuated; use syn::punctuated::Punctuated;
use syn::{Path, Token, parse_macro_input}; use syn::{AngleBracketedGenericArguments, Attribute, DeriveInput, Ident, Path, Token};
struct ImplDevice { #[derive(Debug, Default)]
ty: Path, struct Impl {
impls: Option<Punctuated<Path, Token![,]>>, generics: Option<AngleBracketedGenericArguments>,
traits: Vec<Path>,
} }
impl Parse for ImplDevice { impl Parse for Impl {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> { fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
let ty = input.parse()?; let generics = if input.peek(Token![<]) {
let impls = if input.peek(Token![->]) { let generics = input.parse()?;
input.parse::<Token![->]>()?; input.parse::<Token![:]>()?;
Some(input.parse_terminated(Path::parse, Token![,])?)
Some(generics)
} else { } else {
None None
}; };
Ok(ImplDevice { ty, impls }) let traits: Punctuated<_, _> = input.parse_terminated(Path::parse, Token![,])?;
let traits = traits.into_iter().collect();
Ok(Impl { generics, traits })
} }
} }
pub fn impl_device_macro(input: proc_macro::TokenStream) -> TokenStream { impl Impl {
let ImplDevice { ty, impls } = parse_macro_input!(input as ImplDevice); fn generate(&self, name: &Ident) -> TokenStream {
let generics = &self.generics;
let impls: Vec<_> = impls // If an identifier is specified, assume it is placed in ::automation_lib::lua::traits,
.iter() // otherwise use the provided path
.flatten() let traits = self.traits.iter().map(|t| {
.map(|i| { if let Some(ident) = t.get_ident() {
let ident = i quote! {::automation_lib::lua::traits::#ident }
.segments } else {
.last() t.to_token_stream()
.expect("There should be at least one segment") }
.ident });
.clone();
quote! { quote! {
::automation_lib::lua::traits::#ident::add_methods(methods); impl mlua::UserData for #name #generics {
}
})
.collect();
quote! {
impl mlua::UserData for #ty {
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) { fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) {
methods.add_async_function("new", |_lua, config| async { methods.add_async_function("new", |_lua, config| async {
let device: #ty = LuaDeviceCreate::create(config) let device: Self = LuaDeviceCreate::create(config)
.await .await
.map_err(mlua::ExternalError::into_lua_err)?; .map_err(mlua::ExternalError::into_lua_err)?;
@@ -62,9 +61,28 @@ pub fn impl_device_macro(input: proc_macro::TokenStream) -> TokenStream {
methods.add_async_method("get_id", |_lua, this, _: ()| async move { Ok(this.get_id()) }); methods.add_async_method("get_id", |_lua, this, _: ()| async move { Ok(this.get_id()) });
#( #(
#impls #traits::add_methods(methods);
)* )*
} }
} }
}.into() }
}
}
pub fn impl_device_macro(ast: &DeriveInput) -> TokenStream {
let name = &ast.ident;
let impls: TokenStream = ast
.attrs
.iter()
.filter(|attr| attr.path().is_ident("traits"))
.flat_map(Attribute::parse_args::<Impl>)
.map(|im| im.generate(name))
.collect();
if impls.is_empty() {
Impl::default().generate(name)
} else {
impls
}
} }

View File

@@ -14,7 +14,9 @@ pub fn lua_device_config_derive(input: proc_macro::TokenStream) -> proc_macro::T
impl_lua_device_config_macro(&ast).into() impl_lua_device_config_macro(&ast).into()
} }
#[proc_macro] #[proc_macro_derive(LuaDevice, attributes(traits))]
pub fn impl_device(input: proc_macro::TokenStream) -> proc_macro::TokenStream { pub fn impl_device(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
impl_device_macro(input) let ast = parse_macro_input!(input as DeriveInput);
impl_device_macro(&ast).into()
} }

View File

@@ -29,15 +29,35 @@ local mqtt_client = automation.new_mqtt_client({
tls = host == "zeus" or host == "hephaestus", tls = host == "zeus" or host == "hephaestus",
}) })
automation.device_manager:add(Ntfy.new({ local ntfy = Ntfy.new({
topic = automation.util.get_env("NTFY_TOPIC"), topic = automation.util.get_env("NTFY_TOPIC"),
event_channel = automation.device_manager:event_channel(), event_channel = automation.device_manager:event_channel(),
})) })
automation.device_manager:add(ntfy)
automation.device_manager:add(Presence.new({ automation.device_manager:add(Presence.new({
topic = mqtt_automation("presence/+/#"), topic = mqtt_automation("presence/+/#"),
client = mqtt_client, client = mqtt_client,
event_channel = automation.device_manager:event_channel(), event_channel = automation.device_manager:event_channel(),
callback = function(_, presence)
ntfy:send_notification({
title = "Presence",
message = presence and "Home" or "Away",
tags = { "house" },
priority = "low",
actions = {
{
action = "broadcast",
extras = {
cmd = "presence",
state = presence and "0" or "1",
},
label = presence and "Set away" or "Set home",
clear = true,
},
},
})
end,
})) }))
automation.device_manager:add(DebugBridge.new({ automation.device_manager:add(DebugBridge.new({
@@ -232,6 +252,14 @@ automation.device_manager:add(Washer.new({
client = mqtt_client, client = mqtt_client,
threshold = 1, threshold = 1,
event_channel = automation.device_manager:event_channel(), event_channel = automation.device_manager:event_channel(),
done_callback = function()
ntfy:send_notification({
title = "Laundy is done",
message = "Don't forget to hang it!",
tags = { "womans_clothes" },
priority = "high",
})
end,
})) }))
automation.device_manager:add(OutletOnOff.new({ automation.device_manager:add(OutletOnOff.new({