@avantics/node-red-home-automation 3.0.1 → 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 (108) hide show
  1. package/README.md +262 -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/cover-availability.d.ts +7 -0
  15. package/dist/lib/cover-availability.js +24 -0
  16. package/dist/lib/cover-controller.d.ts +13 -1
  17. package/dist/lib/cover-controller.js +113 -30
  18. package/dist/lib/cover-group.d.ts +62 -0
  19. package/dist/lib/cover-group.js +125 -0
  20. package/dist/lib/cover-models.d.ts +37 -0
  21. package/dist/lib/cover-models.js +83 -0
  22. package/dist/lib/cover-publishing.d.ts +40 -0
  23. package/dist/lib/cover-publishing.js +102 -0
  24. package/dist/lib/cover-requests.d.ts +21 -0
  25. package/dist/lib/cover-requests.js +49 -0
  26. package/dist/lib/display-mode-controller.d.ts +4 -0
  27. package/dist/lib/display-mode-controller.js +26 -2
  28. package/dist/lib/ha-discovery.d.ts +27 -0
  29. package/dist/lib/ha-discovery.js +91 -0
  30. package/dist/lib/house-schedule-publishing.d.ts +23 -0
  31. package/dist/lib/house-schedule-publishing.js +71 -0
  32. package/dist/lib/house-schedule.d.ts +23 -0
  33. package/dist/lib/house-schedule.js +29 -0
  34. package/dist/lib/motion-policy.d.ts +9 -0
  35. package/dist/lib/motion-policy.js +45 -11
  36. package/dist/lib/motion-publishing.d.ts +28 -0
  37. package/dist/lib/motion-publishing.js +92 -0
  38. package/dist/lib/occupancy-publishing.d.ts +10 -0
  39. package/dist/lib/occupancy-publishing.js +45 -0
  40. package/dist/lib/open-close-cover.d.ts +92 -0
  41. package/dist/lib/open-close-cover.js +287 -0
  42. package/dist/lib/publishing-node.d.ts +39 -0
  43. package/dist/lib/publishing-node.js +72 -0
  44. package/dist/lib/retained-topics.d.ts +10 -0
  45. package/dist/lib/retained-topics.js +19 -0
  46. package/dist/lib/room-controller.d.ts +9 -0
  47. package/dist/lib/room-controller.js +47 -56
  48. package/dist/lib/room-lighting-discovery.d.ts +20 -1
  49. package/dist/lib/room-lighting-discovery.js +135 -13
  50. package/dist/lib/room-publishing.d.ts +42 -0
  51. package/dist/lib/room-publishing.js +182 -0
  52. package/dist/lib/room-schedule.d.ts +8 -0
  53. package/dist/lib/room-schedule.js +41 -0
  54. package/dist/lib/settings.d.ts +2 -0
  55. package/dist/lib/settings.js +20 -0
  56. package/dist/lib/source-capability-controller.d.ts +8 -1
  57. package/dist/lib/source-capability-controller.js +29 -3
  58. package/dist/lib/theatre-activity-controller.d.ts +0 -1
  59. package/dist/lib/theatre-activity-controller.js +27 -24
  60. package/dist/lib/theatre-ha-discovery.d.ts +3 -4
  61. package/dist/lib/theatre-ha-discovery.js +46 -36
  62. package/dist/lib/theatre-state-contract.d.ts +6 -0
  63. package/dist/lib/theatre-state-contract.js +83 -47
  64. package/dist/lib/theatre-state.d.ts +1 -1
  65. package/dist/lib/theatre-state.js +1 -1
  66. package/dist/lib/topic-names.d.ts +4 -0
  67. package/dist/lib/topic-names.js +31 -0
  68. package/dist/nodes/activity-lighting-controller.js +5 -3
  69. package/dist/nodes/adapter.d.ts +6 -1
  70. package/dist/nodes/adapter.js +65 -1
  71. package/dist/nodes/avr-controller.html +59 -5
  72. package/dist/nodes/avr-controller.js +74 -4
  73. package/dist/nodes/backlighting-controller.js +5 -3
  74. package/dist/nodes/cover-controller.d.ts +3 -0
  75. package/dist/nodes/cover-controller.html +177 -0
  76. package/dist/nodes/cover-controller.js +178 -0
  77. package/dist/nodes/cover-group.d.ts +3 -0
  78. package/dist/nodes/cover-group.html +89 -0
  79. package/dist/nodes/cover-group.js +84 -0
  80. package/dist/nodes/flows-started.d.ts +4 -0
  81. package/dist/nodes/flows-started.js +39 -0
  82. package/dist/nodes/house-schedule-mqtt.d.ts +3 -0
  83. package/dist/nodes/house-schedule-mqtt.html +61 -0
  84. package/dist/nodes/house-schedule-mqtt.js +80 -0
  85. package/dist/nodes/house-schedule.d.ts +3 -0
  86. package/dist/nodes/house-schedule.html +31 -0
  87. package/dist/nodes/house-schedule.js +51 -0
  88. package/dist/nodes/motion-policy.html +81 -5
  89. package/dist/nodes/motion-policy.js +69 -8
  90. package/dist/nodes/occupancy-fusion.html +69 -14
  91. package/dist/nodes/occupancy-fusion.js +46 -4
  92. package/dist/nodes/publishing-lifecycle.d.ts +25 -0
  93. package/dist/nodes/publishing-lifecycle.js +38 -0
  94. package/dist/nodes/room-controller.html +49 -5
  95. package/dist/nodes/room-controller.js +67 -8
  96. package/dist/nodes/shared-schedule.d.ts +6 -0
  97. package/dist/nodes/shared-schedule.js +15 -0
  98. package/dist/nodes/source-capability-controller.js +5 -3
  99. package/dist/nodes/theatre-activity-controller.html +1 -3
  100. package/dist/nodes/theatre-activity-controller.js +1 -2
  101. package/dist/nodes/theatre-state-contract.html +28 -5
  102. package/dist/nodes/theatre-state-contract.js +22 -4
  103. package/examples/Cover control.json +380 -0
  104. package/examples/Cover pair.json +230 -0
  105. package/examples/Home theatre activity.json +4 -4
  106. package/examples/House schedule.json +164 -0
  107. package/examples/Room lighting.json +4 -3
  108. package/package.json +6 -2
@@ -0,0 +1,125 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_GROUP_DEADLINE_SECONDS = void 0;
4
+ exports.coverGroupMembers = coverGroupMembers;
5
+ exports.transitionCoverGroup = transitionCoverGroup;
6
+ const target_state_1 = require("./target-state");
7
+ const settings_1 = require("./settings");
8
+ const MEMBER = /^[a-z][a-z0-9_-]*$/;
9
+ function coverGroupMembers(value) {
10
+ const members = (0, settings_1.jsonSetting)(value, "members", []);
11
+ if (!Array.isArray(members) || members.length < 2)
12
+ throw new Error("members must be a JSON array of at least two names");
13
+ if (!members.every((name) => typeof name === "string" && MEMBER.test(name)))
14
+ throw new Error("members must be lowercase identifiers");
15
+ if (new Set(members).size !== members.length)
16
+ throw new Error("members must be unique");
17
+ return members;
18
+ }
19
+ exports.DEFAULT_GROUP_DEADLINE_SECONDS = 120;
20
+ const SETTLED = { ready: true, failed: true, unavailable: true, manual_override: true };
21
+ function transitionCoverGroup(saved, event, members, now, deadlineSeconds = exports.DEFAULT_GROUP_DEADLINE_SECONDS) {
22
+ const state = {
23
+ request: saved?.request ? { ...saved.request, settled: saved.request.settled === true, members: { ...saved.request.members } } : null,
24
+ generation: Number.isInteger(saved?.generation) ? saved.generation : 0
25
+ };
26
+ const commands = [];
27
+ const traces = [];
28
+ let changed = false;
29
+ const events = [];
30
+ // The group's answer for its open request, from what its members did.
31
+ function answer(supersededBy = null) {
32
+ const request = state.request;
33
+ const outcomes = Object.values(request.members);
34
+ const allReady = outcomes.every(({ outcome }) => outcome === "ready");
35
+ const allSettled = outcomes.every(({ outcome }) => SETTLED[outcome]);
36
+ const confirmed = Object.entries(request.members).filter(([, member]) => member.outcome === "ready").map(([name]) => name);
37
+ const status = supersededBy ? "failed" : allReady ? "ready" : allSettled ? "failed" : "transitioning";
38
+ if (status !== "transitioning")
39
+ request.settled = true;
40
+ const reason = supersededBy ? "superseded" : confirmed.length ? "partial" : "none-confirmed";
41
+ events.push({ theatre: (0, target_state_1.targetStateEvent)({
42
+ target: "cover",
43
+ requestId: request.requestId,
44
+ generation: request.generation,
45
+ status,
46
+ observedAt: now.toISOString(),
47
+ details: {
48
+ request: request.payload,
49
+ members: Object.fromEntries(Object.entries(request.members).map(([name, member]) => [name, { status: member.outcome, reason: member.reason }])),
50
+ confirmed,
51
+ ...(supersededBy ? { supersededBy } : {})
52
+ },
53
+ failure: status === "failed" ? { reason, confirmed } : null
54
+ }) });
55
+ }
56
+ // Members still silent at the deadline are not answering: the group
57
+ // settles with what it has.
58
+ if (state.request && !state.request.settled && now.getTime() >= state.request.deadlineAt) {
59
+ for (const [name, member] of Object.entries(state.request.members)) {
60
+ if (!SETTLED[member.outcome]) {
61
+ state.request.members[name] = { ...member, outcome: "failed", reason: "no-answer" };
62
+ traces.push({ event: "member", outcome: "failed", reason: "no-answer", details: { member: name } });
63
+ }
64
+ }
65
+ changed = true;
66
+ }
67
+ if (event.kind === "tick") {
68
+ // Only the deadline, above.
69
+ }
70
+ else if (event.kind === "request") {
71
+ if (state.request && !state.request.settled && !changed) {
72
+ // The open request gets its final answer before the new one goes out.
73
+ answer(`group-${now.getTime()}-${state.generation + 1}`);
74
+ traces.push({ event: "request", outcome: "superseded", reason: null, details: { requestId: state.request.requestId } });
75
+ }
76
+ else if (changed && state.request) {
77
+ answer();
78
+ changed = false;
79
+ }
80
+ state.generation += 1;
81
+ const requestId = `group-${now.getTime()}-${state.generation}`;
82
+ state.request = { requestId, generation: state.generation, payload: event.payload, deadlineAt: now.getTime() + deadlineSeconds * 1000, settled: false, members: {} };
83
+ for (const member of members) {
84
+ const memberRequestId = `${requestId}:${member}`;
85
+ state.request.members[member] = { requestId: memberRequestId, outcome: "transitioning", reason: null };
86
+ commands.push({
87
+ topic: member,
88
+ payload: event.payload,
89
+ coverRequestId: memberRequestId,
90
+ ...(event.stopIfMoving === true ? { stopIfMoving: true } : {}),
91
+ ...(event.respectManual === true ? { respectManual: true } : {}),
92
+ ...(typeof event.source === "string" && event.source ? { source: event.source } : {})
93
+ });
94
+ }
95
+ changed = true;
96
+ traces.push({ event: "request", outcome: "sent", reason: null, details: { requestId, members } });
97
+ }
98
+ else {
99
+ const entry = state.request && Object.entries(state.request.members).find(([, member]) => member.requestId === event.requestId);
100
+ if (!entry) {
101
+ traces.push({ event: "member", outcome: "ignored", reason: "other-request", details: { requestId: event.requestId } });
102
+ }
103
+ else {
104
+ const [name, member] = entry;
105
+ const outcome = event.classification === "manual_override" ? "manual_override" : event.status;
106
+ if (member.outcome !== outcome) {
107
+ state.request.members[name] = { ...member, outcome, reason: event.reason ?? null };
108
+ changed = true;
109
+ traces.push({ event: "member", outcome, reason: event.reason ?? null, details: { member: name } });
110
+ }
111
+ }
112
+ }
113
+ if (state.request && changed)
114
+ answer();
115
+ const counts = state.request ? Object.values(state.request.members) : [];
116
+ const ready = counts.filter(({ outcome }) => outcome === "ready").length;
117
+ return {
118
+ state,
119
+ commands,
120
+ events,
121
+ traces,
122
+ status: { text: state.request ? `${ready}/${counts.length} confirmed` : "idle", ready, total: counts.length }
123
+ };
124
+ }
125
+ //# sourceMappingURL=cover-group.js.map
@@ -0,0 +1,37 @@
1
+ export declare const COVER_TYPES: readonly ["position", "open-close"];
2
+ export type CoverType = typeof COVER_TYPES[number];
3
+ export interface CoverTransition {
4
+ state: unknown;
5
+ commands: Array<Record<string, unknown>>;
6
+ events: Array<Record<string, unknown>>;
7
+ traces: Array<{
8
+ event: string;
9
+ outcome: string;
10
+ reason: string | null;
11
+ details: Record<string, unknown>;
12
+ }>;
13
+ status: {
14
+ phase: string;
15
+ moving: boolean;
16
+ text: string;
17
+ battery: number | null;
18
+ observed: boolean;
19
+ };
20
+ }
21
+ export interface CoverView {
22
+ state: "open" | "closed" | "opening" | "closing" | "stopped";
23
+ position: number | null;
24
+ }
25
+ export interface CoverModel {
26
+ positions: boolean;
27
+ transition(saved: unknown, event: unknown, now: Date): CoverTransition;
28
+ moving(saved: unknown): boolean;
29
+ generation(saved: unknown): number;
30
+ tickAt(state: unknown): {
31
+ at: number;
32
+ generation: number;
33
+ } | null;
34
+ view(saved: unknown): CoverView | null;
35
+ }
36
+ export declare function positionCover(settings: Record<string, unknown>): CoverModel;
37
+ export declare function openCloseCover(settings: Record<string, unknown>): CoverModel;
@@ -0,0 +1,83 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.COVER_TYPES = void 0;
4
+ exports.positionCover = positionCover;
5
+ exports.openCloseCover = openCloseCover;
6
+ // The two kinds of cover a cover node can own, behind one shape, so the node
7
+ // treats them alike: a position cover (0 to 100) and an open/close-only
8
+ // cover. Each says how to take an event, whether the cover is moving, when
9
+ // to check on it next, and whether it takes positions.
10
+ const cover_controller_1 = require("./cover-controller");
11
+ const open_close_cover_1 = require("./open-close-cover");
12
+ exports.COVER_TYPES = ["position", "open-close"];
13
+ function positionCover(settings) {
14
+ const config = (0, cover_controller_1.normaliseCoverConfig)(settings);
15
+ return {
16
+ positions: true,
17
+ transition(saved, event, now) {
18
+ const result = (0, cover_controller_1.transitionCover)(saved, { cover: event }, config, now);
19
+ return {
20
+ state: result.state,
21
+ commands: result.commands,
22
+ events: result.events,
23
+ traces: result.traces,
24
+ status: { ...result.status, battery: result.state.observed?.battery ?? null, observed: result.state.observed !== null }
25
+ };
26
+ },
27
+ moving(saved) {
28
+ const state = saved;
29
+ return state ? (0, cover_controller_1.coverMoving)({ observed: state.observed ?? null, phase: state.phase ?? "idle" }) : false;
30
+ },
31
+ generation: (saved) => saved?.generation ?? 0,
32
+ tickAt(state) {
33
+ const cover = state;
34
+ return cover.pending ? { at: Math.min(cover.pending.nextAt, cover.pending.deadlineAt), generation: cover.generation } : null;
35
+ },
36
+ view(saved) {
37
+ const observed = saved?.observed;
38
+ if (!observed)
39
+ return null;
40
+ const motion = observed.motion === "opening" || observed.motion === "closing" ? observed.motion : null;
41
+ return { state: motion ?? (observed.position <= 0 ? "closed" : "open"), position: observed.position };
42
+ }
43
+ };
44
+ }
45
+ function openCloseCover(settings) {
46
+ const config = (0, open_close_cover_1.normaliseOpenCloseConfig)(settings);
47
+ return {
48
+ positions: false,
49
+ transition(saved, event, now) {
50
+ const result = (0, open_close_cover_1.transitionOpenCloseCover)(saved, event, config, now);
51
+ return {
52
+ state: result.state,
53
+ commands: result.commands,
54
+ events: (0, open_close_cover_1.openCloseTargetStates)(result, now),
55
+ traces: result.traces,
56
+ status: { ...result.status, battery: null, observed: result.state.reports }
57
+ };
58
+ },
59
+ moving(saved) {
60
+ const state = saved;
61
+ return state ? (0, open_close_cover_1.openCloseMoving)({ motion: state.motion ?? null, phase: state.phase ?? "idle" }) : false;
62
+ },
63
+ generation: (saved) => saved?.generation ?? 0,
64
+ tickAt(state) {
65
+ const cover = state;
66
+ return cover.pending ? { at: cover.pending.deadlineAt, generation: cover.generation } : null;
67
+ },
68
+ view(saved) {
69
+ const state = saved;
70
+ if (!state)
71
+ return null;
72
+ if (state.motion === "opening" || state.motion === "closing")
73
+ return { state: state.motion, position: null };
74
+ // Stopped partway is open, as a cover entity counts anything not fully
75
+ // closed: with no position, Home Assistant would otherwise keep showing
76
+ // the last move (closed after closing) and refuse to close it.
77
+ if (state.position === "stopped")
78
+ return { state: "open", position: null };
79
+ return state.position && state.position !== "unknown" ? { state: state.position, position: null } : null;
80
+ }
81
+ };
82
+ }
83
+ //# sourceMappingURL=cover-models.js.map
@@ -0,0 +1,40 @@
1
+ import type { TraceEntry } from "./bounded-trace";
2
+ import type { CoverView } from "./cover-models";
3
+ import { type OptInPublishingConfig, type RetainedText } from "./publishing-node";
4
+ export interface CoverPublishingConfig extends OptInPublishingConfig {
5
+ name: string;
6
+ positions: boolean;
7
+ }
8
+ export declare const coverStateTopic: (config: {
9
+ area: string;
10
+ name: string;
11
+ }) => string;
12
+ export declare const coverPositionTopic: (config: {
13
+ area: string;
14
+ name: string;
15
+ }) => string;
16
+ export declare const coverCommandTopic: (config: {
17
+ area: string;
18
+ name: string;
19
+ }) => string;
20
+ export declare const coverSetPositionTopic: (config: {
21
+ area: string;
22
+ name: string;
23
+ }) => string;
24
+ export declare const coverAvailabilityTopic: (config: {
25
+ area: string;
26
+ name: string;
27
+ }) => string;
28
+ export declare function coverDiscovery(config: CoverPublishingConfig): RetainedText[];
29
+ export declare function coverStateOutputs(config: CoverPublishingConfig, view: CoverView | null): RetainedText[];
30
+ export declare const coverStartingOutputs: (config: CoverPublishingConfig, state: CoverView | null) => RetainedText[];
31
+ export declare const coverStoppingOutputs: (config: CoverPublishingConfig) => RetainedText[];
32
+ export declare const coverRetainedTopics: (config: CoverPublishingConfig) => string[];
33
+ export declare function coverInbound(msg: {
34
+ topic?: unknown;
35
+ payload?: unknown;
36
+ retain?: unknown;
37
+ }, config: CoverPublishingConfig): {
38
+ request: string | number | null;
39
+ traces: TraceEntry[];
40
+ } | null;
@@ -0,0 +1,102 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.coverRetainedTopics = exports.coverStoppingOutputs = exports.coverStartingOutputs = exports.coverAvailabilityTopic = exports.coverSetPositionTopic = exports.coverCommandTopic = exports.coverPositionTopic = exports.coverStateTopic = void 0;
4
+ exports.coverDiscovery = coverDiscovery;
5
+ exports.coverStateOutputs = coverStateOutputs;
6
+ exports.coverInbound = coverInbound;
7
+ const publishing_node_1 = require("./publishing-node");
8
+ const topic_names_1 = require("./topic-names");
9
+ function coverTopic(config, path) {
10
+ return "home/" + (0, topic_names_1.areaId)(config.area) + "/cover/" + (0, topic_names_1.areaId)(config.name) + "/" + path;
11
+ }
12
+ const coverStateTopic = (config) => coverTopic(config, "state");
13
+ exports.coverStateTopic = coverStateTopic;
14
+ const coverPositionTopic = (config) => coverTopic(config, "position");
15
+ exports.coverPositionTopic = coverPositionTopic;
16
+ const coverCommandTopic = (config) => coverTopic(config, "set");
17
+ exports.coverCommandTopic = coverCommandTopic;
18
+ const coverSetPositionTopic = (config) => coverTopic(config, "position/set");
19
+ exports.coverSetPositionTopic = coverSetPositionTopic;
20
+ const coverAvailabilityTopic = (config) => coverTopic(config, "availability");
21
+ exports.coverAvailabilityTopic = coverAvailabilityTopic;
22
+ function device(config) {
23
+ return { kind: "cover_" + (0, topic_names_1.areaId)(config.name), label: "Cover " + config.name, model: "Cover controller" };
24
+ }
25
+ // One cover entity: open, close and stop always; set position and the
26
+ // position it reports for a position cover.
27
+ function coverDiscovery(config) {
28
+ const positions = config.positions ? {
29
+ position_topic: (0, exports.coverPositionTopic)(config),
30
+ set_position_topic: (0, exports.coverSetPositionTopic)(config),
31
+ position_open: 100,
32
+ position_closed: 0
33
+ } : {};
34
+ return [
35
+ (0, publishing_node_1.discoveryEntry)(config, device(config), (0, exports.coverAvailabilityTopic)(config), {
36
+ component: "cover",
37
+ id: "cover_" + (0, topic_names_1.areaId)(config.name),
38
+ name: config.name,
39
+ fields: {
40
+ command_topic: (0, exports.coverCommandTopic)(config),
41
+ payload_open: "OPEN",
42
+ payload_close: "CLOSE",
43
+ payload_stop: "STOP",
44
+ state_topic: (0, exports.coverStateTopic)(config),
45
+ state_open: "open",
46
+ state_opening: "opening",
47
+ state_closed: "closed",
48
+ state_closing: "closing",
49
+ state_stopped: "stopped",
50
+ optimistic: false,
51
+ ...positions
52
+ }
53
+ })
54
+ ];
55
+ }
56
+ // The cover's state, and its position when it has one, once it has
57
+ // reported; nothing before.
58
+ function coverStateOutputs(config, view) {
59
+ if (!(0, publishing_node_1.publishesState)(config) || !view)
60
+ return [];
61
+ return [
62
+ (0, publishing_node_1.retainedText)((0, exports.coverStateTopic)(config), view.state),
63
+ ...(config.positions && view.position !== null ? [(0, publishing_node_1.retainedText)((0, exports.coverPositionTopic)(config), String(Math.round(view.position)))] : [])
64
+ ];
65
+ }
66
+ const cover = (0, publishing_node_1.publishingNode)({
67
+ entries: coverDiscovery,
68
+ availabilityTopic: (_area, config) => (0, exports.coverAvailabilityTopic)(config),
69
+ stateTopics: (config) => [(0, exports.coverStateTopic)(config), ...(config.positions ? [(0, exports.coverPositionTopic)(config)] : [])],
70
+ stateOutputs: coverStateOutputs
71
+ });
72
+ exports.coverStartingOutputs = cover.starting;
73
+ exports.coverStoppingOutputs = cover.stopping;
74
+ exports.coverRetainedTopics = cover.retainedTopics;
75
+ // A request from Home Assistant on the cover's set topics, as the payload the
76
+ // cover node takes from a flow: "open", "close", "stop" or a position. Read
77
+ // only while it publishes; retained messages and anything else are ignored
78
+ // with a trace. Anything else passes through (null).
79
+ function coverInbound(msg, config) {
80
+ if (!(0, publishing_node_1.publishesState)(config))
81
+ return null;
82
+ const command = msg.topic === (0, exports.coverCommandTopic)(config);
83
+ const position = config.positions && msg.topic === (0, exports.coverSetPositionTopic)(config);
84
+ if (!command && !position)
85
+ return null;
86
+ const event = command ? "command-set" : "position-set";
87
+ const ignored = (reason, details = {}) => ({ request: null, traces: [{ event, outcome: "ignored", reason, details }] });
88
+ if (msg.retain === true)
89
+ return ignored("retained-message");
90
+ const text = typeof msg.payload === "string" ? msg.payload.trim() : typeof msg.payload === "number" ? String(msg.payload) : "";
91
+ if (command) {
92
+ const requested = text.toUpperCase();
93
+ if (requested !== "OPEN" && requested !== "CLOSE" && requested !== "STOP")
94
+ return ignored("not-open-close-or-stop", { payload: text });
95
+ return { request: requested.toLowerCase(), traces: [] };
96
+ }
97
+ const value = text === "" ? NaN : Number(text);
98
+ if (!Number.isFinite(value) || value < 0 || value > 100)
99
+ return ignored("not-a-position", { payload: text });
100
+ return { request: Math.round(value), traces: [] };
101
+ }
102
+ //# sourceMappingURL=cover-publishing.js.map
@@ -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