@avantics/node-red-home-automation 0.0.0-stage → 2.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 (91) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +292 -2
  3. package/contract-examples/README.md +28 -0
  4. package/contract-examples/_shared.mjs +11 -0
  5. package/contract-examples/motion-lighting.mjs +42 -0
  6. package/contract-examples/occupancy-fusion.mjs +35 -0
  7. package/contract-examples/room-lighting.mjs +58 -0
  8. package/contract-examples/run.mjs +16 -0
  9. package/contract-examples/source-readiness.mjs +64 -0
  10. package/contract-examples/switch-gestures.mjs +34 -0
  11. package/contract-examples/theatre-activity.mjs +62 -0
  12. package/contract-examples/volume-ownership.mjs +59 -0
  13. package/dist/lib/activity-lighting-controller.d.ts +129 -0
  14. package/dist/lib/activity-lighting-controller.js +372 -0
  15. package/dist/lib/avr-controller.d.ts +169 -0
  16. package/dist/lib/avr-controller.js +948 -0
  17. package/dist/lib/backlighting-controller.d.ts +108 -0
  18. package/dist/lib/backlighting-controller.js +269 -0
  19. package/dist/lib/bounded-trace.d.ts +30 -0
  20. package/dist/lib/bounded-trace.js +36 -0
  21. package/dist/lib/circadian-refresh.d.ts +7 -0
  22. package/dist/lib/circadian-refresh.js +11 -0
  23. package/dist/lib/circadian-schedule.d.ts +11 -0
  24. package/dist/lib/circadian-schedule.js +63 -0
  25. package/dist/lib/circadian.d.ts +6 -0
  26. package/dist/lib/circadian.js +15 -0
  27. package/dist/lib/cover-controller.d.ts +130 -0
  28. package/dist/lib/cover-controller.js +336 -0
  29. package/dist/lib/display-mode-controller.d.ts +148 -0
  30. package/dist/lib/display-mode-controller.js +587 -0
  31. package/dist/lib/display-transport.d.ts +41 -0
  32. package/dist/lib/display-transport.js +177 -0
  33. package/dist/lib/light-styling.d.ts +11 -0
  34. package/dist/lib/light-styling.js +15 -0
  35. package/dist/lib/motion-policy.d.ts +72 -0
  36. package/dist/lib/motion-policy.js +251 -0
  37. package/dist/lib/observation-time.d.ts +10 -0
  38. package/dist/lib/observation-time.js +40 -0
  39. package/dist/lib/occupancy-fusion.d.ts +53 -0
  40. package/dist/lib/occupancy-fusion.js +131 -0
  41. package/dist/lib/room-controller.d.ts +113 -0
  42. package/dist/lib/room-controller.js +431 -0
  43. package/dist/lib/source-capability-controller.d.ts +144 -0
  44. package/dist/lib/source-capability-controller.js +494 -0
  45. package/dist/lib/switch-policy.d.ts +53 -0
  46. package/dist/lib/switch-policy.js +110 -0
  47. package/dist/lib/theatre-activity-controller.d.ts +165 -0
  48. package/dist/lib/theatre-activity-controller.js +846 -0
  49. package/dist/lib/theatre-slo.d.ts +49 -0
  50. package/dist/lib/theatre-slo.js +156 -0
  51. package/dist/lib/theatre-state-contract.d.ts +77 -0
  52. package/dist/lib/theatre-state-contract.js +391 -0
  53. package/dist/lib/wall-input.d.ts +62 -0
  54. package/dist/lib/wall-input.js +198 -0
  55. package/dist/nodes/activity-lighting-controller.d.ts +3 -0
  56. package/dist/nodes/activity-lighting-controller.html +38 -0
  57. package/dist/nodes/activity-lighting-controller.js +116 -0
  58. package/dist/nodes/avr-controller.d.ts +3 -0
  59. package/dist/nodes/avr-controller.html +47 -0
  60. package/dist/nodes/avr-controller.js +130 -0
  61. package/dist/nodes/backlighting-controller.d.ts +3 -0
  62. package/dist/nodes/backlighting-controller.html +31 -0
  63. package/dist/nodes/backlighting-controller.js +103 -0
  64. package/dist/nodes/display-mode-controller.d.ts +3 -0
  65. package/dist/nodes/display-mode-controller.html +66 -0
  66. package/dist/nodes/display-mode-controller.js +132 -0
  67. package/dist/nodes/motion-policy.d.ts +3 -0
  68. package/dist/nodes/motion-policy.html +35 -0
  69. package/dist/nodes/motion-policy.js +194 -0
  70. package/dist/nodes/occupancy-fusion.d.ts +3 -0
  71. package/dist/nodes/occupancy-fusion.html +32 -0
  72. package/dist/nodes/occupancy-fusion.js +53 -0
  73. package/dist/nodes/room-controller.d.ts +3 -0
  74. package/dist/nodes/room-controller.html +82 -0
  75. package/dist/nodes/room-controller.js +123 -0
  76. package/dist/nodes/source-capability-controller.d.ts +3 -0
  77. package/dist/nodes/source-capability-controller.html +46 -0
  78. package/dist/nodes/source-capability-controller.js +114 -0
  79. package/dist/nodes/switch-policy.d.ts +3 -0
  80. package/dist/nodes/switch-policy.html +29 -0
  81. package/dist/nodes/switch-policy.js +129 -0
  82. package/dist/nodes/theatre-activity-controller.d.ts +3 -0
  83. package/dist/nodes/theatre-activity-controller.html +32 -0
  84. package/dist/nodes/theatre-activity-controller.js +105 -0
  85. package/dist/nodes/theatre-state-contract.d.ts +3 -0
  86. package/dist/nodes/theatre-state-contract.html +41 -0
  87. package/dist/nodes/theatre-state-contract.js +83 -0
  88. package/examples/Home theatre activity.json +477 -0
  89. package/examples/Home theatre equipment.json +329 -0
  90. package/examples/Room lighting.json +212 -0
  91. package/package.json +62 -4
@@ -0,0 +1,82 @@
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
+ });
26
+ </script>
27
+
28
+ <script type="text/html" data-template-name="home-room-lighting-controller">
29
+ <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>
31
+ <div class="form-row"><label for="node-input-displayName">Display name</label><input type="text" id="node-input-displayName"></div>
32
+ <div class="form-row"><label for="node-input-targets">Targets JSON</label><input type="text" id="node-input-targets"></div>
33
+ <div class="form-row"><label for="node-input-maxBrightnessPct">Daytime brightness %</label><input type="number" id="node-input-maxBrightnessPct"></div>
34
+ <div class="form-row"><label for="node-input-maxColorTempKelvin">Daytime kelvin</label><input type="number" id="node-input-maxColorTempKelvin"></div>
35
+ <div class="form-row"><label for="node-input-sleepBrightnessPct">Sleep brightness %</label><input type="number" id="node-input-sleepBrightnessPct"></div>
36
+ <div class="form-row"><label for="node-input-sleepColorTempKelvin">Sleep kelvin</label><input type="number" id="node-input-sleepColorTempKelvin"></div>
37
+ <div class="form-row"><label for="node-input-initialTransitionSeconds">Initial transition seconds</label><input type="number" id="node-input-initialTransitionSeconds"></div>
38
+ <div class="form-row"><label for="node-input-refreshTransitionSeconds">Refresh transition seconds</label><input type="number" id="node-input-refreshTransitionSeconds"></div>
39
+ <div class="form-row"><label for="node-input-refreshSeconds">Refresh interval seconds</label><input type="number" id="node-input-refreshSeconds"></div>
40
+ <div class="form-row"><label for="node-input-wakeTime">Wake time</label><input type="text" id="node-input-wakeTime" placeholder="07:00"></div>
41
+ <div class="form-row"><label for="node-input-bedTime">Bed time</label><input type="text" id="node-input-bedTime" placeholder="23:00"></div>
42
+ <div class="form-row"><label for="node-input-initialSleep">Initial sleep mode</label><input type="checkbox" id="node-input-initialSleep" style="display:inline-block; width:auto;"></div>
43
+ </script>
44
+
45
+ <script type="text/html" data-help-name="home-room-lighting-controller">
46
+ <p>Owns room MQTT commands, adaptive colour and brightness, manual overrides, discovery and bounded tracing.</p>
47
+ <h3>Circadian schedule</h3>
48
+ <p>Circadian levels follow <b>Wake time</b> and <b>Bed time</b> (24-hour <code>HH:MM</code>, default 07:00 and
49
+ 23:00): they rise to the daytime level over the hour after waking, stay at the daytime brightness and colour
50
+ through the day, wind down to the sleep settings over the three hours before bed, and stay at the sleep
51
+ settings until you wake. A bed time after midnight, or a wake time later than the bed time, works. Sleep mode
52
+ still overrides the schedule.</p>
53
+ <p>Times are the Node-RED host's local time. Docker containers default to UTC: set the container's
54
+ <code>TZ</code> if your host should follow a local timezone.</p>
55
+ <h3>Control state</h3>
56
+ <p>Each target has one control state:</p>
57
+ <dl class="message-properties">
58
+ <dt>in-control</dt><dd>circadian lighting may style and refresh the light. This is the default.</dd>
59
+ <dt>overridden</dt><dd>another owner, such as an activity or a scene, holds the light. Refresh and circadian
60
+ changes leave it alone until that owner releases it.</dd>
61
+ <dt>manual</dt><dd>a person changed the light. Enabling circadian lighting returns manual lights to
62
+ in-control.</dd>
63
+ </dl>
64
+ <p>An overridden light changes only for an intent with an <code>owner</code> (its own, or a newer owner who takes
65
+ it over), a person (a <code>manual: true</code> intent, <code>person: true</code>, set by the wall-switch policies, an external command on the command topic, or a change
66
+ seen at the light), or a release. Any other intent, including motion ON or OFF and owner-less values, leaves it
67
+ alone and is traced as <code>ignored held-by</code>; other targets in the same intent are still handled.
68
+ Switching a light off by its owner or a person returns it to in-control.</p>
69
+ <h3>Inputs</h3>
70
+ <dl class="message-properties">
71
+ <dt>lighting.owner <span class="property-type">string</span></dt>
72
+ <dd>on an <code>intent</code> that switches targets on, marks them overridden by this owner. With
73
+ <code>preserveManual: true</code>, manual lights are skipped.</dd>
74
+ <dt>lighting.kind = "release"</dt>
75
+ <dd>returns overridden <code>targets</code> (default: all) to in-control. With <code>owner</code>, only lights
76
+ held by that owner are released. Released lights that are on are restyled as a refresh would.</dd>
77
+ </dl>
78
+ <h3>Outputs</h3>
79
+ <p>On startup and whenever a target's control state changes, a retained message is sent with topic
80
+ <code>home/&lt;area&gt;/lighting/&lt;target&gt;/control</code> and payload
81
+ <code>{"state": "in-control" | "overridden" | "manual", "owner": string | null}</code>.</p>
82
+ </script>
@@ -0,0 +1,123 @@
1
+ "use strict";
2
+ const bounded_trace_1 = require("../lib/bounded-trace");
3
+ const room_controller_1 = require("../lib/room-controller");
4
+ const circadian_1 = require("../lib/circadian");
5
+ 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
+ }
10
+ function parseTargets(value) {
11
+ const targets = JSON.parse(value || "[]");
12
+ if (!Array.isArray(targets) || targets.some((target) => {
13
+ if (!target || typeof target !== "object")
14
+ return true;
15
+ const candidate = target;
16
+ return typeof candidate.id !== "string" ||
17
+ typeof candidate.stateTopic !== "string" ||
18
+ typeof candidate.commandTopic !== "string";
19
+ })) {
20
+ throw new Error("targets must define id, stateTopic and commandTopic strings");
21
+ }
22
+ const typedTargets = targets;
23
+ if (new Set(typedTargets.map((target) => target.id)).size !== typedTargets.length) {
24
+ throw new Error("target ids must be unique");
25
+ }
26
+ return typedTargets;
27
+ }
28
+ const registerRoomController = (RED) => {
29
+ function HomeRoomLightingController(config) {
30
+ RED.nodes.createNode(this, config);
31
+ const node = this;
32
+ const context = node.context();
33
+ let refreshTimer;
34
+ let controllerConfig;
35
+ try {
36
+ // Saved latitude, longitude and minimum settings from earlier versions
37
+ // are ignored.
38
+ 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)
43
+ };
44
+ const schedule = (0, circadian_schedule_1.resolveSchedule)(config.wakeTime, config.bedTime);
45
+ controllerConfig = {
46
+ area: config.area || "room",
47
+ displayName: config.displayName || config.area || "Room",
48
+ 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",
54
+ // The adapter picks the circadian lighting; the controller only asks
55
+ // it how a light should look.
56
+ lighting: (0, circadian_1.scheduledLighting)(schedule, levels)
57
+ };
58
+ }
59
+ catch (error) {
60
+ node.status({ fill: "red", shape: "ring", text: "invalid configuration" });
61
+ node.error("invalid configuration: " + (error instanceof Error ? error.message : String(error)));
62
+ return;
63
+ }
64
+ function updateStatus(status) {
65
+ node.status({
66
+ fill: status.manualCount ? "yellow" : status.circadianEnabled ? "green" : "grey",
67
+ shape: "dot",
68
+ text: (status.circadianEnabled
69
+ ? (status.sleeping ? "sleep" : "circadian")
70
+ : "manual only") + " · " + status.onCount + " on · " + status.manualCount + " manual" +
71
+ (status.overriddenCount ? " · " + status.overriddenCount + " overridden" : "")
72
+ });
73
+ }
74
+ 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);
83
+ if (result.outputs.length) {
84
+ send([result.outputs.map((output) => ({ ...output, payload: output.payload }))]);
85
+ }
86
+ updateStatus(result.status);
87
+ return result;
88
+ }
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
+ }
105
+ });
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);
115
+ node.on("close", (_removed, done) => {
116
+ clearInterval(refreshTimer);
117
+ done();
118
+ });
119
+ }
120
+ RED.nodes.registerType("home-room-lighting-controller", HomeRoomLightingController);
121
+ };
122
+ module.exports = registerRoomController;
123
+ //# sourceMappingURL=room-controller.js.map
@@ -0,0 +1,3 @@
1
+ import type { NodeInitializer } from "node-red";
2
+ declare const registerSourceCapabilityController: NodeInitializer;
3
+ export = registerSourceCapabilityController;
@@ -0,0 +1,46 @@
1
+ <script type="text/javascript">
2
+ RED.nodes.registerType("home-source-capability-controller", {
3
+ category: "home automation",
4
+ color: "#c7d9f1",
5
+ defaults: {
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
+ },
20
+ pollMs: {value: 2000, required: true, validate: RED.validators.number()},
21
+ confirmationTimeoutMs: {value: 15000, required: true, validate: RED.validators.number()},
22
+ maxAttempts: {value: 2, required: true, validate: RED.validators.number()}
23
+ },
24
+ inputs: 1,
25
+ outputs: 2,
26
+ outputLabels: ["semantic source commands", "theatre target state"],
27
+ icon: "font-awesome/fa-play-circle",
28
+ label: function() { return this.name || "source capability controller"; }
29
+ });
30
+ </script>
31
+
32
+ <script type="text/html" data-template-name="home-source-capability-controller">
33
+ <div class="form-row"><label for="node-input-name">Name</label><input type="text" id="node-input-name"></div>
34
+ <div class="form-row"><label for="node-input-area">Area</label><input type="text" id="node-input-area"></div>
35
+ <div class="form-row"><label for="node-input-sources">Source capabilities</label><input type="text" id="node-input-sources"></div>
36
+ <div class="form-row"><label for="node-input-pollMs">Poll milliseconds</label><input type="number" id="node-input-pollMs"></div>
37
+ <div class="form-row"><label for="node-input-confirmationTimeoutMs">Confirmation timeout</label><input type="number" id="node-input-confirmationTimeoutMs"></div>
38
+ <div class="form-row"><label for="node-input-maxAttempts">Maximum attempts</label><input type="number" id="node-input-maxAttempts"></div>
39
+ </script>
40
+
41
+ <script type="text/html" data-help-name="home-source-capability-controller">
42
+ <p>Coordinates configured source capabilities without containing source names, entity IDs or transport logic.</p>
43
+ <p>Send <code>msg.sourceCapability</code> with <code>kind: "intent"</code>, a request ID, generation, source ID and <code>activate</code> or <code>deactivate</code> action. Adapter observations carry source status, timestamp, optional application identity and optional playback state.</p>
44
+ <p>Source JSON maps deployment-owned IDs to <code>activation</code>, <code>deactivation</code> and <code>confirmation</code> capabilities. Control values are <code>command</code>, <code>external</code> or <code>unavailable</code>. Confirmation values are <code>available</code>, <code>active</code>, <code>application</code>, <code>playing</code> or <code>unavailable</code>.</p>
45
+ <p>The reducer exposes each readiness layer separately and only reports ready when the configured layer has fresh evidence. Output 1 emits semantic commands for a separate transport adapter. Output 2 emits generation-scoped theatre <code>target_state</code> events.</p>
46
+ </script>
@@ -0,0 +1,114 @@
1
+ "use strict";
2
+ const bounded_trace_1 = require("../lib/bounded-trace");
3
+ 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
+ }
8
+ const registerSourceCapabilityController = (RED) => {
9
+ function HomeSourceCapabilityController(config) {
10
+ RED.nodes.createNode(this, config);
11
+ const node = this;
12
+ const context = node.context();
13
+ let timer;
14
+ let sources;
15
+ try {
16
+ sources = (0, source_capability_controller_1.normaliseCapabilities)(JSON.parse(config.sources || "{}"));
17
+ }
18
+ catch (error) {
19
+ node.status({ fill: "red", shape: "ring", text: "invalid source JSON" });
20
+ node.error(error);
21
+ return;
22
+ }
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
+ function updateStatus(status) {
30
+ const appearances = {
31
+ idle: { fill: "grey", shape: "dot" },
32
+ transitioning: { fill: "blue", shape: "dot" },
33
+ confirming: { fill: "blue", shape: "ring" },
34
+ waiting_for_source: { fill: "yellow", shape: "ring" },
35
+ ready: { fill: "green", shape: "dot" },
36
+ unavailable: { fill: "yellow", shape: "dot" },
37
+ failed: { fill: "red", shape: "ring" }
38
+ };
39
+ const appearance = appearances[status.phase] ?? { fill: "grey", shape: "ring" };
40
+ node.status({ ...appearance, text: status.text });
41
+ }
42
+ function schedule(state) {
43
+ clearTimeout(timer);
44
+ timer = undefined;
45
+ if (!state.pending?.nextAt)
46
+ return;
47
+ 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);
56
+ }
57
+ 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);
66
+ if (result.commands.length) {
67
+ send([
68
+ result.commands.map((sourceCommand) => ({ payload: undefined, sourceCommand })),
69
+ null
70
+ ]);
71
+ }
72
+ if (result.events.length) {
73
+ send([null, result.events.map((event) => ({ payload: undefined, ...event }))]);
74
+ }
75
+ updateStatus(result.status);
76
+ schedule(result.state);
77
+ return result;
78
+ }
79
+ // Context survives a redeploy but timers do not. Recover a pending
80
+ // transition with the reducer's own startup (re-observe, never replay)
81
+ // rather than ticking old state; a later startup from the flow repeats it.
82
+ 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);
91
+ }
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
+ }
105
+ });
106
+ node.on("close", (_removed, done) => {
107
+ clearTimeout(timer);
108
+ done();
109
+ });
110
+ }
111
+ RED.nodes.registerType("home-source-capability-controller", HomeSourceCapabilityController);
112
+ };
113
+ module.exports = registerSourceCapabilityController;
114
+ //# sourceMappingURL=source-capability-controller.js.map
@@ -0,0 +1,3 @@
1
+ import type { NodeInitializer } from "node-red";
2
+ declare const registerSwitchPolicy: NodeInitializer;
3
+ export = registerSwitchPolicy;
@@ -0,0 +1,29 @@
1
+ <script type="text/javascript">
2
+ RED.nodes.registerType("home-switch-lighting-policy", {
3
+ category: "home automation",
4
+ color: "#d8bfd8",
5
+ defaults: {
6
+ name: {value: ""},
7
+ area: {value: "room", required: true},
8
+ targets: {value: "[\"main\"]", required: true},
9
+ switchWindowMs: {value: 500, required: true, validate: RED.validators.number()},
10
+ switchFreshnessSeconds: {value: 3600, required: true, validate: RED.validators.number()}
11
+ },
12
+ inputs: 1,
13
+ outputs: 1,
14
+ icon: "font-awesome/fa-toggle-on",
15
+ label: function () { return this.name || this.area + " switch policy"; }
16
+ });
17
+ </script>
18
+
19
+ <script type="text/html" data-template-name="home-switch-lighting-policy">
20
+ <div class="form-row"><label for="node-input-name">Name</label><input type="text" id="node-input-name"></div>
21
+ <div class="form-row"><label for="node-input-area">Area</label><input type="text" id="node-input-area"></div>
22
+ <div class="form-row"><label for="node-input-targets">Targets</label><input type="text" id="node-input-targets"></div>
23
+ <div class="form-row"><label for="node-input-switchWindowMs">Raw-edge window ms</label><input type="number" id="node-input-switchWindowMs"></div>
24
+ <div class="form-row"><label for="node-input-switchFreshnessSeconds">Input freshness seconds</label><input type="number" id="node-input-switchFreshnessSeconds"></div>
25
+ </script>
26
+
27
+ <script type="text/html" data-help-name="home-switch-lighting-policy">
28
+ <p>Turns raw switch edges or pre-classified single/double actions into <code>msg.lighting</code> intents without occupancy or motion state. Raw wall state preserves a persisted baseline, treats retained observations as inert re-baselines and exposes fresh, stale, unavailable or awaiting-baseline status. Send availability as <code>msg.source = "switch-availability"</code>; mark a polled snapshot with <code>msg.baseline = true</code>.</p>
29
+ </script>
@@ -0,0 +1,129 @@
1
+ "use strict";
2
+ const bounded_trace_1 = require("../lib/bounded-trace");
3
+ const wall_input_1 = require("../lib/wall-input");
4
+ const switch_policy_1 = require("../lib/switch-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 parseTargets(value) {
15
+ const parsed = JSON.parse(value || "[\"main\"]");
16
+ if (!Array.isArray(parsed) || parsed.length === 0 || parsed.some((item) => typeof item !== "string")) {
17
+ throw new Error("targets must be a non-empty JSON array of strings");
18
+ }
19
+ return parsed;
20
+ }
21
+ const registerSwitchPolicy = (RED) => {
22
+ function HomeSwitchLightingPolicy(config) {
23
+ RED.nodes.createNode(this, config);
24
+ const node = this;
25
+ const context = node.context();
26
+ let timer;
27
+ let statusTimer;
28
+ let policyConfig;
29
+ try {
30
+ policyConfig = {
31
+ area: config.area || "room",
32
+ targets: parseTargets(config.targets),
33
+ switchWindowMs: Number(config.switchWindowMs ?? 500),
34
+ switchFreshnessMs: Number(config.switchFreshnessSeconds ?? 3600) * 1000
35
+ };
36
+ if (!Number.isFinite(policyConfig.switchWindowMs) || policyConfig.switchWindowMs < 0) {
37
+ throw new Error("switch window must be a non-negative number");
38
+ }
39
+ if (!Number.isFinite(policyConfig.switchFreshnessMs) || policyConfig.switchFreshnessMs <= 0) {
40
+ throw new Error("switch freshness must be a positive number");
41
+ }
42
+ }
43
+ catch (error) {
44
+ node.status({ fill: "red", shape: "ring", text: "invalid configuration" });
45
+ node.error(error);
46
+ return;
47
+ }
48
+ function updateStatus(status) {
49
+ if (status.phase === "fresh") {
50
+ node.status({ fill: "green", shape: "dot", text: `switch fresh · ${ageText(status.ageMs)}` });
51
+ }
52
+ else if (status.phase === "stale") {
53
+ node.status({ fill: "yellow", shape: "ring", text: `switch stale · ${ageText(status.ageMs)}` });
54
+ }
55
+ else if (status.phase === "unavailable") {
56
+ node.status({ fill: "red", shape: "ring", text: "switch unavailable" });
57
+ }
58
+ else {
59
+ node.status({ fill: "yellow", shape: "ring", text: "awaiting switch baseline" });
60
+ }
61
+ }
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);
71
+ for (const effect of result.effects) {
72
+ if (effect.kind === "cancel-switch-timer") {
73
+ clearTimeout(timer);
74
+ timer = undefined;
75
+ }
76
+ else if (effect.kind === "schedule-switch-timer") {
77
+ clearTimeout(timer);
78
+ timer = setTimeout(() => {
79
+ 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);
91
+ }
92
+ else {
93
+ send({ payload: undefined, ...effect.message });
94
+ }
95
+ }
96
+ updateStatus(result.status);
97
+ return result;
98
+ }
99
+ process({ source: "switch-startup" }, node.send.bind(node));
100
+ statusTimer = setInterval(() => {
101
+ const saved = context.get("state");
102
+ updateStatus((0, wall_input_1.wallInputStatus)(saved?.wallInput, policyConfig.switchFreshnessMs));
103
+ }, 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
+ }
119
+ });
120
+ node.on("close", (_removed, done) => {
121
+ clearTimeout(timer);
122
+ clearInterval(statusTimer);
123
+ done();
124
+ });
125
+ }
126
+ RED.nodes.registerType("home-switch-lighting-policy", HomeSwitchLightingPolicy);
127
+ };
128
+ module.exports = registerSwitchPolicy;
129
+ //# sourceMappingURL=switch-policy.js.map
@@ -0,0 +1,3 @@
1
+ import type { NodeInitializer } from "node-red";
2
+ declare const registerTheatreActivityController: NodeInitializer;
3
+ export = registerTheatreActivityController;
@@ -0,0 +1,32 @@
1
+ <script type="text/javascript">
2
+ RED.nodes.registerType("home-theatre-activity-controller", {
3
+ category: "home automation",
4
+ color: "#d9c7f1",
5
+ defaults: {
6
+ name: {value: ""},
7
+ area: {value: "lounge", required: true},
8
+ freshnessMs: {value: 30000, required: true, validate: RED.validators.number()},
9
+ recoveryOffActivity: {value: "off", required: true},
10
+ activityProfiles: {value: "{}", required: true}
11
+ },
12
+ inputs: 1,
13
+ outputs: 2,
14
+ outputLabels: ["semantic target commands", "activity state and events"],
15
+ icon: "font-awesome/fa-sitemap",
16
+ label: function() { return this.name || "theatre activity"; }
17
+ });
18
+ </script>
19
+
20
+ <script type="text/html" data-template-name="home-theatre-activity-controller">
21
+ <div class="form-row"><label for="node-input-name">Name</label><input type="text" id="node-input-name"></div>
22
+ <div class="form-row"><label for="node-input-area">Area</label><input type="text" id="node-input-area"></div>
23
+ <div class="form-row"><label for="node-input-freshnessMs">Freshness ms</label><input type="number" id="node-input-freshnessMs"></div>
24
+ <div class="form-row"><label for="node-input-recoveryOffActivity">Recovery Off activity</label><input type="text" id="node-input-recoveryOffActivity"></div>
25
+ <div class="form-row"><label for="node-input-activityProfiles">Profiles JSON</label><input type="text" id="node-input-activityProfiles"></div>
26
+ </script>
27
+
28
+ <script type="text/html" data-help-name="home-theatre-activity-controller">
29
+ <p>Owns latest-request-wins whole-theatre activity state and aggregates generation-scoped target evidence.</p>
30
+ <p>Input <code>msg.theatre</code> accepts activity intent, target-state, startup, refresh, recovery and tick events. Messages without <code>msg.theatre</code>, such as a target controller's own events on the same wire, are ignored. Output 1 emits semantic <code>msg.theatreCommand</code> messages for target owners. Output 2 emits activity events and a complete state snapshot. Device transports remain separate.</p>
31
+ <p>Startup without persisted intent probes physical state. One fresh profile match is adopted without commands; zero or multiple matches invoke the configured coordinated Off activity. Manual overrides are held without corrective commands and adopted only when the physical state uniquely matches a profile.</p>
32
+ </script>