@avantics/node-red-home-automation 2.3.0 → 3.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 (79) hide show
  1. package/README.md +32 -8
  2. package/contract-examples/room-lighting.mjs +12 -7
  3. package/dist/lib/activity-lighting-controller.d.ts +13 -25
  4. package/dist/lib/activity-lighting-controller.js +15 -11
  5. package/dist/lib/avr-controller.d.ts +13 -47
  6. package/dist/lib/avr-controller.js +39 -90
  7. package/dist/lib/backlighting-controller.d.ts +12 -25
  8. package/dist/lib/backlighting-controller.js +11 -18
  9. package/dist/lib/bounded-trace.d.ts +6 -0
  10. package/dist/lib/command-echo.d.ts +20 -0
  11. package/dist/lib/command-echo.js +82 -0
  12. package/dist/lib/cover-controller.d.ts +15 -28
  13. package/dist/lib/cover-controller.js +6 -8
  14. package/dist/lib/denon-protocol.d.ts +29 -0
  15. package/dist/lib/denon-protocol.js +76 -0
  16. package/dist/lib/display-mode-controller.d.ts +7 -18
  17. package/dist/lib/display-mode-controller.js +39 -47
  18. package/dist/lib/motion-policy.d.ts +12 -22
  19. package/dist/lib/motion-policy.js +53 -56
  20. package/dist/lib/occupancy-fusion.d.ts +8 -12
  21. package/dist/lib/room-controller.d.ts +14 -34
  22. package/dist/lib/room-controller.js +80 -132
  23. package/dist/lib/room-lighting-discovery.d.ts +9 -0
  24. package/dist/lib/room-lighting-discovery.js +45 -0
  25. package/dist/lib/settings.d.ts +5 -0
  26. package/dist/lib/settings.js +68 -0
  27. package/dist/lib/source-capability-controller.d.ts +30 -35
  28. package/dist/lib/source-capability-controller.js +35 -36
  29. package/dist/lib/switch-policy.d.ts +2 -7
  30. package/dist/lib/target-state.d.ts +24 -0
  31. package/dist/lib/target-state.js +38 -0
  32. package/dist/lib/theatre-activity-controller.d.ts +6 -108
  33. package/dist/lib/theatre-activity-controller.js +67 -318
  34. package/dist/lib/theatre-ha-discovery.d.ts +14 -0
  35. package/dist/lib/theatre-ha-discovery.js +163 -0
  36. package/dist/lib/theatre-metrics.d.ts +4 -0
  37. package/dist/lib/theatre-metrics.js +66 -0
  38. package/dist/lib/theatre-profiles.d.ts +23 -0
  39. package/dist/lib/theatre-profiles.js +73 -0
  40. package/dist/lib/theatre-refresh.d.ts +20 -0
  41. package/dist/lib/theatre-refresh.js +46 -0
  42. package/dist/lib/theatre-slo.js +7 -9
  43. package/dist/lib/theatre-state-contract.d.ts +7 -19
  44. package/dist/lib/theatre-state-contract.js +33 -169
  45. package/dist/lib/theatre-state.d.ts +110 -0
  46. package/dist/lib/theatre-state.js +139 -0
  47. package/dist/lib/wall-input.d.ts +2 -7
  48. package/dist/lib/z2m-light.d.ts +16 -0
  49. package/dist/lib/z2m-light.js +36 -0
  50. package/dist/nodes/activity-lighting-controller.html +5 -3
  51. package/dist/nodes/activity-lighting-controller.js +21 -52
  52. package/dist/nodes/adapter.d.ts +15 -0
  53. package/dist/nodes/adapter.js +60 -0
  54. package/dist/nodes/avr-controller.html +3 -3
  55. package/dist/nodes/avr-controller.js +17 -56
  56. package/dist/nodes/backlighting-controller.html +1 -1
  57. package/dist/nodes/backlighting-controller.js +25 -47
  58. package/dist/nodes/display-mode-controller.html +2 -2
  59. package/dist/nodes/display-mode-controller.js +19 -57
  60. package/dist/nodes/motion-policy.html +23 -10
  61. package/dist/nodes/motion-policy.js +14 -135
  62. package/dist/nodes/occupancy-fusion.html +2 -2
  63. package/dist/nodes/occupancy-fusion.js +23 -29
  64. package/dist/nodes/room-controller.html +80 -26
  65. package/dist/nodes/room-controller.js +37 -54
  66. package/dist/nodes/source-capability-controller.html +4 -13
  67. package/dist/nodes/source-capability-controller.js +17 -52
  68. package/dist/nodes/switch-policy.html +3 -3
  69. package/dist/nodes/switch-policy.js +23 -42
  70. package/dist/nodes/theatre-activity-controller.html +4 -2
  71. package/dist/nodes/theatre-activity-controller.js +18 -45
  72. package/dist/nodes/theatre-state-contract.html +55 -22
  73. package/dist/nodes/theatre-state-contract.js +30 -41
  74. package/examples/Home theatre activity.json +13 -12
  75. package/examples/Home theatre equipment.json +4 -4
  76. package/examples/Room lighting.json +9 -9
  77. package/package.json +1 -1
  78. package/dist/lib/circadian-refresh.d.ts +0 -7
  79. package/dist/lib/circadian-refresh.js +0 -11
@@ -2,13 +2,15 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.normaliseBacklightingConfig = normaliseBacklightingConfig;
4
4
  exports.transitionBacklighting = transitionBacklighting;
5
+ const settings_1 = require("./settings");
5
6
  const observation_time_1 = require("./observation-time");
7
+ const target_state_1 = require("./target-state");
6
8
  const POWERS = { on: true, off: true };
7
9
  function normaliseBacklightingConfig(config = {}) {
8
10
  return {
9
- pollMs: Math.max(250, Number(config.pollMs) || 2000),
10
- confirmationTimeoutMs: Math.max(1000, Number(config.confirmationTimeoutMs) || 15000),
11
- maxAttempts: Math.max(1, Math.floor(Number(config.maxAttempts) || 2))
11
+ pollMs: Math.max(250, (0, settings_1.numberSetting)(config.pollMs, "poll interval", 2000)),
12
+ confirmationTimeoutMs: Math.max(1000, (0, settings_1.numberSetting)(config.confirmationTimeoutMs, "confirmation timeout", 15000)),
13
+ maxAttempts: Math.max(1, Math.floor((0, settings_1.numberSetting)(config.maxAttempts, "max attempts", 2)))
12
14
  };
13
15
  }
14
16
  function initialState(saved = {}) {
@@ -234,18 +236,11 @@ function transitionBacklighting(saved, msg, suppliedConfig = {}, nowValue = new
234
236
  throw new Error("unknown backlighting event kind");
235
237
  }
236
238
  if (state.desired) {
237
- const theatre = {
238
- kind: "target_state",
239
+ const theatre = (0, target_state_1.targetStateEvent)({
239
240
  target: "backlighting",
240
241
  requestId: state.desired.requestId,
241
242
  generation: state.generation,
242
- status: state.phase === "failed"
243
- ? "failed"
244
- : state.phase === "ready"
245
- ? "ready"
246
- : state.phase === "manual_override"
247
- ? "transitioning"
248
- : state.phase,
243
+ status: state.phase === "manual_override" ? "transitioning" : (0, target_state_1.asTargetStatus)(state.phase, "confirming"),
249
244
  observedAt: now.toISOString(),
250
245
  details: {
251
246
  power: state.desired.power,
@@ -256,12 +251,10 @@ function transitionBacklighting(saved, msg, suppliedConfig = {}, nowValue = new
256
251
  retries: Math.max(0, state.lastAttempt - 1),
257
252
  fallbackUsed: false
258
253
  }
259
- }
260
- };
261
- if (state.classification)
262
- theatre.classification = state.classification;
263
- if (state.failure)
264
- theatre.failure = { ...state.failure };
254
+ },
255
+ classification: state.classification,
256
+ failure: state.failure
257
+ });
265
258
  events.push({ theatre });
266
259
  }
267
260
  return { state, commands, events, traces, status: statusFor(state) };
@@ -9,6 +9,12 @@ export interface TraceMetadata {
9
9
  component: string;
10
10
  limit?: number;
11
11
  }
12
+ export interface TraceEntry<Details = Record<string, unknown>> {
13
+ event: string;
14
+ outcome: string;
15
+ reason: string | null;
16
+ details: Details;
17
+ }
12
18
  export interface TraceInput {
13
19
  at?: string;
14
20
  event: string;
@@ -0,0 +1,20 @@
1
+ export declare const ECHO_WINDOW_MS = 5000;
2
+ export declare const ECHO_QUEUE_LIMIT = 8;
3
+ export interface ExpectedCommand {
4
+ fingerprint: string;
5
+ expires: number;
6
+ on?: boolean;
7
+ echoed?: boolean;
8
+ }
9
+ export declare function parsePayload(payload: unknown): unknown;
10
+ export declare function fingerprint(payload: unknown): string;
11
+ export declare function rememberCommand(queue: ExpectedCommand[] | undefined, payload: unknown, nowMs: number): ExpectedCommand[];
12
+ export type StateReportVerdict = "confirms" | "stale" | "external";
13
+ export declare function checkStateReport(queue: ExpectedCommand[] | undefined, observedOn: boolean, nowMs: number): {
14
+ queue: ExpectedCommand[];
15
+ verdict: StateReportVerdict;
16
+ };
17
+ export declare function checkCommandEcho(queue: ExpectedCommand[] | undefined, payload: unknown, nowMs: number): {
18
+ queue: ExpectedCommand[];
19
+ own: boolean;
20
+ };
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ECHO_QUEUE_LIMIT = exports.ECHO_WINDOW_MS = void 0;
4
+ exports.parsePayload = parsePayload;
5
+ exports.fingerprint = fingerprint;
6
+ exports.rememberCommand = rememberCommand;
7
+ exports.checkStateReport = checkStateReport;
8
+ exports.checkCommandEcho = checkCommandEcho;
9
+ // Telling the room controller's own light commands from other people's.
10
+ // Each target keeps a short queue of commands it sent; the command topic's
11
+ // echo and the light's state reports are checked against it. Pure: each
12
+ // function takes a queue and returns the new one.
13
+ // How long a sent command is remembered, and how many per target.
14
+ exports.ECHO_WINDOW_MS = 5000;
15
+ exports.ECHO_QUEUE_LIMIT = 8;
16
+ function parsePayload(payload) {
17
+ if (typeof payload !== "string")
18
+ return payload;
19
+ try {
20
+ return JSON.parse(payload);
21
+ }
22
+ catch {
23
+ return payload;
24
+ }
25
+ }
26
+ function stable(value) {
27
+ if (Array.isArray(value))
28
+ return value.map(stable);
29
+ if (value && typeof value === "object") {
30
+ const record = value;
31
+ return Object.fromEntries(Object.keys(record).sort().map((key) => [key, stable(record[key])]));
32
+ }
33
+ return value;
34
+ }
35
+ // The same payload always gives the same fingerprint, whatever its key order.
36
+ function fingerprint(payload) {
37
+ return JSON.stringify(stable(payload));
38
+ }
39
+ function live(queue, nowMs) {
40
+ return (queue || []).filter((entry) => entry.expires > nowMs).map((entry) => ({ ...entry }));
41
+ }
42
+ // Remember a command just sent.
43
+ function rememberCommand(queue, payload, nowMs) {
44
+ const next = live(queue, nowMs);
45
+ const entry = { fingerprint: fingerprint(payload), expires: nowMs + exports.ECHO_WINDOW_MS };
46
+ const requested = payload && typeof payload === "object"
47
+ ? String(payload.state || "").toUpperCase()
48
+ : "";
49
+ if (requested === "ON" || requested === "OFF")
50
+ entry.on = requested === "ON";
51
+ next.push(entry);
52
+ return next.slice(-exports.ECHO_QUEUE_LIMIT);
53
+ }
54
+ function checkStateReport(queue, observedOn, nowMs) {
55
+ const next = live(queue, nowMs);
56
+ const latest = next.filter((entry) => entry.on !== undefined).at(-1);
57
+ const verdict = latest === undefined ? "external" : latest.on === observedOn ? "confirms" : "stale";
58
+ if (verdict === "confirms") {
59
+ for (const entry of next)
60
+ delete entry.on;
61
+ }
62
+ return {
63
+ queue: next.filter((entry) => entry.on !== undefined || entry.echoed !== true),
64
+ verdict
65
+ };
66
+ }
67
+ // A command seen on the command topic: one of ours (its first echo), or
68
+ // someone else's.
69
+ function checkCommandEcho(queue, payload, nowMs) {
70
+ const next = live(queue, nowMs);
71
+ const ownIndex = next.findIndex((entry) => entry.echoed !== true && entry.fingerprint === fingerprint(payload));
72
+ const own = next[ownIndex];
73
+ if (!own)
74
+ return { queue: next, own: false };
75
+ // Keep an unconfirmed power command as in flight for state reports.
76
+ if (own.on === undefined)
77
+ next.splice(ownIndex, 1);
78
+ else
79
+ own.echoed = true;
80
+ return { queue: next, own: true };
81
+ }
82
+ //# sourceMappingURL=command-echo.js.map
@@ -1,3 +1,5 @@
1
+ import type { TraceEntry } from "./bounded-trace";
2
+ import { type TargetStateEvent } from "./target-state";
1
3
  export type CoverMotion = "opening" | "closing" | "stopped";
2
4
  export type CoverOperation = "set_position" | "stop" | "observe";
3
5
  export interface CoverConfig {
@@ -87,41 +89,26 @@ export interface CoverCommand {
87
89
  attempt: number;
88
90
  }
89
91
  export interface CoverOutputEvent {
90
- theatre: {
91
- kind: "target_state";
92
- target: "cover";
93
- requestId: string;
94
- generation: number;
95
- status: string;
96
- observedAt: string;
97
- details: {
98
- operation: "set_position" | "stop";
99
- position: number | null;
100
- observedPosition: number | null;
101
- motion: CoverMotion | null;
102
- source: string | null;
103
- recovery: Record<string, unknown>;
104
- metrics: {
105
- attempts: number;
106
- retries: number;
107
- fallbackUsed: boolean;
108
- };
92
+ theatre: TargetStateEvent<"cover", {
93
+ operation: "set_position" | "stop";
94
+ position: number | null;
95
+ observedPosition: number | null;
96
+ motion: CoverMotion | null;
97
+ source: string | null;
98
+ recovery: Record<string, unknown>;
99
+ metrics: {
100
+ attempts: number;
101
+ retries: number;
102
+ fallbackUsed: boolean;
109
103
  };
110
- classification?: "manual_override";
111
- failure?: CoverFailure;
112
- };
104
+ }, CoverFailure>;
113
105
  }
114
106
  export declare function normaliseCoverConfig(config?: Partial<CoverConfig>): CoverConfig;
115
107
  export declare function transitionCover(saved: Partial<CoverState> | undefined, msg: CoverMessage, suppliedConfig?: Partial<CoverConfig>, nowValue?: Date | string | number): {
116
108
  state: CoverState;
117
109
  commands: CoverCommand[];
118
110
  events: CoverOutputEvent[];
119
- traces: {
120
- event: string;
121
- outcome: string;
122
- reason: string | null;
123
- details: Record<string, unknown>;
124
- }[];
111
+ traces: TraceEntry<Record<string, unknown>>[];
125
112
  status: {
126
113
  phase: string;
127
114
  text: string;
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.normaliseCoverConfig = normaliseCoverConfig;
4
4
  exports.transitionCover = transitionCover;
5
5
  const observation_time_1 = require("./observation-time");
6
+ const target_state_1 = require("./target-state");
6
7
  const MOTIONS = { opening: true, closing: true, stopped: true };
7
8
  function normaliseCoverConfig(config = {}) {
8
9
  const tolerance = Number(config.positionTolerance);
@@ -300,8 +301,7 @@ function transitionCover(saved, msg, suppliedConfig = {}, nowValue = new Date())
300
301
  throw new Error("unknown cover event kind");
301
302
  }
302
303
  if (state.desired) {
303
- const theatre = {
304
- kind: "target_state",
304
+ const theatre = (0, target_state_1.targetStateEvent)({
305
305
  target: "cover",
306
306
  requestId: state.desired.requestId,
307
307
  generation: state.generation,
@@ -323,12 +323,10 @@ function transitionCover(saved, msg, suppliedConfig = {}, nowValue = new Date())
323
323
  retries: Math.max(0, state.lastAttempt - 1),
324
324
  fallbackUsed: false
325
325
  }
326
- }
327
- };
328
- if (state.classification)
329
- theatre.classification = state.classification;
330
- if (state.failure)
331
- theatre.failure = { ...state.failure };
326
+ },
327
+ classification: state.classification,
328
+ failure: state.failure
329
+ });
332
330
  events.push({ theatre });
333
331
  }
334
332
  return { state, commands, events, traces, status: statusFor(state) };
@@ -0,0 +1,29 @@
1
+ export type AvrPower = "on" | "standby";
2
+ export type MainZone = "on" | "off";
3
+ export declare const QUERY_COMMAND = "PW?\rZM?\rSI?\rMV?\r";
4
+ export declare const POWER_ON = "PWON\r";
5
+ export declare const POWER_STANDBY = "PWSTANDBY\r";
6
+ export declare const ZONE_ON = "ZMON\r";
7
+ export declare function selectSource(code: string): string;
8
+ export type ParsedAvrLine = {
9
+ field: "power";
10
+ value: AvrPower;
11
+ line: string;
12
+ } | {
13
+ field: "mainZone";
14
+ value: MainZone;
15
+ line: string;
16
+ } | {
17
+ field: "source";
18
+ value: string | null;
19
+ sourceCode: string;
20
+ line: string;
21
+ } | {
22
+ field: "volume";
23
+ value: number | null;
24
+ line: string;
25
+ };
26
+ export declare function parseSourceCodes(value: unknown): Record<string, string>;
27
+ export declare function roundVolume(value: number): number;
28
+ export declare function formatVolumeCommand(value: number): string;
29
+ export declare function parseAvrLine(value: unknown, sources: Record<string, string>): ParsedAvrLine | null;
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ZONE_ON = exports.POWER_STANDBY = exports.POWER_ON = exports.QUERY_COMMAND = void 0;
4
+ exports.selectSource = selectSource;
5
+ exports.parseSourceCodes = parseSourceCodes;
6
+ exports.roundVolume = roundVolume;
7
+ exports.formatVolumeCommand = formatVolumeCommand;
8
+ exports.parseAvrLine = parseAvrLine;
9
+ // Asks for power, main zone, source and volume.
10
+ exports.QUERY_COMMAND = "PW?\rZM?\rSI?\rMV?\r";
11
+ exports.POWER_ON = "PWON\r";
12
+ exports.POWER_STANDBY = "PWSTANDBY\r";
13
+ exports.ZONE_ON = "ZMON\r";
14
+ function selectSource(code) {
15
+ return "SI" + code + "\r";
16
+ }
17
+ // Configured source names mapped to the receiver's source codes, each code
18
+ // valid and used once.
19
+ function parseSourceCodes(value) {
20
+ const sources = value && typeof value === "object" && !Array.isArray(value)
21
+ ? value
22
+ : {};
23
+ const entries = Object.entries(sources);
24
+ if (entries.some(([name, code]) => !name ||
25
+ !code || typeof code !== "string" ||
26
+ !/^[A-Z0-9][A-Z0-9 /._-]*$/.test(code))) {
27
+ throw new Error("sources must map names to Denon source codes");
28
+ }
29
+ const typedEntries = entries;
30
+ if (new Set(typedEntries.map(([, code]) => code)).size !== typedEntries.length) {
31
+ throw new Error("Denon source codes must be unique");
32
+ }
33
+ return Object.fromEntries(typedEntries);
34
+ }
35
+ // Volume moves in half steps.
36
+ function roundVolume(value) {
37
+ return Math.round(value * 2) / 2;
38
+ }
39
+ // "MV" volume digits: two for a whole step, a trailing 5 for a half step.
40
+ function parseVolume(raw) {
41
+ if (!/^\d{2,3}$/.test(raw))
42
+ return null;
43
+ if (raw.length === 2)
44
+ return Number(raw);
45
+ return Number(raw.slice(0, 2)) + Number(raw.slice(2)) / 10;
46
+ }
47
+ function formatVolumeCommand(value) {
48
+ const rounded = roundVolume(value);
49
+ if (!Number.isFinite(value) || rounded < 0 || rounded > 98 || Math.abs(value - rounded) > 0.001) {
50
+ throw new Error("volume must be a half-step between 0 and 98");
51
+ }
52
+ const whole = Math.floor(rounded).toString().padStart(2, "0");
53
+ return "MV" + whole + (Number.isInteger(rounded) ? "" : "5") + "\r";
54
+ }
55
+ function parseAvrLine(value, sources) {
56
+ const line = String(value ?? "").trim();
57
+ if (line === "PWON")
58
+ return { field: "power", value: "on", line };
59
+ if (line === "PWOFF" || line === "PWSTANDBY") {
60
+ return { field: "power", value: "standby", line };
61
+ }
62
+ if (line === "ZMON")
63
+ return { field: "mainZone", value: "on", line };
64
+ if (line === "ZMOFF")
65
+ return { field: "mainZone", value: "off", line };
66
+ if (/^SI.+/.test(line)) {
67
+ const sourceCode = line.slice(2);
68
+ const source = Object.entries(sources).find(([, code]) => code === sourceCode)?.[0] || null;
69
+ return { field: "source", value: source, sourceCode, line };
70
+ }
71
+ if (/^MV\d{2,3}$/.test(line)) {
72
+ return { field: "volume", value: parseVolume(line.slice(2)), line };
73
+ }
74
+ return null;
75
+ }
76
+ //# sourceMappingURL=denon-protocol.js.map
@@ -1,3 +1,5 @@
1
+ import type { TraceEntry } from "./bounded-trace";
2
+ import { type TargetStateEvent } from "./target-state";
1
3
  export type DisplayMode = "off" | "tv" | "projector";
2
4
  export type DisplayDevice = "tv" | "screen" | "projector";
3
5
  export interface DisplayConfig {
@@ -111,22 +113,14 @@ export type DisplayInputEvent = {
111
113
  export interface DisplayMessage {
112
114
  display?: DisplayInputEvent;
113
115
  }
114
- export interface DisplayTargetState {
115
- kind: "target_state";
116
- target: "display";
117
- requestId: string;
118
- generation: number;
119
- status: string;
120
- observedAt: string;
121
- details: Record<string, unknown>;
122
- classification?: "manual_override";
123
- failure?: DisplayFailure;
124
- }
116
+ export type DisplayTargetState = TargetStateEvent<"display", Record<string, unknown>, DisplayFailure>;
125
117
  export interface DisplayOutputEvent {
126
118
  display: Record<string, unknown>;
127
119
  }
128
120
  export declare function classifyProjectorPower(watts: number, previous?: ProjectorObservation["power"], config?: Partial<DisplayConfig>): ProjectorObservation["power"];
129
- export declare function normaliseConfig(config?: Partial<DisplayConfig>): DisplayConfig;
121
+ export declare function normaliseConfig(config?: {
122
+ [K in keyof DisplayConfig]?: unknown;
123
+ }): DisplayConfig;
130
124
  export declare function transitionDisplay(saved: Partial<DisplayState> | undefined, msg: DisplayMessage, suppliedConfig?: Partial<DisplayConfig>, now?: Date): {
131
125
  state: DisplayState;
132
126
  commands: DisplayCommand[];
@@ -134,12 +128,7 @@ export declare function transitionDisplay(saved: Partial<DisplayState> | undefin
134
128
  targetStates: {
135
129
  theatre: DisplayTargetState;
136
130
  }[];
137
- traces: {
138
- event: string;
139
- outcome: string;
140
- reason: string | null;
141
- details: Record<string, unknown>;
142
- }[];
131
+ traces: TraceEntry<Record<string, unknown>>[];
143
132
  status: {
144
133
  phase: string;
145
134
  text: string;
@@ -3,7 +3,9 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.classifyProjectorPower = classifyProjectorPower;
4
4
  exports.normaliseConfig = normaliseConfig;
5
5
  exports.transitionDisplay = transitionDisplay;
6
+ const settings_1 = require("./settings");
6
7
  const observation_time_1 = require("./observation-time");
8
+ const target_state_1 = require("./target-state");
7
9
  const MODES = { off: true, tv: true, projector: true };
8
10
  const DEVICES = ["tv", "screen", "projector"];
9
11
  function iso(now) {
@@ -94,28 +96,24 @@ function operationSatisfied(operation, observed, config) {
94
96
  default: return false;
95
97
  }
96
98
  }
97
- // A finite number, or the default for missing or unusable input.
98
- function setting(value, fallback) {
99
- const parsed = Number(value ?? fallback);
100
- return Number.isFinite(parsed) ? parsed : fallback;
101
- }
99
+ // Settings may be editor strings; missing or unusable numbers take defaults.
102
100
  function normaliseConfig(config = {}) {
103
- const projectorWarmupMs = Math.max(1000, setting(config.projectorWarmupMs, 60000));
101
+ const projectorWarmupMs = Math.max(1000, (0, settings_1.numberSetting)(config.projectorWarmupMs, "projector warm-up", 60000));
104
102
  return {
105
- screenOpenPosition: setting(config.screenOpenPosition, 82),
106
- screenTolerance: Math.max(0, setting(config.screenTolerance, 2)),
107
- pollMs: Math.max(250, setting(config.pollMs, 2000)),
108
- queryTimeoutMs: Math.max(1000, setting(config.queryTimeoutMs, 5000)),
109
- tvTimeoutMs: Math.max(1000, setting(config.tvTimeoutMs, 30000)),
110
- screenTimeoutMs: Math.max(1000, setting(config.screenTimeoutMs, 65000)),
103
+ screenOpenPosition: (0, settings_1.numberSetting)(config.screenOpenPosition, "screen open position", 82),
104
+ screenTolerance: Math.max(0, (0, settings_1.numberSetting)(config.screenTolerance, "screen tolerance", 2)),
105
+ pollMs: Math.max(250, (0, settings_1.numberSetting)(config.pollMs, "poll interval", 2000)),
106
+ queryTimeoutMs: Math.max(1000, (0, settings_1.numberSetting)(config.queryTimeoutMs, "query timeout", 5000)),
107
+ tvTimeoutMs: Math.max(1000, (0, settings_1.numberSetting)(config.tvTimeoutMs, "TV timeout", 30000)),
108
+ screenTimeoutMs: Math.max(1000, (0, settings_1.numberSetting)(config.screenTimeoutMs, "screen timeout", 65000)),
111
109
  projectorWarmupMs,
112
- projectorMinimumWarmupMs: Math.min(projectorWarmupMs, Math.max(0, setting(config.projectorMinimumWarmupMs, 15000))),
113
- projectorShutdownConfirmMs: Math.max(1000, setting(config.projectorShutdownConfirmMs, 5000)),
114
- projectorCooldownMs: Math.max(1000, setting(config.projectorCooldownMs, 120000)),
115
- maxAttempts: Math.max(1, Math.floor(setting(config.maxAttempts, 2))),
116
- projectorOnWatts: setting(config.projectorOnWatts, 20),
117
- projectorOffWatts: setting(config.projectorOffWatts, 10),
118
- projectorPowerFallback: config.projectorPowerFallback === true
110
+ projectorMinimumWarmupMs: Math.min(projectorWarmupMs, Math.max(0, (0, settings_1.numberSetting)(config.projectorMinimumWarmupMs, "projector minimum warm-up", 15000))),
111
+ projectorShutdownConfirmMs: Math.max(1000, (0, settings_1.numberSetting)(config.projectorShutdownConfirmMs, "projector shutdown confirmation", 5000)),
112
+ projectorCooldownMs: Math.max(1000, (0, settings_1.numberSetting)(config.projectorCooldownMs, "projector cool-down", 120000)),
113
+ maxAttempts: Math.max(1, Math.floor((0, settings_1.numberSetting)(config.maxAttempts, "max attempts", 2))),
114
+ projectorOnWatts: (0, settings_1.numberSetting)(config.projectorOnWatts, "projector on watts", 20),
115
+ projectorOffWatts: (0, settings_1.numberSetting)(config.projectorOffWatts, "projector off watts", 10),
116
+ projectorPowerFallback: (0, settings_1.booleanSetting)(config.projectorPowerFallback, "projector power fallback", false)
119
117
  };
120
118
  }
121
119
  function modeSatisfied(state, config) {
@@ -158,6 +156,20 @@ function transitionDisplay(saved, msg, suppliedConfig = {}, now = new Date()) {
158
156
  events.push(displayEvent("failed", state, { failure: state.failure }));
159
157
  trace("transition", "failed", reason, { device, operation });
160
158
  }
159
+ // Re-send a retryable command with a full deadline of its own, whether its
160
+ // deadline passed or its transport failed.
161
+ function retry(pending, reason) {
162
+ const attempt = pending.attempt + 1;
163
+ const retried = { ...pending.command, attempt };
164
+ commands.push(retried);
165
+ pending.command = retried;
166
+ pending.attempt = attempt;
167
+ const timeout = pending.device === "tv" ? config.tvTimeoutMs : config.screenTimeoutMs;
168
+ pending.deadlineAt = now.getTime() + timeout;
169
+ pending.nextAt = now.getTime() + config.pollMs;
170
+ trace("command", "retried", reason, { device: pending.device, operation: pending.operation, attempt });
171
+ state.lastAttempt = Math.max(state.lastAttempt, attempt);
172
+ }
161
173
  function issue(device, operation, command, timeoutMs, retryable = true) {
162
174
  const attempt = command.attempt || 1;
163
175
  state.pending = {
@@ -408,16 +420,7 @@ function transitionDisplay(saved, msg, suppliedConfig = {}, now = new Date()) {
408
420
  }
409
421
  if (now.getTime() >= pending.deadlineAt) {
410
422
  if (pending.retryable && pending.attempt < config.maxAttempts) {
411
- const attempt = pending.attempt + 1;
412
- const retried = { ...pending.command, attempt };
413
- commands.push(retried);
414
- pending.command = retried;
415
- pending.attempt = attempt;
416
- const timeout = pending.device === "tv" ? config.tvTimeoutMs : config.screenTimeoutMs;
417
- pending.deadlineAt = now.getTime() + timeout;
418
- pending.nextAt = now.getTime() + config.pollMs;
419
- trace("command", "retried", null, { device: pending.device, operation: pending.operation, attempt });
420
- state.lastAttempt = Math.max(state.lastAttempt, attempt);
423
+ retry(pending, null);
421
424
  return;
422
425
  }
423
426
  return fail(pending.device, pending.operation, pending.operation === "projector_settle" ? "projector-power-unsettled" : "confirmation-timeout");
@@ -494,15 +497,7 @@ function transitionDisplay(saved, msg, suppliedConfig = {}, now = new Date()) {
494
497
  else if (state.pending && state.pending.device === event.device &&
495
498
  state.pending.command.operation === event.operation) {
496
499
  if (state.pending.retryable && state.pending.attempt < config.maxAttempts) {
497
- const attempt = state.pending.attempt + 1;
498
- const retried = { ...state.pending.command, attempt };
499
- state.pending.command = retried;
500
- state.pending.attempt = attempt;
501
- commands.push(retried);
502
- trace("command", "retried", event.reason || "transport-failed", {
503
- device: event.device, operation: state.pending.operation, attempt
504
- });
505
- state.lastAttempt = Math.max(state.lastAttempt, attempt);
500
+ retry(state.pending, event.reason || "transport-failed");
506
501
  }
507
502
  else {
508
503
  fail(event.device, state.pending.operation, event.reason || "transport-failed");
@@ -540,10 +535,9 @@ function transitionDisplay(saved, msg, suppliedConfig = {}, now = new Date()) {
540
535
  const confirmedMs = readings.every((ms) => ms !== null) ? Math.min(...readings) : null;
541
536
  const status = state.phase === "manual_override"
542
537
  ? "transitioning"
543
- : state.phase === "idle" ? "confirming" : state.phase;
538
+ : (0, target_state_1.asTargetStatus)(state.phase, "confirming");
544
539
  if (!(status === "ready" && previousPhase === "ready" && !observationAccepted)) {
545
- const theatre = {
546
- kind: "target_state",
540
+ const theatre = (0, target_state_1.targetStateEvent)({
547
541
  target: "display",
548
542
  requestId: state.desired.requestId,
549
543
  generation: state.desired.generation,
@@ -562,12 +556,10 @@ function transitionDisplay(saved, msg, suppliedConfig = {}, now = new Date()) {
562
556
  retries: Math.max(0, state.lastAttempt - 1),
563
557
  fallbackUsed: state.fallbackUsed
564
558
  }
565
- }
566
- };
567
- if (state.classification)
568
- theatre.classification = state.classification;
569
- if (state.failure)
570
- theatre.failure = { ...state.failure };
559
+ },
560
+ classification: state.classification,
561
+ failure: state.failure
562
+ });
571
563
  targetStates.push({ theatre });
572
564
  }
573
565
  }
@@ -1,5 +1,5 @@
1
- import { type WallInputConfig, type WallInputState } from "./wall-input";
2
- export interface MotionConfig extends WallInputConfig {
1
+ import type { TraceEntry } from "./bounded-trace";
2
+ export interface MotionConfig {
3
3
  defaultIlluminanceCutoff: number;
4
4
  defaultDelaySeconds: number;
5
5
  onTargets: string[];
@@ -10,18 +10,16 @@ export interface MotionState {
10
10
  illuminance: number | null;
11
11
  illuminanceCutoff: number;
12
12
  delaySeconds: number;
13
- wallInput: WallInputState;
13
+ illuminanceCutoffSetting: number | null;
14
+ delaySecondsSetting: number | null;
14
15
  offTimerGeneration: number;
15
16
  offTimerDueAt: number | null;
17
+ offTimerArmedAt: number | null;
16
18
  }
17
19
  export interface MotionInput {
18
20
  source: string;
19
- observedAt?: unknown;
20
- baseline?: boolean;
21
21
  payload?: unknown;
22
22
  generation?: number;
23
- switchAt?: number;
24
- retain?: boolean;
25
23
  }
26
24
  export interface LightingIntent {
27
25
  lighting: {
@@ -38,35 +36,27 @@ export type MotionEffect = {
38
36
  kind: "schedule-off-timer";
39
37
  delayMs: number;
40
38
  generation: number;
41
- } | {
42
- kind: "cancel-switch-timer";
43
- } | {
44
- kind: "schedule-switch-timer";
45
- delayMs: number;
46
- generation: number;
47
- switchAt: number;
48
39
  } | {
49
40
  kind: "send";
50
41
  message: LightingIntent;
51
42
  };
52
- export interface MotionTrace {
53
- event: string;
54
- outcome: string;
55
- reason: string | null;
56
- details: Record<string, unknown>;
57
- }
58
43
  export declare function booleanOn(value: unknown): boolean;
44
+ export declare function normaliseMotionConfig(raw: {
45
+ onTargets?: unknown;
46
+ offTargets?: unknown;
47
+ defaultDelaySeconds?: unknown;
48
+ defaultIlluminanceCutoff?: unknown;
49
+ }): MotionConfig;
59
50
  export declare function createMotionState(config: MotionConfig, saved?: Partial<MotionState>): MotionState;
60
51
  export declare function lightingIntent(targets: string[], state: string, source: string, extra?: Record<string, unknown>): LightingIntent;
61
52
  export declare function transitionMotion(saved: Partial<MotionState> | undefined, input: MotionInput, config: MotionConfig, globalEnabled: boolean, now?: number): {
62
53
  state: MotionState;
63
54
  globalEnabled: boolean;
64
55
  effects: MotionEffect[];
65
- traces: MotionTrace[];
56
+ traces: TraceEntry<Record<string, unknown>>[];
66
57
  status: {
67
58
  enabled: boolean;
68
59
  illuminance: number | null;
69
60
  delaySeconds: number;
70
- switch: import("./wall-input").WallInputStatus;
71
61
  };
72
62
  };