@avantics/node-red-home-automation 6.2.0 → 6.3.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.
Files changed (64) hide show
  1. package/README.md +60 -8
  2. package/dist/lib/activity-lighting-controller.d.ts +1 -0
  3. package/dist/lib/activity-lighting-controller.js +37 -10
  4. package/dist/lib/avr-controller.d.ts +3 -0
  5. package/dist/lib/avr-controller.js +24 -2
  6. package/dist/lib/backlighting-controller.d.ts +5 -2
  7. package/dist/lib/backlighting-controller.js +27 -2
  8. package/dist/lib/display-mode-controller.d.ts +3 -0
  9. package/dist/lib/display-mode-controller.js +43 -16
  10. package/dist/lib/esphome-sensor.d.ts +73 -0
  11. package/dist/lib/esphome-sensor.js +261 -0
  12. package/dist/lib/occupancy-fusion.d.ts +1 -0
  13. package/dist/lib/occupancy-fusion.js +15 -2
  14. package/dist/lib/scene.d.ts +9 -1
  15. package/dist/lib/scene.js +61 -8
  16. package/dist/lib/source-capability-controller.d.ts +4 -1
  17. package/dist/lib/source-capability-controller.js +49 -2
  18. package/dist/lib/target-observation.d.ts +14 -0
  19. package/dist/lib/target-observation.js +22 -0
  20. package/dist/lib/theatre-activity-controller.d.ts +5 -0
  21. package/dist/lib/theatre-activity-controller.js +87 -12
  22. package/dist/lib/theatre-state.d.ts +2 -0
  23. package/dist/lib/theatre-state.js +10 -1
  24. package/dist/lib/wled.d.ts +48 -0
  25. package/dist/lib/wled.js +105 -0
  26. package/dist/lib/z2m-power.d.ts +38 -0
  27. package/dist/lib/z2m-power.js +83 -0
  28. package/dist/lib/z2m-sensor.d.ts +37 -0
  29. package/dist/lib/z2m-sensor.js +88 -0
  30. package/dist/nodes/apollo-r-pro-1.d.ts +2 -0
  31. package/dist/nodes/apollo-r-pro-1.html +80 -0
  32. package/dist/nodes/apollo-r-pro-1.js +4 -0
  33. package/dist/nodes/avr-controller.js +1 -1
  34. package/dist/nodes/backlighting-controller.js +3 -2
  35. package/dist/nodes/device-side.d.ts +1 -0
  36. package/dist/nodes/device-side.js +7 -3
  37. package/dist/nodes/display-mode-controller.js +11 -2
  38. package/dist/nodes/esphome-sensor.d.ts +2 -0
  39. package/dist/nodes/esphome-sensor.js +77 -0
  40. package/dist/nodes/everything-presence-one.d.ts +2 -0
  41. package/dist/nodes/everything-presence-one.html +78 -0
  42. package/dist/nodes/everything-presence-one.js +4 -0
  43. package/dist/nodes/occupancy-fusion.html +3 -0
  44. package/dist/nodes/occupancy-fusion.js +2 -1
  45. package/dist/nodes/scene.html +24 -3
  46. package/dist/nodes/scene.js +9 -2
  47. package/dist/nodes/shelly-cover.html +1 -0
  48. package/dist/nodes/shelly-switch.html +1 -0
  49. package/dist/nodes/source-capability-controller.js +3 -2
  50. package/dist/nodes/theatre-activity-controller.html +4 -2
  51. package/dist/nodes/wled.d.ts +3 -0
  52. package/dist/nodes/wled.html +56 -0
  53. package/dist/nodes/wled.js +53 -0
  54. package/dist/nodes/z2m-cover.html +1 -0
  55. package/dist/nodes/z2m-light.html +3 -1
  56. package/dist/nodes/z2m-light.js +17 -0
  57. package/dist/nodes/z2m-power.d.ts +3 -0
  58. package/dist/nodes/z2m-power.html +58 -0
  59. package/dist/nodes/z2m-power.js +53 -0
  60. package/dist/nodes/z2m-sensor.d.ts +3 -0
  61. package/dist/nodes/z2m-sensor.html +69 -0
  62. package/dist/nodes/z2m-sensor.js +62 -0
  63. package/examples/Scene.json +8 -56
  64. package/package.json +7 -2
@@ -0,0 +1,261 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ESPHOME_MODELS = void 0;
4
+ exports.normaliseEsphomeSensorConfig = normaliseEsphomeSensorConfig;
5
+ exports.esphomeSensorTopics = esphomeSensorTopics;
6
+ exports.esphomeRoles = esphomeRoles;
7
+ exports.transitionEsphomeSensor = transitionEsphomeSensor;
8
+ const mqtt_message_1 = require("./mqtt-message");
9
+ exports.ESPHOME_MODELS = {
10
+ "everything-presence-one": {
11
+ label: "Everything Presence One",
12
+ modelNames: ["everythingpresenceone"],
13
+ // Its own "Occupancy" combines the PIR and radar, with its own off
14
+ // latency: occupancy fusion does that combining here.
15
+ exclude: ["occupancy"],
16
+ motion: ["pir"],
17
+ presence: ["mmwave"],
18
+ illuminance: ["illuminance"]
19
+ },
20
+ "apollo-r-pro-1": {
21
+ label: "Apollo R PRO-1",
22
+ modelNames: ["rpro1"],
23
+ exclude: [],
24
+ // Its two radars, LD2450 and LD2412: a moving target is motion. Its
25
+ // firmware has named the LD2450's entities both without a prefix
26
+ // (presence, moving_target) and, currently, with ld2450_.
27
+ motion: ["moving_target", "ld2450_moving_target", "ld2412_moving_target"],
28
+ presence: ["presence", "ld2450_presence", "ld2412_presence"],
29
+ illuminance: ["ltr390_light"]
30
+ }
31
+ };
32
+ function normaliseEsphomeSensorConfig(config) {
33
+ const device = String(config.device ?? "").trim().replace(/^\/+|\/+$/g, "");
34
+ // The user's own device's: no default.
35
+ if (!device)
36
+ throw new Error("the device's name is required");
37
+ if (/[+#]/.test(device))
38
+ throw new Error("the device's name can't contain + or #");
39
+ const model = String(config.model ?? "");
40
+ if (!Object.hasOwn(exports.ESPHOME_MODELS, model))
41
+ throw new Error(`unknown model: ${model}`);
42
+ const discoveryPrefix = String(config.discoveryPrefix ?? "").trim().replace(/^\/+|\/+$/g, "") || "homeassistant";
43
+ if (/[+#]/.test(discoveryPrefix))
44
+ throw new Error("the discovery prefix can't contain + or #");
45
+ return { device, model, discoveryPrefix };
46
+ }
47
+ // The topics a node subscribes to as it starts: the device's discovery,
48
+ // its status, and its preset's states (until discovery says otherwise).
49
+ function esphomeSensorTopics(config) {
50
+ const preset = presetRoles(config, "preset");
51
+ return {
52
+ discovery: `${config.discoveryPrefix}/+/${config.device}/+/config`,
53
+ initial: [...new Set([`${config.discoveryPrefix}/+/${config.device}/+/config`, ...preset.status, ...preset.presence,
54
+ ...preset.motion, ...preset.illuminance])]
55
+ };
56
+ }
57
+ function presetRoles(config, source) {
58
+ const model = exports.ESPHOME_MODELS[config.model];
59
+ const binary = (name) => `${config.device}/binary_sensor/${name}/state`;
60
+ return {
61
+ source,
62
+ motion: model.motion.map(binary),
63
+ presence: model.presence.map(binary),
64
+ illuminance: model.illuminance.map((name) => `${config.device}/sensor/${name}/state`),
65
+ status: [`${config.device}/status`]
66
+ };
67
+ }
68
+ const simplified = (value) => value.toLowerCase().replace(/[^a-z0-9]/g, "");
69
+ // The roles, from the device's discovery when it has one for this model.
70
+ function esphomeRoles(state, config) {
71
+ const model = exports.ESPHOME_MODELS[config.model];
72
+ const entities = Object.values(state.discovered).filter((entity) => !model.exclude.includes(entity.object));
73
+ if (!entities.length)
74
+ return presetRoles(config, "preset");
75
+ const models = entities.map((entity) => entity.model).filter((name) => Boolean(name));
76
+ if (models.some((name) => !model.modelNames.some((fragment) => simplified(name).includes(fragment)))) {
77
+ return presetRoles(config, "preset-other-model");
78
+ }
79
+ const of = (component, classes) => entities
80
+ .filter((entity) => entity.component === component && entity.deviceClass !== null && classes.includes(entity.deviceClass))
81
+ .map((entity) => entity.stateTopic);
82
+ const status = [...new Set([`${config.device}/status`, ...entities.map((entity) => entity.availabilityTopic)
83
+ .filter((topic) => Boolean(topic))])];
84
+ return {
85
+ source: "discovered",
86
+ motion: of("binary_sensor", ["motion"]),
87
+ presence: of("binary_sensor", ["occupancy", "presence"]),
88
+ illuminance: of("sensor", ["illuminance"]),
89
+ status
90
+ };
91
+ }
92
+ function text(payload) {
93
+ return (Buffer.isBuffer(payload) ? payload.toString("utf8") : String(payload ?? "")).trim();
94
+ }
95
+ // A discovery entry's fields, from Home Assistant's discovery format with
96
+ // or without its abbreviated keys. Its "~" base-topic shorthand isn't
97
+ // expanded: ESPHome gives full state and availability topics.
98
+ function discoveredEntity(component, object, payload) {
99
+ let entry;
100
+ try {
101
+ entry = JSON.parse(payload);
102
+ }
103
+ catch {
104
+ return null;
105
+ }
106
+ if (!(0, mqtt_message_1.isObject)(entry))
107
+ return null;
108
+ // Disabled by default on the device (ESPHome's disabled_by_default, "en":
109
+ // false): its maker doesn't mean it as one of its sensors, such as the
110
+ // Apollo's LD2412 light level, a radar reading rather than lux.
111
+ if (entry.en === false || entry.enabled_by_default === false)
112
+ return "disabled";
113
+ const field = (short, long) => (typeof entry[short] === "string" ? entry[short] : typeof entry[long] === "string" ? entry[long] : null);
114
+ const stateTopic = field("stat_t", "state_topic");
115
+ if (!stateTopic)
116
+ return null;
117
+ const device = (0, mqtt_message_1.isObject)(entry.dev) ? entry.dev : (0, mqtt_message_1.isObject)(entry.device) ? entry.device : {};
118
+ const model = typeof device.mdl === "string" ? device.mdl : typeof device.model === "string" ? device.model : null;
119
+ return { component, object, stateTopic, deviceClass: field("dev_cla", "device_class"), model, availabilityTopic: field("avty_t", "availability_topic") };
120
+ }
121
+ function transitionEsphomeSensor(saved, msg, config) {
122
+ const state = {
123
+ entities: saved?.entities && typeof saved.entities === "object" ? { ...saved.entities } : {},
124
+ motion: typeof saved?.motion === "boolean" ? saved.motion : null,
125
+ presence: typeof saved?.presence === "boolean" ? saved.presence : null,
126
+ illuminance: typeof saved?.illuminance === "number" ? saved.illuminance : null,
127
+ online: typeof saved?.online === "boolean" ? saved.online : null,
128
+ awaitingStatus: saved?.awaitingStatus === true,
129
+ discovered: saved?.discovered && typeof saved.discovered === "object" ? { ...saved.discovered } : {}
130
+ };
131
+ const occupancy = [];
132
+ const light = [];
133
+ const traces = [];
134
+ const trace = (event, outcome, reason = null, details = {}) => {
135
+ traces.push({ event, outcome, reason, details });
136
+ };
137
+ const before = esphomeRoles(state, config);
138
+ // A role's value from the entities that have reported: on when any is
139
+ // on, off when all are off, not known while none has reported.
140
+ function roleValue(roles, role) {
141
+ const reported = roles[role].map((topic) => state.entities[topic]).filter((value) => value !== undefined);
142
+ if (!reported.length)
143
+ return null;
144
+ return reported.some((value) => value === true);
145
+ }
146
+ // Each occupancy role that changed, presence first: at a start, presence
147
+ // holds the room before motion's "off" could empty it.
148
+ function sendRoles(roles, baseline) {
149
+ for (const role of ["presence", "motion"]) {
150
+ const value = roleValue(roles, role);
151
+ if (value === null || value === state[role])
152
+ continue;
153
+ state[role] = value;
154
+ occupancy.push(baseline ? { source: role, payload: value, baseline: true } : { source: role, payload: value });
155
+ trace(role, baseline ? "baseline" : "changed", null, { value });
156
+ }
157
+ }
158
+ const retained = msg.retain === true;
159
+ const topic = typeof msg.topic === "string" ? msg.topic : "";
160
+ const discovery = topic.split("/");
161
+ const prefixParts = config.discoveryPrefix.split("/").length;
162
+ if (topic.startsWith(`${config.discoveryPrefix}/`) && discovery.length === prefixParts + 4 && discovery.at(-1) === "config" &&
163
+ discovery[prefixParts + 1] === config.device) {
164
+ const component = discovery[prefixParts];
165
+ const object = discovery[prefixParts + 2];
166
+ const payload = text(msg.payload);
167
+ if (component !== "binary_sensor" && component !== "sensor") {
168
+ trace("discovery", "ignored", "other-component", { component, object });
169
+ }
170
+ else if (payload === "") {
171
+ // An entity removed from the device.
172
+ delete state.discovered[topic];
173
+ trace("discovery", "removed", null, { object });
174
+ }
175
+ else {
176
+ const entity = discoveredEntity(component, object, payload);
177
+ if (entity === "disabled") {
178
+ delete state.discovered[topic];
179
+ trace("discovery", "ignored", "disabled", { object });
180
+ }
181
+ else if (!entity) {
182
+ trace("discovery", "ignored", "no-state-topic", { object });
183
+ }
184
+ else {
185
+ state.discovered[topic] = entity;
186
+ }
187
+ }
188
+ const after = esphomeRoles(state, config);
189
+ if (JSON.stringify(after) !== JSON.stringify(before)) {
190
+ const preset = presetRoles(config, "preset");
191
+ // Discovery wins over the preset; where they differ, it's traced.
192
+ const differs = after.source === "discovered" &&
193
+ ["motion", "presence", "illuminance"].some((role) => JSON.stringify([...after[role]].sort()) !== JSON.stringify([...preset[role]].sort()));
194
+ trace("roles", after.source, differs ? "differs-from-preset" : null, { motion: after.motion, presence: after.presence, illuminance: after.illuminance });
195
+ }
196
+ }
197
+ else if (before.status.includes(topic)) {
198
+ const status = text(msg.payload).toLowerCase();
199
+ if (status !== "online" && status !== "offline") {
200
+ trace("availability", "ignored", "not-online-or-offline", { status });
201
+ }
202
+ else {
203
+ state.online = status === "online";
204
+ trace("availability", status);
205
+ if (state.online && state.awaitingStatus) {
206
+ // The retained states held for this: the room as it is at start.
207
+ state.awaitingStatus = false;
208
+ sendRoles(before, true);
209
+ }
210
+ else if (!state.online) {
211
+ // A device that isn't online: what it last retained isn't current.
212
+ state.awaitingStatus = false;
213
+ if (retained)
214
+ state.entities = {};
215
+ }
216
+ }
217
+ }
218
+ else if (before.motion.includes(topic) || before.presence.includes(topic)) {
219
+ const value = text(msg.payload).toUpperCase();
220
+ if (value !== "ON" && value !== "OFF") {
221
+ // A fixed contract: only ON and OFF pass.
222
+ trace("state", "ignored", "not-on-or-off", { topic, value });
223
+ }
224
+ else if (retained && state.online === false) {
225
+ trace("state", "ignored", "retained-while-offline", { topic });
226
+ }
227
+ else {
228
+ state.entities[topic] = value === "ON";
229
+ if (retained && state.online !== true) {
230
+ state.awaitingStatus = true;
231
+ trace("state", "held", "awaiting-status", { topic });
232
+ }
233
+ else {
234
+ sendRoles(before, retained);
235
+ }
236
+ }
237
+ }
238
+ else if (before.illuminance.includes(topic)) {
239
+ const lux = Number(text(msg.payload));
240
+ if (text(msg.payload) === "" || !Number.isFinite(lux)) {
241
+ // A fixed contract: only a number passes ("nan" doesn't).
242
+ trace("illuminance", "ignored", "not-a-number", { value: text(msg.payload) });
243
+ }
244
+ else if (retained && state.online === false) {
245
+ trace("illuminance", "ignored", "retained-while-offline");
246
+ }
247
+ else if (lux !== state.illuminance) {
248
+ state.illuminance = lux;
249
+ light.push({ source: "illuminance", payload: lux });
250
+ trace("illuminance", "changed", null, { lux });
251
+ }
252
+ }
253
+ else {
254
+ trace("message", "ignored", "other-topic", { topic: topic || null });
255
+ }
256
+ const roles = esphomeRoles(state, config);
257
+ // Every topic the node needs now: it subscribes to any it hasn't yet.
258
+ const topics = [...new Set([esphomeSensorTopics(config).discovery, ...roles.status, ...roles.presence, ...roles.motion, ...roles.illuminance])];
259
+ return { state, occupancy, light, traces, roles, topics };
260
+ }
261
+ //# sourceMappingURL=esphome-sensor.js.map
@@ -10,6 +10,7 @@ export interface OccupancyState {
10
10
  export interface OccupancyInput {
11
11
  source: string;
12
12
  payload: unknown;
13
+ baseline?: boolean;
13
14
  }
14
15
  export interface OccupancyConfig {
15
16
  presenceMode?: "hold" | "ignore";
@@ -78,7 +78,13 @@ function transitionOccupancy(saved, input, config) {
78
78
  const wasActive = state.motionActive;
79
79
  state.motionKnown = true;
80
80
  state.motionActive = active;
81
- if (active) {
81
+ if (active && input.baseline === true) {
82
+ // Someone is there as Node-RED starts: occupied, but nothing is sent,
83
+ // so no light is switched on. Motion acts from its next change.
84
+ state.occupied = true;
85
+ trace("motion", "baseline", "occupied-at-start");
86
+ }
87
+ else if (active) {
82
88
  state.occupied = true;
83
89
  if (!wasKnown || !wasActive) {
84
90
  emit(true, "motion-active", "motion");
@@ -106,7 +112,14 @@ function transitionOccupancy(saved, input, config) {
106
112
  const wasActive = state.presenceActive;
107
113
  state.presenceKnown = true;
108
114
  state.presenceActive = active;
109
- if (active) {
115
+ if (active && input.baseline === true) {
116
+ // Presence as Node-RED starts is someone there: it holds the room as
117
+ // occupied, sending nothing, though live presence alone never starts
118
+ // occupancy.
119
+ state.occupied = true;
120
+ trace("presence", "baseline", "occupied-at-start");
121
+ }
122
+ else if (active) {
110
123
  trace("presence", state.occupied ? "held" : "standby", state.occupied ? "presence-active" : "motion-required");
111
124
  }
112
125
  else if (!state.motionActive && (!wasKnown || wasActive || state.occupied)) {
@@ -10,7 +10,10 @@ export interface SceneConfig {
10
10
  owner: string;
11
11
  lights: SceneLight[];
12
12
  safetyMs: number;
13
+ endBelowWatts: number | null;
14
+ endBelowMs: number;
13
15
  }
16
+ export declare const DEFAULT_END_BELOW_SECONDS = 60;
14
17
  export declare const DEFAULT_SAFETY_HOURS = 4;
15
18
  export declare const RENEW_MS = 60000;
16
19
  export interface SceneState {
@@ -26,10 +29,13 @@ export interface SceneState {
26
29
  by: string;
27
30
  at: number;
28
31
  } | null;
32
+ powerBelowSince: number | null;
33
+ powerUsed: boolean;
29
34
  }
30
35
  export interface SceneEvent {
31
36
  kind?: unknown;
32
37
  by?: unknown;
38
+ watts?: unknown;
33
39
  }
34
40
  export interface SceneLighting {
35
41
  lighting: Record<string, unknown>;
@@ -43,6 +49,8 @@ export declare function normaliseSceneConfig(raw: {
43
49
  owner: string;
44
50
  lights?: unknown;
45
51
  safetyHours?: unknown;
52
+ endBelowWatts?: unknown;
53
+ endBelowSeconds?: unknown;
46
54
  }): SceneConfig;
47
55
  export declare function createSceneState(saved?: Partial<SceneState>): SceneState;
48
56
  export declare function transitionScene(saved: Partial<SceneState> | undefined, msg: {
@@ -58,4 +66,4 @@ export declare function transitionScene(saved: Partial<SceneState> | undefined,
58
66
  text: string;
59
67
  };
60
68
  };
61
- export declare function sceneTickAt(state: SceneState, now: number): number | null;
69
+ export declare function sceneTickAt(state: SceneState, now: number, config?: Pick<SceneConfig, "endBelowMs">): number | null;
package/dist/lib/scene.js CHANGED
@@ -1,12 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.RENEW_MS = exports.DEFAULT_SAFETY_HOURS = void 0;
3
+ exports.RENEW_MS = exports.DEFAULT_SAFETY_HOURS = exports.DEFAULT_END_BELOW_SECONDS = void 0;
4
4
  exports.normaliseSceneConfig = normaliseSceneConfig;
5
5
  exports.createSceneState = createSceneState;
6
6
  exports.transitionScene = transitionScene;
7
7
  exports.sceneTickAt = sceneTickAt;
8
8
  const settings_1 = require("./settings");
9
9
  const topic_names_1 = require("./topic-names");
10
+ exports.DEFAULT_END_BELOW_SECONDS = 60;
10
11
  exports.DEFAULT_SAFETY_HOURS = 4;
11
12
  // How often an active scene renews its motion pause and its status: well
12
13
  // within the motion policy's maximum pause (10 minutes by default).
@@ -58,7 +59,15 @@ function normaliseSceneConfig(raw) {
58
59
  const hours = (0, settings_1.numberSetting)(raw.safetyHours, "safety timer", exports.DEFAULT_SAFETY_HOURS);
59
60
  if (hours < 0)
60
61
  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
+ // Optional: empty (or a scene saved before it) means no power end.
63
+ const below = raw.endBelowWatts === undefined || raw.endBelowWatts === null || String(raw.endBelowWatts).trim() === ""
64
+ ? null : (0, settings_1.numberSetting)(raw.endBelowWatts, "end below", 0);
65
+ if (below !== null && below <= 0)
66
+ throw new Error("end below must be more than 0 watts, or empty for none");
67
+ const seconds = (0, settings_1.numberSetting)(raw.endBelowSeconds, "end below for", exports.DEFAULT_END_BELOW_SECONDS);
68
+ if (seconds < 0)
69
+ throw new Error("end below for must be 0 or more seconds");
70
+ return { owner: raw.owner, lights, safetyMs: Math.round(hours * 3_600_000), endBelowWatts: below, endBelowMs: Math.round(seconds * 1000) };
62
71
  }
63
72
  function createSceneState(saved = {}) {
64
73
  const active = saved.active === true && typeof saved.owner === "string";
@@ -70,7 +79,9 @@ function createSceneState(saved = {}) {
70
79
  : [],
71
80
  startedAt: active && Number.isFinite(saved.startedAt) ? saved.startedAt : null,
72
81
  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
82
+ ended: saved.ended && typeof saved.ended.by === "string" && Number.isFinite(saved.ended.at) ? { ...saved.ended } : null,
83
+ powerBelowSince: active && Number.isFinite(saved.powerBelowSince) ? saved.powerBelowSince : null,
84
+ powerUsed: active && saved.powerUsed === true
74
85
  };
75
86
  }
76
87
  // How a span of time reads on the status: "3h 59m", "12m", "under 1m".
@@ -101,7 +112,7 @@ function transitionScene(saved, msg, config, nowValue = new Date()) {
101
112
  lighting.push({ lighting: { kind: "release", area, owner, targets, source: "scene" } });
102
113
  pause(false);
103
114
  trace("scene", "ended", null, { by, owner });
104
- Object.assign(state, { active: false, owner: null, lights: [], startedAt: null, endsAt: null, ended: { by, at: now } });
115
+ Object.assign(state, { active: false, owner: null, lights: [], startedAt: null, endsAt: null, ended: { by, at: now }, powerBelowSince: null, powerUsed: false });
105
116
  }
106
117
  if (kind === "start") {
107
118
  if (state.active) {
@@ -117,7 +128,9 @@ function transitionScene(saved, msg, config, nowValue = new Date()) {
117
128
  owner: config.owner,
118
129
  lights: config.lights.map(({ area, target }) => ({ area, target })),
119
130
  startedAt: now,
120
- endsAt: config.safetyMs > 0 ? now + config.safetyMs : null
131
+ endsAt: config.safetyMs > 0 ? now + config.safetyMs : null,
132
+ powerBelowSince: null,
133
+ powerUsed: false
121
134
  });
122
135
  for (const light of config.lights) {
123
136
  const values = {
@@ -137,12 +150,47 @@ function transitionScene(saved, msg, config, nowValue = new Date()) {
137
150
  else
138
151
  trace("scene", "ignored", "not-active");
139
152
  }
153
+ else if (kind === "power") {
154
+ const watts = Number(event.watts);
155
+ if (!state.active) {
156
+ trace("power", "ignored", "not-active");
157
+ }
158
+ else if (config.endBelowWatts === null) {
159
+ trace("power", "ignored", "no-end-below");
160
+ }
161
+ else if (!Number.isFinite(watts) || watts < 0) {
162
+ trace("power", "ignored", "not-watts");
163
+ }
164
+ else if (watts >= config.endBelowWatts) {
165
+ if (!state.powerUsed)
166
+ trace("power", "used", null, { watts });
167
+ else if (state.powerBelowSince !== null)
168
+ trace("power", "above", null, { watts });
169
+ state.powerUsed = true;
170
+ state.powerBelowSince = null;
171
+ }
172
+ else if (!state.powerUsed) {
173
+ // Not used yet since it started: a standby draw doesn't end it.
174
+ trace("power", "ignored", "not-used-yet", { watts });
175
+ }
176
+ else {
177
+ if (state.powerBelowSince === null) {
178
+ state.powerBelowSince = now;
179
+ trace("power", "below", null, { watts, endBelowWatts: config.endBelowWatts });
180
+ }
181
+ if (now - state.powerBelowSince >= config.endBelowMs)
182
+ end("power");
183
+ }
184
+ }
140
185
  else if (kind === "tick" || kind === "startup") {
141
186
  // Its timer, or the flows starting again (a redeploy or restart with a
142
187
  // context store): end it if its time is up, otherwise renew its pause.
143
188
  // Its lights are not asked again: the rooms still hold them.
144
189
  if (state.active && state.endsAt !== null && state.endsAt <= now)
145
190
  end("timer");
191
+ else if (state.active && state.powerBelowSince !== null && config.endBelowWatts !== null &&
192
+ now - state.powerBelowSince >= config.endBelowMs)
193
+ end("power");
146
194
  else if (state.active)
147
195
  pause(true);
148
196
  }
@@ -161,10 +209,15 @@ function transitionScene(saved, msg, config, nowValue = new Date()) {
161
209
  }
162
210
  // When it next needs a tick: its next renewal, or its safety timer's end if
163
211
  // sooner. Null when off.
164
- function sceneTickAt(state, now) {
212
+ function sceneTickAt(state, now, config) {
165
213
  if (!state.active)
166
214
  return null;
167
- const renew = now + exports.RENEW_MS;
168
- return state.endsAt !== null ? Math.min(renew, state.endsAt) : renew;
215
+ const at = [now + exports.RENEW_MS];
216
+ if (state.endsAt !== null)
217
+ at.push(state.endsAt);
218
+ // When power held below its End below would end it.
219
+ if (state.powerBelowSince !== null && config)
220
+ at.push(state.powerBelowSince + config.endBelowMs);
221
+ return Math.min(...at);
169
222
  }
170
223
  //# sourceMappingURL=scene.js.map
@@ -1,3 +1,4 @@
1
+ import { type TargetObservationOutput } from "./target-observation";
1
2
  import { type Carried } from "./adopted-request";
2
3
  import type { TraceEntry } from "./bounded-trace";
3
4
  import { type TargetStateEvent } from "./target-state";
@@ -57,6 +58,7 @@ export interface SourceState {
57
58
  refreshAsked: boolean;
58
59
  adoptedGeneration: number | null;
59
60
  carried?: Carried | null;
61
+ probe?: Record<string, SourceObservationStatus | null> | null;
60
62
  }
61
63
  export type SourceEvent = {
62
64
  kind: "intent";
@@ -100,7 +102,7 @@ export declare function normaliseConfig(config?: {
100
102
  export interface SourceCommand {
101
103
  sourceId: string | null;
102
104
  operation: SourceAction | "observe";
103
- requestId: string;
105
+ requestId: string | null;
104
106
  generation: number;
105
107
  attempt: number;
106
108
  }
@@ -140,6 +142,7 @@ export declare function transitionSource(saved: Partial<SourceState> | undefined
140
142
  state: SourceState;
141
143
  commands: SourceCommand[];
142
144
  events: SourceOutputEvent[];
145
+ observations: TargetObservationOutput[];
143
146
  traces: TraceEntry<Record<string, unknown>>[];
144
147
  status: {
145
148
  phase: string;
@@ -4,6 +4,7 @@ exports.normaliseCapabilities = normaliseCapabilities;
4
4
  exports.normaliseConfig = normaliseConfig;
5
5
  exports.readinessEvidence = readinessEvidence;
6
6
  exports.transitionSource = transitionSource;
7
+ const target_observation_1 = require("./target-observation");
7
8
  const adopted_request_1 = require("./adopted-request");
8
9
  const settings_1 = require("./settings");
9
10
  const observation_time_1 = require("./observation-time");
@@ -113,7 +114,8 @@ function initialState(saved = {}, sources = {}) {
113
114
  fallbackUsed: saved.fallbackUsed === true,
114
115
  refreshAsked: saved.refreshAsked === true,
115
116
  adoptedGeneration: (0, adopted_request_1.savedAdoptedGeneration)(saved),
116
- carried: (0, adopted_request_1.savedCarried)(saved)
117
+ carried: (0, adopted_request_1.savedCarried)(saved),
118
+ probe: saved.probe && typeof saved.probe === "object" && !Array.isArray(saved.probe) ? { ...saved.probe } : null
117
119
  };
118
120
  }
119
121
  function commandFor(state, operation, attempt = 1) {
@@ -206,6 +208,19 @@ function transitionSource(saved, msg, suppliedConfig = {}, nowValue = new Date()
206
208
  const event = msg?.sourceCapability;
207
209
  const commands = [];
208
210
  const events = [];
211
+ // Its answer to the theatre's recovery probe, for output 2 as the events.
212
+ const observations = [];
213
+ // What the probed sources show, in the activity profiles' terms: the one
214
+ // active source, or every source inactive; otherwise nothing is known.
215
+ function probeValues(statuses) {
216
+ const entries = Object.entries(statuses);
217
+ const active = entries.filter(([, status]) => status === "active" || status === "available").map(([sourceId]) => sourceId);
218
+ if (active.length === 1)
219
+ return { action: "activate", sourceId: active[0] };
220
+ if (entries.length && entries.every(([, status]) => status === "inactive"))
221
+ return { action: "deactivate" };
222
+ return {};
223
+ }
209
224
  const traces = [];
210
225
  if (!event || typeof event.kind !== "string") {
211
226
  throw new Error("msg.sourceCapability.kind is required");
@@ -353,6 +368,23 @@ function transitionSource(saved, msg, suppliedConfig = {}, nowValue = new Date()
353
368
  }
354
369
  }
355
370
  function acceptObservation(event) {
371
+ if (!state.desired && state.probe && Object.hasOwn(state.probe, event.sourceId)) {
372
+ // The probe's answer, whatever generation the transport echoes.
373
+ if (!Object.hasOwn(OBSERVATION_STATUSES, event.status))
374
+ throw new Error("unknown source observation status");
375
+ const probedAt = (0, observation_time_1.parseObservedAt)(event.observedAt);
376
+ if (probedAt === null || typeof event.observedAt !== "string")
377
+ throw new Error("source observedAt must be an ISO timestamp");
378
+ state.probe[event.sourceId] = event.status;
379
+ trace("probe", "read", null, { sourceId: event.sourceId, status: event.status });
380
+ if (Object.values(state.probe).every((status) => status !== null)) {
381
+ const values = probeValues(state.probe);
382
+ observations.push((0, target_observation_1.targetObservation)("source", (0, observation_time_1.boundObservedAt)(event.observedAt, probedAt, nowMs).observedAt, values));
383
+ state.probe = null;
384
+ trace("probe", "answered", null, values);
385
+ }
386
+ return;
387
+ }
356
388
  if (!Number.isInteger(event.generation) || event.generation < 1) {
357
389
  throw new Error("source observation generation must be a positive integer");
358
390
  }
@@ -494,6 +526,21 @@ function transitionSource(saved, msg, suppliedConfig = {}, nowValue = new Date()
494
526
  state.refreshAsked = true;
495
527
  trace("refresh", "querying", null, { sourceId: state.desired.sourceId });
496
528
  }
529
+ else if (!state.desired && (0, target_observation_1.isProbe)(event)) {
530
+ // The theatre's recovery probe: read every source that can be read, and
531
+ // say what they show. With none, nothing is known.
532
+ const readable = Object.entries(config.sources).filter(([, source]) => source.confirmation !== "unavailable").map(([sourceId]) => sourceId);
533
+ if (readable.length) {
534
+ state.probe = Object.fromEntries(readable.map((sourceId) => [sourceId, null]));
535
+ for (const sourceId of readable)
536
+ commands.push({ sourceId, operation: "observe", requestId: null, generation: 0, attempt: 0 });
537
+ trace("probe", "querying", null, { sources: readable });
538
+ }
539
+ else {
540
+ observations.push((0, target_observation_1.targetObservation)("source", now.toISOString(), {}));
541
+ trace("probe", "answered", "no-readable-source");
542
+ }
543
+ }
497
544
  else if (event.kind === "startup" || event.kind === "refresh") {
498
545
  state.refreshAsked = false;
499
546
  if (state.desired) {
@@ -535,6 +582,6 @@ function transitionSource(saved, msg, suppliedConfig = {}, nowValue = new Date()
535
582
  const outputEvent = (event.kind === "refresh" && state.refreshAsked) || replacedRequest ? null : targetEvent(state, now, config.sources);
536
583
  if (outputEvent)
537
584
  events.push(outputEvent);
538
- return { state, commands, events, traces, status: statusFor(state) };
585
+ return { state, commands, events, observations, traces, status: statusFor(state) };
539
586
  }
540
587
  //# sourceMappingURL=source-capability-controller.js.map
@@ -0,0 +1,14 @@
1
+ export declare function isProbe(event: {
2
+ kind?: unknown;
3
+ requestId?: unknown;
4
+ generation?: unknown;
5
+ }): boolean;
6
+ export interface TargetObservationOutput {
7
+ theatre: {
8
+ kind: "target_observation";
9
+ target: string;
10
+ observedAt: string;
11
+ values: Record<string, unknown>;
12
+ };
13
+ }
14
+ export declare function targetObservation(target: string, observedAt: string, values: Record<string, unknown>): TargetObservationOutput;
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isProbe = isProbe;
4
+ exports.targetObservation = targetObservation;
5
+ // The recovery probe and its answer, for every theatre target owner.
6
+ //
7
+ // After a start with nothing saved, the theatre activity controller sends
8
+ // each owner a refresh with no request (requestId null, generation 0): the
9
+ // probe. An owner with no request of its own answers it by reading its
10
+ // device and reporting what it shows, in the activity profiles' terms, on
11
+ // the output its target states use:
12
+ // msg.theatre = {kind: "target_observation", target, observedAt, values}
13
+ // The activity controller adopts the one activity those observations match,
14
+ // if any, and commands nothing.
15
+ function isProbe(event) {
16
+ return event.kind === "refresh" && (event.requestId === null || event.requestId === undefined || event.requestId === "") &&
17
+ !(Number.isInteger(event.generation) && event.generation >= 1);
18
+ }
19
+ function targetObservation(target, observedAt, values) {
20
+ return { theatre: { kind: "target_observation", target, observedAt, values } };
21
+ }
22
+ //# sourceMappingURL=target-observation.js.map
@@ -25,6 +25,11 @@ export type TheatreInputEvent = {
25
25
  details?: Record<string, unknown>;
26
26
  } | {
27
27
  kind: "startup" | "refresh";
28
+ } | {
29
+ kind: "target_observation";
30
+ target: TheatreTarget;
31
+ observedAt: string;
32
+ values: Record<string, unknown>;
28
33
  } | {
29
34
  kind: "tick";
30
35
  generation?: number;