Compare commits

...

7 Commits

Author SHA1 Message Date
3af618e40f Removed old darkness system
All checks were successful
Build and deploy / build (push) Successful in 8m56s
Build and deploy / Deploy container (push) Successful in 38s
2025-08-31 05:41:49 +02:00
aa730c9738 Moved darkness debug mqtt message to lua 2025-08-31 05:41:49 +02:00
c362952f7c Feature: Get current ms since unix epoch in lua 2025-08-31 05:41:49 +02:00
dd379e4077 Feature: Send mqtt messages from lua 2025-08-31 05:41:48 +02:00
549d821e3a Moved hue bridge on darkness to lua 2025-08-31 05:41:46 +02:00
4980f4888e Removed unused event code 2025-08-31 05:01:56 +02:00
eb36d41f17 Move ntfy and presence to automation_devices 2025-08-31 04:57:31 +02:00
19 changed files with 101 additions and 137 deletions

4
Cargo.lock generated
View File

@@ -131,6 +131,7 @@ dependencies = [
"rumqttc",
"serde",
"serde_json",
"serde_repr",
"thiserror 2.0.16",
"tokio",
"tracing",
@@ -143,18 +144,15 @@ version = "0.1.0"
dependencies = [
"async-trait",
"automation_cast",
"automation_macro",
"bytes",
"dyn-clone",
"futures",
"google_home",
"indexmap",
"mlua",
"reqwest",
"rumqttc",
"serde",
"serde_json",
"serde_repr",
"thiserror 2.0.16",
"tokio",
"tokio-cron-scheduler",

View File

@@ -12,6 +12,7 @@ async-trait = { workspace = true }
dyn-clone = { workspace = true }
rumqttc = { workspace = true }
tokio = { workspace = true }
serde_repr = { workspace = true }
tracing = { workspace = true }
serde_json = { workspace = true }
serde = { workspace = true }

View File

@@ -9,7 +9,6 @@ use automation_lib::error::DeviceConfigError;
use automation_lib::event::{OnMqtt, OnPresence};
use automation_lib::messages::{ContactMessage, PresenceMessage};
use automation_lib::mqtt::WrappedAsyncClient;
use automation_lib::presence::DEFAULT_PRESENCE;
use automation_macro::{LuaDevice, LuaDeviceConfig};
use google_home::device;
use google_home::errors::{DeviceError, ErrorCode};
@@ -20,6 +19,8 @@ use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use tokio::task::JoinHandle;
use tracing::{debug, error, trace, warn};
use crate::presence::DEFAULT_PRESENCE;
#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Copy)]
pub enum SensorType {
Door,

View File

@@ -3,8 +3,8 @@ use std::convert::Infallible;
use async_trait::async_trait;
use automation_lib::config::MqttDeviceConfig;
use automation_lib::device::{Device, LuaDeviceCreate};
use automation_lib::event::{OnDarkness, OnPresence};
use automation_lib::messages::{DarknessMessage, PresenceMessage};
use automation_lib::event::OnPresence;
use automation_lib::messages::PresenceMessage;
use automation_lib::mqtt::WrappedAsyncClient;
use automation_macro::{LuaDevice, LuaDeviceConfig};
use tracing::{trace, warn};
@@ -63,27 +63,3 @@ impl OnPresence for DebugBridge {
.ok();
}
}
#[async_trait]
impl OnDarkness for DebugBridge {
async fn on_darkness(&self, dark: bool) {
let message = DarknessMessage::new(dark);
let topic = format!("{}/darkness", self.config.mqtt.topic);
self.config
.client
.publish(
topic,
rumqttc::QoS::AtLeastOnce,
true,
serde_json::to_string(&message).unwrap(),
)
.await
.map_err(|err| {
warn!(
"Failed to update presence on {}/presence: {err}",
self.config.mqtt.topic
)
})
.ok();
}
}

View File

@@ -3,12 +3,15 @@ use std::net::SocketAddr;
use async_trait::async_trait;
use automation_lib::device::{Device, LuaDeviceCreate};
use automation_lib::event::{OnDarkness, OnPresence};
use automation_lib::event::OnPresence;
use automation_lib::lua::traits::AddAdditionalMethods;
use automation_macro::{LuaDevice, LuaDeviceConfig};
use mlua::LuaSerdeExt;
use serde::{Deserialize, Serialize};
use tracing::{error, trace, warn};
#[derive(Debug)]
#[derive(Debug, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Flag {
Presence,
Darkness,
@@ -30,6 +33,7 @@ pub struct Config {
}
#[derive(Debug, Clone, LuaDevice)]
#[traits(AddAdditionalMethods)]
pub struct HueBridge {
config: Config,
}
@@ -89,6 +93,24 @@ impl Device for HueBridge {
}
}
impl AddAdditionalMethods for HueBridge {
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M)
where
Self: Sized + 'static,
{
methods.add_async_method(
"set_flag",
|lua, this, (flag, value): (mlua::Value, bool)| async move {
let flag: Flag = lua.from_value(flag)?;
this.set_flag(flag, value).await;
Ok(())
},
);
}
}
#[async_trait]
impl OnPresence for HueBridge {
async fn on_presence(&self, presence: bool) {
@@ -96,11 +118,3 @@ impl OnPresence for HueBridge {
self.set_flag(Flag::Presence, presence).await;
}
}
#[async_trait]
impl OnDarkness for HueBridge {
async fn on_darkness(&self, dark: bool) {
trace!("Bridging darkness to hue");
self.set_flag(Flag::Darkness, dark).await;
}
}

View File

@@ -7,6 +7,8 @@ mod hue_switch;
mod ikea_remote;
mod kasa_outlet;
mod light_sensor;
mod ntfy;
mod presence;
mod wake_on_lan;
mod washer;
mod zigbee;
@@ -24,6 +26,8 @@ pub use self::hue_switch::HueSwitch;
pub use self::ikea_remote::IkeaRemote;
pub use self::kasa_outlet::KasaOutlet;
pub use self::light_sensor::LightSensor;
pub use self::ntfy::*;
pub use self::presence::Presence;
pub use self::wake_on_lan::WakeOnLAN;
pub use self::washer::Washer;
@@ -35,11 +39,6 @@ macro_rules! register_device {
}
pub fn register_with_lua(lua: &mlua::Lua) -> mlua::Result<()> {
register_device!(lua, LightOnOff);
register_device!(lua, LightBrightness);
register_device!(lua, LightColorTemperature);
register_device!(lua, OutletOnOff);
register_device!(lua, OutletPower);
register_device!(lua, AirFilter);
register_device!(lua, ContactSensor);
register_device!(lua, DebugBridge);
@@ -48,7 +47,14 @@ pub fn register_with_lua(lua: &mlua::Lua) -> mlua::Result<()> {
register_device!(lua, HueSwitch);
register_device!(lua, IkeaRemote);
register_device!(lua, KasaOutlet);
register_device!(lua, LightBrightness);
register_device!(lua, LightColorTemperature);
register_device!(lua, LightOnOff);
register_device!(lua, LightSensor);
register_device!(lua, Ntfy);
register_device!(lua, OutletOnOff);
register_device!(lua, OutletPower);
register_device!(lua, Presence);
register_device!(lua, WakeOnLAN);
register_device!(lua, Washer);

View File

@@ -1,9 +1,10 @@
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::BrightnessMessage;
use automation_lib::mqtt::WrappedAsyncClient;
use automation_macro::{LuaDevice, LuaDeviceConfig};
@@ -20,6 +21,10 @@ pub struct Config {
pub max: isize,
#[device_config(rename("event_channel"), from_lua, with(|ec: EventChannel| ec.get_tx()))]
pub tx: event::Sender,
#[device_config(from_lua, default)]
pub callback: ActionCallback<LightSensor, bool>,
#[device_config(from_lua)]
pub client: WrappedAsyncClient,
}
@@ -88,6 +93,7 @@ impl OnMqtt for LightSensor {
}
};
// TODO: Move this logic to lua at some point
debug!("Illuminance: {illuminance}");
let is_dark = if illuminance <= self.config.min {
trace!("It is dark");
@@ -108,9 +114,10 @@ impl OnMqtt for LightSensor {
debug!("Dark state has changed: {is_dark}");
self.state_mut().await.is_dark = is_dark;
if self.config.tx.send(Event::Darkness(is_dark)).await.is_err() {
warn!("There are no receivers on the event channel");
}
self.config
.callback
.call(self, &!self.state().await.is_dark)
.await;
}
}
}

View File

@@ -2,16 +2,14 @@ use std::collections::HashMap;
use std::convert::Infallible;
use async_trait::async_trait;
use automation_lib::device::{Device, LuaDeviceCreate};
use automation_lib::lua::traits::AddAdditionalMethods;
use automation_macro::{LuaDevice, LuaDeviceConfig};
use mlua::LuaSerdeExt;
use serde::{Deserialize, Serialize};
use serde_repr::*;
use tracing::{error, trace, warn};
use crate::device::{Device, LuaDeviceCreate};
use crate::event::{self, EventChannel};
use crate::lua::traits::AddAdditionalMethods;
#[derive(Debug, Serialize_repr, Deserialize, Clone, Copy)]
#[repr(u8)]
#[serde(rename_all = "snake_case")]
@@ -118,12 +116,10 @@ pub struct Config {
#[device_config(default("https://ntfy.sh".into()))]
pub url: String,
pub topic: String,
#[device_config(rename("event_channel"), from_lua, with(|ec: EventChannel| ec.get_tx()))]
pub tx: event::Sender,
}
#[derive(Debug, Clone, LuaDevice)]
#[traits(crate::lua::traits::AddAdditionalMethods)]
#[traits(AddAdditionalMethods)]
pub struct Ntfy {
config: Config,
}

View File

@@ -2,18 +2,17 @@ use std::collections::HashMap;
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::messages::PresenceMessage;
use automation_lib::mqtt::WrappedAsyncClient;
use automation_macro::{LuaDevice, LuaDeviceConfig};
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};
use crate::messages::PresenceMessage;
use crate::mqtt::WrappedAsyncClient;
#[derive(Debug, Clone, LuaDeviceConfig)]
pub struct Config {
#[device_config(flatten)]

View File

@@ -4,7 +4,7 @@ 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, EventChannel, OnMqtt};
use automation_lib::event::OnMqtt;
use automation_lib::messages::PowerMessage;
use automation_lib::mqtt::WrappedAsyncClient;
use automation_macro::{LuaDevice, LuaDeviceConfig};
@@ -19,8 +19,6 @@ pub struct Config {
pub mqtt: MqttDeviceConfig,
// Power in Watt
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, ()>,

View File

@@ -4,15 +4,12 @@ version = "0.1.0"
edition = "2024"
[dependencies]
automation_macro = { workspace = true }
automation_cast = { workspace = true }
google_home = { workspace = true }
rumqttc = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true }
reqwest = { workspace = true }
serde_repr = { workspace = true }
tracing = { workspace = true }
bytes = { workspace = true }
async-trait = { workspace = true }

View File

@@ -5,7 +5,7 @@ use dyn_clone::DynClone;
use google_home::traits::OnOff;
use mlua::ObjectLike;
use crate::event::{OnDarkness, OnMqtt, OnPresence};
use crate::event::{OnMqtt, OnPresence};
#[async_trait::async_trait]
pub trait LuaDeviceCreate {
@@ -25,7 +25,6 @@ pub trait Device:
+ Cast<dyn google_home::Device>
+ Cast<dyn OnMqtt>
+ Cast<dyn OnPresence>
+ Cast<dyn OnDarkness>
+ 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, OnPresence};
use crate::event::{Event, EventChannel, OnMqtt, OnPresence};
pub type DeviceMap = HashMap<String, Box<dyn Device>>;
@@ -94,19 +94,6 @@ impl DeviceManager {
join_all(iter).await;
}
Event::Darkness(dark) => {
let devices = self.devices.read().await;
let iter = devices.iter().map(|(id, device)| async move {
let device: Option<&dyn OnDarkness> = device.cast();
if let Some(device) = device {
trace!(id, "Handling");
device.on_darkness(dark).await;
trace!(id, "Done");
}
});
join_all(iter).await;
}
Event::Presence(presence) => {
let devices = self.devices.read().await;
let iter = devices.iter().map(|(id, device)| async move {

View File

@@ -6,7 +6,6 @@ use tokio::sync::mpsc;
#[derive(Debug, Clone)]
pub enum Event {
MqttMessage(Publish),
Darkness(bool),
Presence(bool),
}
@@ -40,8 +39,3 @@ pub trait OnMqtt: Sync + Send {
pub trait OnPresence: Sync + Send {
async fn on_presence(&self, presence: bool);
}
#[async_trait]
pub trait OnDarkness: Sync + Send {
async fn on_darkness(&self, dark: bool);
}

View File

@@ -10,6 +10,4 @@ pub mod helpers;
pub mod lua;
pub mod messages;
pub mod mqtt;
pub mod ntfy;
pub mod presence;
pub mod schedule;

View File

@@ -162,40 +162,6 @@ impl TryFrom<Publish> for ContactMessage {
}
}
// Message used to report the current darkness state
#[derive(Debug, Deserialize, Serialize)]
pub struct DarknessMessage {
state: bool,
updated: Option<u128>,
}
impl DarknessMessage {
pub fn new(state: bool) -> Self {
Self {
state,
updated: Some(
SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("Time is after UNIX EPOCH")
.as_millis(),
),
}
}
pub fn is_dark(&self) -> bool {
self.state
}
}
impl TryFrom<Publish> for DarknessMessage {
type Error = ParseError;
fn try_from(message: Publish) -> Result<Self, Self::Error> {
serde_json::from_slice(&message.payload)
.or(Err(ParseError::InvalidPayload(message.payload.clone())))
}
}
// Message used to report the power draw a smart plug
#[derive(Debug, Deserialize)]
pub struct PowerMessage {

View File

@@ -23,7 +23,25 @@ impl DerefMut for WrappedAsyncClient {
}
}
impl mlua::UserData for WrappedAsyncClient {}
impl mlua::UserData for WrappedAsyncClient {
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) {
methods.add_async_method(
"send_message",
|_lua, this, (topic, message): (String, mlua::Value)| async move {
let message = serde_json::to_string(&message).unwrap();
debug!("message = {message}");
this.0
.publish(topic, rumqttc::QoS::AtLeastOnce, true, message)
.await
.unwrap();
Ok(())
},
);
}
}
pub fn start(mut eventloop: EventLoop, event_channel: &EventChannel) {
let tx = event_channel.get_tx();

View File

@@ -31,7 +31,6 @@ local mqtt_client = automation.new_mqtt_client({
local ntfy = Ntfy.new({
topic = automation.util.get_env("NTFY_TOPIC"),
event_channel = automation.device_manager:event_channel(),
})
automation.device_manager:add(ntfy)
@@ -69,7 +68,7 @@ automation.device_manager:add(DebugBridge.new({
local hue_ip = "10.0.0.102"
local hue_token = automation.util.get_env("HUE_TOKEN")
automation.device_manager:add(HueBridge.new({
local hue_bridge = HueBridge.new({
identifier = "hue_bridge",
ip = hue_ip,
login = hue_token,
@@ -77,7 +76,8 @@ automation.device_manager:add(HueBridge.new({
presence = 41,
darkness = 43,
},
}))
})
automation.device_manager:add(hue_bridge)
local kitchen_lights = HueGroup.new({
identifier = "kitchen_lights",
@@ -127,6 +127,13 @@ automation.device_manager:add(LightSensor.new({
min = 22000,
max = 23500,
event_channel = automation.device_manager:event_channel(),
callback = function(_, light)
hue_bridge:set_flag("darkness", not light)
mqtt_client:send_message(mqtt_automation("debug") .. "/darkness", {
state = not light,
updated = automation.util.get_epoch(),
})
end,
}))
automation.device_manager:add(WakeOnLAN.new({
@@ -251,7 +258,6 @@ automation.device_manager:add(Washer.new({
topic = mqtt_z2m("bathroom/washer"),
client = mqtt_client,
threshold = 1,
event_channel = automation.device_manager:event_channel(),
done_callback = function()
ntfy:send_notification({
title = "Laundy is done",

View File

@@ -3,14 +3,13 @@ mod web;
use std::net::SocketAddr;
use std::path::Path;
use std::process;
use std::time::{SystemTime, UNIX_EPOCH};
use anyhow::anyhow;
use automation_lib::config::{FulfillmentConfig, MqttConfig};
use automation_lib::device_manager::DeviceManager;
use automation_lib::helpers;
use automation_lib::mqtt::{self, WrappedAsyncClient};
use automation_lib::ntfy::Ntfy;
use automation_lib::presence::Presence;
use axum::extract::{FromRef, State};
use axum::http::StatusCode;
use axum::routing::post;
@@ -112,15 +111,19 @@ async fn app() -> anyhow::Result<()> {
.map_err(mlua::ExternalError::into_lua_err)
})?;
util.set("get_hostname", get_hostname)?;
let get_epoch = lua.create_function(|_lua, ()| {
Ok(SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("Time is after UNIX EPOCH")
.as_millis())
})?;
util.set("get_epoch", get_epoch)?;
automation.set("util", util)?;
lua.globals().set("automation", automation)?;
automation_devices::register_with_lua(&lua)?;
helpers::register_with_lua(&lua)?;
lua.globals().set("Ntfy", lua.create_proxy::<Ntfy>()?)?;
lua.globals()
.set("Presence", lua.create_proxy::<Presence>()?)?;
// TODO: Make this not hardcoded
let config_filename = std::env::var("AUTOMATION_CONFIG").unwrap_or("./config.lua".into());