@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,177 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DisplayTransport = void 0;
4
+ exports.safeReason = safeReason;
5
+ function host(value, name) {
6
+ const text = String(value || "").trim();
7
+ if (!/^[a-zA-Z0-9.-]+(?::[0-9]+)?$/.test(text)) {
8
+ throw new Error(`${name} must be a host or host:port`);
9
+ }
10
+ return text;
11
+ }
12
+ function safeReason(error) {
13
+ if (!error || typeof error !== "object")
14
+ return "transport-error";
15
+ const candidate = error;
16
+ if (candidate.name === "TimeoutError" || candidate.name === "AbortError")
17
+ return "timeout";
18
+ if (typeof candidate.code === "string" && /^[a-z0-9_-]+$/i.test(candidate.code)) {
19
+ return candidate.code.toLowerCase();
20
+ }
21
+ return "transport-error";
22
+ }
23
+ async function responseJson(response, allowNull = false) {
24
+ if (!response.ok) {
25
+ const error = new Error("HTTP request failed");
26
+ error.code = `http_${response.status}`;
27
+ throw error;
28
+ }
29
+ let body;
30
+ try {
31
+ const decoded = await response.json();
32
+ if (decoded === null && allowNull)
33
+ return null;
34
+ if (!decoded || typeof decoded !== "object" || Array.isArray(decoded)) {
35
+ throw new Error("response is not an object");
36
+ }
37
+ body = decoded;
38
+ }
39
+ catch {
40
+ const error = new Error("Invalid JSON response");
41
+ error.code = "invalid_json";
42
+ throw error;
43
+ }
44
+ if (body.error) {
45
+ const error = new Error("Device RPC failed");
46
+ error.code = "rpc_error";
47
+ throw error;
48
+ }
49
+ return body;
50
+ }
51
+ class DisplayTransport {
52
+ tvHost;
53
+ tvPsk;
54
+ screenHost;
55
+ projectorMeterHost;
56
+ timeoutMs;
57
+ fetch;
58
+ constructor(options) {
59
+ this.tvHost = host(options.tvHost, "tvHost");
60
+ this.tvPsk = String(options.tvPsk || "");
61
+ if (!this.tvPsk)
62
+ throw new Error("tvPsk is required");
63
+ this.screenHost = host(options.screenHost, "screenHost");
64
+ this.projectorMeterHost = host(options.projectorMeterHost, "projectorMeterHost");
65
+ this.timeoutMs = Math.max(250, Number(options.timeoutMs || 5000));
66
+ this.fetch = options.fetch || globalThis.fetch;
67
+ if (typeof this.fetch !== "function")
68
+ throw new Error("fetch is unavailable");
69
+ }
70
+ signal() {
71
+ return AbortSignal.timeout(this.timeoutMs);
72
+ }
73
+ async bravia(method, params) {
74
+ const response = await this.fetch(`http://${this.tvHost}/sony/system`, {
75
+ method: "POST",
76
+ headers: {
77
+ "Content-Type": "application/json",
78
+ "X-Auth-PSK": this.tvPsk
79
+ },
80
+ body: JSON.stringify({ method, id: method === "getPowerStatus" ? 50 : 55, params, version: "1.0" }),
81
+ signal: this.signal()
82
+ });
83
+ return responseJson(response);
84
+ }
85
+ async shellyGet(deviceHost, component) {
86
+ const response = await this.fetch(`http://${deviceHost}/rpc/${component}`, { signal: this.signal() });
87
+ return responseJson(response);
88
+ }
89
+ async shellyPost(deviceHost, component, params) {
90
+ const response = await this.fetch(`http://${deviceHost}/rpc/${component}`, {
91
+ method: "POST",
92
+ headers: { "Content-Type": "application/json" },
93
+ body: JSON.stringify(params),
94
+ signal: this.signal()
95
+ });
96
+ await responseJson(response, true);
97
+ }
98
+ async execute(command, now = new Date()) {
99
+ const common = {
100
+ generation: command.generation,
101
+ observedAt: now.toISOString()
102
+ };
103
+ try {
104
+ if (command.device === "tv" && command.operation === "query_power") {
105
+ const body = await this.bravia("getPowerStatus", []);
106
+ const value = String(body?.result?.[0]?.status || "").toLowerCase();
107
+ const power = value === "active" || value === "on" ? "on"
108
+ : value === "standby" || value === "off" ? "standby" : null;
109
+ if (!power) {
110
+ const error = new Error("Unknown Bravia power status");
111
+ error.code = "invalid_power_status";
112
+ throw error;
113
+ }
114
+ return { display: { kind: "observed", device: "tv", power, source: "bravia", ...common } };
115
+ }
116
+ if (command.device === "tv" && command.operation === "set_power") {
117
+ await this.bravia("setPowerStatus", [{ status: command.power === "on" }]);
118
+ return null;
119
+ }
120
+ if (command.device === "screen" && command.operation === "query_position") {
121
+ const body = await this.shellyGet(this.screenHost, "Cover.GetStatus?id=0");
122
+ const position = body.current_pos;
123
+ if (typeof position !== "number" || !Number.isFinite(position) || position < 0 || position > 100) {
124
+ const error = new Error("Shelly cover reported no usable position");
125
+ error.code = "invalid_screen_position";
126
+ throw error;
127
+ }
128
+ return {
129
+ display: {
130
+ kind: "observed",
131
+ device: "screen",
132
+ position,
133
+ state: String(body.state || "unknown"),
134
+ source: "shelly-cover",
135
+ ...common
136
+ }
137
+ };
138
+ }
139
+ if (command.device === "screen" && command.operation === "set_position") {
140
+ await this.shellyPost(this.screenHost, "Cover.GoToPosition", { id: 0, pos: command.position });
141
+ return null;
142
+ }
143
+ if (command.device === "projector" && command.operation === "query_power") {
144
+ const body = await this.shellyGet(this.projectorMeterHost, "Switch.GetStatus?id=1");
145
+ const watts = body.apower;
146
+ if (typeof watts !== "number" || !Number.isFinite(watts) || watts < 0) {
147
+ const error = new Error("Shelly switch reported no usable power");
148
+ error.code = "invalid_projector_power";
149
+ throw error;
150
+ }
151
+ return {
152
+ display: {
153
+ kind: "observed",
154
+ device: "projector",
155
+ watts,
156
+ source: "shelly-power",
157
+ ...common
158
+ }
159
+ };
160
+ }
161
+ throw new Error("Unsupported display transport command");
162
+ }
163
+ catch (error) {
164
+ return {
165
+ display: {
166
+ kind: "transport_failed",
167
+ device: command.device,
168
+ operation: command.operation,
169
+ generation: command.generation,
170
+ reason: safeReason(error)
171
+ }
172
+ };
173
+ }
174
+ }
175
+ }
176
+ exports.DisplayTransport = DisplayTransport;
177
+ //# sourceMappingURL=display-transport.js.map
@@ -0,0 +1,11 @@
1
+ export interface LightLevels {
2
+ sleepBrightnessPct: number;
3
+ maxBrightnessPct: number;
4
+ sleepColorTempKelvin: number;
5
+ maxColorTempKelvin: number;
6
+ }
7
+ export interface LightStyle {
8
+ brightness: number;
9
+ color_temp: number;
10
+ }
11
+ export declare function styleAtLevel(level: number, levels: LightLevels): LightStyle;
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.styleAtLevel = styleAtLevel;
4
+ function styleAtLevel(level, levels) {
5
+ const percent = levels.sleepBrightnessPct + (levels.maxBrightnessPct - levels.sleepBrightnessPct) * level;
6
+ // Colour moves evenly in mireds, the unit bulbs take: equal mired steps look
7
+ // evenly spaced, where equal kelvin steps would bunch up at the cool end.
8
+ const sleepMired = 1_000_000 / levels.sleepColorTempKelvin;
9
+ const dayMired = 1_000_000 / levels.maxColorTempKelvin;
10
+ return {
11
+ brightness: Math.min(254, Math.max(1, Math.round(percent * 254 / 100))),
12
+ color_temp: Math.round(sleepMired + (dayMired - sleepMired) * level)
13
+ };
14
+ }
15
+ //# sourceMappingURL=light-styling.js.map
@@ -0,0 +1,72 @@
1
+ import { type WallInputConfig, type WallInputState } from "./wall-input";
2
+ export interface MotionConfig extends WallInputConfig {
3
+ defaultIlluminanceCutoff: number;
4
+ defaultDelaySeconds: number;
5
+ onTargets: string[];
6
+ offTargets: string[];
7
+ }
8
+ export interface MotionState {
9
+ areaEnabled: boolean;
10
+ illuminance: number | null;
11
+ illuminanceCutoff: number;
12
+ delaySeconds: number;
13
+ wallInput: WallInputState;
14
+ offTimerGeneration: number;
15
+ offTimerDueAt: number | null;
16
+ }
17
+ export interface MotionInput {
18
+ source: string;
19
+ observedAt?: unknown;
20
+ baseline?: boolean;
21
+ payload?: unknown;
22
+ generation?: number;
23
+ switchAt?: number;
24
+ retain?: boolean;
25
+ }
26
+ export interface LightingIntent {
27
+ lighting: {
28
+ kind: "intent";
29
+ targets: string[];
30
+ state: string;
31
+ source: string;
32
+ [key: string]: unknown;
33
+ };
34
+ }
35
+ export type MotionEffect = {
36
+ kind: "cancel-off-timer";
37
+ } | {
38
+ kind: "schedule-off-timer";
39
+ delayMs: number;
40
+ generation: number;
41
+ } | {
42
+ kind: "cancel-switch-timer";
43
+ } | {
44
+ kind: "schedule-switch-timer";
45
+ delayMs: number;
46
+ generation: number;
47
+ switchAt: number;
48
+ } | {
49
+ kind: "send";
50
+ message: LightingIntent;
51
+ };
52
+ export interface MotionTrace {
53
+ event: string;
54
+ outcome: string;
55
+ reason: string | null;
56
+ details: Record<string, unknown>;
57
+ }
58
+ export declare function booleanOn(value: unknown): boolean;
59
+ export declare function createMotionState(config: MotionConfig, saved?: Partial<MotionState>): MotionState;
60
+ export declare function lightingIntent(targets: string[], state: string, source: string, extra?: Record<string, unknown>): LightingIntent;
61
+ export declare function transitionMotion(saved: Partial<MotionState> | undefined, input: MotionInput, config: MotionConfig, globalEnabled: boolean, now?: number): {
62
+ state: MotionState;
63
+ globalEnabled: boolean;
64
+ effects: MotionEffect[];
65
+ traces: MotionTrace[];
66
+ status: {
67
+ enabled: boolean;
68
+ illuminance: number | null;
69
+ delaySeconds: number;
70
+ switch: import("./wall-input").WallInputStatus;
71
+ };
72
+ };
@@ -0,0 +1,251 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.booleanOn = booleanOn;
4
+ exports.createMotionState = createMotionState;
5
+ exports.lightingIntent = lightingIntent;
6
+ exports.transitionMotion = transitionMotion;
7
+ const wall_input_1 = require("./wall-input");
8
+ function booleanOn(value) {
9
+ return value === true || (typeof value === "string" && value.toLowerCase() === "on");
10
+ }
11
+ function finiteNumber(value) {
12
+ const number = Number(value);
13
+ return Number.isFinite(number) ? number : null;
14
+ }
15
+ function createMotionState(config, saved = {}) {
16
+ const legacy = saved;
17
+ return {
18
+ areaEnabled: saved.areaEnabled !== false,
19
+ 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
+ }),
29
+ offTimerGeneration: Number(saved.offTimerGeneration) || 0,
30
+ offTimerDueAt: Number(saved.offTimerDueAt) || null
31
+ };
32
+ }
33
+ function lightingIntent(targets, state, source, extra = {}) {
34
+ return {
35
+ lighting: {
36
+ kind: "intent",
37
+ targets,
38
+ state,
39
+ source,
40
+ ...extra
41
+ }
42
+ };
43
+ }
44
+ function transitionMotion(saved, input, config, globalEnabled, now = Date.now()) {
45
+ const state = createMotionState(config, saved);
46
+ const effects = [];
47
+ const traces = [];
48
+ let nextGlobalEnabled = globalEnabled !== false;
49
+ function enabled() {
50
+ return state.areaEnabled && nextGlobalEnabled;
51
+ }
52
+ function trace(event, outcome, reason, details = {}) {
53
+ traces.push({ event, outcome, reason, details });
54
+ }
55
+ function cancelOffTimer(reason) {
56
+ const wasActive = Number(state.offTimerDueAt) > now;
57
+ state.offTimerGeneration += 1;
58
+ state.offTimerDueAt = null;
59
+ effects.push({ kind: "cancel-off-timer" });
60
+ if (wasActive && reason)
61
+ trace("off-timer", "cancelled", reason);
62
+ }
63
+ function scheduleOffTimer() {
64
+ cancelOffTimer("rescheduled");
65
+ const delayMs = Math.max(0, state.delaySeconds) * 1000;
66
+ state.offTimerDueAt = now + delayMs;
67
+ effects.push({
68
+ kind: "schedule-off-timer",
69
+ delayMs,
70
+ generation: state.offTimerGeneration
71
+ });
72
+ trace("off-timer", "scheduled", null, {
73
+ delaySeconds: state.delaySeconds,
74
+ dueAt: new Date(state.offTimerDueAt).toISOString(),
75
+ targets: config.offTargets
76
+ });
77
+ }
78
+ function emitIntent(message, event = "intent") {
79
+ effects.push({ kind: "send", message });
80
+ trace(event, "emitted", null, {
81
+ source: message.lighting.source,
82
+ state: message.lighting.state,
83
+ targets: message.lighting.targets
84
+ });
85
+ }
86
+ const source = input.source;
87
+ const payload = input.payload;
88
+ if (source === "global-enabled") {
89
+ const previous = nextGlobalEnabled;
90
+ nextGlobalEnabled = booleanOn(payload);
91
+ if (previous !== nextGlobalEnabled) {
92
+ trace("enabled", "changed", null, { scope: "global", enabled: nextGlobalEnabled });
93
+ }
94
+ if (!enabled())
95
+ cancelOffTimer("motion-disabled");
96
+ }
97
+ else if (source === "area-enabled") {
98
+ const previous = state.areaEnabled;
99
+ state.areaEnabled = booleanOn(payload);
100
+ if (previous !== state.areaEnabled) {
101
+ trace("enabled", "changed", null, { scope: "area", enabled: state.areaEnabled });
102
+ }
103
+ if (!enabled())
104
+ cancelOffTimer("motion-disabled");
105
+ }
106
+ else if (source === "delay") {
107
+ const minutes = finiteNumber(payload);
108
+ if (minutes !== null)
109
+ state.delaySeconds = minutes * 60;
110
+ }
111
+ else if (source === "illuminance-cut-off") {
112
+ const cutoff = finiteNumber(payload);
113
+ if (cutoff !== null)
114
+ state.illuminanceCutoff = cutoff;
115
+ }
116
+ else if (source === "illuminance") {
117
+ const payloadRecord = payload && typeof payload === "object"
118
+ ? payload
119
+ : {};
120
+ const value = payloadRecord.illuminance ?? payloadRecord.illuminanceLux ?? payload;
121
+ const illuminance = finiteNumber(value);
122
+ if (illuminance !== null)
123
+ state.illuminance = illuminance;
124
+ }
125
+ else if (source === "occupancy") {
126
+ const payloadRecord = payload && typeof payload === "object"
127
+ ? payload
128
+ : {};
129
+ const occupied = payloadRecord.occupied === true;
130
+ if (occupied) {
131
+ cancelOffTimer("occupancy-detected");
132
+ const darkEnough = state.illuminance === null || state.illuminance <= state.illuminanceCutoff;
133
+ const shouldEmit = enabled() && darkEnough;
134
+ const intentSource = typeof payloadRecord.trigger === "string" ? payloadRecord.trigger : "occupancy";
135
+ if (shouldEmit)
136
+ effects.push({ kind: "send", message: lightingIntent(config.onTargets, "ON", intentSource) });
137
+ trace("occupancy", shouldEmit ? "emit-on" : "suppressed", shouldEmit ? null : !enabled() ? "disabled" : "too-bright", {
138
+ occupied: true,
139
+ trigger: payloadRecord.trigger ?? null,
140
+ areaEnabled: state.areaEnabled,
141
+ globalEnabled: nextGlobalEnabled,
142
+ illuminance: state.illuminance,
143
+ illuminanceCutoff: state.illuminanceCutoff,
144
+ targets: config.onTargets
145
+ });
146
+ }
147
+ else {
148
+ if (enabled())
149
+ scheduleOffTimer();
150
+ else
151
+ cancelOffTimer("motion-disabled");
152
+ trace("occupancy", enabled() ? "schedule-off" : "suppressed", enabled() ? null : "disabled", {
153
+ occupied: false,
154
+ areaEnabled: state.areaEnabled,
155
+ globalEnabled: nextGlobalEnabled,
156
+ illuminance: state.illuminance,
157
+ illuminanceCutoff: state.illuminanceCutoff,
158
+ targets: config.offTargets
159
+ });
160
+ }
161
+ }
162
+ else if (source === "light") {
163
+ let parsed = {};
164
+ if (typeof payload === "string") {
165
+ try {
166
+ const decoded = JSON.parse(payload);
167
+ if (decoded && typeof decoded === "object")
168
+ parsed = decoded;
169
+ }
170
+ catch {
171
+ parsed = {};
172
+ }
173
+ }
174
+ else if (payload && typeof payload === "object") {
175
+ parsed = payload;
176
+ }
177
+ if (String(parsed.state || "").toUpperCase() === "OFF") {
178
+ cancelOffTimer("light-observed-off");
179
+ }
180
+ }
181
+ else if (source === "off-timer") {
182
+ if (input.generation !== state.offTimerGeneration || state.offTimerDueAt === null) {
183
+ trace("off-timer", "ignored", "stale-generation", { generation: input.generation });
184
+ }
185
+ else if (!enabled()) {
186
+ // The global switch is shared, so a timer scheduled before another node
187
+ // disabled motion can still fire here.
188
+ state.offTimerDueAt = null;
189
+ trace("off-timer", "suppressed", "disabled", {
190
+ areaEnabled: state.areaEnabled,
191
+ globalEnabled: nextGlobalEnabled
192
+ });
193
+ }
194
+ else {
195
+ state.offTimerDueAt = null;
196
+ emitIntent(lightingIntent(config.offTargets, "OFF", "motion"), "off-timer");
197
+ }
198
+ }
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
+ }
237
+ }
238
+ return {
239
+ state,
240
+ globalEnabled: nextGlobalEnabled,
241
+ effects,
242
+ traces,
243
+ status: {
244
+ enabled: enabled(),
245
+ illuminance: state.illuminance,
246
+ delaySeconds: state.delaySeconds,
247
+ switch: (0, wall_input_1.wallInputStatus)(state.wallInput, config.switchFreshnessMs, now)
248
+ }
249
+ };
250
+ }
251
+ //# sourceMappingURL=motion-policy.js.map
@@ -0,0 +1,10 @@
1
+ export declare const CLOCK_SKEW_MS = 1000;
2
+ export declare function parseObservedAt(value: unknown): number | null;
3
+ export interface BoundedObservation {
4
+ ms: number;
5
+ observedAt: string;
6
+ skewed: boolean;
7
+ }
8
+ export declare function boundObservedAt(reported: string, ms: number, nowMs: number): BoundedObservation;
9
+ export declare function isOutOfOrder(ms: number, previous: unknown, nowMs: number): boolean;
10
+ export declare function isFresh(ms: number | null, nowMs: number, freshnessMs: number): boolean;
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CLOCK_SKEW_MS = void 0;
4
+ exports.parseObservedAt = parseObservedAt;
5
+ exports.boundObservedAt = boundObservedAt;
6
+ exports.isOutOfOrder = isOutOfOrder;
7
+ exports.isFresh = isFresh;
8
+ // Observation times reported by devices and flows. A time more than
9
+ // CLOCK_SKEW_MS ahead of the receiver's clock is treated as observed on
10
+ // receipt, so one bad clock cannot make every later report look older.
11
+ exports.CLOCK_SKEW_MS = 1000;
12
+ // An ISO string or non-negative epoch milliseconds; anything else is null.
13
+ function parseObservedAt(value) {
14
+ if (typeof value === "number")
15
+ return Number.isFinite(value) && value >= 0 ? value : null;
16
+ if (typeof value === "string") {
17
+ const parsed = Date.parse(value);
18
+ return Number.isFinite(parsed) ? parsed : null;
19
+ }
20
+ return null;
21
+ }
22
+ // The time to store for a parsed observation. Times within the limit keep the
23
+ // reported string unchanged.
24
+ function boundObservedAt(reported, ms, nowMs) {
25
+ if (ms > nowMs + exports.CLOCK_SKEW_MS)
26
+ return { ms: nowMs, observedAt: new Date(nowMs).toISOString(), skewed: true };
27
+ return { ms, observedAt: reported, skewed: false };
28
+ }
29
+ // Whether a report is older than the stored one. A stored time beyond the skew
30
+ // limit (saved before this rule existed) counts as now, so it releases.
31
+ function isOutOfOrder(ms, previous, nowMs) {
32
+ const previousMs = parseObservedAt(previous);
33
+ if (previousMs === null)
34
+ return false;
35
+ return ms < (previousMs > nowMs + exports.CLOCK_SKEW_MS ? nowMs : previousMs);
36
+ }
37
+ function isFresh(ms, nowMs, freshnessMs) {
38
+ return ms !== null && nowMs - ms <= freshnessMs && ms <= nowMs + exports.CLOCK_SKEW_MS;
39
+ }
40
+ //# sourceMappingURL=observation-time.js.map
@@ -0,0 +1,53 @@
1
+ export type OccupancySource = "motion" | "presence";
2
+ export interface OccupancyState {
3
+ motionKnown: boolean;
4
+ motionActive: boolean;
5
+ presenceKnown: boolean;
6
+ presenceActive: boolean;
7
+ occupied: boolean;
8
+ }
9
+ export interface OccupancyInput {
10
+ source: string;
11
+ payload: unknown;
12
+ }
13
+ export interface OccupancyConfig {
14
+ presenceMode?: "hold" | "ignore";
15
+ }
16
+ export interface OccupancyOutput {
17
+ source: "occupancy";
18
+ payload: {
19
+ kind: "occupancy";
20
+ occupied: boolean;
21
+ trigger: OccupancySource | null;
22
+ reason: string;
23
+ sources: {
24
+ motion: boolean | null;
25
+ presence: boolean | null;
26
+ };
27
+ };
28
+ }
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
+ };
40
+ };
41
+ }
42
+ export declare function booleanState(value: unknown, source: OccupancySource): boolean | null;
43
+ export declare function createOccupancyState(saved?: Partial<OccupancyState>): OccupancyState;
44
+ export declare function transitionOccupancy(saved: Partial<OccupancyState> | undefined, input: OccupancyInput, config: OccupancyConfig): {
45
+ state: OccupancyState;
46
+ outputs: OccupancyOutput[];
47
+ traces: OccupancyTrace[];
48
+ status: {
49
+ occupied: boolean;
50
+ motion: boolean | null;
51
+ presence: boolean | null;
52
+ };
53
+ };