Compare commits

13 Commits

Author SHA1 Message Date
a0c5189ada feat(config)!: Changed default config location
All checks were successful
Build and deploy / build (push) Successful in 10m26s
Build and deploy / Deploy container (push) Has been skipped
2025-10-19 05:43:43 +02:00
3676aafa23 feat(config)!: Remove device manager lua code
With the recent changes the device manager no longer needs to be
available in lua.
2025-10-19 05:43:43 +02:00
95ec3f28ff feat(config)!: Config now returns the mqtt config instead of the client
Instead the client is now created on the rust side based on the config.
Devices that require the mqtt client will now instead need to be
constructor using a function. This function receives the mqtt client.
2025-10-19 05:43:43 +02:00
303541929c chore: Restructured config to not rely on mqtt client being available
All checks were successful
Build and deploy / build (push) Successful in 10m27s
Build and deploy / Deploy container (push) Has been skipped
In preparation of changes to the mqtt client the config is rewritten to
use a device creation function for devices that need the mqtt client.

This also fixes a but where hallway_top_light was not actually added to
the device manager.
2025-10-19 04:31:25 +02:00
a26a93550b feat(config)!: In config devices can now also be a (table of) function(s)
Some checks failed
Build and deploy / Deploy container (push) Blocked by required conditions
Build and deploy / build (push) Has been cancelled
This function receives the mqtt client as an argument. In the future
this will be the only way to create devices that require the mqtt client.
2025-10-19 04:18:26 +02:00
88a7acd55d feat: Improved device conversion error message
All checks were successful
Build and deploy / build (push) Successful in 10m37s
Build and deploy / Deploy container (push) Has been skipped
2025-10-19 03:40:16 +02:00
3b7579878b feat: Use ActionCallback for schedule
This has two advantages:
- Each schedule entry can take either a single function or table of
  functions.
- We get a better type definition.
2025-10-19 03:40:16 +02:00
46c32c3605 refactor(config)!: Move scheduler out of device_manager
Due to changes made in mlua the new scheduler is much simpler. It also
had no real business being part of the device manager, so it has now been
moved to be part of the returned config.
2025-10-19 03:40:16 +02:00
d1e7988117 feat: Receive devices through config return 2025-10-19 03:40:15 +02:00
93b0a526b1 feat: Ensure consistent ordering device definitions 2025-10-19 03:40:15 +02:00
7bb5e65c1c feat: Generate definitions for config 2025-10-19 03:40:15 +02:00
a0ed373971 refactor: Move definition writing into separate function
Some checks failed
Build and deploy / Deploy container (push) Blocked by required conditions
Build and deploy / build (push) Has been cancelled
2025-10-17 03:12:40 +02:00
5e13dff2b5 chore: Move main.rs to bin/automation.rs 2025-10-17 03:08:37 +02:00
31 changed files with 915 additions and 1444 deletions

View File

@@ -9,10 +9,10 @@ on:
jobs:
build:
uses: dreaded_x/workflows/.gitea/workflows/docker-kubernetes.yaml@ef78704b98c72e4a6b8340f9bff7b085a7bdd95c
uses: dreaded_x/workflows/.gitea/workflows/rust-kubernetes.yaml@22ee0c1788a8d2157db87d6a6f8dbe520fe48592
secrets: inherit
with:
push_manifests: false
upload_manifests: false
deploy:
name: Deploy container
@@ -37,7 +37,7 @@ jobs:
-e AUTOMATION__SECRETS__MQTT_PASSWORD=${{ secrets.MQTT_PASSWORD }} \
-e AUTOMATION__SECRETS__HUE_TOKEN=${{ secrets.HUE_TOKEN }} \
-e AUTOMATION__SECRETS__NTFY_TOPIC=${{ secrets.NTFY_TOPIC }} \
$(echo ${{ toJSON(needs.build.outputs.images) }} | jq .automation -r)
git.huizinga.dev/dreaded_x/automation_rs@${{ needs.build.outputs.digest }}
docker network connect web automation_rs

11
Cargo.lock generated
View File

@@ -555,7 +555,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "778e2ac28f6c47af28e4907f13ffd1e1ddbd400980a9abd7c8df189bf578a5ad"
dependencies = [
"libc",
"windows-sys 0.52.0",
"windows-sys 0.59.0",
]
[[package]]
@@ -1163,16 +1163,17 @@ dependencies = [
[[package]]
name = "lua_typed"
version = "0.1.0"
source = "git+https://git.huizinga.dev/Dreaded_X/lua_typed#3d29c9dd143737c8bffe4bacae8e701de3c6ee10"
source = "git+https://git.huizinga.dev/Dreaded_X/lua_typed#f6a684291432aae2ef7109712882e7e3ed758d08"
dependencies = [
"eui48",
"lua_typed_macro",
"mlua",
]
[[package]]
name = "lua_typed_macro"
version = "0.1.0"
source = "git+https://git.huizinga.dev/Dreaded_X/lua_typed#3d29c9dd143737c8bffe4bacae8e701de3c6ee10"
source = "git+https://git.huizinga.dev/Dreaded_X/lua_typed#f6a684291432aae2ef7109712882e7e3ed758d08"
dependencies = [
"convert_case",
"itertools",
@@ -1567,7 +1568,7 @@ dependencies = [
"once_cell",
"socket2",
"tracing",
"windows-sys 0.52.0",
"windows-sys 0.59.0",
]
[[package]]
@@ -1744,7 +1745,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys",
"windows-sys 0.52.0",
"windows-sys 0.59.0",
]
[[package]]

View File

@@ -3,8 +3,6 @@ ENV CARGO_REGISTRIES_CRATES_IO_PROTOCOL=sparse
RUN cargo install cargo-chef --locked --version 0.1.71 && \
cargo install cargo-auditable --locked --version 0.6.6
WORKDIR /app
COPY ./rust-toolchain.toml .
RUN rustup toolchain install
FROM base AS planner
COPY . .
@@ -23,7 +21,5 @@ RUN cargo auditable build --release
FROM gcr.io/distroless/cc-debian12:nonroot AS runtime
COPY --from=builder /app/target/release/automation /app/automation
ENV AUTOMATION__ENTRYPOINT=/app/config/config.lua
ENV LUA_PATH="/app/?.lua;;"
COPY ./config /app/config
CMD [ "/app/automation" ]

View File

@@ -1,47 +0,0 @@
local ntfy = require("config.ntfy")
--- @class BatteryModule: Module
local module = {}
--- @type {[string]: number}
local low_battery = {}
--- @param device DeviceInterface
--- @param battery number
function module.callback(device, battery)
local id = device:get_id()
if battery < 15 then
print("Device '" .. id .. "' has low battery: " .. tostring(battery))
low_battery[id] = battery
else
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) .. "%")
end
local message = table.concat(lines, "\n")
ntfy.send_notification({
title = "Low battery",
message = message,
tags = { "battery" },
priority = "default",
})
end
--- @type Schedule
module.schedule = {
["0 0 21 */1 * *"] = notify_low_battery,
}
return module

View File

@@ -1,32 +1,774 @@
local devices = require("automation:devices")
local utils = require("automation:utils")
local secrets = require("automation:secrets")
local debug = require("automation:variables").debug and true or false
print(_VERSION)
local host = utils.get_hostname()
print("Lua " .. _VERSION .. " running on " .. utils.get_hostname())
print("Running @" .. host)
---@type Config
return {
fulfillment = {
openid_url = "https://login.huizinga.dev/api/oidc",
--- @param topic string
--- @return string
local function mqtt_z2m(topic)
return "zigbee2mqtt/" .. topic
end
--- @param topic string
--- @return string
local function mqtt_automation(topic)
return "automation/" .. topic
end
--- @return fun(self: OnOffInterface, state: {state: boolean, power: number})
local function auto_off()
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
--- @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
--- @type {[string]: number}
local low_battery = {}
--- @param device DeviceInterface
--- @param battery number
local function check_battery(device, battery)
local id = device:get_id()
if battery < 15 then
print("Device '" .. id .. "' has low battery: " .. tostring(battery))
low_battery[id] = battery
else
low_battery[id] = nil
end
end
local ntfy_topic = secrets.ntfy_topic
if ntfy_topic == nil then
error("Ntfy topic is not specified")
end
local ntfy = devices.Ntfy.new({
topic = ntfy_topic,
})
on_presence:add(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",
},
mqtt = {
label = presence and "Set away" or "Set home",
clear = true,
},
},
})
end)
on_presence:add(function(presence)
if not presence then
local open = {}
for _, sensor in ipairs(window_sensors) do
if sensor:open_percent() > 0 then
local id = sensor:get_id()
print("Open window detected: " .. id)
table.insert(open, id)
end
end
if #open > 0 then
local message = table.concat(open, "\n")
ntfy:send_notification({
title = "Windows are open",
message = message,
tags = { "window" },
priority = "high",
})
end
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) .. "%")
end
local message = table.concat(lines, "\n")
ntfy:send_notification({
title = "Low battery",
message = message,
tags = { "battery" },
priority = "default",
})
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,
login = hue_token,
flags = {
presence = 41,
darkness = 43,
},
})
on_light:add(function(light)
hue_bridge:set_flag("darkness", not light)
end)
on_presence:add(function(presence)
hue_bridge:set_flag("presence", presence)
end)
local kitchen_lights = devices.HueGroup.new({
identifier = "kitchen_lights",
ip = hue_ip,
login = hue_token,
group_id = 7,
scene_id = "7MJLG27RzeRAEVJ",
})
local living_lights = devices.HueGroup.new({
identifier = "living_lights",
ip = hue_ip,
login = hue_token,
group_id = 1,
scene_id = "SNZw7jUhQ3cXSjkj",
})
local living_lights_relax = devices.HueGroup.new({
identifier = "living_lights",
ip = hue_ip,
login = hue_token,
group_id = 1,
scene_id = "eRJ3fvGHCcb6yNw",
})
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",
room = "Living",
client = mqtt_client,
topic = mqtt_z2m("living/switch"),
left_callback = function()
kitchen_lights:set_on(not kitchen_lights:on())
end,
right_callback = function()
living_lights:set_on(not living_lights:on())
end,
right_hold_callback = function()
living_lights_relax:set_on(true)
end,
battery_callback = check_battery,
}))
devs:add(devices.WakeOnLAN.new({
name = "Zeus",
room = "Living Room",
topic = mqtt_automation("appliance/living_room/zeus"),
client = mqtt_client,
mac_address = "30:9c:23:60:9c:13",
broadcast_ip = "10.0.3.255",
}))
local living_mixer = devices.OutletOnOff.new({
name = "Mixer",
room = "Living Room",
topic = mqtt_z2m("living/mixer"),
client = mqtt_client,
})
turn_off_when_away(living_mixer)
devs:add(living_mixer)
local living_speakers = devices.OutletOnOff.new({
name = "Speakers",
room = "Living Room",
topic = mqtt_z2m("living/speakers"),
client = mqtt_client,
})
turn_off_when_away(living_speakers)
devs:add(living_speakers)
devs:add(devices.IkeaRemote.new({
name = "Remote",
room = "Living Room",
client = mqtt_client,
topic = mqtt_z2m("living/remote"),
single_button = true,
callback = function(_, on)
if on then
if living_mixer:on() then
living_mixer:set_on(false)
living_speakers:set_on(false)
else
living_mixer:set_on(true)
living_speakers:set_on(true)
end
else
if not living_mixer:on() then
living_mixer:set_on(true)
else
living_speakers:set_on(not living_speakers:on())
end
end
end,
battery_callback = check_battery,
}))
--- @type OutletPower
local kettle = devices.OutletPower.new({
outlet_type = "Kettle",
name = "Kettle",
room = "Kitchen",
topic = mqtt_z2m("kitchen/kettle"),
client = mqtt_client,
callback = auto_off(),
})
turn_off_when_away(kettle)
devs:add(kettle)
--- @param on boolean
local function set_kettle(_, on)
kettle:set_on(on)
end
devs:add(devices.IkeaRemote.new({
name = "Remote",
room = "Bedroom",
client = mqtt_client,
topic = mqtt_z2m("bedroom/remote"),
single_button = true,
callback = set_kettle,
battery_callback = check_battery,
}))
devs:add(devices.IkeaRemote.new({
name = "Remote",
room = "Kitchen",
client = mqtt_client,
topic = mqtt_z2m("kitchen/remote"),
single_button = true,
callback = set_kettle,
battery_callback = check_battery,
}))
local bathroom_light = devices.LightOnOff.new({
name = "Light",
room = "Bathroom",
topic = mqtt_z2m("bathroom/light"),
client = mqtt_client,
callback = off_timeout(debug and 60 or 45 * 60),
})
devs:add(bathroom_light)
devs:add(devices.Washer.new({
identifier = "bathroom_washer",
topic = mqtt_z2m("bathroom/washer"),
client = mqtt_client,
threshold = 1,
done_callback = function()
ntfy:send_notification({
title = "Laundy is done",
message = "Don't forget to hang it!",
tags = { "womans_clothes" },
priority = "high",
})
end,
}))
devs:add(devices.OutletOnOff.new({
name = "Charger",
room = "Workbench",
topic = mqtt_z2m("workbench/charger"),
client = mqtt_client,
callback = off_timeout(debug and 5 or 20 * 3600),
}))
local workbench_outlet = devices.OutletOnOff.new({
name = "Outlet",
room = "Workbench",
topic = mqtt_z2m("workbench/outlet"),
client = mqtt_client,
})
turn_off_when_away(workbench_outlet)
devs:add(workbench_outlet)
local workbench_light = devices.LightColorTemperature.new({
name = "Light",
room = "Workbench",
topic = mqtt_z2m("workbench/light"),
client = mqtt_client,
})
turn_off_when_away(workbench_light)
devs:add(workbench_light)
local delay_color_temp = utils.Timeout.new()
devs:add(devices.IkeaRemote.new({
name = "Remote",
room = "Workbench",
client = mqtt_client,
topic = mqtt_z2m("workbench/remote"),
callback = function(_, on)
delay_color_temp:cancel()
if on then
workbench_light:set_brightness(82)
-- NOTE: This light does NOT support changing both the brightness and color
-- temperature at the same time, so we first change the brightness and once
-- that is complete we change the color temperature, as that is less likely
-- to have to actually change.
delay_color_temp:start(0.5, function()
workbench_light:set_color_temperature(3333)
end)
else
workbench_light:set_on(false)
end
end,
battery_callback = check_battery,
}))
devs:add(devices.HueSwitch.new({
name = "SwitchBottom",
room = "Hallway",
client = mqtt_client,
topic = mqtt_z2m("hallway/switchbottom"),
left_callback = function()
hallway_top_light:set_on(not hallway_top_light:on())
end,
battery_callback = check_battery,
}))
devs:add(devices.HueSwitch.new({
name = "SwitchTop",
room = "Hallway",
client = mqtt_client,
topic = mqtt_z2m("hallway/switchtop"),
left_callback = function()
hallway_top_light:set_on(not hallway_top_light:on())
end,
battery_callback = check_battery,
}))
local hallway_storage = devices.LightBrightness.new({
name = "Storage",
room = "Hallway",
topic = mqtt_z2m("hallway/storage"),
client = mqtt_client,
callback = hallway_light_automation:light_callback(),
})
turn_off_when_away(hallway_storage)
devs:add(hallway_storage)
-- TODO: Rework
hallway_light_automation.group = {
set_on = function(on)
if on then
hallway_storage:set_brightness(80)
else
hallway_storage:set_on(false)
end
hallway_bottom_lights:set_on(on)
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)
local timeout = utils.Timeout.new()
return function(_, open)
if open then
timeout:cancel()
if not presence_system:overall_presence() then
mqtt_client:send_message(mqtt_automation("presence/contact/frontdoor"), {
state = true,
updated = utils.get_epoch(),
})
end
else
timeout:start(duration, function()
mqtt_client:send_message(mqtt_automation("presence/contact/frontdoor"), nil)
end)
end
end
end
local hallway_frontdoor = devices.ContactSensor.new({
name = "Frontdoor",
room = "Hallway",
sensor_type = "Door",
topic = mqtt_z2m("hallway/frontdoor"),
client = mqtt_client,
callback = {
presence(debug and 10 or 15 * 60),
hallway_light_automation:door_callback(),
},
battery_callback = check_battery,
})
devs:add(hallway_frontdoor)
window_sensors:add(hallway_frontdoor)
hallway_light_automation.door = hallway_frontdoor
local hallway_trash = devices.ContactSensor.new({
name = "Trash",
room = "Hallway",
sensor_type = "Drawer",
topic = mqtt_z2m("hallway/trash"),
client = mqtt_client,
callback = hallway_light_automation:trash_callback(),
battery_callback = check_battery,
})
devs:add(hallway_trash)
hallway_light_automation.trash = hallway_trash
local guest_light = devices.LightOnOff.new({
name = "Light",
room = "Guest Room",
topic = mqtt_z2m("guest/light"),
client = mqtt_client,
})
turn_off_when_away(guest_light)
devs:add(guest_light)
devs:add(devices.HueSwitch.new({
name = "Switch",
room = "Bedroom",
client = mqtt_client,
topic = mqtt_z2m("bedroom/switch"),
left_callback = function()
bedroom_lights:set_on(not bedroom_lights:on())
end,
left_hold_callback = function()
bedroom_lights_relax:set_on(true)
end,
battery_callback = check_battery,
}))
local balcony = devices.ContactSensor.new({
name = "Balcony",
room = "Living Room",
sensor_type = "Door",
topic = mqtt_z2m("living/balcony"),
client = mqtt_client,
battery_callback = check_battery,
})
devs:add(balcony)
window_sensors:add(balcony)
local living_window = devices.ContactSensor.new({
name = "Window",
room = "Living Room",
topic = mqtt_z2m("living/window"),
client = mqtt_client,
battery_callback = check_battery,
})
devs:add(living_window)
window_sensors:add(living_window)
local bedroom_window = devices.ContactSensor.new({
name = "Window",
room = "Bedroom",
topic = mqtt_z2m("bedroom/window"),
client = mqtt_client,
battery_callback = check_battery,
})
devs:add(bedroom_window)
window_sensors:add(bedroom_window)
local guest_window = devices.ContactSensor.new({
name = "Window",
room = "Guest Room",
topic = mqtt_z2m("guest/window"),
client = mqtt_client,
battery_callback = check_battery,
})
devs:add(guest_window)
window_sensors:add(guest_window)
local storage_light = devices.LightBrightness.new({
name = "Light",
room = "Storage",
topic = mqtt_z2m("storage/light"),
client = mqtt_client,
})
turn_off_when_away(storage_light)
devs:add(storage_light)
devs:add(devices.ContactSensor.new({
name = "Door",
room = "Storage",
sensor_type = "Door",
topic = mqtt_z2m("storage/door"),
client = mqtt_client,
callback = function(_, open)
if open then
storage_light:set_brightness(100)
else
storage_light:set_on(false)
end
end,
battery_callback = check_battery,
}))
devs.add = nil
return devs
end
--- @type MqttConfig
local mqtt_config = {
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",
},
modules = {
require("config.battery"),
require("config.debug"),
require("config.hallway_automation"),
require("config.helper"),
require("config.hue_bridge"),
require("config.light"),
require("config.ntfy"),
require("config.presence"),
require("config.rooms"),
require("config.windows"),
mqtt = mqtt_config,
devices = {
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)
end,
["0 0 20 * * *"] = function()
bedroom_air_filter:set_on(false)
end,
["0 0 21 */1 * *"] = notify_low_battery,
},
}

View File

@@ -1,35 +0,0 @@
local helper = require("config.helper")
local light = require("config.light")
local presence = require("config.presence")
local utils = require("automation:utils")
local variables = require("automation:variables")
--- @class DebugModule: Module
local module = {}
if variables.debug == "true" then
module.debug_mode = true
elseif not variables.debug or variables.debug == "false" then
module.debug_mode = false
else
error("Variable debug has invalid value '" .. variables.debug .. "', expected 'true' or 'false'")
end
--- @type SetupFunction
function module.setup(mqtt_client)
presence.add_callback(function(p)
mqtt_client:send_message(helper.mqtt_automation("debug") .. "/presence", {
state = p,
updated = utils.get_epoch(),
})
end)
light.add_callback(function(l)
mqtt_client:send_message(helper.mqtt_automation("debug") .. "/darkness", {
state = not l,
updated = utils.get_epoch(),
})
end)
end
return module

View File

@@ -1,85 +0,0 @@
local debug = require("config.debug")
local utils = require("automation:utils")
--- @class HallwayAutomationModule: Module
local module = {}
local timeout = utils.Timeout.new()
local forced = false
--- @type OpenCloseInterface?
local trash = nil
--- @type OpenCloseInterface?
local door = nil
--- @type fun(on: boolean)[]
local callbacks = {}
--- @param on boolean
local function callback(on)
for _, f in ipairs(callbacks) do
f(on)
end
end
---@type fun(device: DeviceInterface, on: boolean)
function module.switch_callback(_, on)
timeout:cancel()
callback(on)
forced = on
end
---@type fun(device: DeviceInterface, open: boolean)
function module.door_callback(_, open)
if open then
timeout:cancel()
callback(true)
elseif not forced then
timeout:start(debug.debug_mode and 10 or 2 * 60, function()
if trash == nil or trash:open_percent() == 0 then
callback(false)
end
end)
end
end
---@type fun(device: DeviceInterface, open: boolean)
function module.trash_callback(_, open)
if open then
callback(true)
else
if not forced and not timeout:is_waiting() and (door == nil or door:open_percent() == 0) then
callback(false)
end
end
end
---@type fun(device: DeviceInterface, state: { state: boolean })
function module.light_callback(_, state)
print("LIGHT = " .. tostring(state.state))
if state.state and (trash == nil or trash:open_percent()) == 0 and (door == nil or door:open_percent() == 0) then
-- If the door and trash are not open, that means the light got turned on manually
timeout:cancel()
forced = true
elseif not state.state then
-- The light is never forced when it is off
forced = false
end
end
--- @param t OpenCloseInterface
function module.set_trash(t)
trash = t
end
--- @param d OpenCloseInterface
function module.set_door(d)
door = d
end
--- @param c fun(on: boolean)
function module.add_callback(c)
table.insert(callbacks, c)
end
return module

View File

@@ -1,49 +0,0 @@
local utils = require("automation:utils")
--- @class HelperModule: Module
local module = {}
--- @param topic string
--- @return string
function module.mqtt_z2m(topic)
return "zigbee2mqtt/" .. topic
end
--- @param topic string
--- @return string
function module.mqtt_automation(topic)
return "automation/" .. topic
end
--- @return fun(self: OnOffInterface, state: {state: boolean, power: number})
function module.auto_off()
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
--- @param duration number
--- @return fun(self: OnOffInterface, state: {state: boolean})
function module.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
return module

View File

@@ -1,41 +0,0 @@
local devices = require("automation:devices")
local light = require("config.light")
local presence = require("config.presence")
local secrets = require("automation:secrets")
--- @class HueBridgeModule: Module
local module = {}
module.ip = "10.0.0.102"
module.token = secrets.hue_token
if module.token == nil then
error("Hue token is not specified")
end
--- @type SetupFunction
function module.setup()
local bridge = devices.HueBridge.new({
identifier = "hue_bridge",
ip = module.ip,
login = module.token,
flags = {
presence = 41,
darkness = 43,
},
})
light.add_callback(function(l)
bridge:set_flag("darkness", not l)
end)
presence.add_callback(function(p)
bridge:set_flag("presence", p)
end)
return {
bridge,
}
end
return module

View File

@@ -1,44 +0,0 @@
local devices = require("automation:devices")
local helper = require("config.helper")
--- @class LightModule: Module
local module = {}
--- @class OnPresence
--- @field [integer] fun(light: boolean)
local callbacks = {}
--- @param callback fun(light: boolean)
function module.add_callback(callback)
table.insert(callbacks, callback)
end
--- @param _ DeviceInterface
--- @param light boolean
local function callback(_, light)
for _, f in ipairs(callbacks) do
f(light)
end
end
--- @type LightSensor?
module.device = nil
--- @type SetupFunction
function module.setup(mqtt_client)
module.device = devices.LightSensor.new({
identifier = "living_light_sensor",
topic = helper.mqtt_z2m("living/light"),
client = mqtt_client,
min = 22000,
max = 23500,
callback = callback,
})
--- @type Module
return {
module.device,
}
end
return module

View File

@@ -1,34 +0,0 @@
local devices = require("automation:devices")
local secrets = require("automation:secrets")
--- @class NtfyModule: Module
local module = {}
local ntfy_topic = secrets.ntfy_topic
if ntfy_topic == nil then
error("Ntfy topic is not specified")
end
--- @type Ntfy?
local ntfy = nil
--- @param notification Notification
function module.send_notification(notification)
if ntfy then
ntfy:send_notification(notification)
end
end
--- @type SetupFunction
function module.setup()
ntfy = devices.Ntfy.new({
topic = ntfy_topic,
})
--- @type Module
return {
ntfy,
}
end
return module

View File

@@ -1,80 +0,0 @@
local devices = require("automation:devices")
local helper = require("config.helper")
local ntfy = require("config.ntfy")
--- @class PresenceModule: Module
local module = {}
--- @class OnPresence
--- @field [integer] fun(presence: boolean)
local callbacks = {}
--- @param callback fun(presence: boolean)
function module.add_callback(callback)
table.insert(callbacks, callback)
end
--- @param device OnOffInterface
function module.turn_off_when_away(device)
module.add_callback(function(presence)
if not presence then
device:set_on(false)
end
end)
end
--- @param _ DeviceInterface
--- @param presence boolean
local function callback(_, presence)
for _, f in ipairs(callbacks) do
f(presence)
end
end
--- @type Presence?
local presence = nil
--- @type SetupFunction
function module.setup(mqtt_client)
presence = devices.Presence.new({
topic = helper.mqtt_automation("presence/+/#"),
client = mqtt_client,
callback = callback,
})
module.add_callback(function(p)
ntfy.send_notification({
title = "Presence",
message = p and "Home" or "Away",
tags = { "house" },
priority = "low",
actions = {
{
action = "broadcast",
extras = {
cmd = "presence",
state = p and "0" or "1",
},
label = p and "Set away" or "Set home",
clear = true,
},
},
})
end)
--- @type Module
return {
presence,
}
end
function module.overall_presence()
-- Default to no presence when the device has not been created yet
if not presence then
return false
end
return presence:overall_presence()
end
return module

View File

@@ -1,12 +0,0 @@
--- @type Module
return {
require("config.rooms.bathroom"),
require("config.rooms.bedroom"),
require("config.rooms.guest_bedroom"),
require("config.rooms.hallway_bottom"),
require("config.rooms.hallway_top"),
require("config.rooms.kitchen"),
require("config.rooms.living_room"),
require("config.rooms.storage"),
require("config.rooms.workbench"),
}

View File

@@ -1,40 +0,0 @@
local debug = require("config.debug")
local devices = require("automation:devices")
local helper = require("config.helper")
local ntfy = require("config.ntfy")
--- @type Module
local module = {}
function module.setup(mqtt_client)
local light = devices.LightOnOff.new({
name = "Light",
room = "Bathroom",
topic = helper.mqtt_z2m("bathroom/light"),
client = mqtt_client,
callback = helper.off_timeout(debug.debug_mode and 60 or 45 * 60),
})
local washer = devices.Washer.new({
identifier = "bathroom_washer",
topic = helper.mqtt_z2m("bathroom/washer"),
client = mqtt_client,
threshold = 1,
done_callback = function()
ntfy.send_notification({
title = "Laundy is done",
message = "Don't forget to hang it!",
tags = { "womans_clothes" },
priority = "high",
})
end,
})
--- @type Module
return {
light,
washer,
}
end
return module

View File

@@ -1,78 +0,0 @@
local battery = require("config.battery")
local devices = require("automation:devices")
local helper = require("config.helper")
local hue_bridge = require("config.hue_bridge")
local windows = require("config.windows")
--- @type Module
local module = {}
--- @type AirFilter?
local air_filter = nil
function module.setup(mqtt_client)
local lights = devices.HueGroup.new({
identifier = "bedroom_lights",
ip = hue_bridge.ip,
login = hue_bridge.token,
group_id = 3,
scene_id = "PvRs-lGD4VRytL9",
})
local lights_relax = devices.HueGroup.new({
identifier = "bedroom_lights_relax",
ip = hue_bridge.ip,
login = hue_bridge.token,
group_id = 3,
scene_id = "60tfTyR168v2csz",
})
air_filter = devices.AirFilter.new({
name = "Air Filter",
room = "Bedroom",
url = "http://10.0.0.103",
})
local switch = devices.HueSwitch.new({
name = "Switch",
room = "Bedroom",
client = mqtt_client,
topic = helper.mqtt_z2m("bedroom/switch"),
left_callback = function()
lights:set_on(not lights:on())
end,
left_hold_callback = function()
lights_relax:set_on(true)
end,
battery_callback = battery.callback,
})
local window = devices.ContactSensor.new({
name = "Window",
room = "Bedroom",
topic = helper.mqtt_z2m("bedroom/window"),
client = mqtt_client,
battery_callback = battery.callback,
})
windows.add(window)
--- @type Module
return {
devices = {
lights,
lights_relax,
air_filter,
switch,
window,
},
schedule = {
["0 0 19 * * *"] = function()
air_filter:set_on(true)
end,
["0 0 20 * * *"] = function()
air_filter:set_on(false)
end,
},
}
end
return module

View File

@@ -1,43 +0,0 @@
local battery = require("config.battery")
local devices = require("automation:devices")
local helper = require("config.helper")
local presence = require("config.presence")
local windows = require("config.windows")
--- @type Module
local module = {}
function module.setup(mqtt_client)
local light = devices.LightOnOff.new({
name = "Light",
room = "Guest Room",
topic = helper.mqtt_z2m("guest/light"),
client = mqtt_client,
})
presence.turn_off_when_away(light)
local window = devices.ContactSensor.new({
name = "Window",
room = "Guest Room",
topic = helper.mqtt_z2m("guest/window"),
client = mqtt_client,
battery_callback = battery.callback,
})
windows.add(window)
local printer = devices.OutletOnOff.new({
name = "3D Printer",
room = "Guest Room",
topic = helper.mqtt_z2m("guest/printer"),
client = mqtt_client,
})
--- @type Module
return {
light,
window,
printer,
}
end
return module

View File

@@ -1,105 +0,0 @@
local battery = require("config.battery")
local debug = require("config.debug")
local devices = require("automation:devices")
local hallway_automation = require("config.hallway_automation")
local helper = require("config.helper")
local hue_bridge = require("config.hue_bridge")
local presence = require("config.presence")
local utils = require("automation:utils")
local windows = require("config.windows")
--- @type Module
local module = {}
function module.setup(mqtt_client)
local main_light = devices.HueGroup.new({
identifier = "hallway_main_light",
ip = hue_bridge.ip,
login = hue_bridge.token,
group_id = 81,
scene_id = "3qWKxGVadXFFG4o",
})
hallway_automation.add_callback(function(on)
main_light:set_on(on)
end)
local storage_light = devices.LightBrightness.new({
name = "Storage",
room = "Hallway",
topic = helper.mqtt_z2m("hallway/storage"),
client = mqtt_client,
callback = hallway_automation.light_callback,
})
presence.turn_off_when_away(storage_light)
hallway_automation.add_callback(function(on)
if on then
storage_light:set_brightness(80)
else
storage_light:set_on(false)
end
end)
local remote = devices.IkeaRemote.new({
name = "Remote",
room = "Hallway",
client = mqtt_client,
topic = helper.mqtt_z2m("hallway/remote"),
callback = hallway_automation.switch_callback,
battery_callback = battery.callback,
})
local trash = devices.ContactSensor.new({
name = "Trash",
room = "Hallway",
sensor_type = "Drawer",
topic = helper.mqtt_z2m("hallway/trash"),
client = mqtt_client,
callback = hallway_automation.trash_callback,
battery_callback = battery.callback,
})
hallway_automation.set_trash(trash)
local timeout = utils.Timeout.new()
local function frontdoor_presence(_, open)
if open then
timeout:cancel()
if not presence.overall_presence() then
mqtt_client:send_message(helper.mqtt_automation("presence/contact/frontdoor"), {
state = true,
updated = utils.get_epoch(),
})
end
else
timeout:start(debug.debug_mode and 10 or 15 * 60, function()
mqtt_client:send_message(helper.mqtt_automation("presence/contact/frontdoor"), nil)
end)
end
end
local frontdoor = devices.ContactSensor.new({
name = "Frontdoor",
room = "Hallway",
sensor_type = "Door",
topic = helper.mqtt_z2m("hallway/frontdoor"),
client = mqtt_client,
callback = {
frontdoor_presence,
hallway_automation.door_callback,
},
battery_callback = battery.callback,
})
windows.add(frontdoor)
hallway_automation.set_door(frontdoor)
--- @type Module
return {
main_light,
storage_light,
remote,
trash,
frontdoor,
}
end
return module

View File

@@ -1,48 +0,0 @@
local battery = require("config.battery")
local devices = require("automation:devices")
local helper = require("config.helper")
local hue_bridge = require("config.hue_bridge")
--- @type Module
local module = {}
function module.setup(mqtt_client)
local light = devices.HueGroup.new({
identifier = "hallway_top_light",
ip = hue_bridge.ip,
login = hue_bridge.token,
group_id = 83,
scene_id = "QeufkFDICEHWeKJ7",
})
local top_switch = devices.HueSwitch.new({
name = "SwitchTop",
room = "Hallway",
client = mqtt_client,
topic = helper.mqtt_z2m("hallway/switchtop"),
left_callback = function()
light:set_on(not light:on())
end,
battery_callback = battery.callback,
})
local bottom_switch = devices.HueSwitch.new({
name = "SwitchBottom",
room = "Hallway",
client = mqtt_client,
topic = helper.mqtt_z2m("hallway/switchbottom"),
left_callback = function()
light:set_on(not light:on())
end,
battery_callback = battery.callback,
})
--- @type Module
return {
light,
top_switch,
bottom_switch,
}
end
return module

View File

@@ -1,71 +0,0 @@
local battery = require("config.battery")
local devices = require("automation:devices")
local helper = require("config.helper")
local hue_bridge = require("config.hue_bridge")
local presence = require("config.presence")
--- @class KitchenModule: Module
local module = {}
--- @type HueGroup?
local lights = nil
--- @type SetupFunction
function module.setup(mqtt_client)
lights = devices.HueGroup.new({
identifier = "kitchen_lights",
ip = hue_bridge.ip,
login = hue_bridge.token,
group_id = 7,
scene_id = "7MJLG27RzeRAEVJ",
})
local kettle = devices.OutletPower.new({
outlet_type = "Kettle",
name = "Kettle",
room = "Kitchen",
topic = helper.mqtt_z2m("kitchen/kettle"),
client = mqtt_client,
callback = helper.auto_off(),
})
presence.turn_off_when_away(kettle)
local kettle_remote = devices.IkeaRemote.new({
name = "Remote",
room = "Kitchen",
client = mqtt_client,
topic = helper.mqtt_z2m("kitchen/remote"),
single_button = true,
callback = function(_, on)
kettle:set_on(on)
end,
battery_callback = battery.callback,
})
local kettle_remote_bedroom = devices.IkeaRemote.new({
name = "Remote",
room = "Bedroom",
client = mqtt_client,
topic = helper.mqtt_z2m("bedroom/remote"),
single_button = true,
callback = function(_, on)
kettle:set_on(on)
end,
battery_callback = battery.callback,
})
return {
lights,
kettle,
kettle_remote,
kettle_remote_bedroom,
}
end
function module.toggle_lights()
if lights then
lights:set_on(not lights:on())
end
end
return module

View File

@@ -1,126 +0,0 @@
local battery = require("config.battery")
local devices = require("automation:devices")
local helper = require("config.helper")
local hue_bridge = require("config.hue_bridge")
local presence = require("config.presence")
local windows = require("config.windows")
--- @type Module
local module = {}
function module.setup(mqtt_client)
local lights = devices.HueGroup.new({
identifier = "living_lights",
ip = hue_bridge.ip,
login = hue_bridge.token,
group_id = 1,
scene_id = "SNZw7jUhQ3cXSjkj",
})
local lights_relax = devices.HueGroup.new({
identifier = "living_lights_relax",
ip = hue_bridge.ip,
login = hue_bridge.token,
group_id = 1,
scene_id = "eRJ3fvGHCcb6yNw",
})
local switch = devices.HueSwitch.new({
name = "Switch",
room = "Living",
client = mqtt_client,
topic = helper.mqtt_z2m("living/switch"),
left_callback = require("config.rooms.kitchen").toggle_lights,
right_callback = function()
lights:set_on(not lights:on())
end,
right_hold_callback = function()
lights_relax:set_on(true)
end,
battery_callback = battery.callback,
})
local pc = devices.WakeOnLAN.new({
name = "Zeus",
room = "Living Room",
topic = helper.mqtt_automation("appliance/living_room/zeus"),
client = mqtt_client,
mac_address = "30:9c:23:60:9c:13",
broadcast_ip = "10.0.3.255",
})
local mixer = devices.OutletOnOff.new({
name = "Mixer",
room = "Living Room",
topic = helper.mqtt_z2m("living/mixer"),
client = mqtt_client,
})
presence.turn_off_when_away(mixer)
local speakers = devices.OutletOnOff.new({
name = "Speakers",
room = "Living Room",
topic = helper.mqtt_z2m("living/speakers"),
client = mqtt_client,
})
presence.turn_off_when_away(speakers)
local audio_remote = devices.IkeaRemote.new({
name = "Remote",
room = "Living Room",
client = mqtt_client,
topic = helper.mqtt_z2m("living/remote"),
single_button = true,
callback = function(_, on)
if on then
if mixer:on() then
mixer:set_on(false)
speakers:set_on(false)
else
mixer:set_on(true)
speakers:set_on(true)
end
else
if not mixer:on() then
mixer:set_on(true)
else
speakers:set_on(not speakers:on())
end
end
end,
battery_callback = battery.callback,
})
local balcony = devices.ContactSensor.new({
name = "Balcony",
room = "Living Room",
sensor_type = "Door",
topic = helper.mqtt_z2m("living/balcony"),
client = mqtt_client,
battery_callback = battery.callback,
})
windows.add(balcony)
local window = devices.ContactSensor.new({
name = "Window",
room = "Living Room",
topic = helper.mqtt_z2m("living/window"),
client = mqtt_client,
battery_callback = battery.callback,
})
windows.add(window)
--- @type Module
return {
lights,
lights_relax,
switch,
pc,
mixer,
speakers,
audio_remote,
balcony,
window,
}
end
return module

View File

@@ -1,41 +0,0 @@
local battery = require("config.battery")
local devices = require("automation:devices")
local helper = require("config.helper")
local presence = require("config.presence")
--- @type Module
local module = {}
function module.setup(mqtt_client)
local light = devices.LightBrightness.new({
name = "Light",
room = "Storage",
topic = helper.mqtt_z2m("storage/light"),
client = mqtt_client,
})
presence.turn_off_when_away(light)
local door = devices.ContactSensor.new({
name = "Door",
room = "Storage",
sensor_type = "Door",
topic = helper.mqtt_z2m("storage/door"),
client = mqtt_client,
callback = function(_, open)
if open then
light:set_brightness(100)
else
light:set_on(false)
end
end,
battery_callback = battery.callback,
})
--- @type Module
return {
light,
door,
}
end
return module

View File

@@ -1,69 +0,0 @@
local battery = require("config.battery")
local debug = require("config.debug")
local devices = require("automation:devices")
local helper = require("config.helper")
local presence = require("config.presence")
local utils = require("automation:utils")
--- @type Module
local module = {}
function module.setup(mqtt_client)
local charger = devices.OutletOnOff.new({
name = "Charger",
room = "Workbench",
topic = helper.mqtt_z2m("workbench/charger"),
client = mqtt_client,
callback = helper.off_timeout(debug.debug_mode and 5 or 20 * 3600),
})
local outlets = devices.OutletOnOff.new({
name = "Outlets",
room = "Workbench",
topic = helper.mqtt_z2m("workbench/outlet"),
client = mqtt_client,
})
presence.turn_off_when_away(outlets)
local light = devices.LightColorTemperature.new({
name = "Light",
room = "Workbench",
topic = helper.mqtt_z2m("workbench/light"),
client = mqtt_client,
})
presence.turn_off_when_away(light)
local delay_color_temp = utils.Timeout.new()
local remote = devices.IkeaRemote.new({
name = "Remote",
room = "Workbench",
client = mqtt_client,
topic = helper.mqtt_z2m("workbench/remote"),
callback = function(_, on)
delay_color_temp:cancel()
if on then
light:set_brightness(82)
-- NOTE: This light does NOT support changing both the brightness and color
-- temperature at the same time, so we first change the brightness and once
-- that is complete we change the color temperature, as that is less likely
-- to have to actually change.
delay_color_temp:start(0.5, function()
light:set_color_temperature(3333)
end)
else
light:set_on(false)
end
end,
battery_callback = battery.callback,
})
--- @type Module
return {
charger,
outlets,
light,
remote,
}
end
return module

View File

@@ -1,43 +0,0 @@
local ntfy = require("config.ntfy")
local presence = require("config.presence")
--- @class WindowsModule: Module
local module = {}
--- @class OnPresence
--- @field [integer] OpenCloseInterface
local sensors = {}
--- @param sensor OpenCloseInterface
function module.add(sensor)
table.insert(sensors, sensor)
end
--- @type SetupFunction
function module.setup()
presence.add_callback(function(p)
if not p then
local open = {}
for _, sensor in ipairs(sensors) do
if sensor:open_percent() > 0 then
local id = sensor:get_id()
print("Open window detected: " .. id)
table.insert(open, id)
end
end
if #open > 0 then
local message = table.concat(open, "\n")
ntfy.send_notification({
title = "Windows are open",
message = message,
tags = { "window" },
priority = "high",
})
end
end
end)
end
return module

View File

@@ -6,9 +6,9 @@ local devices
---@class Action
---@field action
---| "broadcast"
---@field extras (table<string, string>)?
---@field extras table<string, string>?
---@field label string
---@field clear (boolean)?
---@field clear boolean?
local Action
---@class AirFilter: DeviceInterface, OnOffInterface
@@ -20,49 +20,49 @@ function devices.AirFilter.new(config) end
---@class AirFilterConfig
---@field name string
---@field room (string)?
---@field room string?
---@field url string
local AirFilterConfig
---@class ConfigLightLightStateBrightness
---@field name string
---@field room (string)?
---@field room string?
---@field topic string
---@field callback (fun(_: LightBrightness, _: LightStateBrightness) | fun(_: LightBrightness, _: LightStateBrightness)[])?
---@field client (AsyncClient)?
---@field callback fun(_: LightBrightness, _: LightStateBrightness) | fun(_: LightBrightness, _: LightStateBrightness)[]?
---@field client AsyncClient?
local ConfigLightLightStateBrightness
---@class ConfigLightLightStateColorTemperature
---@field name string
---@field room (string)?
---@field room string?
---@field topic string
---@field callback (fun(_: LightColorTemperature, _: LightStateColorTemperature) | fun(_: LightColorTemperature, _: LightStateColorTemperature)[])?
---@field client (AsyncClient)?
---@field callback fun(_: LightColorTemperature, _: LightStateColorTemperature) | fun(_: LightColorTemperature, _: LightStateColorTemperature)[]?
---@field client AsyncClient?
local ConfigLightLightStateColorTemperature
---@class ConfigLightLightStateOnOff
---@field name string
---@field room (string)?
---@field room string?
---@field topic string
---@field callback (fun(_: LightOnOff, _: LightStateOnOff) | fun(_: LightOnOff, _: LightStateOnOff)[])?
---@field client (AsyncClient)?
---@field callback fun(_: LightOnOff, _: LightStateOnOff) | fun(_: LightOnOff, _: LightStateOnOff)[]?
---@field client AsyncClient?
local ConfigLightLightStateOnOff
---@class ConfigOutletOutletStateOnOff
---@field name string
---@field room (string)?
---@field room string?
---@field topic string
---@field outlet_type (OutletType)?
---@field callback (fun(_: OutletOnOff, _: OutletStateOnOff) | fun(_: OutletOnOff, _: OutletStateOnOff)[])?
---@field outlet_type OutletType?
---@field callback fun(_: OutletOnOff, _: OutletStateOnOff) | fun(_: OutletOnOff, _: OutletStateOnOff)[]?
---@field client AsyncClient
local ConfigOutletOutletStateOnOff
---@class ConfigOutletOutletStatePower
---@field name string
---@field room (string)?
---@field room string?
---@field topic string
---@field outlet_type (OutletType)?
---@field callback (fun(_: OutletPower, _: OutletStatePower) | fun(_: OutletPower, _: OutletStatePower)[])?
---@field outlet_type OutletType?
---@field callback fun(_: OutletPower, _: OutletStatePower) | fun(_: OutletPower, _: OutletStatePower)[]?
---@field client AsyncClient
local ConfigOutletOutletStatePower
@@ -75,12 +75,12 @@ function devices.ContactSensor.new(config) end
---@class ContactSensorConfig
---@field name string
---@field room (string)?
---@field room string?
---@field topic string
---@field sensor_type (SensorType)?
---@field callback (fun(_: ContactSensor, _: boolean) | fun(_: ContactSensor, _: boolean)[])?
---@field battery_callback (fun(_: ContactSensor, _: number) | fun(_: ContactSensor, _: number)[])?
---@field client (AsyncClient)?
---@field sensor_type SensorType?
---@field callback fun(_: ContactSensor, _: boolean) | fun(_: ContactSensor, _: boolean)[]?
---@field battery_callback fun(_: ContactSensor, _: number) | fun(_: ContactSensor, _: number)[]?
---@field client AsyncClient?
local ContactSensorConfig
---@alias Flag
@@ -134,14 +134,14 @@ function devices.HueSwitch.new(config) end
---@class HueSwitchConfig
---@field name string
---@field room (string)?
---@field room string?
---@field topic string
---@field client AsyncClient
---@field left_callback (fun(_: HueSwitch) | fun(_: HueSwitch)[])?
---@field right_callback (fun(_: HueSwitch) | fun(_: HueSwitch)[])?
---@field left_hold_callback (fun(_: HueSwitch) | fun(_: HueSwitch)[])?
---@field right_hold_callback (fun(_: HueSwitch) | fun(_: HueSwitch)[])?
---@field battery_callback (fun(_: HueSwitch, _: number) | fun(_: HueSwitch, _: number)[])?
---@field left_callback fun(_: HueSwitch) | fun(_: HueSwitch)[]?
---@field right_callback fun(_: HueSwitch) | fun(_: HueSwitch)[]?
---@field left_hold_callback fun(_: HueSwitch) | fun(_: HueSwitch)[]?
---@field right_hold_callback fun(_: HueSwitch) | fun(_: HueSwitch)[]?
---@field battery_callback fun(_: HueSwitch, _: number) | fun(_: HueSwitch, _: number)[]?
local HueSwitchConfig
---@class IkeaRemote: DeviceInterface
@@ -153,12 +153,12 @@ function devices.IkeaRemote.new(config) end
---@class IkeaRemoteConfig
---@field name string
---@field room (string)?
---@field single_button (boolean)?
---@field room string?
---@field single_button boolean?
---@field topic string
---@field client AsyncClient
---@field callback (fun(_: IkeaRemote, _: boolean) | fun(_: IkeaRemote, _: boolean)[])?
---@field battery_callback (fun(_: IkeaRemote, _: number) | fun(_: IkeaRemote, _: number)[])?
---@field callback fun(_: IkeaRemote, _: boolean) | fun(_: IkeaRemote, _: boolean)[]?
---@field battery_callback fun(_: IkeaRemote, _: number) | fun(_: IkeaRemote, _: number)[]?
local IkeaRemoteConfig
---@class KasaOutlet: DeviceInterface, OnOffInterface
@@ -206,7 +206,7 @@ function devices.LightSensor.new(config) end
---@field topic string
---@field min integer
---@field max integer
---@field callback (fun(_: LightSensor, _: boolean) | fun(_: LightSensor, _: boolean)[])?
---@field callback fun(_: LightSensor, _: boolean) | fun(_: LightSensor, _: boolean)[]?
---@field client AsyncClient
local LightSensorConfig
@@ -227,10 +227,10 @@ local LightStateOnOff
---@class Notification
---@field title string
---@field message (string)?
---@field tags ((string)[])?
---@field priority (Priority)?
---@field actions ((Action)[])?
---@field message string?
---@field tags string[]?
---@field priority Priority?
---@field actions Action[]?
local Notification
---@class Ntfy: DeviceInterface
@@ -244,7 +244,7 @@ function devices.Ntfy.new(config) end
function Ntfy:send_notification(notification) end
---@class NtfyConfig
---@field url (string)?
---@field url string?
---@field topic string
local NtfyConfig
@@ -287,7 +287,7 @@ function Presence:overall_presence() end
---@class PresenceConfig
---@field topic string
---@field callback (fun(_: Presence, _: boolean) | fun(_: Presence, _: boolean)[])?
---@field callback fun(_: Presence, _: boolean) | fun(_: Presence, _: boolean)[]?
---@field client AsyncClient
local PresenceConfig
@@ -321,16 +321,16 @@ function devices.Washer.new(config) end
---@field identifier string
---@field topic string
---@field threshold number
---@field done_callback (fun(_: Washer) | fun(_: Washer)[])?
---@field done_callback fun(_: Washer) | fun(_: Washer)[]?
---@field client AsyncClient
local WasherConfig
---@class WolConfig
---@field name string
---@field room (string)?
---@field room string?
---@field topic string
---@field mac_address string
---@field broadcast_ip (string)?
---@field broadcast_ip string?
---@field client AsyncClient
local WolConfig

View File

@@ -3,26 +3,18 @@
---@class FulfillmentConfig
---@field openid_url string
---@field ip (string)?
---@field port (integer)?
---@field ip string?
---@field port integer?
local FulfillmentConfig
---@class Config
---@field fulfillment FulfillmentConfig
---@field modules (Module)[]
---@field devices Devices?
---@field mqtt MqttConfig
---@field schedule table<string, fun() | fun()[]>?
local Config
---@alias SetupFunction fun(mqtt_client: AsyncClient): Module | DeviceInterface[] | nil
---@alias Schedule table<string, fun() | fun()[]>
---@class Module
---@field setup (SetupFunction)?
---@field devices (DeviceInterface)[]?
---@field schedule Schedule?
---@field [number] (Module)[]?
local Module
---@alias Devices (DeviceInterface | fun(client: AsyncClient): Devices)[]
---@class MqttConfig
---@field host string
@@ -30,7 +22,7 @@ local Module
---@field client_name string
---@field username string
---@field password string
---@field tls (boolean)?
---@field tls boolean?
local MqttConfig
---@class AsyncClient

View File

@@ -1,18 +0,0 @@
variable "TAG_BASE" {}
variable "RELEASE_VERSION" {}
group "default" {
targets = ["automation"]
}
target "docker-metadata-action" {}
target "automation" {
inherits = ["docker-metadata-action"]
context = "./"
dockerfile = "Dockerfile"
tags = [for tag in target.docker-metadata-action.tags : "${TAG_BASE}:${tag}"]
args = {
RELEASE_VERSION="${RELEASE_VERSION}"
}
}

View File

@@ -6,6 +6,7 @@ use std::process;
use ::config::{Environment, File};
use automation::config::{Config, Setup};
use automation::schedule::start_scheduler;
use automation::secret::EnvironmentSecretFile;
use automation::version::VERSION;
use automation::web::{ApiError, User};
@@ -139,12 +140,13 @@ async fn app() -> anyhow::Result<()> {
let mqtt_client = mqtt::start(config.mqtt, &device_manager.event_channel());
let resolved = config.modules.resolve(&lua, &mqtt_client).await?;
for device in resolved.devices {
if let Some(devices) = config.devices {
for device in devices.get(&lua, &mqtt_client).await? {
device_manager.add(device).await;
}
}
resolved.scheduler.start().await?;
start_scheduler(config.schedule).await?;
// Create google home fulfillment route
let fulfillment = Router::new().route("/google_home", post(fulfillment));

View File

@@ -1,8 +1,10 @@
use std::fs::{self, File};
use std::io::Write;
use automation::config::generate_definitions;
use automation::config::{Config, Devices, FulfillmentConfig};
use automation_lib::Module;
use automation_lib::mqtt::{MqttConfig, WrappedAsyncClient};
use lua_typed::Typed;
use tracing::{info, warn};
extern crate automation_devices;
@@ -25,6 +27,24 @@ fn write_definitions(filename: &str, definitions: &str) -> std::io::Result<()> {
Ok(())
}
fn config_definitions() -> String {
let mut output = "---@meta\n\n".to_string();
output +=
&FulfillmentConfig::generate_full().expect("FulfillmentConfig should have a definition");
output += "\n";
output += &Config::generate_full().expect("Config should have a definition");
output += "\n";
output += &Devices::generate_full().expect("Devices should have a definition");
output += "\n";
output += &MqttConfig::generate_full().expect("MqttConfig should have a definition");
output += "\n";
output +=
&WrappedAsyncClient::generate_full().expect("WrappedAsyncClient should have a definition");
output
}
fn main() -> std::io::Result<()> {
tracing_subscriber::fmt::init();
@@ -39,7 +59,7 @@ fn main() -> std::io::Result<()> {
}
}
write_definitions("config.lua", &generate_definitions())?;
write_definitions("config.lua", &config_definitions())?;
Ok(())
}

View File

@@ -1,6 +1,5 @@
use std::collections::{HashMap, VecDeque};
use std::net::{Ipv4Addr, SocketAddr};
use std::ops::Deref;
use automation_lib::action_callback::ActionCallback;
use automation_lib::device::Device;
@@ -10,8 +9,6 @@ use lua_typed::Typed;
use mlua::FromLua;
use serde::Deserialize;
use crate::schedule::Scheduler;
#[derive(Debug, Deserialize)]
pub struct Setup {
#[serde(default = "default_entrypoint")]
@@ -37,219 +34,81 @@ pub struct FulfillmentConfig {
pub port: u16,
}
#[derive(Debug)]
struct SetupFunction(mlua::Function);
impl Typed for SetupFunction {
fn type_name() -> String {
"SetupFunction".into()
}
fn generate_header() -> Option<String> {
Some(format!(
"---@alias {} fun(mqtt_client: {}): {} | DeviceInterface[] | nil\n",
Self::type_name(),
WrappedAsyncClient::type_name(),
Module::type_name()
))
}
}
impl FromLua for SetupFunction {
fn from_lua(value: mlua::Value, lua: &mlua::Lua) -> mlua::Result<Self> {
Ok(Self(FromLua::from_lua(value, lua)?))
}
}
impl Deref for SetupFunction {
type Target = mlua::Function;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[derive(Debug, Default)]
struct Schedule(HashMap<String, ActionCallback<()>>);
pub struct Devices(mlua::Value);
impl Typed for Schedule {
fn type_name() -> String {
"Schedule".into()
}
fn generate_header() -> Option<String> {
Some(format!(
"---@alias {} {}\n",
Self::type_name(),
HashMap::<String, ActionCallback<()>>::type_name(),
))
}
}
impl FromLua for Schedule {
fn from_lua(value: mlua::Value, lua: &mlua::Lua) -> mlua::Result<Self> {
Ok(Self(FromLua::from_lua(value, lua)?))
}
}
impl IntoIterator for Schedule {
type Item = <HashMap<String, ActionCallback<()>> as IntoIterator>::Item;
type IntoIter = <HashMap<String, ActionCallback<()>> as IntoIterator>::IntoIter;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
#[derive(Debug, Default)]
struct Module {
setup: Option<SetupFunction>,
devices: Vec<Box<dyn Device>>,
schedule: Schedule,
modules: Vec<Module>,
}
// TODO: Add option to typed to rename field
impl Typed for Module {
fn type_name() -> String {
"Module".into()
}
fn generate_header() -> Option<String> {
Some(format!("---@class {}\n", Self::type_name()))
}
fn generate_members() -> Option<String> {
Some(format!(
r#"---@field setup {}
---@field devices {}?
---@field schedule {}?
---@field [number] {}?
"#,
Option::<SetupFunction>::type_name(),
Vec::<Box<dyn Device>>::type_name(),
Schedule::type_name(),
Vec::<Module>::type_name(),
))
}
fn generate_footer() -> Option<String> {
let type_name = <Self as Typed>::type_name();
Some(format!("local {type_name}\n"))
}
}
impl FromLua for Module {
fn from_lua(value: mlua::Value, _lua: &mlua::Lua) -> mlua::Result<Self> {
// When calling require it might return a result from the searcher indicating how the
// module was found, we want to ignore these entries.
// TODO: Find a better solution for this
if value.is_string() {
return Ok(Default::default());
}
let mlua::Value::Table(table) = value else {
return Err(mlua::Error::runtime(format!(
"Expected module table, instead found: {}",
value.type_name()
)));
};
let setup = table.get("setup")?;
let devices = table.get("devices").unwrap_or_default();
let schedule = table.get("schedule").unwrap_or_default();
let mut modules = Vec::new();
for module in table.sequence_values::<Module>() {
modules.push(module?);
}
Ok(Module {
setup,
devices,
schedule,
modules,
})
}
}
#[derive(Debug, Default)]
pub struct Modules(Vec<Module>);
impl Typed for Modules {
fn type_name() -> String {
Vec::<Module>::type_name()
}
}
impl FromLua for Modules {
fn from_lua(value: mlua::Value, lua: &mlua::Lua) -> mlua::Result<Self> {
Ok(Self(FromLua::from_lua(value, lua)?))
}
}
impl Modules {
pub async fn resolve(
impl Devices {
pub async fn get(
self,
lua: &mlua::Lua,
client: &WrappedAsyncClient,
) -> mlua::Result<Resolved> {
) -> mlua::Result<Vec<Box<dyn Device>>> {
let mut devices = Vec::new();
let mut scheduler = Scheduler::default();
let initial_table = match self.0 {
mlua::Value::Table(table) => table,
mlua::Value::Function(f) => f.call_async(client.clone()).await?,
_ => Err(mlua::Error::runtime(format!(
"Expected table or function, instead found: {}",
self.0.type_name()
)))?,
};
let mut modules: VecDeque<_> = self.0.into();
let mut queue: VecDeque<mlua::Table> = [initial_table].into();
loop {
let Some(module) = modules.pop_front() else {
let Some(table) = queue.pop_front() else {
break;
};
modules.extend(module.modules);
for pair in table.pairs() {
let (_, value): (mlua::Value, _) = pair?;
if let Some(setup) = module.setup {
let result: mlua::Value = setup.call_async(client.clone()).await?;
if result.is_nil() {
// We ignore nil results
} else if let Ok(d) = <Vec<_> as FromLua>::from_lua(result.clone(), lua)
&& !d.is_empty()
{
// This is a shortcut for the common pattern of setup functions that only
// return devices
devices.extend(d);
} else if let Ok(module) = FromLua::from_lua(result.clone(), lua) {
modules.push_back(module);
} else {
return Err(mlua::Error::runtime(
"Setup function returned data in an unexpected format",
));
match value {
mlua::Value::UserData(_) => devices.push(Box::from_lua(value, lua)?),
mlua::Value::Function(f) => {
queue.push_back(f.call_async(client.clone()).await?);
}
_ => Err(mlua::Error::runtime(format!(
"Expected a device, table, or function, instead found: {}",
value.type_name()
)))?,
}
}
}
devices.extend(module.devices);
for (cron, f) in module.schedule {
scheduler.add_job(cron, f);
Ok(devices)
}
}
Ok(Resolved { devices, scheduler })
impl FromLua for Devices {
fn from_lua(value: mlua::Value, _lua: &mlua::Lua) -> mlua::Result<Self> {
Ok(Devices(value))
}
}
#[derive(Debug, Default)]
pub struct Resolved {
pub devices: Vec<Box<dyn Device>>,
pub scheduler: Scheduler,
impl Typed for Devices {
fn type_name() -> String {
"Devices".into()
}
fn generate_header() -> Option<String> {
Some(format!(
"---@alias {} (DeviceInterface | fun(client: {}): Devices)[]\n",
<Self as Typed>::type_name(),
<WrappedAsyncClient as Typed>::type_name()
))
}
}
#[derive(Debug, LuaDeviceConfig, Typed)]
pub struct Config {
pub fulfillment: FulfillmentConfig,
#[device_config(from_lua, default)]
pub modules: Modules,
pub devices: Option<Devices>,
#[device_config(from_lua)]
pub mqtt: MqttConfig,
#[device_config(from_lua, default)]
#[typed(default)]
pub schedule: HashMap<String, ActionCallback<()>>,
}
impl From<FulfillmentConfig> for SocketAddr {
@@ -264,25 +123,3 @@ fn default_fulfillment_ip() -> Ipv4Addr {
fn default_fulfillment_port() -> u16 {
7878
}
pub fn generate_definitions() -> String {
let mut output = "---@meta\n\n".to_string();
output +=
&FulfillmentConfig::generate_full().expect("FulfillmentConfig should have a definition");
output += "\n";
output += &Config::generate_full().expect("Config should have a definition");
output += "\n";
output += &SetupFunction::generate_full().expect("SetupFunction should have a definition");
output += "\n";
output += &Schedule::generate_full().expect("Schedule should have a definition");
output += "\n";
output += &Module::generate_full().expect("Module should have a definition");
output += "\n";
output += &MqttConfig::generate_full().expect("MqttConfig should have a definition");
output += "\n";
output +=
&WrappedAsyncClient::generate_full().expect("WrappedAsyncClient should have a definition");
output
}

View File

@@ -1,5 +1,3 @@
#![feature(if_let_guard)]
pub mod config;
pub mod schedule;
pub mod secret;

View File

@@ -1,22 +1,15 @@
use std::collections::HashMap;
use std::pin::Pin;
use automation_lib::action_callback::ActionCallback;
use tokio_cron_scheduler::{Job, JobScheduler, JobSchedulerError};
#[derive(Debug, Default)]
pub struct Scheduler {
jobs: Vec<(String, ActionCallback<()>)>,
}
impl Scheduler {
pub fn add_job(&mut self, cron: String, f: ActionCallback<()>) {
self.jobs.push((cron, f));
}
pub async fn start(self) -> Result<(), JobSchedulerError> {
pub async fn start_scheduler(
schedule: HashMap<String, ActionCallback<()>>,
) -> Result<(), JobSchedulerError> {
let scheduler = JobScheduler::new().await?;
for (s, f) in self.jobs {
for (s, f) in schedule {
let job = {
move |_uuid, _lock| -> Pin<Box<dyn Future<Output = ()> + Send>> {
let f = f.clone();
@@ -34,4 +27,3 @@ impl Scheduler {
scheduler.start().await
}
}