@avantics/node-red-home-automation 6.1.0 → 6.2.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 (70) hide show
  1. package/README.md +204 -42
  2. package/dist/lib/cover-publishing.js +20 -6
  3. package/dist/lib/home-assistant-setting.d.ts +23 -0
  4. package/dist/lib/home-assistant-setting.js +39 -0
  5. package/dist/lib/motion-policy.d.ts +1 -0
  6. package/dist/lib/motion-policy.js +21 -1
  7. package/dist/lib/room-controller.d.ts +1 -0
  8. package/dist/lib/room-controller.js +5 -0
  9. package/dist/lib/room-publishing.d.ts +1 -0
  10. package/dist/lib/room-publishing.js +11 -0
  11. package/dist/lib/scene-publishing.d.ts +30 -0
  12. package/dist/lib/scene-publishing.js +63 -0
  13. package/dist/lib/scene.d.ts +61 -0
  14. package/dist/lib/scene.js +170 -0
  15. package/dist/lib/shelly-cover.js +5 -0
  16. package/dist/lib/shelly-relay-light.d.ts +24 -0
  17. package/dist/lib/shelly-relay-light.js +93 -0
  18. package/dist/lib/shelly-switch.d.ts +8 -0
  19. package/dist/lib/shelly-switch.js +37 -8
  20. package/dist/lib/theatre-activity-controller.js +4 -0
  21. package/dist/lib/theatre-metrics.js +6 -4
  22. package/dist/lib/theatre-slo.js +3 -0
  23. package/dist/lib/theatre-state-contract.d.ts +4 -2
  24. package/dist/lib/theatre-state-contract.js +51 -8
  25. package/dist/lib/theatre-state.js +3 -0
  26. package/dist/nodes/avr-controller.html +82 -21
  27. package/dist/nodes/avr-controller.js +23 -11
  28. package/dist/nodes/circadian-policy.html +84 -20
  29. package/dist/nodes/circadian-policy.js +30 -11
  30. package/dist/nodes/cover-controller.html +87 -25
  31. package/dist/nodes/cover-controller.js +25 -12
  32. package/dist/nodes/device-side.d.ts +20 -0
  33. package/dist/nodes/device-side.js +72 -0
  34. package/dist/nodes/home-assistant-discovery.d.ts +26 -0
  35. package/dist/nodes/home-assistant-discovery.js +64 -0
  36. package/dist/nodes/house-schedule-mqtt.html +70 -5
  37. package/dist/nodes/house-schedule-mqtt.js +22 -8
  38. package/dist/nodes/motion-policy.html +87 -22
  39. package/dist/nodes/motion-policy.js +44 -11
  40. package/dist/nodes/mqtt-broker-link.d.ts +41 -0
  41. package/dist/nodes/mqtt-broker-link.js +91 -0
  42. package/dist/nodes/occupancy-fusion.html +83 -20
  43. package/dist/nodes/occupancy-fusion.js +23 -11
  44. package/dist/nodes/publishing-side.d.ts +20 -0
  45. package/dist/nodes/publishing-side.js +66 -0
  46. package/dist/nodes/room-controller.html +106 -35
  47. package/dist/nodes/room-controller.js +63 -16
  48. package/dist/nodes/scene.d.ts +3 -0
  49. package/dist/nodes/scene.html +226 -0
  50. package/dist/nodes/scene.js +121 -0
  51. package/dist/nodes/shelly-cover.html +46 -2
  52. package/dist/nodes/shelly-cover.js +19 -4
  53. package/dist/nodes/shelly-switch.html +75 -6
  54. package/dist/nodes/shelly-switch.js +32 -7
  55. package/dist/nodes/theatre-state-contract.html +72 -9
  56. package/dist/nodes/theatre-state-contract.js +33 -14
  57. package/dist/nodes/z2m-cover.html +46 -2
  58. package/dist/nodes/z2m-cover.js +21 -4
  59. package/dist/nodes/z2m-light.html +46 -2
  60. package/dist/nodes/z2m-light.js +23 -4
  61. package/examples/Cover control.json +38 -91
  62. package/examples/Cover pair.json +36 -3
  63. package/examples/Home theatre activity.json +46 -91
  64. package/examples/Home theatre equipment.json +34 -2
  65. package/examples/House schedule.json +58 -80
  66. package/examples/Room lighting.json +45 -44
  67. package/examples/Scene.json +215 -0
  68. package/examples/Shelly cover.json +36 -105
  69. package/examples/Shelly switch.json +52 -148
  70. package/package.json +2 -1
@@ -32,7 +32,8 @@ function resetTransitionMetrics(metrics) {
32
32
  }
33
33
  }
34
34
  // A target's report: its attempts, fallback use, how old its observation is
35
- // and, once ready, how long after the transition started it confirmed.
35
+ // and, at its first ready report in this transition, how long after the
36
+ // transition started it confirmed. Its refreshes leave that figure.
36
37
  function recordTargetReport(metric, report, previous, observedAt, transitionStartedAt, nowMs) {
37
38
  const details = report.details && typeof report.details === "object" ? report.details : {};
38
39
  const detailMetrics = details.metrics && typeof details.metrics === "object" &&
@@ -48,10 +49,11 @@ function recordTargetReport(metric, report, previous, observedAt, transitionStar
48
49
  metric.fallbackUsed ||= fallbackUsed;
49
50
  metric.observationAgeMs = observedAt === null ? null : Math.max(0, nowMs - observedAt);
50
51
  if (report.status === "ready") {
52
+ // Null until then: resetTransitionMetrics clears it at each transition.
51
53
  const startedAt = Date.parse(transitionStartedAt || "");
52
- metric.lastConfirmationMs = Number.isFinite(startedAt) && observedAt !== null
53
- ? Math.max(0, observedAt - startedAt)
54
- : null;
54
+ if (metric.lastConfirmationMs === null && Number.isFinite(startedAt) && observedAt !== null) {
55
+ metric.lastConfirmationMs = Math.max(0, observedAt - startedAt);
56
+ }
55
57
  metric.availability = "available";
56
58
  }
57
59
  else if (report.status === "failed" || report.status === "unavailable") {
@@ -16,6 +16,9 @@ function normaliseTheatreSloConfig(config = {}) {
16
16
  };
17
17
  }
18
18
  function duration(value) {
19
+ // Not timed: null, as given. Number(null) would make it 0 ms.
20
+ if (value === null || value === undefined || value === "")
21
+ return null;
19
22
  const parsed = Number(value);
20
23
  return Number.isFinite(parsed) && parsed >= 0 ? parsed : null;
21
24
  }
@@ -3,7 +3,9 @@ import { type TheatreRequestState, type TheatreStateSnapshot } from "./theatre-r
3
3
  import type { TraceEntry } from "./bounded-trace";
4
4
  import { type IdScheme } from "./ha-discovery";
5
5
  export type { ContractRequest, TheatreStateSnapshot } from "./theatre-requests";
6
- export type TheatreStateContractState = TheatreRequestState;
6
+ export type TheatreStateContractState = TheatreRequestState & {
7
+ published: Record<string, string>;
8
+ };
7
9
  export interface TheatreStateContractConfig {
8
10
  nodeId?: string;
9
11
  idScheme?: IdScheme;
@@ -43,7 +45,7 @@ export declare function theatreRetainedTopics(config: TheatreStateContractConfig
43
45
  export declare function theatreStartingPublications(config: TheatreStateContractConfig): ContractPublication[];
44
46
  export declare function theatreStoppingPublications(config: TheatreStateContractConfig): ContractPublication[];
45
47
  export declare function transitionTheatreStateContract(saved: Partial<TheatreStateContractState> | undefined, msg: TheatreStateContractMessage, suppliedConfig: Partial<TheatreStateContractConfig>, nowValue?: Date | string | number): {
46
- state: TheatreRequestState;
48
+ state: TheatreStateContractState;
47
49
  requests: ContractRequestOutput[];
48
50
  publications: ContractPublication[];
49
51
  traces: TraceEntry<Record<string, unknown>>[];
@@ -134,6 +134,37 @@ const STATE_TOPICS = [
134
134
  function statePublications(event, config, slo) {
135
135
  return STATE_TOPICS.map(([name, value]) => publication((0, theatre_ha_discovery_1.theatreTopic)(config.baseTopic, name), value(event, slo)));
136
136
  }
137
+ // Fields that only say when, or how long ago, something was seen: they move
138
+ // on every refresh of a steady target, so a payload that differs only in
139
+ // them is not a change. A target's health keeps the time it last changed.
140
+ // (A target's lastConfirmationMs is set once per transition, so it counts.)
141
+ const TIME_ONLY_FIELDS = new Set(["observedAt", "evaluatedAt", "observationAgeMs"]);
142
+ function comparable(payload) {
143
+ let value;
144
+ try {
145
+ value = JSON.parse(payload);
146
+ }
147
+ catch {
148
+ return payload;
149
+ }
150
+ const strip = (entry) => Array.isArray(entry)
151
+ ? entry.map(strip)
152
+ : entry && typeof entry === "object"
153
+ ? Object.fromEntries(Object.entries(entry).filter(([key]) => !TIME_ONLY_FIELDS.has(key)).map(([key, inner]) => [key, strip(inner)]))
154
+ : entry;
155
+ return JSON.stringify(strip(value));
156
+ }
157
+ // Only the publications whose payload changed, beyond its time-only
158
+ // fields, since the contract last published that topic; it records them.
159
+ function changed(state, publications) {
160
+ return publications.filter(({ topic, payload }) => {
161
+ const key = comparable(payload);
162
+ if (state.published[topic] === key)
163
+ return false;
164
+ state.published[topic] = key;
165
+ return true;
166
+ });
167
+ }
137
168
  function requestPublications(request, config) {
138
169
  const base = config.baseTopic;
139
170
  return [
@@ -174,7 +205,10 @@ function theatreStoppingPublications(config) {
174
205
  }
175
206
  function transitionTheatreStateContract(saved, msg, suppliedConfig, nowValue = new Date()) {
176
207
  const config = normaliseStateContractConfig(suppliedConfig);
177
- const state = (0, theatre_requests_1.createTheatreRequestState)(saved);
208
+ const state = {
209
+ ...(0, theatre_requests_1.createTheatreRequestState)(saved),
210
+ published: saved?.published && typeof saved.published === "object" && !Array.isArray(saved.published) ? { ...saved.published } : {}
211
+ };
178
212
  const now = nowValue instanceof Date ? nowValue : new Date(nowValue);
179
213
  if (!Number.isFinite(now.getTime()))
180
214
  throw new Error("now must be a valid date");
@@ -190,6 +224,9 @@ function transitionTheatreStateContract(saved, msg, suppliedConfig, nowValue = n
190
224
  const entries = config.discovery !== false || config.area ? (0, theatre_ha_discovery_1.theatreDiscovery)(config) : [];
191
225
  publications.push(...entries.map(({ topic, payload }) => publication(topic, config.discovery !== false ? payload : "")));
192
226
  publications.push(publication((0, theatre_ha_discovery_1.theatreTopic)(config.baseTopic, "availability"), ha_discovery_1.ONLINE));
227
+ // Each startup, and with a broker each connect: the next snapshot
228
+ // publishes every state topic again, in case the broker lost them.
229
+ state.published = {};
193
230
  trace("startup", "discovery", null, { publications: publications.length });
194
231
  }
195
232
  else if (msg.topic === (0, theatre_ha_discovery_1.theatreTopic)(config.baseTopic, "request")) {
@@ -207,7 +244,7 @@ function transitionTheatreStateContract(saved, msg, suppliedConfig, nowValue = n
207
244
  else {
208
245
  trace("request", "accepted", null, { requestId: request.requestId, generation: state.generation, activity: request.activity });
209
246
  }
210
- publications.push(...requestPublications(request, config));
247
+ publications.push(...changed(state, requestPublications(request, config)));
211
248
  }
212
249
  }
213
250
  else if (msg.theatre && typeof msg.theatre === "object" && msg.theatre.kind === "state") {
@@ -217,12 +254,18 @@ function transitionTheatreStateContract(saved, msg, suppliedConfig, nowValue = n
217
254
  trace("state", "ignored", "stale-generation", { generation: event.generation });
218
255
  }
219
256
  else {
220
- publications.push(...statePublications(event, config, assessment));
221
- trace("state", "published", null, {
222
- generation: event.generation,
223
- phase: event.phase,
224
- publications: publications.length
225
- });
257
+ const all = statePublications(event, config, assessment);
258
+ publications.push(...changed(state, all));
259
+ if (!publications.length) {
260
+ trace("state", "unchanged", null, { generation: event.generation, phase: event.phase });
261
+ }
262
+ else {
263
+ trace("state", "published", null, {
264
+ generation: event.generation,
265
+ phase: event.phase,
266
+ publications: publications.length
267
+ });
268
+ }
226
269
  }
227
270
  }
228
271
  else {
@@ -43,6 +43,9 @@ function count(value) {
43
43
  return Number.isInteger(parsed) && parsed >= 0 ? parsed : 0;
44
44
  }
45
45
  function nullableDuration(value) {
46
+ // Not a duration yet: null, as saved. Number(null) would make it 0.
47
+ if (value === null || value === undefined || value === "")
48
+ return null;
46
49
  const parsed = Number(value);
47
50
  return Number.isFinite(parsed) && parsed >= 0 ? parsed : null;
48
51
  }
@@ -5,6 +5,31 @@
5
5
  // A dB bound. A node saved before 5.0 has none (its 0-98 bounds were
6
6
  // removed in 6.0), so it shows as invalid until they are set.
7
7
  function volumeBound(value) { return given(value) && Number.isFinite(Number(value)); }
8
+ // Its Publish choice (off, state or discovery), from the open dialog or
9
+ // its saved settings: a node saved before the choice reads its two old
10
+ // settings (lib/home-assistant-setting.ts).
11
+ function publishChoice(node) {
12
+ function on(value) { return value === true || value === "true"; }
13
+ var select = $("#node-input-homeAssistant");
14
+ if (select.length) return select.val();
15
+ if (node.homeAssistant === "off" || node.homeAssistant === "state" || node.homeAssistant === "discovery") return node.homeAssistant;
16
+ return !on(node.publishState) ? "off" : on(node.discovery) ? "discovery" : "state";
17
+ }
18
+ // Whether it publishes through its output, as before 6.2: a node saved
19
+ // before the Publish choice that published, or one opened and saved since
20
+ // without a broker (publishesThroughOutput). It needs no broker until one
21
+ // is chosen; from saved values only, not the open dialog.
22
+ function throughOutput(node) {
23
+ if (node.publishesThroughOutput === true) return true;
24
+ return (node.homeAssistant === null || node.homeAssistant === undefined) && (node.publishState === true || node.publishState === "true");
25
+ }
26
+ // Its area is needed while it publishes, and for a node saved before the
27
+ // choice whenever either old setting was on, as the runtime checks.
28
+ function needsArea(node) {
29
+ function on(value) { return value === true || value === "true"; }
30
+ var saved = !$("#node-input-homeAssistant").length && (node.homeAssistant === null || node.homeAssistant === undefined);
31
+ return publishChoice(node) !== "off" || (saved && (on(node.publishState) || on(node.discovery)));
32
+ }
8
33
  RED.nodes.registerType("home-avr-controller", {
9
34
  category: "home automation",
10
35
  color: "#c7d9f1",
@@ -14,10 +39,7 @@
14
39
  name: {value: "_DEFAULT_"},
15
40
  // Required only when the node publishes, and then with a letter or
16
41
  // digit, from which its topics and IDs are made.
17
- area: {value: "", validate: function (v) {
18
- var publishing = $("#node-input-publishState").length ? $("#node-input-publishState").prop("checked") : on(this.publishState);
19
- return !publishing || /[a-z0-9]/i.test(String(v || ""));
20
- }},
42
+ area: {value: "", validate: function (v) { return !needsArea(this) || /[a-z0-9]/i.test(String(v || "")); }},
21
43
  sources: {value: "{\"shield\":\"SAT/CBL\",\"playstation\":\"GAME\"}", required: true, validate: function (v) { try { JSON.parse(v); return true; } catch (e) { return false; } }},
22
44
  retryMs: {value: 2000, required: true, validate: RED.validators.number()},
23
45
  maxAttempts: {value: 3, required: true, validate: RED.validators.number()},
@@ -34,8 +56,22 @@
34
56
  minVolume: {value: ""},
35
57
  maxVolume: {value: ""},
36
58
  // The receiver published nothing before these settings, so both start off.
59
+ // Publish: off, state or discovery. null means "not set": a node saved
60
+ // before this setting, read from the two below, kept with no rows.
61
+ homeAssistant: {value: null},
62
+ // Node-RED's MQTT broker node, through which it publishes and reads its set
63
+ // topics itself. Needed unless Publish is "Don't publish". The editor offers
64
+ // the first broker when the dialog is opened and saved, not when the node
65
+ // is dropped.
66
+ broker: {value: "", type: "mqtt-broker", required: false, validate: function (v) {
67
+ return publishChoice(this) === "off" || (Boolean(v) && v !== "_ADD_") || throughOutput(this) ? true : "choose a broker, or set Publish to Don't publish";
68
+ }},
37
69
  publishState: {value: false},
38
70
  discovery: {value: false},
71
+ // true for a node that publishes through its output, as before 6.2, and
72
+ // was opened and saved without a broker: it stays valid until a broker is
73
+ // chosen. No form row.
74
+ publishesThroughOutput: {value: false},
39
75
  discoveryPrefix: {value: "homeassistant", required: true, validate: function (v) { var prefix = String(v || "").trim().replace(/^\/+|\/+$/g, ""); return Boolean(prefix) && !/[+#]/.test(prefix); }},
40
76
  // How Home Assistant IDs are named; the receiver has no older entities,
41
77
  // so not set also means "node".
@@ -47,20 +83,26 @@
47
83
  this.idScheme = "node";
48
84
  },
49
85
  oneditprepare: function () {
50
- $("#node-input-publishState").prop("checked", on(this.publishState));
51
- $("#node-input-discovery").prop("checked", on(this.discovery));
52
- // Discovery describes the published state, so it needs it.
53
- function follow() {
54
- var publishing = $("#node-input-publishState").prop("checked");
55
- if (!publishing) $("#node-input-discovery").prop("checked", false);
56
- $("#node-input-discovery").prop("disabled", !publishing);
57
- $("#node-input-area").trigger("change");
86
+ $("#node-input-homeAssistant").val(publishChoice(this));
87
+ // The broker only while it publishes, the prefix only with discovery.
88
+ var outputBefore = throughOutput(this);
89
+ function publishRows() {
90
+ var broker = $("#node-input-broker").val();
91
+ $(".publish-through-output").toggle($("#node-input-homeAssistant").val() !== "off" && outputBefore && (!broker || broker === "_ADD_"));
92
+ var choice = $("#node-input-homeAssistant").val();
93
+ $(".publish-broker").toggle(choice !== "off");
94
+ $(".publish-discovery").toggle(choice === "discovery");
95
+ $("#node-input-area, #node-input-broker").trigger("change");
58
96
  }
59
- $("#node-input-publishState, #node-input-discovery").on("change", follow);
60
- follow();
97
+ $("#node-input-homeAssistant, #node-input-broker").on("change", publishRows);
98
+ publishRows();
61
99
  },
62
100
  // Once the dB bounds are set, the removed 0-98 ones go.
63
101
  oneditsave: function () {
102
+ // Through its output until a broker is chosen (read before the
103
+ // dialog's values are applied).
104
+ var broker = $("#node-input-broker").val();
105
+ this.publishesThroughOutput = throughOutput(this) && (!broker || broker === "_ADD_");
64
106
  if (given($("#node-input-minVolumeDb").val())) this.minVolume = "";
65
107
  if (given($("#node-input-maxVolumeDb").val())) this.maxVolume = "";
66
108
  },
@@ -81,9 +123,20 @@
81
123
  <div class="form-row"><label for="node-input-maxAttempts">Maximum attempts</label><input type="number" id="node-input-maxAttempts"></div>
82
124
  <div class="form-row"><label for="node-input-minVolumeDb">Minimum volume (dB)</label><input type="number" step="0.5" id="node-input-minVolumeDb"></div>
83
125
  <div class="form-row"><label for="node-input-maxVolumeDb">Maximum volume (dB)</label><input type="number" step="0.5" id="node-input-maxVolumeDb"></div>
84
- <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>
85
- <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>
86
- <div class="form-row"><label for="node-input-discoveryPrefix">Discovery prefix</label><input type="text" id="node-input-discoveryPrefix"></div>
126
+ <div class="form-row">
127
+ <label for="node-input-homeAssistant">Publish</label>
128
+ <select id="node-input-homeAssistant">
129
+ <option value="off">Don't publish</option>
130
+ <option value="state">MQTT state</option>
131
+ <option value="discovery">MQTT state and Home Assistant discovery</option>
132
+ </select>
133
+ </div>
134
+ <div class="form-row publish-broker"><label for="node-input-broker">Broker</label><input type="text" id="node-input-broker"></div>
135
+ <div class="form-tips publish-broker">With a broker, it publishes and reads its set topics itself: an MQTT out on its
136
+ publication output, an MQTT in on its set topics, and a Status node are no longer needed and can be deleted.</div>
137
+ <div class="form-tips publish-through-output">This node publishes through its output, as before 6.2, and keeps
138
+ working that way. Choose a Broker to let it publish itself.</div>
139
+ <div class="form-row publish-discovery"><label for="node-input-discoveryPrefix">Discovery prefix</label><input type="text" id="node-input-discoveryPrefix"></div>
87
140
  </script>
88
141
 
89
142
  <script type="text/html" data-help-name="home-avr-controller">
@@ -104,12 +157,12 @@
104
157
  <h3>Publishing</h3>
105
158
  <p>Off unless switched on, and then named after the <b>Area</b>, which is needed.</p>
106
159
  <dl class="message-properties">
107
- <dt>Publish state over MQTT</dt><dd>what the receiver reports, retained, whenever it changes:
160
+ <dt>Publish: MQTT state</dt><dd>what the receiver reports, retained, whenever it changes:
108
161
  <code>home/&lt;area&gt;/receiver/power/state</code> (<code>ON</code> or <code>OFF</code>),
109
162
  <code>…/source/state</code> (the source name) and <code>…/volume/state</code>, with <code>online</code> or
110
163
  <code>offline</code> on <code>…/availability</code>.</dd>
111
- <dt>Home Assistant discovery</dt><dd>power and source sensors, and a volume number in dB between <b>Minimum volume</b>
112
- and <b>Maximum volume</b>. It needs <b>Publish state</b>. A volume set there arrives on
164
+ <dt>Publish: MQTT state and Home Assistant discovery</dt><dd>power and source sensors, and a volume number in dB between <b>Minimum volume</b>
165
+ and <b>Maximum volume</b>. It includes the MQTT state, which they read. A volume set there arrives on
113
166
  <code>…/volume/set</code>; wire an MQTT in node on that topic into this node. Sets arriving within 0.3 seconds
114
167
  of each other (a slider, repeated taps) are settled to the last one, which becomes an ordinary absolute
115
168
  volume request, bounded and confirmed like any other: it waits for a power or source change in progress (such
@@ -117,8 +170,16 @@
117
170
  </dl>
118
171
  <p>These go on the third output; wire it to an MQTT out node. The node announces itself once the flows have
119
172
  started, and again at <code>kind: "startup"</code>.</p>
173
+ <h3>Broker</h3>
174
+ <p>Choose Node-RED's <b>MQTT broker</b> node, and it publishes and reads its set topic itself: it announces everything each time the
175
+ broker connects, reconnects included, and each time Home Assistant comes back (<code>online</code> on
176
+ <code>&lt;prefix&gt;/status</code>), so its entities come back by themselves.
177
+ Each connect also runs its startup message, as a Status node's "connected" did without a broker. Its publication output then sends
178
+ nothing, and an MQTT out on it, an MQTT in on its set topic and a Status node are no longer needed: still wired, they change nothing.
179
+ Opening and saving the node offers the first broker in your flows. A node saved before 6.2 that publishes keeps
180
+ publishing on its output, as below, and needs no broker until you choose one.</p>
120
181
  <h3>When MQTT out connects</h3>
121
- <p>Wire a <b>Status node</b> whose scope is your MQTT out node into this node. Each time MQTT out shows
182
+ <p>Without a broker, wire a <b>Status node</b> whose scope is your MQTT out node into this node. Each time MQTT out shows
122
183
  "connected", this node takes it as its startup message (<code>msg.avr = {kind: "startup"}</code>) and announces itself again:
123
184
  Node-RED's MQTT broker node drops what it is given before it connects, so what the node sends as the flows
124
185
  start is lost on a first start, a full deploy or a restart. Any other status message is ignored.</p>
@@ -6,7 +6,8 @@ const avr_publishing_1 = require("../lib/avr-publishing");
6
6
  const ha_discovery_1 = require("../lib/ha-discovery");
7
7
  const topic_names_1 = require("../lib/topic-names");
8
8
  const publishing_node_1 = require("../lib/publishing-node");
9
- const publishing_lifecycle_1 = require("./publishing-lifecycle");
9
+ const publishing_side_1 = require("./publishing-side");
10
+ const home_assistant_setting_1 = require("../lib/home-assistant-setting");
10
11
  function parseSources(value) {
11
12
  const sources = (0, settings_1.jsonSetting)(value, "sources", {});
12
13
  if (!sources || Array.isArray(sources) || typeof sources !== "object") {
@@ -22,6 +23,7 @@ const registerAvrController = (RED) => {
22
23
  let retryTimer;
23
24
  let controllerConfig;
24
25
  let publishing;
26
+ let broker;
25
27
  try {
26
28
  // The same validation the reducer applies, so a bad configuration
27
29
  // fails here at deploy rather than on every message.
@@ -29,14 +31,14 @@ const registerAvrController = (RED) => {
29
31
  // Off unless switched on, as the receiver published nothing before;
30
32
  // there are no older entities to keep, so not set names them after
31
33
  // 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)
34
+ const publish = (0, home_assistant_setting_1.publishingChoice)(config, { publishState: false, discovery: false });
35
+ if (publish.needsArea)
35
36
  (0, topic_names_1.publishingArea)(controllerConfig.area, true);
37
+ broker = (0, publishing_side_1.brokerSetting)(RED, config.broker, publish.publishState);
36
38
  publishing = {
37
39
  area: controllerConfig.area,
38
- publishState,
39
- discovery,
40
+ publishState: publish.publishState,
41
+ discovery: publish.discovery,
40
42
  discoveryPrefix: (0, ha_discovery_1.discoveryPrefixSetting)(config.discoveryPrefix),
41
43
  nodeId: node.id,
42
44
  idScheme: (0, settings_1.optionalChoiceSetting)(config.idScheme, "ID scheme", ha_discovery_1.ID_SCHEMES) ?? "node",
@@ -79,14 +81,18 @@ const registerAvrController = (RED) => {
79
81
  // commands and the theatre's events. Available, and clear of what it no
80
82
  // longer publishes, as soon as it runs; offline as it stops; nothing
81
83
  // left behind when deleted.
82
- const lifecycle = (0, publishing_lifecycle_1.publishingLifecycle)(RED, node, {
84
+ const trace = { area: controllerConfig.area, component: "avr-controller" };
85
+ const lifecycle = (0, publishing_side_1.publishingSide)(RED, node, broker, {
83
86
  retainedTopics: () => (0, avr_publishing_1.avrRetainedTopics)(publishing),
84
87
  possible: { owner: publishing, topics: () => (0, publishing_node_1.publishesState)(publishing) ? (0, avr_publishing_1.avrRetainedTopics)({ ...publishing, publishState: true, discovery: true }) : [] },
85
88
  starting: () => (0, avr_publishing_1.avrStartingOutputs)(publishing, observed()),
86
89
  stopping: () => (0, avr_publishing_1.avrStoppingOutputs)(publishing),
87
90
  output: 2,
88
- outputs: 3
89
- });
91
+ outputs: 3,
92
+ startupMessage: { avr: { kind: "startup" } },
93
+ statusTopic: publishing.discovery ? publishing.discoveryPrefix + "/status" : null,
94
+ setTopics: (0, publishing_node_1.publishesState)(publishing) ? [(0, avr_publishing_1.receiverTopic)(publishing.area, "volume/set")] : []
95
+ }, trace, (msg, send) => handle(msg, send));
90
96
  let warnedRemovedVolume = false;
91
97
  function process(msg, send) {
92
98
  const before = observed();
@@ -137,7 +143,7 @@ const registerAvrController = (RED) => {
137
143
  volumeRequests += 1;
138
144
  process({ avr: { kind: "volume", requestId: `mqtt-volume-${Date.now()}-${volumeRequests}`, mode: "absolute", valueDb } }, node.send.bind(node));
139
145
  }
140
- (0, adapter_1.onInput)(node, (msg, send) => {
146
+ function handle(msg, send) {
141
147
  const volume = (0, avr_publishing_1.avrVolumeRequest)(msg, publishing);
142
148
  if (volume && "ignored" in volume) {
143
149
  (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 } }] }));
@@ -158,7 +164,13 @@ const registerAvrController = (RED) => {
158
164
  avr: (0, adapter_1.objectField)(msg, "avr"),
159
165
  payload: msg.payload
160
166
  }, send);
161
- }, { message: { avr: { kind: "startup" } }, trace: { area: controllerConfig.area, component: "avr-controller" } });
167
+ }
168
+ (0, adapter_1.onInput)(node, (msg, send) => {
169
+ // With a broker, its set topic comes from the broker: an MQTT in or a
170
+ // Status node still wired in changes nothing.
171
+ if (!lifecycle.fromBroker(msg))
172
+ handle(msg, send);
173
+ }, lifecycle.startupOption({ avr: { kind: "startup" } }));
162
174
  node.on("close", (_removed, done) => {
163
175
  clearTimeout(retryTimer);
164
176
  clearTimeout(volumeSetTimer);
@@ -1,6 +1,31 @@
1
1
  <script type="text/javascript">
2
2
  (function () {
3
3
  function clockTime(v) { return /^([01]\d|2[0-3]):[0-5]\d$/.test(String(v || "")); }
4
+ // Its Publish choice (off, state or discovery), from the open dialog or
5
+ // its saved settings: a node saved before the choice reads its two old
6
+ // settings (lib/home-assistant-setting.ts).
7
+ function publishChoice(node) {
8
+ function on(value) { return value === true || value === "true"; }
9
+ var select = $("#node-input-homeAssistant");
10
+ if (select.length) return select.val();
11
+ if (node.homeAssistant === "off" || node.homeAssistant === "state" || node.homeAssistant === "discovery") return node.homeAssistant;
12
+ return !on(node.publishState) ? "off" : on(node.discovery) ? "discovery" : "state";
13
+ }
14
+ // Whether it publishes through its output, as before 6.2: a node saved
15
+ // before the Publish choice that published, or one opened and saved since
16
+ // without a broker (publishesThroughOutput). It needs no broker until one
17
+ // is chosen; from saved values only, not the open dialog.
18
+ function throughOutput(node) {
19
+ if (node.publishesThroughOutput === true) return true;
20
+ return (node.homeAssistant === null || node.homeAssistant === undefined) && (node.publishState === true || node.publishState === "true");
21
+ }
22
+ // Its area is needed while it publishes, and for a node saved before the
23
+ // choice whenever either old setting was on, as the runtime checks.
24
+ function needsArea(node) {
25
+ function on(value) { return value === true || value === "true"; }
26
+ var saved = !$("#node-input-homeAssistant").length && (node.homeAssistant === null || node.homeAssistant === undefined);
27
+ return publishChoice(node) !== "off" || (saved && (on(node.publishState) || on(node.discovery)));
28
+ }
4
29
  RED.nodes.registerType("home-circadian-lighting-policy", {
5
30
  category: "home automation",
6
31
  color: "#ffd27f",
@@ -8,12 +33,7 @@
8
33
  name: {value: ""},
9
34
  // Required only when the node publishes, and then with a letter or
10
35
  // digit, from which its topics are made.
11
- area: {value: "", validate: function (v) {
12
- var publishing = $("#node-input-publishState").length
13
- ? $("#node-input-publishState").prop("checked") || $("#node-input-discovery").prop("checked")
14
- : this.publishState === true || this.discovery === true;
15
- return !publishing || /[a-z0-9]/i.test(String(v || ""));
16
- }},
36
+ area: {value: "", validate: function (v) { return !needsArea(this) || /[a-z0-9]/i.test(String(v || "")); }},
17
37
  // The house schedule it follows; none: its own wake and bed times.
18
38
  houseSchedule: {value: "", type: "home-house-schedule", required: false},
19
39
  wakeTime: {value: "07:00", validate: function (v) { return Boolean(this.houseSchedule) || clockTime(v); }},
@@ -25,22 +45,46 @@
25
45
  refreshTransitionSeconds: {value: 60, required: true, validate: RED.validators.number()},
26
46
  refreshSeconds: {value: 60, required: true, validate: function (v) { return RED.validators.number()(v) && Number(v) >= 10; }},
27
47
  initialSleep: {value: false},
48
+ // Publish: off, state or discovery. null means "not set": a node saved
49
+ // before this setting, read from the two below, kept with no rows.
50
+ homeAssistant: {value: null},
51
+ // Node-RED's MQTT broker node, through which it publishes and reads its set
52
+ // topics itself. Needed unless Publish is "Don't publish". The editor offers
53
+ // the first broker when the dialog is opened and saved, not when the node
54
+ // is dropped.
55
+ broker: {value: "", type: "mqtt-broker", required: false, validate: function (v) {
56
+ return publishChoice(this) === "off" || (Boolean(v) && v !== "_ADD_") || throughOutput(this) ? true : "choose a broker, or set Publish to Don't publish";
57
+ }},
28
58
  publishState: {value: false},
29
59
  discovery: {value: false},
60
+ // true for a node that publishes through its output, as before 6.2, and
61
+ // was opened and saved without a broker: it stays valid until a broker is
62
+ // chosen. No form row.
63
+ publishesThroughOutput: {value: false},
30
64
  discoveryPrefix: {value: "homeassistant", required: true, validate: function (v) { var prefix = String(v || "").trim().replace(/^\/+|\/+$/g, ""); return Boolean(prefix) && !/[+#]/.test(prefix); }},
31
65
  // A new node, so its Home Assistant entities are named after it.
32
66
  idScheme: {value: "node"}
33
67
  },
68
+ oneditsave: function () {
69
+ // Through its output until a broker is chosen (read before the
70
+ // dialog's values are applied).
71
+ var broker = $("#node-input-broker").val();
72
+ this.publishesThroughOutput = throughOutput(this) && (!broker || broker === "_ADD_");
73
+ },
34
74
  oneditprepare: function () {
35
- // Discovery describes the published state, so it needs it.
36
- function follow() {
37
- var publishing = $("#node-input-publishState").prop("checked");
38
- if (!publishing) $("#node-input-discovery").prop("checked", false);
39
- $("#node-input-discovery").prop("disabled", !publishing);
40
- $("#node-input-area").trigger("change");
75
+ $("#node-input-homeAssistant").val(publishChoice(this));
76
+ // The broker only while it publishes, the prefix only with discovery.
77
+ var outputBefore = throughOutput(this);
78
+ function publishRows() {
79
+ var broker = $("#node-input-broker").val();
80
+ $(".publish-through-output").toggle($("#node-input-homeAssistant").val() !== "off" && outputBefore && (!broker || broker === "_ADD_"));
81
+ var choice = $("#node-input-homeAssistant").val();
82
+ $(".publish-broker").toggle(choice !== "off");
83
+ $(".publish-discovery").toggle(choice === "discovery");
84
+ $("#node-input-area, #node-input-broker").trigger("change");
41
85
  }
42
- $("#node-input-publishState, #node-input-discovery").on("change", follow);
43
- follow();
86
+ $("#node-input-homeAssistant, #node-input-broker").on("change", publishRows);
87
+ publishRows();
44
88
  // Following a house, the times are the house's.
45
89
  function times() {
46
90
  var own = !$("#node-input-houseSchedule").val() || $("#node-input-houseSchedule").val() === "_ADD_";
@@ -71,9 +115,20 @@
71
115
  <div class="form-row"><label for="node-input-refreshSeconds">Restyle interval (s)</label><input type="number" min="10" id="node-input-refreshSeconds"></div>
72
116
  <div class="form-row"><label for="node-input-initialSleep">Start in sleep mode</label><input type="checkbox" id="node-input-initialSleep" style="display:inline-block; width:auto;"></div>
73
117
  <div class="form-row"><label for="node-input-area">Area</label><input type="text" id="node-input-area" placeholder="needed when publishing"></div>
74
- <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>
75
- <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>
76
- <div class="form-row"><label for="node-input-discoveryPrefix">Discovery prefix</label><input type="text" id="node-input-discoveryPrefix"></div>
118
+ <div class="form-row">
119
+ <label for="node-input-homeAssistant">Publish</label>
120
+ <select id="node-input-homeAssistant">
121
+ <option value="off">Don't publish</option>
122
+ <option value="state">MQTT state</option>
123
+ <option value="discovery">MQTT state and Home Assistant discovery</option>
124
+ </select>
125
+ </div>
126
+ <div class="form-row publish-broker"><label for="node-input-broker">Broker</label><input type="text" id="node-input-broker"></div>
127
+ <div class="form-tips publish-broker">With a broker, it publishes and reads its set topics itself: an MQTT out on its
128
+ publication output, an MQTT in on its set topics, and a Status node are no longer needed and can be deleted.</div>
129
+ <div class="form-tips publish-through-output">This node publishes through its output, as before 6.2, and keeps
130
+ working that way. Choose a Broker to let it publish itself.</div>
131
+ <div class="form-row publish-discovery"><label for="node-input-discoveryPrefix">Discovery prefix</label><input type="text" id="node-input-discoveryPrefix"></div>
77
132
  </script>
78
133
 
79
134
  <script type="text/html" data-help-name="home-circadian-lighting-policy">
@@ -107,7 +162,7 @@
107
162
  the flows start, as the examples do.</dd>
108
163
  <dt>topic = home/&lt;area&gt;/circadian/set, home/&lt;area&gt;/sleep/set</dt>
109
164
  <dd><code>ON</code> or <code>OFF</code> from Home Assistant, as <code>lighting.kind = "circadian"</code> or
110
- <code>"sleep"</code> does. Read only while <b>Publish state</b> is on. Retained messages and other payloads are
165
+ <code>"sleep"</code> does. Read only while it publishes. Retained messages and other payloads are
111
166
  ignored.</dd>
112
167
  <dt>topic = home/&lt;area&gt;/wake-time/set or bed-time/set</dt>
113
168
  <dd>A time from Home Assistant, with its own times only.</dd>
@@ -130,15 +185,24 @@
130
185
  <dt>Restyle transition</dt><dd>How long a room takes to move a light that is on to a new style. A light turning
131
186
  on uses the room's own transition.</dd>
132
187
  <dt>Restyle interval</dt><dd>How often it sends its style, at least 10 seconds.</dd>
133
- <dt>Publish state over MQTT, Home Assistant discovery</dt><dd>Off unless switched on. With both on, Home Assistant
188
+ <dt>Publish</dt><dd><i>Don't publish</i> unless chosen. <i>MQTT state</i> publishes its state and reads its set
189
+ topics, plain MQTT; with <i>MQTT state and Home Assistant discovery</i>, Home Assistant
134
190
  shows Circadian lighting and Sleep switches and, with its own times, Wake time and Bed time, named after this
135
191
  node. The topics keep the names the room controller used before 6.0, so a flow already writing
136
192
  <code>home/&lt;area&gt;/circadian/set</code> keeps working when this node has that area. Before announcing, it
137
193
  clears the circadian entities older room controllers in its area published, migrated or not, in the same batch,
138
194
  so Home Assistant can give the new ones the same entity IDs.</dd>
139
195
  </dl>
196
+ <h3>Broker</h3>
197
+ <p>Choose Node-RED's <b>MQTT broker</b> node, and it publishes and reads its set topics itself: it announces everything each time the
198
+ broker connects, reconnects included, and each time Home Assistant comes back (<code>online</code> on
199
+ <code>&lt;prefix&gt;/status</code>), so its entities come back by themselves.
200
+ Each connect also runs its startup message, as a Status node's "connected" did without a broker. Its publication output then sends
201
+ nothing, and an MQTT out on it, an MQTT in on its set topics and a Status node are no longer needed: still wired, they change nothing.
202
+ Opening and saving the node offers the first broker in your flows. A node saved before 6.2 that publishes keeps
203
+ publishing on its output, as below, and needs no broker until you choose one.</p>
140
204
  <h3>When MQTT out connects</h3>
141
- <p>Wire a <b>Status node</b> whose scope is your MQTT out node into this node. Each time MQTT out shows
205
+ <p>Without a broker, wire a <b>Status node</b> whose scope is your MQTT out node into this node. Each time MQTT out shows
142
206
  "connected", this node takes it as its startup message (<code>msg.lighting = {kind: "startup"}</code>) and announces itself again:
143
207
  Node-RED's MQTT broker node drops what it is given before it connects, so what the node sends as the flows
144
208
  start is lost on a first start, a full deploy or a restart. Any other status message is ignored.</p>