@avantics/node-red-home-automation 4.0.3 → 6.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 (116) hide show
  1. package/README.md +447 -64
  2. package/contract-examples/room-lighting.mjs +39 -27
  3. package/contract-examples/switch-gestures.mjs +1 -1
  4. package/contract-examples/volume-ownership.mjs +6 -5
  5. package/dist/lib/activity-lighting-controller.d.ts +9 -2
  6. package/dist/lib/activity-lighting-controller.js +107 -19
  7. package/dist/lib/adopted-request.d.ts +17 -0
  8. package/dist/lib/adopted-request.js +61 -7
  9. package/dist/lib/avr-controller.d.ts +9 -3
  10. package/dist/lib/avr-controller.js +71 -24
  11. package/dist/lib/avr-publishing.d.ts +3 -3
  12. package/dist/lib/avr-publishing.js +11 -5
  13. package/dist/lib/backlighting-controller.d.ts +2 -0
  14. package/dist/lib/backlighting-controller.js +27 -7
  15. package/dist/lib/circadian-policy.d.ts +47 -0
  16. package/dist/lib/circadian-policy.js +111 -0
  17. package/dist/lib/circadian-publishing.d.ts +33 -0
  18. package/dist/lib/circadian-publishing.js +154 -0
  19. package/dist/lib/circadian-schedule.d.ts +4 -0
  20. package/dist/lib/circadian-schedule.js +12 -0
  21. package/dist/lib/command-echo.d.ts +8 -1
  22. package/dist/lib/command-echo.js +37 -6
  23. package/dist/lib/cover-controller.js +4 -0
  24. package/dist/lib/cover-publishing.js +1 -1
  25. package/dist/lib/denon-protocol.d.ts +5 -1
  26. package/dist/lib/denon-protocol.js +27 -11
  27. package/dist/lib/display-mode-controller.d.ts +12 -5
  28. package/dist/lib/display-mode-controller.js +181 -87
  29. package/dist/lib/enable-input.d.ts +3 -0
  30. package/dist/lib/enable-input.js +18 -0
  31. package/dist/lib/house-schedule-publishing.js +1 -1
  32. package/dist/lib/house-schedule.js +2 -2
  33. package/dist/lib/light-contract.d.ts +53 -0
  34. package/dist/lib/light-contract.js +11 -0
  35. package/dist/lib/light-styling.d.ts +2 -2
  36. package/dist/lib/light-styling.js +5 -4
  37. package/dist/lib/motion-policy.d.ts +0 -1
  38. package/dist/lib/motion-policy.js +9 -8
  39. package/dist/lib/motion-publishing.js +3 -2
  40. package/dist/lib/mqtt-message.d.ts +6 -0
  41. package/dist/lib/mqtt-message.js +21 -0
  42. package/dist/lib/occupancy-publishing.js +1 -1
  43. package/dist/lib/power-reading.d.ts +5 -0
  44. package/dist/lib/power-reading.js +13 -0
  45. package/dist/lib/room-controller.d.ts +39 -29
  46. package/dist/lib/room-controller.js +314 -192
  47. package/dist/lib/room-lighting-discovery.d.ts +0 -14
  48. package/dist/lib/room-lighting-discovery.js +20 -126
  49. package/dist/lib/room-publishing.d.ts +10 -12
  50. package/dist/lib/room-publishing.js +65 -125
  51. package/dist/lib/shelly-cover.d.ts +44 -0
  52. package/dist/lib/shelly-cover.js +153 -0
  53. package/dist/lib/shelly-gen2.d.ts +25 -0
  54. package/dist/lib/shelly-gen2.js +58 -0
  55. package/dist/lib/shelly-switch.d.ts +95 -0
  56. package/dist/lib/shelly-switch.js +237 -0
  57. package/dist/lib/source-capability-controller.d.ts +2 -0
  58. package/dist/lib/source-capability-controller.js +27 -6
  59. package/dist/lib/switch-policy.d.ts +1 -1
  60. package/dist/lib/switch-policy.js +1 -1
  61. package/dist/lib/theatre-requests.d.ts +29 -0
  62. package/dist/lib/theatre-requests.js +89 -0
  63. package/dist/lib/theatre-state-contract.d.ts +5 -22
  64. package/dist/lib/theatre-state-contract.js +30 -77
  65. package/dist/lib/toggle-power.d.ts +41 -0
  66. package/dist/lib/toggle-power.js +74 -0
  67. package/dist/lib/topic-names.d.ts +1 -0
  68. package/dist/lib/topic-names.js +7 -0
  69. package/dist/lib/{display-transport.d.ts → transports/display-transport.d.ts} +1 -1
  70. package/dist/lib/{display-transport.js → transports/display-transport.js} +32 -7
  71. package/dist/lib/z2m-cover.d.ts +49 -0
  72. package/dist/lib/z2m-cover.js +120 -0
  73. package/dist/lib/z2m-light-adapter.d.ts +62 -0
  74. package/dist/lib/z2m-light-adapter.js +195 -0
  75. package/dist/lib/z2m-light.d.ts +8 -0
  76. package/dist/lib/z2m-light.js +61 -3
  77. package/dist/nodes/activity-lighting-controller.html +20 -3
  78. package/dist/nodes/activity-lighting-controller.js +21 -0
  79. package/dist/nodes/avr-controller.html +25 -6
  80. package/dist/nodes/avr-controller.js +16 -6
  81. package/dist/nodes/circadian-policy.d.ts +3 -0
  82. package/dist/nodes/circadian-policy.html +140 -0
  83. package/dist/nodes/circadian-policy.js +162 -0
  84. package/dist/nodes/cover-controller.html +4 -3
  85. package/dist/nodes/display-mode-controller.html +58 -11
  86. package/dist/nodes/display-mode-controller.js +19 -6
  87. package/dist/nodes/house-schedule.html +3 -3
  88. package/dist/nodes/motion-policy.html +5 -2
  89. package/dist/nodes/motion-policy.js +3 -0
  90. package/dist/nodes/refused-enable.d.ts +7 -0
  91. package/dist/nodes/refused-enable.js +24 -0
  92. package/dist/nodes/room-controller.html +215 -82
  93. package/dist/nodes/room-controller.js +71 -83
  94. package/dist/nodes/shelly-cover.d.ts +3 -0
  95. package/dist/nodes/shelly-cover.html +65 -0
  96. package/dist/nodes/shelly-cover.js +34 -0
  97. package/dist/nodes/shelly-switch.d.ts +3 -0
  98. package/dist/nodes/shelly-switch.html +82 -0
  99. package/dist/nodes/shelly-switch.js +48 -0
  100. package/dist/nodes/theatre-state-contract.html +4 -3
  101. package/dist/nodes/z2m-cover.d.ts +3 -0
  102. package/dist/nodes/z2m-cover.html +68 -0
  103. package/dist/nodes/z2m-cover.js +41 -0
  104. package/dist/nodes/z2m-light.d.ts +3 -0
  105. package/dist/nodes/z2m-light.html +72 -0
  106. package/dist/nodes/z2m-light.js +50 -0
  107. package/examples/Cover control.json +24 -56
  108. package/examples/Home theatre activity.json +54 -9
  109. package/examples/Home theatre equipment.json +4 -4
  110. package/examples/House schedule.json +106 -24
  111. package/examples/Room lighting.json +54 -11
  112. package/examples/Shelly cover.json +252 -0
  113. package/examples/Shelly switch.json +197 -0
  114. package/package.json +13 -4
  115. package/dist/lib/room-schedule.d.ts +0 -8
  116. package/dist/lib/room-schedule.js +0 -41
@@ -24,7 +24,7 @@ export interface SwitchLightingIntent {
24
24
  person: true;
25
25
  manual?: boolean;
26
26
  values?: {
27
- brightness: number;
27
+ brightnessPct: number;
28
28
  };
29
29
  };
30
30
  }
@@ -23,7 +23,7 @@ function intent(targets, state, manual = false) {
23
23
  state,
24
24
  source: "wall",
25
25
  person: true,
26
- ...(manual ? { manual: true, values: { brightness: 254 } } : {})
26
+ ...(manual ? { manual: true, values: { brightnessPct: 100 } } : {})
27
27
  }
28
28
  };
29
29
  }
@@ -0,0 +1,29 @@
1
+ import type { TheatreTarget } from "./theatre-profiles";
2
+ import type { TheatreMetrics, TheatreSnapshot } from "./theatre-state";
3
+ import { type TheatreSloAssessment, type TheatreSloConfig, type TheatreSloState } from "./theatre-slo";
4
+ export interface ContractRequest {
5
+ requestId: string;
6
+ generation: number;
7
+ activity: string;
8
+ requestedAt: string;
9
+ }
10
+ export interface TheatreRequestState {
11
+ generation: number;
12
+ lastRequest: ContractRequest | null;
13
+ slo: TheatreSloState;
14
+ }
15
+ export type TheatreStateSnapshot = Omit<TheatreSnapshot, "availability" | "targets" | "failure" | "degraded" | "metrics"> & {
16
+ availability: string;
17
+ targets: Partial<Record<TheatreTarget, Record<string, unknown> | null>>;
18
+ failure: Record<string, unknown> | null;
19
+ degraded: Array<Record<string, unknown>>;
20
+ metrics?: TheatreMetrics;
21
+ };
22
+ export declare function createTheatreRequestState(saved?: Partial<TheatreRequestState>): TheatreRequestState;
23
+ export declare function takeTheatreRequest(state: TheatreRequestState, request: {
24
+ requestId?: unknown;
25
+ activity?: unknown;
26
+ requestedAt?: unknown;
27
+ }, activities: string[], now: Date): "accepted" | "duplicate";
28
+ export declare function asTheatreSnapshot(value: unknown): TheatreStateSnapshot;
29
+ export declare function takeTheatreSnapshot(state: TheatreRequestState, event: TheatreStateSnapshot, sloConfig: TheatreSloConfig, now: Date): TheatreSloAssessment | null;
@@ -0,0 +1,89 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createTheatreRequestState = createTheatreRequestState;
4
+ exports.takeTheatreRequest = takeTheatreRequest;
5
+ exports.asTheatreSnapshot = asTheatreSnapshot;
6
+ exports.takeTheatreSnapshot = takeTheatreSnapshot;
7
+ const theatre_slo_1 = require("./theatre-slo");
8
+ const topic_names_1 = require("./topic-names");
9
+ function createTheatreRequestState(saved = {}) {
10
+ const lastRequest = saved.lastRequest && typeof saved.lastRequest === "object"
11
+ ? { ...saved.lastRequest }
12
+ : null;
13
+ return {
14
+ generation: Number.isInteger(saved.generation) && (saved.generation ?? -1) >= 0
15
+ ? saved.generation
16
+ : 0,
17
+ lastRequest,
18
+ slo: {
19
+ samples: Array.isArray(saved.slo?.samples) ? saved.slo.samples.map((sample) => ({ ...sample })) : []
20
+ }
21
+ };
22
+ }
23
+ function validTimestamp(value, fallback) {
24
+ const timestamp = value === undefined ? fallback : String(value);
25
+ if (!Number.isFinite(Date.parse(timestamp)))
26
+ throw new Error("requestedAt must be an ISO timestamp");
27
+ return timestamp;
28
+ }
29
+ // An activity request: a new one takes the next generation; the same
30
+ // request again is passed on as it was. An invalid one is an error.
31
+ function takeTheatreRequest(state, request, activities, now) {
32
+ const requestId = String(request.requestId || "");
33
+ const activity = String(request.activity || "");
34
+ if (!topic_names_1.REQUEST_ID.test(requestId))
35
+ throw new Error("requestId is invalid");
36
+ if (!activities.includes(activity))
37
+ throw new Error("unknown theatre activity");
38
+ const requestedAt = validTimestamp(request.requestedAt, now.toISOString());
39
+ if (state.lastRequest?.requestId === requestId) {
40
+ if (state.lastRequest.activity !== activity) {
41
+ throw new Error("requestId cannot be reused for another activity");
42
+ }
43
+ return "duplicate";
44
+ }
45
+ state.generation += 1;
46
+ state.lastRequest = { requestId, generation: state.generation, activity, requestedAt };
47
+ return "accepted";
48
+ }
49
+ // The activity controller's snapshot, checked for the fields the contract
50
+ // relies on.
51
+ function asTheatreSnapshot(value) {
52
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
53
+ throw new Error("theatre state must be an object");
54
+ }
55
+ const event = value;
56
+ if (event.kind !== "state")
57
+ throw new Error("theatre state kind must be state");
58
+ if (!Number.isInteger(event.generation) || (event.generation ?? -1) < 0) {
59
+ throw new Error("theatre state generation must be a non-negative integer");
60
+ }
61
+ if (typeof event.currentActivity !== "string" || typeof event.phase !== "string" ||
62
+ typeof event.availability !== "string") {
63
+ throw new Error("theatre state must define currentActivity, phase and availability");
64
+ }
65
+ if (!event.targets || typeof event.targets !== "object" || Array.isArray(event.targets)) {
66
+ throw new Error("theatre state targets must be an object");
67
+ }
68
+ return event;
69
+ }
70
+ // A snapshot older than the request in hand is stale; a current one
71
+ // becomes the request in hand and a sample for the SLO, whose assessment
72
+ // it returns.
73
+ function takeTheatreSnapshot(state, event, sloConfig, now) {
74
+ if (event.generation < state.generation)
75
+ return null;
76
+ state.generation = event.generation;
77
+ if (event.requestId && event.desiredActivity) {
78
+ state.lastRequest = {
79
+ requestId: event.requestId,
80
+ generation: event.generation,
81
+ activity: event.desiredActivity,
82
+ requestedAt: event.requestedAt || event.transitionStartedAt || now.toISOString()
83
+ };
84
+ }
85
+ const slo = (0, theatre_slo_1.evaluateTheatreSlo)(state.slo, event, sloConfig, now);
86
+ state.slo = slo.state;
87
+ return slo.assessment;
88
+ }
89
+ //# sourceMappingURL=theatre-requests.js.map
@@ -1,8 +1,9 @@
1
- import { type TheatreTarget } from "./theatre-profiles";
2
- import type { TheatreMetrics, TheatreSnapshot } from "./theatre-state";
3
- import { type TheatreSloConfig, type TheatreSloState } from "./theatre-slo";
1
+ import { type TheatreSloConfig } from "./theatre-slo";
2
+ import { type TheatreRequestState, type TheatreStateSnapshot } from "./theatre-requests";
4
3
  import type { TraceEntry } from "./bounded-trace";
5
4
  import { type IdScheme } from "./ha-discovery";
5
+ export type { ContractRequest, TheatreStateSnapshot } from "./theatre-requests";
6
+ export type TheatreStateContractState = TheatreRequestState;
6
7
  export interface TheatreStateContractConfig {
7
8
  nodeId?: string;
8
9
  idScheme?: IdScheme;
@@ -14,24 +15,6 @@ export interface TheatreStateContractConfig {
14
15
  slo: TheatreSloConfig;
15
16
  discovery?: boolean;
16
17
  }
17
- export interface ContractRequest {
18
- requestId: string;
19
- generation: number;
20
- activity: string;
21
- requestedAt: string;
22
- }
23
- export interface TheatreStateContractState {
24
- generation: number;
25
- lastRequest: ContractRequest | null;
26
- slo: TheatreSloState;
27
- }
28
- export type TheatreStateSnapshot = Omit<TheatreSnapshot, "availability" | "targets" | "failure" | "degraded" | "metrics"> & {
29
- availability: string;
30
- targets: Partial<Record<TheatreTarget, Record<string, unknown> | null>>;
31
- failure: Record<string, unknown> | null;
32
- degraded: Array<Record<string, unknown>>;
33
- metrics?: TheatreMetrics;
34
- };
35
18
  export interface TheatreStateContractMessage {
36
19
  topic?: string;
37
20
  payload?: unknown;
@@ -60,7 +43,7 @@ export declare function theatreRetainedTopics(config: TheatreStateContractConfig
60
43
  export declare function theatreStartingPublications(config: TheatreStateContractConfig): ContractPublication[];
61
44
  export declare function theatreStoppingPublications(config: TheatreStateContractConfig): ContractPublication[];
62
45
  export declare function transitionTheatreStateContract(saved: Partial<TheatreStateContractState> | undefined, msg: TheatreStateContractMessage, suppliedConfig: Partial<TheatreStateContractConfig>, nowValue?: Date | string | number): {
63
- state: TheatreStateContractState;
46
+ state: TheatreRequestState;
64
47
  requests: ContractRequestOutput[];
65
48
  publications: ContractPublication[];
66
49
  traces: TraceEntry<Record<string, unknown>>[];
@@ -5,9 +5,14 @@ exports.theatreRetainedTopics = theatreRetainedTopics;
5
5
  exports.theatreStartingPublications = theatreStartingPublications;
6
6
  exports.theatreStoppingPublications = theatreStoppingPublications;
7
7
  exports.transitionTheatreStateContract = transitionTheatreStateContract;
8
+ // The theatre contract's MQTT and Home Assistant side: it reads activity
9
+ // requests from MQTT, publishes what the activity controller reports as
10
+ // retained topics, and announces the Home Assistant entities. What to do
11
+ // with a request or a snapshot is theatre-requests.ts's.
8
12
  const theatre_profiles_1 = require("./theatre-profiles");
9
13
  const theatre_ha_discovery_1 = require("./theatre-ha-discovery");
10
14
  const theatre_slo_1 = require("./theatre-slo");
15
+ const theatre_requests_1 = require("./theatre-requests");
11
16
  const ha_discovery_1 = require("./ha-discovery");
12
17
  const topic_names_1 = require("./topic-names");
13
18
  function normaliseStateContractConfig(config = {}) {
@@ -20,7 +25,7 @@ function normaliseStateContractConfig(config = {}) {
20
25
  const displayName = String(config.displayName || area).trim();
21
26
  if (discovery && !displayName)
22
27
  throw new Error("displayName is required");
23
- const baseTopic = String(config.baseTopic || `home/${(0, topic_names_1.areaId)(area)}/theatre`).replace(/^\/+|\/+$/g, "");
28
+ const baseTopic = String(config.baseTopic || (0, topic_names_1.homeTopic)(area, "theatre")).replace(/^\/+|\/+$/g, "");
24
29
  const discoveryPrefix = (0, ha_discovery_1.discoveryPrefixSetting)(config.discoveryPrefix);
25
30
  if (!baseTopic || /[+#]/.test(baseTopic))
26
31
  throw new Error("baseTopic must be a concrete MQTT topic");
@@ -45,20 +50,6 @@ function normaliseStateContractConfig(config = {}) {
45
50
  ...(config.idScheme ? { idScheme: config.idScheme } : {})
46
51
  };
47
52
  }
48
- function createState(saved = {}) {
49
- const lastRequest = saved.lastRequest && typeof saved.lastRequest === "object"
50
- ? { ...saved.lastRequest }
51
- : null;
52
- return {
53
- generation: Number.isInteger(saved.generation) && (saved.generation ?? -1) >= 0
54
- ? saved.generation
55
- : 0,
56
- lastRequest,
57
- slo: {
58
- samples: Array.isArray(saved.slo?.samples) ? saved.slo.samples.map((sample) => ({ ...sample })) : []
59
- }
60
- };
61
- }
62
53
  function parsePayload(payload) {
63
54
  let value = payload;
64
55
  if (Buffer.isBuffer(value))
@@ -76,12 +67,6 @@ function parsePayload(payload) {
76
67
  }
77
68
  return value;
78
69
  }
79
- function validTimestamp(value, fallback) {
80
- const timestamp = value === undefined ? fallback : String(value);
81
- if (!Number.isFinite(Date.parse(timestamp)))
82
- throw new Error("requestedAt must be an ISO timestamp");
83
- return timestamp;
84
- }
85
70
  function publication(topic, payload) {
86
71
  return {
87
72
  topic,
@@ -158,25 +143,6 @@ function requestPublications(request, config) {
158
143
  publication((0, theatre_ha_discovery_1.theatreTopic)(base, "readiness"), "unknown")
159
144
  ];
160
145
  }
161
- function asStateSnapshot(value) {
162
- if (!value || typeof value !== "object" || Array.isArray(value)) {
163
- throw new Error("theatre state must be an object");
164
- }
165
- const event = value;
166
- if (event.kind !== "state")
167
- throw new Error("theatre state kind must be state");
168
- if (!Number.isInteger(event.generation) || (event.generation ?? -1) < 0) {
169
- throw new Error("theatre state generation must be a non-negative integer");
170
- }
171
- if (typeof event.currentActivity !== "string" || typeof event.phase !== "string" ||
172
- typeof event.availability !== "string") {
173
- throw new Error("theatre state must define currentActivity, phase and availability");
174
- }
175
- if (!event.targets || typeof event.targets !== "object" || Array.isArray(event.targets)) {
176
- throw new Error("theatre state targets must be an object");
177
- }
178
- return event;
179
- }
180
146
  // Every retained topic the contract publishes, for clearing those it no
181
147
  // longer does after a change: discovery entries, whenever they are published
182
148
  // or cleared at each start, its availability, and its state topics.
@@ -186,21 +152,29 @@ function theatreRetainedTopics(config) {
186
152
  : [];
187
153
  return [
188
154
  ...discovery,
189
- ...theatreStartingPublications(config).map(({ topic }) => topic),
155
+ (0, theatre_ha_discovery_1.theatreTopic)(config.baseTopic, "availability"),
190
156
  ...STATE_TOPICS.map(([name]) => (0, theatre_ha_discovery_1.theatreTopic)(config.baseTopic, name))
191
157
  ];
192
158
  }
193
- // What the contract publishes as it starts and as it stops, so Home Assistant
194
- // shows its entities as available only while it runs.
159
+ // What the contract publishes as the flows start and as it stops: with
160
+ // discovery on, its entries, as the other publishing nodes announce theirs,
161
+ // so Home Assistant has them without a startup message; and its
162
+ // availability, so Home Assistant shows its entities as available only while
163
+ // it runs. Removing entries when discovery is off stays with the startup
164
+ // message.
195
165
  function theatreStartingPublications(config) {
196
- return [publication((0, theatre_ha_discovery_1.theatreTopic)(config.baseTopic, "availability"), ha_discovery_1.ONLINE)];
166
+ const entries = config.discovery !== false ? (0, theatre_ha_discovery_1.theatreDiscovery)(config) : [];
167
+ return [
168
+ ...entries.map(({ topic, payload }) => publication(topic, payload)),
169
+ publication((0, theatre_ha_discovery_1.theatreTopic)(config.baseTopic, "availability"), ha_discovery_1.ONLINE)
170
+ ];
197
171
  }
198
172
  function theatreStoppingPublications(config) {
199
173
  return [publication((0, theatre_ha_discovery_1.theatreTopic)(config.baseTopic, "availability"), ha_discovery_1.OFFLINE)];
200
174
  }
201
175
  function transitionTheatreStateContract(saved, msg, suppliedConfig, nowValue = new Date()) {
202
176
  const config = normaliseStateContractConfig(suppliedConfig);
203
- const state = createState(saved);
177
+ const state = (0, theatre_requests_1.createTheatreRequestState)(saved);
204
178
  const now = nowValue instanceof Date ? nowValue : new Date(nowValue);
205
179
  if (!Number.isFinite(now.getTime()))
206
180
  throw new Error("now must be a valid date");
@@ -224,47 +198,26 @@ function transitionTheatreStateContract(saved, msg, suppliedConfig, nowValue = n
224
198
  }
225
199
  else {
226
200
  const payload = parsePayload(msg.payload);
227
- const requestId = String(payload.requestId || "");
228
- const activity = String(payload.activity || "");
229
- if (!topic_names_1.REQUEST_ID.test(requestId))
230
- throw new Error("requestId is invalid");
231
- if (!config.activities.includes(activity))
232
- throw new Error("unknown theatre activity");
233
- const requestedAt = validTimestamp(payload.requestedAt, now.toISOString());
234
- if (state.lastRequest?.requestId === requestId) {
235
- if (state.lastRequest.activity !== activity) {
236
- throw new Error("requestId cannot be reused for another activity");
237
- }
238
- requests.push({ theatre: { kind: "intent", ...state.lastRequest } });
239
- trace("request", "duplicate", null, { requestId, generation: state.lastRequest.generation });
201
+ const outcome = (0, theatre_requests_1.takeTheatreRequest)(state, payload, config.activities, now);
202
+ const request = state.lastRequest;
203
+ requests.push({ theatre: { kind: "intent", ...request } });
204
+ if (outcome === "duplicate") {
205
+ trace("request", "duplicate", null, { requestId: request.requestId, generation: request.generation });
240
206
  }
241
207
  else {
242
- state.generation += 1;
243
- state.lastRequest = { requestId, generation: state.generation, activity, requestedAt };
244
- requests.push({ theatre: { kind: "intent", ...state.lastRequest } });
245
- trace("request", "accepted", null, { requestId, generation: state.generation, activity });
208
+ trace("request", "accepted", null, { requestId: request.requestId, generation: state.generation, activity: request.activity });
246
209
  }
247
- publications.push(...requestPublications(state.lastRequest, config));
210
+ publications.push(...requestPublications(request, config));
248
211
  }
249
212
  }
250
213
  else if (msg.theatre && typeof msg.theatre === "object" && msg.theatre.kind === "state") {
251
- const event = asStateSnapshot(msg.theatre);
252
- if (event.generation < state.generation) {
214
+ const event = (0, theatre_requests_1.asTheatreSnapshot)(msg.theatre);
215
+ const assessment = (0, theatre_requests_1.takeTheatreSnapshot)(state, event, config.slo, now);
216
+ if (!assessment) {
253
217
  trace("state", "ignored", "stale-generation", { generation: event.generation });
254
218
  }
255
219
  else {
256
- state.generation = event.generation;
257
- if (event.requestId && event.desiredActivity) {
258
- state.lastRequest = {
259
- requestId: event.requestId,
260
- generation: event.generation,
261
- activity: event.desiredActivity,
262
- requestedAt: event.requestedAt || event.transitionStartedAt || now.toISOString()
263
- };
264
- }
265
- const slo = (0, theatre_slo_1.evaluateTheatreSlo)(state.slo, event, config.slo, now);
266
- state.slo = slo.state;
267
- publications.push(...statePublications(event, config, slo.assessment));
220
+ publications.push(...statePublications(event, config, assessment));
268
221
  trace("state", "published", null, {
269
222
  generation: event.generation,
270
223
  phase: event.phase,
@@ -0,0 +1,41 @@
1
+ import type { PowerReading } from "./power-reading";
2
+ export declare const TOGGLE_START = "projector_start";
3
+ export declare const TOGGLE_SETTLE = "projector_settle";
4
+ export declare const TOGGLE_SHUTDOWN_OBSERVE = "projector_shutdown_observe";
5
+ export declare const TOGGLE_SHUTDOWN_CONFIRM = "projector_shutdown_confirm";
6
+ export declare const TOGGLE_COOLDOWN = "projector_cooldown";
7
+ export interface TogglePowerTiming {
8
+ pollMs: number;
9
+ queryTimeoutMs: number;
10
+ warmupMs: number;
11
+ minimumWarmupMs: number;
12
+ shutdownConfirmMs: number;
13
+ cooldownMs: number;
14
+ }
15
+ export interface TogglePending<Device, Command> {
16
+ device: Device;
17
+ operation: string;
18
+ command: Command;
19
+ attempt: number;
20
+ retryable: boolean;
21
+ deadlineAt: number;
22
+ nextAt: number;
23
+ readyAt?: number;
24
+ }
25
+ export declare function togglePowerSatisfied(operation: string, power: PowerReading | undefined): boolean | undefined;
26
+ export declare function startReadyAt(nowMs: number, timing: TogglePowerTiming): number;
27
+ export declare function holdForWarmup(pending: {
28
+ operation: string;
29
+ readyAt?: number;
30
+ deadlineAt: number;
31
+ }, power: PowerReading | undefined, nowMs: number): number | null;
32
+ export declare function shutdownRequestPending<Device, Command>(device: Device, command: Command, nowMs: number, timing: TogglePowerTiming): TogglePending<Device, Command>;
33
+ export declare function beginShutdownConfirm(pending: {
34
+ operation: string;
35
+ nextAt: number;
36
+ deadlineAt: number;
37
+ }, nowMs: number, timing: TogglePowerTiming): void;
38
+ export declare function needsShutdownConfirm(pending: {
39
+ operation: string;
40
+ }, power: PowerReading | undefined): boolean;
41
+ export declare function cooldownPending<Device, Command>(device: Device, command: Command, nowMs: number, timing: TogglePowerTiming): TogglePending<Device, Command>;
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TOGGLE_COOLDOWN = exports.TOGGLE_SHUTDOWN_CONFIRM = exports.TOGGLE_SHUTDOWN_OBSERVE = exports.TOGGLE_SETTLE = exports.TOGGLE_START = void 0;
4
+ exports.togglePowerSatisfied = togglePowerSatisfied;
5
+ exports.startReadyAt = startReadyAt;
6
+ exports.holdForWarmup = holdForWarmup;
7
+ exports.shutdownRequestPending = shutdownRequestPending;
8
+ exports.beginShutdownConfirm = beginShutdownConfirm;
9
+ exports.needsShutdownConfirm = needsShutdownConfirm;
10
+ exports.cooldownPending = cooldownPending;
11
+ exports.TOGGLE_START = "projector_start";
12
+ exports.TOGGLE_SETTLE = "projector_settle";
13
+ exports.TOGGLE_SHUTDOWN_OBSERVE = "projector_shutdown_observe";
14
+ exports.TOGGLE_SHUTDOWN_CONFIRM = "projector_shutdown_confirm";
15
+ exports.TOGGLE_COOLDOWN = "projector_cooldown";
16
+ // Whether a toggle-power step is done, from the reading; undefined for an
17
+ // operation that isn't one of them.
18
+ function togglePowerSatisfied(operation, power) {
19
+ switch (operation) {
20
+ case exports.TOGGLE_START: return power === "on";
21
+ case exports.TOGGLE_SETTLE: return power === "on" || power === "standby";
22
+ case exports.TOGGLE_SHUTDOWN_OBSERVE:
23
+ case exports.TOGGLE_SHUTDOWN_CONFIRM:
24
+ case exports.TOGGLE_COOLDOWN: return power === "standby";
25
+ default: return undefined;
26
+ }
27
+ }
28
+ // When a started lamp may count as on: not before the minimum warm-up.
29
+ function startReadyAt(nowMs, timing) {
30
+ return nowMs + timing.minimumWarmupMs;
31
+ }
32
+ // Reading on during the minimum warm-up: when to look again, or null when
33
+ // the reading may stand.
34
+ function holdForWarmup(pending, power, nowMs) {
35
+ if (pending.operation !== exports.TOGGLE_START || pending.readyAt === undefined || power !== "on" || nowMs >= pending.readyAt)
36
+ return null;
37
+ return Math.min(pending.deadlineAt, pending.readyAt);
38
+ }
39
+ // The shutdown's first toggle: read the meter after shutdownConfirmMs.
40
+ function shutdownRequestPending(device, command, nowMs, timing) {
41
+ return {
42
+ device,
43
+ operation: exports.TOGGLE_SHUTDOWN_OBSERVE,
44
+ command,
45
+ attempt: 1,
46
+ retryable: false,
47
+ deadlineAt: nowMs + timing.shutdownConfirmMs + timing.queryTimeoutMs,
48
+ nextAt: nowMs + timing.shutdownConfirmMs
49
+ };
50
+ }
51
+ // Time to read the meter after the shutdown toggle: the step now waits for
52
+ // that reading, for at most queryTimeoutMs.
53
+ function beginShutdownConfirm(pending, nowMs, timing) {
54
+ pending.operation = exports.TOGGLE_SHUTDOWN_CONFIRM;
55
+ pending.nextAt = nowMs + timing.queryTimeoutMs;
56
+ pending.deadlineAt = pending.nextAt;
57
+ }
58
+ // Still on after the shutdown toggle: it wants the confirming toggle.
59
+ function needsShutdownConfirm(pending, power) {
60
+ return pending.operation === exports.TOGGLE_SHUTDOWN_CONFIRM && power === "on";
61
+ }
62
+ // After the confirming toggle: the cool-down, until it reads standby.
63
+ function cooldownPending(device, command, nowMs, timing) {
64
+ return {
65
+ device,
66
+ operation: exports.TOGGLE_COOLDOWN,
67
+ command,
68
+ attempt: 1,
69
+ retryable: false,
70
+ deadlineAt: nowMs + timing.cooldownMs,
71
+ nextAt: nowMs + timing.pollMs
72
+ };
73
+ }
74
+ //# sourceMappingURL=toggle-power.js.map
@@ -1,4 +1,5 @@
1
1
  export declare const IDENTIFIER: RegExp;
2
2
  export declare function areaId(area: string): string;
3
+ export declare function homeTopic(area: string, ...path: string[]): string;
3
4
  export declare function publishingArea(area: string, needed: boolean): string;
4
5
  export declare const REQUEST_ID: RegExp;
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.REQUEST_ID = exports.IDENTIFIER = void 0;
4
4
  exports.areaId = areaId;
5
+ exports.homeTopic = homeTopic;
5
6
  exports.publishingArea = publishingArea;
6
7
  // How areas and names become parts of MQTT topics and IDs. Shared by every
7
8
  // node that publishes, whether or not Home Assistant reads what it publishes.
@@ -16,6 +17,12 @@ exports.IDENTIFIER = /^[a-z][a-z0-9_-]*$/;
16
17
  function areaId(area) {
17
18
  return area.toLowerCase().replace(/[^a-z0-9_-]+/g, "_").replace(/^[_-]+|[_-]+$/g, "");
18
19
  }
20
+ // The one place a home/<area ID>/... topic is named, for every node that
21
+ // publishes under its area (or, for the house schedule, its name): the rest
22
+ // of the path follows as given.
23
+ function homeTopic(area, ...path) {
24
+ return ["home", areaId(area), ...path].join("/");
25
+ }
19
26
  // The area of a node that publishes under it, as typed. `needed` says
20
27
  // whether this node's publishing needs one at all.
21
28
  function publishingArea(area, needed) {
@@ -1,4 +1,4 @@
1
- import type { DisplayDevice, DisplayMessage } from "./display-mode-controller";
1
+ import type { DisplayDevice, DisplayMessage } from "../display-mode-controller";
2
2
  interface DeviceResponse {
3
3
  error?: unknown;
4
4
  result?: Array<{
@@ -48,6 +48,14 @@ async function responseJson(response, allowNull = false) {
48
48
  }
49
49
  return body;
50
50
  }
51
+ // The Shelly cover's states, as the display reads a screen.
52
+ const SCREEN_STATES = {
53
+ open: "open",
54
+ closed: "closed",
55
+ opening: "opening",
56
+ closing: "closing",
57
+ stopped: "stopped"
58
+ };
51
59
  class DisplayTransport {
52
60
  tvHost;
53
61
  tvPsk;
@@ -61,7 +69,10 @@ class DisplayTransport {
61
69
  if (!this.tvPsk)
62
70
  throw new Error("tvPsk is required");
63
71
  this.screenHost = host(options.screenHost, "screenHost");
64
- this.projectorMeterHost = host(options.projectorMeterHost, "projectorMeterHost");
72
+ // Optional: without it, the projector's power comes from the flow.
73
+ this.projectorMeterHost = String(options.projectorMeterHost || "").trim()
74
+ ? host(options.projectorMeterHost, "projectorMeterHost")
75
+ : "";
65
76
  this.timeoutMs = Math.max(250, Number(options.timeoutMs || 5000));
66
77
  this.fetch = options.fetch || globalThis.fetch;
67
78
  if (typeof this.fetch !== "function")
@@ -119,8 +130,15 @@ class DisplayTransport {
119
130
  }
120
131
  if (command.device === "screen" && command.operation === "query_position") {
121
132
  const body = await this.shellyGet(this.screenHost, "Cover.GetStatus?id=0");
122
- const position = body.current_pos;
123
- if (typeof position !== "number" || !Number.isFinite(position) || position < 0 || position > 100) {
133
+ const position = typeof body.current_pos === "number" && Number.isFinite(body.current_pos) &&
134
+ body.current_pos >= 0 && body.current_pos <= 100 ? body.current_pos : null;
135
+ // Normalised to open, closed, opening, closing or stopped. A screen
136
+ // that doesn't know its position (not calibrated) still says whether
137
+ // it is fully open or closed, or neither: enough for a screen opened
138
+ // by its own command, even one left part-way, which is then sent
139
+ // open or closed. A position out of range is no reading at all.
140
+ const state = SCREEN_STATES[String(body.state)] ?? "stopped";
141
+ if (body.current_pos !== undefined && body.current_pos !== null && position === null) {
124
142
  const error = new Error("Shelly cover reported no usable position");
125
143
  error.code = "invalid_screen_position";
126
144
  throw error;
@@ -130,17 +148,24 @@ class DisplayTransport {
130
148
  kind: "observed",
131
149
  device: "screen",
132
150
  position,
133
- state: String(body.state || "unknown"),
151
+ state,
134
152
  source: "shelly-cover",
135
153
  ...common
136
154
  }
137
155
  };
138
156
  }
139
- if (command.device === "screen" && command.operation === "set_position") {
140
- await this.shellyPost(this.screenHost, "Cover.GoToPosition", { id: 0, pos: command.position });
157
+ // Open or close: to the position the command carries, or with none,
158
+ // by the screen's own open and close.
159
+ if (command.device === "screen" && (command.operation === "open" || command.operation === "close")) {
160
+ if (typeof command.position === "number") {
161
+ await this.shellyPost(this.screenHost, "Cover.GoToPosition", { id: 0, pos: command.position });
162
+ }
163
+ else {
164
+ await this.shellyPost(this.screenHost, command.operation === "open" ? "Cover.Open" : "Cover.Close", { id: 0 });
165
+ }
141
166
  return null;
142
167
  }
143
- if (command.device === "projector" && command.operation === "query_power") {
168
+ if (command.device === "projector" && command.operation === "query_power" && this.projectorMeterHost) {
144
169
  const body = await this.shellyGet(this.projectorMeterHost, "Switch.GetStatus?id=1");
145
170
  const watts = body.apower;
146
171
  if (typeof watts !== "number" || !Number.isFinite(watts) || watts < 0) {
@@ -0,0 +1,49 @@
1
+ import type { TraceEntry } from "./bounded-trace";
2
+ import type { CoverMotion } from "./cover-controller";
3
+ import { type MqttPublication } from "./mqtt-message";
4
+ export interface Z2mCoverConfig {
5
+ baseTopic: string;
6
+ friendlyName: string;
7
+ }
8
+ export interface Z2mCoverState {
9
+ reportsPosition: boolean;
10
+ }
11
+ export interface Z2mCoverMessage {
12
+ topic?: unknown;
13
+ payload?: unknown;
14
+ cover_command?: {
15
+ operation?: unknown;
16
+ position?: unknown;
17
+ generation?: unknown;
18
+ };
19
+ }
20
+ export type Z2mCoverReading = {
21
+ kind: "observed";
22
+ position?: number;
23
+ state?: "open" | "closed";
24
+ motion?: CoverMotion;
25
+ observedAt: string;
26
+ battery?: number;
27
+ charging?: string;
28
+ } | {
29
+ kind: "availability";
30
+ online: boolean;
31
+ };
32
+ export declare function normaliseZ2mCoverConfig(config: {
33
+ baseTopic?: unknown;
34
+ friendlyName?: unknown;
35
+ }): Z2mCoverConfig;
36
+ export declare function z2mCoverTopics(config: Z2mCoverConfig): {
37
+ device: string;
38
+ set: string;
39
+ get: string;
40
+ availability: string;
41
+ };
42
+ export declare function transitionZ2mCover(saved: Partial<Z2mCoverState> | undefined, msg: Z2mCoverMessage, config: Z2mCoverConfig, now: Date): {
43
+ state: Z2mCoverState;
44
+ publications: MqttPublication[];
45
+ readings: {
46
+ cover: Z2mCoverReading;
47
+ }[];
48
+ traces: TraceEntry<Record<string, unknown>>[];
49
+ };