@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.
- package/LICENSE +21 -0
- package/README.md +292 -2
- package/contract-examples/README.md +28 -0
- package/contract-examples/_shared.mjs +11 -0
- package/contract-examples/motion-lighting.mjs +42 -0
- package/contract-examples/occupancy-fusion.mjs +35 -0
- package/contract-examples/room-lighting.mjs +58 -0
- package/contract-examples/run.mjs +16 -0
- package/contract-examples/source-readiness.mjs +64 -0
- package/contract-examples/switch-gestures.mjs +34 -0
- package/contract-examples/theatre-activity.mjs +62 -0
- package/contract-examples/volume-ownership.mjs +59 -0
- package/dist/lib/activity-lighting-controller.d.ts +129 -0
- package/dist/lib/activity-lighting-controller.js +372 -0
- package/dist/lib/avr-controller.d.ts +169 -0
- package/dist/lib/avr-controller.js +948 -0
- package/dist/lib/backlighting-controller.d.ts +108 -0
- package/dist/lib/backlighting-controller.js +269 -0
- package/dist/lib/bounded-trace.d.ts +30 -0
- package/dist/lib/bounded-trace.js +36 -0
- package/dist/lib/circadian-refresh.d.ts +7 -0
- package/dist/lib/circadian-refresh.js +11 -0
- package/dist/lib/circadian-schedule.d.ts +11 -0
- package/dist/lib/circadian-schedule.js +63 -0
- package/dist/lib/circadian.d.ts +6 -0
- package/dist/lib/circadian.js +15 -0
- package/dist/lib/cover-controller.d.ts +130 -0
- package/dist/lib/cover-controller.js +336 -0
- package/dist/lib/display-mode-controller.d.ts +148 -0
- package/dist/lib/display-mode-controller.js +587 -0
- package/dist/lib/display-transport.d.ts +41 -0
- package/dist/lib/display-transport.js +177 -0
- package/dist/lib/light-styling.d.ts +11 -0
- package/dist/lib/light-styling.js +15 -0
- package/dist/lib/motion-policy.d.ts +72 -0
- package/dist/lib/motion-policy.js +251 -0
- package/dist/lib/observation-time.d.ts +10 -0
- package/dist/lib/observation-time.js +40 -0
- package/dist/lib/occupancy-fusion.d.ts +53 -0
- package/dist/lib/occupancy-fusion.js +131 -0
- package/dist/lib/room-controller.d.ts +113 -0
- package/dist/lib/room-controller.js +431 -0
- package/dist/lib/source-capability-controller.d.ts +144 -0
- package/dist/lib/source-capability-controller.js +494 -0
- package/dist/lib/switch-policy.d.ts +53 -0
- package/dist/lib/switch-policy.js +110 -0
- package/dist/lib/theatre-activity-controller.d.ts +165 -0
- package/dist/lib/theatre-activity-controller.js +846 -0
- package/dist/lib/theatre-slo.d.ts +49 -0
- package/dist/lib/theatre-slo.js +156 -0
- package/dist/lib/theatre-state-contract.d.ts +77 -0
- package/dist/lib/theatre-state-contract.js +391 -0
- package/dist/lib/wall-input.d.ts +62 -0
- package/dist/lib/wall-input.js +198 -0
- package/dist/nodes/activity-lighting-controller.d.ts +3 -0
- package/dist/nodes/activity-lighting-controller.html +38 -0
- package/dist/nodes/activity-lighting-controller.js +116 -0
- package/dist/nodes/avr-controller.d.ts +3 -0
- package/dist/nodes/avr-controller.html +47 -0
- package/dist/nodes/avr-controller.js +130 -0
- package/dist/nodes/backlighting-controller.d.ts +3 -0
- package/dist/nodes/backlighting-controller.html +31 -0
- package/dist/nodes/backlighting-controller.js +103 -0
- package/dist/nodes/display-mode-controller.d.ts +3 -0
- package/dist/nodes/display-mode-controller.html +66 -0
- package/dist/nodes/display-mode-controller.js +132 -0
- package/dist/nodes/motion-policy.d.ts +3 -0
- package/dist/nodes/motion-policy.html +35 -0
- package/dist/nodes/motion-policy.js +194 -0
- package/dist/nodes/occupancy-fusion.d.ts +3 -0
- package/dist/nodes/occupancy-fusion.html +32 -0
- package/dist/nodes/occupancy-fusion.js +53 -0
- package/dist/nodes/room-controller.d.ts +3 -0
- package/dist/nodes/room-controller.html +82 -0
- package/dist/nodes/room-controller.js +123 -0
- package/dist/nodes/source-capability-controller.d.ts +3 -0
- package/dist/nodes/source-capability-controller.html +46 -0
- package/dist/nodes/source-capability-controller.js +114 -0
- package/dist/nodes/switch-policy.d.ts +3 -0
- package/dist/nodes/switch-policy.html +29 -0
- package/dist/nodes/switch-policy.js +129 -0
- package/dist/nodes/theatre-activity-controller.d.ts +3 -0
- package/dist/nodes/theatre-activity-controller.html +32 -0
- package/dist/nodes/theatre-activity-controller.js +105 -0
- package/dist/nodes/theatre-state-contract.d.ts +3 -0
- package/dist/nodes/theatre-state-contract.html +41 -0
- package/dist/nodes/theatre-state-contract.js +83 -0
- package/examples/Home theatre activity.json +477 -0
- package/examples/Home theatre equipment.json +329 -0
- package/examples/Room lighting.json +212 -0
- package/package.json +62 -4
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
export type TheatreSloStatus = "learning" | "healthy" | "at_risk" | "breached";
|
|
2
|
+
export type TheatreSloOutcome = "ready" | "failed";
|
|
3
|
+
export interface TheatreSloConfig {
|
|
4
|
+
windowSize: number;
|
|
5
|
+
minimumSamples: number;
|
|
6
|
+
latencyBudgetMs: number;
|
|
7
|
+
successObjectivePct: number;
|
|
8
|
+
}
|
|
9
|
+
export interface TheatreSloSample {
|
|
10
|
+
generation: number;
|
|
11
|
+
activity: string;
|
|
12
|
+
outcome: TheatreSloOutcome;
|
|
13
|
+
transitionMs: number | null;
|
|
14
|
+
completedAt: string;
|
|
15
|
+
}
|
|
16
|
+
export interface TheatreSloState {
|
|
17
|
+
samples: TheatreSloSample[];
|
|
18
|
+
}
|
|
19
|
+
export interface TheatreSloSnapshot {
|
|
20
|
+
generation: number;
|
|
21
|
+
desiredActivity: string | null;
|
|
22
|
+
phase: string;
|
|
23
|
+
transitionStartedAt: string | null;
|
|
24
|
+
transitionCompletedAt: string | null;
|
|
25
|
+
metrics?: {
|
|
26
|
+
lastTransitionMs?: number | null;
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
export interface TheatreSloAssessment {
|
|
30
|
+
status: TheatreSloStatus;
|
|
31
|
+
reason: string;
|
|
32
|
+
sampleCount: number;
|
|
33
|
+
windowSize: number;
|
|
34
|
+
minimumSamples: number;
|
|
35
|
+
latencyBudgetMs: number;
|
|
36
|
+
successObjectivePct: number;
|
|
37
|
+
successRatePct: number | null;
|
|
38
|
+
p50TransitionMs: number | null;
|
|
39
|
+
p95TransitionMs: number | null;
|
|
40
|
+
lastActivity: string | null;
|
|
41
|
+
lastOutcome: TheatreSloOutcome | null;
|
|
42
|
+
lastTransitionMs: number | null;
|
|
43
|
+
evaluatedAt: string;
|
|
44
|
+
}
|
|
45
|
+
export declare function normaliseTheatreSloConfig(config?: Partial<TheatreSloConfig>): TheatreSloConfig;
|
|
46
|
+
export declare function evaluateTheatreSlo(saved: Partial<TheatreSloState> | undefined, snapshot: TheatreSloSnapshot, suppliedConfig?: Partial<TheatreSloConfig>, nowValue?: Date | string | number): {
|
|
47
|
+
state: TheatreSloState;
|
|
48
|
+
assessment: TheatreSloAssessment;
|
|
49
|
+
};
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.normaliseTheatreSloConfig = normaliseTheatreSloConfig;
|
|
4
|
+
exports.evaluateTheatreSlo = evaluateTheatreSlo;
|
|
5
|
+
function boundedInteger(value, fallback, minimum, maximum) {
|
|
6
|
+
const parsed = Number(value);
|
|
7
|
+
if (!Number.isFinite(parsed))
|
|
8
|
+
return fallback;
|
|
9
|
+
return Math.max(minimum, Math.min(maximum, Math.round(parsed)));
|
|
10
|
+
}
|
|
11
|
+
function normaliseTheatreSloConfig(config = {}) {
|
|
12
|
+
const windowSize = boundedInteger(config.windowSize, 20, 5, 100);
|
|
13
|
+
return {
|
|
14
|
+
windowSize,
|
|
15
|
+
minimumSamples: boundedInteger(config.minimumSamples, 5, 1, windowSize),
|
|
16
|
+
latencyBudgetMs: boundedInteger(config.latencyBudgetMs, 60000, 1000, 3600000),
|
|
17
|
+
successObjectivePct: boundedInteger(config.successObjectivePct, 95, 50, 100)
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
function duration(value) {
|
|
21
|
+
const parsed = Number(value);
|
|
22
|
+
return Number.isFinite(parsed) && parsed >= 0 ? parsed : null;
|
|
23
|
+
}
|
|
24
|
+
function timestamp(value) {
|
|
25
|
+
if (typeof value !== "string" || !Number.isFinite(Date.parse(value)))
|
|
26
|
+
return null;
|
|
27
|
+
return value;
|
|
28
|
+
}
|
|
29
|
+
function createState(saved) {
|
|
30
|
+
const samples = Array.isArray(saved?.samples)
|
|
31
|
+
? saved.samples.flatMap((sample) => {
|
|
32
|
+
if (!sample || typeof sample !== "object")
|
|
33
|
+
return [];
|
|
34
|
+
const generation = Number(sample.generation);
|
|
35
|
+
const completedAt = timestamp(sample.completedAt);
|
|
36
|
+
if (!Number.isInteger(generation) || generation < 0 || !completedAt ||
|
|
37
|
+
typeof sample.activity !== "string" ||
|
|
38
|
+
(sample.outcome !== "ready" && sample.outcome !== "failed"))
|
|
39
|
+
return [];
|
|
40
|
+
return [{
|
|
41
|
+
generation,
|
|
42
|
+
activity: sample.activity,
|
|
43
|
+
outcome: sample.outcome,
|
|
44
|
+
transitionMs: duration(sample.transitionMs),
|
|
45
|
+
completedAt
|
|
46
|
+
}];
|
|
47
|
+
})
|
|
48
|
+
: [];
|
|
49
|
+
return { samples };
|
|
50
|
+
}
|
|
51
|
+
function percentile(values, percentage) {
|
|
52
|
+
if (!values.length)
|
|
53
|
+
return null;
|
|
54
|
+
const sorted = [...values].sort((left, right) => left - right);
|
|
55
|
+
const index = Math.max(0, Math.ceil(sorted.length * percentage) - 1);
|
|
56
|
+
return sorted[index] ?? null;
|
|
57
|
+
}
|
|
58
|
+
function transitionDuration(snapshot) {
|
|
59
|
+
const metric = duration(snapshot.metrics?.lastTransitionMs);
|
|
60
|
+
if (metric !== null)
|
|
61
|
+
return metric;
|
|
62
|
+
const startedAt = Date.parse(snapshot.transitionStartedAt || "");
|
|
63
|
+
const completedAt = Date.parse(snapshot.transitionCompletedAt || "");
|
|
64
|
+
return Number.isFinite(startedAt) && Number.isFinite(completedAt)
|
|
65
|
+
? Math.max(0, completedAt - startedAt)
|
|
66
|
+
: null;
|
|
67
|
+
}
|
|
68
|
+
function evaluateTheatreSlo(saved, snapshot, suppliedConfig = {}, nowValue = new Date()) {
|
|
69
|
+
const config = normaliseTheatreSloConfig(suppliedConfig);
|
|
70
|
+
const now = nowValue instanceof Date ? nowValue : new Date(nowValue);
|
|
71
|
+
const nowMs = now.getTime();
|
|
72
|
+
if (!Number.isFinite(nowMs))
|
|
73
|
+
throw new Error("now must be a valid date");
|
|
74
|
+
const state = createState(saved);
|
|
75
|
+
if ((snapshot.phase === "ready" || snapshot.phase === "failed") && snapshot.desiredActivity) {
|
|
76
|
+
const completedAt = timestamp(snapshot.transitionCompletedAt) || now.toISOString();
|
|
77
|
+
const sample = {
|
|
78
|
+
generation: snapshot.generation,
|
|
79
|
+
activity: snapshot.desiredActivity,
|
|
80
|
+
outcome: snapshot.phase,
|
|
81
|
+
transitionMs: transitionDuration(snapshot),
|
|
82
|
+
completedAt
|
|
83
|
+
};
|
|
84
|
+
const existing = state.samples.findIndex(({ generation }) => generation === snapshot.generation);
|
|
85
|
+
if (existing >= 0)
|
|
86
|
+
state.samples[existing] = sample;
|
|
87
|
+
else
|
|
88
|
+
state.samples.push(sample);
|
|
89
|
+
}
|
|
90
|
+
state.samples = state.samples
|
|
91
|
+
.sort((left, right) => left.generation - right.generation)
|
|
92
|
+
.slice(-config.windowSize);
|
|
93
|
+
const readyDurations = state.samples.flatMap((sample) => sample.outcome === "ready" && sample.transitionMs !== null ? [sample.transitionMs] : []);
|
|
94
|
+
const readyCount = state.samples.filter(({ outcome }) => outcome === "ready").length;
|
|
95
|
+
const successRatePct = state.samples.length
|
|
96
|
+
? Math.round(readyCount * 1000 / state.samples.length) / 10
|
|
97
|
+
: null;
|
|
98
|
+
const p50TransitionMs = percentile(readyDurations, 0.5);
|
|
99
|
+
const p95TransitionMs = percentile(readyDurations, 0.95);
|
|
100
|
+
const last = state.samples.at(-1) || null;
|
|
101
|
+
let status = "learning";
|
|
102
|
+
let reason = "minimum_samples";
|
|
103
|
+
const startedAt = Date.parse(snapshot.transitionStartedAt || "");
|
|
104
|
+
const transitionAgeMs = Number.isFinite(startedAt) ? Math.max(0, nowMs - startedAt) : null;
|
|
105
|
+
const timedPhase = ["requested", "preparing", "transitioning", "confirming", "recovering"]
|
|
106
|
+
.includes(snapshot.phase);
|
|
107
|
+
if (snapshot.phase === "failed") {
|
|
108
|
+
status = "breached";
|
|
109
|
+
reason = "transition_failed";
|
|
110
|
+
}
|
|
111
|
+
else if (timedPhase && transitionAgeMs !== null && transitionAgeMs > config.latencyBudgetMs) {
|
|
112
|
+
status = "breached";
|
|
113
|
+
reason = "transition_timeout";
|
|
114
|
+
}
|
|
115
|
+
else if (state.samples.length >= config.minimumSamples) {
|
|
116
|
+
if (successRatePct !== null && successRatePct < config.successObjectivePct) {
|
|
117
|
+
status = "breached";
|
|
118
|
+
reason = "success_objective";
|
|
119
|
+
}
|
|
120
|
+
else if (p95TransitionMs !== null && p95TransitionMs > config.latencyBudgetMs) {
|
|
121
|
+
status = "breached";
|
|
122
|
+
reason = "latency_budget";
|
|
123
|
+
}
|
|
124
|
+
else if ((successRatePct !== null && successRatePct < 100) ||
|
|
125
|
+
(p95TransitionMs !== null && p95TransitionMs >= config.latencyBudgetMs * 0.8)) {
|
|
126
|
+
status = "at_risk";
|
|
127
|
+
reason = successRatePct !== null && successRatePct < 100
|
|
128
|
+
? "error_budget_consumed"
|
|
129
|
+
: "latency_headroom";
|
|
130
|
+
}
|
|
131
|
+
else {
|
|
132
|
+
status = "healthy";
|
|
133
|
+
reason = "objectives_met";
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return {
|
|
137
|
+
state,
|
|
138
|
+
assessment: {
|
|
139
|
+
status,
|
|
140
|
+
reason,
|
|
141
|
+
sampleCount: state.samples.length,
|
|
142
|
+
windowSize: config.windowSize,
|
|
143
|
+
minimumSamples: config.minimumSamples,
|
|
144
|
+
latencyBudgetMs: config.latencyBudgetMs,
|
|
145
|
+
successObjectivePct: config.successObjectivePct,
|
|
146
|
+
successRatePct,
|
|
147
|
+
p50TransitionMs,
|
|
148
|
+
p95TransitionMs,
|
|
149
|
+
lastActivity: last?.activity || null,
|
|
150
|
+
lastOutcome: last?.outcome || null,
|
|
151
|
+
lastTransitionMs: last?.transitionMs ?? null,
|
|
152
|
+
evaluatedAt: now.toISOString()
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
//# sourceMappingURL=theatre-slo.js.map
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { type TheatreMetrics, type TheatreTarget } from "./theatre-activity-controller";
|
|
2
|
+
import { type TheatreSloConfig, type TheatreSloState } from "./theatre-slo";
|
|
3
|
+
export interface TheatreStateContractConfig {
|
|
4
|
+
area: string;
|
|
5
|
+
displayName: string;
|
|
6
|
+
baseTopic: string;
|
|
7
|
+
discoveryPrefix: string;
|
|
8
|
+
activities: string[];
|
|
9
|
+
slo: TheatreSloConfig;
|
|
10
|
+
}
|
|
11
|
+
export interface ContractRequest {
|
|
12
|
+
requestId: string;
|
|
13
|
+
generation: number;
|
|
14
|
+
activity: string;
|
|
15
|
+
requestedAt: string;
|
|
16
|
+
}
|
|
17
|
+
export interface TheatreStateContractState {
|
|
18
|
+
generation: number;
|
|
19
|
+
lastRequest: ContractRequest | null;
|
|
20
|
+
slo: TheatreSloState;
|
|
21
|
+
}
|
|
22
|
+
export interface TheatreStateSnapshot {
|
|
23
|
+
kind: "state";
|
|
24
|
+
area: string;
|
|
25
|
+
requestId: string | null;
|
|
26
|
+
generation: number;
|
|
27
|
+
desiredActivity: string | null;
|
|
28
|
+
requestedAt: string | null;
|
|
29
|
+
currentActivity: string;
|
|
30
|
+
phase: string;
|
|
31
|
+
availability: string;
|
|
32
|
+
transitionStartedAt: string | null;
|
|
33
|
+
transitionCompletedAt: string | null;
|
|
34
|
+
targets: Partial<Record<TheatreTarget, Record<string, unknown> | null>>;
|
|
35
|
+
failure: Record<string, unknown> | null;
|
|
36
|
+
degraded: Array<Record<string, unknown>>;
|
|
37
|
+
metrics?: TheatreMetrics;
|
|
38
|
+
}
|
|
39
|
+
export interface TheatreStateContractMessage {
|
|
40
|
+
topic?: string;
|
|
41
|
+
payload?: unknown;
|
|
42
|
+
retain?: boolean;
|
|
43
|
+
theatre?: TheatreStateSnapshot | Record<string, unknown>;
|
|
44
|
+
theatreStateContract?: {
|
|
45
|
+
kind: "startup";
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
export interface ContractPublication {
|
|
49
|
+
topic: string;
|
|
50
|
+
payload: string;
|
|
51
|
+
retain: true;
|
|
52
|
+
}
|
|
53
|
+
export interface ContractRequestOutput {
|
|
54
|
+
theatre: {
|
|
55
|
+
kind: "intent";
|
|
56
|
+
requestId: string;
|
|
57
|
+
generation: number;
|
|
58
|
+
activity: string;
|
|
59
|
+
requestedAt: string;
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
export declare function normaliseStateContractConfig(config?: Partial<TheatreStateContractConfig>): TheatreStateContractConfig;
|
|
63
|
+
export declare function transitionTheatreStateContract(saved: Partial<TheatreStateContractState> | undefined, msg: TheatreStateContractMessage, suppliedConfig: Partial<TheatreStateContractConfig>, nowValue?: Date | string | number): {
|
|
64
|
+
state: TheatreStateContractState;
|
|
65
|
+
requests: ContractRequestOutput[];
|
|
66
|
+
publications: ContractPublication[];
|
|
67
|
+
traces: {
|
|
68
|
+
event: string;
|
|
69
|
+
outcome: string;
|
|
70
|
+
reason: string | null;
|
|
71
|
+
details: Record<string, unknown>;
|
|
72
|
+
}[];
|
|
73
|
+
status: {
|
|
74
|
+
phase: string;
|
|
75
|
+
text: string;
|
|
76
|
+
};
|
|
77
|
+
};
|
|
@@ -0,0 +1,391 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.normaliseStateContractConfig = normaliseStateContractConfig;
|
|
4
|
+
exports.transitionTheatreStateContract = transitionTheatreStateContract;
|
|
5
|
+
const theatre_activity_controller_1 = require("./theatre-activity-controller");
|
|
6
|
+
const theatre_slo_1 = require("./theatre-slo");
|
|
7
|
+
const NAME = /^[a-z][a-z0-9_-]*$/;
|
|
8
|
+
const REQUEST_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
|
|
9
|
+
function normaliseStateContractConfig(config = {}) {
|
|
10
|
+
const area = String(config.area || "").trim();
|
|
11
|
+
if (!NAME.test(area))
|
|
12
|
+
throw new Error("area must be a lowercase identifier");
|
|
13
|
+
const displayName = String(config.displayName || "").trim();
|
|
14
|
+
if (!displayName)
|
|
15
|
+
throw new Error("displayName is required");
|
|
16
|
+
const baseTopic = String(config.baseTopic || `home/${area}/theatre`).replace(/^\/+|\/+$/g, "");
|
|
17
|
+
const discoveryPrefix = String(config.discoveryPrefix || "homeassistant").replace(/^\/+|\/+$/g, "");
|
|
18
|
+
if (!baseTopic || /[+#]/.test(baseTopic))
|
|
19
|
+
throw new Error("baseTopic must be a concrete MQTT topic");
|
|
20
|
+
if (!discoveryPrefix || /[+#]/.test(discoveryPrefix)) {
|
|
21
|
+
throw new Error("discoveryPrefix must be a concrete MQTT topic prefix");
|
|
22
|
+
}
|
|
23
|
+
if (!Array.isArray(config.activities) || config.activities.length === 0) {
|
|
24
|
+
throw new Error("activities must be a non-empty array");
|
|
25
|
+
}
|
|
26
|
+
const activities = config.activities.map((activity) => String(activity));
|
|
27
|
+
if (activities.some((activity) => !NAME.test(activity))) {
|
|
28
|
+
throw new Error("activities must contain lowercase identifiers");
|
|
29
|
+
}
|
|
30
|
+
if (new Set(activities).size !== activities.length)
|
|
31
|
+
throw new Error("activities must be unique");
|
|
32
|
+
return {
|
|
33
|
+
area,
|
|
34
|
+
displayName,
|
|
35
|
+
baseTopic,
|
|
36
|
+
discoveryPrefix,
|
|
37
|
+
activities,
|
|
38
|
+
slo: (0, theatre_slo_1.normaliseTheatreSloConfig)(config.slo)
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
function createState(saved = {}) {
|
|
42
|
+
const lastRequest = saved.lastRequest && typeof saved.lastRequest === "object"
|
|
43
|
+
? { ...saved.lastRequest }
|
|
44
|
+
: null;
|
|
45
|
+
return {
|
|
46
|
+
generation: Number.isInteger(saved.generation) && (saved.generation ?? -1) >= 0
|
|
47
|
+
? saved.generation
|
|
48
|
+
: 0,
|
|
49
|
+
lastRequest,
|
|
50
|
+
slo: {
|
|
51
|
+
samples: Array.isArray(saved.slo?.samples) ? saved.slo.samples.map((sample) => ({ ...sample })) : []
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
function parsePayload(payload) {
|
|
56
|
+
let value = payload;
|
|
57
|
+
if (Buffer.isBuffer(value))
|
|
58
|
+
value = value.toString("utf8");
|
|
59
|
+
if (typeof value === "string") {
|
|
60
|
+
try {
|
|
61
|
+
value = JSON.parse(value);
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
throw new Error("theatre request payload must be valid JSON");
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
68
|
+
throw new Error("theatre request payload must be an object");
|
|
69
|
+
}
|
|
70
|
+
return value;
|
|
71
|
+
}
|
|
72
|
+
function validTimestamp(value, fallback) {
|
|
73
|
+
const timestamp = value === undefined ? fallback : String(value);
|
|
74
|
+
if (!Number.isFinite(Date.parse(timestamp)))
|
|
75
|
+
throw new Error("requestedAt must be an ISO timestamp");
|
|
76
|
+
return timestamp;
|
|
77
|
+
}
|
|
78
|
+
function publication(topic, payload) {
|
|
79
|
+
return {
|
|
80
|
+
topic,
|
|
81
|
+
payload: typeof payload === "string" ? payload : JSON.stringify(payload),
|
|
82
|
+
retain: true
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
function device(config) {
|
|
86
|
+
return {
|
|
87
|
+
identifiers: [`nodered_${config.area}_theatre`],
|
|
88
|
+
name: `${config.displayName} Theatre Controller`,
|
|
89
|
+
manufacturer: "Node-RED",
|
|
90
|
+
model: "Deterministic theatre activity controller"
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
function discoveryPublications(config) {
|
|
94
|
+
const { area, baseTopic, discoveryPrefix } = config;
|
|
95
|
+
const controllerDevice = device(config);
|
|
96
|
+
const entries = [
|
|
97
|
+
{
|
|
98
|
+
component: "select",
|
|
99
|
+
objectId: `${area}_theatre_activity`,
|
|
100
|
+
payload: {
|
|
101
|
+
name: "Requested activity",
|
|
102
|
+
unique_id: `${area}_theatre_activity`,
|
|
103
|
+
default_entity_id: `select.${area}_theatre_activity`,
|
|
104
|
+
icon: "mdi:theater",
|
|
105
|
+
command_topic: `${baseTopic}/request`,
|
|
106
|
+
state_topic: `${baseTopic}/desired`,
|
|
107
|
+
value_template: "{{ value_json.activity if value_json else none }}",
|
|
108
|
+
command_template: "{\"requestId\":\"ha-{{ now().strftime('%Y%m%d%H%M%S%f') }}\",\"activity\":\"{{ value }}\"}",
|
|
109
|
+
options: config.activities,
|
|
110
|
+
optimistic: false,
|
|
111
|
+
device: controllerDevice
|
|
112
|
+
}
|
|
113
|
+
},
|
|
114
|
+
{
|
|
115
|
+
component: "sensor",
|
|
116
|
+
objectId: `${area}_theatre_current`,
|
|
117
|
+
payload: {
|
|
118
|
+
name: "Current activity",
|
|
119
|
+
unique_id: `${area}_theatre_current`,
|
|
120
|
+
default_entity_id: `sensor.${area}_theatre_current`,
|
|
121
|
+
icon: "mdi:play-circle-outline",
|
|
122
|
+
state_topic: `${baseTopic}/current`,
|
|
123
|
+
device: controllerDevice
|
|
124
|
+
}
|
|
125
|
+
},
|
|
126
|
+
{
|
|
127
|
+
component: "sensor",
|
|
128
|
+
objectId: `${area}_theatre_phase`,
|
|
129
|
+
payload: {
|
|
130
|
+
name: "Phase",
|
|
131
|
+
unique_id: `${area}_theatre_phase`,
|
|
132
|
+
default_entity_id: `sensor.${area}_theatre_phase`,
|
|
133
|
+
icon: "mdi:state-machine",
|
|
134
|
+
state_topic: `${baseTopic}/phase`,
|
|
135
|
+
device: controllerDevice
|
|
136
|
+
}
|
|
137
|
+
},
|
|
138
|
+
{
|
|
139
|
+
component: "sensor",
|
|
140
|
+
objectId: `${area}_theatre_availability`,
|
|
141
|
+
payload: {
|
|
142
|
+
name: "Availability",
|
|
143
|
+
unique_id: `${area}_theatre_availability`,
|
|
144
|
+
default_entity_id: `sensor.${area}_theatre_availability`,
|
|
145
|
+
icon: "mdi:check-network-outline",
|
|
146
|
+
state_topic: `${baseTopic}/availability`,
|
|
147
|
+
entity_category: "diagnostic",
|
|
148
|
+
device: controllerDevice
|
|
149
|
+
}
|
|
150
|
+
},
|
|
151
|
+
{
|
|
152
|
+
component: "sensor",
|
|
153
|
+
objectId: `${area}_theatre_failure`,
|
|
154
|
+
payload: {
|
|
155
|
+
name: "Failure",
|
|
156
|
+
unique_id: `${area}_theatre_failure`,
|
|
157
|
+
default_entity_id: `sensor.${area}_theatre_failure`,
|
|
158
|
+
icon: "mdi:alert-circle-outline",
|
|
159
|
+
state_topic: `${baseTopic}/failure`,
|
|
160
|
+
value_template: "{{ value_json.reason if value_json else '' }}",
|
|
161
|
+
entity_category: "diagnostic",
|
|
162
|
+
device: controllerDevice
|
|
163
|
+
}
|
|
164
|
+
},
|
|
165
|
+
{
|
|
166
|
+
component: "sensor",
|
|
167
|
+
objectId: `${area}_theatre_transition_metrics`,
|
|
168
|
+
payload: {
|
|
169
|
+
name: "Transition latency",
|
|
170
|
+
unique_id: `${area}_theatre_transition_metrics`,
|
|
171
|
+
default_entity_id: `sensor.${area}_theatre_transition_metrics`,
|
|
172
|
+
icon: "mdi:timer-check-outline",
|
|
173
|
+
state_topic: `${baseTopic}/metrics`,
|
|
174
|
+
value_template: "{{ value_json.lastTransitionMs if value_json.lastTransitionMs is not none else 'unknown' }}",
|
|
175
|
+
json_attributes_topic: `${baseTopic}/metrics`,
|
|
176
|
+
unit_of_measurement: "ms",
|
|
177
|
+
entity_category: "diagnostic",
|
|
178
|
+
device: controllerDevice
|
|
179
|
+
}
|
|
180
|
+
},
|
|
181
|
+
{
|
|
182
|
+
component: "sensor",
|
|
183
|
+
objectId: `${area}_theatre_slo_status`,
|
|
184
|
+
payload: {
|
|
185
|
+
name: "Operational SLO",
|
|
186
|
+
unique_id: `${area}_theatre_slo_status`,
|
|
187
|
+
default_entity_id: `sensor.${area}_theatre_slo_status`,
|
|
188
|
+
icon: "mdi:target-account",
|
|
189
|
+
state_topic: `${baseTopic}/slo`,
|
|
190
|
+
value_template: "{{ value_json.status }}",
|
|
191
|
+
json_attributes_topic: `${baseTopic}/slo`,
|
|
192
|
+
entity_category: "diagnostic",
|
|
193
|
+
device: controllerDevice
|
|
194
|
+
}
|
|
195
|
+
},
|
|
196
|
+
{
|
|
197
|
+
component: "binary_sensor",
|
|
198
|
+
objectId: `${area}_theatre_slo_breach`,
|
|
199
|
+
payload: {
|
|
200
|
+
name: "Operational SLO breach",
|
|
201
|
+
unique_id: `${area}_theatre_slo_breach`,
|
|
202
|
+
default_entity_id: `binary_sensor.${area}_theatre_slo_breach`,
|
|
203
|
+
icon: "mdi:alert-decagram-outline",
|
|
204
|
+
state_topic: `${baseTopic}/slo/breach`,
|
|
205
|
+
payload_on: "ON",
|
|
206
|
+
payload_off: "OFF",
|
|
207
|
+
device_class: "problem",
|
|
208
|
+
entity_category: "diagnostic",
|
|
209
|
+
device: controllerDevice
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
];
|
|
213
|
+
for (const target of theatre_activity_controller_1.TARGETS) {
|
|
214
|
+
entries.push({
|
|
215
|
+
component: "sensor",
|
|
216
|
+
objectId: `${area}_theatre_${target}_health`,
|
|
217
|
+
payload: {
|
|
218
|
+
name: `${target[0]?.toUpperCase()}${target.slice(1)} health`,
|
|
219
|
+
unique_id: `${area}_theatre_${target}_health`,
|
|
220
|
+
default_entity_id: `sensor.${area}_theatre_${target}_health`,
|
|
221
|
+
icon: "mdi:heart-pulse",
|
|
222
|
+
state_topic: `${baseTopic}/health/${target}`,
|
|
223
|
+
value_template: "{{ value_json.status }}",
|
|
224
|
+
json_attributes_topic: `${baseTopic}/health/${target}`,
|
|
225
|
+
entity_category: "diagnostic",
|
|
226
|
+
device: controllerDevice
|
|
227
|
+
}
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
return entries.map(({ component, objectId, payload }) => publication(`${discoveryPrefix}/${component}/${objectId}/config`, payload));
|
|
231
|
+
}
|
|
232
|
+
function statePublications(event, config, slo) {
|
|
233
|
+
const base = config.baseTopic;
|
|
234
|
+
const desired = event.requestId && event.desiredActivity
|
|
235
|
+
? {
|
|
236
|
+
requestId: event.requestId,
|
|
237
|
+
generation: event.generation,
|
|
238
|
+
activity: event.desiredActivity,
|
|
239
|
+
requestedAt: event.requestedAt
|
|
240
|
+
}
|
|
241
|
+
: null;
|
|
242
|
+
const outputs = [
|
|
243
|
+
publication(`${base}/desired`, desired),
|
|
244
|
+
publication(`${base}/current`, event.currentActivity),
|
|
245
|
+
publication(`${base}/phase`, event.phase),
|
|
246
|
+
publication(`${base}/failure`, event.failure),
|
|
247
|
+
publication(`${base}/availability`, event.availability),
|
|
248
|
+
publication(`${base}/metrics`, event.metrics || {
|
|
249
|
+
requests: 0,
|
|
250
|
+
ready: 0,
|
|
251
|
+
failed: 0,
|
|
252
|
+
superseded: 0,
|
|
253
|
+
manualOverrides: 0,
|
|
254
|
+
driftEvents: 0,
|
|
255
|
+
recoveriesAdopted: 0,
|
|
256
|
+
recoveriesSafeOff: 0,
|
|
257
|
+
lastTransitionMs: null,
|
|
258
|
+
maxTransitionMs: null,
|
|
259
|
+
lastOutcome: null,
|
|
260
|
+
targets: {}
|
|
261
|
+
}),
|
|
262
|
+
publication(`${base}/slo`, slo),
|
|
263
|
+
publication(`${base}/slo/breach`, slo.status === "breached" ? "ON" : "OFF")
|
|
264
|
+
];
|
|
265
|
+
for (const target of theatre_activity_controller_1.TARGETS) {
|
|
266
|
+
const health = event.targets[target];
|
|
267
|
+
outputs.push(publication(`${base}/health/${target}`, health || {
|
|
268
|
+
status: "unknown",
|
|
269
|
+
observedAt: null,
|
|
270
|
+
classification: null,
|
|
271
|
+
failure: null,
|
|
272
|
+
details: null
|
|
273
|
+
}));
|
|
274
|
+
}
|
|
275
|
+
return outputs;
|
|
276
|
+
}
|
|
277
|
+
function requestPublications(request, config) {
|
|
278
|
+
const base = config.baseTopic;
|
|
279
|
+
return [
|
|
280
|
+
publication(`${base}/desired`, request),
|
|
281
|
+
publication(`${base}/phase`, "requested"),
|
|
282
|
+
publication(`${base}/failure`, null),
|
|
283
|
+
publication(`${base}/availability`, "unknown")
|
|
284
|
+
];
|
|
285
|
+
}
|
|
286
|
+
function asStateSnapshot(value) {
|
|
287
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
288
|
+
throw new Error("theatre state must be an object");
|
|
289
|
+
}
|
|
290
|
+
const event = value;
|
|
291
|
+
if (event.kind !== "state")
|
|
292
|
+
throw new Error("theatre state kind must be state");
|
|
293
|
+
if (!Number.isInteger(event.generation) || (event.generation ?? -1) < 0) {
|
|
294
|
+
throw new Error("theatre state generation must be a non-negative integer");
|
|
295
|
+
}
|
|
296
|
+
if (typeof event.currentActivity !== "string" || typeof event.phase !== "string" ||
|
|
297
|
+
typeof event.availability !== "string") {
|
|
298
|
+
throw new Error("theatre state must define currentActivity, phase and availability");
|
|
299
|
+
}
|
|
300
|
+
if (!event.targets || typeof event.targets !== "object" || Array.isArray(event.targets)) {
|
|
301
|
+
throw new Error("theatre state targets must be an object");
|
|
302
|
+
}
|
|
303
|
+
return event;
|
|
304
|
+
}
|
|
305
|
+
function transitionTheatreStateContract(saved, msg, suppliedConfig, nowValue = new Date()) {
|
|
306
|
+
const config = normaliseStateContractConfig(suppliedConfig);
|
|
307
|
+
const state = createState(saved);
|
|
308
|
+
const now = nowValue instanceof Date ? nowValue : new Date(nowValue);
|
|
309
|
+
if (!Number.isFinite(now.getTime()))
|
|
310
|
+
throw new Error("now must be a valid date");
|
|
311
|
+
const requests = [];
|
|
312
|
+
const publications = [];
|
|
313
|
+
const traces = [];
|
|
314
|
+
function trace(event, outcome, reason = null, details = {}) {
|
|
315
|
+
traces.push({ event, outcome, reason, details });
|
|
316
|
+
}
|
|
317
|
+
if (msg.theatreStateContract?.kind === "startup") {
|
|
318
|
+
publications.push(...discoveryPublications(config));
|
|
319
|
+
trace("startup", "discovery", null, { publications: publications.length });
|
|
320
|
+
}
|
|
321
|
+
else if (msg.topic === `${config.baseTopic}/request`) {
|
|
322
|
+
if (msg.retain === true) {
|
|
323
|
+
trace("request", "ignored", "retained-request");
|
|
324
|
+
}
|
|
325
|
+
else {
|
|
326
|
+
const payload = parsePayload(msg.payload);
|
|
327
|
+
const requestId = String(payload.requestId || "");
|
|
328
|
+
const activity = String(payload.activity || "");
|
|
329
|
+
if (!REQUEST_ID.test(requestId))
|
|
330
|
+
throw new Error("requestId is invalid");
|
|
331
|
+
if (!config.activities.includes(activity))
|
|
332
|
+
throw new Error("unknown theatre activity");
|
|
333
|
+
const requestedAt = validTimestamp(payload.requestedAt, now.toISOString());
|
|
334
|
+
if (state.lastRequest?.requestId === requestId) {
|
|
335
|
+
if (state.lastRequest.activity !== activity) {
|
|
336
|
+
throw new Error("requestId cannot be reused for another activity");
|
|
337
|
+
}
|
|
338
|
+
requests.push({ theatre: { kind: "intent", ...state.lastRequest } });
|
|
339
|
+
trace("request", "duplicate", null, { requestId, generation: state.lastRequest.generation });
|
|
340
|
+
}
|
|
341
|
+
else {
|
|
342
|
+
state.generation += 1;
|
|
343
|
+
state.lastRequest = { requestId, generation: state.generation, activity, requestedAt };
|
|
344
|
+
requests.push({ theatre: { kind: "intent", ...state.lastRequest } });
|
|
345
|
+
trace("request", "accepted", null, { requestId, generation: state.generation, activity });
|
|
346
|
+
}
|
|
347
|
+
publications.push(...requestPublications(state.lastRequest, config));
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
else if (msg.theatre && typeof msg.theatre === "object" && msg.theatre.kind === "state") {
|
|
351
|
+
const event = asStateSnapshot(msg.theatre);
|
|
352
|
+
if (event.generation < state.generation) {
|
|
353
|
+
trace("state", "ignored", "stale-generation", { generation: event.generation });
|
|
354
|
+
}
|
|
355
|
+
else {
|
|
356
|
+
state.generation = event.generation;
|
|
357
|
+
if (event.requestId && event.desiredActivity) {
|
|
358
|
+
state.lastRequest = {
|
|
359
|
+
requestId: event.requestId,
|
|
360
|
+
generation: event.generation,
|
|
361
|
+
activity: event.desiredActivity,
|
|
362
|
+
requestedAt: event.requestedAt || event.transitionStartedAt || now.toISOString()
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
const slo = (0, theatre_slo_1.evaluateTheatreSlo)(state.slo, event, config.slo, now);
|
|
366
|
+
state.slo = slo.state;
|
|
367
|
+
publications.push(...statePublications(event, config, slo.assessment));
|
|
368
|
+
trace("state", "published", null, {
|
|
369
|
+
generation: event.generation,
|
|
370
|
+
phase: event.phase,
|
|
371
|
+
publications: publications.length
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
else {
|
|
376
|
+
trace("message", "ignored", "unrelated-message");
|
|
377
|
+
}
|
|
378
|
+
return {
|
|
379
|
+
state,
|
|
380
|
+
requests,
|
|
381
|
+
publications,
|
|
382
|
+
traces,
|
|
383
|
+
status: {
|
|
384
|
+
phase: requests.length ? "requested" : publications.length ? "published" : "idle",
|
|
385
|
+
text: state.lastRequest
|
|
386
|
+
? `${state.lastRequest.activity} · ${state.generation}`
|
|
387
|
+
: "waiting for state"
|
|
388
|
+
}
|
|
389
|
+
};
|
|
390
|
+
}
|
|
391
|
+
//# sourceMappingURL=theatre-state-contract.js.map
|