Compare commits
81 Commits
a0eccc1a53
...
feature/im
| Author | SHA1 | Date | |
|---|---|---|---|
|
ad158f2c22
|
|||
|
f36adf2f19
|
|||
|
5947098bfb
|
|||
|
8a3143a3ea
|
|||
|
9546585440
|
|||
|
a938f3d71b
|
|||
|
a6c19eb9b4
|
|||
|
7db628709a
|
|||
|
bc75f7005c
|
|||
|
2056c6c70d
|
|||
|
2fe9fbadfb
|
|||
|
2db4af7427
|
|||
|
7b7279017f
|
|||
|
f05856cd0c
|
|||
|
02b6cf12a1
|
|||
|
02b87126e1
|
|||
|
1ffccd955c
|
|||
|
948380ea9b
|
|||
|
0c80cef5a1
|
|||
|
84e8942fc9
|
|||
|
b557afe2fc
|
|||
|
5801421378
|
|||
|
ba818c6b60
|
|||
|
a95574b731
|
|||
|
810fae8da5
|
|||
|
6fc3783d7a
|
|||
|
df64804b00
|
|||
|
11b9787890
|
|||
|
8961101fdf
|
|||
|
17a68e8991
|
|||
|
be1602d0e2
|
|||
|
9bddeae54e
|
|||
|
97b944874a
|
|||
|
54164c517b
|
|||
|
518abd169d
|
|||
|
30ea9b2737
|
|||
|
cd470cadaf
|
|||
|
4b76bde2a6
|
|||
|
006a561307
|
|||
|
745a1025bb
|
|||
|
45485fca37
|
|||
|
1532958a86
|
|||
|
76eb63cd97
|
|||
|
b784cfed4a
|
|||
|
06b3154733
|
|||
|
580a5187bd
|
|||
|
8982e9c165
|
|||
|
4e28ad0f85
|
|||
|
f0e4c9dd21
|
|||
|
5271e5ad81
|
|||
|
1d28b43264
|
|||
|
da04fad520
|
|||
|
84e4b30b6a
|
|||
|
95a8a377e8
|
|||
|
23355190ca
|
|||
|
2dbd491b81
|
|||
|
aad089aa10
|
|||
|
18e40726fe
|
|||
|
1925bac73c
|
|||
|
5383e7265d
|
|||
|
352654107a
|
|||
|
3a7f2f9bd7
|
|||
|
3be11b0c6a
|
|||
|
e880efe4cf
|
|||
|
e2fb680cd6
|
|||
|
edee032b91
|
|||
|
8bb17e1440
|
|||
|
ba37de3939
|
|||
|
22fee0ed77
|
|||
|
5aebab28ed
|
|||
|
e626caad8a
|
|||
|
0090a77dc1
|
|||
|
4d356001c3
|
|||
|
aa22132dd6
|
|||
|
1db269f65e
|
|||
|
77d7881a57
|
|||
|
f3b1854beb
|
|||
|
8109dcf2f5
|
|||
|
1b8566e593
|
|||
|
e21ea0f34e
|
|||
|
fb7e1f1472
|
2
.cargo/config.toml
Normal file
2
.cargo/config.toml
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
[env]
|
||||||
|
RUST_LOG = "automation=debug"
|
||||||
@@ -34,9 +34,9 @@ jobs:
|
|||||||
--name automation_rs \
|
--name automation_rs \
|
||||||
--network mqtt \
|
--network mqtt \
|
||||||
-e RUST_LOG=automation=debug \
|
-e RUST_LOG=automation=debug \
|
||||||
-e MQTT_PASSWORD=${{ secrets.MQTT_PASSWORD }} \
|
-e AUTOMATION__SECRETS__MQTT_PASSWORD=${{ secrets.MQTT_PASSWORD }} \
|
||||||
-e HUE_TOKEN=${{ secrets.HUE_TOKEN }} \
|
-e AUTOMATION__SECRETS__HUE_TOKEN=${{ secrets.HUE_TOKEN }} \
|
||||||
-e NTFY_TOPIC=${{ secrets.NTFY_TOPIC }} \
|
-e AUTOMATION__SECRETS__NTFY_TOPIC=${{ secrets.NTFY_TOPIC }} \
|
||||||
git.huizinga.dev/dreaded_x/automation_rs@${{ needs.build.outputs.digest }}
|
git.huizinga.dev/dreaded_x/automation_rs@${{ needs.build.outputs.digest }}
|
||||||
|
|
||||||
docker network connect web automation_rs
|
docker network connect web automation_rs
|
||||||
|
|||||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -1,2 +1,3 @@
|
|||||||
/target
|
/target
|
||||||
.env
|
.env
|
||||||
|
automation.toml
|
||||||
|
|||||||
@@ -1,6 +1,12 @@
|
|||||||
|
default_install_hook_types:
|
||||||
|
- pre-commit
|
||||||
|
- commit-msg
|
||||||
|
default_stages:
|
||||||
|
- pre-commit
|
||||||
|
|
||||||
repos:
|
repos:
|
||||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||||
rev: v4.6.0
|
rev: v6.0.0
|
||||||
hooks:
|
hooks:
|
||||||
- id: trailing-whitespace
|
- id: trailing-whitespace
|
||||||
- id: end-of-file-fixer
|
- id: end-of-file-fixer
|
||||||
@@ -11,13 +17,20 @@ repos:
|
|||||||
- id: check-added-large-files
|
- id: check-added-large-files
|
||||||
- id: check-merge-conflict
|
- id: check-merge-conflict
|
||||||
|
|
||||||
|
- repo: https://github.com/compilerla/conventional-pre-commit
|
||||||
|
rev: v4.2.0
|
||||||
|
hooks:
|
||||||
|
- id: conventional-pre-commit
|
||||||
|
stages: [commit-msg]
|
||||||
|
args: [--verbose]
|
||||||
|
|
||||||
- repo: https://github.com/JohnnyMorganz/StyLua
|
- repo: https://github.com/JohnnyMorganz/StyLua
|
||||||
rev: v0.20.0
|
rev: v2.1.0
|
||||||
hooks:
|
hooks:
|
||||||
- id: stylua
|
- id: stylua
|
||||||
|
|
||||||
- repo: https://github.com/crate-ci/typos
|
- repo: https://github.com/crate-ci/typos
|
||||||
rev: v1.21.0
|
rev: v1.36.1
|
||||||
hooks:
|
hooks:
|
||||||
- id: typos
|
- id: typos
|
||||||
args: ["--force-exclude"]
|
args: ["--force-exclude"]
|
||||||
@@ -44,24 +57,12 @@ repos:
|
|||||||
files: (\.rs|Cargo.lock)$
|
files: (\.rs|Cargo.lock)$
|
||||||
pass_filenames: false
|
pass_filenames: false
|
||||||
|
|
||||||
- id: audit
|
- id: generate_definitions
|
||||||
name: audit
|
name: generate definitions
|
||||||
description: Audit packages
|
description: Generate lua definitions
|
||||||
entry: cargo audit
|
entry: cargo run --bin generate_definitions
|
||||||
args: ["--deny", "warnings"]
|
|
||||||
language: system
|
language: system
|
||||||
pass_filenames: false
|
types: [rust]
|
||||||
verbose: true
|
|
||||||
always_run: true
|
|
||||||
|
|
||||||
- id: udeps
|
|
||||||
name: unused
|
|
||||||
description: Check for unused crates
|
|
||||||
entry: cargo udeps
|
|
||||||
args: ["--workspace"]
|
|
||||||
language: system
|
|
||||||
types: [file]
|
|
||||||
files: (\.rs|Cargo.lock)$
|
|
||||||
pass_filenames: false
|
pass_filenames: false
|
||||||
|
|
||||||
- id: test
|
- id: test
|
||||||
@@ -74,7 +75,27 @@ repos:
|
|||||||
files: (\.rs|Cargo.lock)$
|
files: (\.rs|Cargo.lock)$
|
||||||
pass_filenames: false
|
pass_filenames: false
|
||||||
|
|
||||||
|
- id: udeps
|
||||||
|
name: unused
|
||||||
|
description: Check for unused crates
|
||||||
|
entry: cargo udeps
|
||||||
|
args: ["--workspace"]
|
||||||
|
language: system
|
||||||
|
types: [file]
|
||||||
|
files: (\.rs|Cargo.lock)$
|
||||||
|
pass_filenames: false
|
||||||
|
|
||||||
|
- id: audit
|
||||||
|
name: audit
|
||||||
|
description: Audit packages
|
||||||
|
entry: cargo audit
|
||||||
|
args: ["--deny", "warnings"]
|
||||||
|
language: system
|
||||||
|
pass_filenames: false
|
||||||
|
verbose: true
|
||||||
|
always_run: true
|
||||||
|
|
||||||
- repo: https://github.com/hadolint/hadolint
|
- repo: https://github.com/hadolint/hadolint
|
||||||
rev: v2.12.0
|
rev: v2.13.1
|
||||||
hooks:
|
hooks:
|
||||||
- id: hadolint
|
- id: hadolint
|
||||||
|
|||||||
@@ -1,2 +0,0 @@
|
|||||||
[default.extend-words]
|
|
||||||
mosquitto = "mosquitto"
|
|
||||||
603
Cargo.lock
generated
603
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
119
Cargo.toml
119
Cargo.toml
@@ -2,19 +2,42 @@
|
|||||||
name = "automation"
|
name = "automation"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
default-run = "automation"
|
||||||
|
|
||||||
[workspace]
|
[workspace]
|
||||||
members = [
|
members = [
|
||||||
"automation_macro",
|
|
||||||
"automation_cast",
|
"automation_cast",
|
||||||
"google_home/google_home",
|
|
||||||
"google_home/google_home_macro",
|
|
||||||
"automation_devices",
|
"automation_devices",
|
||||||
"automation_lib",
|
"automation_lib",
|
||||||
|
"automation_macro",
|
||||||
|
"google_home/google_home",
|
||||||
|
"google_home/google_home_macro",
|
||||||
]
|
]
|
||||||
|
|
||||||
[workspace.dependencies]
|
[workspace.dependencies]
|
||||||
mlua = { version = "0.10.1", features = [
|
air_filter_types = { git = "https://git.huizinga.dev/Dreaded_X/airfilter", tag = "v0.4.4" }
|
||||||
|
anyhow = "1.0.99"
|
||||||
|
async-trait = "0.1.89"
|
||||||
|
automation_cast = { path = "./automation_cast" }
|
||||||
|
automation_devices = { path = "./automation_devices" }
|
||||||
|
automation_lib = { path = "./automation_lib" }
|
||||||
|
automation_macro = { path = "./automation_macro" }
|
||||||
|
axum = "0.8.4"
|
||||||
|
bytes = "1.10.1"
|
||||||
|
dyn-clone = "1.0.20"
|
||||||
|
eui48 = { version = "1.1.0", features = [
|
||||||
|
"disp_hexstring",
|
||||||
|
"serde",
|
||||||
|
], default-features = false }
|
||||||
|
futures = "0.3.31"
|
||||||
|
google_home = { path = "./google_home/google_home" }
|
||||||
|
google_home_macro = { path = "./google_home/google_home_macro" }
|
||||||
|
hostname = "0.4.1"
|
||||||
|
inventory = "0.3.21"
|
||||||
|
itertools = "0.14.0"
|
||||||
|
json_value_merge = "2.0.1"
|
||||||
|
lua_typed = { git = "https://git.huizinga.dev/Dreaded_X/lua_typed" }
|
||||||
|
mlua = { version = "0.11.3", features = [
|
||||||
"lua54",
|
"lua54",
|
||||||
"vendored",
|
"vendored",
|
||||||
"macros",
|
"macros",
|
||||||
@@ -22,67 +45,55 @@ mlua = { version = "0.10.1", features = [
|
|||||||
"async",
|
"async",
|
||||||
"send",
|
"send",
|
||||||
] }
|
] }
|
||||||
automation_macro = { path = "./automation_macro" }
|
proc-macro2 = "1.0.101"
|
||||||
automation_cast = { path = "./automation_cast" }
|
quote = "1.0.40"
|
||||||
automation_lib = { path = "./automation_lib" }
|
reqwest = { version = "0.12.23", features = [
|
||||||
automation_devices = { path = "./automation_devices" }
|
|
||||||
google_home = { path = "./google_home/google_home" }
|
|
||||||
google_home_macro = { path = "./google_home/google_home_macro" }
|
|
||||||
tokio = { version = "1", features = ["rt-multi-thread"] }
|
|
||||||
rumqttc = "0.24.0"
|
|
||||||
tracing = "0.1.37"
|
|
||||||
anyhow = "1.0.68"
|
|
||||||
async-trait = "0.1.83"
|
|
||||||
axum = "0.7.9"
|
|
||||||
bytes = "1.3.0"
|
|
||||||
dotenvy = "0.15.0"
|
|
||||||
dyn-clone = "1.0.17"
|
|
||||||
eui48 = { version = "1.1.0", features = [
|
|
||||||
"disp_hexstring",
|
|
||||||
"serde",
|
|
||||||
], default-features = false }
|
|
||||||
futures = "0.3.25"
|
|
||||||
hostname = "0.4.0"
|
|
||||||
indexmap = { version = "2.0.0", features = ["serde"] }
|
|
||||||
itertools = "0.13.0"
|
|
||||||
json_value_merge = "2.0.0"
|
|
||||||
proc-macro2 = "1.0.81"
|
|
||||||
quote = "1.0.36"
|
|
||||||
reqwest = { version = "0.12.9", features = [
|
|
||||||
"json",
|
"json",
|
||||||
"rustls-tls",
|
"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
|
||||||
serde = { version = "1.0.149", features = ["derive"] }
|
rumqttc = "0.24.0"
|
||||||
serde_json = "1.0.89"
|
serde = { version = "1.0.219", features = ["derive"] }
|
||||||
serde_repr = "0.1.10"
|
serde_json = "1.0.143"
|
||||||
syn = { version = "2.0.60", features = ["extra-traits", "full"] }
|
serde_repr = "0.1.20"
|
||||||
thiserror = "2.0.5"
|
syn = { version = "2.0.106" }
|
||||||
tokio-cron-scheduler = "0.13.0"
|
thiserror = "2.0.16"
|
||||||
tracing-subscriber = "0.3.16"
|
tokio = { version = "1", features = ["rt-multi-thread"] }
|
||||||
uuid = "1.8.0"
|
tokio-cron-scheduler = "0.15.0"
|
||||||
|
tracing = "0.1.41"
|
||||||
|
tracing-subscriber = "0.3.20"
|
||||||
wakey = "0.3.0"
|
wakey = "0.3.0"
|
||||||
air_filter_types = { git = "https://git.huizinga.dev/Dreaded_X/airfilter", tag = "v0.4.4" }
|
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
automation_lib = { workspace = true }
|
|
||||||
automation_devices = { workspace = true }
|
|
||||||
google_home = { workspace = true }
|
|
||||||
mlua = { workspace = true }
|
|
||||||
tokio = { workspace = true }
|
|
||||||
hostname = { workspace = true }
|
|
||||||
rumqttc = { workspace = true }
|
|
||||||
axum = { workspace = true }
|
|
||||||
tracing = { workspace = true }
|
|
||||||
anyhow = { workspace = true }
|
anyhow = { workspace = true }
|
||||||
dotenvy = { workspace = true }
|
async-trait = { workspace = true }
|
||||||
tracing-subscriber = { workspace = true }
|
automation_devices = { workspace = true }
|
||||||
serde = { workspace = true }
|
automation_lib = { workspace = true }
|
||||||
thiserror = { workspace = true }
|
automation_macro = { path = "./automation_macro" }
|
||||||
serde_json = { workspace = true }
|
axum = { workspace = true }
|
||||||
|
config = { version = "0.15.15", default-features = false, features = [
|
||||||
|
"async",
|
||||||
|
"toml",
|
||||||
|
] }
|
||||||
|
git-version = "0.3.9"
|
||||||
|
google_home = { workspace = true }
|
||||||
|
lua_typed = { workspace = true }
|
||||||
|
inventory = { workspace = true }
|
||||||
|
mlua = { workspace = true }
|
||||||
reqwest = { workspace = true }
|
reqwest = { workspace = true }
|
||||||
|
rumqttc = { workspace = true }
|
||||||
|
serde = { workspace = true }
|
||||||
|
serde_json = { workspace = true }
|
||||||
|
thiserror = { workspace = true }
|
||||||
|
tokio = { workspace = true }
|
||||||
|
tokio-cron-scheduler = { workspace = true }
|
||||||
|
tracing = { workspace = true }
|
||||||
|
tracing-subscriber = { 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" }
|
||||||
|
|
||||||
[profile.release]
|
[profile.release]
|
||||||
lto = true
|
lto = true
|
||||||
|
|
||||||
|
[package.metadata.typos.default.extend-words]
|
||||||
|
mosquitto = "mosquitto"
|
||||||
|
|||||||
@@ -21,6 +21,5 @@ RUN cargo auditable build --release
|
|||||||
|
|
||||||
FROM gcr.io/distroless/cc-debian12:nonroot AS runtime
|
FROM gcr.io/distroless/cc-debian12:nonroot AS runtime
|
||||||
COPY --from=builder /app/target/release/automation /app/automation
|
COPY --from=builder /app/target/release/automation /app/automation
|
||||||
ENV AUTOMATION_CONFIG=/app/config.lua
|
COPY ./config /app/config
|
||||||
COPY ./config.lua /app/config.lua
|
|
||||||
CMD [ "/app/automation" ]
|
CMD [ "/app/automation" ]
|
||||||
|
|||||||
@@ -3,6 +3,4 @@ name = "automation_cast"
|
|||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
|||||||
@@ -4,23 +4,24 @@ version = "0.1.0"
|
|||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
air_filter_types = { workspace = true }
|
||||||
|
anyhow = { workspace = true }
|
||||||
|
async-trait = { workspace = true }
|
||||||
automation_lib = { workspace = true }
|
automation_lib = { workspace = true }
|
||||||
automation_macro = { workspace = true }
|
automation_macro = { workspace = true }
|
||||||
google_home = { workspace = true }
|
|
||||||
mlua = { workspace = true }
|
|
||||||
async-trait = { workspace = true }
|
|
||||||
dyn-clone = { workspace = true }
|
|
||||||
rumqttc = { workspace = true }
|
|
||||||
tokio = { workspace = true }
|
|
||||||
serde_repr = { workspace = true }
|
|
||||||
tracing = { workspace = true }
|
|
||||||
serde_json = { workspace = true }
|
|
||||||
serde = { workspace = true }
|
|
||||||
reqwest = { workspace = true } # Use rustls, since the other packages also use rustls
|
|
||||||
anyhow = { workspace = true }
|
|
||||||
axum = { workspace = true }
|
|
||||||
bytes = { workspace = true }
|
bytes = { workspace = true }
|
||||||
thiserror = { workspace = true }
|
dyn-clone = { workspace = true }
|
||||||
eui48 = { workspace = true }
|
eui48 = { workspace = true }
|
||||||
|
google_home = { workspace = true }
|
||||||
|
inventory = { workspace = true }
|
||||||
|
lua_typed = { workspace = true }
|
||||||
|
mlua = { workspace = true }
|
||||||
|
reqwest = { workspace = true }
|
||||||
|
rumqttc = { workspace = true }
|
||||||
|
serde = { workspace = true }
|
||||||
|
serde_json = { workspace = true }
|
||||||
|
serde_repr = { workspace = true }
|
||||||
|
thiserror = { workspace = true }
|
||||||
|
tokio = { workspace = true }
|
||||||
|
tracing = { workspace = true }
|
||||||
wakey = { workspace = true }
|
wakey = { workspace = true }
|
||||||
air_filter_types = { workspace = true }
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use automation_lib::config::InfoConfig;
|
use automation_lib::config::InfoConfig;
|
||||||
use automation_lib::device::{Device, LuaDeviceCreate};
|
use automation_lib::device::{Device, LuaDeviceCreate};
|
||||||
use automation_macro::{LuaDevice, LuaDeviceConfig};
|
use automation_macro::{Device, LuaDeviceConfig};
|
||||||
use google_home::device::Name;
|
use google_home::device::Name;
|
||||||
use google_home::errors::ErrorCode;
|
use google_home::errors::ErrorCode;
|
||||||
use google_home::traits::{
|
use google_home::traits::{
|
||||||
@@ -9,21 +9,26 @@ use google_home::traits::{
|
|||||||
TemperatureUnit,
|
TemperatureUnit,
|
||||||
};
|
};
|
||||||
use google_home::types::Type;
|
use google_home::types::Type;
|
||||||
|
use lua_typed::Typed;
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
use tracing::{debug, trace};
|
use tracing::{debug, trace};
|
||||||
|
|
||||||
#[derive(Debug, Clone, LuaDeviceConfig)]
|
#[derive(Debug, Clone, LuaDeviceConfig, Typed)]
|
||||||
|
#[typed(as = "AirFilterConfig")]
|
||||||
pub struct Config {
|
pub struct Config {
|
||||||
#[device_config(flatten)]
|
#[device_config(flatten)]
|
||||||
|
#[typed(flatten)]
|
||||||
pub info: InfoConfig,
|
pub info: InfoConfig,
|
||||||
pub url: String,
|
pub url: String,
|
||||||
}
|
}
|
||||||
|
crate::register_type!(Config);
|
||||||
|
|
||||||
#[derive(Debug, Clone, LuaDevice)]
|
#[derive(Debug, Clone, Device)]
|
||||||
#[traits(OnOff)]
|
#[device(traits(OnOff))]
|
||||||
pub struct AirFilter {
|
pub struct AirFilter {
|
||||||
config: Config,
|
config: Config,
|
||||||
}
|
}
|
||||||
|
crate::register_device!(AirFilter);
|
||||||
|
|
||||||
#[derive(Debug, Error)]
|
#[derive(Debug, Error)]
|
||||||
pub enum Error {
|
pub enum Error {
|
||||||
|
|||||||
@@ -8,49 +8,63 @@ use automation_lib::error::DeviceConfigError;
|
|||||||
use automation_lib::event::OnMqtt;
|
use automation_lib::event::OnMqtt;
|
||||||
use automation_lib::messages::ContactMessage;
|
use automation_lib::messages::ContactMessage;
|
||||||
use automation_lib::mqtt::WrappedAsyncClient;
|
use automation_lib::mqtt::WrappedAsyncClient;
|
||||||
use automation_macro::{LuaDevice, LuaDeviceConfig};
|
use automation_macro::{Device, LuaDeviceConfig};
|
||||||
use google_home::device;
|
use google_home::device;
|
||||||
use google_home::errors::{DeviceError, ErrorCode};
|
use google_home::errors::{DeviceError, ErrorCode};
|
||||||
use google_home::traits::OpenClose;
|
use google_home::traits::OpenClose;
|
||||||
use google_home::types::Type;
|
use google_home::types::Type;
|
||||||
|
use lua_typed::Typed;
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
|
use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
|
||||||
use tracing::{debug, error, trace};
|
use tracing::{debug, error, trace};
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Copy)]
|
#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Copy, Typed)]
|
||||||
pub enum SensorType {
|
pub enum SensorType {
|
||||||
Door,
|
Door,
|
||||||
Drawer,
|
Drawer,
|
||||||
Window,
|
Window,
|
||||||
}
|
}
|
||||||
|
crate::register_type!(SensorType);
|
||||||
|
|
||||||
#[derive(Debug, Clone, LuaDeviceConfig)]
|
#[derive(Debug, Clone, LuaDeviceConfig, Typed)]
|
||||||
|
#[typed(as = "ContactSensorConfig")]
|
||||||
pub struct Config {
|
pub struct Config {
|
||||||
#[device_config(flatten)]
|
#[device_config(flatten)]
|
||||||
|
#[typed(flatten)]
|
||||||
pub info: InfoConfig,
|
pub info: InfoConfig,
|
||||||
#[device_config(flatten)]
|
#[device_config(flatten)]
|
||||||
|
#[typed(flatten)]
|
||||||
pub mqtt: MqttDeviceConfig,
|
pub mqtt: MqttDeviceConfig,
|
||||||
|
|
||||||
#[device_config(default(SensorType::Window))]
|
#[device_config(default(SensorType::Window))]
|
||||||
|
#[typed(default)]
|
||||||
pub sensor_type: SensorType,
|
pub sensor_type: SensorType,
|
||||||
|
|
||||||
#[device_config(from_lua, default)]
|
#[device_config(from_lua, default)]
|
||||||
pub callback: ActionCallback<ContactSensor, bool>,
|
#[typed(default)]
|
||||||
|
pub callback: ActionCallback<(ContactSensor, bool)>,
|
||||||
|
#[device_config(from_lua, default)]
|
||||||
|
#[typed(default)]
|
||||||
|
pub battery_callback: ActionCallback<(ContactSensor, f32)>,
|
||||||
|
|
||||||
#[device_config(from_lua)]
|
#[device_config(from_lua)]
|
||||||
|
#[typed(default)]
|
||||||
pub client: WrappedAsyncClient,
|
pub client: WrappedAsyncClient,
|
||||||
}
|
}
|
||||||
|
crate::register_type!(Config);
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
struct State {
|
struct State {
|
||||||
is_closed: bool,
|
is_closed: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, LuaDevice)]
|
#[derive(Debug, Clone, Device)]
|
||||||
#[traits(OpenClose)]
|
#[device(traits(OpenClose))]
|
||||||
pub struct ContactSensor {
|
pub struct ContactSensor {
|
||||||
config: Config,
|
config: Config,
|
||||||
state: Arc<RwLock<State>>,
|
state: Arc<RwLock<State>>,
|
||||||
}
|
}
|
||||||
|
crate::register_device!(ContactSensor);
|
||||||
|
|
||||||
impl ContactSensor {
|
impl ContactSensor {
|
||||||
async fn state(&self) -> RwLockReadGuard<'_, State> {
|
async fn state(&self) -> RwLockReadGuard<'_, State> {
|
||||||
@@ -149,21 +163,30 @@ impl OnMqtt for ContactSensor {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let is_closed = match ContactMessage::try_from(message) {
|
let message = match ContactMessage::try_from(message) {
|
||||||
Ok(state) => state.is_closed(),
|
Ok(message) => message,
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
error!(id = self.get_id(), "Failed to parse message: {err}");
|
error!(id = self.get_id(), "Failed to parse message: {err}");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if let Some(is_closed) = message.contact {
|
||||||
if is_closed == self.state().await.is_closed {
|
if is_closed == self.state().await.is_closed {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
self.config.callback.call(self, &!is_closed).await;
|
self.config.callback.call((self.clone(), !is_closed)).await;
|
||||||
|
|
||||||
debug!(id = self.get_id(), "Updating state to {is_closed}");
|
debug!(id = self.get_id(), "Updating state to {is_closed}");
|
||||||
self.state_mut().await.is_closed = is_closed;
|
self.state_mut().await.is_closed = is_closed;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if let Some(battery) = message.battery {
|
||||||
|
self.config
|
||||||
|
.battery_callback
|
||||||
|
.call((self.clone(), battery))
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,39 +3,71 @@ use std::net::SocketAddr;
|
|||||||
|
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use automation_lib::device::{Device, LuaDeviceCreate};
|
use automation_lib::device::{Device, LuaDeviceCreate};
|
||||||
use automation_lib::lua::traits::AddAdditionalMethods;
|
use automation_lib::lua::traits::PartialUserData;
|
||||||
use automation_macro::{LuaDevice, LuaDeviceConfig};
|
use automation_macro::{Device, LuaDeviceConfig};
|
||||||
|
use lua_typed::Typed;
|
||||||
use mlua::LuaSerdeExt;
|
use mlua::LuaSerdeExt;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use tracing::{error, trace, warn};
|
use tracing::{error, trace, warn};
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize, Typed)]
|
||||||
#[serde(rename_all = "snake_case")]
|
#[serde(rename_all = "snake_case")]
|
||||||
|
#[typed(rename_all = "snake_case")]
|
||||||
pub enum Flag {
|
pub enum Flag {
|
||||||
Presence,
|
Presence,
|
||||||
Darkness,
|
Darkness,
|
||||||
}
|
}
|
||||||
|
crate::register_type!(Flag);
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize)]
|
#[derive(Debug, Clone, Deserialize, Typed)]
|
||||||
pub struct FlagIDs {
|
pub struct FlagIDs {
|
||||||
presence: isize,
|
presence: isize,
|
||||||
darkness: isize,
|
darkness: isize,
|
||||||
}
|
}
|
||||||
|
crate::register_type!(FlagIDs);
|
||||||
|
|
||||||
#[derive(Debug, LuaDeviceConfig, Clone)]
|
#[derive(Debug, LuaDeviceConfig, Clone, Typed)]
|
||||||
|
#[typed(as = "HueBridgeConfig")]
|
||||||
pub struct Config {
|
pub struct Config {
|
||||||
pub identifier: String,
|
pub identifier: String,
|
||||||
#[device_config(rename("ip"), with(|ip| SocketAddr::new(ip, 80)))]
|
#[device_config(rename("ip"), with(|ip| SocketAddr::new(ip, 80)))]
|
||||||
|
#[typed(as = "ip")]
|
||||||
pub addr: SocketAddr,
|
pub addr: SocketAddr,
|
||||||
pub login: String,
|
pub login: String,
|
||||||
pub flags: FlagIDs,
|
pub flags: FlagIDs,
|
||||||
}
|
}
|
||||||
|
crate::register_type!(Config);
|
||||||
|
|
||||||
#[derive(Debug, Clone, LuaDevice)]
|
#[derive(Debug, Clone, Device)]
|
||||||
#[traits(AddAdditionalMethods)]
|
#[device(extra_user_data = SetFlag)]
|
||||||
pub struct HueBridge {
|
pub struct HueBridge {
|
||||||
config: Config,
|
config: Config,
|
||||||
}
|
}
|
||||||
|
crate::register_device!(HueBridge);
|
||||||
|
|
||||||
|
struct SetFlag;
|
||||||
|
impl PartialUserData<HueBridge> for SetFlag {
|
||||||
|
fn add_methods<M: mlua::UserDataMethods<HueBridge>>(methods: &mut M) {
|
||||||
|
methods.add_async_method(
|
||||||
|
"set_flag",
|
||||||
|
async |lua, this, (flag, value): (mlua::Value, bool)| {
|
||||||
|
let flag: Flag = lua.from_value(flag)?;
|
||||||
|
|
||||||
|
this.set_flag(flag, value).await;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn definitions() -> Option<String> {
|
||||||
|
Some(format!(
|
||||||
|
"---@async\n---@param flag {}\n---@param value boolean\nfunction {}:set_flag(flag, value) end\n",
|
||||||
|
<Flag as Typed>::type_name(),
|
||||||
|
<HueBridge as Typed>::type_name(),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Serialize)]
|
#[derive(Debug, Serialize)]
|
||||||
struct FlagMessage {
|
struct FlagMessage {
|
||||||
@@ -91,21 +123,3 @@ impl Device for HueBridge {
|
|||||||
self.config.identifier.clone()
|
self.config.identifier.clone()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AddAdditionalMethods for HueBridge {
|
|
||||||
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M)
|
|
||||||
where
|
|
||||||
Self: Sized + 'static,
|
|
||||||
{
|
|
||||||
methods.add_async_method(
|
|
||||||
"set_flag",
|
|
||||||
|lua, this, (flag, value): (mlua::Value, bool)| async move {
|
|
||||||
let flag: Flag = lua.from_value(flag)?;
|
|
||||||
|
|
||||||
this.set_flag(flag, value).await;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -2,28 +2,33 @@ use std::net::SocketAddr;
|
|||||||
|
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use automation_macro::{LuaDevice, 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;
|
||||||
|
use lua_typed::Typed;
|
||||||
use tracing::{error, trace, warn};
|
use tracing::{error, trace, warn};
|
||||||
|
|
||||||
use super::{Device, LuaDeviceCreate};
|
use super::{Device, LuaDeviceCreate};
|
||||||
|
|
||||||
#[derive(Debug, Clone, LuaDeviceConfig)]
|
#[derive(Debug, Clone, LuaDeviceConfig, Typed)]
|
||||||
|
#[typed(as = "HueGroupConfig")]
|
||||||
pub struct Config {
|
pub struct Config {
|
||||||
pub identifier: String,
|
pub identifier: String,
|
||||||
#[device_config(rename("ip"), with(|ip| SocketAddr::new(ip, 80)))]
|
#[device_config(rename("ip"), with(|ip| SocketAddr::new(ip, 80)))]
|
||||||
|
#[typed(as = "ip")]
|
||||||
pub addr: SocketAddr,
|
pub addr: SocketAddr,
|
||||||
pub login: String,
|
pub login: String,
|
||||||
pub group_id: isize,
|
pub group_id: isize,
|
||||||
pub scene_id: String,
|
pub scene_id: String,
|
||||||
}
|
}
|
||||||
|
crate::register_type!(Config);
|
||||||
|
|
||||||
#[derive(Debug, Clone, LuaDevice)]
|
#[derive(Debug, Clone, Device)]
|
||||||
#[traits(OnOff)]
|
#[device(traits(OnOff))]
|
||||||
pub struct HueGroup {
|
pub struct HueGroup {
|
||||||
config: Config,
|
config: Config,
|
||||||
}
|
}
|
||||||
|
crate::register_device!(HueGroup);
|
||||||
|
|
||||||
// Couple of helper function to get the correct urls
|
// Couple of helper function to get the correct urls
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
|
|||||||
@@ -4,36 +4,49 @@ use automation_lib::config::{InfoConfig, MqttDeviceConfig};
|
|||||||
use automation_lib::device::{Device, LuaDeviceCreate};
|
use automation_lib::device::{Device, LuaDeviceCreate};
|
||||||
use automation_lib::event::OnMqtt;
|
use automation_lib::event::OnMqtt;
|
||||||
use automation_lib::mqtt::WrappedAsyncClient;
|
use automation_lib::mqtt::WrappedAsyncClient;
|
||||||
use automation_macro::{LuaDevice, LuaDeviceConfig};
|
use automation_macro::{Device, LuaDeviceConfig};
|
||||||
|
use lua_typed::Typed;
|
||||||
use rumqttc::{Publish, matches};
|
use rumqttc::{Publish, matches};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use tracing::{debug, trace, warn};
|
use tracing::{debug, trace, warn};
|
||||||
|
|
||||||
#[derive(Debug, Clone, LuaDeviceConfig)]
|
#[derive(Debug, Clone, LuaDeviceConfig, Typed)]
|
||||||
|
#[typed(as = "HueSwitchConfig")]
|
||||||
pub struct Config {
|
pub struct Config {
|
||||||
#[device_config(flatten)]
|
#[device_config(flatten)]
|
||||||
|
#[typed(flatten)]
|
||||||
pub info: InfoConfig,
|
pub info: InfoConfig,
|
||||||
|
|
||||||
#[device_config(flatten)]
|
#[device_config(flatten)]
|
||||||
|
#[typed(flatten)]
|
||||||
pub mqtt: MqttDeviceConfig,
|
pub mqtt: MqttDeviceConfig,
|
||||||
|
|
||||||
#[device_config(from_lua)]
|
#[device_config(from_lua)]
|
||||||
pub client: WrappedAsyncClient,
|
pub client: WrappedAsyncClient,
|
||||||
|
|
||||||
#[device_config(from_lua, default)]
|
#[device_config(from_lua, default)]
|
||||||
pub left_callback: ActionCallback<HueSwitch, ()>,
|
#[typed(default)]
|
||||||
|
pub left_callback: ActionCallback<HueSwitch>,
|
||||||
|
|
||||||
#[device_config(from_lua, default)]
|
#[device_config(from_lua, default)]
|
||||||
pub right_callback: ActionCallback<HueSwitch, ()>,
|
#[typed(default)]
|
||||||
|
pub right_callback: ActionCallback<HueSwitch>,
|
||||||
|
|
||||||
#[device_config(from_lua, default)]
|
#[device_config(from_lua, default)]
|
||||||
pub left_hold_callback: ActionCallback<HueSwitch, ()>,
|
#[typed(default)]
|
||||||
|
pub left_hold_callback: ActionCallback<HueSwitch>,
|
||||||
|
|
||||||
#[device_config(from_lua, default)]
|
#[device_config(from_lua, default)]
|
||||||
pub right_hold_callback: ActionCallback<HueSwitch, ()>,
|
#[typed(default)]
|
||||||
|
pub right_hold_callback: ActionCallback<HueSwitch>,
|
||||||
|
|
||||||
|
#[device_config(from_lua, default)]
|
||||||
|
#[typed(default)]
|
||||||
|
pub battery_callback: ActionCallback<(HueSwitch, f32)>,
|
||||||
}
|
}
|
||||||
|
crate::register_type!(Config);
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize)]
|
#[derive(Debug, Copy, Clone, Deserialize)]
|
||||||
#[serde(rename_all = "snake_case")]
|
#[serde(rename_all = "snake_case")]
|
||||||
enum Action {
|
enum Action {
|
||||||
LeftPress,
|
LeftPress,
|
||||||
@@ -48,13 +61,15 @@ enum Action {
|
|||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize)]
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
struct State {
|
struct State {
|
||||||
action: Action,
|
action: Option<Action>,
|
||||||
|
battery: Option<f32>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, LuaDevice)]
|
#[derive(Debug, Clone, Device)]
|
||||||
pub struct HueSwitch {
|
pub struct HueSwitch {
|
||||||
config: Config,
|
config: Config,
|
||||||
}
|
}
|
||||||
|
crate::register_device!(HueSwitch);
|
||||||
|
|
||||||
impl Device for HueSwitch {
|
impl Device for HueSwitch {
|
||||||
fn get_id(&self) -> String {
|
fn get_id(&self) -> String {
|
||||||
@@ -84,33 +99,49 @@ 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(&message.topic, &self.config.mqtt.topic) {
|
if matches(&message.topic, &self.config.mqtt.topic) {
|
||||||
let action = match serde_json::from_slice::<State>(&message.payload) {
|
let message = match serde_json::from_slice::<State>(&message.payload) {
|
||||||
Ok(message) => message.action,
|
Ok(message) => message,
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
warn!(id = Device::get_id(self), "Failed to parse message: {err}");
|
warn!(id = Device::get_id(self), "Failed to parse message: {err}");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
debug!(id = Device::get_id(self), "Remote action = {:?}", action);
|
|
||||||
|
if let Some(action) = message.action {
|
||||||
|
debug!(
|
||||||
|
id = Device::get_id(self),
|
||||||
|
?message.action,
|
||||||
|
"Action received",
|
||||||
|
);
|
||||||
|
|
||||||
match action {
|
match action {
|
||||||
Action::LeftPressRelease => self.config.left_callback.call(self, &()).await,
|
Action::LeftPressRelease => self.config.left_callback.call(self.clone()).await,
|
||||||
Action::RightPressRelease => self.config.right_callback.call(self, &()).await,
|
Action::RightPressRelease => {
|
||||||
Action::LeftHold => self.config.left_hold_callback.call(self, &()).await,
|
self.config.right_callback.call(self.clone()).await
|
||||||
Action::RightHold => self.config.right_hold_callback.call(self, &()).await,
|
}
|
||||||
|
Action::LeftHold => self.config.left_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 => {
|
Action::RightHoldRelease => {
|
||||||
if !self.config.right_hold_callback.is_set() {
|
if self.config.right_hold_callback.is_empty() {
|
||||||
self.config.right_callback.call(self, &()).await
|
self.config.right_callback.call(self.clone()).await
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Action::LeftHoldRelease => {
|
Action::LeftHoldRelease => {
|
||||||
if !self.config.left_hold_callback.is_set() {
|
if self.config.left_hold_callback.is_empty() {
|
||||||
self.config.left_callback.call(self, &()).await
|
self.config.left_callback.call(self.clone()).await
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if let Some(battery) = message.battery {
|
||||||
|
self.config
|
||||||
|
.battery_callback
|
||||||
|
.call((self.clone(), battery))
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,36 +1,47 @@
|
|||||||
|
use async_trait::async_trait;
|
||||||
use automation_lib::action_callback::ActionCallback;
|
use automation_lib::action_callback::ActionCallback;
|
||||||
use automation_lib::config::{InfoConfig, MqttDeviceConfig};
|
use automation_lib::config::{InfoConfig, MqttDeviceConfig};
|
||||||
use automation_lib::device::{Device, LuaDeviceCreate};
|
use automation_lib::device::{Device, LuaDeviceCreate};
|
||||||
use automation_lib::event::OnMqtt;
|
use automation_lib::event::OnMqtt;
|
||||||
use automation_lib::messages::{RemoteAction, RemoteMessage};
|
use automation_lib::messages::{RemoteAction, RemoteMessage};
|
||||||
use automation_lib::mqtt::WrappedAsyncClient;
|
use automation_lib::mqtt::WrappedAsyncClient;
|
||||||
use automation_macro::{LuaDevice, LuaDeviceConfig};
|
use automation_macro::{Device, LuaDeviceConfig};
|
||||||
use axum::async_trait;
|
use lua_typed::Typed;
|
||||||
use rumqttc::{Publish, matches};
|
use rumqttc::{Publish, matches};
|
||||||
use tracing::{debug, error, trace};
|
use tracing::{debug, error, trace};
|
||||||
|
|
||||||
#[derive(Debug, Clone, LuaDeviceConfig)]
|
#[derive(Debug, Clone, LuaDeviceConfig, Typed)]
|
||||||
|
#[typed(as = "IkeaRemoteConfig")]
|
||||||
pub struct Config {
|
pub struct Config {
|
||||||
#[device_config(flatten)]
|
#[device_config(flatten)]
|
||||||
|
#[typed(flatten)]
|
||||||
pub info: InfoConfig,
|
pub info: InfoConfig,
|
||||||
|
|
||||||
#[device_config(default)]
|
#[device_config(default)]
|
||||||
|
#[typed(default)]
|
||||||
pub single_button: bool,
|
pub single_button: bool,
|
||||||
|
|
||||||
#[device_config(flatten)]
|
#[device_config(flatten)]
|
||||||
|
#[typed(flatten)]
|
||||||
pub mqtt: MqttDeviceConfig,
|
pub mqtt: MqttDeviceConfig,
|
||||||
|
|
||||||
#[device_config(from_lua)]
|
#[device_config(from_lua)]
|
||||||
pub client: WrappedAsyncClient,
|
pub client: WrappedAsyncClient,
|
||||||
|
|
||||||
#[device_config(from_lua)]
|
#[device_config(from_lua, default)]
|
||||||
pub callback: ActionCallback<IkeaRemote, bool>,
|
#[typed(default)]
|
||||||
|
pub callback: ActionCallback<(IkeaRemote, bool)>,
|
||||||
|
#[device_config(from_lua, default)]
|
||||||
|
#[typed(default)]
|
||||||
|
pub battery_callback: ActionCallback<(IkeaRemote, f32)>,
|
||||||
}
|
}
|
||||||
|
crate::register_type!(Config);
|
||||||
|
|
||||||
#[derive(Debug, Clone, LuaDevice)]
|
#[derive(Debug, Clone, Device)]
|
||||||
pub struct IkeaRemote {
|
pub struct IkeaRemote {
|
||||||
config: Config,
|
config: Config,
|
||||||
}
|
}
|
||||||
|
crate::register_device!(IkeaRemote);
|
||||||
|
|
||||||
impl Device for IkeaRemote {
|
impl Device for IkeaRemote {
|
||||||
fn get_id(&self) -> String {
|
fn get_id(&self) -> String {
|
||||||
@@ -60,13 +71,15 @@ 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(&message.topic, &self.config.mqtt.topic) {
|
if matches(&message.topic, &self.config.mqtt.topic) {
|
||||||
let action = match RemoteMessage::try_from(message) {
|
let message = match RemoteMessage::try_from(message) {
|
||||||
Ok(message) => message.action(),
|
Ok(message) => message,
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
error!(id = Device::get_id(self), "Failed to parse message: {err}");
|
error!(id = Device::get_id(self), "Failed to parse message: {err}");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if let Some(action) = message.action {
|
||||||
debug!(id = Device::get_id(self), "Remote action = {:?}", action);
|
debug!(id = Device::get_id(self), "Remote action = {:?}", action);
|
||||||
|
|
||||||
let on = if self.config.single_button {
|
let on = if self.config.single_button {
|
||||||
@@ -84,7 +97,15 @@ impl OnMqtt for IkeaRemote {
|
|||||||
};
|
};
|
||||||
|
|
||||||
if let Some(on) = on {
|
if let Some(on) = on {
|
||||||
self.config.callback.call(self, &on).await;
|
self.config.callback.call((self.clone(), on)).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(battery) = message.battery {
|
||||||
|
self.config
|
||||||
|
.battery_callback
|
||||||
|
.call((self.clone(), battery))
|
||||||
|
.await;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,28 +4,33 @@ use std::str::Utf8Error;
|
|||||||
|
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use automation_lib::device::{Device, LuaDeviceCreate};
|
use automation_lib::device::{Device, LuaDeviceCreate};
|
||||||
use automation_macro::{LuaDevice, LuaDeviceConfig};
|
use automation_macro::{Device, LuaDeviceConfig};
|
||||||
use bytes::{Buf, BufMut};
|
use bytes::{Buf, BufMut};
|
||||||
use google_home::errors::{self, DeviceError};
|
use google_home::errors::{self, DeviceError};
|
||||||
use google_home::traits::OnOff;
|
use google_home::traits::OnOff;
|
||||||
|
use lua_typed::Typed;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
use tokio::net::TcpStream;
|
use tokio::net::TcpStream;
|
||||||
use tracing::trace;
|
use tracing::trace;
|
||||||
|
|
||||||
#[derive(Debug, Clone, LuaDeviceConfig)]
|
#[derive(Debug, Clone, LuaDeviceConfig, Typed)]
|
||||||
|
#[typed(as = "KasaOutletConfig")]
|
||||||
pub struct Config {
|
pub struct Config {
|
||||||
pub identifier: String,
|
pub identifier: String,
|
||||||
#[device_config(rename("ip"), with(|ip| SocketAddr::new(ip, 9999)))]
|
#[device_config(rename("ip"), with(|ip| SocketAddr::new(ip, 9999)))]
|
||||||
|
#[typed(as = "ip")]
|
||||||
pub addr: SocketAddr,
|
pub addr: SocketAddr,
|
||||||
}
|
}
|
||||||
|
crate::register_type!(Config);
|
||||||
|
|
||||||
#[derive(Debug, Clone, LuaDevice)]
|
#[derive(Debug, Clone, Device)]
|
||||||
#[traits(OnOff)]
|
#[device(traits(OnOff))]
|
||||||
pub struct KasaOutlet {
|
pub struct KasaOutlet {
|
||||||
config: Config,
|
config: Config,
|
||||||
}
|
}
|
||||||
|
crate::register_device!(KasaOutlet);
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl LuaDeviceCreate for KasaOutlet {
|
impl LuaDeviceCreate for KasaOutlet {
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
#![feature(iter_intersperse)]
|
||||||
mod air_filter;
|
mod air_filter;
|
||||||
mod contact_sensor;
|
mod contact_sensor;
|
||||||
mod hue_bridge;
|
mod hue_bridge;
|
||||||
@@ -12,48 +13,118 @@ mod wake_on_lan;
|
|||||||
mod washer;
|
mod washer;
|
||||||
mod zigbee;
|
mod zigbee;
|
||||||
|
|
||||||
|
use automation_lib::Module;
|
||||||
use automation_lib::device::{Device, LuaDeviceCreate};
|
use automation_lib::device::{Device, LuaDeviceCreate};
|
||||||
use zigbee::light::{LightBrightness, LightColorTemperature, LightOnOff};
|
use tracing::{debug, warn};
|
||||||
use zigbee::outlet::{OutletOnOff, OutletPower};
|
|
||||||
|
|
||||||
pub use self::air_filter::AirFilter;
|
type DeviceNameFn = fn() -> String;
|
||||||
pub use self::contact_sensor::ContactSensor;
|
type RegisterDeviceFn = fn(lua: &mlua::Lua) -> mlua::Result<mlua::AnyUserData>;
|
||||||
pub use self::hue_bridge::HueBridge;
|
|
||||||
pub use self::hue_group::HueGroup;
|
pub struct RegisteredDevice {
|
||||||
pub use self::hue_switch::HueSwitch;
|
name_fn: DeviceNameFn,
|
||||||
pub use self::ikea_remote::IkeaRemote;
|
register_fn: RegisterDeviceFn,
|
||||||
pub use self::kasa_outlet::KasaOutlet;
|
}
|
||||||
pub use self::light_sensor::LightSensor;
|
|
||||||
pub use self::ntfy::*;
|
impl RegisteredDevice {
|
||||||
pub use self::presence::Presence;
|
pub const fn new(name_fn: DeviceNameFn, register_fn: RegisterDeviceFn) -> Self {
|
||||||
pub use self::wake_on_lan::WakeOnLAN;
|
Self {
|
||||||
pub use self::washer::Washer;
|
name_fn,
|
||||||
|
register_fn,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_name(&self) -> String {
|
||||||
|
(self.name_fn)()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn register(&self, lua: &mlua::Lua) -> mlua::Result<mlua::AnyUserData> {
|
||||||
|
(self.register_fn)(lua)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
macro_rules! register_device {
|
macro_rules! register_device {
|
||||||
($lua:expr, $device:ty) => {
|
($device:ty) => {
|
||||||
$lua.globals()
|
::inventory::submit!(crate::RegisteredDevice::new(
|
||||||
.set(stringify!($device), $lua.create_proxy::<$device>()?)?;
|
<$device as ::lua_typed::Typed>::type_name,
|
||||||
|
::mlua::Lua::create_proxy::<$device>
|
||||||
|
));
|
||||||
|
|
||||||
|
crate::register_type!($device);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
pub(crate) use register_device;
|
||||||
|
|
||||||
pub fn register_with_lua(lua: &mlua::Lua) -> mlua::Result<()> {
|
inventory::collect!(RegisteredDevice);
|
||||||
register_device!(lua, AirFilter);
|
|
||||||
register_device!(lua, ContactSensor);
|
|
||||||
register_device!(lua, HueBridge);
|
|
||||||
register_device!(lua, HueGroup);
|
|
||||||
register_device!(lua, HueSwitch);
|
|
||||||
register_device!(lua, IkeaRemote);
|
|
||||||
register_device!(lua, KasaOutlet);
|
|
||||||
register_device!(lua, LightBrightness);
|
|
||||||
register_device!(lua, LightColorTemperature);
|
|
||||||
register_device!(lua, LightOnOff);
|
|
||||||
register_device!(lua, LightSensor);
|
|
||||||
register_device!(lua, Ntfy);
|
|
||||||
register_device!(lua, OutletOnOff);
|
|
||||||
register_device!(lua, OutletPower);
|
|
||||||
register_device!(lua, Presence);
|
|
||||||
register_device!(lua, WakeOnLAN);
|
|
||||||
register_device!(lua, Washer);
|
|
||||||
|
|
||||||
Ok(())
|
pub fn create_module(lua: &mlua::Lua) -> mlua::Result<mlua::Table> {
|
||||||
|
let devices = lua.create_table()?;
|
||||||
|
|
||||||
|
debug!("Loading devices...");
|
||||||
|
for device in inventory::iter::<RegisteredDevice> {
|
||||||
|
let name = device.get_name();
|
||||||
|
debug!(name, "Registering device");
|
||||||
|
let proxy = device.register(lua)?;
|
||||||
|
devices.set(name, proxy)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Ok(devices)
|
||||||
|
}
|
||||||
|
|
||||||
|
type TypeNameFn = fn() -> String;
|
||||||
|
type TypeDefinitionFn = fn() -> Option<String>;
|
||||||
|
|
||||||
|
pub struct RegisteredType {
|
||||||
|
name_fn: TypeNameFn,
|
||||||
|
definition_fn: TypeDefinitionFn,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RegisteredType {
|
||||||
|
pub const fn new(name_fn: TypeNameFn, definition_fn: TypeDefinitionFn) -> Self {
|
||||||
|
Self {
|
||||||
|
name_fn,
|
||||||
|
definition_fn,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_name(&self) -> String {
|
||||||
|
(self.name_fn)()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn register(&self) -> Option<String> {
|
||||||
|
(self.definition_fn)()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! register_type {
|
||||||
|
($ty:ty) => {
|
||||||
|
::inventory::submit!(crate::RegisteredType::new(
|
||||||
|
<$ty as ::lua_typed::Typed>::type_name,
|
||||||
|
<$ty as ::lua_typed::Typed>::generate_full
|
||||||
|
));
|
||||||
|
};
|
||||||
|
}
|
||||||
|
pub(crate) use register_type;
|
||||||
|
|
||||||
|
inventory::collect!(RegisteredType);
|
||||||
|
|
||||||
|
fn generate_definitions() -> String {
|
||||||
|
let mut output = String::new();
|
||||||
|
|
||||||
|
let mut types: Vec<_> = inventory::iter::<RegisteredType>.into_iter().collect();
|
||||||
|
types.sort_by_key(|ty| ty.get_name());
|
||||||
|
|
||||||
|
output += "---@meta\n\nlocal devices\n\n";
|
||||||
|
for ty in types {
|
||||||
|
if let Some(def) = (ty.definition_fn)() {
|
||||||
|
output += &(def + "\n");
|
||||||
|
} else {
|
||||||
|
// NOTE: Due to how this works the typed is erased, so we don't know the cause
|
||||||
|
warn!("Registered type is missing generate_full function");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
output += "return devices";
|
||||||
|
|
||||||
|
output
|
||||||
|
}
|
||||||
|
|
||||||
|
inventory::submit! {Module::new("automation:devices", create_module, Some(generate_definitions))}
|
||||||
|
|||||||
@@ -7,25 +7,30 @@ use automation_lib::device::{Device, LuaDeviceCreate};
|
|||||||
use automation_lib::event::OnMqtt;
|
use automation_lib::event::OnMqtt;
|
||||||
use automation_lib::messages::BrightnessMessage;
|
use automation_lib::messages::BrightnessMessage;
|
||||||
use automation_lib::mqtt::WrappedAsyncClient;
|
use automation_lib::mqtt::WrappedAsyncClient;
|
||||||
use automation_macro::{LuaDevice, LuaDeviceConfig};
|
use automation_macro::{Device, LuaDeviceConfig};
|
||||||
|
use lua_typed::Typed;
|
||||||
use rumqttc::Publish;
|
use rumqttc::Publish;
|
||||||
use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
|
use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
|
||||||
use tracing::{debug, trace, warn};
|
use tracing::{debug, trace, warn};
|
||||||
|
|
||||||
#[derive(Debug, Clone, LuaDeviceConfig)]
|
#[derive(Debug, Clone, LuaDeviceConfig, Typed)]
|
||||||
|
#[typed(as = "LightSensorConfig")]
|
||||||
pub struct Config {
|
pub struct Config {
|
||||||
pub identifier: String,
|
pub identifier: String,
|
||||||
#[device_config(flatten)]
|
#[device_config(flatten)]
|
||||||
|
#[typed(flatten)]
|
||||||
pub mqtt: MqttDeviceConfig,
|
pub mqtt: MqttDeviceConfig,
|
||||||
pub min: isize,
|
pub min: isize,
|
||||||
pub max: isize,
|
pub max: isize,
|
||||||
|
|
||||||
#[device_config(from_lua, default)]
|
#[device_config(from_lua, default)]
|
||||||
pub callback: ActionCallback<LightSensor, bool>,
|
#[typed(default)]
|
||||||
|
pub callback: ActionCallback<(LightSensor, bool)>,
|
||||||
|
|
||||||
#[device_config(from_lua)]
|
#[device_config(from_lua)]
|
||||||
pub client: WrappedAsyncClient,
|
pub client: WrappedAsyncClient,
|
||||||
}
|
}
|
||||||
|
crate::register_type!(Config);
|
||||||
|
|
||||||
const DEFAULT: bool = false;
|
const DEFAULT: bool = false;
|
||||||
|
|
||||||
@@ -34,11 +39,12 @@ pub struct State {
|
|||||||
is_dark: bool,
|
is_dark: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, LuaDevice)]
|
#[derive(Debug, Clone, Device)]
|
||||||
pub struct LightSensor {
|
pub struct LightSensor {
|
||||||
config: Config,
|
config: Config,
|
||||||
state: Arc<RwLock<State>>,
|
state: Arc<RwLock<State>>,
|
||||||
}
|
}
|
||||||
|
crate::register_device!(LightSensor);
|
||||||
|
|
||||||
impl LightSensor {
|
impl LightSensor {
|
||||||
async fn state(&self) -> RwLockReadGuard<'_, State> {
|
async fn state(&self) -> RwLockReadGuard<'_, State> {
|
||||||
@@ -114,7 +120,7 @@ impl OnMqtt for LightSensor {
|
|||||||
|
|
||||||
self.config
|
self.config
|
||||||
.callback
|
.callback
|
||||||
.call(self, &!self.state().await.is_dark)
|
.call((self.clone(), !self.state().await.is_dark))
|
||||||
.await;
|
.await;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,16 +3,18 @@ use std::convert::Infallible;
|
|||||||
|
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use automation_lib::device::{Device, LuaDeviceCreate};
|
use automation_lib::device::{Device, LuaDeviceCreate};
|
||||||
use automation_lib::lua::traits::AddAdditionalMethods;
|
use automation_lib::lua::traits::PartialUserData;
|
||||||
use automation_macro::{LuaDevice, LuaDeviceConfig};
|
use automation_macro::{Device, LuaDeviceConfig};
|
||||||
|
use lua_typed::Typed;
|
||||||
use mlua::LuaSerdeExt;
|
use mlua::LuaSerdeExt;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use serde_repr::*;
|
use serde_repr::*;
|
||||||
use tracing::{error, trace, warn};
|
use tracing::{error, trace, warn};
|
||||||
|
|
||||||
#[derive(Debug, Serialize_repr, Deserialize, Clone, Copy)]
|
#[derive(Debug, Serialize_repr, Deserialize, Clone, Copy, Typed)]
|
||||||
#[repr(u8)]
|
#[repr(u8)]
|
||||||
#[serde(rename_all = "snake_case")]
|
#[serde(rename_all = "snake_case")]
|
||||||
|
#[typed(rename_all = "snake_case")]
|
||||||
pub enum Priority {
|
pub enum Priority {
|
||||||
Min = 1,
|
Min = 1,
|
||||||
Low,
|
Low,
|
||||||
@@ -20,83 +22,56 @@ pub enum Priority {
|
|||||||
High,
|
High,
|
||||||
Max,
|
Max,
|
||||||
}
|
}
|
||||||
|
crate::register_type!(Priority);
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
#[derive(Debug, Serialize, Deserialize, Clone, Typed)]
|
||||||
#[serde(rename_all = "snake_case", tag = "action")]
|
#[serde(rename_all = "snake_case", tag = "action")]
|
||||||
|
#[typed(rename_all = "snake_case", tag = "action")]
|
||||||
pub enum ActionType {
|
pub enum ActionType {
|
||||||
Broadcast {
|
Broadcast {
|
||||||
#[serde(skip_serializing_if = "HashMap::is_empty")]
|
#[serde(skip_serializing_if = "HashMap::is_empty")]
|
||||||
|
#[serde(default)]
|
||||||
|
#[typed(default)]
|
||||||
extras: HashMap<String, String>,
|
extras: HashMap<String, String>,
|
||||||
},
|
},
|
||||||
// View,
|
// View,
|
||||||
// Http
|
// Http
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
#[derive(Debug, Serialize, Deserialize, Clone, Typed)]
|
||||||
pub struct Action {
|
pub struct Action {
|
||||||
#[serde(flatten)]
|
#[serde(flatten)]
|
||||||
|
#[typed(flatten)]
|
||||||
pub action: ActionType,
|
pub action: ActionType,
|
||||||
pub label: String,
|
pub label: String,
|
||||||
pub clear: Option<bool>,
|
pub clear: Option<bool>,
|
||||||
}
|
}
|
||||||
|
crate::register_type!(Action);
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize)]
|
#[derive(Serialize, Deserialize, Typed)]
|
||||||
struct NotificationFinal {
|
struct NotificationFinal {
|
||||||
topic: String,
|
topic: String,
|
||||||
#[serde(flatten)]
|
#[serde(flatten)]
|
||||||
|
#[typed(flatten)]
|
||||||
inner: Notification,
|
inner: Notification,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Clone, Deserialize)]
|
#[derive(Debug, Serialize, Clone, Deserialize, Typed)]
|
||||||
pub struct Notification {
|
pub struct Notification {
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
title: String,
|
||||||
title: Option<String>,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
message: Option<String>,
|
message: Option<String>,
|
||||||
#[serde(skip_serializing_if = "Vec::is_empty", default = "Default::default")]
|
#[serde(skip_serializing_if = "Vec::is_empty", default = "Default::default")]
|
||||||
|
#[typed(default)]
|
||||||
tags: Vec<String>,
|
tags: Vec<String>,
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
priority: Option<Priority>,
|
priority: Option<Priority>,
|
||||||
#[serde(skip_serializing_if = "Vec::is_empty", default = "Default::default")]
|
#[serde(skip_serializing_if = "Vec::is_empty", default = "Default::default")]
|
||||||
|
#[typed(default)]
|
||||||
actions: Vec<Action>,
|
actions: Vec<Action>,
|
||||||
}
|
}
|
||||||
|
crate::register_type!(Notification);
|
||||||
|
|
||||||
impl Notification {
|
impl Notification {
|
||||||
pub fn new() -> Self {
|
|
||||||
Self {
|
|
||||||
title: None,
|
|
||||||
message: None,
|
|
||||||
tags: Vec::new(),
|
|
||||||
priority: None,
|
|
||||||
actions: Vec::new(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_title(mut self, title: &str) -> Self {
|
|
||||||
self.title = Some(title.into());
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_message(mut self, message: &str) -> Self {
|
|
||||||
self.message = Some(message.into());
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn add_tag(mut self, tag: &str) -> Self {
|
|
||||||
self.tags.push(tag.into());
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_priority(mut self, priority: Priority) -> Self {
|
|
||||||
self.priority = Some(priority);
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn add_action(mut self, action: Action) -> Self {
|
|
||||||
self.actions.push(action);
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
fn finalize(self, topic: &str) -> NotificationFinal {
|
fn finalize(self, topic: &str) -> NotificationFinal {
|
||||||
NotificationFinal {
|
NotificationFinal {
|
||||||
topic: topic.into(),
|
topic: topic.into(),
|
||||||
@@ -105,24 +80,46 @@ impl Notification {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for Notification {
|
#[derive(Debug, Clone, LuaDeviceConfig, Typed)]
|
||||||
fn default() -> Self {
|
#[typed(as = "NtfyConfig")]
|
||||||
Self::new()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, LuaDeviceConfig)]
|
|
||||||
pub struct Config {
|
pub struct Config {
|
||||||
#[device_config(default("https://ntfy.sh".into()))]
|
#[device_config(default("https://ntfy.sh".into()))]
|
||||||
|
#[typed(default)]
|
||||||
pub url: String,
|
pub url: String,
|
||||||
pub topic: String,
|
pub topic: String,
|
||||||
}
|
}
|
||||||
|
crate::register_type!(Config);
|
||||||
|
|
||||||
#[derive(Debug, Clone, LuaDevice)]
|
#[derive(Debug, Clone, Device)]
|
||||||
#[traits(AddAdditionalMethods)]
|
#[device(extra_user_data = SendNotification)]
|
||||||
pub struct Ntfy {
|
pub struct Ntfy {
|
||||||
config: Config,
|
config: Config,
|
||||||
}
|
}
|
||||||
|
crate::register_device!(Ntfy);
|
||||||
|
|
||||||
|
struct SendNotification;
|
||||||
|
impl PartialUserData<Ntfy> for SendNotification {
|
||||||
|
fn add_methods<M: mlua::UserDataMethods<Ntfy>>(methods: &mut M) {
|
||||||
|
methods.add_async_method(
|
||||||
|
"send_notification",
|
||||||
|
async |lua, this, notification: mlua::Value| {
|
||||||
|
let notification: Notification = lua.from_value(notification)?;
|
||||||
|
|
||||||
|
this.send(notification).await;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn definitions() -> Option<String> {
|
||||||
|
Some(format!(
|
||||||
|
"---@async\n---@param notification {}\nfunction {}:send_notification(notification) end\n",
|
||||||
|
<Notification as Typed>::type_name(),
|
||||||
|
<Ntfy as Typed>::type_name(),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl LuaDeviceCreate for Ntfy {
|
impl LuaDeviceCreate for Ntfy {
|
||||||
@@ -162,21 +159,3 @@ impl Ntfy {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AddAdditionalMethods for Ntfy {
|
|
||||||
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M)
|
|
||||||
where
|
|
||||||
Self: Sized + 'static,
|
|
||||||
{
|
|
||||||
methods.add_async_method(
|
|
||||||
"send_notification",
|
|
||||||
|lua, this, notification: mlua::Value| async move {
|
|
||||||
let notification: Notification = lua.from_value(notification)?;
|
|
||||||
|
|
||||||
this.send(notification).await;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -6,25 +6,30 @@ use automation_lib::action_callback::ActionCallback;
|
|||||||
use automation_lib::config::MqttDeviceConfig;
|
use automation_lib::config::MqttDeviceConfig;
|
||||||
use automation_lib::device::{Device, LuaDeviceCreate};
|
use automation_lib::device::{Device, LuaDeviceCreate};
|
||||||
use automation_lib::event::OnMqtt;
|
use automation_lib::event::OnMqtt;
|
||||||
use automation_lib::lua::traits::AddAdditionalMethods;
|
use automation_lib::lua::traits::PartialUserData;
|
||||||
use automation_lib::messages::PresenceMessage;
|
use automation_lib::messages::PresenceMessage;
|
||||||
use automation_lib::mqtt::WrappedAsyncClient;
|
use automation_lib::mqtt::WrappedAsyncClient;
|
||||||
use automation_macro::{LuaDevice, LuaDeviceConfig};
|
use automation_macro::{Device, LuaDeviceConfig};
|
||||||
|
use lua_typed::Typed;
|
||||||
use rumqttc::Publish;
|
use rumqttc::Publish;
|
||||||
use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
|
use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
|
||||||
use tracing::{debug, trace, warn};
|
use tracing::{debug, trace, warn};
|
||||||
|
|
||||||
#[derive(Debug, Clone, LuaDeviceConfig)]
|
#[derive(Debug, Clone, LuaDeviceConfig, Typed)]
|
||||||
|
#[typed(as = "PresenceConfig")]
|
||||||
pub struct Config {
|
pub struct Config {
|
||||||
#[device_config(flatten)]
|
#[device_config(flatten)]
|
||||||
|
#[typed(flatten)]
|
||||||
pub mqtt: MqttDeviceConfig,
|
pub mqtt: MqttDeviceConfig,
|
||||||
|
|
||||||
#[device_config(from_lua, default)]
|
#[device_config(from_lua, default)]
|
||||||
pub callback: ActionCallback<Presence, bool>,
|
#[typed(default)]
|
||||||
|
pub callback: ActionCallback<(Presence, bool)>,
|
||||||
|
|
||||||
#[device_config(from_lua)]
|
#[device_config(from_lua)]
|
||||||
pub client: WrappedAsyncClient,
|
pub client: WrappedAsyncClient,
|
||||||
}
|
}
|
||||||
|
crate::register_type!(Config);
|
||||||
|
|
||||||
pub const DEFAULT_PRESENCE: bool = false;
|
pub const DEFAULT_PRESENCE: bool = false;
|
||||||
|
|
||||||
@@ -34,12 +39,29 @@ pub struct State {
|
|||||||
current_overall_presence: bool,
|
current_overall_presence: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, LuaDevice)]
|
#[derive(Debug, Clone, Device)]
|
||||||
#[traits(AddAdditionalMethods)]
|
#[device(extra_user_data = OverallPresence)]
|
||||||
pub struct Presence {
|
pub struct Presence {
|
||||||
config: Config,
|
config: Config,
|
||||||
state: Arc<RwLock<State>>,
|
state: Arc<RwLock<State>>,
|
||||||
}
|
}
|
||||||
|
crate::register_device!(Presence);
|
||||||
|
|
||||||
|
struct OverallPresence;
|
||||||
|
impl PartialUserData<Presence> for OverallPresence {
|
||||||
|
fn add_methods<M: mlua::UserDataMethods<Presence>>(methods: &mut M) {
|
||||||
|
methods.add_async_method("overall_presence", async |_lua, this, ()| {
|
||||||
|
Ok(this.state().await.current_overall_presence)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn definitions() -> Option<String> {
|
||||||
|
Some(format!(
|
||||||
|
"---@async\n---@return boolean\nfunction {}:overall_presence() end\n",
|
||||||
|
<Presence as Typed>::type_name(),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl Presence {
|
impl Presence {
|
||||||
async fn state(&self) -> RwLockReadGuard<'_, State> {
|
async fn state(&self) -> RwLockReadGuard<'_, State> {
|
||||||
@@ -118,18 +140,10 @@ impl OnMqtt for Presence {
|
|||||||
debug!("Overall presence updated: {overall_presence}");
|
debug!("Overall presence updated: {overall_presence}");
|
||||||
self.state_mut().await.current_overall_presence = overall_presence;
|
self.state_mut().await.current_overall_presence = overall_presence;
|
||||||
|
|
||||||
self.config.callback.call(self, &overall_presence).await;
|
self.config
|
||||||
|
.callback
|
||||||
|
.call((self.clone(), overall_presence))
|
||||||
|
.await;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AddAdditionalMethods for Presence {
|
|
||||||
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M)
|
|
||||||
where
|
|
||||||
Self: Sized + 'static,
|
|
||||||
{
|
|
||||||
methods.add_async_method("overall_presence", async |_lua, this, ()| {
|
|
||||||
Ok(this.state().await.current_overall_presence)
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -6,32 +6,39 @@ use automation_lib::device::{Device, LuaDeviceCreate};
|
|||||||
use automation_lib::event::OnMqtt;
|
use automation_lib::event::OnMqtt;
|
||||||
use automation_lib::messages::ActivateMessage;
|
use automation_lib::messages::ActivateMessage;
|
||||||
use automation_lib::mqtt::WrappedAsyncClient;
|
use automation_lib::mqtt::WrappedAsyncClient;
|
||||||
use automation_macro::{LuaDevice, LuaDeviceConfig};
|
use automation_macro::{Device, LuaDeviceConfig};
|
||||||
use eui48::MacAddress;
|
use eui48::MacAddress;
|
||||||
use google_home::device;
|
use google_home::device;
|
||||||
use google_home::errors::ErrorCode;
|
use google_home::errors::ErrorCode;
|
||||||
use google_home::traits::{self, Scene};
|
use google_home::traits::{self, Scene};
|
||||||
use google_home::types::Type;
|
use google_home::types::Type;
|
||||||
|
use lua_typed::Typed;
|
||||||
use rumqttc::Publish;
|
use rumqttc::Publish;
|
||||||
use tracing::{debug, error, trace};
|
use tracing::{debug, error, trace};
|
||||||
|
|
||||||
#[derive(Debug, Clone, LuaDeviceConfig)]
|
#[derive(Debug, Clone, LuaDeviceConfig, Typed)]
|
||||||
|
#[typed(as = "WolConfig")]
|
||||||
pub struct Config {
|
pub struct Config {
|
||||||
#[device_config(flatten)]
|
#[device_config(flatten)]
|
||||||
|
#[typed(flatten)]
|
||||||
pub info: InfoConfig,
|
pub info: InfoConfig,
|
||||||
#[device_config(flatten)]
|
#[device_config(flatten)]
|
||||||
|
#[typed(flatten)]
|
||||||
pub mqtt: MqttDeviceConfig,
|
pub mqtt: MqttDeviceConfig,
|
||||||
pub mac_address: MacAddress,
|
pub mac_address: MacAddress,
|
||||||
#[device_config(default(Ipv4Addr::new(255, 255, 255, 255)))]
|
#[device_config(default(Ipv4Addr::new(255, 255, 255, 255)))]
|
||||||
|
#[typed(default)]
|
||||||
pub broadcast_ip: Ipv4Addr,
|
pub broadcast_ip: Ipv4Addr,
|
||||||
#[device_config(from_lua)]
|
#[device_config(from_lua)]
|
||||||
pub client: WrappedAsyncClient,
|
pub client: WrappedAsyncClient,
|
||||||
}
|
}
|
||||||
|
crate::register_type!(Config);
|
||||||
|
|
||||||
#[derive(Debug, Clone, LuaDevice)]
|
#[derive(Debug, Clone, Device)]
|
||||||
pub struct WakeOnLAN {
|
pub struct WakeOnLAN {
|
||||||
config: Config,
|
config: Config,
|
||||||
}
|
}
|
||||||
|
crate::register_device!(WakeOnLAN);
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl LuaDeviceCreate for WakeOnLAN {
|
impl LuaDeviceCreate for WakeOnLAN {
|
||||||
|
|||||||
@@ -7,25 +7,30 @@ use automation_lib::device::{Device, LuaDeviceCreate};
|
|||||||
use automation_lib::event::OnMqtt;
|
use automation_lib::event::OnMqtt;
|
||||||
use automation_lib::messages::PowerMessage;
|
use automation_lib::messages::PowerMessage;
|
||||||
use automation_lib::mqtt::WrappedAsyncClient;
|
use automation_lib::mqtt::WrappedAsyncClient;
|
||||||
use automation_macro::{LuaDevice, LuaDeviceConfig};
|
use automation_macro::{Device, LuaDeviceConfig};
|
||||||
|
use lua_typed::Typed;
|
||||||
use rumqttc::Publish;
|
use rumqttc::Publish;
|
||||||
use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
|
use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
|
||||||
use tracing::{debug, error, trace};
|
use tracing::{debug, error, trace};
|
||||||
|
|
||||||
#[derive(Debug, Clone, LuaDeviceConfig)]
|
#[derive(Debug, Clone, LuaDeviceConfig, Typed)]
|
||||||
|
#[typed(as = "WasherConfig")]
|
||||||
pub struct Config {
|
pub struct Config {
|
||||||
pub identifier: String,
|
pub identifier: String,
|
||||||
#[device_config(flatten)]
|
#[device_config(flatten)]
|
||||||
|
#[typed(flatten)]
|
||||||
pub mqtt: MqttDeviceConfig,
|
pub mqtt: MqttDeviceConfig,
|
||||||
// Power in Watt
|
// Power in Watt
|
||||||
pub threshold: f32,
|
pub threshold: f32,
|
||||||
|
|
||||||
#[device_config(from_lua, default)]
|
#[device_config(from_lua, default)]
|
||||||
pub done_callback: ActionCallback<Washer, ()>,
|
#[typed(default)]
|
||||||
|
pub done_callback: ActionCallback<Washer>,
|
||||||
|
|
||||||
#[device_config(from_lua)]
|
#[device_config(from_lua)]
|
||||||
pub client: WrappedAsyncClient,
|
pub client: WrappedAsyncClient,
|
||||||
}
|
}
|
||||||
|
crate::register_type!(Config);
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct State {
|
pub struct State {
|
||||||
@@ -33,11 +38,12 @@ pub struct State {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Add google home integration
|
// TODO: Add google home integration
|
||||||
#[derive(Debug, Clone, LuaDevice)]
|
#[derive(Debug, Clone, Device)]
|
||||||
pub struct Washer {
|
pub struct Washer {
|
||||||
config: Config,
|
config: Config,
|
||||||
state: Arc<RwLock<State>>,
|
state: Arc<RwLock<State>>,
|
||||||
}
|
}
|
||||||
|
crate::register_device!(Washer);
|
||||||
|
|
||||||
impl Washer {
|
impl Washer {
|
||||||
async fn state(&self) -> RwLockReadGuard<'_, State> {
|
async fn state(&self) -> RwLockReadGuard<'_, State> {
|
||||||
@@ -109,7 +115,7 @@ impl OnMqtt for Washer {
|
|||||||
|
|
||||||
self.state_mut().await.running = 0;
|
self.state_mut().await.running = 0;
|
||||||
|
|
||||||
self.config.done_callback.call(self, &()).await;
|
self.config.done_callback.call(self.clone()).await;
|
||||||
} else if power < self.config.threshold {
|
} else if power < self.config.threshold {
|
||||||
// Prevent false positives
|
// Prevent false positives
|
||||||
self.state_mut().await.running = 0;
|
self.state_mut().await.running = 0;
|
||||||
|
|||||||
@@ -10,11 +10,12 @@ use automation_lib::device::{Device, LuaDeviceCreate};
|
|||||||
use automation_lib::event::OnMqtt;
|
use automation_lib::event::OnMqtt;
|
||||||
use automation_lib::helpers::serialization::state_deserializer;
|
use automation_lib::helpers::serialization::state_deserializer;
|
||||||
use automation_lib::mqtt::WrappedAsyncClient;
|
use automation_lib::mqtt::WrappedAsyncClient;
|
||||||
use automation_macro::{LuaDevice, LuaDeviceConfig};
|
use automation_macro::{Device, LuaDeviceConfig, LuaSerialize};
|
||||||
use google_home::device;
|
use google_home::device;
|
||||||
use google_home::errors::ErrorCode;
|
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 rumqttc::{Publish, matches};
|
use rumqttc::{Publish, matches};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
@@ -22,33 +23,47 @@ use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
|
|||||||
use tracing::{debug, trace, warn};
|
use tracing::{debug, trace, warn};
|
||||||
|
|
||||||
pub trait LightState:
|
pub trait LightState:
|
||||||
Debug + Clone + Default + Sync + Send + Serialize + Into<StateOnOff> + 'static
|
Debug + Clone + Default + Sync + Send + Serialize + Into<StateOnOff> + Typed + 'static
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, LuaDeviceConfig)]
|
#[derive(Debug, Clone, LuaDeviceConfig, Typed)]
|
||||||
pub struct Config<T: LightState> {
|
#[typed(as = "ConfigLight")]
|
||||||
|
pub struct Config<T: LightState>
|
||||||
|
where
|
||||||
|
Light<T>: Typed,
|
||||||
|
{
|
||||||
#[device_config(flatten)]
|
#[device_config(flatten)]
|
||||||
|
#[typed(flatten)]
|
||||||
pub info: InfoConfig,
|
pub info: InfoConfig,
|
||||||
#[device_config(flatten)]
|
#[device_config(flatten)]
|
||||||
|
#[typed(flatten)]
|
||||||
pub mqtt: MqttDeviceConfig,
|
pub mqtt: MqttDeviceConfig,
|
||||||
|
|
||||||
#[device_config(from_lua, default)]
|
#[device_config(from_lua, default)]
|
||||||
pub callback: ActionCallback<Light<T>, T>,
|
#[typed(default)]
|
||||||
|
pub callback: ActionCallback<(Light<T>, T)>,
|
||||||
|
|
||||||
#[device_config(from_lua)]
|
#[device_config(from_lua)]
|
||||||
|
#[typed(default)]
|
||||||
pub client: WrappedAsyncClient,
|
pub client: WrappedAsyncClient,
|
||||||
}
|
}
|
||||||
|
crate::register_type!(Config<StateOnOff>);
|
||||||
|
crate::register_type!(Config<StateBrightness>);
|
||||||
|
crate::register_type!(Config<StateColorTemperature>);
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Default, Serialize, Deserialize, LuaSerialize, Typed)]
|
||||||
|
#[typed(as = "LightStateOnOff")]
|
||||||
pub struct StateOnOff {
|
pub struct StateOnOff {
|
||||||
#[serde(deserialize_with = "state_deserializer")]
|
#[serde(deserialize_with = "state_deserializer")]
|
||||||
state: bool,
|
state: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl LightState for StateOnOff {}
|
impl LightState for StateOnOff {}
|
||||||
|
crate::register_type!(StateOnOff);
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Default, Serialize, Deserialize, LuaSerialize, Typed)]
|
||||||
|
#[typed(as = "LightStateBrightness")]
|
||||||
pub struct StateBrightness {
|
pub struct StateBrightness {
|
||||||
#[serde(deserialize_with = "state_deserializer")]
|
#[serde(deserialize_with = "state_deserializer")]
|
||||||
state: bool,
|
state: bool,
|
||||||
@@ -56,6 +71,7 @@ pub struct StateBrightness {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl LightState for StateBrightness {}
|
impl LightState for StateBrightness {}
|
||||||
|
crate::register_type!(StateBrightness);
|
||||||
|
|
||||||
impl From<StateBrightness> for StateOnOff {
|
impl From<StateBrightness> for StateOnOff {
|
||||||
fn from(state: StateBrightness) -> Self {
|
fn from(state: StateBrightness) -> Self {
|
||||||
@@ -63,13 +79,15 @@ impl From<StateBrightness> for StateOnOff {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Default, Serialize, Deserialize, LuaSerialize, Typed)]
|
||||||
|
#[typed(as = "LightStateColorTemperature")]
|
||||||
pub struct StateColorTemperature {
|
pub struct StateColorTemperature {
|
||||||
#[serde(deserialize_with = "state_deserializer")]
|
#[serde(deserialize_with = "state_deserializer")]
|
||||||
state: bool,
|
state: bool,
|
||||||
brightness: f32,
|
brightness: f32,
|
||||||
color_temp: u32,
|
color_temp: u32,
|
||||||
}
|
}
|
||||||
|
crate::register_type!(StateColorTemperature);
|
||||||
|
|
||||||
impl LightState for StateColorTemperature {}
|
impl LightState for StateColorTemperature {}
|
||||||
|
|
||||||
@@ -88,21 +106,32 @@ impl From<StateColorTemperature> for StateBrightness {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, LuaDevice)]
|
#[derive(Debug, Clone, Device)]
|
||||||
#[traits(<StateOnOff>: OnOff)]
|
#[device(traits(OnOff for LightOnOff, LightBrightness, LightColorTemperature))]
|
||||||
#[traits(<StateBrightness>: OnOff, Brightness)]
|
#[device(traits(Brightness for LightBrightness, LightColorTemperature))]
|
||||||
#[traits(<StateColorTemperature>: OnOff, Brightness, ColorSetting)]
|
#[device(traits(ColorSetting for LightColorTemperature))]
|
||||||
pub struct Light<T: LightState> {
|
pub struct Light<T: LightState>
|
||||||
|
where
|
||||||
|
Light<T>: Typed,
|
||||||
|
{
|
||||||
config: Config<T>,
|
config: Config<T>,
|
||||||
|
|
||||||
state: Arc<RwLock<T>>,
|
state: Arc<RwLock<T>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub type LightOnOff = Light<StateOnOff>;
|
pub type LightOnOff = Light<StateOnOff>;
|
||||||
pub type LightBrightness = Light<StateBrightness>;
|
crate::register_device!(LightOnOff);
|
||||||
pub type LightColorTemperature = Light<StateColorTemperature>;
|
|
||||||
|
|
||||||
impl<T: LightState> Light<T> {
|
pub type LightBrightness = Light<StateBrightness>;
|
||||||
|
crate::register_device!(LightBrightness);
|
||||||
|
|
||||||
|
pub type LightColorTemperature = Light<StateColorTemperature>;
|
||||||
|
crate::register_device!(LightColorTemperature);
|
||||||
|
|
||||||
|
impl<T: LightState> Light<T>
|
||||||
|
where
|
||||||
|
Light<T>: Typed,
|
||||||
|
{
|
||||||
async fn state(&self) -> RwLockReadGuard<'_, T> {
|
async fn state(&self) -> RwLockReadGuard<'_, T> {
|
||||||
self.state.read().await
|
self.state.read().await
|
||||||
}
|
}
|
||||||
@@ -113,7 +142,10 @@ impl<T: LightState> Light<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl<T: LightState> LuaDeviceCreate for Light<T> {
|
impl<T: LightState> LuaDeviceCreate for Light<T>
|
||||||
|
where
|
||||||
|
Light<T>: Typed,
|
||||||
|
{
|
||||||
type Config = Config<T>;
|
type Config = Config<T>;
|
||||||
type Error = rumqttc::ClientError;
|
type Error = rumqttc::ClientError;
|
||||||
|
|
||||||
@@ -132,14 +164,17 @@ impl<T: LightState> LuaDeviceCreate for Light<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: LightState> Device for Light<T> {
|
impl<T: LightState> Device for Light<T>
|
||||||
|
where
|
||||||
|
Light<T>: Typed,
|
||||||
|
{
|
||||||
fn get_id(&self) -> String {
|
fn get_id(&self) -> String {
|
||||||
self.config.info.identifier()
|
self.config.info.identifier()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl OnMqtt for Light<StateOnOff> {
|
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(&message.topic, &self.config.mqtt.topic) {
|
if matches(&message.topic, &self.config.mqtt.topic) {
|
||||||
@@ -165,14 +200,14 @@ impl OnMqtt for Light<StateOnOff> {
|
|||||||
|
|
||||||
self.config
|
self.config
|
||||||
.callback
|
.callback
|
||||||
.call(self, self.state().await.deref())
|
.call((self.clone(), self.state().await.clone()))
|
||||||
.await;
|
.await;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl OnMqtt for Light<StateBrightness> {
|
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(&message.topic, &self.config.mqtt.topic) {
|
if matches(&message.topic, &self.config.mqtt.topic) {
|
||||||
@@ -204,14 +239,14 @@ impl OnMqtt for Light<StateBrightness> {
|
|||||||
|
|
||||||
self.config
|
self.config
|
||||||
.callback
|
.callback
|
||||||
.call(self, self.state().await.deref())
|
.call((self.clone(), self.state().await.clone()))
|
||||||
.await;
|
.await;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl OnMqtt for Light<StateColorTemperature> {
|
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(&message.topic, &self.config.mqtt.topic) {
|
if matches(&message.topic, &self.config.mqtt.topic) {
|
||||||
@@ -245,14 +280,17 @@ impl OnMqtt for Light<StateColorTemperature> {
|
|||||||
|
|
||||||
self.config
|
self.config
|
||||||
.callback
|
.callback
|
||||||
.call(self, self.state().await.deref())
|
.call((self.clone(), self.state().await.clone()))
|
||||||
.await;
|
.await;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl<T: LightState> google_home::Device for Light<T> {
|
impl<T: LightState> google_home::Device for Light<T>
|
||||||
|
where
|
||||||
|
Light<T>: Typed,
|
||||||
|
{
|
||||||
fn get_device_type(&self) -> Type {
|
fn get_device_type(&self) -> Type {
|
||||||
Type::Light
|
Type::Light
|
||||||
}
|
}
|
||||||
@@ -283,6 +321,7 @@ impl<T: LightState> google_home::Device for Light<T> {
|
|||||||
impl<T> OnOff for Light<T>
|
impl<T> OnOff for Light<T>
|
||||||
where
|
where
|
||||||
T: LightState,
|
T: LightState,
|
||||||
|
Light<T>: Typed,
|
||||||
{
|
{
|
||||||
async fn on(&self) -> Result<bool, ErrorCode> {
|
async fn on(&self) -> Result<bool, ErrorCode> {
|
||||||
let state = self.state().await;
|
let state = self.state().await;
|
||||||
@@ -322,6 +361,7 @@ impl<T> Brightness for Light<T>
|
|||||||
where
|
where
|
||||||
T: LightState,
|
T: LightState,
|
||||||
T: Into<StateBrightness>,
|
T: Into<StateBrightness>,
|
||||||
|
Light<T>: Typed,
|
||||||
{
|
{
|
||||||
async fn brightness(&self) -> Result<u8, ErrorCode> {
|
async fn brightness(&self) -> Result<u8, ErrorCode> {
|
||||||
let state = self.state().await;
|
let state = self.state().await;
|
||||||
@@ -363,6 +403,7 @@ impl<T> ColorSetting for Light<T>
|
|||||||
where
|
where
|
||||||
T: LightState,
|
T: LightState,
|
||||||
T: Into<StateColorTemperature>,
|
T: Into<StateColorTemperature>,
|
||||||
|
Light<T>: Typed,
|
||||||
{
|
{
|
||||||
fn color_temperature_range(&self) -> ColorTemperatureRange {
|
fn color_temperature_range(&self) -> ColorTemperatureRange {
|
||||||
ColorTemperatureRange {
|
ColorTemperatureRange {
|
||||||
|
|||||||
@@ -10,11 +10,12 @@ use automation_lib::device::{Device, LuaDeviceCreate};
|
|||||||
use automation_lib::event::OnMqtt;
|
use automation_lib::event::OnMqtt;
|
||||||
use automation_lib::helpers::serialization::state_deserializer;
|
use automation_lib::helpers::serialization::state_deserializer;
|
||||||
use automation_lib::mqtt::WrappedAsyncClient;
|
use automation_lib::mqtt::WrappedAsyncClient;
|
||||||
use automation_macro::{LuaDevice, LuaDeviceConfig};
|
use automation_macro::{Device, LuaDeviceConfig, LuaSerialize};
|
||||||
use google_home::device;
|
use google_home::device;
|
||||||
use google_home::errors::ErrorCode;
|
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 rumqttc::{Publish, matches};
|
use rumqttc::{Publish, matches};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
@@ -22,15 +23,16 @@ use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
|
|||||||
use tracing::{debug, trace, warn};
|
use tracing::{debug, trace, warn};
|
||||||
|
|
||||||
pub trait OutletState:
|
pub trait OutletState:
|
||||||
Debug + Clone + Default + Sync + Send + Serialize + Into<StateOnOff> + 'static
|
Debug + Clone + Default + Sync + Send + Serialize + Into<StateOnOff> + Typed + 'static
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Copy)]
|
#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Copy, Typed)]
|
||||||
pub enum OutletType {
|
pub enum OutletType {
|
||||||
Outlet,
|
Outlet,
|
||||||
Kettle,
|
Kettle,
|
||||||
}
|
}
|
||||||
|
crate::register_type!(OutletType);
|
||||||
|
|
||||||
impl From<OutletType> for Type {
|
impl From<OutletType> for Type {
|
||||||
fn from(outlet: OutletType) -> Self {
|
fn from(outlet: OutletType) -> Self {
|
||||||
@@ -41,36 +43,50 @@ impl From<OutletType> for Type {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, LuaDeviceConfig)]
|
#[derive(Debug, Clone, LuaDeviceConfig, Typed)]
|
||||||
pub struct Config<T: OutletState> {
|
#[typed(as = "ConfigOutlet")]
|
||||||
|
pub struct Config<T: OutletState>
|
||||||
|
where
|
||||||
|
Outlet<T>: Typed,
|
||||||
|
{
|
||||||
#[device_config(flatten)]
|
#[device_config(flatten)]
|
||||||
|
#[typed(flatten)]
|
||||||
pub info: InfoConfig,
|
pub info: InfoConfig,
|
||||||
#[device_config(flatten)]
|
#[device_config(flatten)]
|
||||||
|
#[typed(flatten)]
|
||||||
pub mqtt: MqttDeviceConfig,
|
pub mqtt: MqttDeviceConfig,
|
||||||
#[device_config(default(OutletType::Outlet))]
|
#[device_config(default(OutletType::Outlet))]
|
||||||
|
#[typed(default)]
|
||||||
pub outlet_type: OutletType,
|
pub outlet_type: OutletType,
|
||||||
|
|
||||||
#[device_config(from_lua, default)]
|
#[device_config(from_lua, default)]
|
||||||
pub callback: ActionCallback<Outlet<T>, T>,
|
#[typed(default)]
|
||||||
|
pub callback: ActionCallback<(Outlet<T>, T)>,
|
||||||
|
|
||||||
#[device_config(from_lua)]
|
#[device_config(from_lua)]
|
||||||
pub client: WrappedAsyncClient,
|
pub client: WrappedAsyncClient,
|
||||||
}
|
}
|
||||||
|
crate::register_type!(Config<StateOnOff>);
|
||||||
|
crate::register_type!(Config<StatePower>);
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Default, Serialize, Deserialize, LuaSerialize, Typed)]
|
||||||
|
#[typed(as = "OutletStateOnOff")]
|
||||||
pub struct StateOnOff {
|
pub struct StateOnOff {
|
||||||
#[serde(deserialize_with = "state_deserializer")]
|
#[serde(deserialize_with = "state_deserializer")]
|
||||||
state: bool,
|
state: bool,
|
||||||
}
|
}
|
||||||
|
crate::register_type!(StateOnOff);
|
||||||
|
|
||||||
impl OutletState for StateOnOff {}
|
impl OutletState for StateOnOff {}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Default, Serialize, Deserialize, LuaSerialize, Typed)]
|
||||||
|
#[typed(as = "OutletStatePower")]
|
||||||
pub struct StatePower {
|
pub struct StatePower {
|
||||||
#[serde(deserialize_with = "state_deserializer")]
|
#[serde(deserialize_with = "state_deserializer")]
|
||||||
state: bool,
|
state: bool,
|
||||||
power: f64,
|
power: f64,
|
||||||
}
|
}
|
||||||
|
crate::register_type!(StatePower);
|
||||||
|
|
||||||
impl OutletState for StatePower {}
|
impl OutletState for StatePower {}
|
||||||
|
|
||||||
@@ -80,19 +96,27 @@ impl From<StatePower> for StateOnOff {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, LuaDevice)]
|
#[derive(Debug, Clone, Device)]
|
||||||
#[traits(<StateOnOff>: OnOff)]
|
#[device(traits(OnOff for OutletOnOff, OutletPower))]
|
||||||
#[traits(<StatePower>: OnOff)]
|
pub struct Outlet<T: OutletState>
|
||||||
pub struct Outlet<T: OutletState> {
|
where
|
||||||
|
Outlet<T>: Typed,
|
||||||
|
{
|
||||||
config: Config<T>,
|
config: Config<T>,
|
||||||
|
|
||||||
state: Arc<RwLock<T>>,
|
state: Arc<RwLock<T>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub type OutletOnOff = Outlet<StateOnOff>;
|
pub type OutletOnOff = Outlet<StateOnOff>;
|
||||||
pub type OutletPower = Outlet<StatePower>;
|
crate::register_device!(OutletOnOff);
|
||||||
|
|
||||||
impl<T: OutletState> Outlet<T> {
|
pub type OutletPower = Outlet<StatePower>;
|
||||||
|
crate::register_device!(OutletPower);
|
||||||
|
|
||||||
|
impl<T: OutletState> Outlet<T>
|
||||||
|
where
|
||||||
|
Outlet<T>: Typed,
|
||||||
|
{
|
||||||
async fn state(&self) -> RwLockReadGuard<'_, T> {
|
async fn state(&self) -> RwLockReadGuard<'_, T> {
|
||||||
self.state.read().await
|
self.state.read().await
|
||||||
}
|
}
|
||||||
@@ -103,7 +127,10 @@ impl<T: OutletState> Outlet<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl<T: OutletState> LuaDeviceCreate for Outlet<T> {
|
impl<T: OutletState> LuaDeviceCreate for Outlet<T>
|
||||||
|
where
|
||||||
|
Outlet<T>: Typed,
|
||||||
|
{
|
||||||
type Config = Config<T>;
|
type Config = Config<T>;
|
||||||
type Error = rumqttc::ClientError;
|
type Error = rumqttc::ClientError;
|
||||||
|
|
||||||
@@ -122,14 +149,17 @@ impl<T: OutletState> LuaDeviceCreate for Outlet<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: OutletState> Device for Outlet<T> {
|
impl<T: OutletState> Device for Outlet<T>
|
||||||
|
where
|
||||||
|
Outlet<T>: Typed,
|
||||||
|
{
|
||||||
fn get_id(&self) -> String {
|
fn get_id(&self) -> String {
|
||||||
self.config.info.identifier()
|
self.config.info.identifier()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl OnMqtt for Outlet<StateOnOff> {
|
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(&message.topic, &self.config.mqtt.topic) {
|
if matches(&message.topic, &self.config.mqtt.topic) {
|
||||||
@@ -155,14 +185,14 @@ impl OnMqtt for Outlet<StateOnOff> {
|
|||||||
|
|
||||||
self.config
|
self.config
|
||||||
.callback
|
.callback
|
||||||
.call(self, self.state().await.deref())
|
.call((self.clone(), self.state().await.clone()))
|
||||||
.await;
|
.await;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl OnMqtt for Outlet<StatePower> {
|
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(&message.topic, &self.config.mqtt.topic) {
|
if matches(&message.topic, &self.config.mqtt.topic) {
|
||||||
@@ -192,14 +222,17 @@ impl OnMqtt for Outlet<StatePower> {
|
|||||||
|
|
||||||
self.config
|
self.config
|
||||||
.callback
|
.callback
|
||||||
.call(self, self.state().await.deref())
|
.call((self.clone(), self.state().await.clone()))
|
||||||
.await;
|
.await;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl<T: OutletState> google_home::Device for Outlet<T> {
|
impl<T: OutletState> google_home::Device for Outlet<T>
|
||||||
|
where
|
||||||
|
Outlet<T>: Typed,
|
||||||
|
{
|
||||||
fn get_device_type(&self) -> Type {
|
fn get_device_type(&self) -> Type {
|
||||||
self.config.outlet_type.into()
|
self.config.outlet_type.into()
|
||||||
}
|
}
|
||||||
@@ -230,6 +263,7 @@ impl<T: OutletState> google_home::Device for Outlet<T> {
|
|||||||
impl<T> OnOff for Outlet<T>
|
impl<T> OnOff for Outlet<T>
|
||||||
where
|
where
|
||||||
T: OutletState,
|
T: OutletState,
|
||||||
|
Outlet<T>: Typed,
|
||||||
{
|
{
|
||||||
async fn on(&self) -> Result<bool, ErrorCode> {
|
async fn on(&self) -> Result<bool, ErrorCode> {
|
||||||
let state = self.state().await;
|
let state = self.state().await;
|
||||||
|
|||||||
@@ -4,19 +4,20 @@ version = "0.1.0"
|
|||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
automation_macro = { workspace = true }
|
||||||
|
async-trait = { workspace = true }
|
||||||
automation_cast = { workspace = true }
|
automation_cast = { workspace = true }
|
||||||
|
bytes = { workspace = true }
|
||||||
|
dyn-clone = { workspace = true }
|
||||||
|
futures = { workspace = true }
|
||||||
google_home = { workspace = true }
|
google_home = { workspace = true }
|
||||||
|
hostname = { workspace = true }
|
||||||
|
inventory = { workspace = true }
|
||||||
|
lua_typed = { workspace = true }
|
||||||
|
mlua = { workspace = true }
|
||||||
rumqttc = { workspace = true }
|
rumqttc = { workspace = true }
|
||||||
serde = { workspace = true }
|
serde = { workspace = true }
|
||||||
serde_json = { workspace = true }
|
serde_json = { workspace = true }
|
||||||
|
thiserror = { workspace = true }
|
||||||
tokio = { workspace = true }
|
tokio = { workspace = true }
|
||||||
tracing = { workspace = true }
|
tracing = { workspace = true }
|
||||||
bytes = { workspace = true }
|
|
||||||
async-trait = { workspace = true }
|
|
||||||
futures = { workspace = true }
|
|
||||||
thiserror = { workspace = true }
|
|
||||||
indexmap = { workspace = true }
|
|
||||||
tokio-cron-scheduler = { workspace = true }
|
|
||||||
mlua = { workspace = true }
|
|
||||||
uuid = { workspace = true }
|
|
||||||
dyn-clone = { workspace = true }
|
|
||||||
|
|||||||
@@ -1,71 +1,94 @@
|
|||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
|
|
||||||
use mlua::{FromLua, IntoLua, LuaSerdeExt};
|
use futures::future::try_join_all;
|
||||||
use serde::Serialize;
|
use lua_typed::Typed;
|
||||||
|
use mlua::{FromLua, IntoLuaMulti};
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
struct Internal {
|
pub struct ActionCallback<P> {
|
||||||
uuid: uuid::Uuid,
|
callbacks: Vec<mlua::Function>,
|
||||||
lua: mlua::Lua,
|
_parameters: PhantomData<P>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
impl Typed for ActionCallback<()> {
|
||||||
pub struct ActionCallback<T, S> {
|
fn type_name() -> String {
|
||||||
internal: Option<Internal>,
|
"fun() | fun()[]".into()
|
||||||
_this: PhantomData<T>,
|
}
|
||||||
_state: PhantomData<S>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, S> Default for ActionCallback<T, S> {
|
impl<A: Typed> Typed for ActionCallback<A> {
|
||||||
|
fn type_name() -> String {
|
||||||
|
let type_name = A::type_name();
|
||||||
|
format!("fun(_: {type_name}) | fun(_: {type_name})[]")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<A: Typed, B: Typed> Typed for ActionCallback<(A, B)> {
|
||||||
|
fn type_name() -> String {
|
||||||
|
let type_name_a = A::type_name();
|
||||||
|
let type_name_b = B::type_name();
|
||||||
|
format!(
|
||||||
|
"fun(_: {type_name_a}, _: {type_name_b}) | fun(_: {type_name_a}, _: {type_name_b})[]"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NOTE: For some reason the derive macro combined with PhantomData leads to issues where it
|
||||||
|
// requires all types part of P to implement default, even if they never actually get constructed.
|
||||||
|
// By manually implemented Default it works fine.
|
||||||
|
impl<P> Default for ActionCallback<P> {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
internal: None,
|
callbacks: Default::default(),
|
||||||
_this: PhantomData::<T>,
|
_parameters: Default::default(),
|
||||||
_state: PhantomData::<S>,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, S> FromLua for ActionCallback<T, S> {
|
impl<P> FromLua for ActionCallback<P> {
|
||||||
fn from_lua(value: mlua::Value, lua: &mlua::Lua) -> mlua::Result<Self> {
|
fn from_lua(value: mlua::Value, _lua: &mlua::Lua) -> mlua::Result<Self> {
|
||||||
let uuid = uuid::Uuid::new_v4();
|
let callbacks = match value {
|
||||||
lua.set_named_registry_value(&uuid.to_string(), value)?;
|
mlua::Value::Function(f) => vec![f],
|
||||||
|
mlua::Value::Table(table) => table
|
||||||
|
.pairs::<mlua::Value, mlua::Function>()
|
||||||
|
.map(|pair| {
|
||||||
|
let (_, f) = pair?;
|
||||||
|
|
||||||
|
Ok::<_, mlua::Error>(f)
|
||||||
|
})
|
||||||
|
.try_collect()?,
|
||||||
|
_ => {
|
||||||
|
return Err(mlua::Error::FromLuaConversionError {
|
||||||
|
from: value.type_name(),
|
||||||
|
to: "ActionCallback".into(),
|
||||||
|
message: Some("expected function or table of functions".into()),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
Ok(ActionCallback {
|
Ok(ActionCallback {
|
||||||
internal: Some(Internal {
|
callbacks,
|
||||||
uuid,
|
_parameters: PhantomData::<P>,
|
||||||
lua: lua.clone(),
|
|
||||||
}),
|
|
||||||
_this: PhantomData::<T>,
|
|
||||||
_state: PhantomData::<S>,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Return proper error here
|
// TODO: Return proper error here
|
||||||
impl<T, S> ActionCallback<T, S>
|
impl<P> ActionCallback<P>
|
||||||
where
|
where
|
||||||
T: IntoLua + Sync + Send + Clone + 'static,
|
P: IntoLuaMulti + Sync + Clone,
|
||||||
S: Serialize,
|
|
||||||
{
|
{
|
||||||
pub async fn call(&self, this: &T, state: &S) {
|
pub async fn call(&self, parameters: P) {
|
||||||
let Some(internal) = self.internal.as_ref() else {
|
try_join_all(
|
||||||
return;
|
self.callbacks
|
||||||
};
|
.iter()
|
||||||
|
.map(async |f| f.call_async::<()>(parameters.clone()).await),
|
||||||
let state = internal.lua.to_value(state).unwrap();
|
)
|
||||||
|
.await
|
||||||
let callback: mlua::Value = internal
|
|
||||||
.lua
|
|
||||||
.named_registry_value(&internal.uuid.to_string())
|
|
||||||
.unwrap();
|
.unwrap();
|
||||||
match callback {
|
|
||||||
mlua::Value::Function(f) => f.call_async::<()>((this.clone(), state)).await.unwrap(),
|
|
||||||
_ => todo!("Only functions are currently supported"),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn is_set(&self) -> bool {
|
pub fn is_empty(&self) -> bool {
|
||||||
self.internal.is_some()
|
self.callbacks.is_empty()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,58 +1,7 @@
|
|||||||
use std::net::{Ipv4Addr, SocketAddr};
|
use lua_typed::Typed;
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
use rumqttc::{MqttOptions, Transport};
|
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
||||||
#[derive(Debug, Clone, 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, Deserialize)]
|
|
||||||
pub struct FulfillmentConfig {
|
|
||||||
pub openid_url: String,
|
|
||||||
#[serde(default = "default_fulfillment_ip")]
|
|
||||||
pub ip: Ipv4Addr,
|
|
||||||
#[serde(default = "default_fulfillment_port")]
|
|
||||||
pub port: u16,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<FulfillmentConfig> for SocketAddr {
|
|
||||||
fn from(fulfillment: FulfillmentConfig) -> Self {
|
|
||||||
(fulfillment.ip, fulfillment.port).into()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn default_fulfillment_ip() -> Ipv4Addr {
|
|
||||||
[0, 0, 0, 0].into()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn default_fulfillment_port() -> u16 {
|
|
||||||
7878
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize)]
|
|
||||||
pub struct InfoConfig {
|
pub struct InfoConfig {
|
||||||
pub name: String,
|
pub name: String,
|
||||||
pub room: Option<String>,
|
pub room: Option<String>,
|
||||||
@@ -68,7 +17,7 @@ impl InfoConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize)]
|
#[derive(Debug, Clone, Deserialize, Typed)]
|
||||||
pub struct MqttDeviceConfig {
|
pub struct MqttDeviceConfig {
|
||||||
pub topic: String,
|
pub topic: String,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ use std::fmt::Debug;
|
|||||||
|
|
||||||
use automation_cast::Cast;
|
use automation_cast::Cast;
|
||||||
use dyn_clone::DynClone;
|
use dyn_clone::DynClone;
|
||||||
use google_home::traits::OnOff;
|
use lua_typed::Typed;
|
||||||
use mlua::ObjectLike;
|
use mlua::ObjectLike;
|
||||||
|
|
||||||
use crate::event::OnMqtt;
|
use crate::event::OnMqtt;
|
||||||
@@ -18,7 +18,7 @@ pub trait LuaDeviceCreate {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub trait Device:
|
pub trait Device:
|
||||||
Debug + DynClone + Sync + Send + Cast<dyn google_home::Device> + Cast<dyn OnMqtt> + Cast<dyn OnOff>
|
Debug + DynClone + Sync + Send + Cast<dyn google_home::Device> + Cast<dyn OnMqtt>
|
||||||
{
|
{
|
||||||
fn get_id(&self) -> String;
|
fn get_id(&self) -> String;
|
||||||
}
|
}
|
||||||
@@ -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::<Box<dyn Device>>() {
|
let ud = if ud.is::<Self>() {
|
||||||
ud
|
ud
|
||||||
} else {
|
} else {
|
||||||
ud.call_method::<_>("__box", ())?
|
ud.call_method::<_>("__box", ())?
|
||||||
@@ -36,10 +36,19 @@ 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::RuntimeError("Expected user data".into())),
|
_ => Err(mlua::Error::runtime(format!(
|
||||||
|
"Expected user data, instead found: {}",
|
||||||
|
value.type_name()
|
||||||
|
))),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl mlua::UserData for Box<dyn Device> {}
|
impl mlua::UserData for Box<dyn Device> {}
|
||||||
|
|
||||||
|
impl Typed for Box<dyn Device> {
|
||||||
|
fn type_name() -> String {
|
||||||
|
"DeviceInterface".into()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
dyn_clone::clone_trait_object!(Device);
|
dyn_clone::clone_trait_object!(Device);
|
||||||
|
|||||||
@@ -1,11 +1,8 @@
|
|||||||
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 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;
|
||||||
@@ -17,7 +14,6 @@ pub type DeviceMap = HashMap<String, Box<dyn Device>>;
|
|||||||
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 {
|
||||||
@@ -27,7 +23,6 @@ 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({
|
||||||
@@ -43,8 +38,6 @@ impl DeviceManager {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
device_manager.scheduler.start().await.unwrap();
|
|
||||||
|
|
||||||
device_manager
|
device_manager
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -73,9 +66,7 @@ impl DeviceManager {
|
|||||||
match event {
|
match event {
|
||||||
Event::MqttMessage(message) => {
|
Event::MqttMessage(message) => {
|
||||||
let devices = self.devices.read().await;
|
let devices = self.devices.read().await;
|
||||||
let iter = devices.iter().map(|(id, device)| {
|
let iter = devices.iter().map(async |(id, device)| {
|
||||||
let message = message.clone();
|
|
||||||
async move {
|
|
||||||
let device: Option<&dyn OnMqtt> = device.cast();
|
let device: Option<&dyn OnMqtt> = device.cast();
|
||||||
if let Some(device) = device {
|
if let Some(device) = device {
|
||||||
// let subscribed = device
|
// let subscribed = device
|
||||||
@@ -85,11 +76,10 @@ impl DeviceManager {
|
|||||||
//
|
//
|
||||||
// if subscribed {
|
// if subscribed {
|
||||||
trace!(id, "Handling");
|
trace!(id, "Handling");
|
||||||
device.on_mqtt(message).await;
|
device.on_mqtt(message.clone()).await;
|
||||||
trace!(id, "Done");
|
trace!(id, "Done");
|
||||||
// }
|
// }
|
||||||
}
|
}
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
join_all(iter).await;
|
join_all(iter).await;
|
||||||
@@ -97,51 +87,3 @@ impl DeviceManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl mlua::UserData for DeviceManager {
|
|
||||||
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) {
|
|
||||||
methods.add_async_method("add", |_lua, this, device: Box<dyn Device>| async move {
|
|
||||||
this.add(device).await;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
});
|
|
||||||
|
|
||||||
methods.add_async_method(
|
|
||||||
"schedule",
|
|
||||||
|lua, this, (schedule, f): (String, mlua::Function)| async move {
|
|
||||||
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()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,11 +1 @@
|
|||||||
pub mod serialization;
|
pub mod serialization;
|
||||||
mod timeout;
|
|
||||||
|
|
||||||
pub use timeout::Timeout;
|
|
||||||
|
|
||||||
pub fn register_with_lua(lua: &mlua::Lua) -> mlua::Result<()> {
|
|
||||||
lua.globals()
|
|
||||||
.set("Timeout", lua.create_proxy::<Timeout>()?)?;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
#![allow(incomplete_features)]
|
#![feature(iterator_try_collect)]
|
||||||
|
#![feature(with_negative_coherence)]
|
||||||
|
|
||||||
|
use tracing::debug;
|
||||||
|
|
||||||
pub mod action_callback;
|
pub mod action_callback;
|
||||||
pub mod config;
|
pub mod config;
|
||||||
@@ -10,4 +13,50 @@ 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 DefinitionsFn = fn() -> String;
|
||||||
|
|
||||||
|
pub struct Module {
|
||||||
|
name: &'static str,
|
||||||
|
register_fn: RegisterFn,
|
||||||
|
definitions_fn: Option<DefinitionsFn>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Module {
|
||||||
|
pub const fn new(
|
||||||
|
name: &'static str,
|
||||||
|
register_fn: RegisterFn,
|
||||||
|
definitions_fn: Option<DefinitionsFn>,
|
||||||
|
) -> Self {
|
||||||
|
Self {
|
||||||
|
name,
|
||||||
|
register_fn,
|
||||||
|
definitions_fn,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const fn get_name(&self) -> &'static str {
|
||||||
|
self.name
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn register(&self, lua: &mlua::Lua) -> mlua::Result<mlua::Table> {
|
||||||
|
(self.register_fn)(lua)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn definitions(&self) -> Option<String> {
|
||||||
|
self.definitions_fn.map(|f| f())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn load_modules(lua: &mlua::Lua) -> mlua::Result<()> {
|
||||||
|
for module in inventory::iter::<Module> {
|
||||||
|
debug!(name = module.get_name(), "Loading module");
|
||||||
|
let table = module.register(lua)?;
|
||||||
|
lua.register_module(module.get_name(), table)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
inventory::collect!(Module);
|
||||||
|
|||||||
@@ -1 +1,3 @@
|
|||||||
pub mod traits;
|
pub mod traits;
|
||||||
|
|
||||||
|
mod utils;
|
||||||
|
|||||||
@@ -2,50 +2,89 @@ use std::ops::Deref;
|
|||||||
|
|
||||||
// TODO: Enable and disable functions based on query_only and command_only
|
// TODO: Enable and disable functions based on query_only and command_only
|
||||||
|
|
||||||
pub trait OnOff {
|
pub trait PartialUserData<T> {
|
||||||
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M)
|
fn add_methods<M: mlua::UserDataMethods<T>>(methods: &mut M);
|
||||||
|
|
||||||
|
fn interface_name() -> Option<&'static str> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
fn definitions() -> Option<String> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Device;
|
||||||
|
|
||||||
|
impl<T> PartialUserData<T> for Device
|
||||||
where
|
where
|
||||||
Self: Sized + google_home::traits::OnOff + 'static,
|
T: crate::device::Device + 'static,
|
||||||
{
|
{
|
||||||
methods.add_async_method("set_on", |_lua, this, on: bool| async move {
|
fn add_methods<M: mlua::UserDataMethods<T>>(methods: &mut M) {
|
||||||
|
methods.add_async_method("get_id", async |_lua, this, _: ()| Ok(this.get_id()));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn interface_name() -> Option<&'static str> {
|
||||||
|
Some("DeviceInterface")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct OnOff;
|
||||||
|
|
||||||
|
impl<T> PartialUserData<T> for OnOff
|
||||||
|
where
|
||||||
|
T: google_home::traits::OnOff + 'static,
|
||||||
|
{
|
||||||
|
fn add_methods<M: mlua::UserDataMethods<T>>(methods: &mut M) {
|
||||||
|
methods.add_async_method("set_on", async |_lua, this, on: bool| {
|
||||||
this.deref().set_on(on).await.unwrap();
|
this.deref().set_on(on).await.unwrap();
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
});
|
});
|
||||||
|
|
||||||
methods.add_async_method("on", |_lua, this, ()| async move {
|
methods.add_async_method("on", async |_lua, this, ()| {
|
||||||
Ok(this.deref().on().await.unwrap())
|
Ok(this.deref().on().await.unwrap())
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
|
||||||
impl<T> OnOff for T where T: google_home::traits::OnOff {}
|
|
||||||
|
|
||||||
pub trait Brightness {
|
fn interface_name() -> Option<&'static str> {
|
||||||
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M)
|
Some("OnOffInterface")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Brightness;
|
||||||
|
|
||||||
|
impl<T> PartialUserData<T> for Brightness
|
||||||
where
|
where
|
||||||
Self: Sized + google_home::traits::Brightness + 'static,
|
T: google_home::traits::Brightness + 'static,
|
||||||
{
|
{
|
||||||
methods.add_async_method("set_brightness", |_lua, this, brightness: u8| async move {
|
fn add_methods<M: mlua::UserDataMethods<T>>(methods: &mut M) {
|
||||||
|
methods.add_async_method("set_brightness", async |_lua, this, brightness: u8| {
|
||||||
this.set_brightness(brightness).await.unwrap();
|
this.set_brightness(brightness).await.unwrap();
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
});
|
});
|
||||||
|
|
||||||
methods.add_async_method("brightness", |_lua, this, _: ()| async move {
|
methods.add_async_method("brightness", async |_lua, this, _: ()| {
|
||||||
Ok(this.brightness().await.unwrap())
|
Ok(this.brightness().await.unwrap())
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
|
||||||
impl<T> Brightness for T where T: google_home::traits::Brightness {}
|
|
||||||
|
|
||||||
pub trait ColorSetting {
|
fn interface_name() -> Option<&'static str> {
|
||||||
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M)
|
Some("BrightnessInterface")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct ColorSetting;
|
||||||
|
|
||||||
|
impl<T> PartialUserData<T> for ColorSetting
|
||||||
where
|
where
|
||||||
Self: Sized + google_home::traits::ColorSetting + 'static,
|
T: google_home::traits::ColorSetting + 'static,
|
||||||
{
|
{
|
||||||
|
fn add_methods<M: mlua::UserDataMethods<T>>(methods: &mut M) {
|
||||||
methods.add_async_method(
|
methods.add_async_method(
|
||||||
"set_color_temperature",
|
"set_color_temperature",
|
||||||
|_lua, this, temperature: u32| async move {
|
async |_lua, this, temperature: u32| {
|
||||||
this.set_color(google_home::traits::Color { temperature })
|
this.set_color(google_home::traits::Color { temperature })
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -54,36 +93,35 @@ pub trait ColorSetting {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
methods.add_async_method("color_temperature", |_lua, this, ()| async move {
|
methods.add_async_method("color_temperature", async |_lua, this, ()| {
|
||||||
Ok(this.color().await.temperature)
|
Ok(this.color().await.temperature)
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
|
||||||
impl<T> ColorSetting for T where T: google_home::traits::ColorSetting {}
|
|
||||||
|
|
||||||
pub trait OpenClose {
|
fn interface_name() -> Option<&'static str> {
|
||||||
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M)
|
Some("ColorSettingInterface")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct OpenClose;
|
||||||
|
|
||||||
|
impl<T> PartialUserData<T> for OpenClose
|
||||||
where
|
where
|
||||||
Self: Sized + google_home::traits::OpenClose + 'static,
|
T: google_home::traits::OpenClose + 'static,
|
||||||
{
|
{
|
||||||
methods.add_async_method(
|
fn add_methods<M: mlua::UserDataMethods<T>>(methods: &mut M) {
|
||||||
"set_open_percent",
|
methods.add_async_method("set_open_percent", async |_lua, this, open_percent: u8| {
|
||||||
|_lua, this, open_percent: u8| async move {
|
|
||||||
this.set_open_percent(open_percent).await.unwrap();
|
this.set_open_percent(open_percent).await.unwrap();
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
},
|
});
|
||||||
);
|
|
||||||
|
|
||||||
methods.add_async_method("open_percent", |_lua, this, _: ()| async move {
|
methods.add_async_method("open_percent", async |_lua, this, _: ()| {
|
||||||
Ok(this.open_percent().await.unwrap())
|
Ok(this.open_percent().await.unwrap())
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
|
||||||
impl<T> OpenClose for T where T: google_home::traits::OpenClose {}
|
|
||||||
|
|
||||||
pub trait AddAdditionalMethods {
|
fn interface_name() -> Option<&'static str> {
|
||||||
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M)
|
Some("OpenCloseInterface")
|
||||||
where
|
}
|
||||||
Self: Sized + 'static;
|
|
||||||
}
|
}
|
||||||
|
|||||||
48
automation_lib/src/lua/utils/mod.rs
Normal file
48
automation_lib/src/lua/utils/mod.rs
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
mod timeout;
|
||||||
|
|
||||||
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
|
use lua_typed::Typed;
|
||||||
|
pub use timeout::Timeout;
|
||||||
|
|
||||||
|
use crate::Module;
|
||||||
|
|
||||||
|
fn create_module(lua: &mlua::Lua) -> mlua::Result<mlua::Table> {
|
||||||
|
let utils = lua.create_table()?;
|
||||||
|
|
||||||
|
utils.set(Timeout::type_name(), lua.create_proxy::<Timeout>()?)?;
|
||||||
|
|
||||||
|
let get_hostname = lua.create_function(|_lua, ()| {
|
||||||
|
hostname::get()
|
||||||
|
.map(|name| name.to_str().unwrap_or("unknown").to_owned())
|
||||||
|
.map_err(mlua::ExternalError::into_lua_err)
|
||||||
|
})?;
|
||||||
|
utils.set("get_hostname", get_hostname)?;
|
||||||
|
let get_epoch = lua.create_function(|_lua, ()| {
|
||||||
|
Ok(SystemTime::now()
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.expect("Time is after UNIX EPOCH")
|
||||||
|
.as_millis())
|
||||||
|
})?;
|
||||||
|
utils.set("get_epoch", get_epoch)?;
|
||||||
|
|
||||||
|
Ok(utils)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn generate_definitions() -> String {
|
||||||
|
let mut output = String::new();
|
||||||
|
|
||||||
|
output += "---@meta\n\nlocal utils\n\n";
|
||||||
|
|
||||||
|
output += &Timeout::generate_full().expect("Timeout should have generate_full");
|
||||||
|
output += "\n";
|
||||||
|
|
||||||
|
output += "---@return string\nfunction utils.get_hostname() end\n\n";
|
||||||
|
output += "---@return integer\nfunction utils.get_epoch() end\n\n";
|
||||||
|
|
||||||
|
output += "return utils";
|
||||||
|
|
||||||
|
output
|
||||||
|
}
|
||||||
|
|
||||||
|
inventory::submit! {Module::new("automation:utils", create_module, Some(generate_definitions))}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use lua_typed::Typed;
|
||||||
use tokio::sync::RwLock;
|
use tokio::sync::RwLock;
|
||||||
use tokio::task::JoinHandle;
|
use tokio::task::JoinHandle;
|
||||||
use tracing::debug;
|
use tracing::debug;
|
||||||
@@ -29,7 +30,7 @@ impl mlua::UserData for Timeout {
|
|||||||
|
|
||||||
methods.add_async_method(
|
methods.add_async_method(
|
||||||
"start",
|
"start",
|
||||||
|_lua, this, (timeout, callback): (f32, ActionCallback<mlua::Value, bool>)| async move {
|
async |_lua, this, (timeout, callback): (f32, ActionCallback<()>)| {
|
||||||
if let Some(handle) = this.state.write().await.handle.take() {
|
if let Some(handle) = this.state.write().await.handle.take() {
|
||||||
handle.abort();
|
handle.abort();
|
||||||
}
|
}
|
||||||
@@ -42,7 +43,7 @@ impl mlua::UserData for Timeout {
|
|||||||
async move {
|
async move {
|
||||||
tokio::time::sleep(timeout).await;
|
tokio::time::sleep(timeout).await;
|
||||||
|
|
||||||
callback.call(&mlua::Nil, &false).await;
|
callback.call(()).await;
|
||||||
}
|
}
|
||||||
}));
|
}));
|
||||||
|
|
||||||
@@ -50,7 +51,7 @@ impl mlua::UserData for Timeout {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
methods.add_async_method("cancel", |_lua, this, ()| async move {
|
methods.add_async_method("cancel", async |_lua, this, ()| {
|
||||||
debug!("Canceling timeout callback");
|
debug!("Canceling timeout callback");
|
||||||
|
|
||||||
if let Some(handle) = this.state.write().await.handle.take() {
|
if let Some(handle) = this.state.write().await.handle.take() {
|
||||||
@@ -60,7 +61,7 @@ impl mlua::UserData for Timeout {
|
|||||||
Ok(())
|
Ok(())
|
||||||
});
|
});
|
||||||
|
|
||||||
methods.add_async_method("is_waiting", |_lua, this, ()| async move {
|
methods.add_async_method("is_waiting", async |_lua, this, ()| {
|
||||||
debug!("Canceling timeout callback");
|
debug!("Canceling timeout callback");
|
||||||
|
|
||||||
if let Some(handle) = this.state.read().await.handle.as_ref() {
|
if let Some(handle) = this.state.read().await.handle.as_ref() {
|
||||||
@@ -74,3 +75,44 @@ impl mlua::UserData for Timeout {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Typed for Timeout {
|
||||||
|
fn type_name() -> String {
|
||||||
|
"Timeout".into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn generate_header() -> Option<String> {
|
||||||
|
let type_name = Self::type_name();
|
||||||
|
Some(format!("---@class {type_name}\nlocal {type_name}\n"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn generate_members() -> Option<String> {
|
||||||
|
let mut output = String::new();
|
||||||
|
|
||||||
|
let type_name = Self::type_name();
|
||||||
|
|
||||||
|
output += &format!(
|
||||||
|
"---@async\n---@param timeout number\n---@param callback {}\nfunction {type_name}:start(timeout, callback) end\n",
|
||||||
|
ActionCallback::<()>::type_name()
|
||||||
|
);
|
||||||
|
|
||||||
|
output += &format!("---@async\nfunction {type_name}:cancel() end\n",);
|
||||||
|
|
||||||
|
output +=
|
||||||
|
&format!("---@async\n---@return boolean\nfunction {type_name}:is_waiting() end\n",);
|
||||||
|
|
||||||
|
Some(output)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn generate_footer() -> Option<String> {
|
||||||
|
let mut output = String::new();
|
||||||
|
|
||||||
|
let type_name = Self::type_name();
|
||||||
|
|
||||||
|
output += &format!("utils.{type_name} = {{}}\n");
|
||||||
|
output += &format!("---@return {type_name}\n");
|
||||||
|
output += &format!("function utils.{type_name}.new() end\n");
|
||||||
|
|
||||||
|
Some(output)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -68,13 +68,8 @@ pub enum RemoteAction {
|
|||||||
// Message used to report the action performed by a remote
|
// Message used to report the action performed by a remote
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize)]
|
||||||
pub struct RemoteMessage {
|
pub struct RemoteMessage {
|
||||||
action: RemoteAction,
|
pub action: Option<RemoteAction>,
|
||||||
}
|
pub battery: Option<f32>,
|
||||||
|
|
||||||
impl RemoteMessage {
|
|
||||||
pub fn action(&self) -> RemoteAction {
|
|
||||||
self.action
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TryFrom<Publish> for RemoteMessage {
|
impl TryFrom<Publish> for RemoteMessage {
|
||||||
@@ -144,13 +139,8 @@ impl TryFrom<Publish> for BrightnessMessage {
|
|||||||
// Message to report the state of a contact sensor
|
// Message to report the state of a contact sensor
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize)]
|
||||||
pub struct ContactMessage {
|
pub struct ContactMessage {
|
||||||
contact: bool,
|
pub contact: Option<bool>,
|
||||||
}
|
pub battery: Option<f32>,
|
||||||
|
|
||||||
impl ContactMessage {
|
|
||||||
pub fn is_closed(&self) -> bool {
|
|
||||||
self.contact
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TryFrom<Publish> for ContactMessage {
|
impl TryFrom<Publish> for ContactMessage {
|
||||||
|
|||||||
@@ -1,14 +1,67 @@
|
|||||||
use std::ops::{Deref, DerefMut};
|
use std::ops::{Deref, DerefMut};
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use automation_macro::LuaDeviceConfig;
|
||||||
|
use lua_typed::Typed;
|
||||||
use mlua::FromLua;
|
use mlua::FromLua;
|
||||||
use rumqttc::{AsyncClient, Event, EventLoop, Incoming};
|
use rumqttc::{AsyncClient, Event, Incoming, MqttOptions, Transport};
|
||||||
|
use serde::Deserialize;
|
||||||
use tracing::{debug, warn};
|
use tracing::{debug, warn};
|
||||||
|
|
||||||
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(Duration::from_secs(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);
|
||||||
|
|
||||||
|
impl Typed for WrappedAsyncClient {
|
||||||
|
fn type_name() -> String {
|
||||||
|
"AsyncClient".into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn generate_header() -> Option<String> {
|
||||||
|
let type_name = Self::type_name();
|
||||||
|
Some(format!("---@class {type_name}\nlocal {type_name}\n"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn generate_members() -> Option<String> {
|
||||||
|
let mut output = String::new();
|
||||||
|
|
||||||
|
let type_name = Self::type_name();
|
||||||
|
|
||||||
|
output += &format!(
|
||||||
|
"---@async\n---@param topic string\n---@param message table?\nfunction {type_name}:send_message(topic, message) end\n"
|
||||||
|
);
|
||||||
|
|
||||||
|
Some(output)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl Deref for WrappedAsyncClient {
|
impl Deref for WrappedAsyncClient {
|
||||||
type Target = AsyncClient;
|
type Target = AsyncClient;
|
||||||
|
|
||||||
@@ -27,8 +80,14 @@ impl mlua::UserData for WrappedAsyncClient {
|
|||||||
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) {
|
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) {
|
||||||
methods.add_async_method(
|
methods.add_async_method(
|
||||||
"send_message",
|
"send_message",
|
||||||
|_lua, this, (topic, message): (String, mlua::Value)| async move {
|
async |_lua, this, (topic, message): (String, mlua::Value)| {
|
||||||
let message = serde_json::to_string(&message).unwrap();
|
// serde_json converts nil => "null", but we actually want nil to send an empty
|
||||||
|
// message
|
||||||
|
let message = if message.is_nil() {
|
||||||
|
"".into()
|
||||||
|
} else {
|
||||||
|
serde_json::to_string(&message).unwrap()
|
||||||
|
};
|
||||||
|
|
||||||
debug!("message = {message}");
|
debug!("message = {message}");
|
||||||
|
|
||||||
@@ -43,8 +102,9 @@ impl mlua::UserData for WrappedAsyncClient {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn start(mut eventloop: EventLoop, event_channel: &EventChannel) {
|
pub fn start(config: MqttConfig, event_channel: &EventChannel) -> WrappedAsyncClient {
|
||||||
let tx = event_channel.get_tx();
|
let tx = event_channel.get_tx();
|
||||||
|
let (client, mut eventloop) = AsyncClient::new(config.into(), 100);
|
||||||
|
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
debug!("Listening for MQTT events");
|
debug!("Listening for MQTT events");
|
||||||
@@ -63,4 +123,6 @@ pub fn start(mut eventloop: EventLoop, event_channel: &EventChannel) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
WrappedAsyncClient(client)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,17 +0,0 @@
|
|||||||
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>>,
|
|
||||||
// }
|
|
||||||
@@ -11,3 +11,6 @@ itertools = { workspace = true }
|
|||||||
proc-macro2 = { workspace = true }
|
proc-macro2 = { workspace = true }
|
||||||
quote = { workspace = true }
|
quote = { workspace = true }
|
||||||
syn = { workspace = true }
|
syn = { workspace = true }
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
mlua = { workspace = true }
|
||||||
|
|||||||
265
automation_macro/src/device.rs
Normal file
265
automation_macro/src/device.rs
Normal file
@@ -0,0 +1,265 @@
|
|||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use proc_macro2::TokenStream as TokenStream2;
|
||||||
|
use quote::quote;
|
||||||
|
use syn::parse::{Parse, ParseStream};
|
||||||
|
use syn::punctuated::Punctuated;
|
||||||
|
use syn::spanned::Spanned;
|
||||||
|
use syn::{Attribute, DeriveInput, Token, parenthesized};
|
||||||
|
|
||||||
|
enum Attr {
|
||||||
|
Trait(TraitAttr),
|
||||||
|
ExtraUserData(ExtraUserDataAttr),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Attr {
|
||||||
|
fn parse(attr: &Attribute) -> syn::Result<Self> {
|
||||||
|
let mut parsed = None;
|
||||||
|
attr.parse_nested_meta(|meta| {
|
||||||
|
if meta.path.is_ident("traits") {
|
||||||
|
let input;
|
||||||
|
_ = parenthesized!(input in meta.input);
|
||||||
|
parsed = Some(Attr::Trait(input.parse()?));
|
||||||
|
} else if meta.path.is_ident("extra_user_data") {
|
||||||
|
let value = meta.value()?;
|
||||||
|
parsed = Some(Attr::ExtraUserData(value.parse()?));
|
||||||
|
} else {
|
||||||
|
return Err(syn::Error::new(meta.path.span(), "Unknown attribute"));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
})?;
|
||||||
|
|
||||||
|
Ok(parsed.expect("Parsed should be set"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TraitAttr {
|
||||||
|
traits: Traits,
|
||||||
|
aliases: Aliases,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Parse for TraitAttr {
|
||||||
|
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||||
|
Ok(Self {
|
||||||
|
traits: input.parse()?,
|
||||||
|
aliases: input.parse()?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct Traits(Vec<syn::Ident>);
|
||||||
|
|
||||||
|
impl Traits {
|
||||||
|
fn extend(&mut self, other: &Traits) {
|
||||||
|
self.0.extend_from_slice(&other.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Parse for Traits {
|
||||||
|
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||||
|
input
|
||||||
|
.call(Punctuated::<_, Token![,]>::parse_separated_nonempty)
|
||||||
|
.map(|traits| traits.into_iter().collect())
|
||||||
|
.map(Self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct Aliases(Vec<syn::Ident>);
|
||||||
|
|
||||||
|
impl Aliases {
|
||||||
|
fn has_aliases(&self) -> bool {
|
||||||
|
!self.0.is_empty()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Parse for Aliases {
|
||||||
|
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||||
|
if !input.peek(Token![for]) {
|
||||||
|
if input.is_empty() {
|
||||||
|
return Ok(Default::default());
|
||||||
|
} else {
|
||||||
|
return Err(input.error("Expected ')' or 'for'"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = input.parse::<syn::Token![for]>()?;
|
||||||
|
|
||||||
|
input
|
||||||
|
.call(Punctuated::<_, Token![,]>::parse_separated_nonempty)
|
||||||
|
.map(|aliases| aliases.into_iter().collect())
|
||||||
|
.map(Self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
struct ExtraUserDataAttr(syn::Ident);
|
||||||
|
|
||||||
|
impl Parse for ExtraUserDataAttr {
|
||||||
|
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||||
|
Ok(Self(input.parse()?))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Implementation {
|
||||||
|
name: syn::Ident,
|
||||||
|
traits: Traits,
|
||||||
|
extra_user_data: Vec<ExtraUserDataAttr>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl quote::ToTokens for Implementation {
|
||||||
|
fn to_tokens(&self, tokens: &mut TokenStream2) {
|
||||||
|
let Self {
|
||||||
|
name,
|
||||||
|
traits,
|
||||||
|
extra_user_data,
|
||||||
|
} = &self;
|
||||||
|
let Traits(traits) = traits;
|
||||||
|
let extra_user_data: Vec<_> = extra_user_data.iter().map(|tr| tr.0.clone()).collect();
|
||||||
|
|
||||||
|
tokens.extend(quote! {
|
||||||
|
impl mlua::UserData for #name {
|
||||||
|
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) {
|
||||||
|
methods.add_async_function("new", async |_lua, config| {
|
||||||
|
let device: Self = LuaDeviceCreate::create(config)
|
||||||
|
.await
|
||||||
|
.map_err(mlua::ExternalError::into_lua_err)?;
|
||||||
|
|
||||||
|
Ok(device)
|
||||||
|
});
|
||||||
|
|
||||||
|
methods.add_method("__box", |_lua, this, _: ()| {
|
||||||
|
let b: Box<dyn Device> = Box::new(this.clone());
|
||||||
|
Ok(b)
|
||||||
|
});
|
||||||
|
|
||||||
|
<::automation_lib::lua::traits::Device as ::automation_lib::lua::traits::PartialUserData<#name>>::add_methods(methods);
|
||||||
|
|
||||||
|
#(
|
||||||
|
<::automation_lib::lua::traits::#traits as ::automation_lib::lua::traits::PartialUserData<#name>>::add_methods(methods);
|
||||||
|
)*
|
||||||
|
|
||||||
|
#(
|
||||||
|
<#extra_user_data as ::automation_lib::lua::traits::PartialUserData<#name>>::add_methods(methods);
|
||||||
|
)*
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ::lua_typed::Typed for #name {
|
||||||
|
fn type_name() -> String {
|
||||||
|
stringify!(#name).into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn generate_header() -> std::option::Option<::std::string::String> {
|
||||||
|
let type_name = <Self as ::lua_typed::Typed>::type_name();
|
||||||
|
let mut output = String::new();
|
||||||
|
|
||||||
|
let interfaces: String = [
|
||||||
|
<::automation_lib::lua::traits::Device as ::automation_lib::lua::traits::PartialUserData<#name>>::interface_name(),
|
||||||
|
#(
|
||||||
|
<::automation_lib::lua::traits::#traits as ::automation_lib::lua::traits::PartialUserData<#name>>::interface_name(),
|
||||||
|
)*
|
||||||
|
].into_iter().flatten().intersperse(", ").collect();
|
||||||
|
|
||||||
|
let interfaces = if interfaces.is_empty() {
|
||||||
|
"".into()
|
||||||
|
} else {
|
||||||
|
format!(": {interfaces}")
|
||||||
|
};
|
||||||
|
|
||||||
|
Some(format!("---@class {type_name}{interfaces}\nlocal {type_name}\n"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn generate_members() -> Option<String> {
|
||||||
|
let mut output = String::new();
|
||||||
|
|
||||||
|
let type_name = <Self as ::lua_typed::Typed>::type_name();
|
||||||
|
output += &format!("devices.{type_name} = {{}}\n");
|
||||||
|
let config_name = <<Self as ::automation_lib::device::LuaDeviceCreate>::Config as ::lua_typed::Typed>::type_name();
|
||||||
|
output += &format!("---@param config {config_name}\n");
|
||||||
|
output += &format!("---@return {type_name}\n");
|
||||||
|
output += &format!("function devices.{type_name}.new(config) end\n");
|
||||||
|
|
||||||
|
output += &<::automation_lib::lua::traits::Device as ::automation_lib::lua::traits::PartialUserData<#name>>::definitions().unwrap_or("".into());
|
||||||
|
|
||||||
|
#(
|
||||||
|
output += &<::automation_lib::lua::traits::#traits as ::automation_lib::lua::traits::PartialUserData<#name>>::definitions().unwrap_or("".into());
|
||||||
|
)*
|
||||||
|
#(
|
||||||
|
output += &<#extra_user_data as ::automation_lib::lua::traits::PartialUserData<#name>>::definitions().unwrap_or("".into());
|
||||||
|
)*
|
||||||
|
|
||||||
|
|
||||||
|
Some(output)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Implementations(Vec<Implementation>);
|
||||||
|
|
||||||
|
impl Implementations {
|
||||||
|
fn from_attr(attributes: Vec<Attr>, name: syn::Ident) -> Self {
|
||||||
|
let mut add_methods = Vec::new();
|
||||||
|
let mut all = Traits::default();
|
||||||
|
let mut implementations: HashMap<_, Traits> = HashMap::new();
|
||||||
|
for attribute in attributes {
|
||||||
|
match attribute {
|
||||||
|
Attr::Trait(attribute) => {
|
||||||
|
if attribute.aliases.has_aliases() {
|
||||||
|
for alias in &attribute.aliases.0 {
|
||||||
|
implementations
|
||||||
|
.entry(Some(alias.clone()))
|
||||||
|
.or_default()
|
||||||
|
.extend(&attribute.traits);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
all.extend(&attribute.traits);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Attr::ExtraUserData(attribute) => add_methods.push(attribute),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if implementations.is_empty() {
|
||||||
|
implementations.entry(None).or_default().extend(&all);
|
||||||
|
} else {
|
||||||
|
for traits in implementations.values_mut() {
|
||||||
|
traits.extend(&all);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Self(
|
||||||
|
implementations
|
||||||
|
.into_iter()
|
||||||
|
.map(|(alias, traits)| Implementation {
|
||||||
|
name: alias.unwrap_or(name.clone()),
|
||||||
|
traits,
|
||||||
|
extra_user_data: add_methods.clone(),
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn device(input: DeriveInput) -> TokenStream2 {
|
||||||
|
let Implementations(imp) = match input
|
||||||
|
.attrs
|
||||||
|
.iter()
|
||||||
|
.filter(|attr| attr.path().is_ident("device"))
|
||||||
|
.map(Attr::parse)
|
||||||
|
.try_collect::<Vec<_>>()
|
||||||
|
{
|
||||||
|
Ok(attr) => Implementations::from_attr(attr, input.ident),
|
||||||
|
Err(err) => return err.into_compile_error(),
|
||||||
|
};
|
||||||
|
|
||||||
|
quote! {
|
||||||
|
#(
|
||||||
|
#imp
|
||||||
|
)*
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,88 +0,0 @@
|
|||||||
use proc_macro2::TokenStream;
|
|
||||||
use quote::{ToTokens, quote};
|
|
||||||
use syn::parse::Parse;
|
|
||||||
use syn::punctuated::Punctuated;
|
|
||||||
use syn::{AngleBracketedGenericArguments, Attribute, DeriveInput, Ident, Path, Token};
|
|
||||||
|
|
||||||
#[derive(Debug, Default)]
|
|
||||||
struct Impl {
|
|
||||||
generics: Option<AngleBracketedGenericArguments>,
|
|
||||||
traits: Vec<Path>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Parse for Impl {
|
|
||||||
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
|
|
||||||
let generics = if input.peek(Token![<]) {
|
|
||||||
let generics = input.parse()?;
|
|
||||||
input.parse::<Token![:]>()?;
|
|
||||||
|
|
||||||
Some(generics)
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
|
|
||||||
let traits: Punctuated<_, _> = input.parse_terminated(Path::parse, Token![,])?;
|
|
||||||
let traits = traits.into_iter().collect();
|
|
||||||
|
|
||||||
Ok(Impl { generics, traits })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Impl {
|
|
||||||
fn generate(&self, name: &Ident) -> TokenStream {
|
|
||||||
let generics = &self.generics;
|
|
||||||
|
|
||||||
// If an identifier is specified, assume it is placed in ::automation_lib::lua::traits,
|
|
||||||
// otherwise use the provided path
|
|
||||||
let traits = self.traits.iter().map(|t| {
|
|
||||||
if let Some(ident) = t.get_ident() {
|
|
||||||
quote! {::automation_lib::lua::traits::#ident }
|
|
||||||
} else {
|
|
||||||
t.to_token_stream()
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
quote! {
|
|
||||||
impl mlua::UserData for #name #generics {
|
|
||||||
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) {
|
|
||||||
methods.add_async_function("new", |_lua, config| async {
|
|
||||||
let device: Self = LuaDeviceCreate::create(config)
|
|
||||||
.await
|
|
||||||
.map_err(mlua::ExternalError::into_lua_err)?;
|
|
||||||
|
|
||||||
Ok(device)
|
|
||||||
});
|
|
||||||
|
|
||||||
methods.add_method("__box", |_lua, this, _: ()| {
|
|
||||||
let b: Box<dyn Device> = Box::new(this.clone());
|
|
||||||
Ok(b)
|
|
||||||
});
|
|
||||||
|
|
||||||
methods.add_async_method("get_id", |_lua, this, _: ()| async move { Ok(this.get_id()) });
|
|
||||||
|
|
||||||
#(
|
|
||||||
#traits::add_methods(methods);
|
|
||||||
)*
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn impl_device_macro(ast: &DeriveInput) -> TokenStream {
|
|
||||||
let name = &ast.ident;
|
|
||||||
|
|
||||||
let impls: TokenStream = ast
|
|
||||||
.attrs
|
|
||||||
.iter()
|
|
||||||
.filter(|attr| attr.path().is_ident("traits"))
|
|
||||||
.flat_map(Attribute::parse_args::<Impl>)
|
|
||||||
.map(|im| im.generate(name))
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
if impls.is_empty() {
|
|
||||||
Impl::default().generate(name)
|
|
||||||
} else {
|
|
||||||
impls
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,12 +1,12 @@
|
|||||||
#![feature(iter_intersperse)]
|
#![feature(iter_intersperse)]
|
||||||
mod impl_device;
|
#![feature(iterator_try_collect)]
|
||||||
|
mod device;
|
||||||
mod lua_device_config;
|
mod lua_device_config;
|
||||||
|
|
||||||
use lua_device_config::impl_lua_device_config_macro;
|
use lua_device_config::impl_lua_device_config_macro;
|
||||||
|
use quote::quote;
|
||||||
use syn::{DeriveInput, parse_macro_input};
|
use syn::{DeriveInput, parse_macro_input};
|
||||||
|
|
||||||
use crate::impl_device::impl_device_macro;
|
|
||||||
|
|
||||||
#[proc_macro_derive(LuaDeviceConfig, attributes(device_config))]
|
#[proc_macro_derive(LuaDeviceConfig, attributes(device_config))]
|
||||||
pub fn lua_device_config_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
|
pub fn lua_device_config_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
|
||||||
let ast = parse_macro_input!(input as DeriveInput);
|
let ast = parse_macro_input!(input as DeriveInput);
|
||||||
@@ -14,9 +14,60 @@ pub fn lua_device_config_derive(input: proc_macro::TokenStream) -> proc_macro::T
|
|||||||
impl_lua_device_config_macro(&ast).into()
|
impl_lua_device_config_macro(&ast).into()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[proc_macro_derive(LuaDevice, attributes(traits))]
|
#[proc_macro_derive(LuaSerialize, attributes(traits))]
|
||||||
pub fn impl_device(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
|
pub fn lua_serialize(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
|
||||||
let ast = parse_macro_input!(input as DeriveInput);
|
let ast = parse_macro_input!(input as DeriveInput);
|
||||||
|
|
||||||
impl_device_macro(&ast).into()
|
let name = &ast.ident;
|
||||||
|
|
||||||
|
quote! {
|
||||||
|
impl ::mlua::IntoLua for #name {
|
||||||
|
fn into_lua(self, lua: &::mlua::Lua) -> ::mlua::Result<::mlua::Value> {
|
||||||
|
::mlua::LuaSerdeExt::to_value(lua, &self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Derive macro generating an impl for the trait `::mlua::UserData`
|
||||||
|
///
|
||||||
|
/// # Device traits
|
||||||
|
/// The `device(traits)` attribute can be used to tell the macro what traits are implemented so that
|
||||||
|
/// the appropriate methods can automatically be registered.
|
||||||
|
/// If the struct does not have any type parameters the syntax is very simple:
|
||||||
|
/// ```rust
|
||||||
|
/// #[device(traits(TraitA, TraitB))]
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// If the type does have type parameters you will have to manually specify all variations that
|
||||||
|
/// have the trait available:
|
||||||
|
/// ```rust
|
||||||
|
/// #[device(traits(TraitA, TraitB for <StateA>, <StateB>))]
|
||||||
|
/// ```
|
||||||
|
/// If multiple of these attributes are specified they will all combined appropriately.
|
||||||
|
///
|
||||||
|
///
|
||||||
|
/// ## NOTE
|
||||||
|
/// If your type _has_ type parameters any instance of the traits attribute that does not specify
|
||||||
|
/// any type parameters will have the traits applied to _all_ other type parameter variations
|
||||||
|
/// listed in the other trait attributes. This behavior only applies if there is at least one
|
||||||
|
/// instance with type parameters specified.
|
||||||
|
///
|
||||||
|
/// # Additional methods
|
||||||
|
/// Additional methods can be added by using the `device(add_methods)` attribute. This attribute
|
||||||
|
/// takes the path to a function with the following signature that can register the additional methods:
|
||||||
|
///
|
||||||
|
/// ```rust
|
||||||
|
/// # struct D;
|
||||||
|
/// fn top_secret<M: mlua::UserDataMethods<D>>(methods: &mut M) {}
|
||||||
|
/// ```
|
||||||
|
/// It can then be registered with:
|
||||||
|
/// ```rust
|
||||||
|
/// #[device(add_methods = top_secret)]
|
||||||
|
/// ```
|
||||||
|
#[proc_macro_derive(Device, attributes(device))]
|
||||||
|
pub fn device(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
|
||||||
|
let ast = parse_macro_input!(input as DeriveInput);
|
||||||
|
device::device(ast).into()
|
||||||
}
|
}
|
||||||
|
|||||||
624
config.lua
624
config.lua
@@ -1,624 +0,0 @@
|
|||||||
print(_VERSION)
|
|
||||||
|
|
||||||
local host = automation.util.get_hostname()
|
|
||||||
print("Running @" .. host)
|
|
||||||
|
|
||||||
local debug, value = pcall(automation.util.get_env, "DEBUG")
|
|
||||||
if debug and value ~= "true" then
|
|
||||||
debug = false
|
|
||||||
end
|
|
||||||
|
|
||||||
local function mqtt_z2m(topic)
|
|
||||||
return "zigbee2mqtt/" .. topic
|
|
||||||
end
|
|
||||||
|
|
||||||
local function mqtt_automation(topic)
|
|
||||||
return "automation/" .. topic
|
|
||||||
end
|
|
||||||
|
|
||||||
automation.fulfillment = {
|
|
||||||
openid_url = "https://login.huizinga.dev/api/oidc",
|
|
||||||
}
|
|
||||||
|
|
||||||
local mqtt_client = automation.new_mqtt_client({
|
|
||||||
host = ((host == "zeus" or host == "hephaestus") and "olympus.lan.huizinga.dev") or "mosquitto",
|
|
||||||
port = 8883,
|
|
||||||
client_name = "automation-" .. host,
|
|
||||||
username = "mqtt",
|
|
||||||
password = automation.util.get_env("MQTT_PASSWORD"),
|
|
||||||
tls = host == "zeus" or host == "hephaestus",
|
|
||||||
})
|
|
||||||
|
|
||||||
local ntfy = Ntfy.new({
|
|
||||||
topic = automation.util.get_env("NTFY_TOPIC"),
|
|
||||||
})
|
|
||||||
automation.device_manager:add(ntfy)
|
|
||||||
|
|
||||||
local on_presence = {
|
|
||||||
add = function(self, f)
|
|
||||||
self[#self + 1] = f
|
|
||||||
end,
|
|
||||||
}
|
|
||||||
|
|
||||||
local presence_system = 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,
|
|
||||||
})
|
|
||||||
automation.device_manager: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 = automation.util.get_epoch(),
|
|
||||||
})
|
|
||||||
end)
|
|
||||||
|
|
||||||
local function turn_off_when_away(device)
|
|
||||||
on_presence:add(function(presence)
|
|
||||||
if not presence then
|
|
||||||
device:set_on(false)
|
|
||||||
end
|
|
||||||
end)
|
|
||||||
end
|
|
||||||
|
|
||||||
local on_light = {
|
|
||||||
add = function(self, f)
|
|
||||||
self[#self + 1] = f
|
|
||||||
end,
|
|
||||||
}
|
|
||||||
automation.device_manager:add(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 = automation.util.get_epoch(),
|
|
||||||
})
|
|
||||||
end)
|
|
||||||
|
|
||||||
local hue_ip = "10.0.0.102"
|
|
||||||
local hue_token = automation.util.get_env("HUE_TOKEN")
|
|
||||||
|
|
||||||
local hue_bridge = HueBridge.new({
|
|
||||||
identifier = "hue_bridge",
|
|
||||||
ip = hue_ip,
|
|
||||||
login = hue_token,
|
|
||||||
flags = {
|
|
||||||
presence = 41,
|
|
||||||
darkness = 43,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
automation.device_manager: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 = HueGroup.new({
|
|
||||||
identifier = "kitchen_lights",
|
|
||||||
ip = hue_ip,
|
|
||||||
login = hue_token,
|
|
||||||
group_id = 7,
|
|
||||||
scene_id = "7MJLG27RzeRAEVJ",
|
|
||||||
})
|
|
||||||
automation.device_manager:add(kitchen_lights)
|
|
||||||
local living_lights = HueGroup.new({
|
|
||||||
identifier = "living_lights",
|
|
||||||
ip = hue_ip,
|
|
||||||
login = hue_token,
|
|
||||||
group_id = 1,
|
|
||||||
scene_id = "SNZw7jUhQ3cXSjkj",
|
|
||||||
})
|
|
||||||
automation.device_manager:add(living_lights)
|
|
||||||
local living_lights_relax = HueGroup.new({
|
|
||||||
identifier = "living_lights",
|
|
||||||
ip = hue_ip,
|
|
||||||
login = hue_token,
|
|
||||||
group_id = 1,
|
|
||||||
scene_id = "eRJ3fvGHCcb6yNw",
|
|
||||||
})
|
|
||||||
automation.device_manager:add(living_lights_relax)
|
|
||||||
|
|
||||||
automation.device_manager:add(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,
|
|
||||||
}))
|
|
||||||
|
|
||||||
automation.device_manager:add(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 = OutletOnOff.new({
|
|
||||||
name = "Mixer",
|
|
||||||
room = "Living Room",
|
|
||||||
topic = mqtt_z2m("living/mixer"),
|
|
||||||
client = mqtt_client,
|
|
||||||
})
|
|
||||||
turn_off_when_away(living_mixer)
|
|
||||||
automation.device_manager:add(living_mixer)
|
|
||||||
local living_speakers = OutletOnOff.new({
|
|
||||||
name = "Speakers",
|
|
||||||
room = "Living Room",
|
|
||||||
topic = mqtt_z2m("living/speakers"),
|
|
||||||
client = mqtt_client,
|
|
||||||
})
|
|
||||||
turn_off_when_away(living_speakers)
|
|
||||||
automation.device_manager:add(living_speakers)
|
|
||||||
|
|
||||||
automation.device_manager:add(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,
|
|
||||||
}))
|
|
||||||
|
|
||||||
local function kettle_timeout()
|
|
||||||
local timeout = 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
|
|
||||||
|
|
||||||
local kettle = 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)
|
|
||||||
automation.device_manager:add(kettle)
|
|
||||||
|
|
||||||
local function set_kettle(_, on)
|
|
||||||
kettle:set_on(on)
|
|
||||||
end
|
|
||||||
|
|
||||||
automation.device_manager:add(IkeaRemote.new({
|
|
||||||
name = "Remote",
|
|
||||||
room = "Bedroom",
|
|
||||||
client = mqtt_client,
|
|
||||||
topic = mqtt_z2m("bedroom/remote"),
|
|
||||||
single_button = true,
|
|
||||||
callback = set_kettle,
|
|
||||||
}))
|
|
||||||
|
|
||||||
automation.device_manager:add(IkeaRemote.new({
|
|
||||||
name = "Remote",
|
|
||||||
room = "Kitchen",
|
|
||||||
client = mqtt_client,
|
|
||||||
topic = mqtt_z2m("kitchen/remote"),
|
|
||||||
single_button = true,
|
|
||||||
callback = set_kettle,
|
|
||||||
}))
|
|
||||||
|
|
||||||
local function off_timeout(duration)
|
|
||||||
local timeout = 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 = LightOnOff.new({
|
|
||||||
name = "Light",
|
|
||||||
room = "Bathroom",
|
|
||||||
topic = mqtt_z2m("bathroom/light"),
|
|
||||||
client = mqtt_client,
|
|
||||||
callback = off_timeout(debug and 60 or 45 * 60),
|
|
||||||
})
|
|
||||||
automation.device_manager:add(bathroom_light)
|
|
||||||
|
|
||||||
automation.device_manager:add(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,
|
|
||||||
}))
|
|
||||||
|
|
||||||
automation.device_manager:add(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 = OutletOnOff.new({
|
|
||||||
name = "Outlet",
|
|
||||||
room = "Workbench",
|
|
||||||
topic = mqtt_z2m("workbench/outlet"),
|
|
||||||
client = mqtt_client,
|
|
||||||
})
|
|
||||||
turn_off_when_away(workbench_outlet)
|
|
||||||
automation.device_manager:add(workbench_outlet)
|
|
||||||
|
|
||||||
local workbench_light = LightColorTemperature.new({
|
|
||||||
name = "Light",
|
|
||||||
room = "Workbench",
|
|
||||||
topic = mqtt_z2m("workbench/light"),
|
|
||||||
client = mqtt_client,
|
|
||||||
})
|
|
||||||
turn_off_when_away(workbench_light)
|
|
||||||
automation.device_manager:add(workbench_light)
|
|
||||||
|
|
||||||
local delay_color_temp = Timeout.new()
|
|
||||||
automation.device_manager:add(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,
|
|
||||||
}))
|
|
||||||
|
|
||||||
local hallway_top_light = HueGroup.new({
|
|
||||||
identifier = "hallway_top_light",
|
|
||||||
ip = hue_ip,
|
|
||||||
login = hue_token,
|
|
||||||
group_id = 83,
|
|
||||||
scene_id = "QeufkFDICEHWeKJ7",
|
|
||||||
})
|
|
||||||
automation.device_manager:add(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,
|
|
||||||
}))
|
|
||||||
automation.device_manager:add(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,
|
|
||||||
}))
|
|
||||||
|
|
||||||
local hallway_light_automation = {
|
|
||||||
timeout = Timeout.new(),
|
|
||||||
forced = false,
|
|
||||||
switch_callback = function(self, on)
|
|
||||||
self.timeout:cancel()
|
|
||||||
self.group.set_on(on)
|
|
||||||
self.forced = on
|
|
||||||
end,
|
|
||||||
door_callback = function(self, 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:open_percent() == 0 then
|
|
||||||
self.group.set_on(false)
|
|
||||||
end
|
|
||||||
end)
|
|
||||||
end
|
|
||||||
end,
|
|
||||||
trash_callback = function(self, open)
|
|
||||||
if open then
|
|
||||||
self.group.set_on(true)
|
|
||||||
else
|
|
||||||
if not self.timeout:is_waiting() and self.door:open_percent() == 0 and not self.forced then
|
|
||||||
self.group.set_on(false)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end,
|
|
||||||
light_callback = function(self, on)
|
|
||||||
if on and self.trash:open_percent() == 0 and 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 on then
|
|
||||||
-- The light is never forced when it is off
|
|
||||||
self.forced = false
|
|
||||||
end
|
|
||||||
end,
|
|
||||||
}
|
|
||||||
|
|
||||||
local hallway_storage = LightBrightness.new({
|
|
||||||
name = "Storage",
|
|
||||||
room = "Hallway",
|
|
||||||
topic = mqtt_z2m("hallway/storage"),
|
|
||||||
client = mqtt_client,
|
|
||||||
callback = function(_, state)
|
|
||||||
hallway_light_automation:light_callback(state.state)
|
|
||||||
end,
|
|
||||||
})
|
|
||||||
turn_off_when_away(hallway_storage)
|
|
||||||
automation.device_manager:add(hallway_storage)
|
|
||||||
|
|
||||||
local hallway_bottom_lights = HueGroup.new({
|
|
||||||
identifier = "hallway_bottom_lights",
|
|
||||||
ip = hue_ip,
|
|
||||||
login = hue_token,
|
|
||||||
group_id = 81,
|
|
||||||
scene_id = "3qWKxGVadXFFG4o",
|
|
||||||
})
|
|
||||||
automation.device_manager: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,
|
|
||||||
}
|
|
||||||
|
|
||||||
local frontdoor_presence = {
|
|
||||||
timeout = Timeout.new(),
|
|
||||||
}
|
|
||||||
setmetatable(frontdoor_presence, {
|
|
||||||
__call = function(self, open)
|
|
||||||
if open then
|
|
||||||
self.timeout:cancel()
|
|
||||||
|
|
||||||
if not presence_system:overall_presence() then
|
|
||||||
mqtt_client:send_message(mqtt_automation("presence/contact/frontdoor"), {
|
|
||||||
state = true,
|
|
||||||
updated = automation.util.get_epoch(),
|
|
||||||
})
|
|
||||||
end
|
|
||||||
else
|
|
||||||
self.timeout:start(debug and 10 or 15 * 60, function()
|
|
||||||
mqtt_client:send_message(mqtt_automation("presence/contact/frontdoor"), {})
|
|
||||||
end)
|
|
||||||
end
|
|
||||||
end,
|
|
||||||
})
|
|
||||||
|
|
||||||
automation.device_manager:add(IkeaRemote.new({
|
|
||||||
name = "Remote",
|
|
||||||
room = "Hallway",
|
|
||||||
client = mqtt_client,
|
|
||||||
topic = mqtt_z2m("hallway/remote"),
|
|
||||||
callback = function(_, on)
|
|
||||||
hallway_light_automation:switch_callback(on)
|
|
||||||
end,
|
|
||||||
}))
|
|
||||||
local hallway_frontdoor = ContactSensor.new({
|
|
||||||
name = "Frontdoor",
|
|
||||||
room = "Hallway",
|
|
||||||
sensor_type = "Door",
|
|
||||||
topic = mqtt_z2m("hallway/frontdoor"),
|
|
||||||
client = mqtt_client,
|
|
||||||
presence = {
|
|
||||||
topic = mqtt_automation("presence/contact/frontdoor"),
|
|
||||||
timeout = debug and 10 or 15 * 60,
|
|
||||||
},
|
|
||||||
callback = function(_, open)
|
|
||||||
hallway_light_automation:door_callback(open)
|
|
||||||
frontdoor_presence(open)
|
|
||||||
end,
|
|
||||||
})
|
|
||||||
automation.device_manager:add(hallway_frontdoor)
|
|
||||||
hallway_light_automation.door = hallway_frontdoor
|
|
||||||
|
|
||||||
local hallway_trash = ContactSensor.new({
|
|
||||||
name = "Trash",
|
|
||||||
room = "Hallway",
|
|
||||||
sensor_type = "Drawer",
|
|
||||||
topic = mqtt_z2m("hallway/trash"),
|
|
||||||
client = mqtt_client,
|
|
||||||
callback = function(_, open)
|
|
||||||
hallway_light_automation:trash_callback(open)
|
|
||||||
end,
|
|
||||||
})
|
|
||||||
automation.device_manager:add(hallway_trash)
|
|
||||||
hallway_light_automation.trash = hallway_trash
|
|
||||||
|
|
||||||
local guest_light = LightOnOff.new({
|
|
||||||
name = "Light",
|
|
||||||
room = "Guest Room",
|
|
||||||
topic = mqtt_z2m("guest/light"),
|
|
||||||
client = mqtt_client,
|
|
||||||
})
|
|
||||||
turn_off_when_away(guest_light)
|
|
||||||
automation.device_manager:add(guest_light)
|
|
||||||
|
|
||||||
local bedroom_air_filter = AirFilter.new({
|
|
||||||
name = "Air Filter",
|
|
||||||
room = "Bedroom",
|
|
||||||
url = "http://10.0.0.103",
|
|
||||||
})
|
|
||||||
automation.device_manager:add(bedroom_air_filter)
|
|
||||||
|
|
||||||
local bedroom_lights = HueGroup.new({
|
|
||||||
identifier = "bedroom_lights",
|
|
||||||
ip = hue_ip,
|
|
||||||
login = hue_token,
|
|
||||||
group_id = 3,
|
|
||||||
scene_id = "PvRs-lGD4VRytL9",
|
|
||||||
})
|
|
||||||
automation.device_manager:add(bedroom_lights)
|
|
||||||
local bedroom_lights_relax = HueGroup.new({
|
|
||||||
identifier = "bedroom_lights",
|
|
||||||
ip = hue_ip,
|
|
||||||
login = hue_token,
|
|
||||||
group_id = 3,
|
|
||||||
scene_id = "60tfTyR168v2csz",
|
|
||||||
})
|
|
||||||
automation.device_manager:add(bedroom_lights_relax)
|
|
||||||
|
|
||||||
automation.device_manager:add(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,
|
|
||||||
}))
|
|
||||||
|
|
||||||
automation.device_manager:add(ContactSensor.new({
|
|
||||||
name = "Balcony",
|
|
||||||
room = "Living Room",
|
|
||||||
sensor_type = "Door",
|
|
||||||
topic = mqtt_z2m("living/balcony"),
|
|
||||||
client = mqtt_client,
|
|
||||||
}))
|
|
||||||
automation.device_manager:add(ContactSensor.new({
|
|
||||||
name = "Window",
|
|
||||||
room = "Living Room",
|
|
||||||
topic = mqtt_z2m("living/window"),
|
|
||||||
client = mqtt_client,
|
|
||||||
}))
|
|
||||||
automation.device_manager:add(ContactSensor.new({
|
|
||||||
name = "Window",
|
|
||||||
room = "Bedroom",
|
|
||||||
topic = mqtt_z2m("bedroom/window"),
|
|
||||||
client = mqtt_client,
|
|
||||||
}))
|
|
||||||
automation.device_manager:add(ContactSensor.new({
|
|
||||||
name = "Window",
|
|
||||||
room = "Guest Room",
|
|
||||||
topic = mqtt_z2m("guest/window"),
|
|
||||||
client = mqtt_client,
|
|
||||||
}))
|
|
||||||
|
|
||||||
local storage_light = LightBrightness.new({
|
|
||||||
name = "Light",
|
|
||||||
room = "Storage",
|
|
||||||
topic = mqtt_z2m("storage/light"),
|
|
||||||
client = mqtt_client,
|
|
||||||
})
|
|
||||||
turn_off_when_away(storage_light)
|
|
||||||
automation.device_manager:add(storage_light)
|
|
||||||
|
|
||||||
automation.device_manager:add(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,
|
|
||||||
}))
|
|
||||||
|
|
||||||
automation.device_manager:schedule("0 0 19 * * *", function()
|
|
||||||
bedroom_air_filter:set_on(true)
|
|
||||||
end)
|
|
||||||
automation.device_manager:schedule("0 0 20 * * *", function()
|
|
||||||
bedroom_air_filter:set_on(false)
|
|
||||||
end)
|
|
||||||
47
config/battery.lua
Normal file
47
config/battery.lua
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
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
config/config.lua
Normal file
32
config/config.lua
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
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.lan.huizinga.dev") or "mosquitto",
|
||||||
|
port = 8883,
|
||||||
|
client_name = "automation-" .. host,
|
||||||
|
username = "mqtt",
|
||||||
|
password = secrets.mqtt_password,
|
||||||
|
tls = host == "zeus" or host == "hephaestus",
|
||||||
|
},
|
||||||
|
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
config/debug.lua
Normal file
35
config/debug.lua
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
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
config/hallway_automation.lua
Normal file
85
config/hallway_automation.lua
Normal file
@@ -0,0 +1,85 @@
|
|||||||
|
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
config/helper.lua
Normal file
49
config/helper.lua
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
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
config/hue_bridge.lua
Normal file
41
config/hue_bridge.lua
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
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
config/light.lua
Normal file
44
config/light.lua
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
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
config/ntfy.lua
Normal file
34
config/ntfy.lua
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
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
config/presence.lua
Normal file
80
config/presence.lua
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
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
config/rooms.lua
Normal file
12
config/rooms.lua
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
--- @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
config/rooms/bathroom.lua
Normal file
40
config/rooms/bathroom.lua
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
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
|
||||||
78
config/rooms/bedroom.lua
Normal file
78
config/rooms/bedroom.lua
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
local battery = require("config.battery")
|
||||||
|
local devices = require("automation:devices")
|
||||||
|
local helper = require("config.helper")
|
||||||
|
local hue_bridge = require("config.hue_bridge")
|
||||||
|
local windows = require("config.windows")
|
||||||
|
|
||||||
|
--- @type Module
|
||||||
|
local module = {}
|
||||||
|
|
||||||
|
--- @type AirFilter?
|
||||||
|
local air_filter = nil
|
||||||
|
|
||||||
|
function module.setup(mqtt_client)
|
||||||
|
local lights = devices.HueGroup.new({
|
||||||
|
identifier = "bedroom_lights",
|
||||||
|
ip = hue_bridge.ip,
|
||||||
|
login = hue_bridge.token,
|
||||||
|
group_id = 3,
|
||||||
|
scene_id = "PvRs-lGD4VRytL9",
|
||||||
|
})
|
||||||
|
local lights_relax = devices.HueGroup.new({
|
||||||
|
identifier = "bedroom_lights_relax",
|
||||||
|
ip = hue_bridge.ip,
|
||||||
|
login = hue_bridge.token,
|
||||||
|
group_id = 3,
|
||||||
|
scene_id = "60tfTyR168v2csz",
|
||||||
|
})
|
||||||
|
|
||||||
|
air_filter = devices.AirFilter.new({
|
||||||
|
name = "Air Filter",
|
||||||
|
room = "Bedroom",
|
||||||
|
url = "http://10.0.0.103",
|
||||||
|
})
|
||||||
|
|
||||||
|
local switch = devices.HueSwitch.new({
|
||||||
|
name = "Switch",
|
||||||
|
room = "Bedroom",
|
||||||
|
client = mqtt_client,
|
||||||
|
topic = helper.mqtt_z2m("bedroom/switch"),
|
||||||
|
left_callback = function()
|
||||||
|
lights:set_on(not lights:on())
|
||||||
|
end,
|
||||||
|
left_hold_callback = function()
|
||||||
|
lights_relax:set_on(true)
|
||||||
|
end,
|
||||||
|
battery_callback = battery.callback,
|
||||||
|
})
|
||||||
|
|
||||||
|
local window = devices.ContactSensor.new({
|
||||||
|
name = "Window",
|
||||||
|
room = "Bedroom",
|
||||||
|
topic = helper.mqtt_z2m("bedroom/window"),
|
||||||
|
client = mqtt_client,
|
||||||
|
battery_callback = battery.callback,
|
||||||
|
})
|
||||||
|
windows.add(window)
|
||||||
|
|
||||||
|
--- @type Module
|
||||||
|
return {
|
||||||
|
devices = {
|
||||||
|
lights,
|
||||||
|
lights_relax,
|
||||||
|
air_filter,
|
||||||
|
switch,
|
||||||
|
window,
|
||||||
|
},
|
||||||
|
schedule = {
|
||||||
|
["0 0 19 * * *"] = function()
|
||||||
|
air_filter:set_on(true)
|
||||||
|
end,
|
||||||
|
["0 0 20 * * *"] = function()
|
||||||
|
air_filter:set_on(false)
|
||||||
|
end,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
|
return module
|
||||||
35
config/rooms/guest_bedroom.lua
Normal file
35
config/rooms/guest_bedroom.lua
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
local battery = require("config.battery")
|
||||||
|
local devices = require("automation:devices")
|
||||||
|
local helper = require("config.helper")
|
||||||
|
local presence = require("config.presence")
|
||||||
|
local windows = require("config.windows")
|
||||||
|
|
||||||
|
--- @type Module
|
||||||
|
local module = {}
|
||||||
|
|
||||||
|
function module.setup(mqtt_client)
|
||||||
|
local light = devices.LightOnOff.new({
|
||||||
|
name = "Light",
|
||||||
|
room = "Guest Room",
|
||||||
|
topic = helper.mqtt_z2m("guest/light"),
|
||||||
|
client = mqtt_client,
|
||||||
|
})
|
||||||
|
presence.turn_off_when_away(light)
|
||||||
|
|
||||||
|
local window = devices.ContactSensor.new({
|
||||||
|
name = "Window",
|
||||||
|
room = "Guest Room",
|
||||||
|
topic = helper.mqtt_z2m("guest/window"),
|
||||||
|
client = mqtt_client,
|
||||||
|
battery_callback = battery.callback,
|
||||||
|
})
|
||||||
|
windows.add(window)
|
||||||
|
|
||||||
|
--- @type Module
|
||||||
|
return {
|
||||||
|
light,
|
||||||
|
window,
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
|
return module
|
||||||
110
config/rooms/hallway_bottom.lua
Normal file
110
config/rooms/hallway_bottom.lua
Normal file
@@ -0,0 +1,110 @@
|
|||||||
|
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)
|
||||||
|
|
||||||
|
---@param duration number
|
||||||
|
---@return fun(_, open: boolean)
|
||||||
|
local function frontdoor_presence(duration)
|
||||||
|
local timeout = utils.Timeout.new()
|
||||||
|
|
||||||
|
return function(_, open)
|
||||||
|
if open then
|
||||||
|
timeout:cancel()
|
||||||
|
|
||||||
|
if presence.overall_presence() then
|
||||||
|
mqtt_client:send_message(helper.mqtt_automation("presence/contact/frontdoor"), {
|
||||||
|
state = true,
|
||||||
|
updated = utils.get_epoch(),
|
||||||
|
})
|
||||||
|
end
|
||||||
|
else
|
||||||
|
timeout:start(duration, function()
|
||||||
|
mqtt_client:send_message(helper.mqtt_automation("presence/contact/frontdoor"), nil)
|
||||||
|
end)
|
||||||
|
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(debug.debug_mode and 10 or 15 * 60),
|
||||||
|
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
config/rooms/hallway_top.lua
Normal file
48
config/rooms/hallway_top.lua
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
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
config/rooms/kitchen.lua
Normal file
71
config/rooms/kitchen.lua
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
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
config/rooms/living_room.lua
Normal file
126
config/rooms/living_room.lua
Normal file
@@ -0,0 +1,126 @@
|
|||||||
|
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
config/rooms/storage.lua
Normal file
41
config/rooms/storage.lua
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
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
config/rooms/workbench.lua
Normal file
69
config/rooms/workbench.lua
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
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
config/windows.lua
Normal file
43
config/windows.lua
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
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
|
||||||
337
definitions/automation:devices.lua
Normal file
337
definitions/automation:devices.lua
Normal file
@@ -0,0 +1,337 @@
|
|||||||
|
-- DO NOT MODIFY, FILE IS AUTOMATICALLY GENERATED
|
||||||
|
---@meta
|
||||||
|
|
||||||
|
local devices
|
||||||
|
|
||||||
|
---@class Action
|
||||||
|
---@field action
|
||||||
|
---| "broadcast"
|
||||||
|
---@field extras (table<string, string>)?
|
||||||
|
---@field label string
|
||||||
|
---@field clear (boolean)?
|
||||||
|
local Action
|
||||||
|
|
||||||
|
---@class AirFilter: DeviceInterface, OnOffInterface
|
||||||
|
local AirFilter
|
||||||
|
devices.AirFilter = {}
|
||||||
|
---@param config AirFilterConfig
|
||||||
|
---@return AirFilter
|
||||||
|
function devices.AirFilter.new(config) end
|
||||||
|
|
||||||
|
---@class AirFilterConfig
|
||||||
|
---@field name string
|
||||||
|
---@field room (string)?
|
||||||
|
---@field url string
|
||||||
|
local AirFilterConfig
|
||||||
|
|
||||||
|
---@class ConfigLightLightStateBrightness
|
||||||
|
---@field name string
|
||||||
|
---@field room (string)?
|
||||||
|
---@field topic string
|
||||||
|
---@field callback (fun(_: LightBrightness, _: LightStateBrightness) | fun(_: LightBrightness, _: LightStateBrightness)[])?
|
||||||
|
---@field client (AsyncClient)?
|
||||||
|
local ConfigLightLightStateBrightness
|
||||||
|
|
||||||
|
---@class ConfigLightLightStateColorTemperature
|
||||||
|
---@field name string
|
||||||
|
---@field room (string)?
|
||||||
|
---@field topic string
|
||||||
|
---@field callback (fun(_: LightColorTemperature, _: LightStateColorTemperature) | fun(_: LightColorTemperature, _: LightStateColorTemperature)[])?
|
||||||
|
---@field client (AsyncClient)?
|
||||||
|
local ConfigLightLightStateColorTemperature
|
||||||
|
|
||||||
|
---@class ConfigLightLightStateOnOff
|
||||||
|
---@field name string
|
||||||
|
---@field room (string)?
|
||||||
|
---@field topic string
|
||||||
|
---@field callback (fun(_: LightOnOff, _: LightStateOnOff) | fun(_: LightOnOff, _: LightStateOnOff)[])?
|
||||||
|
---@field client (AsyncClient)?
|
||||||
|
local ConfigLightLightStateOnOff
|
||||||
|
|
||||||
|
---@class ConfigOutletOutletStateOnOff
|
||||||
|
---@field name string
|
||||||
|
---@field room (string)?
|
||||||
|
---@field topic string
|
||||||
|
---@field outlet_type (OutletType)?
|
||||||
|
---@field callback (fun(_: OutletOnOff, _: OutletStateOnOff) | fun(_: OutletOnOff, _: OutletStateOnOff)[])?
|
||||||
|
---@field client AsyncClient
|
||||||
|
local ConfigOutletOutletStateOnOff
|
||||||
|
|
||||||
|
---@class ConfigOutletOutletStatePower
|
||||||
|
---@field name string
|
||||||
|
---@field room (string)?
|
||||||
|
---@field topic string
|
||||||
|
---@field outlet_type (OutletType)?
|
||||||
|
---@field callback (fun(_: OutletPower, _: OutletStatePower) | fun(_: OutletPower, _: OutletStatePower)[])?
|
||||||
|
---@field client AsyncClient
|
||||||
|
local ConfigOutletOutletStatePower
|
||||||
|
|
||||||
|
---@class ContactSensor: DeviceInterface, OpenCloseInterface
|
||||||
|
local ContactSensor
|
||||||
|
devices.ContactSensor = {}
|
||||||
|
---@param config ContactSensorConfig
|
||||||
|
---@return ContactSensor
|
||||||
|
function devices.ContactSensor.new(config) end
|
||||||
|
|
||||||
|
---@class ContactSensorConfig
|
||||||
|
---@field name string
|
||||||
|
---@field room (string)?
|
||||||
|
---@field topic string
|
||||||
|
---@field sensor_type (SensorType)?
|
||||||
|
---@field callback (fun(_: ContactSensor, _: boolean) | fun(_: ContactSensor, _: boolean)[])?
|
||||||
|
---@field battery_callback (fun(_: ContactSensor, _: number) | fun(_: ContactSensor, _: number)[])?
|
||||||
|
---@field client (AsyncClient)?
|
||||||
|
local ContactSensorConfig
|
||||||
|
|
||||||
|
---@alias Flag
|
||||||
|
---| "presence"
|
||||||
|
---| "darkness"
|
||||||
|
|
||||||
|
---@class FlagIDs
|
||||||
|
---@field presence integer
|
||||||
|
---@field darkness integer
|
||||||
|
local FlagIDs
|
||||||
|
|
||||||
|
---@class HueBridge: DeviceInterface
|
||||||
|
local HueBridge
|
||||||
|
devices.HueBridge = {}
|
||||||
|
---@param config HueBridgeConfig
|
||||||
|
---@return HueBridge
|
||||||
|
function devices.HueBridge.new(config) end
|
||||||
|
---@async
|
||||||
|
---@param flag Flag
|
||||||
|
---@param value boolean
|
||||||
|
function HueBridge:set_flag(flag, value) end
|
||||||
|
|
||||||
|
---@class HueBridgeConfig
|
||||||
|
---@field identifier string
|
||||||
|
---@field ip string
|
||||||
|
---@field login string
|
||||||
|
---@field flags FlagIDs
|
||||||
|
local HueBridgeConfig
|
||||||
|
|
||||||
|
---@class HueGroup: DeviceInterface, OnOffInterface
|
||||||
|
local HueGroup
|
||||||
|
devices.HueGroup = {}
|
||||||
|
---@param config HueGroupConfig
|
||||||
|
---@return HueGroup
|
||||||
|
function devices.HueGroup.new(config) end
|
||||||
|
|
||||||
|
---@class HueGroupConfig
|
||||||
|
---@field identifier string
|
||||||
|
---@field ip string
|
||||||
|
---@field login string
|
||||||
|
---@field group_id integer
|
||||||
|
---@field scene_id string
|
||||||
|
local HueGroupConfig
|
||||||
|
|
||||||
|
---@class HueSwitch: DeviceInterface
|
||||||
|
local HueSwitch
|
||||||
|
devices.HueSwitch = {}
|
||||||
|
---@param config HueSwitchConfig
|
||||||
|
---@return HueSwitch
|
||||||
|
function devices.HueSwitch.new(config) end
|
||||||
|
|
||||||
|
---@class HueSwitchConfig
|
||||||
|
---@field name string
|
||||||
|
---@field room (string)?
|
||||||
|
---@field topic string
|
||||||
|
---@field client AsyncClient
|
||||||
|
---@field left_callback (fun(_: HueSwitch) | fun(_: HueSwitch)[])?
|
||||||
|
---@field right_callback (fun(_: HueSwitch) | fun(_: HueSwitch)[])?
|
||||||
|
---@field left_hold_callback (fun(_: HueSwitch) | fun(_: HueSwitch)[])?
|
||||||
|
---@field right_hold_callback (fun(_: HueSwitch) | fun(_: HueSwitch)[])?
|
||||||
|
---@field battery_callback (fun(_: HueSwitch, _: number) | fun(_: HueSwitch, _: number)[])?
|
||||||
|
local HueSwitchConfig
|
||||||
|
|
||||||
|
---@class IkeaRemote: DeviceInterface
|
||||||
|
local IkeaRemote
|
||||||
|
devices.IkeaRemote = {}
|
||||||
|
---@param config IkeaRemoteConfig
|
||||||
|
---@return IkeaRemote
|
||||||
|
function devices.IkeaRemote.new(config) end
|
||||||
|
|
||||||
|
---@class IkeaRemoteConfig
|
||||||
|
---@field name string
|
||||||
|
---@field room (string)?
|
||||||
|
---@field single_button (boolean)?
|
||||||
|
---@field topic string
|
||||||
|
---@field client AsyncClient
|
||||||
|
---@field callback (fun(_: IkeaRemote, _: boolean) | fun(_: IkeaRemote, _: boolean)[])?
|
||||||
|
---@field battery_callback (fun(_: IkeaRemote, _: number) | fun(_: IkeaRemote, _: number)[])?
|
||||||
|
local IkeaRemoteConfig
|
||||||
|
|
||||||
|
---@class KasaOutlet: DeviceInterface, OnOffInterface
|
||||||
|
local KasaOutlet
|
||||||
|
devices.KasaOutlet = {}
|
||||||
|
---@param config KasaOutletConfig
|
||||||
|
---@return KasaOutlet
|
||||||
|
function devices.KasaOutlet.new(config) end
|
||||||
|
|
||||||
|
---@class KasaOutletConfig
|
||||||
|
---@field identifier string
|
||||||
|
---@field ip string
|
||||||
|
local KasaOutletConfig
|
||||||
|
|
||||||
|
---@class LightBrightness: DeviceInterface, OnOffInterface, BrightnessInterface
|
||||||
|
local LightBrightness
|
||||||
|
devices.LightBrightness = {}
|
||||||
|
---@param config ConfigLightLightStateBrightness
|
||||||
|
---@return LightBrightness
|
||||||
|
function devices.LightBrightness.new(config) end
|
||||||
|
|
||||||
|
---@class LightColorTemperature: DeviceInterface, OnOffInterface, BrightnessInterface, ColorSettingInterface
|
||||||
|
local LightColorTemperature
|
||||||
|
devices.LightColorTemperature = {}
|
||||||
|
---@param config ConfigLightLightStateColorTemperature
|
||||||
|
---@return LightColorTemperature
|
||||||
|
function devices.LightColorTemperature.new(config) end
|
||||||
|
|
||||||
|
---@class LightOnOff: DeviceInterface, OnOffInterface
|
||||||
|
local LightOnOff
|
||||||
|
devices.LightOnOff = {}
|
||||||
|
---@param config ConfigLightLightStateOnOff
|
||||||
|
---@return LightOnOff
|
||||||
|
function devices.LightOnOff.new(config) end
|
||||||
|
|
||||||
|
---@class LightSensor: DeviceInterface
|
||||||
|
local LightSensor
|
||||||
|
devices.LightSensor = {}
|
||||||
|
---@param config LightSensorConfig
|
||||||
|
---@return LightSensor
|
||||||
|
function devices.LightSensor.new(config) end
|
||||||
|
|
||||||
|
---@class LightSensorConfig
|
||||||
|
---@field identifier string
|
||||||
|
---@field topic string
|
||||||
|
---@field min integer
|
||||||
|
---@field max integer
|
||||||
|
---@field callback (fun(_: LightSensor, _: boolean) | fun(_: LightSensor, _: boolean)[])?
|
||||||
|
---@field client AsyncClient
|
||||||
|
local LightSensorConfig
|
||||||
|
|
||||||
|
---@class LightStateBrightness
|
||||||
|
---@field state boolean
|
||||||
|
---@field brightness number
|
||||||
|
local LightStateBrightness
|
||||||
|
|
||||||
|
---@class LightStateColorTemperature
|
||||||
|
---@field state boolean
|
||||||
|
---@field brightness number
|
||||||
|
---@field color_temp integer
|
||||||
|
local LightStateColorTemperature
|
||||||
|
|
||||||
|
---@class LightStateOnOff
|
||||||
|
---@field state boolean
|
||||||
|
local LightStateOnOff
|
||||||
|
|
||||||
|
---@class Notification
|
||||||
|
---@field title string
|
||||||
|
---@field message (string)?
|
||||||
|
---@field tags ((string)[])?
|
||||||
|
---@field priority (Priority)?
|
||||||
|
---@field actions ((Action)[])?
|
||||||
|
local Notification
|
||||||
|
|
||||||
|
---@class Ntfy: DeviceInterface
|
||||||
|
local Ntfy
|
||||||
|
devices.Ntfy = {}
|
||||||
|
---@param config NtfyConfig
|
||||||
|
---@return Ntfy
|
||||||
|
function devices.Ntfy.new(config) end
|
||||||
|
---@async
|
||||||
|
---@param notification Notification
|
||||||
|
function Ntfy:send_notification(notification) end
|
||||||
|
|
||||||
|
---@class NtfyConfig
|
||||||
|
---@field url (string)?
|
||||||
|
---@field topic string
|
||||||
|
local NtfyConfig
|
||||||
|
|
||||||
|
---@class OutletOnOff: DeviceInterface, OnOffInterface
|
||||||
|
local OutletOnOff
|
||||||
|
devices.OutletOnOff = {}
|
||||||
|
---@param config ConfigOutletOutletStateOnOff
|
||||||
|
---@return OutletOnOff
|
||||||
|
function devices.OutletOnOff.new(config) end
|
||||||
|
|
||||||
|
---@class OutletPower: DeviceInterface, OnOffInterface
|
||||||
|
local OutletPower
|
||||||
|
devices.OutletPower = {}
|
||||||
|
---@param config ConfigOutletOutletStatePower
|
||||||
|
---@return OutletPower
|
||||||
|
function devices.OutletPower.new(config) end
|
||||||
|
|
||||||
|
---@class OutletStateOnOff
|
||||||
|
---@field state boolean
|
||||||
|
local OutletStateOnOff
|
||||||
|
|
||||||
|
---@class OutletStatePower
|
||||||
|
---@field state boolean
|
||||||
|
---@field power number
|
||||||
|
local OutletStatePower
|
||||||
|
|
||||||
|
---@alias OutletType
|
||||||
|
---| "Outlet"
|
||||||
|
---| "Kettle"
|
||||||
|
|
||||||
|
---@class Presence: DeviceInterface
|
||||||
|
local Presence
|
||||||
|
devices.Presence = {}
|
||||||
|
---@param config PresenceConfig
|
||||||
|
---@return Presence
|
||||||
|
function devices.Presence.new(config) end
|
||||||
|
---@async
|
||||||
|
---@return boolean
|
||||||
|
function Presence:overall_presence() end
|
||||||
|
|
||||||
|
---@class PresenceConfig
|
||||||
|
---@field topic string
|
||||||
|
---@field callback (fun(_: Presence, _: boolean) | fun(_: Presence, _: boolean)[])?
|
||||||
|
---@field client AsyncClient
|
||||||
|
local PresenceConfig
|
||||||
|
|
||||||
|
---@alias Priority
|
||||||
|
---| "min"
|
||||||
|
---| "low"
|
||||||
|
---| "default"
|
||||||
|
---| "high"
|
||||||
|
---| "max"
|
||||||
|
|
||||||
|
---@alias SensorType
|
||||||
|
---| "Door"
|
||||||
|
---| "Drawer"
|
||||||
|
---| "Window"
|
||||||
|
|
||||||
|
---@class WakeOnLAN: DeviceInterface
|
||||||
|
local WakeOnLAN
|
||||||
|
devices.WakeOnLAN = {}
|
||||||
|
---@param config WolConfig
|
||||||
|
---@return WakeOnLAN
|
||||||
|
function devices.WakeOnLAN.new(config) end
|
||||||
|
|
||||||
|
---@class Washer: DeviceInterface
|
||||||
|
local Washer
|
||||||
|
devices.Washer = {}
|
||||||
|
---@param config WasherConfig
|
||||||
|
---@return Washer
|
||||||
|
function devices.Washer.new(config) end
|
||||||
|
|
||||||
|
---@class WasherConfig
|
||||||
|
---@field identifier string
|
||||||
|
---@field topic string
|
||||||
|
---@field threshold number
|
||||||
|
---@field done_callback (fun(_: Washer) | fun(_: Washer)[])?
|
||||||
|
---@field client AsyncClient
|
||||||
|
local WasherConfig
|
||||||
|
|
||||||
|
---@class WolConfig
|
||||||
|
---@field name string
|
||||||
|
---@field room (string)?
|
||||||
|
---@field topic string
|
||||||
|
---@field mac_address string
|
||||||
|
---@field broadcast_ip (string)?
|
||||||
|
---@field client AsyncClient
|
||||||
|
local WolConfig
|
||||||
|
|
||||||
|
return devices
|
||||||
6
definitions/automation:secrets.lua
Normal file
6
definitions/automation:secrets.lua
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
---@meta
|
||||||
|
|
||||||
|
---@type table<string, string?>
|
||||||
|
local secrets
|
||||||
|
|
||||||
|
return secrets
|
||||||
27
definitions/automation:utils.lua
Normal file
27
definitions/automation:utils.lua
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
-- DO NOT MODIFY, FILE IS AUTOMATICALLY GENERATED
|
||||||
|
---@meta
|
||||||
|
|
||||||
|
local utils
|
||||||
|
|
||||||
|
---@class Timeout
|
||||||
|
local Timeout
|
||||||
|
---@async
|
||||||
|
---@param timeout number
|
||||||
|
---@param callback fun() | fun()[]
|
||||||
|
function Timeout:start(timeout, callback) end
|
||||||
|
---@async
|
||||||
|
function Timeout:cancel() end
|
||||||
|
---@async
|
||||||
|
---@return boolean
|
||||||
|
function Timeout:is_waiting() end
|
||||||
|
utils.Timeout = {}
|
||||||
|
---@return Timeout
|
||||||
|
function utils.Timeout.new() end
|
||||||
|
|
||||||
|
---@return string
|
||||||
|
function utils.get_hostname() end
|
||||||
|
|
||||||
|
---@return integer
|
||||||
|
function utils.get_epoch() end
|
||||||
|
|
||||||
|
return utils
|
||||||
6
definitions/automation:variables.lua
Normal file
6
definitions/automation:variables.lua
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
---@meta
|
||||||
|
|
||||||
|
---@type table<string, string?>
|
||||||
|
local variables
|
||||||
|
|
||||||
|
return variables
|
||||||
41
definitions/config.lua
Normal file
41
definitions/config.lua
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
-- DO NOT MODIFY, FILE IS AUTOMATICALLY GENERATED
|
||||||
|
---@meta
|
||||||
|
|
||||||
|
---@class FulfillmentConfig
|
||||||
|
---@field openid_url string
|
||||||
|
---@field ip (string)?
|
||||||
|
---@field port (integer)?
|
||||||
|
local FulfillmentConfig
|
||||||
|
|
||||||
|
---@class Config
|
||||||
|
---@field fulfillment FulfillmentConfig
|
||||||
|
---@field modules (Module)[]
|
||||||
|
---@field mqtt MqttConfig
|
||||||
|
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
|
||||||
42
definitions/interfaces.lua
Normal file
42
definitions/interfaces.lua
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
--- @meta
|
||||||
|
|
||||||
|
---@class DeviceInterface
|
||||||
|
local DeviceInterface
|
||||||
|
---@return string
|
||||||
|
function DeviceInterface:get_id() end
|
||||||
|
|
||||||
|
---@class OnOffInterface: DeviceInterface
|
||||||
|
local OnOffInterface
|
||||||
|
---@async
|
||||||
|
---@param on boolean
|
||||||
|
function OnOffInterface:set_on(on) end
|
||||||
|
---@async
|
||||||
|
---@return boolean
|
||||||
|
function OnOffInterface:on() end
|
||||||
|
|
||||||
|
---@class BrightnessInterface: DeviceInterface
|
||||||
|
local BrightnessInterface
|
||||||
|
---@async
|
||||||
|
---@param brightness integer
|
||||||
|
function BrightnessInterface:set_brightness(brightness) end
|
||||||
|
---@async
|
||||||
|
---@return integer
|
||||||
|
function BrightnessInterface:brightness() end
|
||||||
|
|
||||||
|
---@class ColorSettingInterface: DeviceInterface
|
||||||
|
local ColorSettingInterface
|
||||||
|
---@async
|
||||||
|
---@param temperature integer
|
||||||
|
function ColorSettingInterface:set_color_temperature(temperature) end
|
||||||
|
---@async
|
||||||
|
---@return integer
|
||||||
|
function ColorSettingInterface:color_temperature() end
|
||||||
|
|
||||||
|
---@class OpenCloseInterface: DeviceInterface
|
||||||
|
local OpenCloseInterface
|
||||||
|
---@async
|
||||||
|
---@param open_percent integer
|
||||||
|
function OpenCloseInterface:set_open_percent(open_percent) end
|
||||||
|
---@async
|
||||||
|
---@return integer
|
||||||
|
function OpenCloseInterface:open_percent() end
|
||||||
@@ -3,15 +3,13 @@ name = "google_home"
|
|||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
async-trait = { workspace = true }
|
||||||
automation_cast = { workspace = true }
|
automation_cast = { workspace = true }
|
||||||
|
futures = { workspace = true }
|
||||||
google_home_macro = { workspace = true }
|
google_home_macro = { workspace = true }
|
||||||
|
json_value_merge = { 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 }
|
||||||
async-trait = { workspace = true }
|
|
||||||
futures = { workspace = true }
|
|
||||||
json_value_merge = { workspace = true }
|
|
||||||
|
|||||||
@@ -40,8 +40,7 @@ impl GoogleHome {
|
|||||||
let intent = request.inputs.into_iter().next();
|
let intent = request.inputs.into_iter().next();
|
||||||
|
|
||||||
let payload: OptionFuture<_> = intent
|
let payload: OptionFuture<_> = intent
|
||||||
.map(|intent| async move {
|
.map(async |intent| match intent {
|
||||||
match intent {
|
|
||||||
Intent::Sync => ResponsePayload::Sync(self.sync(devices).await),
|
Intent::Sync => ResponsePayload::Sync(self.sync(devices).await),
|
||||||
Intent::Query(payload) => {
|
Intent::Query(payload) => {
|
||||||
ResponsePayload::Query(self.query(payload, devices).await)
|
ResponsePayload::Query(self.query(payload, devices).await)
|
||||||
@@ -49,7 +48,6 @@ impl GoogleHome {
|
|||||||
Intent::Execute(payload) => {
|
Intent::Execute(payload) => {
|
||||||
ResponsePayload::Execute(self.execute(payload, devices).await)
|
ResponsePayload::Execute(self.execute(payload, devices).await)
|
||||||
}
|
}
|
||||||
}
|
|
||||||
})
|
})
|
||||||
.into();
|
.into();
|
||||||
|
|
||||||
@@ -64,7 +62,7 @@ impl GoogleHome {
|
|||||||
devices: &HashMap<String, Box<T>>,
|
devices: &HashMap<String, Box<T>>,
|
||||||
) -> sync::Payload {
|
) -> sync::Payload {
|
||||||
let mut resp_payload = sync::Payload::new(&self.user_id);
|
let mut resp_payload = sync::Payload::new(&self.user_id);
|
||||||
let f = devices.values().map(|device| async move {
|
let f = devices.values().map(async |device| {
|
||||||
if let Some(device) = device.as_ref().cast() {
|
if let Some(device) = device.as_ref().cast() {
|
||||||
Some(Device::sync(device).await)
|
Some(Device::sync(device).await)
|
||||||
} else {
|
} else {
|
||||||
@@ -86,7 +84,7 @@ impl GoogleHome {
|
|||||||
.devices
|
.devices
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|device| device.id)
|
.map(|device| device.id)
|
||||||
.map(|id| async move {
|
.map(async |id| {
|
||||||
// NOTE: Requires let_chains feature
|
// NOTE: Requires let_chains feature
|
||||||
let device = if let Some(device) = devices.get(id.as_str())
|
let device = if let Some(device) = devices.get(id.as_str())
|
||||||
&& let Some(device) = device.as_ref().cast()
|
&& let Some(device) = device.as_ref().cast()
|
||||||
@@ -115,9 +113,7 @@ impl GoogleHome {
|
|||||||
) -> execute::Payload {
|
) -> execute::Payload {
|
||||||
let resp_payload = Arc::new(Mutex::new(response::execute::Payload::new()));
|
let resp_payload = Arc::new(Mutex::new(response::execute::Payload::new()));
|
||||||
|
|
||||||
let f = payload.commands.into_iter().map(|command| {
|
let f = payload.commands.into_iter().map(async |command| {
|
||||||
let resp_payload = resp_payload.clone();
|
|
||||||
async move {
|
|
||||||
let mut success = response::execute::Command::new(execute::Status::Success);
|
let mut success = response::execute::Command::new(execute::Status::Success);
|
||||||
success.states = Some(execute::States {
|
success.states = Some(execute::States {
|
||||||
online: true,
|
online: true,
|
||||||
@@ -134,9 +130,7 @@ impl GoogleHome {
|
|||||||
.devices
|
.devices
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|device| device.id)
|
.map(|device| device.id)
|
||||||
.map(|id| {
|
.map(async |id| {
|
||||||
let execution = command.execution.clone();
|
|
||||||
async move {
|
|
||||||
if let Some(device) = devices.get(id.as_str())
|
if let Some(device) = devices.get(id.as_str())
|
||||||
&& let Some(device) = device.as_ref().cast()
|
&& let Some(device) = device.as_ref().cast()
|
||||||
{
|
{
|
||||||
@@ -146,14 +140,13 @@ impl GoogleHome {
|
|||||||
|
|
||||||
// NOTE: We can not use .map here because async =(
|
// NOTE: We can not use .map here because async =(
|
||||||
let mut results = Vec::new();
|
let mut results = Vec::new();
|
||||||
for cmd in &execution {
|
for cmd in &command.execution {
|
||||||
results.push(Device::execute(device, cmd.clone()).await);
|
results.push(Device::execute(device, cmd.clone()).await);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Convert vec of results to a result with a vec and the first
|
// Convert vec of results to a result with a vec and the first
|
||||||
// encountered error
|
// encountered error
|
||||||
let results =
|
let results = results.into_iter().collect::<Result<Vec<_>, ErrorCode>>();
|
||||||
results.into_iter().collect::<Result<Vec<_>, ErrorCode>>();
|
|
||||||
|
|
||||||
// TODO: We only get one error not all errors
|
// TODO: We only get one error not all errors
|
||||||
if let Err(err) = results {
|
if let Err(err) = results {
|
||||||
@@ -164,7 +157,6 @@ impl GoogleHome {
|
|||||||
} else {
|
} else {
|
||||||
(id.clone(), Err(DeviceError::DeviceNotFound.into()))
|
(id.clone(), Err(DeviceError::DeviceNotFound.into()))
|
||||||
}
|
}
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
let a = join_all(f).await;
|
let a = join_all(f).await;
|
||||||
@@ -193,7 +185,6 @@ impl GoogleHome {
|
|||||||
cmd.error_code = Some(error);
|
cmd.error_code = Some(error);
|
||||||
resp_payload.add_command(cmd);
|
resp_payload.add_command(cmd);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
join_all(f).await;
|
join_all(f).await;
|
||||||
|
|||||||
167
src/bin/automation.rs
Normal file
167
src/bin/automation.rs
Normal file
@@ -0,0 +1,167 @@
|
|||||||
|
#![feature(iter_intersperse)]
|
||||||
|
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
use std::path::Path;
|
||||||
|
use std::process;
|
||||||
|
|
||||||
|
use ::config::{Environment, File};
|
||||||
|
use automation::config::{Config, Setup};
|
||||||
|
use automation::secret::EnvironmentSecretFile;
|
||||||
|
use automation::version::VERSION;
|
||||||
|
use automation::web::{ApiError, User};
|
||||||
|
use automation_lib::device_manager::DeviceManager;
|
||||||
|
use automation_lib::mqtt;
|
||||||
|
use axum::extract::{FromRef, State};
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use axum::routing::post;
|
||||||
|
use axum::{Json, Router};
|
||||||
|
use google_home::{GoogleHome, Request, Response};
|
||||||
|
use mlua::LuaSerdeExt;
|
||||||
|
use tokio::net::TcpListener;
|
||||||
|
use tracing::{debug, error, info, warn};
|
||||||
|
|
||||||
|
// Force automation_devices to link so that it gets registered as a module
|
||||||
|
extern crate automation_devices;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
struct AppState {
|
||||||
|
pub openid_url: String,
|
||||||
|
pub device_manager: DeviceManager,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromRef<AppState> for String {
|
||||||
|
fn from_ref(input: &AppState) -> Self {
|
||||||
|
input.openid_url.clone()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() {
|
||||||
|
if let Err(err) = app().await {
|
||||||
|
error!("Error: {err}");
|
||||||
|
let mut cause = err.source();
|
||||||
|
while let Some(c) = cause {
|
||||||
|
error!("Cause: {c}");
|
||||||
|
cause = c.source();
|
||||||
|
}
|
||||||
|
process::exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn fulfillment(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
user: User,
|
||||||
|
Json(payload): Json<Request>,
|
||||||
|
) -> Result<Json<Response>, ApiError> {
|
||||||
|
debug!(username = user.preferred_username, "{payload:#?}");
|
||||||
|
let gc = GoogleHome::new(&user.preferred_username);
|
||||||
|
let devices = state.device_manager.devices().await;
|
||||||
|
let result = gc
|
||||||
|
.handle_request(payload, &devices)
|
||||||
|
.await
|
||||||
|
.map_err(|err| ApiError::new(StatusCode::INTERNAL_SERVER_ERROR, err.into()))?;
|
||||||
|
|
||||||
|
debug!(username = user.preferred_username, "{result:#?}");
|
||||||
|
|
||||||
|
Ok(Json(result))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn app() -> anyhow::Result<()> {
|
||||||
|
tracing_subscriber::fmt::init();
|
||||||
|
|
||||||
|
info!(version = VERSION, "automation_rs");
|
||||||
|
|
||||||
|
let setup: Setup = ::config::Config::builder()
|
||||||
|
.add_source(
|
||||||
|
File::with_name(&format!("{}.toml", std::env!("CARGO_PKG_NAME"))).required(false),
|
||||||
|
)
|
||||||
|
.add_source(
|
||||||
|
Environment::default()
|
||||||
|
.prefix(std::env!("CARGO_PKG_NAME"))
|
||||||
|
.separator("__"),
|
||||||
|
)
|
||||||
|
.add_source(EnvironmentSecretFile::default())
|
||||||
|
.build()
|
||||||
|
.unwrap()
|
||||||
|
.try_deserialize()
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
// Setup the device handler
|
||||||
|
let device_manager = DeviceManager::new().await;
|
||||||
|
|
||||||
|
let lua = mlua::Lua::new();
|
||||||
|
|
||||||
|
lua.set_warning_function(|_lua, text, _cont| {
|
||||||
|
warn!("{text}");
|
||||||
|
Ok(())
|
||||||
|
});
|
||||||
|
let print = lua.create_function(|lua, values: mlua::Variadic<mlua::Value>| {
|
||||||
|
// Fortmat the values the same way lua does by default
|
||||||
|
let text: String = values
|
||||||
|
.iter()
|
||||||
|
.map(|value| {
|
||||||
|
value.to_string().unwrap_or_else(|_| {
|
||||||
|
format!("{}: {}", value.type_name(), value.to_pointer().addr())
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.intersperse("\t".to_owned())
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
// Level 1 of the stack gives us the location that called this function
|
||||||
|
let (file, line) = lua
|
||||||
|
.inspect_stack(1, |debug| {
|
||||||
|
(
|
||||||
|
debug
|
||||||
|
.source()
|
||||||
|
.short_src
|
||||||
|
.unwrap_or("???".into())
|
||||||
|
.into_owned(),
|
||||||
|
debug.current_line().unwrap_or(0),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
// The target is overridden to make it possible to filter for logs originating from the
|
||||||
|
// config
|
||||||
|
info!(target: "automation_config", %file, line, "{text}");
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
})?;
|
||||||
|
lua.globals().set("print", print)?;
|
||||||
|
|
||||||
|
automation_lib::load_modules(&lua)?;
|
||||||
|
|
||||||
|
lua.register_module("automation:variables", lua.to_value(&setup.variables)?)?;
|
||||||
|
lua.register_module("automation:secrets", lua.to_value(&setup.secrets)?)?;
|
||||||
|
|
||||||
|
let entrypoint = Path::new(&setup.entrypoint);
|
||||||
|
let config: Config = lua.load(entrypoint).eval_async().await?;
|
||||||
|
|
||||||
|
let mqtt_client = mqtt::start(config.mqtt, &device_manager.event_channel());
|
||||||
|
|
||||||
|
let resolved = config.modules.resolve(&lua, &mqtt_client).await?;
|
||||||
|
for device in resolved.devices {
|
||||||
|
device_manager.add(device).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
resolved.scheduler.start().await?;
|
||||||
|
|
||||||
|
// Create google home fulfillment route
|
||||||
|
let fulfillment = Router::new().route("/google_home", post(fulfillment));
|
||||||
|
|
||||||
|
// Combine together all the routes
|
||||||
|
let app = Router::new()
|
||||||
|
.nest("/fulfillment", fulfillment)
|
||||||
|
.with_state(AppState {
|
||||||
|
openid_url: config.fulfillment.openid_url.clone(),
|
||||||
|
device_manager,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Start the web server
|
||||||
|
let addr: SocketAddr = config.fulfillment.into();
|
||||||
|
info!("Server started on http://{addr}");
|
||||||
|
let listener = TcpListener::bind(addr).await?;
|
||||||
|
axum::serve(listener, app).await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
45
src/bin/generate_definitions.rs
Normal file
45
src/bin/generate_definitions.rs
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
use std::fs::{self, File};
|
||||||
|
use std::io::Write;
|
||||||
|
|
||||||
|
use automation::config::generate_definitions;
|
||||||
|
use automation_lib::Module;
|
||||||
|
use tracing::{info, warn};
|
||||||
|
|
||||||
|
extern crate automation_devices;
|
||||||
|
|
||||||
|
fn write_definitions(filename: &str, definitions: &str) -> std::io::Result<()> {
|
||||||
|
let definitions_directory =
|
||||||
|
std::path::Path::new(std::env!("CARGO_MANIFEST_DIR")).join("definitions");
|
||||||
|
fs::create_dir_all(&definitions_directory)?;
|
||||||
|
|
||||||
|
let mut file = File::create(definitions_directory.join(filename))?;
|
||||||
|
|
||||||
|
file.write_all(b"-- DO NOT MODIFY, FILE IS AUTOMATICALLY GENERATED\n")?;
|
||||||
|
file.write_all(definitions.as_bytes())?;
|
||||||
|
|
||||||
|
// Make sure we have a trailing new line
|
||||||
|
if !definitions.ends_with("\n") {
|
||||||
|
file.write_all(b"\n")?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() -> std::io::Result<()> {
|
||||||
|
tracing_subscriber::fmt::init();
|
||||||
|
|
||||||
|
for module in inventory::iter::<Module> {
|
||||||
|
if let Some(definitions) = module.definitions() {
|
||||||
|
info!(name = module.get_name(), "Generating definitions");
|
||||||
|
|
||||||
|
let filename = format!("{}.lua", module.get_name());
|
||||||
|
write_definitions(&filename, &definitions)?;
|
||||||
|
} else {
|
||||||
|
warn!(name = module.get_name(), "No definitions");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
write_definitions("config.lua", &generate_definitions())?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
288
src/config.rs
Normal file
288
src/config.rs
Normal file
@@ -0,0 +1,288 @@
|
|||||||
|
use std::collections::{HashMap, VecDeque};
|
||||||
|
use std::net::{Ipv4Addr, SocketAddr};
|
||||||
|
use std::ops::Deref;
|
||||||
|
|
||||||
|
use automation_lib::action_callback::ActionCallback;
|
||||||
|
use automation_lib::device::Device;
|
||||||
|
use automation_lib::mqtt::{MqttConfig, WrappedAsyncClient};
|
||||||
|
use automation_macro::LuaDeviceConfig;
|
||||||
|
use lua_typed::Typed;
|
||||||
|
use mlua::FromLua;
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
use crate::schedule::Scheduler;
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
pub struct Setup {
|
||||||
|
#[serde(default = "default_entrypoint")]
|
||||||
|
pub entrypoint: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub variables: HashMap<String, String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub secrets: HashMap<String, String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_entrypoint() -> String {
|
||||||
|
"./config/config.lua".into()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, Typed)]
|
||||||
|
pub struct FulfillmentConfig {
|
||||||
|
pub openid_url: String,
|
||||||
|
#[serde(default = "default_fulfillment_ip")]
|
||||||
|
#[typed(default)]
|
||||||
|
pub ip: Ipv4Addr,
|
||||||
|
#[serde(default = "default_fulfillment_port")]
|
||||||
|
#[typed(default)]
|
||||||
|
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)]
|
||||||
|
pub struct Config {
|
||||||
|
pub fulfillment: FulfillmentConfig,
|
||||||
|
#[device_config(from_lua, default)]
|
||||||
|
pub modules: Modules,
|
||||||
|
#[device_config(from_lua)]
|
||||||
|
pub mqtt: MqttConfig,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<FulfillmentConfig> for SocketAddr {
|
||||||
|
fn from(fulfillment: FulfillmentConfig) -> Self {
|
||||||
|
(fulfillment.ip, fulfillment.port).into()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn default_fulfillment_ip() -> Ipv4Addr {
|
||||||
|
[0, 0, 0, 0].into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_fulfillment_port() -> u16 {
|
||||||
|
7878
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn generate_definitions() -> String {
|
||||||
|
let mut output = "---@meta\n\n".to_string();
|
||||||
|
|
||||||
|
output +=
|
||||||
|
&FulfillmentConfig::generate_full().expect("FulfillmentConfig should have a definition");
|
||||||
|
output += "\n";
|
||||||
|
output += &Config::generate_full().expect("Config should have a definition");
|
||||||
|
output += "\n";
|
||||||
|
output += &SetupFunction::generate_full().expect("SetupFunction should have a definition");
|
||||||
|
output += "\n";
|
||||||
|
output += &Schedule::generate_full().expect("Schedule should have a definition");
|
||||||
|
output += "\n";
|
||||||
|
output += &Module::generate_full().expect("Module should have a definition");
|
||||||
|
output += "\n";
|
||||||
|
output += &MqttConfig::generate_full().expect("MqttConfig should have a definition");
|
||||||
|
output += "\n";
|
||||||
|
output +=
|
||||||
|
&WrappedAsyncClient::generate_full().expect("WrappedAsyncClient should have a definition");
|
||||||
|
|
||||||
|
output
|
||||||
|
}
|
||||||
7
src/lib.rs
Normal file
7
src/lib.rs
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
#![feature(if_let_guard)]
|
||||||
|
|
||||||
|
pub mod config;
|
||||||
|
pub mod schedule;
|
||||||
|
pub mod secret;
|
||||||
|
pub mod version;
|
||||||
|
pub mod web;
|
||||||
168
src/main.rs
168
src/main.rs
@@ -1,168 +0,0 @@
|
|||||||
mod web;
|
|
||||||
|
|
||||||
use std::net::SocketAddr;
|
|
||||||
use std::path::Path;
|
|
||||||
use std::process;
|
|
||||||
use std::time::{SystemTime, UNIX_EPOCH};
|
|
||||||
|
|
||||||
use anyhow::anyhow;
|
|
||||||
use automation_lib::config::{FulfillmentConfig, MqttConfig};
|
|
||||||
use automation_lib::device_manager::DeviceManager;
|
|
||||||
use automation_lib::helpers;
|
|
||||||
use automation_lib::mqtt::{self, WrappedAsyncClient};
|
|
||||||
use axum::extract::{FromRef, State};
|
|
||||||
use axum::http::StatusCode;
|
|
||||||
use axum::routing::post;
|
|
||||||
use axum::{Json, Router};
|
|
||||||
use dotenvy::dotenv;
|
|
||||||
use google_home::{GoogleHome, Request, Response};
|
|
||||||
use mlua::LuaSerdeExt;
|
|
||||||
use rumqttc::AsyncClient;
|
|
||||||
use tokio::net::TcpListener;
|
|
||||||
use tracing::{debug, error, info, warn};
|
|
||||||
use web::{ApiError, User};
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
struct AppState {
|
|
||||||
pub openid_url: String,
|
|
||||||
pub device_manager: DeviceManager,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl FromRef<AppState> for String {
|
|
||||||
fn from_ref(input: &AppState) -> Self {
|
|
||||||
input.openid_url.clone()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::main]
|
|
||||||
async fn main() {
|
|
||||||
if let Err(err) = app().await {
|
|
||||||
error!("Error: {err}");
|
|
||||||
let mut cause = err.source();
|
|
||||||
while let Some(c) = cause {
|
|
||||||
error!("Cause: {c}");
|
|
||||||
cause = c.source();
|
|
||||||
}
|
|
||||||
process::exit(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn fulfillment(
|
|
||||||
State(state): State<AppState>,
|
|
||||||
user: User,
|
|
||||||
Json(payload): Json<Request>,
|
|
||||||
) -> Result<Json<Response>, ApiError> {
|
|
||||||
debug!(username = user.preferred_username, "{payload:#?}");
|
|
||||||
let gc = GoogleHome::new(&user.preferred_username);
|
|
||||||
let devices = state.device_manager.devices().await;
|
|
||||||
let result = gc
|
|
||||||
.handle_request(payload, &devices)
|
|
||||||
.await
|
|
||||||
.map_err(|err| ApiError::new(StatusCode::INTERNAL_SERVER_ERROR, err.into()))?;
|
|
||||||
|
|
||||||
debug!(username = user.preferred_username, "{result:#?}");
|
|
||||||
|
|
||||||
Ok(Json(result))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn app() -> anyhow::Result<()> {
|
|
||||||
dotenv().ok();
|
|
||||||
|
|
||||||
tracing_subscriber::fmt::init();
|
|
||||||
// console_subscriber::init();
|
|
||||||
|
|
||||||
info!("Starting automation_rs...");
|
|
||||||
|
|
||||||
// Setup the device handler
|
|
||||||
let device_manager = DeviceManager::new().await;
|
|
||||||
|
|
||||||
let fulfillment_config = {
|
|
||||||
let lua = mlua::Lua::new();
|
|
||||||
|
|
||||||
lua.set_warning_function(|_lua, text, _cont| {
|
|
||||||
warn!("{text}");
|
|
||||||
Ok(())
|
|
||||||
});
|
|
||||||
|
|
||||||
let automation = lua.create_table()?;
|
|
||||||
let event_channel = device_manager.event_channel();
|
|
||||||
let new_mqtt_client = lua.create_function(move |lua, config: mlua::Value| {
|
|
||||||
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);
|
|
||||||
mqtt::start(eventloop, &event_channel);
|
|
||||||
|
|
||||||
Ok(WrappedAsyncClient(client))
|
|
||||||
})?;
|
|
||||||
|
|
||||||
automation.set("new_mqtt_client", new_mqtt_client)?;
|
|
||||||
automation.set("device_manager", device_manager.clone())?;
|
|
||||||
|
|
||||||
let util = lua.create_table()?;
|
|
||||||
let get_env = lua.create_function(|_lua, name: String| {
|
|
||||||
std::env::var(name).map_err(mlua::ExternalError::into_lua_err)
|
|
||||||
})?;
|
|
||||||
util.set("get_env", get_env)?;
|
|
||||||
let get_hostname = lua.create_function(|_lua, ()| {
|
|
||||||
hostname::get()
|
|
||||||
.map(|name| name.to_str().unwrap_or("unknown").to_owned())
|
|
||||||
.map_err(mlua::ExternalError::into_lua_err)
|
|
||||||
})?;
|
|
||||||
util.set("get_hostname", get_hostname)?;
|
|
||||||
let get_epoch = lua.create_function(|_lua, ()| {
|
|
||||||
Ok(SystemTime::now()
|
|
||||||
.duration_since(UNIX_EPOCH)
|
|
||||||
.expect("Time is after UNIX EPOCH")
|
|
||||||
.as_millis())
|
|
||||||
})?;
|
|
||||||
util.set("get_epoch", get_epoch)?;
|
|
||||||
automation.set("util", util)?;
|
|
||||||
|
|
||||||
lua.globals().set("automation", automation)?;
|
|
||||||
|
|
||||||
automation_devices::register_with_lua(&lua)?;
|
|
||||||
helpers::register_with_lua(&lua)?;
|
|
||||||
|
|
||||||
// TODO: Make this not hardcoded
|
|
||||||
let config_filename = std::env::var("AUTOMATION_CONFIG").unwrap_or("./config.lua".into());
|
|
||||||
let config_path = Path::new(&config_filename);
|
|
||||||
match lua.load(config_path).exec_async().await {
|
|
||||||
Err(error) => {
|
|
||||||
println!("{error}");
|
|
||||||
Err(error)
|
|
||||||
}
|
|
||||||
result => result,
|
|
||||||
}?;
|
|
||||||
|
|
||||||
let automation: mlua::Table = lua.globals().get("automation")?;
|
|
||||||
let fulfillment_config: Option<mlua::Value> = automation.get("fulfillment")?;
|
|
||||||
if let Some(fulfillment_config) = fulfillment_config {
|
|
||||||
let fulfillment_config: FulfillmentConfig = lua.from_value(fulfillment_config)?;
|
|
||||||
debug!("automation.fulfillment = {fulfillment_config:?}");
|
|
||||||
fulfillment_config
|
|
||||||
} else {
|
|
||||||
return Err(anyhow!("Fulfillment is not configured"));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Create google home fulfillment route
|
|
||||||
let fulfillment = Router::new().route("/google_home", post(fulfillment));
|
|
||||||
|
|
||||||
// Combine together all the routes
|
|
||||||
let app = Router::new()
|
|
||||||
.nest("/fulfillment", fulfillment)
|
|
||||||
.with_state(AppState {
|
|
||||||
openid_url: fulfillment_config.openid_url.clone(),
|
|
||||||
device_manager,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Start the web server
|
|
||||||
let addr: SocketAddr = fulfillment_config.into();
|
|
||||||
info!("Server started on http://{addr}");
|
|
||||||
let listener = TcpListener::bind(addr).await?;
|
|
||||||
axum::serve(listener, app).await?;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
37
src/schedule.rs
Normal file
37
src/schedule.rs
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
43
src/secret.rs
Normal file
43
src/secret.rs
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
use std::str::from_utf8;
|
||||||
|
|
||||||
|
use config::{ConfigError, Source, Value, ValueKind};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default)]
|
||||||
|
pub struct EnvironmentSecretFile {}
|
||||||
|
|
||||||
|
const SUFFIX: &str = "__file";
|
||||||
|
const PREFIX: &str = concat!(std::env!("CARGO_PKG_NAME"), "__");
|
||||||
|
|
||||||
|
impl Source for EnvironmentSecretFile {
|
||||||
|
fn clone_into_box(&self) -> Box<dyn Source + Send + Sync> {
|
||||||
|
Box::new((*self).clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn collect(&self) -> Result<config::Map<String, config::Value>, ConfigError> {
|
||||||
|
Ok(std::env::vars()
|
||||||
|
.flat_map(|(key, value): (String, String)| {
|
||||||
|
let key = key.to_lowercase();
|
||||||
|
if !key.starts_with(PREFIX) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
if !key.ends_with(SUFFIX) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let suffix_length = key.len() - SUFFIX.len();
|
||||||
|
let key = key[PREFIX.len()..suffix_length].replace("__", ".");
|
||||||
|
|
||||||
|
if key.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let content = from_utf8(&std::fs::read(&value).unwrap())
|
||||||
|
.unwrap()
|
||||||
|
.to_owned();
|
||||||
|
|
||||||
|
Some((key, Value::new(Some(&value), ValueKind::String(content))))
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
}
|
||||||
11
src/version.rs
Normal file
11
src/version.rs
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
pub const VERSION: &str = get_version();
|
||||||
|
|
||||||
|
const fn get_version() -> &'static str {
|
||||||
|
if let Some(version) = std::option_env!("RELEASE_VERSION")
|
||||||
|
&& !version.is_empty()
|
||||||
|
{
|
||||||
|
version
|
||||||
|
} else {
|
||||||
|
git_version::git_version!(fallback = "unknown")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
use std::result;
|
use std::result;
|
||||||
|
|
||||||
use axum::async_trait;
|
|
||||||
use axum::extract::{FromRef, FromRequestParts};
|
use axum::extract::{FromRef, FromRequestParts};
|
||||||
use axum::http::StatusCode;
|
use axum::http::StatusCode;
|
||||||
use axum::http::request::Parts;
|
use axum::http::request::Parts;
|
||||||
@@ -79,7 +78,6 @@ pub struct User {
|
|||||||
pub preferred_username: String,
|
pub preferred_username: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl<S> FromRequestParts<S> for User
|
impl<S> FromRequestParts<S> for User
|
||||||
where
|
where
|
||||||
String: FromRef<S>,
|
String: FromRef<S>,
|
||||||
@@ -116,7 +114,7 @@ where
|
|||||||
.await
|
.await
|
||||||
.map_err(|err| ApiError::new(StatusCode::INTERNAL_SERVER_ERROR, err.into()))?;
|
.map_err(|err| ApiError::new(StatusCode::INTERNAL_SERVER_ERROR, err.into()))?;
|
||||||
|
|
||||||
return Ok(user);
|
Ok(user)
|
||||||
} else {
|
} else {
|
||||||
let err: ApiErrorJson = res
|
let err: ApiErrorJson = res
|
||||||
.json()
|
.json()
|
||||||
|
|||||||
Reference in New Issue
Block a user