@avantics/node-red-home-automation 5.0.0 → 6.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/README.md +413 -77
  2. package/contract-examples/room-lighting.mjs +39 -27
  3. package/dist/lib/activity-lighting-controller.d.ts +7 -2
  4. package/dist/lib/activity-lighting-controller.js +75 -16
  5. package/dist/lib/avr-controller.d.ts +2 -2
  6. package/dist/lib/avr-controller.js +21 -26
  7. package/dist/lib/circadian-policy.d.ts +47 -0
  8. package/dist/lib/circadian-policy.js +111 -0
  9. package/dist/lib/circadian-publishing.d.ts +33 -0
  10. package/dist/lib/circadian-publishing.js +154 -0
  11. package/dist/lib/circadian-schedule.d.ts +4 -0
  12. package/dist/lib/circadian-schedule.js +12 -0
  13. package/dist/lib/command-echo.d.ts +8 -1
  14. package/dist/lib/command-echo.js +37 -6
  15. package/dist/lib/cover-controller.js +4 -0
  16. package/dist/lib/denon-protocol.js +3 -2
  17. package/dist/lib/enable-input.d.ts +3 -0
  18. package/dist/lib/enable-input.js +18 -0
  19. package/dist/lib/house-schedule.js +2 -2
  20. package/dist/lib/light-contract.d.ts +53 -0
  21. package/dist/lib/light-contract.js +11 -0
  22. package/dist/lib/motion-policy.d.ts +0 -1
  23. package/dist/lib/motion-policy.js +9 -8
  24. package/dist/lib/motion-publishing.js +2 -1
  25. package/dist/lib/mqtt-message.d.ts +6 -0
  26. package/dist/lib/mqtt-message.js +21 -0
  27. package/dist/lib/room-controller.d.ts +41 -27
  28. package/dist/lib/room-controller.js +422 -213
  29. package/dist/lib/room-holds.d.ts +34 -0
  30. package/dist/lib/room-holds.js +66 -0
  31. package/dist/lib/room-lighting-discovery.d.ts +0 -14
  32. package/dist/lib/room-lighting-discovery.js +19 -125
  33. package/dist/lib/room-publishing.d.ts +7 -12
  34. package/dist/lib/room-publishing.js +65 -125
  35. package/dist/lib/shelly-cover.d.ts +2 -4
  36. package/dist/lib/shelly-cover.js +30 -70
  37. package/dist/lib/shelly-gen2.d.ts +25 -0
  38. package/dist/lib/shelly-gen2.js +58 -0
  39. package/dist/lib/shelly-switch.d.ts +95 -0
  40. package/dist/lib/shelly-switch.js +237 -0
  41. package/dist/lib/theatre-state-contract.js +12 -4
  42. package/dist/lib/z2m-cover.d.ts +49 -0
  43. package/dist/lib/z2m-cover.js +120 -0
  44. package/dist/lib/z2m-light-adapter.d.ts +62 -0
  45. package/dist/lib/z2m-light-adapter.js +195 -0
  46. package/dist/lib/z2m-light.d.ts +2 -2
  47. package/dist/lib/z2m-light.js +11 -14
  48. package/dist/nodes/activity-lighting-controller.html +15 -6
  49. package/dist/nodes/activity-lighting-controller.js +21 -0
  50. package/dist/nodes/adapter.d.ts +5 -1
  51. package/dist/nodes/adapter.js +35 -2
  52. package/dist/nodes/avr-controller.html +20 -18
  53. package/dist/nodes/avr-controller.js +5 -5
  54. package/dist/nodes/circadian-policy.d.ts +3 -0
  55. package/dist/nodes/circadian-policy.html +145 -0
  56. package/dist/nodes/circadian-policy.js +162 -0
  57. package/dist/nodes/cover-controller.html +9 -3
  58. package/dist/nodes/cover-controller.js +1 -1
  59. package/dist/nodes/display-mode-controller.html +14 -17
  60. package/dist/nodes/display-mode-controller.js +4 -1
  61. package/dist/nodes/house-schedule-mqtt.html +5 -0
  62. package/dist/nodes/house-schedule-mqtt.js +1 -1
  63. package/dist/nodes/house-schedule.html +3 -3
  64. package/dist/nodes/motion-policy.html +10 -2
  65. package/dist/nodes/motion-policy.js +4 -1
  66. package/dist/nodes/occupancy-fusion.html +5 -0
  67. package/dist/nodes/occupancy-fusion.js +1 -1
  68. package/dist/nodes/refused-enable.d.ts +7 -0
  69. package/dist/nodes/refused-enable.js +24 -0
  70. package/dist/nodes/room-controller.html +232 -85
  71. package/dist/nodes/room-controller.js +71 -97
  72. package/dist/nodes/shelly-switch.d.ts +3 -0
  73. package/dist/nodes/shelly-switch.html +87 -0
  74. package/dist/nodes/shelly-switch.js +48 -0
  75. package/dist/nodes/theatre-state-contract.html +9 -3
  76. package/dist/nodes/theatre-state-contract.js +1 -1
  77. package/dist/nodes/z2m-cover.d.ts +3 -0
  78. package/dist/nodes/z2m-cover.html +68 -0
  79. package/dist/nodes/z2m-cover.js +41 -0
  80. package/dist/nodes/z2m-light.d.ts +3 -0
  81. package/dist/nodes/z2m-light.html +76 -0
  82. package/dist/nodes/z2m-light.js +51 -0
  83. package/examples/Cover control.json +28 -71
  84. package/examples/Home theatre activity.json +53 -19
  85. package/examples/House schedule.json +106 -24
  86. package/examples/Room lighting.json +57 -25
  87. package/examples/Shelly cover.json +5 -16
  88. package/examples/Shelly switch.json +197 -0
  89. package/package.json +12 -4
  90. package/dist/lib/room-schedule.d.ts +0 -8
  91. package/dist/lib/room-schedule.js +0 -41
@@ -1,23 +1,62 @@
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");
11
+ const room_holds_1 = require("./room-holds");
9
12
  const command_echo_1 = require("./command-echo");
10
13
  var command_echo_2 = require("./command-echo");
11
14
  Object.defineProperty(exports, "fingerprint", { enumerable: true, get: function () { return command_echo_2.fingerprint; } });
12
15
  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";
16
+ // Traced when an intent gives brightness or color_temp, Zigbee2MQTT's own
17
+ // units, removed in 6.0: left out of the command, and the node warns.
18
+ exports.REMOVED_LIGHT_UNITS = "removed-light-units";
17
19
  // Traced when an intent's brightnessPct or colorTempKelvin is unusable (not
18
20
  // a number, or a kelvin of 0 or less): it is left out of the command, and
19
21
  // the node warns.
20
22
  exports.INVALID_LIGHT_VALUES = "invalid-light-values";
23
+ // Traced when an intent gives values for a light that only switches on and
24
+ // off: they are left out, and the node warns.
25
+ exports.ON_OFF_ONLY = "on-off-only";
26
+ // The settings a room had for circadian lighting before 6.0, now the
27
+ // circadian lighting policy's. A room whose saved settings still have any of
28
+ // them hasn't been migrated: it is an invalid configuration, so it can't
29
+ // quietly run unstyled. Empty, as a new 6.0 room has them, means absent.
30
+ exports.MOVED_CIRCADIAN_SETTINGS = [
31
+ "houseSchedule", "wakeTime", "bedTime", "maxBrightnessPct", "maxColorTempKelvin", "sleepBrightnessPct",
32
+ "sleepColorTempKelvin", "refreshTransitionSeconds", "refreshSeconds", "initialSleep",
33
+ // A room saved by 2.x and never re-saved has only these, ignored since 3.0.
34
+ "latitude", "longitude", "minBrightnessPct", "minColorTempKelvin"
35
+ ];
36
+ function movedCircadianSettings(config) {
37
+ return exports.MOVED_CIRCADIAN_SETTINGS.filter((key) => config[key] !== undefined && config[key] !== null && config[key] !== "");
38
+ }
39
+ // The targets of a room saved before 6.0, which named each light's
40
+ // Zigbee2MQTT topics (stateTopic, commandTopic): they move to a light
41
+ // adapter each, so such a room hasn't been migrated either. Their ids.
42
+ function targetsWithTopics(targets) {
43
+ let parsed = targets;
44
+ if (typeof targets === "string") {
45
+ try {
46
+ parsed = JSON.parse(targets);
47
+ }
48
+ catch {
49
+ return [];
50
+ }
51
+ }
52
+ return Array.isArray(parsed)
53
+ ? parsed.filter((target) => target && typeof target === "object" && ("stateTopic" in target || "commandTopic" in target))
54
+ .map((target) => String(target.id))
55
+ : [];
56
+ }
57
+ // Traced when the room is sent circadian, sleep or schedule messages, which
58
+ // the circadian lighting policy takes since 6.0: ignored, and the node warns.
59
+ exports.MOVED_TO_CIRCADIAN = "moved-to-circadian";
21
60
  function savedControl(saved) {
22
61
  if (saved.control) {
23
62
  return Object.fromEntries(Object.entries(saved.control).map(([target, entry]) => [target, { ...entry }]));
@@ -28,28 +67,79 @@ function savedControl(saved) {
28
67
  .map(([target]) => [target, { state: "manual" }]));
29
68
  }
30
69
  function createRoomState(config, saved = {}) {
70
+ const control = savedControl(saved);
31
71
  return {
32
72
  observed: { ...(saved.observed || {}) },
33
73
  desired: { ...(saved.desired || {}) },
34
- control: savedControl(saved),
74
+ control,
75
+ holds: (0, room_holds_1.savedHolds)(saved.holds, (target) => control[target]?.state === "overridden"),
35
76
  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),
77
+ style: savedStyle(saved.style),
39
78
  personAt: Object.fromEntries(Object.entries(saved.personAt || {})
40
79
  .filter(([, at]) => Number.isFinite(at))),
41
80
  untold: Array.isArray(saved.untold)
42
81
  ? saved.untold.filter((id) => config.targets.some((target) => target.id === id))
43
82
  : [],
44
83
  restyledAt: Object.fromEntries(Object.entries(saved.restyledAt || {})
45
- .filter(([target, at]) => Number.isFinite(at) && config.targets.some((entry) => entry.id === target)))
84
+ .filter(([target, at]) => Number.isFinite(at) && config.targets.some((entry) => entry.id === target))),
85
+ available: Object.fromEntries(Object.entries(saved.available || {}).filter(([, online]) => typeof online === "boolean")),
86
+ commandSeq: Number.isInteger(saved.commandSeq) ? saved.commandSeq : 0
46
87
  };
47
88
  }
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);
89
+ // A brightness percent or kelvin as a number: a number, or a finite numeric
90
+ // string; null otherwise.
91
+ function numberValue(value) {
92
+ const number = typeof value === "number" ? value : typeof value === "string" && value.trim() !== "" ? Number(value) : NaN;
93
+ return Number.isFinite(number) ? number : null;
94
+ }
95
+ // An intent's values for a light: brightnessPct and colorTempKelvin as
96
+ // numbers, anything else (an effect, say) passed on as it is, in its order.
97
+ // brightness and color_temp, Zigbee2MQTT's own units removed in 6.0, are
98
+ // `removed`; an unusable brightnessPct or colorTempKelvin is `invalid`.
99
+ // Neither reaches the light.
100
+ function intentValues(values) {
101
+ const extra = {};
102
+ const removed = [];
103
+ const invalid = [];
104
+ let brightnessPct;
105
+ let colorTempKelvin;
106
+ for (const [key, value] of Object.entries(values)) {
107
+ if (key === "brightnessPct" || key === "colorTempKelvin") {
108
+ const number = numberValue(value);
109
+ if (number === null || (key === "colorTempKelvin" && number <= 0))
110
+ invalid.push(key);
111
+ else if (key === "brightnessPct")
112
+ brightnessPct = number;
113
+ else
114
+ colorTempKelvin = number;
115
+ }
116
+ else if (z2m_light_1.REMOVED_LIGHT_FIELDS.includes(key)) {
117
+ removed.push(key);
118
+ }
119
+ else {
120
+ extra[key] = value;
121
+ }
122
+ }
123
+ return { brightnessPct, colorTempKelvin, extra, removed, invalid };
124
+ }
125
+ // A style as received or saved, or null if it isn't one. State saved before
126
+ // 6.0 has none.
127
+ function savedStyle(style) {
128
+ if (!style || typeof style !== "object")
129
+ return null;
130
+ const entry = style;
131
+ const values = entry.values && typeof entry.values === "object" &&
132
+ Number.isFinite(entry.values.brightnessPct) && Number.isFinite(entry.values.colorTempKelvin) && entry.values.colorTempKelvin > 0
133
+ ? { brightnessPct: entry.values.brightnessPct, colorTempKelvin: entry.values.colorTempKelvin }
134
+ : null;
135
+ if (typeof entry.until !== "string" || !Number.isFinite(Date.parse(entry.until)))
136
+ return null;
137
+ return {
138
+ values,
139
+ transitionSeconds: Number.isFinite(entry.transitionSeconds) ? Number(entry.transitionSeconds) : 0,
140
+ until: entry.until,
141
+ source: typeof entry.source === "string" && entry.source ? entry.source : "style"
142
+ };
53
143
  }
54
144
  function transitionRoom(saved, msg, config, nowValue = new Date()) {
55
145
  const now = nowValue instanceof Date ? nowValue : new Date(nowValue);
@@ -57,23 +147,24 @@ function transitionRoom(saved, msg, config, nowValue = new Date()) {
57
147
  const state = createRoomState(config, saved);
58
148
  if (saved === undefined)
59
149
  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
150
  const targetById = Object.fromEntries(config.targets.map((target) => [target.id, target]));
64
151
  const traces = [];
65
152
  const outputs = [];
153
+ // Light commands (and requests for readings), for the lights' adapters.
154
+ const commands = [];
66
155
  function trace(event, outcome, reason = null, details = {}) {
67
156
  traces.push({ event, outcome, reason, details });
68
157
  }
69
- function targetForTopic(topic, field) {
70
- return config.targets.find((target) => target[field] === topic);
71
- }
72
158
  const controlChanged = new Set();
159
+ // Lights whose availability changed, for their control state publications.
160
+ const availabilityChanged = new Set();
73
161
  function controlOf(targetId) {
74
162
  return state.control[targetId]?.state ?? "in-control";
75
163
  }
76
164
  function setControl(targetId, next, reason) {
165
+ // A light no owner holds has no owners to remember.
166
+ if (next?.state !== "overridden")
167
+ delete state.holds[targetId];
77
168
  const previous = state.control[targetId] ?? null;
78
169
  if (JSON.stringify(previous) === JSON.stringify(next))
79
170
  return;
@@ -89,6 +180,72 @@ function transitionRoom(saved, msg, config, nowValue = new Date()) {
89
180
  previous: previous?.state ?? "in-control"
90
181
  });
91
182
  }
183
+ // An overridden light's owners. A light held under state saved before 6.1
184
+ // has its one owner, with nothing known of what it was before.
185
+ function holdOf(targetId) {
186
+ const entry = state.control[targetId];
187
+ state.holds[targetId] ??= entry?.state === "overridden" ? (0, room_holds_1.legacyHold)(entry.owner) : { owners: [], before: null };
188
+ return state.holds[targetId];
189
+ }
190
+ // Whether the owner on top holds the light off.
191
+ function heldOff(targetId) {
192
+ return controlOf(targetId) === "overridden" && (0, room_holds_1.heldOff)(state.holds[targetId]);
193
+ }
194
+ // An owner taking a light, or asking again. The first owner records what
195
+ // the light was; a newer one goes on top. True when the owner is beneath
196
+ // a newer one: its request is remembered for when the newer lets go, and
197
+ // the light is left as it is.
198
+ function takeHold(targetId, owner, wasOn) {
199
+ const entry = state.control[targetId];
200
+ if (entry?.state !== "overridden") {
201
+ const observed = state.observed[targetId];
202
+ state.holds[targetId] = (0, room_holds_1.newHold)(owner, {
203
+ control: entry?.state === "manual" ? "manual" : "in-control",
204
+ on: wasOn,
205
+ ...(typeof observed?.brightnessPct === "number" ? { brightnessPct: observed.brightnessPct } : {}),
206
+ ...(typeof observed?.colorTempKelvin === "number" ? { colorTempKelvin: observed.colorTempKelvin } : {})
207
+ });
208
+ setControl(targetId, { state: "overridden", owner }, "owner-intent");
209
+ return false;
210
+ }
211
+ const added = (0, room_holds_1.addOwner)(holdOf(targetId), owner);
212
+ if (added === "pushed")
213
+ setControl(targetId, { state: "overridden", owner }, "owner-intent");
214
+ return added === "beneath";
215
+ }
216
+ // The last owner let go: the light goes back to what it was. One the room
217
+ // was running is the room's again, on or off as it was, in the style in
218
+ // force; one that was a person's gets their values back and stays theirs.
219
+ function restoreHeld(targetId, before, source) {
220
+ setControl(targetId, before?.control === "manual" ? { state: "manual" } : null, "released");
221
+ told(targetId);
222
+ const on = intendedOn(targetId);
223
+ if (before && !before.on) {
224
+ if (!on)
225
+ return;
226
+ state.desired[targetId] = false;
227
+ command(targetId, { state: "OFF" }, source);
228
+ }
229
+ else if (before?.control === "manual") {
230
+ state.desired[targetId] = true;
231
+ command(targetId, onOffOnly(targetId) ? { state: "ON" } : {
232
+ state: "ON",
233
+ ...(before.brightnessPct !== undefined ? { brightnessPct: before.brightnessPct } : {}),
234
+ ...(before.colorTempKelvin !== undefined ? { colorTempKelvin: before.colorTempKelvin } : {}),
235
+ transitionSeconds: config.initialTransitionSeconds
236
+ }, source);
237
+ }
238
+ else if (on) {
239
+ // Back in the room's style, over the style's own transition.
240
+ const style = state.style ? styled(targetId, state.style.transitionSeconds) : null;
241
+ if (style)
242
+ command(targetId, style, source);
243
+ }
244
+ else if (before) {
245
+ state.desired[targetId] = true;
246
+ command(targetId, styled(targetId, config.initialTransitionSeconds) ?? { state: "ON" }, source);
247
+ }
248
+ }
92
249
  function told(targetId) {
93
250
  state.untold = state.untold.filter((id) => id !== targetId);
94
251
  }
@@ -97,37 +254,55 @@ function transitionRoom(saved, msg, config, nowValue = new Date()) {
97
254
  return state.desired[targetId] === true;
98
255
  return state.observed[targetId]?.on === true;
99
256
  }
100
- function command(targetId, payload, source) {
101
- const target = targetById[targetId];
102
- if (!target)
257
+ // A command for a light, remembered for its power until a reading confirms
258
+ // it; a restyle only tentatively, until its adapter says it sent it.
259
+ function command(targetId, spec, source) {
260
+ if (!targetById[targetId])
103
261
  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
- };
262
+ state.commandSeq += 1;
263
+ const id = String(state.commandSeq);
264
+ state.expected[targetId] = (0, command_echo_1.rememberCommand)(state.expected[targetId], { state: spec.state }, nowMs, { id, tentative: spec.restyle === true });
265
+ const message = { kind: "command", target: targetId, ...spec, source, id };
266
+ commands.push(message);
267
+ return message;
111
268
  }
112
- function refreshCommands(source) {
113
- if (!state.circadianEnabled)
114
- return [];
115
- const commands = [];
269
+ function onOffOnly(targetId) {
270
+ return targetById[targetId]?.onOffOnly === true;
271
+ }
272
+ // The style in force: one with values that hasn't gone stale.
273
+ function currentStyle() {
274
+ const style = state.style;
275
+ return style?.values && Date.parse(style.until) > nowMs ? style.values : null;
276
+ }
277
+ // A style command for a light, over a transition; null for a light that
278
+ // only switches on and off, or with no style in force.
279
+ function styled(targetId, transitionSeconds) {
280
+ const style = currentStyle();
281
+ return style && !onOffOnly(targetId)
282
+ ? { state: "ON", brightnessPct: style.brightnessPct, colorTempKelvin: style.colorTempKelvin, transitionSeconds }
283
+ : null;
284
+ }
285
+ // Each light that is on and the room's to style, moved to the style in
286
+ // force over the style's transition.
287
+ // Each light that is on and the room's to style, moved to the style in
288
+ // force over the style's transition. Its adapter skips a light that
289
+ // already shows it (and says so).
290
+ function restyleLights(source) {
291
+ const style = currentStyle();
292
+ if (!style || !state.style)
293
+ return;
116
294
  for (const target of config.targets) {
117
295
  if (!intendedOn(target.id) || controlOf(target.id) !== "in-control")
118
296
  continue;
297
+ if (onOffOnly(target.id))
298
+ continue;
119
299
  if (state.untold.includes(target.id)) {
120
300
  trace("refresh", "skipped", "not-told-since-start", { target: target.id });
121
301
  continue;
122
302
  }
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));
303
+ command(target.id, { state: "ON", brightnessPct: style.brightnessPct, colorTempKelvin: style.colorTempKelvin,
304
+ transitionSeconds: state.style.transitionSeconds, restyle: true }, source);
129
305
  }
130
- return commands.filter((entry) => entry !== null);
131
306
  }
132
307
  function emitIntent(event) {
133
308
  const targets = Array.isArray(event.targets)
@@ -136,7 +311,7 @@ function transitionRoom(saved, msg, config, nowValue = new Date()) {
136
311
  const requestedState = String(event.state || "").toUpperCase();
137
312
  if (!["ON", "OFF", "TOGGLE"].includes(requestedState))
138
313
  return [];
139
- const commands = [];
314
+ const sent = [];
140
315
  const manualValues = event.values && typeof event.values === "object" ? event.values : null;
141
316
  const owner = typeof event.owner === "string" && event.owner ? event.owner : null;
142
317
  for (const targetId of targets) {
@@ -169,232 +344,266 @@ function transitionRoom(saved, msg, config, nowValue = new Date()) {
169
344
  continue;
170
345
  if (event.preserveManual === true && controlOf(targetId) === "manual")
171
346
  continue;
172
- if (resolvedState === "OFF") {
347
+ // An owner holds a light on or off; a newer owner goes on top.
348
+ const beneath = owner ? takeHold(targetId, owner, wasOn) : false;
349
+ if (owner) {
350
+ // Held: set below.
351
+ }
352
+ else if (resolvedState === "OFF") {
173
353
  // An off light has no style to protect: it returns to the room controller.
174
354
  setControl(targetId, null, "off");
175
355
  }
176
- else if (owner) {
177
- setControl(targetId, { state: "overridden", owner }, "owner-intent");
178
- }
179
- else if (event.manual === true || (manualValues && event.source !== "activity")) {
356
+ else if (event.manual === true) {
357
+ // Only a person's change makes a light manual: since 6.0, an intent's
358
+ // values alone don't.
180
359
  setControl(targetId, { state: "manual" }, "manual-intent");
181
360
  }
182
- let payload;
361
+ else if (person && resolvedState === "ON" && heldOff(targetId)) {
362
+ // A person switching on a light an owner holds off: theirs now.
363
+ setControl(targetId, { state: "manual" }, "person-changed");
364
+ }
365
+ let spec;
183
366
  if (resolvedState === "OFF") {
184
- payload = { state: "OFF" };
367
+ spec = { state: "OFF" };
185
368
  }
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
- }
369
+ else if (manualValues && onOffOnly(targetId)) {
370
+ // Nothing to set on a light that only switches: left out, and the
371
+ // node warns.
372
+ trace("intent", "accepted", exports.ON_OFF_ONLY, { target: targetId, dropped: Object.keys(manualValues) });
373
+ spec = { state: "ON" };
199
374
  }
200
- else if (state.circadianEnabled && controlOf(targetId) === "in-control") {
201
- payload = adaptivePayload("ON", event.refresh === true, state.sleeping, now, active);
375
+ else if (manualValues) {
376
+ const values = intentValues(manualValues);
377
+ if (values.removed.length)
378
+ trace("intent", "accepted", exports.REMOVED_LIGHT_UNITS, { target: targetId, dropped: values.removed, values: manualValues });
379
+ if (values.invalid.length)
380
+ trace("intent", "accepted", exports.INVALID_LIGHT_VALUES, { target: targetId, dropped: values.invalid, values: manualValues });
381
+ spec = {
382
+ state: "ON",
383
+ ...(Object.keys(values.extra).length ? { extra: values.extra } : {}),
384
+ ...(values.brightnessPct !== undefined ? { brightnessPct: values.brightnessPct } : {}),
385
+ ...(values.colorTempKelvin !== undefined ? { colorTempKelvin: values.colorTempKelvin } : {}),
386
+ // An intent's own transition (among its other fields) stands.
387
+ transitionSeconds: config.initialTransitionSeconds
388
+ };
202
389
  }
203
390
  else {
204
- payload = { state: "ON" };
391
+ // A bare ON: the style in force for a light the room controls,
392
+ // otherwise just on.
393
+ spec = (controlOf(targetId) === "in-control" ? styled(targetId, config.initialTransitionSeconds) : null) ?? { state: "ON" };
394
+ }
395
+ if (owner) {
396
+ (0, room_holds_1.setOwnerSpec)(holdOf(targetId), owner, spec);
397
+ if (beneath) {
398
+ trace("intent", "held", "beneath-owner", { target: targetId, owner, top: state.control[targetId].owner });
399
+ continue;
400
+ }
205
401
  }
206
402
  state.desired[targetId] = resolvedState === "ON";
207
403
  told(targetId);
208
- commands.push(command(targetId, payload, event.source || "intent"));
404
+ sent.push(command(targetId, spec, event.source || "intent"));
209
405
  }
210
- return commands.filter((entry) => entry !== null);
406
+ return sent.filter((entry) => entry !== null);
211
407
  }
212
408
  // What the room publishes, and the MQTT it reads for itself, are
213
409
  // room-publishing.ts's; this decides about lights only.
214
410
  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
- }
411
+ const reading = (0, light_contract_1.isLightReading)(msg.light) && targetById[msg.light.target] ? msg.light : null;
412
+ if (reading?.kind === "observed") {
413
+ const target = targetById[reading.target];
414
+ const previousOn = state.observed[target.id]?.on;
415
+ const nextOn = reading.on === true;
416
+ state.observed[target.id] = {
417
+ on: nextOn,
418
+ ...(typeof reading.brightnessPct === "number" ? { brightnessPct: reading.brightnessPct } : {}),
419
+ ...(typeof reading.colorTempKelvin === "number" ? { colorTempKelvin: reading.colorTempKelvin } : {}),
420
+ fields: Array.isArray(reading.fields) ? [...reading.fields] : [],
421
+ observedAt: now.toISOString()
422
+ };
423
+ if (previousOn !== nextOn) {
424
+ trace("state-observed", "changed", null, {
425
+ target: target.id,
426
+ state: nextOn ? "ON" : "OFF"
427
+ });
428
+ }
429
+ const report = (0, command_echo_1.checkStateReport)(state.expected[target.id], nextOn, nowMs);
430
+ state.expected[target.id] = report.queue;
431
+ if (report.verdict === "confirms") {
432
+ // Our own command, now done: the intended state already says so.
433
+ // A confirmed OFF deliberately leaves control alone: our OFFs come
434
+ // from OFF intents, which already returned the light to in-control.
435
+ trace("state-observed", "confirmed", "own-command", { target: target.id, state: nextOn ? "ON" : "OFF" });
436
+ }
437
+ else if (report.verdict === "stale") {
438
+ // Older than our pending command; the light will report again.
439
+ trace("state-observed", "ignored", "stale-report", { target: target.id, state: nextOn ? "ON" : "OFF" });
440
+ }
441
+ else {
442
+ // A change the controller didn't cause becomes the intended state.
443
+ state.desired[target.id] = nextOn;
444
+ if (!nextOn)
445
+ setControl(target.id, null, "observed-off");
446
+ // Switched on while an owner holds it off: a person's now.
447
+ else if (heldOff(target.id))
448
+ setControl(target.id, { state: "manual" }, "person-changed");
248
449
  }
249
450
  }
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
- }
451
+ else if (reading?.kind === "echo-changed") {
452
+ // Our own command, changed on the way (the command path should pass it
453
+ // through as it is): never answered as someone else's. Its adapter knew.
454
+ trace("command-observed", "ignored", "mutated-own-command", { target: reading.target, state: String(reading.state || "").toUpperCase() });
455
+ }
456
+ else if (reading?.kind === "skipped") {
457
+ // A restyle its adapter didn't send: the light already shows it.
458
+ state.expected[reading.target] = (0, command_echo_1.commandSkipped)(state.expected[reading.target], String(reading.id), nowMs);
459
+ trace("refresh", "skipped", "already-at-level", { target: reading.target });
460
+ }
461
+ else if (reading?.kind === "sent") {
462
+ state.expected[reading.target] = (0, command_echo_1.commandSent)(state.expected[reading.target], String(reading.id), nowMs);
463
+ }
464
+ else if (reading?.kind === "availability") {
465
+ // Shown, never acted on.
466
+ if (state.available[reading.target] !== reading.online) {
467
+ state.available[reading.target] = reading.online === true;
468
+ availabilityChanged.add(reading.target);
469
+ trace("availability", reading.online ? "online" : "offline", null, { target: reading.target });
302
470
  }
303
471
  }
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 });
472
+ else if (reading?.kind === "external") {
473
+ // Someone else's command, as its adapter told it from the room's own.
474
+ const target = targetById[reading.target];
475
+ const requestedState = String(reading.state || "").toUpperCase();
476
+ if (requestedState === "OFF") {
477
+ state.desired[target.id] = false;
478
+ setControl(target.id, null, "external-off");
309
479
  }
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)
480
+ else if (requestedState === "ON") {
481
+ state.desired[target.id] = true;
482
+ if (reading.setsValues === true && !onOffOnly(target.id)) {
483
+ setControl(target.id, { state: "manual" }, "external-values");
484
+ }
485
+ else if (heldOff(target.id)) {
486
+ // Switched on while an owner holds it off: a person's now.
487
+ setControl(target.id, { state: "manual" }, "person-changed");
488
+ }
489
+ else if (currentStyle() && !onOffOnly(target.id) && controlOf(target.id) === "in-control") {
490
+ // At most one restyle per light per echo window, whatever comes
491
+ // back: a bare ON delivered twice (two subscriptions, or a QoS
492
+ // redelivery) can't make the room answer itself in a loop.
493
+ const last = state.restyledAt[target.id];
494
+ if (last !== undefined && nowMs - last >= 0 && nowMs - last < command_echo_1.ECHO_WINDOW_MS) {
495
+ trace("external-command", "suppressed", "restyled-recently", { target: target.id });
496
+ }
497
+ else if (command(target.id, styled(target.id, config.initialTransitionSeconds), "external-bare-on")) {
498
+ state.restyledAt[target.id] = nowMs;
499
+ }
500
+ // Styled now, so a style keeps it in step from here.
314
501
  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
502
  }
320
- outputs.push(...refreshCommands("circadian-enabled"));
321
503
  }
504
+ else if (requestedState === "TOGGLE") {
505
+ state.desired[target.id] = !intendedOn(target.id);
506
+ }
507
+ state.personAt[target.id] = now.getTime();
508
+ trace("external-command", "observed", null, {
509
+ target: target.id,
510
+ state: requestedState || "UNKNOWN",
511
+ control: controlOf(target.id)
512
+ });
513
+ }
514
+ else if (event.kind === "startup") {
515
+ // Each light is asked for a fresh reading, rather than waiting for a change.
516
+ for (const target of config.targets)
517
+ commands.push({ kind: "observe", target: target.id });
322
518
  }
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"));
519
+ else if (event.kind === "circadian" || event.kind === "sleep" || event.kind === "schedule") {
520
+ // The circadian lighting policy's since 6.0: the node warns.
521
+ trace(event.kind, "ignored", exports.MOVED_TO_CIRCADIAN);
329
522
  }
330
- else if (event.kind === "schedule") {
331
- const next = (0, room_schedule_1.requestedSchedule)(state.schedule, event);
523
+ else if (event.kind === "style") {
524
+ const previous = state.style;
525
+ const next = savedStyle({ ...event, source: event.source });
332
526
  if (!next) {
333
- trace("schedule", "ignored", "invalid-times", { wakeTime: event.wakeTime, bedTime: event.bedTime });
527
+ trace("style", "ignored", "not-a-style");
334
528
  }
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"));
529
+ else {
530
+ state.style = next;
531
+ // Traced when it starts or stops styling, or comes from someone else,
532
+ // not at every interval.
533
+ if (!previous || (previous.values === null) !== (next.values === null) || previous.source !== next.source) {
534
+ trace("style", "changed", null, { source: next.source, styling: next.values !== null });
535
+ }
536
+ if (event.takeBack === true) {
537
+ // The one time a style changes who controls a light: circadian
538
+ // lighting switched on takes back what a person set, and the room
539
+ // has then been told about every light. Other owners keep theirs.
540
+ for (const target of config.targets) {
541
+ told(target.id);
542
+ if (controlOf(target.id) === "manual")
543
+ setControl(target.id, null, "taken-back");
544
+ }
545
+ }
546
+ restyleLights(next.source);
340
547
  }
341
548
  }
342
- else if (event.kind === "refresh") {
343
- outputs.push(...refreshCommands("periodic-refresh"));
344
- }
345
549
  else if (event.kind === "release") {
346
- // Hand overridden lights back; an owner name releases only that owner's lights.
550
+ // An owner name lets go of that owner's lights; none lets go of every
551
+ // owner's. A light goes to the owner beneath, with what it asked for, or
552
+ // with none left back to what it was before the first.
347
553
  const targets = Array.isArray(event.targets) ? event.targets : config.targets.map((target) => target.id);
348
554
  const owner = typeof event.owner === "string" && event.owner ? event.owner : null;
555
+ const source = event.source || "release";
349
556
  for (const targetId of targets) {
350
- const entry = state.control[targetId];
351
- if (!targetById[targetId] || entry?.state !== "overridden" || (owner && entry.owner !== owner))
557
+ if (!targetById[targetId] || state.control[targetId]?.state !== "overridden")
352
558
  continue;
353
- setControl(targetId, null, "released");
354
- 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);
559
+ const released = (0, room_holds_1.releaseOwner)(holdOf(targetId), owner);
560
+ if (released.kind === "dropped") {
561
+ trace("release", "dropped", "beneath-owner", { target: targetId, owner });
562
+ }
563
+ else if (released.kind === "next") {
564
+ setControl(targetId, { state: "overridden", owner: released.owner }, "released-to-owner");
565
+ told(targetId);
566
+ if (released.spec) {
567
+ state.desired[targetId] = released.spec.state === "ON";
568
+ command(targetId, released.spec, source);
569
+ }
570
+ }
571
+ else if (released.kind === "restore") {
572
+ restoreHeld(targetId, released.before, source);
359
573
  }
360
574
  }
361
575
  }
362
576
  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", {
577
+ const sent = emitIntent(event).map(({ target, state: power }) => ({ target, state: power }));
578
+ trace("intent", sent.length ? "commanded" : "suppressed", sent.length ? null : "no-command-required", {
376
579
  source: event.source || "intent",
377
580
  state: String(event.state || "").toUpperCase(),
378
581
  targets: Array.isArray(event.targets)
379
582
  ? event.targets
380
583
  : config.targets.map((target) => target.id),
381
- commands
584
+ commands: sent
382
585
  });
383
586
  }
384
587
  const onCount = Object.values(state.desired).filter(Boolean).length;
385
588
  const control = Object.fromEntries(config.targets.map((target) => [target.id, controlOf(target.id)]));
386
589
  const manualCount = Object.values(control).filter((entry) => entry === "manual").length;
387
590
  const overriddenCount = Object.values(control).filter((entry) => entry === "overridden").length;
591
+ const offlineCount = config.targets.filter((target) => state.available[target.id] === false).length;
388
592
  return {
389
593
  state,
390
594
  outputs,
595
+ // Light commands for the lights' adapters, in the order sent.
596
+ commands,
391
597
  traces,
392
- // The lights whose control state changed, in configured order.
393
- controlChanged: config.targets.map((target) => target.id).filter((id) => controlChanged.has(id)),
598
+ // The lights whose control state, or availability, changed, in
599
+ // configured order.
600
+ controlChanged: config.targets.map((target) => target.id).filter((id) => controlChanged.has(id) || availabilityChanged.has(id)),
394
601
  status: {
395
- circadianEnabled: state.circadianEnabled,
396
- sleeping: state.sleeping,
602
+ // Whether a style is in force, and whose it is.
603
+ styled: currentStyle() !== null,
604
+ styleSource: state.style?.source ?? null,
397
605
  onCount,
606
+ offlineCount,
398
607
  manualCount,
399
608
  overriddenCount,
400
609
  control