@avantics/node-red-home-automation 2.2.1 → 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 (85) hide show
  1. package/README.md +76 -89
  2. package/contract-examples/room-lighting.mjs +12 -9
  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 +17 -28
  6. package/dist/lib/avr-controller.js +165 -116
  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/circadian-schedule.d.ts +11 -0
  11. package/dist/lib/circadian-schedule.js +63 -0
  12. package/dist/lib/circadian.d.ts +6 -0
  13. package/dist/lib/circadian.js +15 -0
  14. package/dist/lib/command-echo.d.ts +20 -0
  15. package/dist/lib/command-echo.js +82 -0
  16. package/dist/lib/cover-controller.d.ts +15 -28
  17. package/dist/lib/cover-controller.js +6 -8
  18. package/dist/lib/denon-protocol.d.ts +29 -0
  19. package/dist/lib/denon-protocol.js +76 -0
  20. package/dist/lib/display-mode-controller.d.ts +11 -6
  21. package/dist/lib/display-mode-controller.js +90 -39
  22. package/dist/lib/light-styling.d.ts +11 -0
  23. package/dist/lib/light-styling.js +15 -0
  24. package/dist/lib/motion-policy.d.ts +12 -22
  25. package/dist/lib/motion-policy.js +53 -56
  26. package/dist/lib/occupancy-fusion.d.ts +8 -12
  27. package/dist/lib/occupancy-fusion.js +3 -2
  28. package/dist/lib/room-controller.d.ts +13 -38
  29. package/dist/lib/room-controller.js +85 -180
  30. package/dist/lib/room-lighting-discovery.d.ts +9 -0
  31. package/dist/lib/room-lighting-discovery.js +45 -0
  32. package/dist/lib/settings.d.ts +5 -0
  33. package/dist/lib/settings.js +68 -0
  34. package/dist/lib/source-capability-controller.d.ts +32 -35
  35. package/dist/lib/source-capability-controller.js +51 -35
  36. package/dist/lib/switch-policy.d.ts +2 -7
  37. package/dist/lib/target-state.d.ts +24 -0
  38. package/dist/lib/target-state.js +38 -0
  39. package/dist/lib/theatre-activity-controller.d.ts +6 -108
  40. package/dist/lib/theatre-activity-controller.js +67 -318
  41. package/dist/lib/theatre-ha-discovery.d.ts +14 -0
  42. package/dist/lib/theatre-ha-discovery.js +163 -0
  43. package/dist/lib/theatre-metrics.d.ts +4 -0
  44. package/dist/lib/theatre-metrics.js +66 -0
  45. package/dist/lib/theatre-profiles.d.ts +23 -0
  46. package/dist/lib/theatre-profiles.js +73 -0
  47. package/dist/lib/theatre-refresh.d.ts +20 -0
  48. package/dist/lib/theatre-refresh.js +46 -0
  49. package/dist/lib/theatre-slo.js +7 -9
  50. package/dist/lib/theatre-state-contract.d.ts +7 -19
  51. package/dist/lib/theatre-state-contract.js +33 -169
  52. package/dist/lib/theatre-state.d.ts +110 -0
  53. package/dist/lib/theatre-state.js +139 -0
  54. package/dist/lib/wall-input.d.ts +2 -7
  55. package/dist/lib/z2m-light.d.ts +16 -0
  56. package/dist/lib/z2m-light.js +36 -0
  57. package/dist/nodes/activity-lighting-controller.html +5 -3
  58. package/dist/nodes/activity-lighting-controller.js +21 -52
  59. package/dist/nodes/adapter.d.ts +15 -0
  60. package/dist/nodes/adapter.js +60 -0
  61. package/dist/nodes/avr-controller.html +13 -4
  62. package/dist/nodes/avr-controller.js +23 -62
  63. package/dist/nodes/backlighting-controller.html +1 -1
  64. package/dist/nodes/backlighting-controller.js +25 -47
  65. package/dist/nodes/display-mode-controller.html +4 -4
  66. package/dist/nodes/display-mode-controller.js +22 -59
  67. package/dist/nodes/motion-policy.html +23 -10
  68. package/dist/nodes/motion-policy.js +14 -135
  69. package/dist/nodes/occupancy-fusion.html +2 -2
  70. package/dist/nodes/occupancy-fusion.js +23 -29
  71. package/dist/nodes/room-controller.html +92 -34
  72. package/dist/nodes/room-controller.js +46 -64
  73. package/dist/nodes/source-capability-controller.html +4 -13
  74. package/dist/nodes/source-capability-controller.js +17 -52
  75. package/dist/nodes/switch-policy.html +3 -3
  76. package/dist/nodes/switch-policy.js +23 -42
  77. package/dist/nodes/theatre-activity-controller.html +5 -3
  78. package/dist/nodes/theatre-activity-controller.js +23 -43
  79. package/dist/nodes/theatre-state-contract.html +55 -22
  80. package/dist/nodes/theatre-state-contract.js +30 -41
  81. package/examples/Home theatre activity.json +307 -43
  82. package/examples/Home theatre equipment.json +4 -4
  83. package/examples/Room lighting.json +15 -17
  84. package/package.json +3 -7
  85. package/THIRD-PARTY-NOTICES.md +0 -218
@@ -0,0 +1,6 @@
1
+ import { type DaySchedule } from "./circadian-schedule";
2
+ import { type LightLevels, type LightStyle } from "./light-styling";
3
+ export interface CircadianLighting {
4
+ styleAt(now: Date, sleeping: boolean): LightStyle;
5
+ }
6
+ export declare function scheduledLighting(schedule: DaySchedule, levels: LightLevels): CircadianLighting;
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.scheduledLighting = scheduledLighting;
4
+ const circadian_schedule_1 = require("./circadian-schedule");
5
+ const light_styling_1 = require("./light-styling");
6
+ // Circadian lighting that follows a wake and bed schedule; sleep mode holds
7
+ // the sleep settings.
8
+ function scheduledLighting(schedule, levels) {
9
+ return {
10
+ styleAt(now, sleeping) {
11
+ return (0, light_styling_1.styleAtLevel)(sleeping ? 0 : (0, circadian_schedule_1.scheduleLevel)(now, schedule.wakeTime, schedule.bedTime), levels);
12
+ }
13
+ };
14
+ }
15
+ //# sourceMappingURL=circadian.js.map
@@ -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 {
@@ -105,25 +107,28 @@ export type DisplayInputEvent = {
105
107
  } | {
106
108
  kind: "tick";
107
109
  generation?: number;
110
+ } | {
111
+ kind: "refresh";
108
112
  };
109
113
  export interface DisplayMessage {
110
114
  display?: DisplayInputEvent;
111
115
  }
116
+ export type DisplayTargetState = TargetStateEvent<"display", Record<string, unknown>, DisplayFailure>;
112
117
  export interface DisplayOutputEvent {
113
118
  display: Record<string, unknown>;
114
119
  }
115
120
  export declare function classifyProjectorPower(watts: number, previous?: ProjectorObservation["power"], config?: Partial<DisplayConfig>): ProjectorObservation["power"];
116
- export declare function normaliseConfig(config?: Partial<DisplayConfig>): DisplayConfig;
121
+ export declare function normaliseConfig(config?: {
122
+ [K in keyof DisplayConfig]?: unknown;
123
+ }): DisplayConfig;
117
124
  export declare function transitionDisplay(saved: Partial<DisplayState> | undefined, msg: DisplayMessage, suppliedConfig?: Partial<DisplayConfig>, now?: Date): {
118
125
  state: DisplayState;
119
126
  commands: DisplayCommand[];
120
127
  events: DisplayOutputEvent[];
121
- traces: {
122
- event: string;
123
- outcome: string;
124
- reason: string | null;
125
- details: Record<string, unknown>;
128
+ targetStates: {
129
+ theatre: DisplayTargetState;
126
130
  }[];
131
+ traces: TraceEntry<Record<string, unknown>>[];
127
132
  status: {
128
133
  phase: string;
129
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) {
@@ -138,9 +136,14 @@ function modeSatisfied(state, config) {
138
136
  function transitionDisplay(saved, msg, suppliedConfig = {}, now = new Date()) {
139
137
  const config = normaliseConfig(suppliedConfig);
140
138
  const state = initialState(saved);
139
+ const previousPhase = state.phase;
140
+ // Set when a device reading is stored: only then may a settled display
141
+ // report itself ready again.
142
+ let observationAccepted = false;
141
143
  const event = msg?.display;
142
144
  const commands = [];
143
145
  const events = [];
146
+ const targetStates = [];
144
147
  const traces = [];
145
148
  function trace(name, outcome, reason = null, details = {}) {
146
149
  traces.push({ event: name, outcome, reason, details });
@@ -153,6 +156,20 @@ function transitionDisplay(saved, msg, suppliedConfig = {}, now = new Date()) {
153
156
  events.push(displayEvent("failed", state, { failure: state.failure }));
154
157
  trace("transition", "failed", reason, { device, operation });
155
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
+ }
156
173
  function issue(device, operation, command, timeoutMs, retryable = true) {
157
174
  const attempt = command.attempt || 1;
158
175
  state.pending = {
@@ -340,6 +357,7 @@ function transitionDisplay(saved, msg, suppliedConfig = {}, now = new Date()) {
340
357
  };
341
358
  }
342
359
  state.seen[device] = true;
360
+ observationAccepted = true;
343
361
  state.querying[device] = false;
344
362
  trace("observation", "accepted", null, { device });
345
363
  if (state.phase === "ready" && !state.pending && state.desired &&
@@ -402,16 +420,7 @@ function transitionDisplay(saved, msg, suppliedConfig = {}, now = new Date()) {
402
420
  }
403
421
  if (now.getTime() >= pending.deadlineAt) {
404
422
  if (pending.retryable && pending.attempt < config.maxAttempts) {
405
- const attempt = pending.attempt + 1;
406
- const retried = { ...pending.command, attempt };
407
- commands.push(retried);
408
- pending.command = retried;
409
- pending.attempt = attempt;
410
- const timeout = pending.device === "tv" ? config.tvTimeoutMs : config.screenTimeoutMs;
411
- pending.deadlineAt = now.getTime() + timeout;
412
- pending.nextAt = now.getTime() + config.pollMs;
413
- trace("command", "retried", null, { device: pending.device, operation: pending.operation, attempt });
414
- state.lastAttempt = Math.max(state.lastAttempt, attempt);
423
+ retry(pending, null);
415
424
  return;
416
425
  }
417
426
  return fail(pending.device, pending.operation, pending.operation === "projector_settle" ? "projector-power-unsettled" : "confirmation-timeout");
@@ -488,15 +497,7 @@ function transitionDisplay(saved, msg, suppliedConfig = {}, now = new Date()) {
488
497
  else if (state.pending && state.pending.device === event.device &&
489
498
  state.pending.command.operation === event.operation) {
490
499
  if (state.pending.retryable && state.pending.attempt < config.maxAttempts) {
491
- const attempt = state.pending.attempt + 1;
492
- const retried = { ...state.pending.command, attempt };
493
- state.pending.command = retried;
494
- state.pending.attempt = attempt;
495
- commands.push(retried);
496
- trace("command", "retried", event.reason || "transport-failed", {
497
- device: event.device, operation: state.pending.operation, attempt
498
- });
499
- state.lastAttempt = Math.max(state.lastAttempt, attempt);
500
+ retry(state.pending, event.reason || "transport-failed");
500
501
  }
501
502
  else {
502
503
  fail(event.device, state.pending.operation, event.reason || "transport-failed");
@@ -509,9 +510,59 @@ function transitionDisplay(saved, msg, suppliedConfig = {}, now = new Date()) {
509
510
  else if (event.kind === "tick") {
510
511
  handleTick(event);
511
512
  }
513
+ else if (event.kind === "refresh") {
514
+ // Re-confirm a settled display from fresh readings; its target state
515
+ // follows them. These queries are not discovery, so a failed one is
516
+ // ignored rather than failing the request.
517
+ if (state.desired && state.phase === "ready" && !state.pending) {
518
+ for (const device of DEVICES)
519
+ commands.push(queryFor(state, device));
520
+ trace("refresh", "querying");
521
+ }
522
+ else {
523
+ trace("refresh", "reported", null, { phase: state.phase });
524
+ }
525
+ }
512
526
  else {
513
527
  throw new Error("unknown display event kind");
514
528
  }
529
+ // The theatre activity controller's view of this target. A settled display
530
+ // reports ready only with a reading taken in this event, stamped with the
531
+ // oldest of the device readings every mode relies on, so it is only as
532
+ // fresh as its least recent confirmation.
533
+ if (state.desired) {
534
+ const readings = DEVICES.map((device) => (0, observation_time_1.parseObservedAt)(state.observed[device]?.observedAt));
535
+ const confirmedMs = readings.every((ms) => ms !== null) ? Math.min(...readings) : null;
536
+ const status = state.phase === "manual_override"
537
+ ? "transitioning"
538
+ : (0, target_state_1.asTargetStatus)(state.phase, "confirming");
539
+ if (!(status === "ready" && previousPhase === "ready" && !observationAccepted)) {
540
+ const theatre = (0, target_state_1.targetStateEvent)({
541
+ target: "display",
542
+ requestId: state.desired.requestId,
543
+ generation: state.desired.generation,
544
+ status,
545
+ observedAt: status === "ready" && confirmedMs !== null ? new Date(confirmedMs).toISOString() : now.toISOString(),
546
+ details: {
547
+ mode: state.desired.mode,
548
+ observed: {
549
+ tv: state.observed.tv?.power ?? null,
550
+ screen: state.observed.screen?.position ?? null,
551
+ projector: state.observed.projector?.power ?? null
552
+ },
553
+ recovery: { mode: state.phase === "ready" ? state.desired.mode : null },
554
+ metrics: {
555
+ attempts: state.lastAttempt,
556
+ retries: Math.max(0, state.lastAttempt - 1),
557
+ fallbackUsed: state.fallbackUsed
558
+ }
559
+ },
560
+ classification: state.classification,
561
+ failure: state.failure
562
+ });
563
+ targetStates.push({ theatre });
564
+ }
565
+ }
515
566
  events.unshift(displayEvent("state", state, {
516
567
  phase: state.phase,
517
568
  observed: state.observed,
@@ -523,6 +574,6 @@ function transitionDisplay(saved, msg, suppliedConfig = {}, now = new Date()) {
523
574
  fallbackUsed: state.fallbackUsed
524
575
  }
525
576
  }));
526
- return { state, commands, events, traces, status: statusFor(state) };
577
+ return { state, commands, events, targetStates, traces, status: statusFor(state) };
527
578
  }
528
579
  //# sourceMappingURL=display-mode-controller.js.map
@@ -0,0 +1,11 @@
1
+ export interface LightLevels {
2
+ sleepBrightnessPct: number;
3
+ maxBrightnessPct: number;
4
+ sleepColorTempKelvin: number;
5
+ maxColorTempKelvin: number;
6
+ }
7
+ export interface LightStyle {
8
+ brightness: number;
9
+ color_temp: number;
10
+ }
11
+ export declare function styleAtLevel(level: number, levels: LightLevels): LightStyle;
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.styleAtLevel = styleAtLevel;
4
+ function styleAtLevel(level, levels) {
5
+ const percent = levels.sleepBrightnessPct + (levels.maxBrightnessPct - levels.sleepBrightnessPct) * level;
6
+ // Colour moves evenly in mireds, the unit bulbs take: equal mired steps look
7
+ // evenly spaced, where equal kelvin steps would bunch up at the cool end.
8
+ const sleepMired = 1_000_000 / levels.sleepColorTempKelvin;
9
+ const dayMired = 1_000_000 / levels.maxColorTempKelvin;
10
+ return {
11
+ brightness: Math.min(254, Math.max(1, Math.round(percent * 254 / 100))),
12
+ color_temp: Math.round(sleepMired + (dayMired - sleepMired) * level)
13
+ };
14
+ }
15
+ //# sourceMappingURL=light-styling.js.map