@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
@@ -1,6 +1,23 @@
1
1
  <script type="text/javascript">
2
2
  (function () {
3
3
  function on(value) { return value === true || value === "true"; }
4
+ // Its Publish choice: it always publishes state, so state or discovery,
5
+ // from the open dialog or its saved settings; a node saved before the
6
+ // choice reads its old discovery setting.
7
+ function publishChoice(node) {
8
+ var select = $("#node-input-homeAssistant");
9
+ if (select.length) return select.val();
10
+ if (node.homeAssistant === "state" || node.homeAssistant === "discovery") return node.homeAssistant;
11
+ return on(node.discovery) ? "discovery" : "state";
12
+ }
13
+ // Whether it publishes through its output, as before 6.2: a node saved
14
+ // before the Publish choice that published, or one opened and saved since
15
+ // without a broker (publishesThroughOutput). It needs no broker until one
16
+ // is chosen; from saved values only, not the open dialog.
17
+ function throughOutput(node) {
18
+ if (node.publishesThroughOutput === true) return true;
19
+ return node.homeAssistant === null || node.homeAssistant === undefined;
20
+ }
4
21
  RED.nodes.registerType("home-house-schedule-mqtt", {
5
22
  category: "home automation",
6
23
  color: "#ffd27f",
@@ -9,7 +26,21 @@
9
26
  // and paste keep the saved name, so onadd leaves a saved node's settings.
10
27
  name: {value: "_DEFAULT_"},
11
28
  schedule: {value: "", type: "home-house-schedule", required: true},
29
+ // Publish: state or discovery. null means "not set": a node saved
30
+ // before this setting, read from discovery, kept with no row.
31
+ homeAssistant: {value: null},
32
+ // Node-RED's MQTT broker node, through which it publishes and reads its
33
+ // set topics itself. It always publishes, so it needs one. The editor offers
34
+ // the first broker when the dialog is opened and saved, not when the
35
+ // node is dropped.
36
+ broker: {value: "", type: "mqtt-broker", required: false, validate: function (v) {
37
+ return Boolean(v) && v !== "_ADD_" || throughOutput(this) ? true : "choose a broker";
38
+ }},
12
39
  discovery: {value: true},
40
+ // true for a node that publishes through its output, as before 6.2, and
41
+ // was opened and saved without a broker: it stays valid until a broker is
42
+ // chosen. No form row.
43
+ publishesThroughOutput: {value: false},
13
44
  discoveryPrefix: {value: "homeassistant", required: true, validate: function (v) { var prefix = String(v || "").trim().replace(/^\/+|\/+$/g, ""); return Boolean(prefix) && !/[+#]/.test(prefix); }},
14
45
  // How Home Assistant IDs are named; this node has no older entities,
15
46
  // so not set also means "node".
@@ -19,9 +50,24 @@
19
50
  if (this.name !== "_DEFAULT_") return;
20
51
  this.name = "";
21
52
  this.idScheme = "node";
53
+ // A new node always publishes, through its broker: discovery, as the
54
+ // default above.
55
+ this.homeAssistant = "discovery";
56
+ },
57
+ oneditsave: function () {
58
+ // Through its output until a broker is chosen (read before the
59
+ // dialog's values are applied).
60
+ var broker = $("#node-input-broker").val();
61
+ this.publishesThroughOutput = throughOutput(this) && (!broker || broker === "_ADD_");
22
62
  },
23
63
  oneditprepare: function () {
24
- $("#node-input-discovery").prop("checked", on(this.discovery));
64
+ $("#node-input-homeAssistant").val(publishChoice(this));
65
+ var outputBefore = throughOutput(this);
66
+ function publishRows() {
67
+ var broker = $("#node-input-broker").val();
68
+ $(".publish-through-output").toggle($("#node-input-homeAssistant").val() !== "off" && outputBefore && (!broker || broker === "_ADD_")); $(".publish-discovery").toggle($("#node-input-homeAssistant").val() === "discovery"); }
69
+ $("#node-input-homeAssistant, #node-input-broker").on("change", publishRows);
70
+ publishRows();
25
71
  },
26
72
  inputs: 1,
27
73
  outputs: 1,
@@ -35,15 +81,26 @@
35
81
  <script type="text/html" data-template-name="home-house-schedule-mqtt">
36
82
  <div class="form-row"><label for="node-input-name">Name</label><input type="text" id="node-input-name"></div>
37
83
  <div class="form-row"><label for="node-input-schedule">Schedule</label><input type="text" id="node-input-schedule"></div>
38
- <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;"></div>
39
- <div class="form-row"><label for="node-input-discoveryPrefix">Discovery prefix</label><input type="text" id="node-input-discoveryPrefix"></div>
84
+ <div class="form-row">
85
+ <label for="node-input-homeAssistant">Publish</label>
86
+ <select id="node-input-homeAssistant">
87
+ <option value="state">MQTT state</option>
88
+ <option value="discovery">MQTT state and Home Assistant discovery</option>
89
+ </select>
90
+ </div>
91
+ <div class="form-row"><label for="node-input-broker">Broker</label><input type="text" id="node-input-broker"></div>
92
+ <div class="form-tips">With a broker, it publishes and reads its set topics itself: an MQTT out on its publication output, an
93
+ MQTT in on its set topics, and a Status node are no longer needed and can be deleted.</div>
94
+ <div class="form-tips publish-through-output">This node publishes through its output, as before 6.2, and keeps
95
+ working that way. Choose a Broker to let it publish itself.</div>
96
+ <div class="form-row publish-discovery"><label for="node-input-discoveryPrefix">Discovery prefix</label><input type="text" id="node-input-discoveryPrefix"></div>
40
97
  </script>
41
98
 
42
99
  <script type="text/html" data-help-name="home-house-schedule-mqtt">
43
100
  <p>A house schedule's MQTT and Home Assistant side. Optional: rooms follow the schedule without it.</p>
44
101
  <p>It publishes the schedule's times, retained, on <code>home/&lt;name&gt;/schedule/wake-time/state</code> and
45
102
  <code>bed-time/state</code>, with availability on <code>home/&lt;name&gt;/schedule/availability</code>; with
46
- <b>Home Assistant discovery</b>, wake and bed time entities, named after the schedule so a replacement node keeps
103
+ <b>Publish</b> set to <i>MQTT state and Home Assistant discovery</i>, wake and bed time entities, named after the schedule so a replacement node keeps
47
104
  them. Use one per schedule: two would share the same topics and entities, and deleting one clears them for both
48
105
  until the other next starts. Wire its output to an MQTT out node, and an MQTT in node on the set topics to its input.</p>
49
106
  <h3>Inputs</h3>
@@ -58,8 +115,16 @@
58
115
  <ol class="node-ports">
59
116
  <li>MQTT publications.</li>
60
117
  </ol>
118
+ <h3>Broker</h3>
119
+ <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
120
+ broker connects, reconnects included, and each time Home Assistant comes back (<code>online</code> on
121
+ <code>&lt;prefix&gt;/status</code>), so its entities come back by themselves.
122
+ Each connect also runs its startup message, as a Status node's "connected" did without a broker. Its publication output then sends
123
+ 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.
124
+ Opening and saving the node offers the first broker in your flows. A node saved before 6.2 that publishes keeps
125
+ publishing on its output, as below, and needs no broker until you choose one.</p>
61
126
  <h3>When MQTT out connects</h3>
62
- <p>Wire a <b>Status node</b> whose scope is your MQTT out node into this node. Each time MQTT out shows
127
+ <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
63
128
  "connected", this node takes it as its startup message (<code>msg.source = "startup"</code>) and announces itself again:
64
129
  Node-RED's MQTT broker node drops what it is given before it connects, so what the node sends as the flows
65
130
  start is lost on a first start, a full deploy or a restart. Any other status message is ignored.</p>
@@ -4,7 +4,8 @@ const house_schedule_publishing_1 = require("../lib/house-schedule-publishing");
4
4
  const settings_1 = require("../lib/settings");
5
5
  const topic_names_1 = require("../lib/topic-names");
6
6
  const adapter_1 = require("./adapter");
7
- const publishing_lifecycle_1 = require("./publishing-lifecycle");
7
+ const publishing_side_1 = require("./publishing-side");
8
+ const home_assistant_setting_1 = require("../lib/home-assistant-setting");
8
9
  const shared_schedule_1 = require("./shared-schedule");
9
10
  const registerHouseScheduleMqtt = (RED) => {
10
11
  function HomeHouseScheduleMqtt(config) {
@@ -12,7 +13,9 @@ const registerHouseScheduleMqtt = (RED) => {
12
13
  const node = this;
13
14
  let house;
14
15
  let publishing;
16
+ let broker;
15
17
  try {
18
+ const choice = (0, settings_1.optionalChoiceSetting)(config.homeAssistant, "Publish", home_assistant_setting_1.HOME_ASSISTANT_CHOICES);
16
19
  const referenced = (0, shared_schedule_1.referencedSchedule)(RED, config.schedule);
17
20
  if (!referenced.schedule)
18
21
  throw new Error(referenced.missing ? "the house schedule is missing" : "no house schedule");
@@ -20,15 +23,17 @@ const registerHouseScheduleMqtt = (RED) => {
20
23
  publishing = {
21
24
  area: (0, topic_names_1.publishingArea)(house.name, true),
22
25
  // Publishing is what this node is for; discovery is off unless
23
- // switched on.
26
+ // switched on. Publish (MQTT state, or MQTT state and Home Assistant
27
+ // discovery) replaced the discovery setting; not set: from it.
24
28
  publishState: true,
25
- discovery: (0, settings_1.optionalBooleanSetting)(config.discovery, "Home Assistant discovery") ?? false,
29
+ discovery: choice ? choice === "discovery" : (0, settings_1.optionalBooleanSetting)(config.discovery, "Home Assistant discovery") ?? false,
26
30
  discoveryPrefix: (0, ha_discovery_1.discoveryPrefixSetting)(config.discoveryPrefix),
27
31
  // Named after the schedule, not this node, so a replacement node
28
32
  // keeps the same entities.
29
33
  nodeId: config.schedule,
30
34
  idScheme: (0, settings_1.optionalChoiceSetting)(config.idScheme, "ID scheme", ha_discovery_1.ID_SCHEMES) ?? "node"
31
35
  };
36
+ broker = (0, publishing_side_1.brokerSetting)(RED, config.broker, true);
32
37
  }
33
38
  catch (error) {
34
39
  (0, adapter_1.invalidConfig)(node, error);
@@ -39,7 +44,7 @@ const registerHouseScheduleMqtt = (RED) => {
39
44
  const { wakeTime, bedTime } = house.schedule();
40
45
  node.status({ fill: "green", shape: "dot", text: `wake ${wakeTime} · bed ${bedTime}` });
41
46
  }
42
- const lifecycle = (0, publishing_lifecycle_1.publishingLifecycle)(RED, node, {
47
+ const lifecycle = (0, publishing_side_1.publishingSide)(RED, node, broker, {
43
48
  retainedTopics: () => (0, house_schedule_publishing_1.houseRetainedTopics)(publishing),
44
49
  // Its own entities, named after the schedule, cleared when discovery is
45
50
  // switched off, with or without a record (see ownDiscoveryTopics).
@@ -47,15 +52,18 @@ const registerHouseScheduleMqtt = (RED) => {
47
52
  starting: () => (0, house_schedule_publishing_1.houseStartingOutputs)(publishing, house.schedule()),
48
53
  stopping: () => (0, house_schedule_publishing_1.houseStoppingOutputs)(publishing),
49
54
  output: 0,
50
- outputs: 1
51
- });
55
+ outputs: 1,
56
+ startupMessage: { lighting: { kind: "startup" } },
57
+ statusTopic: publishing.discovery ? publishing.discoveryPrefix + "/status" : null,
58
+ setTopics: [(0, house_schedule_publishing_1.houseCommandTopic)(publishing.area, "wake-time"), (0, house_schedule_publishing_1.houseCommandTopic)(publishing.area, "bed-time")]
59
+ }, trace, (msg, send) => handle(msg, send));
52
60
  const unsubscribe = house.subscribe((0, adapter_1.guarded)(node, () => {
53
61
  lifecycle.publish(node.send.bind(node), (0, house_schedule_publishing_1.houseStateOutputs)(publishing, house.schedule()));
54
62
  showTimes();
55
63
  }));
56
64
  node.on("close", unsubscribe);
57
65
  showTimes();
58
- (0, adapter_1.onInput)(node, (msg, send) => {
66
+ function handle(msg, send) {
59
67
  const lighting = (0, adapter_1.objectField)(msg, "lighting");
60
68
  if (lighting?.kind === "startup" || msg.source === "startup") {
61
69
  lifecycle.startup(send, (0, house_schedule_publishing_1.houseStartingOutputs)(publishing, house.schedule()));
@@ -72,7 +80,13 @@ const registerHouseScheduleMqtt = (RED) => {
72
80
  else if (inbound) {
73
81
  (0, adapter_1.runReducer)(node, trace, (state) => ({ state, traces: inbound.traces }));
74
82
  }
75
- }, { message: { lighting: { kind: "startup" } }, trace: trace });
83
+ }
84
+ (0, adapter_1.onInput)(node, (msg, send) => {
85
+ // With a broker, its set topics come from the broker: an MQTT in or a
86
+ // Status node still wired in changes nothing.
87
+ if (!lifecycle.fromBroker(msg))
88
+ handle(msg, send);
89
+ }, lifecycle.startupOption({ lighting: { kind: "startup" } }));
76
90
  }
77
91
  RED.nodes.registerType("home-house-schedule-mqtt", HomeHouseScheduleMqtt);
78
92
  };
@@ -1,6 +1,31 @@
1
1
  <script type="text/javascript">
2
2
  (function () {
3
3
  function on(value) { return value === true || value === "true"; }
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-motion-lighting-policy", {
5
30
  category: "home automation",
6
31
  color: "#d8bfd8",
@@ -10,10 +35,7 @@
10
35
  name: {value: "_DEFAULT_"},
11
36
  // Required only when the node publishes, and then with a letter or
12
37
  // 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
- }},
38
+ area: {value: "", validate: function (v) { return !needsArea(this) || /[a-z0-9]/i.test(String(v || "")); }},
17
39
  onTargets: {value: "[\"main\"]", required: true, validate: function (v) { try { JSON.parse(v); return true; } catch (e) { return false; } }},
18
40
  offTargets: {value: "[\"main\"]", required: true, validate: function (v) { try { JSON.parse(v); return true; } catch (e) { return false; } }},
19
41
  defaultDelaySeconds: {value: 120, required: true, validate: RED.validators.number()},
@@ -22,8 +44,22 @@
22
44
  // motion lighting for good.
23
45
  maxPauseSeconds: {value: 600, required: true, validate: function (v) { return RED.validators.number()(v) && Number(v) >= 1; }},
24
46
  // Motion published nothing before these settings, so both start off.
47
+ // Publish: off, state or discovery. null means "not set": a node saved
48
+ // before this setting, read from the two below, kept with no rows.
49
+ homeAssistant: {value: null},
50
+ // Node-RED's MQTT broker node, through which it publishes and reads its set
51
+ // topics itself. Needed unless Publish is "Don't publish". The editor offers
52
+ // the first broker when the dialog is opened and saved, not when the node
53
+ // is dropped.
54
+ broker: {value: "", type: "mqtt-broker", required: false, validate: function (v) {
55
+ return publishChoice(this) === "off" || (Boolean(v) && v !== "_ADD_") || throughOutput(this) ? true : "choose a broker, or set Publish to Don't publish";
56
+ }},
25
57
  publishState: {value: false},
26
58
  discovery: {value: false},
59
+ // true for a node that publishes through its output, as before 6.2, and
60
+ // was opened and saved without a broker: it stays valid until a broker is
61
+ // chosen. No form row.
62
+ publishesThroughOutput: {value: false},
27
63
  discoveryPrefix: {value: "homeassistant", required: true, validate: function (v) { var prefix = String(v || "").trim().replace(/^\/+|\/+$/g, ""); return Boolean(prefix) && !/[+#]/.test(prefix); }},
28
64
  // How Home Assistant IDs are named; motion has no older entities, so not
29
65
  // set also means "node".
@@ -34,18 +70,26 @@
34
70
  this.name = "";
35
71
  this.idScheme = "node";
36
72
  },
73
+ oneditsave: function () {
74
+ // Through its output until a broker is chosen (read before the
75
+ // dialog's values are applied).
76
+ var broker = $("#node-input-broker").val();
77
+ this.publishesThroughOutput = throughOutput(this) && (!broker || broker === "_ADD_");
78
+ },
37
79
  oneditprepare: function () {
38
- $("#node-input-publishState").prop("checked", on(this.publishState));
39
- $("#node-input-discovery").prop("checked", on(this.discovery));
40
- // Discovery describes the published state, so it needs it.
41
- function follow() {
42
- var publishing = $("#node-input-publishState").prop("checked");
43
- if (!publishing) $("#node-input-discovery").prop("checked", false);
44
- $("#node-input-discovery").prop("disabled", !publishing);
45
- $("#node-input-area").trigger("change");
80
+ $("#node-input-homeAssistant").val(publishChoice(this));
81
+ // The broker only while it publishes, the prefix only with discovery.
82
+ var outputBefore = throughOutput(this);
83
+ function publishRows() {
84
+ var broker = $("#node-input-broker").val();
85
+ $(".publish-through-output").toggle($("#node-input-homeAssistant").val() !== "off" && outputBefore && (!broker || broker === "_ADD_"));
86
+ var choice = $("#node-input-homeAssistant").val();
87
+ $(".publish-broker").toggle(choice !== "off");
88
+ $(".publish-discovery").toggle(choice === "discovery");
89
+ $("#node-input-area, #node-input-broker").trigger("change");
46
90
  }
47
- $("#node-input-publishState, #node-input-discovery").on("change", follow);
48
- follow();
91
+ $("#node-input-homeAssistant, #node-input-broker").on("change", publishRows);
92
+ publishRows();
49
93
  },
50
94
  inputs: 1,
51
95
  outputs: 2,
@@ -64,9 +108,20 @@
64
108
  <div class="form-row"><label for="node-input-defaultDelaySeconds">Vacancy seconds</label><input type="number" id="node-input-defaultDelaySeconds"></div>
65
109
  <div class="form-row"><label for="node-input-defaultIlluminanceCutoff">Lux cutoff</label><input type="number" id="node-input-defaultIlluminanceCutoff"></div>
66
110
  <div class="form-row"><label for="node-input-maxPauseSeconds">Maximum pause (s)</label><input type="number" id="node-input-maxPauseSeconds"></div>
67
- <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>
68
- <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>
69
- <div class="form-row"><label for="node-input-discoveryPrefix">Discovery prefix</label><input type="text" id="node-input-discoveryPrefix"></div>
111
+ <div class="form-row">
112
+ <label for="node-input-homeAssistant">Publish</label>
113
+ <select id="node-input-homeAssistant">
114
+ <option value="off">Don't publish</option>
115
+ <option value="state">MQTT state</option>
116
+ <option value="discovery">MQTT state and Home Assistant discovery</option>
117
+ </select>
118
+ </div>
119
+ <div class="form-row publish-broker"><label for="node-input-broker">Broker</label><input type="text" id="node-input-broker"></div>
120
+ <div class="form-tips publish-broker">With a broker, it publishes and reads its set topics itself: an MQTT out on its
121
+ publication output, an MQTT in on its set topics, and a Status node are no longer needed and can be deleted.</div>
122
+ <div class="form-tips publish-through-output">This node publishes through its output, as before 6.2, and keeps
123
+ working that way. Choose a Broker to let it publish itself.</div>
124
+ <div class="form-row publish-discovery"><label for="node-input-discoveryPrefix">Discovery prefix</label><input type="text" id="node-input-discoveryPrefix"></div>
70
125
  </script>
71
126
 
72
127
  <script type="text/html" data-help-name="home-motion-lighting-policy">
@@ -89,7 +144,9 @@
89
144
  <dt>pause</dt><dd><code>true</code> pauses motion lighting, <code>false</code> releases it, for the owner in
90
145
  <code>msg.owner</code> (for example a cover's name), which is required. A pause lasts at most the
91
146
  <b>Maximum pause</b> unless sent again, so a lost release can't stop motion lighting for good. Motion lighting acts only while no owner holds a pause,
92
- and a pause cancels a pending vacancy timer, as switching it off does. A pause never changes the enables,
147
+ and a pause cancels a pending vacancy timer, as switching it off does. A vacancy while paused or switched
148
+ off isn't forgotten: when motion resumes (every pause released or run out, and both enables on) in a room
149
+ still vacant, the vacancy timer starts then, and the off intent names when the room went vacant. A pause never changes the enables,
93
150
  which are the user's own: wire a cover's <i>moving</i> output here to pause motion while it moves. Any value but
94
151
  <code>true</code> or <code>false</code> is refused, as for the enables.</dd>
95
152
  </dl>
@@ -105,7 +162,7 @@
105
162
  <h3>Publishing</h3>
106
163
  <p>Off unless switched on, and then named after the <b>Area</b>, which is needed.</p>
107
164
  <dl class="message-properties">
108
- <dt>Publish state over MQTT</dt><dd>whether this node's motion lighting is enabled, retained <code>ON</code> or
165
+ <dt>Publish: MQTT state</dt><dd>whether this node's motion lighting is enabled, retained <code>ON</code> or
109
166
  <code>OFF</code> on <code>home/&lt;area&gt;/motion/enabled/state</code>, and its vacancy delay in seconds on
110
167
  <code>home/&lt;area&gt;/motion/delay/state</code>, with <code>online</code> or <code>offline</code> on
111
168
  <code>home/&lt;area&gt;/motion/availability</code>. It acts on <code>ON</code>/<code>OFF</code> sent to
@@ -114,8 +171,8 @@
114
171
  <code>home/&lt;area&gt;/motion/+/set</code> into this node. The shared <code>global-enabled</code> is not
115
172
  published, and the switch shows this node's enable only, so motion can still be off everywhere while it
116
173
  shows on.</dd>
117
- <dt>Home Assistant discovery</dt><dd>a motion lighting switch and a vacancy delay number (in the device's
118
- configuration). It needs <b>Publish state</b>.</dd>
174
+ <dt>Publish: MQTT state and Home Assistant discovery</dt><dd>a motion lighting switch and a vacancy delay number (in the device's
175
+ configuration). It includes the MQTT state, which they read.</dd>
119
176
  </dl>
120
177
  <p>These go on the second output; wire it to an MQTT out node. The node announces itself once the flows have
121
178
  started, and again when it receives <code>msg.source = "startup"</code>.</p>
@@ -124,8 +181,16 @@
124
181
  <li>Lighting intents, for the room lighting controller.</li>
125
182
  <li>MQTT publications, when publishing is on.</li>
126
183
  </ol>
184
+ <h3>Broker</h3>
185
+ <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
186
+ broker connects, reconnects included, and each time Home Assistant comes back (<code>online</code> on
187
+ <code>&lt;prefix&gt;/status</code>), so its entities come back by themselves.
188
+ Each connect also runs its startup message, as a Status node's "connected" did without a broker. Its publication output then sends
189
+ 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.
190
+ Opening and saving the node offers the first broker in your flows. A node saved before 6.2 that publishes keeps
191
+ publishing on its output, as below, and needs no broker until you choose one.</p>
127
192
  <h3>When MQTT out connects</h3>
128
- <p>Wire a <b>Status node</b> whose scope is your MQTT out node into this node. Each time MQTT out shows
193
+ <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
129
194
  "connected", this node takes it as its startup message (<code>msg.source = "startup"</code>) and announces itself again:
130
195
  Node-RED's MQTT broker node drops what it is given before it connects, so what the node sends as the flows
131
196
  start is lost on a first start, a full deploy or a restart. Any other status message is ignored.</p>
@@ -6,8 +6,11 @@ const settings_1 = require("../lib/settings");
6
6
  const topic_names_1 = require("../lib/topic-names");
7
7
  const adapter_1 = require("./adapter");
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
  const refused_enable_1 = require("./refused-enable");
12
+ // The longest wait setTimeout takes: anything longer fires at once.
13
+ const MAX_TIMEOUT_MS = 2 ** 31 - 1;
11
14
  const registerMotionPolicy = (RED) => {
12
15
  function HomeMotionLightingPolicy(config) {
13
16
  RED.nodes.createNode(this, config);
@@ -15,21 +18,23 @@ const registerMotionPolicy = (RED) => {
15
18
  const context = node.context();
16
19
  const globalContext = context.global;
17
20
  let offTimer;
21
+ let pauseTimer;
18
22
  let policyConfig;
19
23
  let publishing;
24
+ let broker;
20
25
  try {
21
26
  const area = (0, adapter_1.optionalArea)(config);
22
27
  policyConfig = { area, ...(0, motion_policy_1.normaliseMotionConfig)(config) };
23
28
  // Off unless switched on, as motion published nothing before; there are
24
29
  // no older entities to keep, so not set names them after the node.
25
- const publishState = (0, settings_1.optionalBooleanSetting)(config.publishState, "publish state") ?? false;
26
- const discovery = (0, settings_1.optionalBooleanSetting)(config.discovery, "Home Assistant discovery") ?? false;
27
- if (publishState || discovery)
30
+ const publish = (0, home_assistant_setting_1.publishingChoice)(config, { publishState: false, discovery: false });
31
+ if (publish.needsArea)
28
32
  (0, topic_names_1.publishingArea)(area, true);
33
+ broker = (0, publishing_side_1.brokerSetting)(RED, config.broker, publish.publishState);
29
34
  publishing = {
30
35
  area,
31
- publishState,
32
- discovery,
36
+ publishState: publish.publishState,
37
+ discovery: publish.discovery,
33
38
  discoveryPrefix: (0, ha_discovery_1.discoveryPrefixSetting)(config.discoveryPrefix),
34
39
  nodeId: node.id,
35
40
  idScheme: (0, settings_1.optionalChoiceSetting)(config.idScheme, "ID scheme", ha_discovery_1.ID_SCHEMES) ?? "node"
@@ -55,6 +60,21 @@ const registerMotionPolicy = (RED) => {
55
60
  process({ source: "off-timer", generation }, node.send.bind(node));
56
61
  }), delayMs);
57
62
  }
63
+ // Wakes the policy when the first pause runs out, so motion resumes then
64
+ // (and acts on a vacancy meanwhile) rather than at the next message. A
65
+ // wait longer than setTimeout takes (about 24.8 days) is split: it wakes
66
+ // at the longest and arms again.
67
+ function armPauseTimer(state) {
68
+ clearTimeout(pauseTimer);
69
+ pauseTimer = undefined;
70
+ const ends = (state?.pausedBy ?? []).map(({ until }) => until).filter(Number.isFinite);
71
+ if (!ends.length)
72
+ return;
73
+ pauseTimer = setTimeout((0, adapter_1.guarded)(node, () => {
74
+ pauseTimer = undefined;
75
+ process({ source: "pause-check" }, node.send.bind(node));
76
+ }), Math.min(MAX_TIMEOUT_MS, Math.max(0, Math.min(...ends) - Date.now()) + 1));
77
+ }
58
78
  // The enable state and delay in use, by the reducer's own rule: a saved
59
79
  // delay stands only while the setting it was based on is unchanged.
60
80
  function savedPolicyState() {
@@ -64,14 +84,18 @@ const registerMotionPolicy = (RED) => {
64
84
  // intents the room controller reads on the first. Available, and clear
65
85
  // of what it no longer publishes, as soon as it runs; offline as it
66
86
  // stops; nothing left behind when deleted.
67
- const lifecycle = (0, publishing_lifecycle_1.publishingLifecycle)(RED, node, {
87
+ const trace = { area: policyConfig.area, component: "motion-policy" };
88
+ const lifecycle = (0, publishing_side_1.publishingSide)(RED, node, broker, {
68
89
  retainedTopics: () => (0, motion_publishing_1.motionRetainedTopics)(publishing),
69
90
  possible: { owner: publishing, topics: () => (0, publishing_node_1.publishesState)(publishing) ? (0, motion_publishing_1.motionRetainedTopics)({ ...publishing, publishState: true, discovery: true }) : [] },
70
91
  starting: () => (0, motion_publishing_1.motionStartingOutputs)(publishing, savedPolicyState()),
71
92
  stopping: () => (0, motion_publishing_1.motionStoppingOutputs)(publishing),
72
93
  output: 1,
73
- outputs: 2
74
- });
94
+ outputs: 2,
95
+ startupMessage: { source: "startup" },
96
+ statusTopic: publishing.discovery ? publishing.discoveryPrefix + "/status" : null,
97
+ setTopics: (0, publishing_node_1.publishesState)(publishing) ? [(0, motion_publishing_1.motionEnabledTopic)(publishing.area, "set"), (0, motion_publishing_1.motionDelayTopic)(publishing.area, "set")] : []
98
+ }, trace, (msg, send) => handle(msg, send));
75
99
  function process(input, send, inboundTraces = null) {
76
100
  const globalEnabled = globalContext.get("MOTION_ENABLED_STATE") !== false;
77
101
  const before = savedPolicyState();
@@ -102,6 +126,7 @@ const registerMotionPolicy = (RED) => {
102
126
  }
103
127
  updateStatus(result.status);
104
128
  showRefused(result.traces);
129
+ armPauseTimer(result.state);
105
130
  return result;
106
131
  }
107
132
  const showRefused = (0, refused_enable_1.refusedEnables)(node);
@@ -110,13 +135,14 @@ const registerMotionPolicy = (RED) => {
110
135
  // off-timer is re-armed. Without one, it starts with nothing saved, and
111
136
  // vacancy starts now.
112
137
  const savedState = context.get("state");
138
+ armPauseTimer(savedState);
113
139
  if (typeof savedState?.offTimerDueAt === "number") {
114
140
  armOffTimer(Math.max(0, savedState.offTimerDueAt - Date.now()), Number(savedState.offTimerGeneration) || 0);
115
141
  }
116
142
  else if (savedState === undefined) {
117
143
  process({ source: "cold-start" }, node.send.bind(node));
118
144
  }
119
- (0, adapter_1.onInput)(node, (msg, send) => {
145
+ function handle(msg, send) {
120
146
  if (msg.source === "startup") {
121
147
  lifecycle.startup(send, (0, motion_publishing_1.motionStartingOutputs)(publishing, savedPolicyState()));
122
148
  return;
@@ -125,9 +151,16 @@ const registerMotionPolicy = (RED) => {
125
151
  // else is an input as sent, with a pause's owner.
126
152
  const inbound = (0, motion_publishing_1.motionInbound)(msg, publishing);
127
153
  process(inbound?.input ?? { source: String(msg.source ?? ""), payload: msg.payload, owner: typeof msg.owner === "string" ? msg.owner : undefined }, send, inbound);
128
- }, { message: { source: "startup" }, trace: { area: policyConfig.area, component: "motion-policy" } });
154
+ }
155
+ (0, adapter_1.onInput)(node, (msg, send) => {
156
+ // With a broker, its set topics come from the broker: an MQTT in or a
157
+ // Status node still wired in changes nothing.
158
+ if (!lifecycle.fromBroker(msg))
159
+ handle(msg, send);
160
+ }, lifecycle.startupOption({ source: "startup" }));
129
161
  node.on("close", (_removed, done) => {
130
162
  clearTimeout(offTimer);
163
+ clearTimeout(pauseTimer);
131
164
  done();
132
165
  });
133
166
  }
@@ -0,0 +1,41 @@
1
+ export declare const MQTT_CONNECTED = "node-red:common.status.connected";
2
+ export interface BrokerNode {
3
+ connected?: boolean;
4
+ register(user: BrokerUser): void;
5
+ deregister(user: BrokerUser, done: () => void, autoDisconnect?: boolean): void;
6
+ subscribe(topic: string, options: {
7
+ qos: number;
8
+ }, callback: (topic: string, payload: Buffer | string, packet?: {
9
+ retain?: boolean;
10
+ }) => void, ref: string): void;
11
+ unsubscribe(topic: string, ref: string, removeClientSubscription?: boolean): void;
12
+ publish(msg: {
13
+ topic: string;
14
+ payload: string;
15
+ qos: number;
16
+ retain: boolean;
17
+ }, done?: (error?: unknown) => void): void;
18
+ }
19
+ interface BrokerUser {
20
+ id: string;
21
+ status(status: {
22
+ text?: unknown;
23
+ }): void;
24
+ }
25
+ export interface BrokerMessage {
26
+ topic: string;
27
+ payload: string;
28
+ retain: boolean;
29
+ }
30
+ export interface BrokerLink {
31
+ connected(): boolean;
32
+ onConnected(callback: () => void): void;
33
+ publish(topic: string, payload: string, options?: {
34
+ retain?: boolean;
35
+ qos?: number;
36
+ }): void;
37
+ subscribe(topic: string, callback: (message: BrokerMessage) => void): void;
38
+ close(removed: boolean, done: () => void): void;
39
+ }
40
+ export declare function brokerLink(broker: BrokerNode, ownerId: string, onError?: (error: unknown) => void): BrokerLink;
41
+ export {};