@avantics/node-red-home-automation 5.0.0 → 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 (80) hide show
  1. package/README.md +340 -70
  2. package/contract-examples/room-lighting.mjs +39 -27
  3. package/dist/lib/activity-lighting-controller.d.ts +7 -2
  4. package/dist/lib/activity-lighting-controller.js +75 -16
  5. package/dist/lib/avr-controller.d.ts +2 -2
  6. package/dist/lib/avr-controller.js +21 -26
  7. package/dist/lib/circadian-policy.d.ts +47 -0
  8. package/dist/lib/circadian-policy.js +111 -0
  9. package/dist/lib/circadian-publishing.d.ts +33 -0
  10. package/dist/lib/circadian-publishing.js +154 -0
  11. package/dist/lib/circadian-schedule.d.ts +4 -0
  12. package/dist/lib/circadian-schedule.js +12 -0
  13. package/dist/lib/command-echo.d.ts +8 -1
  14. package/dist/lib/command-echo.js +37 -6
  15. package/dist/lib/cover-controller.js +4 -0
  16. package/dist/lib/denon-protocol.js +3 -2
  17. package/dist/lib/enable-input.d.ts +3 -0
  18. package/dist/lib/enable-input.js +18 -0
  19. package/dist/lib/house-schedule.js +2 -2
  20. package/dist/lib/light-contract.d.ts +53 -0
  21. package/dist/lib/light-contract.js +11 -0
  22. package/dist/lib/motion-policy.d.ts +0 -1
  23. package/dist/lib/motion-policy.js +9 -8
  24. package/dist/lib/motion-publishing.js +2 -1
  25. package/dist/lib/mqtt-message.d.ts +6 -0
  26. package/dist/lib/mqtt-message.js +21 -0
  27. package/dist/lib/room-controller.d.ts +38 -27
  28. package/dist/lib/room-controller.js +310 -204
  29. package/dist/lib/room-lighting-discovery.d.ts +0 -14
  30. package/dist/lib/room-lighting-discovery.js +19 -125
  31. package/dist/lib/room-publishing.d.ts +7 -12
  32. package/dist/lib/room-publishing.js +65 -125
  33. package/dist/lib/shelly-cover.d.ts +2 -4
  34. package/dist/lib/shelly-cover.js +30 -70
  35. package/dist/lib/shelly-gen2.d.ts +25 -0
  36. package/dist/lib/shelly-gen2.js +58 -0
  37. package/dist/lib/shelly-switch.d.ts +95 -0
  38. package/dist/lib/shelly-switch.js +237 -0
  39. package/dist/lib/theatre-state-contract.js +12 -4
  40. package/dist/lib/z2m-cover.d.ts +49 -0
  41. package/dist/lib/z2m-cover.js +120 -0
  42. package/dist/lib/z2m-light-adapter.d.ts +62 -0
  43. package/dist/lib/z2m-light-adapter.js +195 -0
  44. package/dist/lib/z2m-light.d.ts +2 -2
  45. package/dist/lib/z2m-light.js +11 -14
  46. package/dist/nodes/activity-lighting-controller.html +14 -5
  47. package/dist/nodes/activity-lighting-controller.js +21 -0
  48. package/dist/nodes/avr-controller.html +15 -18
  49. package/dist/nodes/avr-controller.js +4 -4
  50. package/dist/nodes/circadian-policy.d.ts +3 -0
  51. package/dist/nodes/circadian-policy.html +140 -0
  52. package/dist/nodes/circadian-policy.js +162 -0
  53. package/dist/nodes/cover-controller.html +4 -3
  54. package/dist/nodes/display-mode-controller.html +14 -17
  55. package/dist/nodes/display-mode-controller.js +4 -1
  56. package/dist/nodes/house-schedule.html +3 -3
  57. package/dist/nodes/motion-policy.html +5 -2
  58. package/dist/nodes/motion-policy.js +3 -0
  59. package/dist/nodes/refused-enable.d.ts +7 -0
  60. package/dist/nodes/refused-enable.js +24 -0
  61. package/dist/nodes/room-controller.html +215 -82
  62. package/dist/nodes/room-controller.js +70 -96
  63. package/dist/nodes/shelly-switch.d.ts +3 -0
  64. package/dist/nodes/shelly-switch.html +82 -0
  65. package/dist/nodes/shelly-switch.js +48 -0
  66. package/dist/nodes/theatre-state-contract.html +4 -3
  67. package/dist/nodes/z2m-cover.d.ts +3 -0
  68. package/dist/nodes/z2m-cover.html +68 -0
  69. package/dist/nodes/z2m-cover.js +41 -0
  70. package/dist/nodes/z2m-light.d.ts +3 -0
  71. package/dist/nodes/z2m-light.html +72 -0
  72. package/dist/nodes/z2m-light.js +50 -0
  73. package/examples/Cover control.json +24 -56
  74. package/examples/Home theatre activity.json +49 -4
  75. package/examples/House schedule.json +106 -24
  76. package/examples/Room lighting.json +54 -11
  77. package/examples/Shelly switch.json +197 -0
  78. package/package.json +12 -4
  79. package/dist/lib/room-schedule.d.ts +0 -8
  80. package/dist/lib/room-schedule.js +0 -41
@@ -1,23 +1,61 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.INVALID_LIGHT_VALUES = exports.LEGACY_LIGHT_UNITS = 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; } });
13
- // Traced when an intent gives brightness or color_temp in Zigbee2MQTT's own
14
- // units rather than brightnessPct or colorTempKelvin: still accepted during
15
- // 5.x, and the node warns.
16
- exports.LEGACY_LIGHT_UNITS = "legacy-light-units";
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";
17
18
  // Traced when an intent's brightnessPct or colorTempKelvin is unusable (not
18
19
  // a number, or a kelvin of 0 or less): it is left out of the command, and
19
20
  // the node warns.
20
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";
21
59
  function savedControl(saved) {
22
60
  if (saved.control) {
23
61
  return Object.fromEntries(Object.entries(saved.control).map(([target, entry]) => [target, { ...entry }]));
@@ -33,23 +71,72 @@ function createRoomState(config, saved = {}) {
33
71
  desired: { ...(saved.desired || {}) },
34
72
  control: savedControl(saved),
35
73
  expected: Object.fromEntries(Object.entries(saved.expected || {}).map(([target, entries]) => [target, entries.map((entry) => ({ ...entry }))])),
36
- circadianEnabled: saved.circadianEnabled !== false,
37
- sleeping: saved.sleeping === undefined ? config.initialSleep : saved.sleeping === true,
38
- ...(0, room_schedule_1.savedSchedule)(config, saved),
74
+ style: savedStyle(saved.style),
39
75
  personAt: Object.fromEntries(Object.entries(saved.personAt || {})
40
76
  .filter(([, at]) => Number.isFinite(at))),
41
77
  untold: Array.isArray(saved.untold)
42
78
  ? saved.untold.filter((id) => config.targets.some((target) => target.id === id))
43
79
  : [],
44
80
  restyledAt: Object.fromEntries(Object.entries(saved.restyledAt || {})
45
- .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
46
84
  };
47
85
  }
48
- // A circadian light command for this moment.
49
- function adaptivePayload(lightState, isRefresh, sleeping, now, config) {
50
- if (lightState === "OFF")
51
- return { state: lightState };
52
- 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
+ };
53
140
  }
54
141
  function transitionRoom(saved, msg, config, nowValue = new Date()) {
55
142
  const now = nowValue instanceof Date ? nowValue : new Date(nowValue);
@@ -57,19 +144,17 @@ function transitionRoom(saved, msg, config, nowValue = new Date()) {
57
144
  const state = createRoomState(config, saved);
58
145
  if (saved === undefined)
59
146
  state.untold = config.targets.map((target) => target.id);
60
- // The settings with lighting on the times in use; a schedule change
61
- // below replaces it.
62
- let active = (0, room_schedule_1.withActiveSchedule)(config, state);
63
147
  const targetById = Object.fromEntries(config.targets.map((target) => [target.id, target]));
64
148
  const traces = [];
65
149
  const outputs = [];
150
+ // Light commands (and requests for readings), for the lights' adapters.
151
+ const commands = [];
66
152
  function trace(event, outcome, reason = null, details = {}) {
67
153
  traces.push({ event, outcome, reason, details });
68
154
  }
69
- function targetForTopic(topic, field) {
70
- return config.targets.find((target) => target[field] === topic);
71
- }
72
155
  const controlChanged = new Set();
156
+ // Lights whose availability changed, for their control state publications.
157
+ const availabilityChanged = new Set();
73
158
  function controlOf(targetId) {
74
159
  return state.control[targetId]?.state ?? "in-control";
75
160
  }
@@ -97,37 +182,55 @@ function transitionRoom(saved, msg, config, nowValue = new Date()) {
97
182
  return state.desired[targetId] === true;
98
183
  return state.observed[targetId]?.on === true;
99
184
  }
100
- function command(targetId, payload, source) {
101
- const target = targetById[targetId];
102
- 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])
103
189
  return null;
104
- state.expected[targetId] = (0, command_echo_1.rememberCommand)(state.expected[targetId], payload, nowMs);
105
- return {
106
- topic: target.commandTopic,
107
- payload,
108
- retain: false,
109
- lighting_command: { area: config.area, target: targetId, source }
110
- };
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;
111
196
  }
112
- function refreshCommands(source) {
113
- if (!state.circadianEnabled)
114
- return [];
115
- 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;
116
222
  for (const target of config.targets) {
117
223
  if (!intendedOn(target.id) || controlOf(target.id) !== "in-control")
118
224
  continue;
225
+ if (onOffOnly(target.id))
226
+ continue;
119
227
  if (state.untold.includes(target.id)) {
120
228
  trace("refresh", "skipped", "not-told-since-start", { target: target.id });
121
229
  continue;
122
230
  }
123
- // Nothing to change when the light last reported exactly this style.
124
- if ((0, z2m_light_1.alreadyStyled)(active.lighting.styleAt(now, state.sleeping), state.observed[target.id])) {
125
- trace("refresh", "skipped", "already-at-level", { target: target.id });
126
- continue;
127
- }
128
- 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);
129
233
  }
130
- return commands.filter((entry) => entry !== null);
131
234
  }
132
235
  function emitIntent(event) {
133
236
  const targets = Array.isArray(event.targets)
@@ -136,7 +239,7 @@ function transitionRoom(saved, msg, config, nowValue = new Date()) {
136
239
  const requestedState = String(event.state || "").toUpperCase();
137
240
  if (!["ON", "OFF", "TOGGLE"].includes(requestedState))
138
241
  return [];
139
- const commands = [];
242
+ const sent = [];
140
243
  const manualValues = event.values && typeof event.values === "object" ? event.values : null;
141
244
  const owner = typeof event.owner === "string" && event.owner ? event.owner : null;
142
245
  for (const targetId of targets) {
@@ -176,172 +279,181 @@ function transitionRoom(saved, msg, config, nowValue = new Date()) {
176
279
  else if (owner) {
177
280
  setControl(targetId, { state: "overridden", owner }, "owner-intent");
178
281
  }
179
- 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.
180
285
  setControl(targetId, { state: "manual" }, "manual-intent");
181
286
  }
182
- let payload;
287
+ let spec;
183
288
  if (resolvedState === "OFF") {
184
- payload = { state: "OFF" };
289
+ spec = { state: "OFF" };
185
290
  }
186
- else if (manualValues) {
187
- // The intent's values in the light's own units (z2m-light).
188
- const device = (0, z2m_light_1.lightValues)(manualValues);
189
- if (device.legacy)
190
- trace("intent", "accepted", exports.LEGACY_LIGHT_UNITS, { target: targetId, values: manualValues });
191
- if (device.superseded.length)
192
- trace("intent", "accepted", "legacy-light-units-ignored", { target: targetId, ignored: device.superseded });
193
- if (device.invalid.length)
194
- trace("intent", "accepted", exports.INVALID_LIGHT_VALUES, { target: targetId, dropped: device.invalid, values: manualValues });
195
- payload = { state: "ON", ...device.values };
196
- if (!Object.hasOwn(payload, "transition")) {
197
- payload.transition = config.initialTransitionSeconds;
198
- }
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" };
199
296
  }
200
- else if (state.circadianEnabled && controlOf(targetId) === "in-control") {
201
- 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
+ };
202
311
  }
203
312
  else {
204
- 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" };
205
316
  }
206
317
  state.desired[targetId] = resolvedState === "ON";
207
318
  told(targetId);
208
- commands.push(command(targetId, payload, event.source || "intent"));
319
+ sent.push(command(targetId, spec, event.source || "intent"));
209
320
  }
210
- return commands.filter((entry) => entry !== null);
321
+ return sent.filter((entry) => entry !== null);
211
322
  }
212
323
  // What the room publishes, and the MQTT it reads for itself, are
213
324
  // room-publishing.ts's; this decides about lights only.
214
325
  const event = msg.lighting || {};
215
- if (event.kind === "observed") {
216
- const target = event.target ? targetById[event.target] : targetForTopic(msg.topic, "stateTopic");
217
- const parsed = (0, command_echo_1.parsePayload)(msg.payload);
218
- const payload = parsed && typeof parsed === "object" ? parsed : null;
219
- const light = payload ? (0, z2m_light_1.readLightReport)(payload) : null;
220
- if (target && light) {
221
- const previousOn = state.observed[target.id]?.on;
222
- const nextOn = light.on;
223
- state.observed[target.id] = { ...light, observedAt: now.toISOString() };
224
- if (previousOn !== nextOn) {
225
- trace("state-observed", "changed", null, {
226
- target: target.id,
227
- state: nextOn ? "ON" : "OFF"
228
- });
229
- }
230
- const report = (0, command_echo_1.checkStateReport)(state.expected[target.id], nextOn, nowMs);
231
- state.expected[target.id] = report.queue;
232
- if (report.verdict === "confirms") {
233
- // Our own command, now done: the intended state already says so.
234
- // A confirmed OFF deliberately leaves control alone: our OFFs come
235
- // from OFF intents, which already returned the light to in-control.
236
- trace("state-observed", "confirmed", "own-command", { target: target.id, state: nextOn ? "ON" : "OFF" });
237
- }
238
- else if (report.verdict === "stale") {
239
- // Older than our pending command; the light will report again.
240
- trace("state-observed", "ignored", "stale-report", { target: target.id, state: nextOn ? "ON" : "OFF" });
241
- }
242
- else {
243
- // A change the controller didn't cause becomes the intended state.
244
- state.desired[target.id] = nextOn;
245
- if (!nextOn)
246
- setControl(target.id, null, "observed-off");
247
- }
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");
248
361
  }
249
362
  }
250
- else if (event.kind === "command-observed") {
251
- const target = event.target ? targetById[event.target] : targetForTopic(msg.topic, "commandTopic");
252
- const parsed = (0, command_echo_1.parsePayload)(msg.payload);
253
- const payload = parsed && typeof parsed === "object" ? parsed : null;
254
- if (msg.retain !== true && event.retained !== true && target && payload) {
255
- const echo = (0, command_echo_1.checkCommandEcho)(state.expected[target.id], payload, nowMs);
256
- state.expected[target.id] = echo.queue;
257
- if (echo.changed) {
258
- // Our own command, changed on the way to MQTT (the command path
259
- // should pass it through as it is): never answered as someone else's.
260
- trace("command-observed", "ignored", "mutated-own-command", { target: target.id, state: String(payload.state || "").toUpperCase() });
261
- }
262
- if (!echo.own) {
263
- const requestedState = String(payload.state || "").toUpperCase();
264
- if (requestedState === "OFF") {
265
- state.desired[target.id] = false;
266
- setControl(target.id, null, "external-off");
267
- }
268
- else if (requestedState === "ON") {
269
- state.desired[target.id] = true;
270
- if ((0, z2m_light_1.setsLightValues)(payload)) {
271
- setControl(target.id, { state: "manual" }, "external-values");
272
- }
273
- else if (state.circadianEnabled && controlOf(target.id) === "in-control") {
274
- // At most one restyle per light per echo window, whatever comes
275
- // back: a bare ON delivered twice (two subscriptions, or a QoS
276
- // redelivery) can't make the room answer itself in a loop.
277
- const last = state.restyledAt[target.id];
278
- if (last !== undefined && nowMs - last >= 0 && nowMs - last < command_echo_1.ECHO_WINDOW_MS) {
279
- trace("external-command", "suppressed", "restyled-recently", { target: target.id });
280
- }
281
- else {
282
- const corrective = command(target.id, adaptivePayload("ON", false, state.sleeping, now, active), "external-bare-on");
283
- if (corrective) {
284
- outputs.push(corrective);
285
- state.restyledAt[target.id] = nowMs;
286
- }
287
- }
288
- // Styled now, so the refresh keeps it in step from here.
289
- told(target.id);
290
- }
291
- }
292
- else if (requestedState === "TOGGLE") {
293
- state.desired[target.id] = !intendedOn(target.id);
294
- }
295
- state.personAt[target.id] = now.getTime();
296
- trace("external-command", "observed", null, {
297
- target: target.id,
298
- state: requestedState || "UNKNOWN",
299
- control: controlOf(target.id)
300
- });
301
- }
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 });
302
382
  }
303
383
  }
304
- else if (event.kind === "circadian") {
305
- const previous = state.circadianEnabled;
306
- state.circadianEnabled = event.enabled === true;
307
- if (previous !== state.circadianEnabled) {
308
- 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");
309
391
  }
310
- if (state.circadianEnabled) {
311
- // Switching circadian lighting on takes the lights back, so the room
312
- // has been told about every light.
313
- 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.
314
409
  told(target.id);
315
- // Enabling circadian takes back manual lights; other owners keep theirs.
316
- for (const target of config.targets) {
317
- if (controlOf(target.id) === "manual")
318
- setControl(target.id, null, "circadian-enabled");
319
410
  }
320
- outputs.push(...refreshCommands("circadian-enabled"));
321
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
+ });
322
421
  }
323
- else if (event.kind === "sleep") {
324
- const previous = state.sleeping;
325
- state.sleeping = event.enabled === true;
326
- if (previous !== state.sleeping)
327
- trace("sleep", "changed", null, { enabled: state.sleeping });
328
- 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 });
329
426
  }
330
- else if (event.kind === "schedule") {
331
- 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 });
332
434
  if (!next) {
333
- trace("schedule", "ignored", "invalid-times", { wakeTime: event.wakeTime, bedTime: event.bedTime });
435
+ trace("style", "ignored", "not-a-style");
334
436
  }
335
- else if (next.wakeTime !== state.schedule.wakeTime || next.bedTime !== state.schedule.bedTime) {
336
- state.schedule = next;
337
- active = (0, room_schedule_1.withActiveSchedule)(config, state);
338
- trace("schedule", "changed", null, { ...next });
339
- 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);
340
455
  }
341
456
  }
342
- else if (event.kind === "refresh") {
343
- outputs.push(...refreshCommands("periodic-refresh"));
344
- }
345
457
  else if (event.kind === "release") {
346
458
  // Hand overridden lights back; an owner name releases only that owner's lights.
347
459
  const targets = Array.isArray(event.targets) ? event.targets : config.targets.map((target) => target.id);
@@ -352,49 +464,43 @@ function transitionRoom(saved, msg, config, nowValue = new Date()) {
352
464
  continue;
353
465
  setControl(targetId, null, "released");
354
466
  told(targetId);
355
- if (state.circadianEnabled && intendedOn(targetId)) {
356
- const restyle = command(targetId, adaptivePayload("ON", true, state.sleeping, now, active), event.source || "release");
357
- if (restyle)
358
- outputs.push(restyle);
359
- }
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");
360
471
  }
361
472
  }
362
473
  else if (event.kind === "intent") {
363
- outputs.push(...emitIntent(event));
364
- const commands = outputs.flatMap((message) => {
365
- if (!message.lighting_command)
366
- return [];
367
- const payload = message.payload && typeof message.payload === "object"
368
- ? message.payload
369
- : {};
370
- return [{
371
- target: message.lighting_command.target,
372
- state: String(payload.state || "").toUpperCase()
373
- }];
374
- });
375
- 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", {
376
476
  source: event.source || "intent",
377
477
  state: String(event.state || "").toUpperCase(),
378
478
  targets: Array.isArray(event.targets)
379
479
  ? event.targets
380
480
  : config.targets.map((target) => target.id),
381
- commands
481
+ commands: sent
382
482
  });
383
483
  }
384
484
  const onCount = Object.values(state.desired).filter(Boolean).length;
385
485
  const control = Object.fromEntries(config.targets.map((target) => [target.id, controlOf(target.id)]));
386
486
  const manualCount = Object.values(control).filter((entry) => entry === "manual").length;
387
487
  const overriddenCount = Object.values(control).filter((entry) => entry === "overridden").length;
488
+ const offlineCount = config.targets.filter((target) => state.available[target.id] === false).length;
388
489
  return {
389
490
  state,
390
491
  outputs,
492
+ // Light commands for the lights' adapters, in the order sent.
493
+ commands,
391
494
  traces,
392
- // The lights whose control state changed, in configured order.
393
- 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)),
394
498
  status: {
395
- circadianEnabled: state.circadianEnabled,
396
- sleeping: state.sleeping,
499
+ // Whether a style is in force, and whose it is.
500
+ styled: currentStyle() !== null,
501
+ styleSource: state.style?.source ?? null,
397
502
  onCount,
503
+ offlineCount,
398
504
  manualCount,
399
505
  overriddenCount,
400
506
  control