@avantics/node-red-home-automation 6.1.0 → 6.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 (115) hide show
  1. package/README.md +260 -46
  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/cover-publishing.js +20 -6
  9. package/dist/lib/display-mode-controller.d.ts +3 -0
  10. package/dist/lib/display-mode-controller.js +43 -16
  11. package/dist/lib/esphome-sensor.d.ts +73 -0
  12. package/dist/lib/esphome-sensor.js +261 -0
  13. package/dist/lib/home-assistant-setting.d.ts +23 -0
  14. package/dist/lib/home-assistant-setting.js +39 -0
  15. package/dist/lib/motion-policy.d.ts +1 -0
  16. package/dist/lib/motion-policy.js +21 -1
  17. package/dist/lib/occupancy-fusion.d.ts +1 -0
  18. package/dist/lib/occupancy-fusion.js +15 -2
  19. package/dist/lib/room-controller.d.ts +1 -0
  20. package/dist/lib/room-controller.js +5 -0
  21. package/dist/lib/room-publishing.d.ts +1 -0
  22. package/dist/lib/room-publishing.js +11 -0
  23. package/dist/lib/scene-publishing.d.ts +30 -0
  24. package/dist/lib/scene-publishing.js +63 -0
  25. package/dist/lib/scene.d.ts +69 -0
  26. package/dist/lib/scene.js +223 -0
  27. package/dist/lib/shelly-cover.js +5 -0
  28. package/dist/lib/shelly-relay-light.d.ts +24 -0
  29. package/dist/lib/shelly-relay-light.js +93 -0
  30. package/dist/lib/shelly-switch.d.ts +8 -0
  31. package/dist/lib/shelly-switch.js +37 -8
  32. package/dist/lib/source-capability-controller.d.ts +4 -1
  33. package/dist/lib/source-capability-controller.js +49 -2
  34. package/dist/lib/target-observation.d.ts +14 -0
  35. package/dist/lib/target-observation.js +22 -0
  36. package/dist/lib/theatre-activity-controller.d.ts +5 -0
  37. package/dist/lib/theatre-activity-controller.js +91 -12
  38. package/dist/lib/theatre-metrics.js +6 -4
  39. package/dist/lib/theatre-slo.js +3 -0
  40. package/dist/lib/theatre-state-contract.d.ts +4 -2
  41. package/dist/lib/theatre-state-contract.js +51 -8
  42. package/dist/lib/theatre-state.d.ts +2 -0
  43. package/dist/lib/theatre-state.js +13 -1
  44. package/dist/lib/wled.d.ts +48 -0
  45. package/dist/lib/wled.js +105 -0
  46. package/dist/lib/z2m-power.d.ts +38 -0
  47. package/dist/lib/z2m-power.js +83 -0
  48. package/dist/lib/z2m-sensor.d.ts +37 -0
  49. package/dist/lib/z2m-sensor.js +88 -0
  50. package/dist/nodes/apollo-r-pro-1.d.ts +2 -0
  51. package/dist/nodes/apollo-r-pro-1.html +80 -0
  52. package/dist/nodes/apollo-r-pro-1.js +4 -0
  53. package/dist/nodes/avr-controller.html +82 -21
  54. package/dist/nodes/avr-controller.js +24 -12
  55. package/dist/nodes/backlighting-controller.js +3 -2
  56. package/dist/nodes/circadian-policy.html +84 -20
  57. package/dist/nodes/circadian-policy.js +30 -11
  58. package/dist/nodes/cover-controller.html +87 -25
  59. package/dist/nodes/cover-controller.js +25 -12
  60. package/dist/nodes/device-side.d.ts +21 -0
  61. package/dist/nodes/device-side.js +76 -0
  62. package/dist/nodes/display-mode-controller.js +11 -2
  63. package/dist/nodes/esphome-sensor.d.ts +2 -0
  64. package/dist/nodes/esphome-sensor.js +77 -0
  65. package/dist/nodes/everything-presence-one.d.ts +2 -0
  66. package/dist/nodes/everything-presence-one.html +78 -0
  67. package/dist/nodes/everything-presence-one.js +4 -0
  68. package/dist/nodes/home-assistant-discovery.d.ts +26 -0
  69. package/dist/nodes/home-assistant-discovery.js +64 -0
  70. package/dist/nodes/house-schedule-mqtt.html +70 -5
  71. package/dist/nodes/house-schedule-mqtt.js +22 -8
  72. package/dist/nodes/motion-policy.html +87 -22
  73. package/dist/nodes/motion-policy.js +44 -11
  74. package/dist/nodes/mqtt-broker-link.d.ts +41 -0
  75. package/dist/nodes/mqtt-broker-link.js +91 -0
  76. package/dist/nodes/occupancy-fusion.html +86 -20
  77. package/dist/nodes/occupancy-fusion.js +25 -12
  78. package/dist/nodes/publishing-side.d.ts +20 -0
  79. package/dist/nodes/publishing-side.js +66 -0
  80. package/dist/nodes/room-controller.html +106 -35
  81. package/dist/nodes/room-controller.js +63 -16
  82. package/dist/nodes/scene.d.ts +3 -0
  83. package/dist/nodes/scene.html +247 -0
  84. package/dist/nodes/scene.js +128 -0
  85. package/dist/nodes/shelly-cover.html +47 -2
  86. package/dist/nodes/shelly-cover.js +19 -4
  87. package/dist/nodes/shelly-switch.html +76 -6
  88. package/dist/nodes/shelly-switch.js +32 -7
  89. package/dist/nodes/source-capability-controller.js +3 -2
  90. package/dist/nodes/theatre-activity-controller.html +4 -2
  91. package/dist/nodes/theatre-state-contract.html +72 -9
  92. package/dist/nodes/theatre-state-contract.js +33 -14
  93. package/dist/nodes/wled.d.ts +3 -0
  94. package/dist/nodes/wled.html +56 -0
  95. package/dist/nodes/wled.js +53 -0
  96. package/dist/nodes/z2m-cover.html +47 -2
  97. package/dist/nodes/z2m-cover.js +21 -4
  98. package/dist/nodes/z2m-light.html +49 -3
  99. package/dist/nodes/z2m-light.js +40 -4
  100. package/dist/nodes/z2m-power.d.ts +3 -0
  101. package/dist/nodes/z2m-power.html +58 -0
  102. package/dist/nodes/z2m-power.js +53 -0
  103. package/dist/nodes/z2m-sensor.d.ts +3 -0
  104. package/dist/nodes/z2m-sensor.html +69 -0
  105. package/dist/nodes/z2m-sensor.js +62 -0
  106. package/examples/Cover control.json +38 -91
  107. package/examples/Cover pair.json +36 -3
  108. package/examples/Home theatre activity.json +46 -91
  109. package/examples/Home theatre equipment.json +34 -2
  110. package/examples/House schedule.json +58 -80
  111. package/examples/Room lighting.json +45 -44
  112. package/examples/Scene.json +167 -0
  113. package/examples/Shelly cover.json +36 -105
  114. package/examples/Shelly switch.json +52 -148
  115. package/package.json +8 -2
@@ -0,0 +1,23 @@
1
+ export declare const HOME_ASSISTANT_CHOICES: readonly ["off", "state", "discovery"];
2
+ export type HomeAssistantChoice = typeof HOME_ASSISTANT_CHOICES[number];
3
+ export declare function homeAssistantSetting(config: {
4
+ homeAssistant?: unknown;
5
+ publishState?: unknown;
6
+ discovery?: unknown;
7
+ }, unsetMeans: {
8
+ publishState: boolean;
9
+ discovery: boolean;
10
+ }): HomeAssistantChoice;
11
+ export declare function publishingChoice(config: {
12
+ homeAssistant?: unknown;
13
+ publishState?: unknown;
14
+ discovery?: unknown;
15
+ }, unsetMeans: {
16
+ publishState: boolean;
17
+ discovery: boolean;
18
+ }): {
19
+ choice: HomeAssistantChoice;
20
+ publishState: boolean;
21
+ discovery: boolean;
22
+ needsArea: boolean;
23
+ };
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HOME_ASSISTANT_CHOICES = void 0;
4
+ exports.homeAssistantSetting = homeAssistantSetting;
5
+ exports.publishingChoice = publishingChoice;
6
+ // The one publishing setting a node has, Publish in the editor: off ("Don't
7
+ // publish"), state ("MQTT state": its state and availability as retained
8
+ // MQTT topics, plain MQTT) or discovery ("MQTT state and Home Assistant
9
+ // discovery": its entities announced to Home Assistant too, which read that
10
+ // state). It replaced two on/off settings, publishState and discovery, which
11
+ // stay in a node's saved flow: a node saved before reads as they said.
12
+ // Decided by the person on 2026-11-28.
13
+ const settings_1 = require("./settings");
14
+ exports.HOME_ASSISTANT_CHOICES = ["off", "state", "discovery"];
15
+ // The choice, or for a node saved before it, its two old settings: off/off
16
+ // is off, on/off state only, on/on state and discovery (discovery needs the
17
+ // state). `unsetMeans` is what an old setting not set at all meant for this
18
+ // node: on for the room's publishing, so a saved flow behaves the same.
19
+ function homeAssistantSetting(config, unsetMeans) {
20
+ const choice = (0, settings_1.optionalChoiceSetting)(config.homeAssistant, "Home Assistant", exports.HOME_ASSISTANT_CHOICES);
21
+ if (choice)
22
+ return choice;
23
+ const state = (0, settings_1.optionalBooleanSetting)(config.publishState, "publish state") ?? unsetMeans.publishState;
24
+ const discovery = (0, settings_1.optionalBooleanSetting)(config.discovery, "Home Assistant discovery") ?? unsetMeans.discovery;
25
+ return !state ? "off" : discovery ? "discovery" : "state";
26
+ }
27
+ // The choice as a node's publishing reads it, and whether it needs an area:
28
+ // with the choice set, unless off; for a node saved before it, whenever
29
+ // either old setting was on, even discovery alone, which published nothing:
30
+ // as each node checked it before the choice.
31
+ function publishingChoice(config, unsetMeans) {
32
+ const choice = homeAssistantSetting(config, unsetMeans);
33
+ const saved = config.homeAssistant === undefined || config.homeAssistant === null;
34
+ const needsArea = choice !== "off" || (saved &&
35
+ (((0, settings_1.optionalBooleanSetting)(config.publishState, "publish state") ?? unsetMeans.publishState) ||
36
+ ((0, settings_1.optionalBooleanSetting)(config.discovery, "Home Assistant discovery") ?? unsetMeans.discovery)));
37
+ return { choice, publishState: choice !== "off", discovery: choice === "discovery", needsArea };
38
+ }
39
+ //# sourceMappingURL=home-assistant-setting.js.map
@@ -17,6 +17,7 @@ export interface MotionState {
17
17
  offTimerGeneration: number;
18
18
  offTimerDueAt: number | null;
19
19
  offTimerArmedAt: number | null;
20
+ vacantSince: number | null;
20
21
  pausedBy: Array<{
21
22
  owner: string;
22
23
  until: number;
@@ -50,7 +50,8 @@ function createMotionState(config, saved = {}) {
50
50
  delaySecondsSetting: config.defaultDelaySeconds,
51
51
  offTimerGeneration: Number(saved.offTimerGeneration) || 0,
52
52
  offTimerDueAt: Number(saved.offTimerDueAt) || null,
53
- offTimerArmedAt: Number(saved.offTimerArmedAt) || null
53
+ offTimerArmedAt: Number(saved.offTimerArmedAt) || null,
54
+ vacantSince: Number(saved.vacantSince) || null
54
55
  };
55
56
  }
56
57
  function lightingIntent(targets, state, source, extra = {}) {
@@ -69,6 +70,9 @@ function transitionMotion(saved, input, config, globalEnabled, now = Date.now())
69
70
  const effects = [];
70
71
  const traces = [];
71
72
  let nextGlobalEnabled = globalEnabled !== false;
73
+ // Whether motion could act before this input, counting a pause that has
74
+ // just run out, so its running out resumes motion like a release.
75
+ const wasEnabled = state.areaEnabled && nextGlobalEnabled && state.pausedBy.length === 0;
72
76
  // A pause past its time counts as released, even if its owner never said.
73
77
  for (const pause of state.pausedBy.filter(({ until }) => until <= now)) {
74
78
  traces.push({ event: "pause", outcome: "expired", reason: null, details: { owner: pause.owner } });
@@ -182,6 +186,7 @@ function transitionMotion(saved, input, config, globalEnabled, now = Date.now())
182
186
  : {};
183
187
  const occupied = payloadRecord.occupied === true;
184
188
  if (occupied) {
189
+ state.vacantSince = null;
185
190
  cancelOffTimer("occupancy-detected");
186
191
  const darkEnough = state.illuminance === null || state.illuminance <= state.illuminanceCutoff;
187
192
  const shouldEmit = enabled() && darkEnough;
@@ -199,6 +204,7 @@ function transitionMotion(saved, input, config, globalEnabled, now = Date.now())
199
204
  });
200
205
  }
201
206
  else {
207
+ state.vacantSince = now;
202
208
  if (enabled())
203
209
  scheduleOffTimer();
204
210
  else
@@ -251,9 +257,14 @@ function transitionMotion(saved, input, config, globalEnabled, now = Date.now())
251
257
  const vacantSince = new Date(state.offTimerArmedAt ?? now).toISOString();
252
258
  state.offTimerDueAt = null;
253
259
  state.offTimerArmedAt = null;
260
+ state.vacantSince = null;
254
261
  emitIntent(lightingIntent(config.offTargets, "OFF", "motion", { vacantSince }), "off-timer");
255
262
  }
256
263
  }
264
+ else if (source === "pause-check") {
265
+ // The node's own wake-up as a pause runs out: dropped above, and motion
266
+ // resumes below.
267
+ }
257
268
  else if (source === "cold-start") {
258
269
  // Started with nothing saved: a first deploy, or a redeploy or restart
259
270
  // without a context store, when a running off-timer was lost. Whether the
@@ -267,6 +278,15 @@ function transitionMotion(saved, input, config, globalEnabled, now = Date.now())
267
278
  else if (source.startsWith("switch")) {
268
279
  trace("message", "ignored", "wall switches belong to the switch policy", { source });
269
280
  }
281
+ // Motion resumed (a pause released or run out, or enabled again) in a room
282
+ // that went vacant meanwhile: the vacancy delay starts now, and the off
283
+ // intent names when the room went vacant.
284
+ if (!wasEnabled && enabled() && state.vacantSince !== null && state.offTimerDueAt === null) {
285
+ const vacantSince = state.vacantSince;
286
+ scheduleOffTimer();
287
+ state.offTimerArmedAt = vacantSince;
288
+ trace("off-timer", "scheduled", "resumed-vacant", { vacantSince: new Date(vacantSince).toISOString() });
289
+ }
270
290
  return {
271
291
  state,
272
292
  globalEnabled: nextGlobalEnabled,
@@ -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)) {
@@ -57,6 +57,7 @@ export interface RoomState {
57
57
  }
58
58
  export interface LightingEvent {
59
59
  kind?: string;
60
+ area?: string;
60
61
  targets?: string[];
61
62
  target?: string;
62
63
  state?: string;
@@ -8,6 +8,7 @@ exports.intentValues = intentValues;
8
8
  exports.transitionRoom = transitionRoom;
9
9
  const light_contract_1 = require("./light-contract");
10
10
  const z2m_light_1 = require("./z2m-light");
11
+ const topic_names_1 = require("./topic-names");
11
12
  const room_holds_1 = require("./room-holds");
12
13
  const command_echo_1 = require("./command-echo");
13
14
  var command_echo_2 = require("./command-echo");
@@ -546,6 +547,10 @@ function transitionRoom(saved, msg, config, nowValue = new Date()) {
546
547
  restyleLights(next.source);
547
548
  }
548
549
  }
550
+ else if ((event.kind === "intent" || event.kind === "release") && typeof event.area === "string" && (0, topic_names_1.areaId)(event.area) !== (0, topic_names_1.areaId)(config.area)) {
551
+ // For another room.
552
+ trace(event.kind, "ignored", "other-area", { area: event.area, source: event.source || event.kind });
553
+ }
549
554
  else if (event.kind === "release") {
550
555
  // An owner name lets go of that owner's lights; none lets go of every
551
556
  // owner's. A light goes to the owner beneath, with what it asked for, or
@@ -18,6 +18,7 @@ export declare function withoutCircadianState(recorded: readonly string[]): stri
18
18
  export declare function roomPublishesState(config: PublishSettings): boolean;
19
19
  export declare function roomPublishesDiscovery(config: PublishSettings): boolean;
20
20
  export declare function roomStartingOutputs(config: PublishingRoomConfig): RoomOutput[];
21
+ export declare function roomAnnouncement(config: PublishingRoomConfig, saved: Partial<RoomState> | undefined): RoomOutput[];
21
22
  export declare function roomStoppingOutputs(config: PublishSettings): RoomOutput[];
22
23
  export declare function publishRoom(saved: Partial<RoomState> | undefined, msg: RoomMessage, config: PublishingRoomConfig, now?: Date | string | number): {
23
24
  state: RoomState;
@@ -5,6 +5,7 @@ exports.withoutCircadianState = withoutCircadianState;
5
5
  exports.roomPublishesState = roomPublishesState;
6
6
  exports.roomPublishesDiscovery = roomPublishesDiscovery;
7
7
  exports.roomStartingOutputs = roomStartingOutputs;
8
+ exports.roomAnnouncement = roomAnnouncement;
8
9
  exports.roomStoppingOutputs = roomStoppingOutputs;
9
10
  exports.publishRoom = publishRoom;
10
11
  // The room's MQTT and Home Assistant side, as the theatre state contract is
@@ -85,6 +86,16 @@ function roomStartingOutputs(config) {
85
86
  function roomStartupOutputs(config) {
86
87
  return [...oldCircadianClears(config), ...roomDiscoveryOutputs(config), ...(roomPublishesState(config) ? [(0, room_lighting_discovery_1.roomAvailabilityMessage)(config.area, true)] : [])];
87
88
  }
89
+ // Everything the room announces when its broker connects, or Home
90
+ // Assistant comes back: as at the startup message, then every light's
91
+ // control state, so Home Assistant has all of it again.
92
+ function roomAnnouncement(config, saved) {
93
+ const state = (0, room_controller_1.createRoomState)(config, saved);
94
+ return [
95
+ ...roomStartupOutputs(config),
96
+ ...(roomPublishesState(config) ? config.targets.map((target) => controlMessage(config, state, target.id)) : [])
97
+ ];
98
+ }
88
99
  function roomStoppingOutputs(config) {
89
100
  return roomPublishesState(config) ? [(0, room_lighting_discovery_1.roomAvailabilityMessage)(config.area, false)] : [];
90
101
  }
@@ -0,0 +1,30 @@
1
+ import type { TraceEntry } from "./bounded-trace";
2
+ import { type OptInPublishingConfig, type RetainedText } from "./publishing-node";
3
+ export interface ScenePublishingConfig extends OptInPublishingConfig {
4
+ name: string;
5
+ }
6
+ export declare const sceneStateTopic: (config: {
7
+ area: string;
8
+ name: string;
9
+ }) => string;
10
+ export declare const sceneCommandTopic: (config: {
11
+ area: string;
12
+ name: string;
13
+ }) => string;
14
+ export declare const sceneAvailabilityTopic: (config: {
15
+ area: string;
16
+ name: string;
17
+ }) => string;
18
+ export declare function sceneDiscovery(config: ScenePublishingConfig): RetainedText[];
19
+ export declare function sceneStateOutputs(config: ScenePublishingConfig, active: boolean): RetainedText[];
20
+ export declare const sceneStartingOutputs: (config: ScenePublishingConfig, state: boolean) => RetainedText[];
21
+ export declare const sceneStoppingOutputs: (config: ScenePublishingConfig) => RetainedText[];
22
+ export declare const sceneRetainedTopics: (config: ScenePublishingConfig) => string[];
23
+ export declare function sceneInbound(msg: {
24
+ topic?: unknown;
25
+ payload?: unknown;
26
+ retain?: unknown;
27
+ }, config: ScenePublishingConfig): {
28
+ kind: "start" | "end" | null;
29
+ traces: TraceEntry[];
30
+ } | null;
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sceneRetainedTopics = exports.sceneStoppingOutputs = exports.sceneStartingOutputs = exports.sceneAvailabilityTopic = exports.sceneCommandTopic = exports.sceneStateTopic = void 0;
4
+ exports.sceneDiscovery = sceneDiscovery;
5
+ exports.sceneStateOutputs = sceneStateOutputs;
6
+ exports.sceneInbound = sceneInbound;
7
+ const publishing_node_1 = require("./publishing-node");
8
+ const topic_names_1 = require("./topic-names");
9
+ function sceneTopic(config, path) {
10
+ return (0, topic_names_1.homeTopic)(config.area, "scene", (0, topic_names_1.areaId)(config.name), path);
11
+ }
12
+ const sceneStateTopic = (config) => sceneTopic(config, "state");
13
+ exports.sceneStateTopic = sceneStateTopic;
14
+ const sceneCommandTopic = (config) => sceneTopic(config, "set");
15
+ exports.sceneCommandTopic = sceneCommandTopic;
16
+ const sceneAvailabilityTopic = (config) => sceneTopic(config, "availability");
17
+ exports.sceneAvailabilityTopic = sceneAvailabilityTopic;
18
+ function sceneDiscovery(config) {
19
+ return [
20
+ (0, publishing_node_1.discoveryEntry)(config, { kind: "scene_" + (0, topic_names_1.areaId)(config.name), label: "Scene " + config.name, model: "Scene" }, (0, exports.sceneAvailabilityTopic)(config), {
21
+ component: "switch",
22
+ id: "scene_" + (0, topic_names_1.areaId)(config.name),
23
+ name: config.name,
24
+ fields: {
25
+ icon: "mdi:palette",
26
+ command_topic: (0, exports.sceneCommandTopic)(config),
27
+ state_topic: (0, exports.sceneStateTopic)(config),
28
+ payload_on: "ON",
29
+ payload_off: "OFF",
30
+ optimistic: false
31
+ }
32
+ })
33
+ ];
34
+ }
35
+ function sceneStateOutputs(config, active) {
36
+ return (0, publishing_node_1.publishesState)(config) ? [(0, publishing_node_1.retainedText)((0, exports.sceneStateTopic)(config), active ? "ON" : "OFF")] : [];
37
+ }
38
+ const scene = (0, publishing_node_1.publishingNode)({
39
+ entries: sceneDiscovery,
40
+ availabilityTopic: (_area, config) => (0, exports.sceneAvailabilityTopic)(config),
41
+ stateTopics: (config) => [(0, exports.sceneStateTopic)(config)],
42
+ stateOutputs: sceneStateOutputs
43
+ });
44
+ exports.sceneStartingOutputs = scene.starting;
45
+ exports.sceneStoppingOutputs = scene.stopping;
46
+ exports.sceneRetainedTopics = scene.retainedTopics;
47
+ // Home Assistant's ON or OFF on the scene's set topic, as a start or an end.
48
+ // Read only while it publishes; retained messages and anything else are
49
+ // ignored with a trace. Anything on another topic passes through (null).
50
+ function sceneInbound(msg, config) {
51
+ if (!(0, publishing_node_1.publishesState)(config) || msg.topic !== (0, exports.sceneCommandTopic)(config))
52
+ return null;
53
+ const ignored = (reason, details = {}) => ({ kind: null, traces: [{ event: "command-set", outcome: "ignored", reason, details }] });
54
+ if (msg.retain === true)
55
+ return ignored("retained-message");
56
+ const text = typeof msg.payload === "string" ? msg.payload.trim().toUpperCase() : "";
57
+ if (text === "ON")
58
+ return { kind: "start", traces: [] };
59
+ if (text === "OFF")
60
+ return { kind: "end", traces: [] };
61
+ return ignored("not-on-or-off", { payload: typeof msg.payload === "string" ? msg.payload : typeof msg.payload });
62
+ }
63
+ //# sourceMappingURL=scene-publishing.js.map
@@ -0,0 +1,69 @@
1
+ import type { TraceEntry } from "./bounded-trace";
2
+ export interface SceneLight {
3
+ area: string;
4
+ target: string;
5
+ state: "ON" | "OFF";
6
+ brightnessPct?: number;
7
+ colorTempKelvin?: number;
8
+ }
9
+ export interface SceneConfig {
10
+ owner: string;
11
+ lights: SceneLight[];
12
+ safetyMs: number;
13
+ endBelowWatts: number | null;
14
+ endBelowMs: number;
15
+ }
16
+ export declare const DEFAULT_END_BELOW_SECONDS = 60;
17
+ export declare const DEFAULT_SAFETY_HOURS = 4;
18
+ export declare const RENEW_MS = 60000;
19
+ export interface SceneState {
20
+ active: boolean;
21
+ owner: string | null;
22
+ lights: Array<{
23
+ area: string;
24
+ target: string;
25
+ }>;
26
+ startedAt: number | null;
27
+ endsAt: number | null;
28
+ ended: {
29
+ by: string;
30
+ at: number;
31
+ } | null;
32
+ powerBelowSince: number | null;
33
+ powerUsed: boolean;
34
+ }
35
+ export interface SceneEvent {
36
+ kind?: unknown;
37
+ by?: unknown;
38
+ watts?: unknown;
39
+ }
40
+ export interface SceneLighting {
41
+ lighting: Record<string, unknown>;
42
+ }
43
+ export interface SceneMotion {
44
+ source: "pause";
45
+ payload: boolean;
46
+ owner: string;
47
+ }
48
+ export declare function normaliseSceneConfig(raw: {
49
+ owner: string;
50
+ lights?: unknown;
51
+ safetyHours?: unknown;
52
+ endBelowWatts?: unknown;
53
+ endBelowSeconds?: unknown;
54
+ }): SceneConfig;
55
+ export declare function createSceneState(saved?: Partial<SceneState>): SceneState;
56
+ export declare function transitionScene(saved: Partial<SceneState> | undefined, msg: {
57
+ scene?: SceneEvent;
58
+ }, config: SceneConfig, nowValue?: Date | string | number): {
59
+ state: SceneState;
60
+ lighting: SceneLighting[];
61
+ motion: SceneMotion[];
62
+ traces: TraceEntry<Record<string, unknown>>[];
63
+ status: {
64
+ fill: string;
65
+ shape: string;
66
+ text: string;
67
+ };
68
+ };
69
+ export declare function sceneTickAt(state: SceneState, now: number, config?: Pick<SceneConfig, "endBelowMs">): number | null;
@@ -0,0 +1,223 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RENEW_MS = exports.DEFAULT_SAFETY_HOURS = exports.DEFAULT_END_BELOW_SECONDS = void 0;
4
+ exports.normaliseSceneConfig = normaliseSceneConfig;
5
+ exports.createSceneState = createSceneState;
6
+ exports.transitionScene = transitionScene;
7
+ exports.sceneTickAt = sceneTickAt;
8
+ const settings_1 = require("./settings");
9
+ const topic_names_1 = require("./topic-names");
10
+ exports.DEFAULT_END_BELOW_SECONDS = 60;
11
+ exports.DEFAULT_SAFETY_HOURS = 4;
12
+ // How often an active scene renews its motion pause and its status: well
13
+ // within the motion policy's maximum pause (10 minutes by default).
14
+ exports.RENEW_MS = 60_000;
15
+ function normaliseSceneConfig(raw) {
16
+ const parsed = (0, settings_1.jsonSetting)(raw.lights, "lights", []);
17
+ if (!Array.isArray(parsed))
18
+ throw new Error("lights must be a JSON array");
19
+ const seen = new Set();
20
+ const lights = parsed.map((entry, index) => {
21
+ const at = `light ${index + 1}`;
22
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
23
+ throw new Error(`${at} must be an object`);
24
+ const light = entry;
25
+ const target = typeof light.target === "string" ? light.target.trim() : "";
26
+ if (!target)
27
+ throw new Error(`${at} needs a target: the light's id in its room controller`);
28
+ const area = typeof light.area === "string" ? light.area.trim() : "";
29
+ if (!(0, topic_names_1.areaId)(area))
30
+ throw new Error(`${at} (${target}) needs an area: its room controller's Area`);
31
+ const key = (0, topic_names_1.areaId)(area) + "/" + target;
32
+ if (seen.has(key))
33
+ throw new Error(`${at}: ${target} in ${area} is listed twice`);
34
+ seen.add(key);
35
+ const state = String(light.state ?? "").toUpperCase();
36
+ if (state !== "ON" && state !== "OFF")
37
+ throw new Error(`${at} (${target}): state must be ON or OFF`);
38
+ const scene = { area, target, state };
39
+ for (const key of ["brightnessPct", "colorTempKelvin"]) {
40
+ if (light[key] === undefined)
41
+ continue;
42
+ const value = light[key];
43
+ if (typeof value !== "number" || !Number.isFinite(value))
44
+ throw new Error(`${at} (${target}): ${key} must be a number`);
45
+ if (key === "brightnessPct" && (value < 0 || value > 100))
46
+ throw new Error(`${at} (${target}): brightnessPct must be 0-100`);
47
+ if (key === "colorTempKelvin" && value <= 0)
48
+ throw new Error(`${at} (${target}): colorTempKelvin must be above 0`);
49
+ if (state === "OFF")
50
+ throw new Error(`${at} (${target}): an OFF light takes no ${key}`);
51
+ scene[key] = value;
52
+ }
53
+ for (const key of Object.keys(light)) {
54
+ if (!["area", "target", "state", "brightnessPct", "colorTempKelvin"].includes(key))
55
+ throw new Error(`${at} (${target}): unknown field ${key}`);
56
+ }
57
+ return scene;
58
+ });
59
+ const hours = (0, settings_1.numberSetting)(raw.safetyHours, "safety timer", exports.DEFAULT_SAFETY_HOURS);
60
+ if (hours < 0)
61
+ throw new Error("safety timer must be 0 (off) or more hours");
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) };
71
+ }
72
+ function createSceneState(saved = {}) {
73
+ const active = saved.active === true && typeof saved.owner === "string";
74
+ return {
75
+ active,
76
+ owner: active ? saved.owner : null,
77
+ lights: active && Array.isArray(saved.lights)
78
+ ? saved.lights.filter((light) => typeof light?.area === "string" && typeof light.target === "string").map(({ area, target }) => ({ area, target }))
79
+ : [],
80
+ startedAt: active && Number.isFinite(saved.startedAt) ? saved.startedAt : null,
81
+ endsAt: active && Number.isFinite(saved.endsAt) ? saved.endsAt : 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
85
+ };
86
+ }
87
+ // How a span of time reads on the status: "3h 59m", "12m", "under 1m".
88
+ function span(ms) {
89
+ const minutes = Math.floor(ms / 60_000);
90
+ if (minutes < 1)
91
+ return "under 1m";
92
+ const hours = Math.floor(minutes / 60);
93
+ return hours ? `${hours}h ${minutes % 60}m` : `${minutes}m`;
94
+ }
95
+ function transitionScene(saved, msg, config, nowValue = new Date()) {
96
+ const now = (nowValue instanceof Date ? nowValue : new Date(nowValue)).getTime();
97
+ const state = createSceneState(saved);
98
+ const lighting = [];
99
+ const motion = [];
100
+ const traces = [];
101
+ const trace = (event, outcome, reason = null, details = {}) => traces.push({ event, outcome, reason, details });
102
+ const event = msg.scene && typeof msg.scene === "object" ? msg.scene : {};
103
+ const kind = String(event.kind ?? "");
104
+ const pause = (on) => motion.push({ source: "pause", payload: on, owner: state.owner });
105
+ function end(by) {
106
+ const owner = state.owner;
107
+ // One release per room, for the lights it took there.
108
+ const rooms = new Map();
109
+ for (const { area, target } of state.lights)
110
+ rooms.set(area, [...(rooms.get(area) ?? []), target]);
111
+ for (const [area, targets] of rooms)
112
+ lighting.push({ lighting: { kind: "release", area, owner, targets, source: "scene" } });
113
+ pause(false);
114
+ trace("scene", "ended", null, { by, owner });
115
+ Object.assign(state, { active: false, owner: null, lights: [], startedAt: null, endsAt: null, ended: { by, at: now }, powerBelowSince: null, powerUsed: false });
116
+ }
117
+ if (kind === "start") {
118
+ if (state.active) {
119
+ // On again: a fresh safety timer; its lights are left as they are, so
120
+ // a person's change during the scene stands.
121
+ state.endsAt = config.safetyMs > 0 ? now + config.safetyMs : null;
122
+ pause(true);
123
+ trace("scene", "renewed", null, { owner: state.owner });
124
+ }
125
+ else {
126
+ Object.assign(state, {
127
+ active: true,
128
+ owner: config.owner,
129
+ lights: config.lights.map(({ area, target }) => ({ area, target })),
130
+ startedAt: now,
131
+ endsAt: config.safetyMs > 0 ? now + config.safetyMs : null,
132
+ powerBelowSince: null,
133
+ powerUsed: false
134
+ });
135
+ for (const light of config.lights) {
136
+ const values = {
137
+ ...(light.brightnessPct !== undefined ? { brightnessPct: light.brightnessPct } : {}),
138
+ ...(light.colorTempKelvin !== undefined ? { colorTempKelvin: light.colorTempKelvin } : {})
139
+ };
140
+ lighting.push({ lighting: { kind: "intent", area: light.area, targets: [light.target], state: light.state, owner: config.owner, source: "scene",
141
+ ...(Object.keys(values).length ? { values } : {}) } });
142
+ }
143
+ pause(true);
144
+ trace("scene", "started", null, { owner: config.owner, lights: state.lights });
145
+ }
146
+ }
147
+ else if (kind === "end") {
148
+ if (state.active)
149
+ end(typeof event.by === "string" && event.by.trim() ? event.by.trim() : "request");
150
+ else
151
+ trace("scene", "ignored", "not-active");
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
+ }
185
+ else if (kind === "tick" || kind === "startup") {
186
+ // Its timer, or the flows starting again (a redeploy or restart with a
187
+ // context store): end it if its time is up, otherwise renew its pause.
188
+ // Its lights are not asked again: the rooms still hold them.
189
+ if (state.active && state.endsAt !== null && state.endsAt <= now)
190
+ end("timer");
191
+ else if (state.active && state.powerBelowSince !== null && config.endBelowWatts !== null &&
192
+ now - state.powerBelowSince >= config.endBelowMs)
193
+ end("power");
194
+ else if (state.active)
195
+ pause(true);
196
+ }
197
+ else {
198
+ trace("input", "ignored", "not-a-scene-message");
199
+ }
200
+ return {
201
+ state,
202
+ lighting,
203
+ motion,
204
+ traces,
205
+ status: state.active
206
+ ? { fill: "green", shape: "dot", text: "on" + (state.endsAt !== null ? ` · ${span(state.endsAt - now)} left` : "") }
207
+ : { fill: "grey", shape: state.ended ? "dot" : "ring", text: state.ended ? `off · ended by ${state.ended.by}` : "off" }
208
+ };
209
+ }
210
+ // When it next needs a tick: its next renewal, or its safety timer's end if
211
+ // sooner. Null when off.
212
+ function sceneTickAt(state, now, config) {
213
+ if (!state.active)
214
+ return null;
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);
222
+ }
223
+ //# sourceMappingURL=scene.js.map
@@ -100,6 +100,11 @@ function transitionShellyCover(saved, msg, config, now) {
100
100
  trace("command", "sent", null, { operation, position });
101
101
  }
102
102
  }
103
+ else if (operation === "observe" && !Number.isInteger(generation)) {
104
+ // Its own read on connecting, not the controller's: no command for the
105
+ // reply to answer.
106
+ requestStatus("connected");
107
+ }
103
108
  else if (operation === "stop" || operation === "observe") {
104
109
  state.command = { operation, generation };
105
110
  // observe asks for the device's full status, so the reading is fresh.