@avantics/node-red-home-automation 3.0.1 → 4.0.1

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 (108) hide show
  1. package/README.md +278 -13
  2. package/dist/lib/activity-lighting-controller.d.ts +7 -1
  3. package/dist/lib/activity-lighting-controller.js +37 -3
  4. package/dist/lib/adopted-request.d.ts +26 -0
  5. package/dist/lib/adopted-request.js +44 -0
  6. package/dist/lib/avr-controller.d.ts +8 -1
  7. package/dist/lib/avr-controller.js +27 -3
  8. package/dist/lib/avr-publishing.d.ts +24 -0
  9. package/dist/lib/avr-publishing.js +80 -0
  10. package/dist/lib/backlighting-controller.d.ts +7 -1
  11. package/dist/lib/backlighting-controller.js +26 -3
  12. package/dist/lib/circadian.d.ts +1 -0
  13. package/dist/lib/circadian.js +3 -0
  14. package/dist/lib/cover-availability.d.ts +7 -0
  15. package/dist/lib/cover-availability.js +24 -0
  16. package/dist/lib/cover-controller.d.ts +13 -1
  17. package/dist/lib/cover-controller.js +145 -31
  18. package/dist/lib/cover-group.d.ts +62 -0
  19. package/dist/lib/cover-group.js +125 -0
  20. package/dist/lib/cover-models.d.ts +37 -0
  21. package/dist/lib/cover-models.js +83 -0
  22. package/dist/lib/cover-publishing.d.ts +40 -0
  23. package/dist/lib/cover-publishing.js +102 -0
  24. package/dist/lib/cover-requests.d.ts +21 -0
  25. package/dist/lib/cover-requests.js +49 -0
  26. package/dist/lib/display-mode-controller.d.ts +4 -0
  27. package/dist/lib/display-mode-controller.js +26 -2
  28. package/dist/lib/ha-discovery.d.ts +27 -0
  29. package/dist/lib/ha-discovery.js +91 -0
  30. package/dist/lib/house-schedule-publishing.d.ts +23 -0
  31. package/dist/lib/house-schedule-publishing.js +71 -0
  32. package/dist/lib/house-schedule.d.ts +23 -0
  33. package/dist/lib/house-schedule.js +29 -0
  34. package/dist/lib/motion-policy.d.ts +9 -0
  35. package/dist/lib/motion-policy.js +45 -11
  36. package/dist/lib/motion-publishing.d.ts +28 -0
  37. package/dist/lib/motion-publishing.js +92 -0
  38. package/dist/lib/occupancy-publishing.d.ts +10 -0
  39. package/dist/lib/occupancy-publishing.js +45 -0
  40. package/dist/lib/open-close-cover.d.ts +92 -0
  41. package/dist/lib/open-close-cover.js +287 -0
  42. package/dist/lib/publishing-node.d.ts +39 -0
  43. package/dist/lib/publishing-node.js +72 -0
  44. package/dist/lib/retained-topics.d.ts +10 -0
  45. package/dist/lib/retained-topics.js +19 -0
  46. package/dist/lib/room-controller.d.ts +9 -0
  47. package/dist/lib/room-controller.js +47 -56
  48. package/dist/lib/room-lighting-discovery.d.ts +20 -1
  49. package/dist/lib/room-lighting-discovery.js +135 -13
  50. package/dist/lib/room-publishing.d.ts +42 -0
  51. package/dist/lib/room-publishing.js +182 -0
  52. package/dist/lib/room-schedule.d.ts +8 -0
  53. package/dist/lib/room-schedule.js +41 -0
  54. package/dist/lib/settings.d.ts +2 -0
  55. package/dist/lib/settings.js +20 -0
  56. package/dist/lib/source-capability-controller.d.ts +8 -1
  57. package/dist/lib/source-capability-controller.js +29 -3
  58. package/dist/lib/theatre-activity-controller.d.ts +0 -1
  59. package/dist/lib/theatre-activity-controller.js +27 -24
  60. package/dist/lib/theatre-ha-discovery.d.ts +3 -4
  61. package/dist/lib/theatre-ha-discovery.js +46 -36
  62. package/dist/lib/theatre-state-contract.d.ts +6 -0
  63. package/dist/lib/theatre-state-contract.js +83 -47
  64. package/dist/lib/theatre-state.d.ts +1 -1
  65. package/dist/lib/theatre-state.js +1 -1
  66. package/dist/lib/topic-names.d.ts +4 -0
  67. package/dist/lib/topic-names.js +31 -0
  68. package/dist/nodes/activity-lighting-controller.js +5 -3
  69. package/dist/nodes/adapter.d.ts +6 -1
  70. package/dist/nodes/adapter.js +65 -1
  71. package/dist/nodes/avr-controller.html +59 -5
  72. package/dist/nodes/avr-controller.js +74 -4
  73. package/dist/nodes/backlighting-controller.js +5 -3
  74. package/dist/nodes/cover-controller.d.ts +3 -0
  75. package/dist/nodes/cover-controller.html +181 -0
  76. package/dist/nodes/cover-controller.js +178 -0
  77. package/dist/nodes/cover-group.d.ts +3 -0
  78. package/dist/nodes/cover-group.html +89 -0
  79. package/dist/nodes/cover-group.js +84 -0
  80. package/dist/nodes/flows-started.d.ts +4 -0
  81. package/dist/nodes/flows-started.js +39 -0
  82. package/dist/nodes/house-schedule-mqtt.d.ts +3 -0
  83. package/dist/nodes/house-schedule-mqtt.html +61 -0
  84. package/dist/nodes/house-schedule-mqtt.js +80 -0
  85. package/dist/nodes/house-schedule.d.ts +3 -0
  86. package/dist/nodes/house-schedule.html +31 -0
  87. package/dist/nodes/house-schedule.js +51 -0
  88. package/dist/nodes/motion-policy.html +81 -5
  89. package/dist/nodes/motion-policy.js +69 -8
  90. package/dist/nodes/occupancy-fusion.html +69 -14
  91. package/dist/nodes/occupancy-fusion.js +46 -4
  92. package/dist/nodes/publishing-lifecycle.d.ts +25 -0
  93. package/dist/nodes/publishing-lifecycle.js +38 -0
  94. package/dist/nodes/room-controller.html +49 -5
  95. package/dist/nodes/room-controller.js +67 -8
  96. package/dist/nodes/shared-schedule.d.ts +6 -0
  97. package/dist/nodes/shared-schedule.js +15 -0
  98. package/dist/nodes/source-capability-controller.js +5 -3
  99. package/dist/nodes/theatre-activity-controller.html +1 -3
  100. package/dist/nodes/theatre-activity-controller.js +1 -2
  101. package/dist/nodes/theatre-state-contract.html +28 -5
  102. package/dist/nodes/theatre-state-contract.js +22 -4
  103. package/examples/Cover control.json +380 -0
  104. package/examples/Cover pair.json +230 -0
  105. package/examples/Home theatre activity.json +4 -4
  106. package/examples/House schedule.json +164 -0
  107. package/examples/Room lighting.json +4 -3
  108. package/package.json +6 -2
@@ -4,8 +4,8 @@ exports.parsePayload = exports.fingerprint = void 0;
4
4
  exports.createRoomState = createRoomState;
5
5
  exports.adaptivePayload = adaptivePayload;
6
6
  exports.transitionRoom = transitionRoom;
7
+ const room_schedule_1 = require("./room-schedule");
7
8
  const z2m_light_1 = require("./z2m-light");
8
- const room_lighting_discovery_1 = require("./room-lighting-discovery");
9
9
  const command_echo_1 = require("./command-echo");
10
10
  var command_echo_2 = require("./command-echo");
11
11
  Object.defineProperty(exports, "fingerprint", { enumerable: true, get: function () { return command_echo_2.fingerprint; } });
@@ -27,8 +27,12 @@ function createRoomState(config, saved = {}) {
27
27
  expected: Object.fromEntries(Object.entries(saved.expected || {}).map(([target, entries]) => [target, entries.map((entry) => ({ ...entry }))])),
28
28
  circadianEnabled: saved.circadianEnabled !== false,
29
29
  sleeping: saved.sleeping === undefined ? config.initialSleep : saved.sleeping === true,
30
+ ...(0, room_schedule_1.savedSchedule)(config, saved),
30
31
  personAt: Object.fromEntries(Object.entries(saved.personAt || {})
31
32
  .filter(([, at]) => Number.isFinite(at))),
33
+ untold: Array.isArray(saved.untold)
34
+ ? saved.untold.filter((id) => config.targets.some((target) => target.id === id))
35
+ : [],
32
36
  restyledAt: Object.fromEntries(Object.entries(saved.restyledAt || {})
33
37
  .filter(([target, at]) => Number.isFinite(at) && config.targets.some((entry) => entry.id === target)))
34
38
  };
@@ -43,6 +47,11 @@ function transitionRoom(saved, msg, config, nowValue = new Date()) {
43
47
  const now = nowValue instanceof Date ? nowValue : new Date(nowValue);
44
48
  const nowMs = now.getTime();
45
49
  const state = createRoomState(config, saved);
50
+ if (saved === undefined)
51
+ 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);
46
55
  const targetById = Object.fromEntries(config.targets.map((target) => [target.id, target]));
47
56
  const traces = [];
48
57
  const outputs = [];
@@ -72,13 +81,8 @@ function transitionRoom(saved, msg, config, nowValue = new Date()) {
72
81
  previous: previous?.state ?? "in-control"
73
82
  });
74
83
  }
75
- function controlMessage(targetId) {
76
- const entry = state.control[targetId];
77
- return {
78
- topic: "home/" + config.area + "/lighting/" + targetId + "/control",
79
- payload: { state: entry?.state ?? "in-control", owner: entry?.state === "overridden" ? entry.owner : null },
80
- retain: true
81
- };
84
+ function told(targetId) {
85
+ state.untold = state.untold.filter((id) => id !== targetId);
82
86
  }
83
87
  function intendedOn(targetId) {
84
88
  if (Object.hasOwn(state.desired, targetId))
@@ -97,11 +101,6 @@ function transitionRoom(saved, msg, config, nowValue = new Date()) {
97
101
  lighting_command: { area: config.area, target: targetId, source }
98
102
  };
99
103
  }
100
- // What the room publishes for MQTT and Home Assistant to see is named after
101
- // its area, so it needs one, and is switched on by its settings; light
102
- // control depends on neither.
103
- const publishesArea = config.area !== "" && config.publishState !== false;
104
- const publishesDiscovery = publishesArea && config.discovery !== false;
105
104
  function refreshCommands(source) {
106
105
  if (!state.circadianEnabled)
107
106
  return [];
@@ -109,12 +108,16 @@ function transitionRoom(saved, msg, config, nowValue = new Date()) {
109
108
  for (const target of config.targets) {
110
109
  if (!intendedOn(target.id) || controlOf(target.id) !== "in-control")
111
110
  continue;
111
+ if (state.untold.includes(target.id)) {
112
+ trace("refresh", "skipped", "not-told-since-start", { target: target.id });
113
+ continue;
114
+ }
112
115
  // Nothing to change when the light last reported exactly this style.
113
- if ((0, z2m_light_1.alreadyStyled)(config.lighting.styleAt(now, state.sleeping), state.observed[target.id])) {
116
+ if ((0, z2m_light_1.alreadyStyled)(active.lighting.styleAt(now, state.sleeping), state.observed[target.id])) {
114
117
  trace("refresh", "skipped", "already-at-level", { target: target.id });
115
118
  continue;
116
119
  }
117
- commands.push(command(target.id, adaptivePayload("ON", true, state.sleeping, now, config), source));
120
+ commands.push(command(target.id, adaptivePayload("ON", true, state.sleeping, now, active), source));
118
121
  }
119
122
  return commands.filter((entry) => entry !== null);
120
123
  }
@@ -179,48 +182,21 @@ function transitionRoom(saved, msg, config, nowValue = new Date()) {
179
182
  }
180
183
  }
181
184
  else if (state.circadianEnabled && controlOf(targetId) === "in-control") {
182
- payload = adaptivePayload("ON", event.refresh === true, state.sleeping, now, config);
185
+ payload = adaptivePayload("ON", event.refresh === true, state.sleeping, now, active);
183
186
  }
184
187
  else {
185
188
  payload = { state: "ON" };
186
189
  }
187
190
  state.desired[targetId] = resolvedState === "ON";
191
+ told(targetId);
188
192
  commands.push(command(targetId, payload, event.source || "intent"));
189
193
  }
190
194
  return commands.filter((entry) => entry !== null);
191
195
  }
192
- let event = msg.lighting || {};
193
- // The circadian switch's set topic: Home Assistant sends ON or OFF there.
194
- // Read only while the room publishes, as the switch is only discovered then;
195
- // a bare MQTT message, or one a flow tagged as observed, is accepted.
196
- if (publishesArea && msg.topic === (0, room_lighting_discovery_1.circadianCommandTopic)(config.area) &&
197
- (!event.kind || event.kind === "observed" || event.kind === "command-observed")) {
198
- const requested = typeof msg.payload === "string" ? msg.payload.trim().toUpperCase() : "";
199
- if (msg.retain === true || event.retained === true) {
200
- trace("circadian-set", "ignored", "retained-message");
201
- event = { kind: "ignored" };
202
- }
203
- else if (requested === "ON" || requested === "OFF") {
204
- event = { kind: "circadian", enabled: requested === "ON" };
205
- }
206
- else {
207
- trace("circadian-set", "ignored", "not-on-or-off", { payload: typeof msg.payload === "string" ? msg.payload : null });
208
- event = { kind: "ignored" };
209
- }
210
- }
211
- if (event.kind === "startup") {
212
- if (config.area !== "") {
213
- const entry = (0, room_lighting_discovery_1.roomLightingDiscovery)(config.area, config.displayName, state.circadianEnabled)[0];
214
- // Discovery switched off: an empty retained entry removes the switch
215
- // from Home Assistant.
216
- outputs.push(publishesDiscovery ? entry : { topic: entry.topic, payload: "", retain: true });
217
- }
218
- if (publishesArea)
219
- outputs.push((0, room_lighting_discovery_1.circadianStateMessage)(config.area, state.circadianEnabled));
220
- for (const target of config.targets)
221
- controlChanged.add(target.id);
222
- }
223
- else if (event.kind === "observed") {
196
+ // What the room publishes, and the MQTT it reads for itself, are
197
+ // room-publishing.ts's; this decides about lights only.
198
+ const event = msg.lighting || {};
199
+ if (event.kind === "observed") {
224
200
  const target = event.target ? targetById[event.target] : targetForTopic(msg.topic, "stateTopic");
225
201
  const parsed = (0, command_echo_1.parsePayload)(msg.payload);
226
202
  const payload = parsed && typeof parsed === "object" ? parsed : null;
@@ -287,12 +263,14 @@ function transitionRoom(saved, msg, config, nowValue = new Date()) {
287
263
  trace("external-command", "suppressed", "restyled-recently", { target: target.id });
288
264
  }
289
265
  else {
290
- const corrective = command(target.id, adaptivePayload("ON", false, state.sleeping, now, config), "external-bare-on");
266
+ const corrective = command(target.id, adaptivePayload("ON", false, state.sleeping, now, active), "external-bare-on");
291
267
  if (corrective) {
292
268
  outputs.push(corrective);
293
269
  state.restyledAt[target.id] = nowMs;
294
270
  }
295
271
  }
272
+ // Styled now, so the refresh keeps it in step from here.
273
+ told(target.id);
296
274
  }
297
275
  }
298
276
  else if (requestedState === "TOGGLE") {
@@ -313,9 +291,11 @@ function transitionRoom(saved, msg, config, nowValue = new Date()) {
313
291
  if (previous !== state.circadianEnabled) {
314
292
  trace("circadian", "changed", null, { enabled: state.circadianEnabled });
315
293
  }
316
- if (publishesArea)
317
- outputs.push((0, room_lighting_discovery_1.circadianStateMessage)(config.area, state.circadianEnabled));
318
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)
298
+ told(target.id);
319
299
  // Enabling circadian takes back manual lights; other owners keep theirs.
320
300
  for (const target of config.targets) {
321
301
  if (controlOf(target.id) === "manual")
@@ -331,6 +311,18 @@ function transitionRoom(saved, msg, config, nowValue = new Date()) {
331
311
  trace("sleep", "changed", null, { enabled: state.sleeping });
332
312
  outputs.push(...refreshCommands("sleep-policy"));
333
313
  }
314
+ else if (event.kind === "schedule") {
315
+ const next = (0, room_schedule_1.requestedSchedule)(state.schedule, event);
316
+ if (!next) {
317
+ trace("schedule", "ignored", "invalid-times", { wakeTime: event.wakeTime, bedTime: event.bedTime });
318
+ }
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"));
324
+ }
325
+ }
334
326
  else if (event.kind === "refresh") {
335
327
  outputs.push(...refreshCommands("periodic-refresh"));
336
328
  }
@@ -343,8 +335,9 @@ function transitionRoom(saved, msg, config, nowValue = new Date()) {
343
335
  if (!targetById[targetId] || entry?.state !== "overridden" || (owner && entry.owner !== owner))
344
336
  continue;
345
337
  setControl(targetId, null, "released");
338
+ told(targetId);
346
339
  if (state.circadianEnabled && intendedOn(targetId)) {
347
- const restyle = command(targetId, adaptivePayload("ON", true, state.sleeping, now, config), event.source || "release");
340
+ const restyle = command(targetId, adaptivePayload("ON", true, state.sleeping, now, active), event.source || "release");
348
341
  if (restyle)
349
342
  outputs.push(restyle);
350
343
  }
@@ -372,10 +365,6 @@ function transitionRoom(saved, msg, config, nowValue = new Date()) {
372
365
  commands
373
366
  });
374
367
  }
375
- for (const target of config.targets) {
376
- if (publishesArea && controlChanged.has(target.id))
377
- outputs.push(controlMessage(target.id));
378
- }
379
368
  const onCount = Object.values(state.desired).filter(Boolean).length;
380
369
  const control = Object.fromEntries(config.targets.map((target) => [target.id, controlOf(target.id)]));
381
370
  const manualCount = Object.values(control).filter((entry) => entry === "manual").length;
@@ -384,6 +373,8 @@ function transitionRoom(saved, msg, config, nowValue = new Date()) {
384
373
  state,
385
374
  outputs,
386
375
  traces,
376
+ // The lights whose control state changed, in configured order.
377
+ controlChanged: config.targets.map((target) => target.id).filter((id) => controlChanged.has(id)),
387
378
  status: {
388
379
  circadianEnabled: state.circadianEnabled,
389
380
  sleeping: state.sleeping,
@@ -1,9 +1,28 @@
1
+ import { type DiscoveryOwner } from "./ha-discovery";
2
+ import type { DaySchedule } from "./circadian-schedule";
1
3
  export interface DiscoveryMessage {
2
4
  topic: string;
3
5
  payload: unknown;
4
6
  retain: boolean;
5
7
  }
8
+ export declare function roomTopic(area: string, name: string): string;
6
9
  export declare function circadianStateTopic(area: string): string;
7
10
  export declare function circadianCommandTopic(area: string): string;
11
+ export declare function roomAvailabilityTopic(area: string): string;
12
+ export declare function roomAvailabilityMessage(area: string, online: boolean): DiscoveryMessage;
13
+ export declare function roomControlTopic(area: string, targetId: string): string;
14
+ export declare function sleepStateTopic(area: string): string;
15
+ export declare function sleepCommandTopic(area: string): string;
16
+ export type ScheduleTime = "wake-time" | "bed-time";
17
+ export declare function scheduleStateTopic(area: string, time: ScheduleTime): string;
18
+ export declare function scheduleCommandTopic(area: string, time: ScheduleTime): string;
19
+ export declare function sleepStateMessage(area: string, sleeping: boolean): DiscoveryMessage;
20
+ export declare function scheduleStateMessages(area: string, schedule: DaySchedule): DiscoveryMessage[];
8
21
  export declare function circadianStateMessage(area: string, enabled: boolean): DiscoveryMessage;
9
- export declare function roomLightingDiscovery(area: string, displayName: string, circadianEnabled: boolean): DiscoveryMessage[];
22
+ export interface RoomDiscoveryConfig extends DiscoveryOwner {
23
+ displayName: string;
24
+ timesFrom?: "room" | "house";
25
+ }
26
+ export declare function roomTimeDiscoveryTopics(config: RoomDiscoveryConfig): string[];
27
+ export declare function roomDiscovery(config: RoomDiscoveryConfig, targetIds: string[]): DiscoveryMessage[];
28
+ export declare function roomLightingDiscovery(config: RoomDiscoveryConfig, circadianEnabled: boolean): DiscoveryMessage[];
@@ -1,41 +1,163 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.roomTopic = roomTopic;
3
4
  exports.circadianStateTopic = circadianStateTopic;
4
5
  exports.circadianCommandTopic = circadianCommandTopic;
6
+ exports.roomAvailabilityTopic = roomAvailabilityTopic;
7
+ exports.roomAvailabilityMessage = roomAvailabilityMessage;
8
+ exports.roomControlTopic = roomControlTopic;
9
+ exports.sleepStateTopic = sleepStateTopic;
10
+ exports.sleepCommandTopic = sleepCommandTopic;
11
+ exports.scheduleStateTopic = scheduleStateTopic;
12
+ exports.scheduleCommandTopic = scheduleCommandTopic;
13
+ exports.sleepStateMessage = sleepStateMessage;
14
+ exports.scheduleStateMessages = scheduleStateMessages;
5
15
  exports.circadianStateMessage = circadianStateMessage;
16
+ exports.roomTimeDiscoveryTopics = roomTimeDiscoveryTopics;
17
+ exports.roomDiscovery = roomDiscovery;
6
18
  exports.roomLightingDiscovery = roomLightingDiscovery;
19
+ // The room controller's Home Assistant view: a discovery entry for its
20
+ // circadian switch and the retained state that entry reads. Home Assistant
21
+ // may send ON/OFF on the command topic, which the room controller acts on.
22
+ const ha_discovery_1 = require("./ha-discovery");
23
+ const topic_names_1 = require("./topic-names");
24
+ // The one place a room topic is named: home/<area ID>/<name>.
25
+ function roomTopic(area, name) {
26
+ return "home/" + (0, topic_names_1.areaId)(area) + "/" + name;
27
+ }
7
28
  function circadianStateTopic(area) {
8
- return "home/" + area + "/circadian/state";
29
+ return roomTopic(area, "circadian/state");
9
30
  }
10
31
  function circadianCommandTopic(area) {
11
- return "home/" + area + "/circadian/set";
32
+ return roomTopic(area, "circadian/set");
33
+ }
34
+ // The room's own availability, online or offline, for Home Assistant.
35
+ function roomAvailabilityTopic(area) {
36
+ return roomTopic(area, "lighting/availability");
37
+ }
38
+ function roomAvailabilityMessage(area, online) {
39
+ return { topic: roomAvailabilityTopic(area), payload: online ? ha_discovery_1.ONLINE : ha_discovery_1.OFFLINE, retain: true };
40
+ }
41
+ // A light's control state: in-control, overridden or manual.
42
+ function roomControlTopic(area, targetId) {
43
+ return roomTopic(area, "lighting/" + targetId + "/control");
44
+ }
45
+ // Sleep, and the wake and bed times, each with a state topic and a set
46
+ // topic Home Assistant commands.
47
+ function sleepStateTopic(area) {
48
+ return roomTopic(area, "sleep/state");
49
+ }
50
+ function sleepCommandTopic(area) {
51
+ return roomTopic(area, "sleep/set");
52
+ }
53
+ function scheduleStateTopic(area, time) {
54
+ return roomTopic(area, time + "/state");
55
+ }
56
+ function scheduleCommandTopic(area, time) {
57
+ return roomTopic(area, time + "/set");
58
+ }
59
+ function sleepStateMessage(area, sleeping) {
60
+ return { topic: sleepStateTopic(area), payload: sleeping ? "ON" : "OFF", retain: true };
61
+ }
62
+ // The times in use, "HH:MM:SS" as Home Assistant's time entity reads them.
63
+ function scheduleStateMessages(area, schedule) {
64
+ return [
65
+ { topic: scheduleStateTopic(area, "wake-time"), payload: schedule.wakeTime + ":00", retain: true },
66
+ { topic: scheduleStateTopic(area, "bed-time"), payload: schedule.bedTime + ":00", retain: true }
67
+ ];
12
68
  }
13
69
  // The retained circadian state, as Home Assistant reads it.
14
70
  function circadianStateMessage(area, enabled) {
15
71
  return { topic: circadianStateTopic(area), payload: enabled ? "ON" : "OFF", retain: true };
16
72
  }
73
+ const CIRCADIAN_ENTITY = "circadian_lighting";
74
+ function roomDevice(config) {
75
+ return {
76
+ ...(0, ha_discovery_1.discoveryDevice)(config, "lighting"),
77
+ name: config.displayName + " Lighting Controller",
78
+ manufacturer: "Node-RED",
79
+ model: "Composable circadian lighting"
80
+ };
81
+ }
82
+ // One more entity on the room's device, with the IDs, availability and
83
+ // origin every room entity carries.
84
+ function roomEntity(config, component, entity, name, fields) {
85
+ const ids = (0, ha_discovery_1.discoveryEntity)(config, component, entity);
86
+ return {
87
+ topic: ids.topic,
88
+ payload: {
89
+ name: config.displayName + " " + name,
90
+ unique_id: ids.uniqueId,
91
+ default_entity_id: ids.defaultEntityId,
92
+ ...fields,
93
+ availability_topic: roomAvailabilityTopic(config.area),
94
+ device: roomDevice(config),
95
+ origin: ha_discovery_1.DISCOVERY_ORIGIN
96
+ },
97
+ retain: true
98
+ };
99
+ }
100
+ // Every discovery entry the room publishes: its circadian switch, a sleep
101
+ // switch, its wake and bed times, and each light's control state.
102
+ function roomTimeEntities(config) {
103
+ const time = (which, entity, name, icon) => roomEntity(config, "time", entity, name, {
104
+ icon,
105
+ command_topic: scheduleCommandTopic(config.area, which),
106
+ state_topic: scheduleStateTopic(config.area, which),
107
+ entity_category: "config"
108
+ });
109
+ return [
110
+ time("wake-time", "wake_time", "Wake time", "mdi:weather-sunset-up"),
111
+ time("bed-time", "bed_time", "Bed time", "mdi:weather-night")
112
+ ];
113
+ }
114
+ // The discovery topics of the room's own wake and bed time entities.
115
+ function roomTimeDiscoveryTopics(config) {
116
+ return roomTimeEntities(config).map(({ topic }) => topic);
117
+ }
118
+ function roomDiscovery(config, targetIds) {
119
+ const { area } = config;
120
+ return [
121
+ roomLightingDiscovery(config, false)[0],
122
+ roomEntity(config, "switch", "sleep", "Sleep", {
123
+ icon: "mdi:sleep",
124
+ command_topic: sleepCommandTopic(area),
125
+ state_topic: sleepStateTopic(area),
126
+ payload_on: "ON",
127
+ payload_off: "OFF",
128
+ optimistic: false
129
+ }),
130
+ ...(config.timesFrom === "house" ? [] : roomTimeEntities(config)),
131
+ ...targetIds.map((id) => roomEntity(config, "sensor", id + "_control", id + " control", {
132
+ icon: "mdi:account-lock-outline",
133
+ state_topic: roomControlTopic(area, id),
134
+ value_template: "{{ value_json.state }}",
135
+ json_attributes_topic: roomControlTopic(area, id),
136
+ json_attributes_template: "{{ {'owner': value_json.owner} | tojson }}",
137
+ entity_category: "diagnostic"
138
+ }))
139
+ ];
140
+ }
17
141
  // The discovery entry for the room's circadian switch, then its state.
18
- function roomLightingDiscovery(area, displayName, circadianEnabled) {
19
- const objectId = area + "_circadian_lighting";
142
+ function roomLightingDiscovery(config, circadianEnabled) {
143
+ const { area, displayName } = config;
144
+ const ids = (0, ha_discovery_1.discoveryEntity)(config, "switch", CIRCADIAN_ENTITY);
20
145
  return [
21
146
  {
22
- topic: "homeassistant/switch/" + objectId + "/config",
147
+ topic: ids.topic,
23
148
  payload: {
24
149
  name: displayName + " Circadian Lighting",
25
- unique_id: objectId,
26
- default_entity_id: "switch." + objectId,
150
+ unique_id: ids.uniqueId,
151
+ default_entity_id: ids.defaultEntityId,
27
152
  icon: "mdi:clock-time-seven-outline",
28
153
  command_topic: circadianCommandTopic(area),
29
154
  state_topic: circadianStateTopic(area),
155
+ availability_topic: roomAvailabilityTopic(area),
30
156
  payload_on: "ON",
31
157
  payload_off: "OFF",
32
158
  optimistic: false,
33
- device: {
34
- identifiers: ["nodered_" + area + "_lighting"],
35
- name: displayName + " Lighting Controller",
36
- manufacturer: "Node-RED",
37
- model: "Composable circadian lighting"
38
- }
159
+ device: roomDevice(config),
160
+ origin: ha_discovery_1.DISCOVERY_ORIGIN
39
161
  },
40
162
  retain: true
41
163
  },
@@ -0,0 +1,42 @@
1
+ import type { TraceEntry } from "./bounded-trace";
2
+ import { type IdScheme } from "./ha-discovery";
3
+ import { type RoomConfig, type RoomMessage, type RoomOutput, type RoomState } from "./room-controller";
4
+ type PublishSettings = {
5
+ area: string;
6
+ publishState?: boolean;
7
+ discovery?: boolean;
8
+ timesFrom?: TimesFrom;
9
+ };
10
+ export type TimesFrom = "room" | "house";
11
+ export interface RoomPublishingConfig {
12
+ nodeId?: string;
13
+ idScheme?: IdScheme;
14
+ timesFrom?: TimesFrom;
15
+ }
16
+ type PublishingRoomConfig = RoomConfig & RoomPublishingConfig;
17
+ export declare function roomRetainedTopics(config: PublishingRoomConfig): string[];
18
+ export declare function roomPublishesState(config: PublishSettings): boolean;
19
+ export declare function roomPublishesDiscovery(config: PublishSettings): boolean;
20
+ export declare function roomStartingOutputs(config: PublishSettings): RoomOutput[];
21
+ export declare function roomStoppingOutputs(config: PublishSettings): RoomOutput[];
22
+ export declare function roomInbound(msg: RoomMessage, config: PublishSettings): {
23
+ msg: RoomMessage;
24
+ traces: TraceEntry[];
25
+ };
26
+ export declare function publishRoom(saved: Partial<RoomState> | undefined, msg: RoomMessage, config: PublishingRoomConfig, now?: Date | string | number): {
27
+ state: RoomState;
28
+ controlChanged: string[];
29
+ status: {
30
+ circadianEnabled: boolean;
31
+ sleeping: boolean;
32
+ onCount: number;
33
+ manualCount: number;
34
+ overriddenCount: number;
35
+ control: {
36
+ [k: string]: import("./room-controller").TargetControlState;
37
+ };
38
+ };
39
+ outputs: RoomOutput[];
40
+ traces: TraceEntry<Record<string, unknown>>[];
41
+ };
42
+ export {};
@@ -0,0 +1,182 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.roomRetainedTopics = roomRetainedTopics;
4
+ exports.roomPublishesState = roomPublishesState;
5
+ exports.roomPublishesDiscovery = roomPublishesDiscovery;
6
+ exports.roomStartingOutputs = roomStartingOutputs;
7
+ exports.roomStoppingOutputs = roomStoppingOutputs;
8
+ exports.roomInbound = roomInbound;
9
+ exports.publishRoom = publishRoom;
10
+ const ha_discovery_1 = require("./ha-discovery");
11
+ const room_controller_1 = require("./room-controller");
12
+ const room_lighting_discovery_1 = require("./room-lighting-discovery");
13
+ const topic_names_1 = require("./topic-names");
14
+ function ownTimes(config) {
15
+ return config.timesFrom !== "house";
16
+ }
17
+ function targetIds(config) {
18
+ return config.targets.map((target) => target.id);
19
+ }
20
+ function discoveryConfig(config) {
21
+ return { ...config, discoveryPrefix: config.discoveryPrefix ?? ha_discovery_1.DEFAULT_DISCOVERY_PREFIX };
22
+ }
23
+ // Every retained topic the room publishes, for clearing those it no longer
24
+ // does after a change. The discovery entry counts whenever the room has an
25
+ // area, as it is published or cleared at each start.
26
+ function roomRetainedTopics(config) {
27
+ const topics = (0, topic_names_1.areaId)(config.area) ? (0, room_lighting_discovery_1.roomDiscovery)(discoveryConfig(config), targetIds(config)).map(({ topic }) => topic) : [];
28
+ if (roomPublishesState(config)) {
29
+ topics.push((0, room_lighting_discovery_1.roomAvailabilityTopic)(config.area), (0, room_lighting_discovery_1.circadianStateTopic)(config.area), (0, room_lighting_discovery_1.sleepStateTopic)(config.area));
30
+ if (ownTimes(config))
31
+ topics.push((0, room_lighting_discovery_1.scheduleStateTopic)(config.area, "wake-time"), (0, room_lighting_discovery_1.scheduleStateTopic)(config.area, "bed-time"));
32
+ topics.push(...config.targets.map((target) => (0, room_lighting_discovery_1.roomControlTopic)(config.area, target.id)));
33
+ }
34
+ return topics;
35
+ }
36
+ // Whether the room publishes state under its area, and its circadian
37
+ // switch's discovery, which reads that state.
38
+ function roomPublishesState(config) {
39
+ return config.area !== "" && config.publishState !== false;
40
+ }
41
+ function roomPublishesDiscovery(config) {
42
+ return roomPublishesState(config) && config.discovery !== false;
43
+ }
44
+ // What the room publishes as it starts and as it stops, when it publishes at
45
+ // all, so Home Assistant shows its entities as available only while it runs.
46
+ function roomStartingOutputs(config) {
47
+ return roomPublishesState(config) ? [(0, room_lighting_discovery_1.roomAvailabilityMessage)(config.area, true)] : [];
48
+ }
49
+ function roomStoppingOutputs(config) {
50
+ return roomPublishesState(config) ? [(0, room_lighting_discovery_1.roomAvailabilityMessage)(config.area, false)] : [];
51
+ }
52
+ function onOff(payload) {
53
+ const requested = typeof payload === "string" ? payload.trim().toUpperCase() : "";
54
+ return requested === "ON" ? true : requested === "OFF" ? false : null;
55
+ }
56
+ // The set topics the room reads, what each payload means as a room event,
57
+ // and the trace reason when it means nothing.
58
+ function setTopics(area, ownTimesToo) {
59
+ const topics = [
60
+ { name: "circadian-set", topic: (0, room_lighting_discovery_1.circadianCommandTopic)(area), invalid: "not-on-or-off",
61
+ event: (payload) => {
62
+ const enabled = onOff(payload);
63
+ return enabled === null ? null : { kind: "circadian", enabled };
64
+ } },
65
+ { name: "sleep-set", topic: (0, room_lighting_discovery_1.sleepCommandTopic)(area), invalid: "not-on-or-off",
66
+ event: (payload) => {
67
+ const enabled = onOff(payload);
68
+ return enabled === null ? null : { kind: "sleep", enabled };
69
+ } },
70
+ { name: "wake-time-set", topic: (0, room_lighting_discovery_1.scheduleCommandTopic)(area, "wake-time"), invalid: "not-a-time",
71
+ event: (payload) => {
72
+ const wakeTime = (0, ha_discovery_1.timeEntityValue)(payload);
73
+ return wakeTime === null ? null : { kind: "schedule", wakeTime };
74
+ } },
75
+ { name: "bed-time-set", topic: (0, room_lighting_discovery_1.scheduleCommandTopic)(area, "bed-time"), invalid: "not-a-time",
76
+ event: (payload) => {
77
+ const bedTime = (0, ha_discovery_1.timeEntityValue)(payload);
78
+ return bedTime === null ? null : { kind: "schedule", bedTime };
79
+ } }
80
+ ];
81
+ // Following the house, the room's own wake and bed set topics are not read.
82
+ return ownTimesToo ? topics : topics.filter(({ name }) => name !== "wake-time-set" && name !== "bed-time-set");
83
+ }
84
+ // MQTT the room reads, as room events: the set topics of its Home Assistant
85
+ // entities (circadian lighting and sleep, ON or OFF; wake and bed times).
86
+ // Read only while the room publishes, as the entities are only discovered
87
+ // then; a bare MQTT message, or one a flow tagged as observed, is accepted.
88
+ // Anything else passes through unchanged.
89
+ function roomInbound(msg, config) {
90
+ const event = msg.lighting || {};
91
+ const set = roomPublishesState(config) && (!event.kind || event.kind === "observed" || event.kind === "command-observed")
92
+ ? setTopics(config.area, ownTimes(config)).find(({ topic }) => topic === msg.topic)
93
+ : undefined;
94
+ if (!set)
95
+ return { msg, traces: [] };
96
+ if (msg.retain === true || event.retained === true) {
97
+ return {
98
+ msg: { ...msg, lighting: { kind: "ignored" } },
99
+ traces: [{ event: set.name, outcome: "ignored", reason: "retained-message", details: {} }]
100
+ };
101
+ }
102
+ const mapped = set.event(msg.payload);
103
+ if (mapped)
104
+ return { msg: { ...msg, lighting: mapped }, traces: [] };
105
+ return {
106
+ msg: { ...msg, lighting: { kind: "ignored" } },
107
+ traces: [{
108
+ event: set.name,
109
+ outcome: "ignored",
110
+ reason: set.invalid,
111
+ details: { payload: typeof msg.payload === "string" ? msg.payload : null }
112
+ }]
113
+ };
114
+ }
115
+ // A light's retained control state: in-control, overridden or manual.
116
+ function controlMessage(config, state, targetId) {
117
+ const entry = state.control[targetId];
118
+ return {
119
+ topic: (0, room_lighting_discovery_1.roomControlTopic)(config.area, targetId),
120
+ payload: { state: entry?.state ?? "in-control", owner: entry?.state === "overridden" ? entry.owner : null },
121
+ retain: true
122
+ };
123
+ }
124
+ // The room's transition with its MQTT side: incoming MQTT becomes room
125
+ // events, and the controller's decisions are published. At startup, the
126
+ // discovery entry (or its removal), availability and circadian state come
127
+ // first and every light's control state last; a circadian change publishes
128
+ // the circadian state before the lights are restyled; any light whose control
129
+ // state changed has it published after the commands.
130
+ function publishRoom(saved, msg, config, now) {
131
+ const inbound = roomInbound(msg, config);
132
+ const result = (0, room_controller_1.transitionRoom)(saved, inbound.msg, config, now);
133
+ const kind = inbound.msg.lighting?.kind;
134
+ const publishes = roomPublishesState(config);
135
+ const before = [];
136
+ if (kind === "startup") {
137
+ if ((0, topic_names_1.areaId)(config.area) !== "") {
138
+ // Discovery switched off: empty retained entries remove the entities
139
+ // from Home Assistant.
140
+ for (const entry of (0, room_lighting_discovery_1.roomDiscovery)(discoveryConfig(config), targetIds(config))) {
141
+ before.push(roomPublishesDiscovery(config) ? entry : { topic: entry.topic, payload: "", retain: true });
142
+ }
143
+ }
144
+ if (publishes) {
145
+ before.push((0, room_lighting_discovery_1.roomAvailabilityMessage)(config.area, true));
146
+ before.push((0, room_lighting_discovery_1.circadianStateMessage)(config.area, result.state.circadianEnabled));
147
+ before.push((0, room_lighting_discovery_1.sleepStateMessage)(config.area, result.state.sleeping));
148
+ if (ownTimes(config))
149
+ before.push(...(0, room_lighting_discovery_1.scheduleStateMessages)(config.area, result.state.schedule));
150
+ }
151
+ // Following the house, the room's own time entities and their state are
152
+ // cleared, every start, whatever was published before.
153
+ if (!ownTimes(config) && (0, topic_names_1.areaId)(config.area) !== "") {
154
+ const ownTimeTopics = [
155
+ ...(0, room_lighting_discovery_1.roomTimeDiscoveryTopics)(discoveryConfig(config)),
156
+ (0, room_lighting_discovery_1.scheduleStateTopic)(config.area, "wake-time"),
157
+ (0, room_lighting_discovery_1.scheduleStateTopic)(config.area, "bed-time")
158
+ ];
159
+ before.push(...ownTimeTopics.map((topic) => ({ topic, payload: "", retain: true })));
160
+ }
161
+ }
162
+ else if (kind === "circadian" && publishes) {
163
+ before.push((0, room_lighting_discovery_1.circadianStateMessage)(config.area, result.state.circadianEnabled));
164
+ }
165
+ else if (kind === "sleep" && publishes) {
166
+ before.push((0, room_lighting_discovery_1.sleepStateMessage)(config.area, result.state.sleeping));
167
+ }
168
+ else if (kind === "schedule" && publishes && ownTimes(config)) {
169
+ before.push(...(0, room_lighting_discovery_1.scheduleStateMessages)(config.area, result.state.schedule));
170
+ }
171
+ const controls = publishes
172
+ ? config.targets
173
+ .filter((target) => kind === "startup" || result.controlChanged.includes(target.id))
174
+ .map((target) => controlMessage(config, result.state, target.id))
175
+ : [];
176
+ return {
177
+ ...result,
178
+ outputs: [...before, ...result.outputs, ...controls],
179
+ traces: [...inbound.traces, ...result.traces]
180
+ };
181
+ }
182
+ //# sourceMappingURL=room-publishing.js.map
@@ -0,0 +1,8 @@
1
+ import { type DaySchedule } from "./circadian-schedule";
2
+ import type { RoomConfig, RoomState } from "./room-controller";
3
+ export declare function savedSchedule(config: RoomConfig, saved: Partial<RoomState>): Pick<RoomState, "schedule" | "scheduleSetting">;
4
+ export declare function withActiveSchedule(config: RoomConfig, state: RoomState): RoomConfig;
5
+ export declare function requestedSchedule(current: DaySchedule, event: {
6
+ wakeTime?: unknown;
7
+ bedTime?: unknown;
8
+ }): DaySchedule | null;