@avantics/node-red-home-automation 3.0.1 → 4.0.1

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 +278 -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 +145 -31
  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 +181 -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
@@ -1,49 +1,48 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.normaliseStateContractConfig = normaliseStateContractConfig;
4
+ exports.theatreRetainedTopics = theatreRetainedTopics;
5
+ exports.theatreStartingPublications = theatreStartingPublications;
6
+ exports.theatreStoppingPublications = theatreStoppingPublications;
4
7
  exports.transitionTheatreStateContract = transitionTheatreStateContract;
5
8
  const theatre_profiles_1 = require("./theatre-profiles");
6
9
  const theatre_ha_discovery_1 = require("./theatre-ha-discovery");
7
10
  const theatre_slo_1 = require("./theatre-slo");
8
- const settings_1 = require("./settings");
9
- const NAME = /^[a-z][a-z0-9_-]*$/;
10
- const REQUEST_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
11
+ const ha_discovery_1 = require("./ha-discovery");
12
+ const topic_names_1 = require("./topic-names");
11
13
  function normaliseStateContractConfig(config = {}) {
12
14
  const discovery = config.discovery !== false;
13
- // The area names the discovery entities and the default base topic, so it
14
- // is needed for either; otherwise it is optional.
15
- const area = String(config.area || "").trim();
16
- if (!area && (discovery || !config.baseTopic))
17
- throw new Error("area is required");
18
- if (area && !NAME.test(area))
19
- throw new Error("area must be a lowercase identifier");
15
+ // The area names the default base topic, so it is needed without one. It
16
+ // also names an area-scheme contract's entities; a node-scheme contract's
17
+ // are named after the node, and its entity IDs fall back to the display
18
+ // name. Otherwise it is optional.
19
+ const area = (0, topic_names_1.publishingArea)(String(config.area || "").trim(), !config.baseTopic || (discovery && config.idScheme !== "node"));
20
20
  const displayName = String(config.displayName || area).trim();
21
21
  if (discovery && !displayName)
22
22
  throw new Error("displayName is required");
23
- const baseTopic = String(config.baseTopic || `home/${area}/theatre`).replace(/^\/+|\/+$/g, "");
24
- const discoveryPrefix = (0, settings_1.textSetting)(config.discoveryPrefix, "discovery prefix", "homeassistant").replace(/^\/+|\/+$/g, "");
23
+ const baseTopic = String(config.baseTopic || `home/${(0, topic_names_1.areaId)(area)}/theatre`).replace(/^\/+|\/+$/g, "");
24
+ const discoveryPrefix = (0, ha_discovery_1.discoveryPrefixSetting)(config.discoveryPrefix);
25
25
  if (!baseTopic || /[+#]/.test(baseTopic))
26
26
  throw new Error("baseTopic must be a concrete MQTT topic");
27
- if (!discoveryPrefix || /[+#]/.test(discoveryPrefix)) {
28
- throw new Error("discoveryPrefix must be a concrete MQTT topic prefix");
29
- }
30
27
  if (!Array.isArray(config.activities) || config.activities.length === 0) {
31
28
  throw new Error("activities must be a non-empty array");
32
29
  }
33
30
  const activities = config.activities.map((activity) => String(activity));
34
- if (activities.some((activity) => !NAME.test(activity))) {
31
+ if (activities.some((activity) => !topic_names_1.IDENTIFIER.test(activity))) {
35
32
  throw new Error("activities must contain lowercase identifiers");
36
33
  }
37
34
  if (new Set(activities).size !== activities.length)
38
35
  throw new Error("activities must be unique");
39
36
  return {
37
+ ...(config.nodeId ? { nodeId: config.nodeId } : {}),
40
38
  area,
41
39
  displayName,
42
40
  baseTopic,
43
41
  discoveryPrefix,
44
42
  activities,
45
43
  slo: (0, theatre_slo_1.normaliseTheatreSloConfig)(config.slo),
46
- discovery
44
+ discovery,
45
+ ...(config.idScheme ? { idScheme: config.idScheme } : {})
47
46
  };
48
47
  }
49
48
  function createState(saved = {}) {
@@ -90,23 +89,37 @@ function publication(topic, payload) {
90
89
  retain: true
91
90
  };
92
91
  }
93
- function statePublications(event, config, slo) {
94
- const base = config.baseTopic;
95
- const desired = event.requestId && event.desiredActivity
96
- ? {
97
- requestId: event.requestId,
98
- generation: event.generation,
99
- activity: event.desiredActivity,
100
- requestedAt: event.requestedAt
101
- }
102
- : null;
103
- const outputs = [
104
- publication((0, theatre_ha_discovery_1.theatreTopic)(base, "desired"), desired),
105
- publication((0, theatre_ha_discovery_1.theatreTopic)(base, "current"), event.currentActivity),
106
- publication((0, theatre_ha_discovery_1.theatreTopic)(base, "phase"), event.phase),
107
- publication((0, theatre_ha_discovery_1.theatreTopic)(base, "failure"), event.failure),
108
- publication((0, theatre_ha_discovery_1.theatreTopic)(base, "availability"), event.availability),
109
- publication((0, theatre_ha_discovery_1.theatreTopic)(base, "metrics"), event.metrics || {
92
+ // When the latest transition started and finished, and which targets it
93
+ // left degraded: the Phase sensor's attributes in Home Assistant.
94
+ function transitionDetails(event) {
95
+ const timestamp = (value) => (typeof value === "string" ? value : null);
96
+ return {
97
+ startedAt: timestamp(event.transitionStartedAt),
98
+ completedAt: timestamp(event.transitionCompletedAt),
99
+ degraded: (Array.isArray(event.degraded) ? event.degraded : []).map((entry) => ({
100
+ target: String(entry.target),
101
+ reason: String(entry.reason)
102
+ }))
103
+ };
104
+ }
105
+ // What the contract publishes from each controller snapshot, one retained
106
+ // topic per entry, in this order. The publications and the list of topics
107
+ // the contract publishes both come from this table.
108
+ const STATE_TOPICS = [
109
+ ["desired", (event) => (event.requestId && event.desiredActivity
110
+ ? {
111
+ requestId: event.requestId,
112
+ generation: event.generation,
113
+ activity: event.desiredActivity,
114
+ requestedAt: event.requestedAt
115
+ }
116
+ : null)],
117
+ ["current", (event) => event.currentActivity],
118
+ ["phase", (event) => event.phase],
119
+ ["transition", (event) => transitionDetails(event)],
120
+ ["failure", (event) => event.failure],
121
+ ["readiness", (event) => event.availability],
122
+ ["metrics", (event) => event.metrics || {
110
123
  requests: 0,
111
124
  ready: 0,
112
125
  failed: 0,
@@ -114,26 +127,27 @@ function statePublications(event, config, slo) {
114
127
  manualOverrides: 0,
115
128
  driftEvents: 0,
116
129
  recoveriesAdopted: 0,
117
- recoveriesSafeOff: 0,
130
+ recoveriesUnknown: 0,
118
131
  lastTransitionMs: null,
119
132
  maxTransitionMs: null,
120
133
  lastOutcome: null,
121
134
  targets: {}
122
- }),
123
- publication((0, theatre_ha_discovery_1.theatreTopic)(base, "slo"), slo),
124
- publication((0, theatre_ha_discovery_1.theatreTopic)(base, "slo/breach"), slo.status === "breached" ? "ON" : "OFF")
125
- ];
126
- for (const target of theatre_profiles_1.TARGETS) {
127
- const health = event.targets[target];
128
- outputs.push(publication((0, theatre_ha_discovery_1.theatreTopic)(base, `health/${target}`), health || {
135
+ }],
136
+ ["slo", (_event, slo) => slo],
137
+ ["slo/breach", (_event, slo) => (slo.status === "breached" ? "ON" : "OFF")],
138
+ ...theatre_profiles_1.TARGETS.map((target) => [
139
+ `health/${target}`,
140
+ (event) => event.targets[target] || {
129
141
  status: "unknown",
130
142
  observedAt: null,
131
143
  classification: null,
132
144
  failure: null,
133
145
  details: null
134
- }));
135
- }
136
- return outputs;
146
+ }
147
+ ])
148
+ ];
149
+ function statePublications(event, config, slo) {
150
+ return STATE_TOPICS.map(([name, value]) => publication((0, theatre_ha_discovery_1.theatreTopic)(config.baseTopic, name), value(event, slo)));
137
151
  }
138
152
  function requestPublications(request, config) {
139
153
  const base = config.baseTopic;
@@ -141,7 +155,7 @@ function requestPublications(request, config) {
141
155
  publication((0, theatre_ha_discovery_1.theatreTopic)(base, "desired"), request),
142
156
  publication((0, theatre_ha_discovery_1.theatreTopic)(base, "phase"), "requested"),
143
157
  publication((0, theatre_ha_discovery_1.theatreTopic)(base, "failure"), null),
144
- publication((0, theatre_ha_discovery_1.theatreTopic)(base, "availability"), "unknown")
158
+ publication((0, theatre_ha_discovery_1.theatreTopic)(base, "readiness"), "unknown")
145
159
  ];
146
160
  }
147
161
  function asStateSnapshot(value) {
@@ -163,6 +177,27 @@ function asStateSnapshot(value) {
163
177
  }
164
178
  return event;
165
179
  }
180
+ // Every retained topic the contract publishes, for clearing those it no
181
+ // longer does after a change: discovery entries, whenever they are published
182
+ // or cleared at each start, its availability, and its state topics.
183
+ function theatreRetainedTopics(config) {
184
+ const discovery = config.discovery !== false || config.area
185
+ ? (0, theatre_ha_discovery_1.theatreDiscovery)(config).map(({ topic }) => topic)
186
+ : [];
187
+ return [
188
+ ...discovery,
189
+ ...theatreStartingPublications(config).map(({ topic }) => topic),
190
+ ...STATE_TOPICS.map(([name]) => (0, theatre_ha_discovery_1.theatreTopic)(config.baseTopic, name))
191
+ ];
192
+ }
193
+ // What the contract publishes as it starts and as it stops, so Home Assistant
194
+ // shows its entities as available only while it runs.
195
+ function theatreStartingPublications(config) {
196
+ return [publication((0, theatre_ha_discovery_1.theatreTopic)(config.baseTopic, "availability"), ha_discovery_1.ONLINE)];
197
+ }
198
+ function theatreStoppingPublications(config) {
199
+ return [publication((0, theatre_ha_discovery_1.theatreTopic)(config.baseTopic, "availability"), ha_discovery_1.OFFLINE)];
200
+ }
166
201
  function transitionTheatreStateContract(saved, msg, suppliedConfig, nowValue = new Date()) {
167
202
  const config = normaliseStateContractConfig(suppliedConfig);
168
203
  const state = createState(saved);
@@ -180,6 +215,7 @@ function transitionTheatreStateContract(saved, msg, suppliedConfig, nowValue = n
180
215
  // from Home Assistant.
181
216
  const entries = config.discovery !== false || config.area ? (0, theatre_ha_discovery_1.theatreDiscovery)(config) : [];
182
217
  publications.push(...entries.map(({ topic, payload }) => publication(topic, config.discovery !== false ? payload : "")));
218
+ publications.push(publication((0, theatre_ha_discovery_1.theatreTopic)(config.baseTopic, "availability"), ha_discovery_1.ONLINE));
183
219
  trace("startup", "discovery", null, { publications: publications.length });
184
220
  }
185
221
  else if (msg.topic === (0, theatre_ha_discovery_1.theatreTopic)(config.baseTopic, "request")) {
@@ -190,7 +226,7 @@ function transitionTheatreStateContract(saved, msg, suppliedConfig, nowValue = n
190
226
  const payload = parsePayload(msg.payload);
191
227
  const requestId = String(payload.requestId || "");
192
228
  const activity = String(payload.activity || "");
193
- if (!REQUEST_ID.test(requestId))
229
+ if (!topic_names_1.REQUEST_ID.test(requestId))
194
230
  throw new Error("requestId is invalid");
195
231
  if (!config.activities.includes(activity))
196
232
  throw new Error("unknown theatre activity");
@@ -47,7 +47,7 @@ export interface TheatreMetrics {
47
47
  manualOverrides: number;
48
48
  driftEvents: number;
49
49
  recoveriesAdopted: number;
50
- recoveriesSafeOff: number;
50
+ recoveriesUnknown: number;
51
51
  lastTransitionMs: number | null;
52
52
  maxTransitionMs: number | null;
53
53
  lastOutcome: string | null;
@@ -75,7 +75,7 @@ function createMetrics(saved = {}) {
75
75
  manualOverrides: count(saved.manualOverrides),
76
76
  driftEvents: count(saved.driftEvents),
77
77
  recoveriesAdopted: count(saved.recoveriesAdopted),
78
- recoveriesSafeOff: count(saved.recoveriesSafeOff),
78
+ recoveriesUnknown: count(saved.recoveriesUnknown),
79
79
  lastTransitionMs: nullableDuration(saved.lastTransitionMs),
80
80
  maxTransitionMs: nullableDuration(saved.maxTransitionMs),
81
81
  lastOutcome: typeof saved.lastOutcome === "string" ? saved.lastOutcome : null,
@@ -0,0 +1,4 @@
1
+ export declare const IDENTIFIER: RegExp;
2
+ export declare function areaId(area: string): string;
3
+ export declare function publishingArea(area: string, needed: boolean): string;
4
+ export declare const REQUEST_ID: RegExp;
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.REQUEST_ID = exports.IDENTIFIER = void 0;
4
+ exports.areaId = areaId;
5
+ exports.publishingArea = publishingArea;
6
+ // How areas and names become parts of MQTT topics and IDs. Shared by every
7
+ // node that publishes, whether or not Home Assistant reads what it publishes.
8
+ // A lowercase identifier: safe in MQTT topics, unique IDs and entity IDs.
9
+ exports.IDENTIFIER = /^[a-z][a-z0-9_-]*$/;
10
+ // The form of an area used in topics, unique IDs, object IDs and device
11
+ // identifiers: lowercase, each run of characters other than letters, digits,
12
+ // "_" and "-" as one "_", with no "_" or "-" at either end. "Living Room"
13
+ // becomes "living_room", and an area that is already an identifier, such as
14
+ // "living-room", stays as it is. The area as typed is kept for names shown
15
+ // to people.
16
+ function areaId(area) {
17
+ return area.toLowerCase().replace(/[^a-z0-9_-]+/g, "_").replace(/^[_-]+|[_-]+$/g, "");
18
+ }
19
+ // The area of a node that publishes under it, as typed. `needed` says
20
+ // whether this node's publishing needs one at all.
21
+ function publishingArea(area, needed) {
22
+ if (!area && needed)
23
+ throw new Error("area is required");
24
+ if (area && !areaId(area))
25
+ throw new Error("area must contain a letter or digit");
26
+ return area;
27
+ }
28
+ // A request ID a caller gives: a letter or digit, then up to 127 more of
29
+ // letters, digits and . _ : -. Safe in topics and logs.
30
+ exports.REQUEST_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
31
+ //# sourceMappingURL=topic-names.js.map
@@ -61,9 +61,11 @@ const registerActivityLightingController = (RED) => {
61
61
  schedule(result.state);
62
62
  return result;
63
63
  }
64
- // Context survives a redeploy but timers do not. Recover a pending
65
- // transition with the reducer's own startup (re-observe, never replay)
66
- // rather than ticking old state; a later startup from the flow repeats it.
64
+ // A pending transition is here only if the node's context survived its
65
+ // stop, which needs a configured context store (see the README); timers
66
+ // never survive. Recover it with the reducer's own startup (re-observe,
67
+ // never replay) rather than ticking old state; a later startup from the
68
+ // flow repeats it.
67
69
  if (context.get("state")?.pending) {
68
70
  timer = setTimeout((0, adapter_1.guarded)(node, () => {
69
71
  process({ activityLighting: { kind: "startup" } }, node.send.bind(node));
@@ -1,5 +1,6 @@
1
- import type { Node, NodeMessage } from "node-red";
1
+ import type { Node, NodeAPI, NodeMessage } from "node-red";
2
2
  import { type TraceInput, type TraceMetadata } from "../lib/bounded-trace";
3
+ import { type RetainedClear } from "../lib/retained-topics";
3
4
  export type Send = (msg: NodeMessage | Array<NodeMessage | NodeMessage[] | null>) => void;
4
5
  export type InputMessage = NodeMessage & Record<string, unknown>;
5
6
  export declare function objectField<T>(msg: InputMessage, key: string): T | undefined;
@@ -13,3 +14,7 @@ export declare function optionalArea(config: {
13
14
  area?: unknown;
14
15
  }): string;
15
16
  export declare function invalidConfig(node: Node, reason: unknown): void;
17
+ export declare function whenFlowsStarted(RED: NodeAPI, node: Node, action: () => void): void;
18
+ export declare function allRetainedTopics(node: Node, current: string[]): string[];
19
+ export declare function clearStaleRetained(node: Node, current: string[], when?: "flows-started" | "startup", possible?: string[]): RetainedClear[];
20
+ export declare function wasDeleted(RED: NodeAPI, node: Node, removed: boolean): boolean;
@@ -6,7 +6,13 @@ exports.guarded = guarded;
6
6
  exports.runReducer = runReducer;
7
7
  exports.optionalArea = optionalArea;
8
8
  exports.invalidConfig = invalidConfig;
9
+ exports.whenFlowsStarted = whenFlowsStarted;
10
+ exports.allRetainedTopics = allRetainedTopics;
11
+ exports.clearStaleRetained = clearStaleRetained;
12
+ exports.wasDeleted = wasDeleted;
9
13
  const bounded_trace_1 = require("../lib/bounded-trace");
14
+ const retained_topics_1 = require("../lib/retained-topics");
15
+ const flows_started_1 = require("./flows-started");
10
16
  // The object a message carries under a key, or undefined.
11
17
  function objectField(msg, key) {
12
18
  const value = msg[key];
@@ -20,7 +26,8 @@ function onInput(node, handle) {
20
26
  done();
21
27
  }
22
28
  catch (error) {
23
- node.error(error, msg);
29
+ // done(error) reports it against the message, once, so a Catch node
30
+ // fires once (Node-RED 5.0.10 runtime/lib/nodes/Node.js:132-143).
24
31
  done(error instanceof Error ? error : new Error(String(error)));
25
32
  }
26
33
  });
@@ -57,4 +64,61 @@ function invalidConfig(node, reason) {
57
64
  node.status({ fill: "red", shape: "ring", text: "invalid configuration" });
58
65
  node.error("invalid configuration: " + (reason instanceof Error ? reason.message : String(reason)));
59
66
  }
67
+ // Runs once every flow has started, when the node's outputs reach the nodes
68
+ // wired to them: Node-RED creates a flow's nodes one at a time, so a send
69
+ // from a constructor may find the next node not there yet. Stops waiting if
70
+ // the node closes first.
71
+ function whenFlowsStarted(RED, node, action) {
72
+ const run = guarded(node, action);
73
+ const stop = (0, flows_started_1.onFlowsStarted)(RED.events, () => {
74
+ stop();
75
+ run();
76
+ }, (error) => node.error(error));
77
+ node.on("close", stop);
78
+ }
79
+ // Every retained topic a node publishes now or recorded at its last start,
80
+ // for clearing them all when it is deleted.
81
+ function allRetainedTopics(node, current) {
82
+ const recorded = node.context().get("retainedTopics");
83
+ return [...current, ...(recorded ?? [])];
84
+ }
85
+ // At a node's start: the empty retained messages that clear what it
86
+ // published before and no longer does, recording what it publishes now. The
87
+ // record is kept in the node's context, which Node-RED deletes when the node
88
+ // stops unless a context store is configured (see the README). `possible` is
89
+ // every topic the node could publish with its current names (area, IDs,
90
+ // prefix, targets) and its publishing switched on: those it doesn't publish
91
+ // now are cleared too, so switching publishing off clears its topics even
92
+ // with no record. Only a change of names needs the record.
93
+ //
94
+ // It runs twice: once the flows have started, so no startup message is
95
+ // needed, and again at the startup message. The first may go out before the
96
+ // MQTT broker has reconnected (after a full deploy or a restart), when the
97
+ // broker node drops it, so it keeps the cleared topics in the record and the
98
+ // second clears them again and settles the record. Clearing a topic twice
99
+ // does no harm.
100
+ function clearStaleRetained(node, current, when = "startup", possible = []) {
101
+ const context = node.context();
102
+ const recorded = context.get("retainedTopics");
103
+ const { clears, record } = (0, retained_topics_1.staleRetainedTopics)([...(recorded ?? []), ...possible], current, when === "flows-started");
104
+ context.set("retainedTopics", record);
105
+ return clears;
106
+ }
107
+ // Whether a closing node was deleted, rather than disabled or redeployed.
108
+ // Node-RED 5 reports `removed` for a deleted node and for a disabled node or
109
+ // flow alike. During a deploy, RED.nodes.eachNode already lists the new
110
+ // flows, which still hold a disabled node but not a deleted one. A node in a
111
+ // subflow instance is looked up by the subflow's own copy of it (_alias), so
112
+ // it never counts as deleted.
113
+ function wasDeleted(RED, node, removed) {
114
+ if (!removed)
115
+ return false;
116
+ const id = node._alias ?? node.id;
117
+ let listed = false;
118
+ RED.nodes.eachNode((entry) => {
119
+ if (entry.id === id)
120
+ listed = true;
121
+ });
122
+ return !listed;
123
+ }
60
124
  //# sourceMappingURL=adapter.js.map
@@ -1,22 +1,57 @@
1
1
  <script type="text/javascript">
2
+ (function () {
3
+ function on(value) { return value === true || value === "true"; }
2
4
  RED.nodes.registerType("home-avr-controller", {
3
5
  category: "home automation",
4
6
  color: "#c7d9f1",
5
7
  defaults: {
6
- name: {value: ""},
7
- area: {value: ""},
8
+ // A marker only a node new from the palette has, as core nodes do: import
9
+ // and paste keep the saved name, so onadd leaves a saved node's settings.
10
+ name: {value: "_DEFAULT_"},
11
+ // Required only when the node publishes, and then with a letter or
12
+ // digit, from which its topics and IDs are made.
13
+ area: {value: "", validate: function (v) {
14
+ var publishing = $("#node-input-publishState").length ? $("#node-input-publishState").prop("checked") : on(this.publishState);
15
+ return !publishing || /[a-z0-9]/i.test(String(v || ""));
16
+ }},
8
17
  sources: {value: "{\"shield\":\"SAT/CBL\",\"playstation\":\"GAME\"}", required: true, validate: function (v) { try { JSON.parse(v); return true; } catch (e) { return false; } }},
9
18
  retryMs: {value: 2000, required: true, validate: RED.validators.number()},
10
19
  maxAttempts: {value: 3, required: true, validate: RED.validators.number()},
11
20
  minVolume: {value: 0, required: true, validate: RED.validators.number()},
12
- maxVolume: {value: 60, required: true, validate: RED.validators.number()}
21
+ maxVolume: {value: 60, required: true, validate: RED.validators.number()},
22
+ // The receiver published nothing before these settings, so both start off.
23
+ publishState: {value: false},
24
+ discovery: {value: false},
25
+ discoveryPrefix: {value: "homeassistant", required: true, validate: function (v) { var prefix = String(v || "").trim().replace(/^\/+|\/+$/g, ""); return Boolean(prefix) && !/[+#]/.test(prefix); }},
26
+ // How Home Assistant IDs are named; the receiver has no older entities,
27
+ // so not set also means "node".
28
+ idScheme: {value: null}
29
+ },
30
+ onadd: function () {
31
+ if (this.name !== "_DEFAULT_") return;
32
+ this.name = "";
33
+ this.idScheme = "node";
34
+ },
35
+ oneditprepare: function () {
36
+ $("#node-input-publishState").prop("checked", on(this.publishState));
37
+ $("#node-input-discovery").prop("checked", on(this.discovery));
38
+ // Discovery describes the published state, so it needs it.
39
+ function follow() {
40
+ var publishing = $("#node-input-publishState").prop("checked");
41
+ if (!publishing) $("#node-input-discovery").prop("checked", false);
42
+ $("#node-input-discovery").prop("disabled", !publishing);
43
+ $("#node-input-area").trigger("change");
44
+ }
45
+ $("#node-input-publishState, #node-input-discovery").on("change", follow);
46
+ follow();
13
47
  },
14
48
  inputs: 1,
15
- outputs: 2,
16
- outputLabels: ["Denon commands", "state and results"],
49
+ outputs: 3,
50
+ outputLabels: ["Denon commands", "state and results", "MQTT publications"],
17
51
  icon: "font-awesome/fa-volume-up",
18
52
  label: function () { return this.name || (this.area ? this.area + " " : "") + "AVR controller"; }
19
53
  });
54
+ })();
20
55
  </script>
21
56
 
22
57
  <script type="text/html" data-template-name="home-avr-controller">
@@ -27,6 +62,9 @@
27
62
  <div class="form-row"><label for="node-input-maxAttempts">Maximum attempts</label><input type="number" id="node-input-maxAttempts"></div>
28
63
  <div class="form-row"><label for="node-input-minVolume">Minimum volume</label><input type="number" step="0.5" id="node-input-minVolume"></div>
29
64
  <div class="form-row"><label for="node-input-maxVolume">Maximum volume</label><input type="number" step="0.5" id="node-input-maxVolume"></div>
65
+ <div class="form-row"><label for="node-input-publishState">Publish state over MQTT</label><input type="checkbox" id="node-input-publishState" style="display:inline-block; width:auto;"></div>
66
+ <div class="form-row"><label for="node-input-discovery">Home Assistant discovery</label><input type="checkbox" id="node-input-discovery" style="display:inline-block; width:auto;"> <span>(needs Publish state)</span></div>
67
+ <div class="form-row"><label for="node-input-discoveryPrefix">Discovery prefix</label><input type="text" id="node-input-discoveryPrefix"></div>
30
68
  </script>
31
69
 
32
70
  <script type="text/html" data-help-name="home-avr-controller">
@@ -44,4 +82,20 @@
44
82
  <dt>volume_manual_override</dt><dd><code>{kind, area, requestId, reason, observed, target}</code>: the receiver moved elsewhere while the request was in flight.</dd>
45
83
  <dt>volume_external</dt><dd><code>{kind, area, previous, observed}</code>: a change made outside any request.</dd>
46
84
  </dl>
85
+ <h3>Publishing</h3>
86
+ <p>Off unless switched on, and then named after the <b>Area</b>, which is needed.</p>
87
+ <dl class="message-properties">
88
+ <dt>Publish state over MQTT</dt><dd>what the receiver reports, retained, whenever it changes:
89
+ <code>home/&lt;area&gt;/receiver/power/state</code> (<code>ON</code> or <code>OFF</code>),
90
+ <code>…/source/state</code> (the source name) and <code>…/volume/state</code>, with <code>online</code> or
91
+ <code>offline</code> on <code>…/availability</code>.</dd>
92
+ <dt>Home Assistant discovery</dt><dd>power and source sensors, and a volume number between <b>Minimum volume</b>
93
+ and <b>Maximum volume</b>. It needs <b>Publish state</b>. A volume set there arrives on
94
+ <code>…/volume/set</code>; wire an MQTT in node on that topic into this node. Sets arriving within 0.3 seconds
95
+ of each other (a slider, repeated taps) are settled to the last one, which becomes an ordinary absolute
96
+ volume request, bounded and confirmed like any other: it waits for a power or source change in progress (such
97
+ as a theatre activity's), and is rejected with <code>receiver-not-ready</code> while the receiver is off.</dd>
98
+ </dl>
99
+ <p>These go on the third output; wire it to an MQTT out node. The node announces itself once the flows have
100
+ started, and again at <code>kind: "startup"</code>.</p>
47
101
  </script>
@@ -2,6 +2,11 @@
2
2
  const avr_controller_1 = require("../lib/avr-controller");
3
3
  const adapter_1 = require("./adapter");
4
4
  const settings_1 = require("../lib/settings");
5
+ const avr_publishing_1 = require("../lib/avr-publishing");
6
+ const ha_discovery_1 = require("../lib/ha-discovery");
7
+ const topic_names_1 = require("../lib/topic-names");
8
+ const publishing_node_1 = require("../lib/publishing-node");
9
+ const publishing_lifecycle_1 = require("./publishing-lifecycle");
5
10
  function parseSources(value) {
6
11
  const sources = (0, settings_1.jsonSetting)(value, "sources", {});
7
12
  if (!sources || Array.isArray(sources) || typeof sources !== "object") {
@@ -16,10 +21,28 @@ const registerAvrController = (RED) => {
16
21
  const context = node.context();
17
22
  let retryTimer;
18
23
  let controllerConfig;
24
+ let publishing;
19
25
  try {
20
26
  // The same validation the reducer applies, so a bad configuration
21
27
  // fails here at deploy rather than on every message.
22
28
  controllerConfig = (0, avr_controller_1.normaliseAvrConfig)({ ...config, area: (0, adapter_1.optionalArea)(config), sources: parseSources(config.sources) });
29
+ // Off unless switched on, as the receiver published nothing before;
30
+ // there are no older entities to keep, so not set names them after
31
+ // the node.
32
+ const publishState = (0, settings_1.optionalBooleanSetting)(config.publishState, "publish state") ?? false;
33
+ const discovery = (0, settings_1.optionalBooleanSetting)(config.discovery, "Home Assistant discovery") ?? false;
34
+ if (publishState || discovery)
35
+ (0, topic_names_1.publishingArea)(controllerConfig.area, true);
36
+ publishing = {
37
+ area: controllerConfig.area,
38
+ publishState,
39
+ discovery,
40
+ discoveryPrefix: (0, ha_discovery_1.discoveryPrefixSetting)(config.discoveryPrefix),
41
+ nodeId: node.id,
42
+ idScheme: (0, settings_1.optionalChoiceSetting)(config.idScheme, "ID scheme", ha_discovery_1.ID_SCHEMES) ?? "node",
43
+ minVolume: controllerConfig.minVolume,
44
+ maxVolume: controllerConfig.maxVolume
45
+ };
23
46
  }
24
47
  catch (error) {
25
48
  (0, adapter_1.invalidConfig)(node, error);
@@ -47,7 +70,23 @@ const registerAvrController = (RED) => {
47
70
  process({ avr: { kind: "tick" } }, node.send.bind(node));
48
71
  }), delay);
49
72
  }
73
+ function observed() {
74
+ return context.get("state")?.observed;
75
+ }
76
+ // MQTT publications go on the third output, apart from the receiver's
77
+ // commands and the theatre's events. Available, and clear of what it no
78
+ // longer publishes, as soon as it runs; offline as it stops; nothing
79
+ // left behind when deleted.
80
+ const lifecycle = (0, publishing_lifecycle_1.publishingLifecycle)(RED, node, {
81
+ retainedTopics: () => (0, avr_publishing_1.avrRetainedTopics)(publishing),
82
+ possible: { owner: publishing, topics: () => (0, publishing_node_1.publishesState)(publishing) ? (0, avr_publishing_1.avrRetainedTopics)({ ...publishing, publishState: true, discovery: true }) : [] },
83
+ starting: () => (0, avr_publishing_1.avrStartingOutputs)(publishing, observed()),
84
+ stopping: () => (0, avr_publishing_1.avrStoppingOutputs)(publishing),
85
+ output: 2,
86
+ outputs: 3
87
+ });
50
88
  function process(msg, send) {
89
+ const before = observed();
51
90
  const result = (0, adapter_1.runReducer)(node, { area: controllerConfig.area, component: "avr-controller" }, (saved, now) => (0, avr_controller_1.transitionAvr)(saved, msg, controllerConfig, now));
52
91
  const commands = result.commands.map((command) => ({
53
92
  payload: Buffer.from(command.payload, "utf8"),
@@ -59,22 +98,52 @@ const registerAvrController = (RED) => {
59
98
  commands.length ? commands : null,
60
99
  outputs.length
61
100
  ? outputs.map((event) => ({ payload: undefined, ...event }))
62
- : null
101
+ : null,
102
+ null
63
103
  ]);
64
104
  }
105
+ // Whatever it now observes differently from before.
106
+ lifecycle.publish(send, (0, avr_publishing_1.avrStateOutputs)(publishing, result.state.observed, before ?? {}));
65
107
  updateStatus(result.status);
66
108
  scheduleRetry(result.state);
67
109
  return result;
68
110
  }
69
- // Context survives a redeploy but timers do not. Recover a pending
70
- // transition with the reducer's own startup (re-observe, never replay)
71
- // rather than ticking old state; a later startup from the flow repeats it.
111
+ // A pending transition is here only if the node's context survived its
112
+ // stop, which needs a configured context store (see the README); timers
113
+ // never survive. Recover it with the reducer's own startup (re-observe,
114
+ // never replay) rather than ticking old state; a later startup from the
115
+ // flow repeats it.
72
116
  if (context.get("state")?.pending) {
73
117
  retryTimer = setTimeout((0, adapter_1.guarded)(node, () => {
74
118
  process({ avr: { kind: "startup" } }, node.send.bind(node));
75
119
  }), 0);
76
120
  }
121
+ // Each request from the volume number gets its own ID, as the receiver
122
+ // answers a repeated ID only once. Sets arriving in a burst are settled
123
+ // to the last one first.
124
+ let volumeRequests = 0;
125
+ let volumeSetTimer;
126
+ function requestVolume(value) {
127
+ volumeRequests += 1;
128
+ process({ avr: { kind: "volume", requestId: `mqtt-volume-${Date.now()}-${volumeRequests}`, mode: "absolute", value } }, node.send.bind(node));
129
+ }
77
130
  (0, adapter_1.onInput)(node, (msg, send) => {
131
+ const volume = (0, avr_publishing_1.avrVolumeRequest)(msg, publishing);
132
+ if (volume && "ignored" in volume) {
133
+ (0, adapter_1.runReducer)(node, { area: controllerConfig.area, component: "avr-controller" }, (saved) => ({ state: saved, traces: [{ event: "volume-set", outcome: "ignored", reason: volume.ignored, details: { payload: volume.payload } }] }));
134
+ return;
135
+ }
136
+ if (volume) {
137
+ clearTimeout(volumeSetTimer);
138
+ volumeSetTimer = setTimeout((0, adapter_1.guarded)(node, () => {
139
+ volumeSetTimer = undefined;
140
+ requestVolume(volume.value);
141
+ }), avr_publishing_1.VOLUME_SET_SETTLE_MS);
142
+ return;
143
+ }
144
+ if ((0, adapter_1.objectField)(msg, "avr")?.kind === "startup") {
145
+ lifecycle.startup(send, (0, avr_publishing_1.avrStartingOutputs)(publishing, observed()));
146
+ }
78
147
  process({
79
148
  avr: (0, adapter_1.objectField)(msg, "avr"),
80
149
  payload: msg.payload
@@ -82,6 +151,7 @@ const registerAvrController = (RED) => {
82
151
  });
83
152
  node.on("close", (_removed, done) => {
84
153
  clearTimeout(retryTimer);
154
+ clearTimeout(volumeSetTimer);
85
155
  done();
86
156
  });
87
157
  }
@@ -57,9 +57,11 @@ const registerBacklightingController = (RED) => {
57
57
  schedule(result.state);
58
58
  return result;
59
59
  }
60
- // Context survives a redeploy but timers do not. Recover a pending
61
- // transition with the reducer's own startup (re-observe, never replay)
62
- // rather than ticking old state; a later startup from the flow repeats it.
60
+ // A pending transition is here only if the node's context survived its
61
+ // stop, which needs a configured context store (see the README); timers
62
+ // never survive. Recover it with the reducer's own startup (re-observe,
63
+ // never replay) rather than ticking old state; a later startup from the
64
+ // flow repeats it.
63
65
  if (context.get("state")?.pending) {
64
66
  timer = setTimeout((0, adapter_1.guarded)(node, () => {
65
67
  process({ backlighting: { kind: "startup" } }, node.send.bind(node));
@@ -0,0 +1,3 @@
1
+ import type { NodeInitializer } from "node-red";
2
+ declare const registerCoverController: NodeInitializer;
3
+ export = registerCoverController;