@avantics/node-red-home-automation 4.0.3 → 5.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 (60) hide show
  1. package/README.md +117 -4
  2. package/contract-examples/switch-gestures.mjs +1 -1
  3. package/contract-examples/volume-ownership.mjs +6 -5
  4. package/dist/lib/activity-lighting-controller.d.ts +2 -0
  5. package/dist/lib/activity-lighting-controller.js +35 -6
  6. package/dist/lib/adopted-request.d.ts +17 -0
  7. package/dist/lib/adopted-request.js +61 -7
  8. package/dist/lib/avr-controller.d.ts +9 -3
  9. package/dist/lib/avr-controller.js +76 -24
  10. package/dist/lib/avr-publishing.d.ts +3 -3
  11. package/dist/lib/avr-publishing.js +11 -5
  12. package/dist/lib/backlighting-controller.d.ts +2 -0
  13. package/dist/lib/backlighting-controller.js +27 -7
  14. package/dist/lib/cover-publishing.js +1 -1
  15. package/dist/lib/denon-protocol.d.ts +5 -1
  16. package/dist/lib/denon-protocol.js +26 -11
  17. package/dist/lib/display-mode-controller.d.ts +12 -5
  18. package/dist/lib/display-mode-controller.js +181 -87
  19. package/dist/lib/house-schedule-publishing.js +1 -1
  20. package/dist/lib/light-styling.d.ts +2 -2
  21. package/dist/lib/light-styling.js +5 -4
  22. package/dist/lib/motion-publishing.js +1 -1
  23. package/dist/lib/occupancy-publishing.js +1 -1
  24. package/dist/lib/power-reading.d.ts +5 -0
  25. package/dist/lib/power-reading.js +13 -0
  26. package/dist/lib/room-controller.d.ts +2 -3
  27. package/dist/lib/room-controller.js +18 -2
  28. package/dist/lib/room-lighting-discovery.js +1 -1
  29. package/dist/lib/room-publishing.d.ts +3 -0
  30. package/dist/lib/shelly-cover.d.ts +46 -0
  31. package/dist/lib/shelly-cover.js +193 -0
  32. package/dist/lib/source-capability-controller.d.ts +2 -0
  33. package/dist/lib/source-capability-controller.js +27 -6
  34. package/dist/lib/switch-policy.d.ts +1 -1
  35. package/dist/lib/switch-policy.js +1 -1
  36. package/dist/lib/theatre-requests.d.ts +29 -0
  37. package/dist/lib/theatre-requests.js +89 -0
  38. package/dist/lib/theatre-state-contract.d.ts +5 -22
  39. package/dist/lib/theatre-state-contract.js +18 -73
  40. package/dist/lib/toggle-power.d.ts +41 -0
  41. package/dist/lib/toggle-power.js +74 -0
  42. package/dist/lib/topic-names.d.ts +1 -0
  43. package/dist/lib/topic-names.js +7 -0
  44. package/dist/lib/{display-transport.d.ts → transports/display-transport.d.ts} +1 -1
  45. package/dist/lib/{display-transport.js → transports/display-transport.js} +32 -7
  46. package/dist/lib/z2m-light.d.ts +8 -0
  47. package/dist/lib/z2m-light.js +64 -3
  48. package/dist/nodes/activity-lighting-controller.html +8 -0
  49. package/dist/nodes/avr-controller.html +28 -6
  50. package/dist/nodes/avr-controller.js +16 -6
  51. package/dist/nodes/display-mode-controller.html +61 -11
  52. package/dist/nodes/display-mode-controller.js +16 -6
  53. package/dist/nodes/room-controller.js +14 -0
  54. package/dist/nodes/shelly-cover.d.ts +3 -0
  55. package/dist/nodes/shelly-cover.html +65 -0
  56. package/dist/nodes/shelly-cover.js +34 -0
  57. package/examples/Home theatre activity.json +5 -5
  58. package/examples/Home theatre equipment.json +4 -4
  59. package/examples/Shelly cover.json +252 -0
  60. package/package.json +3 -2
package/README.md CHANGED
@@ -100,6 +100,19 @@ on output 2. Example: [`Home theatre equipment.json`](https://github.com/avantic
100
100
  | `home-source-capability-controller` | Gates source readiness on fresh availability, active-device, application or playback evidence. |
101
101
  | `home-backlighting-controller` | Owns TV-backlight power with observation-gated confirmation. |
102
102
 
103
+ The display controller reads the projector's power from any meter or adapter:
104
+ send `msg.display = {kind: "observed", device: "projector", power: "on"}`
105
+ (`"on"`, `"standby"` or `"transitioning"`), or `watts` from a meter. Its
106
+ built-in Shelly meter is optional. Without one, it asks for a reading on output
107
+ 3 whenever it needs one; wire that to your meter, unless the meter reports on
108
+ its own at least once per query timeout. A device that doesn't report fails
109
+ the request with reason `no-reading`. The node's help has the details.
110
+
111
+ For projector mode it opens the screen to its **Screen viewing position**, or,
112
+ left empty (the default for a new node), by the screen's own open command,
113
+ confirmed when the screen reports itself fully open. A node saved with a
114
+ position keeps it.
115
+
103
116
  ### Theatre activities
104
117
 
105
118
  One request, such as "tv" or "off", drives every target. The state contract
@@ -175,10 +188,24 @@ curtain: it sends each member the request on that member's own output, labelled
175
188
  from its Members setting, and reports ready only when every member confirms,
176
189
  or, if only some do, which did what.
177
190
 
191
+ A Shelly Gen2 or later device in cover mode wires straight to a cover
192
+ controller through the Shelly cover adapter, with no function nodes: an MQTT in
193
+ node subscribed to the device's `<prefix>/#` feeds the adapter, the
194
+ controller's device commands go to it too, and its two outputs go to an MQTT
195
+ out node and back to the controller. It speaks the device's own MQTT API, never
196
+ Home Assistant: it sends `pos,<0-100>`, `stop`, and `status_update` (for a fresh
197
+ reading) on `<prefix>/command/cover:<id>` (the device's MQTT Control, on by
198
+ default), and turns the device's status and
199
+ change notifications into position and motion readings, and its online topic
200
+ into availability. A cover that isn't calibrated, or has lost its position,
201
+ fails the command in hand with the reason rather than reporting a position.
202
+ Example: [`Shelly cover.json`](https://github.com/avantics-hq/node-red-home-automation/blob/main/examples/Shelly%20cover.json).
203
+
178
204
  | Node | Purpose |
179
205
  |---|---|
180
206
  | `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. |
181
207
  | `home-cover-group` | Moves several covers as one, with an honest result when only some confirm. |
208
+ | `home-shelly-cover` | Connects a Shelly Gen2+ cover to a cover controller over the device's own MQTT API. |
182
209
 
183
210
  ## Requirements
184
211
 
@@ -200,11 +227,79 @@ also attaches the package tarball and its SHA-256 checksum. Install a downloaded
200
227
  tarball through **Manage palette → Install → Upload module**, or with:
201
228
 
202
229
  ```sh
203
- npm install /path/to/avantics-node-red-home-automation-4.0.3.tgz
230
+ npm install /path/to/avantics-node-red-home-automation-5.0.0.tgz
204
231
  ```
205
232
 
206
233
  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.
207
234
 
235
+ ### 5.0.0
236
+
237
+ Separates the decision logic from the devices it drives, adds a Shelly cover
238
+ adapter, and fixes theatre recovery and screen handling. Check these after
239
+ upgrading from 4.0:
240
+
241
+ - **Lighting values are in percent and kelvin.** Intents and activity lighting
242
+ profiles take `brightnessPct` (0-100) and `colorTempKelvin` instead of
243
+ Zigbee2MQTT's `brightness` (1-254) and `color_temp` (mireds), and the switch
244
+ policy's double press now sends `{brightnessPct: 100}`. Your lights get the
245
+ same commands. The old values still work in 5.x, with a warning in the log;
246
+ change them before 6.0. For example, brightness 64 becomes brightnessPct 25,
247
+ and color_temp 400 becomes colorTempKelvin 2500 (1,000,000 ÷ mireds). 0% is
248
+ the dimmest level, not off: send state OFF to switch a light off.
249
+ - **Receiver volume is in dB** (a Denon's 80 is 0 dB). Send `valueDb` in volume
250
+ requests. `value` on the receiver's 0-98 scale still works in 5.x, with a
251
+ warning, and stops in 6.0. Saved volume bounds are converted when read; open
252
+ and save the node to store them in dB. The published volume state and the
253
+ Home Assistant volume number now show dB, as do the node's volume results and
254
+ state messages, so update any automation or flow that sets or reads them with
255
+ 0-98 values. Without a context store, the old retained
256
+ volume can sit outside Home Assistant's new dB range until the receiver
257
+ first reports after a restart.
258
+ - **The display controller's settings are named by role:** TV host, TV
259
+ pre-shared key, Screen controller host and Projector power meter host (saved
260
+ as `projectorPowerMeterHost`). A flow saved before 5.0 keeps working; open and
261
+ save the node to store the new name before 6.0, when `projectorMeterHost`
262
+ stops being read. No warning is logged for this one.
263
+ - **The projector's power can come from any meter or adapter:** send
264
+ `msg.display = {kind: "observed", device: "projector", power: "on" |
265
+ "standby" | "transitioning"}`, or `watts`. The built-in power meter host is
266
+ now optional. Without it, wire the new third output (projector power queries)
267
+ to ask your meter for a reading. Leave output 3 unwired only if your meter
268
+ reports on its own at least once every Query timeout, even when the power
269
+ doesn't change: a meter that reports only on a change says nothing while the
270
+ projector sits steady. Saved wiring on outputs 1 and 2 is kept. Power values
271
+ are lower case only (`on`, `standby`, `transitioning`); a smart plug's own
272
+ `ON` or `OFF` is rejected, so send its watts.
273
+ - **A display request fails rather than waiting** when a device hasn't reported
274
+ within Query timeout × Maximum attempts (it's asked again once): the reason is
275
+ `no-reading`, naming the device. Before, it waited in discovering. This
276
+ applies with the built-in hosts too.
277
+ - **The screen opens by its own command when no viewing position is set.** A
278
+ display node with no Screen viewing position (new nodes, and flows written
279
+ without the key) opens the screen with the screen's own open command and
280
+ confirms it fully open, rather than going to 82%. Nodes saved with a position
281
+ keep it; a saved position must now be above 0 and at most 100, or empty, or
282
+ the node won't deploy. Closing always uses the screen's own close command and runs to the
283
+ end, which also restores a position the screen has lost. A screen with a
284
+ viewing position but no known position is closed first, then sent to the
285
+ position; one that has never been calibrated fails with
286
+ `screen-not-calibrated`. The display's state events may report the screen's
287
+ position as null when it reports only open or closed.
288
+ - **Theatre recovery now reaches the devices.** After the theatre recovers an
289
+ activity, each device takes on the new request by reading itself, never by
290
+ commanding: one that matches is ready, and its old manual override clears;
291
+ one that doesn't reports a manual override once. Before, devices kept the old
292
+ request, and a flow that recovered on every manual override could loop.
293
+ - **Backlighting's ready carries the time of its reading,** so a repeated
294
+ request no longer counts as a fresh reading, and a silent device is reported
295
+ stale and then not responding.
296
+ - **New node: Shelly cover**, which connects a Shelly Gen2+ cover to a cover
297
+ controller over the device's own MQTT API (see "Covers").
298
+ - **For code that imports the package's files directly:** the display's device
299
+ transport moved from `dist/lib/display-transport` to
300
+ `dist/lib/transports/display-transport`. Only the nodes are a public
301
+ interface.
302
+
208
303
  ### 4.0.3
209
304
 
210
305
  Fixes the theatre state flapping on every scheduled refresh: with an activity
@@ -477,11 +572,21 @@ msg.lighting = {
477
572
  state: "ON",
478
573
  source: "activity",
479
574
  owner: "theatre",
480
- values: {brightness: 64, color_temp: 400},
575
+ values: {brightnessPct: 25, colorTempKelvin: 2500},
481
576
  preserveManual: true
482
577
  };
483
578
  ```
484
579
 
580
+ An intent's `values` use the package's own units: `brightnessPct` (0-100) and
581
+ `colorTempKelvin`. The room controller converts them for the light (for a
582
+ Zigbee2MQTT light, to its 1-254 brightness and mireds); other fields, such as
583
+ `effect`, are passed on as they are. `brightnessPct: 0` is the dimmest the
584
+ light goes, not off: send `state: "OFF"` to switch it off. A value that isn't a
585
+ number (a numeric string such as `"50"` counts), or a colour temperature of 0
586
+ or less, is left out with a warning in the log. During 5.x, `brightness` and `color_temp`
587
+ in Zigbee2MQTT's own units are still accepted and passed on unchanged, and the
588
+ room controller logs a warning once per deploy; they stop working in 6.0.
589
+
485
590
  `home-activity-lighting-controller` does this itself: while a profile is active
486
591
  it overrides that profile's lights under its configured owner (default
487
592
  `activity`), and when a new profile drops a light, including an off profile
@@ -538,10 +643,18 @@ msg.avr = {
538
643
  kind: "volume",
539
644
  requestId: "volume-control-1",
540
645
  mode: "relative",
541
- value: 1
646
+ valueDb: 1
542
647
  };
543
648
  ```
544
649
 
650
+ Volume is in dB: `valueDb` is the volume for `absolute`, or the change for
651
+ `relative`, and the bounds, results, published state and Home Assistant
652
+ number are in dB too. The controller converts for the receiver (for a Denon,
653
+ whose 0-98 has 80 at 0 dB, -80 to +18 dB in half steps). During 5.x, a request
654
+ with `value` in the receiver's own 0-98, and bounds saved before 5.0 as
655
+ **minVolume** and **maxVolume**, are still read, and the node logs a warning
656
+ once per deploy for such requests; they stop working in 6.0.
657
+
545
658
  `mode` may be `absolute` or `relative`. The controller resolves relative input
546
659
  from fresh observed volume, accumulates rapid requests against the pending
547
660
  target, applies configured half-step bounds, retries through the existing
@@ -585,7 +698,7 @@ Each example uses synthetic identifiers and configuration, asserts its central i
585
698
 
586
699
  The repository contains no home-network addresses, deployment coordinates, or live credentials. Device hosts and room coordinates are required configuration where applicable.
587
700
 
588
- The display controller stores its Bravia PSK as a Node-RED credential. Keep credentials in Node-RED's encrypted credential store rather than flow fields or repository files.
701
+ The display controller stores its TV pre-shared key as a Node-RED credential. Keep credentials in Node-RED's encrypted credential store rather than flow fields or repository files.
589
702
 
590
703
  Report suspected vulnerabilities privately using the process in
591
704
  [`SECURITY.md`](https://github.com/avantics-hq/node-red-home-automation/blob/main/SECURITY.md), not through a public issue.
@@ -19,7 +19,7 @@ export function run() {
19
19
  source: "wall",
20
20
  person: true,
21
21
  manual: true,
22
- values: {brightness: 254}
22
+ values: {brightnessPct: 100}
23
23
  }
24
24
  }]);
25
25
 
@@ -9,13 +9,14 @@ export function run() {
9
9
  sources: {streamer: "MEDIA"},
10
10
  retryMs: 1000,
11
11
  maxAttempts: 2,
12
- minVolume: 10,
13
- maxVolume: 45
12
+ // In dB; the receiver's 80 is 0 dB.
13
+ minVolumeDb: -70,
14
+ maxVolumeDb: -35
14
15
  };
15
16
  const inputs = [
16
17
  {kind: "observed", line: "PWON\rZMON\rSIMEDIA\rMV30\r"},
17
- {kind: "volume", requestId: "volume-1", mode: "relative", value: 1},
18
- {kind: "volume", requestId: "volume-2", mode: "relative", value: 1},
18
+ {kind: "volume", requestId: "volume-1", mode: "relative", valueDb: 1},
19
+ {kind: "volume", requestId: "volume-2", mode: "relative", valueDb: 1},
19
20
  {kind: "observed", line: "MV32"},
20
21
  {kind: "observed", line: "MV28"}
21
22
  ];
@@ -36,7 +37,7 @@ export function run() {
36
37
  {payload: "MV31\r", operation: "volume"},
37
38
  {payload: "MV32\r", operation: "volume"}
38
39
  ]);
39
- assert.equal(result.state.observed.volume, 28);
40
+ assert.equal(result.state.observed.volume, -52);
40
41
  assert.equal(result.state.volumeRequest, null);
41
42
  assert.deepEqual(result.state.volumeMetrics, {
42
43
  intents: 2,
@@ -1,3 +1,4 @@
1
+ import { type Carried } from "./adopted-request";
1
2
  import type { TraceEntry } from "./bounded-trace";
2
3
  import type { LightingEvent } from "./room-controller";
3
4
  import { type TargetStateEvent } from "./target-state";
@@ -49,6 +50,7 @@ export interface ActivityLightingState {
49
50
  failure: ActivityLightingFailure | null;
50
51
  blockedGeneration: number | null;
51
52
  adoptedGeneration: number | null;
53
+ carried?: Carried | null;
52
54
  }
53
55
  export type ActivityLightingEvent = {
54
56
  kind: "intent";
@@ -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 z2m_light_1 = require("./z2m-light");
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");
@@ -18,7 +19,10 @@ function stable(value) {
18
19
  }
19
20
  return value;
20
21
  }
21
- function valuesMatch(expected, actual) {
22
+ // Whether a light's report shows the profile's values. Reports come in the
23
+ // light's own units, so the profile's are converted first (z2m-light).
24
+ function valuesMatch(profileValues, actual) {
25
+ const expected = (0, z2m_light_1.lightValues)(profileValues).values;
22
26
  return Object.entries(expected).every(([key, value]) => Object.hasOwn(actual, key) && JSON.stringify(stable(actual[key])) === JSON.stringify(stable(value)));
23
27
  }
24
28
  function normaliseLightingProfiles(value) {
@@ -47,6 +51,17 @@ function normaliseLightingProfiles(value) {
47
51
  if (!values || typeof values !== "object" || Array.isArray(values)) {
48
52
  throw new Error(`lighting profile ${name} has invalid values`);
49
53
  }
54
+ // The package's own units, checked when deployed so a bad profile shows
55
+ // on the node rather than leaving lights unstyled.
56
+ const { brightnessPct, colorTempKelvin } = values;
57
+ if (brightnessPct !== undefined &&
58
+ (typeof brightnessPct !== "number" || !Number.isFinite(brightnessPct) || brightnessPct < 0 || brightnessPct > 100)) {
59
+ throw new Error(`lighting profile ${name} brightnessPct must be a number from 0 to 100`);
60
+ }
61
+ if (colorTempKelvin !== undefined &&
62
+ (typeof colorTempKelvin !== "number" || !Number.isFinite(colorTempKelvin) || colorTempKelvin <= 0)) {
63
+ throw new Error(`lighting profile ${name} colorTempKelvin must be a number above 0`);
64
+ }
50
65
  profiles[name] = {
51
66
  targets: [...descriptor.targets],
52
67
  values: { ...values }
@@ -81,7 +96,8 @@ function initialState(saved = {}, profiles = {}) {
81
96
  pending: saved.pending && typeof saved.pending === "object" ? { ...saved.pending } : null,
82
97
  failure: saved.failure && typeof saved.failure === "object" ? { ...saved.failure } : null,
83
98
  blockedGeneration: Number.isInteger(saved.blockedGeneration) ? saved.blockedGeneration : null,
84
- adoptedGeneration: (0, adopted_request_1.savedAdoptedGeneration)(saved)
99
+ adoptedGeneration: (0, adopted_request_1.savedAdoptedGeneration)(saved),
100
+ carried: (0, adopted_request_1.savedCarried)(saved)
85
101
  };
86
102
  }
87
103
  function profileFor(state, config) {
@@ -272,7 +288,7 @@ function transitionActivityLighting(saved, msg, suppliedConfig = {}, nowValue =
272
288
  if (parsedAt === null || typeof observation.observedAt !== "string") {
273
289
  throw new Error("activity lighting observedAt must be an ISO timestamp");
274
290
  }
275
- if (!state.desired || observation.generation !== state.generation) {
291
+ if (!state.desired || !(0, adopted_request_1.answersRequest)(state.carried, state.generation, observation.generation)) {
276
292
  trace("observation", "ignored", "stale-generation");
277
293
  return;
278
294
  }
@@ -309,13 +325,26 @@ function transitionActivityLighting(saved, msg, suppliedConfig = {}, nowValue =
309
325
  // unknown, so the next activity releases every light it holds.
310
326
  let answerWithReading = false;
311
327
  const adoptable = event.kind === "refresh" ? (0, adopted_request_1.adoptableRefresh)(event, state) : null;
312
- const adopted = adoptable !== null && event.kind === "refresh" && typeof event.profile === "string" && Object.hasOwn(config.profiles, event.profile);
328
+ // The same wanted values as the work in hand: carry on under the new
329
+ // request rather than adopting it read-only (see carryOn).
330
+ const carried = event.kind === "refresh" && (0, adopted_request_1.carryOn)(state, adoptable, event.profile === state.desired?.profile, state.phase === "manual_override" || state.phase === "failed" || state.blockedGeneration === state.desired?.generation);
331
+ if (carried)
332
+ trace("refresh", "continued", "same-request", { generation: state.generation });
333
+ const adopted = !carried && adoptable !== null && event.kind === "refresh" && typeof event.profile === "string" && Object.hasOwn(config.profiles, event.profile);
313
334
  if (adopted && event.kind === "refresh") {
335
+ const reason = (0, adopted_request_1.adoptionReason)(state.desired);
336
+ // Replacing a request the theatre already counts as ready, it answers
337
+ // from its reading, not with an interim state the theatre would take as
338
+ // drift.
339
+ answerWithReading = reason === "newer-generation";
340
+ // A request it replaces takes its failure with it.
341
+ state.failure = null;
342
+ state.blockedGeneration = null;
314
343
  state.desired = { ...adoptable, profile: event.profile, requestedAt: now.toISOString() };
315
344
  state.generation = adoptable.generation;
316
345
  state.adoptedGeneration = adoptable.generation;
317
346
  state.applied = { profile: event.profile, targets: null };
318
- trace("refresh", "adopted", "nothing-desired", { profile: event.profile, generation: adoptable.generation });
347
+ trace("refresh", "adopted", reason, { profile: event.profile, generation: adoptable.generation });
319
348
  }
320
349
  if (event.kind === "intent") {
321
350
  acceptIntent(event);
@@ -324,7 +353,7 @@ function transitionActivityLighting(saved, msg, suppliedConfig = {}, nowValue =
324
353
  acceptObservation(event);
325
354
  }
326
355
  else if (event.kind === "command_result") {
327
- if (!state.desired || event.generation !== state.generation || !state.pending) {
356
+ if (!state.desired || !(0, adopted_request_1.answersRequest)(state.carried, state.generation, event.generation) || !state.pending) {
328
357
  trace("command-result", "ignored", "stale-generation");
329
358
  }
330
359
  else if (event.ok === true) {
@@ -11,6 +11,23 @@ export declare function adoptableRefresh(event: {
11
11
  desired: unknown;
12
12
  generation: number;
13
13
  }): AdoptedRequest | null;
14
+ export declare function carryOn(state: {
15
+ desired: AdoptedRequest | null;
16
+ generation: number;
17
+ adoptedGeneration: number | null;
18
+ phase: string;
19
+ pending?: unknown;
20
+ carried?: Carried | null;
21
+ }, adoptable: AdoptedRequest | null, wantsSame: boolean, held: boolean): boolean;
22
+ export interface Carried {
23
+ from: number;
24
+ to: number;
25
+ }
26
+ export declare function savedCarried(saved: {
27
+ carried?: unknown;
28
+ }): Carried | null;
29
+ export declare function answersRequest(carried: Carried | null | undefined, current: number, generation: unknown): boolean;
30
+ export declare function adoptionReason(desired: unknown): string;
14
31
  export interface AdoptableState {
15
32
  generation: number;
16
33
  adoptedGeneration: number | null;
@@ -2,28 +2,82 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ADOPTED_MISMATCH = void 0;
4
4
  exports.adoptableRefresh = adoptableRefresh;
5
+ exports.carryOn = carryOn;
6
+ exports.savedCarried = savedCarried;
7
+ exports.answersRequest = answersRequest;
8
+ exports.adoptionReason = adoptionReason;
5
9
  exports.savedAdoptedGeneration = savedAdoptedGeneration;
6
10
  exports.isAdopted = isAdopted;
7
11
  exports.readsOnly = readsOnly;
8
12
  // A theatre device controller that starts with nothing saved (a redeploy or
9
13
  // restart without a context store) adopts the request the theatre activity
10
14
  // 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
15
+ // it. So does one holding an older request than the refresh's: the theatre
16
+ // moved on without sending it an intent, as when it adopts the activity the
17
+ // devices already show after a manual override or a restart, and the
18
+ // device's answers under its old request would be ignored as stale. It only ever reads the device for that request: a device found in the
12
19
  // wanted state reports ready, and one that isn't is a manual override, with
13
20
  // nothing commanded until a new explicit request. The five device reducers
14
21
  // share these rules so they stay the same.
15
22
  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.
23
+ // The request a refresh carries, if this node can adopt it: with nothing
24
+ // desired, one whose generation isn't older than its own; with a request,
25
+ // only a newer one. Each reducer checks the wanted values itself, and clears
26
+ // what belonged to a request it replaces.
19
27
  function adoptableRefresh(event, state) {
20
- if (event.kind !== "refresh" || state.desired)
28
+ if (event.kind !== "refresh")
21
29
  return null;
22
30
  if (typeof event.requestId !== "string" || event.requestId === "")
23
31
  return null;
24
- if (!Number.isInteger(event.generation) || event.generation < Math.max(1, state.generation))
32
+ if (!Number.isInteger(event.generation))
25
33
  return null;
26
- return { requestId: event.requestId, generation: event.generation };
34
+ const generation = event.generation;
35
+ if (state.desired ? generation <= state.generation : generation < Math.max(1, state.generation))
36
+ return null;
37
+ return { requestId: event.requestId, generation };
38
+ }
39
+ // A newer refresh that wants exactly what this node is already doing (the
40
+ // same mode, power, source or profile): rather than adopting it read-only,
41
+ // which would drop the work in hand (a lamp warming up, a source switching),
42
+ // the node takes the refresh's request ID and generation and carries on. Not
43
+ // when it holds a manual override or a failure (`held`): those are read
44
+ // afresh by adopting. An adopted request stays read-only under the new
45
+ // generation. Returns whether it carried on.
46
+ function carryOn(state, adoptable, wantsSame, held) {
47
+ if (!adoptable || !state.desired || !wantsSame || held)
48
+ return false;
49
+ const adopted = isAdopted(state);
50
+ // Answers to commands already sent are tagged with the generation it
51
+ // carries on from (see answersRequest).
52
+ state.carried = { from: state.desired.generation, to: adoptable.generation };
53
+ state.desired.requestId = adoptable.requestId;
54
+ state.desired.generation = adoptable.generation;
55
+ state.generation = adoptable.generation;
56
+ if (adopted)
57
+ state.adoptedGeneration = adoptable.generation;
58
+ // A command in flight belongs to the request it carries on.
59
+ const command = state.pending?.command;
60
+ if (command && typeof command.generation === "number") {
61
+ command.generation = adoptable.generation;
62
+ command.requestId = adoptable.requestId;
63
+ }
64
+ return true;
65
+ }
66
+ function savedCarried(saved) {
67
+ const carried = saved.carried;
68
+ return carried && Number.isInteger(carried.from) && Number.isInteger(carried.to) ? { from: carried.from, to: carried.to } : null;
69
+ }
70
+ // Whether a reading or command result tagged `generation` answers the
71
+ // request `current`: its own generation, or the one it carried on from, for
72
+ // a command sent before it did. Once a later request replaces it, only that
73
+ // request's generation counts.
74
+ function answersRequest(carried, current, generation) {
75
+ return generation === current || (Boolean(carried) && carried.to === current && generation === carried.from);
76
+ }
77
+ // The trace reason for an adoption: a node with nothing saved, or one whose
78
+ // request the theatre replaced.
79
+ function adoptionReason(desired) {
80
+ return desired ? "newer-generation" : "nothing-desired";
27
81
  }
28
82
  function savedAdoptedGeneration(saved) {
29
83
  return Number.isInteger(saved.adoptedGeneration) ? saved.adoptedGeneration : null;
@@ -8,9 +8,10 @@ export interface AvrConfig {
8
8
  sources: Record<string, string>;
9
9
  retryMs: number;
10
10
  maxAttempts: number;
11
- minVolume: number;
12
- maxVolume: number;
11
+ minVolumeDb: number;
12
+ maxVolumeDb: number;
13
13
  }
14
+ export declare const LEGACY_VOLUME_UNITS = "legacy-volume-units";
14
15
  export interface AvrObserved {
15
16
  power: AvrPower | null;
16
17
  mainZone: MainZone | null;
@@ -69,6 +70,7 @@ export interface AvrState {
69
70
  volumeMetrics: AvrVolumeMetrics;
70
71
  lastAttempt: number;
71
72
  adoptedGeneration: number | null;
73
+ volumeUnits: "dB";
72
74
  }
73
75
  export type AvrInputEvent = {
74
76
  kind: "startup";
@@ -91,7 +93,8 @@ export type AvrInputEvent = {
91
93
  kind: "volume";
92
94
  requestId: string;
93
95
  mode: AvrVolumeMode;
94
- value: number;
96
+ valueDb?: number | string;
97
+ value?: number | string;
95
98
  } | {
96
99
  kind: "tick";
97
100
  };
@@ -126,6 +129,9 @@ export interface AvrOutputEvent {
126
129
  export declare function createAvrState(_config: AvrConfig, saved?: Partial<AvrState>): AvrState;
127
130
  export declare function normaliseAvrConfig(rawConfig: {
128
131
  [K in keyof AvrConfig]?: unknown;
132
+ } & {
133
+ minVolume?: unknown;
134
+ maxVolume?: unknown;
129
135
  }): AvrConfig;
130
136
  export declare function transitionAvr(saved: Partial<AvrState> | undefined, msg: AvrMessage, rawConfig: Partial<AvrConfig>, nowValue?: Date | string | number): {
131
137
  state: AvrState;