@avantics/node-red-home-automation 3.0.1 → 4.0.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 (108) hide show
  1. package/README.md +262 -13
  2. package/dist/lib/activity-lighting-controller.d.ts +7 -1
  3. package/dist/lib/activity-lighting-controller.js +37 -3
  4. package/dist/lib/adopted-request.d.ts +26 -0
  5. package/dist/lib/adopted-request.js +44 -0
  6. package/dist/lib/avr-controller.d.ts +8 -1
  7. package/dist/lib/avr-controller.js +27 -3
  8. package/dist/lib/avr-publishing.d.ts +24 -0
  9. package/dist/lib/avr-publishing.js +80 -0
  10. package/dist/lib/backlighting-controller.d.ts +7 -1
  11. package/dist/lib/backlighting-controller.js +26 -3
  12. package/dist/lib/circadian.d.ts +1 -0
  13. package/dist/lib/circadian.js +3 -0
  14. package/dist/lib/cover-availability.d.ts +7 -0
  15. package/dist/lib/cover-availability.js +24 -0
  16. package/dist/lib/cover-controller.d.ts +13 -1
  17. package/dist/lib/cover-controller.js +113 -30
  18. package/dist/lib/cover-group.d.ts +62 -0
  19. package/dist/lib/cover-group.js +125 -0
  20. package/dist/lib/cover-models.d.ts +37 -0
  21. package/dist/lib/cover-models.js +83 -0
  22. package/dist/lib/cover-publishing.d.ts +40 -0
  23. package/dist/lib/cover-publishing.js +102 -0
  24. package/dist/lib/cover-requests.d.ts +21 -0
  25. package/dist/lib/cover-requests.js +49 -0
  26. package/dist/lib/display-mode-controller.d.ts +4 -0
  27. package/dist/lib/display-mode-controller.js +26 -2
  28. package/dist/lib/ha-discovery.d.ts +27 -0
  29. package/dist/lib/ha-discovery.js +91 -0
  30. package/dist/lib/house-schedule-publishing.d.ts +23 -0
  31. package/dist/lib/house-schedule-publishing.js +71 -0
  32. package/dist/lib/house-schedule.d.ts +23 -0
  33. package/dist/lib/house-schedule.js +29 -0
  34. package/dist/lib/motion-policy.d.ts +9 -0
  35. package/dist/lib/motion-policy.js +45 -11
  36. package/dist/lib/motion-publishing.d.ts +28 -0
  37. package/dist/lib/motion-publishing.js +92 -0
  38. package/dist/lib/occupancy-publishing.d.ts +10 -0
  39. package/dist/lib/occupancy-publishing.js +45 -0
  40. package/dist/lib/open-close-cover.d.ts +92 -0
  41. package/dist/lib/open-close-cover.js +287 -0
  42. package/dist/lib/publishing-node.d.ts +39 -0
  43. package/dist/lib/publishing-node.js +72 -0
  44. package/dist/lib/retained-topics.d.ts +10 -0
  45. package/dist/lib/retained-topics.js +19 -0
  46. package/dist/lib/room-controller.d.ts +9 -0
  47. package/dist/lib/room-controller.js +47 -56
  48. package/dist/lib/room-lighting-discovery.d.ts +20 -1
  49. package/dist/lib/room-lighting-discovery.js +135 -13
  50. package/dist/lib/room-publishing.d.ts +42 -0
  51. package/dist/lib/room-publishing.js +182 -0
  52. package/dist/lib/room-schedule.d.ts +8 -0
  53. package/dist/lib/room-schedule.js +41 -0
  54. package/dist/lib/settings.d.ts +2 -0
  55. package/dist/lib/settings.js +20 -0
  56. package/dist/lib/source-capability-controller.d.ts +8 -1
  57. package/dist/lib/source-capability-controller.js +29 -3
  58. package/dist/lib/theatre-activity-controller.d.ts +0 -1
  59. package/dist/lib/theatre-activity-controller.js +27 -24
  60. package/dist/lib/theatre-ha-discovery.d.ts +3 -4
  61. package/dist/lib/theatre-ha-discovery.js +46 -36
  62. package/dist/lib/theatre-state-contract.d.ts +6 -0
  63. package/dist/lib/theatre-state-contract.js +83 -47
  64. package/dist/lib/theatre-state.d.ts +1 -1
  65. package/dist/lib/theatre-state.js +1 -1
  66. package/dist/lib/topic-names.d.ts +4 -0
  67. package/dist/lib/topic-names.js +31 -0
  68. package/dist/nodes/activity-lighting-controller.js +5 -3
  69. package/dist/nodes/adapter.d.ts +6 -1
  70. package/dist/nodes/adapter.js +65 -1
  71. package/dist/nodes/avr-controller.html +59 -5
  72. package/dist/nodes/avr-controller.js +74 -4
  73. package/dist/nodes/backlighting-controller.js +5 -3
  74. package/dist/nodes/cover-controller.d.ts +3 -0
  75. package/dist/nodes/cover-controller.html +177 -0
  76. package/dist/nodes/cover-controller.js +178 -0
  77. package/dist/nodes/cover-group.d.ts +3 -0
  78. package/dist/nodes/cover-group.html +89 -0
  79. package/dist/nodes/cover-group.js +84 -0
  80. package/dist/nodes/flows-started.d.ts +4 -0
  81. package/dist/nodes/flows-started.js +39 -0
  82. package/dist/nodes/house-schedule-mqtt.d.ts +3 -0
  83. package/dist/nodes/house-schedule-mqtt.html +61 -0
  84. package/dist/nodes/house-schedule-mqtt.js +80 -0
  85. package/dist/nodes/house-schedule.d.ts +3 -0
  86. package/dist/nodes/house-schedule.html +31 -0
  87. package/dist/nodes/house-schedule.js +51 -0
  88. package/dist/nodes/motion-policy.html +81 -5
  89. package/dist/nodes/motion-policy.js +69 -8
  90. package/dist/nodes/occupancy-fusion.html +69 -14
  91. package/dist/nodes/occupancy-fusion.js +46 -4
  92. package/dist/nodes/publishing-lifecycle.d.ts +25 -0
  93. package/dist/nodes/publishing-lifecycle.js +38 -0
  94. package/dist/nodes/room-controller.html +49 -5
  95. package/dist/nodes/room-controller.js +67 -8
  96. package/dist/nodes/shared-schedule.d.ts +6 -0
  97. package/dist/nodes/shared-schedule.js +15 -0
  98. package/dist/nodes/source-capability-controller.js +5 -3
  99. package/dist/nodes/theatre-activity-controller.html +1 -3
  100. package/dist/nodes/theatre-activity-controller.js +1 -2
  101. package/dist/nodes/theatre-state-contract.html +28 -5
  102. package/dist/nodes/theatre-state-contract.js +22 -4
  103. package/examples/Cover control.json +380 -0
  104. package/examples/Cover pair.json +230 -0
  105. package/examples/Home theatre activity.json +4 -4
  106. package/examples/House schedule.json +164 -0
  107. package/examples/Room lighting.json +4 -3
  108. package/package.json +6 -2
@@ -0,0 +1,177 @@
1
+ <script type="text/javascript">
2
+ (function () {
3
+ // Whether the node publishes, from the open dialog or its saved settings.
4
+ function publishes(node) {
5
+ function on(value) { return value === true || value === "true"; }
6
+ var state = $("#node-input-publishState");
7
+ var discovery = $("#node-input-discovery");
8
+ return state.length ? state.prop("checked") || discovery.prop("checked") : on(node.publishState) || on(node.discovery);
9
+ }
10
+ RED.nodes.registerType("home-cover-controller", {
11
+ category: "home automation",
12
+ color: "#e2d96e",
13
+ defaults: {
14
+ // A marker only a node new from the palette has, as core nodes do: import
15
+ // and paste keep the saved name, so onadd leaves a saved node's settings.
16
+ name: {value: "_DEFAULT_"},
17
+ area: {value: "", validate: function (v) { return !publishes(this) || /[a-z0-9]/i.test(String(v || "")); }},
18
+ // Not set: a position cover, as every cover node was before this setting.
19
+ coverType: {value: "position"},
20
+ presets: {value: "{\"partial\":60}", required: true, validate: function (v) {
21
+ try {
22
+ var parsed = JSON.parse(v);
23
+ return Boolean(parsed) && typeof parsed === "object" && !Array.isArray(parsed) && Object.keys(parsed).every(function (name) {
24
+ var position = parsed[name];
25
+ return /^[a-z][a-z0-9_-]*$/.test(name) && ["open", "close", "stop"].indexOf(name) === -1 &&
26
+ typeof position === "number" && position >= 0 && position <= 100;
27
+ });
28
+ } catch (e) { return false; }
29
+ }},
30
+ positionTolerance: {value: 2, required: true, validate: RED.validators.number()},
31
+ invert: {value: false},
32
+ travelTimeoutMs: {value: 90000, required: true, validate: RED.validators.number()},
33
+ maxAttempts: {value: 2, required: true, validate: RED.validators.number()},
34
+ pollMs: {value: 5000, required: true, validate: RED.validators.number()},
35
+ settleMs: {value: 5000, required: true, validate: RED.validators.number()},
36
+ travelMs: {value: 30000, required: true, validate: RED.validators.number()},
37
+ marginMs: {value: 10000, required: true, validate: RED.validators.number()},
38
+ // Its name in its topics, home/<area>/cover/<name>/..., as a room
39
+ // usually has more than one cover: no default, so two covers can't
40
+ // share topics by leaving it alone. Needed only while it publishes.
41
+ topicName: {value: "", validate: function (v) { return !publishes(this) || /[a-z0-9]/i.test(String(v || "")); }},
42
+ // Off until switched on.
43
+ publishState: {value: false},
44
+ discovery: {value: false},
45
+ discoveryPrefix: {value: "homeassistant", required: true, validate: function (v) { var prefix = String(v || "").trim().replace(/^\/+|\/+$/g, ""); return Boolean(prefix) && !/[+#]/.test(prefix); }},
46
+ // How Home Assistant IDs are named; not set also means "node".
47
+ idScheme: {value: null}
48
+ },
49
+ onadd: function () {
50
+ if (this.name !== "_DEFAULT_") return;
51
+ this.name = "";
52
+ this.idScheme = "node";
53
+ },
54
+ oneditprepare: function () {
55
+ function on(value) { return value === true || value === "true"; }
56
+ function follow() {
57
+ var position = $("#node-input-coverType").val() !== "open-close";
58
+ $(".cover-position").toggle(position);
59
+ $(".cover-open-close").toggle(!position);
60
+ }
61
+ $("#node-input-coverType").on("change", follow);
62
+ follow();
63
+ $("#node-input-publishState").prop("checked", on(this.publishState));
64
+ $("#node-input-discovery").prop("checked", on(this.discovery));
65
+ // Discovery describes the published state, so it needs it.
66
+ function publishing() {
67
+ var state = $("#node-input-publishState").prop("checked");
68
+ if (!state) $("#node-input-discovery").prop("checked", false);
69
+ $("#node-input-discovery").prop("disabled", !state);
70
+ }
71
+ $("#node-input-publishState, #node-input-discovery").on("change", publishing);
72
+ publishing();
73
+ },
74
+ inputs: 1,
75
+ outputs: 4,
76
+ outputLabels: ["device commands", "state and results", "moving", "MQTT publications"],
77
+ icon: "font-awesome/fa-columns",
78
+ label: function () { return this.name || (this.area ? this.area + " " : "") + "cover"; }
79
+ });
80
+ })();
81
+ </script>
82
+
83
+ <script type="text/html" data-template-name="home-cover-controller">
84
+ <div class="form-row"><label for="node-input-name">Name</label><input type="text" id="node-input-name"></div>
85
+ <div class="form-row"><label for="node-input-area">Area</label><input type="text" id="node-input-area"></div>
86
+ <div class="form-row">
87
+ <label for="node-input-coverType">Cover</label>
88
+ <select id="node-input-coverType">
89
+ <option value="position">Takes a position (0 to 100)</option>
90
+ <option value="open-close">Open, close and stop only</option>
91
+ </select>
92
+ </div>
93
+ <div class="form-row cover-position"><label for="node-input-presets">Presets</label><input type="text" id="node-input-presets"></div>
94
+ <div class="form-row cover-position"><label for="node-input-positionTolerance">Position tolerance</label><input type="number" id="node-input-positionTolerance"></div>
95
+ <div class="form-row cover-position"><label for="node-input-invert">Invert positions</label><input type="checkbox" id="node-input-invert" style="display:inline-block; width:auto;"> <span>(the device reports 0 as open)</span></div>
96
+ <div class="form-row cover-position"><label for="node-input-travelTimeoutMs">Travel timeout (ms)</label><input type="number" id="node-input-travelTimeoutMs"></div>
97
+ <div class="form-row cover-position"><label for="node-input-pollMs">Poll interval (ms)</label><input type="number" id="node-input-pollMs"></div>
98
+ <div class="form-row cover-position"><label for="node-input-settleMs">Settle time (ms)</label><input type="number" id="node-input-settleMs"></div>
99
+ <div class="form-row cover-open-close"><label for="node-input-travelMs">Full travel time (ms)</label><input type="number" id="node-input-travelMs"></div>
100
+ <div class="form-row cover-open-close"><label for="node-input-marginMs">Travel margin (ms)</label><input type="number" id="node-input-marginMs"></div>
101
+ <div class="form-row"><label for="node-input-maxAttempts">Maximum attempts</label><input type="number" id="node-input-maxAttempts"></div>
102
+ <div class="form-row"><label for="node-input-topicName">Name in topics</label><input type="text" id="node-input-topicName" placeholder="left, for example"></div>
103
+ <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>
104
+ <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>
105
+ <div class="form-row"><label for="node-input-discoveryPrefix">Discovery prefix</label><input type="text" id="node-input-discoveryPrefix"></div>
106
+ </script>
107
+
108
+ <script type="text/html" data-help-name="home-cover-controller">
109
+ <p>Owns one position cover: a blind, shutter or curtain motor that takes and reports a position from 0 (closed) to
110
+ 100 (open). It sends a move, confirms it from what the cover reports, retries a bounded number of times, and
111
+ leaves a cover a person moved where they put it.</p>
112
+ <h3>Inputs</h3>
113
+ <dl class="message-properties">
114
+ <dt>payload</dt><dd><code>"open"</code>, <code>"close"</code> or <code>"stop"</code>; a position from 0 to 100;
115
+ or the name of one of the <b>Presets</b>. A position the cover is already at, and still, is confirmed without
116
+ a command.</dd>
117
+ <dt>stopIfMoving <span class="property-type">boolean</span></dt><dd><code>true</code> for a button: if the
118
+ cover is moving (as it reports, or while a move is unconfirmed), it stops; otherwise it does the request, such
119
+ as <code>"open"</code>.</dd>
120
+ <dt>respectManual <span class="property-type">boolean</span></dt><dd><code>true</code> for an automatic target,
121
+ such as a schedule or a position computed from the weather: it waits while a person's move holds the cover.
122
+ A request without it (a button, say) takes the cover back.</dd>
123
+ <dt>cover <span class="property-type">object</span></dt><dd>what the cover reports, as
124
+ <code>{kind: "observed", position, motion, observedAt, battery, charging}</code>, where <code>motion</code> is
125
+ <code>opening</code>, <code>closing</code> or <code>stopped</code> and <code>battery</code> and
126
+ <code>charging</code> are optional. <code>{kind: "availability", online}</code> from the device's
127
+ availability report: while it is offline nothing is sent and requests are answered <code>unavailable</code>;
128
+ when it is back, the node reads it again before trusting anything. Also <code>{kind: "startup"}</code> after a deploy (it re-reads the cover
129
+ rather than trusting old state), <code>{kind: "command_result", generation, ok}</code> from the device path,
130
+ or a full request such as <code>{kind: "set_position", requestId, generation, position}</code>.</dd>
131
+ </dl>
132
+ <h3>Outputs</h3>
133
+ <ol class="node-ports">
134
+ <li>Device commands, in a neutral shape: <code>msg.cover_command = {operation, position, requestId, generation,
135
+ attempt}</code>, where <code>operation</code> is <code>set_position</code>, <code>stop</code> or
136
+ <code>observe</code> (read the cover now). Map them to your device, as the example flow does for a
137
+ Zigbee2MQTT cover.</li>
138
+ <li>State and results: <code>msg.theatre = {kind: "target_state", target: "cover", status, details}</code>, with
139
+ the confirmed and observed positions and any failure or manual override.</li>
140
+ <li>Whether the cover is moving, <code>msg.payload</code> <code>true</code> or <code>false</code> with
141
+ <code>topic</code> <code>moving</code>, sent when it changes: from the cover's own motion reports, or, for a
142
+ device without them, while a move is unconfirmed. Wire it to other policies that should react. To pause
143
+ motion lighting while a blind moves, send it to the motion policy's <code>pause</code> input (with
144
+ <code>msg.owner</code>), as the example does, not its enable (<code>area-enabled</code>): that is the
145
+ user's own switch, and a cover move must not change it.</li>
146
+ <li>MQTT publications, when <b>Publish state</b> is on: wire it to an MQTT out node.</li>
147
+ </ol>
148
+ <h3>Publishing</h3>
149
+ <p>Off unless switched on, and then named after the <b>Area</b> and the <b>Name in topics</b>, both needed then.
150
+ The name tells this cover from others in the room and has no default, so give each cover its own. With <b>Publish state</b> it publishes, retained, the cover's
151
+ state (<code>open</code>, <code>closed</code>, <code>opening</code>, <code>closing</code> or
152
+ <code>stopped</code>) on <code>home/&lt;area&gt;/cover/&lt;name&gt;/state</code> and, for a position cover,
153
+ its position on <code>…/position</code>, once it has reported, with <code>online</code> or <code>offline</code>
154
+ on <code>…/availability</code>. It takes <code>OPEN</code>, <code>CLOSE</code> or <code>STOP</code> on
155
+ <code>…/set</code>, and a position on <code>…/position/set</code>, as requests like any other, carried out and
156
+ confirmed as above; wire an MQTT in node on <code>home/&lt;area&gt;/cover/&lt;name&gt;/+</code> (and
157
+ <code>…/position/set</code>) into this node. Nothing commands the device through Home Assistant. With
158
+ <b>Home Assistant discovery</b>, a cover entity, named after this node.</p>
159
+ <h3>Open, close and stop only</h3>
160
+ <p>For a motor with no reliable position, set <b>Cover</b> to <i>Open, close and stop only</i>. It takes
161
+ <code>"open"</code>, <code>"close"</code> and <code>"stop"</code> (positions and presets are ignored), and sends
162
+ <code>open</code>, <code>close</code>, <code>stop</code> or <code>observe</code>. Its state is open, closed,
163
+ stopped (partway) or unknown, from what it reports in
164
+ <code>msg.cover = {kind: "observed", motion, state, observedAt}</code>, where <code>state</code> is an end state
165
+ (<code>open</code> or <code>closed</code>) if the device reports one:</p>
166
+ <ul>
167
+ <li>A reported end state confirms a move.</li>
168
+ <li>Without one, a move it reported making the right way, that stopped after at least the <b>Full travel
169
+ time</b>, counts as done, shown as judged <i>by travel time</i>.</li>
170
+ <li>Stopping sooner, or moving the other way, is a person's move: the cover is left alone until a newer
171
+ request.</li>
172
+ <li>A cover that reports nothing is <i>unconfirmed</i> after its retries (failed, with reason
173
+ <code>no-reports</code>, for the theatre): nothing is assumed.</li>
174
+ </ul>
175
+ <p>Battery and charging status, when the cover reports them, are kept as facts and shown in the status; the node
176
+ never acts on them.</p>
177
+ </script>
@@ -0,0 +1,178 @@
1
+ "use strict";
2
+ const cover_models_1 = require("../lib/cover-models");
3
+ const cover_publishing_1 = require("../lib/cover-publishing");
4
+ const cover_requests_1 = require("../lib/cover-requests");
5
+ const ha_discovery_1 = require("../lib/ha-discovery");
6
+ const publishing_node_1 = require("../lib/publishing-node");
7
+ const settings_1 = require("../lib/settings");
8
+ const target_state_1 = require("../lib/target-state");
9
+ const topic_names_1 = require("../lib/topic-names");
10
+ const adapter_1 = require("./adapter");
11
+ const publishing_lifecycle_1 = require("./publishing-lifecycle");
12
+ // The cover's name in its topics, which it needs while it publishes.
13
+ function coverTopicName(value) {
14
+ const name = (0, settings_1.textSetting)(value, "name in topics");
15
+ if (!(0, topic_names_1.areaId)(name))
16
+ throw new Error("name in topics must contain a letter or digit");
17
+ return name;
18
+ }
19
+ const registerCoverController = (RED) => {
20
+ function HomeCoverController(config) {
21
+ RED.nodes.createNode(this, config);
22
+ const node = this;
23
+ const context = node.context();
24
+ let timer;
25
+ let requests = 0;
26
+ let model;
27
+ let presets;
28
+ let area;
29
+ let publishing;
30
+ try {
31
+ area = (0, adapter_1.optionalArea)(config);
32
+ // Not set: a position cover, as every cover node was before the type.
33
+ const type = (0, settings_1.optionalChoiceSetting)(config.coverType, "cover type", cover_models_1.COVER_TYPES) ?? "position";
34
+ model = type === "open-close" ? (0, cover_models_1.openCloseCover)(config) : (0, cover_models_1.positionCover)(config);
35
+ presets = (0, cover_requests_1.coverPresets)(config.presets);
36
+ // Off unless switched on, as the cover published nothing before; not
37
+ // set names its entity after the node.
38
+ const publishState = (0, settings_1.optionalBooleanSetting)(config.publishState, "publish state") ?? false;
39
+ const discovery = (0, settings_1.optionalBooleanSetting)(config.discovery, "Home Assistant discovery") ?? false;
40
+ if (publishState || discovery)
41
+ (0, topic_names_1.publishingArea)(area, true);
42
+ publishing = {
43
+ area,
44
+ // No default: two covers in a room must not share topics.
45
+ name: publishState || discovery ? coverTopicName(config.topicName) : "",
46
+ positions: model.positions,
47
+ publishState,
48
+ discovery,
49
+ discoveryPrefix: (0, ha_discovery_1.discoveryPrefixSetting)(config.discoveryPrefix),
50
+ nodeId: node.id,
51
+ idScheme: (0, settings_1.optionalChoiceSetting)(config.idScheme, "ID scheme", ha_discovery_1.ID_SCHEMES) ?? "node"
52
+ };
53
+ }
54
+ catch (error) {
55
+ (0, adapter_1.invalidConfig)(node, error);
56
+ return;
57
+ }
58
+ const trace = { area, component: "cover-controller" };
59
+ function saved() {
60
+ return context.get("state");
61
+ }
62
+ function schedule(state) {
63
+ clearTimeout(timer);
64
+ timer = undefined;
65
+ const next = model.tickAt(state);
66
+ if (!next)
67
+ return;
68
+ timer = setTimeout((0, adapter_1.guarded)(node, () => {
69
+ process({ kind: "tick", generation: next.generation }, node.send.bind(node));
70
+ }), Math.max(0, next.at - Date.now()));
71
+ }
72
+ // MQTT publications on output 4, apart from the cover's own outputs:
73
+ // available and clear of what it no longer publishes as soon as it runs,
74
+ // offline as it stops, nothing left behind when deleted.
75
+ const lifecycle = (0, publishing_lifecycle_1.publishingLifecycle)(RED, node, {
76
+ retainedTopics: () => (0, cover_publishing_1.coverRetainedTopics)(publishing),
77
+ possible: { owner: publishing, topics: () => (0, publishing_node_1.publishesState)(publishing) ? (0, cover_publishing_1.coverRetainedTopics)({ ...publishing, discovery: true }) : [] },
78
+ starting: () => (0, cover_publishing_1.coverStartingOutputs)(publishing, model.view(saved())),
79
+ stopping: () => (0, cover_publishing_1.coverStoppingOutputs)(publishing),
80
+ output: 3,
81
+ outputs: 4
82
+ });
83
+ function process(event, send) {
84
+ const wasMoving = model.moving(saved());
85
+ const viewBefore = JSON.stringify(model.view(saved()));
86
+ const result = (0, adapter_1.runReducer)(node, trace, (state, now) => model.transition(state, event, now));
87
+ const moving = result.status.moving;
88
+ // Device commands in a neutral shape on output 1, state and results
89
+ // (including the theatre's target state) on output 2, and whether the
90
+ // cover is moving on output 3, whenever that changes.
91
+ const outputs = [
92
+ result.commands.length ? result.commands.map((command) => ({ payload: { ...command }, cover_command: command })) : null,
93
+ result.events.length ? result.events.map((entry) => ({ payload: undefined, ...entry })) : null,
94
+ moving !== wasMoving ? { topic: "moving", payload: moving } : null
95
+ ];
96
+ if (outputs.some((output) => output !== null))
97
+ send(outputs);
98
+ // What Home Assistant shows, whenever it changes.
99
+ const view = model.view(result.state);
100
+ if (JSON.stringify(view) !== viewBefore)
101
+ lifecycle.publish(send, (0, cover_publishing_1.coverStateOutputs)(publishing, view));
102
+ const { phase, battery } = result.status;
103
+ node.status({
104
+ fill: phase === "failed" ? "red" : phase === "unavailable" || phase === "unconfirmed" ? "grey"
105
+ : phase === "manual_override" ? "yellow" : moving ? "blue" : "green",
106
+ shape: result.status.observed ? "dot" : "ring",
107
+ text: result.status.text + (typeof battery === "number" ? ` · battery ${battery}%` : "")
108
+ });
109
+ schedule(result.state);
110
+ return result;
111
+ }
112
+ // Context survives a redeploy but timers do not: re-observe a move in
113
+ // flight rather than trusting the old state.
114
+ if (saved()?.pending) {
115
+ timer = setTimeout((0, adapter_1.guarded)(node, () => {
116
+ process({ kind: "startup" }, node.send.bind(node));
117
+ }), 0);
118
+ }
119
+ (0, adapter_1.onInput)(node, (msg, send) => {
120
+ const cover = (0, adapter_1.objectField)(msg, "cover");
121
+ if (cover) {
122
+ if (cover.kind === "startup")
123
+ lifecycle.startup(send, (0, cover_publishing_1.coverStartingOutputs)(publishing, model.view(saved())));
124
+ process(cover, send);
125
+ return;
126
+ }
127
+ // Home Assistant's open, close, stop and set position, on the cover's
128
+ // own set topics, are requests like any other.
129
+ const inbound = (0, cover_publishing_1.coverInbound)(msg, publishing);
130
+ if (inbound && inbound.request === null) {
131
+ (0, adapter_1.runReducer)(node, trace, (state) => ({ state, traces: inbound.traces }));
132
+ return;
133
+ }
134
+ handleRequest(inbound ? { payload: inbound.request, source: "home-assistant" } : msg, send);
135
+ });
136
+ function handleRequest(msg, send) {
137
+ requests += 1;
138
+ // A cover group's own ID for its request, so it can match the answer.
139
+ // Only msg.coverRequestId is read, in the request ID format.
140
+ const callerId = typeof msg.coverRequestId === "string" && topic_names_1.REQUEST_ID.test(msg.coverRequestId) ? msg.coverRequestId : null;
141
+ const current = saved();
142
+ const request = (0, cover_requests_1.coverRequest)({ payload: msg.payload, respectManual: msg.respectManual, stopIfMoving: msg.stopIfMoving, source: msg.source }, presets, { requestId: callerId ?? `cover-${Date.now()}-${requests}`, generation: model.generation(current) + 1 }, model.moving(current));
143
+ const invalid = "invalid" in request ? request.invalid
144
+ : request.intent.kind === "set_position" && !model.positions ? "position-not-supported"
145
+ : null;
146
+ if (invalid) {
147
+ (0, adapter_1.runReducer)(node, trace, (state) => ({ state, traces: [{ event: "request", outcome: "ignored", reason: invalid, details: { payload: msg.payload } }] }));
148
+ // A caller waiting on this request hears why nothing happened.
149
+ if (callerId) {
150
+ send([null, { payload: undefined, theatre: (0, target_state_1.targetStateEvent)({
151
+ target: "cover",
152
+ requestId: callerId,
153
+ generation: model.generation(current),
154
+ status: "failed",
155
+ observedAt: new Date().toISOString(),
156
+ details: { request: msg.payload },
157
+ failure: { reason: invalid }
158
+ }) }, null]);
159
+ }
160
+ return;
161
+ }
162
+ if ("intent" in request)
163
+ process(request.intent, send);
164
+ }
165
+ node.on("close", (_removed, done) => {
166
+ clearTimeout(timer);
167
+ // Whatever it paused shouldn't wait for a move this node no longer
168
+ // follows. Best effort: it reaches nodes still running, as in a deploy
169
+ // of this node alone.
170
+ if (model.moving(saved()))
171
+ node.send([null, null, { topic: "moving", payload: false }]);
172
+ done();
173
+ });
174
+ }
175
+ RED.nodes.registerType("home-cover-controller", HomeCoverController);
176
+ };
177
+ module.exports = registerCoverController;
178
+ //# sourceMappingURL=cover-controller.js.map
@@ -0,0 +1,3 @@
1
+ import type { NodeInitializer } from "node-red";
2
+ declare const registerCoverGroup: NodeInitializer;
3
+ export = registerCoverGroup;
@@ -0,0 +1,89 @@
1
+ <script type="text/javascript">
2
+ RED.nodes.registerType("home-cover-group", {
3
+ category: "home automation",
4
+ color: "#e2d96e",
5
+ defaults: {
6
+ name: {value: ""},
7
+ area: {value: ""},
8
+ members: {value: "[\"left\",\"right\"]", required: true, validate: function (v) {
9
+ try {
10
+ var parsed = JSON.parse(v);
11
+ return Array.isArray(parsed) && parsed.length >= 2 && parsed.every(function (name) {
12
+ return typeof name === "string" && /^[a-z][a-z0-9_-]*$/.test(name);
13
+ }) && parsed.filter(function (name, index) { return parsed.indexOf(name) === index; }).length === parsed.length;
14
+ } catch (e) { return false; }
15
+ }},
16
+ deadlineSeconds: {value: 120, required: true, validate: function (v) { return RED.validators.number()(v) && Number(v) >= 1; }},
17
+ // The group's result, then one output per member (as the core switch
18
+ // node sets its outputs from its rules).
19
+ outputs: {value: 3}
20
+ },
21
+ inputs: 1,
22
+ outputs: 3,
23
+ outputLabels: function (index) {
24
+ if (index === 0) return "group result";
25
+ try { return JSON.parse(this.members)[index - 1] || ""; } catch (e) { return ""; }
26
+ },
27
+ oneditprepare: function () {
28
+ // As the core switch node does, the hidden outputs field holds a port
29
+ // map, {old port: new port, or "-1" when removed}, plus a key per new
30
+ // port, so the editor moves each member's wire with its name. Every
31
+ // kept port is listed, as the editor counts the outputs from the map.
32
+ var opened = [];
33
+ try { opened = JSON.parse(this.members); } catch (e) { opened = []; }
34
+ if (!Array.isArray(opened)) opened = [];
35
+ function portMap() {
36
+ var members;
37
+ try { members = JSON.parse($("#node-input-members").val()); } catch (e) { return; }
38
+ if (!Array.isArray(members)) return;
39
+ var map = {"0": "0"};
40
+ opened.forEach(function (name, index) {
41
+ var now = members.indexOf(name);
42
+ map[String(index + 1)] = now < 0 ? "-1" : String(now + 1);
43
+ });
44
+ members.forEach(function (name, index) {
45
+ if (opened.indexOf(name) < 0) map["new-" + name] = String(index + 1);
46
+ });
47
+ $("#node-input-outputs").val(JSON.stringify(map));
48
+ }
49
+ $("#node-input-members").on("change keyup", portMap);
50
+ portMap();
51
+ },
52
+ icon: "font-awesome/fa-columns",
53
+ label: function () { return this.name || (this.area ? this.area + " " : "") + "cover group"; }
54
+ });
55
+ </script>
56
+
57
+ <script type="text/html" data-template-name="home-cover-group">
58
+ <div class="form-row"><label for="node-input-name">Name</label><input type="text" id="node-input-name"></div>
59
+ <div class="form-row"><label for="node-input-area">Area</label><input type="text" id="node-input-area"></div>
60
+ <div class="form-row"><label for="node-input-members">Members</label><input type="text" id="node-input-members"></div>
61
+ <input type="hidden" id="node-input-outputs">
62
+ <div class="form-row"><label for="node-input-deadlineSeconds">Answer deadline (s)</label><input type="number" id="node-input-deadlineSeconds"></div>
63
+ </script>
64
+
65
+ <script type="text/html" data-help-name="home-cover-group">
66
+ <p>Moves several covers as one, such as the left and right of a curtain: one request goes to every member, and
67
+ the group says honestly how far it got.</p>
68
+ <h3>Inputs</h3>
69
+ <dl class="message-properties">
70
+ <dt>payload</dt><dd>a cover request (<code>"open"</code>, <code>"close"</code>, <code>"stop"</code>, a position or a
71
+ preset name), with <code>stopIfMoving</code> or <code>respectManual</code> if wanted. Each member gets the same
72
+ request.</dd>
73
+ <dt>theatre</dt><dd>a member's result: wire each member cover node's second output back into the group. Other
74
+ state from a cover node, and its <code>moving</code> signal, are ignored.</dd>
75
+ </dl>
76
+ <h3>Outputs</h3>
77
+ <ol class="node-ports">
78
+ <li>The group's result, <code>msg.theatre = {kind: "target_state", target: "cover", status, details}</code>:
79
+ <code>ready</code> only when every member confirms; once every member has settled with any not ready,
80
+ <code>failed</code> with reason <code>partial</code> (some confirmed) or <code>none-confirmed</code>, and
81
+ <code>details.members</code> saying what each did. A member silent at the <b>Answer deadline</b> counts as
82
+ <code>no-answer</code>, and a new request first answers the open one <code>failed</code> with reason
83
+ <code>superseded</code>.</li>
84
+ <li>Then one output per member, in the order of <b>Members</b> and labelled with its name: that member's
85
+ request, with its own <code>coverRequestId</code> (and <code>msg.topic</code> naming it). Wire each to its
86
+ cover node; no switch node is needed. A cover node answers the request even when it doesn't carry it out,
87
+ with the reason. Changing <b>Members</b> changes the number of outputs.</li>
88
+ </ol>
89
+ </script>
@@ -0,0 +1,84 @@
1
+ "use strict";
2
+ const cover_group_1 = require("../lib/cover-group");
3
+ const settings_1 = require("../lib/settings");
4
+ const adapter_1 = require("./adapter");
5
+ const registerCoverGroup = (RED) => {
6
+ function HomeCoverGroup(config) {
7
+ RED.nodes.createNode(this, config);
8
+ const node = this;
9
+ let members;
10
+ let area;
11
+ let deadlineSeconds;
12
+ try {
13
+ area = (0, adapter_1.optionalArea)(config);
14
+ members = (0, cover_group_1.coverGroupMembers)(config.members);
15
+ deadlineSeconds = Math.max(1, (0, settings_1.numberSetting)(config.deadlineSeconds, "answer deadline", cover_group_1.DEFAULT_GROUP_DEADLINE_SECONDS));
16
+ }
17
+ catch (error) {
18
+ (0, adapter_1.invalidConfig)(node, error);
19
+ return;
20
+ }
21
+ const trace = { area, component: "cover-group" };
22
+ let timer;
23
+ function process(event, send) {
24
+ const result = (0, adapter_1.runReducer)(node, trace, (saved, now) => (0, cover_group_1.transitionCoverGroup)(saved, event, members, now, deadlineSeconds));
25
+ // The group's result on output 1, then one output per member, in the
26
+ // order of Members, each with that member's request (msg.topic still
27
+ // names it).
28
+ const outputs = [
29
+ result.events.length ? result.events.map((entry) => ({ payload: undefined, ...entry })) : null,
30
+ ...members.map((member) => {
31
+ const request = result.commands.filter((command) => command.topic === member);
32
+ return request.length ? request.map((command) => ({ ...command })) : null;
33
+ })
34
+ ];
35
+ if (outputs.some((output) => output !== null))
36
+ send(outputs);
37
+ node.status({
38
+ fill: result.status.total && result.status.ready === result.status.total ? "green" : "blue",
39
+ shape: "dot",
40
+ text: result.status.text
41
+ });
42
+ // At the deadline, members that never answered count as not answering.
43
+ clearTimeout(timer);
44
+ timer = undefined;
45
+ const request = result.state.request;
46
+ if (request && !request.settled) {
47
+ timer = setTimeout((0, adapter_1.guarded)(node, () => process({ kind: "tick" }, node.send.bind(node))), Math.max(0, request.deadlineAt - Date.now()));
48
+ }
49
+ }
50
+ // Context survives a redeploy but timers do not: re-arm the deadline of
51
+ // a request still open (an overdue one settles at the first tick).
52
+ const open = node.context().get("state")?.request;
53
+ if (open && !open.settled && Number.isFinite(open.deadlineAt)) {
54
+ timer = setTimeout((0, adapter_1.guarded)(node, () => process({ kind: "tick" }, node.send.bind(node))), Math.max(0, open.deadlineAt - Date.now()));
55
+ }
56
+ (0, adapter_1.onInput)(node, (msg, send) => {
57
+ const theatre = (0, adapter_1.objectField)(msg, "theatre");
58
+ // A member's answer, from its cover node's second output. Anything else
59
+ // a cover node sends (other state, its moving signal) is not a request.
60
+ if (theatre?.kind === "target_state" && typeof theatre.requestId === "string") {
61
+ process({ kind: "member", requestId: theatre.requestId, status: String(theatre.status), classification: theatre.classification, reason: theatre.failure?.reason ?? null }, send);
62
+ return;
63
+ }
64
+ if (theatre || msg.topic === "moving") {
65
+ (0, adapter_1.runReducer)(node, trace, (state) => ({ state, traces: [{ event: "input", outcome: "ignored", reason: theatre ? "not-a-member-answer" : "moving-signal", details: {} }] }));
66
+ return;
67
+ }
68
+ process({
69
+ kind: "request",
70
+ payload: msg.payload,
71
+ stopIfMoving: msg.stopIfMoving === true,
72
+ respectManual: msg.respectManual === true,
73
+ source: typeof msg.source === "string" ? msg.source : undefined
74
+ }, send);
75
+ });
76
+ node.on("close", (_removed, done) => {
77
+ clearTimeout(timer);
78
+ done();
79
+ });
80
+ }
81
+ RED.nodes.registerType("home-cover-group", HomeCoverGroup);
82
+ };
83
+ module.exports = registerCoverGroup;
84
+ //# sourceMappingURL=cover-group.js.map
@@ -0,0 +1,4 @@
1
+ import type { NodeAPI } from "node-red";
2
+ type Events = NodeAPI["events"];
3
+ export declare function onFlowsStarted(events: Events, callback: () => void, report: (error: unknown) => void): () => void;
4
+ export {};
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.onFlowsStarted = onFlowsStarted;
4
+ const callbacks = new WeakMap();
5
+ // Calls `callback` every time the flows start, until the returned function
6
+ // is called. Callbacks run in the order they were added; one added or
7
+ // removed while they run takes effect from the next start. Each runs on its
8
+ // own: an error goes to `report` (the registering node's error), so it can
9
+ // neither stop the others nor escape Node-RED's emit of "flows:started".
10
+ function onFlowsStarted(events, callback, report) {
11
+ let waiting = callbacks.get(events);
12
+ if (!waiting) {
13
+ const created = new Set();
14
+ waiting = created;
15
+ callbacks.set(events, created);
16
+ events.on("flows:started", () => {
17
+ for (const run of [...created])
18
+ run();
19
+ });
20
+ }
21
+ const own = () => {
22
+ try {
23
+ callback();
24
+ }
25
+ catch (error) {
26
+ try {
27
+ report(error);
28
+ }
29
+ catch {
30
+ // Reporting failed too: nothing more can be done here.
31
+ }
32
+ }
33
+ };
34
+ waiting.add(own);
35
+ return () => {
36
+ waiting.delete(own);
37
+ };
38
+ }
39
+ //# sourceMappingURL=flows-started.js.map
@@ -0,0 +1,3 @@
1
+ import type { NodeInitializer } from "node-red";
2
+ declare const registerHouseScheduleMqtt: NodeInitializer;
3
+ export = registerHouseScheduleMqtt;