@avantics/node-red-home-automation 0.0.0-stage → 2.3.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/LICENSE +21 -0
  2. package/README.md +292 -2
  3. package/contract-examples/README.md +28 -0
  4. package/contract-examples/_shared.mjs +11 -0
  5. package/contract-examples/motion-lighting.mjs +42 -0
  6. package/contract-examples/occupancy-fusion.mjs +35 -0
  7. package/contract-examples/room-lighting.mjs +58 -0
  8. package/contract-examples/run.mjs +16 -0
  9. package/contract-examples/source-readiness.mjs +64 -0
  10. package/contract-examples/switch-gestures.mjs +34 -0
  11. package/contract-examples/theatre-activity.mjs +62 -0
  12. package/contract-examples/volume-ownership.mjs +59 -0
  13. package/dist/lib/activity-lighting-controller.d.ts +129 -0
  14. package/dist/lib/activity-lighting-controller.js +372 -0
  15. package/dist/lib/avr-controller.d.ts +169 -0
  16. package/dist/lib/avr-controller.js +948 -0
  17. package/dist/lib/backlighting-controller.d.ts +108 -0
  18. package/dist/lib/backlighting-controller.js +269 -0
  19. package/dist/lib/bounded-trace.d.ts +30 -0
  20. package/dist/lib/bounded-trace.js +36 -0
  21. package/dist/lib/circadian-refresh.d.ts +7 -0
  22. package/dist/lib/circadian-refresh.js +11 -0
  23. package/dist/lib/circadian-schedule.d.ts +11 -0
  24. package/dist/lib/circadian-schedule.js +63 -0
  25. package/dist/lib/circadian.d.ts +6 -0
  26. package/dist/lib/circadian.js +15 -0
  27. package/dist/lib/cover-controller.d.ts +130 -0
  28. package/dist/lib/cover-controller.js +336 -0
  29. package/dist/lib/display-mode-controller.d.ts +148 -0
  30. package/dist/lib/display-mode-controller.js +587 -0
  31. package/dist/lib/display-transport.d.ts +41 -0
  32. package/dist/lib/display-transport.js +177 -0
  33. package/dist/lib/light-styling.d.ts +11 -0
  34. package/dist/lib/light-styling.js +15 -0
  35. package/dist/lib/motion-policy.d.ts +72 -0
  36. package/dist/lib/motion-policy.js +251 -0
  37. package/dist/lib/observation-time.d.ts +10 -0
  38. package/dist/lib/observation-time.js +40 -0
  39. package/dist/lib/occupancy-fusion.d.ts +53 -0
  40. package/dist/lib/occupancy-fusion.js +131 -0
  41. package/dist/lib/room-controller.d.ts +113 -0
  42. package/dist/lib/room-controller.js +431 -0
  43. package/dist/lib/source-capability-controller.d.ts +144 -0
  44. package/dist/lib/source-capability-controller.js +494 -0
  45. package/dist/lib/switch-policy.d.ts +53 -0
  46. package/dist/lib/switch-policy.js +110 -0
  47. package/dist/lib/theatre-activity-controller.d.ts +165 -0
  48. package/dist/lib/theatre-activity-controller.js +846 -0
  49. package/dist/lib/theatre-slo.d.ts +49 -0
  50. package/dist/lib/theatre-slo.js +156 -0
  51. package/dist/lib/theatre-state-contract.d.ts +77 -0
  52. package/dist/lib/theatre-state-contract.js +391 -0
  53. package/dist/lib/wall-input.d.ts +62 -0
  54. package/dist/lib/wall-input.js +198 -0
  55. package/dist/nodes/activity-lighting-controller.d.ts +3 -0
  56. package/dist/nodes/activity-lighting-controller.html +38 -0
  57. package/dist/nodes/activity-lighting-controller.js +116 -0
  58. package/dist/nodes/avr-controller.d.ts +3 -0
  59. package/dist/nodes/avr-controller.html +47 -0
  60. package/dist/nodes/avr-controller.js +130 -0
  61. package/dist/nodes/backlighting-controller.d.ts +3 -0
  62. package/dist/nodes/backlighting-controller.html +31 -0
  63. package/dist/nodes/backlighting-controller.js +103 -0
  64. package/dist/nodes/display-mode-controller.d.ts +3 -0
  65. package/dist/nodes/display-mode-controller.html +66 -0
  66. package/dist/nodes/display-mode-controller.js +132 -0
  67. package/dist/nodes/motion-policy.d.ts +3 -0
  68. package/dist/nodes/motion-policy.html +35 -0
  69. package/dist/nodes/motion-policy.js +194 -0
  70. package/dist/nodes/occupancy-fusion.d.ts +3 -0
  71. package/dist/nodes/occupancy-fusion.html +32 -0
  72. package/dist/nodes/occupancy-fusion.js +53 -0
  73. package/dist/nodes/room-controller.d.ts +3 -0
  74. package/dist/nodes/room-controller.html +82 -0
  75. package/dist/nodes/room-controller.js +123 -0
  76. package/dist/nodes/source-capability-controller.d.ts +3 -0
  77. package/dist/nodes/source-capability-controller.html +46 -0
  78. package/dist/nodes/source-capability-controller.js +114 -0
  79. package/dist/nodes/switch-policy.d.ts +3 -0
  80. package/dist/nodes/switch-policy.html +29 -0
  81. package/dist/nodes/switch-policy.js +129 -0
  82. package/dist/nodes/theatre-activity-controller.d.ts +3 -0
  83. package/dist/nodes/theatre-activity-controller.html +32 -0
  84. package/dist/nodes/theatre-activity-controller.js +105 -0
  85. package/dist/nodes/theatre-state-contract.d.ts +3 -0
  86. package/dist/nodes/theatre-state-contract.html +41 -0
  87. package/dist/nodes/theatre-state-contract.js +83 -0
  88. package/examples/Home theatre activity.json +477 -0
  89. package/examples/Home theatre equipment.json +329 -0
  90. package/examples/Room lighting.json +212 -0
  91. package/package.json +62 -4
@@ -0,0 +1,131 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.booleanState = booleanState;
4
+ exports.createOccupancyState = createOccupancyState;
5
+ exports.transitionOccupancy = transitionOccupancy;
6
+ function booleanState(value, source) {
7
+ if (value && typeof value === "object") {
8
+ const record = value;
9
+ const keys = source === "presence"
10
+ ? ["presence", "occupancy", "active"]
11
+ : ["motion", "occupancy", "active"];
12
+ for (const key of keys) {
13
+ if (Object.hasOwn(record, key))
14
+ return booleanState(record[key], source);
15
+ }
16
+ return null;
17
+ }
18
+ if (value === true || value === false)
19
+ return value;
20
+ const normalized = String(value ?? "").trim().toLowerCase();
21
+ if (["on", "true", "occupied", "active", "detected"].includes(normalized))
22
+ return true;
23
+ if (["off", "false", "clear", "inactive", "not_detected"].includes(normalized))
24
+ return false;
25
+ return null;
26
+ }
27
+ function createOccupancyState(saved = {}) {
28
+ return {
29
+ motionKnown: saved.motionKnown === true,
30
+ motionActive: saved.motionActive === true,
31
+ presenceKnown: saved.presenceKnown === true,
32
+ presenceActive: saved.presenceActive === true,
33
+ occupied: saved.occupied === true
34
+ };
35
+ }
36
+ function transitionOccupancy(saved, input, config) {
37
+ const state = createOccupancyState(saved);
38
+ const outputs = [];
39
+ const traces = [];
40
+ const source = input.source;
41
+ const usesPresence = config.presenceMode === "hold";
42
+ const active = source === "motion" || source === "presence"
43
+ ? booleanState(input.payload, source)
44
+ : null;
45
+ function sources() {
46
+ return {
47
+ motion: state.motionKnown ? state.motionActive : null,
48
+ presence: usesPresence && state.presenceKnown ? state.presenceActive : null
49
+ };
50
+ }
51
+ function trace(event, outcome, reason = null) {
52
+ traces.push({ event, outcome, reason, details: { active, occupied: state.occupied, sources: sources() } });
53
+ }
54
+ function emit(occupied, reason, trigger = null) {
55
+ state.occupied = occupied;
56
+ outputs.push({
57
+ source: "occupancy",
58
+ payload: {
59
+ kind: "occupancy",
60
+ occupied,
61
+ trigger,
62
+ reason,
63
+ sources: sources()
64
+ }
65
+ });
66
+ }
67
+ if (source !== "motion" && source !== "presence") {
68
+ trace("input", "ignored", "unsupported-source");
69
+ }
70
+ else if (source === "presence" && !usesPresence) {
71
+ trace("presence", "ignored", "presence-disabled");
72
+ }
73
+ else if (active === null) {
74
+ trace(source, "ignored", "unknown-state");
75
+ }
76
+ else if (source === "motion") {
77
+ const wasKnown = state.motionKnown;
78
+ const wasActive = state.motionActive;
79
+ state.motionKnown = true;
80
+ state.motionActive = active;
81
+ if (active) {
82
+ state.occupied = true;
83
+ if (!wasKnown || !wasActive) {
84
+ emit(true, "motion-active", "motion");
85
+ trace("motion", "triggered");
86
+ }
87
+ else {
88
+ trace("motion", "unchanged");
89
+ }
90
+ }
91
+ else if (usesPresence && state.presenceKnown && state.presenceActive) {
92
+ // Presence only holds occupancy that motion established; it never
93
+ // establishes it, so the state (and what was last emitted) is unchanged.
94
+ trace("motion", state.occupied ? "held" : "unchanged", state.occupied ? "presence-active" : "motion-required");
95
+ }
96
+ else if (!wasKnown || wasActive || state.occupied) {
97
+ emit(false, "all-sources-inactive");
98
+ trace("motion", "vacant");
99
+ }
100
+ else {
101
+ trace("motion", "unchanged");
102
+ }
103
+ }
104
+ else {
105
+ const wasKnown = state.presenceKnown;
106
+ const wasActive = state.presenceActive;
107
+ state.presenceKnown = true;
108
+ state.presenceActive = active;
109
+ if (active) {
110
+ trace("presence", state.occupied ? "held" : "standby", state.occupied ? "presence-active" : "motion-required");
111
+ }
112
+ else if (!state.motionActive && (!wasKnown || wasActive || state.occupied)) {
113
+ emit(false, "all-sources-inactive");
114
+ trace("presence", "vacant");
115
+ }
116
+ else {
117
+ trace("presence", state.motionActive ? "held" : "unchanged", state.motionActive ? "motion-active" : null);
118
+ }
119
+ }
120
+ return {
121
+ state,
122
+ outputs,
123
+ traces,
124
+ status: {
125
+ occupied: state.occupied,
126
+ motion: state.motionKnown ? state.motionActive : null,
127
+ presence: usesPresence && state.presenceKnown ? state.presenceActive : null
128
+ }
129
+ };
130
+ }
131
+ //# sourceMappingURL=occupancy-fusion.js.map
@@ -0,0 +1,113 @@
1
+ import { type CircadianLighting } from "./circadian";
2
+ import type { LightLevels } from "./light-styling";
3
+ export interface RoomTarget {
4
+ id: string;
5
+ stateTopic: string;
6
+ commandTopic: string;
7
+ }
8
+ export interface RoomConfig extends LightLevels {
9
+ area: string;
10
+ displayName: string;
11
+ targets: RoomTarget[];
12
+ initialSleep: boolean;
13
+ sleepBrightnessPct: number;
14
+ maxBrightnessPct: number;
15
+ sleepColorTempKelvin: number;
16
+ maxColorTempKelvin: number;
17
+ refreshTransitionSeconds: number;
18
+ initialTransitionSeconds: number;
19
+ wakeTime?: string;
20
+ bedTime?: string;
21
+ lighting?: CircadianLighting;
22
+ }
23
+ export interface RoomObservation {
24
+ on: boolean;
25
+ brightness: unknown;
26
+ color_temp: unknown;
27
+ observedAt: string;
28
+ }
29
+ export interface ExpectedCommand {
30
+ fingerprint: string;
31
+ expires: number;
32
+ on?: boolean;
33
+ echoed?: boolean;
34
+ }
35
+ export type TargetControlState = "in-control" | "overridden" | "manual";
36
+ export type TargetControl = {
37
+ state: "manual";
38
+ } | {
39
+ state: "overridden";
40
+ owner: string;
41
+ };
42
+ export interface RoomState {
43
+ observed: Record<string, RoomObservation>;
44
+ desired: Record<string, boolean>;
45
+ control: Record<string, TargetControl>;
46
+ expected: Record<string, ExpectedCommand[]>;
47
+ circadianEnabled: boolean;
48
+ sleeping: boolean;
49
+ }
50
+ export interface LightingEvent {
51
+ kind?: string;
52
+ targets?: string[];
53
+ target?: string;
54
+ state?: string;
55
+ values?: Record<string, unknown>;
56
+ updateOnOnly?: boolean;
57
+ updateOffOnly?: boolean;
58
+ preserveManual?: boolean;
59
+ manual?: boolean;
60
+ person?: boolean;
61
+ owner?: string;
62
+ source?: string;
63
+ refresh?: boolean;
64
+ retained?: boolean;
65
+ enabled?: boolean;
66
+ }
67
+ export interface RoomMessage {
68
+ lighting?: LightingEvent;
69
+ topic?: string;
70
+ payload?: unknown;
71
+ retain?: boolean;
72
+ }
73
+ export interface RoomOutput {
74
+ topic: string;
75
+ payload: unknown;
76
+ retain: boolean;
77
+ lighting_command?: {
78
+ area: string;
79
+ target: string;
80
+ source: string;
81
+ };
82
+ }
83
+ export declare function parsePayload(payload: unknown): unknown;
84
+ export declare function fingerprint(payload: unknown): string;
85
+ export declare function createRoomState(config: RoomConfig, saved?: Partial<RoomState> & {
86
+ manual?: Record<string, boolean>;
87
+ }): 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
+ };
94
+ export declare function transitionRoom(saved: Partial<RoomState> | undefined, msg: RoomMessage, config: RoomConfig, nowValue?: Date | string | number): {
95
+ state: RoomState;
96
+ outputs: RoomOutput[];
97
+ traces: {
98
+ event: string;
99
+ outcome: string;
100
+ reason: string | null;
101
+ details: Record<string, unknown>;
102
+ }[];
103
+ status: {
104
+ circadianEnabled: boolean;
105
+ sleeping: boolean;
106
+ onCount: number;
107
+ manualCount: number;
108
+ overriddenCount: number;
109
+ control: {
110
+ [k: string]: TargetControlState;
111
+ };
112
+ };
113
+ };
@@ -0,0 +1,431 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parsePayload = parsePayload;
4
+ exports.fingerprint = fingerprint;
5
+ exports.createRoomState = createRoomState;
6
+ exports.adaptivePayload = adaptivePayload;
7
+ 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
+ }
33
+ function savedControl(saved) {
34
+ if (saved.control) {
35
+ return Object.fromEntries(Object.entries(saved.control).map(([target, entry]) => [target, { ...entry }]));
36
+ }
37
+ // State saved before control states existed: manual: true means manual.
38
+ return Object.fromEntries(Object.entries(saved.manual || {})
39
+ .filter(([, manual]) => manual === true)
40
+ .map(([target]) => [target, { state: "manual" }]));
41
+ }
42
+ function createRoomState(config, saved = {}) {
43
+ return {
44
+ observed: { ...(saved.observed || {}) },
45
+ desired: { ...(saved.desired || {}) },
46
+ control: savedControl(saved),
47
+ expected: Object.fromEntries(Object.entries(saved.expected || {}).map(([target, entries]) => [target, entries.map((entry) => ({ ...entry }))])),
48
+ circadianEnabled: saved.circadianEnabled !== false,
49
+ sleeping: saved.sleeping === undefined ? config.initialSleep : saved.sleeping === true
50
+ };
51
+ }
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
+ // A circadian light command for this moment.
58
+ function adaptivePayload(lightState, isRefresh, sleeping, now, config) {
59
+ if (lightState === "OFF")
60
+ return { state: lightState };
61
+ return {
62
+ state: lightState,
63
+ ...lightingFor(config).styleAt(now, sleeping),
64
+ transition: isRefresh ? config.refreshTransitionSeconds : config.initialTransitionSeconds
65
+ };
66
+ }
67
+ function transitionRoom(saved, msg, config, nowValue = new Date()) {
68
+ const now = nowValue instanceof Date ? nowValue : new Date(nowValue);
69
+ const nowMs = now.getTime();
70
+ const state = createRoomState(config, saved);
71
+ const targetById = Object.fromEntries(config.targets.map((target) => [target.id, target]));
72
+ const traces = [];
73
+ const outputs = [];
74
+ function trace(event, outcome, reason = null, details = {}) {
75
+ traces.push({ event, outcome, reason, details });
76
+ }
77
+ function targetForTopic(topic, field) {
78
+ return config.targets.find((target) => target[field] === topic);
79
+ }
80
+ const controlChanged = new Set();
81
+ function controlOf(targetId) {
82
+ return state.control[targetId]?.state ?? "in-control";
83
+ }
84
+ function setControl(targetId, next, reason) {
85
+ const previous = state.control[targetId] ?? null;
86
+ if (JSON.stringify(previous) === JSON.stringify(next))
87
+ return;
88
+ if (next)
89
+ state.control[targetId] = next;
90
+ else
91
+ delete state.control[targetId];
92
+ controlChanged.add(targetId);
93
+ trace("control", "changed", reason, {
94
+ target: targetId,
95
+ state: next?.state ?? "in-control",
96
+ owner: next?.state === "overridden" ? next.owner : null,
97
+ previous: previous?.state ?? "in-control"
98
+ });
99
+ }
100
+ function controlMessage(targetId) {
101
+ const entry = state.control[targetId];
102
+ return {
103
+ topic: "home/" + config.area + "/lighting/" + targetId + "/control",
104
+ payload: { state: entry?.state ?? "in-control", owner: entry?.state === "overridden" ? entry.owner : null },
105
+ retain: true
106
+ };
107
+ }
108
+ function intendedOn(targetId) {
109
+ if (Object.hasOwn(state.desired, targetId))
110
+ return state.desired[targetId] === true;
111
+ return state.observed[targetId]?.on === true;
112
+ }
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
+ function command(targetId, payload, source) {
137
+ const target = targetById[targetId];
138
+ if (!target)
139
+ return null;
140
+ rememberExpected(targetId, payload);
141
+ return {
142
+ topic: target.commandTopic,
143
+ payload,
144
+ retain: false,
145
+ lighting_command: { area: config.area, target: targetId, source }
146
+ };
147
+ }
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
+ }
179
+ function refreshCommands(source) {
180
+ if (!state.circadianEnabled)
181
+ return [];
182
+ const commands = [];
183
+ for (const target of config.targets) {
184
+ if (!intendedOn(target.id) || controlOf(target.id) !== "in-control")
185
+ continue;
186
+ // 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])) {
188
+ trace("refresh", "skipped", "already-at-level", { target: target.id });
189
+ continue;
190
+ }
191
+ commands.push(command(target.id, adaptivePayload("ON", true, state.sleeping, now, config), source));
192
+ }
193
+ return commands.filter((entry) => entry !== null);
194
+ }
195
+ function emitIntent(event) {
196
+ const targets = Array.isArray(event.targets)
197
+ ? event.targets
198
+ : config.targets.map((target) => target.id);
199
+ const requestedState = String(event.state || "").toUpperCase();
200
+ if (!["ON", "OFF", "TOGGLE"].includes(requestedState))
201
+ return [];
202
+ const commands = [];
203
+ const manualValues = event.values && typeof event.values === "object" ? event.values : null;
204
+ const owner = typeof event.owner === "string" && event.owner ? event.owner : null;
205
+ for (const targetId of targets) {
206
+ if (!targetById[targetId])
207
+ continue;
208
+ // A held light changes only for an owner (its own or a newer one), a
209
+ // person (manual: true or person: true) or a release; any other intent
210
+ // leaves it alone.
211
+ const held = state.control[targetId];
212
+ const person = event.manual === true || event.person === true;
213
+ if (held?.state === "overridden" && !owner && !person) {
214
+ trace("intent", "ignored", "held-by", { target: targetId, owner: held.owner, source: event.source || "intent" });
215
+ continue;
216
+ }
217
+ const wasOn = intendedOn(targetId);
218
+ const resolvedState = requestedState === "TOGGLE" ? (wasOn ? "OFF" : "ON") : requestedState;
219
+ if (event.updateOnOnly === true && !wasOn)
220
+ continue;
221
+ if (event.updateOffOnly === true && wasOn)
222
+ continue;
223
+ if (event.preserveManual === true && controlOf(targetId) === "manual")
224
+ continue;
225
+ if (resolvedState === "OFF") {
226
+ // An off light has no style to protect: it returns to the room controller.
227
+ setControl(targetId, null, "off");
228
+ }
229
+ else if (owner) {
230
+ setControl(targetId, { state: "overridden", owner }, "owner-intent");
231
+ }
232
+ else if (event.manual === true || (manualValues && event.source !== "activity")) {
233
+ setControl(targetId, { state: "manual" }, "manual-intent");
234
+ }
235
+ let payload;
236
+ if (resolvedState === "OFF") {
237
+ payload = { state: "OFF" };
238
+ }
239
+ else if (manualValues) {
240
+ payload = { state: "ON", ...manualValues };
241
+ if (!Object.hasOwn(payload, "transition")) {
242
+ payload.transition = config.initialTransitionSeconds;
243
+ }
244
+ }
245
+ else if (state.circadianEnabled && controlOf(targetId) === "in-control") {
246
+ payload = adaptivePayload("ON", event.refresh === true, state.sleeping, now, config);
247
+ }
248
+ else {
249
+ payload = { state: "ON" };
250
+ }
251
+ state.desired[targetId] = resolvedState === "ON";
252
+ commands.push(command(targetId, payload, event.source || "intent"));
253
+ }
254
+ return commands.filter((entry) => entry !== null);
255
+ }
256
+ const event = msg.lighting || {};
257
+ if (event.kind === "startup") {
258
+ outputs.push(...discoveryMessages());
259
+ for (const target of config.targets)
260
+ controlChanged.add(target.id);
261
+ }
262
+ else if (event.kind === "observed") {
263
+ const target = event.target ? targetById[event.target] : targetForTopic(msg.topic, "stateTopic");
264
+ const parsed = parsePayload(msg.payload);
265
+ const payload = parsed && typeof parsed === "object" ? parsed : null;
266
+ if (target && payload && ["ON", "OFF"].includes(String(payload.state).toUpperCase())) {
267
+ 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
+ };
275
+ if (previousOn !== nextOn) {
276
+ trace("state-observed", "changed", null, {
277
+ target: target.id,
278
+ state: nextOn ? "ON" : "OFF"
279
+ });
280
+ }
281
+ if (contradictsOwnCommand(target.id, nextOn)) {
282
+ trace("state-observed", "ignored", "own-command-in-flight", { target: target.id, state: nextOn ? "ON" : "OFF" });
283
+ }
284
+ else {
285
+ // A change the controller didn't cause becomes the intended state.
286
+ state.desired[target.id] = nextOn;
287
+ if (!nextOn)
288
+ setControl(target.id, null, "observed-off");
289
+ }
290
+ }
291
+ }
292
+ else if (event.kind === "command-observed") {
293
+ const target = event.target ? targetById[event.target] : targetForTopic(msg.topic, "commandTopic");
294
+ const parsed = parsePayload(msg.payload);
295
+ const payload = parsed && typeof parsed === "object" ? parsed : null;
296
+ 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;
310
+ 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
+ if (requestedState === "OFF") {
316
+ state.desired[target.id] = false;
317
+ setControl(target.id, null, "external-off");
318
+ }
319
+ else if (requestedState === "ON") {
320
+ state.desired[target.id] = true;
321
+ if (fields.some((field) => Object.hasOwn(payload, field))) {
322
+ setControl(target.id, { state: "manual" }, "external-values");
323
+ }
324
+ else if (state.circadianEnabled && controlOf(target.id) === "in-control") {
325
+ const corrective = command(target.id, adaptivePayload("ON", false, state.sleeping, now, config), "external-bare-on");
326
+ if (corrective)
327
+ outputs.push(corrective);
328
+ }
329
+ }
330
+ else if (requestedState === "TOGGLE") {
331
+ state.desired[target.id] = !intendedOn(target.id);
332
+ }
333
+ trace("external-command", "observed", null, {
334
+ target: target.id,
335
+ state: requestedState || "UNKNOWN",
336
+ control: controlOf(target.id)
337
+ });
338
+ }
339
+ }
340
+ }
341
+ else if (event.kind === "circadian") {
342
+ const previous = state.circadianEnabled;
343
+ state.circadianEnabled = event.enabled === true;
344
+ if (previous !== state.circadianEnabled) {
345
+ trace("circadian", "changed", null, { enabled: state.circadianEnabled });
346
+ }
347
+ outputs.push({
348
+ topic: "home/" + config.area + "/circadian/state",
349
+ payload: state.circadianEnabled ? "ON" : "OFF",
350
+ retain: true
351
+ });
352
+ if (state.circadianEnabled) {
353
+ // Enabling circadian takes back manual lights; other owners keep theirs.
354
+ for (const target of config.targets) {
355
+ if (controlOf(target.id) === "manual")
356
+ setControl(target.id, null, "circadian-enabled");
357
+ }
358
+ outputs.push(...refreshCommands("circadian-enabled"));
359
+ }
360
+ }
361
+ else if (event.kind === "sleep") {
362
+ const previous = state.sleeping;
363
+ state.sleeping = event.enabled === true;
364
+ if (previous !== state.sleeping)
365
+ trace("sleep", "changed", null, { enabled: state.sleeping });
366
+ outputs.push(...refreshCommands("sleep-policy"));
367
+ }
368
+ else if (event.kind === "refresh") {
369
+ outputs.push(...refreshCommands("periodic-refresh"));
370
+ }
371
+ else if (event.kind === "release") {
372
+ // Hand overridden lights back; an owner name releases only that owner's lights.
373
+ const targets = Array.isArray(event.targets) ? event.targets : config.targets.map((target) => target.id);
374
+ const owner = typeof event.owner === "string" && event.owner ? event.owner : null;
375
+ for (const targetId of targets) {
376
+ const entry = state.control[targetId];
377
+ if (!targetById[targetId] || entry?.state !== "overridden" || (owner && entry.owner !== owner))
378
+ continue;
379
+ setControl(targetId, null, "released");
380
+ if (state.circadianEnabled && intendedOn(targetId)) {
381
+ const restyle = command(targetId, adaptivePayload("ON", true, state.sleeping, now, config), event.source || "release");
382
+ if (restyle)
383
+ outputs.push(restyle);
384
+ }
385
+ }
386
+ }
387
+ else if (event.kind === "intent") {
388
+ outputs.push(...emitIntent(event));
389
+ const commands = outputs.flatMap((message) => {
390
+ if (!message.lighting_command)
391
+ return [];
392
+ const payload = message.payload && typeof message.payload === "object"
393
+ ? message.payload
394
+ : {};
395
+ return [{
396
+ target: message.lighting_command.target,
397
+ state: String(payload.state || "").toUpperCase()
398
+ }];
399
+ });
400
+ trace("intent", commands.length ? "commanded" : "suppressed", commands.length ? null : "no-command-required", {
401
+ source: event.source || "intent",
402
+ state: String(event.state || "").toUpperCase(),
403
+ targets: Array.isArray(event.targets)
404
+ ? event.targets
405
+ : config.targets.map((target) => target.id),
406
+ commands
407
+ });
408
+ }
409
+ for (const target of config.targets) {
410
+ if (controlChanged.has(target.id))
411
+ outputs.push(controlMessage(target.id));
412
+ }
413
+ const onCount = Object.values(state.desired).filter(Boolean).length;
414
+ const control = Object.fromEntries(config.targets.map((target) => [target.id, controlOf(target.id)]));
415
+ const manualCount = Object.values(control).filter((entry) => entry === "manual").length;
416
+ const overriddenCount = Object.values(control).filter((entry) => entry === "overridden").length;
417
+ return {
418
+ state,
419
+ outputs,
420
+ traces,
421
+ status: {
422
+ circadianEnabled: state.circadianEnabled,
423
+ sleeping: state.sleeping,
424
+ onCount,
425
+ manualCount,
426
+ overriddenCount,
427
+ control
428
+ }
429
+ };
430
+ }
431
+ //# sourceMappingURL=room-controller.js.map