@avantics/node-red-home-automation 6.2.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 (64) hide show
  1. package/README.md +60 -8
  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/display-mode-controller.d.ts +3 -0
  9. package/dist/lib/display-mode-controller.js +43 -16
  10. package/dist/lib/esphome-sensor.d.ts +73 -0
  11. package/dist/lib/esphome-sensor.js +261 -0
  12. package/dist/lib/occupancy-fusion.d.ts +1 -0
  13. package/dist/lib/occupancy-fusion.js +15 -2
  14. package/dist/lib/scene.d.ts +9 -1
  15. package/dist/lib/scene.js +61 -8
  16. package/dist/lib/source-capability-controller.d.ts +4 -1
  17. package/dist/lib/source-capability-controller.js +49 -2
  18. package/dist/lib/target-observation.d.ts +14 -0
  19. package/dist/lib/target-observation.js +22 -0
  20. package/dist/lib/theatre-activity-controller.d.ts +5 -0
  21. package/dist/lib/theatre-activity-controller.js +87 -12
  22. package/dist/lib/theatre-state.d.ts +2 -0
  23. package/dist/lib/theatre-state.js +10 -1
  24. package/dist/lib/wled.d.ts +48 -0
  25. package/dist/lib/wled.js +105 -0
  26. package/dist/lib/z2m-power.d.ts +38 -0
  27. package/dist/lib/z2m-power.js +83 -0
  28. package/dist/lib/z2m-sensor.d.ts +37 -0
  29. package/dist/lib/z2m-sensor.js +88 -0
  30. package/dist/nodes/apollo-r-pro-1.d.ts +2 -0
  31. package/dist/nodes/apollo-r-pro-1.html +80 -0
  32. package/dist/nodes/apollo-r-pro-1.js +4 -0
  33. package/dist/nodes/avr-controller.js +1 -1
  34. package/dist/nodes/backlighting-controller.js +3 -2
  35. package/dist/nodes/device-side.d.ts +1 -0
  36. package/dist/nodes/device-side.js +7 -3
  37. package/dist/nodes/display-mode-controller.js +11 -2
  38. package/dist/nodes/esphome-sensor.d.ts +2 -0
  39. package/dist/nodes/esphome-sensor.js +77 -0
  40. package/dist/nodes/everything-presence-one.d.ts +2 -0
  41. package/dist/nodes/everything-presence-one.html +78 -0
  42. package/dist/nodes/everything-presence-one.js +4 -0
  43. package/dist/nodes/occupancy-fusion.html +3 -0
  44. package/dist/nodes/occupancy-fusion.js +2 -1
  45. package/dist/nodes/scene.html +24 -3
  46. package/dist/nodes/scene.js +9 -2
  47. package/dist/nodes/shelly-cover.html +1 -0
  48. package/dist/nodes/shelly-switch.html +1 -0
  49. package/dist/nodes/source-capability-controller.js +3 -2
  50. package/dist/nodes/theatre-activity-controller.html +4 -2
  51. package/dist/nodes/wled.d.ts +3 -0
  52. package/dist/nodes/wled.html +56 -0
  53. package/dist/nodes/wled.js +53 -0
  54. package/dist/nodes/z2m-cover.html +1 -0
  55. package/dist/nodes/z2m-light.html +3 -1
  56. package/dist/nodes/z2m-light.js +17 -0
  57. package/dist/nodes/z2m-power.d.ts +3 -0
  58. package/dist/nodes/z2m-power.html +58 -0
  59. package/dist/nodes/z2m-power.js +53 -0
  60. package/dist/nodes/z2m-sensor.d.ts +3 -0
  61. package/dist/nodes/z2m-sensor.html +69 -0
  62. package/dist/nodes/z2m-sensor.js +62 -0
  63. package/examples/Scene.json +8 -56
  64. package/package.json +7 -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));
@@ -570,6 +642,7 @@ function transitionTheatre(saved, msg, suppliedConfig = {}, nowValue = new Date(
570
642
  commands.push(...targetProbeCommands());
571
643
  for (const target of theatre_profiles_1.TARGETS)
572
644
  state.refreshPending[target] = { sentAt: nowMs, attempts: 1, exhausted: false };
645
+ state.recoveryObservations = {};
573
646
  state.phase = "recovering";
574
647
  state.availability = "unknown";
575
648
  emit("recovery_required", { reason: "startup" });
@@ -583,10 +656,12 @@ function transitionTheatre(saved, msg, suppliedConfig = {}, nowValue = new Date(
583
656
  else {
584
657
  tickRefreshes();
585
658
  if (!state.desired && state.phase === "recovering" &&
586
- theatre_profiles_1.TARGETS.every((target) => state.refreshPending[target]?.exhausted === true)) {
587
- // Nobody supplied recovery observations: fall back as for no evidence.
588
- trace("recovery", "timed-out", "no-observations");
589
- 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);
590
665
  }
591
666
  else {
592
667
  reconcile();
@@ -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;
@@ -117,7 +117,16 @@ function createTheatreState(saved = {}, activityProfiles = {}) {
117
117
  transitionCompletedAt: typeof saved.transitionCompletedAt === "string"
118
118
  ? saved.transitionCompletedAt
119
119
  : null,
120
- 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
+ : []
121
130
  };
122
131
  }
123
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
+ };
@@ -0,0 +1,83 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.normaliseZ2mPowerConfig = normaliseZ2mPowerConfig;
4
+ exports.z2mPowerTopics = z2mPowerTopics;
5
+ exports.transitionZ2mPower = transitionZ2mPower;
6
+ const mqtt_message_1 = require("./mqtt-message");
7
+ function normaliseZ2mPowerConfig(config) {
8
+ const baseTopic = String(config.baseTopic ?? "").trim().replace(/^\/+|\/+$/g, "") || "zigbee2mqtt";
9
+ // The user's own device's: no default.
10
+ const friendlyName = String(config.friendlyName ?? "").trim().replace(/^\/+|\/+$/g, "");
11
+ if (!friendlyName)
12
+ throw new Error("the device's friendly name is required");
13
+ if (/[+#]/.test(baseTopic) || /[+#]/.test(friendlyName))
14
+ throw new Error("the base topic and friendly name can't contain + or #");
15
+ return { baseTopic, friendlyName };
16
+ }
17
+ function z2mPowerTopics(config) {
18
+ const device = `${config.baseTopic}/${config.friendlyName}`;
19
+ return { device, get: `${device}/get`, availability: `${device}/availability` };
20
+ }
21
+ function transitionZ2mPower(saved, msg, config, now) {
22
+ const state = {
23
+ watts: typeof saved?.watts === "number" ? saved.watts : null,
24
+ online: typeof saved?.online === "boolean" ? saved.online : null
25
+ };
26
+ const topics = z2mPowerTopics(config);
27
+ const publications = [];
28
+ const readings = [];
29
+ const traces = [];
30
+ const trace = (event, outcome, reason = null, details = {}) => {
31
+ traces.push({ event, outcome, reason, details });
32
+ };
33
+ if ((0, mqtt_message_1.isObject)(msg.power)) {
34
+ if (msg.power.kind === "read") {
35
+ // A fresh reading, where the device answers /get; otherwise its next
36
+ // report.
37
+ publications.push({ topic: topics.get, payload: JSON.stringify({ power: "" }) });
38
+ trace("read", "sent");
39
+ }
40
+ else {
41
+ trace("message", "ignored", "not-a-read-request", { kind: String(msg.power.kind) });
42
+ }
43
+ }
44
+ else if (msg.topic === topics.device) {
45
+ const report = (0, mqtt_message_1.parsedPayload)(msg.payload);
46
+ if (!(0, mqtt_message_1.isObject)(report))
47
+ throw new Error(`${topics.device} must carry the device's state object`);
48
+ const watts = report.power;
49
+ state.online = true;
50
+ if (msg.retain === true) {
51
+ // A retained report is an old one (with retain set for the plug in
52
+ // Zigbee2MQTT): never passed on; the read on connect brings a fresh
53
+ // one.
54
+ if (watts !== undefined)
55
+ trace("power", "ignored", "retained", { value: watts });
56
+ }
57
+ else if (typeof watts !== "number" || !Number.isFinite(watts) || watts < 0) {
58
+ // A fixed contract: only watts pass. A report without power (or
59
+ // nothing new) sends nothing.
60
+ if (watts !== undefined)
61
+ trace("power", "ignored", "not-watts", { value: watts });
62
+ }
63
+ else if (watts !== state.watts) {
64
+ state.watts = watts;
65
+ readings.push({ power: { kind: "observed", watts, observedAt: now.toISOString() } });
66
+ trace("power", "changed", null, { watts });
67
+ }
68
+ }
69
+ else if (msg.topic === topics.availability) {
70
+ // {"state": "online"}, or the plain "online" of older setups.
71
+ const received = (0, mqtt_message_1.parsedPayload)(msg.payload);
72
+ const value = (0, mqtt_message_1.isObject)(received) ? received.state : received;
73
+ if (value !== "online" && value !== "offline")
74
+ throw new Error(`${topics.availability} must say online or offline`);
75
+ state.online = value === "online";
76
+ trace("availability", value);
77
+ }
78
+ else {
79
+ trace("message", "ignored", "other-topic", { topic: typeof msg.topic === "string" ? msg.topic : null });
80
+ }
81
+ return { state, publications, readings, traces };
82
+ }
83
+ //# sourceMappingURL=z2m-power.js.map
@@ -0,0 +1,37 @@
1
+ import type { TraceEntry } from "./bounded-trace";
2
+ export type OccupancyKind = "motion" | "presence";
3
+ export interface Z2mSensorConfig {
4
+ baseTopic: string;
5
+ friendlyName: string;
6
+ occupancyIs: OccupancyKind;
7
+ }
8
+ export interface Z2mSensorState {
9
+ motion: boolean | null;
10
+ presence: boolean | null;
11
+ illuminance: number | null;
12
+ online: boolean | null;
13
+ }
14
+ export interface Z2mSensorMessage {
15
+ topic?: unknown;
16
+ payload?: unknown;
17
+ retain?: unknown;
18
+ }
19
+ export interface SensorReading {
20
+ source: "motion" | "presence" | "illuminance";
21
+ payload: boolean | number;
22
+ }
23
+ export declare function normaliseZ2mSensorConfig(config: {
24
+ baseTopic?: unknown;
25
+ friendlyName?: unknown;
26
+ occupancyIs?: unknown;
27
+ }): Z2mSensorConfig;
28
+ export declare function z2mSensorTopics(config: Z2mSensorConfig): {
29
+ device: string;
30
+ availability: string;
31
+ };
32
+ export declare function transitionZ2mSensor(saved: Partial<Z2mSensorState> | undefined, msg: Z2mSensorMessage, config: Z2mSensorConfig): {
33
+ state: Z2mSensorState;
34
+ occupancy: SensorReading[];
35
+ light: SensorReading[];
36
+ traces: TraceEntry<Record<string, unknown>>[];
37
+ };
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.normaliseZ2mSensorConfig = normaliseZ2mSensorConfig;
4
+ exports.z2mSensorTopics = z2mSensorTopics;
5
+ exports.transitionZ2mSensor = transitionZ2mSensor;
6
+ const mqtt_message_1 = require("./mqtt-message");
7
+ function normaliseZ2mSensorConfig(config) {
8
+ const baseTopic = String(config.baseTopic ?? "").trim().replace(/^\/+|\/+$/g, "") || "zigbee2mqtt";
9
+ // The user's own device's: no default.
10
+ const friendlyName = String(config.friendlyName ?? "").trim().replace(/^\/+|\/+$/g, "");
11
+ if (!friendlyName)
12
+ throw new Error("the device's friendly name is required");
13
+ if (/[+#]/.test(baseTopic) || /[+#]/.test(friendlyName))
14
+ throw new Error("the base topic and friendly name can't contain + or #");
15
+ const occupancyIs = config.occupancyIs === undefined || config.occupancyIs === null || config.occupancyIs === "" ? "motion" : config.occupancyIs;
16
+ if (occupancyIs !== "motion" && occupancyIs !== "presence")
17
+ throw new Error("occupancy is must be motion or presence");
18
+ return { baseTopic, friendlyName, occupancyIs };
19
+ }
20
+ function z2mSensorTopics(config) {
21
+ const device = `${config.baseTopic}/${config.friendlyName}`;
22
+ return { device, availability: `${device}/availability` };
23
+ }
24
+ function transitionZ2mSensor(saved, msg, config) {
25
+ const state = {
26
+ motion: typeof saved?.motion === "boolean" ? saved.motion : null,
27
+ presence: typeof saved?.presence === "boolean" ? saved.presence : null,
28
+ illuminance: typeof saved?.illuminance === "number" ? saved.illuminance : null,
29
+ online: typeof saved?.online === "boolean" ? saved.online : null
30
+ };
31
+ const topics = z2mSensorTopics(config);
32
+ const occupancy = [];
33
+ const light = [];
34
+ const traces = [];
35
+ const trace = (event, outcome, reason = null, details = {}) => {
36
+ traces.push({ event, outcome, reason, details });
37
+ };
38
+ if (msg.topic === topics.device) {
39
+ const report = (0, mqtt_message_1.parsedPayload)(msg.payload);
40
+ if (!(0, mqtt_message_1.isObject)(report))
41
+ throw new Error(`${topics.device} must carry the device's state object`);
42
+ const retained = msg.retain === true;
43
+ // Each occupancy field, as the room's source for it.
44
+ const fields = [];
45
+ if (Object.hasOwn(report, "occupancy"))
46
+ fields.push([config.occupancyIs, report.occupancy]);
47
+ if (Object.hasOwn(report, "presence"))
48
+ fields.push(["presence", report.presence]);
49
+ for (const [source, value] of fields) {
50
+ if (typeof value !== "boolean")
51
+ continue;
52
+ if (retained) {
53
+ // A retained state is an old one: never acted on, and not kept
54
+ // either, so the next live report is passed on whatever it says.
55
+ trace(source, "ignored", "retained", { value });
56
+ continue;
57
+ }
58
+ if (state[source] === value)
59
+ continue;
60
+ state[source] = value;
61
+ occupancy.push({ source, payload: value });
62
+ trace(source, "changed", null, { value });
63
+ }
64
+ // Lux: illuminance_lux where a device sends it beside a raw illuminance.
65
+ const lux = typeof report.illuminance_lux === "number" ? report.illuminance_lux
66
+ : typeof report.illuminance === "number" ? report.illuminance : null;
67
+ if (lux !== null && Number.isFinite(lux) && lux !== state.illuminance) {
68
+ state.illuminance = lux;
69
+ light.push({ source: "illuminance", payload: lux });
70
+ trace("illuminance", "changed", null, { lux });
71
+ }
72
+ state.online = true;
73
+ }
74
+ else if (msg.topic === topics.availability) {
75
+ // {"state": "online"}, or the plain "online" of older setups.
76
+ const received = (0, mqtt_message_1.parsedPayload)(msg.payload);
77
+ const value = (0, mqtt_message_1.isObject)(received) ? received.state : received;
78
+ if (value !== "online" && value !== "offline")
79
+ throw new Error(`${topics.availability} must say online or offline`);
80
+ state.online = value === "online";
81
+ trace("availability", value);
82
+ }
83
+ else {
84
+ trace("message", "ignored", "other-topic", { topic: typeof msg.topic === "string" ? msg.topic : null });
85
+ }
86
+ return { state, occupancy, light, traces };
87
+ }
88
+ //# sourceMappingURL=z2m-sensor.js.map
@@ -0,0 +1,2 @@
1
+ declare const _default: import("node-red").NodeInitializer<import("node-red").NodeAPISettingsWithData>;
2
+ export = _default;