@avantics/node-red-home-automation 3.0.1 → 4.0.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 (108) hide show
  1. package/README.md +262 -13
  2. package/dist/lib/activity-lighting-controller.d.ts +7 -1
  3. package/dist/lib/activity-lighting-controller.js +37 -3
  4. package/dist/lib/adopted-request.d.ts +26 -0
  5. package/dist/lib/adopted-request.js +44 -0
  6. package/dist/lib/avr-controller.d.ts +8 -1
  7. package/dist/lib/avr-controller.js +27 -3
  8. package/dist/lib/avr-publishing.d.ts +24 -0
  9. package/dist/lib/avr-publishing.js +80 -0
  10. package/dist/lib/backlighting-controller.d.ts +7 -1
  11. package/dist/lib/backlighting-controller.js +26 -3
  12. package/dist/lib/circadian.d.ts +1 -0
  13. package/dist/lib/circadian.js +3 -0
  14. package/dist/lib/cover-availability.d.ts +7 -0
  15. package/dist/lib/cover-availability.js +24 -0
  16. package/dist/lib/cover-controller.d.ts +13 -1
  17. package/dist/lib/cover-controller.js +113 -30
  18. package/dist/lib/cover-group.d.ts +62 -0
  19. package/dist/lib/cover-group.js +125 -0
  20. package/dist/lib/cover-models.d.ts +37 -0
  21. package/dist/lib/cover-models.js +83 -0
  22. package/dist/lib/cover-publishing.d.ts +40 -0
  23. package/dist/lib/cover-publishing.js +102 -0
  24. package/dist/lib/cover-requests.d.ts +21 -0
  25. package/dist/lib/cover-requests.js +49 -0
  26. package/dist/lib/display-mode-controller.d.ts +4 -0
  27. package/dist/lib/display-mode-controller.js +26 -2
  28. package/dist/lib/ha-discovery.d.ts +27 -0
  29. package/dist/lib/ha-discovery.js +91 -0
  30. package/dist/lib/house-schedule-publishing.d.ts +23 -0
  31. package/dist/lib/house-schedule-publishing.js +71 -0
  32. package/dist/lib/house-schedule.d.ts +23 -0
  33. package/dist/lib/house-schedule.js +29 -0
  34. package/dist/lib/motion-policy.d.ts +9 -0
  35. package/dist/lib/motion-policy.js +45 -11
  36. package/dist/lib/motion-publishing.d.ts +28 -0
  37. package/dist/lib/motion-publishing.js +92 -0
  38. package/dist/lib/occupancy-publishing.d.ts +10 -0
  39. package/dist/lib/occupancy-publishing.js +45 -0
  40. package/dist/lib/open-close-cover.d.ts +92 -0
  41. package/dist/lib/open-close-cover.js +287 -0
  42. package/dist/lib/publishing-node.d.ts +39 -0
  43. package/dist/lib/publishing-node.js +72 -0
  44. package/dist/lib/retained-topics.d.ts +10 -0
  45. package/dist/lib/retained-topics.js +19 -0
  46. package/dist/lib/room-controller.d.ts +9 -0
  47. package/dist/lib/room-controller.js +47 -56
  48. package/dist/lib/room-lighting-discovery.d.ts +20 -1
  49. package/dist/lib/room-lighting-discovery.js +135 -13
  50. package/dist/lib/room-publishing.d.ts +42 -0
  51. package/dist/lib/room-publishing.js +182 -0
  52. package/dist/lib/room-schedule.d.ts +8 -0
  53. package/dist/lib/room-schedule.js +41 -0
  54. package/dist/lib/settings.d.ts +2 -0
  55. package/dist/lib/settings.js +20 -0
  56. package/dist/lib/source-capability-controller.d.ts +8 -1
  57. package/dist/lib/source-capability-controller.js +29 -3
  58. package/dist/lib/theatre-activity-controller.d.ts +0 -1
  59. package/dist/lib/theatre-activity-controller.js +27 -24
  60. package/dist/lib/theatre-ha-discovery.d.ts +3 -4
  61. package/dist/lib/theatre-ha-discovery.js +46 -36
  62. package/dist/lib/theatre-state-contract.d.ts +6 -0
  63. package/dist/lib/theatre-state-contract.js +83 -47
  64. package/dist/lib/theatre-state.d.ts +1 -1
  65. package/dist/lib/theatre-state.js +1 -1
  66. package/dist/lib/topic-names.d.ts +4 -0
  67. package/dist/lib/topic-names.js +31 -0
  68. package/dist/nodes/activity-lighting-controller.js +5 -3
  69. package/dist/nodes/adapter.d.ts +6 -1
  70. package/dist/nodes/adapter.js +65 -1
  71. package/dist/nodes/avr-controller.html +59 -5
  72. package/dist/nodes/avr-controller.js +74 -4
  73. package/dist/nodes/backlighting-controller.js +5 -3
  74. package/dist/nodes/cover-controller.d.ts +3 -0
  75. package/dist/nodes/cover-controller.html +177 -0
  76. package/dist/nodes/cover-controller.js +178 -0
  77. package/dist/nodes/cover-group.d.ts +3 -0
  78. package/dist/nodes/cover-group.html +89 -0
  79. package/dist/nodes/cover-group.js +84 -0
  80. package/dist/nodes/flows-started.d.ts +4 -0
  81. package/dist/nodes/flows-started.js +39 -0
  82. package/dist/nodes/house-schedule-mqtt.d.ts +3 -0
  83. package/dist/nodes/house-schedule-mqtt.html +61 -0
  84. package/dist/nodes/house-schedule-mqtt.js +80 -0
  85. package/dist/nodes/house-schedule.d.ts +3 -0
  86. package/dist/nodes/house-schedule.html +31 -0
  87. package/dist/nodes/house-schedule.js +51 -0
  88. package/dist/nodes/motion-policy.html +81 -5
  89. package/dist/nodes/motion-policy.js +69 -8
  90. package/dist/nodes/occupancy-fusion.html +69 -14
  91. package/dist/nodes/occupancy-fusion.js +46 -4
  92. package/dist/nodes/publishing-lifecycle.d.ts +25 -0
  93. package/dist/nodes/publishing-lifecycle.js +38 -0
  94. package/dist/nodes/room-controller.html +49 -5
  95. package/dist/nodes/room-controller.js +67 -8
  96. package/dist/nodes/shared-schedule.d.ts +6 -0
  97. package/dist/nodes/shared-schedule.js +15 -0
  98. package/dist/nodes/source-capability-controller.js +5 -3
  99. package/dist/nodes/theatre-activity-controller.html +1 -3
  100. package/dist/nodes/theatre-activity-controller.js +1 -2
  101. package/dist/nodes/theatre-state-contract.html +28 -5
  102. package/dist/nodes/theatre-state-contract.js +22 -4
  103. package/examples/Cover control.json +380 -0
  104. package/examples/Cover pair.json +230 -0
  105. package/examples/Home theatre activity.json +4 -4
  106. package/examples/House schedule.json +164 -0
  107. package/examples/Room lighting.json +4 -3
  108. package/package.json +6 -2
package/README.md CHANGED
@@ -10,6 +10,11 @@ State-aware Node-RED controllers for reliable lighting and home-theatre automati
10
10
 
11
11
  Most home automations translate an event directly into a command. This package adds a deterministic control layer between them: it tracks desired and observed state, preserves manual control, confirms outcomes, retries bounded failures, and rejects stale work.
12
12
 
13
+ > [!NOTE]
14
+ > **Under active development.** This package is changing quickly. Versions follow semver, but an update can
15
+ > still change behaviour in ways that aren't marked as breaking. Read the release notes before updating, pin the
16
+ > version you run, and check your flows after each update.
17
+
13
18
  ## What it solves
14
19
 
15
20
  - **Occupancy without flicker:** combine PIR motion with optional presence sensing before changing room state.
@@ -19,7 +24,7 @@ Most home automations translate an event directly into a command. This package a
19
24
  - **Honest source readiness:** model controllable, externally controlled, and unavailable playback sources without claiming success from an input selection alone.
20
25
  - **Owned theatre atmosphere:** apply activity lighting only to active, non-manual room lights and confirm TV backlighting independently.
21
26
  - **Bounded receiver volume:** coordinate absolute and relative requests through one transport owner while preserving later physical adjustments.
22
- - **Recoverable automation:** adopt one fresh, uniquely matching physical activity after lost state; otherwise coordinate a safe Off request.
27
+ - **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.
23
28
 
24
29
  ![Architecture diagram. Inputs (wall switches, motion and presence sensors, illuminance, and theatre requests over MQTT) feed two groups of nodes. Room lighting: occupancy-fusion, motion-lighting-policy and switch-lighting-policy feed room-lighting-controller, which sends set commands to the lights (for example Zigbee2MQTT) and reads back their observed state. Theatre activities: theatre-state-contract passes activity intents to theatre-activity-controller and publishes retained theatre state and Home Assistant discovery; your flow routes each theatreCommand by target to the theatre equipment controllers (AVR, display mode, source capability, backlighting), which command the devices, or to activity-lighting-controller, which holds room lights; both report target state back to the activity controller.](https://avantics-hq.github.io/node-red-home-automation/images/architecture.svg)
25
30
 
@@ -28,7 +33,7 @@ commands, and reports done only when fresh observations confirm them.
28
33
 
29
34
  ## Included nodes
30
35
 
31
- The nodes come in three groups. Each group has an importable example flow
36
+ The nodes come in four groups. Each group has an importable example flow
32
37
  (**Import → Examples** in the Node-RED editor).
33
38
 
34
39
  ### Room lighting
@@ -37,7 +42,12 @@ Motion, presence, illuminance and wall switches drive one room's lights, with
37
42
  circadian styling and manual ownership. Wire occupancy fusion into the motion
38
43
  policy, wall switches into the switch policy, and both policies into the room
39
44
  controller. The room controller keeps a light a person set after the room went
40
- vacant, so motion doesn't switch it straight off. Circadian
45
+ vacant, so motion doesn't switch it straight off. Without a Node-RED context
46
+ store, a motion node that restarts or is redeployed doesn't know whether the
47
+ room is occupied, so it counts the room as vacant from then: someone sitting
48
+ still in a lit room has the motion-lit lights switched off after the vacancy
49
+ delay unless motion is seen. After a restart the room has also forgotten which
50
+ lights a person set, so it doesn't keep those either. Circadian
41
51
  levels follow the room controller's wake and bed times (default 07:00 and
42
52
  23:00): they rise over the hour after waking, stay bright and cool through the
43
53
  day, and wind down to the sleep settings over the three hours before bed. Times
@@ -62,6 +72,21 @@ way; other rewrites can still be misread.
62
72
  | `home-switch-lighting-policy` | Converts raw edges or pre-classified button actions into lighting intent while exposing input freshness and availability. |
63
73
  | `home-room-lighting-controller` | Owns the room's light commands, adaptive styling, manual and held lights, and lighting state. |
64
74
 
75
+ One house schedule can set the wake and bed times for many rooms. It is a
76
+ configuration node, like an MQTT broker: choose it as a room controller's
77
+ **Schedule** and the room follows it, hearing of every change without wires.
78
+ Those rooms then have no wake and bed time entities of their own in Home
79
+ Assistant. Rooms that need their own times (a child's room, say) choose none.
80
+ Deleting the house schedule in the editor returns its rooms to their own times.
81
+ The optional house schedule MQTT node publishes the schedule's times and Home
82
+ Assistant time entities, and takes changes from them.
83
+ Example: [`House schedule.json`](https://github.com/avantics-hq/node-red-home-automation/blob/main/examples/House%20schedule.json).
84
+
85
+ | Node | Purpose |
86
+ |---|---|
87
+ | `home-house-schedule` | A configuration node: one wake and bed time for every room that uses it. |
88
+ | `home-house-schedule-mqtt` | Publishes a house schedule for Home Assistant and changes it from Home Assistant. |
89
+
65
90
  ### Home theatre equipment
66
91
 
67
92
  Each controller owns one kind of device. It accepts a generation-scoped intent,
@@ -102,6 +127,53 @@ Pure TypeScript policy modules live in `lib/`; thin Node-RED runtime and editor
102
127
 
103
128
  Importable example flows for the Node-RED editor live in [`examples/`](https://github.com/avantics-hq/node-red-home-automation/tree/main/examples) (**Import → Examples**). Executable, deployment-neutral contract examples live in [`contract-examples/`](https://github.com/avantics-hq/node-red-home-automation/tree/main/contract-examples) and exercise the same reducers as the runtime adapters.
104
129
 
130
+
131
+ ### Covers
132
+
133
+ One cover controller owns one position cover: a blind, shutter or curtain motor
134
+ that takes and reports a position from 0 (closed) to 100 (open). Send it
135
+ `"open"`, `"close"`, `"stop"`, a position, or the name of a preset such as
136
+ `partial`. It confirms a move from what the cover reports, retries a bounded
137
+ number of times, and leaves a cover a person moved where they put it. An
138
+ automatic target, such as a position computed from the weather, sets
139
+ `msg.respectManual = true` so it waits while a person's move holds; a target
140
+ the cover is already at is confirmed without a command. A button can send
141
+ `msg.stopIfMoving = true` with `"open"` or `"close"` to stop the cover if it is
142
+ moving and do the request otherwise. The cover's availability report
143
+ (`{kind: "availability", online}`) keeps requests from going to an offline
144
+ device: they are answered `unavailable`, and the cover is read again when it is
145
+ back. A motor with no reliable position can be set to *open, close and
146
+ stop only*: it confirms a move from a reported end state, or from a move that
147
+ ran for its full travel time, and says when it could only judge by travel time
148
+ or could not confirm at all. Its third output says whether the cover is
149
+ moving, so other policies can react. To pause motion lighting while a blind
150
+ moves, send it to the motion policy's pause input
151
+ (`msg.source = "pause"`, `msg.payload` true or false, `msg.owner` naming the
152
+ cover), as the example does; a pause lasts at most the motion policy's
153
+ **Maximum pause** unless sent again; never its enable (`area-enabled`), which is the
154
+ user's own switch. Device commands come out in a neutral
155
+ shape (`set_position`, `stop` or `observe`); the example flow maps them to and
156
+ from a Zigbee2MQTT cover. Battery and charging status are kept as reported
157
+ facts and never acted on.
158
+
159
+ Switched on, a cover node publishes its state (and position) under
160
+ `home/<area>/cover/<name>/`, named by its **Name in topics** (no default: give
161
+ each cover in a room its own), and announces a Home Assistant cover entity. Its open,
162
+ close, stop and set position come back to the cover node on its own set topics
163
+ as requests like any other, carried out and confirmed as above; nothing
164
+ commands the device through Home Assistant. A cover group has no entity of its
165
+ own: Home Assistant can group the covers' entities itself.
166
+
167
+ A cover group moves several covers as one, such as the left and right of a
168
+ curtain: it sends each member the request on that member's own output, labelled
169
+ from its Members setting, and reports ready only when every member confirms,
170
+ or, if only some do, which did what.
171
+
172
+ | Node | Purpose |
173
+ |---|---|
174
+ | `home-cover-controller` | Owns one cover's moves (a position cover, or open, close and stop only), confirmed from what it reports, with presets, manual ownership and a moving signal. |
175
+ | `home-cover-group` | Moves several covers as one, with an honest result when only some confirm. |
176
+
105
177
  ## Requirements
106
178
 
107
179
  - Node.js 22.9 or newer
@@ -122,11 +194,49 @@ also attaches the package tarball and its SHA-256 checksum. Install a downloaded
122
194
  tarball through **Manage palette → Install → Upload module**, or with:
123
195
 
124
196
  ```sh
125
- npm install /path/to/avantics-node-red-home-automation-3.0.1.tgz
197
+ npm install /path/to/avantics-node-red-home-automation-4.0.0.tgz
126
198
  ```
127
199
 
128
200
  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.
129
201
 
202
+ ### 4.0.0
203
+
204
+ Adds cover control, a house schedule, and Home Assistant entities for every
205
+ publishing node. Check these after upgrading from 3.0:
206
+
207
+ - **Breaking: theatre recovery never switches a running activity off.** After a
208
+ restart or redeploy with unclear evidence, the activity is reported as unknown
209
+ and the devices are left alone until the next request. The "Recovery Off
210
+ activity" setting is gone, and a saved value is ignored. The metric
211
+ `recoveriesSafeOff` is now `recoveriesUnknown` (in `<base>/metrics`, shown as
212
+ attributes of the "Transition latency" sensor), and the event
213
+ `recovery_safe_off` is now `recovery_unknown`. Update any dashboard, template
214
+ or flow that uses the old names.
215
+ - **Breaking: the theatre's readiness moved topics.** It is now on
216
+ `<base>/readiness`, and its Home Assistant sensor is "Readiness".
217
+ `<base>/availability` now carries `online` or `offline` (see "Availability"
218
+ below).
219
+ - **Breaking for areas that aren't identifiers:** a room or theatre contract whose
220
+ area has spaces or other characters now publishes under the lowercase form,
221
+ for example `home/living_room/…` instead of `home/Living Room/…` (see
222
+ "Discovery" below).
223
+ - **Without a context store, a restart or redeploy is gentler:** a room leaves
224
+ its lights alone until something names them, motion lighting starts its
225
+ vacancy countdown, and a theatre device re-learns its activity from the
226
+ theatre instead of being marked unresponsive. A [file context store](#recommended-setup-a-file-context-store) keeps state
227
+ across restarts instead.
228
+ - **A Catch node fires once per input error,** not twice.
229
+ - **New nodes:** a cover controller for blinds, shutters and curtains, a cover
230
+ group, a house schedule that sets many rooms' wake and bed times, and a house
231
+ schedule MQTT node for Home Assistant (see "Covers" and "Room lighting").
232
+ - **New outputs, off until you switch publishing on:** occupancy fusion and the
233
+ motion policy gain a second output, and the AVR controller a third, for their
234
+ MQTT state and Home Assistant entities. Saved nodes are unchanged.
235
+ - **Home Assistant:** availability, entity names that survive area renames, the
236
+ room's sleep switch and wake and bed times, receiver volume, and cleanup of a
237
+ deleted node's entities, described under "Upgrading from 2.x" below.
238
+ - **Other flows can pause motion lighting** without changing the user's enable.
239
+
130
240
  ### 3.0.1
131
241
 
132
242
  Fixes the room lighting controller looping on its own commands when something
@@ -141,7 +251,7 @@ its commands to MQTT out unchanged (see Room lighting).
141
251
 
142
252
  ### Upgrading from 2.x
143
253
 
144
- Version 3.0 changes some behaviour. Check these after upgrading:
254
+ Version 3.0 changed some behaviour, and later versions added to it. Check these after upgrading from 2.x, along with the notes above:
145
255
 
146
256
  - **Wall switches go through the switch lighting policy node.** The motion lighting policy no longer handles them,
147
257
  and ignores switch messages, so rewire any wall switch that feeds a motion node. The room lighting controller now
@@ -150,17 +260,76 @@ Version 3.0 changes some behaviour. Check these after upgrading:
150
260
  minutes before. A redeploy with a changed vacancy delay or lux cutoff now takes effect.
151
261
  - **Settings are checked when you deploy.** An emptied or unusable setting shows "invalid configuration", and the
152
262
  node's log says which setting is wrong. A setting your flow saved before it existed still takes its default.
153
- - **No node assumes a room.** An empty area is allowed, except on the theatre state contract, which needs one to name
154
- its topics. A room lighting controller with no area still controls its lights, but publishes no state or discovery.
263
+ - **No node assumes a room.** An empty area is allowed. A node that publishes needs one where it names something:
264
+ the theatre state contract for its default base topic (`home/<area>/theatre`), and a room lighting controller for
265
+ the topics it publishes. A theatre state contract added from now on doesn't need one for Home Assistant
266
+ discovery: its entity IDs then come from its display name. With an area, it suggests that area to Home Assistant,
267
+ which creates it if no area of that name exists. One saved before needs an area for discovery, as before. A room
268
+ lighting controller with no area still controls its lights, but publishes no state or discovery.
155
269
  - **MQTT state publishing and Home Assistant discovery are opt-in** on the room lighting controller and the theatre
156
270
  state contract. New nodes start with them off. Nodes in a flow saved before 3.0 keep publishing until you untick
157
271
  the setting. Switching discovery off removes the entities from Home Assistant.
272
+ - **Discovery** goes under the **Discovery prefix** setting (`homeassistant` by default, as in Home Assistant) on
273
+ both nodes, and every entry names this package and its version as its origin. Topics and IDs use the area in
274
+ lowercase, with each run of spaces or other characters (anything but letters, digits, `_` and `-`) as `_`:
275
+ "Living Room" publishes under `home/living_room/…`, and "living-room" is unchanged.
276
+ Names shown in Home Assistant keep the area as you typed it.
277
+ - **Entity names.** A room lighting controller or theatre state contract you add from now on names its Home
278
+ Assistant device, unique IDs and discovery topics after its Node-RED node ID (`nrha_<node id>…`), so renaming its
279
+ area or display name updates the same entities. Nodes in flows saved before this keep naming them after the area,
280
+ exactly as before, so nothing changes for them in Home Assistant. Either way, the entity ID Home Assistant first
281
+ gives an entity comes from the area, with `-` as `_`.
282
+ Importing or pasting a node in the editor keeps its saved settings, including its ID scheme and publishing, so
283
+ an older node restored from a backup keeps its area-named entities. Only a node added from the palette starts as
284
+ new.
285
+ - **Occupancy fusion can publish too**, off unless you switch it on: its occupancy as retained `ON`/`OFF` on
286
+ `home/<area>/occupancy/state`, with availability, and an occupancy binary sensor in Home Assistant. These go on its
287
+ new second output, so wire that to an MQTT out node; the first output still feeds the motion policy.
288
+ - **The motion lighting policy can publish too**, off unless you switch it on: whether this node's motion lighting
289
+ is enabled and its vacancy delay in seconds (`home/<area>/motion/enabled/state` and `…/delay/state`), which it also
290
+ takes from their `/set` topics, and a switch and a vacancy delay number in Home Assistant. These go on its new
291
+ second output; the shared global enable is not published.
292
+ - **The AVR controller can publish what the receiver reports**, off unless you switch it on: power, source and
293
+ volume, retained under `home/<area>/receiver/`, with availability, and Home Assistant power and source sensors
294
+ and a volume number (see "Receiver volume ownership"). These go on its new
295
+ third output, apart from the receiver commands and the theatre's state.
296
+ - **Topics no longer published are cleared.** Once the flows have started, and again at its startup message, a node
297
+ clears any retained topic it published before and no longer does, for example after an area, base topic,
298
+ discovery prefix or target change. It remembers what it published in its node context, which lasts across
299
+ deploys and restarts only with a context store configured (see "Recommended setup"). Without that record, an occupancy, motion, receiver or
300
+ house schedule MQTT node named after itself (node-based IDs) that publishes state still clears its own Home Assistant
301
+ entities it no longer publishes, such as after you switch discovery off; it never clears topics another node could
302
+ publish. Other old topics, after an area, base topic, discovery prefix or target change, or after you switch
303
+ publishing off entirely, are cleared only from the record. A node that never gets a startup message
304
+ keeps clearing its old topics at every start, so to move an area from one older room node to another, send the old
305
+ node a startup message, or delete it.
306
+ - **Send each publishing node a startup message once, a few seconds after deploy.** The example flows do this with an
307
+ inject node set to fire once after 3 seconds: by then the MQTT broker node has usually connected, and a message
308
+ sent before it connects is dropped, along with the discovery and state it carried.
309
+ - **Removing entities:** deleting a node clears its Home Assistant entities and retained state, but only when you
310
+ deploy with "Modified nodes" or "Modified flows". On a full deploy (the deploy button's default), Node-RED stops the
311
+ MQTT out node at the same moment, so the clearing never reaches the broker. Disabling a node or its flow keeps its
312
+ entities, so they come back unchanged when you enable it again. To remove a node's entities after a full deploy,
313
+ or to remove the entities of a flow you copied to another Node-RED (the copy's nodes have new IDs, so new
314
+ entities), delete the device in Home Assistant: Settings → Devices & services → Devices, open the device, then
315
+ Delete. Home Assistant then clears its retained discovery entry itself.
316
+ - **Availability:** each publishing node sends a retained `online` once the flows have started (and again at its
317
+ startup message) and `offline` when it stops, on `home/<area>/lighting/availability` (room) or
318
+ `<base>/availability` (theatre), and its Home Assistant entities follow it. These get through when the node is
319
+ deployed on its own ("Modified nodes" or "Modified flows"), while the MQTT connection stays up. On a full deploy, a
320
+ restart or a shutdown, Node-RED stops the MQTT out node at the same moment and reconnects to the broker afterwards,
321
+ so set the MQTT broker node's **Birth message** to `online`, and its **Close message** and **Will message** (which
322
+ covers crashes) to `offline`, all retained, on the same topic; with several publishing nodes, the broker can cover
323
+ one of them. The theatre's readiness (`unknown`, `available`, `degraded`
324
+ or `unavailable`), which used `<base>/availability` before, is now on `<base>/readiness`.
325
+
326
+ ## Theatre MQTT contract
158
327
 
159
328
  The whole-theatre MQTT contract uses non-retained requests at
160
329
  `home/<area>/theatre/request`; every request supplies a unique `requestId` and an
161
330
  explicit configured activity. Controller output is retained under `desired`,
162
- `current`, `phase`, `failure`, `availability`, `metrics`, `slo`, and
163
- `health/<target>`. Metrics expose transition latency and outcome counts plus
331
+ `current`, `phase`, `transition` (when the latest transition started and finished, and which
332
+ targets it left degraded), `failure`, `readiness`, `metrics`, `slo`, and `health/<target>`. Metrics expose transition latency and outcome counts plus
164
333
  per-target retry, fallback, confirmation-latency, failure, manual-override, and
165
334
  availability evidence. The SLO evaluator keeps a bounded outcome window,
166
335
  publishes success rate plus p50/p95 transition latency, and exposes an
@@ -187,10 +356,62 @@ second ahead of Node-RED's clock is treated as observed on receipt and traced as
187
356
 
188
357
  Unsolicited display, AVR, source, and backlighting changes latch manual
189
358
  ownership instead of issuing corrective commands. A newer explicit activity
190
- request resumes automation. Recovery adopts physical state only when fresh
359
+ request resumes automation. A target controller that starts with nothing
360
+ saved (a redeploy or restart without a context store) takes the activity's
361
+ wanted values from the activity controller's next refresh, which carries them
362
+ as the intent did, and only reads its device for it: it reports ready when
363
+ the device already matches, and a manual override (reason `adopted-mismatch`)
364
+ when it doesn't, sending no command until the next request.
365
+ Recovery adopts physical state only when fresh
191
366
  display, AVR, source, and backlighting evidence matches exactly one configured
192
- profile; missing or ambiguous startup evidence invokes the configured Off
193
- activity.
367
+ profile. With missing or ambiguous startup evidence the activity is unknown,
368
+ and nothing is commanded until the next request: a redeploy or restart, which
369
+ starts the controller with nothing saved unless a context store is configured,
370
+ never switches a running activity off. While it is unknown, the theatre's
371
+ phase shows `idle` (the controller isn't working on anything) and its current
372
+ activity `unknown` until the next request, even if something is playing.
373
+ (Earlier versions ran a configured Off activity here; that setting is gone,
374
+ and a saved value is ignored.)
375
+
376
+ ## Recommended setup: a file context store
377
+
378
+ The nodes keep what they are doing in Node-RED's node context. By default
379
+ Node-RED keeps context in memory and deletes a node's context whenever the
380
+ node stops: on a full deploy, on a "Modified flows" deploy of its flow (which
381
+ restarts every node in that flow, changed or not), on a "Modified nodes"
382
+ deploy of the node itself, and on every restart. Configure the file context
383
+ store so it survives. In `settings.js` in your Node-RED user directory, set:
384
+
385
+ ```js
386
+ contextStorage: {
387
+ default: { module: "localfilesystem" }
388
+ },
389
+ ```
390
+
391
+ then restart Node-RED. The file store writes changes to disk every 30 seconds
392
+ by default, so a change made just before Node-RED stops can still be lost.
393
+
394
+ Without a context store, after a node is redeployed or Node-RED restarts:
395
+
396
+ - **A room forgets which lights are held or manual:** every light an activity
397
+ held, or a person set by hand, is back under the room's control, so the next
398
+ refresh restyles an activity's lights and lights a person set.
399
+ - **Changes made at runtime go back to the node's settings:** for example motion
400
+ lighting's enable, vacancy delay and lux cutoff, a room's circadian lighting,
401
+ sleep, and wake and bed times, and the house schedule's times, set from Home
402
+ Assistant or a message.
403
+ - **The theatre starts its counts again:** its counters and operational SLO
404
+ samples restart, and the activity controller no longer knows the current
405
+ activity. At its next startup recovery it works it out from what the devices
406
+ report, and if no single activity matches, it switches to the recovery off
407
+ activity.
408
+ - **Work in progress is not recovered:** a motion off-timer that was running,
409
+ or a theatre device change still being confirmed. The node starts afresh
410
+ and goes by what it next observes.
411
+ - **Old retained topics are not cleared:** a node can't remember what it
412
+ published before, so after you change an area, base topic, discovery prefix
413
+ or targets, the old retained topics and Home Assistant entities stay until
414
+ you remove them yourself.
194
415
 
195
416
  ## Room light control
196
417
 
@@ -201,6 +422,16 @@ The room lighting controller gives each target one control state:
201
422
  refresh and circadian changes leave it alone until it is released.
202
423
  - `manual`: a person changed the light.
203
424
 
425
+ The control states live in the node's context. A room controller that starts
426
+ with nothing saved (its first deploy, or a redeploy or restart without a
427
+ context store) can't know which lights an activity held or a person set, so it
428
+ leaves every light as it is: the periodic refresh restyles a light again only
429
+ once an intent or release names it, someone switches it on with a bare ON, or
430
+ circadian lighting is switched on. A light that is on at that start and that
431
+ nothing names can keep its start-time style all day; to bring it back into step,
432
+ switch circadian lighting on (for example with the Home Assistant circadian
433
+ switch), or let motion or a wall switch name it.
434
+
204
435
  Add `owner` to an intent to override the targets it switches on. With
205
436
  `preserveManual: true`, manual lights are skipped:
206
437
 
@@ -253,7 +484,14 @@ Flows that filter that output by topic must pass the `/control` topics through.
253
484
  It also publishes the circadian state on `home/<area>/circadian/state`, and
254
485
  acts on ON or OFF sent to `home/<area>/circadian/set`, which is where the Home
255
486
  Assistant circadian switch sends them: wire an MQTT in node subscribed to that
256
- topic into the room controller.
487
+ topic into the room controller. In the same way it publishes and acts on sleep
488
+ (`home/<area>/sleep/state` and `/set`, ON or OFF) and the wake and bed times
489
+ (`home/<area>/wake-time/state` and `/set`, likewise `bed-time`, as `HH:MM:SS`);
490
+ subscribing to `home/<area>/+/set` covers all four. A time set from Home
491
+ Assistant lasts until the node is deployed with a different setting for it.
492
+ With discovery on, Home Assistant also gets a sleep switch, wake and bed time
493
+ entities (under the device's configuration), and a diagnostic sensor per light
494
+ showing its control state, with the owner as an attribute.
257
495
 
258
496
  ## Receiver volume ownership
259
497
 
@@ -277,6 +515,17 @@ Once confirmed, it releases the volume target; a later physical or external
277
515
  adjustment becomes the new baseline instead of being corrected. A request still pending when Node-RED restarts is reported as
278
516
  `volume_failed` with reason `restart`, not replayed.
279
517
 
518
+ With publishing and discovery on, Home Assistant gets a volume number. A
519
+ value set there arrives on `home/<area>/receiver/volume/set`; values arriving
520
+ within 0.3 seconds of each other are settled to the last, which becomes an
521
+ ordinary absolute request (`msg.avr = {kind: "volume", mode: "absolute", ...}`),
522
+ so it is bounded, sent and confirmed in the same way, and never sent to the
523
+ receiver directly. The number shows the confirmed volume. A theatre activity
524
+ owns the receiver's power and source, not its volume: a volume request made
525
+ while an activity is switching power or source waits until that is done, and
526
+ one made while the receiver is off (an activity's `off`, say) is rejected
527
+ with `receiver-not-ready`, as any request would be.
528
+
280
529
  ## Contract examples
281
530
 
282
531
  Build and run all seven public contracts:
@@ -48,6 +48,7 @@ export interface ActivityLightingState {
48
48
  pending: ActivityLightingPending | null;
49
49
  failure: ActivityLightingFailure | null;
50
50
  blockedGeneration: number | null;
51
+ adoptedGeneration: number | null;
51
52
  }
52
53
  export type ActivityLightingEvent = {
53
54
  kind: "intent";
@@ -73,7 +74,12 @@ export type ActivityLightingEvent = {
73
74
  kind: "tick";
74
75
  generation: number;
75
76
  } | {
76
- kind: "startup" | "refresh";
77
+ kind: "startup";
78
+ } | {
79
+ kind: "refresh";
80
+ requestId?: string | null;
81
+ generation?: number;
82
+ profile?: string;
77
83
  };
78
84
  export interface ActivityLightingMessage {
79
85
  activityLighting?: ActivityLightingEvent;
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.normaliseLightingProfiles = normaliseLightingProfiles;
4
4
  exports.normaliseActivityLightingConfig = normaliseActivityLightingConfig;
5
5
  exports.transitionActivityLighting = transitionActivityLighting;
6
+ const adopted_request_1 = require("./adopted-request");
6
7
  const settings_1 = require("./settings");
7
8
  const observation_time_1 = require("./observation-time");
8
9
  const target_state_1 = require("./target-state");
@@ -79,7 +80,8 @@ function initialState(saved = {}, profiles = {}) {
79
80
  observed: Object.fromEntries(Object.entries(saved.observed || {}).map(([target, observation]) => [target, { ...observation }])),
80
81
  pending: saved.pending && typeof saved.pending === "object" ? { ...saved.pending } : null,
81
82
  failure: saved.failure && typeof saved.failure === "object" ? { ...saved.failure } : null,
82
- blockedGeneration: Number.isInteger(saved.blockedGeneration) ? saved.blockedGeneration : null
83
+ blockedGeneration: Number.isInteger(saved.blockedGeneration) ? saved.blockedGeneration : null,
84
+ adoptedGeneration: (0, adopted_request_1.savedAdoptedGeneration)(saved)
83
85
  };
84
86
  }
85
87
  function profileFor(state, config) {
@@ -179,6 +181,14 @@ function transitionActivityLighting(saved, msg, suppliedConfig = {}, nowValue =
179
181
  continue;
180
182
  }
181
183
  if (!valuesMatch(profile.values, observation.values)) {
184
+ if ((0, adopted_request_1.isAdopted)(state)) {
185
+ // An adopted request the lights don't match: someone else's, and
186
+ // never re-applied.
187
+ state.pending = null;
188
+ state.phase = "manual_override";
189
+ trace("observation", "manual_override", adopted_request_1.ADOPTED_MISMATCH, { target });
190
+ return;
191
+ }
182
192
  state.phase = "confirming";
183
193
  return;
184
194
  }
@@ -293,6 +303,19 @@ function transitionActivityLighting(saved, msg, suppliedConfig = {}, nowValue =
293
303
  trace("observation", "accepted", null, { target: observation.target });
294
304
  reconcile();
295
305
  }
306
+ // A refresh with the activity's wanted values, reaching a node with
307
+ // nothing desired (it started with nothing saved): adopt them, and observe
308
+ // below as at startup (see adopted-request.ts). Which lights it held is
309
+ // unknown, so the next activity releases every light it holds.
310
+ const adoptable = event.kind === "refresh" ? (0, adopted_request_1.adoptableRefresh)(event, state) : null;
311
+ const adopted = adoptable !== null && event.kind === "refresh" && typeof event.profile === "string" && Object.hasOwn(config.profiles, event.profile);
312
+ if (adopted && event.kind === "refresh") {
313
+ state.desired = { ...adoptable, profile: event.profile, requestedAt: now.toISOString() };
314
+ state.generation = adoptable.generation;
315
+ state.adoptedGeneration = adoptable.generation;
316
+ state.applied = { profile: event.profile, targets: null };
317
+ trace("refresh", "adopted", "nothing-desired", { profile: event.profile, generation: adoptable.generation });
318
+ }
296
319
  if (event.kind === "intent") {
297
320
  acceptIntent(event);
298
321
  }
@@ -336,7 +359,7 @@ function transitionActivityLighting(saved, msg, suppliedConfig = {}, nowValue =
336
359
  state.phase = "confirming";
337
360
  // After a restart nothing else would end an unanswered observe: give
338
361
  // it a deadline, so it re-applies and then fails as a live request.
339
- if (event.kind === "startup" && state.blockedGeneration !== state.generation) {
362
+ if ((event.kind === "startup" || adopted) && state.blockedGeneration !== state.generation) {
340
363
  state.pending = { attempt: 0, deadlineAt: nowMs + config.confirmationTimeoutMs };
341
364
  }
342
365
  trace(event.kind, "observing", null, { profile: state.desired.profile });
@@ -349,12 +372,23 @@ function transitionActivityLighting(saved, msg, suppliedConfig = {}, nowValue =
349
372
  else {
350
373
  throw new Error("unknown activity lighting event kind");
351
374
  }
375
+ // An adopted request only reads the lights (see adopted-request.ts): an
376
+ // apply means they aren't as wanted.
377
+ const held = (0, adopted_request_1.readsOnly)(state, commands, (command) => command.operation === "observe");
378
+ if (held.mismatch) {
379
+ commands.splice(0, commands.length, ...held.commands);
380
+ state.pending = null;
381
+ state.phase = "manual_override";
382
+ trace("command", "withheld", adopted_request_1.ADOPTED_MISMATCH);
383
+ }
352
384
  if (state.desired) {
385
+ const manual = state.phase === "manual_override";
353
386
  const theatre = (0, target_state_1.targetStateEvent)({
354
387
  target: "lighting",
355
388
  requestId: state.desired.requestId,
356
389
  generation: state.generation,
357
- status: (0, target_state_1.asTargetStatus)(state.phase, "confirming"),
390
+ status: manual ? "transitioning" : (0, target_state_1.asTargetStatus)(state.phase, "confirming"),
391
+ classification: manual ? "manual_override" : null,
358
392
  observedAt: now.toISOString(),
359
393
  details: {
360
394
  profile: state.desired.profile,
@@ -0,0 +1,26 @@
1
+ export declare const ADOPTED_MISMATCH = "adopted-mismatch";
2
+ export interface AdoptedRequest {
3
+ requestId: string;
4
+ generation: number;
5
+ }
6
+ export declare function adoptableRefresh(event: {
7
+ kind: string;
8
+ requestId?: unknown;
9
+ generation?: unknown;
10
+ }, state: {
11
+ desired: unknown;
12
+ generation: number;
13
+ }): AdoptedRequest | null;
14
+ export interface AdoptableState {
15
+ generation: number;
16
+ adoptedGeneration: number | null;
17
+ phase: string;
18
+ }
19
+ export declare function savedAdoptedGeneration(saved: {
20
+ adoptedGeneration?: unknown;
21
+ }): number | null;
22
+ export declare function isAdopted(state: AdoptableState): boolean;
23
+ export declare function readsOnly<Command>(state: AdoptableState, commands: Command[], reads: (command: Command) => boolean): {
24
+ commands: Command[];
25
+ mismatch: boolean;
26
+ };
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ADOPTED_MISMATCH = void 0;
4
+ exports.adoptableRefresh = adoptableRefresh;
5
+ exports.savedAdoptedGeneration = savedAdoptedGeneration;
6
+ exports.isAdopted = isAdopted;
7
+ exports.readsOnly = readsOnly;
8
+ // A theatre device controller that starts with nothing saved (a redeploy or
9
+ // restart without a context store) adopts the request the theatre activity
10
+ // controller's refresh carries, with its wanted values, so it can report on
11
+ // it. It only ever reads the device for that request: a device found in the
12
+ // wanted state reports ready, and one that isn't is a manual override, with
13
+ // nothing commanded until a new explicit request. The five device reducers
14
+ // share these rules so they stay the same.
15
+ exports.ADOPTED_MISMATCH = "adopted-mismatch";
16
+ // The request a refresh carries, if this node can adopt it: it has nothing
17
+ // desired, and the generation isn't older than its own. Each reducer checks
18
+ // the wanted values itself.
19
+ function adoptableRefresh(event, state) {
20
+ if (event.kind !== "refresh" || state.desired)
21
+ return null;
22
+ if (typeof event.requestId !== "string" || event.requestId === "")
23
+ return null;
24
+ if (!Number.isInteger(event.generation) || event.generation < Math.max(1, state.generation))
25
+ return null;
26
+ return { requestId: event.requestId, generation: event.generation };
27
+ }
28
+ function savedAdoptedGeneration(saved) {
29
+ return Number.isInteger(saved.adoptedGeneration) ? saved.adoptedGeneration : null;
30
+ }
31
+ function isAdopted(state) {
32
+ return state.adoptedGeneration !== null && state.adoptedGeneration === state.generation;
33
+ }
34
+ // For an adopted request, keeps only the commands that read the device. Any
35
+ // other command means the reducer tried to bring the device to the wanted
36
+ // state, so it isn't in it: the result says so, and the caller records a
37
+ // manual override instead.
38
+ function readsOnly(state, commands, reads) {
39
+ if (!isAdopted(state))
40
+ return { commands, mismatch: false };
41
+ const kept = commands.filter(reads);
42
+ return { commands: kept, mismatch: kept.length !== commands.length };
43
+ }
44
+ //# sourceMappingURL=adopted-request.js.map
@@ -68,9 +68,16 @@ export interface AvrState {
68
68
  recentVolumeRequestIds: string[];
69
69
  volumeMetrics: AvrVolumeMetrics;
70
70
  lastAttempt: number;
71
+ adoptedGeneration: number | null;
71
72
  }
72
73
  export type AvrInputEvent = {
73
- kind: "startup" | "refresh";
74
+ kind: "startup";
75
+ } | {
76
+ kind: "refresh";
77
+ requestId?: string | null;
78
+ generation?: number;
79
+ power?: string;
80
+ source?: string | null;
74
81
  } | {
75
82
  kind: "observed";
76
83
  line?: unknown;
@@ -4,6 +4,7 @@ exports.parseAvrLine = exports.formatVolumeCommand = exports.QUERY_COMMAND = voi
4
4
  exports.createAvrState = createAvrState;
5
5
  exports.normaliseAvrConfig = normaliseAvrConfig;
6
6
  exports.transitionAvr = transitionAvr;
7
+ const adopted_request_1 = require("./adopted-request");
7
8
  const settings_1 = require("./settings");
8
9
  const target_state_1 = require("./target-state");
9
10
  const denon_protocol_1 = require("./denon-protocol");
@@ -73,7 +74,8 @@ function createAvrState(_config, saved = {}) {
73
74
  },
74
75
  lastAttempt: Number.isInteger(saved.lastAttempt) && (saved.lastAttempt ?? -1) >= 0
75
76
  ? saved.lastAttempt
76
- : 0
77
+ : 0,
78
+ adoptedGeneration: (0, adopted_request_1.savedAdoptedGeneration)(saved)
77
79
  };
78
80
  }
79
81
  function sameVolume(left, right) {
@@ -450,7 +452,19 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
450
452
  return "zero-volume-delta";
451
453
  return null;
452
454
  }
453
- if (event.kind === "refresh") {
455
+ // A refresh with the activity's wanted values, reaching a node with
456
+ // nothing desired (it started with nothing saved): adopt them, and
457
+ // rediscover below as at startup (see adopted-request.ts).
458
+ const adoptable = event.kind === "refresh" ? (0, adopted_request_1.adoptableRefresh)(event, state) : null;
459
+ const adopted = adoptable !== null && event.kind === "refresh" &&
460
+ validateIntent({ kind: "intent", ...adoptable, power: event.power, source: event.source ?? null }) === null;
461
+ if (adopted && event.kind === "refresh") {
462
+ state.desired = { ...adoptable, power: event.power, source: event.source || null };
463
+ state.generation = adoptable.generation;
464
+ state.adoptedGeneration = adoptable.generation;
465
+ trace("refresh", "adopted", "nothing-desired", { power: event.power, source: event.source || null, generation: adoptable.generation });
466
+ }
467
+ if (event.kind === "refresh" && !adopted) {
454
468
  // Re-read the receiver without touching work in flight: desired state,
455
469
  // pending commands, the volume request and the phase all carry on.
456
470
  commands.push({
@@ -466,7 +480,7 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
466
480
  trace("refresh", "querying", null, { pending: state.pending?.operation ?? null });
467
481
  forceStateEvent = true;
468
482
  }
469
- else if (event.kind === "startup") {
483
+ else if (event.kind === "startup" || adopted) {
470
484
  const requestBlocked = state.desired &&
471
485
  state.blockedGeneration === state.desired.generation;
472
486
  const abandonedVolumeRequest = state.volumeRequest?.requestId || null;
@@ -785,6 +799,16 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
785
799
  }
786
800
  forceStateEvent = true;
787
801
  }
802
+ // An adopted request only reads the receiver (see adopted-request.ts): a
803
+ // power, zone or source command means it isn't as wanted.
804
+ const held = (0, adopted_request_1.readsOnly)(state, commands, (command) => command.avrCommand.operation === "query" || command.avrCommand.operation === "volume-query");
805
+ if (held.mismatch) {
806
+ commands.splice(0, commands.length, ...held.commands);
807
+ state.pending = null;
808
+ state.classification = "manual_override";
809
+ state.phase = "manual_override";
810
+ trace("command", "withheld", adopted_request_1.ADOPTED_MISMATCH);
811
+ }
788
812
  const after = JSON.stringify({
789
813
  observed: state.observed,
790
814
  seen: state.seen,