@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,92 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.motionRetainedTopics = exports.motionStoppingOutputs = exports.motionStartingOutputs = exports.motionAvailabilityTopic = exports.motionDelayTopic = exports.motionEnabledTopic = exports.MAX_DELAY_SECONDS = void 0;
4
+ exports.motionDiscovery = motionDiscovery;
5
+ exports.motionStateOutputs = motionStateOutputs;
6
+ exports.motionInbound = motionInbound;
7
+ const topic_names_1 = require("./topic-names");
8
+ const publishing_node_1 = require("./publishing-node");
9
+ // The vacancy delays Home Assistant offers, in seconds: up to a day.
10
+ exports.MAX_DELAY_SECONDS = 86400;
11
+ function motionTopic(area, name) {
12
+ return "home/" + (0, topic_names_1.areaId)(area) + "/motion/" + name;
13
+ }
14
+ const motionEnabledTopic = (area, end) => motionTopic(area, "enabled/" + end);
15
+ exports.motionEnabledTopic = motionEnabledTopic;
16
+ const motionDelayTopic = (area, end) => motionTopic(area, "delay/" + end);
17
+ exports.motionDelayTopic = motionDelayTopic;
18
+ const motionAvailabilityTopic = (area) => motionTopic(area, "availability");
19
+ exports.motionAvailabilityTopic = motionAvailabilityTopic;
20
+ const DEVICE = { kind: "motion", label: "Motion Lighting", model: "Motion lighting policy" };
21
+ // The enable switch and the vacancy delay number, on one device per node.
22
+ function motionDiscovery(config) {
23
+ const availability = (0, exports.motionAvailabilityTopic)(config.area);
24
+ return [
25
+ (0, publishing_node_1.discoveryEntry)(config, DEVICE, availability, { component: "switch", id: "motion_lighting", name: "Motion lighting", fields: {
26
+ icon: "mdi:motion-sensor",
27
+ command_topic: (0, exports.motionEnabledTopic)(config.area, "set"),
28
+ state_topic: (0, exports.motionEnabledTopic)(config.area, "state"),
29
+ payload_on: "ON",
30
+ payload_off: "OFF",
31
+ optimistic: false
32
+ } }),
33
+ (0, publishing_node_1.discoveryEntry)(config, DEVICE, availability, { component: "number", id: "vacancy_delay", name: "Vacancy delay", fields: {
34
+ icon: "mdi:timer-outline",
35
+ command_topic: (0, exports.motionDelayTopic)(config.area, "set"),
36
+ state_topic: (0, exports.motionDelayTopic)(config.area, "state"),
37
+ device_class: "duration",
38
+ unit_of_measurement: "s",
39
+ min: 0,
40
+ max: exports.MAX_DELAY_SECONDS,
41
+ step: 1,
42
+ mode: "box",
43
+ entity_category: "config"
44
+ } })
45
+ ];
46
+ }
47
+ // This node's enable state and vacancy delay, whenever either may change.
48
+ function motionStateOutputs(config, state) {
49
+ if (!(0, publishing_node_1.publishesState)(config))
50
+ return [];
51
+ return [
52
+ (0, publishing_node_1.retainedText)((0, exports.motionEnabledTopic)(config.area, "state"), state.areaEnabled ? "ON" : "OFF"),
53
+ (0, publishing_node_1.retainedText)((0, exports.motionDelayTopic)(config.area, "state"), String(state.delaySeconds))
54
+ ];
55
+ }
56
+ const motion = (0, publishing_node_1.publishingNode)({
57
+ entries: motionDiscovery,
58
+ availabilityTopic: exports.motionAvailabilityTopic,
59
+ stateTopics: (config) => [(0, exports.motionEnabledTopic)(config.area, "state"), (0, exports.motionDelayTopic)(config.area, "state")],
60
+ stateOutputs: motionStateOutputs
61
+ });
62
+ exports.motionStartingOutputs = motion.starting;
63
+ exports.motionStoppingOutputs = motion.stopping;
64
+ exports.motionRetainedTopics = motion.retainedTopics;
65
+ // MQTT the node reads, as its own inputs: ON or OFF on the enable set topic,
66
+ // and a delay in seconds on the delay set topic. Read only while it
67
+ // publishes; retained messages and other payloads are ignored with a trace.
68
+ // Anything else passes through unchanged.
69
+ function motionInbound(msg, config) {
70
+ if (!(0, publishing_node_1.publishesState)(config))
71
+ return null;
72
+ const enabledSet = msg.topic === (0, exports.motionEnabledTopic)(config.area, "set");
73
+ const delaySet = msg.topic === (0, exports.motionDelayTopic)(config.area, "set");
74
+ if (!enabledSet && !delaySet)
75
+ return null;
76
+ const event = enabledSet ? "enabled-set" : "delay-set";
77
+ const ignored = (reason, details = {}) => ({ input: { source: "ignored", payload: undefined }, traces: [{ event, outcome: "ignored", reason, details }] });
78
+ if (msg.retain === true)
79
+ return ignored("retained-message");
80
+ const text = typeof msg.payload === "string" ? msg.payload.trim() : typeof msg.payload === "number" ? String(msg.payload) : "";
81
+ if (enabledSet) {
82
+ const requested = text.toUpperCase();
83
+ if (requested !== "ON" && requested !== "OFF")
84
+ return ignored("not-on-or-off", { payload: text });
85
+ return { input: { source: "area-enabled", payload: requested }, traces: [] };
86
+ }
87
+ const seconds = text === "" ? NaN : Number(text);
88
+ if (!Number.isFinite(seconds) || seconds < 0 || seconds > exports.MAX_DELAY_SECONDS)
89
+ return ignored("not-a-delay", { payload: text });
90
+ return { input: { source: "delay", payload: Math.round(seconds) }, traces: [] };
91
+ }
92
+ //# sourceMappingURL=motion-publishing.js.map
@@ -0,0 +1,10 @@
1
+ import { type OptInPublishingConfig, type RetainedText } from "./publishing-node";
2
+ export type OccupancyPublishingConfig = OptInPublishingConfig;
3
+ export type OccupancyPublication = RetainedText;
4
+ export declare function occupancyStateTopic(area: string): string;
5
+ export declare function occupancyAvailabilityTopic(area: string): string;
6
+ export declare function occupancyDiscovery(config: OccupancyPublishingConfig): OccupancyPublication;
7
+ export declare function occupancyStateOutputs(config: OccupancyPublishingConfig, occupied: boolean): OccupancyPublication[];
8
+ export declare const occupancyStartingOutputs: (config: OptInPublishingConfig, state: boolean) => RetainedText[];
9
+ export declare const occupancyStoppingOutputs: (config: OptInPublishingConfig) => RetainedText[];
10
+ export declare const occupancyRetainedTopics: (config: OptInPublishingConfig) => string[];
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.occupancyRetainedTopics = exports.occupancyStoppingOutputs = exports.occupancyStartingOutputs = void 0;
4
+ exports.occupancyStateTopic = occupancyStateTopic;
5
+ exports.occupancyAvailabilityTopic = occupancyAvailabilityTopic;
6
+ exports.occupancyDiscovery = occupancyDiscovery;
7
+ exports.occupancyStateOutputs = occupancyStateOutputs;
8
+ // Occupancy fusion's MQTT and Home Assistant side: the room's occupancy as a
9
+ // retained ON/OFF state, its availability, and an occupancy binary sensor.
10
+ // All of it is opt-in (see publishing-node.ts); the fusion itself only
11
+ // decides occupancy.
12
+ const topic_names_1 = require("./topic-names");
13
+ const publishing_node_1 = require("./publishing-node");
14
+ function occupancyTopic(area, name) {
15
+ return "home/" + (0, topic_names_1.areaId)(area) + "/occupancy/" + name;
16
+ }
17
+ function occupancyStateTopic(area) {
18
+ return occupancyTopic(area, "state");
19
+ }
20
+ function occupancyAvailabilityTopic(area) {
21
+ return occupancyTopic(area, "availability");
22
+ }
23
+ // The occupancy binary sensor's discovery entry.
24
+ function occupancyDiscovery(config) {
25
+ return (0, publishing_node_1.discoveryEntry)(config, { kind: "occupancy", label: "Occupancy", model: "Occupancy fusion" }, occupancyAvailabilityTopic(config.area), {
26
+ component: "binary_sensor",
27
+ id: "occupancy",
28
+ name: "Occupancy",
29
+ fields: { device_class: "occupancy", state_topic: occupancyStateTopic(config.area), payload_on: "ON", payload_off: "OFF" }
30
+ });
31
+ }
32
+ // The occupancy state, published whenever it changes.
33
+ function occupancyStateOutputs(config, occupied) {
34
+ return (0, publishing_node_1.publishesState)(config) ? [(0, publishing_node_1.retainedText)(occupancyStateTopic(config.area), occupied ? "ON" : "OFF")] : [];
35
+ }
36
+ const occupancy = (0, publishing_node_1.publishingNode)({
37
+ entries: (config) => [occupancyDiscovery(config)],
38
+ availabilityTopic: occupancyAvailabilityTopic,
39
+ stateTopics: (config) => [occupancyStateTopic(config.area)],
40
+ stateOutputs: occupancyStateOutputs
41
+ });
42
+ exports.occupancyStartingOutputs = occupancy.starting;
43
+ exports.occupancyStoppingOutputs = occupancy.stopping;
44
+ exports.occupancyRetainedTopics = occupancy.retainedTopics;
45
+ //# sourceMappingURL=occupancy-publishing.js.map
@@ -0,0 +1,92 @@
1
+ import type { CoverMotion } from "./cover-controller";
2
+ import { type TargetStateEvent } from "./target-state";
3
+ export type OpenCloseOperation = "open" | "close" | "stop" | "observe";
4
+ export type OpenClosePosition = "open" | "closed" | "stopped" | "unknown";
5
+ export type OpenCloseEvidence = "reported" | "travel-time";
6
+ export interface OpenCloseConfig {
7
+ travelMs: number;
8
+ marginMs: number;
9
+ maxAttempts: number;
10
+ }
11
+ export declare function normaliseOpenCloseConfig(config?: Partial<Record<keyof OpenCloseConfig, unknown>>): OpenCloseConfig;
12
+ export interface OpenCloseState {
13
+ desired: {
14
+ requestId: string;
15
+ generation: number;
16
+ operation: "open" | "close" | "stop";
17
+ source: string | null;
18
+ } | null;
19
+ generation: number;
20
+ phase: string;
21
+ position: OpenClosePosition;
22
+ evidence: OpenCloseEvidence | null;
23
+ motion: CoverMotion | null;
24
+ observedAt: string | null;
25
+ reports: boolean;
26
+ pending: {
27
+ operation: OpenCloseOperation;
28
+ attempt: number;
29
+ issuedAt: number;
30
+ deadlineAt: number;
31
+ movingSince: number | null;
32
+ reported: boolean;
33
+ } | null;
34
+ failure: {
35
+ reason: string;
36
+ occurredAt: string;
37
+ } | null;
38
+ classification: "manual_override" | null;
39
+ available: boolean;
40
+ phaseBeforeUnavailable: string | null;
41
+ }
42
+ export type OpenCloseEvent = {
43
+ kind: "open" | "close" | "stop";
44
+ requestId: string;
45
+ generation: number;
46
+ source?: string;
47
+ respectManual?: boolean;
48
+ } | {
49
+ kind: "observed";
50
+ motion?: CoverMotion;
51
+ state?: "open" | "closed";
52
+ observedAt: string;
53
+ } | {
54
+ kind: "tick";
55
+ generation: number;
56
+ } | {
57
+ kind: "availability";
58
+ online: boolean;
59
+ } | {
60
+ kind: "startup" | "refresh";
61
+ };
62
+ export interface OpenCloseCommand {
63
+ operation: OpenCloseOperation;
64
+ requestId: string | null;
65
+ generation: number;
66
+ attempt: number;
67
+ }
68
+ export declare function openCloseMoving(state: Pick<OpenCloseState, "motion" | "phase">): boolean;
69
+ export declare function transitionOpenCloseCover(saved: Partial<OpenCloseState> | undefined, event: OpenCloseEvent, suppliedConfig?: Partial<Record<keyof OpenCloseConfig, unknown>>, nowValue?: Date | string | number): {
70
+ state: OpenCloseState;
71
+ commands: OpenCloseCommand[];
72
+ rejected: {
73
+ requestId: string;
74
+ generation: number;
75
+ operation: "open" | "close" | "stop";
76
+ reason: string;
77
+ }[];
78
+ traces: {
79
+ event: string;
80
+ outcome: string;
81
+ reason: string | null;
82
+ details: Record<string, unknown>;
83
+ }[];
84
+ status: {
85
+ phase: string;
86
+ moving: boolean;
87
+ text: string;
88
+ };
89
+ };
90
+ export declare function openCloseTargetStates(result: ReturnType<typeof transitionOpenCloseCover>, now: Date): Array<{
91
+ theatre: TargetStateEvent<"cover">;
92
+ }>;
@@ -0,0 +1,287 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.normaliseOpenCloseConfig = normaliseOpenCloseConfig;
4
+ exports.openCloseMoving = openCloseMoving;
5
+ exports.transitionOpenCloseCover = transitionOpenCloseCover;
6
+ exports.openCloseTargetStates = openCloseTargetStates;
7
+ // A cover that can only be told to open, close or stop, with no reliable
8
+ // position: a curtain motor, say. Its state is open, closed, opening,
9
+ // closing, stopped (partway) or unknown, from what it reports: its motion
10
+ // and, if it reports one, its end state. Without an end state, a move that
11
+ // ran for the full travel time and then stopped counts as done, marked as
12
+ // judged from travel time. Nothing else is assumed: a cover that reports
13
+ // nothing is "unconfirmed", not ready.
14
+ const cover_availability_1 = require("./cover-availability");
15
+ const observation_time_1 = require("./observation-time");
16
+ const settings_1 = require("./settings");
17
+ const target_state_1 = require("./target-state");
18
+ const MOTIONS = { opening: true, closing: true, stopped: true };
19
+ function normaliseOpenCloseConfig(config = {}) {
20
+ return {
21
+ travelMs: Math.max(1000, (0, settings_1.numberSetting)(config.travelMs, "travel time", 30000)),
22
+ marginMs: Math.max(1000, (0, settings_1.numberSetting)(config.marginMs, "travel margin", 10000)),
23
+ maxAttempts: Math.max(1, Math.floor((0, settings_1.numberSetting)(config.maxAttempts, "maximum attempts", 2)))
24
+ };
25
+ }
26
+ function initialState(saved = {}) {
27
+ return {
28
+ desired: saved.desired && typeof saved.desired === "object" ? { ...saved.desired } : null,
29
+ generation: Number.isInteger(saved.generation) && (saved.generation ?? -1) >= 0 ? saved.generation : 0,
30
+ phase: typeof saved.phase === "string" ? saved.phase : "idle",
31
+ position: saved.position ?? "unknown",
32
+ evidence: saved.evidence ?? null,
33
+ motion: saved.motion ?? null,
34
+ observedAt: typeof saved.observedAt === "string" ? saved.observedAt : null,
35
+ reports: saved.reports === true,
36
+ pending: saved.pending && typeof saved.pending === "object" ? { ...saved.pending } : null,
37
+ failure: saved.failure && typeof saved.failure === "object" ? { ...saved.failure } : null,
38
+ classification: saved.classification === "manual_override" ? "manual_override" : null,
39
+ available: saved.available !== false,
40
+ phaseBeforeUnavailable: typeof saved.phaseBeforeUnavailable === "string" ? saved.phaseBeforeUnavailable : null
41
+ };
42
+ }
43
+ // Whether it is moving: as it reports, or while a move it was sent is
44
+ // unconfirmed and it reports nothing.
45
+ function openCloseMoving(state) {
46
+ if (state.motion !== null)
47
+ return state.motion !== "stopped";
48
+ return state.phase === "moving" || state.phase === "stopping";
49
+ }
50
+ function transitionOpenCloseCover(saved, event, suppliedConfig = {}, nowValue = new Date()) {
51
+ const config = normaliseOpenCloseConfig(suppliedConfig);
52
+ const now = nowValue instanceof Date ? nowValue : new Date(nowValue);
53
+ const nowMs = now.getTime();
54
+ const state = initialState(saved);
55
+ const commands = [];
56
+ const traces = [];
57
+ const trace = (name, outcome, reason = null, details = {}) => traces.push({ event: name, outcome, reason, details });
58
+ function issue(operation, attempt) {
59
+ commands.push({ operation, requestId: state.desired?.requestId ?? null, generation: state.generation, attempt });
60
+ // A retry of the same request keeps what was heard since it was first sent.
61
+ const reported = attempt > 1 && state.pending?.operation === operation ? state.pending.reported : false;
62
+ state.pending = { operation, attempt, issuedAt: nowMs, deadlineAt: nowMs + config.travelMs + config.marginMs, movingSince: null, reported };
63
+ state.phase = operation === "stop" ? "stopping" : operation === "observe" ? "confirming" : "moving";
64
+ trace("command", "emitted", null, { operation, attempt });
65
+ }
66
+ function settle(position, evidence, reason) {
67
+ state.position = position;
68
+ state.evidence = evidence;
69
+ state.pending = null;
70
+ state.failure = null;
71
+ state.classification = null;
72
+ state.phase = "ready";
73
+ trace("cover", "ready", reason, { position, evidence });
74
+ }
75
+ function latchManual(reason, position) {
76
+ state.position = position;
77
+ state.evidence = position === "stopped" ? null : state.evidence;
78
+ state.pending = null;
79
+ state.classification = "manual_override";
80
+ state.phase = "manual_override";
81
+ trace("cover", "manual_override", reason, { position });
82
+ }
83
+ // What it reported before is not trusted after a restart, or once it has
84
+ // been offline: read it again.
85
+ function reobserve(reason) {
86
+ state.motion = null;
87
+ state.observedAt = null;
88
+ state.reports = false;
89
+ state.position = "unknown";
90
+ state.evidence = null;
91
+ state.pending = null;
92
+ if (state.phase !== "failed")
93
+ state.phase = state.desired ? "confirming" : "idle";
94
+ commands.push({ operation: "observe", requestId: state.desired?.requestId ?? null, generation: state.generation, attempt: 0 });
95
+ trace(reason, "observing");
96
+ }
97
+ // Answers to requests not carried out: unavailable while offline, or held
98
+ // by a person's move.
99
+ const rejected = [];
100
+ const target = (operation) => (operation === "open" ? "open" : "closed");
101
+ const towards = (operation) => (operation === "open" ? "opening" : "closing");
102
+ if (event.kind === "open" || event.kind === "close" || event.kind === "stop") {
103
+ if (typeof event.requestId !== "string" || !event.requestId)
104
+ throw new Error("cover requestId is required");
105
+ if (!Number.isInteger(event.generation) || event.generation < 1)
106
+ throw new Error("cover generation must be a positive integer");
107
+ if (!state.available) {
108
+ rejected.push({ requestId: event.requestId, generation: event.generation, operation: event.kind, reason: "unavailable" });
109
+ trace("intent", "rejected", "unavailable", { kind: event.kind });
110
+ }
111
+ else if (event.respectManual === true && state.classification === "manual_override") {
112
+ rejected.push({ requestId: event.requestId, generation: event.generation, operation: event.kind, reason: "manual-hold" });
113
+ trace("intent", "rejected", "manual-hold", { kind: event.kind });
114
+ }
115
+ else if (event.generation <= state.generation && state.desired) {
116
+ trace("intent", "ignored", event.generation === state.generation ? "duplicate" : "stale-generation");
117
+ }
118
+ else {
119
+ state.desired = { requestId: event.requestId, generation: event.generation, operation: event.kind, source: event.source ?? null };
120
+ state.generation = event.generation;
121
+ state.failure = null;
122
+ state.classification = null;
123
+ if (event.kind !== "stop" && state.position === target(event.kind) && state.motion !== "opening" && state.motion !== "closing") {
124
+ trace("intent", "accepted", "already-there", { kind: event.kind });
125
+ settle(state.position, state.evidence, "already-there");
126
+ }
127
+ else {
128
+ issue(event.kind, 1);
129
+ trace("intent", "accepted", null, { kind: event.kind });
130
+ }
131
+ }
132
+ }
133
+ else if (event.kind === "observed") {
134
+ if (event.motion !== undefined && !Object.hasOwn(MOTIONS, event.motion))
135
+ throw new Error("unknown observed cover motion");
136
+ if (event.state !== undefined && event.state !== "open" && event.state !== "closed")
137
+ throw new Error("unknown observed cover state");
138
+ const parsedAt = (0, observation_time_1.parseObservedAt)(event.observedAt);
139
+ if (parsedAt === null)
140
+ throw new Error("cover observedAt must be an ISO timestamp");
141
+ const bounded = (0, observation_time_1.boundObservedAt)(event.observedAt, parsedAt, nowMs);
142
+ if ((0, observation_time_1.isOutOfOrder)(bounded.ms, state.observedAt, nowMs)) {
143
+ trace("observation", "ignored", "out-of-order");
144
+ }
145
+ else {
146
+ state.reports = true;
147
+ state.observedAt = bounded.observedAt;
148
+ if (event.motion !== undefined)
149
+ state.motion = event.motion;
150
+ const pending = state.pending;
151
+ const operation = state.desired?.operation;
152
+ if (pending && bounded.ms >= pending.issuedAt)
153
+ pending.reported = true;
154
+ if (pending && bounded.ms < pending.issuedAt) {
155
+ trace("observation", "ignored", "stale-observation");
156
+ }
157
+ else if (pending && (operation === "open" || operation === "close")) {
158
+ if (event.motion === towards(operation) && pending.movingSince === null)
159
+ pending.movingSince = bounded.ms;
160
+ if (event.state !== undefined) {
161
+ if (event.state === target(operation))
162
+ settle(event.state, "reported", null);
163
+ else
164
+ latchManual("ended-elsewhere", event.state);
165
+ }
166
+ else if (event.motion && event.motion !== "stopped" && event.motion !== towards(operation)) {
167
+ latchManual("moved-the-other-way", "unknown");
168
+ }
169
+ else if (event.motion === "stopped" && pending.movingSince !== null) {
170
+ if (bounded.ms - pending.movingSince >= config.travelMs)
171
+ settle(target(operation), "travel-time", null);
172
+ else
173
+ latchManual("stopped-short", "stopped");
174
+ }
175
+ }
176
+ else if (pending && operation === "stop") {
177
+ if (event.state !== undefined)
178
+ settle(event.state, "reported", null);
179
+ else if (event.motion === "stopped")
180
+ settle("stopped", null, null);
181
+ }
182
+ else if (event.state !== undefined && (state.phase === "unconfirmed" || state.phase === "failed") &&
183
+ state.desired && state.desired.operation !== "stop" && event.state === target(state.desired.operation)) {
184
+ // A late report of the end the request asked for settles it after all.
185
+ settle(event.state, "reported", "late-report");
186
+ }
187
+ else if (event.state !== undefined) {
188
+ // Not ours: an end state reported while nothing was asked.
189
+ state.position = event.state;
190
+ state.evidence = "reported";
191
+ if (state.phase === "ready" && state.desired && state.desired.operation !== "stop" && event.state !== target(state.desired.operation)) {
192
+ latchManual("moved-by-someone", event.state);
193
+ }
194
+ }
195
+ else if (event.motion === "opening" || event.motion === "closing") {
196
+ if (state.phase === "ready")
197
+ latchManual("moved-by-someone", "unknown");
198
+ else
199
+ state.position = "unknown";
200
+ }
201
+ }
202
+ }
203
+ else if (event.kind === "tick") {
204
+ const pending = state.pending;
205
+ if (!pending || event.generation !== state.generation) {
206
+ trace("tick", "ignored", "stale-generation");
207
+ }
208
+ else if (nowMs >= pending.deadlineAt) {
209
+ if (pending.operation !== "observe" && pending.attempt < config.maxAttempts && pending.movingSince === null) {
210
+ issue(pending.operation, pending.attempt + 1);
211
+ }
212
+ else {
213
+ // Nothing it reported settles it. Without any reports, that is all we
214
+ // can know, so it is unconfirmed rather than failed.
215
+ state.pending = null;
216
+ state.phase = pending.reported ? "failed" : "unconfirmed";
217
+ state.failure = { reason: pending.reported ? "no-confirmation" : "no-reports", occurredAt: now.toISOString() };
218
+ trace("cover", state.phase, state.failure.reason, { operation: pending.operation });
219
+ }
220
+ }
221
+ }
222
+ else if (event.kind === "availability") {
223
+ const change = (0, cover_availability_1.applyCoverAvailability)(state, event.online);
224
+ if (change === "offline")
225
+ state.motion = null;
226
+ if (change)
227
+ trace("availability", change);
228
+ if (change === "online")
229
+ reobserve("online");
230
+ }
231
+ else if (!state.available) {
232
+ trace(event.kind, "ignored", "unavailable");
233
+ }
234
+ else if (event.kind === "startup" || event.kind === "refresh") {
235
+ reobserve(event.kind);
236
+ }
237
+ else {
238
+ throw new Error("unknown cover event kind");
239
+ }
240
+ const moving = openCloseMoving(state);
241
+ const evidenceNote = state.evidence === "travel-time" ? " (by travel time)" : "";
242
+ return {
243
+ state,
244
+ commands,
245
+ rejected,
246
+ traces,
247
+ status: { phase: state.phase, moving, text: `${state.position}${evidenceNote}: ${state.phase}` }
248
+ };
249
+ }
250
+ // The theatre's target state for the current request, and for each request
251
+ // answered unavailable. A cover that never reported, and so stays
252
+ // unconfirmed, is failed for the theatre, with the reason saying why.
253
+ function openCloseTargetStates(result, now) {
254
+ const { state } = result;
255
+ const status = (phase) => phase === "ready" || phase === "failed" || phase === "confirming" || phase === "unavailable" ? phase
256
+ : phase === "unconfirmed" ? "failed"
257
+ : "transitioning";
258
+ const details = (operation) => ({
259
+ operation,
260
+ state: state.position,
261
+ evidence: state.evidence,
262
+ motion: state.motion
263
+ });
264
+ const events = result.rejected.map((request) => ({ theatre: (0, target_state_1.targetStateEvent)({
265
+ target: "cover",
266
+ requestId: request.requestId,
267
+ generation: request.generation,
268
+ status: request.reason === "unavailable" ? "unavailable" : "failed",
269
+ observedAt: now.toISOString(),
270
+ details: details(request.operation),
271
+ failure: { operation: request.operation, reason: request.reason, occurredAt: now.toISOString() }
272
+ }) }));
273
+ if (state.desired) {
274
+ events.push({ theatre: (0, target_state_1.targetStateEvent)({
275
+ target: "cover",
276
+ requestId: state.desired.requestId,
277
+ generation: state.generation,
278
+ status: status(state.phase),
279
+ observedAt: now.toISOString(),
280
+ details: details(state.desired.operation),
281
+ classification: state.classification,
282
+ failure: state.failure ? { operation: state.desired.operation, ...state.failure } : null
283
+ }) });
284
+ }
285
+ return events;
286
+ }
287
+ //# sourceMappingURL=open-close-cover.js.map
@@ -0,0 +1,39 @@
1
+ import { type IdScheme } from "./ha-discovery";
2
+ export interface OptInPublishingConfig {
3
+ area: string;
4
+ publishState?: boolean;
5
+ discovery?: boolean;
6
+ discoveryPrefix: string;
7
+ nodeId?: string;
8
+ idScheme?: IdScheme;
9
+ }
10
+ export interface RetainedText {
11
+ topic: string;
12
+ payload: string;
13
+ retain: true;
14
+ }
15
+ export declare function retainedText(topic: string, payload: string): RetainedText;
16
+ export declare function publishesState(config: OptInPublishingConfig): boolean;
17
+ export declare function publishesDiscovery(config: OptInPublishingConfig): boolean;
18
+ export interface PublishingDevice {
19
+ kind: string;
20
+ label: string;
21
+ model: string;
22
+ }
23
+ export declare function discoveryEntry(config: OptInPublishingConfig, device: PublishingDevice, availabilityTopic: string, entity: {
24
+ component: string;
25
+ id: string;
26
+ name: string;
27
+ fields: Record<string, unknown>;
28
+ }): RetainedText;
29
+ export interface PublishingParts<State, Config extends OptInPublishingConfig> {
30
+ entries(config: Config): RetainedText[];
31
+ availabilityTopic(area: string, config: Config): string;
32
+ stateTopics(config: Config): string[];
33
+ stateOutputs(config: Config, state: State): RetainedText[];
34
+ }
35
+ export declare function publishingNode<State, Config extends OptInPublishingConfig = OptInPublishingConfig>(parts: PublishingParts<State, Config>): {
36
+ starting(config: Config, state: State): RetainedText[];
37
+ stopping(config: Config): RetainedText[];
38
+ retainedTopics(config: Config): string[];
39
+ };
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.retainedText = retainedText;
4
+ exports.publishesState = publishesState;
5
+ exports.publishesDiscovery = publishesDiscovery;
6
+ exports.discoveryEntry = discoveryEntry;
7
+ exports.publishingNode = publishingNode;
8
+ // What every opt-in publishing node shares (occupancy fusion, the motion
9
+ // policy, the AVR controller): publishing is off unless switched on and
10
+ // needs an area; discovery needs the state; each entity carries the node's
11
+ // IDs, availability, device and origin; and it publishes its entries, then
12
+ // online, then its state as it starts, and offline as it stops. Each node
13
+ // supplies only its own entries and state.
14
+ //
15
+ // The room lighting controller and the theatre state contract publish by
16
+ // default for older flows, and clear rather than omit entries with discovery
17
+ // off, so they keep their own rules.
18
+ const ha_discovery_1 = require("./ha-discovery");
19
+ function retainedText(topic, payload) {
20
+ return { topic, payload, retain: true };
21
+ }
22
+ function publishesState(config) {
23
+ return config.area !== "" && config.publishState === true;
24
+ }
25
+ function publishesDiscovery(config) {
26
+ return publishesState(config) && config.discovery === true;
27
+ }
28
+ // One discovery entry on the node's device, with the IDs, availability and
29
+ // origin every entity carries.
30
+ function discoveryEntry(config, device, availabilityTopic, entity) {
31
+ const ids = (0, ha_discovery_1.discoveryEntity)(config, entity.component, entity.id);
32
+ return retainedText(ids.topic, JSON.stringify({
33
+ // Home Assistant shows it after the device's name, which has the area.
34
+ name: entity.name,
35
+ unique_id: ids.uniqueId,
36
+ default_entity_id: ids.defaultEntityId,
37
+ ...entity.fields,
38
+ availability_topic: availabilityTopic,
39
+ device: {
40
+ ...(0, ha_discovery_1.discoveryDevice)(config, device.kind),
41
+ name: config.area + " " + device.label,
42
+ manufacturer: "Node-RED",
43
+ model: device.model
44
+ },
45
+ origin: ha_discovery_1.DISCOVERY_ORIGIN
46
+ }));
47
+ }
48
+ function publishingNode(parts) {
49
+ return {
50
+ // Its entries, availability and state, as it starts. Entries from before
51
+ // discovery was switched off are cleared by the node's record of what it
52
+ // published.
53
+ starting(config, state) {
54
+ const outputs = publishesDiscovery(config) ? parts.entries(config) : [];
55
+ if (publishesState(config))
56
+ outputs.push(retainedText(parts.availabilityTopic(config.area, config), ha_discovery_1.ONLINE));
57
+ return [...outputs, ...parts.stateOutputs(config, state)];
58
+ },
59
+ stopping(config) {
60
+ return publishesState(config) ? [retainedText(parts.availabilityTopic(config.area, config), ha_discovery_1.OFFLINE)] : [];
61
+ },
62
+ // Every retained topic it publishes, for clearing those it no longer
63
+ // does after a change, or all of them when deleted.
64
+ retainedTopics(config) {
65
+ const topics = publishesDiscovery(config) ? parts.entries(config).map(({ topic }) => topic) : [];
66
+ if (publishesState(config))
67
+ topics.push(parts.availabilityTopic(config.area, config), ...parts.stateTopics(config));
68
+ return topics;
69
+ }
70
+ };
71
+ }
72
+ //# sourceMappingURL=publishing-node.js.map
@@ -0,0 +1,10 @@
1
+ export interface RetainedClear {
2
+ topic: string;
3
+ payload: "";
4
+ retain: true;
5
+ }
6
+ export declare function retainedClears(topics: readonly string[]): RetainedClear[];
7
+ export declare function staleRetainedTopics(recorded: readonly string[] | undefined, current: readonly string[], keepStale?: boolean): {
8
+ clears: RetainedClear[];
9
+ record: string[];
10
+ };