@avantics/node-red-home-automation 6.1.0 → 6.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 (115) hide show
  1. package/README.md +260 -46
  2. package/dist/lib/activity-lighting-controller.d.ts +1 -0
  3. package/dist/lib/activity-lighting-controller.js +37 -10
  4. package/dist/lib/avr-controller.d.ts +3 -0
  5. package/dist/lib/avr-controller.js +24 -2
  6. package/dist/lib/backlighting-controller.d.ts +5 -2
  7. package/dist/lib/backlighting-controller.js +27 -2
  8. package/dist/lib/cover-publishing.js +20 -6
  9. package/dist/lib/display-mode-controller.d.ts +3 -0
  10. package/dist/lib/display-mode-controller.js +43 -16
  11. package/dist/lib/esphome-sensor.d.ts +73 -0
  12. package/dist/lib/esphome-sensor.js +261 -0
  13. package/dist/lib/home-assistant-setting.d.ts +23 -0
  14. package/dist/lib/home-assistant-setting.js +39 -0
  15. package/dist/lib/motion-policy.d.ts +1 -0
  16. package/dist/lib/motion-policy.js +21 -1
  17. package/dist/lib/occupancy-fusion.d.ts +1 -0
  18. package/dist/lib/occupancy-fusion.js +15 -2
  19. package/dist/lib/room-controller.d.ts +1 -0
  20. package/dist/lib/room-controller.js +5 -0
  21. package/dist/lib/room-publishing.d.ts +1 -0
  22. package/dist/lib/room-publishing.js +11 -0
  23. package/dist/lib/scene-publishing.d.ts +30 -0
  24. package/dist/lib/scene-publishing.js +63 -0
  25. package/dist/lib/scene.d.ts +69 -0
  26. package/dist/lib/scene.js +223 -0
  27. package/dist/lib/shelly-cover.js +5 -0
  28. package/dist/lib/shelly-relay-light.d.ts +24 -0
  29. package/dist/lib/shelly-relay-light.js +93 -0
  30. package/dist/lib/shelly-switch.d.ts +8 -0
  31. package/dist/lib/shelly-switch.js +37 -8
  32. package/dist/lib/source-capability-controller.d.ts +4 -1
  33. package/dist/lib/source-capability-controller.js +49 -2
  34. package/dist/lib/target-observation.d.ts +14 -0
  35. package/dist/lib/target-observation.js +22 -0
  36. package/dist/lib/theatre-activity-controller.d.ts +5 -0
  37. package/dist/lib/theatre-activity-controller.js +91 -12
  38. package/dist/lib/theatre-metrics.js +6 -4
  39. package/dist/lib/theatre-slo.js +3 -0
  40. package/dist/lib/theatre-state-contract.d.ts +4 -2
  41. package/dist/lib/theatre-state-contract.js +51 -8
  42. package/dist/lib/theatre-state.d.ts +2 -0
  43. package/dist/lib/theatre-state.js +13 -1
  44. package/dist/lib/wled.d.ts +48 -0
  45. package/dist/lib/wled.js +105 -0
  46. package/dist/lib/z2m-power.d.ts +38 -0
  47. package/dist/lib/z2m-power.js +83 -0
  48. package/dist/lib/z2m-sensor.d.ts +37 -0
  49. package/dist/lib/z2m-sensor.js +88 -0
  50. package/dist/nodes/apollo-r-pro-1.d.ts +2 -0
  51. package/dist/nodes/apollo-r-pro-1.html +80 -0
  52. package/dist/nodes/apollo-r-pro-1.js +4 -0
  53. package/dist/nodes/avr-controller.html +82 -21
  54. package/dist/nodes/avr-controller.js +24 -12
  55. package/dist/nodes/backlighting-controller.js +3 -2
  56. package/dist/nodes/circadian-policy.html +84 -20
  57. package/dist/nodes/circadian-policy.js +30 -11
  58. package/dist/nodes/cover-controller.html +87 -25
  59. package/dist/nodes/cover-controller.js +25 -12
  60. package/dist/nodes/device-side.d.ts +21 -0
  61. package/dist/nodes/device-side.js +76 -0
  62. package/dist/nodes/display-mode-controller.js +11 -2
  63. package/dist/nodes/esphome-sensor.d.ts +2 -0
  64. package/dist/nodes/esphome-sensor.js +77 -0
  65. package/dist/nodes/everything-presence-one.d.ts +2 -0
  66. package/dist/nodes/everything-presence-one.html +78 -0
  67. package/dist/nodes/everything-presence-one.js +4 -0
  68. package/dist/nodes/home-assistant-discovery.d.ts +26 -0
  69. package/dist/nodes/home-assistant-discovery.js +64 -0
  70. package/dist/nodes/house-schedule-mqtt.html +70 -5
  71. package/dist/nodes/house-schedule-mqtt.js +22 -8
  72. package/dist/nodes/motion-policy.html +87 -22
  73. package/dist/nodes/motion-policy.js +44 -11
  74. package/dist/nodes/mqtt-broker-link.d.ts +41 -0
  75. package/dist/nodes/mqtt-broker-link.js +91 -0
  76. package/dist/nodes/occupancy-fusion.html +86 -20
  77. package/dist/nodes/occupancy-fusion.js +25 -12
  78. package/dist/nodes/publishing-side.d.ts +20 -0
  79. package/dist/nodes/publishing-side.js +66 -0
  80. package/dist/nodes/room-controller.html +106 -35
  81. package/dist/nodes/room-controller.js +63 -16
  82. package/dist/nodes/scene.d.ts +3 -0
  83. package/dist/nodes/scene.html +247 -0
  84. package/dist/nodes/scene.js +128 -0
  85. package/dist/nodes/shelly-cover.html +47 -2
  86. package/dist/nodes/shelly-cover.js +19 -4
  87. package/dist/nodes/shelly-switch.html +76 -6
  88. package/dist/nodes/shelly-switch.js +32 -7
  89. package/dist/nodes/source-capability-controller.js +3 -2
  90. package/dist/nodes/theatre-activity-controller.html +4 -2
  91. package/dist/nodes/theatre-state-contract.html +72 -9
  92. package/dist/nodes/theatre-state-contract.js +33 -14
  93. package/dist/nodes/wled.d.ts +3 -0
  94. package/dist/nodes/wled.html +56 -0
  95. package/dist/nodes/wled.js +53 -0
  96. package/dist/nodes/z2m-cover.html +47 -2
  97. package/dist/nodes/z2m-cover.js +21 -4
  98. package/dist/nodes/z2m-light.html +49 -3
  99. package/dist/nodes/z2m-light.js +40 -4
  100. package/dist/nodes/z2m-power.d.ts +3 -0
  101. package/dist/nodes/z2m-power.html +58 -0
  102. package/dist/nodes/z2m-power.js +53 -0
  103. package/dist/nodes/z2m-sensor.d.ts +3 -0
  104. package/dist/nodes/z2m-sensor.html +69 -0
  105. package/dist/nodes/z2m-sensor.js +62 -0
  106. package/examples/Cover control.json +38 -91
  107. package/examples/Cover pair.json +36 -3
  108. package/examples/Home theatre activity.json +46 -91
  109. package/examples/Home theatre equipment.json +34 -2
  110. package/examples/House schedule.json +58 -80
  111. package/examples/Room lighting.json +45 -44
  112. package/examples/Scene.json +167 -0
  113. package/examples/Shelly cover.json +36 -105
  114. package/examples/Shelly switch.json +52 -148
  115. package/package.json +8 -2
@@ -79,9 +79,27 @@ function statusFor(state) {
79
79
  return { phase: state.phase, text: `${activity}: ${state.phase}` };
80
80
  }
81
81
  const RECOVERY_TARGETS = ["display", "avr", "source", "backlighting"];
82
- function recoveryMatches(profile, observations, nowMs, freshnessMs) {
82
+ // What tells activities apart, and can always be read: after a start with
83
+ // nothing saved, an activity is recovered only once both have answered.
84
+ const IDENTIFYING_TARGETS = ["display", "avr"];
85
+ // The recovery targets with a fresh observation.
86
+ function answered(observations, nowMs, freshnessMs) {
87
+ return RECOVERY_TARGETS.filter((target) => {
88
+ const observation = observations[target];
89
+ return Boolean(observation && isFresh(observation, nowMs, freshnessMs));
90
+ });
91
+ }
92
+ // Whether a profile is what the observations show: every recovery target,
93
+ // or after a start with nothing saved (partial), every one that answered,
94
+ // the display and the AVR among them.
95
+ function recoveryMatches(profile, observations, nowMs, freshnessMs, partial = false) {
96
+ const fresh = answered(observations, nowMs, freshnessMs);
97
+ if (partial && !IDENTIFYING_TARGETS.every((target) => fresh.includes(target)))
98
+ return false;
83
99
  return RECOVERY_TARGETS.every((target) => {
84
100
  const observation = observations[target];
101
+ if (partial && !fresh.includes(target))
102
+ return true;
85
103
  if (!observation || !isFresh(observation, nowMs, freshnessMs))
86
104
  return false;
87
105
  const expected = { ...profile[target] };
@@ -179,7 +197,7 @@ function transitionTheatre(saved, msg, suppliedConfig = {}, nowValue = new Date(
179
197
  continue;
180
198
  const targetState = state.targets[target];
181
199
  if (!targetState) {
182
- state.degraded.push({ target, reason: "unconfirmed" });
200
+ state.degraded.push({ target, reason: state.unobserved.includes(target) ? "unobserved" : "unconfirmed" });
183
201
  }
184
202
  else if (!isFresh(targetState, nowMs, config.freshnessMs)) {
185
203
  state.degraded.push({ target, reason: "stale" });
@@ -187,6 +205,10 @@ function transitionTheatre(saved, msg, suppliedConfig = {}, nowValue = new Date(
187
205
  else if (targetState.status !== "ready") {
188
206
  state.degraded.push({ target, reason: targetState.failure?.reason || targetState.status });
189
207
  }
208
+ else if (Array.isArray(targetState.details?.unobserved) && targetState.details.unobserved.length) {
209
+ // Ready without lights that never reported (activity lighting).
210
+ state.degraded.push({ target, reason: "unobserved" });
211
+ }
190
212
  }
191
213
  const manualTarget = theatre_profiles_1.TARGETS.find((target) => {
192
214
  const targetState = state.targets[target];
@@ -230,6 +252,11 @@ function transitionTheatre(saved, msg, suppliedConfig = {}, nowValue = new Date(
230
252
  };
231
253
  for (const target of theatre_profiles_1.REQUIRED_TARGETS) {
232
254
  const targetState = state.targets[target];
255
+ if (!targetState && holdReady && state.unobserved.includes(target)) {
256
+ // Recovered without it: the activity stays ready until it reports.
257
+ state.degraded.push({ target, reason: "unobserved" });
258
+ continue;
259
+ }
233
260
  if (targetState && holdReady && targetState.status === "ready" &&
234
261
  !isFresh(targetState, nowMs, config.freshnessMs)) {
235
262
  unverified(target);
@@ -254,7 +281,9 @@ function transitionTheatre(saved, msg, suppliedConfig = {}, nowValue = new Date(
254
281
  const source = state.targets.source;
255
282
  const staleButHeld = source && holdReady && source.status === "ready" &&
256
283
  !isFresh(source, nowMs, config.freshnessMs);
257
- if (staleButHeld)
284
+ if (!source && holdReady && state.unobserved.includes("source"))
285
+ state.degraded.push({ target: "source", reason: "unobserved" });
286
+ else if (staleButHeld)
258
287
  unverified("source");
259
288
  else if (!source || !isFresh(source, nowMs, config.freshnessMs) || source.status !== "ready") {
260
289
  state.phase = "waiting_for_source";
@@ -377,6 +406,7 @@ function transitionTheatre(saved, msg, suppliedConfig = {}, nowValue = new Date(
377
406
  state.phase = "preparing";
378
407
  state.currentActivity = "unknown";
379
408
  state.targets = (0, theatre_state_1.emptyTargets)();
409
+ state.unobserved = [];
380
410
  state.refreshPending = (0, theatre_state_1.emptyRefreshPending)();
381
411
  state.failure = null;
382
412
  state.blockedGeneration = null;
@@ -409,6 +439,9 @@ function transitionTheatre(saved, msg, suppliedConfig = {}, nowValue = new Date(
409
439
  return;
410
440
  }
411
441
  const previous = state.targets[event.target];
442
+ // A target the activity was recovered without has reported.
443
+ if (state.unobserved.includes(event.target))
444
+ state.unobserved = state.unobserved.filter((target) => target !== event.target);
412
445
  const bounded = (0, observation_time_1.boundObservedAt)(event.observedAt, observationTime(event), nowMs);
413
446
  if (bounded.skewed) {
414
447
  trace("target-state", "adjusted", "clock-skew", { target: event.target, reported: event.observedAt, usedAt: bounded.observedAt });
@@ -445,7 +478,33 @@ function transitionTheatre(saved, msg, suppliedConfig = {}, nowValue = new Date(
445
478
  }
446
479
  reconcile();
447
480
  }
448
- function acceptRecovery(event) {
481
+ function acceptTargetObservation(event) {
482
+ if (!theatre_profiles_1.TARGETS.includes(event.target))
483
+ throw new Error("unknown theatre target");
484
+ if (!event.values || typeof event.values !== "object" || Array.isArray(event.values)) {
485
+ throw new Error("target observation values must be an object");
486
+ }
487
+ const observedMs = observationTime(event);
488
+ if (observedMs === null)
489
+ throw new Error("target observedAt must be an ISO timestamp");
490
+ if (state.desired || state.phase !== "recovering") {
491
+ trace("target-observation", "ignored", "not-recovering", { target: event.target });
492
+ return;
493
+ }
494
+ const bounded = (0, observation_time_1.boundObservedAt)(event.observedAt, observedMs, nowMs);
495
+ state.recoveryObservations[event.target] = { observedAt: bounded.observedAt, values: { ...event.values } };
496
+ state.refreshPending[event.target] = null;
497
+ trace("target-observation", "accepted", null, { target: event.target, values: event.values });
498
+ // Every target recovery reads has answered: recover now, rather than
499
+ // waiting for lighting's probe, which nobody answers, to run out.
500
+ if (RECOVERY_TARGETS.every((target) => state.recoveryObservations[target])) {
501
+ acceptRecovery({ kind: "recover", reason: "startup", observations: state.recoveryObservations });
502
+ }
503
+ }
504
+ // asOfMs: when the observations are judged fresh, now unless given. The
505
+ // answers to one probe count together, as of the latest of them: the
506
+ // probes run out only after the freshness window.
507
+ function acceptRecovery(event, asOfMs = nowMs) {
449
508
  if (!event.observations || typeof event.observations !== "object" ||
450
509
  Array.isArray(event.observations)) {
451
510
  throw new Error("recovery observations must be an object");
@@ -458,8 +517,9 @@ function transitionTheatre(saved, msg, suppliedConfig = {}, nowValue = new Date(
458
517
  trace("recovery", "ignored", "manual-override-cleared");
459
518
  return;
460
519
  }
520
+ state.recoveryObservations = {};
461
521
  const matches = Object.entries(config.activityProfiles)
462
- .filter(([, profile]) => recoveryMatches(profile, event.observations, nowMs, config.freshnessMs))
522
+ .filter(([, profile]) => recoveryMatches(profile, event.observations, asOfMs, config.freshnessMs, event.reason === "startup"))
463
523
  .map(([activity]) => activity);
464
524
  if (matches.length === 1) {
465
525
  const activity = matches[0];
@@ -480,8 +540,15 @@ function transitionTheatre(saved, msg, suppliedConfig = {}, nowValue = new Date(
480
540
  state.transitionStartedAt = requestedAt;
481
541
  state.transitionCompletedAt = requestedAt;
482
542
  (0, theatre_metrics_1.resetTransitionMetrics)(state.metrics);
543
+ const fresh = answered(event.observations, asOfMs, config.freshnessMs);
544
+ state.unobserved = RECOVERY_TARGETS.filter((target) => !fresh.includes(target));
483
545
  for (const target of theatre_profiles_1.TARGETS) {
484
546
  const observation = event.observations[target];
547
+ if (state.unobserved.includes(target)) {
548
+ // Not answered: unconfirmed until it reports.
549
+ state.targets[target] = null;
550
+ continue;
551
+ }
485
552
  state.targets[target] = {
486
553
  status: "ready",
487
554
  observedAt: observation?.observedAt || requestedAt,
@@ -496,12 +563,13 @@ function transitionTheatre(saved, msg, suppliedConfig = {}, nowValue = new Date(
496
563
  }
497
564
  state.phase = "ready";
498
565
  state.currentActivity = activity;
499
- state.availability = "available";
566
+ state.degraded = state.unobserved.map((target) => ({ target, reason: "unobserved" }));
567
+ state.availability = state.unobserved.length ? "degraded" : "available";
500
568
  state.metrics.recoveriesAdopted += 1;
501
569
  completeTransition("ready");
502
570
  state.metrics.lastOutcome = "recovery_adopted";
503
- emit("recovery_adopted", { reason: event.reason, matchedActivity: activity });
504
- trace("recovery", "adopted", null, { reason: event.reason, activity });
571
+ emit("recovery_adopted", { reason: event.reason, matchedActivity: activity, unobserved: state.unobserved });
572
+ trace("recovery", "adopted", null, { reason: event.reason, activity, unobserved: state.unobserved });
505
573
  return;
506
574
  }
507
575
  if (event.reason === "startup") {
@@ -545,8 +613,12 @@ function transitionTheatre(saved, msg, suppliedConfig = {}, nowValue = new Date(
545
613
  else if (event.kind === "recover") {
546
614
  acceptRecovery(event);
547
615
  }
616
+ else if (event.kind === "target_observation") {
617
+ acceptTargetObservation(event);
618
+ }
548
619
  else if (event.kind === "startup" || event.kind === "refresh") {
549
620
  state.targets = (0, theatre_state_1.emptyTargets)();
621
+ state.unobserved = [];
550
622
  state.refreshPending = (0, theatre_state_1.emptyRefreshPending)();
551
623
  if (state.desired) {
552
624
  commands.push(...targetRefreshCommands(state.desired, config));
@@ -560,12 +632,17 @@ function transitionTheatre(saved, msg, suppliedConfig = {}, nowValue = new Date(
560
632
  if (state.blockedGeneration !== state.generation) {
561
633
  state.transitionStartedAt = now.toISOString();
562
634
  state.transitionCompletedAt = null;
635
+ // Re-confirming is a transition of its own: each target's
636
+ // confirmation is timed again from now.
637
+ for (const target of theatre_profiles_1.TARGETS)
638
+ state.metrics.targets[target].lastConfirmationMs = null;
563
639
  }
564
640
  }
565
641
  else {
566
642
  commands.push(...targetProbeCommands());
567
643
  for (const target of theatre_profiles_1.TARGETS)
568
644
  state.refreshPending[target] = { sentAt: nowMs, attempts: 1, exhausted: false };
645
+ state.recoveryObservations = {};
569
646
  state.phase = "recovering";
570
647
  state.availability = "unknown";
571
648
  emit("recovery_required", { reason: "startup" });
@@ -579,10 +656,12 @@ function transitionTheatre(saved, msg, suppliedConfig = {}, nowValue = new Date(
579
656
  else {
580
657
  tickRefreshes();
581
658
  if (!state.desired && state.phase === "recovering" &&
582
- theatre_profiles_1.TARGETS.every((target) => state.refreshPending[target]?.exhausted === true)) {
583
- // Nobody supplied recovery observations: fall back as for no evidence.
584
- trace("recovery", "timed-out", "no-observations");
585
- acceptRecovery({ kind: "recover", reason: "startup", observations: {} });
659
+ theatre_profiles_1.TARGETS.every((target) => state.refreshPending[target] === null || state.refreshPending[target]?.exhausted === true)) {
660
+ // The probes ran out: recover from what answered, the display and the
661
+ // AVR among them; a target that didn't is unobserved.
662
+ trace("recovery", "timed-out", Object.keys(state.recoveryObservations).length ? "partial-observations" : "no-observations", { answered: Object.keys(state.recoveryObservations) });
663
+ const latest = Math.max(...Object.values(state.recoveryObservations).map((entry) => Date.parse(entry.observedAt)));
664
+ acceptRecovery({ kind: "recover", reason: "startup", observations: state.recoveryObservations }, Number.isFinite(latest) ? Math.min(latest, nowMs) : nowMs);
586
665
  }
587
666
  else {
588
667
  reconcile();
@@ -32,7 +32,8 @@ function resetTransitionMetrics(metrics) {
32
32
  }
33
33
  }
34
34
  // A target's report: its attempts, fallback use, how old its observation is
35
- // and, once ready, how long after the transition started it confirmed.
35
+ // and, at its first ready report in this transition, how long after the
36
+ // transition started it confirmed. Its refreshes leave that figure.
36
37
  function recordTargetReport(metric, report, previous, observedAt, transitionStartedAt, nowMs) {
37
38
  const details = report.details && typeof report.details === "object" ? report.details : {};
38
39
  const detailMetrics = details.metrics && typeof details.metrics === "object" &&
@@ -48,10 +49,11 @@ function recordTargetReport(metric, report, previous, observedAt, transitionStar
48
49
  metric.fallbackUsed ||= fallbackUsed;
49
50
  metric.observationAgeMs = observedAt === null ? null : Math.max(0, nowMs - observedAt);
50
51
  if (report.status === "ready") {
52
+ // Null until then: resetTransitionMetrics clears it at each transition.
51
53
  const startedAt = Date.parse(transitionStartedAt || "");
52
- metric.lastConfirmationMs = Number.isFinite(startedAt) && observedAt !== null
53
- ? Math.max(0, observedAt - startedAt)
54
- : null;
54
+ if (metric.lastConfirmationMs === null && Number.isFinite(startedAt) && observedAt !== null) {
55
+ metric.lastConfirmationMs = Math.max(0, observedAt - startedAt);
56
+ }
55
57
  metric.availability = "available";
56
58
  }
57
59
  else if (report.status === "failed" || report.status === "unavailable") {
@@ -16,6 +16,9 @@ function normaliseTheatreSloConfig(config = {}) {
16
16
  };
17
17
  }
18
18
  function duration(value) {
19
+ // Not timed: null, as given. Number(null) would make it 0 ms.
20
+ if (value === null || value === undefined || value === "")
21
+ return null;
19
22
  const parsed = Number(value);
20
23
  return Number.isFinite(parsed) && parsed >= 0 ? parsed : null;
21
24
  }
@@ -3,7 +3,9 @@ import { type TheatreRequestState, type TheatreStateSnapshot } from "./theatre-r
3
3
  import type { TraceEntry } from "./bounded-trace";
4
4
  import { type IdScheme } from "./ha-discovery";
5
5
  export type { ContractRequest, TheatreStateSnapshot } from "./theatre-requests";
6
- export type TheatreStateContractState = TheatreRequestState;
6
+ export type TheatreStateContractState = TheatreRequestState & {
7
+ published: Record<string, string>;
8
+ };
7
9
  export interface TheatreStateContractConfig {
8
10
  nodeId?: string;
9
11
  idScheme?: IdScheme;
@@ -43,7 +45,7 @@ export declare function theatreRetainedTopics(config: TheatreStateContractConfig
43
45
  export declare function theatreStartingPublications(config: TheatreStateContractConfig): ContractPublication[];
44
46
  export declare function theatreStoppingPublications(config: TheatreStateContractConfig): ContractPublication[];
45
47
  export declare function transitionTheatreStateContract(saved: Partial<TheatreStateContractState> | undefined, msg: TheatreStateContractMessage, suppliedConfig: Partial<TheatreStateContractConfig>, nowValue?: Date | string | number): {
46
- state: TheatreRequestState;
48
+ state: TheatreStateContractState;
47
49
  requests: ContractRequestOutput[];
48
50
  publications: ContractPublication[];
49
51
  traces: TraceEntry<Record<string, unknown>>[];
@@ -134,6 +134,37 @@ const STATE_TOPICS = [
134
134
  function statePublications(event, config, slo) {
135
135
  return STATE_TOPICS.map(([name, value]) => publication((0, theatre_ha_discovery_1.theatreTopic)(config.baseTopic, name), value(event, slo)));
136
136
  }
137
+ // Fields that only say when, or how long ago, something was seen: they move
138
+ // on every refresh of a steady target, so a payload that differs only in
139
+ // them is not a change. A target's health keeps the time it last changed.
140
+ // (A target's lastConfirmationMs is set once per transition, so it counts.)
141
+ const TIME_ONLY_FIELDS = new Set(["observedAt", "evaluatedAt", "observationAgeMs"]);
142
+ function comparable(payload) {
143
+ let value;
144
+ try {
145
+ value = JSON.parse(payload);
146
+ }
147
+ catch {
148
+ return payload;
149
+ }
150
+ const strip = (entry) => Array.isArray(entry)
151
+ ? entry.map(strip)
152
+ : entry && typeof entry === "object"
153
+ ? Object.fromEntries(Object.entries(entry).filter(([key]) => !TIME_ONLY_FIELDS.has(key)).map(([key, inner]) => [key, strip(inner)]))
154
+ : entry;
155
+ return JSON.stringify(strip(value));
156
+ }
157
+ // Only the publications whose payload changed, beyond its time-only
158
+ // fields, since the contract last published that topic; it records them.
159
+ function changed(state, publications) {
160
+ return publications.filter(({ topic, payload }) => {
161
+ const key = comparable(payload);
162
+ if (state.published[topic] === key)
163
+ return false;
164
+ state.published[topic] = key;
165
+ return true;
166
+ });
167
+ }
137
168
  function requestPublications(request, config) {
138
169
  const base = config.baseTopic;
139
170
  return [
@@ -174,7 +205,10 @@ function theatreStoppingPublications(config) {
174
205
  }
175
206
  function transitionTheatreStateContract(saved, msg, suppliedConfig, nowValue = new Date()) {
176
207
  const config = normaliseStateContractConfig(suppliedConfig);
177
- const state = (0, theatre_requests_1.createTheatreRequestState)(saved);
208
+ const state = {
209
+ ...(0, theatre_requests_1.createTheatreRequestState)(saved),
210
+ published: saved?.published && typeof saved.published === "object" && !Array.isArray(saved.published) ? { ...saved.published } : {}
211
+ };
178
212
  const now = nowValue instanceof Date ? nowValue : new Date(nowValue);
179
213
  if (!Number.isFinite(now.getTime()))
180
214
  throw new Error("now must be a valid date");
@@ -190,6 +224,9 @@ function transitionTheatreStateContract(saved, msg, suppliedConfig, nowValue = n
190
224
  const entries = config.discovery !== false || config.area ? (0, theatre_ha_discovery_1.theatreDiscovery)(config) : [];
191
225
  publications.push(...entries.map(({ topic, payload }) => publication(topic, config.discovery !== false ? payload : "")));
192
226
  publications.push(publication((0, theatre_ha_discovery_1.theatreTopic)(config.baseTopic, "availability"), ha_discovery_1.ONLINE));
227
+ // Each startup, and with a broker each connect: the next snapshot
228
+ // publishes every state topic again, in case the broker lost them.
229
+ state.published = {};
193
230
  trace("startup", "discovery", null, { publications: publications.length });
194
231
  }
195
232
  else if (msg.topic === (0, theatre_ha_discovery_1.theatreTopic)(config.baseTopic, "request")) {
@@ -207,7 +244,7 @@ function transitionTheatreStateContract(saved, msg, suppliedConfig, nowValue = n
207
244
  else {
208
245
  trace("request", "accepted", null, { requestId: request.requestId, generation: state.generation, activity: request.activity });
209
246
  }
210
- publications.push(...requestPublications(request, config));
247
+ publications.push(...changed(state, requestPublications(request, config)));
211
248
  }
212
249
  }
213
250
  else if (msg.theatre && typeof msg.theatre === "object" && msg.theatre.kind === "state") {
@@ -217,12 +254,18 @@ function transitionTheatreStateContract(saved, msg, suppliedConfig, nowValue = n
217
254
  trace("state", "ignored", "stale-generation", { generation: event.generation });
218
255
  }
219
256
  else {
220
- publications.push(...statePublications(event, config, assessment));
221
- trace("state", "published", null, {
222
- generation: event.generation,
223
- phase: event.phase,
224
- publications: publications.length
225
- });
257
+ const all = statePublications(event, config, assessment);
258
+ publications.push(...changed(state, all));
259
+ if (!publications.length) {
260
+ trace("state", "unchanged", null, { generation: event.generation, phase: event.phase });
261
+ }
262
+ else {
263
+ trace("state", "published", null, {
264
+ generation: event.generation,
265
+ phase: event.phase,
266
+ publications: publications.length
267
+ });
268
+ }
226
269
  }
227
270
  }
228
271
  else {
@@ -81,6 +81,8 @@ export interface TheatreState {
81
81
  transitionStartedAt: string | null;
82
82
  transitionCompletedAt: string | null;
83
83
  metrics: TheatreMetrics;
84
+ recoveryObservations: RecoveryObservations;
85
+ unobserved: TheatreTarget[];
84
86
  }
85
87
  export declare function emptyTargets(saved?: Partial<Record<TheatreTarget, TargetState | null>>): Record<TheatreTarget, TargetState | null>;
86
88
  export declare const REFRESH_ATTEMPTS = 3;
@@ -43,6 +43,9 @@ function count(value) {
43
43
  return Number.isInteger(parsed) && parsed >= 0 ? parsed : 0;
44
44
  }
45
45
  function nullableDuration(value) {
46
+ // Not a duration yet: null, as saved. Number(null) would make it 0.
47
+ if (value === null || value === undefined || value === "")
48
+ return null;
46
49
  const parsed = Number(value);
47
50
  return Number.isFinite(parsed) && parsed >= 0 ? parsed : null;
48
51
  }
@@ -114,7 +117,16 @@ function createTheatreState(saved = {}, activityProfiles = {}) {
114
117
  transitionCompletedAt: typeof saved.transitionCompletedAt === "string"
115
118
  ? saved.transitionCompletedAt
116
119
  : null,
117
- metrics: createMetrics(saved.metrics)
120
+ metrics: createMetrics(saved.metrics),
121
+ recoveryObservations: saved.recoveryObservations && typeof saved.recoveryObservations === "object" &&
122
+ !Array.isArray(saved.recoveryObservations)
123
+ ? Object.fromEntries(Object.entries(saved.recoveryObservations)
124
+ .filter(([target, entry]) => theatre_profiles_1.TARGETS.includes(target) && entry && typeof entry === "object")
125
+ .map(([target, entry]) => [target, { ...entry }]))
126
+ : {},
127
+ unobserved: Array.isArray(saved.unobserved)
128
+ ? saved.unobserved.filter((target) => theatre_profiles_1.TARGETS.includes(target))
129
+ : []
118
130
  };
119
131
  }
120
132
  function theatreSnapshot(state, area) {
@@ -0,0 +1,48 @@
1
+ import type { TraceEntry } from "./bounded-trace";
2
+ import { type MqttPublication } from "./mqtt-message";
3
+ export interface WledConfig {
4
+ deviceTopic: string;
5
+ }
6
+ export type WledPower = "on" | "off";
7
+ export interface WledState {
8
+ power: WledPower | null;
9
+ observedAt: string | null;
10
+ online: boolean | null;
11
+ generation: number | null;
12
+ }
13
+ export interface WledMessage {
14
+ topic?: unknown;
15
+ payload?: unknown;
16
+ backlightingCommand?: {
17
+ operation?: unknown;
18
+ generation?: unknown;
19
+ power?: unknown;
20
+ };
21
+ }
22
+ export type WledReading = {
23
+ kind: "observed";
24
+ generation: number;
25
+ power: WledPower;
26
+ observedAt: string;
27
+ } | {
28
+ kind: "command_result";
29
+ generation: number;
30
+ ok: boolean;
31
+ reason?: string;
32
+ };
33
+ export declare function normaliseWledConfig(config: {
34
+ deviceTopic?: unknown;
35
+ }): WledConfig;
36
+ export declare function wledTopics(config: WledConfig): {
37
+ device: string;
38
+ brightness: string;
39
+ status: string;
40
+ };
41
+ export declare function transitionWled(saved: Partial<WledState> | undefined, msg: WledMessage, config: WledConfig, now: Date): {
42
+ state: WledState;
43
+ publications: MqttPublication[];
44
+ readings: {
45
+ backlighting: WledReading;
46
+ }[];
47
+ traces: TraceEntry<Record<string, unknown>>[];
48
+ };
@@ -0,0 +1,105 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.normaliseWledConfig = normaliseWledConfig;
4
+ exports.wledTopics = wledTopics;
5
+ exports.transitionWled = transitionWled;
6
+ const mqtt_message_1 = require("./mqtt-message");
7
+ function normaliseWledConfig(config) {
8
+ const deviceTopic = String(config.deviceTopic ?? "").trim().replace(/^\/+|\/+$/g, "");
9
+ // The user's own device's: no default.
10
+ if (!deviceTopic)
11
+ throw new Error("WLED's device topic is required");
12
+ if (/[+#]/.test(deviceTopic))
13
+ throw new Error("the device topic can't contain + or #");
14
+ return { deviceTopic };
15
+ }
16
+ function wledTopics(config) {
17
+ const device = config.deviceTopic;
18
+ return { device, brightness: `${device}/g`, status: `${device}/status` };
19
+ }
20
+ function text(payload) {
21
+ if (Buffer.isBuffer(payload))
22
+ return payload.toString("utf8").trim();
23
+ return String(payload ?? "").trim();
24
+ }
25
+ function transitionWled(saved, msg, config, now) {
26
+ const state = {
27
+ power: saved?.power === "on" || saved?.power === "off" ? saved.power : null,
28
+ observedAt: typeof saved?.observedAt === "string" ? saved.observedAt : null,
29
+ online: typeof saved?.online === "boolean" ? saved.online : null,
30
+ generation: Number.isInteger(saved?.generation) ? saved.generation : null
31
+ };
32
+ const topics = wledTopics(config);
33
+ const publications = [];
34
+ const readings = [];
35
+ const traces = [];
36
+ const trace = (event, outcome, reason = null, details = {}) => {
37
+ traces.push({ event, outcome, reason, details });
38
+ };
39
+ // What it knows, as a reading for the command in hand.
40
+ const reading = () => {
41
+ if (state.generation === null || state.power === null)
42
+ return;
43
+ readings.push({ backlighting: { kind: "observed", generation: state.generation, power: state.power, observedAt: now.toISOString() } });
44
+ };
45
+ const command = msg.backlightingCommand;
46
+ if ((0, mqtt_message_1.isObject)(command)) {
47
+ const operation = String(command.operation);
48
+ const generation = Number(command.generation);
49
+ if (!Number.isInteger(generation) || generation < 0)
50
+ throw new Error("a backlighting command needs its generation");
51
+ state.generation = generation;
52
+ if (operation === "set_power") {
53
+ if (command.power !== "on" && command.power !== "off")
54
+ throw new Error("set_power needs power on or off");
55
+ if (state.online === false) {
56
+ // It would be lost: WLED isn't connected to the broker.
57
+ readings.push({ backlighting: { kind: "command_result", generation, ok: false, reason: "unavailable" } });
58
+ trace("command", "refused", "offline", { power: command.power });
59
+ }
60
+ else {
61
+ publications.push({ topic: topics.device, payload: command.power === "on" ? "ON" : "OFF" });
62
+ readings.push({ backlighting: { kind: "command_result", generation, ok: true } });
63
+ trace("command", "sent", null, { power: command.power });
64
+ }
65
+ }
66
+ else if (operation === "observe") {
67
+ // WLED publishes every change while it is connected, so the last
68
+ // report is what it shows now; with none since the node started, or
69
+ // with WLED offline, there is nothing to say yet.
70
+ if (state.online !== false && state.power !== null) {
71
+ reading();
72
+ trace("command", "observed", null, { power: state.power });
73
+ }
74
+ else {
75
+ trace("command", "unanswered", state.online === false ? "offline" : "no-report");
76
+ }
77
+ }
78
+ else {
79
+ trace("command", "ignored", "unknown-operation", { operation });
80
+ }
81
+ }
82
+ else if (msg.topic === topics.brightness) {
83
+ const brightness = Number(text(msg.payload));
84
+ if (!Number.isFinite(brightness) || brightness < 0)
85
+ throw new Error(`${topics.brightness} must carry a brightness 0-255`);
86
+ // Off is brightness 0.
87
+ state.power = brightness > 0 ? "on" : "off";
88
+ state.observedAt = now.toISOString();
89
+ state.online = true;
90
+ reading();
91
+ trace("report", "read", null, { brightness, power: state.power });
92
+ }
93
+ else if (msg.topic === topics.status) {
94
+ const status = text(msg.payload).toLowerCase();
95
+ if (status !== "online" && status !== "offline")
96
+ throw new Error(`${topics.status} must be online or offline`);
97
+ state.online = status === "online";
98
+ trace("availability", status);
99
+ }
100
+ else {
101
+ trace("message", "ignored", "other-topic", { topic: typeof msg.topic === "string" ? msg.topic : null });
102
+ }
103
+ return { state, publications, readings, traces };
104
+ }
105
+ //# sourceMappingURL=wled.js.map
@@ -0,0 +1,38 @@
1
+ import type { TraceEntry } from "./bounded-trace";
2
+ import { type MqttPublication } from "./mqtt-message";
3
+ export interface Z2mPowerConfig {
4
+ baseTopic: string;
5
+ friendlyName: string;
6
+ }
7
+ export interface Z2mPowerState {
8
+ watts: number | null;
9
+ online: boolean | null;
10
+ }
11
+ export interface Z2mPowerMessage {
12
+ topic?: unknown;
13
+ payload?: unknown;
14
+ retain?: unknown;
15
+ power?: unknown;
16
+ }
17
+ export interface PowerReading {
18
+ kind: "observed";
19
+ watts: number;
20
+ observedAt: string;
21
+ }
22
+ export declare function normaliseZ2mPowerConfig(config: {
23
+ baseTopic?: unknown;
24
+ friendlyName?: unknown;
25
+ }): Z2mPowerConfig;
26
+ export declare function z2mPowerTopics(config: Z2mPowerConfig): {
27
+ device: string;
28
+ get: string;
29
+ availability: string;
30
+ };
31
+ export declare function transitionZ2mPower(saved: Partial<Z2mPowerState> | undefined, msg: Z2mPowerMessage, config: Z2mPowerConfig, now: Date): {
32
+ state: Z2mPowerState;
33
+ publications: MqttPublication[];
34
+ readings: {
35
+ power: PowerReading;
36
+ }[];
37
+ traces: TraceEntry<Record<string, unknown>>[];
38
+ };