Compare commits
11 Commits
6c7a774d7e
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
8c6adae3ae
|
|||
|
2158bde1c2
|
|||
|
b547f66d86
|
|||
|
f3de8e36ea
|
|||
|
44f2c57819
|
|||
|
ad158f2c22
|
|||
|
f36adf2f19
|
|||
|
5947098bfb
|
|||
|
8a3143a3ea
|
|||
|
9546585440
|
|||
|
a938f3d71b
|
@@ -9,10 +9,10 @@ on:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
uses: dreaded_x/workflows/.gitea/workflows/rust-kubernetes.yaml@22ee0c1788a8d2157db87d6a6f8dbe520fe48592
|
||||
uses: dreaded_x/workflows/.gitea/workflows/docker-kubernetes.yaml@ef78704b98c72e4a6b8340f9bff7b085a7bdd95c
|
||||
secrets: inherit
|
||||
with:
|
||||
upload_manifests: false
|
||||
push_manifests: false
|
||||
|
||||
deploy:
|
||||
name: Deploy container
|
||||
@@ -37,7 +37,7 @@ jobs:
|
||||
-e AUTOMATION__SECRETS__MQTT_PASSWORD=${{ secrets.MQTT_PASSWORD }} \
|
||||
-e AUTOMATION__SECRETS__HUE_TOKEN=${{ secrets.HUE_TOKEN }} \
|
||||
-e AUTOMATION__SECRETS__NTFY_TOPIC=${{ secrets.NTFY_TOPIC }} \
|
||||
git.huizinga.dev/dreaded_x/automation_rs@${{ needs.build.outputs.digest }}
|
||||
$(echo ${{ toJSON(needs.build.outputs.images) }} | jq .automation -r)
|
||||
|
||||
docker network connect web automation_rs
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@ ENV CARGO_REGISTRIES_CRATES_IO_PROTOCOL=sparse
|
||||
RUN cargo install cargo-chef --locked --version 0.1.71 && \
|
||||
cargo install cargo-auditable --locked --version 0.6.6
|
||||
WORKDIR /app
|
||||
COPY ./rust-toolchain.toml .
|
||||
RUN rustup toolchain install
|
||||
|
||||
FROM base AS planner
|
||||
COPY . .
|
||||
@@ -21,5 +23,7 @@ RUN cargo auditable build --release
|
||||
|
||||
FROM gcr.io/distroless/cc-debian12:nonroot AS runtime
|
||||
COPY --from=builder /app/target/release/automation /app/automation
|
||||
ENV AUTOMATION__ENTRYPOINT=/app/config/config.lua
|
||||
ENV LUA_PATH="/app/?.lua;;"
|
||||
COPY ./config /app/config
|
||||
CMD [ "/app/automation" ]
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
local ntfy = require("config.ntfy")
|
||||
|
||||
--- @class BatteryModule: Module
|
||||
local module = {}
|
||||
|
||||
--- @type {[string]: number}
|
||||
@@ -17,7 +18,7 @@ function module.callback(device, battery)
|
||||
end
|
||||
end
|
||||
|
||||
function module.notify_low_battery()
|
||||
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")
|
||||
@@ -38,4 +39,9 @@ function module.notify_low_battery()
|
||||
})
|
||||
end
|
||||
|
||||
--- @type Schedule
|
||||
module.schedule = {
|
||||
["0 0 21 */1 * *"] = notify_low_battery,
|
||||
}
|
||||
|
||||
return module
|
||||
|
||||
@@ -29,14 +29,4 @@ return {
|
||||
require("config.rooms"),
|
||||
require("config.windows"),
|
||||
},
|
||||
-- TODO: Make this also part of the modules
|
||||
schedule = {
|
||||
["0 0 19 * * *"] = function()
|
||||
require("config.rooms.bedroom").set_airfilter_on(true)
|
||||
end,
|
||||
["0 0 20 * * *"] = function()
|
||||
require("config.rooms.bedroom").set_airfilter_on(false)
|
||||
end,
|
||||
["0 0 21 */1 * *"] = require("config.battery").notify_low_battery,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ 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
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
local debug = require("config.debug")
|
||||
local utils = require("automation:utils")
|
||||
|
||||
--- @class HallwayAutomationModule: Module
|
||||
local module = {}
|
||||
|
||||
local timeout = utils.Timeout.new()
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
local utils = require("automation:utils")
|
||||
|
||||
--- @class HelperModule: Module
|
||||
local module = {}
|
||||
|
||||
--- @param topic string
|
||||
|
||||
@@ -3,6 +3,7 @@ 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"
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
local devices = require("automation:devices")
|
||||
local helper = require("config.helper")
|
||||
|
||||
--- @class LightModule: Module
|
||||
local module = {}
|
||||
|
||||
--- @class OnPresence
|
||||
@@ -34,6 +35,7 @@ function module.setup(mqtt_client)
|
||||
callback = callback,
|
||||
})
|
||||
|
||||
--- @type Module
|
||||
return {
|
||||
module.device,
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
local devices = require("automation:devices")
|
||||
local secrets = require("automation:secrets")
|
||||
|
||||
--- @class NtfyModule: Module
|
||||
local module = {}
|
||||
|
||||
local ntfy_topic = secrets.ntfy_topic
|
||||
@@ -24,6 +25,7 @@ function module.setup()
|
||||
topic = ntfy_topic,
|
||||
})
|
||||
|
||||
--- @type Module
|
||||
return {
|
||||
ntfy,
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ local devices = require("automation:devices")
|
||||
local helper = require("config.helper")
|
||||
local ntfy = require("config.ntfy")
|
||||
|
||||
--- @class PresenceModule: Module
|
||||
local module = {}
|
||||
|
||||
--- @class OnPresence
|
||||
@@ -61,6 +62,7 @@ function module.setup(mqtt_client)
|
||||
})
|
||||
end)
|
||||
|
||||
--- @type Module
|
||||
return {
|
||||
presence,
|
||||
}
|
||||
|
||||
@@ -3,9 +3,9 @@ local devices = require("automation:devices")
|
||||
local helper = require("config.helper")
|
||||
local ntfy = require("config.ntfy")
|
||||
|
||||
--- @type Module
|
||||
local module = {}
|
||||
|
||||
--- @type SetupFunction
|
||||
function module.setup(mqtt_client)
|
||||
local light = devices.LightOnOff.new({
|
||||
name = "Light",
|
||||
@@ -30,6 +30,7 @@ function module.setup(mqtt_client)
|
||||
end,
|
||||
})
|
||||
|
||||
--- @type Module
|
||||
return {
|
||||
light,
|
||||
washer,
|
||||
|
||||
@@ -4,12 +4,12 @@ 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
|
||||
|
||||
--- @type SetupFunction
|
||||
function module.setup(mqtt_client)
|
||||
local lights = devices.HueGroup.new({
|
||||
identifier = "bedroom_lights",
|
||||
@@ -55,20 +55,24 @@ function module.setup(mqtt_client)
|
||||
})
|
||||
windows.add(window)
|
||||
|
||||
--- @type Module
|
||||
return {
|
||||
lights,
|
||||
lights_relax,
|
||||
air_filter,
|
||||
switch,
|
||||
window,
|
||||
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
|
||||
|
||||
--- @param on boolean
|
||||
function module.set_airfilter_on(on)
|
||||
if air_filter then
|
||||
air_filter:set_on(on)
|
||||
end
|
||||
end
|
||||
|
||||
return module
|
||||
|
||||
@@ -4,9 +4,9 @@ local helper = require("config.helper")
|
||||
local presence = require("config.presence")
|
||||
local windows = require("config.windows")
|
||||
|
||||
--- @type Module
|
||||
local module = {}
|
||||
|
||||
--- @type SetupFunction
|
||||
function module.setup(mqtt_client)
|
||||
local light = devices.LightOnOff.new({
|
||||
name = "Light",
|
||||
@@ -25,9 +25,18 @@ function module.setup(mqtt_client)
|
||||
})
|
||||
windows.add(window)
|
||||
|
||||
local printer = devices.OutletOnOff.new({
|
||||
name = "3D Printer",
|
||||
room = "Guest Room",
|
||||
topic = helper.mqtt_z2m("guest/printer"),
|
||||
client = mqtt_client,
|
||||
})
|
||||
|
||||
--- @type Module
|
||||
return {
|
||||
light,
|
||||
window,
|
||||
printer,
|
||||
}
|
||||
end
|
||||
|
||||
|
||||
@@ -8,9 +8,9 @@ local presence = require("config.presence")
|
||||
local utils = require("automation:utils")
|
||||
local windows = require("config.windows")
|
||||
|
||||
--- @type Module
|
||||
local module = {}
|
||||
|
||||
--- @type SetupFunction
|
||||
function module.setup(mqtt_client)
|
||||
local main_light = devices.HueGroup.new({
|
||||
identifier = "hallway_main_light",
|
||||
@@ -59,26 +59,21 @@ function module.setup(mqtt_client)
|
||||
})
|
||||
hallway_automation.set_trash(trash)
|
||||
|
||||
---@param duration number
|
||||
---@return fun(_, open: boolean)
|
||||
local function frontdoor_presence(duration)
|
||||
local timeout = utils.Timeout.new()
|
||||
local timeout = utils.Timeout.new()
|
||||
local function frontdoor_presence(_, open)
|
||||
if open then
|
||||
timeout:cancel()
|
||||
|
||||
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)
|
||||
if not presence.overall_presence() then
|
||||
mqtt_client:send_message(helper.mqtt_automation("presence/contact/frontdoor"), {
|
||||
state = true,
|
||||
updated = utils.get_epoch(),
|
||||
})
|
||||
end
|
||||
else
|
||||
timeout:start(debug.debug_mode and 10 or 15 * 60, function()
|
||||
mqtt_client:send_message(helper.mqtt_automation("presence/contact/frontdoor"), nil)
|
||||
end)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -89,7 +84,7 @@ function module.setup(mqtt_client)
|
||||
topic = helper.mqtt_z2m("hallway/frontdoor"),
|
||||
client = mqtt_client,
|
||||
callback = {
|
||||
frontdoor_presence(debug.debug_mode and 10 or 15 * 60),
|
||||
frontdoor_presence,
|
||||
hallway_automation.door_callback,
|
||||
},
|
||||
battery_callback = battery.callback,
|
||||
@@ -97,6 +92,7 @@ function module.setup(mqtt_client)
|
||||
windows.add(frontdoor)
|
||||
hallway_automation.set_door(frontdoor)
|
||||
|
||||
--- @type Module
|
||||
return {
|
||||
main_light,
|
||||
storage_light,
|
||||
|
||||
@@ -3,9 +3,9 @@ local devices = require("automation:devices")
|
||||
local helper = require("config.helper")
|
||||
local hue_bridge = require("config.hue_bridge")
|
||||
|
||||
--- @type Module
|
||||
local module = {}
|
||||
|
||||
--- @type SetupFunction
|
||||
function module.setup(mqtt_client)
|
||||
local light = devices.HueGroup.new({
|
||||
identifier = "hallway_top_light",
|
||||
@@ -37,6 +37,7 @@ function module.setup(mqtt_client)
|
||||
battery_callback = battery.callback,
|
||||
})
|
||||
|
||||
--- @type Module
|
||||
return {
|
||||
light,
|
||||
top_switch,
|
||||
|
||||
@@ -4,6 +4,7 @@ local helper = require("config.helper")
|
||||
local hue_bridge = require("config.hue_bridge")
|
||||
local presence = require("config.presence")
|
||||
|
||||
--- @class KitchenModule: Module
|
||||
local module = {}
|
||||
|
||||
--- @type HueGroup?
|
||||
|
||||
@@ -5,9 +5,9 @@ local hue_bridge = require("config.hue_bridge")
|
||||
local presence = require("config.presence")
|
||||
local windows = require("config.windows")
|
||||
|
||||
--- @type Module
|
||||
local module = {}
|
||||
|
||||
--- @type SetupFunction
|
||||
function module.setup(mqtt_client)
|
||||
local lights = devices.HueGroup.new({
|
||||
identifier = "living_lights",
|
||||
@@ -109,6 +109,7 @@ function module.setup(mqtt_client)
|
||||
})
|
||||
windows.add(window)
|
||||
|
||||
--- @type Module
|
||||
return {
|
||||
lights,
|
||||
lights_relax,
|
||||
|
||||
@@ -3,9 +3,9 @@ local devices = require("automation:devices")
|
||||
local helper = require("config.helper")
|
||||
local presence = require("config.presence")
|
||||
|
||||
--- @type Module
|
||||
local module = {}
|
||||
|
||||
--- @type SetupFunction
|
||||
function module.setup(mqtt_client)
|
||||
local light = devices.LightBrightness.new({
|
||||
name = "Light",
|
||||
@@ -31,6 +31,7 @@ function module.setup(mqtt_client)
|
||||
battery_callback = battery.callback,
|
||||
})
|
||||
|
||||
--- @type Module
|
||||
return {
|
||||
light,
|
||||
door,
|
||||
|
||||
@@ -5,9 +5,9 @@ local helper = require("config.helper")
|
||||
local presence = require("config.presence")
|
||||
local utils = require("automation:utils")
|
||||
|
||||
--- @type Module
|
||||
local module = {}
|
||||
|
||||
--- @type SetupFunction
|
||||
function module.setup(mqtt_client)
|
||||
local charger = devices.OutletOnOff.new({
|
||||
name = "Charger",
|
||||
@@ -57,6 +57,7 @@ function module.setup(mqtt_client)
|
||||
battery_callback = battery.callback,
|
||||
})
|
||||
|
||||
--- @type Module
|
||||
return {
|
||||
charger,
|
||||
outlets,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
local ntfy = require("config.ntfy")
|
||||
local presence = require("config.presence")
|
||||
|
||||
--- @class WindowsModule: Module
|
||||
local module = {}
|
||||
|
||||
--- @class OnPresence
|
||||
|
||||
@@ -11,13 +11,17 @@ local FulfillmentConfig
|
||||
---@field fulfillment FulfillmentConfig
|
||||
---@field modules (Module)[]
|
||||
---@field mqtt MqttConfig
|
||||
---@field schedule (table<string, fun() | fun()[]>)?
|
||||
local Config
|
||||
|
||||
---@alias SetupFunction fun(mqtt_client: AsyncClient): Module | DeviceInterface[] | nil
|
||||
|
||||
---@alias Schedule table<string, fun() | fun()[]>
|
||||
|
||||
---@class Module
|
||||
---@field setup (fun(mqtt_client: AsyncClient): Module | DeviceInterface[] | nil)?
|
||||
---@field devices DeviceInterface[]?
|
||||
---@field [number] Module[]?
|
||||
---@field setup (SetupFunction)?
|
||||
---@field devices (DeviceInterface)[]?
|
||||
---@field schedule Schedule?
|
||||
---@field [number] (Module)[]?
|
||||
local Module
|
||||
|
||||
---@class MqttConfig
|
||||
|
||||
18
docker-bake.hcl
Normal file
18
docker-bake.hcl
Normal file
@@ -0,0 +1,18 @@
|
||||
variable "TAG_BASE" {}
|
||||
variable "RELEASE_VERSION" {}
|
||||
|
||||
group "default" {
|
||||
targets = ["automation"]
|
||||
}
|
||||
|
||||
target "docker-metadata-action" {}
|
||||
|
||||
target "automation" {
|
||||
inherits = ["docker-metadata-action"]
|
||||
context = "./"
|
||||
dockerfile = "Dockerfile"
|
||||
tags = [for tag in target.docker-metadata-action.tags : "${TAG_BASE}:${tag}"]
|
||||
args = {
|
||||
RELEASE_VERSION="${RELEASE_VERSION}"
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,6 @@ use std::process;
|
||||
|
||||
use ::config::{Environment, File};
|
||||
use automation::config::{Config, Setup};
|
||||
use automation::schedule::start_scheduler;
|
||||
use automation::secret::EnvironmentSecretFile;
|
||||
use automation::version::VERSION;
|
||||
use automation::web::{ApiError, User};
|
||||
@@ -145,7 +144,7 @@ async fn app() -> anyhow::Result<()> {
|
||||
device_manager.add(device).await;
|
||||
}
|
||||
|
||||
start_scheduler(config.schedule).await?;
|
||||
resolved.scheduler.start().await?;
|
||||
|
||||
// Create google home fulfillment route
|
||||
let fulfillment = Router::new().route("/google_home", post(fulfillment));
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
use std::fs::{self, File};
|
||||
use std::io::Write;
|
||||
|
||||
use automation::config::{Config, FulfillmentConfig, Module as ConfigModule};
|
||||
use automation::config::generate_definitions;
|
||||
use automation_lib::Module;
|
||||
use automation_lib::mqtt::{MqttConfig, WrappedAsyncClient};
|
||||
use lua_typed::Typed;
|
||||
use tracing::{info, warn};
|
||||
|
||||
extern crate automation_devices;
|
||||
@@ -27,24 +25,6 @@ fn write_definitions(filename: &str, definitions: &str) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn config_definitions() -> String {
|
||||
let mut output = "---@meta\n\n".to_string();
|
||||
|
||||
output +=
|
||||
&FulfillmentConfig::generate_full().expect("FulfillmentConfig should have a definition");
|
||||
output += "\n";
|
||||
output += &Config::generate_full().expect("Config should have a definition");
|
||||
output += "\n";
|
||||
output += &ConfigModule::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
|
||||
}
|
||||
|
||||
fn main() -> std::io::Result<()> {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
@@ -59,7 +39,7 @@ fn main() -> std::io::Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
write_definitions("config.lua", &config_definitions())?;
|
||||
write_definitions("config.lua", &generate_definitions())?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
117
src/config.rs
117
src/config.rs
@@ -1,5 +1,6 @@
|
||||
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;
|
||||
@@ -9,6 +10,8 @@ use lua_typed::Typed;
|
||||
use mlua::FromLua;
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::schedule::Scheduler;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct Setup {
|
||||
#[serde(default = "default_entrypoint")]
|
||||
@@ -35,15 +38,20 @@ pub struct FulfillmentConfig {
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct SetupFunction(mlua::Function);
|
||||
struct SetupFunction(mlua::Function);
|
||||
|
||||
impl Typed for SetupFunction {
|
||||
fn type_name() -> String {
|
||||
format!(
|
||||
"fun(mqtt_client: {}): {} | DeviceInterface[] | nil",
|
||||
"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()
|
||||
)
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,11 +61,53 @@ impl FromLua for SetupFunction {
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for SetupFunction {
|
||||
type Target = mlua::Function;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Module {
|
||||
pub setup: Option<SetupFunction>,
|
||||
pub devices: Vec<Box<dyn Device>>,
|
||||
pub modules: Vec<Module>,
|
||||
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
|
||||
@@ -73,10 +123,14 @@ impl Typed for Module {
|
||||
fn generate_members() -> Option<String> {
|
||||
Some(format!(
|
||||
r#"---@field setup {}
|
||||
---@field devices DeviceInterface[]?
|
||||
---@field [number] Module[]?
|
||||
---@field devices {}?
|
||||
---@field schedule {}?
|
||||
---@field [number] {}?
|
||||
"#,
|
||||
Option::<SetupFunction>::type_name()
|
||||
Option::<SetupFunction>::type_name(),
|
||||
Vec::<Box<dyn Device>>::type_name(),
|
||||
Schedule::type_name(),
|
||||
Vec::<Module>::type_name(),
|
||||
))
|
||||
}
|
||||
|
||||
@@ -103,8 +157,9 @@ impl FromLua for Module {
|
||||
};
|
||||
|
||||
let setup = table.get("setup")?;
|
||||
let devices = table.get("devices").unwrap_or_default();
|
||||
let schedule = table.get("schedule").unwrap_or_default();
|
||||
|
||||
let devices = table.get("devices").unwrap_or_else(|_| Vec::new());
|
||||
let mut modules = Vec::new();
|
||||
|
||||
for module in table.sequence_values::<Module>() {
|
||||
@@ -114,6 +169,7 @@ impl FromLua for Module {
|
||||
Ok(Module {
|
||||
setup,
|
||||
devices,
|
||||
schedule,
|
||||
modules,
|
||||
})
|
||||
}
|
||||
@@ -140,10 +196,10 @@ impl Modules {
|
||||
lua: &mlua::Lua,
|
||||
client: &WrappedAsyncClient,
|
||||
) -> mlua::Result<Resolved> {
|
||||
let mut modules: VecDeque<_> = self.0.into();
|
||||
|
||||
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;
|
||||
@@ -152,7 +208,7 @@ impl Modules {
|
||||
modules.extend(module.modules);
|
||||
|
||||
if let Some(setup) = module.setup {
|
||||
let result: mlua::Value = setup.0.call_async(client.clone()).await?;
|
||||
let result: mlua::Value = setup.call_async(client.clone()).await?;
|
||||
|
||||
if result.is_nil() {
|
||||
// We ignore nil results
|
||||
@@ -172,15 +228,19 @@ impl Modules {
|
||||
}
|
||||
|
||||
devices.extend(module.devices);
|
||||
for (cron, f) in module.schedule {
|
||||
scheduler.add_job(cron, f);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Resolved { devices })
|
||||
Ok(Resolved { devices, scheduler })
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Resolved {
|
||||
pub devices: Vec<Box<dyn Device>>,
|
||||
pub scheduler: Scheduler,
|
||||
}
|
||||
|
||||
#[derive(Debug, LuaDeviceConfig, Typed)]
|
||||
@@ -190,9 +250,6 @@ pub struct Config {
|
||||
pub modules: Modules,
|
||||
#[device_config(from_lua)]
|
||||
pub mqtt: MqttConfig,
|
||||
#[device_config(from_lua, default)]
|
||||
#[typed(default)]
|
||||
pub schedule: HashMap<String, ActionCallback<()>>,
|
||||
}
|
||||
|
||||
impl From<FulfillmentConfig> for SocketAddr {
|
||||
@@ -207,3 +264,25 @@ fn default_fulfillment_ip() -> Ipv4Addr {
|
||||
fn default_fulfillment_port() -> u16 {
|
||||
7878
|
||||
}
|
||||
|
||||
pub fn generate_definitions() -> String {
|
||||
let mut output = "---@meta\n\n".to_string();
|
||||
|
||||
output +=
|
||||
&FulfillmentConfig::generate_full().expect("FulfillmentConfig should have a definition");
|
||||
output += "\n";
|
||||
output += &Config::generate_full().expect("Config should have a definition");
|
||||
output += "\n";
|
||||
output += &SetupFunction::generate_full().expect("SetupFunction should have a definition");
|
||||
output += "\n";
|
||||
output += &Schedule::generate_full().expect("Schedule should have a definition");
|
||||
output += "\n";
|
||||
output += &Module::generate_full().expect("Module should have a definition");
|
||||
output += "\n";
|
||||
output += &MqttConfig::generate_full().expect("MqttConfig should have a definition");
|
||||
output += "\n";
|
||||
output +=
|
||||
&WrappedAsyncClient::generate_full().expect("WrappedAsyncClient should have a definition");
|
||||
|
||||
output
|
||||
}
|
||||
|
||||
@@ -1,29 +1,37 @@
|
||||
use std::collections::HashMap;
|
||||
use std::pin::Pin;
|
||||
|
||||
use automation_lib::action_callback::ActionCallback;
|
||||
use tokio_cron_scheduler::{Job, JobScheduler, JobSchedulerError};
|
||||
|
||||
pub async fn start_scheduler(
|
||||
schedule: HashMap<String, ActionCallback<()>>,
|
||||
) -> Result<(), JobSchedulerError> {
|
||||
let scheduler = JobScheduler::new().await?;
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Scheduler {
|
||||
jobs: Vec<(String, ActionCallback<()>)>,
|
||||
}
|
||||
|
||||
for (s, f) in schedule {
|
||||
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?;
|
||||
impl Scheduler {
|
||||
pub fn add_job(&mut self, cron: String, f: ActionCallback<()>) {
|
||||
self.jobs.push((cron, f));
|
||||
}
|
||||
|
||||
scheduler.start().await
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user