@avantics/node-red-home-automation 3.0.0 → 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 (110) hide show
  1. package/README.md +285 -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/command-echo.d.ts +2 -0
  15. package/dist/lib/command-echo.js +39 -15
  16. package/dist/lib/cover-availability.d.ts +7 -0
  17. package/dist/lib/cover-availability.js +24 -0
  18. package/dist/lib/cover-controller.d.ts +13 -1
  19. package/dist/lib/cover-controller.js +113 -30
  20. package/dist/lib/cover-group.d.ts +62 -0
  21. package/dist/lib/cover-group.js +125 -0
  22. package/dist/lib/cover-models.d.ts +37 -0
  23. package/dist/lib/cover-models.js +83 -0
  24. package/dist/lib/cover-publishing.d.ts +40 -0
  25. package/dist/lib/cover-publishing.js +102 -0
  26. package/dist/lib/cover-requests.d.ts +21 -0
  27. package/dist/lib/cover-requests.js +49 -0
  28. package/dist/lib/display-mode-controller.d.ts +4 -0
  29. package/dist/lib/display-mode-controller.js +26 -2
  30. package/dist/lib/ha-discovery.d.ts +27 -0
  31. package/dist/lib/ha-discovery.js +91 -0
  32. package/dist/lib/house-schedule-publishing.d.ts +23 -0
  33. package/dist/lib/house-schedule-publishing.js +71 -0
  34. package/dist/lib/house-schedule.d.ts +23 -0
  35. package/dist/lib/house-schedule.js +29 -0
  36. package/dist/lib/motion-policy.d.ts +9 -0
  37. package/dist/lib/motion-policy.js +45 -11
  38. package/dist/lib/motion-publishing.d.ts +28 -0
  39. package/dist/lib/motion-publishing.js +92 -0
  40. package/dist/lib/occupancy-publishing.d.ts +10 -0
  41. package/dist/lib/occupancy-publishing.js +45 -0
  42. package/dist/lib/open-close-cover.d.ts +92 -0
  43. package/dist/lib/open-close-cover.js +287 -0
  44. package/dist/lib/publishing-node.d.ts +39 -0
  45. package/dist/lib/publishing-node.js +72 -0
  46. package/dist/lib/retained-topics.d.ts +10 -0
  47. package/dist/lib/retained-topics.js +19 -0
  48. package/dist/lib/room-controller.d.ts +10 -0
  49. package/dist/lib/room-controller.js +68 -59
  50. package/dist/lib/room-lighting-discovery.d.ts +20 -1
  51. package/dist/lib/room-lighting-discovery.js +135 -13
  52. package/dist/lib/room-publishing.d.ts +42 -0
  53. package/dist/lib/room-publishing.js +182 -0
  54. package/dist/lib/room-schedule.d.ts +8 -0
  55. package/dist/lib/room-schedule.js +41 -0
  56. package/dist/lib/settings.d.ts +2 -0
  57. package/dist/lib/settings.js +20 -0
  58. package/dist/lib/source-capability-controller.d.ts +8 -1
  59. package/dist/lib/source-capability-controller.js +29 -3
  60. package/dist/lib/theatre-activity-controller.d.ts +0 -1
  61. package/dist/lib/theatre-activity-controller.js +27 -24
  62. package/dist/lib/theatre-ha-discovery.d.ts +3 -4
  63. package/dist/lib/theatre-ha-discovery.js +46 -36
  64. package/dist/lib/theatre-state-contract.d.ts +6 -0
  65. package/dist/lib/theatre-state-contract.js +83 -47
  66. package/dist/lib/theatre-state.d.ts +1 -1
  67. package/dist/lib/theatre-state.js +1 -1
  68. package/dist/lib/topic-names.d.ts +4 -0
  69. package/dist/lib/topic-names.js +31 -0
  70. package/dist/nodes/activity-lighting-controller.js +5 -3
  71. package/dist/nodes/adapter.d.ts +6 -1
  72. package/dist/nodes/adapter.js +65 -1
  73. package/dist/nodes/avr-controller.html +59 -5
  74. package/dist/nodes/avr-controller.js +74 -4
  75. package/dist/nodes/backlighting-controller.js +5 -3
  76. package/dist/nodes/cover-controller.d.ts +3 -0
  77. package/dist/nodes/cover-controller.html +177 -0
  78. package/dist/nodes/cover-controller.js +178 -0
  79. package/dist/nodes/cover-group.d.ts +3 -0
  80. package/dist/nodes/cover-group.html +89 -0
  81. package/dist/nodes/cover-group.js +84 -0
  82. package/dist/nodes/flows-started.d.ts +4 -0
  83. package/dist/nodes/flows-started.js +39 -0
  84. package/dist/nodes/house-schedule-mqtt.d.ts +3 -0
  85. package/dist/nodes/house-schedule-mqtt.html +61 -0
  86. package/dist/nodes/house-schedule-mqtt.js +80 -0
  87. package/dist/nodes/house-schedule.d.ts +3 -0
  88. package/dist/nodes/house-schedule.html +31 -0
  89. package/dist/nodes/house-schedule.js +51 -0
  90. package/dist/nodes/motion-policy.html +81 -5
  91. package/dist/nodes/motion-policy.js +69 -8
  92. package/dist/nodes/occupancy-fusion.html +69 -14
  93. package/dist/nodes/occupancy-fusion.js +46 -4
  94. package/dist/nodes/publishing-lifecycle.d.ts +25 -0
  95. package/dist/nodes/publishing-lifecycle.js +38 -0
  96. package/dist/nodes/room-controller.html +54 -5
  97. package/dist/nodes/room-controller.js +67 -8
  98. package/dist/nodes/shared-schedule.d.ts +6 -0
  99. package/dist/nodes/shared-schedule.js +15 -0
  100. package/dist/nodes/source-capability-controller.js +5 -3
  101. package/dist/nodes/theatre-activity-controller.html +1 -3
  102. package/dist/nodes/theatre-activity-controller.js +1 -2
  103. package/dist/nodes/theatre-state-contract.html +28 -5
  104. package/dist/nodes/theatre-state-contract.js +22 -4
  105. package/examples/Cover control.json +380 -0
  106. package/examples/Cover pair.json +230 -0
  107. package/examples/Home theatre activity.json +4 -4
  108. package/examples/House schedule.json +164 -0
  109. package/examples/Room lighting.json +4 -3
  110. package/package.json +6 -2
@@ -1,22 +1,57 @@
1
1
  <script type="text/javascript">
2
+ (function () {
3
+ function on(value) { return value === true || value === "true"; }
2
4
  RED.nodes.registerType("home-avr-controller", {
3
5
  category: "home automation",
4
6
  color: "#c7d9f1",
5
7
  defaults: {
6
- name: {value: ""},
7
- area: {value: ""},
8
+ // A marker only a node new from the palette has, as core nodes do: import
9
+ // and paste keep the saved name, so onadd leaves a saved node's settings.
10
+ name: {value: "_DEFAULT_"},
11
+ // Required only when the node publishes, and then with a letter or
12
+ // 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
+ }},
8
17
  sources: {value: "{\"shield\":\"SAT/CBL\",\"playstation\":\"GAME\"}", required: true, validate: function (v) { try { JSON.parse(v); return true; } catch (e) { return false; } }},
9
18
  retryMs: {value: 2000, required: true, validate: RED.validators.number()},
10
19
  maxAttempts: {value: 3, required: true, validate: RED.validators.number()},
11
20
  minVolume: {value: 0, required: true, validate: RED.validators.number()},
12
- maxVolume: {value: 60, required: true, validate: RED.validators.number()}
21
+ maxVolume: {value: 60, required: true, validate: RED.validators.number()},
22
+ // The receiver published nothing before these settings, so both start off.
23
+ publishState: {value: false},
24
+ discovery: {value: false},
25
+ discoveryPrefix: {value: "homeassistant", required: true, validate: function (v) { var prefix = String(v || "").trim().replace(/^\/+|\/+$/g, ""); return Boolean(prefix) && !/[+#]/.test(prefix); }},
26
+ // How Home Assistant IDs are named; the receiver has no older entities,
27
+ // so not set also means "node".
28
+ idScheme: {value: null}
29
+ },
30
+ onadd: function () {
31
+ if (this.name !== "_DEFAULT_") return;
32
+ this.name = "";
33
+ this.idScheme = "node";
34
+ },
35
+ oneditprepare: function () {
36
+ $("#node-input-publishState").prop("checked", on(this.publishState));
37
+ $("#node-input-discovery").prop("checked", on(this.discovery));
38
+ // Discovery describes the published state, so it needs it.
39
+ function follow() {
40
+ var publishing = $("#node-input-publishState").prop("checked");
41
+ if (!publishing) $("#node-input-discovery").prop("checked", false);
42
+ $("#node-input-discovery").prop("disabled", !publishing);
43
+ $("#node-input-area").trigger("change");
44
+ }
45
+ $("#node-input-publishState, #node-input-discovery").on("change", follow);
46
+ follow();
13
47
  },
14
48
  inputs: 1,
15
- outputs: 2,
16
- outputLabels: ["Denon commands", "state and results"],
49
+ outputs: 3,
50
+ outputLabels: ["Denon commands", "state and results", "MQTT publications"],
17
51
  icon: "font-awesome/fa-volume-up",
18
52
  label: function () { return this.name || (this.area ? this.area + " " : "") + "AVR controller"; }
19
53
  });
54
+ })();
20
55
  </script>
21
56
 
22
57
  <script type="text/html" data-template-name="home-avr-controller">
@@ -27,6 +62,9 @@
27
62
  <div class="form-row"><label for="node-input-maxAttempts">Maximum attempts</label><input type="number" id="node-input-maxAttempts"></div>
28
63
  <div class="form-row"><label for="node-input-minVolume">Minimum volume</label><input type="number" step="0.5" id="node-input-minVolume"></div>
29
64
  <div class="form-row"><label for="node-input-maxVolume">Maximum volume</label><input type="number" step="0.5" id="node-input-maxVolume"></div>
65
+ <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>
66
+ <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>
67
+ <div class="form-row"><label for="node-input-discoveryPrefix">Discovery prefix</label><input type="text" id="node-input-discoveryPrefix"></div>
30
68
  </script>
31
69
 
32
70
  <script type="text/html" data-help-name="home-avr-controller">
@@ -44,4 +82,20 @@
44
82
  <dt>volume_manual_override</dt><dd><code>{kind, area, requestId, reason, observed, target}</code>: the receiver moved elsewhere while the request was in flight.</dd>
45
83
  <dt>volume_external</dt><dd><code>{kind, area, previous, observed}</code>: a change made outside any request.</dd>
46
84
  </dl>
85
+ <h3>Publishing</h3>
86
+ <p>Off unless switched on, and then named after the <b>Area</b>, which is needed.</p>
87
+ <dl class="message-properties">
88
+ <dt>Publish state over MQTT</dt><dd>what the receiver reports, retained, whenever it changes:
89
+ <code>home/&lt;area&gt;/receiver/power/state</code> (<code>ON</code> or <code>OFF</code>),
90
+ <code>…/source/state</code> (the source name) and <code>…/volume/state</code>, with <code>online</code> or
91
+ <code>offline</code> on <code>…/availability</code>.</dd>
92
+ <dt>Home Assistant discovery</dt><dd>power and source sensors, and a volume number between <b>Minimum volume</b>
93
+ and <b>Maximum volume</b>. It needs <b>Publish state</b>. A volume set there arrives on
94
+ <code>…/volume/set</code>; wire an MQTT in node on that topic into this node. Sets arriving within 0.3 seconds
95
+ of each other (a slider, repeated taps) are settled to the last one, which becomes an ordinary absolute
96
+ volume request, bounded and confirmed like any other: it waits for a power or source change in progress (such
97
+ as a theatre activity's), and is rejected with <code>receiver-not-ready</code> while the receiver is off.</dd>
98
+ </dl>
99
+ <p>These go on the third output; wire it to an MQTT out node. The node announces itself once the flows have
100
+ started, and again at <code>kind: "startup"</code>.</p>
47
101
  </script>
@@ -2,6 +2,11 @@
2
2
  const avr_controller_1 = require("../lib/avr-controller");
3
3
  const adapter_1 = require("./adapter");
4
4
  const settings_1 = require("../lib/settings");
5
+ const avr_publishing_1 = require("../lib/avr-publishing");
6
+ const ha_discovery_1 = require("../lib/ha-discovery");
7
+ const topic_names_1 = require("../lib/topic-names");
8
+ const publishing_node_1 = require("../lib/publishing-node");
9
+ const publishing_lifecycle_1 = require("./publishing-lifecycle");
5
10
  function parseSources(value) {
6
11
  const sources = (0, settings_1.jsonSetting)(value, "sources", {});
7
12
  if (!sources || Array.isArray(sources) || typeof sources !== "object") {
@@ -16,10 +21,28 @@ const registerAvrController = (RED) => {
16
21
  const context = node.context();
17
22
  let retryTimer;
18
23
  let controllerConfig;
24
+ let publishing;
19
25
  try {
20
26
  // The same validation the reducer applies, so a bad configuration
21
27
  // fails here at deploy rather than on every message.
22
28
  controllerConfig = (0, avr_controller_1.normaliseAvrConfig)({ ...config, area: (0, adapter_1.optionalArea)(config), sources: parseSources(config.sources) });
29
+ // Off unless switched on, as the receiver published nothing before;
30
+ // there are no older entities to keep, so not set names them after
31
+ // the node.
32
+ const publishState = (0, settings_1.optionalBooleanSetting)(config.publishState, "publish state") ?? false;
33
+ const discovery = (0, settings_1.optionalBooleanSetting)(config.discovery, "Home Assistant discovery") ?? false;
34
+ if (publishState || discovery)
35
+ (0, topic_names_1.publishingArea)(controllerConfig.area, true);
36
+ publishing = {
37
+ area: controllerConfig.area,
38
+ publishState,
39
+ discovery,
40
+ discoveryPrefix: (0, ha_discovery_1.discoveryPrefixSetting)(config.discoveryPrefix),
41
+ nodeId: node.id,
42
+ idScheme: (0, settings_1.optionalChoiceSetting)(config.idScheme, "ID scheme", ha_discovery_1.ID_SCHEMES) ?? "node",
43
+ minVolume: controllerConfig.minVolume,
44
+ maxVolume: controllerConfig.maxVolume
45
+ };
23
46
  }
24
47
  catch (error) {
25
48
  (0, adapter_1.invalidConfig)(node, error);
@@ -47,7 +70,23 @@ const registerAvrController = (RED) => {
47
70
  process({ avr: { kind: "tick" } }, node.send.bind(node));
48
71
  }), delay);
49
72
  }
73
+ function observed() {
74
+ return context.get("state")?.observed;
75
+ }
76
+ // MQTT publications go on the third output, apart from the receiver's
77
+ // commands and the theatre's events. Available, and clear of what it no
78
+ // longer publishes, as soon as it runs; offline as it stops; nothing
79
+ // left behind when deleted.
80
+ const lifecycle = (0, publishing_lifecycle_1.publishingLifecycle)(RED, node, {
81
+ retainedTopics: () => (0, avr_publishing_1.avrRetainedTopics)(publishing),
82
+ possible: { owner: publishing, topics: () => (0, publishing_node_1.publishesState)(publishing) ? (0, avr_publishing_1.avrRetainedTopics)({ ...publishing, publishState: true, discovery: true }) : [] },
83
+ starting: () => (0, avr_publishing_1.avrStartingOutputs)(publishing, observed()),
84
+ stopping: () => (0, avr_publishing_1.avrStoppingOutputs)(publishing),
85
+ output: 2,
86
+ outputs: 3
87
+ });
50
88
  function process(msg, send) {
89
+ const before = observed();
51
90
  const result = (0, adapter_1.runReducer)(node, { area: controllerConfig.area, component: "avr-controller" }, (saved, now) => (0, avr_controller_1.transitionAvr)(saved, msg, controllerConfig, now));
52
91
  const commands = result.commands.map((command) => ({
53
92
  payload: Buffer.from(command.payload, "utf8"),
@@ -59,22 +98,52 @@ const registerAvrController = (RED) => {
59
98
  commands.length ? commands : null,
60
99
  outputs.length
61
100
  ? outputs.map((event) => ({ payload: undefined, ...event }))
62
- : null
101
+ : null,
102
+ null
63
103
  ]);
64
104
  }
105
+ // Whatever it now observes differently from before.
106
+ lifecycle.publish(send, (0, avr_publishing_1.avrStateOutputs)(publishing, result.state.observed, before ?? {}));
65
107
  updateStatus(result.status);
66
108
  scheduleRetry(result.state);
67
109
  return result;
68
110
  }
69
- // Context survives a redeploy but timers do not. Recover a pending
70
- // transition with the reducer's own startup (re-observe, never replay)
71
- // rather than ticking old state; a later startup from the flow repeats it.
111
+ // A pending transition is here only if the node's context survived its
112
+ // stop, which needs a configured context store (see the README); timers
113
+ // never survive. Recover it with the reducer's own startup (re-observe,
114
+ // never replay) rather than ticking old state; a later startup from the
115
+ // flow repeats it.
72
116
  if (context.get("state")?.pending) {
73
117
  retryTimer = setTimeout((0, adapter_1.guarded)(node, () => {
74
118
  process({ avr: { kind: "startup" } }, node.send.bind(node));
75
119
  }), 0);
76
120
  }
121
+ // Each request from the volume number gets its own ID, as the receiver
122
+ // answers a repeated ID only once. Sets arriving in a burst are settled
123
+ // to the last one first.
124
+ let volumeRequests = 0;
125
+ let volumeSetTimer;
126
+ function requestVolume(value) {
127
+ volumeRequests += 1;
128
+ process({ avr: { kind: "volume", requestId: `mqtt-volume-${Date.now()}-${volumeRequests}`, mode: "absolute", value } }, node.send.bind(node));
129
+ }
77
130
  (0, adapter_1.onInput)(node, (msg, send) => {
131
+ const volume = (0, avr_publishing_1.avrVolumeRequest)(msg, publishing);
132
+ if (volume && "ignored" in volume) {
133
+ (0, adapter_1.runReducer)(node, { area: controllerConfig.area, component: "avr-controller" }, (saved) => ({ state: saved, traces: [{ event: "volume-set", outcome: "ignored", reason: volume.ignored, details: { payload: volume.payload } }] }));
134
+ return;
135
+ }
136
+ if (volume) {
137
+ clearTimeout(volumeSetTimer);
138
+ volumeSetTimer = setTimeout((0, adapter_1.guarded)(node, () => {
139
+ volumeSetTimer = undefined;
140
+ requestVolume(volume.value);
141
+ }), avr_publishing_1.VOLUME_SET_SETTLE_MS);
142
+ return;
143
+ }
144
+ if ((0, adapter_1.objectField)(msg, "avr")?.kind === "startup") {
145
+ lifecycle.startup(send, (0, avr_publishing_1.avrStartingOutputs)(publishing, observed()));
146
+ }
78
147
  process({
79
148
  avr: (0, adapter_1.objectField)(msg, "avr"),
80
149
  payload: msg.payload
@@ -82,6 +151,7 @@ const registerAvrController = (RED) => {
82
151
  });
83
152
  node.on("close", (_removed, done) => {
84
153
  clearTimeout(retryTimer);
154
+ clearTimeout(volumeSetTimer);
85
155
  done();
86
156
  });
87
157
  }
@@ -57,9 +57,11 @@ const registerBacklightingController = (RED) => {
57
57
  schedule(result.state);
58
58
  return result;
59
59
  }
60
- // Context survives a redeploy but timers do not. Recover a pending
61
- // transition with the reducer's own startup (re-observe, never replay)
62
- // rather than ticking old state; a later startup from the flow repeats it.
60
+ // A pending transition is here only if the node's context survived its
61
+ // stop, which needs a configured context store (see the README); timers
62
+ // never survive. Recover it with the reducer's own startup (re-observe,
63
+ // never replay) rather than ticking old state; a later startup from the
64
+ // flow repeats it.
63
65
  if (context.get("state")?.pending) {
64
66
  timer = setTimeout((0, adapter_1.guarded)(node, () => {
65
67
  process({ backlighting: { kind: "startup" } }, node.send.bind(node));
@@ -0,0 +1,3 @@
1
+ import type { NodeInitializer } from "node-red";
2
+ declare const registerCoverController: NodeInitializer;
3
+ export = registerCoverController;
@@ -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;