@avantics/node-red-home-automation 4.0.3 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/README.md +447 -64
  2. package/contract-examples/room-lighting.mjs +39 -27
  3. package/contract-examples/switch-gestures.mjs +1 -1
  4. package/contract-examples/volume-ownership.mjs +6 -5
  5. package/dist/lib/activity-lighting-controller.d.ts +9 -2
  6. package/dist/lib/activity-lighting-controller.js +107 -19
  7. package/dist/lib/adopted-request.d.ts +17 -0
  8. package/dist/lib/adopted-request.js +61 -7
  9. package/dist/lib/avr-controller.d.ts +9 -3
  10. package/dist/lib/avr-controller.js +71 -24
  11. package/dist/lib/avr-publishing.d.ts +3 -3
  12. package/dist/lib/avr-publishing.js +11 -5
  13. package/dist/lib/backlighting-controller.d.ts +2 -0
  14. package/dist/lib/backlighting-controller.js +27 -7
  15. package/dist/lib/circadian-policy.d.ts +47 -0
  16. package/dist/lib/circadian-policy.js +111 -0
  17. package/dist/lib/circadian-publishing.d.ts +33 -0
  18. package/dist/lib/circadian-publishing.js +154 -0
  19. package/dist/lib/circadian-schedule.d.ts +4 -0
  20. package/dist/lib/circadian-schedule.js +12 -0
  21. package/dist/lib/command-echo.d.ts +8 -1
  22. package/dist/lib/command-echo.js +37 -6
  23. package/dist/lib/cover-controller.js +4 -0
  24. package/dist/lib/cover-publishing.js +1 -1
  25. package/dist/lib/denon-protocol.d.ts +5 -1
  26. package/dist/lib/denon-protocol.js +27 -11
  27. package/dist/lib/display-mode-controller.d.ts +12 -5
  28. package/dist/lib/display-mode-controller.js +181 -87
  29. package/dist/lib/enable-input.d.ts +3 -0
  30. package/dist/lib/enable-input.js +18 -0
  31. package/dist/lib/house-schedule-publishing.js +1 -1
  32. package/dist/lib/house-schedule.js +2 -2
  33. package/dist/lib/light-contract.d.ts +53 -0
  34. package/dist/lib/light-contract.js +11 -0
  35. package/dist/lib/light-styling.d.ts +2 -2
  36. package/dist/lib/light-styling.js +5 -4
  37. package/dist/lib/motion-policy.d.ts +0 -1
  38. package/dist/lib/motion-policy.js +9 -8
  39. package/dist/lib/motion-publishing.js +3 -2
  40. package/dist/lib/mqtt-message.d.ts +6 -0
  41. package/dist/lib/mqtt-message.js +21 -0
  42. package/dist/lib/occupancy-publishing.js +1 -1
  43. package/dist/lib/power-reading.d.ts +5 -0
  44. package/dist/lib/power-reading.js +13 -0
  45. package/dist/lib/room-controller.d.ts +39 -29
  46. package/dist/lib/room-controller.js +314 -192
  47. package/dist/lib/room-lighting-discovery.d.ts +0 -14
  48. package/dist/lib/room-lighting-discovery.js +20 -126
  49. package/dist/lib/room-publishing.d.ts +10 -12
  50. package/dist/lib/room-publishing.js +65 -125
  51. package/dist/lib/shelly-cover.d.ts +44 -0
  52. package/dist/lib/shelly-cover.js +153 -0
  53. package/dist/lib/shelly-gen2.d.ts +25 -0
  54. package/dist/lib/shelly-gen2.js +58 -0
  55. package/dist/lib/shelly-switch.d.ts +95 -0
  56. package/dist/lib/shelly-switch.js +237 -0
  57. package/dist/lib/source-capability-controller.d.ts +2 -0
  58. package/dist/lib/source-capability-controller.js +27 -6
  59. package/dist/lib/switch-policy.d.ts +1 -1
  60. package/dist/lib/switch-policy.js +1 -1
  61. package/dist/lib/theatre-requests.d.ts +29 -0
  62. package/dist/lib/theatre-requests.js +89 -0
  63. package/dist/lib/theatre-state-contract.d.ts +5 -22
  64. package/dist/lib/theatre-state-contract.js +30 -77
  65. package/dist/lib/toggle-power.d.ts +41 -0
  66. package/dist/lib/toggle-power.js +74 -0
  67. package/dist/lib/topic-names.d.ts +1 -0
  68. package/dist/lib/topic-names.js +7 -0
  69. package/dist/lib/{display-transport.d.ts → transports/display-transport.d.ts} +1 -1
  70. package/dist/lib/{display-transport.js → transports/display-transport.js} +32 -7
  71. package/dist/lib/z2m-cover.d.ts +49 -0
  72. package/dist/lib/z2m-cover.js +120 -0
  73. package/dist/lib/z2m-light-adapter.d.ts +62 -0
  74. package/dist/lib/z2m-light-adapter.js +195 -0
  75. package/dist/lib/z2m-light.d.ts +8 -0
  76. package/dist/lib/z2m-light.js +61 -3
  77. package/dist/nodes/activity-lighting-controller.html +20 -3
  78. package/dist/nodes/activity-lighting-controller.js +21 -0
  79. package/dist/nodes/avr-controller.html +25 -6
  80. package/dist/nodes/avr-controller.js +16 -6
  81. package/dist/nodes/circadian-policy.d.ts +3 -0
  82. package/dist/nodes/circadian-policy.html +140 -0
  83. package/dist/nodes/circadian-policy.js +162 -0
  84. package/dist/nodes/cover-controller.html +4 -3
  85. package/dist/nodes/display-mode-controller.html +58 -11
  86. package/dist/nodes/display-mode-controller.js +19 -6
  87. package/dist/nodes/house-schedule.html +3 -3
  88. package/dist/nodes/motion-policy.html +5 -2
  89. package/dist/nodes/motion-policy.js +3 -0
  90. package/dist/nodes/refused-enable.d.ts +7 -0
  91. package/dist/nodes/refused-enable.js +24 -0
  92. package/dist/nodes/room-controller.html +215 -82
  93. package/dist/nodes/room-controller.js +71 -83
  94. package/dist/nodes/shelly-cover.d.ts +3 -0
  95. package/dist/nodes/shelly-cover.html +65 -0
  96. package/dist/nodes/shelly-cover.js +34 -0
  97. package/dist/nodes/shelly-switch.d.ts +3 -0
  98. package/dist/nodes/shelly-switch.html +82 -0
  99. package/dist/nodes/shelly-switch.js +48 -0
  100. package/dist/nodes/theatre-state-contract.html +4 -3
  101. package/dist/nodes/z2m-cover.d.ts +3 -0
  102. package/dist/nodes/z2m-cover.html +68 -0
  103. package/dist/nodes/z2m-cover.js +41 -0
  104. package/dist/nodes/z2m-light.d.ts +3 -0
  105. package/dist/nodes/z2m-light.html +72 -0
  106. package/dist/nodes/z2m-light.js +50 -0
  107. package/examples/Cover control.json +24 -56
  108. package/examples/Home theatre activity.json +54 -9
  109. package/examples/Home theatre equipment.json +4 -4
  110. package/examples/House schedule.json +106 -24
  111. package/examples/Room lighting.json +54 -11
  112. package/examples/Shelly cover.json +252 -0
  113. package/examples/Shelly switch.json +197 -0
  114. package/package.json +13 -4
  115. package/dist/lib/room-schedule.d.ts +0 -8
  116. package/dist/lib/room-schedule.js +0 -41
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- 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,17 @@ 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
+ // 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";
15
18
  function observedTime(value) {
16
19
  return typeof value === "string" && Number.isFinite(Date.parse(value)) ? value : null;
17
20
  }
21
+ // A number, or a finite numeric string, as a number; null otherwise.
22
+ function numberValue(value) {
23
+ const number = typeof value === "number" ? value : typeof value === "string" && value.trim() !== "" ? Number(value) : NaN;
24
+ return Number.isFinite(number) ? number : null;
25
+ }
18
26
  function createAvrState(_config, saved = {}) {
19
27
  const observed = saved.observed || {};
20
28
  const seen = saved.seen || {};
@@ -22,13 +30,19 @@ function createAvrState(_config, saved = {}) {
22
30
  ? saved.volumeRequest
23
31
  : null;
24
32
  const volumeMetrics = saved.volumeMetrics || {};
33
+ // A state saved before 5.0, from a context store, holds volumes in the
34
+ // receiver's units; a relative request's `requested` is a change, the same
35
+ // in both.
36
+ const savedInReceiverUnits = Object.keys(saved).length > 0 && saved.volumeUnits !== "dB";
37
+ const db = (value) => (savedInReceiverUnits ? (0, denon_protocol_1.legacyVolumeDb)(value, "absolute") : value);
25
38
  return {
39
+ volumeUnits: "dB",
26
40
  observed: {
27
41
  power: observed.power === "on" || observed.power === "standby" ? observed.power : null,
28
42
  mainZone: observed.mainZone === "on" || observed.mainZone === "off" ? observed.mainZone : null,
29
43
  source: typeof observed.source === "string" ? observed.source : null,
30
44
  sourceCode: typeof observed.sourceCode === "string" ? observed.sourceCode : null,
31
- volume: Number.isFinite(observed.volume) ? observed.volume : null,
45
+ volume: Number.isFinite(observed.volume) ? db(observed.volume) : null,
32
46
  at: typeof observed.at === "string" ? observed.at : null
33
47
  },
34
48
  fieldObservedAt: {
@@ -56,8 +70,10 @@ function createAvrState(_config, saved = {}) {
56
70
  ? {
57
71
  requestId: volumeRequest.requestId,
58
72
  mode: volumeRequest.mode,
59
- requested: Number(volumeRequest.requested) || 0,
60
- target: Number.isFinite(volumeRequest.target) ? volumeRequest.target : null,
73
+ requested: volumeRequest.mode === "absolute" && Number.isFinite(volumeRequest.requested)
74
+ ? db(volumeRequest.requested)
75
+ : Number(volumeRequest.requested) || 0,
76
+ target: Number.isFinite(volumeRequest.target) ? db(volumeRequest.target) : null,
61
77
  bounded: volumeRequest.bounded === true
62
78
  }
63
79
  : null,
@@ -86,16 +102,25 @@ function sameVolume(left, right) {
86
102
  // failing every message.
87
103
  // Settings may be editor strings. Missing or unusable numbers take their
88
104
  // defaults: retry 2000 ms (at least 250), 3 attempts (at least 1) and volume
89
- // bounds 0 to 60.
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.
90
109
  function normaliseAvrConfig(rawConfig) {
91
- const rawMinVolume = (0, settings_1.numberSetting)(rawConfig.minVolume, "minimum volume", 0);
92
- const rawMaxVolume = (0, settings_1.numberSetting)(rawConfig.maxVolume, "maximum volume", 60);
110
+ const given = (value) => value !== undefined && value !== null && String(value).trim() !== "";
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);
93
118
  const minVolume = (0, denon_protocol_1.roundVolume)(rawMinVolume);
94
119
  const maxVolume = (0, denon_protocol_1.roundVolume)(rawMaxVolume);
95
120
  if (!Number.isFinite(rawMinVolume) || !Number.isFinite(rawMaxVolume) ||
96
121
  Math.abs(rawMinVolume - minVolume) > 0.001 || Math.abs(rawMaxVolume - maxVolume) > 0.001 ||
97
- minVolume < 0 || maxVolume > 98 || minVolume >= maxVolume) {
98
- throw new Error("volume bounds must be half-step values between 0 and 98 with minimum below maximum");
122
+ minVolume < denon_protocol_1.VOLUME_MIN_DB || maxVolume > denon_protocol_1.VOLUME_MAX_DB || minVolume >= maxVolume) {
123
+ throw new Error("volume bounds must be half-step values between -80 and 18 dB with minimum below maximum");
99
124
  }
100
125
  return {
101
126
  // Optional: an empty area means none.
@@ -103,8 +128,8 @@ function normaliseAvrConfig(rawConfig) {
103
128
  sources: (0, denon_protocol_1.parseSourceCodes)(rawConfig.sources),
104
129
  retryMs: Math.max(250, (0, settings_1.numberSetting)(rawConfig.retryMs, "retry interval", 2000)),
105
130
  maxAttempts: Math.max(1, Math.floor((0, settings_1.numberSetting)(rawConfig.maxAttempts, "max attempts", 3))),
106
- minVolume,
107
- maxVolume
131
+ minVolumeDb: minVolume,
132
+ maxVolumeDb: maxVolume
108
133
  };
109
134
  }
110
135
  function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
@@ -245,7 +270,7 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
245
270
  }
246
271
  function clampVolume(value) {
247
272
  const rounded = (0, denon_protocol_1.roundVolume)(value);
248
- const bounded = Math.max(config.minVolume, Math.min(config.maxVolume, rounded));
273
+ const bounded = Math.max(config.minVolumeDb, Math.min(config.maxVolumeDb, rounded));
249
274
  return { value: bounded, bounded: Math.abs(bounded - value) > 0.001 };
250
275
  }
251
276
  // The phase once no volume work is in flight; a failed request stays failed.
@@ -455,14 +480,30 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
455
480
  // A refresh with the activity's wanted values, reaching a node with
456
481
  // nothing desired (it started with nothing saved): adopt them, and
457
482
  // rediscover below as at startup (see adopted-request.ts).
483
+ let replacedRequest = false;
458
484
  const adoptable = event.kind === "refresh" ? (0, adopted_request_1.adoptableRefresh)(event, state) : null;
459
- const adopted = adoptable !== null && event.kind === "refresh" &&
485
+ // The same wanted values as the work in hand: carry on under the new
486
+ // request rather than adopting it read-only (see carryOn).
487
+ const carried = event.kind === "refresh" && (0, adopted_request_1.carryOn)(state, adoptable, event.power === state.desired?.power && (event.source || null) === (state.desired?.source ?? null), state.classification === "manual_override" || state.phase === "failed" || state.blockedGeneration === state.desired?.generation);
488
+ if (carried)
489
+ trace("refresh", "continued", "same-request", { generation: state.generation });
490
+ const adopted = !carried && adoptable !== null && event.kind === "refresh" &&
460
491
  validateIntent({ kind: "intent", ...adoptable, power: event.power, source: event.source ?? null }) === null;
461
492
  if (adopted && event.kind === "refresh") {
493
+ const reason = (0, adopted_request_1.adoptionReason)(state.desired);
494
+ // Replacing a request the theatre already counts as ready, it answers
495
+ // from its reading, not with an interim state the theatre would take as
496
+ // drift.
497
+ replacedRequest = reason === "newer-generation";
498
+ // A request it replaces takes its classification and failure with it.
499
+ state.failure = null;
500
+ state.blockedGeneration = null;
501
+ state.classification = null;
502
+ state.lastAttempt = 0;
462
503
  state.desired = { ...adoptable, power: event.power, source: event.source || null };
463
504
  state.generation = adoptable.generation;
464
505
  state.adoptedGeneration = adoptable.generation;
465
- trace("refresh", "adopted", "nothing-desired", { power: event.power, source: event.source || null, generation: adoptable.generation });
506
+ trace("refresh", "adopted", reason, { power: event.power, source: event.source || null, generation: adoptable.generation });
466
507
  }
467
508
  if (event.kind === "refresh" && !adopted) {
468
509
  // Re-read the receiver without touching work in flight: desired state,
@@ -669,7 +710,13 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
669
710
  forceStateEvent = true;
670
711
  }
671
712
  else if (event.kind === "volume") {
672
- const reason = validateVolumeIntent(event);
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.
716
+ const valueDb = numberValue(event.valueDb);
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);
673
720
  if (reason) {
674
721
  events.push({
675
722
  avr: {
@@ -688,32 +735,32 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
688
735
  else {
689
736
  const existing = state.volumeRequest;
690
737
  let mode = event.mode;
691
- let requested = event.value;
738
+ let requested = volume.value;
692
739
  let target = null;
693
740
  let bounded = false;
694
741
  let boundedThisIntent = false;
695
742
  if (event.mode === "absolute") {
696
- const resolved = clampVolume(event.value);
743
+ const resolved = clampVolume(volume.value);
697
744
  target = resolved.value;
698
745
  bounded = resolved.bounded;
699
746
  boundedThisIntent = resolved.bounded;
700
747
  }
701
748
  else if (existing?.target !== null && existing?.target !== undefined) {
702
- const unresolvedTarget = existing.target + event.value;
749
+ const unresolvedTarget = existing.target + volume.value;
703
750
  const resolved = clampVolume(unresolvedTarget);
704
751
  mode = existing.mode;
705
752
  requested = existing.mode === "relative"
706
- ? existing.requested + event.value
753
+ ? existing.requested + volume.value
707
754
  : unresolvedTarget;
708
755
  target = resolved.value;
709
756
  bounded = existing.bounded || resolved.bounded;
710
757
  boundedThisIntent = resolved.bounded;
711
758
  }
712
759
  else if (existing?.mode === "relative") {
713
- requested = existing.requested + event.value;
760
+ requested = existing.requested + volume.value;
714
761
  }
715
762
  else if (state.seen.volume && state.observed.volume !== null) {
716
- const resolved = clampVolume(state.observed.volume + event.value);
763
+ const resolved = clampVolume(state.observed.volume + volume.value);
717
764
  target = resolved.value;
718
765
  bounded = resolved.bounded;
719
766
  boundedThisIntent = resolved.bounded;
@@ -739,7 +786,7 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
739
786
  trace("volume", "accepted", null, {
740
787
  requestId: event.requestId,
741
788
  mode: event.mode,
742
- value: event.value,
789
+ value: volume.value,
743
790
  target,
744
791
  bounded
745
792
  });
@@ -842,7 +889,7 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
842
889
  classification: state.classification,
843
890
  volume: {
844
891
  request: state.volumeRequest ? { ...state.volumeRequest } : null,
845
- bounds: { minimum: config.minVolume, maximum: config.maxVolume },
892
+ bounds: { minimum: config.minVolumeDb, maximum: config.maxVolumeDb },
846
893
  metrics: { ...state.volumeMetrics }
847
894
  },
848
895
  metrics: {
@@ -874,7 +921,7 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
874
921
  // with the oldest report among the fields the request needs, so it is only
875
922
  // as fresh as its least recent confirmation, and is re-sent only when the
876
923
  // receiver reports one of those fields.
877
- if (state.desired) {
924
+ if (state.desired && !replacedRequest) {
878
925
  const fields = requiredFields();
879
926
  const status = state.phase === "manual_override"
880
927
  ? "transitioning"
@@ -1,8 +1,8 @@
1
1
  import type { AvrObserved } from "./avr-controller";
2
2
  import { type OptInPublishingConfig, type RetainedText } from "./publishing-node";
3
3
  export interface AvrPublishingConfig extends OptInPublishingConfig {
4
- minVolume: number;
5
- maxVolume: number;
4
+ minVolumeDb: number;
5
+ maxVolumeDb: number;
6
6
  }
7
7
  export type AvrPublication = RetainedText;
8
8
  export declare function receiverTopic(area: string, name: string): string;
@@ -13,7 +13,7 @@ export declare function avrVolumeRequest(msg: {
13
13
  payload?: unknown;
14
14
  retain?: unknown;
15
15
  }, config: AvrPublishingConfig): {
16
- value: number;
16
+ valueDb: number;
17
17
  } | {
18
18
  ignored: string;
19
19
  payload: string;
@@ -5,12 +5,17 @@ exports.receiverTopic = receiverTopic;
5
5
  exports.avrDiscovery = avrDiscovery;
6
6
  exports.avrVolumeRequest = avrVolumeRequest;
7
7
  exports.avrStateOutputs = avrStateOutputs;
8
+ // The receiver's MQTT and Home Assistant side: its observed power, source
9
+ // and volume as retained state, its availability, power and source sensors,
10
+ // and a volume number. All of it is opt-in (see publishing-node.ts); the
11
+ // receiver controller only commands and observes the receiver.
12
+ const denon_protocol_1 = require("./denon-protocol");
8
13
  const topic_names_1 = require("./topic-names");
9
14
  const publishing_node_1 = require("./publishing-node");
10
15
  const FIELDS = ["power", "source", "volume"];
11
16
  const DEVICE = { kind: "receiver", label: "Receiver", model: "AV receiver controller" };
12
17
  function receiverTopic(area, name) {
13
- return "home/" + (0, topic_names_1.areaId)(area) + "/receiver/" + name;
18
+ return (0, topic_names_1.homeTopic)(area, "receiver", name);
14
19
  }
15
20
  // A field's state as published, or null while it isn't known.
16
21
  function fieldValue(observed, field) {
@@ -32,9 +37,10 @@ function avrDiscovery(config) {
32
37
  icon: "mdi:volume-high",
33
38
  state_topic: receiverTopic(config.area, "volume/state"),
34
39
  command_topic: receiverTopic(config.area, "volume/set"),
35
- min: config.minVolume,
36
- max: config.maxVolume,
37
- step: 0.5,
40
+ min: config.minVolumeDb,
41
+ max: config.maxVolumeDb,
42
+ step: denon_protocol_1.VOLUME_STEP_DB,
43
+ unit_of_measurement: "dB",
38
44
  mode: "slider"
39
45
  })
40
46
  ];
@@ -54,7 +60,7 @@ function avrVolumeRequest(msg, config) {
54
60
  if (msg.retain === true)
55
61
  return { ignored: "retained-message", payload: text };
56
62
  const value = text === "" ? NaN : Number(text);
57
- return Number.isFinite(value) ? { value } : { ignored: "not-a-number", payload: text };
63
+ return Number.isFinite(value) ? { valueDb: value } : { ignored: "not-a-number", payload: text };
58
64
  }
59
65
  // The observed fields that changed since `before` (all known fields when
60
66
  // there's no `before`).
@@ -1,3 +1,4 @@
1
+ import { type Carried } from "./adopted-request";
1
2
  import type { TraceEntry } from "./bounded-trace";
2
3
  import { type TargetStateEvent } from "./target-state";
3
4
  export type BacklightingPower = "on" | "off";
@@ -38,6 +39,7 @@ export interface BacklightingState {
38
39
  classification: "manual_override" | null;
39
40
  lastAttempt: number;
40
41
  adoptedGeneration: number | null;
42
+ carried?: Carried | null;
41
43
  }
42
44
  export type BacklightingEvent = {
43
45
  kind: "intent";
@@ -27,7 +27,8 @@ function initialState(saved = {}) {
27
27
  lastAttempt: Number.isInteger(saved.lastAttempt) && (saved.lastAttempt ?? -1) >= 0
28
28
  ? saved.lastAttempt
29
29
  : 0,
30
- adoptedGeneration: (0, adopted_request_1.savedAdoptedGeneration)(saved)
30
+ adoptedGeneration: (0, adopted_request_1.savedAdoptedGeneration)(saved),
31
+ carried: (0, adopted_request_1.savedCarried)(saved)
31
32
  };
32
33
  }
33
34
  function commandFor(state, operation, attempt) {
@@ -129,7 +130,7 @@ function transitionBacklighting(saved, msg, suppliedConfig = {}, nowValue = new
129
130
  if (parsedAt === null || typeof observation.observedAt !== "string") {
130
131
  throw new Error("backlighting observedAt must be an ISO timestamp");
131
132
  }
132
- if (!state.desired || observation.generation !== state.generation) {
133
+ if (!state.desired || !(0, adopted_request_1.answersRequest)(state.carried, state.generation, observation.generation)) {
133
134
  trace("observation", "ignored", "stale-generation");
134
135
  return;
135
136
  }
@@ -182,11 +183,26 @@ function transitionBacklighting(saved, msg, suppliedConfig = {}, nowValue = new
182
183
  // below as at startup (see adopted-request.ts).
183
184
  let answerWithReading = false;
184
185
  const adoptable = event.kind === "refresh" ? (0, adopted_request_1.adoptableRefresh)(event, state) : null;
185
- if (adoptable && event.kind === "refresh" && typeof event.power === "string" && Object.hasOwn(POWERS, event.power)) {
186
+ // The same wanted values as the work in hand: carry on under the new
187
+ // request rather than adopting it read-only (see carryOn).
188
+ const carried = event.kind === "refresh" && (0, adopted_request_1.carryOn)(state, adoptable, event.power === state.desired?.power, state.classification === "manual_override" || state.phase === "failed" || state.blockedGeneration === state.desired?.generation);
189
+ if (carried)
190
+ trace("refresh", "continued", "same-request", { generation: state.generation });
191
+ if (!carried && adoptable && event.kind === "refresh" && typeof event.power === "string" && Object.hasOwn(POWERS, event.power)) {
192
+ const reason = (0, adopted_request_1.adoptionReason)(state.desired);
193
+ // Replacing a request the theatre already counts as ready, it answers
194
+ // from its reading, not with an interim state the theatre would take as
195
+ // drift.
196
+ answerWithReading = reason === "newer-generation";
197
+ // A request it replaces takes its classification and failure with it.
198
+ state.failure = null;
199
+ state.blockedGeneration = null;
200
+ state.classification = null;
201
+ state.lastAttempt = 0;
186
202
  state.desired = { ...adoptable, power: event.power, requestedAt: now.toISOString() };
187
203
  state.generation = adoptable.generation;
188
204
  state.adoptedGeneration = adoptable.generation;
189
- trace("refresh", "adopted", "nothing-desired", { power: event.power, generation: adoptable.generation });
205
+ trace("refresh", "adopted", reason, { power: event.power, generation: adoptable.generation });
190
206
  }
191
207
  if (event.kind === "intent") {
192
208
  acceptIntent(event);
@@ -195,7 +211,7 @@ function transitionBacklighting(saved, msg, suppliedConfig = {}, nowValue = new
195
211
  acceptObservation(event);
196
212
  }
197
213
  else if (event.kind === "command_result") {
198
- if (!state.desired || event.generation !== state.generation || !state.pending) {
214
+ if (!state.desired || !(0, adopted_request_1.answersRequest)(state.carried, state.generation, event.generation) || !state.pending) {
199
215
  trace("command-result", "ignored", "stale-generation");
200
216
  }
201
217
  else if (event.ok === true) {
@@ -268,12 +284,16 @@ function transitionBacklighting(saved, msg, suppliedConfig = {}, nowValue = new
268
284
  trace("command", "withheld", adopted_request_1.ADOPTED_MISMATCH);
269
285
  }
270
286
  if (state.desired && !answerWithReading) {
287
+ const status = state.phase === "manual_override" ? "transitioning" : (0, target_state_1.asTargetStatus)(state.phase, "confirming");
271
288
  const theatre = (0, target_state_1.targetStateEvent)({
272
289
  target: "backlighting",
273
290
  requestId: state.desired.requestId,
274
291
  generation: state.generation,
275
- status: state.phase === "manual_override" ? "transitioning" : (0, target_state_1.asTargetStatus)(state.phase, "confirming"),
276
- observedAt: now.toISOString(),
292
+ status,
293
+ // Ready is only as fresh as the reading it rests on, as the display's
294
+ // is: a repeated intent or other input with nothing new read must not
295
+ // look like a new reading, or it would answer a theatre refresh.
296
+ observedAt: status === "ready" && state.observed ? state.observed.observedAt : now.toISOString(),
277
297
  details: {
278
298
  power: state.desired.power,
279
299
  observedPower: state.observed?.power ?? null,
@@ -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 {};