@avantics/node-red-home-automation 2.3.0 → 3.0.1

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 +55 -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 +22 -0
  11. package/dist/lib/command-echo.js +106 -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 +15 -34
  22. package/dist/lib/room-controller.js +100 -134
  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 +85 -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,31 +1,22 @@
1
1
  "use strict";
2
- const bounded_trace_1 = require("../lib/bounded-trace");
3
2
  const source_capability_controller_1 = require("../lib/source-capability-controller");
4
- function number(value, fallback) {
5
- const parsed = Number(value);
6
- return Number.isFinite(parsed) ? parsed : fallback;
7
- }
3
+ const adapter_1 = require("./adapter");
4
+ const settings_1 = require("../lib/settings");
8
5
  const registerSourceCapabilityController = (RED) => {
9
6
  function HomeSourceCapabilityController(config) {
10
7
  RED.nodes.createNode(this, config);
11
8
  const node = this;
12
9
  const context = node.context();
13
10
  let timer;
14
- let sources;
11
+ let controllerConfig;
15
12
  try {
16
- sources = (0, source_capability_controller_1.normaliseCapabilities)(JSON.parse(config.sources || "{}"));
13
+ // Defaults and limits come from the reducer's own normalisation.
14
+ controllerConfig = (0, source_capability_controller_1.normaliseConfig)({ ...config, sources: (0, settings_1.jsonSetting)(config.sources, "sources", {}) });
17
15
  }
18
16
  catch (error) {
19
- node.status({ fill: "red", shape: "ring", text: "invalid source JSON" });
20
- node.error(error);
17
+ (0, adapter_1.invalidConfig)(node, error);
21
18
  return;
22
19
  }
23
- const controllerConfig = {
24
- sources,
25
- pollMs: number(config.pollMs, 2000),
26
- confirmationTimeoutMs: number(config.confirmationTimeoutMs, 15000),
27
- maxAttempts: number(config.maxAttempts, 2)
28
- };
29
20
  function updateStatus(status) {
30
21
  const appearances = {
31
22
  idle: { fill: "grey", shape: "dot" },
@@ -45,24 +36,12 @@ const registerSourceCapabilityController = (RED) => {
45
36
  if (!state.pending?.nextAt)
46
37
  return;
47
38
  const delay = Math.max(0, state.pending.nextAt - Date.now());
48
- timer = setTimeout(() => {
49
- try {
50
- process({ sourceCapability: { kind: "tick", generation: state.generation } }, node.send.bind(node));
51
- }
52
- catch (error) {
53
- node.error(error);
54
- }
55
- }, delay);
39
+ timer = setTimeout((0, adapter_1.guarded)(node, () => {
40
+ process({ sourceCapability: { kind: "tick", generation: state.generation } }, node.send.bind(node));
41
+ }), delay);
56
42
  }
57
43
  function process(msg, send) {
58
- const now = new Date();
59
- const saved = context.get("state");
60
- const result = (0, source_capability_controller_1.transitionSource)(saved, msg, controllerConfig, now);
61
- context.set("state", result.state);
62
- (0, bounded_trace_1.appendTrace)(context, {
63
- area: config.area || "lounge",
64
- component: "source-capability-controller"
65
- }, result.traces, now);
44
+ const result = (0, adapter_1.runReducer)(node, { area: (0, adapter_1.optionalArea)(config), component: "source-capability-controller" }, (saved, now) => (0, source_capability_controller_1.transitionSource)(saved, msg, controllerConfig, now));
66
45
  if (result.commands.length) {
67
46
  send([
68
47
  result.commands.map((sourceCommand) => ({ payload: undefined, sourceCommand })),
@@ -80,28 +59,14 @@ const registerSourceCapabilityController = (RED) => {
80
59
  // transition with the reducer's own startup (re-observe, never replay)
81
60
  // rather than ticking old state; a later startup from the flow repeats it.
82
61
  if (context.get("state")?.pending) {
83
- timer = setTimeout(() => {
84
- try {
85
- process({ sourceCapability: { kind: "startup" } }, node.send.bind(node));
86
- }
87
- catch (error) {
88
- node.error(error);
89
- }
90
- }, 0);
62
+ timer = setTimeout((0, adapter_1.guarded)(node, () => {
63
+ process({ sourceCapability: { kind: "startup" } }, node.send.bind(node));
64
+ }), 0);
91
65
  }
92
- node.on("input", (msg, send, done) => {
93
- try {
94
- process({
95
- sourceCapability: msg.sourceCapability && typeof msg.sourceCapability === "object"
96
- ? msg.sourceCapability
97
- : undefined
98
- }, send);
99
- done();
100
- }
101
- catch (error) {
102
- node.error(error, msg);
103
- done(error instanceof Error ? error : new Error(String(error)));
104
- }
66
+ (0, adapter_1.onInput)(node, (msg, send) => {
67
+ process({
68
+ sourceCapability: (0, adapter_1.objectField)(msg, "sourceCapability")
69
+ }, send);
105
70
  });
106
71
  node.on("close", (_removed, done) => {
107
72
  clearTimeout(timer);
@@ -4,15 +4,15 @@
4
4
  color: "#d8bfd8",
5
5
  defaults: {
6
6
  name: {value: ""},
7
- area: {value: "room", required: true},
8
- targets: {value: "[\"main\"]", required: true},
7
+ area: {value: ""},
8
+ targets: {value: "[\"main\"]", required: true, validate: function (v) { try { JSON.parse(v); return true; } catch (e) { return false; } }},
9
9
  switchWindowMs: {value: 500, required: true, validate: RED.validators.number()},
10
10
  switchFreshnessSeconds: {value: 3600, required: true, validate: RED.validators.number()}
11
11
  },
12
12
  inputs: 1,
13
13
  outputs: 1,
14
14
  icon: "font-awesome/fa-toggle-on",
15
- label: function () { return this.name || this.area + " switch policy"; }
15
+ label: function () { return this.name || (this.area ? this.area + " " : "") + "switch policy"; }
16
16
  });
17
17
  </script>
18
18
 
@@ -1,7 +1,8 @@
1
1
  "use strict";
2
- const bounded_trace_1 = require("../lib/bounded-trace");
3
2
  const wall_input_1 = require("../lib/wall-input");
4
3
  const switch_policy_1 = require("../lib/switch-policy");
4
+ const adapter_1 = require("./adapter");
5
+ const settings_1 = require("../lib/settings");
5
6
  function ageText(ageMs) {
6
7
  if (ageMs === null)
7
8
  return "age ?";
@@ -12,7 +13,7 @@ function ageText(ageMs) {
12
13
  return `${Math.floor(ageMs / 3_600_000)}h`;
13
14
  }
14
15
  function parseTargets(value) {
15
- const parsed = JSON.parse(value || "[\"main\"]");
16
+ const parsed = (0, settings_1.jsonSetting)(value, "targets", ["main"]);
16
17
  if (!Array.isArray(parsed) || parsed.length === 0 || parsed.some((item) => typeof item !== "string")) {
17
18
  throw new Error("targets must be a non-empty JSON array of strings");
18
19
  }
@@ -28,10 +29,10 @@ const registerSwitchPolicy = (RED) => {
28
29
  let policyConfig;
29
30
  try {
30
31
  policyConfig = {
31
- area: config.area || "room",
32
+ area: (0, adapter_1.optionalArea)(config),
32
33
  targets: parseTargets(config.targets),
33
- switchWindowMs: Number(config.switchWindowMs ?? 500),
34
- switchFreshnessMs: Number(config.switchFreshnessSeconds ?? 3600) * 1000
34
+ switchWindowMs: (0, settings_1.numberSetting)(config.switchWindowMs, "switch window", 500),
35
+ switchFreshnessMs: (0, settings_1.numberSetting)(config.switchFreshnessSeconds, "switch freshness", 3600) * 1000
35
36
  };
36
37
  if (!Number.isFinite(policyConfig.switchWindowMs) || policyConfig.switchWindowMs < 0) {
37
38
  throw new Error("switch window must be a non-negative number");
@@ -41,8 +42,7 @@ const registerSwitchPolicy = (RED) => {
41
42
  }
42
43
  }
43
44
  catch (error) {
44
- node.status({ fill: "red", shape: "ring", text: "invalid configuration" });
45
- node.error(error);
45
+ (0, adapter_1.invalidConfig)(node, error);
46
46
  return;
47
47
  }
48
48
  function updateStatus(status) {
@@ -60,14 +60,7 @@ const registerSwitchPolicy = (RED) => {
60
60
  }
61
61
  }
62
62
  function process(input, send) {
63
- const now = new Date();
64
- const saved = context.get("state");
65
- const result = (0, switch_policy_1.transitionSwitchPolicy)(saved, input, policyConfig, now.getTime());
66
- context.set("state", result.state);
67
- (0, bounded_trace_1.appendTrace)(context, {
68
- area: policyConfig.area,
69
- component: "switch-policy"
70
- }, result.traces, now);
63
+ const result = (0, adapter_1.runReducer)(node, { area: policyConfig.area, component: "switch-policy" }, (saved, now) => (0, switch_policy_1.transitionSwitchPolicy)(saved, input, policyConfig, now.getTime()));
71
64
  for (const effect of result.effects) {
72
65
  if (effect.kind === "cancel-switch-timer") {
73
66
  clearTimeout(timer);
@@ -75,19 +68,14 @@ const registerSwitchPolicy = (RED) => {
75
68
  }
76
69
  else if (effect.kind === "schedule-switch-timer") {
77
70
  clearTimeout(timer);
78
- timer = setTimeout(() => {
71
+ timer = setTimeout((0, adapter_1.guarded)(node, () => {
79
72
  timer = undefined;
80
- try {
81
- process({
82
- source: "switch-timer",
83
- generation: effect.generation,
84
- switchAt: effect.switchAt
85
- }, node.send.bind(node));
86
- }
87
- catch (error) {
88
- node.error(error);
89
- }
90
- }, effect.delayMs);
73
+ process({
74
+ source: "switch-timer",
75
+ generation: effect.generation,
76
+ switchAt: effect.switchAt
77
+ }, node.send.bind(node));
78
+ }), effect.delayMs);
91
79
  }
92
80
  else {
93
81
  send({ payload: undefined, ...effect.message });
@@ -101,21 +89,14 @@ const registerSwitchPolicy = (RED) => {
101
89
  const saved = context.get("state");
102
90
  updateStatus((0, wall_input_1.wallInputStatus)(saved?.wallInput, policyConfig.switchFreshnessMs));
103
91
  }, Math.max(1000, Math.min(60_000, policyConfig.switchFreshnessMs)));
104
- node.on("input", (msg, send, done) => {
105
- try {
106
- process({
107
- source: String(msg.source ?? ""),
108
- payload: msg.payload,
109
- retain: msg.retain === true,
110
- baseline: msg.baseline === true,
111
- observedAt: msg.observedAt
112
- }, send);
113
- done();
114
- }
115
- catch (error) {
116
- node.error(error, msg);
117
- done(error instanceof Error ? error : new Error(String(error)));
118
- }
92
+ (0, adapter_1.onInput)(node, (msg, send) => {
93
+ process({
94
+ source: String(msg.source ?? ""),
95
+ payload: msg.payload,
96
+ retain: msg.retain === true,
97
+ baseline: msg.baseline === true,
98
+ observedAt: msg.observedAt
99
+ }, send);
119
100
  });
120
101
  node.on("close", (_removed, done) => {
121
102
  clearTimeout(timer);
@@ -4,10 +4,12 @@
4
4
  color: "#d9c7f1",
5
5
  defaults: {
6
6
  name: {value: ""},
7
- area: {value: "lounge", required: true},
7
+ area: {value: ""},
8
8
  freshnessMs: {value: 30000, required: true, validate: RED.validators.number()},
9
9
  recoveryOffActivity: {value: "off", required: true},
10
- activityProfiles: {value: "{}", required: true}
10
+ // User data with no sensible default: empty until the user fills it in,
11
+ // and marked invalid until then, as the runtime rejects it.
12
+ activityProfiles: {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; } }}
11
13
  },
12
14
  inputs: 1,
13
15
  outputs: 2,
@@ -1,31 +1,26 @@
1
1
  "use strict";
2
- const bounded_trace_1 = require("../lib/bounded-trace");
3
2
  const theatre_activity_controller_1 = require("../lib/theatre-activity-controller");
4
- function number(value, fallback) {
5
- const parsed = Number(value);
6
- return Number.isFinite(parsed) ? parsed : fallback;
7
- }
3
+ const adapter_1 = require("./adapter");
4
+ const settings_1 = require("../lib/settings");
8
5
  const registerTheatreActivityController = (RED) => {
9
6
  function HomeTheatreActivityController(config) {
10
7
  RED.nodes.createNode(this, config);
11
8
  const node = this;
12
9
  const context = node.context();
13
10
  let timer;
14
- let activityProfiles;
11
+ let controllerConfig;
15
12
  try {
16
- activityProfiles = (0, theatre_activity_controller_1.normaliseActivityProfiles)(JSON.parse(config.activityProfiles || "{}"));
13
+ controllerConfig = {
14
+ area: (0, adapter_1.optionalArea)(config),
15
+ freshnessMs: Math.max(1000, (0, settings_1.numberSetting)(config.freshnessMs, "freshness", 30000)),
16
+ activityProfiles: (0, theatre_activity_controller_1.normaliseActivityProfiles)((0, settings_1.jsonSetting)(config.activityProfiles, "activity profiles", {})),
17
+ recoveryOffActivity: (0, settings_1.textSetting)(config.recoveryOffActivity, "recovery off activity", "off")
18
+ };
17
19
  }
18
20
  catch (error) {
19
- node.status({ fill: "red", shape: "ring", text: "invalid activity profiles" });
20
- node.error(error);
21
+ (0, adapter_1.invalidConfig)(node, error);
21
22
  return;
22
23
  }
23
- const controllerConfig = {
24
- area: config.area || "lounge",
25
- freshnessMs: Math.max(1000, number(config.freshnessMs, 30000)),
26
- activityProfiles,
27
- recoveryOffActivity: config.recoveryOffActivity || "off"
28
- };
29
24
  function updateStatus(status) {
30
25
  const appearances = {
31
26
  idle: { fill: "grey", shape: "dot" },
@@ -41,14 +36,7 @@ const registerTheatreActivityController = (RED) => {
41
36
  node.status({ ...appearance, text: status.text });
42
37
  }
43
38
  function process(msg, send) {
44
- const now = new Date();
45
- const saved = context.get("state");
46
- const result = (0, theatre_activity_controller_1.transitionTheatre)(saved, msg, controllerConfig, now);
47
- context.set("state", result.state);
48
- (0, bounded_trace_1.appendTrace)(context, {
49
- area: controllerConfig.area,
50
- component: "theatre-activity-controller"
51
- }, result.traces, now);
39
+ const result = (0, adapter_1.runReducer)(node, { area: controllerConfig.area, component: "theatre-activity-controller" }, (saved, now) => (0, theatre_activity_controller_1.transitionTheatre)(saved, msg, controllerConfig, now));
52
40
  if (result.commands.length) {
53
41
  send([
54
42
  result.commands.map((theatreCommand) => ({ payload: undefined, theatreCommand })),
@@ -61,39 +49,24 @@ const registerTheatreActivityController = (RED) => {
61
49
  updateStatus(result.status);
62
50
  return result;
63
51
  }
64
- node.on("input", (msg, send, done) => {
52
+ (0, adapter_1.onInput)(node, (msg, send) => {
65
53
  // Target controllers' output 2 also carries their own events (such as
66
54
  // msg.avr and msg.display) beside target state; only msg.theatre is
67
55
  // for this controller.
68
56
  if (!msg.theatre || typeof msg.theatre !== "object") {
69
- done();
70
57
  return;
71
58
  }
72
- try {
73
- process({
74
- theatre: msg.theatre && typeof msg.theatre === "object"
75
- ? msg.theatre
76
- : undefined
77
- }, send);
78
- done();
79
- }
80
- catch (error) {
81
- node.error(error, msg);
82
- done(error instanceof Error ? error : new Error(String(error)));
83
- }
59
+ process({
60
+ theatre: (0, adapter_1.objectField)(msg, "theatre")
61
+ }, send);
84
62
  });
85
- timer = setInterval(() => {
63
+ timer = setInterval((0, adapter_1.guarded)(node, () => {
86
64
  const saved = context.get("state");
87
65
  // Recovering has no desired activity yet but still needs ticks to time out.
88
66
  if (!saved?.desired && saved?.phase !== "recovering")
89
67
  return;
90
- try {
91
- process({ theatre: { kind: "tick", generation: saved.generation } }, node.send.bind(node));
92
- }
93
- catch (error) {
94
- node.error(error);
95
- }
96
- }, Math.max(1000, Math.floor(controllerConfig.freshnessMs / 2)));
68
+ process({ theatre: { kind: "tick", generation: saved.generation } }, node.send.bind(node));
69
+ }), Math.max(1000, Math.floor(controllerConfig.freshnessMs / 2)));
97
70
  node.on("close", (_removed, done) => {
98
71
  clearInterval(timer);
99
72
  done();
@@ -1,25 +1,51 @@
1
1
  <script type="text/javascript">
2
- RED.nodes.registerType("home-theatre-state-contract", {
3
- category: "home automation",
4
- color: "#d9c7f1",
5
- defaults: {
6
- name: {value: ""},
7
- area: {value: "lounge", required: true},
8
- displayName: {value: "Lounge", required: true},
9
- baseTopic: {value: "home/lounge/theatre", required: true},
10
- discoveryPrefix: {value: "homeassistant", required: true},
11
- activities: {value: "[]", required: true},
12
- sloWindowSize: {value: 20, required: true, validate: RED.validators.number()},
13
- sloMinimumSamples: {value: 5, required: true, validate: RED.validators.number()},
14
- sloLatencyBudgetMs: {value: 60000, required: true, validate: RED.validators.number()},
15
- sloSuccessObjectivePct: {value: 95, required: true, validate: RED.validators.number()}
16
- },
17
- inputs: 1,
18
- outputs: 2,
19
- outputLabels: ["activity requests", "retained MQTT state and HA discovery"],
20
- icon: "font-awesome/fa-exchange",
21
- label: function() { return this.name || "theatre state contract"; }
22
- });
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-theatre-state-contract", {
7
+ category: "home automation",
8
+ color: "#d9c7f1",
9
+ defaults: {
10
+ name: {value: ""},
11
+ // Required for discovery, and for the default base topic home/<area>/theatre.
12
+ area: {value: "", validate: function (v) {
13
+ var dialog = $("#node-input-discovery").length > 0;
14
+ var discovery = dialog ? $("#node-input-discovery").prop("checked") : on(this.discovery);
15
+ var baseTopic = dialog ? $("#node-input-baseTopic").val() : this.baseTopic;
16
+ return !(discovery || !baseTopic) || Boolean(v && v.trim());
17
+ }},
18
+ // null means "not set": Node-RED fills it into a saved flow from before
19
+ // this setting, which keeps publishing discovery. New nodes start with
20
+ // it off (onadd).
21
+ discovery: {value: null},
22
+ displayName: {value: ""},
23
+ baseTopic: {value: ""},
24
+ discoveryPrefix: {value: "homeassistant", required: true},
25
+ // User data with no sensible default: empty until the user fills it in,
26
+ // and marked invalid until then, as the runtime rejects it.
27
+ activities: {value: "[]", required: true, validate: function (v) { try { var parsed = JSON.parse(v); return Array.isArray(parsed) && parsed.length > 0; } catch (e) { return false; } }},
28
+ sloWindowSize: {value: 20, required: true, validate: RED.validators.number()},
29
+ sloMinimumSamples: {value: 5, required: true, validate: RED.validators.number()},
30
+ sloLatencyBudgetMs: {value: 60000, required: true, validate: RED.validators.number()},
31
+ sloSuccessObjectivePct: {value: 95, required: true, validate: RED.validators.number()}
32
+ },
33
+ onadd: function () {
34
+ this.discovery = false;
35
+ },
36
+ oneditprepare: function () {
37
+ $("#node-input-discovery").prop("checked", on(this.discovery));
38
+ $("#node-input-discovery, #node-input-baseTopic").on("change keyup", function () {
39
+ $("#node-input-area").trigger("change");
40
+ });
41
+ },
42
+ inputs: 1,
43
+ outputs: 2,
44
+ outputLabels: ["activity requests", "retained MQTT state and HA discovery"],
45
+ icon: "font-awesome/fa-exchange",
46
+ label: function() { return this.name || "theatre state contract"; }
47
+ });
48
+ })();
23
49
  </script>
24
50
 
25
51
  <script type="text/html" data-template-name="home-theatre-state-contract">
@@ -27,6 +53,7 @@
27
53
  <div class="form-row"><label for="node-input-area">Area</label><input type="text" id="node-input-area"></div>
28
54
  <div class="form-row"><label for="node-input-displayName">Display name</label><input type="text" id="node-input-displayName"></div>
29
55
  <div class="form-row"><label for="node-input-baseTopic">Base topic</label><input type="text" id="node-input-baseTopic"></div>
56
+ <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>
30
57
  <div class="form-row"><label for="node-input-discoveryPrefix">Discovery prefix</label><input type="text" id="node-input-discoveryPrefix"></div>
31
58
  <div class="form-row"><label for="node-input-activities">Activities JSON</label><input type="text" id="node-input-activities"></div>
32
59
  <div class="form-row"><label for="node-input-sloWindowSize">SLO window</label><input type="number" id="node-input-sloWindowSize"></div>
@@ -37,5 +64,11 @@
37
64
 
38
65
  <script type="text/html" data-help-name="home-theatre-state-contract">
39
66
  <p>Bridges non-retained MQTT activity requests to the theatre controller and publishes retained controller truth.</p>
40
- <p>Requests arrive on <code>&lt;base&gt;/request</code> with a request ID and activity. Retained requests are inert. Complete <code>msg.theatre</code> state snapshots publish desired, current, phase, failure, availability, operational SLO and per-target health topics. A startup event emits Home Assistant discovery for the activity selector and status sensors.</p>
67
+ <p>Requests arrive on <code>&lt;base&gt;/request</code> with a request ID and activity. Retained requests are inert. Complete <code>msg.theatre</code> state snapshots publish desired, current, phase, failure, availability, operational SLO and per-target health topics. </p>
68
+ <p>With <b>Home Assistant discovery</b> on, a startup event also publishes discovery for the activity selector and
69
+ status sensors; switched off, it clears them, so Home Assistant removes them. New nodes start with it off; a node
70
+ saved before the setting existed keeps it on.</p>
71
+ <p>The <b>Area</b> names the discovery entities and the default base topic <code>home/&lt;area&gt;/theatre</code>,
72
+ so it is needed when discovery is on or the base topic is empty. With discovery off and a base topic set, it is
73
+ optional.</p>
41
74
  </script>
@@ -1,42 +1,42 @@
1
1
  "use strict";
2
- const bounded_trace_1 = require("../lib/bounded-trace");
3
2
  const theatre_state_contract_1 = require("../lib/theatre-state-contract");
3
+ const adapter_1 = require("./adapter");
4
+ const settings_1 = require("../lib/settings");
4
5
  const registerTheatreStateContract = (RED) => {
5
6
  function HomeTheatreStateContract(config) {
6
7
  RED.nodes.createNode(this, config);
7
8
  const node = this;
8
- const context = node.context();
9
+ // Needed for discovery and for the default base topic; the normaliser
10
+ // says "area is required" when it is.
11
+ const area = (0, adapter_1.optionalArea)(config);
9
12
  let controllerConfig;
10
13
  try {
11
- const activities = JSON.parse(config.activities || "[]");
14
+ const activities = (0, settings_1.jsonSetting)(config.activities, "activities", []);
12
15
  controllerConfig = (0, theatre_state_contract_1.normaliseStateContractConfig)({
13
- area: config.area || "lounge",
14
- displayName: config.displayName || config.area || "Lounge",
15
- baseTopic: config.baseTopic || `home/${config.area || "lounge"}/theatre`,
16
- discoveryPrefix: config.discoveryPrefix || "homeassistant",
17
- activities: Array.isArray(activities) ? activities.map(String) : [],
16
+ area,
17
+ // Optional, with documented meanings: an empty display name is the
18
+ // area, and an empty base topic is home/<area>/theatre.
19
+ displayName: config.displayName || area,
20
+ baseTopic: config.baseTopic || "",
21
+ // Not set (null, or absent from a flow saved before the setting)
22
+ // means on, so an older flow keeps publishing discovery.
23
+ discovery: (0, settings_1.optionalBooleanSetting)(config.discovery, "Home Assistant discovery") ?? true,
24
+ discoveryPrefix: (0, settings_1.textSetting)(config.discoveryPrefix, "discovery prefix", "homeassistant"),
25
+ activities: (Array.isArray(activities) ? activities.map(String) : activities),
18
26
  slo: {
19
- windowSize: Number(config.sloWindowSize ?? 20),
20
- minimumSamples: Number(config.sloMinimumSamples ?? 5),
21
- latencyBudgetMs: Number(config.sloLatencyBudgetMs ?? 60000),
22
- successObjectivePct: Number(config.sloSuccessObjectivePct ?? 95)
27
+ windowSize: (0, settings_1.numberSetting)(config.sloWindowSize, "SLO window", 20),
28
+ minimumSamples: (0, settings_1.numberSetting)(config.sloMinimumSamples, "minimum samples", 5),
29
+ latencyBudgetMs: (0, settings_1.numberSetting)(config.sloLatencyBudgetMs, "latency budget", 60000),
30
+ successObjectivePct: (0, settings_1.numberSetting)(config.sloSuccessObjectivePct, "success objective", 95)
23
31
  }
24
32
  });
25
33
  }
26
34
  catch (error) {
27
- node.status({ fill: "red", shape: "ring", text: "invalid state contract" });
28
- node.error(error);
35
+ (0, adapter_1.invalidConfig)(node, error);
29
36
  return;
30
37
  }
31
38
  function process(msg, send) {
32
- const now = new Date();
33
- const saved = context.get("state");
34
- const result = (0, theatre_state_contract_1.transitionTheatreStateContract)(saved, msg, controllerConfig, now);
35
- context.set("state", result.state);
36
- (0, bounded_trace_1.appendTrace)(context, {
37
- area: controllerConfig.area,
38
- component: "theatre-state-contract"
39
- }, result.traces, now);
39
+ const result = (0, adapter_1.runReducer)(node, { area: controllerConfig.area, component: "theatre-state-contract" }, (saved, now) => (0, theatre_state_contract_1.transitionTheatreStateContract)(saved, msg, controllerConfig, now));
40
40
  if (result.requests.length) {
41
41
  send([
42
42
  result.requests.map((request) => ({ payload: undefined, ...request })),
@@ -53,25 +53,14 @@ const registerTheatreStateContract = (RED) => {
53
53
  });
54
54
  return result;
55
55
  }
56
- node.on("input", (msg, send, done) => {
57
- try {
58
- process({
59
- topic: typeof msg.topic === "string" ? msg.topic : undefined,
60
- payload: msg.payload,
61
- retain: msg.retain === true,
62
- theatre: msg.theatre && typeof msg.theatre === "object"
63
- ? msg.theatre
64
- : undefined,
65
- theatreStateContract: msg.theatreStateContract && typeof msg.theatreStateContract === "object"
66
- ? msg.theatreStateContract
67
- : undefined
68
- }, send);
69
- done();
70
- }
71
- catch (error) {
72
- node.error(error, msg);
73
- done(error instanceof Error ? error : new Error(String(error)));
74
- }
56
+ (0, adapter_1.onInput)(node, (msg, send) => {
57
+ process({
58
+ topic: typeof msg.topic === "string" ? msg.topic : undefined,
59
+ payload: msg.payload,
60
+ retain: msg.retain === true,
61
+ theatre: (0, adapter_1.objectField)(msg, "theatre"),
62
+ theatreStateContract: (0, adapter_1.objectField)(msg, "theatreStateContract")
63
+ }, send);
75
64
  });
76
65
  node.on("close", (_removed, done) => {
77
66
  done();