@avantics/node-red-home-automation 2.3.0 → 3.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 (79) hide show
  1. package/README.md +32 -8
  2. package/contract-examples/room-lighting.mjs +12 -7
  3. package/dist/lib/activity-lighting-controller.d.ts +13 -25
  4. package/dist/lib/activity-lighting-controller.js +15 -11
  5. package/dist/lib/avr-controller.d.ts +13 -47
  6. package/dist/lib/avr-controller.js +39 -90
  7. package/dist/lib/backlighting-controller.d.ts +12 -25
  8. package/dist/lib/backlighting-controller.js +11 -18
  9. package/dist/lib/bounded-trace.d.ts +6 -0
  10. package/dist/lib/command-echo.d.ts +20 -0
  11. package/dist/lib/command-echo.js +82 -0
  12. package/dist/lib/cover-controller.d.ts +15 -28
  13. package/dist/lib/cover-controller.js +6 -8
  14. package/dist/lib/denon-protocol.d.ts +29 -0
  15. package/dist/lib/denon-protocol.js +76 -0
  16. package/dist/lib/display-mode-controller.d.ts +7 -18
  17. package/dist/lib/display-mode-controller.js +39 -47
  18. package/dist/lib/motion-policy.d.ts +12 -22
  19. package/dist/lib/motion-policy.js +53 -56
  20. package/dist/lib/occupancy-fusion.d.ts +8 -12
  21. package/dist/lib/room-controller.d.ts +14 -34
  22. package/dist/lib/room-controller.js +80 -132
  23. package/dist/lib/room-lighting-discovery.d.ts +9 -0
  24. package/dist/lib/room-lighting-discovery.js +45 -0
  25. package/dist/lib/settings.d.ts +5 -0
  26. package/dist/lib/settings.js +68 -0
  27. package/dist/lib/source-capability-controller.d.ts +30 -35
  28. package/dist/lib/source-capability-controller.js +35 -36
  29. package/dist/lib/switch-policy.d.ts +2 -7
  30. package/dist/lib/target-state.d.ts +24 -0
  31. package/dist/lib/target-state.js +38 -0
  32. package/dist/lib/theatre-activity-controller.d.ts +6 -108
  33. package/dist/lib/theatre-activity-controller.js +67 -318
  34. package/dist/lib/theatre-ha-discovery.d.ts +14 -0
  35. package/dist/lib/theatre-ha-discovery.js +163 -0
  36. package/dist/lib/theatre-metrics.d.ts +4 -0
  37. package/dist/lib/theatre-metrics.js +66 -0
  38. package/dist/lib/theatre-profiles.d.ts +23 -0
  39. package/dist/lib/theatre-profiles.js +73 -0
  40. package/dist/lib/theatre-refresh.d.ts +20 -0
  41. package/dist/lib/theatre-refresh.js +46 -0
  42. package/dist/lib/theatre-slo.js +7 -9
  43. package/dist/lib/theatre-state-contract.d.ts +7 -19
  44. package/dist/lib/theatre-state-contract.js +33 -169
  45. package/dist/lib/theatre-state.d.ts +110 -0
  46. package/dist/lib/theatre-state.js +139 -0
  47. package/dist/lib/wall-input.d.ts +2 -7
  48. package/dist/lib/z2m-light.d.ts +16 -0
  49. package/dist/lib/z2m-light.js +36 -0
  50. package/dist/nodes/activity-lighting-controller.html +5 -3
  51. package/dist/nodes/activity-lighting-controller.js +21 -52
  52. package/dist/nodes/adapter.d.ts +15 -0
  53. package/dist/nodes/adapter.js +60 -0
  54. package/dist/nodes/avr-controller.html +3 -3
  55. package/dist/nodes/avr-controller.js +17 -56
  56. package/dist/nodes/backlighting-controller.html +1 -1
  57. package/dist/nodes/backlighting-controller.js +25 -47
  58. package/dist/nodes/display-mode-controller.html +2 -2
  59. package/dist/nodes/display-mode-controller.js +19 -57
  60. package/dist/nodes/motion-policy.html +23 -10
  61. package/dist/nodes/motion-policy.js +14 -135
  62. package/dist/nodes/occupancy-fusion.html +2 -2
  63. package/dist/nodes/occupancy-fusion.js +23 -29
  64. package/dist/nodes/room-controller.html +80 -26
  65. package/dist/nodes/room-controller.js +37 -54
  66. package/dist/nodes/source-capability-controller.html +4 -13
  67. package/dist/nodes/source-capability-controller.js +17 -52
  68. package/dist/nodes/switch-policy.html +3 -3
  69. package/dist/nodes/switch-policy.js +23 -42
  70. package/dist/nodes/theatre-activity-controller.html +4 -2
  71. package/dist/nodes/theatre-activity-controller.js +18 -45
  72. package/dist/nodes/theatre-state-contract.html +55 -22
  73. package/dist/nodes/theatre-state-contract.js +30 -41
  74. package/examples/Home theatre activity.json +13 -12
  75. package/examples/Home theatre equipment.json +4 -4
  76. package/examples/Room lighting.json +9 -9
  77. package/package.json +1 -1
  78. package/dist/lib/circadian-refresh.d.ts +0 -7
  79. package/dist/lib/circadian-refresh.js +0 -11
@@ -1,10 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.booleanOn = booleanOn;
4
+ exports.normaliseMotionConfig = normaliseMotionConfig;
4
5
  exports.createMotionState = createMotionState;
5
6
  exports.lightingIntent = lightingIntent;
6
7
  exports.transitionMotion = transitionMotion;
7
- const wall_input_1 = require("./wall-input");
8
+ const settings_1 = require("./settings");
8
9
  function booleanOn(value) {
9
10
  return value === true || (typeof value === "string" && value.toLowerCase() === "on");
10
11
  }
@@ -12,22 +13,48 @@ function finiteNumber(value) {
12
13
  const number = Number(value);
13
14
  return Number.isFinite(number) ? number : null;
14
15
  }
16
+ // A JSON array of target names from the editor, or the fallback when the
17
+ // setting is absent from an older saved flow.
18
+ function targetList(value, label, fallback) {
19
+ const parsed = (0, settings_1.jsonSetting)(value, label, fallback);
20
+ if (!Array.isArray(parsed) || parsed.some((item) => typeof item !== "string")) {
21
+ throw new Error(`${label} must be a JSON array of strings`);
22
+ }
23
+ return parsed;
24
+ }
25
+ // The motion policy's settings from a node's editor values: on targets
26
+ // default to ["main"] and off targets to the on targets; the vacancy delay
27
+ // (120 s) and illuminance cutoff (10) take their defaults only when absent
28
+ // from an older saved flow. Throws on settings it cannot use.
29
+ function normaliseMotionConfig(raw) {
30
+ const onTargets = targetList(raw.onTargets, "on targets", ["main"]);
31
+ return {
32
+ onTargets,
33
+ offTargets: targetList(raw.offTargets, "off targets", onTargets),
34
+ defaultDelaySeconds: (0, settings_1.numberSetting)(raw.defaultDelaySeconds, "vacancy delay", 120),
35
+ defaultIlluminanceCutoff: (0, settings_1.numberSetting)(raw.defaultIlluminanceCutoff, "illuminance cutoff", 10)
36
+ };
37
+ }
38
+ // Saved wall-switch state from earlier versions (wallInput and the older
39
+ // switch* fields) is not read.
15
40
  function createMotionState(config, saved = {}) {
16
- const legacy = saved;
17
41
  return {
18
42
  areaEnabled: saved.areaEnabled !== false,
19
43
  illuminance: saved.illuminance ?? null,
20
- illuminanceCutoff: saved.illuminanceCutoff ?? config.defaultIlluminanceCutoff,
21
- delaySeconds: saved.delaySeconds ?? config.defaultDelaySeconds,
22
- wallInput: (0, wall_input_1.createWallInputState)(saved.wallInput ?? {
23
- baselineKnown: legacy.switchStateKnown,
24
- value: legacy.switchState === true,
25
- generation: legacy.switchGeneration,
26
- edgeAt: legacy.switchAt,
27
- timerDueAt: legacy.switchTimerDueAt
28
- }),
44
+ // A saved value stands only while the setting it was based on is
45
+ // unchanged; state saved before this rule recorded none, so the setting
46
+ // applies.
47
+ illuminanceCutoff: saved.illuminanceCutoffSetting === config.defaultIlluminanceCutoff && saved.illuminanceCutoff !== undefined
48
+ ? saved.illuminanceCutoff
49
+ : config.defaultIlluminanceCutoff,
50
+ delaySeconds: saved.delaySecondsSetting === config.defaultDelaySeconds && saved.delaySeconds !== undefined
51
+ ? saved.delaySeconds
52
+ : config.defaultDelaySeconds,
53
+ illuminanceCutoffSetting: config.defaultIlluminanceCutoff,
54
+ delaySecondsSetting: config.defaultDelaySeconds,
29
55
  offTimerGeneration: Number(saved.offTimerGeneration) || 0,
30
- offTimerDueAt: Number(saved.offTimerDueAt) || null
56
+ offTimerDueAt: Number(saved.offTimerDueAt) || null,
57
+ offTimerArmedAt: Number(saved.offTimerArmedAt) || null
31
58
  };
32
59
  }
33
60
  function lightingIntent(targets, state, source, extra = {}) {
@@ -56,6 +83,7 @@ function transitionMotion(saved, input, config, globalEnabled, now = Date.now())
56
83
  const wasActive = Number(state.offTimerDueAt) > now;
57
84
  state.offTimerGeneration += 1;
58
85
  state.offTimerDueAt = null;
86
+ state.offTimerArmedAt = null;
59
87
  effects.push({ kind: "cancel-off-timer" });
60
88
  if (wasActive && reason)
61
89
  trace("off-timer", "cancelled", reason);
@@ -63,6 +91,7 @@ function transitionMotion(saved, input, config, globalEnabled, now = Date.now())
63
91
  function scheduleOffTimer() {
64
92
  cancelOffTimer("rescheduled");
65
93
  const delayMs = Math.max(0, state.delaySeconds) * 1000;
94
+ state.offTimerArmedAt = now;
66
95
  state.offTimerDueAt = now + delayMs;
67
96
  effects.push({
68
97
  kind: "schedule-off-timer",
@@ -104,9 +133,10 @@ function transitionMotion(saved, input, config, globalEnabled, now = Date.now())
104
133
  cancelOffTimer("motion-disabled");
105
134
  }
106
135
  else if (source === "delay") {
107
- const minutes = finiteNumber(payload);
108
- if (minutes !== null)
109
- state.delaySeconds = minutes * 60;
136
+ // Seconds, the same unit as the vacancy setting.
137
+ const seconds = finiteNumber(payload);
138
+ if (seconds !== null)
139
+ state.delaySeconds = seconds;
110
140
  }
111
141
  else if (source === "illuminance-cut-off") {
112
142
  const cutoff = finiteNumber(payload);
@@ -192,48 +222,16 @@ function transitionMotion(saved, input, config, globalEnabled, now = Date.now())
192
222
  });
193
223
  }
194
224
  else {
225
+ // vacantSince lets the room controller keep a light a person set after
226
+ // the room went vacant.
227
+ const vacantSince = new Date(state.offTimerArmedAt ?? now).toISOString();
195
228
  state.offTimerDueAt = null;
196
- emitIntent(lightingIntent(config.offTargets, "OFF", "motion"), "off-timer");
229
+ state.offTimerArmedAt = null;
230
+ emitIntent(lightingIntent(config.offTargets, "OFF", "motion", { vacantSince }), "off-timer");
197
231
  }
198
232
  }
199
- else if (source === "switch-startup" ||
200
- source === "switch" ||
201
- source === "switch-availability" ||
202
- source === "switch-timer") {
203
- const wallInput = (0, wall_input_1.transitionWallInput)(state.wallInput, source === "switch-startup"
204
- ? { kind: "startup" }
205
- : source === "switch"
206
- ? {
207
- kind: "observation",
208
- payload,
209
- retain: input.retain,
210
- baseline: input.baseline,
211
- observedAt: input.observedAt
212
- }
213
- : source === "switch-availability"
214
- ? { kind: "availability", payload }
215
- : {
216
- kind: "timer",
217
- generation: input.generation,
218
- edgeAt: input.switchAt
219
- }, config, now);
220
- state.wallInput = wallInput.state;
221
- effects.push(...wallInput.effects);
222
- traces.push(...wallInput.traces);
223
- const startedGesture = source === "switch" && (wallInput.gesture === "double" ||
224
- wallInput.effects.some((effect) => effect.kind === "schedule-switch-timer"));
225
- if (startedGesture)
226
- cancelOffTimer("wall-switch");
227
- if (wallInput.gesture === "single") {
228
- emitIntent(lightingIntent(config.onTargets, "TOGGLE", "wall", { person: true }), "switch");
229
- }
230
- else if (wallInput.gesture === "double") {
231
- emitIntent(lightingIntent(config.onTargets, "ON", "wall", {
232
- person: true,
233
- manual: true,
234
- values: { brightness: 254 }
235
- }), "switch");
236
- }
233
+ else if (source.startsWith("switch")) {
234
+ trace("message", "ignored", "wall switches belong to the switch policy", { source });
237
235
  }
238
236
  return {
239
237
  state,
@@ -243,8 +241,7 @@ function transitionMotion(saved, input, config, globalEnabled, now = Date.now())
243
241
  status: {
244
242
  enabled: enabled(),
245
243
  illuminance: state.illuminance,
246
- delaySeconds: state.delaySeconds,
247
- switch: (0, wall_input_1.wallInputStatus)(state.wallInput, config.switchFreshnessMs, now)
244
+ delaySeconds: state.delaySeconds
248
245
  }
249
246
  };
250
247
  }
@@ -1,3 +1,4 @@
1
+ import type { TraceEntry } from "./bounded-trace";
1
2
  export type OccupancySource = "motion" | "presence";
2
3
  export interface OccupancyState {
3
4
  motionKnown: boolean;
@@ -26,19 +27,14 @@ export interface OccupancyOutput {
26
27
  };
27
28
  };
28
29
  }
29
- export interface OccupancyTrace {
30
- event: string;
31
- outcome: string;
32
- reason: string | null;
33
- details: {
34
- active: boolean | null;
35
- occupied: boolean;
36
- sources: {
37
- motion: boolean | null;
38
- presence: boolean | null;
39
- };
30
+ export type OccupancyTrace = TraceEntry<{
31
+ active: boolean | null;
32
+ occupied: boolean;
33
+ sources: {
34
+ motion: boolean | null;
35
+ presence: boolean | null;
40
36
  };
41
- }
37
+ }>;
42
38
  export declare function booleanState(value: unknown, source: OccupancySource): boolean | null;
43
39
  export declare function createOccupancyState(saved?: Partial<OccupancyState>): OccupancyState;
44
40
  export declare function transitionOccupancy(saved: Partial<OccupancyState> | undefined, input: OccupancyInput, config: OccupancyConfig): {
@@ -1,37 +1,27 @@
1
- import { type CircadianLighting } from "./circadian";
2
- import type { LightLevels } from "./light-styling";
1
+ import type { TraceEntry } from "./bounded-trace";
2
+ import type { CircadianLighting } from "./circadian";
3
+ import { type LightCommand, type LightReport } from "./z2m-light";
4
+ import { type ExpectedCommand } from "./command-echo";
5
+ export { fingerprint, parsePayload, type ExpectedCommand } from "./command-echo";
3
6
  export interface RoomTarget {
4
7
  id: string;
5
8
  stateTopic: string;
6
9
  commandTopic: string;
7
10
  }
8
- export interface RoomConfig extends LightLevels {
11
+ export interface RoomConfig {
9
12
  area: string;
10
13
  displayName: string;
11
14
  targets: RoomTarget[];
12
15
  initialSleep: boolean;
13
- sleepBrightnessPct: number;
14
- maxBrightnessPct: number;
15
- sleepColorTempKelvin: number;
16
- maxColorTempKelvin: number;
16
+ publishState?: boolean;
17
+ discovery?: boolean;
17
18
  refreshTransitionSeconds: number;
18
19
  initialTransitionSeconds: number;
19
- wakeTime?: string;
20
- bedTime?: string;
21
- lighting?: CircadianLighting;
20
+ lighting: CircadianLighting;
22
21
  }
23
- export interface RoomObservation {
24
- on: boolean;
25
- brightness: unknown;
26
- color_temp: unknown;
22
+ export interface RoomObservation extends LightReport {
27
23
  observedAt: string;
28
24
  }
29
- export interface ExpectedCommand {
30
- fingerprint: string;
31
- expires: number;
32
- on?: boolean;
33
- echoed?: boolean;
34
- }
35
25
  export type TargetControlState = "in-control" | "overridden" | "manual";
36
26
  export type TargetControl = {
37
27
  state: "manual";
@@ -46,6 +36,7 @@ export interface RoomState {
46
36
  expected: Record<string, ExpectedCommand[]>;
47
37
  circadianEnabled: boolean;
48
38
  sleeping: boolean;
39
+ personAt: Record<string, number>;
49
40
  }
50
41
  export interface LightingEvent {
51
42
  kind?: string;
@@ -63,6 +54,7 @@ export interface LightingEvent {
63
54
  refresh?: boolean;
64
55
  retained?: boolean;
65
56
  enabled?: boolean;
57
+ vacantSince?: string;
66
58
  }
67
59
  export interface RoomMessage {
68
60
  lighting?: LightingEvent;
@@ -80,26 +72,14 @@ export interface RoomOutput {
80
72
  source: string;
81
73
  };
82
74
  }
83
- export declare function parsePayload(payload: unknown): unknown;
84
- export declare function fingerprint(payload: unknown): string;
85
75
  export declare function createRoomState(config: RoomConfig, saved?: Partial<RoomState> & {
86
76
  manual?: Record<string, boolean>;
87
77
  }): RoomState;
88
- export declare function adaptivePayload(lightState: string, isRefresh: boolean, sleeping: boolean, now: Date, config: RoomConfig): {
89
- state: string;
90
- brightness?: number;
91
- color_temp?: number;
92
- transition?: number;
93
- };
78
+ export declare function adaptivePayload(lightState: string, isRefresh: boolean, sleeping: boolean, now: Date, config: RoomConfig): LightCommand;
94
79
  export declare function transitionRoom(saved: Partial<RoomState> | undefined, msg: RoomMessage, config: RoomConfig, nowValue?: Date | string | number): {
95
80
  state: RoomState;
96
81
  outputs: RoomOutput[];
97
- traces: {
98
- event: string;
99
- outcome: string;
100
- reason: string | null;
101
- details: Record<string, unknown>;
102
- }[];
82
+ traces: TraceEntry<Record<string, unknown>>[];
103
83
  status: {
104
84
  circadianEnabled: boolean;
105
85
  sleeping: boolean;
@@ -1,35 +1,15 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.parsePayload = parsePayload;
4
- exports.fingerprint = fingerprint;
3
+ exports.parsePayload = exports.fingerprint = void 0;
5
4
  exports.createRoomState = createRoomState;
6
5
  exports.adaptivePayload = adaptivePayload;
7
6
  exports.transitionRoom = transitionRoom;
8
- const circadian_1 = require("./circadian");
9
- const circadian_refresh_1 = require("./circadian-refresh");
10
- const circadian_schedule_1 = require("./circadian-schedule");
11
- function parsePayload(payload) {
12
- if (typeof payload !== "string")
13
- return payload;
14
- try {
15
- return JSON.parse(payload);
16
- }
17
- catch {
18
- return payload;
19
- }
20
- }
21
- function stable(value) {
22
- if (Array.isArray(value))
23
- return value.map(stable);
24
- if (value && typeof value === "object") {
25
- const record = value;
26
- return Object.fromEntries(Object.keys(record).sort().map((key) => [key, stable(record[key])]));
27
- }
28
- return value;
29
- }
30
- function fingerprint(payload) {
31
- return JSON.stringify(stable(payload));
32
- }
7
+ const z2m_light_1 = require("./z2m-light");
8
+ const room_lighting_discovery_1 = require("./room-lighting-discovery");
9
+ const command_echo_1 = require("./command-echo");
10
+ var command_echo_2 = require("./command-echo");
11
+ Object.defineProperty(exports, "fingerprint", { enumerable: true, get: function () { return command_echo_2.fingerprint; } });
12
+ Object.defineProperty(exports, "parsePayload", { enumerable: true, get: function () { return command_echo_2.parsePayload; } });
33
13
  function savedControl(saved) {
34
14
  if (saved.control) {
35
15
  return Object.fromEntries(Object.entries(saved.control).map(([target, entry]) => [target, { ...entry }]));
@@ -46,23 +26,16 @@ function createRoomState(config, saved = {}) {
46
26
  control: savedControl(saved),
47
27
  expected: Object.fromEntries(Object.entries(saved.expected || {}).map(([target, entries]) => [target, entries.map((entry) => ({ ...entry }))])),
48
28
  circadianEnabled: saved.circadianEnabled !== false,
49
- sleeping: saved.sleeping === undefined ? config.initialSleep : saved.sleeping === true
29
+ sleeping: saved.sleeping === undefined ? config.initialSleep : saved.sleeping === true,
30
+ personAt: Object.fromEntries(Object.entries(saved.personAt || {})
31
+ .filter(([, at]) => Number.isFinite(at)))
50
32
  };
51
33
  }
52
- // The circadian lighting a room uses: the one passed in, or the wake and bed
53
- // schedule from its configuration.
54
- function lightingFor(config) {
55
- return config.lighting ?? (0, circadian_1.scheduledLighting)((0, circadian_schedule_1.resolveSchedule)(config.wakeTime, config.bedTime), config);
56
- }
57
34
  // A circadian light command for this moment.
58
35
  function adaptivePayload(lightState, isRefresh, sleeping, now, config) {
59
36
  if (lightState === "OFF")
60
37
  return { state: lightState };
61
- return {
62
- state: lightState,
63
- ...lightingFor(config).styleAt(now, sleeping),
64
- transition: isRefresh ? config.refreshTransitionSeconds : config.initialTransitionSeconds
65
- };
38
+ return (0, z2m_light_1.lightCommand)(lightState, config.lighting.styleAt(now, sleeping), isRefresh ? config.refreshTransitionSeconds : config.initialTransitionSeconds);
66
39
  }
67
40
  function transitionRoom(saved, msg, config, nowValue = new Date()) {
68
41
  const now = nowValue instanceof Date ? nowValue : new Date(nowValue);
@@ -110,34 +83,11 @@ function transitionRoom(saved, msg, config, nowValue = new Date()) {
110
83
  return state.desired[targetId] === true;
111
84
  return state.observed[targetId]?.on === true;
112
85
  }
113
- function rememberExpected(targetId, payload) {
114
- const queue = (state.expected[targetId] || []).filter((entry) => entry.expires > nowMs);
115
- const entry = { fingerprint: fingerprint(payload), expires: nowMs + 5000 };
116
- const requested = payload && typeof payload === "object"
117
- ? String(payload.state || "").toUpperCase()
118
- : "";
119
- if (requested === "ON" || requested === "OFF")
120
- entry.on = requested === "ON";
121
- queue.push(entry);
122
- state.expected[targetId] = queue.slice(-8);
123
- }
124
- // Whether a state report is stale against the controller's own command in
125
- // flight. A report that matches the newest unconfirmed command confirms it.
126
- function contradictsOwnCommand(targetId, observedOn) {
127
- const queue = (state.expected[targetId] || []).filter((entry) => entry.expires > nowMs);
128
- const latest = queue.filter((entry) => entry.on !== undefined).at(-1);
129
- if (latest && latest.on === observedOn) {
130
- for (const entry of queue)
131
- delete entry.on;
132
- }
133
- state.expected[targetId] = queue.filter((entry) => entry.on !== undefined || entry.echoed !== true);
134
- return latest !== undefined && latest.on !== observedOn;
135
- }
136
86
  function command(targetId, payload, source) {
137
87
  const target = targetById[targetId];
138
88
  if (!target)
139
89
  return null;
140
- rememberExpected(targetId, payload);
90
+ state.expected[targetId] = (0, command_echo_1.rememberCommand)(state.expected[targetId], payload, nowMs);
141
91
  return {
142
92
  topic: target.commandTopic,
143
93
  payload,
@@ -145,37 +95,11 @@ function transitionRoom(saved, msg, config, nowValue = new Date()) {
145
95
  lighting_command: { area: config.area, target: targetId, source }
146
96
  };
147
97
  }
148
- function discoveryMessages() {
149
- const objectId = config.area + "_circadian_lighting";
150
- return [
151
- {
152
- topic: "homeassistant/switch/" + objectId + "/config",
153
- payload: {
154
- name: config.displayName + " Circadian Lighting",
155
- unique_id: objectId,
156
- default_entity_id: "switch." + objectId,
157
- icon: "mdi:clock-time-seven-outline",
158
- command_topic: "home/" + config.area + "/circadian/set",
159
- state_topic: "home/" + config.area + "/circadian/state",
160
- payload_on: "ON",
161
- payload_off: "OFF",
162
- optimistic: false,
163
- device: {
164
- identifiers: ["nodered_" + config.area + "_lighting"],
165
- name: config.displayName + " Lighting Controller",
166
- manufacturer: "Node-RED",
167
- model: "Composable circadian lighting"
168
- }
169
- },
170
- retain: true
171
- },
172
- {
173
- topic: "home/" + config.area + "/circadian/state",
174
- payload: state.circadianEnabled ? "ON" : "OFF",
175
- retain: true
176
- }
177
- ];
178
- }
98
+ // What the room publishes for MQTT and Home Assistant to see is named after
99
+ // its area, so it needs one, and is switched on by its settings; light
100
+ // control depends on neither.
101
+ const publishesArea = config.area !== "" && config.publishState !== false;
102
+ const publishesDiscovery = publishesArea && config.discovery !== false;
179
103
  function refreshCommands(source) {
180
104
  if (!state.circadianEnabled)
181
105
  return [];
@@ -184,7 +108,7 @@ function transitionRoom(saved, msg, config, nowValue = new Date()) {
184
108
  if (!intendedOn(target.id) || controlOf(target.id) !== "in-control")
185
109
  continue;
186
110
  // Nothing to change when the light last reported exactly this style.
187
- if ((0, circadian_refresh_1.alreadyStyled)(lightingFor(config).styleAt(now, state.sleeping), state.observed[target.id])) {
111
+ if ((0, z2m_light_1.alreadyStyled)(config.lighting.styleAt(now, state.sleeping), state.observed[target.id])) {
188
112
  trace("refresh", "skipped", "already-at-level", { target: target.id });
189
113
  continue;
190
114
  }
@@ -216,6 +140,16 @@ function transitionRoom(saved, msg, config, nowValue = new Date()) {
216
140
  }
217
141
  const wasOn = intendedOn(targetId);
218
142
  const resolvedState = requestedState === "TOGGLE" ? (wasOn ? "OFF" : "ON") : requestedState;
143
+ // Motion switches off a vacant room, but not a light a person set after
144
+ // the room went vacant: they are using it.
145
+ const vacantSince = typeof event.vacantSince === "string" ? Date.parse(event.vacantSince) : NaN;
146
+ if (event.source === "motion" && resolvedState === "OFF" && Number.isFinite(vacantSince) &&
147
+ (state.personAt[targetId] ?? -Infinity) >= vacantSince) {
148
+ trace("intent", "ignored", "person-set-after-vacancy", { target: targetId, vacantSince: event.vacantSince });
149
+ continue;
150
+ }
151
+ if (person)
152
+ state.personAt[targetId] = now.getTime();
219
153
  if (event.updateOnOnly === true && !wasOn)
220
154
  continue;
221
155
  if (event.updateOffOnly === true && wasOn)
@@ -253,33 +187,63 @@ function transitionRoom(saved, msg, config, nowValue = new Date()) {
253
187
  }
254
188
  return commands.filter((entry) => entry !== null);
255
189
  }
256
- const event = msg.lighting || {};
190
+ let event = msg.lighting || {};
191
+ // The circadian switch's set topic: Home Assistant sends ON or OFF there.
192
+ // Read only while the room publishes, as the switch is only discovered then;
193
+ // a bare MQTT message, or one a flow tagged as observed, is accepted.
194
+ if (publishesArea && msg.topic === (0, room_lighting_discovery_1.circadianCommandTopic)(config.area) &&
195
+ (!event.kind || event.kind === "observed" || event.kind === "command-observed")) {
196
+ const requested = typeof msg.payload === "string" ? msg.payload.trim().toUpperCase() : "";
197
+ if (msg.retain === true || event.retained === true) {
198
+ trace("circadian-set", "ignored", "retained-message");
199
+ event = { kind: "ignored" };
200
+ }
201
+ else if (requested === "ON" || requested === "OFF") {
202
+ event = { kind: "circadian", enabled: requested === "ON" };
203
+ }
204
+ else {
205
+ trace("circadian-set", "ignored", "not-on-or-off", { payload: typeof msg.payload === "string" ? msg.payload : null });
206
+ event = { kind: "ignored" };
207
+ }
208
+ }
257
209
  if (event.kind === "startup") {
258
- outputs.push(...discoveryMessages());
210
+ if (config.area !== "") {
211
+ const entry = (0, room_lighting_discovery_1.roomLightingDiscovery)(config.area, config.displayName, state.circadianEnabled)[0];
212
+ // Discovery switched off: an empty retained entry removes the switch
213
+ // from Home Assistant.
214
+ outputs.push(publishesDiscovery ? entry : { topic: entry.topic, payload: "", retain: true });
215
+ }
216
+ if (publishesArea)
217
+ outputs.push((0, room_lighting_discovery_1.circadianStateMessage)(config.area, state.circadianEnabled));
259
218
  for (const target of config.targets)
260
219
  controlChanged.add(target.id);
261
220
  }
262
221
  else if (event.kind === "observed") {
263
222
  const target = event.target ? targetById[event.target] : targetForTopic(msg.topic, "stateTopic");
264
- const parsed = parsePayload(msg.payload);
223
+ const parsed = (0, command_echo_1.parsePayload)(msg.payload);
265
224
  const payload = parsed && typeof parsed === "object" ? parsed : null;
266
- if (target && payload && ["ON", "OFF"].includes(String(payload.state).toUpperCase())) {
225
+ const light = payload ? (0, z2m_light_1.readLightReport)(payload) : null;
226
+ if (target && light) {
267
227
  const previousOn = state.observed[target.id]?.on;
268
- const nextOn = String(payload.state).toUpperCase() === "ON";
269
- state.observed[target.id] = {
270
- on: nextOn,
271
- brightness: payload.brightness ?? null,
272
- color_temp: payload.color_temp ?? null,
273
- observedAt: now.toISOString()
274
- };
228
+ const nextOn = light.on;
229
+ state.observed[target.id] = { ...light, observedAt: now.toISOString() };
275
230
  if (previousOn !== nextOn) {
276
231
  trace("state-observed", "changed", null, {
277
232
  target: target.id,
278
233
  state: nextOn ? "ON" : "OFF"
279
234
  });
280
235
  }
281
- if (contradictsOwnCommand(target.id, nextOn)) {
282
- trace("state-observed", "ignored", "own-command-in-flight", { target: target.id, state: nextOn ? "ON" : "OFF" });
236
+ const report = (0, command_echo_1.checkStateReport)(state.expected[target.id], nextOn, nowMs);
237
+ state.expected[target.id] = report.queue;
238
+ if (report.verdict === "confirms") {
239
+ // Our own command, now done: the intended state already says so.
240
+ // A confirmed OFF deliberately leaves control alone: our OFFs come
241
+ // from OFF intents, which already returned the light to in-control.
242
+ trace("state-observed", "confirmed", "own-command", { target: target.id, state: nextOn ? "ON" : "OFF" });
243
+ }
244
+ else if (report.verdict === "stale") {
245
+ // Older than our pending command; the light will report again.
246
+ trace("state-observed", "ignored", "stale-report", { target: target.id, state: nextOn ? "ON" : "OFF" });
283
247
  }
284
248
  else {
285
249
  // A change the controller didn't cause becomes the intended state.
@@ -291,34 +255,20 @@ function transitionRoom(saved, msg, config, nowValue = new Date()) {
291
255
  }
292
256
  else if (event.kind === "command-observed") {
293
257
  const target = event.target ? targetById[event.target] : targetForTopic(msg.topic, "commandTopic");
294
- const parsed = parsePayload(msg.payload);
258
+ const parsed = (0, command_echo_1.parsePayload)(msg.payload);
295
259
  const payload = parsed && typeof parsed === "object" ? parsed : null;
296
260
  if (msg.retain !== true && event.retained !== true && target && payload) {
297
- const queue = (state.expected[target.id] || []).filter((entry) => entry.expires > nowMs);
298
- const ownIndex = queue.findIndex((entry) => entry.echoed !== true && entry.fingerprint === fingerprint(payload));
299
- const own = queue[ownIndex];
300
- if (own) {
301
- // Keep an unconfirmed power command as in flight for state reports.
302
- if (own.on === undefined)
303
- queue.splice(ownIndex, 1);
304
- else
305
- own.echoed = true;
306
- state.expected[target.id] = queue;
307
- }
308
- else {
309
- state.expected[target.id] = queue;
261
+ const echo = (0, command_echo_1.checkCommandEcho)(state.expected[target.id], payload, nowMs);
262
+ state.expected[target.id] = echo.queue;
263
+ if (!echo.own) {
310
264
  const requestedState = String(payload.state || "").toUpperCase();
311
- const fields = [
312
- "brightness", "brightness_percent", "color", "color_temp", "color_temp_kelvin",
313
- "effect", "hue", "saturation", "x", "y"
314
- ];
315
265
  if (requestedState === "OFF") {
316
266
  state.desired[target.id] = false;
317
267
  setControl(target.id, null, "external-off");
318
268
  }
319
269
  else if (requestedState === "ON") {
320
270
  state.desired[target.id] = true;
321
- if (fields.some((field) => Object.hasOwn(payload, field))) {
271
+ if ((0, z2m_light_1.setsLightValues)(payload)) {
322
272
  setControl(target.id, { state: "manual" }, "external-values");
323
273
  }
324
274
  else if (state.circadianEnabled && controlOf(target.id) === "in-control") {
@@ -330,6 +280,7 @@ function transitionRoom(saved, msg, config, nowValue = new Date()) {
330
280
  else if (requestedState === "TOGGLE") {
331
281
  state.desired[target.id] = !intendedOn(target.id);
332
282
  }
283
+ state.personAt[target.id] = now.getTime();
333
284
  trace("external-command", "observed", null, {
334
285
  target: target.id,
335
286
  state: requestedState || "UNKNOWN",
@@ -344,11 +295,8 @@ function transitionRoom(saved, msg, config, nowValue = new Date()) {
344
295
  if (previous !== state.circadianEnabled) {
345
296
  trace("circadian", "changed", null, { enabled: state.circadianEnabled });
346
297
  }
347
- outputs.push({
348
- topic: "home/" + config.area + "/circadian/state",
349
- payload: state.circadianEnabled ? "ON" : "OFF",
350
- retain: true
351
- });
298
+ if (publishesArea)
299
+ outputs.push((0, room_lighting_discovery_1.circadianStateMessage)(config.area, state.circadianEnabled));
352
300
  if (state.circadianEnabled) {
353
301
  // Enabling circadian takes back manual lights; other owners keep theirs.
354
302
  for (const target of config.targets) {
@@ -407,7 +355,7 @@ function transitionRoom(saved, msg, config, nowValue = new Date()) {
407
355
  });
408
356
  }
409
357
  for (const target of config.targets) {
410
- if (controlChanged.has(target.id))
358
+ if (publishesArea && controlChanged.has(target.id))
411
359
  outputs.push(controlMessage(target.id));
412
360
  }
413
361
  const onCount = Object.values(state.desired).filter(Boolean).length;
@@ -0,0 +1,9 @@
1
+ export interface DiscoveryMessage {
2
+ topic: string;
3
+ payload: unknown;
4
+ retain: boolean;
5
+ }
6
+ export declare function circadianStateTopic(area: string): string;
7
+ export declare function circadianCommandTopic(area: string): string;
8
+ export declare function circadianStateMessage(area: string, enabled: boolean): DiscoveryMessage;
9
+ export declare function roomLightingDiscovery(area: string, displayName: string, circadianEnabled: boolean): DiscoveryMessage[];