@avantics/node-red-home-automation 6.2.0 → 6.4.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 +93 -12
  2. package/dist/lib/activity-lighting-controller.d.ts +1 -0
  3. package/dist/lib/activity-lighting-controller.js +37 -10
  4. package/dist/lib/avr-controller.d.ts +3 -0
  5. package/dist/lib/avr-controller.js +24 -2
  6. package/dist/lib/backlighting-controller.d.ts +5 -2
  7. package/dist/lib/backlighting-controller.js +27 -2
  8. package/dist/lib/display-mode-controller.d.ts +3 -0
  9. package/dist/lib/display-mode-controller.js +43 -16
  10. package/dist/lib/esphome-sensor.d.ts +73 -0
  11. package/dist/lib/esphome-sensor.js +261 -0
  12. package/dist/lib/ha-discovery.js +3 -2
  13. package/dist/lib/occupancy-fusion.d.ts +1 -0
  14. package/dist/lib/occupancy-fusion.js +15 -2
  15. package/dist/lib/scene.d.ts +9 -1
  16. package/dist/lib/scene.js +61 -8
  17. package/dist/lib/source-capability-controller.d.ts +4 -1
  18. package/dist/lib/source-capability-controller.js +49 -2
  19. package/dist/lib/target-observation.d.ts +14 -0
  20. package/dist/lib/target-observation.js +22 -0
  21. package/dist/lib/theatre-activity-controller.d.ts +5 -0
  22. package/dist/lib/theatre-activity-controller.js +87 -12
  23. package/dist/lib/theatre-state.d.ts +2 -0
  24. package/dist/lib/theatre-state.js +10 -1
  25. package/dist/lib/wled.d.ts +48 -0
  26. package/dist/lib/wled.js +105 -0
  27. package/dist/lib/z2m-power.d.ts +38 -0
  28. package/dist/lib/z2m-power.js +83 -0
  29. package/dist/lib/z2m-sensor.d.ts +37 -0
  30. package/dist/lib/z2m-sensor.js +88 -0
  31. package/dist/nodes/activity-lighting-controller.html +2 -1
  32. package/dist/nodes/apollo-r-pro-1.d.ts +2 -0
  33. package/dist/nodes/apollo-r-pro-1.html +80 -0
  34. package/dist/nodes/apollo-r-pro-1.js +4 -0
  35. package/dist/nodes/avr-controller.html +2 -1
  36. package/dist/nodes/avr-controller.js +1 -1
  37. package/dist/nodes/backlighting-controller.html +2 -1
  38. package/dist/nodes/backlighting-controller.js +3 -2
  39. package/dist/nodes/circadian-policy.html +2 -1
  40. package/dist/nodes/cover-controller.html +2 -1
  41. package/dist/nodes/cover-group.html +2 -1
  42. package/dist/nodes/device-side.d.ts +1 -0
  43. package/dist/nodes/device-side.js +7 -3
  44. package/dist/nodes/display-mode-controller.html +2 -1
  45. package/dist/nodes/display-mode-controller.js +11 -2
  46. package/dist/nodes/esphome-sensor.d.ts +2 -0
  47. package/dist/nodes/esphome-sensor.js +77 -0
  48. package/dist/nodes/everything-presence-one.d.ts +2 -0
  49. package/dist/nodes/everything-presence-one.html +78 -0
  50. package/dist/nodes/everything-presence-one.js +4 -0
  51. package/dist/nodes/house-schedule-mqtt.html +2 -1
  52. package/dist/nodes/motion-policy.html +6 -4
  53. package/dist/nodes/motion-policy.js +10 -1
  54. package/dist/nodes/occupancy-fusion.html +5 -1
  55. package/dist/nodes/occupancy-fusion.js +2 -1
  56. package/dist/nodes/room-controller.html +2 -1
  57. package/dist/nodes/scene.html +25 -4
  58. package/dist/nodes/scene.js +9 -2
  59. package/dist/nodes/shelly-cover.html +2 -1
  60. package/dist/nodes/shelly-switch.html +2 -1
  61. package/dist/nodes/source-capability-controller.html +2 -1
  62. package/dist/nodes/source-capability-controller.js +3 -2
  63. package/dist/nodes/switch-policy.html +2 -1
  64. package/dist/nodes/theatre-activity-controller.html +6 -3
  65. package/dist/nodes/theatre-state-contract.html +2 -1
  66. package/dist/nodes/wled.d.ts +3 -0
  67. package/dist/nodes/wled.html +56 -0
  68. package/dist/nodes/wled.js +53 -0
  69. package/dist/nodes/z2m-cover.html +2 -1
  70. package/dist/nodes/z2m-light.html +4 -2
  71. package/dist/nodes/z2m-light.js +17 -0
  72. package/dist/nodes/z2m-power.d.ts +3 -0
  73. package/dist/nodes/z2m-power.html +58 -0
  74. package/dist/nodes/z2m-power.js +53 -0
  75. package/dist/nodes/z2m-sensor.d.ts +3 -0
  76. package/dist/nodes/z2m-sensor.html +69 -0
  77. package/dist/nodes/z2m-sensor.js +62 -0
  78. package/examples/Scene.json +8 -56
  79. package/package.json +31 -16
@@ -0,0 +1,73 @@
1
+ import type { TraceEntry } from "./bounded-trace";
2
+ export type SensorRole = "motion" | "presence" | "illuminance";
3
+ export interface EsphomeModel {
4
+ label: string;
5
+ modelNames: readonly string[];
6
+ exclude: readonly string[];
7
+ motion: readonly string[];
8
+ presence: readonly string[];
9
+ illuminance: readonly string[];
10
+ }
11
+ export declare const ESPHOME_MODELS: Readonly<Record<string, EsphomeModel>>;
12
+ export interface EsphomeSensorConfig {
13
+ device: string;
14
+ model: string;
15
+ discoveryPrefix: string;
16
+ }
17
+ export interface DiscoveredEntity {
18
+ component: string;
19
+ object: string;
20
+ stateTopic: string;
21
+ deviceClass: string | null;
22
+ model: string | null;
23
+ availabilityTopic: string | null;
24
+ }
25
+ export interface EsphomeSensorState {
26
+ entities: Record<string, boolean>;
27
+ motion: boolean | null;
28
+ presence: boolean | null;
29
+ illuminance: number | null;
30
+ online: boolean | null;
31
+ awaitingStatus: boolean;
32
+ discovered: Record<string, DiscoveredEntity>;
33
+ }
34
+ export interface EsphomeSensorMessage {
35
+ topic?: unknown;
36
+ payload?: unknown;
37
+ retain?: unknown;
38
+ }
39
+ export interface OccupancyMessage {
40
+ source: "motion" | "presence";
41
+ payload: boolean;
42
+ baseline?: true;
43
+ }
44
+ export interface LightMessage {
45
+ source: "illuminance";
46
+ payload: number;
47
+ }
48
+ export type RoleSource = "discovered" | "preset" | "preset-other-model";
49
+ export interface Roles {
50
+ source: RoleSource;
51
+ motion: string[];
52
+ presence: string[];
53
+ illuminance: string[];
54
+ status: string[];
55
+ }
56
+ export declare function normaliseEsphomeSensorConfig(config: {
57
+ device?: unknown;
58
+ model?: unknown;
59
+ discoveryPrefix?: unknown;
60
+ }): EsphomeSensorConfig;
61
+ export declare function esphomeSensorTopics(config: EsphomeSensorConfig): {
62
+ discovery: string;
63
+ initial: string[];
64
+ };
65
+ export declare function esphomeRoles(state: Pick<EsphomeSensorState, "discovered">, config: EsphomeSensorConfig): Roles;
66
+ export declare function transitionEsphomeSensor(saved: Partial<EsphomeSensorState> | undefined, msg: EsphomeSensorMessage, config: EsphomeSensorConfig): {
67
+ state: EsphomeSensorState;
68
+ occupancy: OccupancyMessage[];
69
+ light: LightMessage[];
70
+ traces: TraceEntry<Record<string, unknown>>[];
71
+ roles: Roles;
72
+ topics: string[];
73
+ };
@@ -0,0 +1,261 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ESPHOME_MODELS = void 0;
4
+ exports.normaliseEsphomeSensorConfig = normaliseEsphomeSensorConfig;
5
+ exports.esphomeSensorTopics = esphomeSensorTopics;
6
+ exports.esphomeRoles = esphomeRoles;
7
+ exports.transitionEsphomeSensor = transitionEsphomeSensor;
8
+ const mqtt_message_1 = require("./mqtt-message");
9
+ exports.ESPHOME_MODELS = {
10
+ "everything-presence-one": {
11
+ label: "Everything Presence One",
12
+ modelNames: ["everythingpresenceone"],
13
+ // Its own "Occupancy" combines the PIR and radar, with its own off
14
+ // latency: occupancy fusion does that combining here.
15
+ exclude: ["occupancy"],
16
+ motion: ["pir"],
17
+ presence: ["mmwave"],
18
+ illuminance: ["illuminance"]
19
+ },
20
+ "apollo-r-pro-1": {
21
+ label: "Apollo R PRO-1",
22
+ modelNames: ["rpro1"],
23
+ exclude: [],
24
+ // Its two radars, LD2450 and LD2412: a moving target is motion. Its
25
+ // firmware has named the LD2450's entities both without a prefix
26
+ // (presence, moving_target) and, currently, with ld2450_.
27
+ motion: ["moving_target", "ld2450_moving_target", "ld2412_moving_target"],
28
+ presence: ["presence", "ld2450_presence", "ld2412_presence"],
29
+ illuminance: ["ltr390_light"]
30
+ }
31
+ };
32
+ function normaliseEsphomeSensorConfig(config) {
33
+ const device = String(config.device ?? "").trim().replace(/^\/+|\/+$/g, "");
34
+ // The user's own device's: no default.
35
+ if (!device)
36
+ throw new Error("the device's name is required");
37
+ if (/[+#]/.test(device))
38
+ throw new Error("the device's name can't contain + or #");
39
+ const model = String(config.model ?? "");
40
+ if (!Object.hasOwn(exports.ESPHOME_MODELS, model))
41
+ throw new Error(`unknown model: ${model}`);
42
+ const discoveryPrefix = String(config.discoveryPrefix ?? "").trim().replace(/^\/+|\/+$/g, "") || "homeassistant";
43
+ if (/[+#]/.test(discoveryPrefix))
44
+ throw new Error("the discovery prefix can't contain + or #");
45
+ return { device, model, discoveryPrefix };
46
+ }
47
+ // The topics a node subscribes to as it starts: the device's discovery,
48
+ // its status, and its preset's states (until discovery says otherwise).
49
+ function esphomeSensorTopics(config) {
50
+ const preset = presetRoles(config, "preset");
51
+ return {
52
+ discovery: `${config.discoveryPrefix}/+/${config.device}/+/config`,
53
+ initial: [...new Set([`${config.discoveryPrefix}/+/${config.device}/+/config`, ...preset.status, ...preset.presence,
54
+ ...preset.motion, ...preset.illuminance])]
55
+ };
56
+ }
57
+ function presetRoles(config, source) {
58
+ const model = exports.ESPHOME_MODELS[config.model];
59
+ const binary = (name) => `${config.device}/binary_sensor/${name}/state`;
60
+ return {
61
+ source,
62
+ motion: model.motion.map(binary),
63
+ presence: model.presence.map(binary),
64
+ illuminance: model.illuminance.map((name) => `${config.device}/sensor/${name}/state`),
65
+ status: [`${config.device}/status`]
66
+ };
67
+ }
68
+ const simplified = (value) => value.toLowerCase().replace(/[^a-z0-9]/g, "");
69
+ // The roles, from the device's discovery when it has one for this model.
70
+ function esphomeRoles(state, config) {
71
+ const model = exports.ESPHOME_MODELS[config.model];
72
+ const entities = Object.values(state.discovered).filter((entity) => !model.exclude.includes(entity.object));
73
+ if (!entities.length)
74
+ return presetRoles(config, "preset");
75
+ const models = entities.map((entity) => entity.model).filter((name) => Boolean(name));
76
+ if (models.some((name) => !model.modelNames.some((fragment) => simplified(name).includes(fragment)))) {
77
+ return presetRoles(config, "preset-other-model");
78
+ }
79
+ const of = (component, classes) => entities
80
+ .filter((entity) => entity.component === component && entity.deviceClass !== null && classes.includes(entity.deviceClass))
81
+ .map((entity) => entity.stateTopic);
82
+ const status = [...new Set([`${config.device}/status`, ...entities.map((entity) => entity.availabilityTopic)
83
+ .filter((topic) => Boolean(topic))])];
84
+ return {
85
+ source: "discovered",
86
+ motion: of("binary_sensor", ["motion"]),
87
+ presence: of("binary_sensor", ["occupancy", "presence"]),
88
+ illuminance: of("sensor", ["illuminance"]),
89
+ status
90
+ };
91
+ }
92
+ function text(payload) {
93
+ return (Buffer.isBuffer(payload) ? payload.toString("utf8") : String(payload ?? "")).trim();
94
+ }
95
+ // A discovery entry's fields, from Home Assistant's discovery format with
96
+ // or without its abbreviated keys. Its "~" base-topic shorthand isn't
97
+ // expanded: ESPHome gives full state and availability topics.
98
+ function discoveredEntity(component, object, payload) {
99
+ let entry;
100
+ try {
101
+ entry = JSON.parse(payload);
102
+ }
103
+ catch {
104
+ return null;
105
+ }
106
+ if (!(0, mqtt_message_1.isObject)(entry))
107
+ return null;
108
+ // Disabled by default on the device (ESPHome's disabled_by_default, "en":
109
+ // false): its maker doesn't mean it as one of its sensors, such as the
110
+ // Apollo's LD2412 light level, a radar reading rather than lux.
111
+ if (entry.en === false || entry.enabled_by_default === false)
112
+ return "disabled";
113
+ const field = (short, long) => (typeof entry[short] === "string" ? entry[short] : typeof entry[long] === "string" ? entry[long] : null);
114
+ const stateTopic = field("stat_t", "state_topic");
115
+ if (!stateTopic)
116
+ return null;
117
+ const device = (0, mqtt_message_1.isObject)(entry.dev) ? entry.dev : (0, mqtt_message_1.isObject)(entry.device) ? entry.device : {};
118
+ const model = typeof device.mdl === "string" ? device.mdl : typeof device.model === "string" ? device.model : null;
119
+ return { component, object, stateTopic, deviceClass: field("dev_cla", "device_class"), model, availabilityTopic: field("avty_t", "availability_topic") };
120
+ }
121
+ function transitionEsphomeSensor(saved, msg, config) {
122
+ const state = {
123
+ entities: saved?.entities && typeof saved.entities === "object" ? { ...saved.entities } : {},
124
+ motion: typeof saved?.motion === "boolean" ? saved.motion : null,
125
+ presence: typeof saved?.presence === "boolean" ? saved.presence : null,
126
+ illuminance: typeof saved?.illuminance === "number" ? saved.illuminance : null,
127
+ online: typeof saved?.online === "boolean" ? saved.online : null,
128
+ awaitingStatus: saved?.awaitingStatus === true,
129
+ discovered: saved?.discovered && typeof saved.discovered === "object" ? { ...saved.discovered } : {}
130
+ };
131
+ const occupancy = [];
132
+ const light = [];
133
+ const traces = [];
134
+ const trace = (event, outcome, reason = null, details = {}) => {
135
+ traces.push({ event, outcome, reason, details });
136
+ };
137
+ const before = esphomeRoles(state, config);
138
+ // A role's value from the entities that have reported: on when any is
139
+ // on, off when all are off, not known while none has reported.
140
+ function roleValue(roles, role) {
141
+ const reported = roles[role].map((topic) => state.entities[topic]).filter((value) => value !== undefined);
142
+ if (!reported.length)
143
+ return null;
144
+ return reported.some((value) => value === true);
145
+ }
146
+ // Each occupancy role that changed, presence first: at a start, presence
147
+ // holds the room before motion's "off" could empty it.
148
+ function sendRoles(roles, baseline) {
149
+ for (const role of ["presence", "motion"]) {
150
+ const value = roleValue(roles, role);
151
+ if (value === null || value === state[role])
152
+ continue;
153
+ state[role] = value;
154
+ occupancy.push(baseline ? { source: role, payload: value, baseline: true } : { source: role, payload: value });
155
+ trace(role, baseline ? "baseline" : "changed", null, { value });
156
+ }
157
+ }
158
+ const retained = msg.retain === true;
159
+ const topic = typeof msg.topic === "string" ? msg.topic : "";
160
+ const discovery = topic.split("/");
161
+ const prefixParts = config.discoveryPrefix.split("/").length;
162
+ if (topic.startsWith(`${config.discoveryPrefix}/`) && discovery.length === prefixParts + 4 && discovery.at(-1) === "config" &&
163
+ discovery[prefixParts + 1] === config.device) {
164
+ const component = discovery[prefixParts];
165
+ const object = discovery[prefixParts + 2];
166
+ const payload = text(msg.payload);
167
+ if (component !== "binary_sensor" && component !== "sensor") {
168
+ trace("discovery", "ignored", "other-component", { component, object });
169
+ }
170
+ else if (payload === "") {
171
+ // An entity removed from the device.
172
+ delete state.discovered[topic];
173
+ trace("discovery", "removed", null, { object });
174
+ }
175
+ else {
176
+ const entity = discoveredEntity(component, object, payload);
177
+ if (entity === "disabled") {
178
+ delete state.discovered[topic];
179
+ trace("discovery", "ignored", "disabled", { object });
180
+ }
181
+ else if (!entity) {
182
+ trace("discovery", "ignored", "no-state-topic", { object });
183
+ }
184
+ else {
185
+ state.discovered[topic] = entity;
186
+ }
187
+ }
188
+ const after = esphomeRoles(state, config);
189
+ if (JSON.stringify(after) !== JSON.stringify(before)) {
190
+ const preset = presetRoles(config, "preset");
191
+ // Discovery wins over the preset; where they differ, it's traced.
192
+ const differs = after.source === "discovered" &&
193
+ ["motion", "presence", "illuminance"].some((role) => JSON.stringify([...after[role]].sort()) !== JSON.stringify([...preset[role]].sort()));
194
+ trace("roles", after.source, differs ? "differs-from-preset" : null, { motion: after.motion, presence: after.presence, illuminance: after.illuminance });
195
+ }
196
+ }
197
+ else if (before.status.includes(topic)) {
198
+ const status = text(msg.payload).toLowerCase();
199
+ if (status !== "online" && status !== "offline") {
200
+ trace("availability", "ignored", "not-online-or-offline", { status });
201
+ }
202
+ else {
203
+ state.online = status === "online";
204
+ trace("availability", status);
205
+ if (state.online && state.awaitingStatus) {
206
+ // The retained states held for this: the room as it is at start.
207
+ state.awaitingStatus = false;
208
+ sendRoles(before, true);
209
+ }
210
+ else if (!state.online) {
211
+ // A device that isn't online: what it last retained isn't current.
212
+ state.awaitingStatus = false;
213
+ if (retained)
214
+ state.entities = {};
215
+ }
216
+ }
217
+ }
218
+ else if (before.motion.includes(topic) || before.presence.includes(topic)) {
219
+ const value = text(msg.payload).toUpperCase();
220
+ if (value !== "ON" && value !== "OFF") {
221
+ // A fixed contract: only ON and OFF pass.
222
+ trace("state", "ignored", "not-on-or-off", { topic, value });
223
+ }
224
+ else if (retained && state.online === false) {
225
+ trace("state", "ignored", "retained-while-offline", { topic });
226
+ }
227
+ else {
228
+ state.entities[topic] = value === "ON";
229
+ if (retained && state.online !== true) {
230
+ state.awaitingStatus = true;
231
+ trace("state", "held", "awaiting-status", { topic });
232
+ }
233
+ else {
234
+ sendRoles(before, retained);
235
+ }
236
+ }
237
+ }
238
+ else if (before.illuminance.includes(topic)) {
239
+ const lux = Number(text(msg.payload));
240
+ if (text(msg.payload) === "" || !Number.isFinite(lux)) {
241
+ // A fixed contract: only a number passes ("nan" doesn't).
242
+ trace("illuminance", "ignored", "not-a-number", { value: text(msg.payload) });
243
+ }
244
+ else if (retained && state.online === false) {
245
+ trace("illuminance", "ignored", "retained-while-offline");
246
+ }
247
+ else if (lux !== state.illuminance) {
248
+ state.illuminance = lux;
249
+ light.push({ source: "illuminance", payload: lux });
250
+ trace("illuminance", "changed", null, { lux });
251
+ }
252
+ }
253
+ else {
254
+ trace("message", "ignored", "other-topic", { topic: topic || null });
255
+ }
256
+ const roles = esphomeRoles(state, config);
257
+ // Every topic the node needs now: it subscribes to any it hasn't yet.
258
+ const topics = [...new Set([esphomeSensorTopics(config).discovery, ...roles.status, ...roles.presence, ...roles.motion, ...roles.illuminance])];
259
+ return { state, occupancy, light, traces, roles, topics };
260
+ }
261
+ //# sourceMappingURL=esphome-sensor.js.map
@@ -17,11 +17,12 @@ const circadian_schedule_1 = require("./circadian-schedule");
17
17
  // the compiler copy package.json into dist/, which isn't published.
18
18
  const manifest = require("../../package.json");
19
19
  // Home Assistant's `origin` block, abbreviated `o`, with its `name`,
20
- // `sw` (software version) and `url` (support URL).
20
+ // `sw` (software version) and `url` (support URL): the repository, where
21
+ // issues are raised.
21
22
  exports.DISCOVERY_ORIGIN = Object.freeze({
22
23
  name: manifest.name,
23
24
  sw: manifest.version,
24
- url: manifest.homepage.split("#")[0]
25
+ url: manifest.repository.url.replace(/^git\+/, "").replace(/\.git$/, "")
25
26
  });
26
27
  // Home Assistant's default discovery prefix.
27
28
  exports.DEFAULT_DISCOVERY_PREFIX = "homeassistant";
@@ -10,6 +10,7 @@ export interface OccupancyState {
10
10
  export interface OccupancyInput {
11
11
  source: string;
12
12
  payload: unknown;
13
+ baseline?: boolean;
13
14
  }
14
15
  export interface OccupancyConfig {
15
16
  presenceMode?: "hold" | "ignore";
@@ -78,7 +78,13 @@ function transitionOccupancy(saved, input, config) {
78
78
  const wasActive = state.motionActive;
79
79
  state.motionKnown = true;
80
80
  state.motionActive = active;
81
- if (active) {
81
+ if (active && input.baseline === true) {
82
+ // Someone is there as Node-RED starts: occupied, but nothing is sent,
83
+ // so no light is switched on. Motion acts from its next change.
84
+ state.occupied = true;
85
+ trace("motion", "baseline", "occupied-at-start");
86
+ }
87
+ else if (active) {
82
88
  state.occupied = true;
83
89
  if (!wasKnown || !wasActive) {
84
90
  emit(true, "motion-active", "motion");
@@ -106,7 +112,14 @@ function transitionOccupancy(saved, input, config) {
106
112
  const wasActive = state.presenceActive;
107
113
  state.presenceKnown = true;
108
114
  state.presenceActive = active;
109
- if (active) {
115
+ if (active && input.baseline === true) {
116
+ // Presence as Node-RED starts is someone there: it holds the room as
117
+ // occupied, sending nothing, though live presence alone never starts
118
+ // occupancy.
119
+ state.occupied = true;
120
+ trace("presence", "baseline", "occupied-at-start");
121
+ }
122
+ else if (active) {
110
123
  trace("presence", state.occupied ? "held" : "standby", state.occupied ? "presence-active" : "motion-required");
111
124
  }
112
125
  else if (!state.motionActive && (!wasKnown || wasActive || state.occupied)) {
@@ -10,7 +10,10 @@ export interface SceneConfig {
10
10
  owner: string;
11
11
  lights: SceneLight[];
12
12
  safetyMs: number;
13
+ endBelowWatts: number | null;
14
+ endBelowMs: number;
13
15
  }
16
+ export declare const DEFAULT_END_BELOW_SECONDS = 60;
14
17
  export declare const DEFAULT_SAFETY_HOURS = 4;
15
18
  export declare const RENEW_MS = 60000;
16
19
  export interface SceneState {
@@ -26,10 +29,13 @@ export interface SceneState {
26
29
  by: string;
27
30
  at: number;
28
31
  } | null;
32
+ powerBelowSince: number | null;
33
+ powerUsed: boolean;
29
34
  }
30
35
  export interface SceneEvent {
31
36
  kind?: unknown;
32
37
  by?: unknown;
38
+ watts?: unknown;
33
39
  }
34
40
  export interface SceneLighting {
35
41
  lighting: Record<string, unknown>;
@@ -43,6 +49,8 @@ export declare function normaliseSceneConfig(raw: {
43
49
  owner: string;
44
50
  lights?: unknown;
45
51
  safetyHours?: unknown;
52
+ endBelowWatts?: unknown;
53
+ endBelowSeconds?: unknown;
46
54
  }): SceneConfig;
47
55
  export declare function createSceneState(saved?: Partial<SceneState>): SceneState;
48
56
  export declare function transitionScene(saved: Partial<SceneState> | undefined, msg: {
@@ -58,4 +66,4 @@ export declare function transitionScene(saved: Partial<SceneState> | undefined,
58
66
  text: string;
59
67
  };
60
68
  };
61
- export declare function sceneTickAt(state: SceneState, now: number): number | null;
69
+ export declare function sceneTickAt(state: SceneState, now: number, config?: Pick<SceneConfig, "endBelowMs">): number | null;
package/dist/lib/scene.js CHANGED
@@ -1,12 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.RENEW_MS = exports.DEFAULT_SAFETY_HOURS = void 0;
3
+ exports.RENEW_MS = exports.DEFAULT_SAFETY_HOURS = exports.DEFAULT_END_BELOW_SECONDS = void 0;
4
4
  exports.normaliseSceneConfig = normaliseSceneConfig;
5
5
  exports.createSceneState = createSceneState;
6
6
  exports.transitionScene = transitionScene;
7
7
  exports.sceneTickAt = sceneTickAt;
8
8
  const settings_1 = require("./settings");
9
9
  const topic_names_1 = require("./topic-names");
10
+ exports.DEFAULT_END_BELOW_SECONDS = 60;
10
11
  exports.DEFAULT_SAFETY_HOURS = 4;
11
12
  // How often an active scene renews its motion pause and its status: well
12
13
  // within the motion policy's maximum pause (10 minutes by default).
@@ -58,7 +59,15 @@ function normaliseSceneConfig(raw) {
58
59
  const hours = (0, settings_1.numberSetting)(raw.safetyHours, "safety timer", exports.DEFAULT_SAFETY_HOURS);
59
60
  if (hours < 0)
60
61
  throw new Error("safety timer must be 0 (off) or more hours");
61
- return { owner: raw.owner, lights, safetyMs: Math.round(hours * 3_600_000) };
62
+ // Optional: empty (or a scene saved before it) means no power end.
63
+ const below = raw.endBelowWatts === undefined || raw.endBelowWatts === null || String(raw.endBelowWatts).trim() === ""
64
+ ? null : (0, settings_1.numberSetting)(raw.endBelowWatts, "end below", 0);
65
+ if (below !== null && below <= 0)
66
+ throw new Error("end below must be more than 0 watts, or empty for none");
67
+ const seconds = (0, settings_1.numberSetting)(raw.endBelowSeconds, "end below for", exports.DEFAULT_END_BELOW_SECONDS);
68
+ if (seconds < 0)
69
+ throw new Error("end below for must be 0 or more seconds");
70
+ return { owner: raw.owner, lights, safetyMs: Math.round(hours * 3_600_000), endBelowWatts: below, endBelowMs: Math.round(seconds * 1000) };
62
71
  }
63
72
  function createSceneState(saved = {}) {
64
73
  const active = saved.active === true && typeof saved.owner === "string";
@@ -70,7 +79,9 @@ function createSceneState(saved = {}) {
70
79
  : [],
71
80
  startedAt: active && Number.isFinite(saved.startedAt) ? saved.startedAt : null,
72
81
  endsAt: active && Number.isFinite(saved.endsAt) ? saved.endsAt : null,
73
- ended: saved.ended && typeof saved.ended.by === "string" && Number.isFinite(saved.ended.at) ? { ...saved.ended } : null
82
+ ended: saved.ended && typeof saved.ended.by === "string" && Number.isFinite(saved.ended.at) ? { ...saved.ended } : null,
83
+ powerBelowSince: active && Number.isFinite(saved.powerBelowSince) ? saved.powerBelowSince : null,
84
+ powerUsed: active && saved.powerUsed === true
74
85
  };
75
86
  }
76
87
  // How a span of time reads on the status: "3h 59m", "12m", "under 1m".
@@ -101,7 +112,7 @@ function transitionScene(saved, msg, config, nowValue = new Date()) {
101
112
  lighting.push({ lighting: { kind: "release", area, owner, targets, source: "scene" } });
102
113
  pause(false);
103
114
  trace("scene", "ended", null, { by, owner });
104
- Object.assign(state, { active: false, owner: null, lights: [], startedAt: null, endsAt: null, ended: { by, at: now } });
115
+ Object.assign(state, { active: false, owner: null, lights: [], startedAt: null, endsAt: null, ended: { by, at: now }, powerBelowSince: null, powerUsed: false });
105
116
  }
106
117
  if (kind === "start") {
107
118
  if (state.active) {
@@ -117,7 +128,9 @@ function transitionScene(saved, msg, config, nowValue = new Date()) {
117
128
  owner: config.owner,
118
129
  lights: config.lights.map(({ area, target }) => ({ area, target })),
119
130
  startedAt: now,
120
- endsAt: config.safetyMs > 0 ? now + config.safetyMs : null
131
+ endsAt: config.safetyMs > 0 ? now + config.safetyMs : null,
132
+ powerBelowSince: null,
133
+ powerUsed: false
121
134
  });
122
135
  for (const light of config.lights) {
123
136
  const values = {
@@ -137,12 +150,47 @@ function transitionScene(saved, msg, config, nowValue = new Date()) {
137
150
  else
138
151
  trace("scene", "ignored", "not-active");
139
152
  }
153
+ else if (kind === "power") {
154
+ const watts = Number(event.watts);
155
+ if (!state.active) {
156
+ trace("power", "ignored", "not-active");
157
+ }
158
+ else if (config.endBelowWatts === null) {
159
+ trace("power", "ignored", "no-end-below");
160
+ }
161
+ else if (!Number.isFinite(watts) || watts < 0) {
162
+ trace("power", "ignored", "not-watts");
163
+ }
164
+ else if (watts >= config.endBelowWatts) {
165
+ if (!state.powerUsed)
166
+ trace("power", "used", null, { watts });
167
+ else if (state.powerBelowSince !== null)
168
+ trace("power", "above", null, { watts });
169
+ state.powerUsed = true;
170
+ state.powerBelowSince = null;
171
+ }
172
+ else if (!state.powerUsed) {
173
+ // Not used yet since it started: a standby draw doesn't end it.
174
+ trace("power", "ignored", "not-used-yet", { watts });
175
+ }
176
+ else {
177
+ if (state.powerBelowSince === null) {
178
+ state.powerBelowSince = now;
179
+ trace("power", "below", null, { watts, endBelowWatts: config.endBelowWatts });
180
+ }
181
+ if (now - state.powerBelowSince >= config.endBelowMs)
182
+ end("power");
183
+ }
184
+ }
140
185
  else if (kind === "tick" || kind === "startup") {
141
186
  // Its timer, or the flows starting again (a redeploy or restart with a
142
187
  // context store): end it if its time is up, otherwise renew its pause.
143
188
  // Its lights are not asked again: the rooms still hold them.
144
189
  if (state.active && state.endsAt !== null && state.endsAt <= now)
145
190
  end("timer");
191
+ else if (state.active && state.powerBelowSince !== null && config.endBelowWatts !== null &&
192
+ now - state.powerBelowSince >= config.endBelowMs)
193
+ end("power");
146
194
  else if (state.active)
147
195
  pause(true);
148
196
  }
@@ -161,10 +209,15 @@ function transitionScene(saved, msg, config, nowValue = new Date()) {
161
209
  }
162
210
  // When it next needs a tick: its next renewal, or its safety timer's end if
163
211
  // sooner. Null when off.
164
- function sceneTickAt(state, now) {
212
+ function sceneTickAt(state, now, config) {
165
213
  if (!state.active)
166
214
  return null;
167
- const renew = now + exports.RENEW_MS;
168
- return state.endsAt !== null ? Math.min(renew, state.endsAt) : renew;
215
+ const at = [now + exports.RENEW_MS];
216
+ if (state.endsAt !== null)
217
+ at.push(state.endsAt);
218
+ // When power held below its End below would end it.
219
+ if (state.powerBelowSince !== null && config)
220
+ at.push(state.powerBelowSince + config.endBelowMs);
221
+ return Math.min(...at);
169
222
  }
170
223
  //# sourceMappingURL=scene.js.map
@@ -1,3 +1,4 @@
1
+ import { type TargetObservationOutput } from "./target-observation";
1
2
  import { type Carried } from "./adopted-request";
2
3
  import type { TraceEntry } from "./bounded-trace";
3
4
  import { type TargetStateEvent } from "./target-state";
@@ -57,6 +58,7 @@ export interface SourceState {
57
58
  refreshAsked: boolean;
58
59
  adoptedGeneration: number | null;
59
60
  carried?: Carried | null;
61
+ probe?: Record<string, SourceObservationStatus | null> | null;
60
62
  }
61
63
  export type SourceEvent = {
62
64
  kind: "intent";
@@ -100,7 +102,7 @@ export declare function normaliseConfig(config?: {
100
102
  export interface SourceCommand {
101
103
  sourceId: string | null;
102
104
  operation: SourceAction | "observe";
103
- requestId: string;
105
+ requestId: string | null;
104
106
  generation: number;
105
107
  attempt: number;
106
108
  }
@@ -140,6 +142,7 @@ export declare function transitionSource(saved: Partial<SourceState> | undefined
140
142
  state: SourceState;
141
143
  commands: SourceCommand[];
142
144
  events: SourceOutputEvent[];
145
+ observations: TargetObservationOutput[];
143
146
  traces: TraceEntry<Record<string, unknown>>[];
144
147
  status: {
145
148
  phase: string;