@avantics/node-red-home-automation 2.2.1 → 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 (85) hide show
  1. package/README.md +76 -89
  2. package/contract-examples/room-lighting.mjs +12 -9
  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 +17 -28
  6. package/dist/lib/avr-controller.js +165 -116
  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/circadian-schedule.d.ts +11 -0
  11. package/dist/lib/circadian-schedule.js +63 -0
  12. package/dist/lib/circadian.d.ts +6 -0
  13. package/dist/lib/circadian.js +15 -0
  14. package/dist/lib/command-echo.d.ts +20 -0
  15. package/dist/lib/command-echo.js +82 -0
  16. package/dist/lib/cover-controller.d.ts +15 -28
  17. package/dist/lib/cover-controller.js +6 -8
  18. package/dist/lib/denon-protocol.d.ts +29 -0
  19. package/dist/lib/denon-protocol.js +76 -0
  20. package/dist/lib/display-mode-controller.d.ts +11 -6
  21. package/dist/lib/display-mode-controller.js +90 -39
  22. package/dist/lib/light-styling.d.ts +11 -0
  23. package/dist/lib/light-styling.js +15 -0
  24. package/dist/lib/motion-policy.d.ts +12 -22
  25. package/dist/lib/motion-policy.js +53 -56
  26. package/dist/lib/occupancy-fusion.d.ts +8 -12
  27. package/dist/lib/occupancy-fusion.js +3 -2
  28. package/dist/lib/room-controller.d.ts +13 -38
  29. package/dist/lib/room-controller.js +85 -180
  30. package/dist/lib/room-lighting-discovery.d.ts +9 -0
  31. package/dist/lib/room-lighting-discovery.js +45 -0
  32. package/dist/lib/settings.d.ts +5 -0
  33. package/dist/lib/settings.js +68 -0
  34. package/dist/lib/source-capability-controller.d.ts +32 -35
  35. package/dist/lib/source-capability-controller.js +51 -35
  36. package/dist/lib/switch-policy.d.ts +2 -7
  37. package/dist/lib/target-state.d.ts +24 -0
  38. package/dist/lib/target-state.js +38 -0
  39. package/dist/lib/theatre-activity-controller.d.ts +6 -108
  40. package/dist/lib/theatre-activity-controller.js +67 -318
  41. package/dist/lib/theatre-ha-discovery.d.ts +14 -0
  42. package/dist/lib/theatre-ha-discovery.js +163 -0
  43. package/dist/lib/theatre-metrics.d.ts +4 -0
  44. package/dist/lib/theatre-metrics.js +66 -0
  45. package/dist/lib/theatre-profiles.d.ts +23 -0
  46. package/dist/lib/theatre-profiles.js +73 -0
  47. package/dist/lib/theatre-refresh.d.ts +20 -0
  48. package/dist/lib/theatre-refresh.js +46 -0
  49. package/dist/lib/theatre-slo.js +7 -9
  50. package/dist/lib/theatre-state-contract.d.ts +7 -19
  51. package/dist/lib/theatre-state-contract.js +33 -169
  52. package/dist/lib/theatre-state.d.ts +110 -0
  53. package/dist/lib/theatre-state.js +139 -0
  54. package/dist/lib/wall-input.d.ts +2 -7
  55. package/dist/lib/z2m-light.d.ts +16 -0
  56. package/dist/lib/z2m-light.js +36 -0
  57. package/dist/nodes/activity-lighting-controller.html +5 -3
  58. package/dist/nodes/activity-lighting-controller.js +21 -52
  59. package/dist/nodes/adapter.d.ts +15 -0
  60. package/dist/nodes/adapter.js +60 -0
  61. package/dist/nodes/avr-controller.html +13 -4
  62. package/dist/nodes/avr-controller.js +23 -62
  63. package/dist/nodes/backlighting-controller.html +1 -1
  64. package/dist/nodes/backlighting-controller.js +25 -47
  65. package/dist/nodes/display-mode-controller.html +4 -4
  66. package/dist/nodes/display-mode-controller.js +22 -59
  67. package/dist/nodes/motion-policy.html +23 -10
  68. package/dist/nodes/motion-policy.js +14 -135
  69. package/dist/nodes/occupancy-fusion.html +2 -2
  70. package/dist/nodes/occupancy-fusion.js +23 -29
  71. package/dist/nodes/room-controller.html +92 -34
  72. package/dist/nodes/room-controller.js +46 -64
  73. package/dist/nodes/source-capability-controller.html +4 -13
  74. package/dist/nodes/source-capability-controller.js +17 -52
  75. package/dist/nodes/switch-policy.html +3 -3
  76. package/dist/nodes/switch-policy.js +23 -42
  77. package/dist/nodes/theatre-activity-controller.html +5 -3
  78. package/dist/nodes/theatre-activity-controller.js +23 -43
  79. package/dist/nodes/theatre-state-contract.html +55 -22
  80. package/dist/nodes/theatre-state-contract.js +30 -41
  81. package/examples/Home theatre activity.json +307 -43
  82. package/examples/Home theatre equipment.json +4 -4
  83. package/examples/Room lighting.json +15 -17
  84. package/package.json +3 -7
  85. package/THIRD-PARTY-NOTICES.md +0 -218
@@ -1,26 +1,18 @@
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;
5
+ exports.normaliseAvrConfig = normaliseAvrConfig;
7
6
  exports.transitionAvr = transitionAvr;
8
- exports.QUERY_COMMAND = "PW?\rZM?\rSI?\rMV?\r";
9
- function parseSources(value) {
10
- const sources = value && typeof value === "object" && !Array.isArray(value)
11
- ? value
12
- : {};
13
- const entries = Object.entries(sources);
14
- if (entries.some(([name, code]) => !name ||
15
- !code || typeof code !== "string" ||
16
- !/^[A-Z0-9][A-Z0-9 /._-]*$/.test(code))) {
17
- throw new Error("sources must map names to Denon source codes");
18
- }
19
- const typedEntries = entries;
20
- if (new Set(typedEntries.map(([, code]) => code)).size !== typedEntries.length) {
21
- throw new Error("Denon source codes must be unique");
22
- }
23
- return Object.fromEntries(typedEntries);
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; } });
14
+ function observedTime(value) {
15
+ return typeof value === "string" && Number.isFinite(Date.parse(value)) ? value : null;
24
16
  }
25
17
  function createAvrState(_config, saved = {}) {
26
18
  const observed = saved.observed || {};
@@ -38,6 +30,12 @@ function createAvrState(_config, saved = {}) {
38
30
  volume: Number.isFinite(observed.volume) ? observed.volume : null,
39
31
  at: typeof observed.at === "string" ? observed.at : null
40
32
  },
33
+ fieldObservedAt: {
34
+ power: observedTime(saved.fieldObservedAt?.power),
35
+ mainZone: observedTime(saved.fieldObservedAt?.mainZone),
36
+ source: observedTime(saved.fieldObservedAt?.source),
37
+ volume: observedTime(saved.fieldObservedAt?.volume)
38
+ },
41
39
  seen: {
42
40
  power: seen.power === true,
43
41
  mainZone: seen.mainZone === true,
@@ -78,76 +76,52 @@ function createAvrState(_config, saved = {}) {
78
76
  : 0
79
77
  };
80
78
  }
81
- function parseVolume(raw) {
82
- if (!/^\d{2,3}$/.test(raw))
83
- return null;
84
- if (raw.length === 2)
85
- return Number(raw);
86
- return Number(raw.slice(0, 2)) + Number(raw.slice(2)) / 10;
87
- }
88
- function roundVolume(value) {
89
- return Math.round(value * 2) / 2;
90
- }
91
79
  function sameVolume(left, right) {
92
80
  return left !== null && right !== null && Math.abs(left - right) < 0.001;
93
81
  }
94
- function formatVolumeCommand(value) {
95
- const rounded = roundVolume(value);
96
- if (!Number.isFinite(value) || rounded < 0 || rounded > 98 || Math.abs(value - rounded) > 0.001) {
97
- throw new Error("volume must be a half-step between 0 and 98");
98
- }
99
- const whole = Math.floor(rounded).toString().padStart(2, "0");
100
- return "MV" + whole + (Number.isInteger(rounded) ? "" : "5") + "\r";
101
- }
102
- function parseAvrLine(value, sources) {
103
- const line = String(value ?? "").trim();
104
- if (line === "PWON")
105
- return { field: "power", value: "on", line };
106
- if (line === "PWOFF" || line === "PWSTANDBY") {
107
- return { field: "power", value: "standby", line };
108
- }
109
- if (line === "ZMON")
110
- return { field: "mainZone", value: "on", line };
111
- if (line === "ZMOFF")
112
- return { field: "mainZone", value: "off", line };
113
- if (/^SI.+/.test(line)) {
114
- const sourceCode = line.slice(2);
115
- const source = Object.entries(sources).find(([, code]) => code === sourceCode)?.[0] || null;
116
- return { field: "source", value: source, sourceCode, line };
117
- }
118
- if (/^MV\d{2,3}$/.test(line)) {
119
- return { field: "volume", value: parseVolume(line.slice(2)), line };
120
- }
121
- return null;
122
- }
123
- function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
124
- const rawMinVolume = Number(rawConfig.minVolume);
125
- const rawMaxVolume = Number(rawConfig.maxVolume);
126
- const minVolume = roundVolume(rawMinVolume);
127
- const maxVolume = roundVolume(rawMaxVolume);
82
+ // Validates AVR configuration and fills its defaults. The Node-RED adapter
83
+ // calls this at deploy, so a bad configuration shows on the node instead of
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.
88
+ function normaliseAvrConfig(rawConfig) {
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);
128
93
  if (!Number.isFinite(rawMinVolume) || !Number.isFinite(rawMaxVolume) ||
129
94
  Math.abs(rawMinVolume - minVolume) > 0.001 || Math.abs(rawMaxVolume - maxVolume) > 0.001 ||
130
95
  minVolume < 0 || maxVolume > 98 || minVolume >= maxVolume) {
131
96
  throw new Error("volume bounds must be half-step values between 0 and 98 with minimum below maximum");
132
97
  }
133
- const config = {
134
- area: rawConfig.area || "room",
135
- sources: parseSources(rawConfig.sources),
136
- retryMs: Math.max(250, Number(rawConfig.retryMs) || 2000),
137
- maxAttempts: Math.max(1, Math.floor(Number(rawConfig.maxAttempts) || 3)),
98
+ return {
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))),
138
104
  minVolume,
139
105
  maxVolume
140
106
  };
107
+ }
108
+ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
109
+ const config = normaliseAvrConfig(rawConfig);
141
110
  const now = nowValue instanceof Date ? nowValue : new Date(nowValue);
142
111
  const nowMs = now.getTime();
143
112
  const state = createAvrState(config, saved);
144
113
  const commands = [];
145
114
  const events = [];
115
+ const targetStates = [];
146
116
  const traces = [];
147
117
  const event = msg.avr || { kind: "unknown" };
118
+ const previousPhase = state.phase;
119
+ // Fields the receiver reported in this event.
120
+ const reportedFields = new Set();
148
121
  const before = JSON.stringify({
149
122
  observed: state.observed,
150
123
  seen: state.seen,
124
+ fieldObservedAt: state.fieldObservedAt,
151
125
  desired: state.desired,
152
126
  generation: state.generation,
153
127
  pending: state.pending,
@@ -233,9 +207,11 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
233
207
  attempt,
234
208
  deadlineAt: nowMs + config.retryMs
235
209
  };
236
- state.phase = operation === "query" || operation === "volume-query"
237
- ? "discovering"
238
- : "transitioning";
210
+ state.phase = volumeOperation && blocked()
211
+ ? "failed"
212
+ : operation === "query" || operation === "volume-query"
213
+ ? "discovering"
214
+ : "transitioning";
239
215
  if (operation === "volume")
240
216
  state.volumeMetrics.commands += 1;
241
217
  trace("command", "emitted", null, { operation, attempt });
@@ -266,10 +242,28 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
266
242
  }
267
243
  }
268
244
  function clampVolume(value) {
269
- const rounded = roundVolume(value);
245
+ const rounded = (0, denon_protocol_1.roundVolume)(value);
270
246
  const bounded = Math.max(config.minVolume, Math.min(config.maxVolume, rounded));
271
247
  return { value: bounded, bounded: Math.abs(bounded - value) > 0.001 };
272
248
  }
249
+ // The phase once no volume work is in flight; a failed request stays failed.
250
+ function blocked() {
251
+ return state.desired !== null && state.blockedGeneration === state.desired.generation;
252
+ }
253
+ function restingPhase() {
254
+ if (state.classification === "manual_override")
255
+ return "manual_override";
256
+ if (blocked())
257
+ return "failed";
258
+ return state.desired && targetSatisfied() ? "ready" : "idle";
259
+ }
260
+ // Every failed volume request is reported in one shape; operation and
261
+ // attempts are null when no command was involved (a restart).
262
+ function volumeFailed(requestId, reason, operation, attempts) {
263
+ state.volumeMetrics.failures += 1;
264
+ events.push({ avr: { kind: "volume_failed", area: config.area, requestId, reason, operation, attempts } });
265
+ trace("volume", "failed", reason, { requestId, operation, attempts });
266
+ }
273
267
  function completeVolume() {
274
268
  const request = state.volumeRequest;
275
269
  if (!request || request.target === null)
@@ -292,11 +286,7 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
292
286
  bounded: request.bounded
293
287
  });
294
288
  state.volumeRequest = null;
295
- state.phase = state.classification === "manual_override"
296
- ? "manual_override"
297
- : state.desired && targetSatisfied()
298
- ? "ready"
299
- : "idle";
289
+ state.phase = restingPhase();
300
290
  }
301
291
  function abandonVolume(reason, observed = state.observed.volume) {
302
292
  const request = state.volumeRequest;
@@ -320,11 +310,7 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
320
310
  target: request.target
321
311
  });
322
312
  state.volumeRequest = null;
323
- state.phase = state.classification === "manual_override"
324
- ? "manual_override"
325
- : state.desired && targetSatisfied()
326
- ? "ready"
327
- : "idle";
313
+ state.phase = restingPhase();
328
314
  }
329
315
  function resolveRelativeVolume() {
330
316
  const request = state.volumeRequest;
@@ -344,7 +330,7 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
344
330
  return true;
345
331
  if (!state.seen.power || !state.seen.mainZone || !state.seen.volume) {
346
332
  if (allowQuery)
347
- emitCommand("volume-query", exports.QUERY_COMMAND, 1);
333
+ emitCommand("volume-query", denon_protocol_1.QUERY_COMMAND, 1);
348
334
  return true;
349
335
  }
350
336
  if (state.observed.power !== "on" || state.observed.mainZone !== "on") {
@@ -371,7 +357,7 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
371
357
  }
372
358
  if (state.volumeRequest.target === null)
373
359
  return true;
374
- emitCommand("volume", formatVolumeCommand(state.volumeRequest.target), 1);
360
+ emitCommand("volume", (0, denon_protocol_1.formatVolumeCommand)(state.volumeRequest.target), 1);
375
361
  return true;
376
362
  }
377
363
  function reconcile(allowQuery = true) {
@@ -400,25 +386,29 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
400
386
  trace("observation", "manual_override");
401
387
  }
402
388
  if (state.desired && state.classification !== "manual_override" && !targetSatisfied()) {
403
- if (state.blockedGeneration === state.desired.generation)
389
+ // A failed request still answers volume: sent if the receiver is on,
390
+ // rejected otherwise.
391
+ if (blocked()) {
392
+ reconcileVolume(allowQuery);
404
393
  return;
394
+ }
405
395
  if (!hasFreshTargetState()) {
406
396
  state.phase = "discovering";
407
397
  if (allowQuery)
408
- emitCommand("query", exports.QUERY_COMMAND, 1);
398
+ emitCommand("query", denon_protocol_1.QUERY_COMMAND, 1);
409
399
  return;
410
400
  }
411
401
  if (state.desired.power === "standby") {
412
- emitCommand("standby", "PWSTANDBY\r", 1);
402
+ emitCommand("standby", denon_protocol_1.POWER_STANDBY, 1);
413
403
  }
414
404
  else if (state.observed.power !== "on") {
415
- emitCommand("power-on", "PWON\r", 1);
405
+ emitCommand("power-on", denon_protocol_1.POWER_ON, 1);
416
406
  }
417
407
  else if (state.observed.mainZone !== "on") {
418
- emitCommand("main-zone-on", "ZMON\r", 1);
408
+ emitCommand("main-zone-on", denon_protocol_1.ZONE_ON, 1);
419
409
  }
420
410
  else if (state.desired.source && state.observed.sourceCode !== desiredSourceCode()) {
421
- emitCommand("source", "SI" + desiredSourceCode() + "\r", 1);
411
+ emitCommand("source", (0, denon_protocol_1.selectSource)(desiredSourceCode()), 1);
422
412
  }
423
413
  return;
424
414
  }
@@ -460,17 +450,36 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
460
450
  return "zero-volume-delta";
461
451
  return null;
462
452
  }
463
- if (event.kind === "startup" || event.kind === "refresh") {
453
+ if (event.kind === "refresh") {
454
+ // Re-read the receiver without touching work in flight: desired state,
455
+ // pending commands, the volume request and the phase all carry on.
456
+ commands.push({
457
+ payload: denon_protocol_1.QUERY_COMMAND,
458
+ avrCommand: {
459
+ area: config.area,
460
+ operation: "query",
461
+ requestId: state.desired?.requestId || null,
462
+ generation: state.desired?.generation ?? state.generation,
463
+ attempt: 1
464
+ }
465
+ });
466
+ trace("refresh", "querying", null, { pending: state.pending?.operation ?? null });
467
+ forceStateEvent = true;
468
+ }
469
+ else if (event.kind === "startup") {
464
470
  const requestBlocked = state.desired &&
465
471
  state.blockedGeneration === state.desired.generation;
466
472
  const abandonedVolumeRequest = state.volumeRequest?.requestId || null;
473
+ // Not replayed after a restart: the caller hears it failed.
474
+ if (abandonedVolumeRequest)
475
+ volumeFailed(abandonedVolumeRequest, "restart", null, null);
467
476
  state.seen = { power: false, mainZone: false, source: false, volume: false };
468
477
  state.pending = null;
469
478
  state.volumeRequest = null;
470
479
  state.phase = requestBlocked ? "failed" : "discovering";
471
480
  state.querySentAt = nowMs;
472
481
  commands.push({
473
- payload: exports.QUERY_COMMAND,
482
+ payload: denon_protocol_1.QUERY_COMMAND,
474
483
  avrCommand: {
475
484
  area: config.area,
476
485
  operation: "query",
@@ -483,7 +492,7 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
483
492
  if (state.desired && !requestBlocked && state.classification !== "manual_override") {
484
493
  state.pending = {
485
494
  operation: "query",
486
- payload: exports.QUERY_COMMAND,
495
+ payload: denon_protocol_1.QUERY_COMMAND,
487
496
  attempt: 1,
488
497
  deadlineAt: nowMs + config.retryMs
489
498
  };
@@ -498,7 +507,7 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
498
507
  const lines = String(value ?? "").split(/[\r\n]+/).filter(Boolean);
499
508
  let recognised = 0;
500
509
  for (const line of lines) {
501
- const parsed = parseAvrLine(line, config.sources);
510
+ const parsed = (0, denon_protocol_1.parseAvrLine)(line, config.sources);
502
511
  if (!parsed)
503
512
  continue;
504
513
  recognised += 1;
@@ -506,6 +515,8 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
506
515
  let current;
507
516
  const wasFresh = state.seen[parsed.field];
508
517
  state.seen[parsed.field] = true;
518
+ state.fieldObservedAt[parsed.field] = now.toISOString();
519
+ reportedFields.add(parsed.field);
509
520
  if (parsed.field === "source") {
510
521
  previous = state.observed.sourceCode;
511
522
  state.observed.source = parsed.value;
@@ -629,6 +640,10 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
629
640
  state.blockedGeneration = null;
630
641
  state.classification = null;
631
642
  state.lastAttempt = 0;
643
+ // Ready belonged to the previous request; left as it was, the drift
644
+ // check would read this request's unmet target as a manual change.
645
+ if (state.phase === "ready" || state.phase === "manual_override")
646
+ state.phase = "idle";
632
647
  trace("intent", "accepted", null, {
633
648
  requestId: event.requestId,
634
649
  generation: event.generation,
@@ -700,8 +715,13 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
700
715
  state.volumeMetrics.intents += 1;
701
716
  if (boundedThisIntent)
702
717
  state.volumeMetrics.bounded += 1;
703
- if (state.pending?.operation === "volume")
718
+ if (state.pending?.operation === "volume") {
704
719
  state.pending = null;
720
+ // The last reading predates the command in flight, so it cannot
721
+ // confirm the new target: re-read before deciding.
722
+ if (target !== null && sameVolume(state.observed.volume, target))
723
+ state.seen.volume = false;
724
+ }
705
725
  trace("volume", "accepted", null, {
706
726
  requestId: event.requestId,
707
727
  mode: event.mode,
@@ -730,27 +750,9 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
730
750
  state.pending = null;
731
751
  if (isVolumeOperation(failed.operation)) {
732
752
  const requestId = state.volumeRequest?.requestId || null;
733
- state.volumeMetrics.failures += 1;
734
753
  state.volumeRequest = null;
735
- state.phase = state.classification === "manual_override"
736
- ? "manual_override"
737
- : state.desired && targetSatisfied()
738
- ? "ready"
739
- : "idle";
740
- events.push({
741
- avr: {
742
- kind: "volume_failed",
743
- area: config.area,
744
- requestId,
745
- operation: failed.operation,
746
- attempts: failed.attempt
747
- }
748
- });
749
- trace("volume", "failed", "attempts-exhausted", {
750
- requestId,
751
- operation: failed.operation,
752
- attempts: failed.attempt
753
- });
754
+ state.phase = restingPhase();
755
+ volumeFailed(requestId, "attempts-exhausted", failed.operation, failed.attempt);
754
756
  reconcile(false);
755
757
  }
756
758
  else {
@@ -786,6 +788,7 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
786
788
  const after = JSON.stringify({
787
789
  observed: state.observed,
788
790
  seen: state.seen,
791
+ fieldObservedAt: state.fieldObservedAt,
789
792
  desired: state.desired,
790
793
  generation: state.generation,
791
794
  pending: state.pending,
@@ -843,6 +846,52 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
843
846
  : state.phase === "ready"
844
847
  ? { phase: "ready", text: (state.observed.power || "unknown") + " · " + source }
845
848
  : { phase: "idle", text: (state.observed.power || "unknown") + " · " + source };
846
- return { state, commands, events, traces, status };
849
+ // The theatre activity controller's view of this target. Ready is stamped
850
+ // with the oldest report among the fields the request needs, so it is only
851
+ // as fresh as its least recent confirmation, and is re-sent only when the
852
+ // receiver reports one of those fields.
853
+ if (state.desired) {
854
+ const fields = requiredFields();
855
+ const status = state.phase === "manual_override"
856
+ ? "transitioning"
857
+ : (0, target_state_1.asTargetStatus)(state.phase, "confirming");
858
+ const confirmedAt = fields
859
+ .map((field) => state.fieldObservedAt[field])
860
+ .reduce((oldest, at) => at === null || oldest === null ? null : Date.parse(at) < Date.parse(oldest) ? at : oldest, now.toISOString());
861
+ const reported = fields.some((field) => reportedFields.has(field));
862
+ if (status !== "ready" || ((previousPhase !== "ready" || reported) && confirmedAt !== null)) {
863
+ const theatre = (0, target_state_1.targetStateEvent)({
864
+ target: "avr",
865
+ requestId: state.desired.requestId,
866
+ generation: state.desired.generation,
867
+ status,
868
+ observedAt: status === "ready" && confirmedAt !== null ? confirmedAt : now.toISOString(),
869
+ details: {
870
+ power: state.desired.power,
871
+ source: state.desired.source,
872
+ observed: {
873
+ power: state.observed.power,
874
+ mainZone: state.observed.mainZone,
875
+ source: state.observed.source
876
+ },
877
+ recovery: { power: state.observed.power, source: state.observed.source },
878
+ metrics: {
879
+ attempts: state.lastAttempt,
880
+ retries: Math.max(0, state.lastAttempt - 1),
881
+ fallbackUsed: false
882
+ }
883
+ },
884
+ classification: state.classification,
885
+ failure: state.failure && {
886
+ operation: state.failure.operation,
887
+ reason: "attempts-exhausted",
888
+ attempts: state.failure.attempts,
889
+ occurredAt: state.failure.at
890
+ }
891
+ });
892
+ targetStates.push({ theatre });
893
+ }
894
+ }
895
+ return { state, commands, events, targetStates, traces, status };
847
896
  }
848
897
  //# sourceMappingURL=avr-controller.js.map
@@ -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;
@@ -2,13 +2,15 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.normaliseBacklightingConfig = normaliseBacklightingConfig;
4
4
  exports.transitionBacklighting = transitionBacklighting;
5
+ const settings_1 = require("./settings");
5
6
  const observation_time_1 = require("./observation-time");
7
+ const target_state_1 = require("./target-state");
6
8
  const POWERS = { on: true, off: true };
7
9
  function normaliseBacklightingConfig(config = {}) {
8
10
  return {
9
- pollMs: Math.max(250, Number(config.pollMs) || 2000),
10
- confirmationTimeoutMs: Math.max(1000, Number(config.confirmationTimeoutMs) || 15000),
11
- maxAttempts: Math.max(1, Math.floor(Number(config.maxAttempts) || 2))
11
+ pollMs: Math.max(250, (0, settings_1.numberSetting)(config.pollMs, "poll interval", 2000)),
12
+ confirmationTimeoutMs: Math.max(1000, (0, settings_1.numberSetting)(config.confirmationTimeoutMs, "confirmation timeout", 15000)),
13
+ maxAttempts: Math.max(1, Math.floor((0, settings_1.numberSetting)(config.maxAttempts, "max attempts", 2)))
12
14
  };
13
15
  }
14
16
  function initialState(saved = {}) {
@@ -234,18 +236,11 @@ function transitionBacklighting(saved, msg, suppliedConfig = {}, nowValue = new
234
236
  throw new Error("unknown backlighting event kind");
235
237
  }
236
238
  if (state.desired) {
237
- const theatre = {
238
- kind: "target_state",
239
+ const theatre = (0, target_state_1.targetStateEvent)({
239
240
  target: "backlighting",
240
241
  requestId: state.desired.requestId,
241
242
  generation: state.generation,
242
- status: state.phase === "failed"
243
- ? "failed"
244
- : state.phase === "ready"
245
- ? "ready"
246
- : state.phase === "manual_override"
247
- ? "transitioning"
248
- : state.phase,
243
+ status: state.phase === "manual_override" ? "transitioning" : (0, target_state_1.asTargetStatus)(state.phase, "confirming"),
249
244
  observedAt: now.toISOString(),
250
245
  details: {
251
246
  power: state.desired.power,
@@ -256,12 +251,10 @@ function transitionBacklighting(saved, msg, suppliedConfig = {}, nowValue = new
256
251
  retries: Math.max(0, state.lastAttempt - 1),
257
252
  fallbackUsed: false
258
253
  }
259
- }
260
- };
261
- if (state.classification)
262
- theatre.classification = state.classification;
263
- if (state.failure)
264
- theatre.failure = { ...state.failure };
254
+ },
255
+ classification: state.classification,
256
+ failure: state.failure
257
+ });
265
258
  events.push({ theatre });
266
259
  }
267
260
  return { state, commands, events, traces, status: statusFor(state) };
@@ -9,6 +9,12 @@ export interface TraceMetadata {
9
9
  component: string;
10
10
  limit?: number;
11
11
  }
12
+ export interface TraceEntry<Details = Record<string, unknown>> {
13
+ event: string;
14
+ outcome: string;
15
+ reason: string | null;
16
+ details: Details;
17
+ }
12
18
  export interface TraceInput {
13
19
  at?: string;
14
20
  event: string;
@@ -0,0 +1,11 @@
1
+ export declare const WAKE_RISE_MINUTES = 60;
2
+ export declare const WIND_DOWN_MINUTES = 180;
3
+ export declare const DEFAULT_WAKE_TIME = "07:00";
4
+ export declare const DEFAULT_BED_TIME = "23:00";
5
+ export interface DaySchedule {
6
+ wakeTime: string;
7
+ bedTime: string;
8
+ }
9
+ export declare function clockMinutes(value: unknown): number | null;
10
+ export declare function resolveSchedule(wakeTime?: unknown, bedTime?: unknown): DaySchedule;
11
+ export declare function scheduleLevel(now: Date, wakeTime: string, bedTime: string): number;
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_BED_TIME = exports.DEFAULT_WAKE_TIME = exports.WIND_DOWN_MINUTES = exports.WAKE_RISE_MINUTES = void 0;
4
+ exports.clockMinutes = clockMinutes;
5
+ exports.resolveSchedule = resolveSchedule;
6
+ exports.scheduleLevel = scheduleLevel;
7
+ // A daily wake and bed schedule, and how far into the day a given moment is.
8
+ // Pure: it knows nothing about lights, and takes the time it is asked about.
9
+ // After waking, the day level rises over this long; before bed it winds down
10
+ // over the three hours that evidence on evening light exposure points to
11
+ // (Brown et al. 2022, PLOS Biology).
12
+ exports.WAKE_RISE_MINUTES = 60;
13
+ exports.WIND_DOWN_MINUTES = 180;
14
+ // A conventional day, used until a room is given its own times.
15
+ exports.DEFAULT_WAKE_TIME = "07:00";
16
+ exports.DEFAULT_BED_TIME = "23:00";
17
+ const MINUTES_PER_DAY = 24 * 60;
18
+ const CLOCK_TIME = /^([01]\d|2[0-3]):([0-5]\d)$/;
19
+ // Minutes after midnight for an "HH:MM" clock time, or null if it is not one.
20
+ function clockMinutes(value) {
21
+ const match = typeof value === "string" ? CLOCK_TIME.exec(value.trim()) : null;
22
+ return match ? Number(match[1]) * 60 + Number(match[2]) : null;
23
+ }
24
+ // A usable schedule from configured times: a blank time takes its default;
25
+ // each must be "HH:MM" and they must differ.
26
+ function resolveSchedule(wakeTime, bedTime) {
27
+ const wake = (typeof wakeTime === "string" ? wakeTime.trim() : "") || exports.DEFAULT_WAKE_TIME;
28
+ const bed = (typeof bedTime === "string" ? bedTime.trim() : "") || exports.DEFAULT_BED_TIME;
29
+ const wakeMinutes = clockMinutes(wake);
30
+ const bedMinutes = clockMinutes(bed);
31
+ if (wakeMinutes === null || bedMinutes === null)
32
+ throw new Error("wake and bed times must both be HH:MM (24-hour)");
33
+ if (wakeMinutes === bedMinutes)
34
+ throw new Error("wake and bed times must differ");
35
+ return { wakeTime: wake, bedTime: bed };
36
+ }
37
+ // Ease in and out, so neither end of a ramp is a visible step.
38
+ function ease(fraction) {
39
+ return fraction * fraction * (3 - 2 * fraction);
40
+ }
41
+ // The day level, from 0 (asleep) to 1 (full day), for the given local time.
42
+ // Times wrap at midnight, so a bed time after midnight or a wake time later
43
+ // than the bed time both work. A waking day shorter than the rise and the
44
+ // wind-down together shortens both in proportion.
45
+ function scheduleLevel(now, wakeTime, bedTime) {
46
+ const wake = clockMinutes(wakeTime);
47
+ const bed = clockMinutes(bedTime);
48
+ if (wake === null || bed === null || wake === bed)
49
+ throw new Error("wake and bed times must be different HH:MM times");
50
+ const awakeMinutes = (bed - wake + MINUTES_PER_DAY) % MINUTES_PER_DAY;
51
+ const minuteOfDay = now.getHours() * 60 + now.getMinutes() + now.getSeconds() / 60;
52
+ const sinceWake = (minuteOfDay - wake + MINUTES_PER_DAY) % MINUTES_PER_DAY;
53
+ if (sinceWake >= awakeMinutes)
54
+ return 0;
55
+ const shrink = Math.min(1, awakeMinutes / (exports.WAKE_RISE_MINUTES + exports.WIND_DOWN_MINUTES));
56
+ const rise = exports.WAKE_RISE_MINUTES * shrink;
57
+ const windDown = exports.WIND_DOWN_MINUTES * shrink;
58
+ if (sinceWake < rise)
59
+ return ease(sinceWake / rise);
60
+ const untilBed = awakeMinutes - sinceWake;
61
+ return untilBed < windDown ? ease(untilBed / windDown) : 1;
62
+ }
63
+ //# sourceMappingURL=circadian-schedule.js.map