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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +32 -8
  2. package/contract-examples/room-lighting.mjs +12 -7
  3. package/dist/lib/activity-lighting-controller.d.ts +13 -25
  4. package/dist/lib/activity-lighting-controller.js +15 -11
  5. package/dist/lib/avr-controller.d.ts +13 -47
  6. package/dist/lib/avr-controller.js +39 -90
  7. package/dist/lib/backlighting-controller.d.ts +12 -25
  8. package/dist/lib/backlighting-controller.js +11 -18
  9. package/dist/lib/bounded-trace.d.ts +6 -0
  10. package/dist/lib/command-echo.d.ts +20 -0
  11. package/dist/lib/command-echo.js +82 -0
  12. package/dist/lib/cover-controller.d.ts +15 -28
  13. package/dist/lib/cover-controller.js +6 -8
  14. package/dist/lib/denon-protocol.d.ts +29 -0
  15. package/dist/lib/denon-protocol.js +76 -0
  16. package/dist/lib/display-mode-controller.d.ts +7 -18
  17. package/dist/lib/display-mode-controller.js +39 -47
  18. package/dist/lib/motion-policy.d.ts +12 -22
  19. package/dist/lib/motion-policy.js +53 -56
  20. package/dist/lib/occupancy-fusion.d.ts +8 -12
  21. package/dist/lib/room-controller.d.ts +14 -34
  22. package/dist/lib/room-controller.js +80 -132
  23. package/dist/lib/room-lighting-discovery.d.ts +9 -0
  24. package/dist/lib/room-lighting-discovery.js +45 -0
  25. package/dist/lib/settings.d.ts +5 -0
  26. package/dist/lib/settings.js +68 -0
  27. package/dist/lib/source-capability-controller.d.ts +30 -35
  28. package/dist/lib/source-capability-controller.js +35 -36
  29. package/dist/lib/switch-policy.d.ts +2 -7
  30. package/dist/lib/target-state.d.ts +24 -0
  31. package/dist/lib/target-state.js +38 -0
  32. package/dist/lib/theatre-activity-controller.d.ts +6 -108
  33. package/dist/lib/theatre-activity-controller.js +67 -318
  34. package/dist/lib/theatre-ha-discovery.d.ts +14 -0
  35. package/dist/lib/theatre-ha-discovery.js +163 -0
  36. package/dist/lib/theatre-metrics.d.ts +4 -0
  37. package/dist/lib/theatre-metrics.js +66 -0
  38. package/dist/lib/theatre-profiles.d.ts +23 -0
  39. package/dist/lib/theatre-profiles.js +73 -0
  40. package/dist/lib/theatre-refresh.d.ts +20 -0
  41. package/dist/lib/theatre-refresh.js +46 -0
  42. package/dist/lib/theatre-slo.js +7 -9
  43. package/dist/lib/theatre-state-contract.d.ts +7 -19
  44. package/dist/lib/theatre-state-contract.js +33 -169
  45. package/dist/lib/theatre-state.d.ts +110 -0
  46. package/dist/lib/theatre-state.js +139 -0
  47. package/dist/lib/wall-input.d.ts +2 -7
  48. package/dist/lib/z2m-light.d.ts +16 -0
  49. package/dist/lib/z2m-light.js +36 -0
  50. package/dist/nodes/activity-lighting-controller.html +5 -3
  51. package/dist/nodes/activity-lighting-controller.js +21 -52
  52. package/dist/nodes/adapter.d.ts +15 -0
  53. package/dist/nodes/adapter.js +60 -0
  54. package/dist/nodes/avr-controller.html +3 -3
  55. package/dist/nodes/avr-controller.js +17 -56
  56. package/dist/nodes/backlighting-controller.html +1 -1
  57. package/dist/nodes/backlighting-controller.js +25 -47
  58. package/dist/nodes/display-mode-controller.html +2 -2
  59. package/dist/nodes/display-mode-controller.js +19 -57
  60. package/dist/nodes/motion-policy.html +23 -10
  61. package/dist/nodes/motion-policy.js +14 -135
  62. package/dist/nodes/occupancy-fusion.html +2 -2
  63. package/dist/nodes/occupancy-fusion.js +23 -29
  64. package/dist/nodes/room-controller.html +80 -26
  65. package/dist/nodes/room-controller.js +37 -54
  66. package/dist/nodes/source-capability-controller.html +4 -13
  67. package/dist/nodes/source-capability-controller.js +17 -52
  68. package/dist/nodes/switch-policy.html +3 -3
  69. package/dist/nodes/switch-policy.js +23 -42
  70. package/dist/nodes/theatre-activity-controller.html +4 -2
  71. package/dist/nodes/theatre-activity-controller.js +18 -45
  72. package/dist/nodes/theatre-state-contract.html +55 -22
  73. package/dist/nodes/theatre-state-contract.js +30 -41
  74. package/examples/Home theatre activity.json +13 -12
  75. package/examples/Home theatre equipment.json +4 -4
  76. package/examples/Room lighting.json +9 -9
  77. package/package.json +1 -1
  78. package/dist/lib/circadian-refresh.d.ts +0 -7
  79. package/dist/lib/circadian-refresh.js +0 -11
@@ -2,19 +2,26 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.normaliseStateContractConfig = normaliseStateContractConfig;
4
4
  exports.transitionTheatreStateContract = transitionTheatreStateContract;
5
- const theatre_activity_controller_1 = require("./theatre-activity-controller");
5
+ const theatre_profiles_1 = require("./theatre-profiles");
6
+ const theatre_ha_discovery_1 = require("./theatre-ha-discovery");
6
7
  const theatre_slo_1 = require("./theatre-slo");
8
+ const settings_1 = require("./settings");
7
9
  const NAME = /^[a-z][a-z0-9_-]*$/;
8
10
  const REQUEST_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
9
11
  function normaliseStateContractConfig(config = {}) {
12
+ const discovery = config.discovery !== false;
13
+ // The area names the discovery entities and the default base topic, so it
14
+ // is needed for either; otherwise it is optional.
10
15
  const area = String(config.area || "").trim();
11
- if (!NAME.test(area))
16
+ if (!area && (discovery || !config.baseTopic))
17
+ throw new Error("area is required");
18
+ if (area && !NAME.test(area))
12
19
  throw new Error("area must be a lowercase identifier");
13
- const displayName = String(config.displayName || "").trim();
14
- if (!displayName)
20
+ const displayName = String(config.displayName || area).trim();
21
+ if (discovery && !displayName)
15
22
  throw new Error("displayName is required");
16
23
  const baseTopic = String(config.baseTopic || `home/${area}/theatre`).replace(/^\/+|\/+$/g, "");
17
- const discoveryPrefix = String(config.discoveryPrefix || "homeassistant").replace(/^\/+|\/+$/g, "");
24
+ const discoveryPrefix = (0, settings_1.textSetting)(config.discoveryPrefix, "discovery prefix", "homeassistant").replace(/^\/+|\/+$/g, "");
18
25
  if (!baseTopic || /[+#]/.test(baseTopic))
19
26
  throw new Error("baseTopic must be a concrete MQTT topic");
20
27
  if (!discoveryPrefix || /[+#]/.test(discoveryPrefix)) {
@@ -35,7 +42,8 @@ function normaliseStateContractConfig(config = {}) {
35
42
  baseTopic,
36
43
  discoveryPrefix,
37
44
  activities,
38
- slo: (0, theatre_slo_1.normaliseTheatreSloConfig)(config.slo)
45
+ slo: (0, theatre_slo_1.normaliseTheatreSloConfig)(config.slo),
46
+ discovery
39
47
  };
40
48
  }
41
49
  function createState(saved = {}) {
@@ -82,153 +90,6 @@ function publication(topic, payload) {
82
90
  retain: true
83
91
  };
84
92
  }
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
93
  function statePublications(event, config, slo) {
233
94
  const base = config.baseTopic;
234
95
  const desired = event.requestId && event.desiredActivity
@@ -240,12 +101,12 @@ function statePublications(event, config, slo) {
240
101
  }
241
102
  : null;
242
103
  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 || {
104
+ publication((0, theatre_ha_discovery_1.theatreTopic)(base, "desired"), desired),
105
+ publication((0, theatre_ha_discovery_1.theatreTopic)(base, "current"), event.currentActivity),
106
+ publication((0, theatre_ha_discovery_1.theatreTopic)(base, "phase"), event.phase),
107
+ publication((0, theatre_ha_discovery_1.theatreTopic)(base, "failure"), event.failure),
108
+ publication((0, theatre_ha_discovery_1.theatreTopic)(base, "availability"), event.availability),
109
+ publication((0, theatre_ha_discovery_1.theatreTopic)(base, "metrics"), event.metrics || {
249
110
  requests: 0,
250
111
  ready: 0,
251
112
  failed: 0,
@@ -259,12 +120,12 @@ function statePublications(event, config, slo) {
259
120
  lastOutcome: null,
260
121
  targets: {}
261
122
  }),
262
- publication(`${base}/slo`, slo),
263
- publication(`${base}/slo/breach`, slo.status === "breached" ? "ON" : "OFF")
123
+ publication((0, theatre_ha_discovery_1.theatreTopic)(base, "slo"), slo),
124
+ publication((0, theatre_ha_discovery_1.theatreTopic)(base, "slo/breach"), slo.status === "breached" ? "ON" : "OFF")
264
125
  ];
265
- for (const target of theatre_activity_controller_1.TARGETS) {
126
+ for (const target of theatre_profiles_1.TARGETS) {
266
127
  const health = event.targets[target];
267
- outputs.push(publication(`${base}/health/${target}`, health || {
128
+ outputs.push(publication((0, theatre_ha_discovery_1.theatreTopic)(base, `health/${target}`), health || {
268
129
  status: "unknown",
269
130
  observedAt: null,
270
131
  classification: null,
@@ -277,10 +138,10 @@ function statePublications(event, config, slo) {
277
138
  function requestPublications(request, config) {
278
139
  const base = config.baseTopic;
279
140
  return [
280
- publication(`${base}/desired`, request),
281
- publication(`${base}/phase`, "requested"),
282
- publication(`${base}/failure`, null),
283
- publication(`${base}/availability`, "unknown")
141
+ publication((0, theatre_ha_discovery_1.theatreTopic)(base, "desired"), request),
142
+ publication((0, theatre_ha_discovery_1.theatreTopic)(base, "phase"), "requested"),
143
+ publication((0, theatre_ha_discovery_1.theatreTopic)(base, "failure"), null),
144
+ publication((0, theatre_ha_discovery_1.theatreTopic)(base, "availability"), "unknown")
284
145
  ];
285
146
  }
286
147
  function asStateSnapshot(value) {
@@ -315,10 +176,13 @@ function transitionTheatreStateContract(saved, msg, suppliedConfig, nowValue = n
315
176
  traces.push({ event, outcome, reason, details });
316
177
  }
317
178
  if (msg.theatreStateContract?.kind === "startup") {
318
- publications.push(...discoveryPublications(config));
179
+ // Discovery switched off: empty retained entries remove the entities
180
+ // from Home Assistant.
181
+ const entries = config.discovery !== false || config.area ? (0, theatre_ha_discovery_1.theatreDiscovery)(config) : [];
182
+ publications.push(...entries.map(({ topic, payload }) => publication(topic, config.discovery !== false ? payload : "")));
319
183
  trace("startup", "discovery", null, { publications: publications.length });
320
184
  }
321
- else if (msg.topic === `${config.baseTopic}/request`) {
185
+ else if (msg.topic === (0, theatre_ha_discovery_1.theatreTopic)(config.baseTopic, "request")) {
322
186
  if (msg.retain === true) {
323
187
  trace("request", "ignored", "retained-request");
324
188
  }
@@ -0,0 +1,110 @@
1
+ import type { TargetStatus } from "./target-state";
2
+ import { type ActivityProfiles, type TheatreTarget } from "./theatre-profiles";
3
+ export type { TargetStatus };
4
+ export type TargetClassification = "drift" | "manual_override";
5
+ export type TheatreAvailability = "unknown" | "available" | "degraded" | "unavailable";
6
+ export declare const TARGET_CLASSIFICATIONS: Record<TargetClassification, true>;
7
+ export interface TheatreDesired {
8
+ requestId: string;
9
+ generation: number;
10
+ activity: string;
11
+ requestedAt: string;
12
+ }
13
+ export interface TargetFailure {
14
+ operation?: string | null;
15
+ reason?: string;
16
+ occurredAt?: string;
17
+ }
18
+ export interface TargetState {
19
+ status: TargetStatus;
20
+ observedAt: string;
21
+ classification: TargetClassification | null;
22
+ failure: TargetFailure | null;
23
+ details: Record<string, unknown> | null;
24
+ }
25
+ export interface TheatreFailure {
26
+ target: TheatreTarget;
27
+ operation: string | null;
28
+ reason: string;
29
+ occurredAt: string;
30
+ }
31
+ export interface TheatreTargetMetrics {
32
+ attempts: number;
33
+ retries: number;
34
+ failures: number;
35
+ manualOverrides: number;
36
+ fallbackUses: number;
37
+ fallbackUsed: boolean;
38
+ lastConfirmationMs: number | null;
39
+ observationAgeMs: number | null;
40
+ availability: TheatreAvailability;
41
+ }
42
+ export interface TheatreMetrics {
43
+ requests: number;
44
+ ready: number;
45
+ failed: number;
46
+ superseded: number;
47
+ manualOverrides: number;
48
+ driftEvents: number;
49
+ recoveriesAdopted: number;
50
+ recoveriesSafeOff: number;
51
+ lastTransitionMs: number | null;
52
+ maxTransitionMs: number | null;
53
+ lastOutcome: string | null;
54
+ targets: Record<TheatreTarget, TheatreTargetMetrics>;
55
+ }
56
+ export interface RecoveryObservation {
57
+ observedAt: string;
58
+ values: Record<string, unknown>;
59
+ }
60
+ export type RecoveryObservations = Partial<Record<TheatreTarget, RecoveryObservation>>;
61
+ export interface RefreshPending {
62
+ sentAt: number;
63
+ attempts: number;
64
+ exhausted: boolean;
65
+ }
66
+ export interface TheatreState {
67
+ desired: TheatreDesired | null;
68
+ currentActivity: string;
69
+ generation: number;
70
+ lastProposedGeneration: number;
71
+ phase: string;
72
+ targets: Record<TheatreTarget, TargetState | null>;
73
+ refreshPending: Record<TheatreTarget, RefreshPending | null>;
74
+ failure: TheatreFailure | null;
75
+ blockedGeneration: number | null;
76
+ degraded: Array<{
77
+ target: TheatreTarget;
78
+ reason: string;
79
+ }>;
80
+ availability: TheatreAvailability;
81
+ transitionStartedAt: string | null;
82
+ transitionCompletedAt: string | null;
83
+ metrics: TheatreMetrics;
84
+ }
85
+ export declare function emptyTargets(saved?: Partial<Record<TheatreTarget, TargetState | null>>): Record<TheatreTarget, TargetState | null>;
86
+ export declare const REFRESH_ATTEMPTS = 3;
87
+ export declare function emptyRefreshPending(saved?: Partial<Record<TheatreTarget, RefreshPending | boolean | null>>): Record<TheatreTarget, RefreshPending | null>;
88
+ export declare function count(value: unknown): number;
89
+ export declare function createTheatreState(saved?: Partial<TheatreState>, activityProfiles?: ActivityProfiles): TheatreState;
90
+ export interface TheatreSnapshot {
91
+ kind: "state";
92
+ area: string;
93
+ requestId: string | null;
94
+ generation: number;
95
+ desiredActivity: string | null;
96
+ requestedAt: string | null;
97
+ currentActivity: string;
98
+ phase: string;
99
+ availability: TheatreAvailability;
100
+ transitionStartedAt: string | null;
101
+ transitionCompletedAt: string | null;
102
+ targets: Record<TheatreTarget, TargetState | null>;
103
+ failure: TheatreFailure | null;
104
+ degraded: Array<{
105
+ target: TheatreTarget;
106
+ reason: string;
107
+ }>;
108
+ metrics: TheatreMetrics;
109
+ }
110
+ export declare function theatreSnapshot(state: TheatreState, area: string): TheatreSnapshot;
@@ -0,0 +1,139 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.REFRESH_ATTEMPTS = exports.TARGET_CLASSIFICATIONS = void 0;
4
+ exports.emptyTargets = emptyTargets;
5
+ exports.emptyRefreshPending = emptyRefreshPending;
6
+ exports.count = count;
7
+ exports.createTheatreState = createTheatreState;
8
+ exports.theatreSnapshot = theatreSnapshot;
9
+ const theatre_profiles_1 = require("./theatre-profiles");
10
+ exports.TARGET_CLASSIFICATIONS = {
11
+ drift: true,
12
+ manual_override: true
13
+ };
14
+ const AVAILABILITIES = {
15
+ unknown: true,
16
+ available: true,
17
+ degraded: true,
18
+ unavailable: true
19
+ };
20
+ function emptyTargets(saved = {}) {
21
+ return Object.fromEntries(theatre_profiles_1.TARGETS.map((target) => [
22
+ target,
23
+ saved[target] && typeof saved[target] === "object" ? { ...saved[target] } : null
24
+ ]));
25
+ }
26
+ // A refresh is re-sent at this many attempts at most before the target is
27
+ // reported as not responding.
28
+ exports.REFRESH_ATTEMPTS = 3;
29
+ function emptyRefreshPending(saved = {}) {
30
+ return Object.fromEntries(theatre_profiles_1.TARGETS.map((target) => {
31
+ const entry = saved[target];
32
+ // Saved before retries existed: pending with no send time, so it retries.
33
+ if (entry === true)
34
+ return [target, { sentAt: 0, attempts: 1, exhausted: false }];
35
+ if (entry && typeof entry === "object" && Number.isFinite(entry.sentAt) && Number.isInteger(entry.attempts)) {
36
+ return [target, { sentAt: entry.sentAt, attempts: entry.attempts, exhausted: entry.exhausted === true }];
37
+ }
38
+ return [target, null];
39
+ }));
40
+ }
41
+ function count(value) {
42
+ const parsed = Number(value);
43
+ return Number.isInteger(parsed) && parsed >= 0 ? parsed : 0;
44
+ }
45
+ function nullableDuration(value) {
46
+ const parsed = Number(value);
47
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : null;
48
+ }
49
+ function targetMetrics(saved = {}) {
50
+ return Object.fromEntries(theatre_profiles_1.TARGETS.map((target) => {
51
+ const metric = saved[target] || {};
52
+ const availability = typeof metric.availability === "string" &&
53
+ Object.hasOwn(AVAILABILITIES, metric.availability)
54
+ ? metric.availability
55
+ : "unknown";
56
+ return [target, {
57
+ attempts: count(metric.attempts),
58
+ retries: count(metric.retries),
59
+ failures: count(metric.failures),
60
+ manualOverrides: count(metric.manualOverrides),
61
+ fallbackUses: count(metric.fallbackUses),
62
+ fallbackUsed: metric.fallbackUsed === true,
63
+ lastConfirmationMs: nullableDuration(metric.lastConfirmationMs),
64
+ observationAgeMs: nullableDuration(metric.observationAgeMs),
65
+ availability
66
+ }];
67
+ }));
68
+ }
69
+ function createMetrics(saved = {}) {
70
+ return {
71
+ requests: count(saved.requests),
72
+ ready: count(saved.ready),
73
+ failed: count(saved.failed),
74
+ superseded: count(saved.superseded),
75
+ manualOverrides: count(saved.manualOverrides),
76
+ driftEvents: count(saved.driftEvents),
77
+ recoveriesAdopted: count(saved.recoveriesAdopted),
78
+ recoveriesSafeOff: count(saved.recoveriesSafeOff),
79
+ lastTransitionMs: nullableDuration(saved.lastTransitionMs),
80
+ maxTransitionMs: nullableDuration(saved.maxTransitionMs),
81
+ lastOutcome: typeof saved.lastOutcome === "string" ? saved.lastOutcome : null,
82
+ targets: targetMetrics(saved.targets)
83
+ };
84
+ }
85
+ function createTheatreState(saved = {}, activityProfiles = {}) {
86
+ const savedDesired = saved.desired && typeof saved.desired === "object" ? saved.desired : null;
87
+ const desired = savedDesired && Object.hasOwn(activityProfiles, savedDesired.activity)
88
+ ? { ...savedDesired }
89
+ : null;
90
+ return {
91
+ desired,
92
+ currentActivity: typeof saved.currentActivity === "string" &&
93
+ Object.hasOwn(activityProfiles, saved.currentActivity)
94
+ ? saved.currentActivity
95
+ : "unknown",
96
+ generation: Number.isInteger(saved.generation) && (saved.generation ?? -1) >= 0 ? saved.generation : 0,
97
+ lastProposedGeneration: Number.isInteger(saved.lastProposedGeneration)
98
+ ? saved.lastProposedGeneration
99
+ : savedDesired && !savedDesired.requestId.startsWith("recovery-") && Number.isInteger(savedDesired.generation)
100
+ ? savedDesired.generation
101
+ : 0,
102
+ phase: typeof saved.phase === "string" ? saved.phase : "idle",
103
+ targets: emptyTargets(saved.targets),
104
+ refreshPending: emptyRefreshPending(saved.refreshPending),
105
+ failure: saved.failure && typeof saved.failure === "object" ? { ...saved.failure } : null,
106
+ blockedGeneration: Number.isInteger(saved.blockedGeneration) ? saved.blockedGeneration : null,
107
+ degraded: Array.isArray(saved.degraded) ? saved.degraded.map((entry) => ({ ...entry })) : [],
108
+ availability: saved.availability && Object.hasOwn(AVAILABILITIES, saved.availability)
109
+ ? saved.availability
110
+ : "unknown",
111
+ transitionStartedAt: typeof saved.transitionStartedAt === "string"
112
+ ? saved.transitionStartedAt
113
+ : null,
114
+ transitionCompletedAt: typeof saved.transitionCompletedAt === "string"
115
+ ? saved.transitionCompletedAt
116
+ : null,
117
+ metrics: createMetrics(saved.metrics)
118
+ };
119
+ }
120
+ function theatreSnapshot(state, area) {
121
+ return {
122
+ kind: "state",
123
+ area,
124
+ requestId: state.desired?.requestId || null,
125
+ generation: state.generation,
126
+ desiredActivity: state.desired?.activity || null,
127
+ requestedAt: state.desired?.requestedAt || null,
128
+ currentActivity: state.currentActivity,
129
+ phase: state.phase,
130
+ availability: state.availability,
131
+ transitionStartedAt: state.transitionStartedAt,
132
+ transitionCompletedAt: state.transitionCompletedAt,
133
+ targets: emptyTargets(state.targets),
134
+ failure: state.failure ? { ...state.failure } : null,
135
+ degraded: state.degraded.map((entry) => ({ ...entry })),
136
+ metrics: createMetrics(state.metrics)
137
+ };
138
+ }
139
+ //# sourceMappingURL=theatre-state.js.map
@@ -1,3 +1,4 @@
1
+ import type { TraceEntry } from "./bounded-trace";
1
2
  export interface WallInputConfig {
2
3
  switchWindowMs: number;
3
4
  switchFreshnessMs: number;
@@ -37,12 +38,6 @@ export type WallInputEffect = {
37
38
  generation: number;
38
39
  switchAt: number;
39
40
  };
40
- export interface WallInputTrace {
41
- event: string;
42
- outcome: string;
43
- reason: string | null;
44
- details: Record<string, unknown>;
45
- }
46
41
  export interface WallInputStatus {
47
42
  phase: "awaiting-baseline" | "unavailable" | "stale" | "fresh";
48
43
  reason: "no-baseline" | "reported-unavailable" | "startup-unconfirmed" | "timestamp-unknown" | "expired" | null;
@@ -56,7 +51,7 @@ export declare function wallInputStatus(saved: Partial<WallInputState> | undefin
56
51
  export declare function transitionWallInput(saved: Partial<WallInputState> | undefined, input: WallInputInput, config: WallInputConfig, now?: number): {
57
52
  state: WallInputState;
58
53
  effects: WallInputEffect[];
59
- traces: WallInputTrace[];
54
+ traces: TraceEntry<Record<string, unknown>>[];
60
55
  gesture: "double" | "single" | null;
61
56
  status: WallInputStatus;
62
57
  };
@@ -0,0 +1,16 @@
1
+ import type { LightStyle } from "./light-styling";
2
+ export interface LightReport {
3
+ on: boolean;
4
+ brightness: unknown;
5
+ color_temp: unknown;
6
+ }
7
+ export declare function readLightReport(payload: Record<string, unknown>): LightReport | null;
8
+ export type LightCommand = {
9
+ state: string;
10
+ brightness?: number;
11
+ color_temp?: number;
12
+ transition?: number;
13
+ };
14
+ export declare function lightCommand(state: string, style: LightStyle, transitionSeconds: number): LightCommand;
15
+ export declare function setsLightValues(command: Record<string, unknown>): boolean;
16
+ export declare function alreadyStyled(style: LightStyle, report: LightReport | undefined): boolean;
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.readLightReport = readLightReport;
4
+ exports.lightCommand = lightCommand;
5
+ exports.setsLightValues = setsLightValues;
6
+ exports.alreadyStyled = alreadyStyled;
7
+ // A state report, or null when it carries no ON/OFF state.
8
+ function readLightReport(payload) {
9
+ const state = String(payload.state).toUpperCase();
10
+ if (state !== "ON" && state !== "OFF")
11
+ return null;
12
+ return { on: state === "ON", brightness: payload.brightness ?? null, color_temp: payload.color_temp ?? null };
13
+ }
14
+ // A command for a light: OFF on its own, otherwise the state with a style
15
+ // faded in over the transition.
16
+ function lightCommand(state, style, transitionSeconds) {
17
+ if (state === "OFF")
18
+ return { state };
19
+ return { state, ...style, transition: transitionSeconds };
20
+ }
21
+ // Command fields that set a light's values rather than just its power.
22
+ const VALUE_FIELDS = [
23
+ "brightness", "brightness_percent", "color", "color_temp", "color_temp_kelvin",
24
+ "effect", "hue", "saturation", "x", "y"
25
+ ];
26
+ function setsLightValues(command) {
27
+ return VALUE_FIELDS.some((field) => Object.hasOwn(command, field));
28
+ }
29
+ // Whether a light already shows a style, by its own latest report. A bulb
30
+ // that missed a command reports something else, so it is not "styled".
31
+ function alreadyStyled(style, report) {
32
+ return report?.on === true &&
33
+ Number(report.brightness) === style.brightness &&
34
+ Number(report.color_temp) === style.color_temp;
35
+ }
36
+ //# sourceMappingURL=z2m-light.js.map
@@ -4,9 +4,11 @@
4
4
  color: "#c7d9f1",
5
5
  defaults: {
6
6
  name: {value: ""},
7
- area: {value: "lounge", required: true},
8
- profiles: {value: "{}", required: true},
9
- owner: {value: "activity"},
7
+ area: {value: ""},
8
+ // User data with no sensible default: empty until the user fills it in,
9
+ // and marked invalid until then, as the runtime rejects it.
10
+ profiles: {value: "{}", required: true, validate: function (v) { try { var parsed = JSON.parse(v); return Boolean(parsed) && typeof parsed === "object" && !Array.isArray(parsed) && Object.keys(parsed).length > 0; } catch (e) { return false; } }},
11
+ owner: {value: "activity", required: true},
10
12
  confirmationTimeoutMs: {value: 15000, required: true, validate: RED.validators.number()},
11
13
  maxAttempts: {value: 2, required: true, validate: RED.validators.number()}
12
14
  },