Compare commits

..

10 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
d2b01123b8 Made the impl_device macro more explicit about the implemented traits
This also converts impl_device into a procedural macro and get rid of a
lot of "magic" that was happening.
2025-08-31 00:38:58 +02:00
c5262dcf35 Update to rust 1.89 and edition 2024 2025-08-31 00:38:58 +02:00
01e88eeb3b Use new and improved rust workflow and Dockerfile 2025-08-31 00:38:58 +02:00
d6ab38f690 Improve pre-commit hooks 2025-08-31 00:38:58 +02:00
9f3b927cb6 Update dependencies and remove unused dependencies 2025-08-31 00:38:56 +02:00
10 changed files with 79 additions and 97 deletions

View File

@@ -58,7 +58,6 @@ serde_repr = "0.1.10"
syn = { version = "2.0.60", features = ["extra-traits", "full"] }
thiserror = "2.0.5"
tokio-cron-scheduler = "0.13.0"
tokio-util = { version = "0.7.11", features = ["full"] }
tracing-subscriber = "0.3.16"
uuid = "1.8.0"
wakey = "0.3.0"

View File

@@ -62,7 +62,6 @@ struct State {
}
#[derive(Debug, Clone, LuaDevice)]
#[traits(OpenClose)]
pub struct ContactSensor {
config: Config,
state: Arc<RwLock<State>>,

View File

@@ -1,16 +1,16 @@
use std::sync::Arc;
use async_trait::async_trait;
use automation_lib::action_callback::ActionCallback;
use automation_lib::config::MqttDeviceConfig;
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::mqtt::WrappedAsyncClient;
use automation_lib::ntfy::{Notification, Priority};
use automation_macro::{LuaDevice, LuaDeviceConfig};
use rumqttc::Publish;
use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use tracing::{debug, error, trace, warn};
use tracing::{debug, error, trace};
#[derive(Debug, Clone, LuaDeviceConfig)]
pub struct Config {
@@ -21,6 +21,10 @@ pub struct Config {
pub threshold: f32,
#[device_config(rename("event_channel"), from_lua, with(|ec: EventChannel| ec.get_tx()))]
pub tx: event::Sender,
#[device_config(from_lua, default)]
pub done_callback: ActionCallback<Washer, ()>,
#[device_config(from_lua)]
pub client: WrappedAsyncClient,
}
@@ -96,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 {
// The washer is done running
debug!(
@@ -108,21 +110,8 @@ impl OnMqtt for Washer {
);
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
.config
.tx
.send(Event::Ntfy(notification))
.await
.is_err()
{
warn!("There are no receivers on the event channel");
}
self.config.done_callback.call(self, &()).await;
} else if power < self.config.threshold {
// Prevent false positives
self.state_mut().await.running = 0;

View File

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

View File

@@ -9,7 +9,7 @@ use tokio_cron_scheduler::{Job, JobScheduler};
use tracing::{debug, instrument, trace};
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>>;
@@ -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;
}
}

View File

@@ -3,14 +3,11 @@ use mlua::FromLua;
use rumqttc::Publish;
use tokio::sync::mpsc;
use crate::ntfy::Notification;
#[derive(Debug, Clone)]
pub enum Event {
MqttMessage(Publish),
Darkness(bool),
Presence(bool),
Ntfy(Notification),
}
pub type Sender = mpsc::Sender<Event>;
@@ -48,8 +45,3 @@ pub trait OnPresence: Sync + Send {
pub trait OnDarkness: Sync + Send {
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 {}
pub trait AddAdditionalMethods {
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M)
where
Self: Sized + 'static;
}

View File

@@ -3,15 +3,18 @@ use std::convert::Infallible;
use async_trait::async_trait;
use automation_macro::{LuaDevice, LuaDeviceConfig};
use serde::Serialize;
use mlua::LuaSerdeExt;
use serde::{Deserialize, Serialize};
use serde_repr::*;
use tracing::{error, trace, warn};
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)]
#[serde(rename_all = "snake_case")]
pub enum Priority {
Min = 1,
Low,
@@ -20,7 +23,7 @@ pub enum Priority {
Max,
}
#[derive(Debug, Serialize, Clone)]
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "snake_case", tag = "action")]
pub enum ActionType {
Broadcast {
@@ -31,7 +34,7 @@ pub enum ActionType {
// Http
}
#[derive(Debug, Serialize, Clone)]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Action {
#[serde(flatten)]
pub action: ActionType,
@@ -39,24 +42,24 @@ pub struct Action {
pub clear: Option<bool>,
}
#[derive(Serialize)]
#[derive(Serialize, Deserialize)]
struct NotificationFinal {
topic: String,
#[serde(flatten)]
inner: Notification,
}
#[derive(Debug, Serialize, Clone)]
#[derive(Debug, Serialize, Clone, Deserialize)]
pub struct Notification {
#[serde(skip_serializing_if = "Option::is_none")]
title: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
message: Option<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
#[serde(skip_serializing_if = "Vec::is_empty", default = "Default::default")]
tags: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
priority: Option<Priority>,
#[serde(skip_serializing_if = "Vec::is_empty")]
#[serde(skip_serializing_if = "Vec::is_empty", default = "Default::default")]
actions: Vec<Action>,
}
@@ -120,6 +123,7 @@ pub struct Config {
}
#[derive(Debug, Clone, LuaDevice)]
#[traits(crate::lua::traits::AddAdditionalMethods)]
pub struct Ntfy {
config: Config,
}
@@ -163,45 +167,20 @@ impl Ntfy {
}
}
#[async_trait]
impl OnPresence for Ntfy {
async fn on_presence(&self, presence: bool) {
// Setup extras for the broadcast
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()
impl AddAdditionalMethods for Ntfy {
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M)
where
Self: Sized + 'static,
{
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]
impl OnNotification for Ntfy {
async fn on_notification(&self, notification: Notification) {
self.send(notification).await;
this.send(notification).await;
Ok(())
},
);
}
}

View File

@@ -7,6 +7,7 @@ use rumqttc::Publish;
use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use tracing::{debug, trace, warn};
use crate::action_callback::ActionCallback;
use crate::config::MqttDeviceConfig;
use crate::device::{Device, LuaDeviceCreate};
use crate::event::{self, Event, EventChannel, OnMqtt};
@@ -19,6 +20,10 @@ pub struct Config {
pub mqtt: MqttDeviceConfig,
#[device_config(from_lua, rename("event_channel"), with(|ec: EventChannel| ec.get_tx()))]
pub tx: event::Sender,
#[device_config(from_lua, default)]
pub callback: ActionCallback<Presence, bool>,
#[device_config(from_lua)]
pub client: WrappedAsyncClient,
}
@@ -123,6 +128,8 @@ impl OnMqtt for Presence {
{
warn!("There are no receivers on the event channel");
}
self.config.callback.call(self, &overall_presence).await;
}
}
}

View File

@@ -29,15 +29,35 @@ local mqtt_client = automation.new_mqtt_client({
tls = host == "zeus" or host == "hephaestus",
})
automation.device_manager:add(Ntfy.new({
local ntfy = Ntfy.new({
topic = automation.util.get_env("NTFY_TOPIC"),
event_channel = automation.device_manager:event_channel(),
}))
})
automation.device_manager:add(ntfy)
automation.device_manager:add(Presence.new({
topic = mqtt_automation("presence/+/#"),
client = mqtt_client,
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({
@@ -232,6 +252,14 @@ automation.device_manager:add(Washer.new({
client = mqtt_client,
threshold = 1,
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({