@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
package/README.md CHANGED
@@ -27,7 +27,7 @@ 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.
@@ -85,6 +85,8 @@ restyle the light already shows.
85
85
  | Node | Purpose |
86
86
  |---|---|
87
87
  | `home-occupancy-fusion` | Combines PIR motion with optional presence sensing. |
88
+ | `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. |
89
+ | `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. |
88
90
  | `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. |
89
91
  | `home-switch-lighting-policy` | Converts raw edges or pre-classified button actions into lighting intent while exposing input freshness and availability. |
90
92
  | `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. |
@@ -141,8 +143,8 @@ Example: [`House schedule.json`](https://github.com/avantics-hq/node-red-home-au
141
143
  A scene, such as "Exercise mode" or "Bath", takes some of a room's lights for
142
144
  a while: it holds each on or off with the values it gives them, and pauses
143
145
  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
146
+ 0 turns it off), when a device's power, from a power meter node on its plug,
147
+ 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
148
  light control"): a light the room was running is the room's again, on or off
147
149
  as it was, in the room's style as it is now; one that was off goes off; one a
148
150
  person had set gets their values back. A light a person changes during the
@@ -165,7 +167,7 @@ two rooms may each have a `main`:
165
167
  ```
166
168
 
167
169
  Start it with `msg.scene = {kind: "start"}` and end it with
168
- `msg.scene = {kind: "end", by: "trainer off"}` (`by` is optional and shows
170
+ `msg.scene = {kind: "end", by: "door opened"}` (`by` is optional and shows
169
171
  on its status). Example: [`Scene.json`](https://github.com/avantics-hq/node-red-home-automation/blob/main/examples/Scene.json).
170
172
 
171
173
  | Node | Purpose |
@@ -184,6 +186,8 @@ on output 2. Example: [`Home theatre equipment.json`](https://github.com/avantic
184
186
  | `home-display-mode-controller` | Coordinates TV, projector, and screen transitions. |
185
187
  | `home-source-capability-controller` | Gates source readiness on fresh availability, active-device, application or playback evidence. |
186
188
  | `home-backlighting-controller` | Owns TV-backlight power with observation-gated confirmation. |
189
+ | `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. |
190
+ | `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
191
 
188
192
  The display controller reads the projector's power from any meter or adapter:
189
193
  send `msg.display = {kind: "observed", device: "projector", power: "on"}`
@@ -338,7 +342,7 @@ the checksum file to check those. Install a downloaded tarball through
338
342
  **Manage palette → Install → Upload module**, or with:
339
343
 
340
344
  ```sh
341
- npm install /path/to/avantics-node-red-home-automation-6.2.0.tgz
345
+ npm install /path/to/avantics-node-red-home-automation-6.3.0.tgz
342
346
  ```
343
347
 
344
348
  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 +357,54 @@ offers the first broker in your flows. Nodes saved before 6.2 keep working
353
357
  through their MQTT in and out nodes until you choose one; the example flows
354
358
  use one broker node, "your MQTT broker", whose host you set.
355
359
 
360
+ ### 6.3.0
361
+
362
+ Nothing to migrate from 6.2.0. New device nodes replace hand-wired MQTT in,
363
+ change and function nodes for sensors, power meters and a WLED backlight, and
364
+ the theatre now recovers its activity after a restart.
365
+
366
+ **Sensors.** Each feeds occupancy fusion (motion and presence, output 1) and
367
+ the motion lighting policy (light level in lux, output 2), sends only changes,
368
+ and shows offline on its status:
369
+
370
+ - **zigbee2mqtt sensor** (`home-z2m-sensor`), one per Zigbee2MQTT motion or
371
+ presence sensor, with an "Occupancy is" setting for presence-only devices. A
372
+ retained occupancy is never acted on.
373
+ - **Everything Presence One** and **Apollo R PRO-1** (ESPHome), one node per
374
+ device. Each finds its sensors from the device's own MQTT discovery, so a
375
+ firmware rename can't break it, and falls back to known entity names
376
+ without it. Turn on `mqtt: discovery: true` in the device's ESPHome
377
+ configuration to use discovery.
378
+ - **Occupancy fusion takes a start-up baseline** from the ESPHome nodes: a room
379
+ empty at start waits out its vacancy time, and an occupied one switches
380
+ nothing on.
381
+
382
+ **Power.** A **zigbee2mqtt power** node (`home-z2m-power`) reports a plug's
383
+ watts. The display controller takes it as the projector's power, and a scene's
384
+ new **End below** setting ends the scene once the device has been used and
385
+ then stays below the threshold for the set time.
386
+
387
+ **WLED.** A **wled** node (`home-wled`) drives a WLED strip for the
388
+ backlighting controller: on and off, and its brightness as the reading. WLED
389
+ can't be asked for its state over MQTT, so after a restart its reading comes
390
+ at its next change.
391
+
392
+ **The theatre after a restart.** With nothing saved, the display, receiver,
393
+ source and backlighting controllers now answer the activity controller's
394
+ probe with what their devices show, and the theatre adopts the one activity
395
+ that matches, commanding nothing. It needs the display and receiver to have
396
+ answered; a device that can't be asked, such as a WLED backlight, shows as
397
+ unobserved until it reports.
398
+
399
+ Also changed:
400
+
401
+ - A theatre light that never reports ends **unobserved** after the
402
+ confirmation timeout, leaving the theatre ready but degraded instead of
403
+ confirming forever, and a Zigbee2MQTT group with no state says to set
404
+ `retain: true` for it (#186).
405
+ - Each device node's reference links to its maker's or project's
406
+ documentation.
407
+
356
408
  ### 6.2.0
357
409
 
358
410
  Nothing to migrate from 6.1.0: flows wired the 6.1.0 way keep working. Two
@@ -909,9 +961,9 @@ Without a context store, after a node is redeployed or Node-RED restarts:
909
961
  times, set from Home Assistant or a message.
910
962
  - **The theatre starts its counts again:** its counters and operational SLO
911
963
  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).
964
+ activity. It works it out again from what the devices show, when they show
965
+ exactly one activity; otherwise it is unknown, and the devices are left
966
+ alone, until the next request.
915
967
  - **Work in progress is not recovered:** a motion off-timer that was running,
916
968
  or a theatre device change still being confirmed. The node starts afresh
917
969
  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
@@ -0,0 +1,73 @@
1
+ import type { TraceEntry } from "./bounded-trace";
2
+ export type SensorRole = "motion" | "presence" | "illuminance";
3
+ export interface EsphomeModel {
4
+ label: string;
5
+ modelNames: readonly string[];
6
+ exclude: readonly string[];
7
+ motion: readonly string[];
8
+ presence: readonly string[];
9
+ illuminance: readonly string[];
10
+ }
11
+ export declare const ESPHOME_MODELS: Readonly<Record<string, EsphomeModel>>;
12
+ export interface EsphomeSensorConfig {
13
+ device: string;
14
+ model: string;
15
+ discoveryPrefix: string;
16
+ }
17
+ export interface DiscoveredEntity {
18
+ component: string;
19
+ object: string;
20
+ stateTopic: string;
21
+ deviceClass: string | null;
22
+ model: string | null;
23
+ availabilityTopic: string | null;
24
+ }
25
+ export interface EsphomeSensorState {
26
+ entities: Record<string, boolean>;
27
+ motion: boolean | null;
28
+ presence: boolean | null;
29
+ illuminance: number | null;
30
+ online: boolean | null;
31
+ awaitingStatus: boolean;
32
+ discovered: Record<string, DiscoveredEntity>;
33
+ }
34
+ export interface EsphomeSensorMessage {
35
+ topic?: unknown;
36
+ payload?: unknown;
37
+ retain?: unknown;
38
+ }
39
+ export interface OccupancyMessage {
40
+ source: "motion" | "presence";
41
+ payload: boolean;
42
+ baseline?: true;
43
+ }
44
+ export interface LightMessage {
45
+ source: "illuminance";
46
+ payload: number;
47
+ }
48
+ export type RoleSource = "discovered" | "preset" | "preset-other-model";
49
+ export interface Roles {
50
+ source: RoleSource;
51
+ motion: string[];
52
+ presence: string[];
53
+ illuminance: string[];
54
+ status: string[];
55
+ }
56
+ export declare function normaliseEsphomeSensorConfig(config: {
57
+ device?: unknown;
58
+ model?: unknown;
59
+ discoveryPrefix?: unknown;
60
+ }): EsphomeSensorConfig;
61
+ export declare function esphomeSensorTopics(config: EsphomeSensorConfig): {
62
+ discovery: string;
63
+ initial: string[];
64
+ };
65
+ export declare function esphomeRoles(state: Pick<EsphomeSensorState, "discovered">, config: EsphomeSensorConfig): Roles;
66
+ export declare function transitionEsphomeSensor(saved: Partial<EsphomeSensorState> | undefined, msg: EsphomeSensorMessage, config: EsphomeSensorConfig): {
67
+ state: EsphomeSensorState;
68
+ occupancy: OccupancyMessage[];
69
+ light: LightMessage[];
70
+ traces: TraceEntry<Record<string, unknown>>[];
71
+ roles: Roles;
72
+ topics: string[];
73
+ };