@avantics/node-red-home-automation 3.0.1 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/README.md +262 -13
  2. package/dist/lib/activity-lighting-controller.d.ts +7 -1
  3. package/dist/lib/activity-lighting-controller.js +37 -3
  4. package/dist/lib/adopted-request.d.ts +26 -0
  5. package/dist/lib/adopted-request.js +44 -0
  6. package/dist/lib/avr-controller.d.ts +8 -1
  7. package/dist/lib/avr-controller.js +27 -3
  8. package/dist/lib/avr-publishing.d.ts +24 -0
  9. package/dist/lib/avr-publishing.js +80 -0
  10. package/dist/lib/backlighting-controller.d.ts +7 -1
  11. package/dist/lib/backlighting-controller.js +26 -3
  12. package/dist/lib/circadian.d.ts +1 -0
  13. package/dist/lib/circadian.js +3 -0
  14. package/dist/lib/cover-availability.d.ts +7 -0
  15. package/dist/lib/cover-availability.js +24 -0
  16. package/dist/lib/cover-controller.d.ts +13 -1
  17. package/dist/lib/cover-controller.js +113 -30
  18. package/dist/lib/cover-group.d.ts +62 -0
  19. package/dist/lib/cover-group.js +125 -0
  20. package/dist/lib/cover-models.d.ts +37 -0
  21. package/dist/lib/cover-models.js +83 -0
  22. package/dist/lib/cover-publishing.d.ts +40 -0
  23. package/dist/lib/cover-publishing.js +102 -0
  24. package/dist/lib/cover-requests.d.ts +21 -0
  25. package/dist/lib/cover-requests.js +49 -0
  26. package/dist/lib/display-mode-controller.d.ts +4 -0
  27. package/dist/lib/display-mode-controller.js +26 -2
  28. package/dist/lib/ha-discovery.d.ts +27 -0
  29. package/dist/lib/ha-discovery.js +91 -0
  30. package/dist/lib/house-schedule-publishing.d.ts +23 -0
  31. package/dist/lib/house-schedule-publishing.js +71 -0
  32. package/dist/lib/house-schedule.d.ts +23 -0
  33. package/dist/lib/house-schedule.js +29 -0
  34. package/dist/lib/motion-policy.d.ts +9 -0
  35. package/dist/lib/motion-policy.js +45 -11
  36. package/dist/lib/motion-publishing.d.ts +28 -0
  37. package/dist/lib/motion-publishing.js +92 -0
  38. package/dist/lib/occupancy-publishing.d.ts +10 -0
  39. package/dist/lib/occupancy-publishing.js +45 -0
  40. package/dist/lib/open-close-cover.d.ts +92 -0
  41. package/dist/lib/open-close-cover.js +287 -0
  42. package/dist/lib/publishing-node.d.ts +39 -0
  43. package/dist/lib/publishing-node.js +72 -0
  44. package/dist/lib/retained-topics.d.ts +10 -0
  45. package/dist/lib/retained-topics.js +19 -0
  46. package/dist/lib/room-controller.d.ts +9 -0
  47. package/dist/lib/room-controller.js +47 -56
  48. package/dist/lib/room-lighting-discovery.d.ts +20 -1
  49. package/dist/lib/room-lighting-discovery.js +135 -13
  50. package/dist/lib/room-publishing.d.ts +42 -0
  51. package/dist/lib/room-publishing.js +182 -0
  52. package/dist/lib/room-schedule.d.ts +8 -0
  53. package/dist/lib/room-schedule.js +41 -0
  54. package/dist/lib/settings.d.ts +2 -0
  55. package/dist/lib/settings.js +20 -0
  56. package/dist/lib/source-capability-controller.d.ts +8 -1
  57. package/dist/lib/source-capability-controller.js +29 -3
  58. package/dist/lib/theatre-activity-controller.d.ts +0 -1
  59. package/dist/lib/theatre-activity-controller.js +27 -24
  60. package/dist/lib/theatre-ha-discovery.d.ts +3 -4
  61. package/dist/lib/theatre-ha-discovery.js +46 -36
  62. package/dist/lib/theatre-state-contract.d.ts +6 -0
  63. package/dist/lib/theatre-state-contract.js +83 -47
  64. package/dist/lib/theatre-state.d.ts +1 -1
  65. package/dist/lib/theatre-state.js +1 -1
  66. package/dist/lib/topic-names.d.ts +4 -0
  67. package/dist/lib/topic-names.js +31 -0
  68. package/dist/nodes/activity-lighting-controller.js +5 -3
  69. package/dist/nodes/adapter.d.ts +6 -1
  70. package/dist/nodes/adapter.js +65 -1
  71. package/dist/nodes/avr-controller.html +59 -5
  72. package/dist/nodes/avr-controller.js +74 -4
  73. package/dist/nodes/backlighting-controller.js +5 -3
  74. package/dist/nodes/cover-controller.d.ts +3 -0
  75. package/dist/nodes/cover-controller.html +177 -0
  76. package/dist/nodes/cover-controller.js +178 -0
  77. package/dist/nodes/cover-group.d.ts +3 -0
  78. package/dist/nodes/cover-group.html +89 -0
  79. package/dist/nodes/cover-group.js +84 -0
  80. package/dist/nodes/flows-started.d.ts +4 -0
  81. package/dist/nodes/flows-started.js +39 -0
  82. package/dist/nodes/house-schedule-mqtt.d.ts +3 -0
  83. package/dist/nodes/house-schedule-mqtt.html +61 -0
  84. package/dist/nodes/house-schedule-mqtt.js +80 -0
  85. package/dist/nodes/house-schedule.d.ts +3 -0
  86. package/dist/nodes/house-schedule.html +31 -0
  87. package/dist/nodes/house-schedule.js +51 -0
  88. package/dist/nodes/motion-policy.html +81 -5
  89. package/dist/nodes/motion-policy.js +69 -8
  90. package/dist/nodes/occupancy-fusion.html +69 -14
  91. package/dist/nodes/occupancy-fusion.js +46 -4
  92. package/dist/nodes/publishing-lifecycle.d.ts +25 -0
  93. package/dist/nodes/publishing-lifecycle.js +38 -0
  94. package/dist/nodes/room-controller.html +49 -5
  95. package/dist/nodes/room-controller.js +67 -8
  96. package/dist/nodes/shared-schedule.d.ts +6 -0
  97. package/dist/nodes/shared-schedule.js +15 -0
  98. package/dist/nodes/source-capability-controller.js +5 -3
  99. package/dist/nodes/theatre-activity-controller.html +1 -3
  100. package/dist/nodes/theatre-activity-controller.js +1 -2
  101. package/dist/nodes/theatre-state-contract.html +28 -5
  102. package/dist/nodes/theatre-state-contract.js +22 -4
  103. package/examples/Cover control.json +380 -0
  104. package/examples/Cover pair.json +230 -0
  105. package/examples/Home theatre activity.json +4 -4
  106. package/examples/House schedule.json +164 -0
  107. package/examples/Room lighting.json +4 -3
  108. package/package.json +6 -2
@@ -0,0 +1,24 @@
1
+ import type { AvrObserved } from "./avr-controller";
2
+ import { type OptInPublishingConfig, type RetainedText } from "./publishing-node";
3
+ export interface AvrPublishingConfig extends OptInPublishingConfig {
4
+ minVolume: number;
5
+ maxVolume: number;
6
+ }
7
+ export type AvrPublication = RetainedText;
8
+ export declare function receiverTopic(area: string, name: string): string;
9
+ export declare function avrDiscovery(config: AvrPublishingConfig): AvrPublication[];
10
+ export declare const VOLUME_SET_SETTLE_MS = 300;
11
+ export declare function avrVolumeRequest(msg: {
12
+ topic?: unknown;
13
+ payload?: unknown;
14
+ retain?: unknown;
15
+ }, config: AvrPublishingConfig): {
16
+ value: number;
17
+ } | {
18
+ ignored: string;
19
+ payload: string;
20
+ } | null;
21
+ export declare function avrStateOutputs(config: AvrPublishingConfig, observed: Partial<AvrObserved> | undefined, before?: Partial<AvrObserved>): AvrPublication[];
22
+ export declare const avrStartingOutputs: (config: AvrPublishingConfig, state: Partial<AvrObserved> | undefined) => RetainedText[];
23
+ export declare const avrStoppingOutputs: (config: AvrPublishingConfig) => RetainedText[];
24
+ export declare const avrRetainedTopics: (config: AvrPublishingConfig) => string[];
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.avrRetainedTopics = exports.avrStoppingOutputs = exports.avrStartingOutputs = exports.VOLUME_SET_SETTLE_MS = void 0;
4
+ exports.receiverTopic = receiverTopic;
5
+ exports.avrDiscovery = avrDiscovery;
6
+ exports.avrVolumeRequest = avrVolumeRequest;
7
+ exports.avrStateOutputs = avrStateOutputs;
8
+ const topic_names_1 = require("./topic-names");
9
+ const publishing_node_1 = require("./publishing-node");
10
+ const FIELDS = ["power", "source", "volume"];
11
+ const DEVICE = { kind: "receiver", label: "Receiver", model: "AV receiver controller" };
12
+ function receiverTopic(area, name) {
13
+ return "home/" + (0, topic_names_1.areaId)(area) + "/receiver/" + name;
14
+ }
15
+ // A field's state as published, or null while it isn't known.
16
+ function fieldValue(observed, field) {
17
+ const value = observed?.[field];
18
+ if (value === null || value === undefined)
19
+ return null;
20
+ if (field === "power")
21
+ return value === "on" ? "ON" : "OFF";
22
+ return String(value);
23
+ }
24
+ // Power and source sensors, and a volume number that shows the volume and
25
+ // sets it, within the configured bounds, on one device per node.
26
+ function avrDiscovery(config) {
27
+ const entry = (component, id, name, fields) => (0, publishing_node_1.discoveryEntry)(config, DEVICE, receiverTopic(config.area, "availability"), { component, id, name, fields });
28
+ return [
29
+ entry("binary_sensor", "receiver_power", "Power", { device_class: "power", state_topic: receiverTopic(config.area, "power/state"), payload_on: "ON", payload_off: "OFF" }),
30
+ entry("sensor", "receiver_source", "Source", { icon: "mdi:import", state_topic: receiverTopic(config.area, "source/state") }),
31
+ entry("number", "receiver_volume", "Volume", {
32
+ icon: "mdi:volume-high",
33
+ state_topic: receiverTopic(config.area, "volume/state"),
34
+ command_topic: receiverTopic(config.area, "volume/set"),
35
+ min: config.minVolume,
36
+ max: config.maxVolume,
37
+ step: 0.5,
38
+ mode: "slider"
39
+ })
40
+ ];
41
+ }
42
+ // How long a volume from Home Assistant waits for a newer one. A slider,
43
+ // repeated taps or an automation can send several in a row; only the last
44
+ // becomes a request, so the receiver never chases steps already replaced.
45
+ exports.VOLUME_SET_SETTLE_MS = 300;
46
+ // A volume from the volume number's set topic, as the receiver's own
47
+ // absolute volume request, so it takes the same bounded, confirmed path as
48
+ // any other request. Read only while the node publishes; retained messages
49
+ // and anything but a number are ignored with a trace.
50
+ function avrVolumeRequest(msg, config) {
51
+ if (!(0, publishing_node_1.publishesState)(config) || msg.topic !== receiverTopic(config.area, "volume/set"))
52
+ return null;
53
+ const text = typeof msg.payload === "string" ? msg.payload.trim() : typeof msg.payload === "number" ? String(msg.payload) : "";
54
+ if (msg.retain === true)
55
+ return { ignored: "retained-message", payload: text };
56
+ const value = text === "" ? NaN : Number(text);
57
+ return Number.isFinite(value) ? { value } : { ignored: "not-a-number", payload: text };
58
+ }
59
+ // The observed fields that changed since `before` (all known fields when
60
+ // there's no `before`).
61
+ function avrStateOutputs(config, observed, before) {
62
+ if (!(0, publishing_node_1.publishesState)(config))
63
+ return [];
64
+ return FIELDS.flatMap((field) => {
65
+ const value = fieldValue(observed, field);
66
+ if (value === null || (before && fieldValue(before, field) === value))
67
+ return [];
68
+ return [(0, publishing_node_1.retainedText)(receiverTopic(config.area, field + "/state"), value)];
69
+ });
70
+ }
71
+ const receiver = (0, publishing_node_1.publishingNode)({
72
+ entries: avrDiscovery,
73
+ availabilityTopic: (area) => receiverTopic(area, "availability"),
74
+ stateTopics: (config) => FIELDS.map((field) => receiverTopic(config.area, field + "/state")),
75
+ stateOutputs: (config, observed) => avrStateOutputs(config, observed)
76
+ });
77
+ exports.avrStartingOutputs = receiver.starting;
78
+ exports.avrStoppingOutputs = receiver.stopping;
79
+ exports.avrRetainedTopics = receiver.retainedTopics;
80
+ //# sourceMappingURL=avr-publishing.js.map
@@ -37,6 +37,7 @@ export interface BacklightingState {
37
37
  blockedGeneration: number | null;
38
38
  classification: "manual_override" | null;
39
39
  lastAttempt: number;
40
+ adoptedGeneration: number | null;
40
41
  }
41
42
  export type BacklightingEvent = {
42
43
  kind: "intent";
@@ -58,7 +59,12 @@ export type BacklightingEvent = {
58
59
  kind: "tick";
59
60
  generation: number;
60
61
  } | {
61
- kind: "startup" | "refresh";
62
+ kind: "startup";
63
+ } | {
64
+ kind: "refresh";
65
+ requestId?: string | null;
66
+ generation?: number;
67
+ power?: string;
62
68
  };
63
69
  export interface BacklightingMessage {
64
70
  backlighting?: BacklightingEvent;
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.normaliseBacklightingConfig = normaliseBacklightingConfig;
4
4
  exports.transitionBacklighting = transitionBacklighting;
5
+ const adopted_request_1 = require("./adopted-request");
5
6
  const settings_1 = require("./settings");
6
7
  const observation_time_1 = require("./observation-time");
7
8
  const target_state_1 = require("./target-state");
@@ -25,7 +26,8 @@ function initialState(saved = {}) {
25
26
  classification: saved.classification === "manual_override" ? "manual_override" : null,
26
27
  lastAttempt: Number.isInteger(saved.lastAttempt) && (saved.lastAttempt ?? -1) >= 0
27
28
  ? saved.lastAttempt
28
- : 0
29
+ : 0,
30
+ adoptedGeneration: (0, adopted_request_1.savedAdoptedGeneration)(saved)
29
31
  };
30
32
  }
31
33
  function commandFor(state, operation, attempt) {
@@ -152,11 +154,13 @@ function transitionBacklighting(saved, msg, suppliedConfig = {}, nowValue = new
152
154
  state.phase = "ready";
153
155
  trace("observation", "ready", null, { power: observation.power });
154
156
  }
155
- else if (wasReady) {
157
+ else if (wasReady || (0, adopted_request_1.isAdopted)(state)) {
158
+ // A change seen after ready, or an adopted request the device doesn't
159
+ // match: someone else's, and never corrected.
156
160
  state.pending = null;
157
161
  state.classification = "manual_override";
158
162
  state.phase = "manual_override";
159
- trace("observation", "manual_override", null, {
163
+ trace("observation", "manual_override", wasReady ? null : adopted_request_1.ADOPTED_MISMATCH, {
160
164
  expected: state.desired.power,
161
165
  observed: observation.power
162
166
  });
@@ -173,6 +177,16 @@ function transitionBacklighting(saved, msg, suppliedConfig = {}, nowValue = new
173
177
  });
174
178
  }
175
179
  }
180
+ // A refresh with the activity's wanted values, reaching a node with
181
+ // nothing desired (it started with nothing saved): adopt them, and observe
182
+ // below as at startup (see adopted-request.ts).
183
+ const adoptable = event.kind === "refresh" ? (0, adopted_request_1.adoptableRefresh)(event, state) : null;
184
+ if (adoptable && event.kind === "refresh" && typeof event.power === "string" && Object.hasOwn(POWERS, event.power)) {
185
+ state.desired = { ...adoptable, power: event.power, requestedAt: now.toISOString() };
186
+ state.generation = adoptable.generation;
187
+ state.adoptedGeneration = adoptable.generation;
188
+ trace("refresh", "adopted", "nothing-desired", { power: event.power, generation: adoptable.generation });
189
+ }
176
190
  if (event.kind === "intent") {
177
191
  acceptIntent(event);
178
192
  }
@@ -235,6 +249,15 @@ function transitionBacklighting(saved, msg, suppliedConfig = {}, nowValue = new
235
249
  else {
236
250
  throw new Error("unknown backlighting event kind");
237
251
  }
252
+ // An adopted request only reads the device (see adopted-request.ts).
253
+ const held = (0, adopted_request_1.readsOnly)(state, commands, (command) => command.operation === "observe");
254
+ if (held.mismatch) {
255
+ commands.splice(0, commands.length, ...held.commands);
256
+ state.pending = null;
257
+ state.classification = "manual_override";
258
+ state.phase = "manual_override";
259
+ trace("command", "withheld", adopted_request_1.ADOPTED_MISMATCH);
260
+ }
238
261
  if (state.desired) {
239
262
  const theatre = (0, target_state_1.targetStateEvent)({
240
263
  target: "backlighting",
@@ -2,5 +2,6 @@ import { type DaySchedule } from "./circadian-schedule";
2
2
  import { type LightLevels, type LightStyle } from "./light-styling";
3
3
  export interface CircadianLighting {
4
4
  styleAt(now: Date, sleeping: boolean): LightStyle;
5
+ withSchedule(schedule: DaySchedule): CircadianLighting;
5
6
  }
6
7
  export declare function scheduledLighting(schedule: DaySchedule, levels: LightLevels): CircadianLighting;
@@ -9,6 +9,9 @@ function scheduledLighting(schedule, levels) {
9
9
  return {
10
10
  styleAt(now, sleeping) {
11
11
  return (0, light_styling_1.styleAtLevel)(sleeping ? 0 : (0, circadian_schedule_1.scheduleLevel)(now, schedule.wakeTime, schedule.bedTime), levels);
12
+ },
13
+ withSchedule(next) {
14
+ return scheduledLighting(next, levels);
12
15
  }
13
16
  };
14
17
  }
@@ -0,0 +1,7 @@
1
+ export interface CoverAvailability {
2
+ available: boolean;
3
+ phase: string;
4
+ phaseBeforeUnavailable: string | null;
5
+ pending: unknown;
6
+ }
7
+ export declare function applyCoverAvailability(state: CoverAvailability, online: unknown): "offline" | "online" | null;
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.applyCoverAvailability = applyCoverAvailability;
4
+ // Applies a change of availability; says which way it went, or null when it
5
+ // was no change. The caller clears what it observed and re-reads on "online".
6
+ function applyCoverAvailability(state, online) {
7
+ if (online !== true && online !== false)
8
+ throw new Error("cover availability online must be true or false");
9
+ if (!online && state.available) {
10
+ state.available = false;
11
+ state.phaseBeforeUnavailable = state.phase;
12
+ state.pending = null;
13
+ state.phase = "unavailable";
14
+ return "offline";
15
+ }
16
+ if (online && !state.available) {
17
+ state.available = true;
18
+ state.phase = state.phaseBeforeUnavailable ?? "idle";
19
+ state.phaseBeforeUnavailable = null;
20
+ return "online";
21
+ }
22
+ return null;
23
+ }
24
+ //# sourceMappingURL=cover-availability.js.map
@@ -22,6 +22,8 @@ export interface CoverObservation {
22
22
  position: number;
23
23
  motion: CoverMotion | null;
24
24
  observedAt: string;
25
+ battery?: number | null;
26
+ charging?: string | null;
25
27
  }
26
28
  export interface CoverPending {
27
29
  operation: CoverOperation;
@@ -50,12 +52,15 @@ export interface CoverState {
50
52
  blockedGeneration: number | null;
51
53
  classification: "manual_override" | null;
52
54
  lastAttempt: number;
55
+ available: boolean;
56
+ phaseBeforeUnavailable: string | null;
53
57
  }
54
58
  interface IntentBase {
55
59
  requestId: string;
56
60
  generation: number;
57
61
  source?: string;
58
62
  requestedAt?: string;
63
+ respectManual?: boolean;
59
64
  }
60
65
  export type CoverEvent = (IntentBase & {
61
66
  kind: "set_position";
@@ -67,11 +72,16 @@ export type CoverEvent = (IntentBase & {
67
72
  position: number;
68
73
  motion?: CoverMotion;
69
74
  observedAt: string;
75
+ battery?: number;
76
+ charging?: string;
70
77
  } | {
71
78
  kind: "command_result";
72
79
  generation: number;
73
80
  ok: boolean;
74
81
  reason?: string;
82
+ } | {
83
+ kind: "availability";
84
+ online: boolean;
75
85
  } | {
76
86
  kind: "tick";
77
87
  generation: number;
@@ -103,7 +113,8 @@ export interface CoverOutputEvent {
103
113
  };
104
114
  }, CoverFailure>;
105
115
  }
106
- export declare function normaliseCoverConfig(config?: Partial<CoverConfig>): CoverConfig;
116
+ export declare function normaliseCoverConfig(config?: Partial<Record<keyof CoverConfig, unknown>>): CoverConfig;
117
+ export declare function coverMoving(state: Pick<CoverState, "observed" | "phase">): boolean;
107
118
  export declare function transitionCover(saved: Partial<CoverState> | undefined, msg: CoverMessage, suppliedConfig?: Partial<CoverConfig>, nowValue?: Date | string | number): {
108
119
  state: CoverState;
109
120
  commands: CoverCommand[];
@@ -112,6 +123,7 @@ export declare function transitionCover(saved: Partial<CoverState> | undefined,
112
123
  status: {
113
124
  phase: string;
114
125
  text: string;
126
+ moving: boolean;
115
127
  };
116
128
  };
117
129
  export {};
@@ -1,20 +1,25 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.normaliseCoverConfig = normaliseCoverConfig;
4
+ exports.coverMoving = coverMoving;
4
5
  exports.transitionCover = transitionCover;
6
+ const cover_availability_1 = require("./cover-availability");
5
7
  const observation_time_1 = require("./observation-time");
8
+ const settings_1 = require("./settings");
6
9
  const target_state_1 = require("./target-state");
7
10
  const MOTIONS = { opening: true, closing: true, stopped: true };
8
11
  function normaliseCoverConfig(config = {}) {
9
- const tolerance = Number(config.positionTolerance);
10
- const pollMs = Math.max(250, Number(config.pollMs) || 5000);
12
+ const tolerance = (0, settings_1.numberSetting)(config.positionTolerance, "position tolerance", 2);
13
+ if (tolerance < 0)
14
+ throw new Error("position tolerance must not be negative");
15
+ const pollMs = Math.max(250, (0, settings_1.numberSetting)(config.pollMs, "poll interval", 5000));
11
16
  return {
12
- positionTolerance: Number.isFinite(tolerance) && tolerance >= 0 ? Math.min(tolerance, 50) : 2,
13
- invert: config.invert === true,
14
- travelTimeoutMs: Math.max(1000, Number(config.travelTimeoutMs) || 90000),
15
- maxAttempts: Math.max(1, Math.floor(Number(config.maxAttempts) || 2)),
17
+ positionTolerance: Math.min(tolerance, 50),
18
+ invert: (0, settings_1.booleanSetting)(config.invert, "invert", false),
19
+ travelTimeoutMs: Math.max(1000, (0, settings_1.numberSetting)(config.travelTimeoutMs, "travel timeout", 90000)),
20
+ maxAttempts: Math.max(1, Math.floor((0, settings_1.numberSetting)(config.maxAttempts, "maximum attempts", 2))),
16
21
  pollMs,
17
- settleMs: Math.max(250, Number(config.settleMs) || pollMs)
22
+ settleMs: Math.max(250, (0, settings_1.numberSetting)(config.settleMs, "settle time", pollMs))
18
23
  };
19
24
  }
20
25
  function initialState(saved = {}) {
@@ -27,7 +32,9 @@ function initialState(saved = {}) {
27
32
  failure: saved.failure && typeof saved.failure === "object" ? { ...saved.failure } : null,
28
33
  blockedGeneration: Number.isInteger(saved.blockedGeneration) ? saved.blockedGeneration : null,
29
34
  classification: saved.classification === "manual_override" ? "manual_override" : null,
30
- lastAttempt: Number.isInteger(saved.lastAttempt) && (saved.lastAttempt ?? -1) >= 0 ? saved.lastAttempt : 0
35
+ lastAttempt: Number.isInteger(saved.lastAttempt) && (saved.lastAttempt ?? -1) >= 0 ? saved.lastAttempt : 0,
36
+ available: saved.available !== false,
37
+ phaseBeforeUnavailable: typeof saved.phaseBeforeUnavailable === "string" ? saved.phaseBeforeUnavailable : null
31
38
  };
32
39
  }
33
40
  function validPosition(value, label) {
@@ -36,11 +43,19 @@ function validPosition(value, label) {
36
43
  }
37
44
  return value;
38
45
  }
46
+ // Whether the cover is moving: as the device reports it, or, from a device
47
+ // without motion reports, while a move or stop it was sent is unconfirmed.
48
+ function coverMoving(state) {
49
+ const motion = state.observed?.motion ?? null;
50
+ if (motion !== null)
51
+ return motion !== "stopped";
52
+ return state.phase === "moving" || state.phase === "stopping";
53
+ }
39
54
  function statusFor(state) {
40
55
  const target = state.desired?.operation === "stop" && state.desired.position === null
41
56
  ? "stop"
42
57
  : state.desired?.position ?? "none";
43
- return { phase: state.phase, text: `${target}: ${state.phase}` };
58
+ return { phase: state.phase, text: `${target}: ${state.phase}`, moving: coverMoving(state) };
44
59
  }
45
60
  function transitionCover(saved, msg, suppliedConfig = {}, nowValue = new Date()) {
46
61
  const config = normaliseCoverConfig(suppliedConfig);
@@ -112,7 +127,64 @@ function transitionCover(saved, msg, suppliedConfig = {}, nowValue = new Date())
112
127
  state.phase = "ready";
113
128
  trace("observation", "ready", null, { position });
114
129
  }
130
+ // A request not carried out: nothing is sent, the request is answered
131
+ // with why (unavailable while offline, failed otherwise), and what the
132
+ // cover was doing before is kept.
133
+ function rejectRequest(intent, reason) {
134
+ const position = intent.kind === "set_position" ? intent.position : intent.kind === "open" ? 100 : intent.kind === "close" ? 0 : null;
135
+ const operation = position === null ? "stop" : "set_position";
136
+ events.push({ theatre: {
137
+ kind: "target_state",
138
+ target: "cover",
139
+ requestId: intent.requestId,
140
+ generation: intent.generation,
141
+ status: reason === "unavailable" ? "unavailable" : "failed",
142
+ observedAt: now.toISOString(),
143
+ details: {
144
+ operation,
145
+ position,
146
+ observedPosition: null,
147
+ motion: null,
148
+ source: typeof intent.source === "string" && intent.source ? intent.source : null,
149
+ recovery: {},
150
+ metrics: { attempts: 0, retries: 0, fallbackUsed: false }
151
+ },
152
+ failure: { operation, reason, occurredAt: now.toISOString() }
153
+ } });
154
+ trace("intent", "rejected", reason, { kind: intent.kind });
155
+ }
156
+ // Read the cover again rather than trust what it reported before: after a
157
+ // restart, or when it is back online.
158
+ function reobserve(reason) {
159
+ state.observed = null;
160
+ if (!state.desired) {
161
+ state.pending = null;
162
+ trace(reason, "idle");
163
+ }
164
+ else if (state.phase === "failed") {
165
+ state.pending = null;
166
+ trace(reason, "blocked", "failed");
167
+ }
168
+ else if (state.classification === "manual_override") {
169
+ state.pending = null;
170
+ emit("observe", 0);
171
+ trace(reason, "observing", "manual_override");
172
+ }
173
+ else {
174
+ const verifying = state.phase === "ready" && !state.pending;
175
+ issue("observe", 0, verifying);
176
+ trace(reason, "observing", null, { position: state.desired.position, verifying });
177
+ }
178
+ }
115
179
  function acceptIntent(intent) {
180
+ if (!state.available) {
181
+ rejectRequest(intent, "unavailable");
182
+ return;
183
+ }
184
+ if (intent.respectManual === true && state.classification === "manual_override") {
185
+ rejectRequest(intent, "manual-hold");
186
+ return;
187
+ }
116
188
  if (typeof intent.requestId !== "string" || !intent.requestId)
117
189
  throw new Error("cover requestId is required");
118
190
  if (!Number.isInteger(intent.generation) || intent.generation < 1) {
@@ -146,6 +218,16 @@ function transitionCover(saved, msg, suppliedConfig = {}, nowValue = new Date())
146
218
  state.blockedGeneration = null;
147
219
  state.classification = null;
148
220
  state.lastAttempt = 0;
221
+ // Already there and still: confirmed from what the cover reported since
222
+ // the last start, with nothing to send.
223
+ const observed = state.observed;
224
+ if (position !== null && observed && observed.motion !== "opening" && observed.motion !== "closing" &&
225
+ Math.abs(observed.position - position) <= config.positionTolerance) {
226
+ state.pending = null;
227
+ trace("intent", "accepted", "already-there", { kind: intent.kind, position, generation: intent.generation });
228
+ ready(position);
229
+ return;
230
+ }
149
231
  issue(state.desired.operation, 1);
150
232
  trace("intent", "accepted", null, { kind: intent.kind, position, generation: intent.generation });
151
233
  }
@@ -169,7 +251,13 @@ function transitionCover(saved, msg, suppliedConfig = {}, nowValue = new Date())
169
251
  const position = config.invert ? 100 - devicePosition : devicePosition;
170
252
  const motion = observation.motion ?? null;
171
253
  const previous = state.observed;
172
- state.observed = { position, motion, observedAt: bounded.observedAt };
254
+ state.observed = {
255
+ position,
256
+ motion,
257
+ observedAt: bounded.observedAt,
258
+ battery: typeof observation.battery === "number" && Number.isFinite(observation.battery) ? observation.battery : previous?.battery ?? null,
259
+ charging: typeof observation.charging === "string" ? observation.charging : previous?.charging ?? null
260
+ };
173
261
  if (!state.desired)
174
262
  return;
175
263
  const pending = state.pending;
@@ -276,26 +364,21 @@ function transitionCover(saved, msg, suppliedConfig = {}, nowValue = new Date())
276
364
  state.pending.nextAt = nowMs + config.pollMs;
277
365
  }
278
366
  }
367
+ else if (event.kind === "availability") {
368
+ const change = (0, cover_availability_1.applyCoverAvailability)(state, event.online);
369
+ if (change === "offline")
370
+ state.observed = null;
371
+ if (change)
372
+ trace("availability", change);
373
+ if (change === "online")
374
+ reobserve("online");
375
+ }
376
+ else if (!state.available) {
377
+ // Offline: nothing to observe or retry until it is back.
378
+ trace(event.kind, "ignored", "unavailable");
379
+ }
279
380
  else if (event.kind === "startup" || event.kind === "refresh") {
280
- state.observed = null;
281
- if (!state.desired) {
282
- state.pending = null;
283
- trace(event.kind, "idle");
284
- }
285
- else if (state.phase === "failed") {
286
- state.pending = null;
287
- trace(event.kind, "blocked", "failed");
288
- }
289
- else if (state.classification === "manual_override") {
290
- state.pending = null;
291
- emit("observe", 0);
292
- trace(event.kind, "observing", "manual_override");
293
- }
294
- else {
295
- const verifying = state.phase === "ready" && !state.pending;
296
- issue("observe", 0, verifying);
297
- trace(event.kind, "observing", null, { position: state.desired.position, verifying });
298
- }
381
+ reobserve(event.kind);
299
382
  }
300
383
  else {
301
384
  throw new Error("unknown cover event kind");
@@ -307,7 +390,7 @@ function transitionCover(saved, msg, suppliedConfig = {}, nowValue = new Date())
307
390
  generation: state.generation,
308
391
  // Theatre target statuses: cover phases moving/stopping/manual_override
309
392
  // are all "transitioning" there.
310
- status: state.phase === "failed" || state.phase === "ready" || state.phase === "confirming"
393
+ status: state.phase === "failed" || state.phase === "ready" || state.phase === "confirming" || state.phase === "unavailable"
311
394
  ? state.phase
312
395
  : "transitioning",
313
396
  observedAt: now.toISOString(),
@@ -0,0 +1,62 @@
1
+ import type { TargetStatus } from "./target-state";
2
+ import { type TargetStateEvent } from "./target-state";
3
+ export declare function coverGroupMembers(value: unknown): string[];
4
+ type MemberOutcome = TargetStatus | "manual_override";
5
+ export declare const DEFAULT_GROUP_DEADLINE_SECONDS = 120;
6
+ export interface CoverGroupState {
7
+ request: {
8
+ requestId: string;
9
+ generation: number;
10
+ payload: unknown;
11
+ deadlineAt: number;
12
+ settled: boolean;
13
+ members: Record<string, {
14
+ requestId: string;
15
+ outcome: MemberOutcome;
16
+ reason: string | null;
17
+ }>;
18
+ } | null;
19
+ generation: number;
20
+ }
21
+ export type CoverGroupEvent = {
22
+ kind: "request";
23
+ payload: unknown;
24
+ stopIfMoving?: boolean;
25
+ respectManual?: boolean;
26
+ source?: string;
27
+ } | {
28
+ kind: "member";
29
+ requestId: string;
30
+ status: string;
31
+ classification?: string;
32
+ reason?: string | null;
33
+ } | {
34
+ kind: "tick";
35
+ };
36
+ export interface CoverGroupCommand {
37
+ topic: string;
38
+ payload: unknown;
39
+ coverRequestId: string;
40
+ stopIfMoving?: boolean;
41
+ respectManual?: boolean;
42
+ source?: string;
43
+ }
44
+ export declare function transitionCoverGroup(saved: Partial<CoverGroupState> | undefined, event: CoverGroupEvent, members: string[], now: Date, deadlineSeconds?: number): {
45
+ state: CoverGroupState;
46
+ commands: CoverGroupCommand[];
47
+ events: {
48
+ theatre: TargetStateEvent<"cover", Record<string, unknown>>;
49
+ }[];
50
+ traces: {
51
+ event: string;
52
+ outcome: string;
53
+ reason: string | null;
54
+ details: Record<string, unknown>;
55
+ }[];
56
+ status: {
57
+ text: string;
58
+ ready: number;
59
+ total: number;
60
+ };
61
+ };
62
+ export {};