Seed the TinyHouse: nineteen flows in place of eight hundred nodes
The Node-RED installation this replaces is 865 nodes across three tabs, and roughly a fifth of it is unreachable — the pellet stove's controller, the scene engine and the awning's logic were all disconnected from the heartbeat they ran on. What is here is the intent rather than the wiring: nineteen named flows, 109 nodes, and no heartbeat at all. A sensor value is the event. The device layer moves with it. `actor/*` and `light/*` were never a device interface — Node-RED subscribed to its own topics, stamped a DMX channel on each and encoded one Art-Net universe — so those topics retire with it and the encoders are five nodes in the `dmx` flow. Two shared library nodes carry what every actuator needs. `arbiter` answers the thing this design was missing: a value someone sets on a screen is not undone by the next evaluation. A manual value wins for a hold, the house takes over when it expires, and a schedule can force past both — so "off at two in the morning" still means off. The control binds to the message the arbiter writes back, so one tile shows what reached the fixture and setting it is the override. `motor` is why a stop is now commanded once. A rollershutter has no position sensor, so time is the only feedback: it says how long to run and a trigger sends the single STOP that ends it. The reference sent STOP forever. Everything is seeded stopped, the Art-Net node does not transmit and the heat pump does not accept commands until house.json says so. `--dry` checks the whole set without an installation: names nothing provides, loops, type disagreements, widgets bound to nothing, and every Python node run once on values of the shape it declared — including whether what it returns goes anywhere. That last one has already caught a typo that would have published into silence. house.json holds this installation's addresses, MAC addresses and DMX map and is git-ignored, as the Node-RED inventory is. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,18 @@
|
||||
#!/usr/bin/env python
|
||||
"""Seed the TinyHouse: the flows that replace the Node-RED installation.
|
||||
|
||||
make -C app seed-tinyhouse
|
||||
|
||||
See `scripts/tinyhouse/` for what it builds, and `house.json` at the workspace
|
||||
root for this installation's own addresses and DMX wiring.
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
from tinyhouse.__main__ import main # noqa: E402
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main(sys.argv[1:]))
|
||||
@@ -0,0 +1,423 @@
|
||||
"""Seed this house into a Fluksio installation.
|
||||
|
||||
make -C app seed-tinyhouse # check everything, then push
|
||||
make -C app seed-tinyhouse ARGS=--dry # check everything, push nothing
|
||||
|
||||
Everything is seeded **stopped** and nothing is armed: the Art-Net node does
|
||||
not transmit and the heat pump does not accept commands until `house.json`
|
||||
says so. Starting a flow is a decision someone makes while watching, which is
|
||||
the whole of the cutover procedure.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from typing import Any
|
||||
|
||||
from . import actuators, control, dashboards, screens, sensing
|
||||
from .api import Api, Flow, house, report
|
||||
from .library import ARBITER, MOTOR
|
||||
|
||||
#: Which secrets the flows reference. Nothing runs without them, and nothing
|
||||
#: here can invent them.
|
||||
SECRETS = {
|
||||
"influx_token": "InfluxDB 2.x API token, for the history and the charts",
|
||||
"unifi_password": "UniFi controller account (read-only is enough)",
|
||||
"owm_appid": "OpenWeatherMap One Call 3.0 key",
|
||||
"caldav_password": "Nextcloud app password for the shared calendar",
|
||||
}
|
||||
|
||||
|
||||
def build(h: dict[str, Any], commands: bool) -> list[Flow]:
|
||||
"""Every flow, in the order it is safe to start them."""
|
||||
return [
|
||||
sensing.clock(),
|
||||
sensing.power(h),
|
||||
sensing.weather(h),
|
||||
sensing.presence(h),
|
||||
sensing.calendar(h),
|
||||
screens.history(h),
|
||||
control.climate(),
|
||||
control.hvac(h, commands),
|
||||
control.oven(h),
|
||||
control.boiler(h),
|
||||
actuators.shutters(h),
|
||||
actuators.window(h),
|
||||
actuators.canopy(h),
|
||||
actuators.lights(),
|
||||
actuators.plugs(h),
|
||||
actuators.appliances(),
|
||||
actuators.outdoor(),
|
||||
actuators.dmx(h),
|
||||
screens.kiosk(h),
|
||||
]
|
||||
|
||||
|
||||
# ── preflight ────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _qualify(flow: str, name: str) -> str:
|
||||
return name if "." in name else f"{flow}.{name}"
|
||||
|
||||
|
||||
def check(flows: list[Flow]) -> list[str]:
|
||||
"""Everything wrong that can be seen without an installation.
|
||||
|
||||
The API validates too, and better — but it does it one flow at a time as
|
||||
they are created, so a cross-flow name that nothing provides is only
|
||||
reported once the last flow lands. Reading the whole set first means a
|
||||
typo is a message here rather than nineteen flows and a broken house.
|
||||
"""
|
||||
provided: dict[str, list[str]] = {}
|
||||
declared: set[str] = set()
|
||||
problems: list[str] = []
|
||||
|
||||
for flow in flows:
|
||||
for spec in flow.inputs:
|
||||
declared.add(_qualify(flow.name, spec["spec"]["name"]))
|
||||
for node in flow.nodes:
|
||||
for spec in node.get("provides", []):
|
||||
provided.setdefault(_qualify(flow.name, spec["name"]), []).append(
|
||||
f"{flow.name}.{node['id']}"
|
||||
)
|
||||
|
||||
known = set(provided) | declared
|
||||
for flow in flows:
|
||||
ids = [node["id"] for node in flow.nodes]
|
||||
if len(set(ids)) != len(ids):
|
||||
problems.append(f"{flow.name}: two nodes share an id")
|
||||
for node in flow.nodes:
|
||||
for spec in node.get("requires", []):
|
||||
name = _qualify(flow.name, spec["name"])
|
||||
if name not in known:
|
||||
problems.append(
|
||||
f"{flow.name}.{node['id']} needs '{name}', "
|
||||
"which nothing provides and no flow declares"
|
||||
)
|
||||
ports = [s.get("port") or s["name"] for s in node.get("requires", [])]
|
||||
if len(set(ports)) != len(ports):
|
||||
problems.append(f"{flow.name}.{node['id']}: two inputs share a port")
|
||||
settings = set(node.get("params", {}))
|
||||
clash = settings & set(ports)
|
||||
if clash:
|
||||
problems.append(
|
||||
f"{flow.name}.{node['id']}: setting and port share a name: "
|
||||
+ ", ".join(sorted(clash))
|
||||
)
|
||||
|
||||
problems += _check_types(flows)
|
||||
problems += _check_cycles(flows, provided)
|
||||
problems += _check_widgets(known)
|
||||
problems += _check_sources(flows)
|
||||
problems += _check_schemas(flows)
|
||||
return problems
|
||||
|
||||
|
||||
def _check_schemas(flows: list[Flow]) -> list[str]:
|
||||
"""Hand every node to the engine's own models before the API sees them.
|
||||
|
||||
The API would say the same thing, one flow at a time, after creating the
|
||||
ones before it. Importing the models is free and answers it here — a
|
||||
misspelled setting on a connector is otherwise found halfway through a
|
||||
house.
|
||||
"""
|
||||
try:
|
||||
from fluksio.flow.controller import NODE_TYPES
|
||||
from fluksio.flow.schemas import FlowDef
|
||||
except ImportError:
|
||||
return []
|
||||
|
||||
problems = []
|
||||
missing: set[str] = set()
|
||||
for flow in flows:
|
||||
try:
|
||||
FlowDef.model_validate(
|
||||
{
|
||||
"name": flow.name,
|
||||
"title": flow.title,
|
||||
"nodes": flow.nodes,
|
||||
"inputs": flow.inputs,
|
||||
}
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001 - reported, not raised
|
||||
problems.append(f"{flow.name}: {exc}")
|
||||
continue
|
||||
|
||||
for node in flow.nodes:
|
||||
spec = NODE_TYPES.get(node["type"])
|
||||
if spec is None:
|
||||
# Connectors are installed into the image, not into the venv
|
||||
# this runs in, so their absence here says nothing. A type that
|
||||
# is neither built in nor a connector this house uses is a
|
||||
# typo, and that is what is worth saying.
|
||||
if node["type"] not in CONNECTORS:
|
||||
problems.append(
|
||||
f"{flow.name}.{node['id']}: no node type '{node['type']}'"
|
||||
)
|
||||
else:
|
||||
missing.add(node["type"])
|
||||
continue
|
||||
if spec.free_params:
|
||||
continue
|
||||
params = getattr(spec.cls, "Params", None)
|
||||
if params is None:
|
||||
continue
|
||||
try:
|
||||
params.model_validate(_without_secrets(node.get("params", {})))
|
||||
except Exception as exc: # noqa: BLE001 - reported, not raised
|
||||
problems.append(f"{flow.name}.{node['id']} settings: {exc}")
|
||||
|
||||
if missing:
|
||||
print(f" (from the image, not checked here: {', '.join(sorted(missing))})")
|
||||
return problems
|
||||
|
||||
|
||||
def _without_secrets(params: Any) -> Any:
|
||||
"""A secret reference is an ordinary string by the time a node is built."""
|
||||
if isinstance(params, dict):
|
||||
if set(params) == {"$secret"}:
|
||||
return "from-the-store"
|
||||
return {k: _without_secrets(v) for k, v in params.items()}
|
||||
if isinstance(params, list):
|
||||
return [_without_secrets(v) for v in params]
|
||||
return params
|
||||
|
||||
|
||||
#: Node types that come from connector packages. `make connectors` installs
|
||||
#: them into the image, so a checkout does not have them and their absence
|
||||
#: here is not a problem to report.
|
||||
CONNECTORS = {"wfrac", "unifi_presence", "ical", "artnet"}
|
||||
|
||||
#: Ports whose payload has a shape the node reads keys out of. Everything else
|
||||
#: is a scalar or an object the node only ever asks politely.
|
||||
SHAPES: dict[str, Any] = {
|
||||
"chart_request": {"range_s": 3600, "interval_s": 60},
|
||||
"rows": {"rows": [], "range_s": 3600, "interval_s": 60},
|
||||
"limited": {
|
||||
"operation": True,
|
||||
"mode": "fan",
|
||||
"preset_temp": 22.0,
|
||||
"fan_speed": "auto",
|
||||
},
|
||||
}
|
||||
|
||||
#: Something of the right shape to hand a port, so a node can be called at all.
|
||||
SAMPLE: dict[str, Any] = {
|
||||
"float": 1.0,
|
||||
"int": 1,
|
||||
"str": "x",
|
||||
"bool": True,
|
||||
"json": {},
|
||||
"record": {},
|
||||
"list": [],
|
||||
"series": {"lines": []},
|
||||
}
|
||||
|
||||
|
||||
def _check_sources(flows: list[Flow]) -> list[str]:
|
||||
"""Run every Python node once, on values of the shape it declared.
|
||||
|
||||
Not a test of what they decide — that is what the thresholds are for, and
|
||||
they are settings. This catches the class of mistake that is otherwise
|
||||
invisible until the house is running: a name that does not exist, an
|
||||
argument the function does not take, and above all an output key that is
|
||||
not a port, which publishes nothing at all and says nothing about it.
|
||||
"""
|
||||
problems = []
|
||||
for flow in flows:
|
||||
for node in flow.nodes:
|
||||
if node["type"] != "python":
|
||||
continue
|
||||
source = flow.sources.get(node["id"])
|
||||
if source is None:
|
||||
continue
|
||||
namespace: dict[str, Any] = {}
|
||||
where = f"{flow.name}.{node['id']}"
|
||||
try:
|
||||
exec(compile(source, where, "exec"), namespace)
|
||||
except Exception as exc: # noqa: BLE001 - reported, not raised
|
||||
problems.append(f"{where}: will not load: {exc}")
|
||||
continue
|
||||
process = namespace.get("process")
|
||||
if process is None:
|
||||
problems.append(f"{where}: has no process()")
|
||||
continue
|
||||
|
||||
ports = {}
|
||||
for spec in node.get("requires", []):
|
||||
port = spec.get("port") or spec["name"]
|
||||
ports[port] = SHAPES.get(port, SAMPLE.get(spec["dtype"]))
|
||||
try:
|
||||
result = process(**ports, **node.get("params", {}))
|
||||
except Exception as exc: # noqa: BLE001 - reported, not raised
|
||||
problems.append(f"{where}: {type(exc).__name__} when called: {exc}")
|
||||
continue
|
||||
|
||||
if result is None:
|
||||
continue
|
||||
if not isinstance(result, dict):
|
||||
problems.append(
|
||||
f"{where}: returned {type(result).__name__}, not a dict"
|
||||
)
|
||||
continue
|
||||
declared = {
|
||||
spec.get("port") or spec["name"] for spec in node.get("provides", [])
|
||||
}
|
||||
stray = set(result) - declared
|
||||
if stray:
|
||||
problems.append(
|
||||
f"{where}: returns {', '.join(sorted(stray))}, which "
|
||||
"no output port carries — it would publish nothing"
|
||||
)
|
||||
return problems
|
||||
|
||||
|
||||
def _check_cycles(flows: list[Flow], provided: dict[str, list[str]]) -> list[str]:
|
||||
"""A waits for B and B waits for A, so neither of them ever runs.
|
||||
|
||||
The same rule the engine applies: only a *triggering* input creates a
|
||||
dependency, and a node reading a message it also writes is carrying state
|
||||
rather than waiting for itself. Worth doing here because the engine can
|
||||
only see it once every flow exists, and by then the house is half seeded.
|
||||
"""
|
||||
deps: dict[str, set[str]] = {}
|
||||
for flow in flows:
|
||||
for node in flow.nodes:
|
||||
me = f"{flow.name}.{node['id']}"
|
||||
mine = {_qualify(flow.name, s["name"]) for s in node.get("provides", [])}
|
||||
deps[me] = {
|
||||
producer
|
||||
for spec in node.get("requires", [])
|
||||
if spec.get("trigger", True)
|
||||
for producer in provided.get(_qualify(flow.name, spec["name"]), [])
|
||||
if producer != me and _qualify(flow.name, spec["name"]) not in mine
|
||||
}
|
||||
|
||||
# Kahn's algorithm; whatever is left over is in a loop.
|
||||
pending = {node: set(edges) for node, edges in deps.items()}
|
||||
while True:
|
||||
ready = [node for node, edges in pending.items() if not edges]
|
||||
if not ready:
|
||||
break
|
||||
for node in ready:
|
||||
pending.pop(node)
|
||||
for edges in pending.values():
|
||||
edges.difference_update(ready)
|
||||
if pending:
|
||||
return [
|
||||
"these depend on each other in a loop, so none of them can run: "
|
||||
+ ", ".join(sorted(pending))
|
||||
]
|
||||
return []
|
||||
|
||||
|
||||
def _check_types(flows: list[Flow]) -> list[str]:
|
||||
"""One message, one type — whoever writes it and whoever reads it."""
|
||||
types: dict[str, tuple[str, str]] = {}
|
||||
problems = []
|
||||
for flow in flows:
|
||||
for spec in flow.inputs:
|
||||
types.setdefault(
|
||||
_qualify(flow.name, spec["spec"]["name"]),
|
||||
(spec["spec"]["dtype"], f"{flow.name} inputs"),
|
||||
)
|
||||
for node in flow.nodes:
|
||||
for spec in node.get("provides", []) + node.get("requires", []):
|
||||
name = _qualify(flow.name, spec["name"])
|
||||
where = f"{flow.name}.{node['id']}"
|
||||
seen = types.setdefault(name, (spec["dtype"], where))
|
||||
if seen[0] != spec["dtype"]:
|
||||
problems.append(
|
||||
f"'{name}' is {seen[0]} in {seen[1]} but "
|
||||
f"{spec['dtype']} in {where}"
|
||||
)
|
||||
return problems
|
||||
|
||||
|
||||
def _check_widgets(known: set[str]) -> list[str]:
|
||||
"""A tile bound to a message nothing carries draws nothing, quietly."""
|
||||
problems = []
|
||||
for _, title, _, widgets in dashboards.SCREENS:
|
||||
for widget in widgets:
|
||||
config = widget["config"]
|
||||
for key in ("message", "target", "request"):
|
||||
name = config.get(key)
|
||||
if name and name not in known:
|
||||
problems.append(
|
||||
f"{title}: '{widget['id']}' binds {key} to '{name}', "
|
||||
"which no flow carries"
|
||||
)
|
||||
return problems
|
||||
|
||||
|
||||
# ── pushing it ───────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def push(api: Api, flows: list[Flow]) -> None:
|
||||
"""Create every flow, then share the two nodes the rest reference.
|
||||
|
||||
Sharing happens after the flows exist because the library is written from
|
||||
a node that already holds the code — so the first flow to use each carries
|
||||
it in, and the others point at it.
|
||||
"""
|
||||
library = {"arbiter": ARBITER, "motor": MOTOR}
|
||||
owners: dict[str, tuple[str, str]] = {}
|
||||
for flow in flows:
|
||||
for node in flow.nodes:
|
||||
ref = node.get("source_ref")
|
||||
if ref in library and ref not in owners:
|
||||
owners[ref] = (flow.name, node["id"])
|
||||
# This one carries the code in; the rest reference it.
|
||||
node.pop("source_ref")
|
||||
flow.sources[node["id"]] = library[ref]
|
||||
|
||||
for flow in flows:
|
||||
report(flow.name, len(flow.nodes), api.put_flow(flow))
|
||||
|
||||
for ref, (flow_name, node_id) in owners.items():
|
||||
api.share(flow_name, node_id, ref)
|
||||
print(f" library: '{ref}' shared from {flow_name}.{node_id}")
|
||||
|
||||
for name, title, glyph, widgets in dashboards.SCREENS:
|
||||
api.put_dashboard(name, title, glyph, widgets)
|
||||
print(f" dashboard '{name}': {len(widgets)} widgets, published")
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
dry = "--dry" in argv
|
||||
h = house()
|
||||
flows = build(h, commands=bool(h["aircon"].get("commands", False)))
|
||||
|
||||
problems = check(flows)
|
||||
nodes = sum(len(f.nodes) for f in flows)
|
||||
print(f"{len(flows)} flows, {nodes} nodes, {len(dashboards.SCREENS)} dashboards")
|
||||
for problem in problems:
|
||||
print(f" ! {problem}", file=sys.stderr)
|
||||
if problems:
|
||||
print(f"\n{len(problems)} problems; nothing was pushed.", file=sys.stderr)
|
||||
return 1
|
||||
if dry:
|
||||
print("\nEverything checks out. Nothing was pushed (--dry).")
|
||||
return 0
|
||||
|
||||
api = Api()
|
||||
have = set(api("GET", "/secrets/")["data"])
|
||||
missing = [name for name in SECRETS if name not in have]
|
||||
if missing:
|
||||
print("\nAdd these under Secrets first:", file=sys.stderr)
|
||||
for name in missing:
|
||||
print(f" {name} — {SECRETS[name]}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
push(api, flows)
|
||||
print(
|
||||
"\nEvery flow is published and stopped. Start the reading ones first:\n"
|
||||
" clock, power, weather, presence, calendar, history\n"
|
||||
"Nothing moves until 'dmx' is started, and it only transmits once\n"
|
||||
"house.json says so and Node-RED's own Art-Net sender is stopped."
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main(sys.argv[1:]))
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,166 @@
|
||||
"""Talking to the installation, and the constants this house is wired with.
|
||||
|
||||
Addresses, MAC addresses and the DMX map live in ``house.json`` at the
|
||||
workspace root rather than in this package: they are this installation's
|
||||
private data, so they are git-ignored the way the Node-RED inventory is.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
API = os.environ.get("API_URL", "http://api.localhost")
|
||||
EMAIL = os.environ.get("FIRST_SUPERUSER", "")
|
||||
PASSWORD = os.environ.get("FIRST_SUPERUSER_PASSWORD", "")
|
||||
|
||||
HOUSE_FILE = Path(
|
||||
os.environ.get("HOUSE_FILE", Path(__file__).resolve().parents[3] / "house.json")
|
||||
)
|
||||
|
||||
|
||||
def house() -> dict[str, Any]:
|
||||
"""The wiring of this particular house."""
|
||||
if not HOUSE_FILE.exists():
|
||||
raise SystemExit(
|
||||
f"No {HOUSE_FILE}. It holds this installation's addresses and DMX "
|
||||
"map; copy the one from the workspace root or write it from "
|
||||
"docs/private/node-red-transition.md."
|
||||
)
|
||||
data: dict[str, Any] = json.loads(HOUSE_FILE.read_text())
|
||||
return data
|
||||
|
||||
|
||||
class Api:
|
||||
"""The REST API, logged in, raising on anything that is not a 2xx."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
if not EMAIL or not PASSWORD:
|
||||
raise SystemExit("FIRST_SUPERUSER / FIRST_SUPERUSER_PASSWORD are unset.")
|
||||
self.http = httpx.Client(base_url=f"{API}/api/v1", timeout=60)
|
||||
answer = self.http.post(
|
||||
"/login/access-token",
|
||||
data={"username": EMAIL, "password": PASSWORD},
|
||||
)
|
||||
if answer.status_code != 200:
|
||||
raise SystemExit(f"Could not log in to {API}: {answer.text}")
|
||||
self.http.headers["Authorization"] = f"Bearer {answer.json()['access_token']}"
|
||||
|
||||
def __call__(self, method: str, path: str, body: Any = None) -> Any:
|
||||
response = self.http.request(method, path, json=body)
|
||||
response.raise_for_status()
|
||||
return response.json() if response.content else None
|
||||
|
||||
def drop(self, path: str) -> None:
|
||||
"""Delete something that may not be there."""
|
||||
try:
|
||||
self("DELETE", path)
|
||||
except httpx.HTTPStatusError:
|
||||
pass
|
||||
|
||||
# ── flows ────────────────────────────────────────────────────────────
|
||||
|
||||
def put_flow(self, flow: Flow) -> list[str]:
|
||||
"""Create the flow, write its node code, publish it, leave it stopped.
|
||||
|
||||
Stopped is the only safe default here: publishing a flow that drives
|
||||
the house would command every fixture it owns from whatever its inputs
|
||||
happen to hold. Starting one is a decision someone makes while
|
||||
watching.
|
||||
"""
|
||||
self.drop(f"/flows/{flow.name}")
|
||||
self(
|
||||
"PUT",
|
||||
f"/flows/{flow.name}",
|
||||
{
|
||||
"name": flow.name,
|
||||
"title": flow.title,
|
||||
"nodes": flow.nodes,
|
||||
"inputs": flow.inputs,
|
||||
},
|
||||
)
|
||||
for node_id, code in flow.sources.items():
|
||||
self("PUT", f"/flows/{flow.name}/nodes/{node_id}/source", {"code": code})
|
||||
version = self("GET", f"/flows/{flow.name}")["definition"]["version"]
|
||||
self("POST", f"/flows/{flow.name}/publish", {"version": version})
|
||||
self("POST", f"/flows/{flow.name}/stop")
|
||||
issues = self("POST", f"/flows/{flow.name}/validate")["issues"]
|
||||
return [_issue_line(i) for i in issues]
|
||||
|
||||
def share(self, flow: str, node_id: str, lib_name: str) -> None:
|
||||
"""Move a node's code into the library, if it is not there already."""
|
||||
library = {node["name"] for node in self("GET", "/flows/library")}
|
||||
if lib_name in library:
|
||||
return
|
||||
self("POST", f"/flows/{flow}/nodes/{node_id}/share", {"lib_name": lib_name})
|
||||
|
||||
# ── dashboards ───────────────────────────────────────────────────────
|
||||
|
||||
def put_dashboard(self, name: str, title: str, icon: str, widgets: list) -> None:
|
||||
self.drop(f"/dashboards/{name}")
|
||||
self("POST", f"/dashboards/{name}")
|
||||
current = self("GET", f"/dashboards/{name}?draft=true")
|
||||
self(
|
||||
"PUT",
|
||||
f"/dashboards/{name}",
|
||||
{
|
||||
**current,
|
||||
"title": title,
|
||||
"icon": icon,
|
||||
"columns": 16,
|
||||
"canvas_width": 2560,
|
||||
"canvas_height": 1600,
|
||||
"pages": [
|
||||
{
|
||||
"id": "main",
|
||||
"title": title,
|
||||
"sections": [{"id": "main", "widgets": widgets}],
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
version = self("GET", f"/dashboards/{name}?draft=true")["version"]
|
||||
self("POST", f"/dashboards/{name}/publish", {"version": version})
|
||||
|
||||
|
||||
def _issue_line(issue: Any) -> str:
|
||||
if isinstance(issue, dict):
|
||||
return f"{issue.get('code')}: {issue.get('message')}"
|
||||
return str(issue)
|
||||
|
||||
|
||||
class Flow:
|
||||
"""One flow's definition, assembled before it is sent."""
|
||||
|
||||
def __init__(self, name: str, title: str) -> None:
|
||||
self.name = name
|
||||
self.title = title
|
||||
self.nodes: list[dict[str, Any]] = []
|
||||
self.inputs: list[dict[str, Any]] = []
|
||||
self.sources: dict[str, str] = {}
|
||||
|
||||
def add(self, node: dict[str, Any], source: str | None = None) -> dict[str, Any]:
|
||||
self.nodes.append(node)
|
||||
if source is not None:
|
||||
self.sources[node["id"]] = source
|
||||
return node
|
||||
|
||||
def input(self, name: str, dtype: str, initial: Any, **spec: Any) -> None:
|
||||
self.inputs.append(
|
||||
{"spec": {"name": name, "dtype": dtype, **spec}, "initial": initial}
|
||||
)
|
||||
|
||||
def msg(self, name: str) -> str:
|
||||
"""This flow's name for a message, as a dashboard widget spells it."""
|
||||
return f"{self.name}.{name}"
|
||||
|
||||
|
||||
def report(name: str, nodes: int, issues: list[str]) -> None:
|
||||
print(f" {name}: {nodes} nodes, published, stopped")
|
||||
for issue in issues:
|
||||
print(f" ! {issue}", file=sys.stderr)
|
||||
@@ -0,0 +1,985 @@
|
||||
"""What the house wants the temperature to be, and what it runs to get there.
|
||||
|
||||
Four flows and one idea: `climate` works out the bands, and the three things
|
||||
that can change the temperature — the heat pump, the pellet stove, the water
|
||||
boilers competing for the same electricity — read them rather than each
|
||||
deriving their own. The reference computed a winter factor in four places with
|
||||
four different constants; here the calendar part is the clock's and the rest
|
||||
is one node with the constants as settings.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from .api import Flow
|
||||
from .library import arbiter
|
||||
from .sensing import _broker
|
||||
|
||||
# ── climate ──────────────────────────────────────────────────────────────
|
||||
|
||||
BANDS = '''"""The temperature bands, by who is in and what time of year it is.
|
||||
|
||||
Every threshold below is the reference's, and every one of them is a setting,
|
||||
because they are opinions about this house rather than physics. The winter
|
||||
factor lifts the whole band as it gets colder outside: at -5 the house is
|
||||
allowed to be warmer before it counts as too warm, which is what stops the
|
||||
heating fighting the weather in January.
|
||||
|
||||
`indoor` is deliberately not the mean of the two sensors. The bottom sensor is
|
||||
where a person is and the top one is where the heat goes, so the bottom one
|
||||
carries the weight — and when it is silent, which it is while the 433 MHz
|
||||
station is dead, the top one is the whole reading rather than nothing at all.
|
||||
"""
|
||||
|
||||
|
||||
def process(
|
||||
top,
|
||||
bottom=None,
|
||||
outdoor=10.0,
|
||||
preset=21.0,
|
||||
sleeping=False,
|
||||
home=True,
|
||||
winter_k=0.6,
|
||||
winter_from=9.5,
|
||||
night_max=23.0,
|
||||
night_min=19.5,
|
||||
away_max=20.0,
|
||||
away_min=18.0,
|
||||
band=1.5,
|
||||
bottom_weight=0.75,
|
||||
):
|
||||
lift = winter_k * max(0.0, (winter_from - outdoor)) / winter_from
|
||||
indoor = top if bottom is None else (1 - bottom_weight) * top + bottom_weight * bottom
|
||||
|
||||
if not home:
|
||||
low, high = away_min, away_max
|
||||
elif sleeping:
|
||||
low, high = night_min, night_max
|
||||
else:
|
||||
low, high = preset - band, preset
|
||||
|
||||
return {
|
||||
"indoor": round(indoor, 2),
|
||||
"top": top,
|
||||
"lift": round(lift, 2),
|
||||
"setpoint": round(preset + lift, 1),
|
||||
"t_min": round(low + lift, 2),
|
||||
"t_max": round(high + lift, 2),
|
||||
"stratified": bottom is not None and (top - bottom) > 6,
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
def climate() -> Flow:
|
||||
flow = Flow("climate", "Climate")
|
||||
flow.add(
|
||||
{
|
||||
"id": "bands",
|
||||
"type": "python",
|
||||
"title": "Temperature bands",
|
||||
"requires": [
|
||||
# The aircon reports the top of the room and is polled, so it
|
||||
# is the one input that is always there.
|
||||
{"name": "hvac.indoor_temp", "port": "top", "dtype": "float"},
|
||||
{
|
||||
"name": "weather.indoor_temp",
|
||||
"port": "bottom",
|
||||
"dtype": "float",
|
||||
"trigger": False,
|
||||
},
|
||||
{
|
||||
"name": "weather.outdoor_temp",
|
||||
"port": "outdoor",
|
||||
"dtype": "float",
|
||||
"trigger": False,
|
||||
},
|
||||
{"name": "preset", "dtype": "float", "trigger": False},
|
||||
{"name": "presence.sleeping", "port": "sleeping", "dtype": "bool"},
|
||||
{"name": "presence.home", "port": "home", "dtype": "bool"},
|
||||
],
|
||||
"provides": [
|
||||
{"name": "indoor", "dtype": "float"},
|
||||
{"name": "top", "dtype": "float"},
|
||||
{"name": "lift", "dtype": "float"},
|
||||
{"name": "setpoint", "dtype": "float"},
|
||||
{"name": "t_min", "dtype": "float"},
|
||||
{"name": "t_max", "dtype": "float"},
|
||||
{"name": "stratified", "dtype": "bool"},
|
||||
],
|
||||
},
|
||||
BANDS,
|
||||
)
|
||||
flow.input("preset", "float", 21.0)
|
||||
return flow
|
||||
|
||||
|
||||
# ── heat pump ────────────────────────────────────────────────────────────
|
||||
|
||||
HVAC = '''"""What to ask of the heat pump, if anything.
|
||||
|
||||
Ported from the reference's `HVAC Logic`, which is the most conditional thing
|
||||
in that installation and the one worth keeping closest to what it was: every
|
||||
branch is a bill, and the state of charge gates that appear arbitrary are the
|
||||
difference between running the compressor off the sun and running it off the
|
||||
battery at four in the morning.
|
||||
|
||||
What changed: it decides in one place instead of reading nine globals, the
|
||||
enable switch is honoured rather than being overwritten with true on the way
|
||||
past, and it says why. Modes are the unit's own: 1 cool, 2 heat, 3 fan, 4 dry.
|
||||
"""
|
||||
|
||||
OFF = {"operation": False, "mode": "fan", "preset_temp": 22.0, "fan_speed": "auto"}
|
||||
|
||||
|
||||
def process(
|
||||
indoor,
|
||||
top,
|
||||
t_min,
|
||||
t_max,
|
||||
lift=0.0,
|
||||
humidity=None,
|
||||
stratified=False,
|
||||
soc=100.0,
|
||||
out_w=0.0,
|
||||
in_v=230.0,
|
||||
watch=0,
|
||||
enabled=True,
|
||||
home=True,
|
||||
sleeping=False,
|
||||
oven_on=False,
|
||||
hot=29.0,
|
||||
high=26.0,
|
||||
cool_soc=60.0,
|
||||
cool_soc_away=90.0,
|
||||
fan_soc=45.0,
|
||||
dry_soc=35.0,
|
||||
dry_humidity=69.0,
|
||||
dry_humidity_night=73.0,
|
||||
):
|
||||
if not enabled or watch:
|
||||
return {"command": OFF, "why": "off: " + ("disabled" if not enabled else "power")}
|
||||
|
||||
t_hot, t_high = hot + lift, high + lift
|
||||
|
||||
def ask(mode, temp=None, fan="auto", why=""):
|
||||
return {
|
||||
"command": {
|
||||
"operation": True,
|
||||
"mode": mode,
|
||||
"preset_temp": round(temp if temp is not None else t_max, 1),
|
||||
"fan_speed": fan,
|
||||
},
|
||||
"why": why,
|
||||
}
|
||||
|
||||
if not home:
|
||||
# Nobody in: only ever to stop the house cooking, and only on the sun.
|
||||
if top > t_hot and soc > cool_soc_away:
|
||||
return ask("cool", t_hot, why="empty house is too hot")
|
||||
if humidity is not None and humidity > 60 and soc > dry_soc:
|
||||
return ask("dry", t_min + 3, why="empty house is damp")
|
||||
return {"command": OFF, "why": "nobody in"}
|
||||
|
||||
if stratified:
|
||||
# Warm air at the ceiling and cold feet: move it rather than make more.
|
||||
return ask("fan", fan="high" if oven_on else "low", why="stratified")
|
||||
|
||||
limit = t_max if not sleeping else t_max + 1.5
|
||||
if top > limit:
|
||||
if soc > (cool_soc if not sleeping else cool_soc_away):
|
||||
return ask("cool", t_hot, why="too warm")
|
||||
if soc > fan_soc:
|
||||
return ask("fan", why="too warm, saving the battery")
|
||||
return {"command": OFF, "why": "too warm, battery too low to help"}
|
||||
|
||||
damp = dry_humidity_night if sleeping else dry_humidity
|
||||
if humidity is not None and humidity > damp and in_v > 200:
|
||||
return ask("dry", t_min + 3, fan="low", why="damp")
|
||||
|
||||
if indoor < t_min and soc > dry_soc:
|
||||
return ask("heat", t_min + 3, why="too cold")
|
||||
|
||||
return {"command": OFF, "why": "within the band"}
|
||||
'''
|
||||
|
||||
HVAC_LIMIT = '''"""Never let the compressor be the thing that trips the inverter."""
|
||||
|
||||
|
||||
def process(command, out_w=0.0, overload_w=2000.0):
|
||||
if command.get("mode") == "cool" and out_w > overload_w:
|
||||
return {"limited": {**command, "mode": "fan"}}
|
||||
return {"limited": command}
|
||||
'''
|
||||
|
||||
HVAC_PORTS = '''"""One command record into the four ports the connector writes."""
|
||||
|
||||
|
||||
def process(limited):
|
||||
return {
|
||||
"operation": bool(limited["operation"]),
|
||||
"mode": str(limited["mode"]),
|
||||
"preset_temp": float(limited["preset_temp"]),
|
||||
"fan_speed": str(limited["fan_speed"]),
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
def hvac(h: dict[str, Any], commands: bool) -> Flow:
|
||||
flow = Flow("hvac", "Heat pump")
|
||||
# Reading and commanding are two nodes on one adapter, not one node doing
|
||||
# both. A node that did both would sit in its own cascade: the temperature
|
||||
# it reports decides the bands, the bands decide the command, and the
|
||||
# command comes back to it — a cycle the canvas would refuse to run. The
|
||||
# connector already keeps two nodes on one unit from talking over each
|
||||
# other, which is what makes the split safe rather than merely legal.
|
||||
flow.add(
|
||||
{
|
||||
"id": "unit",
|
||||
"type": "wfrac",
|
||||
"title": "Aircon (reading)",
|
||||
"params": {
|
||||
"host": h["aircon"]["host"],
|
||||
"poll_interval": 60.0,
|
||||
"commands": False,
|
||||
},
|
||||
"provides": [
|
||||
{"name": "indoor_temp", "dtype": "float"},
|
||||
{"name": "outdoor_temp", "dtype": "float"},
|
||||
{"name": "reported_temp", "port": "preset_temp", "dtype": "float"},
|
||||
{"name": "running", "port": "operation", "dtype": "bool"},
|
||||
{"name": "reported_mode", "port": "mode", "dtype": "str"},
|
||||
{"name": "electric", "dtype": "float"},
|
||||
],
|
||||
}
|
||||
)
|
||||
flow.add(
|
||||
{
|
||||
"id": "writer",
|
||||
"type": "wfrac",
|
||||
"title": "Aircon (commanding)",
|
||||
"params": {
|
||||
"host": h["aircon"]["host"],
|
||||
# Nothing to poll here; the reader above owns that.
|
||||
"poll_interval": 0.0,
|
||||
# Off until someone is watching: turning a heat pump on has a
|
||||
# bill attached.
|
||||
"commands": commands,
|
||||
},
|
||||
"requires": [
|
||||
{"name": "operation", "dtype": "bool"},
|
||||
{"name": "mode", "dtype": "str"},
|
||||
{"name": "preset_temp", "dtype": "float"},
|
||||
{"name": "fan_speed", "dtype": "str"},
|
||||
],
|
||||
}
|
||||
)
|
||||
flow.add(
|
||||
{
|
||||
"id": "second",
|
||||
"type": "wfrac",
|
||||
"title": "Aircon (bedroom, read only)",
|
||||
"params": {
|
||||
"host": h["aircon"]["second_host"],
|
||||
"poll_interval": 300.0,
|
||||
"commands": False,
|
||||
},
|
||||
"provides": [
|
||||
{"name": "second_indoor", "port": "indoor_temp", "dtype": "float"},
|
||||
{"name": "second_running", "port": "operation", "dtype": "bool"},
|
||||
],
|
||||
}
|
||||
)
|
||||
flow.add(
|
||||
{
|
||||
"id": "decide",
|
||||
"type": "python",
|
||||
"title": "What to ask of it",
|
||||
"requires": [
|
||||
{"name": "climate.indoor", "port": "indoor", "dtype": "float"},
|
||||
{
|
||||
"name": "climate.top",
|
||||
"port": "top",
|
||||
"dtype": "float",
|
||||
"trigger": False,
|
||||
},
|
||||
{
|
||||
"name": "climate.t_min",
|
||||
"port": "t_min",
|
||||
"dtype": "float",
|
||||
"trigger": False,
|
||||
},
|
||||
{
|
||||
"name": "climate.t_max",
|
||||
"port": "t_max",
|
||||
"dtype": "float",
|
||||
"trigger": False,
|
||||
},
|
||||
{
|
||||
"name": "climate.lift",
|
||||
"port": "lift",
|
||||
"dtype": "float",
|
||||
"trigger": False,
|
||||
},
|
||||
{
|
||||
"name": "climate.stratified",
|
||||
"port": "stratified",
|
||||
"dtype": "bool",
|
||||
"trigger": False,
|
||||
},
|
||||
{
|
||||
"name": "weather.indoor_hum",
|
||||
"port": "humidity",
|
||||
"dtype": "float",
|
||||
"trigger": False,
|
||||
},
|
||||
{
|
||||
"name": "power.soc",
|
||||
"port": "soc",
|
||||
"dtype": "float",
|
||||
"trigger": False,
|
||||
},
|
||||
{
|
||||
"name": "power.out_w",
|
||||
"port": "out_w",
|
||||
"dtype": "float",
|
||||
"trigger": False,
|
||||
},
|
||||
{
|
||||
"name": "power.in_v",
|
||||
"port": "in_v",
|
||||
"dtype": "float",
|
||||
"trigger": False,
|
||||
},
|
||||
{"name": "power.watch", "port": "watch", "dtype": "int"},
|
||||
{
|
||||
"name": "presence.home",
|
||||
"port": "home",
|
||||
"dtype": "bool",
|
||||
"trigger": False,
|
||||
},
|
||||
{
|
||||
"name": "presence.sleeping",
|
||||
"port": "sleeping",
|
||||
"dtype": "bool",
|
||||
"trigger": False,
|
||||
},
|
||||
{
|
||||
"name": "oven.running",
|
||||
"port": "oven_on",
|
||||
"dtype": "bool",
|
||||
"trigger": False,
|
||||
},
|
||||
{"name": "enabled", "dtype": "bool", "trigger": False},
|
||||
],
|
||||
"provides": [
|
||||
{"name": "wanted", "port": "command", "dtype": "record"},
|
||||
{"name": "why", "dtype": "str"},
|
||||
],
|
||||
},
|
||||
HVAC,
|
||||
)
|
||||
flow.add(
|
||||
{
|
||||
"id": "limit",
|
||||
"type": "python",
|
||||
"title": "Not while the inverter is loaded",
|
||||
"requires": [
|
||||
{"name": "wanted", "port": "command", "dtype": "record"},
|
||||
{
|
||||
"name": "power.out_w",
|
||||
"port": "out_w",
|
||||
"dtype": "float",
|
||||
"trigger": False,
|
||||
},
|
||||
],
|
||||
"provides": [{"name": "limited", "dtype": "record"}],
|
||||
},
|
||||
HVAC_LIMIT,
|
||||
)
|
||||
flow.add(
|
||||
{
|
||||
"id": "settle",
|
||||
"type": "delay",
|
||||
"title": "At most every fifteen minutes",
|
||||
# A heat pump that is asked something new every minute never
|
||||
# reaches anything. The reference used the same figure.
|
||||
"params": {"interval": 900.0},
|
||||
"requires": [{"name": "limited", "dtype": "record"}],
|
||||
"provides": [{"name": "settled", "dtype": "record"}],
|
||||
}
|
||||
)
|
||||
flow.add(
|
||||
{
|
||||
"id": "changed",
|
||||
"type": "rbe",
|
||||
"title": "Only when it changes",
|
||||
"requires": [{"name": "settled", "port": "settled", "dtype": "record"}],
|
||||
"provides": [{"name": "command", "port": "command", "dtype": "record"}],
|
||||
}
|
||||
)
|
||||
flow.add(
|
||||
{
|
||||
"id": "ports",
|
||||
"type": "python",
|
||||
"title": "Into the unit's ports",
|
||||
"requires": [{"name": "command", "port": "limited", "dtype": "record"}],
|
||||
"provides": [
|
||||
{"name": "operation", "dtype": "bool"},
|
||||
{"name": "mode", "dtype": "str"},
|
||||
{"name": "preset_temp", "dtype": "float"},
|
||||
{"name": "fan_speed", "dtype": "str"},
|
||||
],
|
||||
},
|
||||
HVAC_PORTS,
|
||||
)
|
||||
flow.input("enabled", "bool", True)
|
||||
return flow
|
||||
|
||||
|
||||
# ── pellet stove ─────────────────────────────────────────────────────────
|
||||
|
||||
OVEN = '''"""Whether the pellet stove should be burning.
|
||||
|
||||
The reference decided this by pushing a vote into a twenty-sample array every
|
||||
three seconds and firing when the mean crossed 0.9 — which is a way of
|
||||
building hysteresis out of a heartbeat. With no heartbeat there is no window
|
||||
to average over, so the hysteresis is written down instead: light it below the
|
||||
bottom of the band, stop it above the top, and do nothing in between. That is
|
||||
what the vote was approximating, and it is legible.
|
||||
|
||||
None of this ran in the reference at all — the controller had been
|
||||
disconnected from its heartbeat. It is reinstated here because heating the
|
||||
house is what the stove is for.
|
||||
"""
|
||||
|
||||
|
||||
def process(
|
||||
indoor,
|
||||
t_min,
|
||||
t_max,
|
||||
running=False,
|
||||
heating_season=True,
|
||||
faulty=False,
|
||||
watch=0,
|
||||
margin=0.0,
|
||||
):
|
||||
if not heating_season:
|
||||
return {"wanted": False, "why": "not the season"}
|
||||
if faulty:
|
||||
return {"wanted": False, "why": "the stove reports a fault"}
|
||||
if watch >= 4:
|
||||
return {"wanted": False, "why": "mains is down"}
|
||||
|
||||
if not running and indoor <= t_min - margin:
|
||||
return {"wanted": True, "why": "below the band"}
|
||||
if running and indoor >= t_max + margin:
|
||||
return {"wanted": False, "why": "above the band"}
|
||||
return {"wanted": running, "why": "within the band"}
|
||||
'''
|
||||
|
||||
OVEN_STATE = '''"""What the stove says about itself, and whether to believe it.
|
||||
|
||||
A stove that has claimed to be on for five hours without the room warming up
|
||||
is stuck, and the reference used exactly that to stop the heat pump trying to
|
||||
heat with it. Kept, including the five hours.
|
||||
"""
|
||||
|
||||
import time
|
||||
|
||||
|
||||
def process(onoff=None, power_state=None, memory=None, faulty_after_s=18000.0):
|
||||
state = str(onoff if onoff is not None else power_state or "").upper()
|
||||
if not state:
|
||||
return None
|
||||
running = state in ("ON", "1", "TRUE")
|
||||
|
||||
memory = dict(memory or {})
|
||||
now = time.time()
|
||||
since = memory.get("since", now)
|
||||
if running != memory.get("running"):
|
||||
since = now
|
||||
|
||||
return {
|
||||
"running": running,
|
||||
"faulty": bool(running and now - since > faulty_after_s),
|
||||
"since": since,
|
||||
"oven_memory": {"running": running, "since": since},
|
||||
}
|
||||
'''
|
||||
|
||||
OVEN_CMD = '''"""The stove takes ON to light and 'force' to shut down. Nothing else."""
|
||||
|
||||
|
||||
def process(command):
|
||||
return {"oven_command": "ON" if command else "force"}
|
||||
'''
|
||||
|
||||
PUMP = '''"""The floor-heating pump follows the stove, late and then later.
|
||||
|
||||
The plug labelled microwave in the reference is wired to the pumps that move
|
||||
the water the stove heats. Running them the moment it lights pushes cold water
|
||||
through a cold house, and stopping them the moment it goes out leaves the heat
|
||||
in the stove — so the pump starts a quarter of an hour behind and runs three
|
||||
hours past. Both are settings; they are properties of this plumbing.
|
||||
|
||||
It reads the clock rather than scheduling anything, which is what makes a
|
||||
stove that lights and goes straight back out harmless: there is no pending
|
||||
message to arrive after the reason for it has gone.
|
||||
"""
|
||||
|
||||
import time
|
||||
|
||||
|
||||
def process(running, since=0.0, tick=0, on_after_s=900.0, off_after_s=10800.0):
|
||||
if not since:
|
||||
return {"floor_heating": False}
|
||||
elapsed = time.time() - since
|
||||
if running:
|
||||
return {"floor_heating": elapsed >= on_after_s}
|
||||
return {"floor_heating": elapsed < off_after_s}
|
||||
'''
|
||||
|
||||
|
||||
def oven(h: dict[str, Any]) -> Flow:
|
||||
flow = Flow("oven", "Pellet stove")
|
||||
topics = h["topics"]
|
||||
flow.add(
|
||||
{
|
||||
"id": "stove_in",
|
||||
"type": "mqtt",
|
||||
"title": "What the stove says",
|
||||
"params": {
|
||||
"topic": {
|
||||
"onoff": topics["oven_state"],
|
||||
"power_state": topics["oven_power_state"],
|
||||
"ambient": topics["oven_ambient"],
|
||||
"fume": topics["oven_fume"],
|
||||
},
|
||||
**_broker(h, "fluksio-oven"),
|
||||
},
|
||||
"provides": [
|
||||
{"name": "onoff", "dtype": "str"},
|
||||
{"name": "power_state", "dtype": "str"},
|
||||
{"name": "ambient", "dtype": "float"},
|
||||
{"name": "fume", "dtype": "float"},
|
||||
],
|
||||
}
|
||||
)
|
||||
flow.add(
|
||||
{
|
||||
"id": "state",
|
||||
"type": "python",
|
||||
"title": "Running, and healthy?",
|
||||
"requires": [
|
||||
{"name": "onoff", "dtype": "str"},
|
||||
{"name": "power_state", "dtype": "str", "trigger": False},
|
||||
{
|
||||
"name": "oven_memory",
|
||||
"port": "memory",
|
||||
"dtype": "record",
|
||||
"trigger": False,
|
||||
},
|
||||
],
|
||||
"provides": [
|
||||
{"name": "running", "dtype": "bool"},
|
||||
{"name": "faulty", "dtype": "bool"},
|
||||
{"name": "since", "dtype": "float"},
|
||||
{"name": "oven_memory", "port": "oven_memory", "dtype": "record"},
|
||||
],
|
||||
},
|
||||
OVEN_STATE,
|
||||
)
|
||||
flow.add(
|
||||
{
|
||||
"id": "decide",
|
||||
"type": "python",
|
||||
"title": "Should it be burning?",
|
||||
"requires": [
|
||||
{"name": "climate.indoor", "port": "indoor", "dtype": "float"},
|
||||
{
|
||||
"name": "climate.t_min",
|
||||
"port": "t_min",
|
||||
"dtype": "float",
|
||||
"trigger": False,
|
||||
},
|
||||
{
|
||||
"name": "climate.t_max",
|
||||
"port": "t_max",
|
||||
"dtype": "float",
|
||||
"trigger": False,
|
||||
},
|
||||
{"name": "running", "dtype": "bool", "trigger": False},
|
||||
{
|
||||
"name": "weather.heating_season",
|
||||
"port": "heating_season",
|
||||
"dtype": "bool",
|
||||
"trigger": False,
|
||||
},
|
||||
{"name": "faulty", "dtype": "bool", "trigger": False},
|
||||
{
|
||||
"name": "power.watch",
|
||||
"port": "watch",
|
||||
"dtype": "int",
|
||||
"trigger": False,
|
||||
},
|
||||
],
|
||||
"provides": [
|
||||
{"name": "wanted", "dtype": "bool"},
|
||||
{"name": "why", "dtype": "str"},
|
||||
],
|
||||
},
|
||||
OVEN,
|
||||
)
|
||||
flow.add(
|
||||
arbiter(
|
||||
"arbiter",
|
||||
"Automation or the button",
|
||||
"bool",
|
||||
auto="wanted",
|
||||
manual="oven_manual",
|
||||
command="command",
|
||||
state="oven_arbiter",
|
||||
# Lighting a stove by hand is a decision that should stand for the
|
||||
# evening, not be undone by the next reading.
|
||||
hold_s=10800.0,
|
||||
)
|
||||
)
|
||||
flow.add(
|
||||
{
|
||||
"id": "settle",
|
||||
"type": "delay",
|
||||
"title": "At most every half hour",
|
||||
"params": {"interval": 1800.0},
|
||||
"requires": [{"name": "command", "dtype": "bool"}],
|
||||
"provides": [{"name": "settled", "dtype": "bool"}],
|
||||
}
|
||||
)
|
||||
flow.add(
|
||||
{
|
||||
"id": "changed",
|
||||
"type": "rbe",
|
||||
"title": "Only when it changes",
|
||||
"requires": [{"name": "settled", "port": "settled", "dtype": "bool"}],
|
||||
"provides": [{"name": "to_send", "port": "to_send", "dtype": "bool"}],
|
||||
}
|
||||
)
|
||||
flow.add(
|
||||
{
|
||||
"id": "as_words",
|
||||
"type": "python",
|
||||
"title": "ON or force",
|
||||
"requires": [{"name": "to_send", "port": "command", "dtype": "bool"}],
|
||||
"provides": [{"name": "oven_command", "dtype": "str"}],
|
||||
},
|
||||
OVEN_CMD,
|
||||
)
|
||||
flow.add(
|
||||
{
|
||||
"id": "stove_out",
|
||||
"type": "mqtt",
|
||||
"title": "Tell the stove",
|
||||
"params": {
|
||||
"topic": {"oven_command": topics["oven_command"]},
|
||||
"qos": 1,
|
||||
**_broker(h, "fluksio-oven-out"),
|
||||
},
|
||||
"requires": [{"name": "oven_command", "dtype": "str"}],
|
||||
}
|
||||
)
|
||||
flow.add(
|
||||
{
|
||||
"id": "pump",
|
||||
"type": "python",
|
||||
"title": "Floor heating follows",
|
||||
"requires": [
|
||||
{"name": "running", "port": "running", "dtype": "bool"},
|
||||
{"name": "since", "dtype": "float", "trigger": False},
|
||||
{"name": "clock.minute", "port": "tick", "dtype": "int"},
|
||||
],
|
||||
"provides": [{"name": "floor_heating", "dtype": "bool"}],
|
||||
},
|
||||
PUMP,
|
||||
)
|
||||
flow.input("oven_manual", "bool", False)
|
||||
flow.input("oven_arbiter", "record", {})
|
||||
return flow
|
||||
|
||||
|
||||
# ── water boilers ────────────────────────────────────────────────────────
|
||||
|
||||
HEATED = '''"""Has this boiler had its heating today?
|
||||
|
||||
A boiler with no thermostat readback: the only evidence it got hot is that it
|
||||
drew power for a while without the inverter being busy. The reference counted
|
||||
ten samples of a three-second heartbeat, which is thirty seconds of drawing
|
||||
below 600 W. Kept as thirty seconds of wall clock, which is the same statement
|
||||
without the heartbeat.
|
||||
|
||||
Ratcheting on purpose — once heated, heated, until it is reset at five in the
|
||||
morning. A boiler that cools slightly should not send the house looking for
|
||||
sun again at four in the afternoon.
|
||||
"""
|
||||
|
||||
import time
|
||||
|
||||
|
||||
def process(on, out_w=0.0, hour=12, memory=None, quiet_w=600.0, needs_s=30.0, reset_hour=5):
|
||||
memory = dict(memory or {})
|
||||
now = time.time()
|
||||
|
||||
if hour == reset_hour and memory.get("day") != reset_hour:
|
||||
memory = {"day": reset_hour}
|
||||
elif hour != reset_hour:
|
||||
memory["day"] = hour
|
||||
|
||||
heating_since = memory.get("since", 0.0)
|
||||
if on and out_w < quiet_w:
|
||||
heating_since = heating_since or now
|
||||
else:
|
||||
heating_since = 0.0
|
||||
|
||||
heated = bool(memory.get("heated")) or bool(
|
||||
heating_since and now - heating_since >= needs_s
|
||||
)
|
||||
if memory.get("day") == reset_hour:
|
||||
heated = False
|
||||
|
||||
return {
|
||||
"heated": heated,
|
||||
"heated_memory": {"heated": heated, "since": heating_since, "day": memory.get("day", hour)},
|
||||
}
|
||||
'''
|
||||
|
||||
BOILER = '''"""Whether to put the immersion heater on, and on whose electricity.
|
||||
|
||||
This is the reference's `Water Boiler Logic`, and the thing worth preserving
|
||||
about it is the shape rather than any single number: by day it heats only on
|
||||
surplus solar, and at night it falls back to the grid — but only if the day
|
||||
did not manage it and tomorrow does not look better than today.
|
||||
|
||||
Two boilers share the rules and the constants; the kitchen one is gated on the
|
||||
main one being satisfied first, so they never draw together.
|
||||
|
||||
The battery thresholds are in volts because that is what this bank reports,
|
||||
and the turn-on point moves with the season: 50.4 V in June, 49.8 V in
|
||||
December, because a winter battery that waits for a summer voltage waits all
|
||||
day.
|
||||
"""
|
||||
|
||||
|
||||
def process(
|
||||
batt_v,
|
||||
heated=False,
|
||||
out_w=0.0,
|
||||
in_w=0.0,
|
||||
in_v=230.0,
|
||||
watch=0,
|
||||
hour=12,
|
||||
winter=0.0,
|
||||
tomorrow_day=0.0,
|
||||
tomorrow_clouds=100.0,
|
||||
on=False,
|
||||
day_from=9,
|
||||
day_to=18,
|
||||
night_from=1,
|
||||
night_to=4,
|
||||
min_batt_v=48.4,
|
||||
on_batt_v=50.4,
|
||||
winter_batt_drop=0.6,
|
||||
overload_w=2800.0,
|
||||
busy_w=2600.0,
|
||||
low_grid_v=185.0,
|
||||
better_tomorrow_c=25.0,
|
||||
better_tomorrow_clouds=50.0,
|
||||
):
|
||||
if out_w > overload_w:
|
||||
return {"want": False, "why": "the inverter is overloaded"}
|
||||
if heated:
|
||||
return {"want": False, "why": "already heated today"}
|
||||
|
||||
day = day_from <= hour < day_to
|
||||
night = night_from <= hour < night_to
|
||||
if not day and not night:
|
||||
return {"want": False, "why": "outside both windows"}
|
||||
|
||||
if watch:
|
||||
return {"want": False, "why": "power watch"}
|
||||
if out_w > busy_w:
|
||||
return {"want": False, "why": "the house is drawing too much"}
|
||||
|
||||
if day:
|
||||
if in_w > 0:
|
||||
return {"want": False, "why": "importing rather than exporting"}
|
||||
# Hysteresis: below the floor it stops, above the mark it starts, and
|
||||
# in between it keeps doing whatever it was doing.
|
||||
threshold = on_batt_v - winter_batt_drop * winter
|
||||
if batt_v < min_batt_v:
|
||||
return {"want": False, "why": "battery too low"}
|
||||
if batt_v > threshold:
|
||||
return {"want": True, "why": "surplus solar"}
|
||||
return {"want": on, "why": "holding"}
|
||||
|
||||
if tomorrow_day > better_tomorrow_c and tomorrow_clouds < better_tomorrow_clouds:
|
||||
return {"want": False, "why": "tomorrow looks better than the grid"}
|
||||
if in_v < 10:
|
||||
threshold = on_batt_v - winter_batt_drop * winter
|
||||
if batt_v > threshold:
|
||||
return {"want": True, "why": "no mains, but the battery has it"}
|
||||
return {"want": False, "why": "no mains and the battery is low"}
|
||||
if in_v < low_grid_v:
|
||||
return {"want": False, "why": "mains too weak"}
|
||||
return {"want": True, "why": "the day did not manage it"}
|
||||
'''
|
||||
|
||||
|
||||
def boiler(h: dict[str, Any]) -> Flow:
|
||||
"""Two immersion heaters, one set of rules, one at a time."""
|
||||
flow = Flow("boiler", "Water boilers")
|
||||
|
||||
for which, title, day_from, day_to, night_from, night_to, grid_v in (
|
||||
("water", "Main boiler", 9, 18, 1, 4, 185.0),
|
||||
("kitchen", "Kitchen boiler", 9, 16, 2, 4, 180.0),
|
||||
):
|
||||
state_msg = f"{which}_heated_memory"
|
||||
flow.add(
|
||||
{
|
||||
"id": f"{which}_heated",
|
||||
"type": "python",
|
||||
"title": f"{title}: heated today?",
|
||||
"requires": [
|
||||
{
|
||||
"name": f"{which}_boiler",
|
||||
"port": "on",
|
||||
"dtype": "bool",
|
||||
"trigger": False,
|
||||
},
|
||||
{"name": "power.out_w", "port": "out_w", "dtype": "float"},
|
||||
{
|
||||
"name": "clock.hour",
|
||||
"port": "hour",
|
||||
"dtype": "int",
|
||||
"trigger": False,
|
||||
},
|
||||
{
|
||||
"name": state_msg,
|
||||
"port": "memory",
|
||||
"dtype": "record",
|
||||
"trigger": False,
|
||||
},
|
||||
],
|
||||
"provides": [
|
||||
{"name": f"{which}_heated", "port": "heated", "dtype": "bool"},
|
||||
{"name": state_msg, "port": "heated_memory", "dtype": "record"},
|
||||
],
|
||||
},
|
||||
HEATED,
|
||||
)
|
||||
requires = [
|
||||
{"name": "power.batt_v", "port": "batt_v", "dtype": "float"},
|
||||
{
|
||||
"name": f"{which}_heated",
|
||||
"port": "heated",
|
||||
"dtype": "bool",
|
||||
"trigger": False,
|
||||
},
|
||||
{
|
||||
"name": "power.out_w",
|
||||
"port": "out_w",
|
||||
"dtype": "float",
|
||||
"trigger": False,
|
||||
},
|
||||
{"name": "power.in_w", "port": "in_w", "dtype": "float", "trigger": False},
|
||||
{"name": "power.in_v", "port": "in_v", "dtype": "float", "trigger": False},
|
||||
{"name": "power.watch", "port": "watch", "dtype": "int", "trigger": False},
|
||||
{"name": "clock.hour", "port": "hour", "dtype": "int"},
|
||||
{
|
||||
"name": "clock.winter",
|
||||
"port": "winter",
|
||||
"dtype": "float",
|
||||
"trigger": False,
|
||||
},
|
||||
{
|
||||
"name": "weather.tomorrow_day",
|
||||
"port": "tomorrow_day",
|
||||
"dtype": "float",
|
||||
"trigger": False,
|
||||
},
|
||||
{
|
||||
"name": "weather.tomorrow_clouds",
|
||||
"port": "tomorrow_clouds",
|
||||
"dtype": "float",
|
||||
"trigger": False,
|
||||
},
|
||||
{
|
||||
"name": f"{which}_boiler",
|
||||
"port": "on",
|
||||
"dtype": "bool",
|
||||
"trigger": False,
|
||||
},
|
||||
]
|
||||
if which == "kitchen":
|
||||
# Only once the main one is satisfied: they share an inverter, and
|
||||
# two immersion heaters is more than it has.
|
||||
requires.append(
|
||||
{
|
||||
"name": "water_heated",
|
||||
"port": "main_heated",
|
||||
"dtype": "bool",
|
||||
"trigger": False,
|
||||
}
|
||||
)
|
||||
flow.add(
|
||||
{
|
||||
"id": f"{which}_decide",
|
||||
"type": "python",
|
||||
"title": f"{title}: on?",
|
||||
"params": {
|
||||
"day_from": day_from,
|
||||
"day_to": day_to,
|
||||
"night_from": night_from,
|
||||
"night_to": night_to,
|
||||
"low_grid_v": grid_v,
|
||||
},
|
||||
"requires": requires,
|
||||
"provides": [
|
||||
{"name": f"{which}_want", "port": "want", "dtype": "bool"},
|
||||
{"name": f"{which}_why", "port": "why", "dtype": "str"},
|
||||
],
|
||||
},
|
||||
BOILER if which == "water" else KITCHEN_BOILER,
|
||||
)
|
||||
flow.add(
|
||||
{
|
||||
"id": f"{which}_changed",
|
||||
"type": "rbe",
|
||||
"title": "Only when it changes",
|
||||
"requires": [
|
||||
{"name": f"{which}_want", "port": "want", "dtype": "bool"}
|
||||
],
|
||||
"provides": [
|
||||
{"name": f"{which}_boiler", "port": "on", "dtype": "bool"}
|
||||
],
|
||||
}
|
||||
)
|
||||
flow.input(state_msg, "record", {})
|
||||
flow.input(f"{which}_boiler", "bool", False)
|
||||
return flow
|
||||
|
||||
|
||||
KITCHEN_BOILER = BOILER.replace(
|
||||
"""def process(
|
||||
batt_v,""",
|
||||
"""def process(
|
||||
batt_v,
|
||||
main_heated=False,""",
|
||||
1,
|
||||
).replace(
|
||||
""" if out_w > overload_w:
|
||||
return {"want": False, "why": "the inverter is overloaded"}""",
|
||||
""" if out_w > overload_w:
|
||||
return {"want": False, "why": "the inverter is overloaded"}
|
||||
if not main_heated:
|
||||
return {"want": False, "why": "the main boiler comes first"}""",
|
||||
1,
|
||||
)
|
||||
@@ -0,0 +1,358 @@
|
||||
"""Three screens on one panel: the house, its comfort, and its electricity.
|
||||
|
||||
One dashboard each rather than three pages of one, because a panel carries
|
||||
several whole dashboards and switches between them on a rail — which is the
|
||||
thing that exists, and pages are not.
|
||||
|
||||
Every control binds to the message an arbiter both reads and writes, so a tile
|
||||
shows what actually reached the fixture and setting it is what overrides the
|
||||
automation. There is no second tile saying what the first one really did.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
COLUMNS = 16
|
||||
|
||||
|
||||
def _at(x: int, y: int, w: int, h: int) -> dict[str, Any]:
|
||||
return {"lg": {"x": x, "y": y, "w": w, "h": h}}
|
||||
|
||||
|
||||
def stat(id_, title, message, unit="", precision=1, dtype="float", **at):
|
||||
return {
|
||||
"id": id_,
|
||||
"type": "stat",
|
||||
"title": title,
|
||||
"layout": _at(**at),
|
||||
"config": {
|
||||
"message": message,
|
||||
"dtype": dtype,
|
||||
"unit": unit,
|
||||
"precision": precision,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def switch(id_, title, target, **at):
|
||||
return {
|
||||
"id": id_,
|
||||
"type": "switch",
|
||||
"title": title,
|
||||
"layout": _at(**at),
|
||||
"config": {"target": target, "dtype": "bool", "style": "button"},
|
||||
}
|
||||
|
||||
|
||||
def button(id_, title, target, value, **at):
|
||||
return {
|
||||
"id": id_,
|
||||
"type": "button",
|
||||
"title": title,
|
||||
"layout": _at(**at),
|
||||
"config": {"target": target, "dtype": "str", "value": value, "label": title},
|
||||
}
|
||||
|
||||
|
||||
def slider(id_, title, target, lo, hi, step=1, unit="", **at):
|
||||
return {
|
||||
"id": id_,
|
||||
"type": "slider",
|
||||
"title": title,
|
||||
"layout": _at(**at),
|
||||
"config": {
|
||||
"target": target,
|
||||
"dtype": "float",
|
||||
"min": lo,
|
||||
"max": hi,
|
||||
"step": step,
|
||||
"unit": unit,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def gauge(id_, title, message, lo, hi, unit="", **at):
|
||||
return {
|
||||
"id": id_,
|
||||
"type": "gauge",
|
||||
"title": title,
|
||||
"layout": _at(**at),
|
||||
"config": {
|
||||
"message": message,
|
||||
"dtype": "float",
|
||||
"min": lo,
|
||||
"max": hi,
|
||||
"unit": unit,
|
||||
"precision": 0,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def chart(id_, title, request, series, unit="", **at):
|
||||
return {
|
||||
"id": id_,
|
||||
"type": "chart",
|
||||
"title": title,
|
||||
"layout": _at(**at),
|
||||
"config": {
|
||||
"source": "query",
|
||||
"request": request,
|
||||
"request_dtype": "record",
|
||||
"message": series,
|
||||
"dtype": "series",
|
||||
"range_s": 21600,
|
||||
"refresh_s": 300,
|
||||
"unit": unit,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def icon(id_, title, message, rules, dtype="int", **at):
|
||||
return {
|
||||
"id": id_,
|
||||
"type": "icon",
|
||||
"title": title,
|
||||
"layout": _at(**at),
|
||||
"config": {"message": message, "dtype": dtype, "rules": rules},
|
||||
}
|
||||
|
||||
|
||||
def dropdown(id_, title, target, options, **at):
|
||||
return {
|
||||
"id": id_,
|
||||
"type": "dropdown",
|
||||
"title": title,
|
||||
"layout": _at(**at),
|
||||
"config": {
|
||||
"target": target,
|
||||
"dtype": "str",
|
||||
"style": "segmented",
|
||||
"options": [{"label": label, "value": value} for label, value in options],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _cover(prefix, title, target, y):
|
||||
"""Three buttons, because a shutter with no position sensor has three states."""
|
||||
return [
|
||||
button(f"{prefix}_up", f"{title} up", target, "UP", x=0, y=y, w=2, h=2),
|
||||
button(f"{prefix}_stop", "Stop", target, "STOP", x=2, y=y, w=2, h=2),
|
||||
button(f"{prefix}_down", f"{title} down", target, "DOWN", x=4, y=y, w=2, h=2),
|
||||
]
|
||||
|
||||
|
||||
HOME = [
|
||||
stat("indoor", "Inside", "climate.indoor", "°C", 1, x=0, y=0, w=3, h=2),
|
||||
stat("outdoor", "Outside", "weather.outdoor_temp", "°C", 1, x=3, y=0, w=3, h=2),
|
||||
stat("humidity", "Humidity", "weather.indoor_hum", "%", 0, x=6, y=0, w=3, h=2),
|
||||
icon(
|
||||
"power_state",
|
||||
"Power",
|
||||
"power.watch",
|
||||
[
|
||||
{"at": 0, "icon": "check", "color": "success", "label": "Normal"},
|
||||
{"at": 1, "icon": "triangle-alert", "color": "warning", "label": "Watch"},
|
||||
{"at": 3, "icon": "zap-off", "color": "danger", "label": "Mains"},
|
||||
],
|
||||
x=9,
|
||||
y=0,
|
||||
w=3,
|
||||
h=2,
|
||||
),
|
||||
{
|
||||
"id": "alert",
|
||||
"type": "notification",
|
||||
"title": "What is happening",
|
||||
"layout": _at(x=12, y=0, w=4, h=4),
|
||||
"config": {"message": "power.alert"},
|
||||
},
|
||||
dropdown(
|
||||
"scene",
|
||||
"Scene",
|
||||
"lights.scene",
|
||||
[
|
||||
("Off", "off"),
|
||||
("Day", "day"),
|
||||
("Night", "night"),
|
||||
("Sleep", "sleep"),
|
||||
("Outside", "outside"),
|
||||
],
|
||||
x=0,
|
||||
y=2,
|
||||
w=8,
|
||||
h=2,
|
||||
),
|
||||
slider(
|
||||
"brightness",
|
||||
"Brightness",
|
||||
"lights.brightness",
|
||||
0,
|
||||
100,
|
||||
5,
|
||||
"%",
|
||||
x=8,
|
||||
y=2,
|
||||
w=4,
|
||||
h=2,
|
||||
),
|
||||
stat("lit", "Lit", "lights.lit", dtype="str", precision=0, x=0, y=4, w=4, h=2),
|
||||
switch(
|
||||
"appliances", "Appliances", "appliances.appliances_manual", x=4, y=4, w=3, h=2
|
||||
),
|
||||
switch("bath", "Bathroom plug", "plugs.bath_manual", x=7, y=4, w=3, h=2),
|
||||
stat(
|
||||
"floor",
|
||||
"Floor heating",
|
||||
"oven.floor_heating",
|
||||
dtype="bool",
|
||||
precision=0,
|
||||
x=10,
|
||||
y=4,
|
||||
w=3,
|
||||
h=2,
|
||||
),
|
||||
stat(
|
||||
"presence",
|
||||
"Who is in",
|
||||
"presence.state",
|
||||
dtype="str",
|
||||
precision=0,
|
||||
x=13,
|
||||
y=4,
|
||||
w=3,
|
||||
h=2,
|
||||
),
|
||||
*_cover("door", "Door", "shutters.door_shutter_cmd", y=6),
|
||||
*_cover("bed", "Bed", "shutters.bed_shutter_cmd", y=8),
|
||||
{
|
||||
"id": "load",
|
||||
"type": "bar",
|
||||
"title": "House draw",
|
||||
"layout": _at(x=6, y=6, w=6, h=4),
|
||||
"config": {
|
||||
"message": "power.out_w",
|
||||
"min": 0,
|
||||
"max": 3000,
|
||||
"unit": "W",
|
||||
"precision": 0,
|
||||
"inner": [{"message": "power.pv_w", "dtype": "float"}],
|
||||
},
|
||||
},
|
||||
gauge("soc", "Battery", "power.soc", 0, 100, "%", x=12, y=6, w=4, h=4),
|
||||
]
|
||||
|
||||
COMFORT = [
|
||||
{
|
||||
"id": "forecast",
|
||||
"type": "forecast",
|
||||
"title": "The next few days",
|
||||
"layout": _at(x=0, y=0, w=8, h=3),
|
||||
"config": {"message": "weather.forecast", "count": 4},
|
||||
},
|
||||
{
|
||||
"id": "agenda",
|
||||
"type": "agenda",
|
||||
"title": "Coming up",
|
||||
"layout": _at(x=8, y=0, w=8, h=3),
|
||||
"config": {"message": "calendar.events", "count": 5},
|
||||
},
|
||||
slider("preset", "Wanted", "climate.preset", 16, 26, 0.5, "°C", x=0, y=3, w=5, h=2),
|
||||
stat("setpoint", "Band", "climate.t_max", "°C", 1, x=5, y=3, w=3, h=2),
|
||||
switch("ac", "Heat pump enabled", "hvac.enabled", x=8, y=3, w=4, h=2),
|
||||
stat(
|
||||
"hvac_why",
|
||||
"Heat pump",
|
||||
"hvac.why",
|
||||
dtype="str",
|
||||
precision=0,
|
||||
x=12,
|
||||
y=3,
|
||||
w=4,
|
||||
h=2,
|
||||
),
|
||||
switch("oven", "Pellet stove", "oven.oven_manual", x=0, y=5, w=4, h=2),
|
||||
stat("oven_why", "Stove", "oven.why", dtype="str", precision=0, x=4, y=5, w=4, h=2),
|
||||
stat(
|
||||
"window_why",
|
||||
"Window",
|
||||
"window.why",
|
||||
dtype="str",
|
||||
precision=0,
|
||||
x=8,
|
||||
y=5,
|
||||
w=4,
|
||||
h=2,
|
||||
),
|
||||
stat(
|
||||
"canopy_why",
|
||||
"Awning",
|
||||
"canopy.why",
|
||||
dtype="str",
|
||||
precision=0,
|
||||
x=12,
|
||||
y=5,
|
||||
w=4,
|
||||
h=2,
|
||||
),
|
||||
*_cover("window", "Window", "window.window_manual", y=7),
|
||||
*_cover("canopy", "Awning", "canopy.canopy_manual", y=9),
|
||||
switch("outdoor", "Outdoor plug", "outdoor.outdoor_manual", x=6, y=7, w=4, h=2),
|
||||
stat(
|
||||
"outdoor_why",
|
||||
"Outdoor plug",
|
||||
"outdoor.why",
|
||||
dtype="str",
|
||||
precision=0,
|
||||
x=10,
|
||||
y=7,
|
||||
w=6,
|
||||
h=2,
|
||||
),
|
||||
chart(
|
||||
"climate_chart",
|
||||
"Inside and out",
|
||||
"history.climate_request",
|
||||
"history.climate_series",
|
||||
"°C",
|
||||
x=6,
|
||||
y=9,
|
||||
w=10,
|
||||
h=5,
|
||||
),
|
||||
]
|
||||
|
||||
ENERGY = [
|
||||
gauge("pv", "Solar", "power.pv_w", 0, 3000, "W", x=0, y=0, w=4, h=4),
|
||||
gauge("draw", "House", "power.out_w", 0, 3000, "W", x=4, y=0, w=4, h=4),
|
||||
gauge("grid", "Mains", "power.in_v", 0, 260, "V", x=8, y=0, w=4, h=4),
|
||||
gauge("charge", "Battery", "power.soc", 0, 100, "%", x=12, y=0, w=4, h=4),
|
||||
chart(
|
||||
"power_chart",
|
||||
"Where the power went",
|
||||
"history.power_request",
|
||||
"history.power_series",
|
||||
"W",
|
||||
x=0,
|
||||
y=4,
|
||||
w=16,
|
||||
h=6,
|
||||
),
|
||||
chart(
|
||||
"battery_chart",
|
||||
"State of charge",
|
||||
"history.battery_request",
|
||||
"history.battery_series",
|
||||
"%",
|
||||
x=0,
|
||||
y=10,
|
||||
w=16,
|
||||
h=5,
|
||||
),
|
||||
]
|
||||
|
||||
SCREENS = (
|
||||
("home", "Home", "house", HOME),
|
||||
("comfort", "Comfort", "thermometer", COMFORT),
|
||||
("energy", "Energy", "zap", ENERGY),
|
||||
)
|
||||
@@ -0,0 +1,215 @@
|
||||
"""The two pieces of logic every actuator in the house needs.
|
||||
|
||||
Both are shared library nodes rather than copies: one arbiter fix reaches
|
||||
fifteen actuators, and a rollershutter that learns to stop properly should not
|
||||
have to learn it four times.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
ARBITER = '''"""Which value reaches an actuator: what the house decided, or what a person did.
|
||||
|
||||
Automation runs on a loop and a person does not. Without something between the
|
||||
two, a switch someone presses is undone by the next evaluation — so a manual
|
||||
value wins for a while, and the house takes over again once the hold expires.
|
||||
|
||||
The control on the dashboard binds to ``manual`` in both directions: this node
|
||||
writes back whatever actually reached the actuator, so one tile shows the state
|
||||
and sets it. ``force_at`` is a pulse that outranks a person — the nightly off,
|
||||
and later the fire alarm — because a schedule that a forgotten override can
|
||||
defeat is not a schedule.
|
||||
"""
|
||||
|
||||
import time
|
||||
|
||||
|
||||
def process(auto, manual, state=None, force_at=0.0, hold_s=14400.0, force_value=None):
|
||||
state = dict(state or {})
|
||||
now = time.time()
|
||||
held_until = state.get("override_until", 0.0)
|
||||
|
||||
if not state:
|
||||
# First run: adopt what is already there instead of reading the
|
||||
# difference between two initial values as somebody pressing something.
|
||||
decided = auto
|
||||
held_until = 0.0
|
||||
elif force_at != state.get("force_at", 0.0):
|
||||
decided = auto if force_value is None else force_value
|
||||
held_until = 0.0
|
||||
elif manual != state.get("manual"):
|
||||
# ponytail: a person setting the value it already holds is not seen,
|
||||
# so it does not start a hold. Pressing what the screen already shows
|
||||
# is not how anyone overrides anything; revisit if a control ever
|
||||
# publishes a timestamp of its own.
|
||||
decided = manual
|
||||
held_until = -1.0 if hold_s <= 0 else now + hold_s
|
||||
elif held_until < 0 or now < held_until:
|
||||
decided = state.get("manual")
|
||||
else:
|
||||
decided = auto
|
||||
|
||||
return {
|
||||
"command": decided,
|
||||
"manual": decided,
|
||||
"state": {
|
||||
"manual": decided,
|
||||
"force_at": force_at,
|
||||
"override_until": held_until,
|
||||
},
|
||||
}
|
||||
'''
|
||||
|
||||
MOTOR = '''"""A rollershutter with no position sensor: run for as long as it takes.
|
||||
|
||||
Time is the only feedback there is. The run-time per direction is a setting
|
||||
because it was measured on this hardware and will drift — a motor that stops
|
||||
half a turn early is a knob, not a rewrite.
|
||||
|
||||
What leaves here is the command and how long to hold it: a trigger node
|
||||
downstream sends the STOP when the run is over, once, rather than the
|
||||
reference's forever.
|
||||
"""
|
||||
|
||||
import time
|
||||
|
||||
STOP = "STOP"
|
||||
|
||||
|
||||
def process(cmd, state=None, up_s=26.0, down_s=28.0):
|
||||
now = time.time()
|
||||
state = dict(state or {})
|
||||
# Nothing reports the end of a run, so it is over when it has had its time.
|
||||
moving = state.get("moving", "") if now < state.get("moving_until", 0.0) else ""
|
||||
position = state.get("position", "")
|
||||
|
||||
if cmd == STOP:
|
||||
if not moving:
|
||||
return None
|
||||
run, run_for, target = STOP, 0.0, position
|
||||
elif moving == cmd:
|
||||
return None
|
||||
elif moving:
|
||||
# Reversing mid-travel drives both relays at once on the way past.
|
||||
# Stop; the next command moves it.
|
||||
run, run_for, target = STOP, 0.0, position
|
||||
elif cmd == position:
|
||||
return None
|
||||
else:
|
||||
run = cmd
|
||||
run_for = up_s if cmd == "UP" else down_s
|
||||
target = cmd
|
||||
|
||||
return {
|
||||
"run": run,
|
||||
"run_for": run_for,
|
||||
"state": {
|
||||
"moving": "" if run == STOP else run,
|
||||
"moving_until": 0.0 if run == STOP else now + run_for,
|
||||
"position": target,
|
||||
},
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
def arbiter(
|
||||
node_id: str,
|
||||
title: str,
|
||||
dtype: str,
|
||||
auto: str,
|
||||
manual: str,
|
||||
command: str,
|
||||
state: str,
|
||||
hold_s: float = 14400.0,
|
||||
force_at: str = "",
|
||||
force_value: Any = None,
|
||||
shared: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""One actuator's arbiter, wired to the messages it decides between."""
|
||||
params: dict[str, Any] = {"hold_s": hold_s}
|
||||
if force_at:
|
||||
params["force_value"] = force_value
|
||||
requires = [
|
||||
{"name": auto, "port": "auto", "dtype": dtype},
|
||||
{"name": manual, "port": "manual", "dtype": dtype},
|
||||
{"name": state, "port": "state", "dtype": "record", "trigger": False},
|
||||
]
|
||||
if force_at:
|
||||
requires.append({"name": force_at, "port": "force_at", "dtype": "float"})
|
||||
node = {
|
||||
"id": node_id,
|
||||
"type": "python",
|
||||
"title": title,
|
||||
"params": params,
|
||||
"requires": requires,
|
||||
"provides": [
|
||||
{"name": command, "port": "command", "dtype": dtype},
|
||||
{"name": manual, "port": "manual", "dtype": dtype},
|
||||
{"name": state, "port": "state", "dtype": "record"},
|
||||
],
|
||||
}
|
||||
if shared:
|
||||
node["source_ref"] = "arbiter"
|
||||
return node
|
||||
|
||||
|
||||
def motor(
|
||||
node_id: str,
|
||||
title: str,
|
||||
cmd: str,
|
||||
run: str,
|
||||
run_for: str,
|
||||
state: str,
|
||||
up_s: float,
|
||||
down_s: float,
|
||||
shared: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""One motor's run-time controller."""
|
||||
node = {
|
||||
"id": node_id,
|
||||
"type": "python",
|
||||
"title": title,
|
||||
"params": {"up_s": up_s, "down_s": down_s},
|
||||
"requires": [
|
||||
{"name": cmd, "port": "cmd", "dtype": "str"},
|
||||
{"name": state, "port": "state", "dtype": "record", "trigger": False},
|
||||
],
|
||||
"provides": [
|
||||
{"name": run, "port": "run", "dtype": "str"},
|
||||
{"name": run_for, "port": "run_for", "dtype": "float"},
|
||||
{"name": state, "port": "state", "dtype": "record"},
|
||||
],
|
||||
}
|
||||
if shared:
|
||||
node["source_ref"] = "motor"
|
||||
return node
|
||||
|
||||
|
||||
def stopper(
|
||||
node_id: str, title: str, run: str, run_for: str, cmd: str
|
||||
) -> dict[str, Any]:
|
||||
"""The trigger that sends a motor's STOP when its run is over.
|
||||
|
||||
Passes the command through immediately, then sends STOP once the run-time
|
||||
the motor node worked out has elapsed. A run-time of zero — which is what a
|
||||
STOP itself carries — sends nothing afterwards, so the relays are released
|
||||
once and then left alone.
|
||||
"""
|
||||
return {
|
||||
"id": node_id,
|
||||
"type": "trigger",
|
||||
"title": title,
|
||||
"params": {
|
||||
"then": "STOP",
|
||||
"wait": 60.0,
|
||||
"passthrough": True,
|
||||
"wait_port": "run_for",
|
||||
"extend": True,
|
||||
},
|
||||
"requires": [
|
||||
{"name": run, "port": "run", "dtype": "str"},
|
||||
{"name": run_for, "port": "run_for", "dtype": "float"},
|
||||
],
|
||||
"provides": [{"name": cmd, "port": "cmd", "dtype": "str"}],
|
||||
}
|
||||
@@ -0,0 +1,500 @@
|
||||
"""What the screens read: the charts behind them, and the kiosk still on MQTT.
|
||||
|
||||
`history` answers the chart widgets. The widget publishes the window it wants
|
||||
and draws the series that comes back, so it never learns which database
|
||||
answered — building the query and shaping the rows are ordinary Python nodes
|
||||
on either side of the InfluxDB node, which holds the connection and nothing
|
||||
else.
|
||||
|
||||
`kiosk` is the transition flow, and the one to delete. The e-ink dashboard on
|
||||
the wall speaks a bus that Node-RED used to answer; until a Fluksio panel
|
||||
hangs there instead, this keeps its side of that conversation.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from .api import Flow
|
||||
from .sensing import _broker
|
||||
|
||||
BUILD = '''"""A chart's window into Flux. The database-specific half, and the only one."""
|
||||
|
||||
BUCKET = "{bucket}"
|
||||
|
||||
|
||||
def process(chart_request, series=()):
|
||||
span = int(chart_request["range_s"])
|
||||
every = max(1, int(chart_request["interval_s"]))
|
||||
parts = []
|
||||
for measurement in series:
|
||||
parts.append(
|
||||
"\\n".join(
|
||||
[
|
||||
'from(bucket: "%s")' % BUCKET,
|
||||
" |> range(start: -%ds)" % span,
|
||||
' |> filter(fn: (r) => r["_measurement"] == "%s")' % measurement,
|
||||
' |> filter(fn: (r) => r["_field"] == "value")',
|
||||
" |> aggregateWindow(every: %ds, fn: mean, createEmpty: false)"
|
||||
% every,
|
||||
]
|
||||
)
|
||||
)
|
||||
return {
|
||||
"query": {
|
||||
"flux": "\\n".join(parts),
|
||||
"range_s": chart_request["range_s"],
|
||||
"interval_s": chart_request["interval_s"],
|
||||
}
|
||||
}
|
||||
'''
|
||||
|
||||
PARSE = '''"""Rows into the series a chart draws. Nothing here knows about InfluxDB."""
|
||||
|
||||
|
||||
def process(rows, labels=None):
|
||||
labels = labels or {}
|
||||
lines = {}
|
||||
for row in rows.get("rows", []):
|
||||
if row.get("ts") is None or row.get("value") is None:
|
||||
continue
|
||||
measurement = row.get("measurement", "")
|
||||
lines.setdefault(measurement, []).append([row["ts"], float(row["value"])])
|
||||
|
||||
return {
|
||||
"series": {
|
||||
# The echo the widget matches against what it asked for, so an
|
||||
# answer to an older question is ignored rather than drawn.
|
||||
"range_s": rows["range_s"],
|
||||
"interval_s": rows["interval_s"],
|
||||
"lines": [
|
||||
{"label": labels.get(name, name), "points": points}
|
||||
for name, points in sorted(lines.items())
|
||||
],
|
||||
}
|
||||
}
|
||||
'''
|
||||
|
||||
#: The three charts, and what each one asks the database for.
|
||||
CHARTS = {
|
||||
"power": (
|
||||
["ess/ac/out/power", "ess/dc/pv/power", "ess/ac/in/power"],
|
||||
{
|
||||
"ess/ac/out/power": "House",
|
||||
"ess/dc/pv/power": "Solar",
|
||||
"ess/ac/in/power": "Grid",
|
||||
},
|
||||
),
|
||||
"battery": (["ess/dc/battery/soc"], {"ess/dc/battery/soc": "Charge"}),
|
||||
"climate": (
|
||||
["environment/temperature/1", "environment/temperature/2"],
|
||||
{
|
||||
"environment/temperature/1": "Indoor",
|
||||
"environment/temperature/2": "Outdoor",
|
||||
},
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def history(h: dict[str, Any]) -> Flow:
|
||||
flow = Flow("history", "History")
|
||||
influx = h["influx"]
|
||||
build = BUILD.replace("{bucket}", influx["bucket"])
|
||||
|
||||
for name, (measurements, labels) in CHARTS.items():
|
||||
flow.add(
|
||||
{
|
||||
"id": f"{name}_build",
|
||||
"type": "python",
|
||||
"title": f"{name.title()}: the window into Flux",
|
||||
"params": {"series": measurements},
|
||||
"requires": [
|
||||
{
|
||||
"name": f"{name}_request",
|
||||
"port": "chart_request",
|
||||
"dtype": "record",
|
||||
}
|
||||
],
|
||||
"provides": [
|
||||
{"name": f"{name}_query", "port": "query", "dtype": "record"}
|
||||
],
|
||||
},
|
||||
build,
|
||||
)
|
||||
flow.add(
|
||||
{
|
||||
"id": f"{name}_db",
|
||||
"type": "influxdb",
|
||||
"title": f"{name.title()}: ask",
|
||||
"params": {
|
||||
"url": influx["url"],
|
||||
"token": {"$secret": "influx_token"},
|
||||
"org": influx["org"],
|
||||
"bucket": influx["bucket"],
|
||||
},
|
||||
"requires": [
|
||||
{"name": f"{name}_query", "port": "query", "dtype": "record"}
|
||||
],
|
||||
"provides": [
|
||||
{"name": f"{name}_rows", "port": "rows", "dtype": "record"}
|
||||
],
|
||||
}
|
||||
)
|
||||
flow.add(
|
||||
{
|
||||
"id": f"{name}_parse",
|
||||
"type": "python",
|
||||
"title": f"{name.title()}: rows to a series",
|
||||
"params": {"labels": labels},
|
||||
"requires": [
|
||||
{"name": f"{name}_rows", "port": "rows", "dtype": "record"}
|
||||
],
|
||||
"provides": [
|
||||
{"name": f"{name}_series", "port": "series", "dtype": "series"}
|
||||
],
|
||||
},
|
||||
PARSE,
|
||||
)
|
||||
flow.input(
|
||||
f"{name}_request",
|
||||
"record",
|
||||
{"range_s": 21600, "interval_s": 300},
|
||||
)
|
||||
return flow
|
||||
|
||||
|
||||
# ── the kiosk, until a panel hangs there instead ─────────────────────────
|
||||
|
||||
BRIGHTNESS = '''"""How bright the wall display should be.
|
||||
|
||||
Nobody in: off. Someone asleep: as low as it goes without being off. Otherwise
|
||||
it follows the daylight, which is what makes an e-ink panel readable at noon
|
||||
and not blinding at midnight.
|
||||
"""
|
||||
|
||||
|
||||
def process(state="home", light=0.0, bed_down=False, floor=6.0, gain=2.5):
|
||||
if state == "away":
|
||||
return {"brightness": 0}
|
||||
if bed_down:
|
||||
return {"brightness": 1}
|
||||
return {"brightness": int(round(min(floor + light * gain, 100)))}
|
||||
'''
|
||||
|
||||
ENV = '''"""The blob the e-ink dashboard reads, in the shape Node-RED sent it."""
|
||||
|
||||
import json
|
||||
|
||||
|
||||
def process(
|
||||
indoor_temp=0.0,
|
||||
indoor_hum=0.0,
|
||||
indoor_dewpoint=0.0,
|
||||
outdoor_temp=0.0,
|
||||
outdoor_hum=0.0,
|
||||
outdoor_dewpoint=0.0,
|
||||
forecast=None,
|
||||
):
|
||||
return {
|
||||
"env": json.dumps(
|
||||
{
|
||||
"indoor": {
|
||||
"temp": indoor_temp,
|
||||
"hum": indoor_hum,
|
||||
"dp": indoor_dewpoint,
|
||||
},
|
||||
"outdoor": {
|
||||
"temp": outdoor_temp,
|
||||
"hum": outdoor_hum,
|
||||
"dp": outdoor_dewpoint,
|
||||
"daily": forecast or [],
|
||||
},
|
||||
}
|
||||
)
|
||||
}
|
||||
'''
|
||||
|
||||
ZONES_IN = '''"""The e-ink dashboard's five zone buttons, back into one scene name.
|
||||
|
||||
It speaks zones and this house speaks scenes, so the nearest scene wins. Not a
|
||||
translation worth keeping: it exists so the wall keeps working through the
|
||||
changeover, and it goes when the wall does.
|
||||
"""
|
||||
|
||||
MATCHES = (
|
||||
(("bed", "bath"), "sleep"),
|
||||
(("kitchen", "workspace", "outside"), "night"),
|
||||
(("workspace", "outside"), "outside"),
|
||||
(("workspace",), "day"),
|
||||
)
|
||||
|
||||
|
||||
def process(bed="False", kitchen="False", bath="False", workspace="False", outside="False"):
|
||||
lit = {
|
||||
name
|
||||
for name, value in (
|
||||
("bed", bed),
|
||||
("kitchen", kitchen),
|
||||
("bath", bath),
|
||||
("workspace", workspace),
|
||||
("outside", outside),
|
||||
)
|
||||
if str(value).lower() in ("true", "1", "on")
|
||||
}
|
||||
if not lit:
|
||||
return {"scene": "off"}
|
||||
for zones, scene in MATCHES:
|
||||
if lit == set(zones):
|
||||
return {"scene": scene}
|
||||
return {"scene": "alarm" if len(lit) == 5 else "night"}
|
||||
'''
|
||||
|
||||
BOOLS = '''"""The e-ink dashboard sends the strings "True" and "False"."""
|
||||
|
||||
|
||||
def process(**controls):
|
||||
return {
|
||||
name: str(value).lower() in ("true", "1", "on")
|
||||
for name, value in controls.items()
|
||||
}
|
||||
'''
|
||||
|
||||
SHUTTER_WORDS = '''"""Its bed and door buttons are on/off; the motors speak up and down."""
|
||||
|
||||
|
||||
TRUTHY = ("true", "1", "on")
|
||||
|
||||
|
||||
def process(bed=None, door=None):
|
||||
out = {}
|
||||
if bed is not None:
|
||||
out["bed_cmd"] = "UP" if str(bed).lower() in TRUTHY else "DOWN"
|
||||
if door is not None:
|
||||
out["door_cmd"] = "UP" if str(door).lower() in TRUTHY else "DOWN"
|
||||
return out or None
|
||||
'''
|
||||
|
||||
|
||||
def kiosk(h: dict[str, Any]) -> Flow:
|
||||
"""Keeps the e-ink dashboard working until a Fluksio panel replaces it.
|
||||
|
||||
Delete this flow at the end of the changeover. Everything in it is a
|
||||
translation between two vocabularies, which is exactly the kind of node
|
||||
that should not outlive the reason for it.
|
||||
"""
|
||||
flow = Flow("kiosk", "Kiosk (transitional)")
|
||||
flow.add(
|
||||
{
|
||||
"id": "brightness",
|
||||
"type": "python",
|
||||
"title": "Display brightness",
|
||||
"requires": [
|
||||
{"name": "presence.state", "port": "state", "dtype": "str"},
|
||||
{
|
||||
"name": "weather.light",
|
||||
"port": "light",
|
||||
"dtype": "float",
|
||||
"trigger": False,
|
||||
},
|
||||
{"name": "shutters.bed_down", "port": "bed_down", "dtype": "bool"},
|
||||
],
|
||||
"provides": [{"name": "brightness", "dtype": "int"}],
|
||||
},
|
||||
BRIGHTNESS,
|
||||
)
|
||||
flow.add(
|
||||
{
|
||||
"id": "env",
|
||||
"type": "python",
|
||||
"title": "The weather blob",
|
||||
"requires": [
|
||||
{
|
||||
"name": "weather.indoor_temp",
|
||||
"port": "indoor_temp",
|
||||
"dtype": "float",
|
||||
},
|
||||
{
|
||||
"name": "weather.indoor_hum",
|
||||
"port": "indoor_hum",
|
||||
"dtype": "float",
|
||||
"trigger": False,
|
||||
},
|
||||
{
|
||||
"name": "weather.indoor_dewpoint",
|
||||
"port": "indoor_dewpoint",
|
||||
"dtype": "float",
|
||||
"trigger": False,
|
||||
},
|
||||
{
|
||||
"name": "weather.outdoor_temp",
|
||||
"port": "outdoor_temp",
|
||||
"dtype": "float",
|
||||
},
|
||||
{
|
||||
"name": "weather.outdoor_hum",
|
||||
"port": "outdoor_hum",
|
||||
"dtype": "float",
|
||||
"trigger": False,
|
||||
},
|
||||
{
|
||||
"name": "weather.outdoor_dewpoint",
|
||||
"port": "outdoor_dewpoint",
|
||||
"dtype": "float",
|
||||
"trigger": False,
|
||||
},
|
||||
{
|
||||
"name": "weather.forecast",
|
||||
"port": "forecast",
|
||||
"dtype": "list",
|
||||
"item": "record",
|
||||
"trigger": False,
|
||||
},
|
||||
],
|
||||
"provides": [{"name": "env", "dtype": "str"}],
|
||||
},
|
||||
ENV,
|
||||
)
|
||||
flow.add(
|
||||
{
|
||||
"id": "out",
|
||||
"type": "mqtt",
|
||||
"title": "What the wall reads",
|
||||
"params": {
|
||||
"topic": {
|
||||
"brightness": h["topics"]["kiosk_brightness"],
|
||||
"env": "dashboard/sensors/env",
|
||||
"pv": "dashboard/sensors/pv",
|
||||
"input": "dashboard/sensors/input",
|
||||
"output": "dashboard/sensors/output",
|
||||
"soc": "dashboard/sensors/soc",
|
||||
"notification": "dashboard/notifications",
|
||||
},
|
||||
**_broker(h, "fluksio-kiosk-out"),
|
||||
},
|
||||
"requires": [
|
||||
{"name": "brightness", "dtype": "int", "interval": 60.0},
|
||||
{"name": "env", "dtype": "str", "interval": 20.0},
|
||||
{
|
||||
"name": "power.pv_w",
|
||||
"port": "pv",
|
||||
"dtype": "float",
|
||||
"interval": 10.0,
|
||||
},
|
||||
{
|
||||
"name": "power.in_w",
|
||||
"port": "input",
|
||||
"dtype": "float",
|
||||
"interval": 10.0,
|
||||
},
|
||||
{
|
||||
"name": "power.out_w",
|
||||
"port": "output",
|
||||
"dtype": "float",
|
||||
"interval": 10.0,
|
||||
},
|
||||
{
|
||||
"name": "power.soc",
|
||||
"port": "soc",
|
||||
"dtype": "float",
|
||||
"interval": 10.0,
|
||||
},
|
||||
{
|
||||
"name": "power.alert",
|
||||
"port": "notification",
|
||||
"dtype": "record",
|
||||
"interval": 30.0,
|
||||
},
|
||||
],
|
||||
}
|
||||
)
|
||||
flow.add(
|
||||
{
|
||||
"id": "controls_in",
|
||||
"type": "mqtt",
|
||||
"title": "What the wall presses",
|
||||
"params": {
|
||||
"topic": {
|
||||
"zone_bed": "dashboard/light-mode-bed",
|
||||
"zone_kitchen": "dashboard/light-mode-kitchen",
|
||||
"zone_bath": "dashboard/light-mode-bath",
|
||||
"zone_workspace": "dashboard/light-mode-workspace",
|
||||
"zone_outside": "dashboard/light-mode-outside",
|
||||
"wall_brightness": "dashboard/light-brightness",
|
||||
"wall_appliances": "dashboard/appliances",
|
||||
"wall_bed": "dashboard/bed",
|
||||
"wall_door": "dashboard/doorshutter",
|
||||
},
|
||||
**_broker(h, "fluksio-kiosk-in"),
|
||||
},
|
||||
"provides": [
|
||||
{"name": "zone_bed", "dtype": "str"},
|
||||
{"name": "zone_kitchen", "dtype": "str"},
|
||||
{"name": "zone_bath", "dtype": "str"},
|
||||
{"name": "zone_workspace", "dtype": "str"},
|
||||
{"name": "zone_outside", "dtype": "str"},
|
||||
{
|
||||
"name": "lights.brightness",
|
||||
"port": "wall_brightness",
|
||||
"dtype": "float",
|
||||
},
|
||||
{"name": "wall_appliances", "dtype": "str"},
|
||||
{"name": "wall_bed", "dtype": "str"},
|
||||
{"name": "wall_door", "dtype": "str"},
|
||||
],
|
||||
}
|
||||
)
|
||||
flow.add(
|
||||
{
|
||||
"id": "zones",
|
||||
"type": "python",
|
||||
"title": "Zones to a scene",
|
||||
"requires": [
|
||||
{"name": "zone_bed", "port": "bed", "dtype": "str"},
|
||||
{"name": "zone_kitchen", "port": "kitchen", "dtype": "str"},
|
||||
{"name": "zone_bath", "port": "bath", "dtype": "str"},
|
||||
{"name": "zone_workspace", "port": "workspace", "dtype": "str"},
|
||||
{"name": "zone_outside", "port": "outside", "dtype": "str"},
|
||||
],
|
||||
"provides": [{"name": "lights.scene", "port": "scene", "dtype": "str"}],
|
||||
},
|
||||
ZONES_IN,
|
||||
)
|
||||
flow.add(
|
||||
{
|
||||
"id": "switches",
|
||||
"type": "python",
|
||||
"title": "Its switches",
|
||||
"requires": [
|
||||
{"name": "wall_appliances", "port": "appliances_manual", "dtype": "str"}
|
||||
],
|
||||
"provides": [
|
||||
{
|
||||
"name": "appliances.appliances_manual",
|
||||
"port": "appliances_manual",
|
||||
"dtype": "bool",
|
||||
}
|
||||
],
|
||||
},
|
||||
BOOLS,
|
||||
)
|
||||
flow.add(
|
||||
{
|
||||
"id": "shutter_words",
|
||||
"type": "python",
|
||||
"title": "Its shutter buttons",
|
||||
"requires": [
|
||||
{"name": "wall_bed", "port": "bed", "dtype": "str"},
|
||||
{"name": "wall_door", "port": "door", "dtype": "str"},
|
||||
],
|
||||
"provides": [
|
||||
{"name": "shutters.bed_shutter_cmd", "port": "bed_cmd", "dtype": "str"},
|
||||
{
|
||||
"name": "shutters.door_shutter_cmd",
|
||||
"port": "door_cmd",
|
||||
"dtype": "str",
|
||||
},
|
||||
],
|
||||
},
|
||||
SHUTTER_WORDS,
|
||||
)
|
||||
return flow
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,144 @@
|
||||
"""The two shared nodes, checked the way they will fail.
|
||||
|
||||
Run it directly — it needs no framework and no installation:
|
||||
|
||||
python scripts/tinyhouse/test_library.py
|
||||
|
||||
These two are worth a check because everything else in the house is a table of
|
||||
thresholds, while these carry state between runs and decide who wins.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
from tinyhouse.library import ARBITER, MOTOR # noqa: E402
|
||||
|
||||
|
||||
def _load(source: str):
|
||||
namespace: dict = {}
|
||||
exec(compile(source, "<node>", "exec"), namespace)
|
||||
return namespace["process"]
|
||||
|
||||
|
||||
arbiter = _load(ARBITER)
|
||||
motor = _load(MOTOR)
|
||||
|
||||
|
||||
# ── the arbiter ──────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_the_house_decides_when_nobody_has_said_otherwise():
|
||||
first = arbiter(auto=True, manual=False)
|
||||
assert first["command"] is True, "the first run adopts what is there"
|
||||
|
||||
later = arbiter(auto=False, manual=first["manual"], state=first["state"])
|
||||
assert later["command"] is False, "and follows the house afterwards"
|
||||
|
||||
|
||||
def test_a_person_wins_and_keeps_winning_for_the_hold():
|
||||
state = arbiter(auto=False, manual=False)["state"]
|
||||
|
||||
pressed = arbiter(auto=False, manual=True, state=state, hold_s=3600)
|
||||
assert pressed["command"] is True
|
||||
|
||||
# The house asks for off, once a second, for an hour. It does not get it.
|
||||
state = pressed["state"]
|
||||
for _ in range(5):
|
||||
again = arbiter(auto=False, manual=state["manual"], state=state, hold_s=3600)
|
||||
assert again["command"] is True, "automation must not undo a person"
|
||||
state = again["state"]
|
||||
|
||||
|
||||
def test_the_house_takes_over_once_the_hold_has_run_out():
|
||||
state = arbiter(auto=False, manual=False)["state"]
|
||||
pressed = arbiter(auto=False, manual=True, state=state, hold_s=3600)
|
||||
|
||||
expired = dict(pressed["state"], override_until=time.time() - 1)
|
||||
after = arbiter(auto=False, manual=expired["manual"], state=expired)
|
||||
assert after["command"] is False
|
||||
|
||||
|
||||
def test_a_hold_of_zero_lasts_until_something_forces_it():
|
||||
state = arbiter(auto=False, manual=False, hold_s=0)["state"]
|
||||
pressed = arbiter(auto=False, manual=True, state=state, hold_s=0)
|
||||
assert pressed["state"]["override_until"] == -1.0
|
||||
|
||||
held = arbiter(
|
||||
auto=False, manual=pressed["manual"], state=pressed["state"], hold_s=0
|
||||
)
|
||||
assert held["command"] is True, "no expiry means no expiry"
|
||||
|
||||
# Two in the morning arrives as a new timestamp.
|
||||
forced = arbiter(
|
||||
auto=False,
|
||||
manual=held["manual"],
|
||||
state=held["state"],
|
||||
force_at=1_700_000_000.0,
|
||||
force_value=False,
|
||||
hold_s=0,
|
||||
)
|
||||
assert forced["command"] is False, "a schedule outranks a forgotten override"
|
||||
assert forced["state"]["override_until"] == 0.0
|
||||
|
||||
|
||||
def test_the_control_shows_what_actually_reached_the_fixture():
|
||||
"""One tile reads and writes, so what it publishes is what it displays."""
|
||||
state = arbiter(auto=False, manual=False)["state"]
|
||||
on = arbiter(auto=True, manual=False, state=state)
|
||||
assert on["manual"] == on["command"] is True
|
||||
|
||||
|
||||
# ── the motor ────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_a_shutter_runs_for_as_long_as_that_direction_takes():
|
||||
down = motor(cmd="DOWN", up_s=26, down_s=28)
|
||||
assert (down["run"], down["run_for"]) == ("DOWN", 28)
|
||||
assert down["state"]["position"] == "DOWN"
|
||||
|
||||
settled = dict(down["state"], moving_until=0.0)
|
||||
up = motor(cmd="UP", state=settled, up_s=26, down_s=28)
|
||||
assert (up["run"], up["run_for"]) == ("UP", 26)
|
||||
|
||||
|
||||
def test_asking_again_for_where_it_already_is_does_nothing():
|
||||
down = motor(cmd="DOWN", up_s=26, down_s=28)
|
||||
settled = dict(down["state"], moving_until=0.0)
|
||||
assert motor(cmd="DOWN", state=settled) is None
|
||||
|
||||
|
||||
def test_a_reversal_mid_travel_stops_rather_than_driving_both_ways():
|
||||
down = motor(cmd="DOWN", up_s=26, down_s=28)
|
||||
assert down["state"]["moving_until"] > time.time()
|
||||
|
||||
turn = motor(cmd="UP", state=down["state"], up_s=26, down_s=28)
|
||||
assert turn["run"] == "STOP" and turn["run_for"] == 0.0
|
||||
assert turn["state"]["moving"] == ""
|
||||
|
||||
|
||||
def test_stop_is_commanded_once_and_then_left_alone():
|
||||
"""The reference sent STOP forever. This is the whole reason it does not."""
|
||||
down = motor(cmd="DOWN", up_s=26, down_s=28)
|
||||
stopped = motor(cmd="STOP", state=down["state"])
|
||||
assert (stopped["run"], stopped["run_for"]) == ("STOP", 0.0)
|
||||
assert motor(cmd="STOP", state=stopped["state"]) is None, "nothing more to say"
|
||||
|
||||
|
||||
def test_a_run_is_over_when_it_has_had_its_time():
|
||||
"""Nothing reports the end of a run, so the clock is the only witness."""
|
||||
down = motor(cmd="DOWN", up_s=26, down_s=28)
|
||||
expired = dict(down["state"], moving_until=time.time() - 1)
|
||||
assert motor(cmd="DOWN", state=expired) is None, "it is already there"
|
||||
assert motor(cmd="UP", state=expired)["run"] == "UP", "and free to go back"
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
checks = [v for k, v in sorted(globals().items()) if k.startswith("test_")]
|
||||
for check in checks:
|
||||
check()
|
||||
print(f"{len(checks)} checks passed")
|
||||
Reference in New Issue
Block a user