@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
@@ -4,6 +4,7 @@ exports.REMOVED_VOLUME_VALUE = exports.parseAvrLine = exports.formatVolumeComman
4
4
  exports.createAvrState = createAvrState;
5
5
  exports.normaliseAvrConfig = normaliseAvrConfig;
6
6
  exports.transitionAvr = transitionAvr;
7
+ const target_observation_1 = require("./target-observation");
7
8
  const adopted_request_1 = require("./adopted-request");
8
9
  const settings_1 = require("./settings");
9
10
  const target_state_1 = require("./target-state");
@@ -91,7 +92,8 @@ function createAvrState(_config, saved = {}) {
91
92
  lastAttempt: Number.isInteger(saved.lastAttempt) && (saved.lastAttempt ?? -1) >= 0
92
93
  ? saved.lastAttempt
93
94
  : 0,
94
- adoptedGeneration: (0, adopted_request_1.savedAdoptedGeneration)(saved)
95
+ adoptedGeneration: (0, adopted_request_1.savedAdoptedGeneration)(saved),
96
+ probeAt: typeof saved.probeAt === "string" ? saved.probeAt : null
95
97
  };
96
98
  }
97
99
  function sameVolume(left, right) {
@@ -140,6 +142,8 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
140
142
  const commands = [];
141
143
  const events = [];
142
144
  const targetStates = [];
145
+ // Its answer to the theatre's recovery probe, for output 2 as the target states.
146
+ const observations = [];
143
147
  const traces = [];
144
148
  const event = msg.avr || { kind: "unknown" };
145
149
  const previousPhase = state.phase;
@@ -506,6 +510,12 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
506
510
  trace("refresh", "adopted", reason, { power: event.power, source: event.source || null, generation: adoptable.generation });
507
511
  }
508
512
  if (event.kind === "refresh" && !adopted) {
513
+ // The theatre's recovery probe: the query below, answered with what the
514
+ // receiver then reports.
515
+ if (!state.desired && (0, target_observation_1.isProbe)(event)) {
516
+ state.probeAt = now.toISOString();
517
+ trace("probe", "querying");
518
+ }
509
519
  // Re-read the receiver without touching work in flight: desired state,
510
520
  // pending commands, the volume request and the phase all carry on.
511
521
  commands.push({
@@ -626,6 +636,18 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
626
636
  reconcile();
627
637
  forceStateEvent = true;
628
638
  }
639
+ if (!state.desired && state.probeAt) {
640
+ // Its power since the probe, and its input too when it's on: a receiver
641
+ // in standby needn't say which input it's on.
642
+ const since = Date.parse(state.probeAt);
643
+ const fresh = (field) => state.fieldObservedAt[field] !== null && Date.parse(state.fieldObservedAt[field]) >= since;
644
+ if (fresh("power") && (state.observed.power === "standby" || fresh("source"))) {
645
+ const values = { power: state.observed.power, source: state.observed.source, mainZone: state.observed.mainZone };
646
+ observations.push((0, target_observation_1.targetObservation)("avr", now.toISOString(), values));
647
+ state.probeAt = null;
648
+ trace("probe", "answered", null, values);
649
+ }
650
+ }
629
651
  }
630
652
  else if (event.kind === "intent") {
631
653
  const reason = validateIntent(event);
@@ -963,6 +985,6 @@ function transitionAvr(saved, msg, rawConfig, nowValue = new Date()) {
963
985
  targetStates.push({ theatre });
964
986
  }
965
987
  }
966
- return { state, commands, events, targetStates, traces, status };
988
+ return { state, commands, events, targetStates, observations, traces, status };
967
989
  }
968
990
  //# sourceMappingURL=avr-controller.js.map
@@ -1,3 +1,4 @@
1
+ import { type TargetObservationOutput } from "./target-observation";
1
2
  import { type Carried } from "./adopted-request";
2
3
  import type { TraceEntry } from "./bounded-trace";
3
4
  import { type TargetStateEvent } from "./target-state";
@@ -40,6 +41,7 @@ export interface BacklightingState {
40
41
  lastAttempt: number;
41
42
  adoptedGeneration: number | null;
42
43
  carried?: Carried | null;
44
+ probing?: boolean;
43
45
  }
44
46
  export type BacklightingEvent = {
45
47
  kind: "intent";
@@ -73,9 +75,9 @@ export interface BacklightingMessage {
73
75
  }
74
76
  export interface BacklightingCommand {
75
77
  operation: "set_power" | "observe";
76
- requestId: string;
78
+ requestId: string | null;
77
79
  generation: number;
78
- power: BacklightingPower;
80
+ power: BacklightingPower | null;
79
81
  attempt: number;
80
82
  }
81
83
  export interface BacklightingOutputEvent {
@@ -95,6 +97,7 @@ export declare function transitionBacklighting(saved: Partial<BacklightingState>
95
97
  state: BacklightingState;
96
98
  commands: BacklightingCommand[];
97
99
  events: BacklightingOutputEvent[];
100
+ observations: TargetObservationOutput[];
98
101
  traces: TraceEntry<Record<string, unknown>>[];
99
102
  status: {
100
103
  phase: string;
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.normaliseBacklightingConfig = normaliseBacklightingConfig;
4
4
  exports.transitionBacklighting = transitionBacklighting;
5
+ const target_observation_1 = require("./target-observation");
5
6
  const adopted_request_1 = require("./adopted-request");
6
7
  const settings_1 = require("./settings");
7
8
  const observation_time_1 = require("./observation-time");
@@ -28,7 +29,8 @@ function initialState(saved = {}) {
28
29
  ? saved.lastAttempt
29
30
  : 0,
30
31
  adoptedGeneration: (0, adopted_request_1.savedAdoptedGeneration)(saved),
31
- carried: (0, adopted_request_1.savedCarried)(saved)
32
+ carried: (0, adopted_request_1.savedCarried)(saved),
33
+ probing: saved.probing === true
32
34
  };
33
35
  }
34
36
  function commandFor(state, operation, attempt) {
@@ -58,6 +60,8 @@ function transitionBacklighting(saved, msg, suppliedConfig = {}, nowValue = new
58
60
  const event = msg?.backlighting;
59
61
  const commands = [];
60
62
  const events = [];
63
+ // Its answer to the theatre's recovery probe, for output 2 as the events.
64
+ const observations = [];
61
65
  const traces = [];
62
66
  if (!event || typeof event.kind !== "string")
63
67
  throw new Error("msg.backlighting.kind is required");
@@ -121,6 +125,21 @@ function transitionBacklighting(saved, msg, suppliedConfig = {}, nowValue = new
121
125
  trace("intent", "accepted", null, { power: intent.power, generation: intent.generation });
122
126
  }
123
127
  function acceptObservation(observation) {
128
+ if (!state.desired && state.probing) {
129
+ // The probe's answer, whatever generation the transport echoes.
130
+ if (!Object.hasOwn(POWERS, observation.power))
131
+ throw new Error("unknown observed backlighting power");
132
+ const parsedAt = (0, observation_time_1.parseObservedAt)(observation.observedAt);
133
+ if (parsedAt === null || typeof observation.observedAt !== "string") {
134
+ throw new Error("backlighting observedAt must be an ISO timestamp");
135
+ }
136
+ const observedAt = (0, observation_time_1.boundObservedAt)(observation.observedAt, parsedAt, nowMs).observedAt;
137
+ state.observed = { power: observation.power, observedAt };
138
+ state.probing = false;
139
+ observations.push((0, target_observation_1.targetObservation)("backlighting", observedAt, { power: observation.power }));
140
+ trace("probe", "answered", null, { power: observation.power });
141
+ return;
142
+ }
124
143
  if (!Number.isInteger(observation.generation) || observation.generation < 1) {
125
144
  throw new Error("backlighting observation generation must be a positive integer");
126
145
  }
@@ -245,6 +264,12 @@ function transitionBacklighting(saved, msg, suppliedConfig = {}, nowValue = new
245
264
  trace("command", "emitted", null, { operation: "observe", power: state.desired.power });
246
265
  }
247
266
  }
267
+ else if (!state.desired && (0, target_observation_1.isProbe)(event)) {
268
+ // The theatre's recovery probe: read the backlight and say what it shows.
269
+ state.probing = true;
270
+ commands.push({ operation: "observe", requestId: null, generation: 0, power: null, attempt: 0 });
271
+ trace("probe", "observing");
272
+ }
248
273
  else if (event.kind === "refresh" && state.desired && state.phase === "ready" && !state.pending) {
249
274
  // A settled, ready target is re-read without leaving ready, as the
250
275
  // display, source and receiver are: its target state follows the
@@ -309,6 +334,6 @@ function transitionBacklighting(saved, msg, suppliedConfig = {}, nowValue = new
309
334
  });
310
335
  events.push({ theatre });
311
336
  }
312
- return { state, commands, events, traces, status: statusFor(state) };
337
+ return { state, commands, events, observations, traces, status: statusFor(state) };
313
338
  }
314
339
  //# sourceMappingURL=backlighting-controller.js.map
@@ -72,17 +72,31 @@ const cover = (0, publishing_node_1.publishingNode)({
72
72
  exports.coverStartingOutputs = cover.starting;
73
73
  exports.coverStoppingOutputs = cover.stopping;
74
74
  exports.coverRetainedTopics = cover.retainedTopics;
75
+ // Any cover's topics as this package names them, for any area and name: what
76
+ // a cover publishes, and its set topics. They come back to a cover through
77
+ // a wildcard subscription (home/<area>/cover/#), and are never its requests
78
+ // unless they are its own set topics.
79
+ const COVER_TOPIC = /^home\/[^/]+\/cover\/[^/]+\/(?:state|position|availability|set|position\/set)$/;
75
80
  // A request from Home Assistant on the cover's set topics, as the payload the
76
81
  // cover node takes from a flow: "open", "close", "stop" or a position. Read
77
82
  // only while it publishes; retained messages and anything else are ignored
78
- // with a trace. Anything else passes through (null).
83
+ // with a trace. Its own other topics, and any other cover's, publishing or
84
+ // not, are ignored with a trace too. Anything else, such as a cover group's
85
+ // request named by its member or a flow's own topic, passes through (null).
79
86
  function coverInbound(msg, config) {
80
- if (!(0, publishing_node_1.publishesState)(config))
81
- return null;
82
- const command = msg.topic === (0, exports.coverCommandTopic)(config);
83
- const position = config.positions && msg.topic === (0, exports.coverSetPositionTopic)(config);
84
- if (!command && !position)
87
+ const topic = typeof msg.topic === "string" ? msg.topic : null;
88
+ const publishing = (0, publishing_node_1.publishesState)(config);
89
+ const command = publishing && topic === (0, exports.coverCommandTopic)(config);
90
+ const position = publishing && config.positions && topic === (0, exports.coverSetPositionTopic)(config);
91
+ if (!command && !position) {
92
+ const own = publishing && topic !== null && topic.startsWith(coverTopic(config, ""));
93
+ if (own || (topic !== null && COVER_TOPIC.test(topic))) {
94
+ return { request: null, traces: [own
95
+ ? { event: "own-topic", outcome: "ignored", reason: "not-a-set-topic", details: { topic } }
96
+ : { event: "cover-topic", outcome: "ignored", reason: "another-covers-topic", details: { topic } }] };
97
+ }
85
98
  return null;
99
+ }
86
100
  const event = command ? "command-set" : "position-set";
87
101
  const ignored = (reason, details = {}) => ({ request: null, traces: [{ event, outcome: "ignored", reason, details }] });
88
102
  if (msg.retain === true)
@@ -1,3 +1,4 @@
1
+ import { type TargetObservationOutput } from "./target-observation";
1
2
  import { type Carried } from "./adopted-request";
2
3
  import type { TraceEntry } from "./bounded-trace";
3
4
  import { type PowerReading } from "./power-reading";
@@ -84,6 +85,7 @@ export interface DisplayState {
84
85
  fallbackUsed: boolean;
85
86
  adoptedGeneration: number | null;
86
87
  carried?: Carried | null;
88
+ probeAt?: string | null;
87
89
  discovery?: {
88
90
  attempt: number;
89
91
  nextAt: number;
@@ -139,6 +141,7 @@ export declare function transitionDisplay(saved: Partial<DisplayState> | undefin
139
141
  targetStates: {
140
142
  theatre: DisplayTargetState;
141
143
  }[];
144
+ observations: TargetObservationOutput[];
142
145
  traces: TraceEntry<Record<string, unknown>>[];
143
146
  status: {
144
147
  phase: string;
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.classifyProjectorPower = classifyProjectorPower;
4
4
  exports.normaliseConfig = normaliseConfig;
5
5
  exports.transitionDisplay = transitionDisplay;
6
+ const target_observation_1 = require("./target-observation");
6
7
  const adopted_request_1 = require("./adopted-request");
7
8
  const settings_1 = require("./settings");
8
9
  const observation_time_1 = require("./observation-time");
@@ -32,6 +33,7 @@ function initialState(saved = {}) {
32
33
  fallbackUsed: saved.fallbackUsed === true,
33
34
  adoptedGeneration: (0, adopted_request_1.savedAdoptedGeneration)(saved),
34
35
  carried: (0, adopted_request_1.savedCarried)(saved),
36
+ probeAt: typeof saved.probeAt === "string" ? saved.probeAt : null,
35
37
  ...(saved.discovery && Number.isFinite(saved.discovery.nextAt) ? { discovery: { ...saved.discovery } } : {})
36
38
  };
37
39
  }
@@ -160,22 +162,26 @@ function normaliseConfig(config = {}) {
160
162
  projectorPowerFallback: (0, settings_1.booleanSetting)(config.projectorPowerFallback, "projector power fallback", false)
161
163
  };
162
164
  }
165
+ // Whether the devices show a mode: what each mode sets them to.
166
+ function modeShown(mode, observed, config) {
167
+ if (mode === "tv") {
168
+ return observed.tv?.power === "on" &&
169
+ observed.projector?.power === "standby" &&
170
+ screenClosed(observed.screen, config);
171
+ }
172
+ if (mode === "projector") {
173
+ return observed.tv?.power === "standby" &&
174
+ observed.projector?.power === "on" &&
175
+ screenOpen(observed.screen, config);
176
+ }
177
+ return observed.tv?.power === "standby" &&
178
+ observed.projector?.power === "standby" &&
179
+ screenClosed(observed.screen, config);
180
+ }
163
181
  function modeSatisfied(state, config) {
164
182
  if (!state.desired || !allSeen(state))
165
183
  return false;
166
- if (state.desired.mode === "tv") {
167
- return state.observed.tv?.power === "on" &&
168
- state.observed.projector?.power === "standby" &&
169
- screenClosed(state.observed.screen, config);
170
- }
171
- if (state.desired.mode === "projector") {
172
- return state.observed.tv?.power === "standby" &&
173
- state.observed.projector?.power === "on" &&
174
- screenOpen(state.observed.screen, config);
175
- }
176
- return state.observed.tv?.power === "standby" &&
177
- state.observed.projector?.power === "standby" &&
178
- screenClosed(state.observed.screen, config);
184
+ return modeShown(state.desired.mode, state.observed, config);
179
185
  }
180
186
  function transitionDisplay(saved, msg, suppliedConfig = {}, now = new Date()) {
181
187
  const config = normaliseConfig(suppliedConfig);
@@ -197,6 +203,8 @@ function transitionDisplay(saved, msg, suppliedConfig = {}, now = new Date()) {
197
203
  const commands = [];
198
204
  const events = [];
199
205
  const targetStates = [];
206
+ // Its answer to the theatre's recovery probe, for output 2 as the target states.
207
+ const observations = [];
200
208
  const traces = [];
201
209
  function trace(name, outcome, reason = null, details = {}) {
202
210
  traces.push({ event: name, outcome, reason, details });
@@ -641,8 +649,15 @@ function transitionDisplay(saved, msg, suppliedConfig = {}, now = new Date()) {
641
649
  else if (event.kind === "refresh") {
642
650
  // Re-confirm a settled display from fresh readings; its target state
643
651
  // follows them. These queries are not discovery, so a failed one is
644
- // ignored rather than failing the request.
645
- if (state.desired && state.phase === "ready" && !state.pending) {
652
+ // ignored rather than failing the request. The theatre's recovery probe
653
+ // reads every device the same way, and is answered below.
654
+ if (!state.desired && (0, target_observation_1.isProbe)(event)) {
655
+ state.probeAt = now.toISOString();
656
+ for (const device of DEVICES)
657
+ commands.push(queryFor(state, device));
658
+ trace("probe", "querying");
659
+ }
660
+ else if (state.desired && state.phase === "ready" && !state.pending) {
646
661
  for (const device of DEVICES)
647
662
  commands.push(queryFor(state, device));
648
663
  trace("refresh", "querying");
@@ -716,6 +731,18 @@ function transitionDisplay(saved, msg, suppliedConfig = {}, now = new Date()) {
716
731
  fallbackUsed: state.fallbackUsed
717
732
  }
718
733
  }));
719
- return { state, commands, events, targetStates, traces, status: statusFor(state) };
734
+ if (!state.desired && state.probeAt) {
735
+ // Every device read since the probe: the one mode they show, by the
736
+ // modes' own definitions, or none.
737
+ const since = Date.parse(state.probeAt);
738
+ if (DEVICES.every((device) => state.observed[device] && Date.parse(state.observed[device].observedAt) >= since)) {
739
+ const shown = Object.keys(MODES).filter((mode) => modeShown(mode, state.observed, config));
740
+ const values = { mode: shown.length === 1 ? shown[0] : null };
741
+ observations.push((0, target_observation_1.targetObservation)("display", now.toISOString(), values));
742
+ state.probeAt = null;
743
+ trace("probe", "answered", null, values);
744
+ }
745
+ }
746
+ return { state, commands, events, targetStates, observations, traces, status: statusFor(state) };
720
747
  }
721
748
  //# sourceMappingURL=display-mode-controller.js.map
@@ -0,0 +1,73 @@
1
+ import type { TraceEntry } from "./bounded-trace";
2
+ export type SensorRole = "motion" | "presence" | "illuminance";
3
+ export interface EsphomeModel {
4
+ label: string;
5
+ modelNames: readonly string[];
6
+ exclude: readonly string[];
7
+ motion: readonly string[];
8
+ presence: readonly string[];
9
+ illuminance: readonly string[];
10
+ }
11
+ export declare const ESPHOME_MODELS: Readonly<Record<string, EsphomeModel>>;
12
+ export interface EsphomeSensorConfig {
13
+ device: string;
14
+ model: string;
15
+ discoveryPrefix: string;
16
+ }
17
+ export interface DiscoveredEntity {
18
+ component: string;
19
+ object: string;
20
+ stateTopic: string;
21
+ deviceClass: string | null;
22
+ model: string | null;
23
+ availabilityTopic: string | null;
24
+ }
25
+ export interface EsphomeSensorState {
26
+ entities: Record<string, boolean>;
27
+ motion: boolean | null;
28
+ presence: boolean | null;
29
+ illuminance: number | null;
30
+ online: boolean | null;
31
+ awaitingStatus: boolean;
32
+ discovered: Record<string, DiscoveredEntity>;
33
+ }
34
+ export interface EsphomeSensorMessage {
35
+ topic?: unknown;
36
+ payload?: unknown;
37
+ retain?: unknown;
38
+ }
39
+ export interface OccupancyMessage {
40
+ source: "motion" | "presence";
41
+ payload: boolean;
42
+ baseline?: true;
43
+ }
44
+ export interface LightMessage {
45
+ source: "illuminance";
46
+ payload: number;
47
+ }
48
+ export type RoleSource = "discovered" | "preset" | "preset-other-model";
49
+ export interface Roles {
50
+ source: RoleSource;
51
+ motion: string[];
52
+ presence: string[];
53
+ illuminance: string[];
54
+ status: string[];
55
+ }
56
+ export declare function normaliseEsphomeSensorConfig(config: {
57
+ device?: unknown;
58
+ model?: unknown;
59
+ discoveryPrefix?: unknown;
60
+ }): EsphomeSensorConfig;
61
+ export declare function esphomeSensorTopics(config: EsphomeSensorConfig): {
62
+ discovery: string;
63
+ initial: string[];
64
+ };
65
+ export declare function esphomeRoles(state: Pick<EsphomeSensorState, "discovered">, config: EsphomeSensorConfig): Roles;
66
+ export declare function transitionEsphomeSensor(saved: Partial<EsphomeSensorState> | undefined, msg: EsphomeSensorMessage, config: EsphomeSensorConfig): {
67
+ state: EsphomeSensorState;
68
+ occupancy: OccupancyMessage[];
69
+ light: LightMessage[];
70
+ traces: TraceEntry<Record<string, unknown>>[];
71
+ roles: Roles;
72
+ topics: string[];
73
+ };
@@ -0,0 +1,261 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ESPHOME_MODELS = void 0;
4
+ exports.normaliseEsphomeSensorConfig = normaliseEsphomeSensorConfig;
5
+ exports.esphomeSensorTopics = esphomeSensorTopics;
6
+ exports.esphomeRoles = esphomeRoles;
7
+ exports.transitionEsphomeSensor = transitionEsphomeSensor;
8
+ const mqtt_message_1 = require("./mqtt-message");
9
+ exports.ESPHOME_MODELS = {
10
+ "everything-presence-one": {
11
+ label: "Everything Presence One",
12
+ modelNames: ["everythingpresenceone"],
13
+ // Its own "Occupancy" combines the PIR and radar, with its own off
14
+ // latency: occupancy fusion does that combining here.
15
+ exclude: ["occupancy"],
16
+ motion: ["pir"],
17
+ presence: ["mmwave"],
18
+ illuminance: ["illuminance"]
19
+ },
20
+ "apollo-r-pro-1": {
21
+ label: "Apollo R PRO-1",
22
+ modelNames: ["rpro1"],
23
+ exclude: [],
24
+ // Its two radars, LD2450 and LD2412: a moving target is motion. Its
25
+ // firmware has named the LD2450's entities both without a prefix
26
+ // (presence, moving_target) and, currently, with ld2450_.
27
+ motion: ["moving_target", "ld2450_moving_target", "ld2412_moving_target"],
28
+ presence: ["presence", "ld2450_presence", "ld2412_presence"],
29
+ illuminance: ["ltr390_light"]
30
+ }
31
+ };
32
+ function normaliseEsphomeSensorConfig(config) {
33
+ const device = String(config.device ?? "").trim().replace(/^\/+|\/+$/g, "");
34
+ // The user's own device's: no default.
35
+ if (!device)
36
+ throw new Error("the device's name is required");
37
+ if (/[+#]/.test(device))
38
+ throw new Error("the device's name can't contain + or #");
39
+ const model = String(config.model ?? "");
40
+ if (!Object.hasOwn(exports.ESPHOME_MODELS, model))
41
+ throw new Error(`unknown model: ${model}`);
42
+ const discoveryPrefix = String(config.discoveryPrefix ?? "").trim().replace(/^\/+|\/+$/g, "") || "homeassistant";
43
+ if (/[+#]/.test(discoveryPrefix))
44
+ throw new Error("the discovery prefix can't contain + or #");
45
+ return { device, model, discoveryPrefix };
46
+ }
47
+ // The topics a node subscribes to as it starts: the device's discovery,
48
+ // its status, and its preset's states (until discovery says otherwise).
49
+ function esphomeSensorTopics(config) {
50
+ const preset = presetRoles(config, "preset");
51
+ return {
52
+ discovery: `${config.discoveryPrefix}/+/${config.device}/+/config`,
53
+ initial: [...new Set([`${config.discoveryPrefix}/+/${config.device}/+/config`, ...preset.status, ...preset.presence,
54
+ ...preset.motion, ...preset.illuminance])]
55
+ };
56
+ }
57
+ function presetRoles(config, source) {
58
+ const model = exports.ESPHOME_MODELS[config.model];
59
+ const binary = (name) => `${config.device}/binary_sensor/${name}/state`;
60
+ return {
61
+ source,
62
+ motion: model.motion.map(binary),
63
+ presence: model.presence.map(binary),
64
+ illuminance: model.illuminance.map((name) => `${config.device}/sensor/${name}/state`),
65
+ status: [`${config.device}/status`]
66
+ };
67
+ }
68
+ const simplified = (value) => value.toLowerCase().replace(/[^a-z0-9]/g, "");
69
+ // The roles, from the device's discovery when it has one for this model.
70
+ function esphomeRoles(state, config) {
71
+ const model = exports.ESPHOME_MODELS[config.model];
72
+ const entities = Object.values(state.discovered).filter((entity) => !model.exclude.includes(entity.object));
73
+ if (!entities.length)
74
+ return presetRoles(config, "preset");
75
+ const models = entities.map((entity) => entity.model).filter((name) => Boolean(name));
76
+ if (models.some((name) => !model.modelNames.some((fragment) => simplified(name).includes(fragment)))) {
77
+ return presetRoles(config, "preset-other-model");
78
+ }
79
+ const of = (component, classes) => entities
80
+ .filter((entity) => entity.component === component && entity.deviceClass !== null && classes.includes(entity.deviceClass))
81
+ .map((entity) => entity.stateTopic);
82
+ const status = [...new Set([`${config.device}/status`, ...entities.map((entity) => entity.availabilityTopic)
83
+ .filter((topic) => Boolean(topic))])];
84
+ return {
85
+ source: "discovered",
86
+ motion: of("binary_sensor", ["motion"]),
87
+ presence: of("binary_sensor", ["occupancy", "presence"]),
88
+ illuminance: of("sensor", ["illuminance"]),
89
+ status
90
+ };
91
+ }
92
+ function text(payload) {
93
+ return (Buffer.isBuffer(payload) ? payload.toString("utf8") : String(payload ?? "")).trim();
94
+ }
95
+ // A discovery entry's fields, from Home Assistant's discovery format with
96
+ // or without its abbreviated keys. Its "~" base-topic shorthand isn't
97
+ // expanded: ESPHome gives full state and availability topics.
98
+ function discoveredEntity(component, object, payload) {
99
+ let entry;
100
+ try {
101
+ entry = JSON.parse(payload);
102
+ }
103
+ catch {
104
+ return null;
105
+ }
106
+ if (!(0, mqtt_message_1.isObject)(entry))
107
+ return null;
108
+ // Disabled by default on the device (ESPHome's disabled_by_default, "en":
109
+ // false): its maker doesn't mean it as one of its sensors, such as the
110
+ // Apollo's LD2412 light level, a radar reading rather than lux.
111
+ if (entry.en === false || entry.enabled_by_default === false)
112
+ return "disabled";
113
+ const field = (short, long) => (typeof entry[short] === "string" ? entry[short] : typeof entry[long] === "string" ? entry[long] : null);
114
+ const stateTopic = field("stat_t", "state_topic");
115
+ if (!stateTopic)
116
+ return null;
117
+ const device = (0, mqtt_message_1.isObject)(entry.dev) ? entry.dev : (0, mqtt_message_1.isObject)(entry.device) ? entry.device : {};
118
+ const model = typeof device.mdl === "string" ? device.mdl : typeof device.model === "string" ? device.model : null;
119
+ return { component, object, stateTopic, deviceClass: field("dev_cla", "device_class"), model, availabilityTopic: field("avty_t", "availability_topic") };
120
+ }
121
+ function transitionEsphomeSensor(saved, msg, config) {
122
+ const state = {
123
+ entities: saved?.entities && typeof saved.entities === "object" ? { ...saved.entities } : {},
124
+ motion: typeof saved?.motion === "boolean" ? saved.motion : null,
125
+ presence: typeof saved?.presence === "boolean" ? saved.presence : null,
126
+ illuminance: typeof saved?.illuminance === "number" ? saved.illuminance : null,
127
+ online: typeof saved?.online === "boolean" ? saved.online : null,
128
+ awaitingStatus: saved?.awaitingStatus === true,
129
+ discovered: saved?.discovered && typeof saved.discovered === "object" ? { ...saved.discovered } : {}
130
+ };
131
+ const occupancy = [];
132
+ const light = [];
133
+ const traces = [];
134
+ const trace = (event, outcome, reason = null, details = {}) => {
135
+ traces.push({ event, outcome, reason, details });
136
+ };
137
+ const before = esphomeRoles(state, config);
138
+ // A role's value from the entities that have reported: on when any is
139
+ // on, off when all are off, not known while none has reported.
140
+ function roleValue(roles, role) {
141
+ const reported = roles[role].map((topic) => state.entities[topic]).filter((value) => value !== undefined);
142
+ if (!reported.length)
143
+ return null;
144
+ return reported.some((value) => value === true);
145
+ }
146
+ // Each occupancy role that changed, presence first: at a start, presence
147
+ // holds the room before motion's "off" could empty it.
148
+ function sendRoles(roles, baseline) {
149
+ for (const role of ["presence", "motion"]) {
150
+ const value = roleValue(roles, role);
151
+ if (value === null || value === state[role])
152
+ continue;
153
+ state[role] = value;
154
+ occupancy.push(baseline ? { source: role, payload: value, baseline: true } : { source: role, payload: value });
155
+ trace(role, baseline ? "baseline" : "changed", null, { value });
156
+ }
157
+ }
158
+ const retained = msg.retain === true;
159
+ const topic = typeof msg.topic === "string" ? msg.topic : "";
160
+ const discovery = topic.split("/");
161
+ const prefixParts = config.discoveryPrefix.split("/").length;
162
+ if (topic.startsWith(`${config.discoveryPrefix}/`) && discovery.length === prefixParts + 4 && discovery.at(-1) === "config" &&
163
+ discovery[prefixParts + 1] === config.device) {
164
+ const component = discovery[prefixParts];
165
+ const object = discovery[prefixParts + 2];
166
+ const payload = text(msg.payload);
167
+ if (component !== "binary_sensor" && component !== "sensor") {
168
+ trace("discovery", "ignored", "other-component", { component, object });
169
+ }
170
+ else if (payload === "") {
171
+ // An entity removed from the device.
172
+ delete state.discovered[topic];
173
+ trace("discovery", "removed", null, { object });
174
+ }
175
+ else {
176
+ const entity = discoveredEntity(component, object, payload);
177
+ if (entity === "disabled") {
178
+ delete state.discovered[topic];
179
+ trace("discovery", "ignored", "disabled", { object });
180
+ }
181
+ else if (!entity) {
182
+ trace("discovery", "ignored", "no-state-topic", { object });
183
+ }
184
+ else {
185
+ state.discovered[topic] = entity;
186
+ }
187
+ }
188
+ const after = esphomeRoles(state, config);
189
+ if (JSON.stringify(after) !== JSON.stringify(before)) {
190
+ const preset = presetRoles(config, "preset");
191
+ // Discovery wins over the preset; where they differ, it's traced.
192
+ const differs = after.source === "discovered" &&
193
+ ["motion", "presence", "illuminance"].some((role) => JSON.stringify([...after[role]].sort()) !== JSON.stringify([...preset[role]].sort()));
194
+ trace("roles", after.source, differs ? "differs-from-preset" : null, { motion: after.motion, presence: after.presence, illuminance: after.illuminance });
195
+ }
196
+ }
197
+ else if (before.status.includes(topic)) {
198
+ const status = text(msg.payload).toLowerCase();
199
+ if (status !== "online" && status !== "offline") {
200
+ trace("availability", "ignored", "not-online-or-offline", { status });
201
+ }
202
+ else {
203
+ state.online = status === "online";
204
+ trace("availability", status);
205
+ if (state.online && state.awaitingStatus) {
206
+ // The retained states held for this: the room as it is at start.
207
+ state.awaitingStatus = false;
208
+ sendRoles(before, true);
209
+ }
210
+ else if (!state.online) {
211
+ // A device that isn't online: what it last retained isn't current.
212
+ state.awaitingStatus = false;
213
+ if (retained)
214
+ state.entities = {};
215
+ }
216
+ }
217
+ }
218
+ else if (before.motion.includes(topic) || before.presence.includes(topic)) {
219
+ const value = text(msg.payload).toUpperCase();
220
+ if (value !== "ON" && value !== "OFF") {
221
+ // A fixed contract: only ON and OFF pass.
222
+ trace("state", "ignored", "not-on-or-off", { topic, value });
223
+ }
224
+ else if (retained && state.online === false) {
225
+ trace("state", "ignored", "retained-while-offline", { topic });
226
+ }
227
+ else {
228
+ state.entities[topic] = value === "ON";
229
+ if (retained && state.online !== true) {
230
+ state.awaitingStatus = true;
231
+ trace("state", "held", "awaiting-status", { topic });
232
+ }
233
+ else {
234
+ sendRoles(before, retained);
235
+ }
236
+ }
237
+ }
238
+ else if (before.illuminance.includes(topic)) {
239
+ const lux = Number(text(msg.payload));
240
+ if (text(msg.payload) === "" || !Number.isFinite(lux)) {
241
+ // A fixed contract: only a number passes ("nan" doesn't).
242
+ trace("illuminance", "ignored", "not-a-number", { value: text(msg.payload) });
243
+ }
244
+ else if (retained && state.online === false) {
245
+ trace("illuminance", "ignored", "retained-while-offline");
246
+ }
247
+ else if (lux !== state.illuminance) {
248
+ state.illuminance = lux;
249
+ light.push({ source: "illuminance", payload: lux });
250
+ trace("illuminance", "changed", null, { lux });
251
+ }
252
+ }
253
+ else {
254
+ trace("message", "ignored", "other-topic", { topic: topic || null });
255
+ }
256
+ const roles = esphomeRoles(state, config);
257
+ // Every topic the node needs now: it subscribes to any it hasn't yet.
258
+ const topics = [...new Set([esphomeSensorTopics(config).discovery, ...roles.status, ...roles.presence, ...roles.motion, ...roles.illuminance])];
259
+ return { state, occupancy, light, traces, roles, topics };
260
+ }
261
+ //# sourceMappingURL=esphome-sensor.js.map