@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
@@ -0,0 +1,83 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.normaliseZ2mPowerConfig = normaliseZ2mPowerConfig;
4
+ exports.z2mPowerTopics = z2mPowerTopics;
5
+ exports.transitionZ2mPower = transitionZ2mPower;
6
+ const mqtt_message_1 = require("./mqtt-message");
7
+ function normaliseZ2mPowerConfig(config) {
8
+ const baseTopic = String(config.baseTopic ?? "").trim().replace(/^\/+|\/+$/g, "") || "zigbee2mqtt";
9
+ // The user's own device's: no default.
10
+ const friendlyName = String(config.friendlyName ?? "").trim().replace(/^\/+|\/+$/g, "");
11
+ if (!friendlyName)
12
+ throw new Error("the device's friendly name is required");
13
+ if (/[+#]/.test(baseTopic) || /[+#]/.test(friendlyName))
14
+ throw new Error("the base topic and friendly name can't contain + or #");
15
+ return { baseTopic, friendlyName };
16
+ }
17
+ function z2mPowerTopics(config) {
18
+ const device = `${config.baseTopic}/${config.friendlyName}`;
19
+ return { device, get: `${device}/get`, availability: `${device}/availability` };
20
+ }
21
+ function transitionZ2mPower(saved, msg, config, now) {
22
+ const state = {
23
+ watts: typeof saved?.watts === "number" ? saved.watts : null,
24
+ online: typeof saved?.online === "boolean" ? saved.online : null
25
+ };
26
+ const topics = z2mPowerTopics(config);
27
+ const publications = [];
28
+ const readings = [];
29
+ const traces = [];
30
+ const trace = (event, outcome, reason = null, details = {}) => {
31
+ traces.push({ event, outcome, reason, details });
32
+ };
33
+ if ((0, mqtt_message_1.isObject)(msg.power)) {
34
+ if (msg.power.kind === "read") {
35
+ // A fresh reading, where the device answers /get; otherwise its next
36
+ // report.
37
+ publications.push({ topic: topics.get, payload: JSON.stringify({ power: "" }) });
38
+ trace("read", "sent");
39
+ }
40
+ else {
41
+ trace("message", "ignored", "not-a-read-request", { kind: String(msg.power.kind) });
42
+ }
43
+ }
44
+ else if (msg.topic === topics.device) {
45
+ const report = (0, mqtt_message_1.parsedPayload)(msg.payload);
46
+ if (!(0, mqtt_message_1.isObject)(report))
47
+ throw new Error(`${topics.device} must carry the device's state object`);
48
+ const watts = report.power;
49
+ state.online = true;
50
+ if (msg.retain === true) {
51
+ // A retained report is an old one (with retain set for the plug in
52
+ // Zigbee2MQTT): never passed on; the read on connect brings a fresh
53
+ // one.
54
+ if (watts !== undefined)
55
+ trace("power", "ignored", "retained", { value: watts });
56
+ }
57
+ else if (typeof watts !== "number" || !Number.isFinite(watts) || watts < 0) {
58
+ // A fixed contract: only watts pass. A report without power (or
59
+ // nothing new) sends nothing.
60
+ if (watts !== undefined)
61
+ trace("power", "ignored", "not-watts", { value: watts });
62
+ }
63
+ else if (watts !== state.watts) {
64
+ state.watts = watts;
65
+ readings.push({ power: { kind: "observed", watts, observedAt: now.toISOString() } });
66
+ trace("power", "changed", null, { watts });
67
+ }
68
+ }
69
+ else if (msg.topic === topics.availability) {
70
+ // {"state": "online"}, or the plain "online" of older setups.
71
+ const received = (0, mqtt_message_1.parsedPayload)(msg.payload);
72
+ const value = (0, mqtt_message_1.isObject)(received) ? received.state : received;
73
+ if (value !== "online" && value !== "offline")
74
+ throw new Error(`${topics.availability} must say online or offline`);
75
+ state.online = value === "online";
76
+ trace("availability", value);
77
+ }
78
+ else {
79
+ trace("message", "ignored", "other-topic", { topic: typeof msg.topic === "string" ? msg.topic : null });
80
+ }
81
+ return { state, publications, readings, traces };
82
+ }
83
+ //# sourceMappingURL=z2m-power.js.map
@@ -0,0 +1,37 @@
1
+ import type { TraceEntry } from "./bounded-trace";
2
+ export type OccupancyKind = "motion" | "presence";
3
+ export interface Z2mSensorConfig {
4
+ baseTopic: string;
5
+ friendlyName: string;
6
+ occupancyIs: OccupancyKind;
7
+ }
8
+ export interface Z2mSensorState {
9
+ motion: boolean | null;
10
+ presence: boolean | null;
11
+ illuminance: number | null;
12
+ online: boolean | null;
13
+ }
14
+ export interface Z2mSensorMessage {
15
+ topic?: unknown;
16
+ payload?: unknown;
17
+ retain?: unknown;
18
+ }
19
+ export interface SensorReading {
20
+ source: "motion" | "presence" | "illuminance";
21
+ payload: boolean | number;
22
+ }
23
+ export declare function normaliseZ2mSensorConfig(config: {
24
+ baseTopic?: unknown;
25
+ friendlyName?: unknown;
26
+ occupancyIs?: unknown;
27
+ }): Z2mSensorConfig;
28
+ export declare function z2mSensorTopics(config: Z2mSensorConfig): {
29
+ device: string;
30
+ availability: string;
31
+ };
32
+ export declare function transitionZ2mSensor(saved: Partial<Z2mSensorState> | undefined, msg: Z2mSensorMessage, config: Z2mSensorConfig): {
33
+ state: Z2mSensorState;
34
+ occupancy: SensorReading[];
35
+ light: SensorReading[];
36
+ traces: TraceEntry<Record<string, unknown>>[];
37
+ };
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.normaliseZ2mSensorConfig = normaliseZ2mSensorConfig;
4
+ exports.z2mSensorTopics = z2mSensorTopics;
5
+ exports.transitionZ2mSensor = transitionZ2mSensor;
6
+ const mqtt_message_1 = require("./mqtt-message");
7
+ function normaliseZ2mSensorConfig(config) {
8
+ const baseTopic = String(config.baseTopic ?? "").trim().replace(/^\/+|\/+$/g, "") || "zigbee2mqtt";
9
+ // The user's own device's: no default.
10
+ const friendlyName = String(config.friendlyName ?? "").trim().replace(/^\/+|\/+$/g, "");
11
+ if (!friendlyName)
12
+ throw new Error("the device's friendly name is required");
13
+ if (/[+#]/.test(baseTopic) || /[+#]/.test(friendlyName))
14
+ throw new Error("the base topic and friendly name can't contain + or #");
15
+ const occupancyIs = config.occupancyIs === undefined || config.occupancyIs === null || config.occupancyIs === "" ? "motion" : config.occupancyIs;
16
+ if (occupancyIs !== "motion" && occupancyIs !== "presence")
17
+ throw new Error("occupancy is must be motion or presence");
18
+ return { baseTopic, friendlyName, occupancyIs };
19
+ }
20
+ function z2mSensorTopics(config) {
21
+ const device = `${config.baseTopic}/${config.friendlyName}`;
22
+ return { device, availability: `${device}/availability` };
23
+ }
24
+ function transitionZ2mSensor(saved, msg, config) {
25
+ const state = {
26
+ motion: typeof saved?.motion === "boolean" ? saved.motion : null,
27
+ presence: typeof saved?.presence === "boolean" ? saved.presence : null,
28
+ illuminance: typeof saved?.illuminance === "number" ? saved.illuminance : null,
29
+ online: typeof saved?.online === "boolean" ? saved.online : null
30
+ };
31
+ const topics = z2mSensorTopics(config);
32
+ const occupancy = [];
33
+ const light = [];
34
+ const traces = [];
35
+ const trace = (event, outcome, reason = null, details = {}) => {
36
+ traces.push({ event, outcome, reason, details });
37
+ };
38
+ if (msg.topic === topics.device) {
39
+ const report = (0, mqtt_message_1.parsedPayload)(msg.payload);
40
+ if (!(0, mqtt_message_1.isObject)(report))
41
+ throw new Error(`${topics.device} must carry the device's state object`);
42
+ const retained = msg.retain === true;
43
+ // Each occupancy field, as the room's source for it.
44
+ const fields = [];
45
+ if (Object.hasOwn(report, "occupancy"))
46
+ fields.push([config.occupancyIs, report.occupancy]);
47
+ if (Object.hasOwn(report, "presence"))
48
+ fields.push(["presence", report.presence]);
49
+ for (const [source, value] of fields) {
50
+ if (typeof value !== "boolean")
51
+ continue;
52
+ if (retained) {
53
+ // A retained state is an old one: never acted on, and not kept
54
+ // either, so the next live report is passed on whatever it says.
55
+ trace(source, "ignored", "retained", { value });
56
+ continue;
57
+ }
58
+ if (state[source] === value)
59
+ continue;
60
+ state[source] = value;
61
+ occupancy.push({ source, payload: value });
62
+ trace(source, "changed", null, { value });
63
+ }
64
+ // Lux: illuminance_lux where a device sends it beside a raw illuminance.
65
+ const lux = typeof report.illuminance_lux === "number" ? report.illuminance_lux
66
+ : typeof report.illuminance === "number" ? report.illuminance : null;
67
+ if (lux !== null && Number.isFinite(lux) && lux !== state.illuminance) {
68
+ state.illuminance = lux;
69
+ light.push({ source: "illuminance", payload: lux });
70
+ trace("illuminance", "changed", null, { lux });
71
+ }
72
+ state.online = true;
73
+ }
74
+ else if (msg.topic === topics.availability) {
75
+ // {"state": "online"}, or the plain "online" of older setups.
76
+ const received = (0, mqtt_message_1.parsedPayload)(msg.payload);
77
+ const value = (0, mqtt_message_1.isObject)(received) ? received.state : received;
78
+ if (value !== "online" && value !== "offline")
79
+ throw new Error(`${topics.availability} must say online or offline`);
80
+ state.online = value === "online";
81
+ trace("availability", value);
82
+ }
83
+ else {
84
+ trace("message", "ignored", "other-topic", { topic: typeof msg.topic === "string" ? msg.topic : null });
85
+ }
86
+ return { state, occupancy, light, traces };
87
+ }
88
+ //# sourceMappingURL=z2m-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,80 @@
1
+ <script type="text/javascript">
2
+ RED.nodes.registerType("home-apollo-r-pro-1", {
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 || "apollo r pro-1"; },
29
+ paletteLabel: "apollo r pro-1"
30
+ });
31
+ </script>
32
+
33
+ <script type="text/html" data-template-name="home-apollo-r-pro-1">
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-apollo-r-pro-1">
42
+ <p>Connects an <b>Apollo R PRO-1</b> (Apollo Automation's ESPHome presence sensor) to a room: its two radars and its
43
+ light sensor become the messages <b>home occupancy fusion</b> and the <b>home motion lighting policy</b> take, over
44
+ ESPHome's own MQTT messages: no function or change nodes, and never Home Assistant.</p>
45
+ <p>The device: <a href="https://wiki.apolloautomation.com/products/rpro1/introduction/" target="_blank">Apollo R PRO-1</a> (Apollo Automation'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>apollo-r-pro-1-1a2b3c</code>).</p>
53
+ <h3>What it reads</h3>
54
+ <p>It has two radars, an LD2450 and an LD2412, and no PIR. Each role counts as on when any radar that has reported
55
+ says so, and off when every one that has reported says off. Apollo's firmware has named the LD2450's entities
56
+ without a prefix on earlier releases and with <code>ld2450_</code> on current ones; the node reads both.</p>
57
+ <ul>
58
+ <li><b>Motion</b>: <code>binary_sensor/moving_target</code> (or <code>ld2450_moving_target</code>) and
59
+ <code>binary_sensor/ld2412_moving_target</code>: a moving target.</li>
60
+ <li><b>Presence</b>: <code>binary_sensor/presence</code> (or <code>ld2450_presence</code>) and
61
+ <code>binary_sensor/ld2412_presence</code>: anyone there, still or moving.</li>
62
+ <li><b>Light level</b>: <code>sensor/ltr390_light</code>, the LTR390, in lux.</li>
63
+ </ul>
64
+ <h3>How it finds its entities</h3>
65
+ <p>From the device's own MQTT discovery first: each entity it describes, by device class (motion; occupancy or
66
+ 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
67
+ in its discovery must be this one. Without discovery (turn it on with <code>mqtt: discovery: true</code> in the
68
+ device's ESPHome configuration and flash it again), or with another model's, it uses the entity names below. Its
69
+ status ends with <i>discovered</i> or <i>preset</i>.</p>
70
+ <h3>Readings</h3>
71
+ <ul>
72
+ <li>Output 1: <code>{source: "motion" | "presence", payload: true | false}</code>, from ON and OFF only.</li>
73
+ <li>Output 2: <code>{source: "illuminance", payload: &lt;lux&gt;}</code>, from a number only.</li>
74
+ <li>Anything else (such as <code>nan</code>) is ignored with a trace, and only a change is sent.</li>
75
+ <li>As Node-RED starts, ESPHome's retained states are the device's current ones while its status is online. They
76
+ are sent with <code>msg.baseline = true</code>: an occupied room switches nothing on, and an empty one starts its
77
+ vacancy, so its lights go off when the motion policy's delay runs out. A retained state from a device that isn't
78
+ online is ignored.</li>
79
+ </ul>
80
+ </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-apollo-r-pro-1", "apollo-r-pro-1");
4
+ //# sourceMappingURL=apollo-r-pro-1.js.map
@@ -5,6 +5,31 @@
5
5
  // A dB bound. A node saved before 5.0 has none (its 0-98 bounds were
6
6
  // removed in 6.0), so it shows as invalid until they are set.
7
7
  function volumeBound(value) { return given(value) && Number.isFinite(Number(value)); }
8
+ // Its Publish choice (off, state or discovery), from the open dialog or
9
+ // its saved settings: a node saved before the choice reads its two old
10
+ // settings (lib/home-assistant-setting.ts).
11
+ function publishChoice(node) {
12
+ function on(value) { return value === true || value === "true"; }
13
+ var select = $("#node-input-homeAssistant");
14
+ if (select.length) return select.val();
15
+ if (node.homeAssistant === "off" || node.homeAssistant === "state" || node.homeAssistant === "discovery") return node.homeAssistant;
16
+ return !on(node.publishState) ? "off" : on(node.discovery) ? "discovery" : "state";
17
+ }
18
+ // Whether it publishes through its output, as before 6.2: a node saved
19
+ // before the Publish choice that published, or one opened and saved since
20
+ // without a broker (publishesThroughOutput). It needs no broker until one
21
+ // is chosen; from saved values only, not the open dialog.
22
+ function throughOutput(node) {
23
+ if (node.publishesThroughOutput === true) return true;
24
+ return (node.homeAssistant === null || node.homeAssistant === undefined) && (node.publishState === true || node.publishState === "true");
25
+ }
26
+ // Its area is needed while it publishes, and for a node saved before the
27
+ // choice whenever either old setting was on, as the runtime checks.
28
+ function needsArea(node) {
29
+ function on(value) { return value === true || value === "true"; }
30
+ var saved = !$("#node-input-homeAssistant").length && (node.homeAssistant === null || node.homeAssistant === undefined);
31
+ return publishChoice(node) !== "off" || (saved && (on(node.publishState) || on(node.discovery)));
32
+ }
8
33
  RED.nodes.registerType("home-avr-controller", {
9
34
  category: "home automation",
10
35
  color: "#c7d9f1",
@@ -14,10 +39,7 @@
14
39
  name: {value: "_DEFAULT_"},
15
40
  // Required only when the node publishes, and then with a letter or
16
41
  // digit, from which its topics and IDs are made.
17
- area: {value: "", validate: function (v) {
18
- var publishing = $("#node-input-publishState").length ? $("#node-input-publishState").prop("checked") : on(this.publishState);
19
- return !publishing || /[a-z0-9]/i.test(String(v || ""));
20
- }},
42
+ area: {value: "", validate: function (v) { return !needsArea(this) || /[a-z0-9]/i.test(String(v || "")); }},
21
43
  sources: {value: "{\"shield\":\"SAT/CBL\",\"playstation\":\"GAME\"}", required: true, validate: function (v) { try { JSON.parse(v); return true; } catch (e) { return false; } }},
22
44
  retryMs: {value: 2000, required: true, validate: RED.validators.number()},
23
45
  maxAttempts: {value: 3, required: true, validate: RED.validators.number()},
@@ -34,8 +56,22 @@
34
56
  minVolume: {value: ""},
35
57
  maxVolume: {value: ""},
36
58
  // The receiver published nothing before these settings, so both start off.
59
+ // Publish: off, state or discovery. null means "not set": a node saved
60
+ // before this setting, read from the two below, kept with no rows.
61
+ homeAssistant: {value: null},
62
+ // Node-RED's MQTT broker node, through which it publishes and reads its set
63
+ // topics itself. Needed unless Publish is "Don't publish". The editor offers
64
+ // the first broker when the dialog is opened and saved, not when the node
65
+ // is dropped.
66
+ broker: {value: "", type: "mqtt-broker", required: false, validate: function (v) {
67
+ return publishChoice(this) === "off" || (Boolean(v) && v !== "_ADD_") || throughOutput(this) ? true : "choose a broker, or set Publish to Don't publish";
68
+ }},
37
69
  publishState: {value: false},
38
70
  discovery: {value: false},
71
+ // true for a node that publishes through its output, as before 6.2, and
72
+ // was opened and saved without a broker: it stays valid until a broker is
73
+ // chosen. No form row.
74
+ publishesThroughOutput: {value: false},
39
75
  discoveryPrefix: {value: "homeassistant", required: true, validate: function (v) { var prefix = String(v || "").trim().replace(/^\/+|\/+$/g, ""); return Boolean(prefix) && !/[+#]/.test(prefix); }},
40
76
  // How Home Assistant IDs are named; the receiver has no older entities,
41
77
  // so not set also means "node".
@@ -47,20 +83,26 @@
47
83
  this.idScheme = "node";
48
84
  },
49
85
  oneditprepare: function () {
50
- $("#node-input-publishState").prop("checked", on(this.publishState));
51
- $("#node-input-discovery").prop("checked", on(this.discovery));
52
- // Discovery describes the published state, so it needs it.
53
- function follow() {
54
- var publishing = $("#node-input-publishState").prop("checked");
55
- if (!publishing) $("#node-input-discovery").prop("checked", false);
56
- $("#node-input-discovery").prop("disabled", !publishing);
57
- $("#node-input-area").trigger("change");
86
+ $("#node-input-homeAssistant").val(publishChoice(this));
87
+ // The broker only while it publishes, the prefix only with discovery.
88
+ var outputBefore = throughOutput(this);
89
+ function publishRows() {
90
+ var broker = $("#node-input-broker").val();
91
+ $(".publish-through-output").toggle($("#node-input-homeAssistant").val() !== "off" && outputBefore && (!broker || broker === "_ADD_"));
92
+ var choice = $("#node-input-homeAssistant").val();
93
+ $(".publish-broker").toggle(choice !== "off");
94
+ $(".publish-discovery").toggle(choice === "discovery");
95
+ $("#node-input-area, #node-input-broker").trigger("change");
58
96
  }
59
- $("#node-input-publishState, #node-input-discovery").on("change", follow);
60
- follow();
97
+ $("#node-input-homeAssistant, #node-input-broker").on("change", publishRows);
98
+ publishRows();
61
99
  },
62
100
  // Once the dB bounds are set, the removed 0-98 ones go.
63
101
  oneditsave: function () {
102
+ // Through its output until a broker is chosen (read before the
103
+ // dialog's values are applied).
104
+ var broker = $("#node-input-broker").val();
105
+ this.publishesThroughOutput = throughOutput(this) && (!broker || broker === "_ADD_");
64
106
  if (given($("#node-input-minVolumeDb").val())) this.minVolume = "";
65
107
  if (given($("#node-input-maxVolumeDb").val())) this.maxVolume = "";
66
108
  },
@@ -81,9 +123,20 @@
81
123
  <div class="form-row"><label for="node-input-maxAttempts">Maximum attempts</label><input type="number" id="node-input-maxAttempts"></div>
82
124
  <div class="form-row"><label for="node-input-minVolumeDb">Minimum volume (dB)</label><input type="number" step="0.5" id="node-input-minVolumeDb"></div>
83
125
  <div class="form-row"><label for="node-input-maxVolumeDb">Maximum volume (dB)</label><input type="number" step="0.5" id="node-input-maxVolumeDb"></div>
84
- <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>
85
- <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>
86
- <div class="form-row"><label for="node-input-discoveryPrefix">Discovery prefix</label><input type="text" id="node-input-discoveryPrefix"></div>
126
+ <div class="form-row">
127
+ <label for="node-input-homeAssistant">Publish</label>
128
+ <select id="node-input-homeAssistant">
129
+ <option value="off">Don't publish</option>
130
+ <option value="state">MQTT state</option>
131
+ <option value="discovery">MQTT state and Home Assistant discovery</option>
132
+ </select>
133
+ </div>
134
+ <div class="form-row publish-broker"><label for="node-input-broker">Broker</label><input type="text" id="node-input-broker"></div>
135
+ <div class="form-tips publish-broker">With a broker, it publishes and reads its set topics itself: an MQTT out on its
136
+ publication output, an MQTT in on its set topics, and a Status node are no longer needed and can be deleted.</div>
137
+ <div class="form-tips publish-through-output">This node publishes through its output, as before 6.2, and keeps
138
+ working that way. Choose a Broker to let it publish itself.</div>
139
+ <div class="form-row publish-discovery"><label for="node-input-discoveryPrefix">Discovery prefix</label><input type="text" id="node-input-discoveryPrefix"></div>
87
140
  </script>
88
141
 
89
142
  <script type="text/html" data-help-name="home-avr-controller">
@@ -104,12 +157,12 @@
104
157
  <h3>Publishing</h3>
105
158
  <p>Off unless switched on, and then named after the <b>Area</b>, which is needed.</p>
106
159
  <dl class="message-properties">
107
- <dt>Publish state over MQTT</dt><dd>what the receiver reports, retained, whenever it changes:
160
+ <dt>Publish: MQTT state</dt><dd>what the receiver reports, retained, whenever it changes:
108
161
  <code>home/&lt;area&gt;/receiver/power/state</code> (<code>ON</code> or <code>OFF</code>),
109
162
  <code>…/source/state</code> (the source name) and <code>…/volume/state</code>, with <code>online</code> or
110
163
  <code>offline</code> on <code>…/availability</code>.</dd>
111
- <dt>Home Assistant discovery</dt><dd>power and source sensors, and a volume number in dB between <b>Minimum volume</b>
112
- and <b>Maximum volume</b>. It needs <b>Publish state</b>. A volume set there arrives on
164
+ <dt>Publish: MQTT state and Home Assistant discovery</dt><dd>power and source sensors, and a volume number in dB between <b>Minimum volume</b>
165
+ and <b>Maximum volume</b>. It includes the MQTT state, which they read. A volume set there arrives on
113
166
  <code>…/volume/set</code>; wire an MQTT in node on that topic into this node. Sets arriving within 0.3 seconds
114
167
  of each other (a slider, repeated taps) are settled to the last one, which becomes an ordinary absolute
115
168
  volume request, bounded and confirmed like any other: it waits for a power or source change in progress (such
@@ -117,8 +170,16 @@
117
170
  </dl>
118
171
  <p>These go on the third output; wire it to an MQTT out node. The node announces itself once the flows have
119
172
  started, and again at <code>kind: "startup"</code>.</p>
173
+ <h3>Broker</h3>
174
+ <p>Choose Node-RED's <b>MQTT broker</b> node, and it publishes and reads its set topic itself: it announces everything each time the
175
+ broker connects, reconnects included, and each time Home Assistant comes back (<code>online</code> on
176
+ <code>&lt;prefix&gt;/status</code>), so its entities come back by themselves.
177
+ Each connect also runs its startup message, as a Status node's "connected" did without a broker. Its publication output then sends
178
+ nothing, and an MQTT out on it, an MQTT in on its set topic and a Status node are no longer needed: still wired, they change nothing.
179
+ Opening and saving the node offers the first broker in your flows. A node saved before 6.2 that publishes keeps
180
+ publishing on its output, as below, and needs no broker until you choose one.</p>
120
181
  <h3>When MQTT out connects</h3>
121
- <p>Wire a <b>Status node</b> whose scope is your MQTT out node into this node. Each time MQTT out shows
182
+ <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
122
183
  "connected", this node takes it as its startup message (<code>msg.avr = {kind: "startup"}</code>) and announces itself again:
123
184
  Node-RED's MQTT broker node drops what it is given before it connects, so what the node sends as the flows
124
185
  start is lost on a first start, a full deploy or a restart. Any other status message is ignored.</p>
@@ -6,7 +6,8 @@ const avr_publishing_1 = require("../lib/avr-publishing");
6
6
  const ha_discovery_1 = require("../lib/ha-discovery");
7
7
  const topic_names_1 = require("../lib/topic-names");
8
8
  const publishing_node_1 = require("../lib/publishing-node");
9
- const publishing_lifecycle_1 = require("./publishing-lifecycle");
9
+ const publishing_side_1 = require("./publishing-side");
10
+ const home_assistant_setting_1 = require("../lib/home-assistant-setting");
10
11
  function parseSources(value) {
11
12
  const sources = (0, settings_1.jsonSetting)(value, "sources", {});
12
13
  if (!sources || Array.isArray(sources) || typeof sources !== "object") {
@@ -22,6 +23,7 @@ const registerAvrController = (RED) => {
22
23
  let retryTimer;
23
24
  let controllerConfig;
24
25
  let publishing;
26
+ let broker;
25
27
  try {
26
28
  // The same validation the reducer applies, so a bad configuration
27
29
  // fails here at deploy rather than on every message.
@@ -29,14 +31,14 @@ const registerAvrController = (RED) => {
29
31
  // Off unless switched on, as the receiver published nothing before;
30
32
  // there are no older entities to keep, so not set names them after
31
33
  // 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)
34
+ const publish = (0, home_assistant_setting_1.publishingChoice)(config, { publishState: false, discovery: false });
35
+ if (publish.needsArea)
35
36
  (0, topic_names_1.publishingArea)(controllerConfig.area, true);
37
+ broker = (0, publishing_side_1.brokerSetting)(RED, config.broker, publish.publishState);
36
38
  publishing = {
37
39
  area: controllerConfig.area,
38
- publishState,
39
- discovery,
40
+ publishState: publish.publishState,
41
+ discovery: publish.discovery,
40
42
  discoveryPrefix: (0, ha_discovery_1.discoveryPrefixSetting)(config.discoveryPrefix),
41
43
  nodeId: node.id,
42
44
  idScheme: (0, settings_1.optionalChoiceSetting)(config.idScheme, "ID scheme", ha_discovery_1.ID_SCHEMES) ?? "node",
@@ -79,14 +81,18 @@ const registerAvrController = (RED) => {
79
81
  // commands and the theatre's events. Available, and clear of what it no
80
82
  // longer publishes, as soon as it runs; offline as it stops; nothing
81
83
  // left behind when deleted.
82
- const lifecycle = (0, publishing_lifecycle_1.publishingLifecycle)(RED, node, {
84
+ const trace = { area: controllerConfig.area, component: "avr-controller" };
85
+ const lifecycle = (0, publishing_side_1.publishingSide)(RED, node, broker, {
83
86
  retainedTopics: () => (0, avr_publishing_1.avrRetainedTopics)(publishing),
84
87
  possible: { owner: publishing, topics: () => (0, publishing_node_1.publishesState)(publishing) ? (0, avr_publishing_1.avrRetainedTopics)({ ...publishing, publishState: true, discovery: true }) : [] },
85
88
  starting: () => (0, avr_publishing_1.avrStartingOutputs)(publishing, observed()),
86
89
  stopping: () => (0, avr_publishing_1.avrStoppingOutputs)(publishing),
87
90
  output: 2,
88
- outputs: 3
89
- });
91
+ outputs: 3,
92
+ startupMessage: { avr: { kind: "startup" } },
93
+ statusTopic: publishing.discovery ? publishing.discoveryPrefix + "/status" : null,
94
+ setTopics: (0, publishing_node_1.publishesState)(publishing) ? [(0, avr_publishing_1.receiverTopic)(publishing.area, "volume/set")] : []
95
+ }, trace, (msg, send) => handle(msg, send));
90
96
  let warnedRemovedVolume = false;
91
97
  function process(msg, send) {
92
98
  const before = observed();
@@ -102,7 +108,7 @@ const registerAvrController = (RED) => {
102
108
  node.warn("volume requests with value in the receiver's own 0-98 were removed in 6.0 and are rejected: " +
103
109
  "send valueDb (dB, where the receiver's 80 is 0 dB) instead");
104
110
  }
105
- const outputs = [...result.events, ...result.targetStates];
111
+ const outputs = [...result.events, ...result.targetStates, ...result.observations];
106
112
  if (commands.length || outputs.length) {
107
113
  send([
108
114
  commands.length ? commands : null,
@@ -137,7 +143,7 @@ const registerAvrController = (RED) => {
137
143
  volumeRequests += 1;
138
144
  process({ avr: { kind: "volume", requestId: `mqtt-volume-${Date.now()}-${volumeRequests}`, mode: "absolute", valueDb } }, node.send.bind(node));
139
145
  }
140
- (0, adapter_1.onInput)(node, (msg, send) => {
146
+ function handle(msg, send) {
141
147
  const volume = (0, avr_publishing_1.avrVolumeRequest)(msg, publishing);
142
148
  if (volume && "ignored" in volume) {
143
149
  (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 } }] }));
@@ -158,7 +164,13 @@ const registerAvrController = (RED) => {
158
164
  avr: (0, adapter_1.objectField)(msg, "avr"),
159
165
  payload: msg.payload
160
166
  }, send);
161
- }, { message: { avr: { kind: "startup" } }, trace: { area: controllerConfig.area, component: "avr-controller" } });
167
+ }
168
+ (0, adapter_1.onInput)(node, (msg, send) => {
169
+ // With a broker, its set topic comes from the broker: an MQTT in or a
170
+ // Status node still wired in changes nothing.
171
+ if (!lifecycle.fromBroker(msg))
172
+ handle(msg, send);
173
+ }, lifecycle.startupOption({ avr: { kind: "startup" } }));
162
174
  node.on("close", (_removed, done) => {
163
175
  clearTimeout(retryTimer);
164
176
  clearTimeout(volumeSetTimer);
@@ -50,8 +50,9 @@ const registerBacklightingController = (RED) => {
50
50
  null
51
51
  ]);
52
52
  }
53
- if (result.events.length) {
54
- send([null, result.events.map((event) => ({ payload: undefined, ...event }))]);
53
+ const theatre = [...result.events, ...result.observations];
54
+ if (theatre.length) {
55
+ send([null, theatre.map((event) => ({ payload: undefined, ...event }))]);
55
56
  }
56
57
  updateStatus(result.status);
57
58
  schedule(result.state);