@avantics/node-red-home-automation 2.3.0 → 3.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 (79) hide show
  1. package/README.md +32 -8
  2. package/contract-examples/room-lighting.mjs +12 -7
  3. package/dist/lib/activity-lighting-controller.d.ts +13 -25
  4. package/dist/lib/activity-lighting-controller.js +15 -11
  5. package/dist/lib/avr-controller.d.ts +13 -47
  6. package/dist/lib/avr-controller.js +39 -90
  7. package/dist/lib/backlighting-controller.d.ts +12 -25
  8. package/dist/lib/backlighting-controller.js +11 -18
  9. package/dist/lib/bounded-trace.d.ts +6 -0
  10. package/dist/lib/command-echo.d.ts +20 -0
  11. package/dist/lib/command-echo.js +82 -0
  12. package/dist/lib/cover-controller.d.ts +15 -28
  13. package/dist/lib/cover-controller.js +6 -8
  14. package/dist/lib/denon-protocol.d.ts +29 -0
  15. package/dist/lib/denon-protocol.js +76 -0
  16. package/dist/lib/display-mode-controller.d.ts +7 -18
  17. package/dist/lib/display-mode-controller.js +39 -47
  18. package/dist/lib/motion-policy.d.ts +12 -22
  19. package/dist/lib/motion-policy.js +53 -56
  20. package/dist/lib/occupancy-fusion.d.ts +8 -12
  21. package/dist/lib/room-controller.d.ts +14 -34
  22. package/dist/lib/room-controller.js +80 -132
  23. package/dist/lib/room-lighting-discovery.d.ts +9 -0
  24. package/dist/lib/room-lighting-discovery.js +45 -0
  25. package/dist/lib/settings.d.ts +5 -0
  26. package/dist/lib/settings.js +68 -0
  27. package/dist/lib/source-capability-controller.d.ts +30 -35
  28. package/dist/lib/source-capability-controller.js +35 -36
  29. package/dist/lib/switch-policy.d.ts +2 -7
  30. package/dist/lib/target-state.d.ts +24 -0
  31. package/dist/lib/target-state.js +38 -0
  32. package/dist/lib/theatre-activity-controller.d.ts +6 -108
  33. package/dist/lib/theatre-activity-controller.js +67 -318
  34. package/dist/lib/theatre-ha-discovery.d.ts +14 -0
  35. package/dist/lib/theatre-ha-discovery.js +163 -0
  36. package/dist/lib/theatre-metrics.d.ts +4 -0
  37. package/dist/lib/theatre-metrics.js +66 -0
  38. package/dist/lib/theatre-profiles.d.ts +23 -0
  39. package/dist/lib/theatre-profiles.js +73 -0
  40. package/dist/lib/theatre-refresh.d.ts +20 -0
  41. package/dist/lib/theatre-refresh.js +46 -0
  42. package/dist/lib/theatre-slo.js +7 -9
  43. package/dist/lib/theatre-state-contract.d.ts +7 -19
  44. package/dist/lib/theatre-state-contract.js +33 -169
  45. package/dist/lib/theatre-state.d.ts +110 -0
  46. package/dist/lib/theatre-state.js +139 -0
  47. package/dist/lib/wall-input.d.ts +2 -7
  48. package/dist/lib/z2m-light.d.ts +16 -0
  49. package/dist/lib/z2m-light.js +36 -0
  50. package/dist/nodes/activity-lighting-controller.html +5 -3
  51. package/dist/nodes/activity-lighting-controller.js +21 -52
  52. package/dist/nodes/adapter.d.ts +15 -0
  53. package/dist/nodes/adapter.js +60 -0
  54. package/dist/nodes/avr-controller.html +3 -3
  55. package/dist/nodes/avr-controller.js +17 -56
  56. package/dist/nodes/backlighting-controller.html +1 -1
  57. package/dist/nodes/backlighting-controller.js +25 -47
  58. package/dist/nodes/display-mode-controller.html +2 -2
  59. package/dist/nodes/display-mode-controller.js +19 -57
  60. package/dist/nodes/motion-policy.html +23 -10
  61. package/dist/nodes/motion-policy.js +14 -135
  62. package/dist/nodes/occupancy-fusion.html +2 -2
  63. package/dist/nodes/occupancy-fusion.js +23 -29
  64. package/dist/nodes/room-controller.html +80 -26
  65. package/dist/nodes/room-controller.js +37 -54
  66. package/dist/nodes/source-capability-controller.html +4 -13
  67. package/dist/nodes/source-capability-controller.js +17 -52
  68. package/dist/nodes/switch-policy.html +3 -3
  69. package/dist/nodes/switch-policy.js +23 -42
  70. package/dist/nodes/theatre-activity-controller.html +4 -2
  71. package/dist/nodes/theatre-activity-controller.js +18 -45
  72. package/dist/nodes/theatre-state-contract.html +55 -22
  73. package/dist/nodes/theatre-state-contract.js +30 -41
  74. package/examples/Home theatre activity.json +13 -12
  75. package/examples/Home theatre equipment.json +4 -4
  76. package/examples/Room lighting.json +9 -9
  77. package/package.json +1 -1
  78. package/dist/lib/circadian-refresh.d.ts +0 -7
  79. package/dist/lib/circadian-refresh.js +0 -11
package/README.md CHANGED
@@ -35,7 +35,9 @@ The nodes come in three groups. Each group has an importable example flow
35
35
 
36
36
  Motion, presence, illuminance and wall switches drive one room's lights, with
37
37
  circadian styling and manual ownership. Wire occupancy fusion into the motion
38
- policy, and the motion and switch policies into the room controller. Circadian
38
+ policy, wall switches into the switch policy, and both policies into the room
39
+ 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
39
41
  levels follow the room controller's wake and bed times (default 07:00 and
40
42
  23:00): they rise over the hour after waking, stay bright and cool through the
41
43
  day, and wind down to the sleep settings over the three hours before bed. Times
@@ -45,7 +47,7 @@ Example: [`Room lighting.json`](https://github.com/avantics-hq/node-red-home-aut
45
47
  | Node | Purpose |
46
48
  |---|---|
47
49
  | `home-occupancy-fusion` | Combines PIR motion with optional presence sensing. |
48
- | `home-motion-lighting-policy` | Converts occupancy and illuminance into lighting intent with observable wall-input baselines. |
50
+ | `home-motion-lighting-policy` | Converts occupancy and illuminance into lighting intent. A `delay` message (in seconds) or `illuminance-cut-off` message overrides its settings until they are changed and redeployed. |
49
51
  | `home-switch-lighting-policy` | Converts raw edges or pre-classified button actions into lighting intent while exposing input freshness and availability. |
50
52
  | `home-room-lighting-controller` | Owns the room's light commands, adaptive styling, manual and held lights, and lighting state. |
51
53
 
@@ -81,7 +83,7 @@ Example: [`Home theatre activity.json`](https://github.com/avantics-hq/node-red-
81
83
 
82
84
  | Node | Purpose |
83
85
  |---|---|
84
- | `home-theatre-state-contract` | Bridges non-retained activity requests to retained MQTT truth and HA discovery. |
86
+ | `home-theatre-state-contract` | Bridges non-retained activity requests to retained MQTT truth and, optionally, HA discovery. |
85
87
  | `home-theatre-activity-controller` | Owns latest-request-wins activity state and aggregates target evidence. |
86
88
  | `home-activity-lighting-controller` | Applies activity styles to room lights and holds them while the activity is active. |
87
89
 
@@ -109,11 +111,28 @@ also attaches the package tarball and its SHA-256 checksum. Install a downloaded
109
111
  tarball through **Manage palette → Install → Upload module**, or with:
110
112
 
111
113
  ```sh
112
- npm install /path/to/avantics-node-red-home-automation-2.3.0.tgz
114
+ npm install /path/to/avantics-node-red-home-automation-3.0.0.tgz
113
115
  ```
114
116
 
115
117
  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.
116
118
 
119
+ ### Upgrading from 2.x
120
+
121
+ Version 3.0 changes some behaviour. Check these after upgrading:
122
+
123
+ - **Wall switches go through the switch lighting policy node.** The motion lighting policy no longer handles them,
124
+ and ignores switch messages, so rewire any wall switch that feeds a motion node. The room lighting controller now
125
+ keeps a light that a person set after the room went vacant, instead of the motion node.
126
+ - **The motion node's `delay` message takes seconds,** the same unit as its "Vacancy seconds" setting; it took
127
+ minutes before. A redeploy with a changed vacancy delay or lux cutoff now takes effect.
128
+ - **Settings are checked when you deploy.** An emptied or unusable setting shows "invalid configuration", and the
129
+ node's log says which setting is wrong. A setting your flow saved before it existed still takes its default.
130
+ - **No node assumes a room.** An empty area is allowed, except on the theatre state contract, which needs one to name
131
+ its topics. A room lighting controller with no area still controls its lights, but publishes no state or discovery.
132
+ - **MQTT state publishing and Home Assistant discovery are opt-in** on the room lighting controller and the theatre
133
+ state contract. New nodes start with them off. Nodes in a flow saved before 3.0 keep publishing until you untick
134
+ the setting. Switching discovery off removes the entities from Home Assistant.
135
+
117
136
  The whole-theatre MQTT contract uses non-retained requests at
118
137
  `home/<area>/theatre/request`; every request supplies a unique `requestId` and an
119
138
  explicit configured activity. Controller output is retained under `desired`,
@@ -195,18 +214,23 @@ or a newer owner who takes it over), a person (`manual: true`, an external
195
214
  command on the command topic, or a change seen at the light), or a release.
196
215
  Other intents, such as motion ON or OFF and owner-less values, leave it alone
197
216
  and are traced as `ignored held-by`; their other targets are still handled.
198
- The package's wall-switch policies mark presses with `person: true`. Owner-less
217
+ The switch policy marks presses with `person: true`. Owner-less
199
218
  intents, with or without values, reach a held light only with `manual: true` or
200
219
  `person: true`; a flow acting for a person, such as a dashboard, sets one.
201
- Switching a light off by its owner or a person returns it to `in-control`. On startup
202
- and whenever a target's state changes, the controller sends a retained message
203
- on its command output:
220
+ Switching a light off by its owner or a person returns it to `in-control`. With
221
+ **Publish state over MQTT** on (new nodes start with it off; nodes saved before
222
+ the setting existed keep it on), on startup and whenever a target's state
223
+ changes, the controller sends a retained message on its command output:
204
224
 
205
225
  ```js
206
226
  {topic: "home/<area>/lighting/<target>/control", payload: {state: "overridden", owner: "theatre"}, retain: true}
207
227
  ```
208
228
 
209
229
  Flows that filter that output by topic must pass the `/control` topics through.
230
+ It also publishes the circadian state on `home/<area>/circadian/state`, and
231
+ acts on ON or OFF sent to `home/<area>/circadian/set`, which is where the Home
232
+ Assistant circadian switch sends them: wire an MQTT in node subscribed to that
233
+ topic into the room controller.
210
234
 
211
235
  ## Receiver volume ownership
212
236
 
@@ -1,3 +1,5 @@
1
+ import {scheduledLighting} from "../dist/lib/circadian.js";
2
+ import {resolveSchedule} from "../dist/lib/circadian-schedule.js";
1
3
  import {transitionRoom} from "../dist/lib/room-controller.js";
2
4
  import {assert, runWhenMain} from "./_shared.mjs";
3
5
 
@@ -13,15 +15,18 @@ export function run() {
13
15
  commandTopic: "demo/lighting/ceiling/set"
14
16
  }],
15
17
  initialSleep: false,
16
- sleepBrightnessPct: 5,
17
- maxBrightnessPct: 100,
18
- sleepColorTempKelvin: 1800,
19
- maxColorTempKelvin: 5000,
20
- wakeTime: "07:00",
21
- bedTime: "23:00",
22
18
  refreshTransitionSeconds: 30,
23
19
  initialTransitionSeconds: 1
24
20
  };
21
+ 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
+ });
25
30
  const input = {
26
31
  lighting: {
27
32
  kind: "intent",
@@ -47,7 +52,7 @@ export function run() {
47
52
  configuration: {
48
53
  area: configuration.area,
49
54
  targets: configuration.targets.map(({id}) => id),
50
- schedule: {wakeTime: configuration.wakeTime, bedTime: configuration.bedTime}
55
+ schedule
51
56
  },
52
57
  inputs: [input],
53
58
  outputs,
@@ -1,4 +1,6 @@
1
+ import type { TraceEntry } from "./bounded-trace";
1
2
  import type { LightingEvent } from "./room-controller";
3
+ import { type TargetStateEvent } from "./target-state";
2
4
  export interface ActivityLightingProfile {
3
5
  targets: string[];
4
6
  values: Record<string, unknown>;
@@ -85,26 +87,17 @@ export interface ActivityLightingCommand {
85
87
  lighting?: LightingEvent;
86
88
  }
87
89
  export interface ActivityLightingOutputEvent {
88
- theatre: {
89
- kind: "target_state";
90
- target: "lighting";
91
- requestId: string;
92
- generation: number;
93
- status: string;
94
- observedAt: string;
95
- details: {
96
- profile: string;
97
- matched: number;
98
- preserved: number;
99
- expected: number;
100
- metrics: {
101
- attempts: number;
102
- retries: number;
103
- fallbackUsed: boolean;
104
- };
90
+ theatre: TargetStateEvent<"lighting", {
91
+ profile: string;
92
+ matched: number;
93
+ preserved: number;
94
+ expected: number;
95
+ metrics: {
96
+ attempts: number;
97
+ retries: number;
98
+ fallbackUsed: boolean;
105
99
  };
106
- failure?: ActivityLightingFailure;
107
- };
100
+ }, ActivityLightingFailure>;
108
101
  }
109
102
  export declare function normaliseLightingProfiles(value: unknown): ActivityLightingProfiles;
110
103
  export declare function normaliseActivityLightingConfig(config?: Partial<ActivityLightingConfig> & {
@@ -116,12 +109,7 @@ export declare function transitionActivityLighting(saved: Partial<ActivityLighti
116
109
  state: ActivityLightingState;
117
110
  commands: ActivityLightingCommand[];
118
111
  events: ActivityLightingOutputEvent[];
119
- traces: {
120
- event: string;
121
- outcome: string;
122
- reason: string | null;
123
- details: Record<string, unknown>;
124
- }[];
112
+ traces: TraceEntry<Record<string, unknown>>[];
125
113
  status: {
126
114
  phase: string;
127
115
  text: string;
@@ -3,7 +3,9 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.normaliseLightingProfiles = normaliseLightingProfiles;
4
4
  exports.normaliseActivityLightingConfig = normaliseActivityLightingConfig;
5
5
  exports.transitionActivityLighting = transitionActivityLighting;
6
+ const settings_1 = require("./settings");
6
7
  const observation_time_1 = require("./observation-time");
8
+ const target_state_1 = require("./target-state");
7
9
  const PROFILE_NAME = /^[a-z][a-z0-9_-]*$/;
8
10
  const TARGET_NAME = /^[a-z][a-z0-9_-]*$/;
9
11
  function stable(value) {
@@ -52,12 +54,11 @@ function normaliseLightingProfiles(value) {
52
54
  return profiles;
53
55
  }
54
56
  function normaliseActivityLightingConfig(config = {}) {
55
- const owner = typeof config.owner === "string" ? config.owner.trim() : "";
56
57
  return {
57
58
  profiles: normaliseLightingProfiles(config.profiles),
58
- owner: owner || "activity",
59
- confirmationTimeoutMs: Math.max(1000, Number(config.confirmationTimeoutMs) || 15000),
60
- maxAttempts: Math.max(1, Math.floor(Number(config.maxAttempts) || 2))
59
+ owner: (0, settings_1.textSetting)(config.owner, "owner", "activity"),
60
+ confirmationTimeoutMs: Math.max(1000, (0, settings_1.numberSetting)(config.confirmationTimeoutMs, "confirmation timeout", 15000)),
61
+ maxAttempts: Math.max(1, Math.floor((0, settings_1.numberSetting)(config.maxAttempts, "max attempts", 2)))
61
62
  };
62
63
  }
63
64
  function initialState(saved = {}, profiles = {}) {
@@ -333,6 +334,11 @@ function transitionActivityLighting(saved, msg, suppliedConfig = {}, nowValue =
333
334
  else {
334
335
  commands.push(commandFor(state, config, "observe", 0));
335
336
  state.phase = "confirming";
337
+ // After a restart nothing else would end an unanswered observe: give
338
+ // it a deadline, so it re-applies and then fails as a live request.
339
+ if (event.kind === "startup" && state.blockedGeneration !== state.generation) {
340
+ state.pending = { attempt: 0, deadlineAt: nowMs + config.confirmationTimeoutMs };
341
+ }
336
342
  trace(event.kind, "observing", null, { profile: state.desired.profile });
337
343
  }
338
344
  }
@@ -344,12 +350,11 @@ function transitionActivityLighting(saved, msg, suppliedConfig = {}, nowValue =
344
350
  throw new Error("unknown activity lighting event kind");
345
351
  }
346
352
  if (state.desired) {
347
- const theatre = {
348
- kind: "target_state",
353
+ const theatre = (0, target_state_1.targetStateEvent)({
349
354
  target: "lighting",
350
355
  requestId: state.desired.requestId,
351
356
  generation: state.generation,
352
- status: state.phase === "failed" ? "failed" : state.phase === "ready" ? "ready" : state.phase,
357
+ status: (0, target_state_1.asTargetStatus)(state.phase, "confirming"),
353
358
  observedAt: now.toISOString(),
354
359
  details: {
355
360
  profile: state.desired.profile,
@@ -361,10 +366,9 @@ function transitionActivityLighting(saved, msg, suppliedConfig = {}, nowValue =
361
366
  retries: Math.max(0, (state.pending?.attempt ?? 1) - 1),
362
367
  fallbackUsed: false
363
368
  }
364
- }
365
- };
366
- if (state.failure)
367
- theatre.failure = { ...state.failure };
369
+ },
370
+ failure: state.failure
371
+ });
368
372
  events.push({ theatre });
369
373
  }
370
374
  return { state, commands, events, traces, status: statusFor(state) };
@@ -1,6 +1,7 @@
1
- export declare const QUERY_COMMAND = "PW?\rZM?\rSI?\rMV?\r";
2
- export type AvrPower = "on" | "standby";
3
- export type MainZone = "on" | "off";
1
+ import type { TraceEntry } from "./bounded-trace";
2
+ import { type TargetStateEvent } from "./target-state";
3
+ import { type AvrPower, type MainZone } from "./denon-protocol";
4
+ export { QUERY_COMMAND, formatVolumeCommand, parseAvrLine, type AvrPower, type MainZone, type ParsedAvrLine } from "./denon-protocol";
4
5
  export type AvrField = "power" | "mainZone" | "source" | "volume";
5
6
  export interface AvrConfig {
6
7
  area: string;
@@ -101,22 +102,12 @@ export interface AvrCommand {
101
102
  attempt: number;
102
103
  };
103
104
  }
104
- export interface AvrTargetState {
105
- kind: "target_state";
106
- target: "avr";
107
- requestId: string;
108
- generation: number;
109
- status: string;
110
- observedAt: string;
111
- details: Record<string, unknown>;
112
- classification?: "manual_override";
113
- failure?: {
114
- operation: string;
115
- reason: string;
116
- attempts: number;
117
- occurredAt: string;
118
- };
119
- }
105
+ export type AvrTargetState = TargetStateEvent<"avr", Record<string, unknown>, {
106
+ operation: string;
107
+ reason: string;
108
+ attempts: number;
109
+ occurredAt: string;
110
+ }>;
120
111
  export interface AvrOutputEvent {
121
112
  payload?: unknown;
122
113
  avr: {
@@ -125,29 +116,9 @@ export interface AvrOutputEvent {
125
116
  [key: string]: unknown;
126
117
  };
127
118
  }
128
- export type ParsedAvrLine = {
129
- field: "power";
130
- value: AvrPower;
131
- line: string;
132
- } | {
133
- field: "mainZone";
134
- value: MainZone;
135
- line: string;
136
- } | {
137
- field: "source";
138
- value: string | null;
139
- sourceCode: string;
140
- line: string;
141
- } | {
142
- field: "volume";
143
- value: number | null;
144
- line: string;
145
- };
146
119
  export declare function createAvrState(_config: AvrConfig, saved?: Partial<AvrState>): AvrState;
147
- export declare function formatVolumeCommand(value: number): string;
148
- export declare function parseAvrLine(value: unknown, sources: Record<string, string>): ParsedAvrLine | null;
149
- export declare function normaliseAvrConfig(rawConfig: Omit<Partial<AvrConfig>, "sources"> & {
150
- sources?: unknown;
120
+ export declare function normaliseAvrConfig(rawConfig: {
121
+ [K in keyof AvrConfig]?: unknown;
151
122
  }): AvrConfig;
152
123
  export declare function transitionAvr(saved: Partial<AvrState> | undefined, msg: AvrMessage, rawConfig: Partial<AvrConfig>, nowValue?: Date | string | number): {
153
124
  state: AvrState;
@@ -156,12 +127,7 @@ export declare function transitionAvr(saved: Partial<AvrState> | undefined, msg:
156
127
  targetStates: {
157
128
  theatre: AvrTargetState;
158
129
  }[];
159
- traces: {
160
- event: string;
161
- outcome: string;
162
- reason: string | null;
163
- details: Record<string, unknown>;
164
- }[];
130
+ traces: TraceEntry<Record<string, unknown>>[];
165
131
  status: {
166
132
  phase: string;
167
133
  text: string;
@@ -1,28 +1,16 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.QUERY_COMMAND = void 0;
3
+ exports.parseAvrLine = exports.formatVolumeCommand = exports.QUERY_COMMAND = void 0;
4
4
  exports.createAvrState = createAvrState;
5
- exports.formatVolumeCommand = formatVolumeCommand;
6
- exports.parseAvrLine = parseAvrLine;
7
5
  exports.normaliseAvrConfig = normaliseAvrConfig;
8
6
  exports.transitionAvr = transitionAvr;
9
- exports.QUERY_COMMAND = "PW?\rZM?\rSI?\rMV?\r";
10
- function parseSources(value) {
11
- const sources = value && typeof value === "object" && !Array.isArray(value)
12
- ? value
13
- : {};
14
- const entries = Object.entries(sources);
15
- if (entries.some(([name, code]) => !name ||
16
- !code || typeof code !== "string" ||
17
- !/^[A-Z0-9][A-Z0-9 /._-]*$/.test(code))) {
18
- throw new Error("sources must map names to Denon source codes");
19
- }
20
- const typedEntries = entries;
21
- if (new Set(typedEntries.map(([, code]) => code)).size !== typedEntries.length) {
22
- throw new Error("Denon source codes must be unique");
23
- }
24
- return Object.fromEntries(typedEntries);
25
- }
7
+ const settings_1 = require("./settings");
8
+ const target_state_1 = require("./target-state");
9
+ const denon_protocol_1 = require("./denon-protocol");
10
+ var denon_protocol_2 = require("./denon-protocol");
11
+ Object.defineProperty(exports, "QUERY_COMMAND", { enumerable: true, get: function () { return denon_protocol_2.QUERY_COMMAND; } });
12
+ Object.defineProperty(exports, "formatVolumeCommand", { enumerable: true, get: function () { return denon_protocol_2.formatVolumeCommand; } });
13
+ Object.defineProperty(exports, "parseAvrLine", { enumerable: true, get: function () { return denon_protocol_2.parseAvrLine; } });
26
14
  function observedTime(value) {
27
15
  return typeof value === "string" && Number.isFinite(Date.parse(value)) ? value : null;
28
16
  }
@@ -88,66 +76,31 @@ function createAvrState(_config, saved = {}) {
88
76
  : 0
89
77
  };
90
78
  }
91
- function parseVolume(raw) {
92
- if (!/^\d{2,3}$/.test(raw))
93
- return null;
94
- if (raw.length === 2)
95
- return Number(raw);
96
- return Number(raw.slice(0, 2)) + Number(raw.slice(2)) / 10;
97
- }
98
- function roundVolume(value) {
99
- return Math.round(value * 2) / 2;
100
- }
101
79
  function sameVolume(left, right) {
102
80
  return left !== null && right !== null && Math.abs(left - right) < 0.001;
103
81
  }
104
- function formatVolumeCommand(value) {
105
- const rounded = roundVolume(value);
106
- if (!Number.isFinite(value) || rounded < 0 || rounded > 98 || Math.abs(value - rounded) > 0.001) {
107
- throw new Error("volume must be a half-step between 0 and 98");
108
- }
109
- const whole = Math.floor(rounded).toString().padStart(2, "0");
110
- return "MV" + whole + (Number.isInteger(rounded) ? "" : "5") + "\r";
111
- }
112
- function parseAvrLine(value, sources) {
113
- const line = String(value ?? "").trim();
114
- if (line === "PWON")
115
- return { field: "power", value: "on", line };
116
- if (line === "PWOFF" || line === "PWSTANDBY") {
117
- return { field: "power", value: "standby", line };
118
- }
119
- if (line === "ZMON")
120
- return { field: "mainZone", value: "on", line };
121
- if (line === "ZMOFF")
122
- return { field: "mainZone", value: "off", line };
123
- if (/^SI.+/.test(line)) {
124
- const sourceCode = line.slice(2);
125
- const source = Object.entries(sources).find(([, code]) => code === sourceCode)?.[0] || null;
126
- return { field: "source", value: source, sourceCode, line };
127
- }
128
- if (/^MV\d{2,3}$/.test(line)) {
129
- return { field: "volume", value: parseVolume(line.slice(2)), line };
130
- }
131
- return null;
132
- }
133
82
  // Validates AVR configuration and fills its defaults. The Node-RED adapter
134
83
  // calls this at deploy, so a bad configuration shows on the node instead of
135
84
  // failing every message.
85
+ // Settings may be editor strings. Missing or unusable numbers take their
86
+ // defaults: retry 2000 ms (at least 250), 3 attempts (at least 1) and volume
87
+ // bounds 0 to 60.
136
88
  function normaliseAvrConfig(rawConfig) {
137
- const rawMinVolume = Number(rawConfig.minVolume);
138
- const rawMaxVolume = Number(rawConfig.maxVolume);
139
- const minVolume = roundVolume(rawMinVolume);
140
- const maxVolume = roundVolume(rawMaxVolume);
89
+ const rawMinVolume = (0, settings_1.numberSetting)(rawConfig.minVolume, "minimum volume", 0);
90
+ const rawMaxVolume = (0, settings_1.numberSetting)(rawConfig.maxVolume, "maximum volume", 60);
91
+ const minVolume = (0, denon_protocol_1.roundVolume)(rawMinVolume);
92
+ const maxVolume = (0, denon_protocol_1.roundVolume)(rawMaxVolume);
141
93
  if (!Number.isFinite(rawMinVolume) || !Number.isFinite(rawMaxVolume) ||
142
94
  Math.abs(rawMinVolume - minVolume) > 0.001 || Math.abs(rawMaxVolume - maxVolume) > 0.001 ||
143
95
  minVolume < 0 || maxVolume > 98 || minVolume >= maxVolume) {
144
96
  throw new Error("volume bounds must be half-step values between 0 and 98 with minimum below maximum");
145
97
  }
146
98
  return {
147
- area: rawConfig.area || "room",
148
- sources: parseSources(rawConfig.sources),
149
- retryMs: Math.max(250, Number(rawConfig.retryMs) || 2000),
150
- maxAttempts: Math.max(1, Math.floor(Number(rawConfig.maxAttempts) || 3)),
99
+ // Optional: an empty area means none.
100
+ area: typeof rawConfig.area === "string" ? rawConfig.area.trim() : "",
101
+ sources: (0, denon_protocol_1.parseSourceCodes)(rawConfig.sources),
102
+ retryMs: Math.max(250, (0, settings_1.numberSetting)(rawConfig.retryMs, "retry interval", 2000)),
103
+ maxAttempts: Math.max(1, Math.floor((0, settings_1.numberSetting)(rawConfig.maxAttempts, "max attempts", 3))),
151
104
  minVolume,
152
105
  maxVolume
153
106
  };
@@ -289,7 +242,7 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
289
242
  }
290
243
  }
291
244
  function clampVolume(value) {
292
- const rounded = roundVolume(value);
245
+ const rounded = (0, denon_protocol_1.roundVolume)(value);
293
246
  const bounded = Math.max(config.minVolume, Math.min(config.maxVolume, rounded));
294
247
  return { value: bounded, bounded: Math.abs(bounded - value) > 0.001 };
295
248
  }
@@ -377,7 +330,7 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
377
330
  return true;
378
331
  if (!state.seen.power || !state.seen.mainZone || !state.seen.volume) {
379
332
  if (allowQuery)
380
- emitCommand("volume-query", exports.QUERY_COMMAND, 1);
333
+ emitCommand("volume-query", denon_protocol_1.QUERY_COMMAND, 1);
381
334
  return true;
382
335
  }
383
336
  if (state.observed.power !== "on" || state.observed.mainZone !== "on") {
@@ -404,7 +357,7 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
404
357
  }
405
358
  if (state.volumeRequest.target === null)
406
359
  return true;
407
- emitCommand("volume", formatVolumeCommand(state.volumeRequest.target), 1);
360
+ emitCommand("volume", (0, denon_protocol_1.formatVolumeCommand)(state.volumeRequest.target), 1);
408
361
  return true;
409
362
  }
410
363
  function reconcile(allowQuery = true) {
@@ -442,20 +395,20 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
442
395
  if (!hasFreshTargetState()) {
443
396
  state.phase = "discovering";
444
397
  if (allowQuery)
445
- emitCommand("query", exports.QUERY_COMMAND, 1);
398
+ emitCommand("query", denon_protocol_1.QUERY_COMMAND, 1);
446
399
  return;
447
400
  }
448
401
  if (state.desired.power === "standby") {
449
- emitCommand("standby", "PWSTANDBY\r", 1);
402
+ emitCommand("standby", denon_protocol_1.POWER_STANDBY, 1);
450
403
  }
451
404
  else if (state.observed.power !== "on") {
452
- emitCommand("power-on", "PWON\r", 1);
405
+ emitCommand("power-on", denon_protocol_1.POWER_ON, 1);
453
406
  }
454
407
  else if (state.observed.mainZone !== "on") {
455
- emitCommand("main-zone-on", "ZMON\r", 1);
408
+ emitCommand("main-zone-on", denon_protocol_1.ZONE_ON, 1);
456
409
  }
457
410
  else if (state.desired.source && state.observed.sourceCode !== desiredSourceCode()) {
458
- emitCommand("source", "SI" + desiredSourceCode() + "\r", 1);
411
+ emitCommand("source", (0, denon_protocol_1.selectSource)(desiredSourceCode()), 1);
459
412
  }
460
413
  return;
461
414
  }
@@ -501,7 +454,7 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
501
454
  // Re-read the receiver without touching work in flight: desired state,
502
455
  // pending commands, the volume request and the phase all carry on.
503
456
  commands.push({
504
- payload: exports.QUERY_COMMAND,
457
+ payload: denon_protocol_1.QUERY_COMMAND,
505
458
  avrCommand: {
506
459
  area: config.area,
507
460
  operation: "query",
@@ -526,7 +479,7 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
526
479
  state.phase = requestBlocked ? "failed" : "discovering";
527
480
  state.querySentAt = nowMs;
528
481
  commands.push({
529
- payload: exports.QUERY_COMMAND,
482
+ payload: denon_protocol_1.QUERY_COMMAND,
530
483
  avrCommand: {
531
484
  area: config.area,
532
485
  operation: "query",
@@ -539,7 +492,7 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
539
492
  if (state.desired && !requestBlocked && state.classification !== "manual_override") {
540
493
  state.pending = {
541
494
  operation: "query",
542
- payload: exports.QUERY_COMMAND,
495
+ payload: denon_protocol_1.QUERY_COMMAND,
543
496
  attempt: 1,
544
497
  deadlineAt: nowMs + config.retryMs
545
498
  };
@@ -554,7 +507,7 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
554
507
  const lines = String(value ?? "").split(/[\r\n]+/).filter(Boolean);
555
508
  let recognised = 0;
556
509
  for (const line of lines) {
557
- const parsed = parseAvrLine(line, config.sources);
510
+ const parsed = (0, denon_protocol_1.parseAvrLine)(line, config.sources);
558
511
  if (!parsed)
559
512
  continue;
560
513
  recognised += 1;
@@ -901,14 +854,13 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
901
854
  const fields = requiredFields();
902
855
  const status = state.phase === "manual_override"
903
856
  ? "transitioning"
904
- : state.phase === "idle" || state.phase === "unknown" ? "confirming" : state.phase;
857
+ : (0, target_state_1.asTargetStatus)(state.phase, "confirming");
905
858
  const confirmedAt = fields
906
859
  .map((field) => state.fieldObservedAt[field])
907
860
  .reduce((oldest, at) => at === null || oldest === null ? null : Date.parse(at) < Date.parse(oldest) ? at : oldest, now.toISOString());
908
861
  const reported = fields.some((field) => reportedFields.has(field));
909
862
  if (status !== "ready" || ((previousPhase !== "ready" || reported) && confirmedAt !== null)) {
910
- const theatre = {
911
- kind: "target_state",
863
+ const theatre = (0, target_state_1.targetStateEvent)({
912
864
  target: "avr",
913
865
  requestId: state.desired.requestId,
914
866
  generation: state.desired.generation,
@@ -928,18 +880,15 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
928
880
  retries: Math.max(0, state.lastAttempt - 1),
929
881
  fallbackUsed: false
930
882
  }
931
- }
932
- };
933
- if (state.classification)
934
- theatre.classification = state.classification;
935
- if (state.failure) {
936
- theatre.failure = {
883
+ },
884
+ classification: state.classification,
885
+ failure: state.failure && {
937
886
  operation: state.failure.operation,
938
887
  reason: "attempts-exhausted",
939
888
  attempts: state.failure.attempts,
940
889
  occurredAt: state.failure.at
941
- };
942
- }
890
+ }
891
+ });
943
892
  targetStates.push({ theatre });
944
893
  }
945
894
  }
@@ -1,3 +1,5 @@
1
+ import type { TraceEntry } from "./bounded-trace";
2
+ import { type TargetStateEvent } from "./target-state";
1
3
  export type BacklightingPower = "on" | "off";
2
4
  export interface BacklightingConfig {
3
5
  pollMs: number;
@@ -69,38 +71,23 @@ export interface BacklightingCommand {
69
71
  attempt: number;
70
72
  }
71
73
  export interface BacklightingOutputEvent {
72
- theatre: {
73
- kind: "target_state";
74
- target: "backlighting";
75
- requestId: string;
76
- generation: number;
77
- status: string;
78
- observedAt: string;
79
- details: {
80
- power: BacklightingPower;
81
- observedPower: BacklightingPower | null;
82
- recovery: Record<string, unknown>;
83
- metrics: {
84
- attempts: number;
85
- retries: number;
86
- fallbackUsed: boolean;
87
- };
74
+ theatre: TargetStateEvent<"backlighting", {
75
+ power: BacklightingPower;
76
+ observedPower: BacklightingPower | null;
77
+ recovery: Record<string, unknown>;
78
+ metrics: {
79
+ attempts: number;
80
+ retries: number;
81
+ fallbackUsed: boolean;
88
82
  };
89
- classification?: "manual_override";
90
- failure?: BacklightingFailure;
91
- };
83
+ }, BacklightingFailure>;
92
84
  }
93
85
  export declare function normaliseBacklightingConfig(config?: Partial<BacklightingConfig>): BacklightingConfig;
94
86
  export declare function transitionBacklighting(saved: Partial<BacklightingState> | undefined, msg: BacklightingMessage, suppliedConfig?: Partial<BacklightingConfig>, nowValue?: Date | string | number): {
95
87
  state: BacklightingState;
96
88
  commands: BacklightingCommand[];
97
89
  events: BacklightingOutputEvent[];
98
- traces: {
99
- event: string;
100
- outcome: string;
101
- reason: string | null;
102
- details: Record<string, unknown>;
103
- }[];
90
+ traces: TraceEntry<Record<string, unknown>>[];
104
91
  status: {
105
92
  phase: string;
106
93
  text: string;