@avantics/node-red-home-automation 3.0.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/README.md +285 -13
  2. package/dist/lib/activity-lighting-controller.d.ts +7 -1
  3. package/dist/lib/activity-lighting-controller.js +37 -3
  4. package/dist/lib/adopted-request.d.ts +26 -0
  5. package/dist/lib/adopted-request.js +44 -0
  6. package/dist/lib/avr-controller.d.ts +8 -1
  7. package/dist/lib/avr-controller.js +27 -3
  8. package/dist/lib/avr-publishing.d.ts +24 -0
  9. package/dist/lib/avr-publishing.js +80 -0
  10. package/dist/lib/backlighting-controller.d.ts +7 -1
  11. package/dist/lib/backlighting-controller.js +26 -3
  12. package/dist/lib/circadian.d.ts +1 -0
  13. package/dist/lib/circadian.js +3 -0
  14. package/dist/lib/command-echo.d.ts +2 -0
  15. package/dist/lib/command-echo.js +39 -15
  16. package/dist/lib/cover-availability.d.ts +7 -0
  17. package/dist/lib/cover-availability.js +24 -0
  18. package/dist/lib/cover-controller.d.ts +13 -1
  19. package/dist/lib/cover-controller.js +113 -30
  20. package/dist/lib/cover-group.d.ts +62 -0
  21. package/dist/lib/cover-group.js +125 -0
  22. package/dist/lib/cover-models.d.ts +37 -0
  23. package/dist/lib/cover-models.js +83 -0
  24. package/dist/lib/cover-publishing.d.ts +40 -0
  25. package/dist/lib/cover-publishing.js +102 -0
  26. package/dist/lib/cover-requests.d.ts +21 -0
  27. package/dist/lib/cover-requests.js +49 -0
  28. package/dist/lib/display-mode-controller.d.ts +4 -0
  29. package/dist/lib/display-mode-controller.js +26 -2
  30. package/dist/lib/ha-discovery.d.ts +27 -0
  31. package/dist/lib/ha-discovery.js +91 -0
  32. package/dist/lib/house-schedule-publishing.d.ts +23 -0
  33. package/dist/lib/house-schedule-publishing.js +71 -0
  34. package/dist/lib/house-schedule.d.ts +23 -0
  35. package/dist/lib/house-schedule.js +29 -0
  36. package/dist/lib/motion-policy.d.ts +9 -0
  37. package/dist/lib/motion-policy.js +45 -11
  38. package/dist/lib/motion-publishing.d.ts +28 -0
  39. package/dist/lib/motion-publishing.js +92 -0
  40. package/dist/lib/occupancy-publishing.d.ts +10 -0
  41. package/dist/lib/occupancy-publishing.js +45 -0
  42. package/dist/lib/open-close-cover.d.ts +92 -0
  43. package/dist/lib/open-close-cover.js +287 -0
  44. package/dist/lib/publishing-node.d.ts +39 -0
  45. package/dist/lib/publishing-node.js +72 -0
  46. package/dist/lib/retained-topics.d.ts +10 -0
  47. package/dist/lib/retained-topics.js +19 -0
  48. package/dist/lib/room-controller.d.ts +10 -0
  49. package/dist/lib/room-controller.js +68 -59
  50. package/dist/lib/room-lighting-discovery.d.ts +20 -1
  51. package/dist/lib/room-lighting-discovery.js +135 -13
  52. package/dist/lib/room-publishing.d.ts +42 -0
  53. package/dist/lib/room-publishing.js +182 -0
  54. package/dist/lib/room-schedule.d.ts +8 -0
  55. package/dist/lib/room-schedule.js +41 -0
  56. package/dist/lib/settings.d.ts +2 -0
  57. package/dist/lib/settings.js +20 -0
  58. package/dist/lib/source-capability-controller.d.ts +8 -1
  59. package/dist/lib/source-capability-controller.js +29 -3
  60. package/dist/lib/theatre-activity-controller.d.ts +0 -1
  61. package/dist/lib/theatre-activity-controller.js +27 -24
  62. package/dist/lib/theatre-ha-discovery.d.ts +3 -4
  63. package/dist/lib/theatre-ha-discovery.js +46 -36
  64. package/dist/lib/theatre-state-contract.d.ts +6 -0
  65. package/dist/lib/theatre-state-contract.js +83 -47
  66. package/dist/lib/theatre-state.d.ts +1 -1
  67. package/dist/lib/theatre-state.js +1 -1
  68. package/dist/lib/topic-names.d.ts +4 -0
  69. package/dist/lib/topic-names.js +31 -0
  70. package/dist/nodes/activity-lighting-controller.js +5 -3
  71. package/dist/nodes/adapter.d.ts +6 -1
  72. package/dist/nodes/adapter.js +65 -1
  73. package/dist/nodes/avr-controller.html +59 -5
  74. package/dist/nodes/avr-controller.js +74 -4
  75. package/dist/nodes/backlighting-controller.js +5 -3
  76. package/dist/nodes/cover-controller.d.ts +3 -0
  77. package/dist/nodes/cover-controller.html +177 -0
  78. package/dist/nodes/cover-controller.js +178 -0
  79. package/dist/nodes/cover-group.d.ts +3 -0
  80. package/dist/nodes/cover-group.html +89 -0
  81. package/dist/nodes/cover-group.js +84 -0
  82. package/dist/nodes/flows-started.d.ts +4 -0
  83. package/dist/nodes/flows-started.js +39 -0
  84. package/dist/nodes/house-schedule-mqtt.d.ts +3 -0
  85. package/dist/nodes/house-schedule-mqtt.html +61 -0
  86. package/dist/nodes/house-schedule-mqtt.js +80 -0
  87. package/dist/nodes/house-schedule.d.ts +3 -0
  88. package/dist/nodes/house-schedule.html +31 -0
  89. package/dist/nodes/house-schedule.js +51 -0
  90. package/dist/nodes/motion-policy.html +81 -5
  91. package/dist/nodes/motion-policy.js +69 -8
  92. package/dist/nodes/occupancy-fusion.html +69 -14
  93. package/dist/nodes/occupancy-fusion.js +46 -4
  94. package/dist/nodes/publishing-lifecycle.d.ts +25 -0
  95. package/dist/nodes/publishing-lifecycle.js +38 -0
  96. package/dist/nodes/room-controller.html +54 -5
  97. package/dist/nodes/room-controller.js +67 -8
  98. package/dist/nodes/shared-schedule.d.ts +6 -0
  99. package/dist/nodes/shared-schedule.js +15 -0
  100. package/dist/nodes/source-capability-controller.js +5 -3
  101. package/dist/nodes/theatre-activity-controller.html +1 -3
  102. package/dist/nodes/theatre-activity-controller.js +1 -2
  103. package/dist/nodes/theatre-state-contract.html +28 -5
  104. package/dist/nodes/theatre-state-contract.js +22 -4
  105. package/examples/Cover control.json +380 -0
  106. package/examples/Cover pair.json +230 -0
  107. package/examples/Home theatre activity.json +4 -4
  108. package/examples/House schedule.json +164 -0
  109. package/examples/Room lighting.json +4 -3
  110. package/package.json +6 -2
@@ -0,0 +1,21 @@
1
+ import type { CoverEvent } from "./cover-controller";
2
+ export type CoverPresets = Record<string, number>;
3
+ export declare function coverPresets(value: unknown): CoverPresets;
4
+ export interface CoverRequestInput {
5
+ payload?: unknown;
6
+ stopIfMoving?: unknown;
7
+ respectManual?: unknown;
8
+ source?: unknown;
9
+ }
10
+ type Intent = Extract<CoverEvent, {
11
+ requestId: string;
12
+ }>;
13
+ export declare function coverRequest(input: CoverRequestInput, presets: CoverPresets, ids: {
14
+ requestId: string;
15
+ generation: number;
16
+ }, moving?: boolean): {
17
+ intent: Intent;
18
+ } | {
19
+ invalid: string;
20
+ };
21
+ export {};
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.coverPresets = coverPresets;
4
+ exports.coverRequest = coverRequest;
5
+ const settings_1 = require("./settings");
6
+ const PRESET_NAME = /^[a-z][a-z0-9_-]*$/;
7
+ // Named positions, such as {"partial": 60}, from the node's setting.
8
+ function coverPresets(value) {
9
+ const parsed = (0, settings_1.jsonSetting)(value, "presets", {});
10
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
11
+ throw new Error("presets must be a JSON object");
12
+ const presets = {};
13
+ for (const [name, position] of Object.entries(parsed)) {
14
+ if (!PRESET_NAME.test(name) || ["open", "close", "stop"].includes(name)) {
15
+ throw new Error(`preset name ${name} must be a lowercase identifier other than open, close and stop`);
16
+ }
17
+ if (typeof position !== "number" || !Number.isFinite(position) || position < 0 || position > 100) {
18
+ throw new Error(`preset ${name} must be a position from 0 to 100`);
19
+ }
20
+ presets[name] = position;
21
+ }
22
+ return presets;
23
+ }
24
+ // The request a message asks for, given the next generation and a request
25
+ // ID; or the reason it asks for nothing usable.
26
+ function coverRequest(input, presets, ids,
27
+ // Whether the cover is moving now, as the controller judges it.
28
+ moving = false) {
29
+ const base = {
30
+ ...ids,
31
+ ...(typeof input.source === "string" && input.source ? { source: input.source } : {}),
32
+ ...(input.respectManual === true ? { respectManual: true } : {})
33
+ };
34
+ const payload = typeof input.payload === "string" ? input.payload.trim().toLowerCase() : input.payload;
35
+ if (input.stopIfMoving === true && moving)
36
+ return { intent: { ...base, kind: "stop" } };
37
+ if (payload === "open" || payload === "close" || payload === "stop")
38
+ return { intent: { ...base, kind: payload } };
39
+ const position = typeof payload === "number" ? payload
40
+ : typeof payload === "string" && /^\d+(\.\d+)?$/.test(payload) ? Number(payload)
41
+ : typeof payload === "string" && Object.hasOwn(presets, payload) ? presets[payload]
42
+ : null;
43
+ if (position === null)
44
+ return { invalid: "unknown-request" };
45
+ if (!Number.isFinite(position) || position < 0 || position > 100)
46
+ return { invalid: "position-out-of-range" };
47
+ return { intent: { ...base, kind: "set_position", position } };
48
+ }
49
+ //# sourceMappingURL=cover-requests.js.map
@@ -80,6 +80,7 @@ export interface DisplayState {
80
80
  classification: "manual_override" | null;
81
81
  lastAttempt: number;
82
82
  fallbackUsed: boolean;
83
+ adoptedGeneration: number | null;
83
84
  }
84
85
  export type DisplayInputEvent = {
85
86
  kind: "startup";
@@ -109,6 +110,9 @@ export type DisplayInputEvent = {
109
110
  generation?: number;
110
111
  } | {
111
112
  kind: "refresh";
113
+ requestId?: string | null;
114
+ generation?: number;
115
+ mode?: string;
112
116
  };
113
117
  export interface DisplayMessage {
114
118
  display?: DisplayInputEvent;
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.classifyProjectorPower = classifyProjectorPower;
4
4
  exports.normaliseConfig = normaliseConfig;
5
5
  exports.transitionDisplay = transitionDisplay;
6
+ const adopted_request_1 = require("./adopted-request");
6
7
  const settings_1 = require("./settings");
7
8
  const observation_time_1 = require("./observation-time");
8
9
  const target_state_1 = require("./target-state");
@@ -26,7 +27,8 @@ function initialState(saved = {}) {
26
27
  lastAttempt: Number.isInteger(saved.lastAttempt) && (saved.lastAttempt ?? -1) >= 0
27
28
  ? saved.lastAttempt
28
29
  : 0,
29
- fallbackUsed: saved.fallbackUsed === true
30
+ fallbackUsed: saved.fallbackUsed === true,
31
+ adoptedGeneration: (0, adopted_request_1.savedAdoptedGeneration)(saved)
30
32
  };
31
33
  }
32
34
  function classifyProjectorPower(watts, previous = "unknown", config = {}) {
@@ -431,7 +433,18 @@ function transitionDisplay(saved, msg, suppliedConfig = {}, now = new Date()) {
431
433
  }
432
434
  if (!event || typeof event.kind !== "string")
433
435
  throw new Error("msg.display.kind is required");
434
- if (event.kind === "startup") {
436
+ // A refresh with the activity's wanted values, reaching a node with
437
+ // nothing desired (it started with nothing saved): adopt them, and
438
+ // rediscover below as at startup (see adopted-request.ts).
439
+ const adoptable = event.kind === "refresh" ? (0, adopted_request_1.adoptableRefresh)(event, state) : null;
440
+ const adopted = adoptable !== null && event.kind === "refresh" && typeof event.mode === "string" && Object.hasOwn(MODES, event.mode);
441
+ if (adopted) {
442
+ state.desired = { ...adoptable, mode: event.mode };
443
+ state.generation = adoptable.generation;
444
+ state.adoptedGeneration = adoptable.generation;
445
+ trace("refresh", "adopted", "nothing-desired", { mode: event.mode, generation: adoptable.generation });
446
+ }
447
+ if (event.kind === "startup" || adopted) {
435
448
  // A projector power operation in flight cannot be repeated safely (a
436
449
  // second toggle can switch a warming lamp off), so it survives startup
437
450
  // and is only re-observed; everything else is rediscovered.
@@ -530,6 +543,17 @@ function transitionDisplay(saved, msg, suppliedConfig = {}, now = new Date()) {
530
543
  // reports ready only with a reading taken in this event, stamped with the
531
544
  // oldest of the device readings every mode relies on, so it is only as
532
545
  // fresh as its least recent confirmation.
546
+ // An adopted request only reads the device (see adopted-request.ts): a
547
+ // power, toggle or screen command means the display isn't as wanted.
548
+ const held = (0, adopted_request_1.readsOnly)(state, commands, (command) => command.operation.startsWith("query"));
549
+ if (held.mismatch) {
550
+ commands.splice(0, commands.length, ...held.commands);
551
+ state.pending = null;
552
+ state.classification = "manual_override";
553
+ state.phase = "manual_override";
554
+ events.push(displayEvent("manual_override", state, { reason: adopted_request_1.ADOPTED_MISMATCH }));
555
+ trace("command", "withheld", adopted_request_1.ADOPTED_MISMATCH);
556
+ }
533
557
  if (state.desired) {
534
558
  const readings = DEVICES.map((device) => (0, observation_time_1.parseObservedAt)(state.observed[device]?.observedAt));
535
559
  const confirmedMs = readings.every((ms) => ms !== null) ? Math.min(...readings) : null;
@@ -0,0 +1,27 @@
1
+ export declare const DISCOVERY_ORIGIN: Readonly<{
2
+ name: string;
3
+ sw: string;
4
+ url: string;
5
+ }>;
6
+ export declare const DEFAULT_DISCOVERY_PREFIX = "homeassistant";
7
+ export declare function discoveryPrefixSetting(value: unknown): string;
8
+ export declare const ONLINE = "online";
9
+ export declare const OFFLINE = "offline";
10
+ export declare const ID_SCHEMES: readonly ["area", "node"];
11
+ export type IdScheme = typeof ID_SCHEMES[number];
12
+ export interface DiscoveryOwner {
13
+ nodeId?: string;
14
+ idScheme?: IdScheme;
15
+ area: string;
16
+ discoveryPrefix: string;
17
+ }
18
+ export declare function discoveryDevice(owner: DiscoveryOwner, kind: string): {
19
+ identifiers: string[];
20
+ };
21
+ export declare function ownDiscoveryTopics(owner: DiscoveryOwner, topics: readonly string[]): string[];
22
+ export declare function discoveryEntity(owner: DiscoveryOwner, component: string, entity: string): {
23
+ topic: string;
24
+ uniqueId: string;
25
+ defaultEntityId: string;
26
+ };
27
+ export declare function timeEntityValue(payload: unknown): string | null;
@@ -0,0 +1,91 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ID_SCHEMES = exports.OFFLINE = exports.ONLINE = exports.DEFAULT_DISCOVERY_PREFIX = exports.DISCOVERY_ORIGIN = void 0;
4
+ exports.discoveryPrefixSetting = discoveryPrefixSetting;
5
+ exports.discoveryDevice = discoveryDevice;
6
+ exports.ownDiscoveryTopics = ownDiscoveryTopics;
7
+ exports.discoveryEntity = discoveryEntity;
8
+ exports.timeEntityValue = timeEntityValue;
9
+ // What every Home Assistant discovery entry shares: the origin that says
10
+ // which software published it, the discovery prefix setting, and the
11
+ // availability payloads.
12
+ const settings_1 = require("./settings");
13
+ const topic_names_1 = require("./topic-names");
14
+ const circadian_schedule_1 = require("./circadian-schedule");
15
+ // The package's own manifest, loaded as a module from the package root (two
16
+ // levels above dist/lib), so no file is read here. A JSON import would make
17
+ // the compiler copy package.json into dist/, which isn't published.
18
+ const manifest = require("../../package.json");
19
+ // Home Assistant's `origin` block, abbreviated `o`, with its `name`,
20
+ // `sw` (software version) and `url` (support URL).
21
+ exports.DISCOVERY_ORIGIN = Object.freeze({
22
+ name: manifest.name,
23
+ sw: manifest.version,
24
+ url: manifest.homepage.split("#")[0]
25
+ });
26
+ // Home Assistant's default discovery prefix.
27
+ exports.DEFAULT_DISCOVERY_PREFIX = "homeassistant";
28
+ // The topic prefix Home Assistant listens on for discovery; absent means
29
+ // Home Assistant's default.
30
+ function discoveryPrefixSetting(value) {
31
+ const prefix = (0, settings_1.textSetting)(value, "discovery prefix", exports.DEFAULT_DISCOVERY_PREFIX).replace(/^\/+|\/+$/g, "");
32
+ if (!prefix || /[+#]/.test(prefix))
33
+ throw new Error("discovery prefix must be a concrete MQTT topic prefix");
34
+ return prefix;
35
+ }
36
+ // A publishing node's availability, retained on its availability topic:
37
+ // online when it starts, offline when it stops. These are Home Assistant's
38
+ // default availability payloads, so entities need only the topic.
39
+ exports.ONLINE = "online";
40
+ exports.OFFLINE = "offline";
41
+ // How a node names its Home Assistant device and entities. "area" is how
42
+ // every node did before node IDs: unique IDs, discovery topics and the
43
+ // device come from the area. "node" names them after the Node-RED node, so
44
+ // they stay the same when the area changes. Saved nodes keep "area"; the
45
+ // editor gives new nodes "node".
46
+ exports.ID_SCHEMES = ["area", "node"];
47
+ // The node's ID in a form fit for unique IDs and discovery topics.
48
+ function nodeKey(nodeId) {
49
+ return "nrha_" + nodeId.replace(/[^A-Za-z0-9_-]+/g, "_");
50
+ }
51
+ // The device that groups a node's entities, one per node. Under "area" it
52
+ // is nodered_<area ID>_<kind>, for example nodered_kitchen_lighting.
53
+ function discoveryDevice(owner, kind) {
54
+ return { identifiers: [owner.idScheme === "node" ? nodeKey(owner.nodeId ?? "") : `nodered_${(0, topic_names_1.areaId)(owner.area)}_${kind}`] };
55
+ }
56
+ // Of the given topics, the discovery topics named after this node itself:
57
+ // under the "node" scheme, those whose object ID is nrha_<node ID>_<entity>
58
+ // (the key ends in "_", and the IDs Node-RED makes never contain one: hex
59
+ // digits, joined with "-" for a node in a subflow, so one node's key can't
60
+ // prefix another's; only an ID written by hand with "_" could). Under
61
+ // "area" none are, since another node may share the area, so a node can
62
+ // clear these without ever touching another node's topics.
63
+ function ownDiscoveryTopics(owner, topics) {
64
+ if (owner.idScheme !== "node" || !owner.nodeId)
65
+ return [];
66
+ const key = nodeKey(owner.nodeId) + "_";
67
+ return topics.filter((topic) => {
68
+ const parts = topic.split("/");
69
+ return topic.startsWith(owner.discoveryPrefix + "/") && parts.at(-1) === "config" && (parts.at(-2) ?? "").startsWith(key);
70
+ });
71
+ }
72
+ // An entity's discovery topic and IDs: the topic's object ID and the unique
73
+ // ID are <area ID>_<entity> under "area" and nrha_<node ID>_<entity> under
74
+ // "node". The entity ID Home Assistant first gives it comes from the area
75
+ // either way, with "-" as "_", since entity IDs allow only lowercase
76
+ // letters, digits and "_".
77
+ function discoveryEntity(owner, component, entity) {
78
+ const uniqueId = (owner.idScheme === "node" ? nodeKey(owner.nodeId ?? "") : (0, topic_names_1.areaId)(owner.area)) + "_" + entity;
79
+ return {
80
+ topic: `${owner.discoveryPrefix}/${component}/${uniqueId}/config`,
81
+ uniqueId,
82
+ defaultEntityId: `${component}.${(0, topic_names_1.areaId)(owner.area).replace(/-/g, "_")}_${entity}`
83
+ };
84
+ }
85
+ // A time from Home Assistant's time entity ("HH:MM:SS", in ISO format), or
86
+ // "HH:MM", as "HH:MM"; null if it isn't one.
87
+ function timeEntityValue(payload) {
88
+ const match = typeof payload === "string" ? /^(\d{2}:\d{2})(?::[0-5]\d(?:\.\d+)?)?$/.exec(payload.trim()) : null;
89
+ return match && (0, circadian_schedule_1.clockMinutes)(match[1]) !== null ? match[1] : null;
90
+ }
91
+ //# sourceMappingURL=ha-discovery.js.map
@@ -0,0 +1,23 @@
1
+ import type { TraceEntry } from "./bounded-trace";
2
+ import type { DaySchedule } from "./circadian-schedule";
3
+ import type { HouseScheduleEvent } from "./house-schedule";
4
+ import { type OptInPublishingConfig, type RetainedText } from "./publishing-node";
5
+ type ScheduleTime = "wake-time" | "bed-time";
6
+ export declare const houseStateTopic: (name: string, which: ScheduleTime) => string;
7
+ export declare const houseCommandTopic: (name: string, which: ScheduleTime) => string;
8
+ export type HouseSchedulePublishingConfig = OptInPublishingConfig;
9
+ export declare const houseAvailabilityTopic: (name: string) => string;
10
+ export declare function houseDiscovery(config: HouseSchedulePublishingConfig): RetainedText[];
11
+ export declare function houseStateOutputs(config: HouseSchedulePublishingConfig, schedule: DaySchedule): RetainedText[];
12
+ export declare const houseStartingOutputs: (config: OptInPublishingConfig, state: DaySchedule) => RetainedText[];
13
+ export declare const houseStoppingOutputs: (config: OptInPublishingConfig) => RetainedText[];
14
+ export declare const houseRetainedTopics: (config: OptInPublishingConfig) => string[];
15
+ export declare function houseInbound(msg: {
16
+ topic?: unknown;
17
+ payload?: unknown;
18
+ retain?: unknown;
19
+ }, config: HouseSchedulePublishingConfig): {
20
+ event: HouseScheduleEvent | null;
21
+ traces: TraceEntry[];
22
+ } | null;
23
+ export {};
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.houseRetainedTopics = exports.houseStoppingOutputs = exports.houseStartingOutputs = exports.houseAvailabilityTopic = exports.houseCommandTopic = exports.houseStateTopic = void 0;
4
+ exports.houseDiscovery = houseDiscovery;
5
+ exports.houseStateOutputs = houseStateOutputs;
6
+ exports.houseInbound = houseInbound;
7
+ const ha_discovery_1 = require("./ha-discovery");
8
+ const publishing_node_1 = require("./publishing-node");
9
+ const topic_names_1 = require("./topic-names");
10
+ // The one place a house schedule topic is named.
11
+ function houseTopic(name, path) {
12
+ return "home/" + (0, topic_names_1.areaId)(name) + "/schedule/" + path;
13
+ }
14
+ const houseStateTopic = (name, which) => houseTopic(name, which + "/state");
15
+ exports.houseStateTopic = houseStateTopic;
16
+ const houseCommandTopic = (name, which) => houseTopic(name, which + "/set");
17
+ exports.houseCommandTopic = houseCommandTopic;
18
+ const DEVICE = { kind: "schedule", label: "Schedule", model: "House schedule" };
19
+ const houseAvailabilityTopic = (name) => houseTopic(name, "availability");
20
+ exports.houseAvailabilityTopic = houseAvailabilityTopic;
21
+ function houseDiscovery(config) {
22
+ const time = (which, id, name, icon) => (0, publishing_node_1.discoveryEntry)(config, DEVICE, (0, exports.houseAvailabilityTopic)(config.area), { component: "time", id, name, fields: {
23
+ icon,
24
+ command_topic: (0, exports.houseCommandTopic)(config.area, which),
25
+ state_topic: (0, exports.houseStateTopic)(config.area, which),
26
+ entity_category: "config"
27
+ } });
28
+ return [
29
+ time("wake-time", "wake_time", "Wake time", "mdi:weather-sunset-up"),
30
+ time("bed-time", "bed_time", "Bed time", "mdi:weather-night")
31
+ ];
32
+ }
33
+ function houseStateOutputs(config, schedule) {
34
+ // "HH:MM:SS", as Home Assistant's time entity reads it.
35
+ return (0, publishing_node_1.publishesState)(config)
36
+ ? [
37
+ (0, publishing_node_1.retainedText)((0, exports.houseStateTopic)(config.area, "wake-time"), schedule.wakeTime + ":00"),
38
+ (0, publishing_node_1.retainedText)((0, exports.houseStateTopic)(config.area, "bed-time"), schedule.bedTime + ":00")
39
+ ]
40
+ : [];
41
+ }
42
+ const house = (0, publishing_node_1.publishingNode)({
43
+ entries: houseDiscovery,
44
+ availabilityTopic: exports.houseAvailabilityTopic,
45
+ stateTopics: (config) => [(0, exports.houseStateTopic)(config.area, "wake-time"), (0, exports.houseStateTopic)(config.area, "bed-time")],
46
+ stateOutputs: houseStateOutputs
47
+ });
48
+ exports.houseStartingOutputs = house.starting;
49
+ exports.houseStoppingOutputs = house.stopping;
50
+ exports.houseRetainedTopics = house.retainedTopics;
51
+ // A time from Home Assistant on the house's wake-time or bed-time set topic,
52
+ // as a schedule event; retained messages and anything but a time are
53
+ // ignored with a trace. Read only while the house publishes.
54
+ function houseInbound(msg, config) {
55
+ if (!(0, publishing_node_1.publishesState)(config))
56
+ return null;
57
+ const which = msg.topic === (0, exports.houseCommandTopic)(config.area, "wake-time") ? "wake-time"
58
+ : msg.topic === (0, exports.houseCommandTopic)(config.area, "bed-time") ? "bed-time"
59
+ : null;
60
+ if (!which)
61
+ return null;
62
+ const name = which + "-set";
63
+ if (msg.retain === true)
64
+ return { event: null, traces: [{ event: name, outcome: "ignored", reason: "retained-message", details: {} }] };
65
+ const time = (0, ha_discovery_1.timeEntityValue)(msg.payload);
66
+ if (time === null) {
67
+ return { event: null, traces: [{ event: name, outcome: "ignored", reason: "not-a-time", details: { payload: typeof msg.payload === "string" ? msg.payload : null } }] };
68
+ }
69
+ return { event: which === "wake-time" ? { kind: "schedule", wakeTime: time } : { kind: "schedule", bedTime: time }, traces: [] };
70
+ }
71
+ //# sourceMappingURL=house-schedule-publishing.js.map
@@ -0,0 +1,23 @@
1
+ import type { TraceEntry } from "./bounded-trace";
2
+ import type { DaySchedule } from "./circadian-schedule";
3
+ export interface HouseScheduleState {
4
+ schedule: DaySchedule;
5
+ scheduleSetting: DaySchedule;
6
+ }
7
+ export interface HouseScheduleEvent {
8
+ kind: "schedule";
9
+ wakeTime?: unknown;
10
+ bedTime?: unknown;
11
+ }
12
+ export interface SharedSchedule {
13
+ readonly name: string;
14
+ schedule(): DaySchedule;
15
+ change(event: HouseScheduleEvent, traces?: TraceEntry[]): void;
16
+ subscribe(listener: (schedule: DaySchedule) => void): () => void;
17
+ }
18
+ export declare function houseScheduleInUse(saved: Partial<HouseScheduleState> | undefined, setting: DaySchedule): DaySchedule;
19
+ export declare function transitionHouseSchedule(saved: Partial<HouseScheduleState> | undefined, event: HouseScheduleEvent, setting: DaySchedule): {
20
+ state: HouseScheduleState;
21
+ changed: boolean;
22
+ traces: TraceEntry<Record<string, unknown>>[];
23
+ };
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.houseScheduleInUse = houseScheduleInUse;
4
+ exports.transitionHouseSchedule = transitionHouseSchedule;
5
+ const room_schedule_1 = require("./room-schedule");
6
+ const settings_1 = require("./settings");
7
+ // The times in use: each saved time while its setting is unchanged.
8
+ function houseScheduleInUse(saved, setting) {
9
+ return {
10
+ wakeTime: (0, settings_1.keptOverride)(saved?.schedule?.wakeTime, saved?.scheduleSetting?.wakeTime, setting.wakeTime),
11
+ bedTime: (0, settings_1.keptOverride)(saved?.schedule?.bedTime, saved?.scheduleSetting?.bedTime, setting.bedTime)
12
+ };
13
+ }
14
+ function transitionHouseSchedule(saved, event, setting) {
15
+ const state = { schedule: houseScheduleInUse(saved, setting), scheduleSetting: { ...setting } };
16
+ const traces = [];
17
+ let changed = false;
18
+ const next = (0, room_schedule_1.requestedSchedule)(state.schedule, event);
19
+ if (!next) {
20
+ traces.push({ event: "schedule", outcome: "ignored", reason: "invalid-times", details: { wakeTime: event.wakeTime, bedTime: event.bedTime } });
21
+ }
22
+ else if (next.wakeTime !== state.schedule.wakeTime || next.bedTime !== state.schedule.bedTime) {
23
+ state.schedule = next;
24
+ traces.push({ event: "schedule", outcome: "changed", reason: null, details: { ...next } });
25
+ changed = true;
26
+ }
27
+ return { state, changed, traces };
28
+ }
29
+ //# sourceMappingURL=house-schedule.js.map
@@ -4,7 +4,9 @@ export interface MotionConfig {
4
4
  defaultDelaySeconds: number;
5
5
  onTargets: string[];
6
6
  offTargets: string[];
7
+ maxPauseSeconds?: number;
7
8
  }
9
+ export declare const DEFAULT_MAX_PAUSE_SECONDS = 600;
8
10
  export interface MotionState {
9
11
  areaEnabled: boolean;
10
12
  illuminance: number | null;
@@ -15,10 +17,15 @@ export interface MotionState {
15
17
  offTimerGeneration: number;
16
18
  offTimerDueAt: number | null;
17
19
  offTimerArmedAt: number | null;
20
+ pausedBy: Array<{
21
+ owner: string;
22
+ until: number;
23
+ }>;
18
24
  }
19
25
  export interface MotionInput {
20
26
  source: string;
21
27
  payload?: unknown;
28
+ owner?: string;
22
29
  generation?: number;
23
30
  }
24
31
  export interface LightingIntent {
@@ -46,6 +53,7 @@ export declare function normaliseMotionConfig(raw: {
46
53
  offTargets?: unknown;
47
54
  defaultDelaySeconds?: unknown;
48
55
  defaultIlluminanceCutoff?: unknown;
56
+ maxPauseSeconds?: unknown;
49
57
  }): MotionConfig;
50
58
  export declare function createMotionState(config: MotionConfig, saved?: Partial<MotionState>): MotionState;
51
59
  export declare function lightingIntent(targets: string[], state: string, source: string, extra?: Record<string, unknown>): LightingIntent;
@@ -56,6 +64,7 @@ export declare function transitionMotion(saved: Partial<MotionState> | undefined
56
64
  traces: TraceEntry<Record<string, unknown>>[];
57
65
  status: {
58
66
  enabled: boolean;
67
+ paused: boolean;
59
68
  illuminance: number | null;
60
69
  delaySeconds: number;
61
70
  };
@@ -1,11 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_MAX_PAUSE_SECONDS = void 0;
3
4
  exports.booleanOn = booleanOn;
4
5
  exports.normaliseMotionConfig = normaliseMotionConfig;
5
6
  exports.createMotionState = createMotionState;
6
7
  exports.lightingIntent = lightingIntent;
7
8
  exports.transitionMotion = transitionMotion;
8
9
  const settings_1 = require("./settings");
10
+ exports.DEFAULT_MAX_PAUSE_SECONDS = 600;
9
11
  function booleanOn(value) {
10
12
  return value === true || (typeof value === "string" && value.toLowerCase() === "on");
11
13
  }
@@ -32,7 +34,8 @@ function normaliseMotionConfig(raw) {
32
34
  onTargets,
33
35
  offTargets: targetList(raw.offTargets, "off targets", onTargets),
34
36
  defaultDelaySeconds: (0, settings_1.numberSetting)(raw.defaultDelaySeconds, "vacancy delay", 120),
35
- defaultIlluminanceCutoff: (0, settings_1.numberSetting)(raw.defaultIlluminanceCutoff, "illuminance cutoff", 10)
37
+ defaultIlluminanceCutoff: (0, settings_1.numberSetting)(raw.defaultIlluminanceCutoff, "illuminance cutoff", 10),
38
+ maxPauseSeconds: Math.max(1, (0, settings_1.numberSetting)(raw.maxPauseSeconds, "maximum pause", exports.DEFAULT_MAX_PAUSE_SECONDS))
36
39
  };
37
40
  }
38
41
  // Saved wall-switch state from earlier versions (wallInput and the older
@@ -40,16 +43,12 @@ function normaliseMotionConfig(raw) {
40
43
  function createMotionState(config, saved = {}) {
41
44
  return {
42
45
  areaEnabled: saved.areaEnabled !== false,
46
+ pausedBy: Array.isArray(saved.pausedBy)
47
+ ? saved.pausedBy.filter((pause) => typeof pause?.owner === "string" && Number.isFinite(pause.until)).map((pause) => ({ ...pause }))
48
+ : [],
43
49
  illuminance: saved.illuminance ?? null,
44
- // A saved value stands only while the setting it was based on is
45
- // unchanged; state saved before this rule recorded none, so the setting
46
- // applies.
47
- illuminanceCutoff: saved.illuminanceCutoffSetting === config.defaultIlluminanceCutoff && saved.illuminanceCutoff !== undefined
48
- ? saved.illuminanceCutoff
49
- : config.defaultIlluminanceCutoff,
50
- delaySeconds: saved.delaySecondsSetting === config.defaultDelaySeconds && saved.delaySeconds !== undefined
51
- ? saved.delaySeconds
52
- : config.defaultDelaySeconds,
50
+ illuminanceCutoff: (0, settings_1.keptOverride)(saved.illuminanceCutoff, saved.illuminanceCutoffSetting, config.defaultIlluminanceCutoff),
51
+ delaySeconds: (0, settings_1.keptOverride)(saved.delaySeconds, saved.delaySecondsSetting, config.defaultDelaySeconds),
53
52
  illuminanceCutoffSetting: config.defaultIlluminanceCutoff,
54
53
  delaySecondsSetting: config.defaultDelaySeconds,
55
54
  offTimerGeneration: Number(saved.offTimerGeneration) || 0,
@@ -73,8 +72,13 @@ function transitionMotion(saved, input, config, globalEnabled, now = Date.now())
73
72
  const effects = [];
74
73
  const traces = [];
75
74
  let nextGlobalEnabled = globalEnabled !== false;
75
+ // A pause past its time counts as released, even if its owner never said.
76
+ for (const pause of state.pausedBy.filter(({ until }) => until <= now)) {
77
+ traces.push({ event: "pause", outcome: "expired", reason: null, details: { owner: pause.owner } });
78
+ }
79
+ state.pausedBy = state.pausedBy.filter(({ until }) => until > now);
76
80
  function enabled() {
77
- return state.areaEnabled && nextGlobalEnabled;
81
+ return state.areaEnabled && nextGlobalEnabled && state.pausedBy.length === 0;
78
82
  }
79
83
  function trace(event, outcome, reason, details = {}) {
80
84
  traces.push({ event, outcome, reason, details });
@@ -123,6 +127,25 @@ function transitionMotion(saved, input, config, globalEnabled, now = Date.now())
123
127
  if (!enabled())
124
128
  cancelOffTimer("motion-disabled");
125
129
  }
130
+ else if (source === "pause") {
131
+ // true pauses for this owner until the maximum pause (sending it again
132
+ // renews it), false releases it; motion resumes once every owner has
133
+ // released, or their pauses have run out.
134
+ const owner = typeof input.owner === "string" ? input.owner.trim() : "";
135
+ if (!owner) {
136
+ trace("pause", "ignored", "owner-required");
137
+ }
138
+ else {
139
+ const pause = payload === true || booleanOn(payload);
140
+ const held = state.pausedBy.some((entry) => entry.owner === owner);
141
+ const others = state.pausedBy.filter((entry) => entry.owner !== owner);
142
+ const until = now + (config.maxPauseSeconds ?? exports.DEFAULT_MAX_PAUSE_SECONDS) * 1000;
143
+ state.pausedBy = pause ? [...others, { owner, until }] : others;
144
+ trace("pause", pause ? (held ? "renewed" : "paused") : held ? "released" : "unchanged", null, { owner, until: pause ? until : null });
145
+ if (!enabled())
146
+ cancelOffTimer("motion-paused");
147
+ }
148
+ }
126
149
  else if (source === "area-enabled") {
127
150
  const previous = state.areaEnabled;
128
151
  state.areaEnabled = booleanOn(payload);
@@ -230,6 +253,16 @@ function transitionMotion(saved, input, config, globalEnabled, now = Date.now())
230
253
  emitIntent(lightingIntent(config.offTargets, "OFF", "motion", { vacantSince }), "off-timer");
231
254
  }
232
255
  }
256
+ else if (source === "cold-start") {
257
+ // Started with nothing saved: a first deploy, or a redeploy or restart
258
+ // without a context store, when a running off-timer was lost. Whether the
259
+ // room is occupied is unknown, so vacancy starts now: the off-timer runs
260
+ // unless occupancy is reported first, so lights left on are never on for
261
+ // good.
262
+ if (enabled())
263
+ scheduleOffTimer();
264
+ trace("start", enabled() ? "schedule-off" : "suppressed", enabled() ? "no-saved-state" : "disabled", { targets: config.offTargets });
265
+ }
233
266
  else if (source.startsWith("switch")) {
234
267
  trace("message", "ignored", "wall switches belong to the switch policy", { source });
235
268
  }
@@ -240,6 +273,7 @@ function transitionMotion(saved, input, config, globalEnabled, now = Date.now())
240
273
  traces,
241
274
  status: {
242
275
  enabled: enabled(),
276
+ paused: state.pausedBy.length > 0,
243
277
  illuminance: state.illuminance,
244
278
  delaySeconds: state.delaySeconds
245
279
  }
@@ -0,0 +1,28 @@
1
+ import type { TraceEntry } from "./bounded-trace";
2
+ import type { MotionInput } from "./motion-policy";
3
+ import { type OptInPublishingConfig, type RetainedText } from "./publishing-node";
4
+ export type MotionPublishingConfig = OptInPublishingConfig;
5
+ export type MotionPublication = RetainedText;
6
+ export declare const MAX_DELAY_SECONDS = 86400;
7
+ export declare const motionEnabledTopic: (area: string, end: "state" | "set") => string;
8
+ export declare const motionDelayTopic: (area: string, end: "state" | "set") => string;
9
+ export declare const motionAvailabilityTopic: (area: string) => string;
10
+ export declare function motionDiscovery(config: MotionPublishingConfig): MotionPublication[];
11
+ export declare function motionStateOutputs(config: MotionPublishingConfig, state: {
12
+ areaEnabled: boolean;
13
+ delaySeconds: number;
14
+ }): MotionPublication[];
15
+ export declare const motionStartingOutputs: (config: OptInPublishingConfig, state: {
16
+ areaEnabled: boolean;
17
+ delaySeconds: number;
18
+ }) => RetainedText[];
19
+ export declare const motionStoppingOutputs: (config: OptInPublishingConfig) => RetainedText[];
20
+ export declare const motionRetainedTopics: (config: OptInPublishingConfig) => string[];
21
+ export declare function motionInbound(msg: {
22
+ topic?: unknown;
23
+ payload?: unknown;
24
+ retain?: unknown;
25
+ }, config: MotionPublishingConfig): {
26
+ input: MotionInput;
27
+ traces: TraceEntry[];
28
+ } | null;