@avantics/node-red-home-automation 6.0.0 → 6.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +276 -48
- package/dist/lib/cover-publishing.js +20 -6
- package/dist/lib/home-assistant-setting.d.ts +23 -0
- package/dist/lib/home-assistant-setting.js +39 -0
- package/dist/lib/motion-policy.d.ts +1 -0
- package/dist/lib/motion-policy.js +21 -1
- package/dist/lib/room-controller.d.ts +4 -0
- package/dist/lib/room-controller.js +122 -14
- package/dist/lib/room-holds.d.ts +34 -0
- package/dist/lib/room-holds.js +66 -0
- package/dist/lib/room-publishing.d.ts +1 -0
- package/dist/lib/room-publishing.js +11 -0
- package/dist/lib/scene-publishing.d.ts +30 -0
- package/dist/lib/scene-publishing.js +63 -0
- package/dist/lib/scene.d.ts +61 -0
- package/dist/lib/scene.js +170 -0
- package/dist/lib/shelly-cover.js +5 -0
- package/dist/lib/shelly-relay-light.d.ts +24 -0
- package/dist/lib/shelly-relay-light.js +93 -0
- package/dist/lib/shelly-switch.d.ts +8 -0
- package/dist/lib/shelly-switch.js +37 -8
- package/dist/lib/theatre-activity-controller.js +4 -0
- package/dist/lib/theatre-metrics.js +6 -4
- package/dist/lib/theatre-slo.js +3 -0
- package/dist/lib/theatre-state-contract.d.ts +4 -2
- package/dist/lib/theatre-state-contract.js +51 -8
- package/dist/lib/theatre-state.js +3 -0
- package/dist/nodes/activity-lighting-controller.html +1 -1
- package/dist/nodes/adapter.d.ts +5 -1
- package/dist/nodes/adapter.js +35 -2
- package/dist/nodes/avr-controller.html +86 -20
- package/dist/nodes/avr-controller.js +23 -11
- package/dist/nodes/circadian-policy.html +88 -19
- package/dist/nodes/circadian-policy.js +30 -11
- package/dist/nodes/cover-controller.html +91 -24
- package/dist/nodes/cover-controller.js +25 -12
- package/dist/nodes/device-side.d.ts +20 -0
- package/dist/nodes/device-side.js +72 -0
- package/dist/nodes/home-assistant-discovery.d.ts +26 -0
- package/dist/nodes/home-assistant-discovery.js +64 -0
- package/dist/nodes/house-schedule-mqtt.html +74 -4
- package/dist/nodes/house-schedule-mqtt.js +22 -8
- package/dist/nodes/motion-policy.html +91 -21
- package/dist/nodes/motion-policy.js +44 -11
- package/dist/nodes/mqtt-broker-link.d.ts +41 -0
- package/dist/nodes/mqtt-broker-link.js +91 -0
- package/dist/nodes/occupancy-fusion.html +87 -19
- package/dist/nodes/occupancy-fusion.js +23 -11
- package/dist/nodes/publishing-side.d.ts +20 -0
- package/dist/nodes/publishing-side.js +66 -0
- package/dist/nodes/room-controller.html +128 -43
- package/dist/nodes/room-controller.js +63 -16
- package/dist/nodes/scene.d.ts +3 -0
- package/dist/nodes/scene.html +226 -0
- package/dist/nodes/scene.js +121 -0
- package/dist/nodes/shelly-cover.html +46 -2
- package/dist/nodes/shelly-cover.js +19 -4
- package/dist/nodes/shelly-switch.html +80 -6
- package/dist/nodes/shelly-switch.js +32 -7
- package/dist/nodes/theatre-state-contract.html +76 -8
- package/dist/nodes/theatre-state-contract.js +33 -14
- package/dist/nodes/z2m-cover.html +46 -2
- package/dist/nodes/z2m-cover.js +21 -4
- package/dist/nodes/z2m-light.html +50 -2
- package/dist/nodes/z2m-light.js +26 -6
- package/examples/Cover control.json +38 -102
- package/examples/Cover pair.json +36 -3
- package/examples/Home theatre activity.json +46 -102
- package/examples/Home theatre equipment.json +34 -2
- package/examples/House schedule.json +58 -80
- package/examples/Room lighting.json +45 -55
- package/examples/Scene.json +215 -0
- package/examples/Shelly cover.json +36 -116
- package/examples/Shelly switch.json +52 -148
- package/package.json +2 -1
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.RENEW_MS = exports.DEFAULT_SAFETY_HOURS = void 0;
|
|
4
|
+
exports.normaliseSceneConfig = normaliseSceneConfig;
|
|
5
|
+
exports.createSceneState = createSceneState;
|
|
6
|
+
exports.transitionScene = transitionScene;
|
|
7
|
+
exports.sceneTickAt = sceneTickAt;
|
|
8
|
+
const settings_1 = require("./settings");
|
|
9
|
+
const topic_names_1 = require("./topic-names");
|
|
10
|
+
exports.DEFAULT_SAFETY_HOURS = 4;
|
|
11
|
+
// How often an active scene renews its motion pause and its status: well
|
|
12
|
+
// within the motion policy's maximum pause (10 minutes by default).
|
|
13
|
+
exports.RENEW_MS = 60_000;
|
|
14
|
+
function normaliseSceneConfig(raw) {
|
|
15
|
+
const parsed = (0, settings_1.jsonSetting)(raw.lights, "lights", []);
|
|
16
|
+
if (!Array.isArray(parsed))
|
|
17
|
+
throw new Error("lights must be a JSON array");
|
|
18
|
+
const seen = new Set();
|
|
19
|
+
const lights = parsed.map((entry, index) => {
|
|
20
|
+
const at = `light ${index + 1}`;
|
|
21
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry))
|
|
22
|
+
throw new Error(`${at} must be an object`);
|
|
23
|
+
const light = entry;
|
|
24
|
+
const target = typeof light.target === "string" ? light.target.trim() : "";
|
|
25
|
+
if (!target)
|
|
26
|
+
throw new Error(`${at} needs a target: the light's id in its room controller`);
|
|
27
|
+
const area = typeof light.area === "string" ? light.area.trim() : "";
|
|
28
|
+
if (!(0, topic_names_1.areaId)(area))
|
|
29
|
+
throw new Error(`${at} (${target}) needs an area: its room controller's Area`);
|
|
30
|
+
const key = (0, topic_names_1.areaId)(area) + "/" + target;
|
|
31
|
+
if (seen.has(key))
|
|
32
|
+
throw new Error(`${at}: ${target} in ${area} is listed twice`);
|
|
33
|
+
seen.add(key);
|
|
34
|
+
const state = String(light.state ?? "").toUpperCase();
|
|
35
|
+
if (state !== "ON" && state !== "OFF")
|
|
36
|
+
throw new Error(`${at} (${target}): state must be ON or OFF`);
|
|
37
|
+
const scene = { area, target, state };
|
|
38
|
+
for (const key of ["brightnessPct", "colorTempKelvin"]) {
|
|
39
|
+
if (light[key] === undefined)
|
|
40
|
+
continue;
|
|
41
|
+
const value = light[key];
|
|
42
|
+
if (typeof value !== "number" || !Number.isFinite(value))
|
|
43
|
+
throw new Error(`${at} (${target}): ${key} must be a number`);
|
|
44
|
+
if (key === "brightnessPct" && (value < 0 || value > 100))
|
|
45
|
+
throw new Error(`${at} (${target}): brightnessPct must be 0-100`);
|
|
46
|
+
if (key === "colorTempKelvin" && value <= 0)
|
|
47
|
+
throw new Error(`${at} (${target}): colorTempKelvin must be above 0`);
|
|
48
|
+
if (state === "OFF")
|
|
49
|
+
throw new Error(`${at} (${target}): an OFF light takes no ${key}`);
|
|
50
|
+
scene[key] = value;
|
|
51
|
+
}
|
|
52
|
+
for (const key of Object.keys(light)) {
|
|
53
|
+
if (!["area", "target", "state", "brightnessPct", "colorTempKelvin"].includes(key))
|
|
54
|
+
throw new Error(`${at} (${target}): unknown field ${key}`);
|
|
55
|
+
}
|
|
56
|
+
return scene;
|
|
57
|
+
});
|
|
58
|
+
const hours = (0, settings_1.numberSetting)(raw.safetyHours, "safety timer", exports.DEFAULT_SAFETY_HOURS);
|
|
59
|
+
if (hours < 0)
|
|
60
|
+
throw new Error("safety timer must be 0 (off) or more hours");
|
|
61
|
+
return { owner: raw.owner, lights, safetyMs: Math.round(hours * 3_600_000) };
|
|
62
|
+
}
|
|
63
|
+
function createSceneState(saved = {}) {
|
|
64
|
+
const active = saved.active === true && typeof saved.owner === "string";
|
|
65
|
+
return {
|
|
66
|
+
active,
|
|
67
|
+
owner: active ? saved.owner : null,
|
|
68
|
+
lights: active && Array.isArray(saved.lights)
|
|
69
|
+
? saved.lights.filter((light) => typeof light?.area === "string" && typeof light.target === "string").map(({ area, target }) => ({ area, target }))
|
|
70
|
+
: [],
|
|
71
|
+
startedAt: active && Number.isFinite(saved.startedAt) ? saved.startedAt : null,
|
|
72
|
+
endsAt: active && Number.isFinite(saved.endsAt) ? saved.endsAt : null,
|
|
73
|
+
ended: saved.ended && typeof saved.ended.by === "string" && Number.isFinite(saved.ended.at) ? { ...saved.ended } : null
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
// How a span of time reads on the status: "3h 59m", "12m", "under 1m".
|
|
77
|
+
function span(ms) {
|
|
78
|
+
const minutes = Math.floor(ms / 60_000);
|
|
79
|
+
if (minutes < 1)
|
|
80
|
+
return "under 1m";
|
|
81
|
+
const hours = Math.floor(minutes / 60);
|
|
82
|
+
return hours ? `${hours}h ${minutes % 60}m` : `${minutes}m`;
|
|
83
|
+
}
|
|
84
|
+
function transitionScene(saved, msg, config, nowValue = new Date()) {
|
|
85
|
+
const now = (nowValue instanceof Date ? nowValue : new Date(nowValue)).getTime();
|
|
86
|
+
const state = createSceneState(saved);
|
|
87
|
+
const lighting = [];
|
|
88
|
+
const motion = [];
|
|
89
|
+
const traces = [];
|
|
90
|
+
const trace = (event, outcome, reason = null, details = {}) => traces.push({ event, outcome, reason, details });
|
|
91
|
+
const event = msg.scene && typeof msg.scene === "object" ? msg.scene : {};
|
|
92
|
+
const kind = String(event.kind ?? "");
|
|
93
|
+
const pause = (on) => motion.push({ source: "pause", payload: on, owner: state.owner });
|
|
94
|
+
function end(by) {
|
|
95
|
+
const owner = state.owner;
|
|
96
|
+
// One release per room, for the lights it took there.
|
|
97
|
+
const rooms = new Map();
|
|
98
|
+
for (const { area, target } of state.lights)
|
|
99
|
+
rooms.set(area, [...(rooms.get(area) ?? []), target]);
|
|
100
|
+
for (const [area, targets] of rooms)
|
|
101
|
+
lighting.push({ lighting: { kind: "release", area, owner, targets, source: "scene" } });
|
|
102
|
+
pause(false);
|
|
103
|
+
trace("scene", "ended", null, { by, owner });
|
|
104
|
+
Object.assign(state, { active: false, owner: null, lights: [], startedAt: null, endsAt: null, ended: { by, at: now } });
|
|
105
|
+
}
|
|
106
|
+
if (kind === "start") {
|
|
107
|
+
if (state.active) {
|
|
108
|
+
// On again: a fresh safety timer; its lights are left as they are, so
|
|
109
|
+
// a person's change during the scene stands.
|
|
110
|
+
state.endsAt = config.safetyMs > 0 ? now + config.safetyMs : null;
|
|
111
|
+
pause(true);
|
|
112
|
+
trace("scene", "renewed", null, { owner: state.owner });
|
|
113
|
+
}
|
|
114
|
+
else {
|
|
115
|
+
Object.assign(state, {
|
|
116
|
+
active: true,
|
|
117
|
+
owner: config.owner,
|
|
118
|
+
lights: config.lights.map(({ area, target }) => ({ area, target })),
|
|
119
|
+
startedAt: now,
|
|
120
|
+
endsAt: config.safetyMs > 0 ? now + config.safetyMs : null
|
|
121
|
+
});
|
|
122
|
+
for (const light of config.lights) {
|
|
123
|
+
const values = {
|
|
124
|
+
...(light.brightnessPct !== undefined ? { brightnessPct: light.brightnessPct } : {}),
|
|
125
|
+
...(light.colorTempKelvin !== undefined ? { colorTempKelvin: light.colorTempKelvin } : {})
|
|
126
|
+
};
|
|
127
|
+
lighting.push({ lighting: { kind: "intent", area: light.area, targets: [light.target], state: light.state, owner: config.owner, source: "scene",
|
|
128
|
+
...(Object.keys(values).length ? { values } : {}) } });
|
|
129
|
+
}
|
|
130
|
+
pause(true);
|
|
131
|
+
trace("scene", "started", null, { owner: config.owner, lights: state.lights });
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
else if (kind === "end") {
|
|
135
|
+
if (state.active)
|
|
136
|
+
end(typeof event.by === "string" && event.by.trim() ? event.by.trim() : "request");
|
|
137
|
+
else
|
|
138
|
+
trace("scene", "ignored", "not-active");
|
|
139
|
+
}
|
|
140
|
+
else if (kind === "tick" || kind === "startup") {
|
|
141
|
+
// Its timer, or the flows starting again (a redeploy or restart with a
|
|
142
|
+
// context store): end it if its time is up, otherwise renew its pause.
|
|
143
|
+
// Its lights are not asked again: the rooms still hold them.
|
|
144
|
+
if (state.active && state.endsAt !== null && state.endsAt <= now)
|
|
145
|
+
end("timer");
|
|
146
|
+
else if (state.active)
|
|
147
|
+
pause(true);
|
|
148
|
+
}
|
|
149
|
+
else {
|
|
150
|
+
trace("input", "ignored", "not-a-scene-message");
|
|
151
|
+
}
|
|
152
|
+
return {
|
|
153
|
+
state,
|
|
154
|
+
lighting,
|
|
155
|
+
motion,
|
|
156
|
+
traces,
|
|
157
|
+
status: state.active
|
|
158
|
+
? { fill: "green", shape: "dot", text: "on" + (state.endsAt !== null ? ` · ${span(state.endsAt - now)} left` : "") }
|
|
159
|
+
: { fill: "grey", shape: state.ended ? "dot" : "ring", text: state.ended ? `off · ended by ${state.ended.by}` : "off" }
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
// When it next needs a tick: its next renewal, or its safety timer's end if
|
|
163
|
+
// sooner. Null when off.
|
|
164
|
+
function sceneTickAt(state, now) {
|
|
165
|
+
if (!state.active)
|
|
166
|
+
return null;
|
|
167
|
+
const renew = now + exports.RENEW_MS;
|
|
168
|
+
return state.endsAt !== null ? Math.min(renew, state.endsAt) : renew;
|
|
169
|
+
}
|
|
170
|
+
//# sourceMappingURL=scene.js.map
|
package/dist/lib/shelly-cover.js
CHANGED
|
@@ -100,6 +100,11 @@ function transitionShellyCover(saved, msg, config, now) {
|
|
|
100
100
|
trace("command", "sent", null, { operation, position });
|
|
101
101
|
}
|
|
102
102
|
}
|
|
103
|
+
else if (operation === "observe" && !Number.isInteger(generation)) {
|
|
104
|
+
// Its own read on connecting, not the controller's: no command for the
|
|
105
|
+
// reply to answer.
|
|
106
|
+
requestStatus("connected");
|
|
107
|
+
}
|
|
103
108
|
else if (operation === "stop" || operation === "observe") {
|
|
104
109
|
state.command = { operation, generation };
|
|
105
110
|
// observe asks for the device's full status, so the reading is fresh.
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { TraceEntry } from "./bounded-trace";
|
|
2
|
+
import { type ExpectedCommand } from "./command-echo";
|
|
3
|
+
import type { LightReading } from "./light-contract";
|
|
4
|
+
import type { MqttPublication } from "./mqtt-message";
|
|
5
|
+
export interface RelayLightState {
|
|
6
|
+
expected: ExpectedCommand[];
|
|
7
|
+
lastOn: boolean | null;
|
|
8
|
+
reportedAt: string | null;
|
|
9
|
+
externalOn: boolean | null;
|
|
10
|
+
}
|
|
11
|
+
export declare function createRelayLightState(saved: Partial<RelayLightState> | undefined): RelayLightState;
|
|
12
|
+
export interface RelayLightStep {
|
|
13
|
+
publications: MqttPublication[];
|
|
14
|
+
readings: LightReading[];
|
|
15
|
+
traces: TraceEntry[];
|
|
16
|
+
}
|
|
17
|
+
export declare function relayLightFromRoom(state: RelayLightState, light: {
|
|
18
|
+
kind?: unknown;
|
|
19
|
+
state?: unknown;
|
|
20
|
+
restyle?: unknown;
|
|
21
|
+
id?: unknown;
|
|
22
|
+
}, target: string, commandTopic: string, relayOn: boolean | null, nowMs: number): RelayLightStep;
|
|
23
|
+
export declare function relayLightCommandSeen(state: RelayLightState, payload: unknown, target: string, relayOn: boolean | null, nowMs: number): RelayLightStep;
|
|
24
|
+
export declare function relayLightReport(state: RelayLightState, on: boolean, previous: boolean | null, target: string, nowMs: number): RelayLightStep;
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createRelayLightState = createRelayLightState;
|
|
4
|
+
exports.relayLightFromRoom = relayLightFromRoom;
|
|
5
|
+
exports.relayLightCommandSeen = relayLightCommandSeen;
|
|
6
|
+
exports.relayLightReport = relayLightReport;
|
|
7
|
+
const command_echo_1 = require("./command-echo");
|
|
8
|
+
function createRelayLightState(saved) {
|
|
9
|
+
return {
|
|
10
|
+
expected: Array.isArray(saved?.expected) ? saved.expected.map((entry) => ({ ...entry })) : [],
|
|
11
|
+
lastOn: typeof saved?.lastOn === "boolean" ? saved.lastOn : null,
|
|
12
|
+
reportedAt: typeof saved?.reportedAt === "string" ? saved.reportedAt : null,
|
|
13
|
+
externalOn: typeof saved?.externalOn === "boolean" ? saved.externalOn : null
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
// The relay command as remembered and matched: the room's power, as the echo
|
|
17
|
+
// queue reads it.
|
|
18
|
+
const asCommand = (on) => ({ state: on ? "ON" : "OFF" });
|
|
19
|
+
const step = () => ({ publications: [], readings: [], traces: [] });
|
|
20
|
+
// A room message for this light: a command switches the relay; an observe
|
|
21
|
+
// asks it to report. Brightness, colour and the rest don't apply to a relay
|
|
22
|
+
// and are left out (the room's target should be marked onOffOnly).
|
|
23
|
+
function relayLightFromRoom(state, light, target, commandTopic, relayOn, nowMs) {
|
|
24
|
+
const out = step();
|
|
25
|
+
if (light.kind === "observe") {
|
|
26
|
+
out.publications.push({ topic: commandTopic, payload: "status_update" });
|
|
27
|
+
out.traces.push({ event: "observe", outcome: "sent", reason: null, details: {} });
|
|
28
|
+
return out;
|
|
29
|
+
}
|
|
30
|
+
const on = light.state === "ON";
|
|
31
|
+
if (light.state !== "ON" && light.state !== "OFF") {
|
|
32
|
+
out.traces.push({ event: "command", outcome: "ignored", reason: "not-on-or-off", details: { state: String(light.state) } });
|
|
33
|
+
return out;
|
|
34
|
+
}
|
|
35
|
+
if (light.restyle === true) {
|
|
36
|
+
// A relay has no style: a restyle of a light already on changes nothing.
|
|
37
|
+
if (relayOn === true) {
|
|
38
|
+
out.readings.push({ kind: "skipped", target, id: String(light.id), observedAt: state.reportedAt ?? new Date(nowMs).toISOString() });
|
|
39
|
+
out.traces.push({ event: "command", outcome: "skipped", reason: "relay-has-no-style", details: { id: light.id } });
|
|
40
|
+
return out;
|
|
41
|
+
}
|
|
42
|
+
out.readings.push({ kind: "sent", target, id: String(light.id) });
|
|
43
|
+
}
|
|
44
|
+
state.expected = (0, command_echo_1.rememberCommand)(state.expected, asCommand(on), nowMs);
|
|
45
|
+
state.lastOn = on;
|
|
46
|
+
out.publications.push({ topic: commandTopic, payload: on ? "on" : "off" });
|
|
47
|
+
out.traces.push({ event: "command", outcome: "sent", reason: null, details: { id: light.id, power: on ? "on" : "off" } });
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
// A command seen on the relay's command topic: its own echo, or someone
|
|
51
|
+
// else's (another flow, the device's own app over MQTT), which the room may
|
|
52
|
+
// take as a person's change.
|
|
53
|
+
function relayLightCommandSeen(state, payload, target, relayOn, nowMs) {
|
|
54
|
+
const out = step();
|
|
55
|
+
const text = typeof payload === "string" ? payload.trim().toLowerCase() : "";
|
|
56
|
+
if (text !== "on" && text !== "off" && text !== "toggle")
|
|
57
|
+
return out;
|
|
58
|
+
if (text !== "toggle") {
|
|
59
|
+
const echo = (0, command_echo_1.checkCommandEcho)(state.expected, asCommand(text === "on"), nowMs);
|
|
60
|
+
state.expected = echo.queue;
|
|
61
|
+
if (echo.own) {
|
|
62
|
+
out.traces.push({ event: "command", outcome: "own", reason: "echo", details: { power: text } });
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
65
|
+
state.externalOn = text === "on";
|
|
66
|
+
}
|
|
67
|
+
else {
|
|
68
|
+
// A toggle's result: the opposite of the relay's last report, when known.
|
|
69
|
+
state.externalOn = relayOn === null ? null : !relayOn;
|
|
70
|
+
}
|
|
71
|
+
out.readings.push({ kind: "external", target, state: text.toUpperCase(), setsValues: false, observedAt: new Date(nowMs).toISOString() });
|
|
72
|
+
out.traces.push({ event: "command", outcome: "external", reason: null, details: { power: text } });
|
|
73
|
+
return out;
|
|
74
|
+
}
|
|
75
|
+
// The relay's output as it reports it: the room's reading, and a change it
|
|
76
|
+
// didn't cause (a person at a switch the relay follows, another flow) as
|
|
77
|
+
// someone else's, unless already reported from their command.
|
|
78
|
+
function relayLightReport(state, on, previous, target, nowMs) {
|
|
79
|
+
const out = step();
|
|
80
|
+
const observedAt = new Date(nowMs).toISOString();
|
|
81
|
+
const report = (0, command_echo_1.checkStateReport)(state.expected, on, nowMs);
|
|
82
|
+
state.expected = report.queue;
|
|
83
|
+
state.reportedAt = observedAt;
|
|
84
|
+
const changed = previous !== null && previous !== on;
|
|
85
|
+
if (changed && report.verdict === "external" && state.externalOn !== on) {
|
|
86
|
+
out.readings.push({ kind: "external", target, state: on ? "ON" : "OFF", setsValues: false, observedAt });
|
|
87
|
+
out.traces.push({ event: "relay", outcome: "external", reason: null, details: { on } });
|
|
88
|
+
}
|
|
89
|
+
state.externalOn = null;
|
|
90
|
+
out.readings.push({ kind: "observed", target, on, fields: [], showsLast: state.lastOn === on, observedAt });
|
|
91
|
+
return out;
|
|
92
|
+
}
|
|
93
|
+
//# sourceMappingURL=shelly-relay-light.js.map
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import type { TraceEntry } from "./bounded-trace";
|
|
2
2
|
import { type MqttPublication } from "./mqtt-message";
|
|
3
|
+
import type { LightReading } from "./light-contract";
|
|
4
|
+
import { type RelayLightState } from "./shelly-relay-light";
|
|
3
5
|
export declare const SHELLY_SWITCH_MODES: readonly ["auto", "detached", "relay"];
|
|
4
6
|
export type ShellySwitchMode = typeof SHELLY_SWITCH_MODES[number];
|
|
5
7
|
export declare const CONFIG_TIMEOUT_MS = 10000;
|
|
@@ -7,6 +9,7 @@ export interface ShellySwitchConfig {
|
|
|
7
9
|
topicPrefix: string;
|
|
8
10
|
channel: number;
|
|
9
11
|
mode: ShellySwitchMode;
|
|
12
|
+
target: string | null;
|
|
10
13
|
}
|
|
11
14
|
export interface DeviceSetup {
|
|
12
15
|
inMode: string;
|
|
@@ -21,6 +24,7 @@ export interface ShellySwitchState {
|
|
|
21
24
|
online: boolean;
|
|
22
25
|
relayOn: boolean | null;
|
|
23
26
|
inputState: boolean | null;
|
|
27
|
+
light: RelayLightState;
|
|
24
28
|
}
|
|
25
29
|
export interface ShellySwitchMessage {
|
|
26
30
|
topic?: unknown;
|
|
@@ -31,6 +35,7 @@ export interface ShellySwitchMessage {
|
|
|
31
35
|
switchCommand?: {
|
|
32
36
|
power?: unknown;
|
|
33
37
|
};
|
|
38
|
+
light?: unknown;
|
|
34
39
|
}
|
|
35
40
|
export type SwitchReading = {
|
|
36
41
|
source: "switch";
|
|
@@ -65,6 +70,7 @@ export declare function normaliseShellySwitchConfig(config: {
|
|
|
65
70
|
topicPrefix?: unknown;
|
|
66
71
|
channel?: unknown;
|
|
67
72
|
mode?: unknown;
|
|
73
|
+
target?: unknown;
|
|
68
74
|
}): ShellySwitchConfig;
|
|
69
75
|
export declare function shellySwitchTopics(config: ShellySwitchConfig): {
|
|
70
76
|
command: string;
|
|
@@ -83,11 +89,13 @@ export declare function transitionShellySwitch(saved: Partial<ShellySwitchState>
|
|
|
83
89
|
state: ShellySwitchState;
|
|
84
90
|
publications: MqttPublication[];
|
|
85
91
|
readings: SwitchReading[];
|
|
92
|
+
lightReadings: LightReading[];
|
|
86
93
|
traces: TraceEntry<Record<string, unknown>>[];
|
|
87
94
|
status: {
|
|
88
95
|
text: string;
|
|
89
96
|
fill: "green" | "yellow" | "red" | "grey";
|
|
90
97
|
};
|
|
98
|
+
ignored: boolean;
|
|
91
99
|
};
|
|
92
100
|
export declare function shellySwitchStatus(config: ShellySwitchConfig, state: ShellySwitchState): {
|
|
93
101
|
text: string;
|
|
@@ -8,6 +8,7 @@ exports.transitionShellySwitch = transitionShellySwitch;
|
|
|
8
8
|
exports.shellySwitchStatus = shellySwitchStatus;
|
|
9
9
|
const mqtt_message_1 = require("./mqtt-message");
|
|
10
10
|
const shelly_gen2_1 = require("./shelly-gen2");
|
|
11
|
+
const shelly_relay_light_1 = require("./shelly-relay-light");
|
|
11
12
|
exports.SHELLY_SWITCH_MODES = ["auto", "detached", "relay"];
|
|
12
13
|
// How long to wait for the device's configuration before taking it as
|
|
13
14
|
// unreadable.
|
|
@@ -27,7 +28,9 @@ function normaliseShellySwitchConfig(config) {
|
|
|
27
28
|
const mode = config.mode === undefined || config.mode === "" ? "auto" : String(config.mode);
|
|
28
29
|
if (!exports.SHELLY_SWITCH_MODES.includes(mode))
|
|
29
30
|
throw new Error("mode must be auto, detached or relay");
|
|
30
|
-
|
|
31
|
+
// Not set, or empty: not a room light.
|
|
32
|
+
const target = typeof config.target === "string" && config.target.trim() ? config.target.trim() : null;
|
|
33
|
+
return { topicPrefix, channel, mode: mode, target };
|
|
31
34
|
}
|
|
32
35
|
function shellySwitchTopics(config) {
|
|
33
36
|
const component = (0, shelly_gen2_1.shellyTopics)(config.topicPrefix, `switch:${config.channel}`);
|
|
@@ -59,18 +62,26 @@ function transitionShellySwitch(saved, msg, config, now) {
|
|
|
59
62
|
requestId: Number.isInteger(saved?.requestId) ? saved.requestId : 0,
|
|
60
63
|
online: saved?.online !== false,
|
|
61
64
|
relayOn: typeof saved?.relayOn === "boolean" ? saved.relayOn : null,
|
|
62
|
-
inputState: typeof saved?.inputState === "boolean" ? saved.inputState : null
|
|
65
|
+
inputState: typeof saved?.inputState === "boolean" ? saved.inputState : null,
|
|
66
|
+
light: (0, shelly_relay_light_1.createRelayLightState)(saved?.light)
|
|
63
67
|
};
|
|
64
68
|
const topics = shellySwitchTopics(config);
|
|
65
69
|
const nowMs = now.getTime();
|
|
66
70
|
const observedAt = now.toISOString();
|
|
67
71
|
const publications = [];
|
|
68
72
|
const readings = [];
|
|
73
|
+
// For the room, with a Target.
|
|
74
|
+
const lightReadings = [];
|
|
69
75
|
const traces = [];
|
|
70
76
|
const trace = (event, outcome, reason = null, details = {}) => {
|
|
71
77
|
traces.push({ event, outcome, reason, details });
|
|
72
78
|
};
|
|
73
79
|
const mode = () => effectiveMode(config, state);
|
|
80
|
+
function light(result) {
|
|
81
|
+
publications.push(...result.publications);
|
|
82
|
+
lightReadings.push(...result.readings);
|
|
83
|
+
traces.push(...result.traces);
|
|
84
|
+
}
|
|
74
85
|
// Asks for the device's configuration and its whole status (the baseline).
|
|
75
86
|
function readDevice(reason) {
|
|
76
87
|
state.requestId += 1;
|
|
@@ -95,20 +106,31 @@ function transitionShellySwitch(saved, msg, config, now) {
|
|
|
95
106
|
function relayOutput(status) {
|
|
96
107
|
if (typeof status.output !== "boolean")
|
|
97
108
|
return;
|
|
109
|
+
const previous = state.relayOn;
|
|
98
110
|
state.relayOn = status.output;
|
|
111
|
+
if (config.target)
|
|
112
|
+
light((0, shelly_relay_light_1.relayLightReport)(state.light, status.output, previous, config.target, nowMs));
|
|
99
113
|
if (mode() === "relay") {
|
|
100
114
|
// The device names the source of the last change: its own input is a person at the switch.
|
|
101
115
|
const person = status.source === "button" || status.source === "switch" || status.source === "input";
|
|
102
116
|
readings.push({ switchState: { kind: "observed", on: status.output, person, observedAt } });
|
|
103
117
|
}
|
|
104
|
-
else if (mode() === "detached" && !status.output) {
|
|
118
|
+
else if (mode() === "detached" && !status.output && !config.target) {
|
|
105
119
|
trace("relay", "off", "bulbs-unpowered");
|
|
106
120
|
}
|
|
107
121
|
}
|
|
108
122
|
const inputKey = () => `input:${state.setup?.inputId ?? config.channel}`;
|
|
109
123
|
const command = msg.switchCommand;
|
|
110
124
|
const own = msg.shellySwitch;
|
|
111
|
-
|
|
125
|
+
const room = (0, mqtt_message_1.isObject)(msg.light) && (msg.light.kind === "command" || msg.light.kind === "observe") ? msg.light : null;
|
|
126
|
+
if (room) {
|
|
127
|
+
// The room's messages for every light arrive here; only this one's count.
|
|
128
|
+
if (!config.target || room.target !== config.target) {
|
|
129
|
+
return { state, publications, readings, lightReadings, traces, status: shellySwitchStatus(config, state), ignored: true };
|
|
130
|
+
}
|
|
131
|
+
light((0, shelly_relay_light_1.relayLightFromRoom)(state.light, room, config.target, topics.command, state.relayOn, nowMs));
|
|
132
|
+
}
|
|
133
|
+
else if ((0, mqtt_message_1.isObject)(own) && own.kind === "startup") {
|
|
112
134
|
readDevice("startup");
|
|
113
135
|
}
|
|
114
136
|
else if ((0, mqtt_message_1.isObject)(own) && own.kind === "tick") {
|
|
@@ -207,15 +229,22 @@ function transitionShellySwitch(saved, msg, config, now) {
|
|
|
207
229
|
readings.push({ source: "switch-availability", payload: message.online ? "online" : "offline" });
|
|
208
230
|
if (mode() === "relay")
|
|
209
231
|
readings.push({ switchState: { kind: "availability", online: message.online } });
|
|
232
|
+
if (config.target)
|
|
233
|
+
lightReadings.push({ kind: "availability", target: config.target, online: message.online });
|
|
210
234
|
// Back online: read its configuration again, and a fresh baseline.
|
|
211
235
|
if (message.online)
|
|
212
236
|
readDevice("online");
|
|
213
237
|
}
|
|
214
|
-
else if (msg.topic
|
|
238
|
+
else if (msg.topic === topics.command) {
|
|
239
|
+
// Its own commands, or someone else's: only a room light reads them.
|
|
240
|
+
if (config.target)
|
|
241
|
+
light((0, shelly_relay_light_1.relayLightCommandSeen)(state.light, msg.payload, config.target, state.relayOn, nowMs));
|
|
242
|
+
}
|
|
243
|
+
else if (msg.topic !== topics.rpc && msg.topic !== topics.deviceCommand) {
|
|
215
244
|
trace("message", "ignored", "unrelated-message", { topic: typeof msg.topic === "string" ? msg.topic : null });
|
|
216
245
|
}
|
|
217
246
|
}
|
|
218
|
-
return { state, publications, readings, traces, status: shellySwitchStatus(config, state) };
|
|
247
|
+
return { state, publications, readings, lightReadings, traces, status: shellySwitchStatus(config, state), ignored: false };
|
|
219
248
|
}
|
|
220
249
|
// What the node's status shows: the mode found, and anything to act on.
|
|
221
250
|
function shellySwitchStatus(config, state) {
|
|
@@ -229,9 +258,9 @@ function shellySwitchStatus(config, state) {
|
|
|
229
258
|
: { text: "configuration unreadable: set Mode", fill: "red" };
|
|
230
259
|
}
|
|
231
260
|
const found = config.mode === "auto" ? setup : `${mode} (set)${setup ? `, device ${setup}` : ""}`;
|
|
232
|
-
if (mode === "detached" && state.relayOn === false)
|
|
261
|
+
if (mode === "detached" && state.relayOn === false && !config.target)
|
|
233
262
|
return { text: `${found} · relay off: bulbs unpowered`, fill: "yellow" };
|
|
234
|
-
const now = mode === "relay" && state.relayOn !== null ? ` · ${state.relayOn ? "on" : "off"}` : "";
|
|
263
|
+
const now = (mode === "relay" || config.target) && state.relayOn !== null ? ` · ${config.target ? config.target + " " : ""}${state.relayOn ? "on" : "off"}` : "";
|
|
235
264
|
return { text: `${found ?? mode}${now}`, fill: "green" };
|
|
236
265
|
}
|
|
237
266
|
//# sourceMappingURL=shelly-switch.js.map
|
|
@@ -560,6 +560,10 @@ function transitionTheatre(saved, msg, suppliedConfig = {}, nowValue = new Date(
|
|
|
560
560
|
if (state.blockedGeneration !== state.generation) {
|
|
561
561
|
state.transitionStartedAt = now.toISOString();
|
|
562
562
|
state.transitionCompletedAt = null;
|
|
563
|
+
// Re-confirming is a transition of its own: each target's
|
|
564
|
+
// confirmation is timed again from now.
|
|
565
|
+
for (const target of theatre_profiles_1.TARGETS)
|
|
566
|
+
state.metrics.targets[target].lastConfirmationMs = null;
|
|
563
567
|
}
|
|
564
568
|
}
|
|
565
569
|
else {
|
|
@@ -32,7 +32,8 @@ function resetTransitionMetrics(metrics) {
|
|
|
32
32
|
}
|
|
33
33
|
}
|
|
34
34
|
// A target's report: its attempts, fallback use, how old its observation is
|
|
35
|
-
// and,
|
|
35
|
+
// and, at its first ready report in this transition, how long after the
|
|
36
|
+
// transition started it confirmed. Its refreshes leave that figure.
|
|
36
37
|
function recordTargetReport(metric, report, previous, observedAt, transitionStartedAt, nowMs) {
|
|
37
38
|
const details = report.details && typeof report.details === "object" ? report.details : {};
|
|
38
39
|
const detailMetrics = details.metrics && typeof details.metrics === "object" &&
|
|
@@ -48,10 +49,11 @@ function recordTargetReport(metric, report, previous, observedAt, transitionStar
|
|
|
48
49
|
metric.fallbackUsed ||= fallbackUsed;
|
|
49
50
|
metric.observationAgeMs = observedAt === null ? null : Math.max(0, nowMs - observedAt);
|
|
50
51
|
if (report.status === "ready") {
|
|
52
|
+
// Null until then: resetTransitionMetrics clears it at each transition.
|
|
51
53
|
const startedAt = Date.parse(transitionStartedAt || "");
|
|
52
|
-
metric.lastConfirmationMs
|
|
53
|
-
|
|
54
|
-
|
|
54
|
+
if (metric.lastConfirmationMs === null && Number.isFinite(startedAt) && observedAt !== null) {
|
|
55
|
+
metric.lastConfirmationMs = Math.max(0, observedAt - startedAt);
|
|
56
|
+
}
|
|
55
57
|
metric.availability = "available";
|
|
56
58
|
}
|
|
57
59
|
else if (report.status === "failed" || report.status === "unavailable") {
|
package/dist/lib/theatre-slo.js
CHANGED
|
@@ -16,6 +16,9 @@ function normaliseTheatreSloConfig(config = {}) {
|
|
|
16
16
|
};
|
|
17
17
|
}
|
|
18
18
|
function duration(value) {
|
|
19
|
+
// Not timed: null, as given. Number(null) would make it 0 ms.
|
|
20
|
+
if (value === null || value === undefined || value === "")
|
|
21
|
+
return null;
|
|
19
22
|
const parsed = Number(value);
|
|
20
23
|
return Number.isFinite(parsed) && parsed >= 0 ? parsed : null;
|
|
21
24
|
}
|
|
@@ -3,7 +3,9 @@ import { type TheatreRequestState, type TheatreStateSnapshot } from "./theatre-r
|
|
|
3
3
|
import type { TraceEntry } from "./bounded-trace";
|
|
4
4
|
import { type IdScheme } from "./ha-discovery";
|
|
5
5
|
export type { ContractRequest, TheatreStateSnapshot } from "./theatre-requests";
|
|
6
|
-
export type TheatreStateContractState = TheatreRequestState
|
|
6
|
+
export type TheatreStateContractState = TheatreRequestState & {
|
|
7
|
+
published: Record<string, string>;
|
|
8
|
+
};
|
|
7
9
|
export interface TheatreStateContractConfig {
|
|
8
10
|
nodeId?: string;
|
|
9
11
|
idScheme?: IdScheme;
|
|
@@ -43,7 +45,7 @@ export declare function theatreRetainedTopics(config: TheatreStateContractConfig
|
|
|
43
45
|
export declare function theatreStartingPublications(config: TheatreStateContractConfig): ContractPublication[];
|
|
44
46
|
export declare function theatreStoppingPublications(config: TheatreStateContractConfig): ContractPublication[];
|
|
45
47
|
export declare function transitionTheatreStateContract(saved: Partial<TheatreStateContractState> | undefined, msg: TheatreStateContractMessage, suppliedConfig: Partial<TheatreStateContractConfig>, nowValue?: Date | string | number): {
|
|
46
|
-
state:
|
|
48
|
+
state: TheatreStateContractState;
|
|
47
49
|
requests: ContractRequestOutput[];
|
|
48
50
|
publications: ContractPublication[];
|
|
49
51
|
traces: TraceEntry<Record<string, unknown>>[];
|
|
@@ -134,6 +134,37 @@ const STATE_TOPICS = [
|
|
|
134
134
|
function statePublications(event, config, slo) {
|
|
135
135
|
return STATE_TOPICS.map(([name, value]) => publication((0, theatre_ha_discovery_1.theatreTopic)(config.baseTopic, name), value(event, slo)));
|
|
136
136
|
}
|
|
137
|
+
// Fields that only say when, or how long ago, something was seen: they move
|
|
138
|
+
// on every refresh of a steady target, so a payload that differs only in
|
|
139
|
+
// them is not a change. A target's health keeps the time it last changed.
|
|
140
|
+
// (A target's lastConfirmationMs is set once per transition, so it counts.)
|
|
141
|
+
const TIME_ONLY_FIELDS = new Set(["observedAt", "evaluatedAt", "observationAgeMs"]);
|
|
142
|
+
function comparable(payload) {
|
|
143
|
+
let value;
|
|
144
|
+
try {
|
|
145
|
+
value = JSON.parse(payload);
|
|
146
|
+
}
|
|
147
|
+
catch {
|
|
148
|
+
return payload;
|
|
149
|
+
}
|
|
150
|
+
const strip = (entry) => Array.isArray(entry)
|
|
151
|
+
? entry.map(strip)
|
|
152
|
+
: entry && typeof entry === "object"
|
|
153
|
+
? Object.fromEntries(Object.entries(entry).filter(([key]) => !TIME_ONLY_FIELDS.has(key)).map(([key, inner]) => [key, strip(inner)]))
|
|
154
|
+
: entry;
|
|
155
|
+
return JSON.stringify(strip(value));
|
|
156
|
+
}
|
|
157
|
+
// Only the publications whose payload changed, beyond its time-only
|
|
158
|
+
// fields, since the contract last published that topic; it records them.
|
|
159
|
+
function changed(state, publications) {
|
|
160
|
+
return publications.filter(({ topic, payload }) => {
|
|
161
|
+
const key = comparable(payload);
|
|
162
|
+
if (state.published[topic] === key)
|
|
163
|
+
return false;
|
|
164
|
+
state.published[topic] = key;
|
|
165
|
+
return true;
|
|
166
|
+
});
|
|
167
|
+
}
|
|
137
168
|
function requestPublications(request, config) {
|
|
138
169
|
const base = config.baseTopic;
|
|
139
170
|
return [
|
|
@@ -174,7 +205,10 @@ function theatreStoppingPublications(config) {
|
|
|
174
205
|
}
|
|
175
206
|
function transitionTheatreStateContract(saved, msg, suppliedConfig, nowValue = new Date()) {
|
|
176
207
|
const config = normaliseStateContractConfig(suppliedConfig);
|
|
177
|
-
const state =
|
|
208
|
+
const state = {
|
|
209
|
+
...(0, theatre_requests_1.createTheatreRequestState)(saved),
|
|
210
|
+
published: saved?.published && typeof saved.published === "object" && !Array.isArray(saved.published) ? { ...saved.published } : {}
|
|
211
|
+
};
|
|
178
212
|
const now = nowValue instanceof Date ? nowValue : new Date(nowValue);
|
|
179
213
|
if (!Number.isFinite(now.getTime()))
|
|
180
214
|
throw new Error("now must be a valid date");
|
|
@@ -190,6 +224,9 @@ function transitionTheatreStateContract(saved, msg, suppliedConfig, nowValue = n
|
|
|
190
224
|
const entries = config.discovery !== false || config.area ? (0, theatre_ha_discovery_1.theatreDiscovery)(config) : [];
|
|
191
225
|
publications.push(...entries.map(({ topic, payload }) => publication(topic, config.discovery !== false ? payload : "")));
|
|
192
226
|
publications.push(publication((0, theatre_ha_discovery_1.theatreTopic)(config.baseTopic, "availability"), ha_discovery_1.ONLINE));
|
|
227
|
+
// Each startup, and with a broker each connect: the next snapshot
|
|
228
|
+
// publishes every state topic again, in case the broker lost them.
|
|
229
|
+
state.published = {};
|
|
193
230
|
trace("startup", "discovery", null, { publications: publications.length });
|
|
194
231
|
}
|
|
195
232
|
else if (msg.topic === (0, theatre_ha_discovery_1.theatreTopic)(config.baseTopic, "request")) {
|
|
@@ -207,7 +244,7 @@ function transitionTheatreStateContract(saved, msg, suppliedConfig, nowValue = n
|
|
|
207
244
|
else {
|
|
208
245
|
trace("request", "accepted", null, { requestId: request.requestId, generation: state.generation, activity: request.activity });
|
|
209
246
|
}
|
|
210
|
-
publications.push(...requestPublications(request, config));
|
|
247
|
+
publications.push(...changed(state, requestPublications(request, config)));
|
|
211
248
|
}
|
|
212
249
|
}
|
|
213
250
|
else if (msg.theatre && typeof msg.theatre === "object" && msg.theatre.kind === "state") {
|
|
@@ -217,12 +254,18 @@ function transitionTheatreStateContract(saved, msg, suppliedConfig, nowValue = n
|
|
|
217
254
|
trace("state", "ignored", "stale-generation", { generation: event.generation });
|
|
218
255
|
}
|
|
219
256
|
else {
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
phase: event.phase
|
|
224
|
-
|
|
225
|
-
|
|
257
|
+
const all = statePublications(event, config, assessment);
|
|
258
|
+
publications.push(...changed(state, all));
|
|
259
|
+
if (!publications.length) {
|
|
260
|
+
trace("state", "unchanged", null, { generation: event.generation, phase: event.phase });
|
|
261
|
+
}
|
|
262
|
+
else {
|
|
263
|
+
trace("state", "published", null, {
|
|
264
|
+
generation: event.generation,
|
|
265
|
+
phase: event.phase,
|
|
266
|
+
publications: publications.length
|
|
267
|
+
});
|
|
268
|
+
}
|
|
226
269
|
}
|
|
227
270
|
}
|
|
228
271
|
else {
|
|
@@ -43,6 +43,9 @@ function count(value) {
|
|
|
43
43
|
return Number.isInteger(parsed) && parsed >= 0 ? parsed : 0;
|
|
44
44
|
}
|
|
45
45
|
function nullableDuration(value) {
|
|
46
|
+
// Not a duration yet: null, as saved. Number(null) would make it 0.
|
|
47
|
+
if (value === null || value === undefined || value === "")
|
|
48
|
+
return null;
|
|
46
49
|
const parsed = Number(value);
|
|
47
50
|
return Number.isFinite(parsed) && parsed >= 0 ? parsed : null;
|
|
48
51
|
}
|
|
@@ -52,6 +52,6 @@
|
|
|
52
52
|
<p>While a profile is active, its lights are overridden in the room controller under <b>Owner</b>
|
|
53
53
|
(default <code>activity</code>), so the room's style (from a circadian lighting policy) leaves the activity's alone. When a new profile
|
|
54
54
|
no longer includes a light, including a switch to an off profile with no targets, the node emits
|
|
55
|
-
<code>{kind: "release", owner, targets}</code> for those lights and the room controller
|
|
55
|
+
<code>{kind: "release", owner, targets}</code> for those lights, and the room controller gives each back what it was before the activity took it: one the room was running is restyled.
|
|
56
56
|
Give each activity-lighting node that feeds the same room controller its own owner.</p>
|
|
57
57
|
</script>
|