Compare commits

5 Commits
Author SHA1 Message Date
Dreaded_X 95d7bfc43e feat: Receive devices through config return
Build and deploy / build (push) Successful in 12m8s
Build and deploy / Deploy container (push) Has been skipped
2025-10-17 03:57:33 +02:00
Dreaded_X 4e2da2ecca feat: Ensure consistent ordering device definitions 2025-10-17 03:57:33 +02:00
Dreaded_X 65c7ed6349 feat: Generate definitions for config
Build and deploy / build (push) Successful in 9m15s
Build and deploy / Deploy container (push) Has been skipped
2025-10-17 03:15:27 +02:00
Dreaded_X a0ed373971 refactor: Move definition writing into separate function
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
Dreaded_X 5e13dff2b5 chore: Move main.rs to bin/automation.rs 2025-10-17 03:08:37 +02:00
62 changed files with 1821 additions and 3165 deletions
-3
View File
@@ -1,5 +1,2 @@
[env] [env]
RUST_LOG = "automation=debug" RUST_LOG = "automation=debug"
[target.x86_64-unknown-linux-musl]
rustflags = ["-C", "link-arg=-lc"]
-2
View File
@@ -2,5 +2,3 @@
.env .env
# Use the rust environment provided by the container # Use the rust environment provided by the container
rust-toolchain.toml rust-toolchain.toml
Dockerfile
docker-bake.hcl
-28
View File
@@ -1,28 +0,0 @@
name: Audit
on:
push:
paths:
- "**/Cargo.toml"
- "**/Cargo.lock"
schedule:
- cron: "0 0 * * *"
workflow_dispatch:
jobs:
audit:
name: cargo audit
runs-on: ubuntu-latest
permissions:
issues: write
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Install rust toolchain
uses: dtolnay/rust-toolchain@nightly
- name: Setup rust cache
uses: Swatinem/rust-cache@v2
- name: Audit check
uses: https://git.huizinga.dev/infra/rust-audit-check@v3.0.0
with:
token: ${{ secrets.GITEA_TOKEN }}
+3 -9
View File
@@ -9,10 +9,10 @@ on:
jobs: jobs:
build: build:
uses: infra/workflows/.gitea/workflows/docker.yaml@2bb37b698effa4fba36040d668cfa95d4abc568e uses: dreaded_x/workflows/.gitea/workflows/rust-kubernetes.yaml@22ee0c1788a8d2157db87d6a6f8dbe520fe48592
secrets: inherit secrets: inherit
with: with:
push_manifests: false upload_manifests: false
deploy: deploy:
name: Deploy container name: Deploy container
@@ -26,10 +26,6 @@ jobs:
docker stop automation_rs || true docker stop automation_rs || true
docker rm automation_rs || true docker rm automation_rs || true
- name: Login to registry
run: |
docker login git.huizinga.dev -u ${{ gitea.actor }} -p ${{ secrets.REGISTRY_TOKEN }} \
- name: Create container - name: Create container
run: | run: |
docker create \ docker create \
@@ -41,9 +37,7 @@ jobs:
-e AUTOMATION__SECRETS__MQTT_PASSWORD=${{ secrets.MQTT_PASSWORD }} \ -e AUTOMATION__SECRETS__MQTT_PASSWORD=${{ secrets.MQTT_PASSWORD }} \
-e AUTOMATION__SECRETS__HUE_TOKEN=${{ secrets.HUE_TOKEN }} \ -e AUTOMATION__SECRETS__HUE_TOKEN=${{ secrets.HUE_TOKEN }} \
-e AUTOMATION__SECRETS__NTFY_TOPIC=${{ secrets.NTFY_TOPIC }} \ -e AUTOMATION__SECRETS__NTFY_TOPIC=${{ secrets.NTFY_TOPIC }} \
-e AUTOMATION__SECRETS__PRINTER_DEVICE_ID=${{ secrets.PRINTER_DEVICE_ID }} \ git.huizinga.dev/dreaded_x/automation_rs@${{ needs.build.outputs.digest }}
-e AUTOMATION__SECRETS__PRINTER_ACCESS_CODE=${{ secrets.PRINTER_ACCESS_CODE }} \
$(echo ${{ toJSON(needs.build.outputs.images) }} | jq .automation -r)
docker network connect web automation_rs docker network connect web automation_rs
Generated
+713 -1184
View File
File diff suppressed because it is too large Load Diff
+25 -24
View File
@@ -16,28 +16,29 @@ members = [
[workspace.dependencies] [workspace.dependencies]
air_filter_types = { git = "https://git.huizinga.dev/Dreaded_X/airfilter", tag = "v0.4.4" } air_filter_types = { git = "https://git.huizinga.dev/Dreaded_X/airfilter", tag = "v0.4.4" }
anyhow = "1.0.102" anyhow = "1.0.99"
async-trait = "0.1.89" async-trait = "0.1.89"
automation_cast = { path = "./automation_cast" } automation_cast = { path = "./automation_cast" }
automation_devices = { path = "./automation_devices" } automation_devices = { path = "./automation_devices" }
automation_lib = { path = "./automation_lib" } automation_lib = { path = "./automation_lib" }
automation_macro = { path = "./automation_macro" } automation_macro = { path = "./automation_macro" }
axum = "0.8.9" axum = "0.8.4"
bytes = "1.11.1" bytes = "1.10.1"
dyn-clone = "1.0.20" dyn-clone = "1.0.20"
eui48 = { version = "1.1.0", features = [ eui48 = { version = "1.1.0", features = [
"disp_hexstring", "disp_hexstring",
"serde", "serde",
], default-features = false } ], default-features = false }
futures = "0.3.32" futures = "0.3.31"
google_home = { path = "./google_home/google_home" } google_home = { path = "./google_home/google_home" }
google_home_macro = { path = "./google_home/google_home_macro" } google_home_macro = { path = "./google_home/google_home_macro" }
hostname = "0.4.2" hostname = "0.4.1"
inventory = "0.3.24" indexmap = { version = "2.11.0", features = ["serde"] }
itertools = "0.15.0" inventory = "0.3.21"
itertools = "0.14.0"
json_value_merge = "2.0.1" json_value_merge = "2.0.1"
lua_typed = { git = "https://git.huizinga.dev/Dreaded_X/lua_typed" } lua_typed = { git = "https://git.huizinga.dev/Dreaded_X/lua_typed" }
mlua = { version = "0.12.0", features = [ mlua = { version = "0.11.3", features = [
"lua54", "lua54",
"vendored", "vendored",
"macros", "macros",
@@ -45,23 +46,24 @@ mlua = { version = "0.12.0", features = [
"async", "async",
"send", "send",
] } ] }
proc-macro2 = "1.0.106" proc-macro2 = "1.0.101"
quote = "1.0.45" quote = "1.0.40"
reqwest = { version = "0.13.3", features = [ reqwest = { version = "0.12.23", features = [
"json", "json",
"rustls", "rustls-tls",
], default-features = false } # Use rustls, since the other packages also use rustls ], default-features = false } # Use rustls, since the other packages also use rustls
rumqttc-next = "0.34.0" rumqttc = "0.24.0"
serde = { version = "1.0.228", features = ["derive"] } serde = { version = "1.0.219", features = ["derive"] }
serde_json = "1.0.149" serde_json = "1.0.143"
serde_repr = "0.1.20" serde_repr = "0.1.20"
syn = { version = "3.0.3" } syn = { version = "2.0.106" }
thiserror = "2.0.18" thiserror = "2.0.16"
tokio = { version = "1", features = ["rt-multi-thread"] } tokio = { version = "1", features = ["rt-multi-thread"] }
tokio-cron-scheduler = "0.15.1" tokio-cron-scheduler = "0.14.0"
tracing = "0.1.44" tracing = "0.1.41"
tracing-subscriber = "0.3.23" tracing-subscriber = "0.3.20"
wakey = "0.4.1" uuid = "1.18.1"
wakey = "0.3.0"
[dependencies] [dependencies]
anyhow = { workspace = true } anyhow = { workspace = true }
@@ -70,7 +72,7 @@ automation_devices = { workspace = true }
automation_lib = { workspace = true } automation_lib = { workspace = true }
automation_macro = { path = "./automation_macro" } automation_macro = { path = "./automation_macro" }
axum = { workspace = true } axum = { workspace = true }
config = { version = "0.15.22", default-features = false, features = [ config = { version = "0.15.15", default-features = false, features = [
"async", "async",
"toml", "toml",
] } ] }
@@ -80,14 +82,13 @@ lua_typed = { workspace = true }
inventory = { workspace = true } inventory = { workspace = true }
mlua = { workspace = true } mlua = { workspace = true }
reqwest = { workspace = true } reqwest = { workspace = true }
rumqttc = { workspace = true }
serde = { workspace = true } serde = { workspace = true }
serde_json = { workspace = true } serde_json = { workspace = true }
thiserror = { workspace = true } thiserror = { workspace = true }
tokio = { workspace = true } tokio = { workspace = true }
tokio-cron-scheduler = { workspace = true }
tracing = { workspace = true } tracing = { workspace = true }
tracing-subscriber = { workspace = true } tracing-subscriber = { workspace = true }
rumqttc-next = { workspace = true }
[patch.crates-io] [patch.crates-io]
wakey = { git = "https://git.huizinga.dev/Dreaded_X/wakey" } wakey = { git = "https://git.huizinga.dev/Dreaded_X/wakey" }
+5 -8
View File
@@ -1,15 +1,14 @@
FROM rust:1.98-alpine3.24 AS base FROM rust:1.89 AS base
ENV CARGO_REGISTRIES_CRATES_IO_PROTOCOL=sparse
RUN cargo install cargo-chef --locked --version 0.1.71 && \ RUN cargo install cargo-chef --locked --version 0.1.71 && \
cargo install cargo-auditable --locked --version 0.6.6 cargo install cargo-auditable --locked --version 0.6.6
WORKDIR /app WORKDIR /app
RUN rustup toolchain install
FROM base AS planner FROM base AS planner
COPY . . COPY . .
RUN cargo chef prepare --recipe-path recipe.json RUN cargo chef prepare --recipe-path recipe.json
FROM base AS builder FROM base AS builder
RUN apk add --no-cache g++=15.2.0-r5 cmake=4.2.3-r0 make=4.4.1-r4 openssl-dev=3.5.8-r0 openssl-libs-static=3.5.8-r0
# HACK: Now we can use unstable feature while on stable rust! # HACK: Now we can use unstable feature while on stable rust!
ENV RUSTC_BOOTSTRAP=1 ENV RUSTC_BOOTSTRAP=1
COPY --from=planner /app/recipe.json recipe.json COPY --from=planner /app/recipe.json recipe.json
@@ -20,10 +19,8 @@ ARG RELEASE_VERSION
ENV RELEASE_VERSION=${RELEASE_VERSION} ENV RELEASE_VERSION=${RELEASE_VERSION}
RUN cargo auditable build --release RUN cargo auditable build --release
FROM gcr.io/distroless/cc-debian12:nonroot AS runtime
FROM gcr.io/distroless/static-debian13:nonroot AS runtime
COPY --from=builder /app/target/release/automation /app/automation COPY --from=builder /app/target/release/automation /app/automation
ENV AUTOMATION__ENTRYPOINT=/app/config/config.lua ENV AUTOMATION__ENTRYPOINT=/app/config.lua
ENV LUA_PATH="/app/?.lua;;" COPY ./config.lua /app/config.lua
COPY ./config /app/config
CMD [ "/app/automation" ] CMD [ "/app/automation" ]
+2 -2
View File
@@ -4,9 +4,9 @@ Custom home automation solution with Google Home integration and lua scripting.
## Development ## Development
This repository uses [prek](https://prek.j178.dev/) to make sure everything is ready to go when committing. This repository uses [pre-commit](https://pre-commit.com) to make sure everything is ready to go when committing.
Install the pre-commit hooks by running the following command: Install the pre-commit hooks by running the following command:
```bash ```bash
prek install pre-commit install
``` ```
+1 -2
View File
@@ -17,7 +17,7 @@ inventory = { workspace = true }
lua_typed = { workspace = true } lua_typed = { workspace = true }
mlua = { workspace = true } mlua = { workspace = true }
reqwest = { workspace = true } reqwest = { workspace = true }
rumqttc-next = { workspace = true } rumqttc = { workspace = true }
serde = { workspace = true } serde = { workspace = true }
serde_json = { workspace = true } serde_json = { workspace = true }
serde_repr = { workspace = true } serde_repr = { workspace = true }
@@ -25,4 +25,3 @@ thiserror = { workspace = true }
tokio = { workspace = true } tokio = { workspace = true }
tracing = { workspace = true } tracing = { workspace = true }
wakey = { workspace = true } wakey = { workspace = true }
bambulab = { version = "0.4.30", default-features = false }
-142
View File
@@ -1,142 +0,0 @@
use std::convert::Infallible;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::time::Duration;
use async_trait::async_trait;
use automation_lib::action_callback::ActionCallback;
use automation_lib::device::Device;
use automation_macro::{Device, LuaDeviceConfig};
use bambulab::client::Client;
use bambulab::{Command, Message};
use google_home::errors::{self};
use google_home::traits::OnOff;
use lua_typed::Typed;
use tracing::{debug, trace};
use crate::{DebugWrap, LuaDeviceCreate};
#[derive(Debug, Clone, LuaDeviceConfig, Typed, Default)]
#[typed(as = "BambuCallbacks")]
pub struct Callbacks {
#[device_config(from_lua, default)]
#[typed(default)]
pub state: ActionCallback<Bambu>,
#[device_config(from_lua, default)]
#[typed(default)]
pub connected: ActionCallback<Bambu>,
}
crate::register_type!(Callbacks);
#[derive(Debug, Clone, LuaDeviceConfig, Typed)]
#[typed(as = "BambuConfig")]
pub struct Config {
pub host: String,
pub device_id: String,
pub access_code: String,
#[device_config(from_lua, default)]
pub callbacks: Callbacks,
}
crate::register_type!(Config);
#[derive(Debug, Clone, Device)]
#[device(traits(OnOff))]
pub struct Bambu {
config: Config,
client: DebugWrap<Client>,
state: Arc<AtomicBool>,
}
crate::register_device!(Bambu);
#[async_trait]
impl LuaDeviceCreate for Bambu {
type Config = Config;
type Error = Infallible;
async fn create(config: Self::Config) -> Result<Self, Infallible> {
trace!(id = config.device_id, "Setting up bambu");
let (tx, mut rx) = tokio::sync::broadcast::channel(25);
let client = Client::new(&config.host, &config.access_code, &config.device_id, tx);
let state = Arc::new(AtomicBool::new(false));
let bambu = Self {
config,
client: DebugWrap(client.clone()),
state: state.clone(),
};
tokio::spawn({
let mut bambu = bambu.clone();
async move {
// The printer might be offline so periodically try to reconnecct
loop {
bambu.client.run().await.ok();
tokio::time::sleep(Duration::from_secs(60)).await;
}
}
});
tokio::spawn({
let bambu = bambu.clone();
async move {
loop {
let message = rx.recv().await.unwrap();
match message {
Message::Print(data) => 'print: {
// Extract the state of the chamber light
let Some(light_report) = data.print.lights_report else {
break 'print;
};
let on = light_report
.iter()
.find(|report| report.node == "chamber_light")
.map(|report| report.mode == "on")
.unwrap_or(false);
state.store(on, std::sync::atomic::Ordering::Relaxed);
bambu.config.callbacks.state.call(bambu.clone()).await;
}
Message::Connected => {
debug!(id = bambu.config.device_id, "Connected");
client.publish(Command::PushAll).await.unwrap();
bambu.config.callbacks.connected.call(bambu.clone()).await;
}
// Ignore everything else
_ => {}
}
}
}
});
Ok(bambu)
}
}
impl Device for Bambu {
fn get_id(&self) -> String {
self.config.device_id.clone()
}
}
#[async_trait]
impl OnOff for Bambu {
async fn on(&self) -> Result<bool, errors::ErrorCode> {
Ok(self.state.load(std::sync::atomic::Ordering::Relaxed))
}
async fn set_on(&self, on: bool) -> Result<(), errors::ErrorCode> {
// NOTE: This will error in case the printer is offline, but we don't really care in that
// case so we just ignore the error
self.client.publish(Command::SetChamberLight(on)).await.ok();
Ok(())
}
}
+1 -4
View File
@@ -159,10 +159,7 @@ impl OpenClose for ContactSensor {
#[async_trait] #[async_trait]
impl OnMqtt for ContactSensor { impl OnMqtt for ContactSensor {
async fn on_mqtt(&self, message: rumqttc::Publish) { async fn on_mqtt(&self, message: rumqttc::Publish) {
if !rumqttc::matches( if !rumqttc::matches(&message.topic, &self.config.mqtt.topic) {
str::from_utf8(&message.topic).expect("Topic should be valid"),
&self.config.mqtt.topic,
) {
return; return;
} }
-47
View File
@@ -2,7 +2,6 @@ use std::net::SocketAddr;
use anyhow::Result; use anyhow::Result;
use async_trait::async_trait; use async_trait::async_trait;
use automation_lib::lua::traits::PartialUserData;
use automation_macro::{Device, LuaDeviceConfig}; use automation_macro::{Device, LuaDeviceConfig};
use google_home::errors::ErrorCode; use google_home::errors::ErrorCode;
use google_home::traits::OnOff; use google_home::traits::OnOff;
@@ -26,7 +25,6 @@ crate::register_type!(Config);
#[derive(Debug, Clone, Device)] #[derive(Debug, Clone, Device)]
#[device(traits(OnOff))] #[device(traits(OnOff))]
#[device(extra_user_data = AllOn)]
pub struct HueGroup { pub struct HueGroup {
config: Config, config: Config,
} }
@@ -124,47 +122,6 @@ impl OnOff for HueGroup {
} }
} }
struct AllOn;
impl PartialUserData<HueGroup> for AllOn {
fn add_methods<M: mlua::UserDataMethods<HueGroup>>(methods: &mut M) {
methods.add_async_method("all_on", async |_lua, this, ()| {
let res = reqwest::Client::new()
.get(this.url_get_state())
.send()
.await;
match res {
Ok(res) => {
let status = res.status();
if !status.is_success() {
warn!(id = this.get_id(), "Status code is not success: {status}");
}
let on = match res.json::<message::Info>().await {
Ok(info) => info.all_on(),
Err(err) => {
error!(id = this.get_id(), "Failed to parse message: {err}");
return Ok(false);
}
};
return Ok(on);
}
Err(err) => error!(id = this.get_id(), "Error: {err}"),
}
Ok(false)
});
}
fn definitions() -> Option<String> {
Some(format!(
"---@async\n---@return boolean\nfunction {}:all_on() end\n",
<HueGroup as Typed>::type_name(),
))
}
}
mod message { mod message {
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@@ -207,9 +164,5 @@ mod message {
pub fn any_on(&self) -> bool { pub fn any_on(&self) -> bool {
self.state.any_on self.state.any_on
} }
pub fn all_on(&self) -> bool {
self.state.all_on
}
} }
} }
+9 -8
View File
@@ -98,10 +98,7 @@ impl LuaDeviceCreate for HueSwitch {
impl OnMqtt for HueSwitch { impl OnMqtt for HueSwitch {
async fn on_mqtt(&self, message: Publish) { async fn on_mqtt(&self, message: Publish) {
// Check if the message is from the device itself or from a remote // Check if the message is from the device itself or from a remote
if matches( if matches(&message.topic, &self.config.mqtt.topic) {
str::from_utf8(&message.topic).expect("Topic should be valid"),
&self.config.mqtt.topic,
) {
let message = match serde_json::from_slice::<State>(&message.payload) { let message = match serde_json::from_slice::<State>(&message.payload) {
Ok(message) => message, Ok(message) => message,
Err(err) => { Err(err) => {
@@ -125,11 +122,15 @@ impl OnMqtt for HueSwitch {
Action::LeftHold => self.config.left_hold_callback.call(self.clone()).await, Action::LeftHold => self.config.left_hold_callback.call(self.clone()).await,
Action::RightHold => self.config.right_hold_callback.call(self.clone()).await, Action::RightHold => self.config.right_hold_callback.call(self.clone()).await,
// If there is no hold action, the switch will act like a normal release // If there is no hold action, the switch will act like a normal release
Action::RightHoldRelease if self.config.right_hold_callback.is_empty() => { Action::RightHoldRelease => {
self.config.right_callback.call(self.clone()).await if self.config.right_hold_callback.is_empty() {
self.config.right_callback.call(self.clone()).await
}
} }
Action::LeftHoldRelease if self.config.left_hold_callback.is_empty() => { Action::LeftHoldRelease => {
self.config.left_callback.call(self.clone()).await if self.config.left_hold_callback.is_empty() {
self.config.left_callback.call(self.clone()).await
}
} }
_ => {} _ => {}
} }
+1 -4
View File
@@ -70,10 +70,7 @@ impl LuaDeviceCreate for IkeaRemote {
impl OnMqtt for IkeaRemote { impl OnMqtt for IkeaRemote {
async fn on_mqtt(&self, message: Publish) { async fn on_mqtt(&self, message: Publish) {
// Check if the message is from the deviec itself or from a remote // Check if the message is from the deviec itself or from a remote
if matches( if matches(&message.topic, &self.config.mqtt.topic) {
str::from_utf8(&message.topic).expect("Topic should be valid"),
&self.config.mqtt.topic,
) {
let message = match RemoteMessage::try_from(message) { let message = match RemoteMessage::try_from(message) {
Ok(message) => message, Ok(message) => message,
Err(err) => { Err(err) => {
-30
View File
@@ -1,7 +1,5 @@
#![feature(debug_closure_helpers)]
#![feature(iter_intersperse)] #![feature(iter_intersperse)]
mod air_filter; mod air_filter;
mod bambu;
mod contact_sensor; mod contact_sensor;
mod hue_bridge; mod hue_bridge;
mod hue_group; mod hue_group;
@@ -15,9 +13,6 @@ mod wake_on_lan;
mod washer; mod washer;
mod zigbee; mod zigbee;
use std::fmt;
use std::ops::{Deref, DerefMut};
use automation_lib::Module; use automation_lib::Module;
use automation_lib::device::{Device, LuaDeviceCreate}; use automation_lib::device::{Device, LuaDeviceCreate};
use tracing::{debug, warn}; use tracing::{debug, warn};
@@ -25,31 +20,6 @@ use tracing::{debug, warn};
type DeviceNameFn = fn() -> String; type DeviceNameFn = fn() -> String;
type RegisterDeviceFn = fn(lua: &mlua::Lua) -> mlua::Result<mlua::AnyUserData>; type RegisterDeviceFn = fn(lua: &mlua::Lua) -> mlua::Result<mlua::AnyUserData>;
#[derive(Clone)]
struct DebugWrap<T: Clone>(T);
impl<T: Clone> DerefMut for DebugWrap<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<T: Clone> Deref for DebugWrap<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<T: Clone> fmt::Debug for DebugWrap<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("DebugWrap")
.field_with(|f| f.write_str(stringify!(T)))
.finish()
}
}
pub struct RegisteredDevice { pub struct RegisteredDevice {
name_fn: DeviceNameFn, name_fn: DeviceNameFn,
register_fn: RegisterDeviceFn, register_fn: RegisterDeviceFn,
+1 -4
View File
@@ -85,10 +85,7 @@ impl Device for LightSensor {
#[async_trait] #[async_trait]
impl OnMqtt for LightSensor { impl OnMqtt for LightSensor {
async fn on_mqtt(&self, message: Publish) { async fn on_mqtt(&self, message: Publish) {
if !rumqttc::matches( if !rumqttc::matches(&message.topic, &self.config.mqtt.topic) {
str::from_utf8(&message.topic).expect("Topic should be valid"),
&self.config.mqtt.topic,
) {
return; return;
} }
+2 -7
View File
@@ -105,10 +105,7 @@ impl Device for Presence {
#[async_trait] #[async_trait]
impl OnMqtt for Presence { impl OnMqtt for Presence {
async fn on_mqtt(&self, message: Publish) { async fn on_mqtt(&self, message: Publish) {
if !rumqttc::matches( if !rumqttc::matches(&message.topic, &self.config.mqtt.topic) {
str::from_utf8(&message.topic).expect("Topic should be valid"),
&self.config.mqtt.topic,
) {
return; return;
} }
@@ -119,9 +116,7 @@ impl OnMqtt for Presence {
.find('+') .find('+')
.or(self.config.mqtt.topic.find('#')) .or(self.config.mqtt.topic.find('#'))
.expect("Presence::create fails if it does not contain wildcards"); .expect("Presence::create fails if it does not contain wildcards");
let device_name: String = str::from_utf8(&message.topic[offset..]) let device_name = message.topic[offset..].into();
.expect("Topic should be valid")
.into();
if message.payload.is_empty() { if message.payload.is_empty() {
// Remove the device from the map // Remove the device from the map
+1 -4
View File
@@ -66,10 +66,7 @@ impl Device for WakeOnLAN {
#[async_trait] #[async_trait]
impl OnMqtt for WakeOnLAN { impl OnMqtt for WakeOnLAN {
async fn on_mqtt(&self, message: Publish) { async fn on_mqtt(&self, message: Publish) {
if !rumqttc::matches( if !rumqttc::matches(&message.topic, &self.config.mqtt.topic) {
str::from_utf8(&message.topic).expect("Topic should be valid"),
&self.config.mqtt.topic,
) {
return; return;
} }
+1 -4
View File
@@ -89,10 +89,7 @@ const HYSTERESIS: isize = 10;
#[async_trait] #[async_trait]
impl OnMqtt for Washer { impl OnMqtt for Washer {
async fn on_mqtt(&self, message: Publish) { async fn on_mqtt(&self, message: Publish) {
if !rumqttc::matches( if !rumqttc::matches(&message.topic, &self.config.mqtt.topic) {
str::from_utf8(&message.topic).expect("Topic should be valid"),
&self.config.mqtt.topic,
) {
return; return;
} }
+10 -17
View File
@@ -1,4 +1,3 @@
use core::str;
use std::fmt::Debug; use std::fmt::Debug;
use std::ops::Deref; use std::ops::Deref;
use std::sync::Arc; use std::sync::Arc;
@@ -17,7 +16,7 @@ use google_home::errors::ErrorCode;
use google_home::traits::{Brightness, Color, ColorSetting, ColorTemperatureRange, OnOff}; use google_home::traits::{Brightness, Color, ColorSetting, ColorTemperatureRange, OnOff};
use google_home::types::Type; use google_home::types::Type;
use lua_typed::Typed; use lua_typed::Typed;
use rumqttc::{Publish, PublishOptions, matches}; use rumqttc::{Publish, matches};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::json; use serde_json::json;
use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard}; use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
@@ -178,10 +177,7 @@ where
impl OnMqtt for LightOnOff { impl OnMqtt for LightOnOff {
async fn on_mqtt(&self, message: Publish) { async fn on_mqtt(&self, message: Publish) {
// Check if the message is from the device itself or from a remote // Check if the message is from the device itself or from a remote
if matches( if matches(&message.topic, &self.config.mqtt.topic) {
str::from_utf8(&message.topic).expect("Topic should be valid"),
&self.config.mqtt.topic,
) {
let state = match serde_json::from_slice::<StateOnOff>(&message.payload) { let state = match serde_json::from_slice::<StateOnOff>(&message.payload) {
Ok(state) => state, Ok(state) => state,
Err(err) => { Err(err) => {
@@ -214,10 +210,7 @@ impl OnMqtt for LightOnOff {
impl OnMqtt for LightBrightness { impl OnMqtt for LightBrightness {
async fn on_mqtt(&self, message: Publish) { async fn on_mqtt(&self, message: Publish) {
// Check if the message is from the deviec itself or from a remote // Check if the message is from the deviec itself or from a remote
if matches( if matches(&message.topic, &self.config.mqtt.topic) {
str::from_utf8(&message.topic).expect("Topic should be valid"),
&self.config.mqtt.topic,
) {
let state = match serde_json::from_slice::<StateBrightness>(&message.payload) { let state = match serde_json::from_slice::<StateBrightness>(&message.payload) {
Ok(state) => state, Ok(state) => state,
Err(err) => { Err(err) => {
@@ -256,10 +249,7 @@ impl OnMqtt for LightBrightness {
impl OnMqtt for LightColorTemperature { impl OnMqtt for LightColorTemperature {
async fn on_mqtt(&self, message: Publish) { async fn on_mqtt(&self, message: Publish) {
// Check if the message is from the deviec itself or from a remote // Check if the message is from the deviec itself or from a remote
if matches( if matches(&message.topic, &self.config.mqtt.topic) {
str::from_utf8(&message.topic).expect("Topic should be valid"),
&self.config.mqtt.topic,
) {
let state = match serde_json::from_slice::<StateColorTemperature>(&message.payload) { let state = match serde_json::from_slice::<StateColorTemperature>(&message.payload) {
Ok(state) => state, Ok(state) => state,
Err(err) => { Err(err) => {
@@ -352,8 +342,9 @@ where
.client .client
.publish( .publish(
&topic, &topic,
rumqttc::QoS::AtLeastOnce,
false,
serde_json::to_string(&message).unwrap(), serde_json::to_string(&message).unwrap(),
PublishOptions::at_least_once(),
) )
.await .await
.map_err(|err| warn!("Failed to update state on {topic}: {err}")) .map_err(|err| warn!("Failed to update state on {topic}: {err}"))
@@ -395,8 +386,9 @@ where
.client .client
.publish( .publish(
&topic, &topic,
rumqttc::QoS::AtLeastOnce,
false,
serde_json::to_string(&message).unwrap(), serde_json::to_string(&message).unwrap(),
PublishOptions::at_least_once(),
) )
.await .await
.map_err(|err| warn!("Failed to update state on {topic}: {err}")) .map_err(|err| warn!("Failed to update state on {topic}: {err}"))
@@ -442,8 +434,9 @@ where
.client .client
.publish( .publish(
&topic, &topic,
rumqttc::QoS::AtLeastOnce,
false,
serde_json::to_string(&message).unwrap(), serde_json::to_string(&message).unwrap(),
PublishOptions::at_least_once(),
) )
.await .await
.map_err(|err| warn!("Failed to update state on {topic}: {err}")) .map_err(|err| warn!("Failed to update state on {topic}: {err}"))
+5 -10
View File
@@ -16,7 +16,7 @@ use google_home::errors::ErrorCode;
use google_home::traits::OnOff; use google_home::traits::OnOff;
use google_home::types::Type; use google_home::types::Type;
use lua_typed::Typed; use lua_typed::Typed;
use rumqttc::{Publish, PublishOptions, matches}; use rumqttc::{Publish, matches};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::json; use serde_json::json;
use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard}; use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
@@ -162,10 +162,7 @@ where
impl OnMqtt for OutletOnOff { impl OnMqtt for OutletOnOff {
async fn on_mqtt(&self, message: Publish) { async fn on_mqtt(&self, message: Publish) {
// Check if the message is from the device itself or from a remote // Check if the message is from the device itself or from a remote
if matches( if matches(&message.topic, &self.config.mqtt.topic) {
str::from_utf8(&message.topic).expect("Topic should be valid"),
&self.config.mqtt.topic,
) {
let state = match serde_json::from_slice::<StateOnOff>(&message.payload) { let state = match serde_json::from_slice::<StateOnOff>(&message.payload) {
Ok(state) => state, Ok(state) => state,
Err(err) => { Err(err) => {
@@ -198,10 +195,7 @@ impl OnMqtt for OutletOnOff {
impl OnMqtt for OutletPower { impl OnMqtt for OutletPower {
async fn on_mqtt(&self, message: Publish) { async fn on_mqtt(&self, message: Publish) {
// Check if the message is from the deviec itself or from a remote // Check if the message is from the deviec itself or from a remote
if matches( if matches(&message.topic, &self.config.mqtt.topic) {
str::from_utf8(&message.topic).expect("Topic should be valid"),
&self.config.mqtt.topic,
) {
let state = match serde_json::from_slice::<StatePower>(&message.payload) { let state = match serde_json::from_slice::<StatePower>(&message.payload) {
Ok(state) => state, Ok(state) => state,
Err(err) => { Err(err) => {
@@ -290,8 +284,9 @@ where
.client .client
.publish( .publish(
&topic, &topic,
rumqttc::QoS::AtLeastOnce,
false,
serde_json::to_string(&message).unwrap(), serde_json::to_string(&message).unwrap(),
PublishOptions::at_least_once(),
) )
.await .await
.map_err(|err| warn!("Failed to update state on {topic}: {err}")) .map_err(|err| warn!("Failed to update state on {topic}: {err}"))
+4 -2
View File
@@ -4,7 +4,6 @@ version = "0.1.0"
edition = "2024" edition = "2024"
[dependencies] [dependencies]
automation_macro = { workspace = true }
async-trait = { workspace = true } async-trait = { workspace = true }
automation_cast = { workspace = true } automation_cast = { workspace = true }
bytes = { workspace = true } bytes = { workspace = true }
@@ -12,12 +11,15 @@ dyn-clone = { workspace = true }
futures = { workspace = true } futures = { workspace = true }
google_home = { workspace = true } google_home = { workspace = true }
hostname = { workspace = true } hostname = { workspace = true }
indexmap = { workspace = true }
inventory = { workspace = true } inventory = { workspace = true }
lua_typed = { workspace = true } lua_typed = { workspace = true }
mlua = { workspace = true } mlua = { workspace = true }
rumqttc-next = { workspace = true } rumqttc = { workspace = true }
serde = { workspace = true } serde = { workspace = true }
serde_json = { workspace = true } serde_json = { workspace = true }
thiserror = { workspace = true } thiserror = { workspace = true }
tokio = { workspace = true } tokio = { workspace = true }
tokio-cron-scheduler = { workspace = true }
tracing = { workspace = true } tracing = { workspace = true }
uuid = { workspace = true }
+28
View File
@@ -1,6 +1,34 @@
use std::time::Duration;
use lua_typed::Typed; use lua_typed::Typed;
use rumqttc::{MqttOptions, Transport};
use serde::Deserialize; use serde::Deserialize;
#[derive(Debug, Clone, Deserialize, Typed)]
pub struct MqttConfig {
pub host: String,
pub port: u16,
pub client_name: String,
pub username: String,
pub password: String,
#[serde(default)]
pub tls: bool,
}
impl From<MqttConfig> for MqttOptions {
fn from(value: MqttConfig) -> Self {
let mut mqtt_options = MqttOptions::new(value.client_name, value.host, value.port);
mqtt_options.set_credentials(value.username, value.password);
mqtt_options.set_keep_alive(Duration::from_secs(5));
if value.tls {
mqtt_options.set_transport(Transport::tls_with_default_config());
}
mqtt_options
}
}
#[derive(Debug, Clone, Deserialize, Typed)] #[derive(Debug, Clone, Deserialize, Typed)]
pub struct InfoConfig { pub struct InfoConfig {
pub name: String, pub name: String,
+2 -5
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> { fn from_lua(value: mlua::Value, _lua: &mlua::Lua) -> mlua::Result<Self> {
match value { match value {
mlua::Value::UserData(ud) => { mlua::Value::UserData(ud) => {
let ud = if ud.is::<Self>() { let ud = if ud.is::<Box<dyn Device>>() {
ud ud
} else { } else {
ud.call_method::<_>("__box", ())? ud.call_method::<_>("__box", ())?
@@ -36,10 +36,7 @@ impl mlua::FromLua for Box<dyn Device> {
let b = ud.borrow::<Self>()?.clone(); let b = ud.borrow::<Self>()?.clone();
Ok(b) Ok(b)
} }
_ => Err(mlua::Error::runtime(format!( _ => Err(mlua::Error::RuntimeError("Expected user data".into())),
"Expected user data, instead found: {}",
value.type_name()
))),
} }
} }
} }
+64 -1
View File
@@ -1,8 +1,13 @@
use std::collections::HashMap; use std::collections::HashMap;
use std::pin::Pin;
use std::sync::Arc; use std::sync::Arc;
use futures::Future;
use futures::future::join_all; use futures::future::join_all;
use lua_typed::Typed;
use mlua::FromLua;
use tokio::sync::{RwLock, RwLockReadGuard}; use tokio::sync::{RwLock, RwLockReadGuard};
use tokio_cron_scheduler::{Job, JobScheduler};
use tracing::{debug, instrument, trace}; use tracing::{debug, instrument, trace};
use crate::device::Device; use crate::device::Device;
@@ -10,10 +15,11 @@ use crate::event::{Event, EventChannel, OnMqtt};
pub type DeviceMap = HashMap<String, Box<dyn Device>>; pub type DeviceMap = HashMap<String, Box<dyn Device>>;
#[derive(Clone)] #[derive(Clone, FromLua)]
pub struct DeviceManager { pub struct DeviceManager {
devices: Arc<RwLock<DeviceMap>>, devices: Arc<RwLock<DeviceMap>>,
event_channel: EventChannel, event_channel: EventChannel,
scheduler: JobScheduler,
} }
impl DeviceManager { impl DeviceManager {
@@ -23,6 +29,7 @@ impl DeviceManager {
let device_manager = Self { let device_manager = Self {
devices: Arc::new(RwLock::new(HashMap::new())), devices: Arc::new(RwLock::new(HashMap::new())),
event_channel, event_channel,
scheduler: JobScheduler::new().await.unwrap(),
}; };
tokio::spawn({ tokio::spawn({
@@ -38,6 +45,8 @@ impl DeviceManager {
} }
}); });
device_manager.scheduler.start().await.unwrap();
device_manager device_manager
} }
@@ -87,3 +96,57 @@ impl DeviceManager {
} }
} }
} }
impl mlua::UserData for DeviceManager {
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) {
methods.add_async_method("add", async |_lua, this, device: Box<dyn Device>| {
this.add(device).await;
Ok(())
});
methods.add_async_method(
"schedule",
async |lua, this, (schedule, f): (String, mlua::Function)| {
debug!("schedule = {schedule}");
// This creates a function, that returns the actual job we want to run
let create_job = {
let lua = lua.clone();
move |uuid: uuid::Uuid,
_: tokio_cron_scheduler::JobScheduler|
-> Pin<Box<dyn Future<Output = ()> + Send>> {
let lua = lua.clone();
// Create the actual function we want to run on a schedule
let future = async move {
let f: mlua::Function =
lua.named_registry_value(uuid.to_string().as_str()).unwrap();
f.call_async::<()>(()).await.unwrap();
};
Box::pin(future)
}
};
let job = Job::new_async(schedule.as_str(), create_job).unwrap();
let uuid = this.scheduler.add(job).await.unwrap();
// Store the function in the registry
lua.set_named_registry_value(uuid.to_string().as_str(), f)
.unwrap();
Ok(())
},
);
methods.add_method("event_channel", |_lua, this, ()| Ok(this.event_channel()))
}
}
impl Typed for DeviceManager {
fn type_name() -> String {
"DeviceManager".into()
}
}
+1
View File
@@ -13,6 +13,7 @@ pub mod helpers;
pub mod lua; pub mod lua;
pub mod messages; pub mod messages;
pub mod mqtt; pub mod mqtt;
pub mod schedule;
type RegisterFn = fn(lua: &mlua::Lua) -> mlua::Result<mlua::Table>; type RegisterFn = fn(lua: &mlua::Lua) -> mlua::Result<mlua::Table>;
type DefinitionsFn = fn() -> String; type DefinitionsFn = fn() -> String;
+59 -35
View File
@@ -1,40 +1,15 @@
use std::ops::{Deref, DerefMut}; use std::ops::{Deref, DerefMut};
use automation_macro::LuaDeviceConfig;
use lua_typed::Typed; use lua_typed::Typed;
use mlua::FromLua; use mlua::{FromLua, LuaSerdeExt};
use rumqttc::{AsyncClient, Event, Incoming, MqttOptions, PublishOptions, Transport}; use rumqttc::{AsyncClient, Event, EventLoop, Incoming};
use serde::Deserialize;
use tracing::{debug, warn}; use tracing::{debug, warn};
use crate::Module;
use crate::config::MqttConfig;
use crate::device_manager::DeviceManager;
use crate::event::{self, EventChannel}; use crate::event::{self, EventChannel};
#[derive(Debug, Clone, LuaDeviceConfig, Deserialize, Typed)]
pub struct MqttConfig {
pub host: String,
pub port: u16,
pub client_name: String,
pub username: String,
pub password: String,
#[serde(default)]
#[typed(default)]
pub tls: bool,
}
impl From<MqttConfig> for MqttOptions {
fn from(value: MqttConfig) -> Self {
let mut mqtt_options = MqttOptions::new(value.client_name, (value.host, value.port));
mqtt_options.set_credentials(value.username, value.password);
mqtt_options.set_keep_alive(5);
if value.tls {
mqtt_options.set_transport(Transport::tls_with_default_config());
}
mqtt_options
}
}
#[derive(Debug, Clone, FromLua)] #[derive(Debug, Clone, FromLua)]
pub struct WrappedAsyncClient(pub AsyncClient); pub struct WrappedAsyncClient(pub AsyncClient);
@@ -59,6 +34,20 @@ impl Typed for WrappedAsyncClient {
Some(output) Some(output)
} }
fn generate_footer() -> Option<String> {
let mut output = String::new();
let type_name = Self::type_name();
output += &format!("mqtt.{type_name} = {{}}\n");
output += &format!("---@param device_manager {}\n", DeviceManager::type_name());
output += &format!("---@param config {}\n", MqttConfig::type_name());
output += &format!("---@return {type_name}\n");
output += "function mqtt.new(device_manager, config) end\n";
Some(output)
}
} }
impl Deref for WrappedAsyncClient { impl Deref for WrappedAsyncClient {
@@ -91,7 +80,7 @@ impl mlua::UserData for WrappedAsyncClient {
debug!("message = {message}"); debug!("message = {message}");
this.0 this.0
.publish(topic, message, PublishOptions::at_least_once().retained()) .publish(topic, rumqttc::QoS::AtLeastOnce, true, message)
.await .await
.unwrap(); .unwrap();
@@ -101,9 +90,8 @@ impl mlua::UserData for WrappedAsyncClient {
} }
} }
pub fn start(config: MqttConfig, event_channel: &EventChannel) -> WrappedAsyncClient { pub fn start(mut eventloop: EventLoop, event_channel: &EventChannel) {
let tx = event_channel.get_tx(); let tx = event_channel.get_tx();
let (client, mut eventloop) = AsyncClient::builder(config.into()).capacity(100).build();
tokio::spawn(async move { tokio::spawn(async move {
debug!("Listening for MQTT events"); debug!("Listening for MQTT events");
@@ -122,6 +110,42 @@ pub fn start(config: MqttConfig, event_channel: &EventChannel) -> WrappedAsyncCl
} }
} }
}); });
WrappedAsyncClient(client)
} }
fn create_module(lua: &mlua::Lua) -> mlua::Result<mlua::Table> {
let mqtt = lua.create_table()?;
let mqtt_new = lua.create_function(
move |lua, (device_manager, config): (DeviceManager, mlua::Value)| {
let event_channel = device_manager.event_channel();
let config: MqttConfig = lua.from_value(config)?;
// Create a mqtt client
// TODO: When starting up, the devices are not yet created, this could lead to a device being out of sync
let (client, eventloop) = AsyncClient::new(config.into(), 100);
start(eventloop, &event_channel);
Ok(WrappedAsyncClient(client))
},
)?;
mqtt.set("new", mqtt_new)?;
Ok(mqtt)
}
fn generate_definitions() -> String {
let mut output = String::new();
output += "---@meta\n\nlocal mqtt\n\n";
output += &MqttConfig::generate_full().expect("WrappedAsyncClient should have generate_full");
output += "\n";
output +=
&WrappedAsyncClient::generate_full().expect("WrappedAsyncClient should have generate_full");
output += "\n";
output += "return mqtt";
output
}
inventory::submit! {Module::new("automation:mqtt", create_module, Some(generate_definitions))}
+17
View File
@@ -0,0 +1,17 @@
use indexmap::IndexMap;
use serde::Deserialize;
#[derive(Debug, Deserialize, Hash, PartialEq, Eq, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum Action {
On,
Off,
}
pub type Schedule = IndexMap<String, IndexMap<Action, Vec<String>>>;
// #[derive(Debug, Deserialize)]
// pub struct Schedule {
// pub when: String,
// pub actions: IndexMap<Action, Vec<String>>,
// }
+1
View File
@@ -1,3 +1,4 @@
#![feature(iter_intersperse)]
#![feature(iterator_try_collect)] #![feature(iterator_try_collect)]
mod device; mod device;
mod lua_device_config; mod lua_device_config;
+1 -1
View File
@@ -182,7 +182,7 @@ fn field_from_lua(field: &Field) -> TokenStream {
.iter() .iter()
.filter_map(|arg| match arg { .filter_map(|arg| match arg {
Argument::Flatten { .. } => Some(quote! { Argument::Flatten { .. } => Some(quote! {
mlua::LuaSerdeExt::from_value_with(lua, value.clone(), mlua::serde::DeserializeOptions::new().deny_unsupported_types(false))? mlua::LuaSerdeExt::from_value_with(lua, value.clone(), mlua::DeserializeOptions::new().deny_unsupported_types(false))?
}), }),
Argument::FromLua { .. } => Some(quote! { Argument::FromLua { .. } => Some(quote! {
if table.contains_key(#table_name)? { if table.contains_key(#table_name)? {
+758
View File
@@ -0,0 +1,758 @@
local devices = require("automation:devices")
local device_manager = require("automation:device_manager")
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("Running @" .. host)
--- @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
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",
})
local devs = {}
function devs:add(device)
table.insert(self, device)
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,
})
devs:add(ntfy)
--- @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
device_manager:schedule("0 0 21 */1 * *", function()
-- 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)
--- @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",
message = presence and "Home" or "Away",
tags = { "house" },
priority = "low",
actions = {
{
action = "broadcast",
extras = {
cmd = "presence",
state = presence and "0" or "1",
},
label = presence and "Set away" or "Set home",
clear = true,
},
},
})
end)
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 = {}
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)
--- @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 OnLight
--- @field [integer] fun(light: boolean)
local on_light = {}
--- @param f fun(light: boolean)
function on_light:add(f)
self[#self + 1] = f
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(),
})
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,
},
})
devs:add(hue_bridge)
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",
})
devs:add(kitchen_lights)
local living_lights = devices.HueGroup.new({
identifier = "living_lights",
ip = hue_ip,
login = hue_token,
group_id = 1,
scene_id = "SNZw7jUhQ3cXSjkj",
})
devs:add(living_lights)
local living_lights_relax = devices.HueGroup.new({
identifier = "living_lights",
ip = hue_ip,
login = hue_token,
group_id = 1,
scene_id = "eRJ3fvGHCcb6yNw",
})
devs:add(living_lights_relax)
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,
}))
--- @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",
name = "Kettle",
room = "Kitchen",
topic = mqtt_z2m("kitchen/kettle"),
client = mqtt_client,
callback = kettle_timeout(),
})
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,
}))
--- @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",
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,
}))
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",
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_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",
topic = mqtt_z2m("hallway/storage"),
client = mqtt_client,
callback = hallway_light_automation:light_callback(),
})
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)
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,
}
---@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
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",
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)
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",
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,
}))
device_manager:schedule("0 0 19 * * *", function()
bedroom_air_filter:set_on(true)
end)
device_manager:schedule("0 0 20 * * *", function()
bedroom_air_filter:set_on(false)
end)
---@type Config
return {
fulfillment = {
openid_url = "https://login.huizinga.dev/api/oidc",
},
devices = devs,
}
-47
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
-32
View File
@@ -1,32 +0,0 @@
local utils = require("automation:utils")
local secrets = require("automation:secrets")
local host = utils.get_hostname()
print("Lua " .. _VERSION .. " running on " .. utils.get_hostname())
---@type Config
return {
fulfillment = {
openid_url = "https://login.huizinga.dev/api/oidc",
},
mqtt = {
host = ((host == "zeus" or host == "hephaestus") and "olympus.huizinga.lan") or "mosquitto",
port = 8883,
client_name = "automation-" .. host,
username = "mqtt",
password = secrets.mqtt_password,
tls = false,
},
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"),
},
}
-35
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
-85
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
-49
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
-41
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
-44
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
-34
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
-80
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
-12
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"),
}
-40
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
-109
View File
@@ -1,109 +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",
})
local wardrobe_light = devices.HueGroup.new({
identifier = "bedroom_lights_wardrobe",
ip = hue_bridge.ip,
login = hue_bridge.token,
group_id = 3,
scene_id = "1IDvpsN2YLZsDV95",
})
air_filter = devices.AirFilter.new({
name = "Air Filter",
room = "Bedroom",
url = "http://10.0.0.103",
})
local wardrobe_door = devices.ContactSensor.new({
name = "Wardrobe Door",
room = "Bedroom",
sensor_type = "Door",
topic = helper.mqtt_z2m("bedroom/wardrobe_door"),
client = mqtt_client,
callback = function(_, open)
-- Technically this has an edge case where if one of the spots is
-- on, but that is not something I ever do
if not lights:all_on() then
wardrobe_light:set_on(open)
end
end,
battery_callback = battery.callback,
})
local switch = devices.HueSwitch.new({
name = "Switch",
room = "Bedroom",
client = mqtt_client,
topic = helper.mqtt_z2m("bedroom/switch"),
left_callback = function()
local on = not lights:all_on()
lights:set_on(on)
-- This is a bit janky as the light will start to dim before turning
-- back on, however this is really and edge case that probably won't
-- happen often, so for now it's fine
if not on and wardrobe_door:open_percent() == 100 then
wardrobe_light:set_on(true)
end
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,
wardrobe_door,
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
-64
View File
@@ -1,64 +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")
local secrets = require("automation:secrets")
--- @type Module
local module = {}
function module.setup(mqtt_client)
local light = nil
local bambu = devices.Bambu.new({
host = "10.0.0.108",
device_id = secrets.printer_device_id,
access_code = secrets.printer_access_code,
callbacks = {
connected = function(self)
if light ~= nil then
self:set_on(light:on())
end
end,
},
})
light = devices.LightOnOff.new({
name = "Light",
room = "Guest Room",
topic = helper.mqtt_z2m("guest/light"),
client = mqtt_client,
callback = function(_, state)
bambu:set_on(state.state)
end,
})
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,
bambu,
}
end
return module
-105
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
-48
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
-71
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
-126
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
-41
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
-69
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
-43
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
+12
View File
@@ -0,0 +1,12 @@
---@meta
---@class DeviceManager
local DeviceManager
---@param device DeviceInterface
function DeviceManager:add(device) end
---@param cron string
---@param callback fun()
function DeviceManager:schedule(cron, callback) end
return DeviceManager
+43 -65
View File
@@ -6,9 +6,9 @@ local devices
---@class Action ---@class Action
---@field action ---@field action
---| "broadcast" ---| "broadcast"
---@field extras (table<string, string>)? ---@field extras table<string, string>?
---@field label string ---@field label string
---@field clear (boolean)? ---@field clear boolean?
local Action local Action
---@class AirFilter: DeviceInterface, OnOffInterface ---@class AirFilter: DeviceInterface, OnOffInterface
@@ -20,68 +20,49 @@ function devices.AirFilter.new(config) end
---@class AirFilterConfig ---@class AirFilterConfig
---@field name string ---@field name string
---@field room (string)? ---@field room string?
---@field url string ---@field url string
local AirFilterConfig local AirFilterConfig
---@class Bambu: DeviceInterface, OnOffInterface
local Bambu
devices.Bambu = {}
---@param config BambuConfig
---@return Bambu
function devices.Bambu.new(config) end
---@class BambuCallbacks
---@field state (fun(_: Bambu) | fun(_: Bambu)[])?
---@field connected (fun(_: Bambu) | fun(_: Bambu)[])?
local BambuCallbacks
---@class BambuConfig
---@field host string
---@field device_id string
---@field access_code string
---@field callbacks BambuCallbacks
local BambuConfig
---@class ConfigLightLightStateBrightness ---@class ConfigLightLightStateBrightness
---@field name string ---@field name string
---@field room (string)? ---@field room string?
---@field topic string ---@field topic string
---@field callback (fun(_: LightBrightness, _: LightStateBrightness) | fun(_: LightBrightness, _: LightStateBrightness)[])? ---@field callback fun(_: LightBrightness, _: LightStateBrightness) | fun(_: LightBrightness, _: LightStateBrightness)[]?
---@field client (AsyncClient)? ---@field client AsyncClient?
local ConfigLightLightStateBrightness local ConfigLightLightStateBrightness
---@class ConfigLightLightStateColorTemperature ---@class ConfigLightLightStateColorTemperature
---@field name string ---@field name string
---@field room (string)? ---@field room string?
---@field topic string ---@field topic string
---@field callback (fun(_: LightColorTemperature, _: LightStateColorTemperature) | fun(_: LightColorTemperature, _: LightStateColorTemperature)[])? ---@field callback fun(_: LightColorTemperature, _: LightStateColorTemperature) | fun(_: LightColorTemperature, _: LightStateColorTemperature)[]?
---@field client (AsyncClient)? ---@field client AsyncClient?
local ConfigLightLightStateColorTemperature local ConfigLightLightStateColorTemperature
---@class ConfigLightLightStateOnOff ---@class ConfigLightLightStateOnOff
---@field name string ---@field name string
---@field room (string)? ---@field room string?
---@field topic string ---@field topic string
---@field callback (fun(_: LightOnOff, _: LightStateOnOff) | fun(_: LightOnOff, _: LightStateOnOff)[])? ---@field callback fun(_: LightOnOff, _: LightStateOnOff) | fun(_: LightOnOff, _: LightStateOnOff)[]?
---@field client (AsyncClient)? ---@field client AsyncClient?
local ConfigLightLightStateOnOff local ConfigLightLightStateOnOff
---@class ConfigOutletOutletStateOnOff ---@class ConfigOutletOutletStateOnOff
---@field name string ---@field name string
---@field room (string)? ---@field room string?
---@field topic string ---@field topic string
---@field outlet_type (OutletType)? ---@field outlet_type OutletType?
---@field callback (fun(_: OutletOnOff, _: OutletStateOnOff) | fun(_: OutletOnOff, _: OutletStateOnOff)[])? ---@field callback fun(_: OutletOnOff, _: OutletStateOnOff) | fun(_: OutletOnOff, _: OutletStateOnOff)[]?
---@field client AsyncClient ---@field client AsyncClient
local ConfigOutletOutletStateOnOff local ConfigOutletOutletStateOnOff
---@class ConfigOutletOutletStatePower ---@class ConfigOutletOutletStatePower
---@field name string ---@field name string
---@field room (string)? ---@field room string?
---@field topic string ---@field topic string
---@field outlet_type (OutletType)? ---@field outlet_type OutletType?
---@field callback (fun(_: OutletPower, _: OutletStatePower) | fun(_: OutletPower, _: OutletStatePower)[])? ---@field callback fun(_: OutletPower, _: OutletStatePower) | fun(_: OutletPower, _: OutletStatePower)[]?
---@field client AsyncClient ---@field client AsyncClient
local ConfigOutletOutletStatePower local ConfigOutletOutletStatePower
@@ -94,12 +75,12 @@ function devices.ContactSensor.new(config) end
---@class ContactSensorConfig ---@class ContactSensorConfig
---@field name string ---@field name string
---@field room (string)? ---@field room string?
---@field topic string ---@field topic string
---@field sensor_type (SensorType)? ---@field sensor_type SensorType?
---@field callback (fun(_: ContactSensor, _: boolean) | fun(_: ContactSensor, _: boolean)[])? ---@field callback fun(_: ContactSensor, _: boolean) | fun(_: ContactSensor, _: boolean)[]?
---@field battery_callback (fun(_: ContactSensor, _: number) | fun(_: ContactSensor, _: number)[])? ---@field battery_callback fun(_: ContactSensor, _: number) | fun(_: ContactSensor, _: number)[]?
---@field client (AsyncClient)? ---@field client AsyncClient?
local ContactSensorConfig local ContactSensorConfig
---@alias Flag ---@alias Flag
@@ -135,9 +116,6 @@ devices.HueGroup = {}
---@param config HueGroupConfig ---@param config HueGroupConfig
---@return HueGroup ---@return HueGroup
function devices.HueGroup.new(config) end function devices.HueGroup.new(config) end
---@async
---@return boolean
function HueGroup:all_on() end
---@class HueGroupConfig ---@class HueGroupConfig
---@field identifier string ---@field identifier string
@@ -156,14 +134,14 @@ function devices.HueSwitch.new(config) end
---@class HueSwitchConfig ---@class HueSwitchConfig
---@field name string ---@field name string
---@field room (string)? ---@field room string?
---@field topic string ---@field topic string
---@field client AsyncClient ---@field client AsyncClient
---@field left_callback (fun(_: HueSwitch) | fun(_: HueSwitch)[])? ---@field left_callback fun(_: HueSwitch) | fun(_: HueSwitch)[]?
---@field right_callback (fun(_: HueSwitch) | fun(_: HueSwitch)[])? ---@field right_callback fun(_: HueSwitch) | fun(_: HueSwitch)[]?
---@field left_hold_callback (fun(_: HueSwitch) | fun(_: HueSwitch)[])? ---@field left_hold_callback fun(_: HueSwitch) | fun(_: HueSwitch)[]?
---@field right_hold_callback (fun(_: HueSwitch) | fun(_: HueSwitch)[])? ---@field right_hold_callback fun(_: HueSwitch) | fun(_: HueSwitch)[]?
---@field battery_callback (fun(_: HueSwitch, _: number) | fun(_: HueSwitch, _: number)[])? ---@field battery_callback fun(_: HueSwitch, _: number) | fun(_: HueSwitch, _: number)[]?
local HueSwitchConfig local HueSwitchConfig
---@class IkeaRemote: DeviceInterface ---@class IkeaRemote: DeviceInterface
@@ -175,12 +153,12 @@ function devices.IkeaRemote.new(config) end
---@class IkeaRemoteConfig ---@class IkeaRemoteConfig
---@field name string ---@field name string
---@field room (string)? ---@field room string?
---@field single_button (boolean)? ---@field single_button boolean?
---@field topic string ---@field topic string
---@field client AsyncClient ---@field client AsyncClient
---@field callback (fun(_: IkeaRemote, _: boolean) | fun(_: IkeaRemote, _: boolean)[])? ---@field callback fun(_: IkeaRemote, _: boolean) | fun(_: IkeaRemote, _: boolean)[]?
---@field battery_callback (fun(_: IkeaRemote, _: number) | fun(_: IkeaRemote, _: number)[])? ---@field battery_callback fun(_: IkeaRemote, _: number) | fun(_: IkeaRemote, _: number)[]?
local IkeaRemoteConfig local IkeaRemoteConfig
---@class KasaOutlet: DeviceInterface, OnOffInterface ---@class KasaOutlet: DeviceInterface, OnOffInterface
@@ -228,7 +206,7 @@ function devices.LightSensor.new(config) end
---@field topic string ---@field topic string
---@field min integer ---@field min integer
---@field max integer ---@field max integer
---@field callback (fun(_: LightSensor, _: boolean) | fun(_: LightSensor, _: boolean)[])? ---@field callback fun(_: LightSensor, _: boolean) | fun(_: LightSensor, _: boolean)[]?
---@field client AsyncClient ---@field client AsyncClient
local LightSensorConfig local LightSensorConfig
@@ -249,10 +227,10 @@ local LightStateOnOff
---@class Notification ---@class Notification
---@field title string ---@field title string
---@field message (string)? ---@field message string?
---@field tags ((string)[])? ---@field tags string[]?
---@field priority (Priority)? ---@field priority Priority?
---@field actions ((Action)[])? ---@field actions Action[]?
local Notification local Notification
---@class Ntfy: DeviceInterface ---@class Ntfy: DeviceInterface
@@ -266,7 +244,7 @@ function devices.Ntfy.new(config) end
function Ntfy:send_notification(notification) end function Ntfy:send_notification(notification) end
---@class NtfyConfig ---@class NtfyConfig
---@field url (string)? ---@field url string?
---@field topic string ---@field topic string
local NtfyConfig local NtfyConfig
@@ -309,7 +287,7 @@ function Presence:overall_presence() end
---@class PresenceConfig ---@class PresenceConfig
---@field topic string ---@field topic string
---@field callback (fun(_: Presence, _: boolean) | fun(_: Presence, _: boolean)[])? ---@field callback fun(_: Presence, _: boolean) | fun(_: Presence, _: boolean)[]?
---@field client AsyncClient ---@field client AsyncClient
local PresenceConfig local PresenceConfig
@@ -343,16 +321,16 @@ function devices.Washer.new(config) end
---@field identifier string ---@field identifier string
---@field topic string ---@field topic string
---@field threshold number ---@field threshold number
---@field done_callback (fun(_: Washer) | fun(_: Washer)[])? ---@field done_callback fun(_: Washer) | fun(_: Washer)[]?
---@field client AsyncClient ---@field client AsyncClient
local WasherConfig local WasherConfig
---@class WolConfig ---@class WolConfig
---@field name string ---@field name string
---@field room (string)? ---@field room string?
---@field topic string ---@field topic string
---@field mac_address string ---@field mac_address string
---@field broadcast_ip (string)? ---@field broadcast_ip string?
---@field client AsyncClient ---@field client AsyncClient
local WolConfig local WolConfig
+27
View File
@@ -0,0 +1,27 @@
-- DO NOT MODIFY, FILE IS AUTOMATICALLY GENERATED
---@meta
local mqtt
---@class MqttConfig
---@field host string
---@field port integer
---@field client_name string
---@field username string
---@field password string
---@field tls boolean
local MqttConfig
---@class AsyncClient
local AsyncClient
---@async
---@param topic string
---@param message table?
function AsyncClient:send_message(topic, message) end
mqtt.AsyncClient = {}
---@param device_manager DeviceManager
---@param config MqttConfig
---@return AsyncClient
function mqtt.new(device_manager, config) end
return mqtt
+3 -31
View File
@@ -3,39 +3,11 @@
---@class FulfillmentConfig ---@class FulfillmentConfig
---@field openid_url string ---@field openid_url string
---@field ip (string)? ---@field ip string?
---@field port (integer)? ---@field port integer?
local FulfillmentConfig local FulfillmentConfig
---@class Config ---@class Config
---@field fulfillment FulfillmentConfig ---@field fulfillment FulfillmentConfig
---@field modules (Module)[] ---@field devices DeviceInterface[]
---@field mqtt MqttConfig
local Config 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
---@class MqttConfig
---@field host string
---@field port integer
---@field client_name string
---@field username string
---@field password string
---@field tls (boolean)?
local MqttConfig
---@class AsyncClient
local AsyncClient
---@async
---@param topic string
---@param message table?
function AsyncClient:send_message(topic, message) end
-20
View File
@@ -1,20 +0,0 @@
variable "TAG_BASE" {}
variable "RELEASE_VERSION" {}
group "default" {
targets = ["automation"]
}
target "docker-metadata-action" {
tags = []
}
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}"
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
[toolchain] [toolchain]
channel = "nightly-2026-05-12" channel = "nightly-2025-08-20"
components = ["rustfmt", "clippy", "rust-analyzer"] components = ["rustfmt", "clippy", "rust-analyzer"]
profile = "minimal" profile = "minimal"
+3 -7
View File
@@ -10,7 +10,6 @@ use automation::secret::EnvironmentSecretFile;
use automation::version::VERSION; use automation::version::VERSION;
use automation::web::{ApiError, User}; use automation::web::{ApiError, User};
use automation_lib::device_manager::DeviceManager; use automation_lib::device_manager::DeviceManager;
use automation_lib::mqtt;
use axum::extract::{FromRef, State}; use axum::extract::{FromRef, State};
use axum::http::StatusCode; use axum::http::StatusCode;
use axum::routing::post; use axum::routing::post;
@@ -131,21 +130,18 @@ async fn app() -> anyhow::Result<()> {
automation_lib::load_modules(&lua)?; automation_lib::load_modules(&lua)?;
lua.register_module("automation:device_manager", device_manager.clone())?;
lua.register_module("automation:variables", lua.to_value(&setup.variables)?)?; lua.register_module("automation:variables", lua.to_value(&setup.variables)?)?;
lua.register_module("automation:secrets", lua.to_value(&setup.secrets)?)?; lua.register_module("automation:secrets", lua.to_value(&setup.secrets)?)?;
let entrypoint = Path::new(&setup.entrypoint); let entrypoint = Path::new(&setup.entrypoint);
let config: Config = lua.load(entrypoint).eval_async().await?; let config: Config = lua.load(entrypoint).eval_async().await?;
let mqtt_client = mqtt::start(config.mqtt, &device_manager.event_channel()); for device in config.devices {
let resolved = config.modules.resolve(&lua, &mqtt_client).await?;
for device in resolved.devices {
device_manager.add(device).await; device_manager.add(device).await;
} }
resolved.scheduler.start().await?;
// Create google home fulfillment route // Create google home fulfillment route
let fulfillment = Router::new().route("/google_home", post(fulfillment)); let fulfillment = Router::new().route("/google_home", post(fulfillment));
+14 -2
View File
@@ -1,8 +1,9 @@
use std::fs::{self, File}; use std::fs::{self, File};
use std::io::Write; use std::io::Write;
use automation::config::generate_definitions; use automation::config::{Config, FulfillmentConfig};
use automation_lib::Module; use automation_lib::Module;
use lua_typed::Typed;
use tracing::{info, warn}; use tracing::{info, warn};
extern crate automation_devices; extern crate automation_devices;
@@ -25,6 +26,17 @@ fn write_definitions(filename: &str, definitions: &str) -> std::io::Result<()> {
Ok(()) 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("FulfillmentConfig should have a definition");
output
}
fn main() -> std::io::Result<()> { fn main() -> std::io::Result<()> {
tracing_subscriber::fmt::init(); tracing_subscriber::fmt::init();
@@ -39,7 +51,7 @@ fn main() -> std::io::Result<()> {
} }
} }
write_definitions("config.lua", &generate_definitions())?; write_definitions("config.lua", &config_definitions())?;
Ok(()) Ok(())
} }
+3 -239
View File
@@ -1,17 +1,11 @@
use std::collections::{HashMap, VecDeque}; use std::collections::HashMap;
use std::net::{Ipv4Addr, SocketAddr}; use std::net::{Ipv4Addr, SocketAddr};
use std::ops::Deref;
use automation_lib::action_callback::ActionCallback;
use automation_lib::device::Device; use automation_lib::device::Device;
use automation_lib::mqtt::{MqttConfig, WrappedAsyncClient};
use automation_macro::LuaDeviceConfig; use automation_macro::LuaDeviceConfig;
use lua_typed::Typed; use lua_typed::Typed;
use mlua::FromLua;
use serde::Deserialize; use serde::Deserialize;
use crate::schedule::Scheduler;
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
pub struct Setup { pub struct Setup {
#[serde(default = "default_entrypoint")] #[serde(default = "default_entrypoint")]
@@ -23,7 +17,7 @@ pub struct Setup {
} }
fn default_entrypoint() -> String { fn default_entrypoint() -> String {
"./config/config.lua".into() "./config.lua".into()
} }
#[derive(Debug, Deserialize, Typed)] #[derive(Debug, Deserialize, Typed)]
@@ -37,219 +31,11 @@ pub struct FulfillmentConfig {
pub port: u16, 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<()>>);
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(
self,
lua: &mlua::Lua,
client: &WrappedAsyncClient,
) -> mlua::Result<Resolved> {
let mut devices = Vec::new();
let mut scheduler = Scheduler::default();
let mut modules: VecDeque<_> = self.0.into();
loop {
let Some(module) = modules.pop_front() else {
break;
};
modules.extend(module.modules);
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",
));
}
}
devices.extend(module.devices);
for (cron, f) in module.schedule {
scheduler.add_job(cron, f);
}
}
Ok(Resolved { devices, scheduler })
}
}
#[derive(Debug, Default)]
pub struct Resolved {
pub devices: Vec<Box<dyn Device>>,
pub scheduler: Scheduler,
}
#[derive(Debug, LuaDeviceConfig, Typed)] #[derive(Debug, LuaDeviceConfig, Typed)]
pub struct Config { pub struct Config {
pub fulfillment: FulfillmentConfig, pub fulfillment: FulfillmentConfig,
#[device_config(from_lua, default)] #[device_config(from_lua, default)]
pub modules: Modules, pub devices: Vec<Box<dyn Device>>,
#[device_config(from_lua)]
pub mqtt: MqttConfig,
} }
impl From<FulfillmentConfig> for SocketAddr { impl From<FulfillmentConfig> for SocketAddr {
@@ -264,25 +50,3 @@ fn default_fulfillment_ip() -> Ipv4Addr {
fn default_fulfillment_port() -> u16 { fn default_fulfillment_port() -> u16 {
7878 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
}
-1
View File
@@ -1,5 +1,4 @@
pub mod config; pub mod config;
pub mod schedule;
pub mod secret; pub mod secret;
pub mod version; pub mod version;
pub mod web; pub mod web;
-37
View File
@@ -1,37 +0,0 @@
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> {
let scheduler = JobScheduler::new().await?;
for (s, f) in self.jobs {
let job = {
move |_uuid, _lock| -> Pin<Box<dyn Future<Output = ()> + Send>> {
let f = f.clone();
Box::pin(async move {
f.call(()).await;
})
}
};
let job = Job::new_async(s, job)?;
scheduler.add(job).await?;
}
scheduler.start().await
}
}