@avantics/node-red-home-automation 4.0.3 → 6.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 (116) hide show
  1. package/README.md +447 -64
  2. package/contract-examples/room-lighting.mjs +39 -27
  3. package/contract-examples/switch-gestures.mjs +1 -1
  4. package/contract-examples/volume-ownership.mjs +6 -5
  5. package/dist/lib/activity-lighting-controller.d.ts +9 -2
  6. package/dist/lib/activity-lighting-controller.js +107 -19
  7. package/dist/lib/adopted-request.d.ts +17 -0
  8. package/dist/lib/adopted-request.js +61 -7
  9. package/dist/lib/avr-controller.d.ts +9 -3
  10. package/dist/lib/avr-controller.js +71 -24
  11. package/dist/lib/avr-publishing.d.ts +3 -3
  12. package/dist/lib/avr-publishing.js +11 -5
  13. package/dist/lib/backlighting-controller.d.ts +2 -0
  14. package/dist/lib/backlighting-controller.js +27 -7
  15. package/dist/lib/circadian-policy.d.ts +47 -0
  16. package/dist/lib/circadian-policy.js +111 -0
  17. package/dist/lib/circadian-publishing.d.ts +33 -0
  18. package/dist/lib/circadian-publishing.js +154 -0
  19. package/dist/lib/circadian-schedule.d.ts +4 -0
  20. package/dist/lib/circadian-schedule.js +12 -0
  21. package/dist/lib/command-echo.d.ts +8 -1
  22. package/dist/lib/command-echo.js +37 -6
  23. package/dist/lib/cover-controller.js +4 -0
  24. package/dist/lib/cover-publishing.js +1 -1
  25. package/dist/lib/denon-protocol.d.ts +5 -1
  26. package/dist/lib/denon-protocol.js +27 -11
  27. package/dist/lib/display-mode-controller.d.ts +12 -5
  28. package/dist/lib/display-mode-controller.js +181 -87
  29. package/dist/lib/enable-input.d.ts +3 -0
  30. package/dist/lib/enable-input.js +18 -0
  31. package/dist/lib/house-schedule-publishing.js +1 -1
  32. package/dist/lib/house-schedule.js +2 -2
  33. package/dist/lib/light-contract.d.ts +53 -0
  34. package/dist/lib/light-contract.js +11 -0
  35. package/dist/lib/light-styling.d.ts +2 -2
  36. package/dist/lib/light-styling.js +5 -4
  37. package/dist/lib/motion-policy.d.ts +0 -1
  38. package/dist/lib/motion-policy.js +9 -8
  39. package/dist/lib/motion-publishing.js +3 -2
  40. package/dist/lib/mqtt-message.d.ts +6 -0
  41. package/dist/lib/mqtt-message.js +21 -0
  42. package/dist/lib/occupancy-publishing.js +1 -1
  43. package/dist/lib/power-reading.d.ts +5 -0
  44. package/dist/lib/power-reading.js +13 -0
  45. package/dist/lib/room-controller.d.ts +39 -29
  46. package/dist/lib/room-controller.js +314 -192
  47. package/dist/lib/room-lighting-discovery.d.ts +0 -14
  48. package/dist/lib/room-lighting-discovery.js +20 -126
  49. package/dist/lib/room-publishing.d.ts +10 -12
  50. package/dist/lib/room-publishing.js +65 -125
  51. package/dist/lib/shelly-cover.d.ts +44 -0
  52. package/dist/lib/shelly-cover.js +153 -0
  53. package/dist/lib/shelly-gen2.d.ts +25 -0
  54. package/dist/lib/shelly-gen2.js +58 -0
  55. package/dist/lib/shelly-switch.d.ts +95 -0
  56. package/dist/lib/shelly-switch.js +237 -0
  57. package/dist/lib/source-capability-controller.d.ts +2 -0
  58. package/dist/lib/source-capability-controller.js +27 -6
  59. package/dist/lib/switch-policy.d.ts +1 -1
  60. package/dist/lib/switch-policy.js +1 -1
  61. package/dist/lib/theatre-requests.d.ts +29 -0
  62. package/dist/lib/theatre-requests.js +89 -0
  63. package/dist/lib/theatre-state-contract.d.ts +5 -22
  64. package/dist/lib/theatre-state-contract.js +30 -77
  65. package/dist/lib/toggle-power.d.ts +41 -0
  66. package/dist/lib/toggle-power.js +74 -0
  67. package/dist/lib/topic-names.d.ts +1 -0
  68. package/dist/lib/topic-names.js +7 -0
  69. package/dist/lib/{display-transport.d.ts → transports/display-transport.d.ts} +1 -1
  70. package/dist/lib/{display-transport.js → transports/display-transport.js} +32 -7
  71. package/dist/lib/z2m-cover.d.ts +49 -0
  72. package/dist/lib/z2m-cover.js +120 -0
  73. package/dist/lib/z2m-light-adapter.d.ts +62 -0
  74. package/dist/lib/z2m-light-adapter.js +195 -0
  75. package/dist/lib/z2m-light.d.ts +8 -0
  76. package/dist/lib/z2m-light.js +61 -3
  77. package/dist/nodes/activity-lighting-controller.html +20 -3
  78. package/dist/nodes/activity-lighting-controller.js +21 -0
  79. package/dist/nodes/avr-controller.html +25 -6
  80. package/dist/nodes/avr-controller.js +16 -6
  81. package/dist/nodes/circadian-policy.d.ts +3 -0
  82. package/dist/nodes/circadian-policy.html +140 -0
  83. package/dist/nodes/circadian-policy.js +162 -0
  84. package/dist/nodes/cover-controller.html +4 -3
  85. package/dist/nodes/display-mode-controller.html +58 -11
  86. package/dist/nodes/display-mode-controller.js +19 -6
  87. package/dist/nodes/house-schedule.html +3 -3
  88. package/dist/nodes/motion-policy.html +5 -2
  89. package/dist/nodes/motion-policy.js +3 -0
  90. package/dist/nodes/refused-enable.d.ts +7 -0
  91. package/dist/nodes/refused-enable.js +24 -0
  92. package/dist/nodes/room-controller.html +215 -82
  93. package/dist/nodes/room-controller.js +71 -83
  94. package/dist/nodes/shelly-cover.d.ts +3 -0
  95. package/dist/nodes/shelly-cover.html +65 -0
  96. package/dist/nodes/shelly-cover.js +34 -0
  97. package/dist/nodes/shelly-switch.d.ts +3 -0
  98. package/dist/nodes/shelly-switch.html +82 -0
  99. package/dist/nodes/shelly-switch.js +48 -0
  100. package/dist/nodes/theatre-state-contract.html +4 -3
  101. package/dist/nodes/z2m-cover.d.ts +3 -0
  102. package/dist/nodes/z2m-cover.html +68 -0
  103. package/dist/nodes/z2m-cover.js +41 -0
  104. package/dist/nodes/z2m-light.d.ts +3 -0
  105. package/dist/nodes/z2m-light.html +72 -0
  106. package/dist/nodes/z2m-light.js +50 -0
  107. package/examples/Cover control.json +24 -56
  108. package/examples/Home theatre activity.json +54 -9
  109. package/examples/Home theatre equipment.json +4 -4
  110. package/examples/House schedule.json +106 -24
  111. package/examples/Room lighting.json +54 -11
  112. package/examples/Shelly cover.json +252 -0
  113. package/examples/Shelly switch.json +197 -0
  114. package/package.json +13 -4
  115. package/dist/lib/room-schedule.d.ts +0 -8
  116. package/dist/lib/room-schedule.js +0 -41
@@ -1,6 +1,8 @@
1
1
  import {scheduledLighting} from "../dist/lib/circadian.js";
2
2
  import {resolveSchedule} from "../dist/lib/circadian-schedule.js";
3
+ import {transitionCircadian} from "../dist/lib/circadian-policy.js";
3
4
  import {transitionRoom} from "../dist/lib/room-controller.js";
5
+ import {normaliseZ2mLightConfig, transitionZ2mLight} from "../dist/lib/z2m-light-adapter.js";
4
6
  import {assert, runWhenMain} from "./_shared.mjs";
5
7
 
6
8
  export const name = "room-lighting";
@@ -9,24 +11,27 @@ export function run() {
9
11
  const configuration = {
10
12
  area: "demo_room",
11
13
  displayName: "Demo Room",
12
- targets: [{
13
- id: "ceiling",
14
- stateTopic: "demo/lighting/ceiling/state",
15
- commandTopic: "demo/lighting/ceiling/set"
16
- }],
17
- initialSleep: false,
18
- refreshTransitionSeconds: 30,
14
+ targets: [{id: "ceiling"}],
19
15
  initialTransitionSeconds: 1
20
16
  };
21
17
  const schedule = resolveSchedule("07:00", "23:00");
22
- // The node builds the circadian lighting from its schedule and light
23
- // settings; the room controller only asks it how a light should look.
24
- configuration.lighting = scheduledLighting(schedule, {
25
- sleepBrightnessPct: 5,
26
- maxBrightnessPct: 100,
27
- sleepColorTempKelvin: 1800,
28
- maxColorTempKelvin: 5000
29
- });
18
+ const now = "2026-03-20T10:00:00Z";
19
+ // A circadian lighting policy sends the room how lights should look now; the
20
+ // room uses it for lights it controls.
21
+ const policy = {
22
+ lighting: scheduledLighting(schedule, {
23
+ sleepBrightnessPct: 5,
24
+ maxBrightnessPct: 100,
25
+ sleepColorTempKelvin: 1800,
26
+ maxColorTempKelvin: 5000
27
+ }),
28
+ schedule,
29
+ timesFrom: "own",
30
+ initialSleep: false,
31
+ transitionSeconds: 30,
32
+ intervalSeconds: 60
33
+ };
34
+ const style = {lighting: transitionCircadian(undefined, {kind: "tick"}, policy, now).style};
30
35
  const input = {
31
36
  lighting: {
32
37
  kind: "intent",
@@ -35,18 +40,24 @@ export function run() {
35
40
  source: "motion"
36
41
  }
37
42
  };
38
- const result = transitionRoom(undefined, input, configuration, "2026-03-20T10:00:00Z");
39
- const outputs = result.outputs.map(({topic, payload, retain, lighting_command}) => ({
40
- topic,
41
- payload,
42
- retain,
43
- lighting_command
44
- }));
45
-
43
+ assert.equal(style.lighting.until, "2026-03-20T10:03:00.000Z");
44
+ const styled = transitionRoom(undefined, style, configuration, now);
45
+ assert.equal(styled.commands.length, 0);
46
+ const result = transitionRoom(styled.state, input, configuration, now);
47
+ // The room's neutral command, for the light's adapter.
48
+ assert.equal(result.commands.length, 1);
49
+ const command = result.commands[0];
50
+ assert.equal(command.kind, "command");
51
+ assert.equal(command.target, "ceiling");
52
+ assert.equal(command.state, "ON");
53
+ assert.equal(command.source, "motion");
54
+ // The Zigbee2MQTT light adapter turns it into the light's own message.
55
+ const light = normaliseZ2mLightConfig({target: "ceiling", baseTopic: "demo", friendlyName: "ceiling"});
56
+ const outputs = transitionZ2mLight(undefined, {light: command}, light, now).publications;
46
57
  assert.equal(outputs.length, 1);
47
- assert.equal(outputs[0].topic, "demo/lighting/ceiling/set");
58
+ assert.equal(outputs[0].topic, "demo/ceiling/set");
48
59
  assert.equal(outputs[0].payload.state, "ON");
49
- assert.equal(outputs[0].lighting_command.source, "motion");
60
+ assert.equal(typeof outputs[0].payload.brightness, "number");
50
61
 
51
62
  return {
52
63
  configuration: {
@@ -54,9 +65,10 @@ export function run() {
54
65
  targets: configuration.targets.map(({id}) => id),
55
66
  schedule
56
67
  },
57
- inputs: [input],
68
+ inputs: [style, input],
69
+ commands: result.commands,
58
70
  outputs,
59
- invariant: "The room controller is the only transport command owner and records the policy source."
71
+ invariant: "The room controller owns its lights' commands and records the policy source; a style only shapes how its lights look; each light's adapter speaks the device's own messages."
60
72
  };
61
73
  }
62
74
 
@@ -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";
@@ -23,7 +24,7 @@ export interface ActivityLightingObservation {
23
24
  on: boolean;
24
25
  manual: boolean;
25
26
  available: boolean;
26
- values: Record<string, unknown>;
27
+ showsLast: boolean;
27
28
  observedAt: string;
28
29
  }
29
30
  export interface ActivityLightingPending {
@@ -49,6 +50,10 @@ export interface ActivityLightingState {
49
50
  failure: ActivityLightingFailure | null;
50
51
  blockedGeneration: number | null;
51
52
  adoptedGeneration: number | null;
53
+ carried?: Carried | null;
54
+ reported?: Record<string, string[]>;
55
+ held?: string[];
56
+ overridden?: string[];
52
57
  }
53
58
  export type ActivityLightingEvent = {
54
59
  kind: "intent";
@@ -63,7 +68,8 @@ export type ActivityLightingEvent = {
63
68
  on: boolean;
64
69
  manual?: boolean;
65
70
  available?: boolean;
66
- values?: Record<string, unknown>;
71
+ fields?: string[];
72
+ showsLast?: boolean;
67
73
  observedAt: string;
68
74
  } | {
69
75
  kind: "command_result";
@@ -105,6 +111,7 @@ export interface ActivityLightingOutputEvent {
105
111
  };
106
112
  }, ActivityLightingFailure>;
107
113
  }
114
+ export declare const VALUES_NOT_REPORTED = "values-not-reported";
108
115
  export declare function normaliseLightingProfiles(value: unknown): ActivityLightingProfiles;
109
116
  export declare function normaliseActivityLightingConfig(config?: Partial<ActivityLightingConfig> & {
110
117
  profiles?: unknown;
@@ -1,25 +1,29 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.VALUES_NOT_REPORTED = void 0;
3
4
  exports.normaliseLightingProfiles = normaliseLightingProfiles;
4
5
  exports.normaliseActivityLightingConfig = normaliseActivityLightingConfig;
5
6
  exports.transitionActivityLighting = transitionActivityLighting;
7
+ const z2m_light_1 = require("./z2m-light");
6
8
  const adopted_request_1 = require("./adopted-request");
7
9
  const settings_1 = require("./settings");
8
10
  const observation_time_1 = require("./observation-time");
9
11
  const target_state_1 = require("./target-state");
10
12
  const PROFILE_NAME = /^[a-z][a-z0-9_-]*$/;
11
13
  const TARGET_NAME = /^[a-z][a-z0-9_-]*$/;
12
- function stable(value) {
13
- if (Array.isArray(value))
14
- return value.map(stable);
15
- if (value && typeof value === "object") {
16
- const record = value;
17
- return Object.fromEntries(Object.keys(record).sort().map((key) => [key, stable(record[key])]));
18
- }
19
- return value;
20
- }
21
- function valuesMatch(expected, actual) {
22
- return Object.entries(expected).every(([key, value]) => Object.hasOwn(actual, key) && JSON.stringify(stable(actual[key])) === JSON.stringify(stable(value)));
14
+ // Whether a light's report shows the profile's values. Reports come in the
15
+ // light's own units, so the profile's are converted first (z2m-light).
16
+ // Traced when a light the profile gives values to has never reported any of
17
+ // them since start, so it is confirmed by being on: the node warns once.
18
+ exports.VALUES_NOT_REPORTED = "values-not-reported";
19
+ // The reading fields that show a profile's values.
20
+ const PROFILE_FIELDS = { brightnessPct: "brightness", colorTempKelvin: "colorTemp" };
21
+ // Whether a light has reported any of the profile's fields since start; true
22
+ // when the profile sets none of them, as then there is nothing but on to
23
+ // check.
24
+ function reportsAnyOf(profileValues, reported) {
25
+ const expected = Object.keys(profileValues).flatMap((key) => (PROFILE_FIELDS[key] ? [PROFILE_FIELDS[key]] : []));
26
+ return expected.length === 0 || expected.some((field) => reported.includes(field));
23
27
  }
24
28
  function normaliseLightingProfiles(value) {
25
29
  if (!value || typeof value !== "object" || Array.isArray(value)) {
@@ -47,6 +51,21 @@ 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 removed = z2m_light_1.REMOVED_LIGHT_FIELDS.filter((field) => Object.hasOwn(values, field));
57
+ if (removed.length) {
58
+ throw new Error(`lighting profile ${name} uses ${removed.join(" and ")}, removed in 6.0: use brightnessPct (0-100) and colorTempKelvin`);
59
+ }
60
+ const { brightnessPct, colorTempKelvin } = values;
61
+ if (brightnessPct !== undefined &&
62
+ (typeof brightnessPct !== "number" || !Number.isFinite(brightnessPct) || brightnessPct < 0 || brightnessPct > 100)) {
63
+ throw new Error(`lighting profile ${name} brightnessPct must be a number from 0 to 100`);
64
+ }
65
+ if (colorTempKelvin !== undefined &&
66
+ (typeof colorTempKelvin !== "number" || !Number.isFinite(colorTempKelvin) || colorTempKelvin <= 0)) {
67
+ throw new Error(`lighting profile ${name} colorTempKelvin must be a number above 0`);
68
+ }
50
69
  profiles[name] = {
51
70
  targets: [...descriptor.targets],
52
71
  values: { ...values }
@@ -81,7 +100,12 @@ function initialState(saved = {}, profiles = {}) {
81
100
  pending: saved.pending && typeof saved.pending === "object" ? { ...saved.pending } : null,
82
101
  failure: saved.failure && typeof saved.failure === "object" ? { ...saved.failure } : null,
83
102
  blockedGeneration: Number.isInteger(saved.blockedGeneration) ? saved.blockedGeneration : null,
84
- adoptedGeneration: (0, adopted_request_1.savedAdoptedGeneration)(saved)
103
+ adoptedGeneration: (0, adopted_request_1.savedAdoptedGeneration)(saved),
104
+ carried: (0, adopted_request_1.savedCarried)(saved),
105
+ reported: Object.fromEntries(Object.entries(saved.reported || {})
106
+ .filter(([, fields]) => Array.isArray(fields)).map(([target, fields]) => [target, fields.map(String)])),
107
+ held: Array.isArray(saved.held) ? saved.held.map(String) : [],
108
+ overridden: Array.isArray(saved.overridden) ? saved.overridden.map(String) : []
85
109
  };
86
110
  }
87
111
  function profileFor(state, config) {
@@ -149,7 +173,21 @@ function transitionActivityLighting(saved, msg, suppliedConfig = {}, nowValue =
149
173
  trace("lighting", "failed", reason, { profile: state.desired?.profile ?? null });
150
174
  }
151
175
  function issueApply(attempt) {
152
- commands.push(commandFor(state, config, "apply", attempt));
176
+ const command = commandFor(state, config, "apply", attempt);
177
+ // Lights a person took over from the last request: taken back, so not
178
+ // skipped as a person's (preserveManual). Every other light as before.
179
+ const reclaim = (state.overridden ?? []).filter((target) => command.lighting?.targets?.includes(target));
180
+ if (reclaim.length && command.lighting) {
181
+ const rest = command.lighting.targets.filter((target) => !reclaim.includes(target));
182
+ if (rest.length)
183
+ commands.push({ ...command, lighting: { ...command.lighting, targets: rest } });
184
+ const { preserveManual: _preserve, ...taken } = command.lighting;
185
+ commands.push({ ...command, lighting: { ...taken, targets: reclaim } });
186
+ trace("command", "emitted", "taking-back", { targets: reclaim });
187
+ }
188
+ else {
189
+ commands.push(command);
190
+ }
153
191
  state.pending = { attempt, deadlineAt: nowMs + config.confirmationTimeoutMs };
154
192
  state.phase = "transitioning";
155
193
  trace("command", "emitted", null, { operation: "apply", profile: state.desired?.profile, attempt });
@@ -176,11 +214,32 @@ function transitionActivityLighting(saved, msg, suppliedConfig = {}, nowValue =
176
214
  fail("lighting-unavailable");
177
215
  return;
178
216
  }
217
+ if (observation.manual && state.held?.includes(target)) {
218
+ // A person changed a light this request held: theirs now, as on the
219
+ // other theatre targets. The next request takes it back.
220
+ state.pending = null;
221
+ state.phase = "manual_override";
222
+ if (!state.overridden?.includes(target))
223
+ state.overridden = [...(state.overridden ?? []), target];
224
+ trace("observation", "manual_override", "person-changed", { target });
225
+ return;
226
+ }
179
227
  if (observation.manual || !observation.on) {
228
+ // A person's before this request (or off): left as it is.
180
229
  counts.preserved += 1;
181
230
  continue;
182
231
  }
183
- if (!valuesMatch(profile.values, observation.values)) {
232
+ // A light that has never reported any of the profile's fields (one
233
+ // that only switches on and off) is confirmed by being on, and traced so
234
+ // the node can say its values may not apply.
235
+ if (!reportsAnyOf(profile.values, state.reported?.[target] ?? [])) {
236
+ trace("observation", "confirmed", exports.VALUES_NOT_REPORTED, { target });
237
+ counts.matched += 1;
238
+ continue;
239
+ }
240
+ // It shows the profile's values when it shows the last command sent to
241
+ // it: the profile's, as the activity holds the light.
242
+ if (!observation.showsLast) {
184
243
  if ((0, adopted_request_1.isAdopted)(state)) {
185
244
  // An adopted request the lights don't match: someone else's, and
186
245
  // never re-applied.
@@ -253,6 +312,7 @@ function transitionActivityLighting(saved, msg, suppliedConfig = {}, nowValue =
253
312
  }
254
313
  state.generation = intent.generation;
255
314
  state.observed = {};
315
+ state.held = [];
256
316
  state.pending = null;
257
317
  state.failure = null;
258
318
  state.blockedGeneration = null;
@@ -260,6 +320,8 @@ function transitionActivityLighting(saved, msg, suppliedConfig = {}, nowValue =
260
320
  reconcile();
261
321
  else
262
322
  issueApply(1);
323
+ // Taken back with this request's apply (above), or no longer styled.
324
+ state.overridden = [];
263
325
  trace("intent", "accepted", null, { profile: intent.profile, generation: intent.generation });
264
326
  }
265
327
  function acceptObservation(observation) {
@@ -272,7 +334,7 @@ function transitionActivityLighting(saved, msg, suppliedConfig = {}, nowValue =
272
334
  if (parsedAt === null || typeof observation.observedAt !== "string") {
273
335
  throw new Error("activity lighting observedAt must be an ISO timestamp");
274
336
  }
275
- if (!state.desired || observation.generation !== state.generation) {
337
+ if (!state.desired || !(0, adopted_request_1.answersRequest)(state.carried, state.generation, observation.generation)) {
276
338
  trace("observation", "ignored", "stale-generation");
277
339
  return;
278
340
  }
@@ -292,12 +354,22 @@ function transitionActivityLighting(saved, msg, suppliedConfig = {}, nowValue =
292
354
  trace("observation", "ignored", "out-of-order", { target: observation.target });
293
355
  return;
294
356
  }
357
+ // What it reports since start: which fields, for the profiles' values.
358
+ const fields = Array.isArray(observation.fields) ? observation.fields.map(String) : [];
359
+ const known = state.reported?.[observation.target] ?? [];
360
+ if (fields.some((field) => !known.includes(field))) {
361
+ state.reported = { ...state.reported, [observation.target]: [...new Set([...known, ...fields])] };
362
+ }
363
+ // Held by this request: on, and not a person's.
364
+ if (observation.on === true && observation.manual !== true && !(state.held ?? []).includes(observation.target)) {
365
+ state.held = [...(state.held ?? []), observation.target];
366
+ }
295
367
  state.observed[observation.target] = {
296
368
  target: observation.target,
297
369
  on: observation.on === true,
298
370
  manual: observation.manual === true,
299
371
  available: observation.available !== false,
300
- values: observation.values && typeof observation.values === "object" ? { ...observation.values } : {},
372
+ showsLast: observation.showsLast === true,
301
373
  observedAt: bounded.observedAt
302
374
  };
303
375
  trace("observation", "accepted", null, { target: observation.target });
@@ -309,13 +381,26 @@ function transitionActivityLighting(saved, msg, suppliedConfig = {}, nowValue =
309
381
  // unknown, so the next activity releases every light it holds.
310
382
  let answerWithReading = false;
311
383
  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);
384
+ // The same wanted values as the work in hand: carry on under the new
385
+ // request rather than adopting it read-only (see carryOn).
386
+ 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);
387
+ if (carried)
388
+ trace("refresh", "continued", "same-request", { generation: state.generation });
389
+ const adopted = !carried && adoptable !== null && event.kind === "refresh" && typeof event.profile === "string" && Object.hasOwn(config.profiles, event.profile);
313
390
  if (adopted && event.kind === "refresh") {
391
+ const reason = (0, adopted_request_1.adoptionReason)(state.desired);
392
+ // Replacing a request the theatre already counts as ready, it answers
393
+ // from its reading, not with an interim state the theatre would take as
394
+ // drift.
395
+ answerWithReading = reason === "newer-generation";
396
+ // A request it replaces takes its failure with it.
397
+ state.failure = null;
398
+ state.blockedGeneration = null;
314
399
  state.desired = { ...adoptable, profile: event.profile, requestedAt: now.toISOString() };
315
400
  state.generation = adoptable.generation;
316
401
  state.adoptedGeneration = adoptable.generation;
317
402
  state.applied = { profile: event.profile, targets: null };
318
- trace("refresh", "adopted", "nothing-desired", { profile: event.profile, generation: adoptable.generation });
403
+ trace("refresh", "adopted", reason, { profile: event.profile, generation: adoptable.generation });
319
404
  }
320
405
  if (event.kind === "intent") {
321
406
  acceptIntent(event);
@@ -324,7 +409,7 @@ function transitionActivityLighting(saved, msg, suppliedConfig = {}, nowValue =
324
409
  acceptObservation(event);
325
410
  }
326
411
  else if (event.kind === "command_result") {
327
- if (!state.desired || event.generation !== state.generation || !state.pending) {
412
+ if (!state.desired || !(0, adopted_request_1.answersRequest)(state.carried, state.generation, event.generation) || !state.pending) {
328
413
  trace("command-result", "ignored", "stale-generation");
329
414
  }
330
415
  else if (event.ok === true) {
@@ -360,6 +445,9 @@ function transitionActivityLighting(saved, msg, suppliedConfig = {}, nowValue =
360
445
  }
361
446
  else if (event.kind === "startup" || event.kind === "refresh") {
362
447
  state.observed = {};
448
+ // Since start: what each light reports is learned again.
449
+ if (event.kind === "startup")
450
+ state.reported = {};
363
451
  state.pending = null;
364
452
  if (state.desired) {
365
453
  if (profileFor(state, config).targets.length === 0)
@@ -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 REMOVED_VOLUME_VALUE = "removed-volume-value";
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?: unknown;
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;