@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
@@ -5,6 +5,10 @@ const publishing_lifecycle_1 = require("./publishing-lifecycle");
5
5
  const room_publishing_1 = require("../lib/room-publishing");
6
6
  const adapter_1 = require("./adapter");
7
7
  const settings_1 = require("../lib/settings");
8
+ const home_assistant_setting_1 = require("../lib/home-assistant-setting");
9
+ const bounded_trace_1 = require("../lib/bounded-trace");
10
+ const mqtt_broker_link_1 = require("./mqtt-broker-link");
11
+ const home_assistant_discovery_1 = require("./home-assistant-discovery");
8
12
  const ha_discovery_1 = require("../lib/ha-discovery");
9
13
  const topic_names_1 = require("../lib/topic-names");
10
14
  // The room's lights: an id each, and onOffOnly for one that only switches.
@@ -32,6 +36,7 @@ const registerRoomController = (RED) => {
32
36
  const node = this;
33
37
  const area = (0, adapter_1.optionalArea)(config);
34
38
  let controllerConfig;
39
+ let broker = null;
35
40
  try {
36
41
  // A room saved before 6.0 still has its circadian settings, which moved
37
42
  // to the circadian lighting policy: it runs only once migrated, so it
@@ -50,11 +55,25 @@ const registerRoomController = (RED) => {
50
55
  }
51
56
  // Not set (null, or absent from a flow saved before these settings)
52
57
  // means on, so an older flow keeps publishing as before.
53
- const publishState = (0, settings_1.optionalBooleanSetting)(config.publishState, "publish state") ?? true;
54
- const discovery = (0, settings_1.optionalBooleanSetting)(config.discovery, "Home Assistant discovery") ?? true;
58
+ const homeAssistant = (0, home_assistant_setting_1.homeAssistantSetting)(config, { publishState: true, discovery: true });
59
+ const publishState = homeAssistant !== "off";
60
+ const discovery = homeAssistant === "discovery";
61
+ // A room saved before the choice needed an area whenever either old
62
+ // setting was on, even discovery alone, which published nothing: kept,
63
+ // so it validates as before.
64
+ const legacyArea = (config.homeAssistant === undefined || config.homeAssistant === null) &&
65
+ (((0, settings_1.optionalBooleanSetting)(config.publishState, "publish state") ?? true) || ((0, settings_1.optionalBooleanSetting)(config.discovery, "Home Assistant discovery") ?? true));
66
+ // With a broker, it publishes itself; without one, through output 1,
67
+ // as before 6.2.
68
+ const brokerId = typeof config.broker === "string" ? config.broker.trim() : "";
69
+ if (publishState && brokerId) {
70
+ broker = RED.nodes.getNode(brokerId);
71
+ if (!broker)
72
+ throw new Error("its MQTT broker node isn't in the flows: choose one, or set Publish to Don't publish");
73
+ }
55
74
  // Both publish under topics and IDs named after the area; otherwise the
56
75
  // area is only a label.
57
- if (publishState || discovery)
76
+ if (publishState || legacyArea)
58
77
  (0, topic_names_1.publishingArea)(area, true);
59
78
  controllerConfig = {
60
79
  nodeId: node.id,
@@ -81,15 +100,33 @@ const registerRoomController = (RED) => {
81
100
  const recorded = node.context().get("retainedTopics");
82
101
  if (Array.isArray(recorded))
83
102
  node.context().set("retainedTopics", (0, room_publishing_1.withoutCircadianState)(recorded));
84
- // Available, and clear of what it no longer publishes, as soon as it
85
- // runs; offline as it stops; nothing left behind when deleted.
86
- const lifecycle = (0, publishing_lifecycle_1.publishingLifecycle)(RED, node, {
87
- retainedTopics: () => (0, room_publishing_1.roomRetainedTopics)(controllerConfig),
88
- starting: () => (0, room_publishing_1.roomStartingOutputs)(controllerConfig),
89
- stopping: () => (0, room_publishing_1.roomStoppingOutputs)(controllerConfig),
90
- output: 0,
91
- outputs: 3
92
- });
103
+ const trace = { area: controllerConfig.area, component: "room-controller" };
104
+ // With a broker: everything announced on each connect and when Home
105
+ // Assistant comes back, offline as it stops, nothing left behind when
106
+ // deleted. Without one: the same through output 1, from the flows start
107
+ // and the startup message.
108
+ let homeAssistant = null;
109
+ let lifecycle = null;
110
+ if (broker) {
111
+ homeAssistant = (0, home_assistant_discovery_1.homeAssistantDiscovery)(RED, node, (0, mqtt_broker_link_1.brokerLink)(broker, node.id, (error) => node.error(error)), {
112
+ retainedTopics: () => (0, room_publishing_1.roomRetainedTopics)(controllerConfig),
113
+ announcement: () => (0, room_publishing_1.roomAnnouncement)(controllerConfig, node.context().get("state")),
114
+ stopping: () => (0, room_publishing_1.roomStoppingOutputs)(controllerConfig),
115
+ statusTopic: controllerConfig.discovery ? controllerConfig.discoveryPrefix + "/status" : null,
116
+ // Each connect runs its startup, as a Status node's "connected" did:
117
+ // its announcement, and each light asked for a reading.
118
+ onConnected: () => process({ lighting: { kind: "startup" } }, node.send.bind(node))
119
+ }, trace);
120
+ }
121
+ else {
122
+ lifecycle = (0, publishing_lifecycle_1.publishingLifecycle)(RED, node, {
123
+ retainedTopics: () => (0, room_publishing_1.roomRetainedTopics)(controllerConfig),
124
+ starting: () => (0, room_publishing_1.roomStartingOutputs)(controllerConfig),
125
+ stopping: () => (0, room_publishing_1.roomStoppingOutputs)(controllerConfig),
126
+ output: 0,
127
+ outputs: 3
128
+ });
129
+ }
93
130
  function updateStatus(status) {
94
131
  node.status({
95
132
  fill: status.manualCount ? "yellow" : status.styled ? "green" : "grey",
@@ -110,7 +147,10 @@ const registerRoomController = (RED) => {
110
147
  ];
111
148
  const warned = new Set();
112
149
  function process(msg, send) {
113
- const result = (0, adapter_1.runReducer)(node, { area: controllerConfig.area, component: "room-controller" }, (saved, now) => (0, room_publishing_1.publishRoom)(saved, msg, controllerConfig, now));
150
+ const result = (0, adapter_1.runReducer)(node, trace, (saved, now) => (0, room_publishing_1.publishRoom)(saved, msg, controllerConfig, now));
151
+ // With a broker, the publications go to it, and output 1 is quiet.
152
+ if (homeAssistant)
153
+ homeAssistant.publish(result.outputs);
114
154
  // Output 1: MQTT publications (control states, availability,
115
155
  // discovery). Output 2: light commands, for the lights' adapters.
116
156
  // Output 3: each light's reading passed on with its control state, for
@@ -119,7 +159,7 @@ const registerRoomController = (RED) => {
119
159
  controllerConfig.targets.some(({ id }) => id === msg.light.target) ? msg.light : null;
120
160
  const control = reading ? result.status.control[reading.target] : undefined;
121
161
  const outputs = [
122
- result.outputs.length ? result.outputs.map((output) => ({ ...output, payload: output.payload })) : null,
162
+ !homeAssistant && result.outputs.length ? result.outputs.map((output) => ({ ...output, payload: output.payload })) : null,
123
163
  result.commands.length ? result.commands.map((light) => ({ payload: undefined, light })) : null,
124
164
  reading ? { payload: undefined, light: { ...reading, control, manual: control === "manual" } } : null
125
165
  ];
@@ -135,9 +175,16 @@ const registerRoomController = (RED) => {
135
175
  return result;
136
176
  }
137
177
  (0, adapter_1.onInput)(node, (msg, send) => {
178
+ // With a broker it announces itself on every connect: a Status node
179
+ // still wired in, from before, changes nothing.
180
+ const status = (0, adapter_1.objectField)(msg, "status");
181
+ if (homeAssistant && status && status.source && typeof status.source === "object") {
182
+ (0, bounded_trace_1.appendTrace)(node.context(), trace, [{ event: "input", outcome: "ignored", reason: "has-broker", details: { status: String(status.text ?? "") } }]);
183
+ return;
184
+ }
138
185
  // The startup's own announcement comes from publishRoom.
139
186
  if ((0, adapter_1.objectField)(msg, "lighting")?.kind === "startup")
140
- lifecycle.startup(send);
187
+ lifecycle?.startup(send);
141
188
  process({
142
189
  lighting: (0, adapter_1.objectField)(msg, "lighting"),
143
190
  light: msg.light,
@@ -145,7 +192,7 @@ const registerRoomController = (RED) => {
145
192
  payload: msg.payload,
146
193
  retain: msg.retain === true
147
194
  }, send);
148
- });
195
+ }, broker ? undefined : { message: { lighting: { kind: "startup" } }, trace });
149
196
  }
150
197
  RED.nodes.registerType("home-room-lighting-controller", HomeRoomLightingController);
151
198
  };
@@ -0,0 +1,3 @@
1
+ import type { NodeInitializer } from "node-red";
2
+ declare const registerScene: NodeInitializer;
3
+ export = registerScene;
@@ -0,0 +1,226 @@
1
+ <script type="text/javascript">
2
+ (function () {
3
+ // The lights as lib/scene.ts reads them: its room's area and its id there,
4
+ // ON or OFF, and for an ON light optional brightnessPct (0-100) and
5
+ // colorTempKelvin (above 0); each light once.
6
+ function validLights(v) {
7
+ try {
8
+ var lights = JSON.parse(v);
9
+ if (!Array.isArray(lights)) return false;
10
+ var seen = {};
11
+ return lights.every(function (light) {
12
+ if (!light || typeof light !== "object" || Array.isArray(light)) return false;
13
+ var target = typeof light.target === "string" ? light.target.trim() : "";
14
+ var area = topicName(light.area);
15
+ var state = String(light.state || "").toUpperCase();
16
+ if (!target || !area || seen[area + "/" + target] || (state !== "ON" && state !== "OFF")) return false;
17
+ seen[area + "/" + target] = true;
18
+ return Object.keys(light).every(function (key) {
19
+ var value = light[key];
20
+ if (key === "area" || key === "target" || key === "state") return true;
21
+ if (state === "OFF" || typeof value !== "number" || !isFinite(value)) return false;
22
+ if (key === "brightnessPct") return value >= 0 && value <= 100;
23
+ if (key === "colorTempKelvin") return value > 0;
24
+ return false;
25
+ });
26
+ });
27
+ } catch (e) { return false; }
28
+ }
29
+ // A name or area as topics and Home Assistant IDs read it (lib/topic-names.ts areaId).
30
+ function topicName(v) { return String(v || "").trim().toLowerCase().replace(/[^a-z0-9_-]+/g, "_").replace(/^[_-]+|[_-]+$/g, ""); }
31
+ // Its Publish choice (off, state or discovery), from the open dialog or
32
+ // its saved settings: a node saved before the choice reads its two old
33
+ // settings (lib/home-assistant-setting.ts).
34
+ function publishChoice(node) {
35
+ function on(value) { return value === true || value === "true"; }
36
+ var select = $("#node-input-homeAssistant");
37
+ if (select.length) return select.val();
38
+ if (node.homeAssistant === "off" || node.homeAssistant === "state" || node.homeAssistant === "discovery") return node.homeAssistant;
39
+ return !on(node.publishState) ? "off" : on(node.discovery) ? "discovery" : "state";
40
+ }
41
+ // Whether it publishes through its output, as before 6.2: a node saved
42
+ // before the Publish choice that published, or one opened and saved since
43
+ // without a broker (publishesThroughOutput). It needs no broker until one
44
+ // is chosen; from saved values only, not the open dialog.
45
+ function throughOutput(node) {
46
+ if (node.publishesThroughOutput === true) return true;
47
+ return (node.homeAssistant === null || node.homeAssistant === undefined) && (node.publishState === true || node.publishState === "true");
48
+ }
49
+ // Its area is needed while it publishes, and for a node saved before the
50
+ // choice whenever either old setting was on, as the runtime checks.
51
+ function needsArea(node) {
52
+ function on(value) { return value === true || value === "true"; }
53
+ var saved = !$("#node-input-homeAssistant").length && (node.homeAssistant === null || node.homeAssistant === undefined);
54
+ return publishChoice(node) !== "off" || (saved && (on(node.publishState) || on(node.discovery)));
55
+ }
56
+ RED.nodes.registerType("home-scene", {
57
+ category: "home automation",
58
+ color: "#e2d96e",
59
+ defaults: {
60
+ // No default: it names the scene to its rooms, motion policies and
61
+ // Home Assistant, so two scenes can't share one: they would share an
62
+ // owner, and one's end would release the other's lights and pause.
63
+ name: {value: "", required: true, validate: function (v) {
64
+ var own = topicName(v);
65
+ if (!own) return false;
66
+ var self = this;
67
+ var clash = false;
68
+ RED.nodes.eachNode(function (other) {
69
+ if (other.type === "home-scene" && other.id !== self.id && topicName(other.name) === own) clash = true;
70
+ });
71
+ return clash ? "another scene has this name" : true;
72
+ }},
73
+ lights: {value: "[]", required: true, validate: validLights},
74
+ safetyHours: {value: 4, required: true, validate: function (v) { var n = Number(v); return String(v).trim() !== "" && isFinite(n) && n >= 0; }},
75
+ area: {value: "", validate: function (v) { return !needsArea(this) || /[a-z0-9]/i.test(String(v || "")); }},
76
+ // Off until switched on.
77
+ // Publish: off, state or discovery. null means "not set": a node saved
78
+ // before this setting, read from the two below, kept with no rows.
79
+ homeAssistant: {value: null},
80
+ // Node-RED's MQTT broker node, through which it publishes and reads its set
81
+ // topics itself. Needed unless Publish is "Don't publish". The editor offers
82
+ // the first broker when the dialog is opened and saved, not when the node
83
+ // is dropped.
84
+ broker: {value: "", type: "mqtt-broker", required: false, validate: function (v) {
85
+ return publishChoice(this) === "off" || (Boolean(v) && v !== "_ADD_") || throughOutput(this) ? true : "choose a broker, or set Publish to Don't publish";
86
+ }},
87
+ publishState: {value: false},
88
+ discovery: {value: false},
89
+ // true for a node that publishes through its output, as before 6.2, and
90
+ // was opened and saved without a broker: it stays valid until a broker is
91
+ // chosen. No form row.
92
+ publishesThroughOutput: {value: false},
93
+ discoveryPrefix: {value: "homeassistant", required: true, validate: function (v) { var prefix = String(v || "").trim().replace(/^\/+|\/+$/g, ""); return Boolean(prefix) && !/[+#]/.test(prefix); }},
94
+ idScheme: {value: "node"}
95
+ },
96
+ oneditsave: function () {
97
+ // Through its output until a broker is chosen (read before the
98
+ // dialog's values are applied).
99
+ var broker = $("#node-input-broker").val();
100
+ this.publishesThroughOutput = throughOutput(this) && (!broker || broker === "_ADD_");
101
+ },
102
+ oneditprepare: function () {
103
+ function on(value) { return value === true || value === "true"; }
104
+ $("#node-input-homeAssistant").val(publishChoice(this));
105
+ // The broker only while it publishes, the prefix only with discovery.
106
+ var outputBefore = throughOutput(this);
107
+ function publishRows() {
108
+ var broker = $("#node-input-broker").val();
109
+ $(".publish-through-output").toggle($("#node-input-homeAssistant").val() !== "off" && outputBefore && (!broker || broker === "_ADD_"));
110
+ var choice = $("#node-input-homeAssistant").val();
111
+ $(".publish-broker").toggle(choice !== "off");
112
+ $(".publish-discovery").toggle(choice === "discovery");
113
+ $("#node-input-area, #node-input-broker").trigger("change");
114
+ }
115
+ $("#node-input-homeAssistant, #node-input-broker").on("change", publishRows);
116
+ publishRows();
117
+ },
118
+ inputs: 1,
119
+ outputs: 3,
120
+ outputLabels: ["to room lighting controllers", "to motion lighting policies", "MQTT publications"],
121
+ icon: "font-awesome/fa-magic",
122
+ label: function () { return this.name || "scene"; },
123
+ paletteLabel: "scene"
124
+ });
125
+ })();
126
+ </script>
127
+
128
+ <script type="text/html" data-template-name="home-scene">
129
+ <div class="form-row"><label for="node-input-name">Name</label><input type="text" id="node-input-name" placeholder="Bath, for example"></div>
130
+ <div class="form-row"><label for="node-input-lights">Lights</label><input type="text" id="node-input-lights" placeholder='[{"area":"gym","target":"main","state":"OFF"}]'></div>
131
+ <div class="form-row"><label for="node-input-safetyHours">Safety timer (hours)</label><input type="number" id="node-input-safetyHours" min="0" step="0.25"> <span>(0: off)</span></div>
132
+ <div class="form-row"><label for="node-input-area">Area</label><input type="text" id="node-input-area"></div>
133
+ <div class="form-row">
134
+ <label for="node-input-homeAssistant">Publish</label>
135
+ <select id="node-input-homeAssistant">
136
+ <option value="off">Don't publish</option>
137
+ <option value="state">MQTT state</option>
138
+ <option value="discovery">MQTT state and Home Assistant discovery</option>
139
+ </select>
140
+ </div>
141
+ <div class="form-row publish-broker"><label for="node-input-broker">Broker</label><input type="text" id="node-input-broker"></div>
142
+ <div class="form-tips publish-broker">With a broker, it publishes and reads its set topics itself: an MQTT out on its
143
+ publication output, an MQTT in on its set topics, and a Status node are no longer needed and can be deleted.</div>
144
+ <div class="form-tips publish-through-output">This node publishes through its output, as before 6.2, and keeps
145
+ working that way. Choose a Broker to let it publish itself.</div>
146
+ <div class="form-row publish-discovery"><label for="node-input-discoveryPrefix">Discovery prefix</label><input type="text" id="node-input-discoveryPrefix"></div>
147
+ </script>
148
+
149
+ <script type="text/html" data-help-name="home-scene">
150
+ <p>One scene, such as <i>Bath</i> or <i>Exercise mode</i>. While it is on, it holds some of a room's lights on or
151
+ off with the values it gives them, and pauses motion lighting. When it ends, it lets them go, and each room gives
152
+ its lights back what they were before the scene (or to a scene that is still on beneath it). It reaches lights
153
+ only through room lighting controllers, and never through Home Assistant.</p>
154
+ <h3>Wiring</h3>
155
+ <ol>
156
+ <li>Output 1 → each <b>room lighting controller</b> whose lights it sets.</li>
157
+ <li>Output 2 → each <b>motion lighting policy</b> it should pause while on.</li>
158
+ <li>Output 3 → an <b>MQTT out</b> node, when it publishes its switch for Home Assistant, with an <b>MQTT in</b>
159
+ node on <code>home/&lt;area&gt;/scene/&lt;name&gt;/set</code> into this node.</li>
160
+ </ol>
161
+ <h3>Inputs</h3>
162
+ <dl class="message-properties">
163
+ <dt>scene <span class="property-type">object</span></dt>
164
+ <dd><code>{kind: "start"}</code> turns it on (on again: a fresh safety timer, its lights left as they are);
165
+ <code>{kind: "end", by}</code> ends it, with <code>by</code> (optional) shown as what ended it. An end
166
+ trigger, such as a trainer's power falling, is a flow that sends this end when its condition is met.
167
+ <code>{kind: "startup"}</code> announces its switch again.</dd>
168
+ <dt>payload <span class="property-type">string</span></dt>
169
+ <dd><code>ON</code> or <code>OFF</code> on its set topic, from Home Assistant: a start, or an end by
170
+ <code>home-assistant</code>.</dd>
171
+ </dl>
172
+ <h3>Broker</h3>
173
+ <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
174
+ broker connects, reconnects included, and each time Home Assistant comes back (<code>online</code> on
175
+ <code>&lt;prefix&gt;/status</code>), so its entities come back by themselves.
176
+ Each connect also runs its startup message, as a Status node's "connected" did without a broker. Its publication output then sends
177
+ 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.
178
+ Opening and saving the node offers the first broker in your flows. A node saved before 6.2 that publishes keeps
179
+ publishing on its output, as below, and needs no broker until you choose one.</p>
180
+ <h3>When MQTT out connects</h3>
181
+ <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
182
+ "connected", this node takes it as its startup message (<code>msg.scene = {kind: "startup"}</code>) and announces
183
+ itself again: Node-RED's MQTT broker node drops what it is given before it connects, so what the node sends as
184
+ the flows start is lost on a first start, a full deploy or a restart. Any other status message is ignored.</p>
185
+ <h3>Outputs</h3>
186
+ <ol class="node-ports">
187
+ <li>Room lighting controllers: an owner intent per light as it starts,
188
+ <code>{lighting: {kind: "intent", area, targets: [id], state, values?, owner: "scene:&lt;name&gt;", source: "scene"}}</code>,
189
+ and a release per room as it ends, <code>{lighting: {kind: "release", area, owner, targets, source: "scene"}}</code>.</li>
190
+ <li>Motion lighting policies: <code>{source: "pause", payload: true, owner}</code> as it starts and every minute
191
+ while on, and <code>payload: false</code> as it ends. Keep each motion policy's <b>Maximum pause</b> above a
192
+ minute (10 minutes by default), or motion runs between renewals. If the room went vacant meanwhile, motion's
193
+ vacancy delay starts when the pause lifts.</li>
194
+ <li>MQTT publications: its switch's state, availability and discovery.</li>
195
+ </ol>
196
+ <h3>Settings</h3>
197
+ <dl class="message-properties">
198
+ <dt>Name</dt><dd>Required, and each scene's own: it names the scene to its rooms and motion policies (owner
199
+ <code>scene:&lt;name&gt;</code>), and in its topics and Home Assistant. The editor marks a name another scene
200
+ has (compared as in topics, so <code>Bath</code> and <code>bath</code> are the same).</dd>
201
+ <dt>Lights</dt><dd>A JSON array, one entry per light: <code>area</code> (its room controller's <b>Area</b>),
202
+ <code>target</code> (the light's id in that room's Targets JSON), <code>state</code> <code>ON</code> or
203
+ <code>OFF</code>, and for an ON light <code>brightnessPct</code> (0-100) and <code>colorTempKelvin</code>
204
+ (optional). A socket is a room target with on/off only: give it just its state. For example
205
+ <code>[{"area": "gym", "target": "main", "state": "OFF"}, {"area": "gym", "target": "tv", "state": "ON"}]</code>.</dd>
206
+ <dt>Safety timer</dt><dd>Hours until it ends itself, so a forgotten scene doesn't hold the room: 4 by
207
+ default; 0 turns it off.</dd>
208
+ <dt>Area, Publish</dt><dd><i>Don't publish</i> unless chosen. <i>MQTT state</i>: its state and set topic, plain
209
+ MQTT; <i>MQTT state and Home Assistant discovery</i>: also a switch entity for the scene
210
+ that shows whether it is on and turns it on and off, on <code>home/&lt;area&gt;/scene/&lt;name&gt;/…</code>.</dd>
211
+ </dl>
212
+ <h3>Rules</h3>
213
+ <ul>
214
+ <li>Each light names its room by the room controller's <b>Area</b>, so set the Area on each room a scene uses.
215
+ Its intents and releases carry that area, and a room acts only on those for its own Area: two rooms may each
216
+ have a <code>main</code>.</li>
217
+ <li>Scenes stack: a newer scene holding a light another scene holds takes it, and hands it back to the older
218
+ one when it ends. Ending the older one first leaves the light with the newer.</li>
219
+ <li>A person changing a light the scene holds makes it theirs: the scene's end leaves it alone.</li>
220
+ <li>On while the flows restart (with a context store), it stays on, with its timer; if its time ran out
221
+ meanwhile, it ends as they start. Deleted while on, it lets its lights and motion go.</li>
222
+ </ul>
223
+ <h3>Status</h3>
224
+ <p><b>on · 3h 59m left</b> (green) while on; <b>off · ended by timer</b>, <b>request</b>,
225
+ <b>home-assistant</b> or what the end gave; <b>off</b> before it has run.</p>
226
+ </script>
@@ -0,0 +1,121 @@
1
+ "use strict";
2
+ const ha_discovery_1 = require("../lib/ha-discovery");
3
+ const publishing_node_1 = require("../lib/publishing-node");
4
+ const scene_1 = require("../lib/scene");
5
+ const scene_publishing_1 = require("../lib/scene-publishing");
6
+ const settings_1 = require("../lib/settings");
7
+ const topic_names_1 = require("../lib/topic-names");
8
+ const adapter_1 = require("./adapter");
9
+ const publishing_side_1 = require("./publishing-side");
10
+ const home_assistant_setting_1 = require("../lib/home-assistant-setting");
11
+ const registerScene = (RED) => {
12
+ function HomeScene(config) {
13
+ RED.nodes.createNode(this, config);
14
+ const node = this;
15
+ const context = node.context();
16
+ let timer;
17
+ let scene;
18
+ let publishing;
19
+ let area;
20
+ let broker;
21
+ try {
22
+ // No default: it names the scene to its rooms, motion policies and
23
+ // Home Assistant.
24
+ const name = (0, settings_1.textSetting)(config.name, "name");
25
+ if (!(0, topic_names_1.areaId)(name))
26
+ throw new Error("name must contain a letter or digit");
27
+ scene = (0, scene_1.normaliseSceneConfig)({ owner: "scene:" + name, lights: config.lights, safetyHours: config.safetyHours });
28
+ area = (0, adapter_1.optionalArea)(config);
29
+ const publish = (0, home_assistant_setting_1.publishingChoice)(config, { publishState: false, discovery: false });
30
+ if (publish.needsArea)
31
+ (0, topic_names_1.publishingArea)(area, true);
32
+ broker = (0, publishing_side_1.brokerSetting)(RED, config.broker, publish.publishState);
33
+ publishing = {
34
+ area,
35
+ name,
36
+ publishState: publish.publishState,
37
+ discovery: publish.discovery,
38
+ discoveryPrefix: (0, ha_discovery_1.discoveryPrefixSetting)(config.discoveryPrefix),
39
+ nodeId: node.id,
40
+ idScheme: (0, settings_1.optionalChoiceSetting)(config.idScheme, "ID scheme", ha_discovery_1.ID_SCHEMES) ?? "node"
41
+ };
42
+ }
43
+ catch (error) {
44
+ (0, adapter_1.invalidConfig)(node, error);
45
+ return;
46
+ }
47
+ const trace = { area, component: "scene" };
48
+ const saved = () => context.get("state");
49
+ const active = () => saved()?.active === true;
50
+ // Its switch, available and clear of what it no longer publishes once
51
+ // it can be (with a broker, on each connect; without one, on output 3
52
+ // once the flows have started), offline as it stops, nothing left
53
+ // behind when deleted.
54
+ const lifecycle = (0, publishing_side_1.publishingSide)(RED, node, broker, {
55
+ retainedTopics: () => (0, scene_publishing_1.sceneRetainedTopics)(publishing),
56
+ possible: { owner: publishing, topics: () => (0, publishing_node_1.publishesState)(publishing) ? (0, scene_publishing_1.sceneRetainedTopics)({ ...publishing, discovery: true }) : [] },
57
+ starting: () => (0, scene_publishing_1.sceneStartingOutputs)(publishing, active()),
58
+ stopping: () => (0, scene_publishing_1.sceneStoppingOutputs)(publishing),
59
+ output: 2,
60
+ outputs: 3,
61
+ startupMessage: { scene: { kind: "startup" } },
62
+ statusTopic: publishing.discovery ? publishing.discoveryPrefix + "/status" : null,
63
+ setTopics: (0, publishing_node_1.publishesState)(publishing) ? [(0, scene_publishing_1.sceneCommandTopic)(publishing)] : []
64
+ }, trace, (msg, send) => handle(msg, send));
65
+ function process(event, send) {
66
+ const wasActive = active();
67
+ const result = (0, adapter_1.runReducer)(node, trace, (state, now) => (0, scene_1.transitionScene)(state, { scene: event }, scene, now));
68
+ // Owner intents and releases for room controllers on output 1, owner
69
+ // pauses for motion policies on output 2.
70
+ if (result.lighting.length || result.motion.length) {
71
+ send([result.lighting.length ? result.lighting : null, result.motion.length ? result.motion : null, null]);
72
+ }
73
+ if (result.state.active !== wasActive)
74
+ lifecycle.publish(send, (0, scene_publishing_1.sceneStateOutputs)(publishing, result.state.active));
75
+ node.status(result.status);
76
+ clearTimeout(timer);
77
+ const at = (0, scene_1.sceneTickAt)(result.state, Date.now());
78
+ timer = at === null ? undefined : setTimeout((0, adapter_1.guarded)(node, () => process({ kind: "tick" }, node.send.bind(node))), Math.max(0, at - Date.now()));
79
+ }
80
+ // A scene on when the flows stopped is still on: renew its pause and its
81
+ // timer, or end it if its time ran out meanwhile.
82
+ (0, adapter_1.whenFlowsStarted)(RED, node, () => process({ kind: "startup" }, node.send.bind(node)));
83
+ function handle(msg, send) {
84
+ const event = (0, adapter_1.objectField)(msg, "scene");
85
+ if (event) {
86
+ if (event.kind === "startup")
87
+ lifecycle.startup(send, (0, scene_publishing_1.sceneStartingOutputs)(publishing, active()));
88
+ process(event, send);
89
+ return;
90
+ }
91
+ // Home Assistant's switch, on the scene's set topic.
92
+ const inbound = (0, scene_publishing_1.sceneInbound)(msg, publishing);
93
+ if (inbound?.kind) {
94
+ process(inbound.kind === "end" ? { kind: "end", by: "home-assistant" } : { kind: "start" }, send);
95
+ }
96
+ else if (inbound) {
97
+ (0, adapter_1.runReducer)(node, trace, (state) => ({ state, traces: inbound.traces }));
98
+ }
99
+ else {
100
+ (0, adapter_1.runReducer)(node, trace, (state) => ({ state, traces: [{ event: "input", outcome: "ignored", reason: "not-a-scene-message", details: {} }] }));
101
+ }
102
+ }
103
+ (0, adapter_1.onInput)(node, (msg, send) => {
104
+ // With a broker, its set topic comes from the broker: an MQTT in or a
105
+ // Status node still wired in changes nothing.
106
+ if (!lifecycle.fromBroker(msg))
107
+ handle(msg, send);
108
+ }, lifecycle.startupOption({ scene: { kind: "startup" } }));
109
+ node.on("close", (removed, done) => {
110
+ clearTimeout(timer);
111
+ // Deleted while on: let its lights and motion go. Best effort: it
112
+ // reaches nodes still running, as in a deploy of modified nodes.
113
+ if ((0, adapter_1.wasDeleted)(RED, node, removed) && active())
114
+ process({ kind: "end", by: "deleted" }, node.send.bind(node));
115
+ done();
116
+ });
117
+ }
118
+ RED.nodes.registerType("home-scene", HomeScene);
119
+ };
120
+ module.exports = registerScene;
121
+ //# sourceMappingURL=scene.js.map
@@ -3,7 +3,21 @@
3
3
  category: "home automation",
4
4
  color: "#e2d96e",
5
5
  defaults: {
6
- name: {value: ""},
6
+ // A marker only a node new from the palette has, as core nodes do: import
7
+ // and paste keep the saved name, so onadd leaves a saved node's settings.
8
+ name: {value: "_DEFAULT_"},
9
+ // Node-RED's MQTT broker node, through which it subscribes to its device's
10
+ // topics and publishes on them itself. The editor offers the first broker
11
+ // when the dialog is opened and saved, not when the node is dropped.
12
+ broker: {value: "", type: "mqtt-broker", required: false, validate: function (v) {
13
+ return (Boolean(v) && v !== "_ADD_") || this.publishesThroughOutput !== false ? true : "choose a broker";
14
+ }},
15
+ // Whether it reaches its device through MQTT in and out nodes, as before
16
+ // 6.2, and so needs no broker until one is chosen. A node saved before
17
+ // this setting loads without it (the editor applies no defaults to the
18
+ // deployed flows), which counts as true; a new node sets false (onadd).
19
+ // No row.
20
+ publishesThroughOutput: {value: false},
7
21
  // No default: it names the user's own device.
8
22
  topicPrefix: {value: "", required: true, validate: function (v) {
9
23
  var prefix = String(v || "").trim().replace(/^\/+|\/+$/g, "");
@@ -13,9 +27,31 @@
13
27
  return /^\d+$/.test(String(v).trim());
14
28
  }}
15
29
  },
30
+ onadd: function () {
31
+ if (this.name !== "_DEFAULT_") return;
32
+ this.name = "";
33
+ this.publishesThroughOutput = false;
34
+ },
35
+ oneditprepare: function () {
36
+ var node = this;
37
+ // While it reaches its device through MQTT in and out nodes, that it does
38
+ // until given a broker.
39
+ function rows() {
40
+ var broker = $("#node-input-broker").val();
41
+ $(".device-through-output").toggle(node.publishesThroughOutput !== false && (!broker || broker === "_ADD_"));
42
+ }
43
+ $("#node-input-broker").on("change", rows);
44
+ rows();
45
+ },
46
+ oneditsave: function () {
47
+ // A broker chosen: it publishes itself from now on.
48
+ var broker = $("#node-input-broker").val();
49
+ if (broker && broker !== "_ADD_") this.publishesThroughOutput = false;
50
+ else if (this.publishesThroughOutput !== false) this.publishesThroughOutput = true;
51
+ },
16
52
  inputs: 1,
17
53
  outputs: 2,
18
- outputLabels: ["to the device (MQTT out)", "to the cover controller"],
54
+ outputLabels: ["to the device (MQTT out, without a broker)", "to the cover controller"],
19
55
  icon: "font-awesome/fa-exchange",
20
56
  label: function () { return this.name || "shelly cover"; },
21
57
  paletteLabel: "shelly cover"
@@ -24,6 +60,11 @@
24
60
 
25
61
  <script type="text/html" data-template-name="home-shelly-cover">
26
62
  <div class="form-row"><label for="node-input-name">Name</label><input type="text" id="node-input-name"></div>
63
+ <div class="form-row"><label for="node-input-broker">Broker</label><input type="text" id="node-input-broker"></div>
64
+ <div class="form-tips">With a broker, it subscribes to its device's topics and publishes on them itself: the MQTT in and
65
+ MQTT out nodes around it are no longer needed and can be deleted.</div>
66
+ <div class="form-tips device-through-output">This node reaches its device through MQTT in and out nodes, as before 6.2,
67
+ and keeps working that way. Choose a Broker to let it do so itself.</div>
27
68
  <div class="form-row"><label for="node-input-topicPrefix">MQTT topic prefix</label><input type="text" id="node-input-topicPrefix" placeholder="the device's ID, e.g. shellyplus2pm-a8032ab12345"></div>
28
69
  <div class="form-row"><label for="node-input-channel">Cover ID</label><input type="number" min="0" step="1" id="node-input-channel"></div>
29
70
  </script>
@@ -32,6 +73,9 @@
32
73
  <p>Connects a Shelly Gen2 or later device in cover mode to a <b>home cover controller</b>, over the device's own
33
74
  MQTT API: no function nodes, no Home Assistant and no HTTP.</p>
34
75
  <h3>Wiring</h3>
76
+ <p>With a <b>Broker</b>, it subscribes to <code>&lt;prefix&gt;/#</code> and publishes on its device's topics itself: leave out the MQTT
77
+ in and MQTT out nodes below (still wired, they change nothing). Its first output then sends nothing. It reads its cover on each connect, as a Status node's startup did through the cover controller. A node saved
78
+ before 6.2 keeps using them until you choose a broker.</p>
35
79
  <ol>
36
80
  <li>An <b>MQTT in</b> node subscribed to <code>&lt;prefix&gt;/#</code> (output: auto-detect) → this node.</li>
37
81
  <li>The cover controller's first output (its device commands) → this node.</li>
@@ -1,13 +1,16 @@
1
1
  "use strict";
2
2
  const shelly_cover_1 = require("../lib/shelly-cover");
3
3
  const adapter_1 = require("./adapter");
4
+ const device_side_1 = require("./device-side");
4
5
  const registerShellyCover = (RED) => {
5
6
  function HomeShellyCover(config) {
6
7
  RED.nodes.createNode(this, config);
7
8
  const node = this;
8
9
  let device;
10
+ let broker;
9
11
  try {
10
12
  device = (0, shelly_cover_1.normaliseShellyCoverConfig)(config);
13
+ broker = (0, device_side_1.deviceBroker)(RED, config.broker);
11
14
  }
12
15
  catch (error) {
13
16
  (0, adapter_1.invalidConfig)(node, error);
@@ -15,17 +18,29 @@ const registerShellyCover = (RED) => {
15
18
  }
16
19
  const trace = { area: "", component: "shelly-cover" };
17
20
  node.status({ fill: "grey", shape: "ring", text: "waiting for the device" });
18
- (0, adapter_1.onInput)(node, (msg, send) => {
21
+ // With a broker, it reads its device on each connect, reconnects
22
+ // included, through its own observe: after a restart nothing reported it
23
+ // while it was away, and the controller acts on the reading as on one it
24
+ // asked for.
25
+ // Its prefix is one device: everything under it.
26
+ const side = (0, device_side_1.deviceSide)(node, broker, device.topicPrefix, [device.topicPrefix + "/#"], trace, (msg, send) => handle(msg, send), () => handle({ cover_command: { operation: "observe" } }, node.send.bind(node)));
27
+ function handle(msg, send) {
19
28
  const result = (0, adapter_1.runReducer)(node, trace, (saved, now) => (0, shelly_cover_1.transitionShellyCover)(saved, msg, device, now));
20
- // MQTT publications for the device on output 1, for an MQTT out node;
21
- // readings for the cover controller on output 2.
29
+ // MQTT publications for the device: to the broker, or on output 1 for
30
+ // an MQTT out node; readings for the cover controller on output 2.
22
31
  const outputs = [
23
- result.publications.length ? result.publications.map((publication) => ({ ...publication })) : null,
32
+ side.publish(result.publications),
24
33
  result.readings.length ? result.readings.map((reading) => ({ payload: undefined, ...reading })) : null
25
34
  ];
26
35
  if (outputs.some((output) => output !== null))
27
36
  send(outputs);
28
37
  node.status({ fill: result.status.calibrated ? "green" : "yellow", shape: "dot", text: result.status.text });
38
+ }
39
+ (0, adapter_1.onInput)(node, (msg, send) => {
40
+ // With a broker, its device's messages come from the broker: an MQTT
41
+ // in or a Status node still wired in changes nothing.
42
+ if (!side.fromBroker(msg))
43
+ handle(msg, send);
29
44
  });
30
45
  }
31
46
  RED.nodes.registerType("home-shelly-cover", HomeShellyCover);