@avantics/node-red-home-automation 5.0.0 → 6.1.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 (91) hide show
  1. package/README.md +413 -77
  2. package/contract-examples/room-lighting.mjs +39 -27
  3. package/dist/lib/activity-lighting-controller.d.ts +7 -2
  4. package/dist/lib/activity-lighting-controller.js +75 -16
  5. package/dist/lib/avr-controller.d.ts +2 -2
  6. package/dist/lib/avr-controller.js +21 -26
  7. package/dist/lib/circadian-policy.d.ts +47 -0
  8. package/dist/lib/circadian-policy.js +111 -0
  9. package/dist/lib/circadian-publishing.d.ts +33 -0
  10. package/dist/lib/circadian-publishing.js +154 -0
  11. package/dist/lib/circadian-schedule.d.ts +4 -0
  12. package/dist/lib/circadian-schedule.js +12 -0
  13. package/dist/lib/command-echo.d.ts +8 -1
  14. package/dist/lib/command-echo.js +37 -6
  15. package/dist/lib/cover-controller.js +4 -0
  16. package/dist/lib/denon-protocol.js +3 -2
  17. package/dist/lib/enable-input.d.ts +3 -0
  18. package/dist/lib/enable-input.js +18 -0
  19. package/dist/lib/house-schedule.js +2 -2
  20. package/dist/lib/light-contract.d.ts +53 -0
  21. package/dist/lib/light-contract.js +11 -0
  22. package/dist/lib/motion-policy.d.ts +0 -1
  23. package/dist/lib/motion-policy.js +9 -8
  24. package/dist/lib/motion-publishing.js +2 -1
  25. package/dist/lib/mqtt-message.d.ts +6 -0
  26. package/dist/lib/mqtt-message.js +21 -0
  27. package/dist/lib/room-controller.d.ts +41 -27
  28. package/dist/lib/room-controller.js +422 -213
  29. package/dist/lib/room-holds.d.ts +34 -0
  30. package/dist/lib/room-holds.js +66 -0
  31. package/dist/lib/room-lighting-discovery.d.ts +0 -14
  32. package/dist/lib/room-lighting-discovery.js +19 -125
  33. package/dist/lib/room-publishing.d.ts +7 -12
  34. package/dist/lib/room-publishing.js +65 -125
  35. package/dist/lib/shelly-cover.d.ts +2 -4
  36. package/dist/lib/shelly-cover.js +30 -70
  37. package/dist/lib/shelly-gen2.d.ts +25 -0
  38. package/dist/lib/shelly-gen2.js +58 -0
  39. package/dist/lib/shelly-switch.d.ts +95 -0
  40. package/dist/lib/shelly-switch.js +237 -0
  41. package/dist/lib/theatre-state-contract.js +12 -4
  42. package/dist/lib/z2m-cover.d.ts +49 -0
  43. package/dist/lib/z2m-cover.js +120 -0
  44. package/dist/lib/z2m-light-adapter.d.ts +62 -0
  45. package/dist/lib/z2m-light-adapter.js +195 -0
  46. package/dist/lib/z2m-light.d.ts +2 -2
  47. package/dist/lib/z2m-light.js +11 -14
  48. package/dist/nodes/activity-lighting-controller.html +15 -6
  49. package/dist/nodes/activity-lighting-controller.js +21 -0
  50. package/dist/nodes/adapter.d.ts +5 -1
  51. package/dist/nodes/adapter.js +35 -2
  52. package/dist/nodes/avr-controller.html +20 -18
  53. package/dist/nodes/avr-controller.js +5 -5
  54. package/dist/nodes/circadian-policy.d.ts +3 -0
  55. package/dist/nodes/circadian-policy.html +145 -0
  56. package/dist/nodes/circadian-policy.js +162 -0
  57. package/dist/nodes/cover-controller.html +9 -3
  58. package/dist/nodes/cover-controller.js +1 -1
  59. package/dist/nodes/display-mode-controller.html +14 -17
  60. package/dist/nodes/display-mode-controller.js +4 -1
  61. package/dist/nodes/house-schedule-mqtt.html +5 -0
  62. package/dist/nodes/house-schedule-mqtt.js +1 -1
  63. package/dist/nodes/house-schedule.html +3 -3
  64. package/dist/nodes/motion-policy.html +10 -2
  65. package/dist/nodes/motion-policy.js +4 -1
  66. package/dist/nodes/occupancy-fusion.html +5 -0
  67. package/dist/nodes/occupancy-fusion.js +1 -1
  68. package/dist/nodes/refused-enable.d.ts +7 -0
  69. package/dist/nodes/refused-enable.js +24 -0
  70. package/dist/nodes/room-controller.html +232 -85
  71. package/dist/nodes/room-controller.js +71 -97
  72. package/dist/nodes/shelly-switch.d.ts +3 -0
  73. package/dist/nodes/shelly-switch.html +87 -0
  74. package/dist/nodes/shelly-switch.js +48 -0
  75. package/dist/nodes/theatre-state-contract.html +9 -3
  76. package/dist/nodes/theatre-state-contract.js +1 -1
  77. package/dist/nodes/z2m-cover.d.ts +3 -0
  78. package/dist/nodes/z2m-cover.html +68 -0
  79. package/dist/nodes/z2m-cover.js +41 -0
  80. package/dist/nodes/z2m-light.d.ts +3 -0
  81. package/dist/nodes/z2m-light.html +76 -0
  82. package/dist/nodes/z2m-light.js +51 -0
  83. package/examples/Cover control.json +28 -71
  84. package/examples/Home theatre activity.json +53 -19
  85. package/examples/House schedule.json +106 -24
  86. package/examples/Room lighting.json +57 -25
  87. package/examples/Shelly cover.json +5 -16
  88. package/examples/Shelly switch.json +197 -0
  89. package/package.json +12 -4
  90. package/dist/lib/room-schedule.d.ts +0 -8
  91. 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
 
@@ -24,7 +24,7 @@ export interface ActivityLightingObservation {
24
24
  on: boolean;
25
25
  manual: boolean;
26
26
  available: boolean;
27
- values: Record<string, unknown>;
27
+ showsLast: boolean;
28
28
  observedAt: string;
29
29
  }
30
30
  export interface ActivityLightingPending {
@@ -51,6 +51,9 @@ export interface ActivityLightingState {
51
51
  blockedGeneration: number | null;
52
52
  adoptedGeneration: number | null;
53
53
  carried?: Carried | null;
54
+ reported?: Record<string, string[]>;
55
+ held?: string[];
56
+ overridden?: string[];
54
57
  }
55
58
  export type ActivityLightingEvent = {
56
59
  kind: "intent";
@@ -65,7 +68,8 @@ export type ActivityLightingEvent = {
65
68
  on: boolean;
66
69
  manual?: boolean;
67
70
  available?: boolean;
68
- values?: Record<string, unknown>;
71
+ fields?: string[];
72
+ showsLast?: boolean;
69
73
  observedAt: string;
70
74
  } | {
71
75
  kind: "command_result";
@@ -107,6 +111,7 @@ export interface ActivityLightingOutputEvent {
107
111
  };
108
112
  }, ActivityLightingFailure>;
109
113
  }
114
+ export declare const VALUES_NOT_REPORTED = "values-not-reported";
110
115
  export declare function normaliseLightingProfiles(value: unknown): ActivityLightingProfiles;
111
116
  export declare function normaliseActivityLightingConfig(config?: Partial<ActivityLightingConfig> & {
112
117
  profiles?: unknown;
@@ -1,5 +1,6 @@
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;
@@ -10,20 +11,19 @@ const observation_time_1 = require("./observation-time");
10
11
  const target_state_1 = require("./target-state");
11
12
  const PROFILE_NAME = /^[a-z][a-z0-9_-]*$/;
12
13
  const TARGET_NAME = /^[a-z][a-z0-9_-]*$/;
13
- function stable(value) {
14
- if (Array.isArray(value))
15
- return value.map(stable);
16
- if (value && typeof value === "object") {
17
- const record = value;
18
- return Object.fromEntries(Object.keys(record).sort().map((key) => [key, stable(record[key])]));
19
- }
20
- return value;
21
- }
22
14
  // Whether a light's report shows the profile's values. Reports come in the
23
15
  // 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;
26
- return Object.entries(expected).every(([key, value]) => Object.hasOwn(actual, key) && JSON.stringify(stable(actual[key])) === JSON.stringify(stable(value)));
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));
27
27
  }
28
28
  function normaliseLightingProfiles(value) {
29
29
  if (!value || typeof value !== "object" || Array.isArray(value)) {
@@ -53,6 +53,10 @@ function normaliseLightingProfiles(value) {
53
53
  }
54
54
  // The package's own units, checked when deployed so a bad profile shows
55
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
+ }
56
60
  const { brightnessPct, colorTempKelvin } = values;
57
61
  if (brightnessPct !== undefined &&
58
62
  (typeof brightnessPct !== "number" || !Number.isFinite(brightnessPct) || brightnessPct < 0 || brightnessPct > 100)) {
@@ -97,7 +101,11 @@ function initialState(saved = {}, profiles = {}) {
97
101
  failure: saved.failure && typeof saved.failure === "object" ? { ...saved.failure } : null,
98
102
  blockedGeneration: Number.isInteger(saved.blockedGeneration) ? saved.blockedGeneration : null,
99
103
  adoptedGeneration: (0, adopted_request_1.savedAdoptedGeneration)(saved),
100
- carried: (0, adopted_request_1.savedCarried)(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) : []
101
109
  };
102
110
  }
103
111
  function profileFor(state, config) {
@@ -165,7 +173,21 @@ function transitionActivityLighting(saved, msg, suppliedConfig = {}, nowValue =
165
173
  trace("lighting", "failed", reason, { profile: state.desired?.profile ?? null });
166
174
  }
167
175
  function issueApply(attempt) {
168
- 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
+ }
169
191
  state.pending = { attempt, deadlineAt: nowMs + config.confirmationTimeoutMs };
170
192
  state.phase = "transitioning";
171
193
  trace("command", "emitted", null, { operation: "apply", profile: state.desired?.profile, attempt });
@@ -192,11 +214,32 @@ function transitionActivityLighting(saved, msg, suppliedConfig = {}, nowValue =
192
214
  fail("lighting-unavailable");
193
215
  return;
194
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
+ }
195
227
  if (observation.manual || !observation.on) {
228
+ // A person's before this request (or off): left as it is.
196
229
  counts.preserved += 1;
197
230
  continue;
198
231
  }
199
- 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) {
200
243
  if ((0, adopted_request_1.isAdopted)(state)) {
201
244
  // An adopted request the lights don't match: someone else's, and
202
245
  // never re-applied.
@@ -269,6 +312,7 @@ function transitionActivityLighting(saved, msg, suppliedConfig = {}, nowValue =
269
312
  }
270
313
  state.generation = intent.generation;
271
314
  state.observed = {};
315
+ state.held = [];
272
316
  state.pending = null;
273
317
  state.failure = null;
274
318
  state.blockedGeneration = null;
@@ -276,6 +320,8 @@ function transitionActivityLighting(saved, msg, suppliedConfig = {}, nowValue =
276
320
  reconcile();
277
321
  else
278
322
  issueApply(1);
323
+ // Taken back with this request's apply (above), or no longer styled.
324
+ state.overridden = [];
279
325
  trace("intent", "accepted", null, { profile: intent.profile, generation: intent.generation });
280
326
  }
281
327
  function acceptObservation(observation) {
@@ -308,12 +354,22 @@ function transitionActivityLighting(saved, msg, suppliedConfig = {}, nowValue =
308
354
  trace("observation", "ignored", "out-of-order", { target: observation.target });
309
355
  return;
310
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
+ }
311
367
  state.observed[observation.target] = {
312
368
  target: observation.target,
313
369
  on: observation.on === true,
314
370
  manual: observation.manual === true,
315
371
  available: observation.available !== false,
316
- values: observation.values && typeof observation.values === "object" ? { ...observation.values } : {},
372
+ showsLast: observation.showsLast === true,
317
373
  observedAt: bounded.observedAt
318
374
  };
319
375
  trace("observation", "accepted", null, { target: observation.target });
@@ -389,6 +445,9 @@ function transitionActivityLighting(saved, msg, suppliedConfig = {}, nowValue =
389
445
  }
390
446
  else if (event.kind === "startup" || event.kind === "refresh") {
391
447
  state.observed = {};
448
+ // Since start: what each light reports is learned again.
449
+ if (event.kind === "startup")
450
+ state.reported = {};
392
451
  state.pending = null;
393
452
  if (state.desired) {
394
453
  if (profileFor(state, config).targets.length === 0)
@@ -11,7 +11,7 @@ export interface AvrConfig {
11
11
  minVolumeDb: number;
12
12
  maxVolumeDb: number;
13
13
  }
14
- export declare const LEGACY_VOLUME_UNITS = "legacy-volume-units";
14
+ export declare const REMOVED_VOLUME_VALUE = "removed-volume-value";
15
15
  export interface AvrObserved {
16
16
  power: AvrPower | null;
17
17
  mainZone: MainZone | null;
@@ -94,7 +94,7 @@ export type AvrInputEvent = {
94
94
  requestId: string;
95
95
  mode: AvrVolumeMode;
96
96
  valueDb?: number | string;
97
- value?: number | string;
97
+ value?: unknown;
98
98
  } | {
99
99
  kind: "tick";
100
100
  };
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.LEGACY_VOLUME_UNITS = exports.parseAvrLine = exports.formatVolumeCommand = exports.QUERY_COMMAND = void 0;
3
+ exports.REMOVED_VOLUME_VALUE = exports.parseAvrLine = exports.formatVolumeCommand = exports.QUERY_COMMAND = void 0;
4
4
  exports.createAvrState = createAvrState;
5
5
  exports.normaliseAvrConfig = normaliseAvrConfig;
6
6
  exports.transitionAvr = transitionAvr;
@@ -12,9 +12,9 @@ var denon_protocol_2 = require("./denon-protocol");
12
12
  Object.defineProperty(exports, "QUERY_COMMAND", { enumerable: true, get: function () { return denon_protocol_2.QUERY_COMMAND; } });
13
13
  Object.defineProperty(exports, "formatVolumeCommand", { enumerable: true, get: function () { return denon_protocol_2.formatVolumeCommand; } });
14
14
  Object.defineProperty(exports, "parseAvrLine", { enumerable: true, get: function () { return denon_protocol_2.parseAvrLine; } });
15
- // Traced when a volume request gives `value` in the receiver's own units
16
- // rather than `valueDb`: still read during 5.x, and the node warns.
17
- exports.LEGACY_VOLUME_UNITS = "legacy-volume-units";
15
+ // The reason a volume request that gives only `value`, in the receiver's own
16
+ // 0-98 (removed in 6.0), is rejected; the node warns.
17
+ exports.REMOVED_VOLUME_VALUE = "removed-volume-value";
18
18
  function observedTime(value) {
19
19
  return typeof value === "string" && Number.isFinite(Date.parse(value)) ? value : null;
20
20
  }
@@ -102,16 +102,19 @@ function sameVolume(left, right) {
102
102
  // failing every message.
103
103
  // Settings may be editor strings. Missing or unusable numbers take their
104
104
  // defaults: retry 2000 ms (at least 250), 3 attempts (at least 1) and volume
105
- // bounds -80 to -20 dB. A flow saved before 5.0 has minVolume and maxVolume
106
- // in the receiver's own 0-98, read when the dB settings are missing.
105
+ // bounds -80 to -20 dB. The 0-98 minVolume and maxVolume of flows saved
106
+ // before 5.0 were removed in 6.0: a flow with only those is an invalid
107
+ // configuration rather than one quietly given the default bounds, which
108
+ // could let the receiver go louder than its old cap.
107
109
  function normaliseAvrConfig(rawConfig) {
108
- // The editor keeps the old keys, empty once the dialog saves dB ones.
109
110
  const given = (value) => value !== undefined && value !== null && String(value).trim() !== "";
110
- const bound = (db, legacy, label, fallback) => !given(db) && given(legacy)
111
- ? (0, denon_protocol_1.legacyVolumeDb)((0, settings_1.numberSetting)(legacy, label, fallback - denon_protocol_1.VOLUME_MIN_DB), "absolute")
112
- : (0, settings_1.numberSetting)(db, label, fallback);
113
- const rawMinVolume = bound(rawConfig.minVolumeDb, rawConfig.minVolume, "minimum volume", -80);
114
- const rawMaxVolume = bound(rawConfig.maxVolumeDb, rawConfig.maxVolume, "maximum volume", -20);
111
+ for (const [db, removed, label] of [[rawConfig.minVolumeDb, rawConfig.minVolume, "Minimum volume (dB)"], [rawConfig.maxVolumeDb, rawConfig.maxVolume, "Maximum volume (dB)"]]) {
112
+ if (!given(db) && given(removed)) {
113
+ throw new Error(`volume bounds in the receiver's own 0-98 were removed in 6.0: set ${label}`);
114
+ }
115
+ }
116
+ const rawMinVolume = (0, settings_1.numberSetting)(rawConfig.minVolumeDb, "minimum volume", -80);
117
+ const rawMaxVolume = (0, settings_1.numberSetting)(rawConfig.maxVolumeDb, "maximum volume", -20);
115
118
  const minVolume = (0, denon_protocol_1.roundVolume)(rawMinVolume);
116
119
  const maxVolume = (0, denon_protocol_1.roundVolume)(rawMaxVolume);
117
120
  if (!Number.isFinite(rawMinVolume) || !Number.isFinite(rawMaxVolume) ||
@@ -707,21 +710,13 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
707
710
  forceStateEvent = true;
708
711
  }
709
712
  else if (event.kind === "volume") {
710
- // In dB; a finite numeric string counts. `value` from before 5.0 is in
711
- // the receiver's own units, still read during 5.x and traced so the
712
- // node can warn; given with a usable valueDb, it is ignored and traced.
713
+ // In dB; a finite numeric string counts. `value`, in the receiver's own
714
+ // 0-98, was removed in 6.0: a request with only that is refused, and
715
+ // the node warns.
713
716
  const valueDb = numberValue(event.valueDb);
714
- const value = numberValue(event.value);
715
- const legacyUnits = valueDb === null && event.value !== undefined;
716
- const volume = { ...event, value: valueDb !== null ? valueDb
717
- : value !== null && (event.mode === "absolute" || event.mode === "relative") ? (0, denon_protocol_1.legacyVolumeDb)(value, event.mode)
718
- : value ?? NaN };
719
- if (legacyUnits)
720
- trace("volume", "accepted", exports.LEGACY_VOLUME_UNITS, { requestId: event.requestId, value: event.value });
721
- if (valueDb !== null && event.value !== undefined) {
722
- trace("volume", "accepted", "legacy-volume-units-ignored", { requestId: event.requestId, value: event.value });
723
- }
724
- const reason = validateVolumeIntent(volume);
717
+ const removedValue = valueDb === null && event.value !== undefined;
718
+ const volume = { ...event, value: valueDb ?? NaN };
719
+ const reason = removedValue ? exports.REMOVED_VOLUME_VALUE : validateVolumeIntent(volume);
725
720
  if (reason) {
726
721
  events.push({
727
722
  avr: {
@@ -0,0 +1,47 @@
1
+ import type { TraceEntry } from "./bounded-trace";
2
+ import type { CircadianLighting } from "./circadian";
3
+ import { type DaySchedule } from "./circadian-schedule";
4
+ import type { LightStyle } from "./light-styling";
5
+ export declare const STYLE_LIFETIME_INTERVALS = 3;
6
+ export interface CircadianConfig {
7
+ lighting: CircadianLighting;
8
+ schedule: DaySchedule;
9
+ timesFrom: "own" | "house";
10
+ initialSleep: boolean;
11
+ transitionSeconds: number;
12
+ intervalSeconds: number;
13
+ }
14
+ export interface CircadianState {
15
+ enabled: boolean;
16
+ sleeping: boolean;
17
+ schedule: DaySchedule;
18
+ scheduleSetting: DaySchedule;
19
+ followsHouse?: boolean;
20
+ }
21
+ export interface CircadianEvent {
22
+ kind?: string;
23
+ enabled?: unknown;
24
+ wakeTime?: unknown;
25
+ bedTime?: unknown;
26
+ }
27
+ export interface StyleMessage {
28
+ kind: "style";
29
+ source: string;
30
+ values: LightStyle | null;
31
+ transitionSeconds: number;
32
+ until: string;
33
+ takeBack?: true;
34
+ }
35
+ export declare function createCircadianState(config: CircadianConfig, saved?: Partial<CircadianState>): CircadianState;
36
+ export declare function styleMessage(config: CircadianConfig, state: CircadianState, now: Date, takeBack?: boolean): StyleMessage;
37
+ export declare function transitionCircadian(saved: Partial<CircadianState> | undefined, event: CircadianEvent, config: CircadianConfig, nowValue?: Date | string | number): {
38
+ state: CircadianState;
39
+ style: StyleMessage | null;
40
+ stateChanged: boolean;
41
+ traces: TraceEntry<Record<string, unknown>>[];
42
+ status: {
43
+ enabled: boolean;
44
+ sleeping: boolean;
45
+ values: LightStyle | null;
46
+ };
47
+ };
@@ -0,0 +1,111 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.STYLE_LIFETIME_INTERVALS = void 0;
4
+ exports.createCircadianState = createCircadianState;
5
+ exports.styleMessage = styleMessage;
6
+ exports.transitionCircadian = transitionCircadian;
7
+ const circadian_schedule_1 = require("./circadian-schedule");
8
+ const enable_input_1 = require("./enable-input");
9
+ const settings_1 = require("./settings");
10
+ // A style is stale after this many restyle intervals, so a policy that
11
+ // stopped (deleted, disabled, crashed) stops affecting lights soon after.
12
+ exports.STYLE_LIFETIME_INTERVALS = 3;
13
+ function createCircadianState(config, saved = {}) {
14
+ const kept = (key) => (0, settings_1.keptOverride)(saved.schedule?.[key], saved.scheduleSetting?.[key], config.schedule[key]);
15
+ return {
16
+ enabled: saved.enabled !== false,
17
+ sleeping: saved.sleeping === undefined ? config.initialSleep : saved.sleeping === true,
18
+ // Following a house, its times are the house's last ones (the node passes
19
+ // each change on as a "schedule" event), or the house's as it started.
20
+ schedule: config.timesFrom === "house"
21
+ ? { ...(saved.followsHouse === true && saved.schedule ? saved.schedule : config.schedule) }
22
+ : saved.followsHouse === true ? { ...config.schedule } : { wakeTime: kept("wakeTime"), bedTime: kept("bedTime") },
23
+ scheduleSetting: { ...config.schedule },
24
+ followsHouse: config.timesFrom === "house"
25
+ };
26
+ }
27
+ // The style for this moment, as a room is sent it.
28
+ function styleMessage(config, state, now, takeBack = false) {
29
+ return {
30
+ kind: "style",
31
+ source: "circadian",
32
+ values: state.enabled ? config.lighting.withSchedule(state.schedule).styleAt(now, state.sleeping) : null,
33
+ transitionSeconds: config.transitionSeconds,
34
+ until: new Date(now.getTime() + exports.STYLE_LIFETIME_INTERVALS * config.intervalSeconds * 1000).toISOString(),
35
+ ...(takeBack ? { takeBack: true } : {})
36
+ };
37
+ }
38
+ // One event: "circadian" or "sleep" with enabled true or false, "schedule"
39
+ // with new times, or "tick" (the interval, the flows starting, or a startup
40
+ // message) to send the style as it stands. Returns the style to send, if
41
+ // any, and whether the published state changed.
42
+ function transitionCircadian(saved, event, config, nowValue = new Date()) {
43
+ const now = nowValue instanceof Date ? nowValue : new Date(nowValue);
44
+ const state = createCircadianState(config, saved);
45
+ const traces = [];
46
+ let style = null;
47
+ let stateChanged = false;
48
+ function trace(name, outcome, reason = null, details = {}) {
49
+ traces.push({ event: name, outcome, reason, details });
50
+ }
51
+ if ((event.kind === "circadian" || event.kind === "sleep") && (0, enable_input_1.enableValue)(event.enabled) === null) {
52
+ // Refused, never read as off: the node warns.
53
+ trace(event.kind, "ignored", enable_input_1.NOT_TRUE_OR_FALSE, { source: event.kind, payload: (0, enable_input_1.describeValue)(event.enabled) });
54
+ }
55
+ else if (event.kind === "circadian") {
56
+ const enabled = event.enabled === true;
57
+ const changed = enabled !== state.enabled;
58
+ if (changed) {
59
+ state.enabled = enabled;
60
+ stateChanged = true;
61
+ }
62
+ trace("circadian", changed ? "changed" : "unchanged", null, { enabled });
63
+ // Switched on, even when it already was (as 5.x did: a flow may send it to
64
+ // bring lights back into step), it takes back what a person set.
65
+ // Switched off, rooms stop styling.
66
+ if (enabled)
67
+ style = styleMessage(config, state, now, true);
68
+ else if (changed)
69
+ style = styleMessage(config, state, now);
70
+ }
71
+ else if (event.kind === "sleep") {
72
+ const sleeping = event.enabled === true;
73
+ if (sleeping !== state.sleeping) {
74
+ state.sleeping = sleeping;
75
+ stateChanged = true;
76
+ trace("sleep", "changed", null, { enabled: sleeping });
77
+ if (state.enabled)
78
+ style = styleMessage(config, state, now);
79
+ }
80
+ }
81
+ else if (event.kind === "schedule") {
82
+ const next = (0, circadian_schedule_1.requestedSchedule)(state.schedule, event);
83
+ if (!next) {
84
+ trace("schedule", "ignored", "invalid-times", { wakeTime: event.wakeTime, bedTime: event.bedTime });
85
+ }
86
+ else if (next.wakeTime !== state.schedule.wakeTime || next.bedTime !== state.schedule.bedTime) {
87
+ state.schedule = next;
88
+ stateChanged = true;
89
+ trace("schedule", "changed", null, { ...next });
90
+ if (state.enabled)
91
+ style = styleMessage(config, state, now);
92
+ }
93
+ }
94
+ else if (event.kind === "tick") {
95
+ // While off, a tick says so again, so a room that missed the change or
96
+ // restarted without its saved style stops styling too.
97
+ style = styleMessage(config, state, now);
98
+ }
99
+ else if (event.kind !== "ignored") {
100
+ // "ignored": a set topic's message already traced as such.
101
+ trace("input", "ignored", "unknown-kind", { kind: event.kind ?? null });
102
+ }
103
+ return {
104
+ state,
105
+ style,
106
+ stateChanged,
107
+ traces,
108
+ status: { enabled: state.enabled, sleeping: state.sleeping, values: state.enabled ? styleMessage(config, state, now).values : null }
109
+ };
110
+ }
111
+ //# sourceMappingURL=circadian-policy.js.map
@@ -0,0 +1,33 @@
1
+ import type { TraceEntry } from "./bounded-trace";
2
+ import type { CircadianEvent, CircadianState } from "./circadian-policy";
3
+ import type { DaySchedule } from "./circadian-schedule";
4
+ import { type OptInPublishingConfig, type RetainedText } from "./publishing-node";
5
+ export interface CircadianPublishingConfig extends OptInPublishingConfig {
6
+ timesFrom: "own" | "house";
7
+ }
8
+ type Switch = "circadian" | "sleep";
9
+ type Time = "wake-time" | "bed-time";
10
+ export declare const circadianSwitchTopic: (area: string, which: Switch, end: "state" | "set") => string;
11
+ export declare const circadianTimeTopic: (area: string, which: Time, end: "state" | "set") => string;
12
+ export declare const circadianAvailabilityTopic: (area: string) => string;
13
+ export declare function circadianDiscovery(config: CircadianPublishingConfig): RetainedText[];
14
+ export declare function roomCircadianDiscoveryTopics(config: {
15
+ area: string;
16
+ discoveryPrefix: string;
17
+ }, idScheme?: "area" | "node", nodeId?: string): string[];
18
+ export declare function circadianStateTopics(area: string): string[];
19
+ export declare function circadianStateOutputs(config: CircadianPublishingConfig, state: Pick<CircadianState, "enabled" | "sleeping"> & {
20
+ schedule: DaySchedule;
21
+ }): RetainedText[];
22
+ export declare function circadianStartingOutputs(config: CircadianPublishingConfig, state: CircadianState, roomNodeIds?: readonly string[]): RetainedText[];
23
+ export declare const circadianStoppingOutputs: (config: CircadianPublishingConfig) => RetainedText[];
24
+ export declare const circadianRetainedTopics: (config: CircadianPublishingConfig) => string[];
25
+ export declare function circadianInbound(msg: {
26
+ topic?: unknown;
27
+ payload?: unknown;
28
+ retain?: unknown;
29
+ }, config: CircadianPublishingConfig): {
30
+ event: CircadianEvent;
31
+ traces: TraceEntry[];
32
+ } | null;
33
+ export {};