@avantics/node-red-home-automation 6.2.0 → 6.4.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 (79) hide show
  1. package/README.md +93 -12
  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/ha-discovery.js +3 -2
  13. package/dist/lib/occupancy-fusion.d.ts +1 -0
  14. package/dist/lib/occupancy-fusion.js +15 -2
  15. package/dist/lib/scene.d.ts +9 -1
  16. package/dist/lib/scene.js +61 -8
  17. package/dist/lib/source-capability-controller.d.ts +4 -1
  18. package/dist/lib/source-capability-controller.js +49 -2
  19. package/dist/lib/target-observation.d.ts +14 -0
  20. package/dist/lib/target-observation.js +22 -0
  21. package/dist/lib/theatre-activity-controller.d.ts +5 -0
  22. package/dist/lib/theatre-activity-controller.js +87 -12
  23. package/dist/lib/theatre-state.d.ts +2 -0
  24. package/dist/lib/theatre-state.js +10 -1
  25. package/dist/lib/wled.d.ts +48 -0
  26. package/dist/lib/wled.js +105 -0
  27. package/dist/lib/z2m-power.d.ts +38 -0
  28. package/dist/lib/z2m-power.js +83 -0
  29. package/dist/lib/z2m-sensor.d.ts +37 -0
  30. package/dist/lib/z2m-sensor.js +88 -0
  31. package/dist/nodes/activity-lighting-controller.html +2 -1
  32. package/dist/nodes/apollo-r-pro-1.d.ts +2 -0
  33. package/dist/nodes/apollo-r-pro-1.html +80 -0
  34. package/dist/nodes/apollo-r-pro-1.js +4 -0
  35. package/dist/nodes/avr-controller.html +2 -1
  36. package/dist/nodes/avr-controller.js +1 -1
  37. package/dist/nodes/backlighting-controller.html +2 -1
  38. package/dist/nodes/backlighting-controller.js +3 -2
  39. package/dist/nodes/circadian-policy.html +2 -1
  40. package/dist/nodes/cover-controller.html +2 -1
  41. package/dist/nodes/cover-group.html +2 -1
  42. package/dist/nodes/device-side.d.ts +1 -0
  43. package/dist/nodes/device-side.js +7 -3
  44. package/dist/nodes/display-mode-controller.html +2 -1
  45. package/dist/nodes/display-mode-controller.js +11 -2
  46. package/dist/nodes/esphome-sensor.d.ts +2 -0
  47. package/dist/nodes/esphome-sensor.js +77 -0
  48. package/dist/nodes/everything-presence-one.d.ts +2 -0
  49. package/dist/nodes/everything-presence-one.html +78 -0
  50. package/dist/nodes/everything-presence-one.js +4 -0
  51. package/dist/nodes/house-schedule-mqtt.html +2 -1
  52. package/dist/nodes/motion-policy.html +6 -4
  53. package/dist/nodes/motion-policy.js +10 -1
  54. package/dist/nodes/occupancy-fusion.html +5 -1
  55. package/dist/nodes/occupancy-fusion.js +2 -1
  56. package/dist/nodes/room-controller.html +2 -1
  57. package/dist/nodes/scene.html +25 -4
  58. package/dist/nodes/scene.js +9 -2
  59. package/dist/nodes/shelly-cover.html +2 -1
  60. package/dist/nodes/shelly-switch.html +2 -1
  61. package/dist/nodes/source-capability-controller.html +2 -1
  62. package/dist/nodes/source-capability-controller.js +3 -2
  63. package/dist/nodes/switch-policy.html +2 -1
  64. package/dist/nodes/theatre-activity-controller.html +6 -3
  65. package/dist/nodes/theatre-state-contract.html +2 -1
  66. package/dist/nodes/wled.d.ts +3 -0
  67. package/dist/nodes/wled.html +56 -0
  68. package/dist/nodes/wled.js +53 -0
  69. package/dist/nodes/z2m-cover.html +2 -1
  70. package/dist/nodes/z2m-light.html +4 -2
  71. package/dist/nodes/z2m-light.js +17 -0
  72. package/dist/nodes/z2m-power.d.ts +3 -0
  73. package/dist/nodes/z2m-power.html +58 -0
  74. package/dist/nodes/z2m-power.js +53 -0
  75. package/dist/nodes/z2m-sensor.d.ts +3 -0
  76. package/dist/nodes/z2m-sensor.html +69 -0
  77. package/dist/nodes/z2m-sensor.js +62 -0
  78. package/examples/Scene.json +8 -56
  79. package/package.json +31 -16
package/README.md CHANGED
@@ -27,15 +27,25 @@ Most home automations translate an event directly into a command. This package a
27
27
  - **Scenes that hand everything back:** turn on "Exercise mode" or "Bath" from Home Assistant, and when it ends, by request, a safety timer or a condition in your flow, each light goes back to what it was and motion lighting resumes.
28
28
  - **Recoverable automation:** adopt one fresh, uniquely matching physical activity after lost state; otherwise report the activity as unknown and leave the devices alone until the next request.
29
29
 
30
- ![Architecture diagram. Motion and presence sensors and illuminance feed occupancy-fusion and motion-lighting-policy; wall switch presses come from the shelly-switch adapter to switch-lighting-policy. Both policies send intents to room-lighting-controller, and circadian-lighting-policy, which follows a house-schedule configuration node without wires, sends it a style. The room sends neutral light commands to each light's adapter (z2m-light) and takes back its readings. A cover-controller, which a cover-group can drive, does the same through the z2m-cover and shelly-cover adapters, and pauses motion lighting while a cover moves. Theatre activities: theatre-state-contract passes activity intents to theatre-activity-controller; your flow routes each theatreCommand by target to the equipment controllers (AVR, display mode, source capability, backlighting), which command the AV devices, or to activity-lighting-controller, which holds room lights; both report target state back. The adapters and the theatre contract use the MQTT broker, which carries device topics to and from the Zigbee2MQTT and Shelly devices. Home Assistant is only the panel: it shows state and sends set messages over MQTT.](https://avantics-hq.github.io/node-red-home-automation/images/architecture.svg)
30
+ ![Architecture diagram. Motion and presence sensors, through the z2m-sensor adapter for Zigbee2MQTT ones, and illuminance feed occupancy-fusion and motion-lighting-policy; wall switch presses come from the shelly-switch adapter to switch-lighting-policy. Both policies send intents to room-lighting-controller, and circadian-lighting-policy, which follows a house-schedule configuration node without wires, sends it a style. The room sends neutral light commands to each light's adapter (z2m-light) and takes back its readings. A cover-controller, which a cover-group can drive, does the same through the z2m-cover and shelly-cover adapters, and pauses motion lighting while a cover moves. Theatre activities: theatre-state-contract passes activity intents to theatre-activity-controller; your flow routes each theatreCommand by target to the equipment controllers (AVR, display mode, source capability, backlighting), which command the AV devices, or to activity-lighting-controller, which holds room lights; both report target state back. The adapters and the theatre contract use the MQTT broker, which carries device topics to and from the Zigbee2MQTT, Shelly and WLED devices. Home Assistant is only the panel: it shows state and sends set messages over MQTT.](https://avantics-hq.github.io/node-red-home-automation/images/architecture.svg)
31
31
 
32
32
  Each controller keeps the desired and the observed state, sends semantic
33
33
  commands, and reports done only when fresh observations confirm them.
34
34
 
35
35
  ## Included nodes
36
36
 
37
- The nodes come in five groups. Each group has an importable example flow
38
- (**Import → Examples** in the Node-RED editor).
37
+ In the editor's palette the nodes sit in five categories, by kind:
38
+
39
+ | Palette category | Nodes (palette label: type) |
40
+ |---|---|
41
+ | home devices | zigbee2mqtt light: `home-z2m-light`; zigbee2mqtt cover: `home-z2m-cover`; zigbee2mqtt sensor: `home-z2m-sensor`; zigbee2mqtt power: `home-z2m-power`; shelly switch: `home-shelly-switch`; shelly cover: `home-shelly-cover`; wled: `home-wled`; everything presence one: `home-everything-presence-one`; apollo r pro-1: `home-apollo-r-pro-1` |
42
+ | home lighting | room lighting: `home-room-lighting-controller`; occupancy: `home-occupancy-fusion`; motion policy: `home-motion-lighting-policy`; switch policy: `home-switch-lighting-policy`; circadian policy: `home-circadian-lighting-policy`; scene: `home-scene` |
43
+ | home covers | cover: `home-cover-controller`; cover group: `home-cover-group` |
44
+ | home theatre | theatre activity: `home-theatre-activity-controller`; theatre contract: `home-theatre-state-contract`; display: `home-display-mode-controller`; receiver: `home-avr-controller`; source: `home-source-capability-controller`; backlighting: `home-backlighting-controller`; activity lighting: `home-activity-lighting-controller` |
45
+ | home house | `home-house-schedule` (its configuration node); house schedule mqtt: `home-house-schedule-mqtt` |
46
+
47
+ Below, they come in five groups by what they do together. Each group has an
48
+ importable example flow (**Import → Examples** in the Node-RED editor).
39
49
 
40
50
  ### Room lighting
41
51
 
@@ -85,7 +95,9 @@ restyle the light already shows.
85
95
  | Node | Purpose |
86
96
  |---|---|
87
97
  | `home-occupancy-fusion` | Combines PIR motion with optional presence sensing. |
88
- | `home-motion-lighting-policy` | Converts occupancy and illuminance into lighting intent. A `delay` message (in seconds) or `illuminance-cut-off` message overrides its settings until they are changed and redeployed. |
98
+ | `home-z2m-sensor` | Connects one Zigbee2MQTT motion, presence or light sensor: its occupancy and presence to occupancy fusion, its light level to the motion policy. |
99
+ | `home-everything-presence-one`, `home-apollo-r-pro-1` | Connect those ESPHome presence sensors the same way, one node per device, finding their entities from the device's own MQTT discovery (or the node's preset without it); while the device is online, its retained state at a restart is the room's starting point. |
100
+ | `home-motion-lighting-policy` | Converts occupancy and illuminance into lighting intent. A `delay` message (in seconds) or `illuminance-cut-off` message overrides its settings until they are changed and redeployed. The house-wide `global-enabled` is deprecated and removed in 7.0: send `area-enabled` to each policy instead. |
89
101
  | `home-switch-lighting-policy` | Converts raw edges or pre-classified button actions into lighting intent while exposing input freshness and availability. |
90
102
  | `home-circadian-lighting-policy` | Styles rooms over the day: brightness and colour temperature from wake and bed times, sleep mode, and circadian and sleep switches for Home Assistant. |
91
103
  | `home-room-lighting-controller` | Owns the room's light commands, manual and held lights, and lighting state, and applies the style it is sent. |
@@ -141,8 +153,8 @@ Example: [`House schedule.json`](https://github.com/avantics-hq/node-red-home-au
141
153
  A scene, such as "Exercise mode" or "Bath", takes some of a room's lights for
142
154
  a while: it holds each on or off with the values it gives them, and pauses
143
155
  motion lighting. It ends by request, by its safety timer (4 hours by default;
144
- 0 turns it off), or when your flow sends it an end, such as when a trainer's
145
- power falls. Each room then gives its lights back what they were (see "Room
156
+ 0 turns it off), when a device's power, from a power meter node on its plug,
157
+ stays below its End below for a while, or when your flow sends it an end. Each room then gives its lights back what they were (see "Room
146
158
  light control"): a light the room was running is the room's again, on or off
147
159
  as it was, in the room's style as it is now; one that was off goes off; one a
148
160
  person had set gets their values back. A light a person changes during the
@@ -165,7 +177,7 @@ two rooms may each have a `main`:
165
177
  ```
166
178
 
167
179
  Start it with `msg.scene = {kind: "start"}` and end it with
168
- `msg.scene = {kind: "end", by: "trainer off"}` (`by` is optional and shows
180
+ `msg.scene = {kind: "end", by: "door opened"}` (`by` is optional and shows
169
181
  on its status). Example: [`Scene.json`](https://github.com/avantics-hq/node-red-home-automation/blob/main/examples/Scene.json).
170
182
 
171
183
  | Node | Purpose |
@@ -184,6 +196,8 @@ on output 2. Example: [`Home theatre equipment.json`](https://github.com/avantic
184
196
  | `home-display-mode-controller` | Coordinates TV, projector, and screen transitions. |
185
197
  | `home-source-capability-controller` | Gates source readiness on fresh availability, active-device, application or playback evidence. |
186
198
  | `home-backlighting-controller` | Owns TV-backlight power with observation-gated confirmation. |
199
+ | `home-z2m-power` | Reads a Zigbee2MQTT plug or meter's power as `msg.power`: the display controller's projector power, or a scene's End below. |
200
+ | `home-wled` | Connects a WLED strip to a backlighting controller over WLED's own MQTT: on and off, read back from the brightness WLED reports. |
187
201
 
188
202
  The display controller reads the projector's power from any meter or adapter:
189
203
  send `msg.display = {kind: "observed", device: "projector", power: "on"}`
@@ -311,7 +325,7 @@ Example: [`Cover control.json`](https://github.com/avantics-hq/node-red-home-aut
311
325
 
312
326
  ## Requirements
313
327
 
314
- - Node.js 24 or newer
328
+ - Node.js 22.9 or newer, as Node-RED 5 (releases 6.0.0 to 6.3.0 asked for 24)
315
329
  - Node-RED 5.0.0 or newer
316
330
 
317
331
  ## Install
@@ -338,7 +352,7 @@ the checksum file to check those. Install a downloaded tarball through
338
352
  **Manage palette → Install → Upload module**, or with:
339
353
 
340
354
  ```sh
341
- npm install /path/to/avantics-node-red-home-automation-6.2.0.tgz
355
+ npm install /path/to/avantics-node-red-home-automation-6.4.0.tgz
342
356
  ```
343
357
 
344
358
  Add the installed nodes from the **home automation** section of the Node-RED palette, then configure the room, device hosts, MQTT topics, source mappings, and timing limits for your deployment.
@@ -353,6 +367,73 @@ offers the first broker in your flows. Nodes saved before 6.2 keep working
353
367
  through their MQTT in and out nodes until you choose one; the example flows
354
368
  use one broker node, "your MQTT broker", whose host you set.
355
369
 
370
+ ### 6.4.0
371
+
372
+ Nothing to migrate from 6.3.0.
373
+
374
+ **Node.js 22.9 or newer again.** The package's minimum is back to Node-RED 5's
375
+ own, 22.9; releases 6.0.0 to 6.3.0 asked for 24. Node.js 24 still works. This
376
+ also clears the Flow Library scorecard's Node.js warning.
377
+
378
+ **The nodes are grouped by kind.** The editor's palette has five categories
379
+ (home devices, home lighting, home covers, home theatre, home house) instead
380
+ of one, and every node has a short palette label, such as "zigbee2mqtt light"
381
+ or "receiver". Node types are unchanged, so saved flows are untouched. The
382
+ README and the documentation site list the nodes the same way.
383
+
384
+ **Deprecated: the house-wide motion enable.** `global-enabled`, sent to any
385
+ motion lighting policy, still switches motion lighting for every policy, but
386
+ each policy now warns once per deploy. Send `area-enabled` to each motion
387
+ lighting policy instead; `global-enabled` is removed in 7.0.
388
+
389
+ ### 6.3.0
390
+
391
+ Nothing to migrate from 6.2.0. New device nodes replace hand-wired MQTT in,
392
+ change and function nodes for sensors, power meters and a WLED backlight, and
393
+ the theatre now recovers its activity after a restart.
394
+
395
+ **Sensors.** Each feeds occupancy fusion (motion and presence, output 1) and
396
+ the motion lighting policy (light level in lux, output 2), sends only changes,
397
+ and shows offline on its status:
398
+
399
+ - **zigbee2mqtt sensor** (`home-z2m-sensor`), one per Zigbee2MQTT motion or
400
+ presence sensor, with an "Occupancy is" setting for presence-only devices. A
401
+ retained occupancy is never acted on.
402
+ - **Everything Presence One** and **Apollo R PRO-1** (ESPHome), one node per
403
+ device. Each finds its sensors from the device's own MQTT discovery, so a
404
+ firmware rename can't break it, and falls back to known entity names
405
+ without it. Turn on `mqtt: discovery: true` in the device's ESPHome
406
+ configuration to use discovery.
407
+ - **Occupancy fusion takes a start-up baseline** from the ESPHome nodes: a room
408
+ empty at start waits out its vacancy time, and an occupied one switches
409
+ nothing on.
410
+
411
+ **Power.** A **zigbee2mqtt power** node (`home-z2m-power`) reports a plug's
412
+ watts. The display controller takes it as the projector's power, and a scene's
413
+ new **End below** setting ends the scene once the device has been used and
414
+ then stays below the threshold for the set time.
415
+
416
+ **WLED.** A **wled** node (`home-wled`) drives a WLED strip for the
417
+ backlighting controller: on and off, and its brightness as the reading. WLED
418
+ can't be asked for its state over MQTT, so after a restart its reading comes
419
+ at its next change.
420
+
421
+ **The theatre after a restart.** With nothing saved, the display, receiver,
422
+ source and backlighting controllers now answer the activity controller's
423
+ probe with what their devices show, and the theatre adopts the one activity
424
+ that matches, commanding nothing. It needs the display and receiver to have
425
+ answered; a device that can't be asked, such as a WLED backlight, shows as
426
+ unobserved until it reports.
427
+
428
+ Also changed:
429
+
430
+ - A theatre light that never reports ends **unobserved** after the
431
+ confirmation timeout, leaving the theatre ready but degraded instead of
432
+ confirming forever, and a Zigbee2MQTT group with no state says to set
433
+ `retain: true` for it (#186).
434
+ - Each device node's reference links to its maker's or project's
435
+ documentation.
436
+
356
437
  ### 6.2.0
357
438
 
358
439
  Nothing to migrate from 6.1.0: flows wired the 6.1.0 way keep working. Two
@@ -909,9 +990,9 @@ Without a context store, after a node is redeployed or Node-RED restarts:
909
990
  times, set from Home Assistant or a message.
910
991
  - **The theatre starts its counts again:** its counters and operational SLO
911
992
  samples restart, and the activity controller no longer knows the current
912
- activity. The activity is unknown, and the devices are left alone, until the
913
- next request. Working the activity out from what the devices report after a
914
- cold start is [issue #179](https://github.com/avantics-hq/node-red-home-automation/issues/179).
993
+ activity. It works it out again from what the devices show, when they show
994
+ exactly one activity; otherwise it is unknown, and the devices are left
995
+ alone, until the next request.
915
996
  - **Work in progress is not recovered:** a motion off-timer that was running,
916
997
  or a theatre device change still being confirmed. The node starts afresh
917
998
  and goes by what it next observes.
@@ -54,6 +54,7 @@ export interface ActivityLightingState {
54
54
  reported?: Record<string, string[]>;
55
55
  held?: string[];
56
56
  overridden?: string[];
57
+ unobserved?: string[];
57
58
  }
58
59
  export type ActivityLightingEvent = {
59
60
  kind: "intent";
@@ -105,7 +105,8 @@ function initialState(saved = {}, profiles = {}) {
105
105
  reported: Object.fromEntries(Object.entries(saved.reported || {})
106
106
  .filter(([, fields]) => Array.isArray(fields)).map(([target, fields]) => [target, fields.map(String)])),
107
107
  held: Array.isArray(saved.held) ? saved.held.map(String) : [],
108
- overridden: Array.isArray(saved.overridden) ? saved.overridden.map(String) : []
108
+ overridden: Array.isArray(saved.overridden) ? saved.overridden.map(String) : [],
109
+ unobserved: Array.isArray(saved.unobserved) ? saved.unobserved.map(String) : []
109
110
  };
110
111
  }
111
112
  function profileFor(state, config) {
@@ -144,7 +145,8 @@ function commandFor(state, config, operation, attempt) {
144
145
  function statusFor(state) {
145
146
  return {
146
147
  phase: state.phase,
147
- text: `${state.desired?.profile || "none"}: ${state.phase}`
148
+ text: `${state.desired?.profile || "none"}: ${state.phase}` +
149
+ (state.unobserved?.length ? ` · ${state.unobserved.length} unobserved` : "")
148
150
  };
149
151
  }
150
152
  function transitionActivityLighting(saved, msg, suppliedConfig = {}, nowValue = new Date()) {
@@ -206,6 +208,8 @@ function transitionActivityLighting(saved, msg, suppliedConfig = {}, nowValue =
206
208
  }
207
209
  for (const target of profile.targets) {
208
210
  const observation = state.observed[target];
211
+ if (!observation && state.unobserved?.includes(target))
212
+ continue;
209
213
  if (!observation) {
210
214
  state.phase = state.phase === "transitioning" ? "transitioning" : "confirming";
211
215
  return;
@@ -260,7 +264,8 @@ function transitionActivityLighting(saved, msg, suppliedConfig = {}, nowValue =
260
264
  trace("lighting", "ready", null, {
261
265
  profile: state.desired.profile,
262
266
  matched: counts.matched,
263
- preserved: counts.preserved
267
+ preserved: counts.preserved,
268
+ ...(state.unobserved?.length ? { unobserved: state.unobserved } : {})
264
269
  });
265
270
  }
266
271
  function acceptIntent(intent) {
@@ -313,6 +318,7 @@ function transitionActivityLighting(saved, msg, suppliedConfig = {}, nowValue =
313
318
  state.generation = intent.generation;
314
319
  state.observed = {};
315
320
  state.held = [];
321
+ state.unobserved = [];
316
322
  state.pending = null;
317
323
  state.failure = null;
318
324
  state.blockedGeneration = null;
@@ -372,6 +378,9 @@ function transitionActivityLighting(saved, msg, suppliedConfig = {}, nowValue =
372
378
  showsLast: observation.showsLast === true,
373
379
  observedAt: bounded.observedAt
374
380
  };
381
+ if (state.unobserved?.includes(observation.target)) {
382
+ state.unobserved = state.unobserved.filter((target) => target !== observation.target);
383
+ }
375
384
  trace("observation", "accepted", null, { target: observation.target });
376
385
  reconcile();
377
386
  }
@@ -428,10 +437,24 @@ function transitionActivityLighting(saved, msg, suppliedConfig = {}, nowValue =
428
437
  trace("tick", "ignored", "stale-generation");
429
438
  }
430
439
  else if (nowMs >= state.pending.deadlineAt) {
431
- if (state.pending.attempt < config.maxAttempts)
432
- issueApply(state.pending.attempt + 1);
433
- else
434
- fail("confirmation-timeout");
440
+ // A light with no reading at all by now isn't going to answer: it is
441
+ // unobserved, not re-applied, and fails nothing. The others go on as
442
+ // before: re-applied, then failed.
443
+ const attempt = state.pending.attempt;
444
+ const missing = profileFor(state, config).targets.filter((target) => !state.observed[target]);
445
+ if (missing.length) {
446
+ state.unobserved = [...new Set([...(state.unobserved ?? []), ...missing])];
447
+ trace("lighting", "unobserved", "no-reading", { targets: missing });
448
+ reconcile();
449
+ }
450
+ // Still waiting on a light that reported (reconcile ends the deadline
451
+ // once ready or a person's).
452
+ if (state.pending) {
453
+ if (attempt < config.maxAttempts)
454
+ issueApply(attempt + 1);
455
+ else
456
+ fail("confirmation-timeout");
457
+ }
435
458
  }
436
459
  }
437
460
  else if (event.kind === "refresh" && state.desired && state.phase === "ready" && !state.pending &&
@@ -448,6 +471,7 @@ function transitionActivityLighting(saved, msg, suppliedConfig = {}, nowValue =
448
471
  // Since start: what each light reports is learned again.
449
472
  if (event.kind === "startup")
450
473
  state.reported = {};
474
+ state.unobserved = [];
451
475
  state.pending = null;
452
476
  if (state.desired) {
453
477
  if (profileFor(state, config).targets.length === 0)
@@ -455,9 +479,11 @@ function transitionActivityLighting(saved, msg, suppliedConfig = {}, nowValue =
455
479
  else {
456
480
  commands.push(commandFor(state, config, "observe", 0));
457
481
  state.phase = "confirming";
458
- // After a restart nothing else would end an unanswered observe: give
459
- // it a deadline, so it re-applies and then fails as a live request.
460
- if ((event.kind === "startup" || adopted) && state.blockedGeneration !== state.generation) {
482
+ // After a restart or a refresh nothing else would end an unanswered
483
+ // observe: give it a deadline, by which a light with no reading is
484
+ // unobserved, and one that doesn't match is re-applied and then
485
+ // failed, as for a live request.
486
+ if (state.blockedGeneration !== state.generation) {
461
487
  state.pending = { attempt: 0, deadlineAt: nowMs + config.confirmationTimeoutMs };
462
488
  }
463
489
  trace(event.kind, "observing", null, { profile: state.desired.profile });
@@ -493,6 +519,7 @@ function transitionActivityLighting(saved, msg, suppliedConfig = {}, nowValue =
493
519
  matched: counts.matched,
494
520
  preserved: counts.preserved,
495
521
  expected: profileFor(state, config).targets.length,
522
+ ...(state.unobserved?.length ? { unobserved: [...state.unobserved] } : {}),
496
523
  metrics: {
497
524
  attempts: state.pending?.attempt ?? 0,
498
525
  retries: Math.max(0, (state.pending?.attempt ?? 1) - 1),
@@ -1,3 +1,4 @@
1
+ import { type TargetObservationOutput } from "./target-observation";
1
2
  import type { TraceEntry } from "./bounded-trace";
2
3
  import { type TargetStateEvent } from "./target-state";
3
4
  import { type AvrPower, type MainZone } from "./denon-protocol";
@@ -71,6 +72,7 @@ export interface AvrState {
71
72
  lastAttempt: number;
72
73
  adoptedGeneration: number | null;
73
74
  volumeUnits: "dB";
75
+ probeAt?: string | null;
74
76
  }
75
77
  export type AvrInputEvent = {
76
78
  kind: "startup";
@@ -140,6 +142,7 @@ export declare function transitionAvr(saved: Partial<AvrState> | undefined, msg:
140
142
  targetStates: {
141
143
  theatre: AvrTargetState;
142
144
  }[];
145
+ observations: TargetObservationOutput[];
143
146
  traces: TraceEntry<Record<string, unknown>>[];
144
147
  status: {
145
148
  phase: string;
@@ -4,6 +4,7 @@ exports.REMOVED_VOLUME_VALUE = exports.parseAvrLine = exports.formatVolumeComman
4
4
  exports.createAvrState = createAvrState;
5
5
  exports.normaliseAvrConfig = normaliseAvrConfig;
6
6
  exports.transitionAvr = transitionAvr;
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 target_state_1 = require("./target-state");
@@ -91,7 +92,8 @@ function createAvrState(_config, saved = {}) {
91
92
  lastAttempt: Number.isInteger(saved.lastAttempt) && (saved.lastAttempt ?? -1) >= 0
92
93
  ? saved.lastAttempt
93
94
  : 0,
94
- adoptedGeneration: (0, adopted_request_1.savedAdoptedGeneration)(saved)
95
+ adoptedGeneration: (0, adopted_request_1.savedAdoptedGeneration)(saved),
96
+ probeAt: typeof saved.probeAt === "string" ? saved.probeAt : null
95
97
  };
96
98
  }
97
99
  function sameVolume(left, right) {
@@ -140,6 +142,8 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
140
142
  const commands = [];
141
143
  const events = [];
142
144
  const targetStates = [];
145
+ // Its answer to the theatre's recovery probe, for output 2 as the target states.
146
+ const observations = [];
143
147
  const traces = [];
144
148
  const event = msg.avr || { kind: "unknown" };
145
149
  const previousPhase = state.phase;
@@ -506,6 +510,12 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
506
510
  trace("refresh", "adopted", reason, { power: event.power, source: event.source || null, generation: adoptable.generation });
507
511
  }
508
512
  if (event.kind === "refresh" && !adopted) {
513
+ // The theatre's recovery probe: the query below, answered with what the
514
+ // receiver then reports.
515
+ if (!state.desired && (0, target_observation_1.isProbe)(event)) {
516
+ state.probeAt = now.toISOString();
517
+ trace("probe", "querying");
518
+ }
509
519
  // Re-read the receiver without touching work in flight: desired state,
510
520
  // pending commands, the volume request and the phase all carry on.
511
521
  commands.push({
@@ -626,6 +636,18 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
626
636
  reconcile();
627
637
  forceStateEvent = true;
628
638
  }
639
+ if (!state.desired && state.probeAt) {
640
+ // Its power since the probe, and its input too when it's on: a receiver
641
+ // in standby needn't say which input it's on.
642
+ const since = Date.parse(state.probeAt);
643
+ const fresh = (field) => state.fieldObservedAt[field] !== null && Date.parse(state.fieldObservedAt[field]) >= since;
644
+ if (fresh("power") && (state.observed.power === "standby" || fresh("source"))) {
645
+ const values = { power: state.observed.power, source: state.observed.source, mainZone: state.observed.mainZone };
646
+ observations.push((0, target_observation_1.targetObservation)("avr", now.toISOString(), values));
647
+ state.probeAt = null;
648
+ trace("probe", "answered", null, values);
649
+ }
650
+ }
629
651
  }
630
652
  else if (event.kind === "intent") {
631
653
  const reason = validateIntent(event);
@@ -963,6 +985,6 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
963
985
  targetStates.push({ theatre });
964
986
  }
965
987
  }
966
- return { state, commands, events, targetStates, traces, status };
988
+ return { state, commands, events, targetStates, observations, traces, status };
967
989
  }
968
990
  //# sourceMappingURL=avr-controller.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";
@@ -40,6 +41,7 @@ export interface BacklightingState {
40
41
  lastAttempt: number;
41
42
  adoptedGeneration: number | null;
42
43
  carried?: Carried | null;
44
+ probing?: boolean;
43
45
  }
44
46
  export type BacklightingEvent = {
45
47
  kind: "intent";
@@ -73,9 +75,9 @@ export interface BacklightingMessage {
73
75
  }
74
76
  export interface BacklightingCommand {
75
77
  operation: "set_power" | "observe";
76
- requestId: string;
78
+ requestId: string | null;
77
79
  generation: number;
78
- power: BacklightingPower;
80
+ power: BacklightingPower | null;
79
81
  attempt: number;
80
82
  }
81
83
  export interface BacklightingOutputEvent {
@@ -95,6 +97,7 @@ export declare function transitionBacklighting(saved: Partial<BacklightingState>
95
97
  state: BacklightingState;
96
98
  commands: BacklightingCommand[];
97
99
  events: BacklightingOutputEvent[];
100
+ observations: TargetObservationOutput[];
98
101
  traces: TraceEntry<Record<string, unknown>>[];
99
102
  status: {
100
103
  phase: string;
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.normaliseBacklightingConfig = normaliseBacklightingConfig;
4
4
  exports.transitionBacklighting = transitionBacklighting;
5
+ const target_observation_1 = require("./target-observation");
5
6
  const adopted_request_1 = require("./adopted-request");
6
7
  const settings_1 = require("./settings");
7
8
  const observation_time_1 = require("./observation-time");
@@ -28,7 +29,8 @@ function initialState(saved = {}) {
28
29
  ? saved.lastAttempt
29
30
  : 0,
30
31
  adoptedGeneration: (0, adopted_request_1.savedAdoptedGeneration)(saved),
31
- carried: (0, adopted_request_1.savedCarried)(saved)
32
+ carried: (0, adopted_request_1.savedCarried)(saved),
33
+ probing: saved.probing === true
32
34
  };
33
35
  }
34
36
  function commandFor(state, operation, attempt) {
@@ -58,6 +60,8 @@ function transitionBacklighting(saved, msg, suppliedConfig = {}, nowValue = new
58
60
  const event = msg?.backlighting;
59
61
  const commands = [];
60
62
  const events = [];
63
+ // Its answer to the theatre's recovery probe, for output 2 as the events.
64
+ const observations = [];
61
65
  const traces = [];
62
66
  if (!event || typeof event.kind !== "string")
63
67
  throw new Error("msg.backlighting.kind is required");
@@ -121,6 +125,21 @@ function transitionBacklighting(saved, msg, suppliedConfig = {}, nowValue = new
121
125
  trace("intent", "accepted", null, { power: intent.power, generation: intent.generation });
122
126
  }
123
127
  function acceptObservation(observation) {
128
+ if (!state.desired && state.probing) {
129
+ // The probe's answer, whatever generation the transport echoes.
130
+ if (!Object.hasOwn(POWERS, observation.power))
131
+ throw new Error("unknown observed backlighting power");
132
+ const parsedAt = (0, observation_time_1.parseObservedAt)(observation.observedAt);
133
+ if (parsedAt === null || typeof observation.observedAt !== "string") {
134
+ throw new Error("backlighting observedAt must be an ISO timestamp");
135
+ }
136
+ const observedAt = (0, observation_time_1.boundObservedAt)(observation.observedAt, parsedAt, nowMs).observedAt;
137
+ state.observed = { power: observation.power, observedAt };
138
+ state.probing = false;
139
+ observations.push((0, target_observation_1.targetObservation)("backlighting", observedAt, { power: observation.power }));
140
+ trace("probe", "answered", null, { power: observation.power });
141
+ return;
142
+ }
124
143
  if (!Number.isInteger(observation.generation) || observation.generation < 1) {
125
144
  throw new Error("backlighting observation generation must be a positive integer");
126
145
  }
@@ -245,6 +264,12 @@ function transitionBacklighting(saved, msg, suppliedConfig = {}, nowValue = new
245
264
  trace("command", "emitted", null, { operation: "observe", power: state.desired.power });
246
265
  }
247
266
  }
267
+ else if (!state.desired && (0, target_observation_1.isProbe)(event)) {
268
+ // The theatre's recovery probe: read the backlight and say what it shows.
269
+ state.probing = true;
270
+ commands.push({ operation: "observe", requestId: null, generation: 0, power: null, attempt: 0 });
271
+ trace("probe", "observing");
272
+ }
248
273
  else if (event.kind === "refresh" && state.desired && state.phase === "ready" && !state.pending) {
249
274
  // A settled, ready target is re-read without leaving ready, as the
250
275
  // display, source and receiver are: its target state follows the
@@ -309,6 +334,6 @@ function transitionBacklighting(saved, msg, suppliedConfig = {}, nowValue = new
309
334
  });
310
335
  events.push({ theatre });
311
336
  }
312
- return { state, commands, events, traces, status: statusFor(state) };
337
+ return { state, commands, events, observations, traces, status: statusFor(state) };
313
338
  }
314
339
  //# sourceMappingURL=backlighting-controller.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 PowerReading } from "./power-reading";
@@ -84,6 +85,7 @@ export interface DisplayState {
84
85
  fallbackUsed: boolean;
85
86
  adoptedGeneration: number | null;
86
87
  carried?: Carried | null;
88
+ probeAt?: string | null;
87
89
  discovery?: {
88
90
  attempt: number;
89
91
  nextAt: number;
@@ -139,6 +141,7 @@ export declare function transitionDisplay(saved: Partial<DisplayState> | undefin
139
141
  targetStates: {
140
142
  theatre: DisplayTargetState;
141
143
  }[];
144
+ observations: TargetObservationOutput[];
142
145
  traces: TraceEntry<Record<string, unknown>>[];
143
146
  status: {
144
147
  phase: string;
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.classifyProjectorPower = classifyProjectorPower;
4
4
  exports.normaliseConfig = normaliseConfig;
5
5
  exports.transitionDisplay = transitionDisplay;
6
+ const target_observation_1 = require("./target-observation");
6
7
  const adopted_request_1 = require("./adopted-request");
7
8
  const settings_1 = require("./settings");
8
9
  const observation_time_1 = require("./observation-time");
@@ -32,6 +33,7 @@ function initialState(saved = {}) {
32
33
  fallbackUsed: saved.fallbackUsed === true,
33
34
  adoptedGeneration: (0, adopted_request_1.savedAdoptedGeneration)(saved),
34
35
  carried: (0, adopted_request_1.savedCarried)(saved),
36
+ probeAt: typeof saved.probeAt === "string" ? saved.probeAt : null,
35
37
  ...(saved.discovery && Number.isFinite(saved.discovery.nextAt) ? { discovery: { ...saved.discovery } } : {})
36
38
  };
37
39
  }
@@ -160,22 +162,26 @@ function normaliseConfig(config = {}) {
160
162
  projectorPowerFallback: (0, settings_1.booleanSetting)(config.projectorPowerFallback, "projector power fallback", false)
161
163
  };
162
164
  }
165
+ // Whether the devices show a mode: what each mode sets them to.
166
+ function modeShown(mode, observed, config) {
167
+ if (mode === "tv") {
168
+ return observed.tv?.power === "on" &&
169
+ observed.projector?.power === "standby" &&
170
+ screenClosed(observed.screen, config);
171
+ }
172
+ if (mode === "projector") {
173
+ return observed.tv?.power === "standby" &&
174
+ observed.projector?.power === "on" &&
175
+ screenOpen(observed.screen, config);
176
+ }
177
+ return observed.tv?.power === "standby" &&
178
+ observed.projector?.power === "standby" &&
179
+ screenClosed(observed.screen, config);
180
+ }
163
181
  function modeSatisfied(state, config) {
164
182
  if (!state.desired || !allSeen(state))
165
183
  return false;
166
- if (state.desired.mode === "tv") {
167
- return state.observed.tv?.power === "on" &&
168
- state.observed.projector?.power === "standby" &&
169
- screenClosed(state.observed.screen, config);
170
- }
171
- if (state.desired.mode === "projector") {
172
- return state.observed.tv?.power === "standby" &&
173
- state.observed.projector?.power === "on" &&
174
- screenOpen(state.observed.screen, config);
175
- }
176
- return state.observed.tv?.power === "standby" &&
177
- state.observed.projector?.power === "standby" &&
178
- screenClosed(state.observed.screen, config);
184
+ return modeShown(state.desired.mode, state.observed, config);
179
185
  }
180
186
  function transitionDisplay(saved, msg, suppliedConfig = {}, now = new Date()) {
181
187
  const config = normaliseConfig(suppliedConfig);
@@ -197,6 +203,8 @@ function transitionDisplay(saved, msg, suppliedConfig = {}, now = new Date()) {
197
203
  const commands = [];
198
204
  const events = [];
199
205
  const targetStates = [];
206
+ // Its answer to the theatre's recovery probe, for output 2 as the target states.
207
+ const observations = [];
200
208
  const traces = [];
201
209
  function trace(name, outcome, reason = null, details = {}) {
202
210
  traces.push({ event: name, outcome, reason, details });
@@ -641,8 +649,15 @@ function transitionDisplay(saved, msg, suppliedConfig = {}, now = new Date()) {
641
649
  else if (event.kind === "refresh") {
642
650
  // Re-confirm a settled display from fresh readings; its target state
643
651
  // follows them. These queries are not discovery, so a failed one is
644
- // ignored rather than failing the request.
645
- if (state.desired && state.phase === "ready" && !state.pending) {
652
+ // ignored rather than failing the request. The theatre's recovery probe
653
+ // reads every device the same way, and is answered below.
654
+ if (!state.desired && (0, target_observation_1.isProbe)(event)) {
655
+ state.probeAt = now.toISOString();
656
+ for (const device of DEVICES)
657
+ commands.push(queryFor(state, device));
658
+ trace("probe", "querying");
659
+ }
660
+ else if (state.desired && state.phase === "ready" && !state.pending) {
646
661
  for (const device of DEVICES)
647
662
  commands.push(queryFor(state, device));
648
663
  trace("refresh", "querying");
@@ -716,6 +731,18 @@ function transitionDisplay(saved, msg, suppliedConfig = {}, now = new Date()) {
716
731
  fallbackUsed: state.fallbackUsed
717
732
  }
718
733
  }));
719
- return { state, commands, events, targetStates, traces, status: statusFor(state) };
734
+ if (!state.desired && state.probeAt) {
735
+ // Every device read since the probe: the one mode they show, by the
736
+ // modes' own definitions, or none.
737
+ const since = Date.parse(state.probeAt);
738
+ if (DEVICES.every((device) => state.observed[device] && Date.parse(state.observed[device].observedAt) >= since)) {
739
+ const shown = Object.keys(MODES).filter((mode) => modeShown(mode, state.observed, config));
740
+ const values = { mode: shown.length === 1 ? shown[0] : null };
741
+ observations.push((0, target_observation_1.targetObservation)("display", now.toISOString(), values));
742
+ state.probeAt = null;
743
+ trace("probe", "answered", null, values);
744
+ }
745
+ }
746
+ return { state, commands, events, targetStates, observations, traces, status: statusFor(state) };
720
747
  }
721
748
  //# sourceMappingURL=display-mode-controller.js.map