@avantics/node-red-home-automation 2.3.0 → 3.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 (79) hide show
  1. package/README.md +32 -8
  2. package/contract-examples/room-lighting.mjs +12 -7
  3. package/dist/lib/activity-lighting-controller.d.ts +13 -25
  4. package/dist/lib/activity-lighting-controller.js +15 -11
  5. package/dist/lib/avr-controller.d.ts +13 -47
  6. package/dist/lib/avr-controller.js +39 -90
  7. package/dist/lib/backlighting-controller.d.ts +12 -25
  8. package/dist/lib/backlighting-controller.js +11 -18
  9. package/dist/lib/bounded-trace.d.ts +6 -0
  10. package/dist/lib/command-echo.d.ts +20 -0
  11. package/dist/lib/command-echo.js +82 -0
  12. package/dist/lib/cover-controller.d.ts +15 -28
  13. package/dist/lib/cover-controller.js +6 -8
  14. package/dist/lib/denon-protocol.d.ts +29 -0
  15. package/dist/lib/denon-protocol.js +76 -0
  16. package/dist/lib/display-mode-controller.d.ts +7 -18
  17. package/dist/lib/display-mode-controller.js +39 -47
  18. package/dist/lib/motion-policy.d.ts +12 -22
  19. package/dist/lib/motion-policy.js +53 -56
  20. package/dist/lib/occupancy-fusion.d.ts +8 -12
  21. package/dist/lib/room-controller.d.ts +14 -34
  22. package/dist/lib/room-controller.js +80 -132
  23. package/dist/lib/room-lighting-discovery.d.ts +9 -0
  24. package/dist/lib/room-lighting-discovery.js +45 -0
  25. package/dist/lib/settings.d.ts +5 -0
  26. package/dist/lib/settings.js +68 -0
  27. package/dist/lib/source-capability-controller.d.ts +30 -35
  28. package/dist/lib/source-capability-controller.js +35 -36
  29. package/dist/lib/switch-policy.d.ts +2 -7
  30. package/dist/lib/target-state.d.ts +24 -0
  31. package/dist/lib/target-state.js +38 -0
  32. package/dist/lib/theatre-activity-controller.d.ts +6 -108
  33. package/dist/lib/theatre-activity-controller.js +67 -318
  34. package/dist/lib/theatre-ha-discovery.d.ts +14 -0
  35. package/dist/lib/theatre-ha-discovery.js +163 -0
  36. package/dist/lib/theatre-metrics.d.ts +4 -0
  37. package/dist/lib/theatre-metrics.js +66 -0
  38. package/dist/lib/theatre-profiles.d.ts +23 -0
  39. package/dist/lib/theatre-profiles.js +73 -0
  40. package/dist/lib/theatre-refresh.d.ts +20 -0
  41. package/dist/lib/theatre-refresh.js +46 -0
  42. package/dist/lib/theatre-slo.js +7 -9
  43. package/dist/lib/theatre-state-contract.d.ts +7 -19
  44. package/dist/lib/theatre-state-contract.js +33 -169
  45. package/dist/lib/theatre-state.d.ts +110 -0
  46. package/dist/lib/theatre-state.js +139 -0
  47. package/dist/lib/wall-input.d.ts +2 -7
  48. package/dist/lib/z2m-light.d.ts +16 -0
  49. package/dist/lib/z2m-light.js +36 -0
  50. package/dist/nodes/activity-lighting-controller.html +5 -3
  51. package/dist/nodes/activity-lighting-controller.js +21 -52
  52. package/dist/nodes/adapter.d.ts +15 -0
  53. package/dist/nodes/adapter.js +60 -0
  54. package/dist/nodes/avr-controller.html +3 -3
  55. package/dist/nodes/avr-controller.js +17 -56
  56. package/dist/nodes/backlighting-controller.html +1 -1
  57. package/dist/nodes/backlighting-controller.js +25 -47
  58. package/dist/nodes/display-mode-controller.html +2 -2
  59. package/dist/nodes/display-mode-controller.js +19 -57
  60. package/dist/nodes/motion-policy.html +23 -10
  61. package/dist/nodes/motion-policy.js +14 -135
  62. package/dist/nodes/occupancy-fusion.html +2 -2
  63. package/dist/nodes/occupancy-fusion.js +23 -29
  64. package/dist/nodes/room-controller.html +80 -26
  65. package/dist/nodes/room-controller.js +37 -54
  66. package/dist/nodes/source-capability-controller.html +4 -13
  67. package/dist/nodes/source-capability-controller.js +17 -52
  68. package/dist/nodes/switch-policy.html +3 -3
  69. package/dist/nodes/switch-policy.js +23 -42
  70. package/dist/nodes/theatre-activity-controller.html +4 -2
  71. package/dist/nodes/theatre-activity-controller.js +18 -45
  72. package/dist/nodes/theatre-state-contract.html +55 -22
  73. package/dist/nodes/theatre-state-contract.js +30 -41
  74. package/examples/Home theatre activity.json +13 -12
  75. package/examples/Home theatre equipment.json +4 -4
  76. package/examples/Room lighting.json +9 -9
  77. package/package.json +1 -1
  78. package/dist/lib/circadian-refresh.d.ts +0 -7
  79. package/dist/lib/circadian-refresh.js +0 -11
@@ -1,32 +1,6 @@
1
1
  "use strict";
2
- const bounded_trace_1 = require("../lib/bounded-trace");
3
- const wall_input_1 = require("../lib/wall-input");
4
2
  const motion_policy_1 = require("../lib/motion-policy");
5
- function ageText(ageMs) {
6
- if (ageMs === null)
7
- return "age ?";
8
- if (ageMs < 60_000)
9
- return `${Math.floor(ageMs / 1000)}s`;
10
- if (ageMs < 3_600_000)
11
- return `${Math.floor(ageMs / 60_000)}m`;
12
- return `${Math.floor(ageMs / 3_600_000)}h`;
13
- }
14
- function switchStatusText(status) {
15
- if (status.phase === "fresh")
16
- return `switch ${ageText(status.ageMs)}`;
17
- if (status.phase === "stale")
18
- return `switch stale ${ageText(status.ageMs)}`;
19
- if (status.phase === "unavailable")
20
- return "switch unavailable";
21
- return "switch baseline ?";
22
- }
23
- function parseArray(value, fallback) {
24
- const parsed = JSON.parse(value || JSON.stringify(fallback));
25
- if (!Array.isArray(parsed) || parsed.some((item) => typeof item !== "string")) {
26
- throw new Error("targets must be a JSON array of strings");
27
- }
28
- return parsed;
29
- }
3
+ const adapter_1 = require("./adapter");
30
4
  const registerMotionPolicy = (RED) => {
31
5
  function HomeMotionLightingPolicy(config) {
32
6
  RED.nodes.createNode(this, config);
@@ -34,86 +8,36 @@ const registerMotionPolicy = (RED) => {
34
8
  const context = node.context();
35
9
  const globalContext = context.global;
36
10
  let offTimer;
37
- let switchTimer;
38
- let statusTimer;
39
- const initialState = context.get("state");
40
- let wallInputRelevant = initialState?.wallInput?.baselineKnown === true ||
41
- initialState?.switchStateKnown === true;
42
11
  let policyConfig;
43
12
  try {
44
- const onTargets = parseArray(config.onTargets, ["main"]);
45
- policyConfig = {
46
- area: config.area || "room",
47
- onTargets,
48
- offTargets: parseArray(config.offTargets, onTargets),
49
- defaultDelaySeconds: Number(config.defaultDelaySeconds ?? 120),
50
- defaultIlluminanceCutoff: Number(config.defaultIlluminanceCutoff ?? 10),
51
- switchWindowMs: Number(config.switchWindowMs ?? 500),
52
- switchFreshnessMs: Number(config.switchFreshnessSeconds ?? 3600) * 1000
53
- };
54
- if (!Number.isFinite(policyConfig.switchFreshnessMs) || policyConfig.switchFreshnessMs <= 0) {
55
- throw new Error("switch freshness must be a positive number");
56
- }
13
+ policyConfig = { area: (0, adapter_1.optionalArea)(config), ...(0, motion_policy_1.normaliseMotionConfig)(config) };
57
14
  }
58
15
  catch (error) {
59
- node.status({ fill: "red", shape: "ring", text: "invalid configuration" });
60
- node.error(error);
16
+ (0, adapter_1.invalidConfig)(node, error);
61
17
  return;
62
18
  }
63
19
  function updateStatus(status) {
64
- if (!wallInputRelevant) {
65
- node.status({
66
- fill: status.enabled ? "green" : "grey",
67
- shape: "dot",
68
- text: (status.enabled ? "enabled" : "disabled") + " · " +
69
- (status.illuminance === null ? "lux ?" : status.illuminance + " lux") + " · " +
70
- status.delaySeconds + "s"
71
- });
72
- return;
73
- }
74
- const switchState = status.switch;
75
- const unhealthy = switchState.phase === "unavailable" || switchState.phase === "stale";
76
- const awaiting = switchState.phase === "awaiting-baseline";
77
20
  node.status({
78
- fill: switchState.phase === "unavailable"
79
- ? "red"
80
- : unhealthy || awaiting
81
- ? "yellow"
82
- : status.enabled ? "green" : "grey",
83
- shape: unhealthy || awaiting ? "ring" : "dot",
21
+ fill: status.enabled ? "green" : "grey",
22
+ shape: "dot",
84
23
  text: (status.enabled ? "enabled" : "disabled") + " · " +
85
24
  (status.illuminance === null ? "lux ?" : status.illuminance + " lux") + " · " +
86
- status.delaySeconds + "s · " + switchStatusText(switchState)
25
+ status.delaySeconds + "s"
87
26
  });
88
27
  }
89
28
  function armOffTimer(delayMs, generation) {
90
29
  clearTimeout(offTimer);
91
- offTimer = setTimeout(() => {
30
+ offTimer = setTimeout((0, adapter_1.guarded)(node, () => {
92
31
  offTimer = undefined;
93
- try {
94
- process({ source: "off-timer", generation }, node.send.bind(node));
95
- }
96
- catch (error) {
97
- node.error(error);
98
- }
99
- }, delayMs);
32
+ process({ source: "off-timer", generation }, node.send.bind(node));
33
+ }), delayMs);
100
34
  }
101
35
  function process(input, send) {
102
- if (input.source === "switch" || input.source === "switch-availability") {
103
- wallInputRelevant = true;
104
- }
105
- const now = new Date();
106
36
  const globalEnabled = globalContext.get("MOTION_ENABLED_STATE") !== false;
107
- const saved = context.get("state");
108
- const result = (0, motion_policy_1.transitionMotion)(saved, input, policyConfig, globalEnabled, now.getTime());
109
- context.set("state", result.state);
37
+ const result = (0, adapter_1.runReducer)(node, { area: policyConfig.area, component: "motion-policy" }, (saved, now) => (0, motion_policy_1.transitionMotion)(saved, input, policyConfig, globalEnabled, now.getTime()));
110
38
  if (input.source === "global-enabled") {
111
39
  globalContext.set("MOTION_ENABLED_STATE", result.globalEnabled);
112
40
  }
113
- (0, bounded_trace_1.appendTrace)(context, {
114
- area: policyConfig.area,
115
- component: "motion-policy"
116
- }, result.traces, now);
117
41
  for (const effect of result.effects) {
118
42
  if (effect.kind === "cancel-off-timer") {
119
43
  clearTimeout(offTimer);
@@ -122,26 +46,6 @@ const registerMotionPolicy = (RED) => {
122
46
  else if (effect.kind === "schedule-off-timer") {
123
47
  armOffTimer(effect.delayMs, effect.generation);
124
48
  }
125
- else if (effect.kind === "cancel-switch-timer") {
126
- clearTimeout(switchTimer);
127
- switchTimer = undefined;
128
- }
129
- else if (effect.kind === "schedule-switch-timer") {
130
- clearTimeout(switchTimer);
131
- switchTimer = setTimeout(() => {
132
- switchTimer = undefined;
133
- try {
134
- process({
135
- source: "switch-timer",
136
- generation: effect.generation,
137
- switchAt: effect.switchAt
138
- }, node.send.bind(node));
139
- }
140
- catch (error) {
141
- node.error(error);
142
- }
143
- }, effect.delayMs);
144
- }
145
49
  else if (effect.kind === "send") {
146
50
  send({ payload: undefined, ...effect.message });
147
51
  }
@@ -149,42 +53,17 @@ const registerMotionPolicy = (RED) => {
149
53
  updateStatus(result.status);
150
54
  return result;
151
55
  }
152
- process({ source: "switch-startup" }, node.send.bind(node));
153
- // Context survives a redeploy but timers do not. switch-startup drops a
154
- // half-finished switch gesture by design; a pending off-timer is re-armed.
56
+ // Context survives a redeploy but timers do not: a pending off-timer is
57
+ // re-armed.
155
58
  const savedState = context.get("state");
156
59
  if (typeof savedState?.offTimerDueAt === "number") {
157
60
  armOffTimer(Math.max(0, savedState.offTimerDueAt - Date.now()), Number(savedState.offTimerGeneration) || 0);
158
61
  }
159
- statusTimer = setInterval(() => {
160
- const saved = context.get("state");
161
- updateStatus({
162
- enabled: saved?.areaEnabled !== false && globalContext.get("MOTION_ENABLED_STATE") !== false,
163
- illuminance: saved?.illuminance ?? null,
164
- delaySeconds: saved?.delaySeconds ?? policyConfig.defaultDelaySeconds,
165
- switch: (0, wall_input_1.wallInputStatus)(saved?.wallInput, policyConfig.switchFreshnessMs)
166
- });
167
- }, Math.max(1000, Math.min(60_000, policyConfig.switchFreshnessMs)));
168
- node.on("input", (msg, send, done) => {
169
- try {
170
- process({
171
- source: String(msg.source ?? ""),
172
- payload: msg.payload,
173
- retain: msg.retain === true,
174
- baseline: msg.baseline === true,
175
- observedAt: msg.observedAt
176
- }, send);
177
- done();
178
- }
179
- catch (error) {
180
- node.error(error, msg);
181
- done(error instanceof Error ? error : new Error(String(error)));
182
- }
62
+ (0, adapter_1.onInput)(node, (msg, send) => {
63
+ process({ source: String(msg.source ?? ""), payload: msg.payload }, send);
183
64
  });
184
65
  node.on("close", (_removed, done) => {
185
66
  clearTimeout(offTimer);
186
- clearTimeout(switchTimer);
187
- clearInterval(statusTimer);
188
67
  done();
189
68
  });
190
69
  }
@@ -4,13 +4,13 @@
4
4
  color: "#c7e9c0",
5
5
  defaults: {
6
6
  name: {value: ""},
7
- area: {value: "room", required: true},
7
+ area: {value: ""},
8
8
  presenceMode: {value: "none", required: true}
9
9
  },
10
10
  inputs: 1,
11
11
  outputs: 1,
12
12
  icon: "font-awesome/fa-users",
13
- label: function () { return this.name || this.area + " occupancy"; }
13
+ label: function () { return this.name || (this.area ? this.area + " " : "") + "occupancy"; }
14
14
  });
15
15
  </script>
16
16
 
@@ -1,15 +1,23 @@
1
1
  "use strict";
2
- const bounded_trace_1 = require("../lib/bounded-trace");
3
2
  const occupancy_fusion_1 = require("../lib/occupancy-fusion");
3
+ const adapter_1 = require("./adapter");
4
+ const settings_1 = require("../lib/settings");
4
5
  const registerOccupancyFusion = (RED) => {
5
6
  function HomeOccupancyFusion(config) {
6
7
  RED.nodes.createNode(this, config);
7
8
  const node = this;
8
- const context = node.context();
9
- const fusionConfig = {
10
- area: config.area || "room",
11
- presenceMode: config.presenceMode === "hold" ? "hold" : "ignore"
12
- };
9
+ let fusionConfig;
10
+ try {
11
+ // The editor offers "none" (PIR only) and "hold" (PIR plus presence).
12
+ const presence = (0, settings_1.textSetting)(config.presenceMode, "presence sensor", "none");
13
+ if (presence !== "none" && presence !== "hold")
14
+ throw new Error("presence sensor must be none or hold");
15
+ fusionConfig = { area: (0, adapter_1.optionalArea)(config), presenceMode: presence === "hold" ? "hold" : "ignore" };
16
+ }
17
+ catch (error) {
18
+ (0, adapter_1.invalidConfig)(node, error);
19
+ return;
20
+ }
13
21
  function updateStatus(status) {
14
22
  const details = [status.occupied ? "occupied" : "vacant"];
15
23
  if (status.motion !== null)
@@ -22,29 +30,15 @@ const registerOccupancyFusion = (RED) => {
22
30
  text: details.join(" · ")
23
31
  });
24
32
  }
25
- node.on("input", (msg, send, done) => {
26
- try {
27
- const now = new Date();
28
- const saved = context.get("state");
29
- const input = {
30
- source: String(msg.source ?? ""),
31
- payload: msg.payload
32
- };
33
- const result = (0, occupancy_fusion_1.transitionOccupancy)(saved, input, fusionConfig);
34
- context.set("state", result.state);
35
- (0, bounded_trace_1.appendTrace)(context, {
36
- area: fusionConfig.area,
37
- component: "occupancy-fusion"
38
- }, result.traces, now);
39
- for (const output of result.outputs)
40
- send({ ...output, payload: output.payload });
41
- updateStatus(result.status);
42
- done();
43
- }
44
- catch (error) {
45
- node.error(error, msg);
46
- done(error instanceof Error ? error : new Error(String(error)));
47
- }
33
+ (0, adapter_1.onInput)(node, (msg, send) => {
34
+ const input = {
35
+ source: String(msg.source ?? ""),
36
+ payload: msg.payload
37
+ };
38
+ const result = (0, adapter_1.runReducer)(node, { area: fusionConfig.area, component: "occupancy-fusion" }, (saved) => (0, occupancy_fusion_1.transitionOccupancy)(saved, input, fusionConfig));
39
+ for (const output of result.outputs)
40
+ send({ ...output, payload: output.payload });
41
+ updateStatus(result.status);
48
42
  });
49
43
  }
50
44
  RED.nodes.registerType("home-occupancy-fusion", HomeOccupancyFusion);
@@ -1,33 +1,69 @@
1
1
  <script type="text/javascript">
2
- RED.nodes.registerType("home-room-lighting-controller", {
3
- category: "home automation",
4
- color: "#ffd27f",
5
- defaults: {
6
- name: {value: ""},
7
- area: {value: "room", required: true},
8
- displayName: {value: "Room", required: true},
9
- targets: {value: "[]", required: true},
10
- maxBrightnessPct: {value: 100, required: true, validate: RED.validators.number()},
11
- maxColorTempKelvin: {value: 6500, required: true, validate: RED.validators.number()},
12
- sleepBrightnessPct: {value: 1, required: true, validate: RED.validators.number()},
13
- sleepColorTempKelvin: {value: 2200, required: true, validate: RED.validators.number()},
14
- initialTransitionSeconds: {value: 1, required: true, validate: RED.validators.number()},
15
- refreshTransitionSeconds: {value: 60, required: true, validate: RED.validators.number()},
16
- refreshSeconds: {value: 60, required: true, validate: RED.validators.number()},
17
- initialSleep: {value: false},
18
- wakeTime: {value: "07:00", required: true, validate: function (v) { return /^([01]\d|2[0-3]):[0-5]\d$/.test(v); }},
19
- bedTime: {value: "23:00", required: true, validate: function (v) { return /^([01]\d|2[0-3]):[0-5]\d$/.test(v); }}
20
- },
21
- inputs: 1,
22
- outputs: 1,
23
- icon: "font-awesome/fa-lightbulb-o",
24
- label: function () { return this.name || this.area + " lighting controller"; }
25
- });
2
+ (function () {
3
+ // A setting is on unless it was explicitly switched off; null ("not set")
4
+ // shows as ticked.
5
+ function on(value) { return value !== false && value !== "false"; }
6
+ RED.nodes.registerType("home-room-lighting-controller", {
7
+ category: "home automation",
8
+ color: "#ffd27f",
9
+ defaults: {
10
+ name: {value: ""},
11
+ // Required only when the room publishes something named after it.
12
+ area: {value: "", validate: function (v) {
13
+ var publishing = $("#node-input-publishState").length
14
+ ? $("#node-input-publishState").prop("checked") || $("#node-input-discovery").prop("checked")
15
+ : on(this.publishState) || on(this.discovery);
16
+ return !publishing || Boolean(v && v.trim());
17
+ }},
18
+ // null means "not set": Node-RED fills it into a saved flow from before
19
+ // these settings, which keeps publishing. New nodes start with both
20
+ // off (onadd).
21
+ publishState: {value: null},
22
+ discovery: {value: null},
23
+ displayName: {value: ""},
24
+ targets: {value: "[]", required: true, validate: function (v) { try { JSON.parse(v); return true; } catch (e) { return false; } }},
25
+ maxBrightnessPct: {value: 100, required: true, validate: RED.validators.number()},
26
+ maxColorTempKelvin: {value: 6500, required: true, validate: RED.validators.number()},
27
+ sleepBrightnessPct: {value: 1, required: true, validate: RED.validators.number()},
28
+ sleepColorTempKelvin: {value: 2200, required: true, validate: RED.validators.number()},
29
+ initialTransitionSeconds: {value: 1, required: true, validate: RED.validators.number()},
30
+ refreshTransitionSeconds: {value: 60, required: true, validate: RED.validators.number()},
31
+ refreshSeconds: {value: 60, required: true, validate: RED.validators.number()},
32
+ initialSleep: {value: false},
33
+ wakeTime: {value: "07:00", required: true, validate: function (v) { return /^([01]\d|2[0-3]):[0-5]\d$/.test(v); }},
34
+ bedTime: {value: "23:00", required: true, validate: function (v) { return /^([01]\d|2[0-3]):[0-5]\d$/.test(v); }}
35
+ },
36
+ onadd: function () {
37
+ this.publishState = false;
38
+ this.discovery = false;
39
+ },
40
+ oneditprepare: function () {
41
+ var node = this;
42
+ $("#node-input-publishState").prop("checked", on(node.publishState));
43
+ $("#node-input-discovery").prop("checked", on(node.discovery));
44
+ // Discovery describes the published state, so it needs it.
45
+ function follow() {
46
+ var publishing = $("#node-input-publishState").prop("checked");
47
+ if (!publishing) $("#node-input-discovery").prop("checked", false);
48
+ $("#node-input-discovery").prop("disabled", !publishing);
49
+ $("#node-input-area").trigger("change");
50
+ }
51
+ $("#node-input-publishState, #node-input-discovery").on("change", follow);
52
+ follow();
53
+ },
54
+ inputs: 1,
55
+ outputs: 1,
56
+ icon: "font-awesome/fa-lightbulb-o",
57
+ label: function () { return this.name || (this.area ? this.area + " " : "") + "lighting controller"; }
58
+ });
59
+ })();
26
60
  </script>
27
61
 
28
62
  <script type="text/html" data-template-name="home-room-lighting-controller">
29
63
  <div class="form-row"><label for="node-input-name">Name</label><input type="text" id="node-input-name"></div>
30
- <div class="form-row"><label for="node-input-area">Area</label><input type="text" id="node-input-area"></div>
64
+ <div class="form-row"><label for="node-input-area">Area</label><input type="text" id="node-input-area" placeholder="needed when publishing"></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>
31
67
  <div class="form-row"><label for="node-input-displayName">Display name</label><input type="text" id="node-input-displayName"></div>
32
68
  <div class="form-row"><label for="node-input-targets">Targets JSON</label><input type="text" id="node-input-targets"></div>
33
69
  <div class="form-row"><label for="node-input-maxBrightnessPct">Daytime brightness %</label><input type="number" id="node-input-maxBrightnessPct"></div>
@@ -44,6 +80,19 @@
44
80
 
45
81
  <script type="text/html" data-help-name="home-room-lighting-controller">
46
82
  <p>Owns room MQTT commands, adaptive colour and brightness, manual overrides, discovery and bounded tracing.</p>
83
+ <h3>Publishing</h3>
84
+ <p>The room always commands its lights on each target's own command topic. Two settings add what it publishes
85
+ for other systems to see; both are named after the <b>Area</b>, which is needed only when one of them is on.</p>
86
+ <dl class="message-properties">
87
+ <dt>Publish state over MQTT</dt><dd>each light's control state on
88
+ <code>home/&lt;area&gt;/lighting/&lt;target&gt;/control</code> and the circadian state on
89
+ <code>home/&lt;area&gt;/circadian/state</code>.</dd>
90
+ <dt>Home Assistant discovery</dt><dd>a circadian switch in Home Assistant, which reads that state and sends
91
+ ON/OFF to <code>home/&lt;area&gt;/circadian/set</code>. To act on it, wire an MQTT in node subscribed to that
92
+ topic into this node. It needs <b>Publish state</b>. Switching it off
93
+ removes the switch from Home Assistant at the next start.</dd>
94
+ </dl>
95
+ <p>New nodes start with both off. A node saved before these settings existed keeps publishing both.</p>
47
96
  <h3>Circadian schedule</h3>
48
97
  <p>Circadian levels follow <b>Wake time</b> and <b>Bed time</b> (24-hour <code>HH:MM</code>, default 07:00 and
49
98
  23:00): they rise to the daytime level over the hour after waking, stay at the daytime brightness and colour
@@ -68,6 +117,10 @@
68
117
  Switching a light off by its owner or a person returns it to in-control.</p>
69
118
  <h3>Inputs</h3>
70
119
  <dl class="message-properties">
120
+ <dt>topic = home/&lt;area&gt;/circadian/set</dt>
121
+ <dd>payload <code>ON</code> or <code>OFF</code> (any case) switches circadian lighting on or off, as
122
+ <code>lighting.kind = "circadian"</code> does. Read only while <b>Publish state</b> is on and the area is set.
123
+ Retained messages and other payloads are ignored.</dd>
71
124
  <dt>lighting.owner <span class="property-type">string</span></dt>
72
125
  <dd>on an <code>intent</code> that switches targets on, marks them overridden by this owner. With
73
126
  <code>preserveManual: true</code>, manual lights are skipped.</dd>
@@ -76,7 +129,8 @@
76
129
  held by that owner are released. Released lights that are on are restyled as a refresh would.</dd>
77
130
  </dl>
78
131
  <h3>Outputs</h3>
79
- <p>On startup and whenever a target's control state changes, a retained message is sent with topic
132
+ <p>With <b>Publish state</b> on, on startup and whenever a target's control state changes, a retained message is
133
+ sent with topic
80
134
  <code>home/&lt;area&gt;/lighting/&lt;target&gt;/control</code> and payload
81
135
  <code>{"state": "in-control" | "overridden" | "manual", "owner": string | null}</code>.</p>
82
136
  </script>
@@ -1,14 +1,11 @@
1
1
  "use strict";
2
- const bounded_trace_1 = require("../lib/bounded-trace");
3
2
  const room_controller_1 = require("../lib/room-controller");
4
3
  const circadian_1 = require("../lib/circadian");
5
4
  const circadian_schedule_1 = require("../lib/circadian-schedule");
6
- function number(value, fallback) {
7
- const parsed = Number(value);
8
- return Number.isFinite(parsed) ? parsed : fallback;
9
- }
5
+ const adapter_1 = require("./adapter");
6
+ const settings_1 = require("../lib/settings");
10
7
  function parseTargets(value) {
11
- const targets = JSON.parse(value || "[]");
8
+ const targets = (0, settings_1.jsonSetting)(value, "targets", []);
12
9
  if (!Array.isArray(targets) || targets.some((target) => {
13
10
  if (!target || typeof target !== "object")
14
11
  return true;
@@ -29,36 +26,44 @@ const registerRoomController = (RED) => {
29
26
  function HomeRoomLightingController(config) {
30
27
  RED.nodes.createNode(this, config);
31
28
  const node = this;
32
- const context = node.context();
29
+ const area = (0, adapter_1.optionalArea)(config);
33
30
  let refreshTimer;
34
31
  let controllerConfig;
32
+ let refreshSeconds;
35
33
  try {
34
+ // Not set (null, or absent from a flow saved before these settings)
35
+ // means on, so an older flow keeps publishing as before.
36
+ const publishState = (0, settings_1.optionalBooleanSetting)(config.publishState, "publish state") ?? true;
37
+ const discovery = (0, settings_1.optionalBooleanSetting)(config.discovery, "Home Assistant discovery") ?? true;
38
+ // Both publish under topics and IDs named after the area.
39
+ if ((publishState || discovery) && !area)
40
+ throw new Error("area is required");
41
+ refreshSeconds = Math.max(10, (0, settings_1.numberSetting)(config.refreshSeconds, "refresh interval", 60));
36
42
  // Saved latitude, longitude and minimum settings from earlier versions
37
43
  // are ignored.
38
44
  const levels = {
39
- maxBrightnessPct: number(config.maxBrightnessPct, 100),
40
- maxColorTempKelvin: number(config.maxColorTempKelvin, 6500),
41
- sleepBrightnessPct: number(config.sleepBrightnessPct, 1),
42
- sleepColorTempKelvin: number(config.sleepColorTempKelvin, 2200)
45
+ maxBrightnessPct: (0, settings_1.numberSetting)(config.maxBrightnessPct, "daytime brightness", 100),
46
+ maxColorTempKelvin: (0, settings_1.numberSetting)(config.maxColorTempKelvin, "daytime colour temperature", 6500),
47
+ sleepBrightnessPct: (0, settings_1.numberSetting)(config.sleepBrightnessPct, "sleep brightness", 1),
48
+ sleepColorTempKelvin: (0, settings_1.numberSetting)(config.sleepColorTempKelvin, "sleep colour temperature", 2200)
43
49
  };
44
- const schedule = (0, circadian_schedule_1.resolveSchedule)(config.wakeTime, config.bedTime);
50
+ const schedule = (0, circadian_schedule_1.resolveSchedule)((0, settings_1.textSetting)(config.wakeTime, "wake time", "07:00"), (0, settings_1.textSetting)(config.bedTime, "bed time", "23:00"));
45
51
  controllerConfig = {
46
- area: config.area || "room",
47
- displayName: config.displayName || config.area || "Room",
52
+ area,
53
+ displayName: config.displayName || area,
54
+ publishState,
55
+ discovery,
48
56
  targets: parseTargets(config.targets),
49
- ...levels,
50
- ...schedule,
51
- initialTransitionSeconds: number(config.initialTransitionSeconds, 1),
52
- refreshTransitionSeconds: number(config.refreshTransitionSeconds, 60),
53
- initialSleep: config.initialSleep === true || config.initialSleep === "true",
57
+ initialTransitionSeconds: (0, settings_1.numberSetting)(config.initialTransitionSeconds, "initial transition", 1),
58
+ refreshTransitionSeconds: (0, settings_1.numberSetting)(config.refreshTransitionSeconds, "refresh transition", 60),
59
+ initialSleep: (0, settings_1.booleanSetting)(config.initialSleep, "initial sleep", false),
54
60
  // The adapter picks the circadian lighting; the controller only asks
55
61
  // it how a light should look.
56
62
  lighting: (0, circadian_1.scheduledLighting)(schedule, levels)
57
63
  };
58
64
  }
59
65
  catch (error) {
60
- node.status({ fill: "red", shape: "ring", text: "invalid configuration" });
61
- node.error("invalid configuration: " + (error instanceof Error ? error.message : String(error)));
66
+ (0, adapter_1.invalidConfig)(node, error);
62
67
  return;
63
68
  }
64
69
  function updateStatus(status) {
@@ -72,46 +77,24 @@ const registerRoomController = (RED) => {
72
77
  });
73
78
  }
74
79
  function process(msg, send) {
75
- const now = new Date();
76
- const saved = context.get("state");
77
- const result = (0, room_controller_1.transitionRoom)(saved, msg, controllerConfig, now);
78
- context.set("state", result.state);
79
- (0, bounded_trace_1.appendTrace)(context, {
80
- area: controllerConfig.area,
81
- component: "room-controller"
82
- }, result.traces, now);
80
+ const result = (0, adapter_1.runReducer)(node, { area: controllerConfig.area, component: "room-controller" }, (saved, now) => (0, room_controller_1.transitionRoom)(saved, msg, controllerConfig, now));
83
81
  if (result.outputs.length) {
84
82
  send([result.outputs.map((output) => ({ ...output, payload: output.payload }))]);
85
83
  }
86
84
  updateStatus(result.status);
87
85
  return result;
88
86
  }
89
- node.on("input", (msg, send, done) => {
90
- try {
91
- process({
92
- lighting: msg.lighting && typeof msg.lighting === "object"
93
- ? msg.lighting
94
- : undefined,
95
- topic: typeof msg.topic === "string" ? msg.topic : undefined,
96
- payload: msg.payload,
97
- retain: msg.retain === true
98
- }, send);
99
- done();
100
- }
101
- catch (error) {
102
- node.error(error, msg);
103
- done(error instanceof Error ? error : new Error(String(error)));
104
- }
87
+ (0, adapter_1.onInput)(node, (msg, send) => {
88
+ process({
89
+ lighting: (0, adapter_1.objectField)(msg, "lighting"),
90
+ topic: typeof msg.topic === "string" ? msg.topic : undefined,
91
+ payload: msg.payload,
92
+ retain: msg.retain === true
93
+ }, send);
105
94
  });
106
- const refreshSeconds = Math.max(10, number(config.refreshSeconds, 60));
107
- refreshTimer = setInterval(() => {
108
- try {
109
- process({ lighting: { kind: "refresh" } }, node.send.bind(node));
110
- }
111
- catch (error) {
112
- node.error(error);
113
- }
114
- }, refreshSeconds * 1000);
95
+ refreshTimer = setInterval((0, adapter_1.guarded)(node, () => {
96
+ process({ lighting: { kind: "refresh" } }, node.send.bind(node));
97
+ }), refreshSeconds * 1000);
115
98
  node.on("close", (_removed, done) => {
116
99
  clearInterval(refreshTimer);
117
100
  done();
@@ -4,19 +4,10 @@
4
4
  color: "#c7d9f1",
5
5
  defaults: {
6
6
  name: {value: ""},
7
- area: {value: "lounge", required: true},
8
- sources: {
9
- value: "{}",
10
- required: true,
11
- validate: function(value) {
12
- try {
13
- const parsed = JSON.parse(value);
14
- return parsed && typeof parsed === "object" && !Array.isArray(parsed);
15
- } catch (_) {
16
- return false;
17
- }
18
- }
19
- },
7
+ area: {value: ""},
8
+ // User data with no sensible default: empty until the user fills it in,
9
+ // and marked invalid until then, as the runtime rejects it.
10
+ sources: {value: "{}", required: true, validate: function (v) { try { var parsed = JSON.parse(v); return Boolean(parsed) && typeof parsed === "object" && !Array.isArray(parsed) && Object.keys(parsed).length > 0; } catch (e) { return false; } }},
20
11
  pollMs: {value: 2000, required: true, validate: RED.validators.number()},
21
12
  confirmationTimeoutMs: {value: 15000, required: true, validate: RED.validators.number()},
22
13
  maxAttempts: {value: 2, required: true, validate: RED.validators.number()}