WIP
All checks were successful
Build and deploy / build (push) Successful in 10m49s
Build and deploy / Deploy container (push) Has been skipped

This commit is contained in:
2025-10-18 04:54:45 +02:00
parent 92a0bff8c4
commit b2f3564ab4
8 changed files with 693 additions and 607 deletions

1
Cargo.lock generated
View File

@@ -91,6 +91,7 @@ dependencies = [
"automation_macro",
"axum",
"config",
"futures",
"git-version",
"google_home",
"inventory",

View File

@@ -74,6 +74,7 @@ config = { version = "0.15.15", default-features = false, features = [
"async",
"toml",
] }
futures = { workspace = true }
git-version = "0.3.9"
google_home = { workspace = true }
lua_typed = { workspace = true }

View File

@@ -27,7 +27,7 @@ impl mlua::FromLua for Box<dyn Device> {
fn from_lua(value: mlua::Value, _lua: &mlua::Lua) -> mlua::Result<Self> {
match value {
mlua::Value::UserData(ud) => {
let ud = if ud.is::<Box<dyn Device>>() {
let ud = if ud.is::<Self>() {
ud
} else {
ud.call_method::<_>("__box", ())?

View File

@@ -21,28 +21,133 @@ local function mqtt_automation(topic)
return "automation/" .. topic
end
local mqtt_client = require("automation:mqtt").new(device_manager, {
host = ((host == "zeus" or host == "hephaestus") and "olympus.lan.huizinga.dev") or "mosquitto",
port = 8883,
client_name = "automation-" .. host,
username = "mqtt",
password = secrets.mqtt_password,
tls = host == "zeus" or host == "hephaestus",
})
--- @return fun(self: OnOffInterface, state: {state: boolean, power: number})
local function auto_off()
local timeout = utils.Timeout.new()
local devs = {}
function devs:add(device)
table.insert(self, device)
return function(self, state)
if state.state and state.power < 100 then
timeout:start(3, function()
self:set_on(false)
end)
else
timeout:cancel()
end
end
end
local ntfy_topic = secrets.ntfy_topic
if ntfy_topic == nil then
error("Ntfy topic is not specified")
--- @param duration number
--- @return fun(self: OnOffInterface, state: {state: boolean})
local function off_timeout(duration)
local timeout = utils.Timeout.new()
return function(self, state)
if state.state then
timeout:start(duration, function()
self:set_on(false)
end)
else
timeout:cancel()
end
end
end
local hallway_light_automation = {
timeout = utils.Timeout.new(),
forced = false,
trash = nil,
door = nil,
}
---@return fun(_, on: boolean)
function hallway_light_automation:switch_callback()
return function(_, on)
self.timeout:cancel()
self.group.set_on(on)
self.forced = on
end
end
---@return fun(_, open: boolean)
function hallway_light_automation:door_callback()
return function(_, open)
if open then
self.timeout:cancel()
self.group.set_on(true)
elseif not self.forced then
self.timeout:start(debug and 10 or 2 * 60, function()
if self.trash == nil or self.trash:open_percent() == 0 then
self.group.set_on(false)
end
end)
end
end
end
---@return fun(_, open: boolean)
function hallway_light_automation:trash_callback()
return function(_, open)
if open then
self.group.set_on(true)
else
if
not self.timeout:is_waiting()
and (self.door == nil or self.door:open_percent() == 0)
and not self.forced
then
self.group.set_on(false)
end
end
end
end
---@return fun(_, state: { on: boolean })
function hallway_light_automation:light_callback()
return function(_, state)
if
state.on
and (self.trash == nil or self.trash:open_percent()) == 0
and (self.door == nil or self.door:open_percent() == 0)
then
-- If the door and trash are not open, that means the light got turned on manually
self.timeout:cancel()
self.forced = true
elseif not state.on then
-- The light is never forced when it is off
self.forced = false
end
end
end
--- @class OnPresence
--- @field [integer] fun(presence: boolean)
local on_presence = {}
--- @param f fun(presence: boolean)
function on_presence:add(f)
self[#self + 1] = f
end
--- @param device OnOffInterface
local function turn_off_when_away(device)
on_presence:add(function(presence)
if not presence then
device:set_on(false)
end
end)
end
--- @class WindowSensor
--- @field [integer] OpenCloseInterface
local window_sensors = {}
--- @param sensor OpenCloseInterface
function window_sensors:add(sensor)
self[#self + 1] = sensor
end
--- @class OnLight
--- @field [integer] fun(light: boolean)
local on_light = {}
--- @param f fun(light: boolean)
function on_light:add(f)
self[#self + 1] = f
end
local ntfy = devices.Ntfy.new({
topic = ntfy_topic,
})
devs:add(ntfy)
--- @type {[string]: number}
local low_battery = {}
@@ -57,47 +162,15 @@ local function check_battery(device, battery)
low_battery[id] = nil
end
end
local function notify_low_battery()
-- Don't send notifications if there are now devices with low battery
if next(low_battery) == nil then
print("No devices with low battery")
return
end
local lines = {}
for name, battery in pairs(low_battery) do
table.insert(lines, name .. ": " .. tostring(battery) .. "%")
local ntfy_topic = secrets.ntfy_topic
if ntfy_topic == nil then
error("Ntfy topic is not specified")
end
local message = table.concat(lines, "\n")
ntfy:send_notification({
title = "Low battery",
message = message,
tags = { "battery" },
priority = "default",
local ntfy = devices.Ntfy.new({
topic = ntfy_topic,
})
end
--- @class OnPresence
--- @field [integer] fun(presence: boolean)
local on_presence = {}
--- @param f fun(presence: boolean)
function on_presence:add(f)
self[#self + 1] = f
end
local presence_system = devices.Presence.new({
topic = mqtt_automation("presence/+/#"),
client = mqtt_client,
callback = function(_, presence)
for _, f in ipairs(on_presence) do
if type(f) == "function" then
f(presence)
end
end
end,
})
devs:add(presence_system)
on_presence:add(function(presence)
ntfy:send_notification({
title = "Presence",
@@ -117,20 +190,7 @@ on_presence:add(function(presence)
},
})
end)
on_presence:add(function(presence)
mqtt_client:send_message(mqtt_automation("debug") .. "/presence", {
state = presence,
updated = utils.get_epoch(),
})
end)
--- @class WindowSensor
--- @field [integer] OpenCloseInterface
local window_sensors = {}
--- @param sensor OpenCloseInterface
function window_sensors:add(sensor)
self[#self + 1] = sensor
end
on_presence:add(function(presence)
if not presence then
local open = {}
@@ -155,49 +215,32 @@ on_presence:add(function(presence)
end
end)
--- @param device OnOffInterface
local function turn_off_when_away(device)
on_presence:add(function(presence)
if not presence then
device:set_on(false)
end
end)
local function notify_low_battery()
-- Don't send notifications if there are now devices with low battery
if next(low_battery) == nil then
print("No devices with low battery")
return
end
--- @class OnLight
--- @field [integer] fun(light: boolean)
local on_light = {}
--- @param f fun(light: boolean)
function on_light:add(f)
self[#self + 1] = f
local lines = {}
for name, battery in pairs(low_battery) do
table.insert(lines, name .. ": " .. tostring(battery) .. "%")
end
devs:add(devices.LightSensor.new({
identifier = "living_light_sensor",
topic = mqtt_z2m("living/light"),
client = mqtt_client,
min = 22000,
max = 23500,
callback = function(_, light)
for _, f in ipairs(on_light) do
if type(f) == "function" then
f(light)
end
end
end,
}))
on_light:add(function(light)
mqtt_client:send_message(mqtt_automation("debug") .. "/darkness", {
state = not light,
updated = utils.get_epoch(),
local message = table.concat(lines, "\n")
ntfy:send_notification({
title = "Low battery",
message = message,
tags = { "battery" },
priority = "default",
})
end)
end
local hue_ip = "10.0.0.102"
local hue_token = secrets.hue_token
if hue_token == nil then
error("Hue token is not specified")
end
local hue_bridge = devices.HueBridge.new({
identifier = "hue_bridge",
ip = hue_ip,
@@ -207,7 +250,6 @@ local hue_bridge = devices.HueBridge.new({
darkness = 43,
},
})
devs:add(hue_bridge)
on_light:add(function(light)
hue_bridge:set_flag("darkness", not light)
end)
@@ -222,7 +264,6 @@ local kitchen_lights = devices.HueGroup.new({
group_id = 7,
scene_id = "7MJLG27RzeRAEVJ",
})
devs:add(kitchen_lights)
local living_lights = devices.HueGroup.new({
identifier = "living_lights",
ip = hue_ip,
@@ -230,7 +271,6 @@ local living_lights = devices.HueGroup.new({
group_id = 1,
scene_id = "SNZw7jUhQ3cXSjkj",
})
devs:add(living_lights)
local living_lights_relax = devices.HueGroup.new({
identifier = "living_lights",
ip = hue_ip,
@@ -238,7 +278,88 @@ local living_lights_relax = devices.HueGroup.new({
group_id = 1,
scene_id = "eRJ3fvGHCcb6yNw",
})
devs:add(living_lights_relax)
local hallway_top_light = devices.HueGroup.new({
identifier = "hallway_top_light",
ip = hue_ip,
login = hue_token,
group_id = 83,
scene_id = "QeufkFDICEHWeKJ7",
})
local hallway_bottom_lights = devices.HueGroup.new({
identifier = "hallway_bottom_lights",
ip = hue_ip,
login = hue_token,
group_id = 81,
scene_id = "3qWKxGVadXFFG4o",
})
local bedroom_lights = devices.HueGroup.new({
identifier = "bedroom_lights",
ip = hue_ip,
login = hue_token,
group_id = 3,
scene_id = "PvRs-lGD4VRytL9",
})
local bedroom_lights_relax = devices.HueGroup.new({
identifier = "bedroom_lights",
ip = hue_ip,
login = hue_token,
group_id = 3,
scene_id = "60tfTyR168v2csz",
})
local bedroom_air_filter = devices.AirFilter.new({
name = "Air Filter",
room = "Bedroom",
url = "http://10.0.0.103",
})
local function create_devs(mqtt_client)
on_presence:add(function(presence)
mqtt_client:send_message(mqtt_automation("debug") .. "/presence", {
state = presence,
updated = utils.get_epoch(),
})
end)
on_light:add(function(light)
mqtt_client:send_message(mqtt_automation("debug") .. "/darkness", {
state = not light,
updated = utils.get_epoch(),
})
end)
local devs = {}
function devs:add(device)
table.insert(self, device)
end
local presence_system = devices.Presence.new({
topic = mqtt_automation("presence/+/#"),
client = mqtt_client,
callback = function(_, presence)
for _, f in ipairs(on_presence) do
if type(f) == "function" then
f(presence)
end
end
end,
})
devs:add(presence_system)
devs:add(devices.LightSensor.new({
identifier = "living_light_sensor",
topic = mqtt_z2m("living/light"),
client = mqtt_client,
min = 22000,
max = 23500,
callback = function(_, light)
for _, f in ipairs(on_light) do
if type(f) == "function" then
f(light)
end
end
end,
}))
devs:add(devices.HueSwitch.new({
name = "Switch",
@@ -309,21 +430,6 @@ devs:add(devices.IkeaRemote.new({
battery_callback = check_battery,
}))
--- @return fun(self: OnOffInterface, state: {state: boolean, power: number})
local function kettle_timeout()
local timeout = utils.Timeout.new()
return function(self, state)
if state.state and state.power < 100 then
timeout:start(3, function()
self:set_on(false)
end)
else
timeout:cancel()
end
end
end
--- @type OutletPower
local kettle = devices.OutletPower.new({
outlet_type = "Kettle",
@@ -331,7 +437,7 @@ local kettle = devices.OutletPower.new({
room = "Kitchen",
topic = mqtt_z2m("kitchen/kettle"),
client = mqtt_client,
callback = kettle_timeout(),
callback = auto_off(),
})
turn_off_when_away(kettle)
devs:add(kettle)
@@ -361,22 +467,6 @@ devs:add(devices.IkeaRemote.new({
battery_callback = check_battery,
}))
--- @param duration number
--- @return fun(self: OnOffInterface, state: {state: boolean})
local function off_timeout(duration)
local timeout = utils.Timeout.new()
return function(self, state)
if state.state then
timeout:start(duration, function()
self:set_on(false)
end)
else
timeout:cancel()
end
end
end
local bathroom_light = devices.LightOnOff.new({
name = "Light",
room = "Bathroom",
@@ -451,13 +541,6 @@ devs:add(devices.IkeaRemote.new({
battery_callback = check_battery,
}))
local hallway_top_light = devices.HueGroup.new({
identifier = "hallway_top_light",
ip = hue_ip,
login = hue_token,
group_id = 83,
scene_id = "QeufkFDICEHWeKJ7",
})
devs:add(devices.HueSwitch.new({
name = "SwitchBottom",
room = "Hallway",
@@ -479,70 +562,6 @@ devs:add(devices.HueSwitch.new({
battery_callback = check_battery,
}))
local hallway_light_automation = {
timeout = utils.Timeout.new(),
forced = false,
trash = nil,
door = nil,
}
---@return fun(_, on: boolean)
function hallway_light_automation:switch_callback()
return function(_, on)
self.timeout:cancel()
self.group.set_on(on)
self.forced = on
end
end
---@return fun(_, open: boolean)
function hallway_light_automation:door_callback()
return function(_, open)
if open then
self.timeout:cancel()
self.group.set_on(true)
elseif not self.forced then
self.timeout:start(debug and 10 or 2 * 60, function()
if self.trash == nil or self.trash:open_percent() == 0 then
self.group.set_on(false)
end
end)
end
end
end
---@return fun(_, open: boolean)
function hallway_light_automation:trash_callback()
return function(_, open)
if open then
self.group.set_on(true)
else
if
not self.timeout:is_waiting()
and (self.door == nil or self.door:open_percent() == 0)
and not self.forced
then
self.group.set_on(false)
end
end
end
end
---@return fun(_, state: { on: boolean })
function hallway_light_automation:light_callback()
return function(_, state)
if
state.on
and (self.trash == nil or self.trash:open_percent()) == 0
and (self.door == nil or self.door:open_percent() == 0)
then
-- If the door and trash are not open, that means the light got turned on manually
self.timeout:cancel()
self.forced = true
elseif not state.on then
-- The light is never forced when it is off
self.forced = false
end
end
end
local hallway_storage = devices.LightBrightness.new({
name = "Storage",
room = "Hallway",
@@ -553,15 +572,7 @@ local hallway_storage = devices.LightBrightness.new({
turn_off_when_away(hallway_storage)
devs:add(hallway_storage)
local hallway_bottom_lights = devices.HueGroup.new({
identifier = "hallway_bottom_lights",
ip = hue_ip,
login = hue_token,
group_id = 81,
scene_id = "3qWKxGVadXFFG4o",
})
devs:add(hallway_bottom_lights)
-- TODO: Rework
hallway_light_automation.group = {
set_on = function(on)
if on then
@@ -573,6 +584,15 @@ hallway_light_automation.group = {
end,
}
devs:add(devices.IkeaRemote.new({
name = "Remote",
room = "Hallway",
client = mqtt_client,
topic = mqtt_z2m("hallway/remote"),
callback = hallway_light_automation:switch_callback(),
battery_callback = check_battery,
}))
---@param duration number
---@return fun(_, open: boolean)
local function presence(duration)
@@ -595,15 +615,6 @@ local function presence(duration)
end
end
end
devs:add(devices.IkeaRemote.new({
name = "Remote",
room = "Hallway",
client = mqtt_client,
topic = mqtt_z2m("hallway/remote"),
callback = hallway_light_automation:switch_callback(),
battery_callback = check_battery,
}))
local hallway_frontdoor = devices.ContactSensor.new({
name = "Frontdoor",
room = "Hallway",
@@ -641,30 +652,6 @@ local guest_light = devices.LightOnOff.new({
turn_off_when_away(guest_light)
devs:add(guest_light)
local bedroom_air_filter = devices.AirFilter.new({
name = "Air Filter",
room = "Bedroom",
url = "http://10.0.0.103",
})
devs:add(bedroom_air_filter)
local bedroom_lights = devices.HueGroup.new({
identifier = "bedroom_lights",
ip = hue_ip,
login = hue_token,
group_id = 3,
scene_id = "PvRs-lGD4VRytL9",
})
devs:add(bedroom_lights)
local bedroom_lights_relax = devices.HueGroup.new({
identifier = "bedroom_lights",
ip = hue_ip,
login = hue_token,
group_id = 3,
scene_id = "60tfTyR168v2csz",
})
devs:add(bedroom_lights_relax)
devs:add(devices.HueSwitch.new({
name = "Switch",
room = "Bedroom",
@@ -742,12 +729,39 @@ devs:add(devices.ContactSensor.new({
battery_callback = check_battery,
}))
return devs
end
-- TODO: Pass the mqtt config to the output config, instead of constructing the client here
local mqtt_client = require("automation:mqtt").new(device_manager, {
host = ((host == "zeus" or host == "hephaestus") and "olympus.lan.huizinga.dev") or "mosquitto",
port = 8883,
client_name = "automation-" .. host,
username = "mqtt",
password = secrets.mqtt_password,
tls = host == "zeus" or host == "hephaestus",
})
---@type Config
return {
fulfillment = {
openid_url = "https://login.huizinga.dev/api/oidc",
},
devices = devs,
mqtt = mqtt_client,
devices = {
-- TODO: Fix definition
create_devs,
ntfy,
hue_bridge,
kitchen_lights,
living_lights,
living_lights_relax,
hallway_top_light,
hallway_bottom_lights,
bedroom_lights,
bedroom_lights_relax,
bedroom_air_filter,
},
schedule = {
["0 0 19 * * *"] = function()
bedroom_air_filter:set_on(true)

View File

@@ -9,6 +9,7 @@ local FulfillmentConfig
---@class Config
---@field fulfillment FulfillmentConfig
---@field devices DeviceInterface[]?
---@field schedule table<string, function>?
---@field devices Devices?
---@field mqtt AsyncClient
---@field schedule table<string, fun() | fun()[]>?
local Config

View File

@@ -11,6 +11,7 @@ use automation::secret::EnvironmentSecretFile;
use automation::version::VERSION;
use automation::web::{ApiError, User};
use automation_lib::device_manager::DeviceManager;
use automation_lib::mqtt::WrappedAsyncClient;
use axum::extract::{FromRef, State};
use axum::http::StatusCode;
use axum::routing::post;
@@ -139,7 +140,7 @@ async fn app() -> anyhow::Result<()> {
let entrypoint = Path::new(&setup.entrypoint);
let config: Config = lua.load(entrypoint).eval_async().await?;
for device in config.devices {
for device in config.devices.get(config.mqtt).await? {
device_manager.add(device).await;
}

View File

@@ -1,10 +1,15 @@
use std::collections::HashMap;
use std::net::{Ipv4Addr, SocketAddr};
use automation_lib::action_callback::ActionCallback;
use automation_lib::device::Device;
use automation_lib::mqtt::WrappedAsyncClient;
use automation_macro::LuaDeviceConfig;
use futures::future::try_join_all;
use lua_typed::Typed;
use mlua::{FromLua, LuaSerdeExt};
use serde::Deserialize;
use tracing::warn;
#[derive(Debug, Deserialize)]
pub struct Setup {
@@ -31,15 +36,77 @@ pub struct FulfillmentConfig {
pub port: u16,
}
#[derive(Debug, Typed, Default)]
pub struct Devices {
devices: Vec<Box<dyn Device>>,
fs: Vec<mlua::Function>,
}
impl Devices {
pub async fn get(mut self, client: WrappedAsyncClient) -> mlua::Result<Vec<Box<dyn Device>>> {
let devices = try_join_all(
self.fs
.iter()
.map(async |f| f.call_async::<Vec<Box<dyn Device>>>(client.clone()).await),
)
.await?
.into_iter()
.flatten();
self.devices.extend(devices);
Ok(self.devices)
}
}
fn extract_devices(
value: mlua::Value,
lua: &mlua::Lua,
) -> mlua::Result<(Vec<Box<dyn Device>>, Vec<mlua::Function>)> {
let mut devices = Vec::new();
let mut fs = Vec::new();
if let Ok(device) = Box::<dyn Device>::from_lua(value.clone(), lua) {
devices.push(device);
warn!("Converted to device");
} else {
match value {
mlua::Value::Function(f) => fs.push(f),
mlua::Value::Table(table) => {
for pair in table.pairs::<mlua::Value, mlua::Value>() {
let (_, value) = pair?;
let (a, b) = extract_devices(value, lua)?;
devices.extend(a);
fs.extend(b);
}
}
_ => Err(mlua::Error::RuntimeError("Unexpected type".into()))?,
}
}
Ok((devices, fs))
}
impl mlua::FromLua for Devices {
fn from_lua(value: mlua::Value, lua: &mlua::Lua) -> mlua::Result<Self> {
let (devices, fs) = extract_devices(value, lua)?;
Ok(Devices { devices, fs })
}
}
#[derive(Debug, LuaDeviceConfig, Typed)]
pub struct Config {
pub fulfillment: FulfillmentConfig,
#[device_config(from_lua, default)]
#[typed(default)]
pub devices: Vec<Box<dyn Device>>,
pub devices: Devices,
#[device_config(from_lua)]
pub mqtt: WrappedAsyncClient,
#[device_config(from_lua, default)]
#[typed(default)]
pub schedule: HashMap<String, mlua::Function>,
pub schedule: HashMap<String, ActionCallback<()>>,
}
impl From<FulfillmentConfig> for SocketAddr {

View File

@@ -1,10 +1,11 @@
use std::collections::HashMap;
use std::pin::Pin;
use automation_lib::action_callback::ActionCallback;
use tokio_cron_scheduler::{Job, JobScheduler, JobSchedulerError};
pub async fn start_scheduler(
schedule: HashMap<String, mlua::Function>,
schedule: HashMap<String, ActionCallback<()>>,
) -> Result<(), JobSchedulerError> {
let scheduler = JobScheduler::new().await?;
@@ -14,7 +15,7 @@ pub async fn start_scheduler(
let f = f.clone();
Box::pin(async move {
f.call_async::<()>(()).await.unwrap();
f.call(()).await;
})
}
};