@avantics/node-red-home-automation 2.2.1 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_BED_TIME = exports.DEFAULT_WAKE_TIME = exports.WIND_DOWN_MINUTES = exports.WAKE_RISE_MINUTES = void 0;
4
+ exports.clockMinutes = clockMinutes;
5
+ exports.resolveSchedule = resolveSchedule;
6
+ exports.scheduleLevel = scheduleLevel;
7
+ // A daily wake and bed schedule, and how far into the day a given moment is.
8
+ // Pure: it knows nothing about lights, and takes the time it is asked about.
9
+ // After waking, the day level rises over this long; before bed it winds down
10
+ // over the three hours that evidence on evening light exposure points to
11
+ // (Brown et al. 2022, PLOS Biology).
12
+ exports.WAKE_RISE_MINUTES = 60;
13
+ exports.WIND_DOWN_MINUTES = 180;
14
+ // A conventional day, used until a room is given its own times.
15
+ exports.DEFAULT_WAKE_TIME = "07:00";
16
+ exports.DEFAULT_BED_TIME = "23:00";
17
+ const MINUTES_PER_DAY = 24 * 60;
18
+ const CLOCK_TIME = /^([01]\d|2[0-3]):([0-5]\d)$/;
19
+ // Minutes after midnight for an "HH:MM" clock time, or null if it is not one.
20
+ function clockMinutes(value) {
21
+ const match = typeof value === "string" ? CLOCK_TIME.exec(value.trim()) : null;
22
+ return match ? Number(match[1]) * 60 + Number(match[2]) : null;
23
+ }
24
+ // A usable schedule from configured times: a blank time takes its default;
25
+ // each must be "HH:MM" and they must differ.
26
+ function resolveSchedule(wakeTime, bedTime) {
27
+ const wake = (typeof wakeTime === "string" ? wakeTime.trim() : "") || exports.DEFAULT_WAKE_TIME;
28
+ const bed = (typeof bedTime === "string" ? bedTime.trim() : "") || exports.DEFAULT_BED_TIME;
29
+ const wakeMinutes = clockMinutes(wake);
30
+ const bedMinutes = clockMinutes(bed);
31
+ if (wakeMinutes === null || bedMinutes === null)
32
+ throw new Error("wake and bed times must both be HH:MM (24-hour)");
33
+ if (wakeMinutes === bedMinutes)
34
+ throw new Error("wake and bed times must differ");
35
+ return { wakeTime: wake, bedTime: bed };
36
+ }
37
+ // Ease in and out, so neither end of a ramp is a visible step.
38
+ function ease(fraction) {
39
+ return fraction * fraction * (3 - 2 * fraction);
40
+ }
41
+ // The day level, from 0 (asleep) to 1 (full day), for the given local time.
42
+ // Times wrap at midnight, so a bed time after midnight or a wake time later
43
+ // than the bed time both work. A waking day shorter than the rise and the
44
+ // wind-down together shortens both in proportion.
45
+ function scheduleLevel(now, wakeTime, bedTime) {
46
+ const wake = clockMinutes(wakeTime);
47
+ const bed = clockMinutes(bedTime);
48
+ if (wake === null || bed === null || wake === bed)
49
+ throw new Error("wake and bed times must be different HH:MM times");
50
+ const awakeMinutes = (bed - wake + MINUTES_PER_DAY) % MINUTES_PER_DAY;
51
+ const minuteOfDay = now.getHours() * 60 + now.getMinutes() + now.getSeconds() / 60;
52
+ const sinceWake = (minuteOfDay - wake + MINUTES_PER_DAY) % MINUTES_PER_DAY;
53
+ if (sinceWake >= awakeMinutes)
54
+ return 0;
55
+ const shrink = Math.min(1, awakeMinutes / (exports.WAKE_RISE_MINUTES + exports.WIND_DOWN_MINUTES));
56
+ const rise = exports.WAKE_RISE_MINUTES * shrink;
57
+ const windDown = exports.WIND_DOWN_MINUTES * shrink;
58
+ if (sinceWake < rise)
59
+ return ease(sinceWake / rise);
60
+ const untilBed = awakeMinutes - sinceWake;
61
+ return untilBed < windDown ? ease(untilBed / windDown) : 1;
62
+ }
63
+ //# sourceMappingURL=circadian-schedule.js.map
@@ -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
@@ -105,10 +105,23 @@ export type DisplayInputEvent = {
105
105
  } | {
106
106
  kind: "tick";
107
107
  generation?: number;
108
+ } | {
109
+ kind: "refresh";
108
110
  };
109
111
  export interface DisplayMessage {
110
112
  display?: DisplayInputEvent;
111
113
  }
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
+ }
112
125
  export interface DisplayOutputEvent {
113
126
  display: Record<string, unknown>;
114
127
  }
@@ -118,6 +131,9 @@ export declare function transitionDisplay(saved: Partial<DisplayState> | undefin
118
131
  state: DisplayState;
119
132
  commands: DisplayCommand[];
120
133
  events: DisplayOutputEvent[];
134
+ targetStates: {
135
+ theatre: DisplayTargetState;
136
+ }[];
121
137
  traces: {
122
138
  event: string;
123
139
  outcome: string;
@@ -138,9 +138,14 @@ function modeSatisfied(state, config) {
138
138
  function transitionDisplay(saved, msg, suppliedConfig = {}, now = new Date()) {
139
139
  const config = normaliseConfig(suppliedConfig);
140
140
  const state = initialState(saved);
141
+ const previousPhase = state.phase;
142
+ // Set when a device reading is stored: only then may a settled display
143
+ // report itself ready again.
144
+ let observationAccepted = false;
141
145
  const event = msg?.display;
142
146
  const commands = [];
143
147
  const events = [];
148
+ const targetStates = [];
144
149
  const traces = [];
145
150
  function trace(name, outcome, reason = null, details = {}) {
146
151
  traces.push({ event: name, outcome, reason, details });
@@ -340,6 +345,7 @@ function transitionDisplay(saved, msg, suppliedConfig = {}, now = new Date()) {
340
345
  };
341
346
  }
342
347
  state.seen[device] = true;
348
+ observationAccepted = true;
343
349
  state.querying[device] = false;
344
350
  trace("observation", "accepted", null, { device });
345
351
  if (state.phase === "ready" && !state.pending && state.desired &&
@@ -509,9 +515,62 @@ function transitionDisplay(saved, msg, suppliedConfig = {}, now = new Date()) {
509
515
  else if (event.kind === "tick") {
510
516
  handleTick(event);
511
517
  }
518
+ else if (event.kind === "refresh") {
519
+ // Re-confirm a settled display from fresh readings; its target state
520
+ // follows them. These queries are not discovery, so a failed one is
521
+ // ignored rather than failing the request.
522
+ if (state.desired && state.phase === "ready" && !state.pending) {
523
+ for (const device of DEVICES)
524
+ commands.push(queryFor(state, device));
525
+ trace("refresh", "querying");
526
+ }
527
+ else {
528
+ trace("refresh", "reported", null, { phase: state.phase });
529
+ }
530
+ }
512
531
  else {
513
532
  throw new Error("unknown display event kind");
514
533
  }
534
+ // The theatre activity controller's view of this target. A settled display
535
+ // reports ready only with a reading taken in this event, stamped with the
536
+ // oldest of the device readings every mode relies on, so it is only as
537
+ // fresh as its least recent confirmation.
538
+ if (state.desired) {
539
+ const readings = DEVICES.map((device) => (0, observation_time_1.parseObservedAt)(state.observed[device]?.observedAt));
540
+ const confirmedMs = readings.every((ms) => ms !== null) ? Math.min(...readings) : null;
541
+ const status = state.phase === "manual_override"
542
+ ? "transitioning"
543
+ : state.phase === "idle" ? "confirming" : state.phase;
544
+ if (!(status === "ready" && previousPhase === "ready" && !observationAccepted)) {
545
+ const theatre = {
546
+ kind: "target_state",
547
+ target: "display",
548
+ requestId: state.desired.requestId,
549
+ generation: state.desired.generation,
550
+ status,
551
+ observedAt: status === "ready" && confirmedMs !== null ? new Date(confirmedMs).toISOString() : now.toISOString(),
552
+ details: {
553
+ mode: state.desired.mode,
554
+ observed: {
555
+ tv: state.observed.tv?.power ?? null,
556
+ screen: state.observed.screen?.position ?? null,
557
+ projector: state.observed.projector?.power ?? null
558
+ },
559
+ recovery: { mode: state.phase === "ready" ? state.desired.mode : null },
560
+ metrics: {
561
+ attempts: state.lastAttempt,
562
+ retries: Math.max(0, state.lastAttempt - 1),
563
+ fallbackUsed: state.fallbackUsed
564
+ }
565
+ }
566
+ };
567
+ if (state.classification)
568
+ theatre.classification = state.classification;
569
+ if (state.failure)
570
+ theatre.failure = { ...state.failure };
571
+ targetStates.push({ theatre });
572
+ }
573
+ }
515
574
  events.unshift(displayEvent("state", state, {
516
575
  phase: state.phase,
517
576
  observed: state.observed,
@@ -523,6 +582,6 @@ function transitionDisplay(saved, msg, suppliedConfig = {}, now = new Date()) {
523
582
  fallbackUsed: state.fallbackUsed
524
583
  }
525
584
  }));
526
- return { state, commands, events, traces, status: statusFor(state) };
585
+ return { state, commands, events, targetStates, traces, status: statusFor(state) };
527
586
  }
528
587
  //# 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
@@ -89,8 +89,9 @@ function transitionOccupancy(saved, input, config) {
89
89
  }
90
90
  }
91
91
  else if (usesPresence && state.presenceKnown && state.presenceActive) {
92
- state.occupied = true;
93
- trace("motion", "held", "presence-active");
92
+ // Presence only holds occupancy that motion established; it never
93
+ // establishes it, so the state (and what was last emitted) is unchanged.
94
+ trace("motion", state.occupied ? "held" : "unchanged", state.occupied ? "presence-active" : "motion-required");
94
95
  }
95
96
  else if (!wasKnown || wasActive || state.occupied) {
96
97
  emit(false, "all-sources-inactive");
@@ -1,23 +1,24 @@
1
+ import { type CircadianLighting } from "./circadian";
2
+ import type { LightLevels } from "./light-styling";
1
3
  export interface RoomTarget {
2
4
  id: string;
3
5
  stateTopic: string;
4
6
  commandTopic: string;
5
7
  }
6
- export interface RoomConfig {
8
+ export interface RoomConfig extends LightLevels {
7
9
  area: string;
8
10
  displayName: string;
9
11
  targets: RoomTarget[];
10
12
  initialSleep: boolean;
11
- latitude: number;
12
- longitude: number;
13
13
  sleepBrightnessPct: number;
14
14
  maxBrightnessPct: number;
15
- minBrightnessPct: number;
16
15
  sleepColorTempKelvin: number;
17
- minColorTempKelvin: number;
18
16
  maxColorTempKelvin: number;
19
17
  refreshTransitionSeconds: number;
20
18
  initialTransitionSeconds: number;
19
+ wakeTime?: string;
20
+ bedTime?: string;
21
+ lighting?: CircadianLighting;
21
22
  }
22
23
  export interface RoomObservation {
23
24
  on: boolean;
@@ -84,17 +85,11 @@ export declare function fingerprint(payload: unknown): string;
84
85
  export declare function createRoomState(config: RoomConfig, saved?: Partial<RoomState> & {
85
86
  manual?: Record<string, boolean>;
86
87
  }): RoomState;
87
- export declare function sunPosition(now: Date, config: Pick<RoomConfig, "latitude" | "longitude">): number;
88
88
  export declare function adaptivePayload(lightState: string, isRefresh: boolean, sleeping: boolean, now: Date, config: RoomConfig): {
89
89
  state: string;
90
- brightness?: undefined;
91
- color_temp?: undefined;
92
- transition?: undefined;
93
- } | {
94
- state: string;
95
- brightness: number;
96
- color_temp: number;
97
- transition: number;
90
+ brightness?: number;
91
+ color_temp?: number;
92
+ transition?: number;
98
93
  };
99
94
  export declare function transitionRoom(saved: Partial<RoomState> | undefined, msg: RoomMessage, config: RoomConfig, nowValue?: Date | string | number): {
100
95
  state: RoomState;
@@ -3,13 +3,11 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.parsePayload = parsePayload;
4
4
  exports.fingerprint = fingerprint;
5
5
  exports.createRoomState = createRoomState;
6
- exports.sunPosition = sunPosition;
7
6
  exports.adaptivePayload = adaptivePayload;
8
7
  exports.transitionRoom = transitionRoom;
9
- const SunCalc = require("suncalc");
10
- function clamp(value, minimum, maximum) {
11
- return Math.max(minimum, Math.min(maximum, value));
12
- }
8
+ const circadian_1 = require("./circadian");
9
+ const circadian_refresh_1 = require("./circadian-refresh");
10
+ const circadian_schedule_1 = require("./circadian-schedule");
13
11
  function parsePayload(payload) {
14
12
  if (typeof payload !== "string")
15
13
  return payload;
@@ -51,64 +49,18 @@ function createRoomState(config, saved = {}) {
51
49
  sleeping: saved.sleeping === undefined ? config.initialSleep : saved.sleeping === true
52
50
  };
53
51
  }
54
- // The sun-position curve below and the brightness and colour-temperature rules
55
- // in adaptivePayload are adapted (ported to TypeScript and modified) from
56
- // Adaptive Lighting by basnijholt, https://github.com/basnijholt/adaptive-lighting
57
- // (custom_components/adaptive_lighting/color_and_brightness.py), licensed under
58
- // Apache-2.0; see THIRD-PARTY-NOTICES.md. They are due to be replaced by an
59
- // original implementation.
60
- function sunPosition(now, config) {
61
- const events = [];
62
- for (const dayOffset of [-1, 0, 1]) {
63
- const date = new Date(now);
64
- date.setHours(12, 0, 0, 0);
65
- date.setDate(date.getDate() + dayOffset);
66
- const times = SunCalc.getTimes(date, config.latitude, config.longitude);
67
- for (const [name, at] of [
68
- ["sunrise", times.sunrise],
69
- ["noon", times.solarNoon],
70
- ["sunset", times.sunset],
71
- ["midnight", times.nadir]
72
- ]) {
73
- if (at instanceof Date && Number.isFinite(at.getTime()))
74
- events.push({ name, at: at.getTime() });
75
- }
76
- }
77
- events.sort((left, right) => left.at - right.at);
78
- const target = now.getTime();
79
- const nextIndex = events.findIndex((event) => event.at > target);
80
- if (nextIndex < 1)
81
- throw new Error("cannot bracket the current solar event");
82
- const previous = events[nextIndex - 1];
83
- const next = events[nextIndex];
84
- if (!previous || !next)
85
- throw new Error("cannot bracket the current solar event");
86
- const nextIsHorizon = next.name === "sunrise" || next.name === "sunset";
87
- const h = nextIsHorizon ? previous.at : next.at;
88
- const x = nextIsHorizon ? next.at : previous.at;
89
- const sign = next.name === "sunset" || next.name === "noon" ? 1 : -1;
90
- return clamp(sign * (1 - Math.pow((target - h) / (h - x), 2)), -1, 1);
52
+ // The circadian lighting a room uses: the one passed in, or the wake and bed
53
+ // schedule from its configuration.
54
+ function lightingFor(config) {
55
+ return config.lighting ?? (0, circadian_1.scheduledLighting)((0, circadian_schedule_1.resolveSchedule)(config.wakeTime, config.bedTime), config);
91
56
  }
92
- // Brightness and colour-temperature rules adapted from Adaptive Lighting
93
- // (Apache-2.0); see the note above sunPosition.
57
+ // A circadian light command for this moment.
94
58
  function adaptivePayload(lightState, isRefresh, sleeping, now, config) {
95
59
  if (lightState === "OFF")
96
60
  return { state: lightState };
97
- const position = sunPosition(now, config);
98
- const brightnessPct = sleeping
99
- ? config.sleepBrightnessPct
100
- : position > 0
101
- ? config.maxBrightnessPct
102
- : (config.maxBrightnessPct - config.minBrightnessPct) * (1 + position) + config.minBrightnessPct;
103
- const kelvin = sleeping
104
- ? config.sleepColorTempKelvin
105
- : position > 0
106
- ? 5 * Math.round((config.minColorTempKelvin + (config.maxColorTempKelvin - config.minColorTempKelvin) * position) / 5)
107
- : config.minColorTempKelvin;
108
61
  return {
109
62
  state: lightState,
110
- brightness: clamp(Math.round(brightnessPct * 254 / 100), 1, 254),
111
- color_temp: Math.floor(1000000 / kelvin),
63
+ ...lightingFor(config).styleAt(now, sleeping),
112
64
  transition: isRefresh ? config.refreshTransitionSeconds : config.initialTransitionSeconds
113
65
  };
114
66
  }
@@ -202,7 +154,7 @@ function transitionRoom(saved, msg, config, nowValue = new Date()) {
202
154
  name: config.displayName + " Circadian Lighting",
203
155
  unique_id: objectId,
204
156
  default_entity_id: "switch." + objectId,
205
- icon: "mdi:theme-light-dark",
157
+ icon: "mdi:clock-time-seven-outline",
206
158
  command_topic: "home/" + config.area + "/circadian/set",
207
159
  state_topic: "home/" + config.area + "/circadian/state",
208
160
  payload_on: "ON",
@@ -231,6 +183,11 @@ function transitionRoom(saved, msg, config, nowValue = new Date()) {
231
183
  for (const target of config.targets) {
232
184
  if (!intendedOn(target.id) || controlOf(target.id) !== "in-control")
233
185
  continue;
186
+ // Nothing to change when the light last reported exactly this style.
187
+ if ((0, circadian_refresh_1.alreadyStyled)(lightingFor(config).styleAt(now, state.sleeping), state.observed[target.id])) {
188
+ trace("refresh", "skipped", "already-at-level", { target: target.id });
189
+ continue;
190
+ }
234
191
  commands.push(command(target.id, adaptivePayload("ON", true, state.sleeping, now, config), source));
235
192
  }
236
193
  return commands.filter((entry) => entry !== null);
@@ -26,6 +26,7 @@ export interface SourceObservation {
26
26
  sourceId: string;
27
27
  status: SourceObservationStatus;
28
28
  observedAt: string;
29
+ confirmedAt?: string;
29
30
  application: string | null;
30
31
  playback: SourcePlaybackState;
31
32
  }
@@ -51,6 +52,7 @@ export interface SourceState {
51
52
  classification: "manual_override" | null;
52
53
  lastAttempt: number;
53
54
  fallbackUsed: boolean;
55
+ refreshAsked: boolean;
54
56
  }
55
57
  export type SourceEvent = {
56
58
  kind: "intent";
@@ -105,7 +105,8 @@ function initialState(saved = {}, sources = {}) {
105
105
  lastAttempt: Number.isInteger(saved.lastAttempt) && (saved.lastAttempt ?? -1) >= 0
106
106
  ? saved.lastAttempt
107
107
  : 0,
108
- fallbackUsed: saved.fallbackUsed === true
108
+ fallbackUsed: saved.fallbackUsed === true,
109
+ refreshAsked: saved.refreshAsked === true
109
110
  };
110
111
  }
111
112
  function commandFor(state, operation, attempt = 1) {
@@ -163,7 +164,7 @@ function targetEvent(state, now, sources) {
163
164
  requestId: state.desired.requestId,
164
165
  generation: state.generation,
165
166
  status: targetStatus(state.phase),
166
- observedAt: state.observed?.observedAt ?? iso(now),
167
+ observedAt: state.observed?.confirmedAt ?? state.observed?.observedAt ?? iso(now),
167
168
  sourceId: state.desired.sourceId,
168
169
  action: state.desired.action,
169
170
  details: {
@@ -319,6 +320,7 @@ function transitionSource(saved, msg, suppliedConfig = {}, nowValue = new Date()
319
320
  };
320
321
  state.generation = event.generation;
321
322
  state.observed = null;
323
+ state.refreshAsked = false;
322
324
  state.pending = null;
323
325
  state.failure = null;
324
326
  state.blockedGeneration = null;
@@ -383,6 +385,10 @@ function transitionSource(saved, msg, suppliedConfig = {}, nowValue = new Date()
383
385
  application,
384
386
  playback
385
387
  };
388
+ if (state.refreshAsked) {
389
+ state.observed.confirmedAt = new Date(Math.max(bounded.ms, nowMs)).toISOString();
390
+ state.refreshAsked = false;
391
+ }
386
392
  reconcileObservation();
387
393
  }
388
394
  function acceptCommandResult(event) {
@@ -442,7 +448,17 @@ function transitionSource(saved, msg, suppliedConfig = {}, nowValue = new Date()
442
448
  else if (event.kind === "tick") {
443
449
  tick(event);
444
450
  }
451
+ else if (event.kind === "refresh" && state.desired && state.phase === "ready" && !state.pending &&
452
+ descriptor()?.confirmation !== "unavailable") {
453
+ // Re-read a settled source without putting it back into confirmation: it
454
+ // stays ready, and its target state follows the reading. A refresh that
455
+ // is never answered leaves it to the activity controller to report.
456
+ commands.push(commandFor(state, "observe"));
457
+ state.refreshAsked = true;
458
+ trace("refresh", "querying", null, { sourceId: state.desired.sourceId });
459
+ }
445
460
  else if (event.kind === "startup" || event.kind === "refresh") {
461
+ state.refreshAsked = false;
446
462
  if (state.desired) {
447
463
  if (state.desired.sourceId === null || descriptor()?.confirmation === "unavailable") {
448
464
  markUnavailable(state.desired.sourceId === null ? "unknown-active-source" : "unobservable-source");
@@ -469,7 +485,8 @@ function transitionSource(saved, msg, suppliedConfig = {}, nowValue = new Date()
469
485
  else {
470
486
  throw new Error("unknown source capability event kind");
471
487
  }
472
- const outputEvent = targetEvent(state, now, config.sources);
488
+ // A refresh of a settled source reports nothing until its reading arrives.
489
+ const outputEvent = event.kind === "refresh" && state.refreshAsked ? null : targetEvent(state, now, config.sources);
473
490
  if (outputEvent)
474
491
  events.push(outputEvent);
475
492
  return { state, commands, events, traces, status: statusFor(state) };
@@ -34,5 +34,14 @@
34
34
  <p>Send protocol observations as <code>msg.avr = {kind: "observed", line: msg.payload}</code>.</p>
35
35
  <p>Send activity requests as <code>msg.avr = {kind: "intent", requestId, generation, power: "on", source: "shield"}</code>. Omit <code>source</code> to preserve the current input, or use <code>power: "standby"</code> to stop the AVR.</p>
36
36
  <p>Send volume requests as <code>msg.avr = {kind: "volume", requestId, mode: "absolute", value: 30}</code> or use <code>mode: "relative"</code> with a positive or negative delta. The controller applies configured bounds, accumulates rapid relative requests, confirms fresh <code>MV</code> evidence and releases ownership so external adjustments are preserved.</p>
37
- <p>Send <code>kind: "startup"</code> after deployment to discard stale observations and query the receiver. Output 1 connects to a TCP output node; output 2 emits state plus ready, failed, rejected, superseded and volume results.</p>
37
+ <p>Send <code>kind: "startup"</code> after deployment to discard stale observations and query the receiver; a volume request still pending then is reported as failed with reason <code>restart</code>. Send <code>kind: "refresh"</code> to re-read the receiver without disturbing work in flight. Output 1 connects to a TCP output node; output 2 emits state plus ready, failed, rejected, superseded and volume results.</p>
38
+ <p>While it has a request, output 2 also carries <code>msg.theatre = {kind: "target_state", target: "avr", requestId, generation, status, observedAt, details}</code>, so it can be wired straight back to a theatre activity controller. A ready state is stamped with the oldest receiver reading the request relies on, and a <code>refresh</code> is answered once the receiver reports again.</p>
39
+ <h3>Volume results</h3>
40
+ <dl class="message-properties">
41
+ <dt>volume_ready</dt><dd><code>{kind, area, requestId, volume, bounded}</code>: confirmed by a fresh reading.</dd>
42
+ <dt>volume_rejected</dt><dd><code>{kind, area, requestId, reason}</code>: not sent, for example <code>receiver-not-ready</code> or an invalid request.</dd>
43
+ <dt>volume_failed</dt><dd><code>{kind, area, requestId, reason, operation, attempts}</code>: <code>reason</code> is <code>attempts-exhausted</code> (with the operation and attempts) or <code>restart</code> (operation and attempts are <code>null</code>).</dd>
44
+ <dt>volume_manual_override</dt><dd><code>{kind, area, requestId, reason, observed, target}</code>: the receiver moved elsewhere while the request was in flight.</dd>
45
+ <dt>volume_external</dt><dd><code>{kind, area, previous, observed}</code>: a change made outside any request.</dd>
46
+ </dl>
38
47
  </script>
@@ -10,11 +10,6 @@ function parseSources(value) {
10
10
  if (!sources || Array.isArray(sources) || typeof sources !== "object") {
11
11
  throw new Error("sources must be a JSON object");
12
12
  }
13
- for (const [name, code] of Object.entries(sources)) {
14
- if (typeof name !== "string" || typeof code !== "string") {
15
- throw new Error("sources must map names to Denon source codes");
16
- }
17
- }
18
13
  return sources;
19
14
  }
20
15
  const registerAvrController = (RED) => {
@@ -25,18 +20,22 @@ const registerAvrController = (RED) => {
25
20
  let retryTimer;
26
21
  let controllerConfig;
27
22
  try {
28
- controllerConfig = {
23
+ // The same validation the reducer applies, so a bad configuration
24
+ // fails here at deploy rather than on every message.
25
+ controllerConfig = (0, avr_controller_1.normaliseAvrConfig)({
29
26
  area: config.area || "room",
30
27
  sources: parseSources(config.sources),
31
28
  retryMs: Math.max(250, number(config.retryMs, 2000)),
32
29
  maxAttempts: Math.max(1, Math.floor(number(config.maxAttempts, 3))),
33
30
  minVolume: number(config.minVolume, 0),
34
31
  maxVolume: number(config.maxVolume, 60)
35
- };
32
+ });
36
33
  }
37
34
  catch (error) {
35
+ // A short badge; the full reason goes to the log and debug sidebar.
36
+ const reason = error instanceof Error ? error.message : String(error);
38
37
  node.status({ fill: "red", shape: "ring", text: "invalid configuration" });
39
- node.error(error);
38
+ node.error("invalid configuration: " + reason);
40
39
  return;
41
40
  }
42
41
  function updateStatus(status) {
@@ -79,11 +78,12 @@ const registerAvrController = (RED) => {
79
78
  payload: Buffer.from(command.payload, "utf8"),
80
79
  avr_command: command.avrCommand
81
80
  }));
82
- if (commands.length || result.events.length) {
81
+ const outputs = [...result.events, ...result.targetStates];
82
+ if (commands.length || outputs.length) {
83
83
  send([
84
84
  commands.length ? commands : null,
85
- result.events.length
86
- ? result.events.map((event) => ({ payload: undefined, ...event }))
85
+ outputs.length
86
+ ? outputs.map((event) => ({ payload: undefined, ...event }))
87
87
  : null
88
88
  ]);
89
89
  }
@@ -59,8 +59,8 @@
59
59
 
60
60
  <script type="text/html" data-help-name="home-display-mode-controller">
61
61
  <p>Owns Bravia power, projector lamp power and projector-screen position for <code>off</code>, <code>tv</code> and <code>projector</code> modes.</p>
62
- <p>Send <code>msg.display = {kind: "intent", requestId, generation, mode}</code>. Send <code>kind: "startup"</code> after deployment to query every owned device and reconcile persisted intent.</p>
63
- <p>The Bravia and both Shelly devices use direct LAN APIs. Output 1 is the explicitly named HA/Broadlink projector-power fallback and must connect only to <code>remote.send_command</code> for the projector. Enable “Projector power is fallback” to include its use in activity metrics. Output 2 emits observed state plus ready, manual-override, failed, rejected and superseded results.</p>
62
+ <p>Send <code>msg.display = {kind: "intent", requestId, generation, mode}</code>. Send <code>kind: "startup"</code> after deployment to query every owned device and reconcile persisted intent. Send <code>kind: "refresh"</code> to re-confirm a settled display from fresh readings.</p>
63
+ <p>The Bravia and both Shelly devices use direct LAN APIs. Output 1 carries the projector power toggle (<code>msg.payload = "power"</code> with <code>msg.display_command</code>) for your infrared transport, commanded directly rather than through Home Assistant. Enable “Projector power is fallback” to include its use in activity metrics. Output 2 emits observed state plus ready, manual-override, failed, rejected and superseded results, and <code>msg.theatre</code> target state for the theatre activity controller: wire it straight back to that controller.</p>
64
64
  <p>An unsolicited physical-state change after readiness latches manual ownership. The controller observes and reports it without issuing corrective commands; a newer activity intent resumes automation.</p>
65
65
  <p>The Bravia PSK remains in Node-RED's encrypted credential store and is never emitted in a message or status.</p>
66
66
  </script>
@@ -93,8 +93,9 @@ const registerDisplayModeController = (RED) => {
93
93
  area: config.area || "lounge",
94
94
  component: "display-mode-controller"
95
95
  }, result.traces, now);
96
- if (result.events.length) {
97
- send([null, result.events.map((event) => ({ payload: undefined, ...event }))]);
96
+ const outputs = [...result.events, ...result.targetStates];
97
+ if (outputs.length) {
98
+ send([null, outputs.map((event) => ({ payload: undefined, ...event }))]);
98
99
  }
99
100
  updateStatus(result.status);
100
101
  schedule(result.state);