@avantics/node-red-home-automation 6.1.0 → 6.3.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 (115) hide show
  1. package/README.md +260 -46
  2. package/dist/lib/activity-lighting-controller.d.ts +1 -0
  3. package/dist/lib/activity-lighting-controller.js +37 -10
  4. package/dist/lib/avr-controller.d.ts +3 -0
  5. package/dist/lib/avr-controller.js +24 -2
  6. package/dist/lib/backlighting-controller.d.ts +5 -2
  7. package/dist/lib/backlighting-controller.js +27 -2
  8. package/dist/lib/cover-publishing.js +20 -6
  9. package/dist/lib/display-mode-controller.d.ts +3 -0
  10. package/dist/lib/display-mode-controller.js +43 -16
  11. package/dist/lib/esphome-sensor.d.ts +73 -0
  12. package/dist/lib/esphome-sensor.js +261 -0
  13. package/dist/lib/home-assistant-setting.d.ts +23 -0
  14. package/dist/lib/home-assistant-setting.js +39 -0
  15. package/dist/lib/motion-policy.d.ts +1 -0
  16. package/dist/lib/motion-policy.js +21 -1
  17. package/dist/lib/occupancy-fusion.d.ts +1 -0
  18. package/dist/lib/occupancy-fusion.js +15 -2
  19. package/dist/lib/room-controller.d.ts +1 -0
  20. package/dist/lib/room-controller.js +5 -0
  21. package/dist/lib/room-publishing.d.ts +1 -0
  22. package/dist/lib/room-publishing.js +11 -0
  23. package/dist/lib/scene-publishing.d.ts +30 -0
  24. package/dist/lib/scene-publishing.js +63 -0
  25. package/dist/lib/scene.d.ts +69 -0
  26. package/dist/lib/scene.js +223 -0
  27. package/dist/lib/shelly-cover.js +5 -0
  28. package/dist/lib/shelly-relay-light.d.ts +24 -0
  29. package/dist/lib/shelly-relay-light.js +93 -0
  30. package/dist/lib/shelly-switch.d.ts +8 -0
  31. package/dist/lib/shelly-switch.js +37 -8
  32. package/dist/lib/source-capability-controller.d.ts +4 -1
  33. package/dist/lib/source-capability-controller.js +49 -2
  34. package/dist/lib/target-observation.d.ts +14 -0
  35. package/dist/lib/target-observation.js +22 -0
  36. package/dist/lib/theatre-activity-controller.d.ts +5 -0
  37. package/dist/lib/theatre-activity-controller.js +91 -12
  38. package/dist/lib/theatre-metrics.js +6 -4
  39. package/dist/lib/theatre-slo.js +3 -0
  40. package/dist/lib/theatre-state-contract.d.ts +4 -2
  41. package/dist/lib/theatre-state-contract.js +51 -8
  42. package/dist/lib/theatre-state.d.ts +2 -0
  43. package/dist/lib/theatre-state.js +13 -1
  44. package/dist/lib/wled.d.ts +48 -0
  45. package/dist/lib/wled.js +105 -0
  46. package/dist/lib/z2m-power.d.ts +38 -0
  47. package/dist/lib/z2m-power.js +83 -0
  48. package/dist/lib/z2m-sensor.d.ts +37 -0
  49. package/dist/lib/z2m-sensor.js +88 -0
  50. package/dist/nodes/apollo-r-pro-1.d.ts +2 -0
  51. package/dist/nodes/apollo-r-pro-1.html +80 -0
  52. package/dist/nodes/apollo-r-pro-1.js +4 -0
  53. package/dist/nodes/avr-controller.html +82 -21
  54. package/dist/nodes/avr-controller.js +24 -12
  55. package/dist/nodes/backlighting-controller.js +3 -2
  56. package/dist/nodes/circadian-policy.html +84 -20
  57. package/dist/nodes/circadian-policy.js +30 -11
  58. package/dist/nodes/cover-controller.html +87 -25
  59. package/dist/nodes/cover-controller.js +25 -12
  60. package/dist/nodes/device-side.d.ts +21 -0
  61. package/dist/nodes/device-side.js +76 -0
  62. package/dist/nodes/display-mode-controller.js +11 -2
  63. package/dist/nodes/esphome-sensor.d.ts +2 -0
  64. package/dist/nodes/esphome-sensor.js +77 -0
  65. package/dist/nodes/everything-presence-one.d.ts +2 -0
  66. package/dist/nodes/everything-presence-one.html +78 -0
  67. package/dist/nodes/everything-presence-one.js +4 -0
  68. package/dist/nodes/home-assistant-discovery.d.ts +26 -0
  69. package/dist/nodes/home-assistant-discovery.js +64 -0
  70. package/dist/nodes/house-schedule-mqtt.html +70 -5
  71. package/dist/nodes/house-schedule-mqtt.js +22 -8
  72. package/dist/nodes/motion-policy.html +87 -22
  73. package/dist/nodes/motion-policy.js +44 -11
  74. package/dist/nodes/mqtt-broker-link.d.ts +41 -0
  75. package/dist/nodes/mqtt-broker-link.js +91 -0
  76. package/dist/nodes/occupancy-fusion.html +86 -20
  77. package/dist/nodes/occupancy-fusion.js +25 -12
  78. package/dist/nodes/publishing-side.d.ts +20 -0
  79. package/dist/nodes/publishing-side.js +66 -0
  80. package/dist/nodes/room-controller.html +106 -35
  81. package/dist/nodes/room-controller.js +63 -16
  82. package/dist/nodes/scene.d.ts +3 -0
  83. package/dist/nodes/scene.html +247 -0
  84. package/dist/nodes/scene.js +128 -0
  85. package/dist/nodes/shelly-cover.html +47 -2
  86. package/dist/nodes/shelly-cover.js +19 -4
  87. package/dist/nodes/shelly-switch.html +76 -6
  88. package/dist/nodes/shelly-switch.js +32 -7
  89. package/dist/nodes/source-capability-controller.js +3 -2
  90. package/dist/nodes/theatre-activity-controller.html +4 -2
  91. package/dist/nodes/theatre-state-contract.html +72 -9
  92. package/dist/nodes/theatre-state-contract.js +33 -14
  93. package/dist/nodes/wled.d.ts +3 -0
  94. package/dist/nodes/wled.html +56 -0
  95. package/dist/nodes/wled.js +53 -0
  96. package/dist/nodes/z2m-cover.html +47 -2
  97. package/dist/nodes/z2m-cover.js +21 -4
  98. package/dist/nodes/z2m-light.html +49 -3
  99. package/dist/nodes/z2m-light.js +40 -4
  100. package/dist/nodes/z2m-power.d.ts +3 -0
  101. package/dist/nodes/z2m-power.html +58 -0
  102. package/dist/nodes/z2m-power.js +53 -0
  103. package/dist/nodes/z2m-sensor.d.ts +3 -0
  104. package/dist/nodes/z2m-sensor.html +69 -0
  105. package/dist/nodes/z2m-sensor.js +62 -0
  106. package/examples/Cover control.json +38 -91
  107. package/examples/Cover pair.json +36 -3
  108. package/examples/Home theatre activity.json +46 -91
  109. package/examples/Home theatre equipment.json +34 -2
  110. package/examples/House schedule.json +58 -80
  111. package/examples/Room lighting.json +45 -44
  112. package/examples/Scene.json +167 -0
  113. package/examples/Shelly cover.json +36 -105
  114. package/examples/Shelly switch.json +52 -148
  115. package/package.json +8 -2
@@ -68,7 +68,9 @@ const registerDisplayModeController = (RED) => {
68
68
  return;
69
69
  }
70
70
  if (command.device === "projector" && command.operation === "query_power" && !projectorPowerMeterHost) {
71
- node.send([null, null, { payload: "query", display_command: command }]);
71
+ // power: {kind: "read"} too, so a power meter node (such as a
72
+ // zigbee2mqtt power node) can be wired straight to it.
73
+ node.send([null, null, { payload: "query", display_command: command, power: { kind: "read" } }]);
72
74
  return;
73
75
  }
74
76
  const result = await transport.execute(command);
@@ -77,7 +79,7 @@ const registerDisplayModeController = (RED) => {
77
79
  }
78
80
  function process(msg, send) {
79
81
  const result = (0, adapter_1.runReducer)(node, { area: (0, adapter_1.optionalArea)(config), component: "display-mode-controller" }, (saved, now) => (0, display_mode_controller_1.transitionDisplay)(saved, msg, controllerConfig, now));
80
- const outputs = [...result.events, ...result.targetStates];
82
+ const outputs = [...result.events, ...result.targetStates, ...result.observations];
81
83
  if (outputs.length) {
82
84
  send([null, outputs.map((event) => ({ payload: undefined, ...event })), null]);
83
85
  }
@@ -89,6 +91,13 @@ const registerDisplayModeController = (RED) => {
89
91
  return result;
90
92
  }
91
93
  (0, adapter_1.onInput)(node, (msg, send) => {
94
+ // A power meter node's reading (msg.power) is its projector's power.
95
+ const power = (0, adapter_1.objectField)(msg, "power");
96
+ if (power?.kind === "observed" && !(0, adapter_1.objectField)(msg, "display")) {
97
+ process({ display: { kind: "observed", device: "projector", watts: power.watts,
98
+ ...(typeof power.observedAt === "string" ? { observedAt: power.observedAt } : {}) } }, send);
99
+ return;
100
+ }
92
101
  process({
93
102
  display: (0, adapter_1.objectField)(msg, "display")
94
103
  }, send);
@@ -0,0 +1,2 @@
1
+ import type { NodeInitializer } from "node-red";
2
+ export declare function esphomeSensorNode(type: string, model: string): NodeInitializer;
@@ -0,0 +1,77 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.esphomeSensorNode = esphomeSensorNode;
4
+ const esphome_sensor_1 = require("../lib/esphome-sensor");
5
+ const adapter_1 = require("./adapter");
6
+ const device_side_1 = require("./device-side");
7
+ // One node type per ESPHome device: its entity names belong to its
8
+ // product's firmware, so the model is the node's, not a setting. Each
9
+ // device's node registers this with its model (see ESPHOME_MODELS).
10
+ function esphomeSensorNode(type, model) {
11
+ return (RED) => {
12
+ function HomeEsphomeSensor(config) {
13
+ RED.nodes.createNode(this, config);
14
+ const node = this;
15
+ let device;
16
+ let broker;
17
+ try {
18
+ device = (0, esphome_sensor_1.normaliseEsphomeSensorConfig)({ device: config.device, model, discoveryPrefix: config.discoveryPrefix });
19
+ // Newer than the MQTT in and out way of wiring adapters: it needs its
20
+ // broker.
21
+ broker = (0, device_side_1.deviceBroker)(RED, config.broker);
22
+ if (!broker)
23
+ throw new Error("choose its MQTT broker");
24
+ }
25
+ catch (error) {
26
+ (0, adapter_1.invalidConfig)(node, error);
27
+ return;
28
+ }
29
+ const trace = { area: "", component: "esphome-sensor" };
30
+ node.status({ fill: "grey", shape: "ring", text: "waiting for the device" });
31
+ // Its discovery, its status and its preset's entities; then whatever its
32
+ // discovery names. ESPHome retains them, so on connect the broker hands
33
+ // over the device's description and current state, which passes as a
34
+ // baseline while the device is online.
35
+ const topics = (0, esphome_sensor_1.esphomeSensorTopics)(device);
36
+ const subscribed = new Set(topics.initial);
37
+ const side = (0, device_side_1.deviceSide)(node, broker, device.device, topics.initial, trace, (msg, send) => handle(msg, send));
38
+ function handle(msg, send) {
39
+ const result = (0, adapter_1.runReducer)(node, trace, (saved) => (0, esphome_sensor_1.transitionEsphomeSensor)(saved, msg, device));
40
+ for (const topic of result.topics) {
41
+ if (subscribed.has(topic))
42
+ continue;
43
+ subscribed.add(topic);
44
+ side.subscribe(topic);
45
+ }
46
+ // Output 1: motion and presence, for occupancy fusion. Output 2: the
47
+ // light level, for the motion lighting policy.
48
+ const outputs = [
49
+ result.occupancy.length ? result.occupancy.map((reading) => ({ ...reading })) : null,
50
+ result.light.length ? result.light.map((reading) => ({ ...reading })) : null
51
+ ];
52
+ if (outputs.some((output) => output !== null))
53
+ send(outputs);
54
+ const state = result.state;
55
+ if (state.online === false) {
56
+ node.status({ fill: "grey", shape: "ring", text: "offline" });
57
+ }
58
+ else {
59
+ const occupied = state.motion === true || state.presence === true;
60
+ const known = state.motion !== null || state.presence !== null;
61
+ // And where its entities came from: its discovery, or its preset.
62
+ const source = result.roles.source === "discovered" ? "discovered" : result.roles.source === "preset" ? "preset" : "preset: discovery is another model";
63
+ const parts = [known ? (occupied ? "occupied" : "clear") : "", state.illuminance !== null ? `${state.illuminance} lx` : "", source].filter(Boolean);
64
+ node.status({ fill: occupied ? "green" : "grey", shape: known ? "dot" : "ring", text: parts.join(" · ") });
65
+ }
66
+ }
67
+ (0, adapter_1.onInput)(node, (msg, send) => {
68
+ // Its device's messages come from the broker: an MQTT in node wired in
69
+ // changes nothing.
70
+ if (!side.fromBroker(msg))
71
+ handle(msg, send);
72
+ });
73
+ }
74
+ RED.nodes.registerType(type, HomeEsphomeSensor);
75
+ };
76
+ }
77
+ //# sourceMappingURL=esphome-sensor.js.map
@@ -0,0 +1,2 @@
1
+ declare const _default: import("node-red").NodeInitializer<import("node-red").NodeAPISettingsWithData>;
2
+ export = _default;
@@ -0,0 +1,78 @@
1
+ <script type="text/javascript">
2
+ RED.nodes.registerType("home-everything-presence-one", {
3
+ category: "home automation",
4
+ color: "#e2d96e",
5
+ defaults: {
6
+ name: {value: ""},
7
+ // Node-RED's MQTT broker node, through which it subscribes to the
8
+ // device's topics. The editor offers the first broker when the dialog is
9
+ // opened and saved.
10
+ broker: {value: "", type: "mqtt-broker", required: true},
11
+ // No default: it names the user's own device.
12
+ device: {value: "", required: true, validate: function (v) {
13
+ var device = String(v || "").trim().replace(/^\/+|\/+$/g, "");
14
+ return device !== "" && !/[+#]/.test(device);
15
+ }},
16
+ // Where the device's discovery is: ESPHome's default. A node saved
17
+ // before this setting loads without it (the editor applies no defaults
18
+ // to deployed flows); missing or empty means homeassistant, as the
19
+ // runtime reads it.
20
+ discoveryPrefix: {value: "homeassistant", validate: function (v) {
21
+ return !/[+#]/.test(String(v === undefined || v === null ? "" : v));
22
+ }}
23
+ },
24
+ inputs: 1,
25
+ outputs: 2,
26
+ outputLabels: ["motion and presence, to occupancy fusion", "light level, to the motion lighting policy"],
27
+ icon: "font-awesome/fa-eye",
28
+ label: function () { return this.name || this.device || "everything presence one"; },
29
+ paletteLabel: "everything presence one"
30
+ });
31
+ </script>
32
+
33
+ <script type="text/html" data-template-name="home-everything-presence-one">
34
+ <div class="form-row"><label for="node-input-name">Name</label><input type="text" id="node-input-name"></div>
35
+ <div class="form-row"><label for="node-input-broker">Broker</label><input type="text" id="node-input-broker"></div>
36
+ <div class="form-row"><label for="node-input-device">Device</label><input type="text" id="node-input-device" placeholder="its ESPHome name"></div>
37
+ <div class="form-row"><label for="node-input-discoveryPrefix">Discovery prefix</label><input type="text" id="node-input-discoveryPrefix"></div>
38
+ <div class="form-tips">It subscribes to the device's entities and status itself: no MQTT in, change or function nodes.</div>
39
+ </script>
40
+
41
+ <script type="text/html" data-help-name="home-everything-presence-one">
42
+ <p>Connects an <b>Everything Presence One</b> (Everything Smart Technology's ESPHome presence sensor) to a room: its PIR,
43
+ its mmWave radar and its light sensor become the messages <b>home occupancy fusion</b> and the <b>home motion lighting
44
+ policy</b> take, over ESPHome's own MQTT messages: no function or change nodes, and never Home Assistant.</p>
45
+ <p>The device: <a href="https://docs.everythingsmart.io/docs/products/everything-presence-one-ep1" target="_blank">Everything Presence One</a> (Everything Smart Technology's documentation).</p>
46
+ <h3>Wiring</h3>
47
+ <ol>
48
+ <li>Output 1 (motion and presence) → occupancy fusion, with its presence sensor set to hold.</li>
49
+ <li>Output 2 (light level) → the motion lighting policy.</li>
50
+ </ol>
51
+ <p>Choose the <b>Broker</b> the device uses (MQTT on in its ESPHome configuration), and set <b>Device</b> to its ESPHome
52
+ name, the prefix of its MQTT topics (such as <code>everything-presence-one-1a2b3c</code>).</p>
53
+ <h3>What it reads</h3>
54
+ <ul>
55
+ <li><b>Motion</b>: <code>binary_sensor/pir</code>, the PIR: quick to see someone arrive.</li>
56
+ <li><b>Presence</b>: <code>binary_sensor/mmwave</code>, the radar: sees someone sitting still, so occupancy fusion
57
+ holds the room while they stay.</li>
58
+ <li><b>Light level</b>: <code>sensor/illuminance</code>, in lux.</li>
59
+ <li>Not its own <code>occupancy</code> entity: that combines the two on the device, and occupancy fusion does that
60
+ combining here.</li>
61
+ </ul>
62
+ <h3>How it finds its entities</h3>
63
+ <p>From the device's own MQTT discovery first: each entity it describes, by device class (motion; occupancy or
64
+ presence; illuminance), with its state topic, skipping those it marks disabled by default, so a firmware that renames an entity still works. The device's model
65
+ in its discovery must be this one. Without discovery (turn it on with <code>mqtt: discovery: true</code> in the
66
+ device's ESPHome configuration and flash it again), or with another model's, it uses the entity names below. Its
67
+ status ends with <i>discovered</i> or <i>preset</i>.</p>
68
+ <h3>Readings</h3>
69
+ <ul>
70
+ <li>Output 1: <code>{source: "motion" | "presence", payload: true | false}</code>, from ON and OFF only.</li>
71
+ <li>Output 2: <code>{source: "illuminance", payload: &lt;lux&gt;}</code>, from a number only.</li>
72
+ <li>Anything else (such as <code>nan</code>) is ignored with a trace, and only a change is sent.</li>
73
+ <li>As Node-RED starts, ESPHome's retained states are the device's current ones while its status is online. They
74
+ are sent with <code>msg.baseline = true</code>: an occupied room switches nothing on, and an empty one starts its
75
+ vacancy, so its lights go off when the motion policy's delay runs out. A retained state from a device that isn't
76
+ online is ignored.</li>
77
+ </ul>
78
+ </script>
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ const esphome_sensor_1 = require("./esphome-sensor");
3
+ module.exports = (0, esphome_sensor_1.esphomeSensorNode)("home-everything-presence-one", "everything-presence-one");
4
+ //# sourceMappingURL=everything-presence-one.js.map
@@ -0,0 +1,26 @@
1
+ import type { Node, NodeAPI } from "node-red";
2
+ import { type TraceMetadata } from "../lib/bounded-trace";
3
+ import { type DiscoveryOwner } from "../lib/ha-discovery";
4
+ import type { BrokerLink, BrokerMessage } from "./mqtt-broker-link";
5
+ export interface RetainedPublication {
6
+ topic: string;
7
+ payload: unknown;
8
+ retain: boolean;
9
+ }
10
+ export interface HomeAssistantParts {
11
+ retainedTopics(): string[];
12
+ possible?: {
13
+ owner: DiscoveryOwner;
14
+ topics(): string[];
15
+ };
16
+ announcement(): RetainedPublication[];
17
+ stopping(): RetainedPublication[];
18
+ statusTopic: string | null;
19
+ setTopics?: string[];
20
+ onSet?(message: BrokerMessage): void;
21
+ onConnected?(): void;
22
+ }
23
+ export interface HomeAssistantDiscovery {
24
+ publish(publications: RetainedPublication[]): void;
25
+ }
26
+ export declare function homeAssistantDiscovery(RED: NodeAPI, node: Node, link: BrokerLink, parts: HomeAssistantParts, trace: TraceMetadata): HomeAssistantDiscovery;
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.homeAssistantDiscovery = homeAssistantDiscovery;
4
+ const bounded_trace_1 = require("../lib/bounded-trace");
5
+ const ha_discovery_1 = require("../lib/ha-discovery");
6
+ const retained_topics_1 = require("../lib/retained-topics");
7
+ const adapter_1 = require("./adapter");
8
+ // MQTT payloads as text: an object as JSON, as the broker node would.
9
+ function text(payload) {
10
+ if (payload === null || payload === undefined)
11
+ return "";
12
+ if (typeof payload === "string")
13
+ return payload;
14
+ if (typeof payload === "object")
15
+ return JSON.stringify(payload);
16
+ return String(payload);
17
+ }
18
+ function homeAssistantDiscovery(RED, node, link, parts, trace) {
19
+ const record = (event, outcome, reason, details = {}) => (0, bounded_trace_1.appendTrace)(node.context(), trace, [{ event, outcome, reason, details }]);
20
+ function publish(publications) {
21
+ for (const { topic, payload, retain } of publications)
22
+ link.publish(topic, text(payload), { retain });
23
+ }
24
+ const possible = () => parts.possible ? (0, ha_discovery_1.ownDiscoveryTopics)(parts.possible.owner, parts.possible.topics()) : [];
25
+ function announce(reason) {
26
+ publish([...(0, adapter_1.clearStaleRetained)(node, parts.retainedTopics(), "startup", possible()), ...parts.announcement()]);
27
+ record("home-assistant", "announced", reason);
28
+ }
29
+ link.onConnected(() => {
30
+ if (!parts.onConnected) {
31
+ announce("connected");
32
+ return;
33
+ }
34
+ publish((0, adapter_1.clearStaleRetained)(node, parts.retainedTopics(), "startup", possible()));
35
+ record("home-assistant", "startup", "connected");
36
+ parts.onConnected();
37
+ });
38
+ if (parts.statusTopic) {
39
+ link.subscribe(parts.statusTopic, (message) => {
40
+ if (message.payload.trim().toLowerCase() === "online")
41
+ announce("home-assistant-online");
42
+ });
43
+ }
44
+ for (const topic of parts.setTopics ?? []) {
45
+ link.subscribe(topic, (message) => {
46
+ // A retained set message would replay on every reconnect.
47
+ if (message.retain)
48
+ record("set", "ignored", "retained-message", { topic: message.topic });
49
+ else
50
+ parts.onSet?.(message);
51
+ });
52
+ }
53
+ node.on("close", (removed, done) => {
54
+ // Reaches the broker only while it is still connected, as in a deploy of
55
+ // modified nodes or flows; the broker's own Close and Will messages cover
56
+ // a full deploy, a restart and a crash.
57
+ publish((0, adapter_1.wasDeleted)(RED, node, removed)
58
+ ? (0, retained_topics_1.retainedClears)((0, adapter_1.allRetainedTopics)(node, [...parts.retainedTopics(), ...possible()]))
59
+ : parts.stopping());
60
+ link.close(removed, done);
61
+ });
62
+ return { publish };
63
+ }
64
+ //# sourceMappingURL=home-assistant-discovery.js.map
@@ -1,6 +1,23 @@
1
1
  <script type="text/javascript">
2
2
  (function () {
3
3
  function on(value) { return value === true || value === "true"; }
4
+ // Its Publish choice: it always publishes state, so state or discovery,
5
+ // from the open dialog or its saved settings; a node saved before the
6
+ // choice reads its old discovery setting.
7
+ function publishChoice(node) {
8
+ var select = $("#node-input-homeAssistant");
9
+ if (select.length) return select.val();
10
+ if (node.homeAssistant === "state" || node.homeAssistant === "discovery") return node.homeAssistant;
11
+ return on(node.discovery) ? "discovery" : "state";
12
+ }
13
+ // Whether it publishes through its output, as before 6.2: a node saved
14
+ // before the Publish choice that published, or one opened and saved since
15
+ // without a broker (publishesThroughOutput). It needs no broker until one
16
+ // is chosen; from saved values only, not the open dialog.
17
+ function throughOutput(node) {
18
+ if (node.publishesThroughOutput === true) return true;
19
+ return node.homeAssistant === null || node.homeAssistant === undefined;
20
+ }
4
21
  RED.nodes.registerType("home-house-schedule-mqtt", {
5
22
  category: "home automation",
6
23
  color: "#ffd27f",
@@ -9,7 +26,21 @@
9
26
  // and paste keep the saved name, so onadd leaves a saved node's settings.
10
27
  name: {value: "_DEFAULT_"},
11
28
  schedule: {value: "", type: "home-house-schedule", required: true},
29
+ // Publish: state or discovery. null means "not set": a node saved
30
+ // before this setting, read from discovery, kept with no row.
31
+ homeAssistant: {value: null},
32
+ // Node-RED's MQTT broker node, through which it publishes and reads its
33
+ // set topics itself. It always publishes, so it needs one. The editor offers
34
+ // the first broker when the dialog is opened and saved, not when the
35
+ // node is dropped.
36
+ broker: {value: "", type: "mqtt-broker", required: false, validate: function (v) {
37
+ return Boolean(v) && v !== "_ADD_" || throughOutput(this) ? true : "choose a broker";
38
+ }},
12
39
  discovery: {value: true},
40
+ // true for a node that publishes through its output, as before 6.2, and
41
+ // was opened and saved without a broker: it stays valid until a broker is
42
+ // chosen. No form row.
43
+ publishesThroughOutput: {value: false},
13
44
  discoveryPrefix: {value: "homeassistant", required: true, validate: function (v) { var prefix = String(v || "").trim().replace(/^\/+|\/+$/g, ""); return Boolean(prefix) && !/[+#]/.test(prefix); }},
14
45
  // How Home Assistant IDs are named; this node has no older entities,
15
46
  // so not set also means "node".
@@ -19,9 +50,24 @@
19
50
  if (this.name !== "_DEFAULT_") return;
20
51
  this.name = "";
21
52
  this.idScheme = "node";
53
+ // A new node always publishes, through its broker: discovery, as the
54
+ // default above.
55
+ this.homeAssistant = "discovery";
56
+ },
57
+ oneditsave: function () {
58
+ // Through its output until a broker is chosen (read before the
59
+ // dialog's values are applied).
60
+ var broker = $("#node-input-broker").val();
61
+ this.publishesThroughOutput = throughOutput(this) && (!broker || broker === "_ADD_");
22
62
  },
23
63
  oneditprepare: function () {
24
- $("#node-input-discovery").prop("checked", on(this.discovery));
64
+ $("#node-input-homeAssistant").val(publishChoice(this));
65
+ var outputBefore = throughOutput(this);
66
+ function publishRows() {
67
+ var broker = $("#node-input-broker").val();
68
+ $(".publish-through-output").toggle($("#node-input-homeAssistant").val() !== "off" && outputBefore && (!broker || broker === "_ADD_")); $(".publish-discovery").toggle($("#node-input-homeAssistant").val() === "discovery"); }
69
+ $("#node-input-homeAssistant, #node-input-broker").on("change", publishRows);
70
+ publishRows();
25
71
  },
26
72
  inputs: 1,
27
73
  outputs: 1,
@@ -35,15 +81,26 @@
35
81
  <script type="text/html" data-template-name="home-house-schedule-mqtt">
36
82
  <div class="form-row"><label for="node-input-name">Name</label><input type="text" id="node-input-name"></div>
37
83
  <div class="form-row"><label for="node-input-schedule">Schedule</label><input type="text" id="node-input-schedule"></div>
38
- <div class="form-row"><label for="node-input-discovery">Home Assistant discovery</label><input type="checkbox" id="node-input-discovery" style="display:inline-block; width:auto;"></div>
39
- <div class="form-row"><label for="node-input-discoveryPrefix">Discovery prefix</label><input type="text" id="node-input-discoveryPrefix"></div>
84
+ <div class="form-row">
85
+ <label for="node-input-homeAssistant">Publish</label>
86
+ <select id="node-input-homeAssistant">
87
+ <option value="state">MQTT state</option>
88
+ <option value="discovery">MQTT state and Home Assistant discovery</option>
89
+ </select>
90
+ </div>
91
+ <div class="form-row"><label for="node-input-broker">Broker</label><input type="text" id="node-input-broker"></div>
92
+ <div class="form-tips">With a broker, it publishes and reads its set topics itself: an MQTT out on its publication output, an
93
+ MQTT in on its set topics, and a Status node are no longer needed and can be deleted.</div>
94
+ <div class="form-tips publish-through-output">This node publishes through its output, as before 6.2, and keeps
95
+ working that way. Choose a Broker to let it publish itself.</div>
96
+ <div class="form-row publish-discovery"><label for="node-input-discoveryPrefix">Discovery prefix</label><input type="text" id="node-input-discoveryPrefix"></div>
40
97
  </script>
41
98
 
42
99
  <script type="text/html" data-help-name="home-house-schedule-mqtt">
43
100
  <p>A house schedule's MQTT and Home Assistant side. Optional: rooms follow the schedule without it.</p>
44
101
  <p>It publishes the schedule's times, retained, on <code>home/&lt;name&gt;/schedule/wake-time/state</code> and
45
102
  <code>bed-time/state</code>, with availability on <code>home/&lt;name&gt;/schedule/availability</code>; with
46
- <b>Home Assistant discovery</b>, wake and bed time entities, named after the schedule so a replacement node keeps
103
+ <b>Publish</b> set to <i>MQTT state and Home Assistant discovery</i>, wake and bed time entities, named after the schedule so a replacement node keeps
47
104
  them. Use one per schedule: two would share the same topics and entities, and deleting one clears them for both
48
105
  until the other next starts. Wire its output to an MQTT out node, and an MQTT in node on the set topics to its input.</p>
49
106
  <h3>Inputs</h3>
@@ -58,8 +115,16 @@
58
115
  <ol class="node-ports">
59
116
  <li>MQTT publications.</li>
60
117
  </ol>
118
+ <h3>Broker</h3>
119
+ <p>Choose Node-RED's <b>MQTT broker</b> node, and it publishes and reads its set topics itself: it announces everything each time the
120
+ broker connects, reconnects included, and each time Home Assistant comes back (<code>online</code> on
121
+ <code>&lt;prefix&gt;/status</code>), so its entities come back by themselves.
122
+ Each connect also runs its startup message, as a Status node's "connected" did without a broker. Its publication output then sends
123
+ nothing, and an MQTT out on it, an MQTT in on its set topics and a Status node are no longer needed: still wired, they change nothing.
124
+ Opening and saving the node offers the first broker in your flows. A node saved before 6.2 that publishes keeps
125
+ publishing on its output, as below, and needs no broker until you choose one.</p>
61
126
  <h3>When MQTT out connects</h3>
62
- <p>Wire a <b>Status node</b> whose scope is your MQTT out node into this node. Each time MQTT out shows
127
+ <p>Without a broker, wire a <b>Status node</b> whose scope is your MQTT out node into this node. Each time MQTT out shows
63
128
  "connected", this node takes it as its startup message (<code>msg.source = "startup"</code>) and announces itself again:
64
129
  Node-RED's MQTT broker node drops what it is given before it connects, so what the node sends as the flows
65
130
  start is lost on a first start, a full deploy or a restart. Any other status message is ignored.</p>
@@ -4,7 +4,8 @@ const house_schedule_publishing_1 = require("../lib/house-schedule-publishing");
4
4
  const settings_1 = require("../lib/settings");
5
5
  const topic_names_1 = require("../lib/topic-names");
6
6
  const adapter_1 = require("./adapter");
7
- const publishing_lifecycle_1 = require("./publishing-lifecycle");
7
+ const publishing_side_1 = require("./publishing-side");
8
+ const home_assistant_setting_1 = require("../lib/home-assistant-setting");
8
9
  const shared_schedule_1 = require("./shared-schedule");
9
10
  const registerHouseScheduleMqtt = (RED) => {
10
11
  function HomeHouseScheduleMqtt(config) {
@@ -12,7 +13,9 @@ const registerHouseScheduleMqtt = (RED) => {
12
13
  const node = this;
13
14
  let house;
14
15
  let publishing;
16
+ let broker;
15
17
  try {
18
+ const choice = (0, settings_1.optionalChoiceSetting)(config.homeAssistant, "Publish", home_assistant_setting_1.HOME_ASSISTANT_CHOICES);
16
19
  const referenced = (0, shared_schedule_1.referencedSchedule)(RED, config.schedule);
17
20
  if (!referenced.schedule)
18
21
  throw new Error(referenced.missing ? "the house schedule is missing" : "no house schedule");
@@ -20,15 +23,17 @@ const registerHouseScheduleMqtt = (RED) => {
20
23
  publishing = {
21
24
  area: (0, topic_names_1.publishingArea)(house.name, true),
22
25
  // Publishing is what this node is for; discovery is off unless
23
- // switched on.
26
+ // switched on. Publish (MQTT state, or MQTT state and Home Assistant
27
+ // discovery) replaced the discovery setting; not set: from it.
24
28
  publishState: true,
25
- discovery: (0, settings_1.optionalBooleanSetting)(config.discovery, "Home Assistant discovery") ?? false,
29
+ discovery: choice ? choice === "discovery" : (0, settings_1.optionalBooleanSetting)(config.discovery, "Home Assistant discovery") ?? false,
26
30
  discoveryPrefix: (0, ha_discovery_1.discoveryPrefixSetting)(config.discoveryPrefix),
27
31
  // Named after the schedule, not this node, so a replacement node
28
32
  // keeps the same entities.
29
33
  nodeId: config.schedule,
30
34
  idScheme: (0, settings_1.optionalChoiceSetting)(config.idScheme, "ID scheme", ha_discovery_1.ID_SCHEMES) ?? "node"
31
35
  };
36
+ broker = (0, publishing_side_1.brokerSetting)(RED, config.broker, true);
32
37
  }
33
38
  catch (error) {
34
39
  (0, adapter_1.invalidConfig)(node, error);
@@ -39,7 +44,7 @@ const registerHouseScheduleMqtt = (RED) => {
39
44
  const { wakeTime, bedTime } = house.schedule();
40
45
  node.status({ fill: "green", shape: "dot", text: `wake ${wakeTime} · bed ${bedTime}` });
41
46
  }
42
- const lifecycle = (0, publishing_lifecycle_1.publishingLifecycle)(RED, node, {
47
+ const lifecycle = (0, publishing_side_1.publishingSide)(RED, node, broker, {
43
48
  retainedTopics: () => (0, house_schedule_publishing_1.houseRetainedTopics)(publishing),
44
49
  // Its own entities, named after the schedule, cleared when discovery is
45
50
  // switched off, with or without a record (see ownDiscoveryTopics).
@@ -47,15 +52,18 @@ const registerHouseScheduleMqtt = (RED) => {
47
52
  starting: () => (0, house_schedule_publishing_1.houseStartingOutputs)(publishing, house.schedule()),
48
53
  stopping: () => (0, house_schedule_publishing_1.houseStoppingOutputs)(publishing),
49
54
  output: 0,
50
- outputs: 1
51
- });
55
+ outputs: 1,
56
+ startupMessage: { lighting: { kind: "startup" } },
57
+ statusTopic: publishing.discovery ? publishing.discoveryPrefix + "/status" : null,
58
+ setTopics: [(0, house_schedule_publishing_1.houseCommandTopic)(publishing.area, "wake-time"), (0, house_schedule_publishing_1.houseCommandTopic)(publishing.area, "bed-time")]
59
+ }, trace, (msg, send) => handle(msg, send));
52
60
  const unsubscribe = house.subscribe((0, adapter_1.guarded)(node, () => {
53
61
  lifecycle.publish(node.send.bind(node), (0, house_schedule_publishing_1.houseStateOutputs)(publishing, house.schedule()));
54
62
  showTimes();
55
63
  }));
56
64
  node.on("close", unsubscribe);
57
65
  showTimes();
58
- (0, adapter_1.onInput)(node, (msg, send) => {
66
+ function handle(msg, send) {
59
67
  const lighting = (0, adapter_1.objectField)(msg, "lighting");
60
68
  if (lighting?.kind === "startup" || msg.source === "startup") {
61
69
  lifecycle.startup(send, (0, house_schedule_publishing_1.houseStartingOutputs)(publishing, house.schedule()));
@@ -72,7 +80,13 @@ const registerHouseScheduleMqtt = (RED) => {
72
80
  else if (inbound) {
73
81
  (0, adapter_1.runReducer)(node, trace, (state) => ({ state, traces: inbound.traces }));
74
82
  }
75
- }, { message: { lighting: { kind: "startup" } }, trace: trace });
83
+ }
84
+ (0, adapter_1.onInput)(node, (msg, send) => {
85
+ // With a broker, its set topics come from the broker: an MQTT in or a
86
+ // Status node still wired in changes nothing.
87
+ if (!lifecycle.fromBroker(msg))
88
+ handle(msg, send);
89
+ }, lifecycle.startupOption({ lighting: { kind: "startup" } }));
76
90
  }
77
91
  RED.nodes.registerType("home-house-schedule-mqtt", HomeHouseScheduleMqtt);
78
92
  };