@avantics/node-red-home-automation 6.0.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 (75) hide show
  1. package/README.md +276 -48
  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 +4 -0
  8. package/dist/lib/room-controller.js +122 -14
  9. package/dist/lib/room-holds.d.ts +34 -0
  10. package/dist/lib/room-holds.js +66 -0
  11. package/dist/lib/room-publishing.d.ts +1 -0
  12. package/dist/lib/room-publishing.js +11 -0
  13. package/dist/lib/scene-publishing.d.ts +30 -0
  14. package/dist/lib/scene-publishing.js +63 -0
  15. package/dist/lib/scene.d.ts +61 -0
  16. package/dist/lib/scene.js +170 -0
  17. package/dist/lib/shelly-cover.js +5 -0
  18. package/dist/lib/shelly-relay-light.d.ts +24 -0
  19. package/dist/lib/shelly-relay-light.js +93 -0
  20. package/dist/lib/shelly-switch.d.ts +8 -0
  21. package/dist/lib/shelly-switch.js +37 -8
  22. package/dist/lib/theatre-activity-controller.js +4 -0
  23. package/dist/lib/theatre-metrics.js +6 -4
  24. package/dist/lib/theatre-slo.js +3 -0
  25. package/dist/lib/theatre-state-contract.d.ts +4 -2
  26. package/dist/lib/theatre-state-contract.js +51 -8
  27. package/dist/lib/theatre-state.js +3 -0
  28. package/dist/nodes/activity-lighting-controller.html +1 -1
  29. package/dist/nodes/adapter.d.ts +5 -1
  30. package/dist/nodes/adapter.js +35 -2
  31. package/dist/nodes/avr-controller.html +86 -20
  32. package/dist/nodes/avr-controller.js +23 -11
  33. package/dist/nodes/circadian-policy.html +88 -19
  34. package/dist/nodes/circadian-policy.js +30 -11
  35. package/dist/nodes/cover-controller.html +91 -24
  36. package/dist/nodes/cover-controller.js +25 -12
  37. package/dist/nodes/device-side.d.ts +20 -0
  38. package/dist/nodes/device-side.js +72 -0
  39. package/dist/nodes/home-assistant-discovery.d.ts +26 -0
  40. package/dist/nodes/home-assistant-discovery.js +64 -0
  41. package/dist/nodes/house-schedule-mqtt.html +74 -4
  42. package/dist/nodes/house-schedule-mqtt.js +22 -8
  43. package/dist/nodes/motion-policy.html +91 -21
  44. package/dist/nodes/motion-policy.js +44 -11
  45. package/dist/nodes/mqtt-broker-link.d.ts +41 -0
  46. package/dist/nodes/mqtt-broker-link.js +91 -0
  47. package/dist/nodes/occupancy-fusion.html +87 -19
  48. package/dist/nodes/occupancy-fusion.js +23 -11
  49. package/dist/nodes/publishing-side.d.ts +20 -0
  50. package/dist/nodes/publishing-side.js +66 -0
  51. package/dist/nodes/room-controller.html +128 -43
  52. package/dist/nodes/room-controller.js +63 -16
  53. package/dist/nodes/scene.d.ts +3 -0
  54. package/dist/nodes/scene.html +226 -0
  55. package/dist/nodes/scene.js +121 -0
  56. package/dist/nodes/shelly-cover.html +46 -2
  57. package/dist/nodes/shelly-cover.js +19 -4
  58. package/dist/nodes/shelly-switch.html +80 -6
  59. package/dist/nodes/shelly-switch.js +32 -7
  60. package/dist/nodes/theatre-state-contract.html +76 -8
  61. package/dist/nodes/theatre-state-contract.js +33 -14
  62. package/dist/nodes/z2m-cover.html +46 -2
  63. package/dist/nodes/z2m-cover.js +21 -4
  64. package/dist/nodes/z2m-light.html +50 -2
  65. package/dist/nodes/z2m-light.js +26 -6
  66. package/examples/Cover control.json +38 -102
  67. package/examples/Cover pair.json +36 -3
  68. package/examples/Home theatre activity.json +46 -102
  69. package/examples/Home theatre equipment.json +34 -2
  70. package/examples/House schedule.json +58 -80
  71. package/examples/Room lighting.json +45 -55
  72. package/examples/Scene.json +215 -0
  73. package/examples/Shelly cover.json +36 -116
  74. package/examples/Shelly switch.json +52 -148
  75. package/package.json +2 -1
@@ -4,7 +4,11 @@ import { type RetainedClear } from "../lib/retained-topics";
4
4
  export type Send = (msg: NodeMessage | Array<NodeMessage | NodeMessage[] | null>) => void;
5
5
  export type InputMessage = NodeMessage & Record<string, unknown>;
6
6
  export declare function objectField<T>(msg: InputMessage, key: string): T | undefined;
7
- export declare function onInput(node: Node, handle: (msg: InputMessage, send: Send) => void): void;
7
+ export declare function mqttConnected(msg: InputMessage): boolean;
8
+ export declare function onInput(node: Node, handle: (msg: InputMessage, send: Send) => void, startup?: {
9
+ message: Record<string, unknown>;
10
+ trace: TraceMetadata;
11
+ }): void;
8
12
  export declare function guarded(node: Node, work: () => void): () => void;
9
13
  export declare function runReducer<Saved, Result extends {
10
14
  state: unknown;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.objectField = objectField;
4
+ exports.mqttConnected = mqttConnected;
4
5
  exports.onInput = onInput;
5
6
  exports.guarded = guarded;
6
7
  exports.runReducer = runReducer;
@@ -18,11 +19,43 @@ function objectField(msg, key) {
18
19
  const value = msg[key];
19
20
  return value && typeof value === "object" ? value : undefined;
20
21
  }
22
+ // The status an MQTT out node shows each time its broker connects, as
23
+ // Node-RED's Status node passes it on (Node-RED 5.0.10:
24
+ // nodes/core/network/10-mqtt.js, setStatusConnected; runtime/lib/flows/Flow.js,
25
+ // handleStatus, which adds status.source).
26
+ const MQTT_CONNECTED = "node-red:common.status.connected";
27
+ // A Status node's message: msg.status with the node it came from as
28
+ // status.source.
29
+ function fromStatusNode(msg) {
30
+ const status = objectField(msg, "status");
31
+ return Boolean(status?.source && typeof status.source === "object");
32
+ }
33
+ // Whether a message is a Status node's report that an MQTT out node has
34
+ // connected: until then, the broker drops what it is given to publish.
35
+ function mqttConnected(msg) {
36
+ const status = objectField(msg, "status");
37
+ return fromStatusNode(msg) && status?.text === MQTT_CONNECTED && status.source?.type === "mqtt out";
38
+ }
21
39
  // Handle each input; an error is reported against the message and ends it.
22
- function onInput(node, handle) {
40
+ // With a startup message, a node that announces itself takes a Status
41
+ // node's "MQTT out connected" as that startup message, so it announces again
42
+ // once the broker can take it; any other Status node message is ignored, and
43
+ // traced. Any other message is handled as it is.
44
+ function onInput(node, handle, startup) {
23
45
  node.on("input", (msg, send, done) => {
24
46
  try {
25
- handle(msg, send);
47
+ const input = msg;
48
+ if (startup && mqttConnected(input)) {
49
+ handle(structuredClone(startup.message), send);
50
+ }
51
+ else if (startup && fromStatusNode(input)) {
52
+ const status = input.status;
53
+ (0, bounded_trace_1.appendTrace)(node.context(), startup.trace, [{ event: "input", outcome: "ignored", reason: "status-message",
54
+ details: { text: status.text, source: status.source.type } }]);
55
+ }
56
+ else {
57
+ handle(input, send);
58
+ }
26
59
  done();
27
60
  }
28
61
  catch (error) {
@@ -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,4 +170,17 @@
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>
181
+ <h3>When MQTT out connects</h3>
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
183
+ "connected", this node takes it as its startup message (<code>msg.avr = {kind: "startup"}</code>) and announces itself again:
184
+ Node-RED's MQTT broker node drops what it is given before it connects, so what the node sends as the flows
185
+ start is lost on a first start, a full deploy or a restart. Any other status message is ignored.</p>
120
186
  </script>
@@ -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
- });
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,11 +185,25 @@
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>
204
+ <h3>When MQTT out connects</h3>
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
206
+ "connected", this node takes it as its startup message (<code>msg.lighting = {kind: "startup"}</code>) and announces itself again:
207
+ Node-RED's MQTT broker node drops what it is given before it connects, so what the node sends as the flows
208
+ start is lost on a first start, a full deploy or a restart. Any other status message is ignored.</p>
140
209
  </script>
@@ -8,7 +8,8 @@ const publishing_node_1 = require("../lib/publishing-node");
8
8
  const settings_1 = require("../lib/settings");
9
9
  const topic_names_1 = require("../lib/topic-names");
10
10
  const adapter_1 = require("./adapter");
11
- const publishing_lifecycle_1 = require("./publishing-lifecycle");
11
+ const publishing_side_1 = require("./publishing-side");
12
+ const home_assistant_setting_1 = require("../lib/home-assistant-setting");
12
13
  const refused_enable_1 = require("./refused-enable");
13
14
  const shared_schedule_1 = require("./shared-schedule");
14
15
  const registerCircadianPolicy = (RED) => {
@@ -22,6 +23,7 @@ const registerCircadianPolicy = (RED) => {
22
23
  const { schedule: house, missing: houseMissing } = (0, shared_schedule_1.referencedSchedule)(RED, config.houseSchedule);
23
24
  let policyConfig;
24
25
  let publishing;
26
+ let broker;
25
27
  try {
26
28
  const area = (0, adapter_1.optionalArea)(config);
27
29
  const levels = {
@@ -43,14 +45,14 @@ const registerCircadianPolicy = (RED) => {
43
45
  };
44
46
  // Off unless switched on; a new node, so its entities are named after
45
47
  // it.
46
- const publishState = (0, settings_1.optionalBooleanSetting)(config.publishState, "publish state") ?? false;
47
- const discovery = (0, settings_1.optionalBooleanSetting)(config.discovery, "Home Assistant discovery") ?? false;
48
- if (publishState || discovery)
48
+ const publish = (0, home_assistant_setting_1.publishingChoice)(config, { publishState: false, discovery: false });
49
+ if (publish.needsArea)
49
50
  (0, topic_names_1.publishingArea)(area, true);
51
+ broker = (0, publishing_side_1.brokerSetting)(RED, config.broker, publish.publishState);
50
52
  publishing = {
51
53
  area,
52
- publishState,
53
- discovery,
54
+ publishState: publish.publishState,
55
+ discovery: publish.discovery,
54
56
  discoveryPrefix: (0, ha_discovery_1.discoveryPrefixSetting)(config.discoveryPrefix),
55
57
  nodeId: node.id,
56
58
  // Always named after the node, so its entries never share a topic
@@ -81,14 +83,25 @@ const registerCircadianPolicy = (RED) => {
81
83
  }
82
84
  // Styles go to rooms on the first output; MQTT publications on the
83
85
  // second.
84
- const lifecycle = (0, publishing_lifecycle_1.publishingLifecycle)(RED, node, {
86
+ const trace = { area: publishing.area, component: "circadian-policy" };
87
+ const lifecycle = (0, publishing_side_1.publishingSide)(RED, node, broker, {
85
88
  retainedTopics: () => (0, circadian_publishing_1.circadianRetainedTopics)(publishing),
86
89
  possible: { owner: publishing, topics: () => (0, publishing_node_1.publishesState)(publishing) ? (0, circadian_publishing_1.circadianRetainedTopics)({ ...publishing, publishState: true, discovery: true }) : [] },
87
90
  starting: () => (0, circadian_publishing_1.circadianStartingOutputs)(publishing, savedState(), roomsInArea()),
88
91
  stopping: () => (0, circadian_publishing_1.circadianStoppingOutputs)(publishing),
89
92
  output: 1,
90
- outputs: 2
91
- });
93
+ outputs: 2,
94
+ startupMessage: { lighting: { kind: "startup" } },
95
+ statusTopic: publishing.discovery ? publishing.discoveryPrefix + "/status" : null,
96
+ // Following a house, the wake and bed times are the house's to set.
97
+ setTopics: (0, publishing_node_1.publishesState)(publishing) ? [
98
+ (0, circadian_publishing_1.circadianSwitchTopic)(publishing.area, "circadian", "set"),
99
+ (0, circadian_publishing_1.circadianSwitchTopic)(publishing.area, "sleep", "set"),
100
+ ...(publishing.timesFrom !== "house"
101
+ ? [(0, circadian_publishing_1.circadianTimeTopic)(publishing.area, "wake-time", "set"), (0, circadian_publishing_1.circadianTimeTopic)(publishing.area, "bed-time", "set")]
102
+ : [])
103
+ ] : []
104
+ }, trace, (msg, send) => handle(msg, send));
92
105
  function updateStatus(status) {
93
106
  const values = status.values;
94
107
  node.status(values
@@ -127,7 +140,7 @@ const registerCircadianPolicy = (RED) => {
127
140
  process({ kind: "schedule", ...house.schedule() }, node.send.bind(node));
128
141
  })));
129
142
  }
130
- (0, adapter_1.onInput)(node, (msg, send) => {
143
+ function handle(msg, send) {
131
144
  const lighting = (0, adapter_1.objectField)(msg, "lighting");
132
145
  if (lighting?.kind === "startup") {
133
146
  lifecycle.startup(send, (0, circadian_publishing_1.circadianStartingOutputs)(publishing, savedState(), roomsInArea()));
@@ -143,7 +156,13 @@ const registerCircadianPolicy = (RED) => {
143
156
  else {
144
157
  process(lighting ?? { kind: undefined }, send);
145
158
  }
146
- });
159
+ }
160
+ (0, adapter_1.onInput)(node, (msg, send) => {
161
+ // With a broker, its set topics come from the broker: an MQTT in or a
162
+ // Status node still wired in changes nothing.
163
+ if (!lifecycle.fromBroker(msg))
164
+ handle(msg, send);
165
+ }, lifecycle.startupOption({ lighting: { kind: "startup" } }));
147
166
  tickTimer = setInterval((0, adapter_1.guarded)(node, () => process({ kind: "tick" }, node.send.bind(node))), policyConfig.intervalSeconds * 1000);
148
167
  // Deleted: rooms stop styling at once rather than when the last style
149
168
  // runs out.