@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,103 @@
1
+ "use strict";
2
+ const bounded_trace_1 = require("../lib/bounded-trace");
3
+ const backlighting_controller_1 = require("../lib/backlighting-controller");
4
+ function number(value, fallback) {
5
+ const parsed = Number(value);
6
+ return Number.isFinite(parsed) ? parsed : fallback;
7
+ }
8
+ const registerBacklightingController = (RED) => {
9
+ function HomeBacklightingController(config) {
10
+ RED.nodes.createNode(this, config);
11
+ const node = this;
12
+ const context = node.context();
13
+ let timer;
14
+ const controllerConfig = {
15
+ pollMs: number(config.pollMs, 2000),
16
+ confirmationTimeoutMs: number(config.confirmationTimeoutMs, 15000),
17
+ maxAttempts: number(config.maxAttempts, 2)
18
+ };
19
+ function updateStatus(status) {
20
+ const appearances = {
21
+ idle: { fill: "grey", shape: "dot" },
22
+ transitioning: { fill: "blue", shape: "dot" },
23
+ confirming: { fill: "blue", shape: "ring" },
24
+ ready: { fill: "green", shape: "dot" },
25
+ failed: { fill: "red", shape: "ring" }
26
+ };
27
+ const appearance = appearances[status.phase] ?? { fill: "grey", shape: "ring" };
28
+ node.status({ ...appearance, text: status.text });
29
+ }
30
+ function schedule(state) {
31
+ clearTimeout(timer);
32
+ timer = undefined;
33
+ if (!state.pending)
34
+ return;
35
+ const dueAt = Math.min(state.pending.nextAt, state.pending.deadlineAt);
36
+ const delay = Math.max(0, dueAt - Date.now());
37
+ timer = setTimeout(() => {
38
+ try {
39
+ process({ backlighting: { kind: "tick", generation: state.generation } }, node.send.bind(node));
40
+ }
41
+ catch (error) {
42
+ node.error(error);
43
+ }
44
+ }, delay);
45
+ }
46
+ function process(msg, send) {
47
+ const now = new Date();
48
+ const saved = context.get("state");
49
+ const result = (0, backlighting_controller_1.transitionBacklighting)(saved, msg, controllerConfig, now);
50
+ context.set("state", result.state);
51
+ (0, bounded_trace_1.appendTrace)(context, {
52
+ area: config.area || "lounge",
53
+ component: "backlighting-controller"
54
+ }, result.traces, now);
55
+ if (result.commands.length) {
56
+ send([
57
+ result.commands.map((backlightingCommand) => ({ payload: undefined, backlightingCommand })),
58
+ null
59
+ ]);
60
+ }
61
+ if (result.events.length) {
62
+ send([null, result.events.map((event) => ({ payload: undefined, ...event }))]);
63
+ }
64
+ updateStatus(result.status);
65
+ schedule(result.state);
66
+ return result;
67
+ }
68
+ // Context survives a redeploy but timers do not. Recover a pending
69
+ // transition with the reducer's own startup (re-observe, never replay)
70
+ // rather than ticking old state; a later startup from the flow repeats it.
71
+ if (context.get("state")?.pending) {
72
+ timer = setTimeout(() => {
73
+ try {
74
+ process({ backlighting: { kind: "startup" } }, node.send.bind(node));
75
+ }
76
+ catch (error) {
77
+ node.error(error);
78
+ }
79
+ }, 0);
80
+ }
81
+ node.on("input", (msg, send, done) => {
82
+ try {
83
+ process({
84
+ backlighting: msg.backlighting && typeof msg.backlighting === "object"
85
+ ? msg.backlighting
86
+ : undefined
87
+ }, send);
88
+ done();
89
+ }
90
+ catch (error) {
91
+ node.error(error, msg);
92
+ done(error instanceof Error ? error : new Error(String(error)));
93
+ }
94
+ });
95
+ node.on("close", (_removed, done) => {
96
+ clearTimeout(timer);
97
+ done();
98
+ });
99
+ }
100
+ RED.nodes.registerType("home-backlighting-controller", HomeBacklightingController);
101
+ };
102
+ module.exports = registerBacklightingController;
103
+ //# sourceMappingURL=backlighting-controller.js.map
@@ -0,0 +1,3 @@
1
+ import type { NodeInitializer } from "node-red";
2
+ declare const registerDisplayModeController: NodeInitializer;
3
+ export = registerDisplayModeController;
@@ -0,0 +1,66 @@
1
+ <script type="text/javascript">
2
+ RED.nodes.registerType("home-display-mode-controller", {
3
+ category: "home automation",
4
+ color: "#c7d9f1",
5
+ defaults: {
6
+ name: {value: ""},
7
+ area: {value: "lounge", required: true},
8
+ tvHost: {value: "", required: true},
9
+ screenHost: {value: "", required: true},
10
+ projectorMeterHost: {value: "", required: true},
11
+ screenOpenPosition: {value: 82, required: true, validate: RED.validators.number()},
12
+ screenTolerance: {value: 2, required: true, validate: RED.validators.number()},
13
+ pollMs: {value: 2000, required: true, validate: RED.validators.number()},
14
+ queryTimeoutMs: {value: 5000, required: true, validate: RED.validators.number()},
15
+ tvTimeoutMs: {value: 30000, required: true, validate: RED.validators.number()},
16
+ screenTimeoutMs: {value: 65000, required: true, validate: RED.validators.number()},
17
+ projectorWarmupMs: {value: 60000, required: true, validate: RED.validators.number()},
18
+ projectorMinimumWarmupMs: {value: 15000, required: true, validate: RED.validators.number()},
19
+ projectorShutdownConfirmMs: {value: 5000, required: true, validate: RED.validators.number()},
20
+ projectorCooldownMs: {value: 120000, required: true, validate: RED.validators.number()},
21
+ maxAttempts: {value: 2, required: true, validate: RED.validators.number()},
22
+ projectorOnWatts: {value: 20, required: true, validate: RED.validators.number()},
23
+ projectorOffWatts: {value: 10, required: true, validate: RED.validators.number()},
24
+ projectorPowerFallback: {value: false},
25
+ transportTimeoutMs: {value: 5000, required: true, validate: RED.validators.number()}
26
+ },
27
+ credentials: {tvPsk: {type: "password"}},
28
+ inputs: 1,
29
+ outputs: 2,
30
+ outputLabels: ["projector IR fallback", "state and results"],
31
+ icon: "font-awesome/fa-television",
32
+ label: function () { return this.name || this.area + " display mode"; }
33
+ });
34
+ </script>
35
+
36
+ <script type="text/html" data-template-name="home-display-mode-controller">
37
+ <div class="form-row"><label for="node-input-name">Name</label><input type="text" id="node-input-name"></div>
38
+ <div class="form-row"><label for="node-input-area">Area</label><input type="text" id="node-input-area"></div>
39
+ <div class="form-row"><label for="node-input-tvHost">Bravia host</label><input type="text" id="node-input-tvHost"></div>
40
+ <div class="form-row"><label for="node-input-tvPsk">Bravia PSK</label><input type="password" id="node-input-tvPsk"></div>
41
+ <div class="form-row"><label for="node-input-screenHost">Screen Shelly host</label><input type="text" id="node-input-screenHost"></div>
42
+ <div class="form-row"><label for="node-input-projectorMeterHost">Projector Shelly host</label><input type="text" id="node-input-projectorMeterHost"></div>
43
+ <div class="form-row"><label for="node-input-screenOpenPosition">Screen viewing position</label><input type="number" id="node-input-screenOpenPosition"></div>
44
+ <div class="form-row"><label for="node-input-screenTolerance">Screen position tolerance</label><input type="number" id="node-input-screenTolerance"></div>
45
+ <div class="form-row"><label for="node-input-pollMs">Confirmation poll milliseconds</label><input type="number" id="node-input-pollMs"></div>
46
+ <div class="form-row"><label for="node-input-queryTimeoutMs">Query timeout milliseconds</label><input type="number" id="node-input-queryTimeoutMs"></div>
47
+ <div class="form-row"><label for="node-input-tvTimeoutMs">TV confirmation timeout</label><input type="number" id="node-input-tvTimeoutMs"></div>
48
+ <div class="form-row"><label for="node-input-screenTimeoutMs">Screen movement timeout</label><input type="number" id="node-input-screenTimeoutMs"></div>
49
+ <div class="form-row"><label for="node-input-projectorWarmupMs">Projector warm-up timeout</label><input type="number" id="node-input-projectorWarmupMs"></div>
50
+ <div class="form-row"><label for="node-input-projectorMinimumWarmupMs">Projector minimum warm-up</label><input type="number" id="node-input-projectorMinimumWarmupMs"></div>
51
+ <div class="form-row"><label for="node-input-projectorShutdownConfirmMs">Projector shutdown confirm delay</label><input type="number" id="node-input-projectorShutdownConfirmMs"></div>
52
+ <div class="form-row"><label for="node-input-projectorCooldownMs">Projector cool-down timeout</label><input type="number" id="node-input-projectorCooldownMs"></div>
53
+ <div class="form-row"><label for="node-input-maxAttempts">Maximum idempotent attempts</label><input type="number" id="node-input-maxAttempts"></div>
54
+ <div class="form-row"><label for="node-input-projectorOnWatts">Projector on watts</label><input type="number" id="node-input-projectorOnWatts"></div>
55
+ <div class="form-row"><label for="node-input-projectorOffWatts">Projector standby watts</label><input type="number" id="node-input-projectorOffWatts"></div>
56
+ <div class="form-row"><label for="node-input-projectorPowerFallback">Projector power is fallback</label><input type="checkbox" id="node-input-projectorPowerFallback"></div>
57
+ <div class="form-row"><label for="node-input-transportTimeoutMs">Transport timeout milliseconds</label><input type="number" id="node-input-transportTimeoutMs"></div>
58
+ </script>
59
+
60
+ <script type="text/html" data-help-name="home-display-mode-controller">
61
+ <p>Owns Bravia power, projector lamp power and projector-screen position for <code>off</code>, <code>tv</code> and <code>projector</code> modes.</p>
62
+ <p>Send <code>msg.display = {kind: "intent", requestId, generation, mode}</code>. Send <code>kind: "startup"</code> after deployment to query every owned device and reconcile persisted intent. Send <code>kind: "refresh"</code> to re-confirm a settled display from fresh readings.</p>
63
+ <p>The Bravia and both Shelly devices use direct LAN APIs. Output 1 carries the projector power toggle (<code>msg.payload = "power"</code> with <code>msg.display_command</code>) for your infrared transport, commanded directly rather than through Home Assistant. Enable “Projector power is fallback” to include its use in activity metrics. Output 2 emits observed state plus ready, manual-override, failed, rejected and superseded results, and <code>msg.theatre</code> target state for the theatre activity controller: wire it straight back to that controller.</p>
64
+ <p>An unsolicited physical-state change after readiness latches manual ownership. The controller observes and reports it without issuing corrective commands; a newer activity intent resumes automation.</p>
65
+ <p>The Bravia PSK remains in Node-RED's encrypted credential store and is never emitted in a message or status.</p>
66
+ </script>
@@ -0,0 +1,132 @@
1
+ "use strict";
2
+ const bounded_trace_1 = require("../lib/bounded-trace");
3
+ const display_mode_controller_1 = require("../lib/display-mode-controller");
4
+ const display_transport_1 = require("../lib/display-transport");
5
+ function number(value, fallback) {
6
+ const parsed = Number(value);
7
+ return Number.isFinite(parsed) ? parsed : fallback;
8
+ }
9
+ const registerDisplayModeController = (RED) => {
10
+ function HomeDisplayModeController(config) {
11
+ RED.nodes.createNode(this, config);
12
+ const node = this;
13
+ const context = node.context();
14
+ let timer;
15
+ let closed = false;
16
+ const controllerConfig = {
17
+ screenOpenPosition: number(config.screenOpenPosition, 82),
18
+ screenTolerance: number(config.screenTolerance, 2),
19
+ pollMs: number(config.pollMs, 2000),
20
+ queryTimeoutMs: number(config.queryTimeoutMs, 5000),
21
+ tvTimeoutMs: number(config.tvTimeoutMs, 30000),
22
+ screenTimeoutMs: number(config.screenTimeoutMs, 65000),
23
+ projectorWarmupMs: number(config.projectorWarmupMs, 60000),
24
+ projectorMinimumWarmupMs: number(config.projectorMinimumWarmupMs, 15000),
25
+ projectorShutdownConfirmMs: number(config.projectorShutdownConfirmMs, 5000),
26
+ projectorCooldownMs: number(config.projectorCooldownMs, 120000),
27
+ maxAttempts: number(config.maxAttempts, 2),
28
+ projectorOnWatts: number(config.projectorOnWatts, 20),
29
+ projectorOffWatts: number(config.projectorOffWatts, 10),
30
+ projectorPowerFallback: config.projectorPowerFallback === true
31
+ };
32
+ let transport;
33
+ try {
34
+ transport = new display_transport_1.DisplayTransport({
35
+ tvHost: String(config.tvHost ?? ""),
36
+ tvPsk: String(node.credentials?.tvPsk ?? ""),
37
+ screenHost: String(config.screenHost ?? ""),
38
+ projectorMeterHost: String(config.projectorMeterHost ?? ""),
39
+ timeoutMs: number(config.transportTimeoutMs, 5000)
40
+ });
41
+ }
42
+ catch (error) {
43
+ node.status({ fill: "red", shape: "ring", text: "invalid configuration" });
44
+ node.error(error);
45
+ return;
46
+ }
47
+ function updateStatus(status) {
48
+ const appearances = {
49
+ discovering: { fill: "grey", shape: "ring" },
50
+ idle: { fill: "grey", shape: "dot" },
51
+ transitioning: { fill: "blue", shape: "dot" },
52
+ ready: { fill: "green", shape: "dot" },
53
+ manual_override: { fill: "yellow", shape: "ring" },
54
+ failed: { fill: "red", shape: "ring" }
55
+ };
56
+ const appearance = appearances[status.phase] ?? { fill: "grey", shape: "ring" };
57
+ node.status({ ...appearance, text: status.text });
58
+ }
59
+ function schedule(state) {
60
+ clearTimeout(timer);
61
+ timer = undefined;
62
+ if (!state.pending?.nextAt)
63
+ return;
64
+ const delay = Math.max(0, state.pending.nextAt - Date.now());
65
+ const generation = state.desired?.generation || state.generation;
66
+ timer = setTimeout(() => {
67
+ try {
68
+ process({ display: { kind: "tick", generation } }, node.send.bind(node));
69
+ }
70
+ catch (error) {
71
+ node.error(error);
72
+ }
73
+ }, delay);
74
+ }
75
+ async function dispatch(command) {
76
+ if (command.device === "projector" && command.operation === "power_toggle") {
77
+ node.send([{
78
+ payload: "power",
79
+ display_command: command
80
+ }, null]);
81
+ return;
82
+ }
83
+ const result = await transport.execute(command);
84
+ if (!closed && result)
85
+ process(result, node.send.bind(node));
86
+ }
87
+ function process(msg, send) {
88
+ const now = new Date();
89
+ const saved = context.get("state");
90
+ const result = (0, display_mode_controller_1.transitionDisplay)(saved, msg, controllerConfig, now);
91
+ context.set("state", result.state);
92
+ (0, bounded_trace_1.appendTrace)(context, {
93
+ area: config.area || "lounge",
94
+ component: "display-mode-controller"
95
+ }, result.traces, now);
96
+ const outputs = [...result.events, ...result.targetStates];
97
+ if (outputs.length) {
98
+ send([null, outputs.map((event) => ({ payload: undefined, ...event }))]);
99
+ }
100
+ updateStatus(result.status);
101
+ schedule(result.state);
102
+ for (const command of result.commands) {
103
+ dispatch(command).catch((error) => node.error(error));
104
+ }
105
+ return result;
106
+ }
107
+ node.on("input", (msg, send, done) => {
108
+ try {
109
+ process({
110
+ display: msg.display && typeof msg.display === "object"
111
+ ? msg.display
112
+ : undefined
113
+ }, send);
114
+ done();
115
+ }
116
+ catch (error) {
117
+ node.error(error, msg);
118
+ done(error instanceof Error ? error : new Error(String(error)));
119
+ }
120
+ });
121
+ node.on("close", (_removed, done) => {
122
+ closed = true;
123
+ clearTimeout(timer);
124
+ done();
125
+ });
126
+ }
127
+ RED.nodes.registerType("home-display-mode-controller", HomeDisplayModeController, {
128
+ credentials: { tvPsk: { type: "password" } }
129
+ });
130
+ };
131
+ module.exports = registerDisplayModeController;
132
+ //# sourceMappingURL=display-mode-controller.js.map
@@ -0,0 +1,3 @@
1
+ import type { NodeInitializer } from "node-red";
2
+ declare const registerMotionPolicy: NodeInitializer;
3
+ export = registerMotionPolicy;
@@ -0,0 +1,35 @@
1
+ <script type="text/javascript">
2
+ RED.nodes.registerType("home-motion-lighting-policy", {
3
+ category: "home automation",
4
+ color: "#d8bfd8",
5
+ defaults: {
6
+ name: {value: ""},
7
+ area: {value: "room", required: true},
8
+ onTargets: {value: "[\"main\"]", required: true},
9
+ offTargets: {value: "[\"main\"]", required: true},
10
+ defaultDelaySeconds: {value: 120, required: true, validate: RED.validators.number()},
11
+ defaultIlluminanceCutoff: {value: 10, required: true, validate: RED.validators.number()},
12
+ switchWindowMs: {value: 500, required: true, validate: RED.validators.number()},
13
+ switchFreshnessSeconds: {value: 3600, required: true, validate: RED.validators.number()}
14
+ },
15
+ inputs: 1,
16
+ outputs: 1,
17
+ icon: "font-awesome/fa-lightbulb-o",
18
+ label: function () { return this.name || this.area + " motion policy"; }
19
+ });
20
+ </script>
21
+
22
+ <script type="text/html" data-template-name="home-motion-lighting-policy">
23
+ <div class="form-row"><label for="node-input-name">Name</label><input type="text" id="node-input-name"></div>
24
+ <div class="form-row"><label for="node-input-area">Area</label><input type="text" id="node-input-area"></div>
25
+ <div class="form-row"><label for="node-input-onTargets">ON targets</label><input type="text" id="node-input-onTargets"></div>
26
+ <div class="form-row"><label for="node-input-offTargets">OFF targets</label><input type="text" id="node-input-offTargets"></div>
27
+ <div class="form-row"><label for="node-input-defaultDelaySeconds">Vacancy seconds</label><input type="number" id="node-input-defaultDelaySeconds"></div>
28
+ <div class="form-row"><label for="node-input-defaultIlluminanceCutoff">Lux cutoff</label><input type="number" id="node-input-defaultIlluminanceCutoff"></div>
29
+ <div class="form-row"><label for="node-input-switchWindowMs">Switch window ms</label><input type="number" id="node-input-switchWindowMs"></div>
30
+ <div class="form-row"><label for="node-input-switchFreshnessSeconds">Switch freshness seconds</label><input type="number" id="node-input-switchFreshnessSeconds"></div>
31
+ </script>
32
+
33
+ <script type="text/html" data-help-name="home-motion-lighting-policy">
34
+ <p>Turns normalised occupancy, illuminance, enable-state and wall-switch events into <code>msg.lighting</code> intents. 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>
35
+ </script>
@@ -0,0 +1,194 @@
1
+ "use strict";
2
+ const bounded_trace_1 = require("../lib/bounded-trace");
3
+ const wall_input_1 = require("../lib/wall-input");
4
+ 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
+ }
30
+ const registerMotionPolicy = (RED) => {
31
+ function HomeMotionLightingPolicy(config) {
32
+ RED.nodes.createNode(this, config);
33
+ const node = this;
34
+ const context = node.context();
35
+ const globalContext = context.global;
36
+ 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
+ let policyConfig;
43
+ 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
+ }
57
+ }
58
+ catch (error) {
59
+ node.status({ fill: "red", shape: "ring", text: "invalid configuration" });
60
+ node.error(error);
61
+ return;
62
+ }
63
+ 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
+ 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",
84
+ text: (status.enabled ? "enabled" : "disabled") + " · " +
85
+ (status.illuminance === null ? "lux ?" : status.illuminance + " lux") + " · " +
86
+ status.delaySeconds + "s · " + switchStatusText(switchState)
87
+ });
88
+ }
89
+ function armOffTimer(delayMs, generation) {
90
+ clearTimeout(offTimer);
91
+ offTimer = setTimeout(() => {
92
+ 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);
100
+ }
101
+ function process(input, send) {
102
+ if (input.source === "switch" || input.source === "switch-availability") {
103
+ wallInputRelevant = true;
104
+ }
105
+ const now = new Date();
106
+ 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);
110
+ if (input.source === "global-enabled") {
111
+ globalContext.set("MOTION_ENABLED_STATE", result.globalEnabled);
112
+ }
113
+ (0, bounded_trace_1.appendTrace)(context, {
114
+ area: policyConfig.area,
115
+ component: "motion-policy"
116
+ }, result.traces, now);
117
+ for (const effect of result.effects) {
118
+ if (effect.kind === "cancel-off-timer") {
119
+ clearTimeout(offTimer);
120
+ offTimer = undefined;
121
+ }
122
+ else if (effect.kind === "schedule-off-timer") {
123
+ armOffTimer(effect.delayMs, effect.generation);
124
+ }
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
+ else if (effect.kind === "send") {
146
+ send({ payload: undefined, ...effect.message });
147
+ }
148
+ }
149
+ updateStatus(result.status);
150
+ return result;
151
+ }
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.
155
+ const savedState = context.get("state");
156
+ if (typeof savedState?.offTimerDueAt === "number") {
157
+ armOffTimer(Math.max(0, savedState.offTimerDueAt - Date.now()), Number(savedState.offTimerGeneration) || 0);
158
+ }
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
+ }
183
+ });
184
+ node.on("close", (_removed, done) => {
185
+ clearTimeout(offTimer);
186
+ clearTimeout(switchTimer);
187
+ clearInterval(statusTimer);
188
+ done();
189
+ });
190
+ }
191
+ RED.nodes.registerType("home-motion-lighting-policy", HomeMotionLightingPolicy);
192
+ };
193
+ module.exports = registerMotionPolicy;
194
+ //# sourceMappingURL=motion-policy.js.map
@@ -0,0 +1,3 @@
1
+ import type { NodeInitializer } from "node-red";
2
+ declare const registerOccupancyFusion: NodeInitializer;
3
+ export = registerOccupancyFusion;
@@ -0,0 +1,32 @@
1
+ <script type="text/javascript">
2
+ RED.nodes.registerType("home-occupancy-fusion", {
3
+ category: "home automation",
4
+ color: "#c7e9c0",
5
+ defaults: {
6
+ name: {value: ""},
7
+ area: {value: "room", required: true},
8
+ presenceMode: {value: "none", required: true}
9
+ },
10
+ inputs: 1,
11
+ outputs: 1,
12
+ icon: "font-awesome/fa-users",
13
+ label: function () { return this.name || this.area + " occupancy"; }
14
+ });
15
+ </script>
16
+
17
+ <script type="text/html" data-template-name="home-occupancy-fusion">
18
+ <div class="form-row"><label for="node-input-name">Name</label><input type="text" id="node-input-name"></div>
19
+ <div class="form-row"><label for="node-input-area">Area</label><input type="text" id="node-input-area"></div>
20
+ <div class="form-row">
21
+ <label for="node-input-presenceMode">Presence sensor</label>
22
+ <select id="node-input-presenceMode">
23
+ <option value="none">None (PIR only)</option>
24
+ <option value="hold">Hold occupancy (PIR + mmWave)</option>
25
+ </select>
26
+ </div>
27
+ </script>
28
+
29
+ <script type="text/html" data-help-name="home-occupancy-fusion">
30
+ <p>Combines normalised <code>motion</code> and optional <code>presence</code> events into <code>msg.source = "occupancy"</code>.</p>
31
+ <p>PIR establishes occupancy. Presence can hold an established occupancy but cannot establish one by itself.</p>
32
+ </script>
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ const bounded_trace_1 = require("../lib/bounded-trace");
3
+ const occupancy_fusion_1 = require("../lib/occupancy-fusion");
4
+ const registerOccupancyFusion = (RED) => {
5
+ function HomeOccupancyFusion(config) {
6
+ RED.nodes.createNode(this, config);
7
+ const node = this;
8
+ const context = node.context();
9
+ const fusionConfig = {
10
+ area: config.area || "room",
11
+ presenceMode: config.presenceMode === "hold" ? "hold" : "ignore"
12
+ };
13
+ function updateStatus(status) {
14
+ const details = [status.occupied ? "occupied" : "vacant"];
15
+ if (status.motion !== null)
16
+ details.push("pir " + (status.motion ? "on" : "off"));
17
+ if (status.presence !== null)
18
+ details.push("presence " + (status.presence ? "on" : "off"));
19
+ node.status({
20
+ fill: status.occupied ? "green" : "grey",
21
+ shape: "dot",
22
+ text: details.join(" · ")
23
+ });
24
+ }
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
+ }
48
+ });
49
+ }
50
+ RED.nodes.registerType("home-occupancy-fusion", HomeOccupancyFusion);
51
+ };
52
+ module.exports = registerOccupancyFusion;
53
+ //# sourceMappingURL=occupancy-fusion.js.map
@@ -0,0 +1,3 @@
1
+ import type { NodeInitializer } from "node-red";
2
+ declare const registerRoomController: NodeInitializer;
3
+ export = registerRoomController;