@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,15 +1,61 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.parsePayload = exports.fingerprint = void 0;
3
+ exports.MOVED_TO_CIRCADIAN = exports.MOVED_CIRCADIAN_SETTINGS = exports.ON_OFF_ONLY = exports.INVALID_LIGHT_VALUES = exports.REMOVED_LIGHT_UNITS = exports.parsePayload = exports.fingerprint = void 0;
4
+ exports.movedCircadianSettings = movedCircadianSettings;
5
+ exports.targetsWithTopics = targetsWithTopics;
4
6
  exports.createRoomState = createRoomState;
5
- exports.adaptivePayload = adaptivePayload;
7
+ exports.intentValues = intentValues;
6
8
  exports.transitionRoom = transitionRoom;
7
- const room_schedule_1 = require("./room-schedule");
9
+ const light_contract_1 = require("./light-contract");
8
10
  const z2m_light_1 = require("./z2m-light");
9
11
  const command_echo_1 = require("./command-echo");
10
12
  var command_echo_2 = require("./command-echo");
11
13
  Object.defineProperty(exports, "fingerprint", { enumerable: true, get: function () { return command_echo_2.fingerprint; } });
12
14
  Object.defineProperty(exports, "parsePayload", { enumerable: true, get: function () { return command_echo_2.parsePayload; } });
15
+ // Traced when an intent gives brightness or color_temp, Zigbee2MQTT's own
16
+ // units, removed in 6.0: left out of the command, and the node warns.
17
+ exports.REMOVED_LIGHT_UNITS = "removed-light-units";
18
+ // Traced when an intent's brightnessPct or colorTempKelvin is unusable (not
19
+ // a number, or a kelvin of 0 or less): it is left out of the command, and
20
+ // the node warns.
21
+ exports.INVALID_LIGHT_VALUES = "invalid-light-values";
22
+ // Traced when an intent gives values for a light that only switches on and
23
+ // off: they are left out, and the node warns.
24
+ exports.ON_OFF_ONLY = "on-off-only";
25
+ // The settings a room had for circadian lighting before 6.0, now the
26
+ // circadian lighting policy's. A room whose saved settings still have any of
27
+ // them hasn't been migrated: it is an invalid configuration, so it can't
28
+ // quietly run unstyled. Empty, as a new 6.0 room has them, means absent.
29
+ exports.MOVED_CIRCADIAN_SETTINGS = [
30
+ "houseSchedule", "wakeTime", "bedTime", "maxBrightnessPct", "maxColorTempKelvin", "sleepBrightnessPct",
31
+ "sleepColorTempKelvin", "refreshTransitionSeconds", "refreshSeconds", "initialSleep",
32
+ // A room saved by 2.x and never re-saved has only these, ignored since 3.0.
33
+ "latitude", "longitude", "minBrightnessPct", "minColorTempKelvin"
34
+ ];
35
+ function movedCircadianSettings(config) {
36
+ return exports.MOVED_CIRCADIAN_SETTINGS.filter((key) => config[key] !== undefined && config[key] !== null && config[key] !== "");
37
+ }
38
+ // The targets of a room saved before 6.0, which named each light's
39
+ // Zigbee2MQTT topics (stateTopic, commandTopic): they move to a light
40
+ // adapter each, so such a room hasn't been migrated either. Their ids.
41
+ function targetsWithTopics(targets) {
42
+ let parsed = targets;
43
+ if (typeof targets === "string") {
44
+ try {
45
+ parsed = JSON.parse(targets);
46
+ }
47
+ catch {
48
+ return [];
49
+ }
50
+ }
51
+ return Array.isArray(parsed)
52
+ ? parsed.filter((target) => target && typeof target === "object" && ("stateTopic" in target || "commandTopic" in target))
53
+ .map((target) => String(target.id))
54
+ : [];
55
+ }
56
+ // Traced when the room is sent circadian, sleep or schedule messages, which
57
+ // the circadian lighting policy takes since 6.0: ignored, and the node warns.
58
+ exports.MOVED_TO_CIRCADIAN = "moved-to-circadian";
13
59
  function savedControl(saved) {
14
60
  if (saved.control) {
15
61
  return Object.fromEntries(Object.entries(saved.control).map(([target, entry]) => [target, { ...entry }]));
@@ -25,23 +71,72 @@ function createRoomState(config, saved = {}) {
25
71
  desired: { ...(saved.desired || {}) },
26
72
  control: savedControl(saved),
27
73
  expected: Object.fromEntries(Object.entries(saved.expected || {}).map(([target, entries]) => [target, entries.map((entry) => ({ ...entry }))])),
28
- circadianEnabled: saved.circadianEnabled !== false,
29
- sleeping: saved.sleeping === undefined ? config.initialSleep : saved.sleeping === true,
30
- ...(0, room_schedule_1.savedSchedule)(config, saved),
74
+ style: savedStyle(saved.style),
31
75
  personAt: Object.fromEntries(Object.entries(saved.personAt || {})
32
76
  .filter(([, at]) => Number.isFinite(at))),
33
77
  untold: Array.isArray(saved.untold)
34
78
  ? saved.untold.filter((id) => config.targets.some((target) => target.id === id))
35
79
  : [],
36
80
  restyledAt: Object.fromEntries(Object.entries(saved.restyledAt || {})
37
- .filter(([target, at]) => Number.isFinite(at) && config.targets.some((entry) => entry.id === target)))
81
+ .filter(([target, at]) => Number.isFinite(at) && config.targets.some((entry) => entry.id === target))),
82
+ available: Object.fromEntries(Object.entries(saved.available || {}).filter(([, online]) => typeof online === "boolean")),
83
+ commandSeq: Number.isInteger(saved.commandSeq) ? saved.commandSeq : 0
38
84
  };
39
85
  }
40
- // A circadian light command for this moment.
41
- function adaptivePayload(lightState, isRefresh, sleeping, now, config) {
42
- if (lightState === "OFF")
43
- return { state: lightState };
44
- return (0, z2m_light_1.lightCommand)(lightState, config.lighting.styleAt(now, sleeping), isRefresh ? config.refreshTransitionSeconds : config.initialTransitionSeconds);
86
+ // A brightness percent or kelvin as a number: a number, or a finite numeric
87
+ // string; null otherwise.
88
+ function numberValue(value) {
89
+ const number = typeof value === "number" ? value : typeof value === "string" && value.trim() !== "" ? Number(value) : NaN;
90
+ return Number.isFinite(number) ? number : null;
91
+ }
92
+ // An intent's values for a light: brightnessPct and colorTempKelvin as
93
+ // numbers, anything else (an effect, say) passed on as it is, in its order.
94
+ // brightness and color_temp, Zigbee2MQTT's own units removed in 6.0, are
95
+ // `removed`; an unusable brightnessPct or colorTempKelvin is `invalid`.
96
+ // Neither reaches the light.
97
+ function intentValues(values) {
98
+ const extra = {};
99
+ const removed = [];
100
+ const invalid = [];
101
+ let brightnessPct;
102
+ let colorTempKelvin;
103
+ for (const [key, value] of Object.entries(values)) {
104
+ if (key === "brightnessPct" || key === "colorTempKelvin") {
105
+ const number = numberValue(value);
106
+ if (number === null || (key === "colorTempKelvin" && number <= 0))
107
+ invalid.push(key);
108
+ else if (key === "brightnessPct")
109
+ brightnessPct = number;
110
+ else
111
+ colorTempKelvin = number;
112
+ }
113
+ else if (z2m_light_1.REMOVED_LIGHT_FIELDS.includes(key)) {
114
+ removed.push(key);
115
+ }
116
+ else {
117
+ extra[key] = value;
118
+ }
119
+ }
120
+ return { brightnessPct, colorTempKelvin, extra, removed, invalid };
121
+ }
122
+ // A style as received or saved, or null if it isn't one. State saved before
123
+ // 6.0 has none.
124
+ function savedStyle(style) {
125
+ if (!style || typeof style !== "object")
126
+ return null;
127
+ const entry = style;
128
+ const values = entry.values && typeof entry.values === "object" &&
129
+ Number.isFinite(entry.values.brightnessPct) && Number.isFinite(entry.values.colorTempKelvin) && entry.values.colorTempKelvin > 0
130
+ ? { brightnessPct: entry.values.brightnessPct, colorTempKelvin: entry.values.colorTempKelvin }
131
+ : null;
132
+ if (typeof entry.until !== "string" || !Number.isFinite(Date.parse(entry.until)))
133
+ return null;
134
+ return {
135
+ values,
136
+ transitionSeconds: Number.isFinite(entry.transitionSeconds) ? Number(entry.transitionSeconds) : 0,
137
+ until: entry.until,
138
+ source: typeof entry.source === "string" && entry.source ? entry.source : "style"
139
+ };
45
140
  }
46
141
  function transitionRoom(saved, msg, config, nowValue = new Date()) {
47
142
  const now = nowValue instanceof Date ? nowValue : new Date(nowValue);
@@ -49,19 +144,17 @@ function transitionRoom(saved, msg, config, nowValue = new Date()) {
49
144
  const state = createRoomState(config, saved);
50
145
  if (saved === undefined)
51
146
  state.untold = config.targets.map((target) => target.id);
52
- // The settings with lighting on the times in use; a schedule change
53
- // below replaces it.
54
- let active = (0, room_schedule_1.withActiveSchedule)(config, state);
55
147
  const targetById = Object.fromEntries(config.targets.map((target) => [target.id, target]));
56
148
  const traces = [];
57
149
  const outputs = [];
150
+ // Light commands (and requests for readings), for the lights' adapters.
151
+ const commands = [];
58
152
  function trace(event, outcome, reason = null, details = {}) {
59
153
  traces.push({ event, outcome, reason, details });
60
154
  }
61
- function targetForTopic(topic, field) {
62
- return config.targets.find((target) => target[field] === topic);
63
- }
64
155
  const controlChanged = new Set();
156
+ // Lights whose availability changed, for their control state publications.
157
+ const availabilityChanged = new Set();
65
158
  function controlOf(targetId) {
66
159
  return state.control[targetId]?.state ?? "in-control";
67
160
  }
@@ -89,37 +182,55 @@ function transitionRoom(saved, msg, config, nowValue = new Date()) {
89
182
  return state.desired[targetId] === true;
90
183
  return state.observed[targetId]?.on === true;
91
184
  }
92
- function command(targetId, payload, source) {
93
- const target = targetById[targetId];
94
- if (!target)
185
+ // A command for a light, remembered for its power until a reading confirms
186
+ // it; a restyle only tentatively, until its adapter says it sent it.
187
+ function command(targetId, spec, source) {
188
+ if (!targetById[targetId])
95
189
  return null;
96
- state.expected[targetId] = (0, command_echo_1.rememberCommand)(state.expected[targetId], payload, nowMs);
97
- return {
98
- topic: target.commandTopic,
99
- payload,
100
- retain: false,
101
- lighting_command: { area: config.area, target: targetId, source }
102
- };
190
+ state.commandSeq += 1;
191
+ const id = String(state.commandSeq);
192
+ state.expected[targetId] = (0, command_echo_1.rememberCommand)(state.expected[targetId], { state: spec.state }, nowMs, { id, tentative: spec.restyle === true });
193
+ const message = { kind: "command", target: targetId, ...spec, source, id };
194
+ commands.push(message);
195
+ return message;
103
196
  }
104
- function refreshCommands(source) {
105
- if (!state.circadianEnabled)
106
- return [];
107
- const commands = [];
197
+ function onOffOnly(targetId) {
198
+ return targetById[targetId]?.onOffOnly === true;
199
+ }
200
+ // The style in force: one with values that hasn't gone stale.
201
+ function currentStyle() {
202
+ const style = state.style;
203
+ return style?.values && Date.parse(style.until) > nowMs ? style.values : null;
204
+ }
205
+ // A style command for a light, over a transition; null for a light that
206
+ // only switches on and off, or with no style in force.
207
+ function styled(targetId, transitionSeconds) {
208
+ const style = currentStyle();
209
+ return style && !onOffOnly(targetId)
210
+ ? { state: "ON", brightnessPct: style.brightnessPct, colorTempKelvin: style.colorTempKelvin, transitionSeconds }
211
+ : null;
212
+ }
213
+ // Each light that is on and the room's to style, moved to the style in
214
+ // force over the style's transition.
215
+ // Each light that is on and the room's to style, moved to the style in
216
+ // force over the style's transition. Its adapter skips a light that
217
+ // already shows it (and says so).
218
+ function restyleLights(source) {
219
+ const style = currentStyle();
220
+ if (!style || !state.style)
221
+ return;
108
222
  for (const target of config.targets) {
109
223
  if (!intendedOn(target.id) || controlOf(target.id) !== "in-control")
110
224
  continue;
225
+ if (onOffOnly(target.id))
226
+ continue;
111
227
  if (state.untold.includes(target.id)) {
112
228
  trace("refresh", "skipped", "not-told-since-start", { target: target.id });
113
229
  continue;
114
230
  }
115
- // Nothing to change when the light last reported exactly this style.
116
- if ((0, z2m_light_1.alreadyStyled)(active.lighting.styleAt(now, state.sleeping), state.observed[target.id])) {
117
- trace("refresh", "skipped", "already-at-level", { target: target.id });
118
- continue;
119
- }
120
- commands.push(command(target.id, adaptivePayload("ON", true, state.sleeping, now, active), source));
231
+ command(target.id, { state: "ON", brightnessPct: style.brightnessPct, colorTempKelvin: style.colorTempKelvin,
232
+ transitionSeconds: state.style.transitionSeconds, restyle: true }, source);
121
233
  }
122
- return commands.filter((entry) => entry !== null);
123
234
  }
124
235
  function emitIntent(event) {
125
236
  const targets = Array.isArray(event.targets)
@@ -128,7 +239,7 @@ function transitionRoom(saved, msg, config, nowValue = new Date()) {
128
239
  const requestedState = String(event.state || "").toUpperCase();
129
240
  if (!["ON", "OFF", "TOGGLE"].includes(requestedState))
130
241
  return [];
131
- const commands = [];
242
+ const sent = [];
132
243
  const manualValues = event.values && typeof event.values === "object" ? event.values : null;
133
244
  const owner = typeof event.owner === "string" && event.owner ? event.owner : null;
134
245
  for (const targetId of targets) {
@@ -168,164 +279,181 @@ function transitionRoom(saved, msg, config, nowValue = new Date()) {
168
279
  else if (owner) {
169
280
  setControl(targetId, { state: "overridden", owner }, "owner-intent");
170
281
  }
171
- else if (event.manual === true || (manualValues && event.source !== "activity")) {
282
+ else if (event.manual === true) {
283
+ // Only a person's change makes a light manual: since 6.0, an intent's
284
+ // values alone don't.
172
285
  setControl(targetId, { state: "manual" }, "manual-intent");
173
286
  }
174
- let payload;
287
+ let spec;
175
288
  if (resolvedState === "OFF") {
176
- payload = { state: "OFF" };
289
+ spec = { state: "OFF" };
177
290
  }
178
- else if (manualValues) {
179
- payload = { state: "ON", ...manualValues };
180
- if (!Object.hasOwn(payload, "transition")) {
181
- payload.transition = config.initialTransitionSeconds;
182
- }
291
+ else if (manualValues && onOffOnly(targetId)) {
292
+ // Nothing to set on a light that only switches: left out, and the
293
+ // node warns.
294
+ trace("intent", "accepted", exports.ON_OFF_ONLY, { target: targetId, dropped: Object.keys(manualValues) });
295
+ spec = { state: "ON" };
183
296
  }
184
- else if (state.circadianEnabled && controlOf(targetId) === "in-control") {
185
- payload = adaptivePayload("ON", event.refresh === true, state.sleeping, now, active);
297
+ else if (manualValues) {
298
+ const values = intentValues(manualValues);
299
+ if (values.removed.length)
300
+ trace("intent", "accepted", exports.REMOVED_LIGHT_UNITS, { target: targetId, dropped: values.removed, values: manualValues });
301
+ if (values.invalid.length)
302
+ trace("intent", "accepted", exports.INVALID_LIGHT_VALUES, { target: targetId, dropped: values.invalid, values: manualValues });
303
+ spec = {
304
+ state: "ON",
305
+ ...(Object.keys(values.extra).length ? { extra: values.extra } : {}),
306
+ ...(values.brightnessPct !== undefined ? { brightnessPct: values.brightnessPct } : {}),
307
+ ...(values.colorTempKelvin !== undefined ? { colorTempKelvin: values.colorTempKelvin } : {}),
308
+ // An intent's own transition (among its other fields) stands.
309
+ transitionSeconds: config.initialTransitionSeconds
310
+ };
186
311
  }
187
312
  else {
188
- payload = { state: "ON" };
313
+ // A bare ON: the style in force for a light the room controls,
314
+ // otherwise just on.
315
+ spec = (controlOf(targetId) === "in-control" ? styled(targetId, config.initialTransitionSeconds) : null) ?? { state: "ON" };
189
316
  }
190
317
  state.desired[targetId] = resolvedState === "ON";
191
318
  told(targetId);
192
- commands.push(command(targetId, payload, event.source || "intent"));
319
+ sent.push(command(targetId, spec, event.source || "intent"));
193
320
  }
194
- return commands.filter((entry) => entry !== null);
321
+ return sent.filter((entry) => entry !== null);
195
322
  }
196
323
  // What the room publishes, and the MQTT it reads for itself, are
197
324
  // room-publishing.ts's; this decides about lights only.
198
325
  const event = msg.lighting || {};
199
- if (event.kind === "observed") {
200
- const target = event.target ? targetById[event.target] : targetForTopic(msg.topic, "stateTopic");
201
- const parsed = (0, command_echo_1.parsePayload)(msg.payload);
202
- const payload = parsed && typeof parsed === "object" ? parsed : null;
203
- const light = payload ? (0, z2m_light_1.readLightReport)(payload) : null;
204
- if (target && light) {
205
- const previousOn = state.observed[target.id]?.on;
206
- const nextOn = light.on;
207
- state.observed[target.id] = { ...light, observedAt: now.toISOString() };
208
- if (previousOn !== nextOn) {
209
- trace("state-observed", "changed", null, {
210
- target: target.id,
211
- state: nextOn ? "ON" : "OFF"
212
- });
213
- }
214
- const report = (0, command_echo_1.checkStateReport)(state.expected[target.id], nextOn, nowMs);
215
- state.expected[target.id] = report.queue;
216
- if (report.verdict === "confirms") {
217
- // Our own command, now done: the intended state already says so.
218
- // A confirmed OFF deliberately leaves control alone: our OFFs come
219
- // from OFF intents, which already returned the light to in-control.
220
- trace("state-observed", "confirmed", "own-command", { target: target.id, state: nextOn ? "ON" : "OFF" });
221
- }
222
- else if (report.verdict === "stale") {
223
- // Older than our pending command; the light will report again.
224
- trace("state-observed", "ignored", "stale-report", { target: target.id, state: nextOn ? "ON" : "OFF" });
225
- }
226
- else {
227
- // A change the controller didn't cause becomes the intended state.
228
- state.desired[target.id] = nextOn;
229
- if (!nextOn)
230
- setControl(target.id, null, "observed-off");
231
- }
326
+ const reading = (0, light_contract_1.isLightReading)(msg.light) && targetById[msg.light.target] ? msg.light : null;
327
+ if (reading?.kind === "observed") {
328
+ const target = targetById[reading.target];
329
+ const previousOn = state.observed[target.id]?.on;
330
+ const nextOn = reading.on === true;
331
+ state.observed[target.id] = {
332
+ on: nextOn,
333
+ ...(typeof reading.brightnessPct === "number" ? { brightnessPct: reading.brightnessPct } : {}),
334
+ ...(typeof reading.colorTempKelvin === "number" ? { colorTempKelvin: reading.colorTempKelvin } : {}),
335
+ fields: Array.isArray(reading.fields) ? [...reading.fields] : [],
336
+ observedAt: now.toISOString()
337
+ };
338
+ if (previousOn !== nextOn) {
339
+ trace("state-observed", "changed", null, {
340
+ target: target.id,
341
+ state: nextOn ? "ON" : "OFF"
342
+ });
343
+ }
344
+ const report = (0, command_echo_1.checkStateReport)(state.expected[target.id], nextOn, nowMs);
345
+ state.expected[target.id] = report.queue;
346
+ if (report.verdict === "confirms") {
347
+ // Our own command, now done: the intended state already says so.
348
+ // A confirmed OFF deliberately leaves control alone: our OFFs come
349
+ // from OFF intents, which already returned the light to in-control.
350
+ trace("state-observed", "confirmed", "own-command", { target: target.id, state: nextOn ? "ON" : "OFF" });
351
+ }
352
+ else if (report.verdict === "stale") {
353
+ // Older than our pending command; the light will report again.
354
+ trace("state-observed", "ignored", "stale-report", { target: target.id, state: nextOn ? "ON" : "OFF" });
355
+ }
356
+ else {
357
+ // A change the controller didn't cause becomes the intended state.
358
+ state.desired[target.id] = nextOn;
359
+ if (!nextOn)
360
+ setControl(target.id, null, "observed-off");
232
361
  }
233
362
  }
234
- else if (event.kind === "command-observed") {
235
- const target = event.target ? targetById[event.target] : targetForTopic(msg.topic, "commandTopic");
236
- const parsed = (0, command_echo_1.parsePayload)(msg.payload);
237
- const payload = parsed && typeof parsed === "object" ? parsed : null;
238
- if (msg.retain !== true && event.retained !== true && target && payload) {
239
- const echo = (0, command_echo_1.checkCommandEcho)(state.expected[target.id], payload, nowMs);
240
- state.expected[target.id] = echo.queue;
241
- if (echo.changed) {
242
- // Our own command, changed on the way to MQTT (the command path
243
- // should pass it through as it is): never answered as someone else's.
244
- trace("command-observed", "ignored", "mutated-own-command", { target: target.id, state: String(payload.state || "").toUpperCase() });
245
- }
246
- if (!echo.own) {
247
- const requestedState = String(payload.state || "").toUpperCase();
248
- if (requestedState === "OFF") {
249
- state.desired[target.id] = false;
250
- setControl(target.id, null, "external-off");
251
- }
252
- else if (requestedState === "ON") {
253
- state.desired[target.id] = true;
254
- if ((0, z2m_light_1.setsLightValues)(payload)) {
255
- setControl(target.id, { state: "manual" }, "external-values");
256
- }
257
- else if (state.circadianEnabled && controlOf(target.id) === "in-control") {
258
- // At most one restyle per light per echo window, whatever comes
259
- // back: a bare ON delivered twice (two subscriptions, or a QoS
260
- // redelivery) can't make the room answer itself in a loop.
261
- const last = state.restyledAt[target.id];
262
- if (last !== undefined && nowMs - last >= 0 && nowMs - last < command_echo_1.ECHO_WINDOW_MS) {
263
- trace("external-command", "suppressed", "restyled-recently", { target: target.id });
264
- }
265
- else {
266
- const corrective = command(target.id, adaptivePayload("ON", false, state.sleeping, now, active), "external-bare-on");
267
- if (corrective) {
268
- outputs.push(corrective);
269
- state.restyledAt[target.id] = nowMs;
270
- }
271
- }
272
- // Styled now, so the refresh keeps it in step from here.
273
- told(target.id);
274
- }
275
- }
276
- else if (requestedState === "TOGGLE") {
277
- state.desired[target.id] = !intendedOn(target.id);
278
- }
279
- state.personAt[target.id] = now.getTime();
280
- trace("external-command", "observed", null, {
281
- target: target.id,
282
- state: requestedState || "UNKNOWN",
283
- control: controlOf(target.id)
284
- });
285
- }
363
+ else if (reading?.kind === "echo-changed") {
364
+ // Our own command, changed on the way (the command path should pass it
365
+ // through as it is): never answered as someone else's. Its adapter knew.
366
+ trace("command-observed", "ignored", "mutated-own-command", { target: reading.target, state: String(reading.state || "").toUpperCase() });
367
+ }
368
+ else if (reading?.kind === "skipped") {
369
+ // A restyle its adapter didn't send: the light already shows it.
370
+ state.expected[reading.target] = (0, command_echo_1.commandSkipped)(state.expected[reading.target], String(reading.id), nowMs);
371
+ trace("refresh", "skipped", "already-at-level", { target: reading.target });
372
+ }
373
+ else if (reading?.kind === "sent") {
374
+ state.expected[reading.target] = (0, command_echo_1.commandSent)(state.expected[reading.target], String(reading.id), nowMs);
375
+ }
376
+ else if (reading?.kind === "availability") {
377
+ // Shown, never acted on.
378
+ if (state.available[reading.target] !== reading.online) {
379
+ state.available[reading.target] = reading.online === true;
380
+ availabilityChanged.add(reading.target);
381
+ trace("availability", reading.online ? "online" : "offline", null, { target: reading.target });
286
382
  }
287
383
  }
288
- else if (event.kind === "circadian") {
289
- const previous = state.circadianEnabled;
290
- state.circadianEnabled = event.enabled === true;
291
- if (previous !== state.circadianEnabled) {
292
- trace("circadian", "changed", null, { enabled: state.circadianEnabled });
384
+ else if (reading?.kind === "external") {
385
+ // Someone else's command, as its adapter told it from the room's own.
386
+ const target = targetById[reading.target];
387
+ const requestedState = String(reading.state || "").toUpperCase();
388
+ if (requestedState === "OFF") {
389
+ state.desired[target.id] = false;
390
+ setControl(target.id, null, "external-off");
293
391
  }
294
- if (state.circadianEnabled) {
295
- // Switching circadian lighting on takes the lights back, so the room
296
- // has been told about every light.
297
- for (const target of config.targets)
392
+ else if (requestedState === "ON") {
393
+ state.desired[target.id] = true;
394
+ if (reading.setsValues === true && !onOffOnly(target.id)) {
395
+ setControl(target.id, { state: "manual" }, "external-values");
396
+ }
397
+ else if (currentStyle() && !onOffOnly(target.id) && controlOf(target.id) === "in-control") {
398
+ // At most one restyle per light per echo window, whatever comes
399
+ // back: a bare ON delivered twice (two subscriptions, or a QoS
400
+ // redelivery) can't make the room answer itself in a loop.
401
+ const last = state.restyledAt[target.id];
402
+ if (last !== undefined && nowMs - last >= 0 && nowMs - last < command_echo_1.ECHO_WINDOW_MS) {
403
+ trace("external-command", "suppressed", "restyled-recently", { target: target.id });
404
+ }
405
+ else if (command(target.id, styled(target.id, config.initialTransitionSeconds), "external-bare-on")) {
406
+ state.restyledAt[target.id] = nowMs;
407
+ }
408
+ // Styled now, so a style keeps it in step from here.
298
409
  told(target.id);
299
- // Enabling circadian takes back manual lights; other owners keep theirs.
300
- for (const target of config.targets) {
301
- if (controlOf(target.id) === "manual")
302
- setControl(target.id, null, "circadian-enabled");
303
410
  }
304
- outputs.push(...refreshCommands("circadian-enabled"));
305
411
  }
412
+ else if (requestedState === "TOGGLE") {
413
+ state.desired[target.id] = !intendedOn(target.id);
414
+ }
415
+ state.personAt[target.id] = now.getTime();
416
+ trace("external-command", "observed", null, {
417
+ target: target.id,
418
+ state: requestedState || "UNKNOWN",
419
+ control: controlOf(target.id)
420
+ });
306
421
  }
307
- else if (event.kind === "sleep") {
308
- const previous = state.sleeping;
309
- state.sleeping = event.enabled === true;
310
- if (previous !== state.sleeping)
311
- trace("sleep", "changed", null, { enabled: state.sleeping });
312
- outputs.push(...refreshCommands("sleep-policy"));
422
+ else if (event.kind === "startup") {
423
+ // Each light is asked for a fresh reading, rather than waiting for a change.
424
+ for (const target of config.targets)
425
+ commands.push({ kind: "observe", target: target.id });
313
426
  }
314
- else if (event.kind === "schedule") {
315
- const next = (0, room_schedule_1.requestedSchedule)(state.schedule, event);
427
+ else if (event.kind === "circadian" || event.kind === "sleep" || event.kind === "schedule") {
428
+ // The circadian lighting policy's since 6.0: the node warns.
429
+ trace(event.kind, "ignored", exports.MOVED_TO_CIRCADIAN);
430
+ }
431
+ else if (event.kind === "style") {
432
+ const previous = state.style;
433
+ const next = savedStyle({ ...event, source: event.source });
316
434
  if (!next) {
317
- trace("schedule", "ignored", "invalid-times", { wakeTime: event.wakeTime, bedTime: event.bedTime });
435
+ trace("style", "ignored", "not-a-style");
318
436
  }
319
- else if (next.wakeTime !== state.schedule.wakeTime || next.bedTime !== state.schedule.bedTime) {
320
- state.schedule = next;
321
- active = (0, room_schedule_1.withActiveSchedule)(config, state);
322
- trace("schedule", "changed", null, { ...next });
323
- outputs.push(...refreshCommands("schedule-changed"));
437
+ else {
438
+ state.style = next;
439
+ // Traced when it starts or stops styling, or comes from someone else,
440
+ // not at every interval.
441
+ if (!previous || (previous.values === null) !== (next.values === null) || previous.source !== next.source) {
442
+ trace("style", "changed", null, { source: next.source, styling: next.values !== null });
443
+ }
444
+ if (event.takeBack === true) {
445
+ // The one time a style changes who controls a light: circadian
446
+ // lighting switched on takes back what a person set, and the room
447
+ // has then been told about every light. Other owners keep theirs.
448
+ for (const target of config.targets) {
449
+ told(target.id);
450
+ if (controlOf(target.id) === "manual")
451
+ setControl(target.id, null, "taken-back");
452
+ }
453
+ }
454
+ restyleLights(next.source);
324
455
  }
325
456
  }
326
- else if (event.kind === "refresh") {
327
- outputs.push(...refreshCommands("periodic-refresh"));
328
- }
329
457
  else if (event.kind === "release") {
330
458
  // Hand overridden lights back; an owner name releases only that owner's lights.
331
459
  const targets = Array.isArray(event.targets) ? event.targets : config.targets.map((target) => target.id);
@@ -336,49 +464,43 @@ function transitionRoom(saved, msg, config, nowValue = new Date()) {
336
464
  continue;
337
465
  setControl(targetId, null, "released");
338
466
  told(targetId);
339
- if (state.circadianEnabled && intendedOn(targetId)) {
340
- const restyle = command(targetId, adaptivePayload("ON", true, state.sleeping, now, active), event.source || "release");
341
- if (restyle)
342
- outputs.push(restyle);
343
- }
467
+ // Back in the room's style, over the style's own transition.
468
+ const style = intendedOn(targetId) && state.style ? styled(targetId, state.style.transitionSeconds) : null;
469
+ if (style)
470
+ command(targetId, style, event.source || "release");
344
471
  }
345
472
  }
346
473
  else if (event.kind === "intent") {
347
- outputs.push(...emitIntent(event));
348
- const commands = outputs.flatMap((message) => {
349
- if (!message.lighting_command)
350
- return [];
351
- const payload = message.payload && typeof message.payload === "object"
352
- ? message.payload
353
- : {};
354
- return [{
355
- target: message.lighting_command.target,
356
- state: String(payload.state || "").toUpperCase()
357
- }];
358
- });
359
- trace("intent", commands.length ? "commanded" : "suppressed", commands.length ? null : "no-command-required", {
474
+ const sent = emitIntent(event).map(({ target, state: power }) => ({ target, state: power }));
475
+ trace("intent", sent.length ? "commanded" : "suppressed", sent.length ? null : "no-command-required", {
360
476
  source: event.source || "intent",
361
477
  state: String(event.state || "").toUpperCase(),
362
478
  targets: Array.isArray(event.targets)
363
479
  ? event.targets
364
480
  : config.targets.map((target) => target.id),
365
- commands
481
+ commands: sent
366
482
  });
367
483
  }
368
484
  const onCount = Object.values(state.desired).filter(Boolean).length;
369
485
  const control = Object.fromEntries(config.targets.map((target) => [target.id, controlOf(target.id)]));
370
486
  const manualCount = Object.values(control).filter((entry) => entry === "manual").length;
371
487
  const overriddenCount = Object.values(control).filter((entry) => entry === "overridden").length;
488
+ const offlineCount = config.targets.filter((target) => state.available[target.id] === false).length;
372
489
  return {
373
490
  state,
374
491
  outputs,
492
+ // Light commands for the lights' adapters, in the order sent.
493
+ commands,
375
494
  traces,
376
- // The lights whose control state changed, in configured order.
377
- controlChanged: config.targets.map((target) => target.id).filter((id) => controlChanged.has(id)),
495
+ // The lights whose control state, or availability, changed, in
496
+ // configured order.
497
+ controlChanged: config.targets.map((target) => target.id).filter((id) => controlChanged.has(id) || availabilityChanged.has(id)),
378
498
  status: {
379
- circadianEnabled: state.circadianEnabled,
380
- sleeping: state.sleeping,
499
+ // Whether a style is in force, and whose it is.
500
+ styled: currentStyle() !== null,
501
+ styleSource: state.style?.source ?? null,
381
502
  onCount,
503
+ offlineCount,
382
504
  manualCount,
383
505
  overriddenCount,
384
506
  control