@avantics/node-red-home-automation 4.0.3 → 5.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 (60) hide show
  1. package/README.md +117 -4
  2. package/contract-examples/switch-gestures.mjs +1 -1
  3. package/contract-examples/volume-ownership.mjs +6 -5
  4. package/dist/lib/activity-lighting-controller.d.ts +2 -0
  5. package/dist/lib/activity-lighting-controller.js +35 -6
  6. package/dist/lib/adopted-request.d.ts +17 -0
  7. package/dist/lib/adopted-request.js +61 -7
  8. package/dist/lib/avr-controller.d.ts +9 -3
  9. package/dist/lib/avr-controller.js +76 -24
  10. package/dist/lib/avr-publishing.d.ts +3 -3
  11. package/dist/lib/avr-publishing.js +11 -5
  12. package/dist/lib/backlighting-controller.d.ts +2 -0
  13. package/dist/lib/backlighting-controller.js +27 -7
  14. package/dist/lib/cover-publishing.js +1 -1
  15. package/dist/lib/denon-protocol.d.ts +5 -1
  16. package/dist/lib/denon-protocol.js +26 -11
  17. package/dist/lib/display-mode-controller.d.ts +12 -5
  18. package/dist/lib/display-mode-controller.js +181 -87
  19. package/dist/lib/house-schedule-publishing.js +1 -1
  20. package/dist/lib/light-styling.d.ts +2 -2
  21. package/dist/lib/light-styling.js +5 -4
  22. package/dist/lib/motion-publishing.js +1 -1
  23. package/dist/lib/occupancy-publishing.js +1 -1
  24. package/dist/lib/power-reading.d.ts +5 -0
  25. package/dist/lib/power-reading.js +13 -0
  26. package/dist/lib/room-controller.d.ts +2 -3
  27. package/dist/lib/room-controller.js +18 -2
  28. package/dist/lib/room-lighting-discovery.js +1 -1
  29. package/dist/lib/room-publishing.d.ts +3 -0
  30. package/dist/lib/shelly-cover.d.ts +46 -0
  31. package/dist/lib/shelly-cover.js +193 -0
  32. package/dist/lib/source-capability-controller.d.ts +2 -0
  33. package/dist/lib/source-capability-controller.js +27 -6
  34. package/dist/lib/switch-policy.d.ts +1 -1
  35. package/dist/lib/switch-policy.js +1 -1
  36. package/dist/lib/theatre-requests.d.ts +29 -0
  37. package/dist/lib/theatre-requests.js +89 -0
  38. package/dist/lib/theatre-state-contract.d.ts +5 -22
  39. package/dist/lib/theatre-state-contract.js +18 -73
  40. package/dist/lib/toggle-power.d.ts +41 -0
  41. package/dist/lib/toggle-power.js +74 -0
  42. package/dist/lib/topic-names.d.ts +1 -0
  43. package/dist/lib/topic-names.js +7 -0
  44. package/dist/lib/{display-transport.d.ts → transports/display-transport.d.ts} +1 -1
  45. package/dist/lib/{display-transport.js → transports/display-transport.js} +32 -7
  46. package/dist/lib/z2m-light.d.ts +8 -0
  47. package/dist/lib/z2m-light.js +64 -3
  48. package/dist/nodes/activity-lighting-controller.html +8 -0
  49. package/dist/nodes/avr-controller.html +28 -6
  50. package/dist/nodes/avr-controller.js +16 -6
  51. package/dist/nodes/display-mode-controller.html +61 -11
  52. package/dist/nodes/display-mode-controller.js +16 -6
  53. package/dist/nodes/room-controller.js +14 -0
  54. package/dist/nodes/shelly-cover.d.ts +3 -0
  55. package/dist/nodes/shelly-cover.html +65 -0
  56. package/dist/nodes/shelly-cover.js +34 -0
  57. package/examples/Home theatre activity.json +5 -5
  58. package/examples/Home theatre equipment.json +4 -4
  59. package/examples/Shelly cover.json +252 -0
  60. package/package.json +3 -2
@@ -5,9 +5,14 @@ exports.theatreRetainedTopics = theatreRetainedTopics;
5
5
  exports.theatreStartingPublications = theatreStartingPublications;
6
6
  exports.theatreStoppingPublications = theatreStoppingPublications;
7
7
  exports.transitionTheatreStateContract = transitionTheatreStateContract;
8
+ // The theatre contract's MQTT and Home Assistant side: it reads activity
9
+ // requests from MQTT, publishes what the activity controller reports as
10
+ // retained topics, and announces the Home Assistant entities. What to do
11
+ // with a request or a snapshot is theatre-requests.ts's.
8
12
  const theatre_profiles_1 = require("./theatre-profiles");
9
13
  const theatre_ha_discovery_1 = require("./theatre-ha-discovery");
10
14
  const theatre_slo_1 = require("./theatre-slo");
15
+ const theatre_requests_1 = require("./theatre-requests");
11
16
  const ha_discovery_1 = require("./ha-discovery");
12
17
  const topic_names_1 = require("./topic-names");
13
18
  function normaliseStateContractConfig(config = {}) {
@@ -20,7 +25,7 @@ function normaliseStateContractConfig(config = {}) {
20
25
  const displayName = String(config.displayName || area).trim();
21
26
  if (discovery && !displayName)
22
27
  throw new Error("displayName is required");
23
- const baseTopic = String(config.baseTopic || `home/${(0, topic_names_1.areaId)(area)}/theatre`).replace(/^\/+|\/+$/g, "");
28
+ const baseTopic = String(config.baseTopic || (0, topic_names_1.homeTopic)(area, "theatre")).replace(/^\/+|\/+$/g, "");
24
29
  const discoveryPrefix = (0, ha_discovery_1.discoveryPrefixSetting)(config.discoveryPrefix);
25
30
  if (!baseTopic || /[+#]/.test(baseTopic))
26
31
  throw new Error("baseTopic must be a concrete MQTT topic");
@@ -45,20 +50,6 @@ function normaliseStateContractConfig(config = {}) {
45
50
  ...(config.idScheme ? { idScheme: config.idScheme } : {})
46
51
  };
47
52
  }
48
- function createState(saved = {}) {
49
- const lastRequest = saved.lastRequest && typeof saved.lastRequest === "object"
50
- ? { ...saved.lastRequest }
51
- : null;
52
- return {
53
- generation: Number.isInteger(saved.generation) && (saved.generation ?? -1) >= 0
54
- ? saved.generation
55
- : 0,
56
- lastRequest,
57
- slo: {
58
- samples: Array.isArray(saved.slo?.samples) ? saved.slo.samples.map((sample) => ({ ...sample })) : []
59
- }
60
- };
61
- }
62
53
  function parsePayload(payload) {
63
54
  let value = payload;
64
55
  if (Buffer.isBuffer(value))
@@ -76,12 +67,6 @@ function parsePayload(payload) {
76
67
  }
77
68
  return value;
78
69
  }
79
- function validTimestamp(value, fallback) {
80
- const timestamp = value === undefined ? fallback : String(value);
81
- if (!Number.isFinite(Date.parse(timestamp)))
82
- throw new Error("requestedAt must be an ISO timestamp");
83
- return timestamp;
84
- }
85
70
  function publication(topic, payload) {
86
71
  return {
87
72
  topic,
@@ -158,25 +143,6 @@ function requestPublications(request, config) {
158
143
  publication((0, theatre_ha_discovery_1.theatreTopic)(base, "readiness"), "unknown")
159
144
  ];
160
145
  }
161
- function asStateSnapshot(value) {
162
- if (!value || typeof value !== "object" || Array.isArray(value)) {
163
- throw new Error("theatre state must be an object");
164
- }
165
- const event = value;
166
- if (event.kind !== "state")
167
- throw new Error("theatre state kind must be state");
168
- if (!Number.isInteger(event.generation) || (event.generation ?? -1) < 0) {
169
- throw new Error("theatre state generation must be a non-negative integer");
170
- }
171
- if (typeof event.currentActivity !== "string" || typeof event.phase !== "string" ||
172
- typeof event.availability !== "string") {
173
- throw new Error("theatre state must define currentActivity, phase and availability");
174
- }
175
- if (!event.targets || typeof event.targets !== "object" || Array.isArray(event.targets)) {
176
- throw new Error("theatre state targets must be an object");
177
- }
178
- return event;
179
- }
180
146
  // Every retained topic the contract publishes, for clearing those it no
181
147
  // longer does after a change: discovery entries, whenever they are published
182
148
  // or cleared at each start, its availability, and its state topics.
@@ -200,7 +166,7 @@ function theatreStoppingPublications(config) {
200
166
  }
201
167
  function transitionTheatreStateContract(saved, msg, suppliedConfig, nowValue = new Date()) {
202
168
  const config = normaliseStateContractConfig(suppliedConfig);
203
- const state = createState(saved);
169
+ const state = (0, theatre_requests_1.createTheatreRequestState)(saved);
204
170
  const now = nowValue instanceof Date ? nowValue : new Date(nowValue);
205
171
  if (!Number.isFinite(now.getTime()))
206
172
  throw new Error("now must be a valid date");
@@ -224,47 +190,26 @@ function transitionTheatreStateContract(saved, msg, suppliedConfig, nowValue = n
224
190
  }
225
191
  else {
226
192
  const payload = parsePayload(msg.payload);
227
- const requestId = String(payload.requestId || "");
228
- const activity = String(payload.activity || "");
229
- if (!topic_names_1.REQUEST_ID.test(requestId))
230
- throw new Error("requestId is invalid");
231
- if (!config.activities.includes(activity))
232
- throw new Error("unknown theatre activity");
233
- const requestedAt = validTimestamp(payload.requestedAt, now.toISOString());
234
- if (state.lastRequest?.requestId === requestId) {
235
- if (state.lastRequest.activity !== activity) {
236
- throw new Error("requestId cannot be reused for another activity");
237
- }
238
- requests.push({ theatre: { kind: "intent", ...state.lastRequest } });
239
- trace("request", "duplicate", null, { requestId, generation: state.lastRequest.generation });
193
+ const outcome = (0, theatre_requests_1.takeTheatreRequest)(state, payload, config.activities, now);
194
+ const request = state.lastRequest;
195
+ requests.push({ theatre: { kind: "intent", ...request } });
196
+ if (outcome === "duplicate") {
197
+ trace("request", "duplicate", null, { requestId: request.requestId, generation: request.generation });
240
198
  }
241
199
  else {
242
- state.generation += 1;
243
- state.lastRequest = { requestId, generation: state.generation, activity, requestedAt };
244
- requests.push({ theatre: { kind: "intent", ...state.lastRequest } });
245
- trace("request", "accepted", null, { requestId, generation: state.generation, activity });
200
+ trace("request", "accepted", null, { requestId: request.requestId, generation: state.generation, activity: request.activity });
246
201
  }
247
- publications.push(...requestPublications(state.lastRequest, config));
202
+ publications.push(...requestPublications(request, config));
248
203
  }
249
204
  }
250
205
  else if (msg.theatre && typeof msg.theatre === "object" && msg.theatre.kind === "state") {
251
- const event = asStateSnapshot(msg.theatre);
252
- if (event.generation < state.generation) {
206
+ const event = (0, theatre_requests_1.asTheatreSnapshot)(msg.theatre);
207
+ const assessment = (0, theatre_requests_1.takeTheatreSnapshot)(state, event, config.slo, now);
208
+ if (!assessment) {
253
209
  trace("state", "ignored", "stale-generation", { generation: event.generation });
254
210
  }
255
211
  else {
256
- state.generation = event.generation;
257
- if (event.requestId && event.desiredActivity) {
258
- state.lastRequest = {
259
- requestId: event.requestId,
260
- generation: event.generation,
261
- activity: event.desiredActivity,
262
- requestedAt: event.requestedAt || event.transitionStartedAt || now.toISOString()
263
- };
264
- }
265
- const slo = (0, theatre_slo_1.evaluateTheatreSlo)(state.slo, event, config.slo, now);
266
- state.slo = slo.state;
267
- publications.push(...statePublications(event, config, slo.assessment));
212
+ publications.push(...statePublications(event, config, assessment));
268
213
  trace("state", "published", null, {
269
214
  generation: event.generation,
270
215
  phase: event.phase,
@@ -0,0 +1,41 @@
1
+ import type { PowerReading } from "./power-reading";
2
+ export declare const TOGGLE_START = "projector_start";
3
+ export declare const TOGGLE_SETTLE = "projector_settle";
4
+ export declare const TOGGLE_SHUTDOWN_OBSERVE = "projector_shutdown_observe";
5
+ export declare const TOGGLE_SHUTDOWN_CONFIRM = "projector_shutdown_confirm";
6
+ export declare const TOGGLE_COOLDOWN = "projector_cooldown";
7
+ export interface TogglePowerTiming {
8
+ pollMs: number;
9
+ queryTimeoutMs: number;
10
+ warmupMs: number;
11
+ minimumWarmupMs: number;
12
+ shutdownConfirmMs: number;
13
+ cooldownMs: number;
14
+ }
15
+ export interface TogglePending<Device, Command> {
16
+ device: Device;
17
+ operation: string;
18
+ command: Command;
19
+ attempt: number;
20
+ retryable: boolean;
21
+ deadlineAt: number;
22
+ nextAt: number;
23
+ readyAt?: number;
24
+ }
25
+ export declare function togglePowerSatisfied(operation: string, power: PowerReading | undefined): boolean | undefined;
26
+ export declare function startReadyAt(nowMs: number, timing: TogglePowerTiming): number;
27
+ export declare function holdForWarmup(pending: {
28
+ operation: string;
29
+ readyAt?: number;
30
+ deadlineAt: number;
31
+ }, power: PowerReading | undefined, nowMs: number): number | null;
32
+ export declare function shutdownRequestPending<Device, Command>(device: Device, command: Command, nowMs: number, timing: TogglePowerTiming): TogglePending<Device, Command>;
33
+ export declare function beginShutdownConfirm(pending: {
34
+ operation: string;
35
+ nextAt: number;
36
+ deadlineAt: number;
37
+ }, nowMs: number, timing: TogglePowerTiming): void;
38
+ export declare function needsShutdownConfirm(pending: {
39
+ operation: string;
40
+ }, power: PowerReading | undefined): boolean;
41
+ export declare function cooldownPending<Device, Command>(device: Device, command: Command, nowMs: number, timing: TogglePowerTiming): TogglePending<Device, Command>;
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TOGGLE_COOLDOWN = exports.TOGGLE_SHUTDOWN_CONFIRM = exports.TOGGLE_SHUTDOWN_OBSERVE = exports.TOGGLE_SETTLE = exports.TOGGLE_START = void 0;
4
+ exports.togglePowerSatisfied = togglePowerSatisfied;
5
+ exports.startReadyAt = startReadyAt;
6
+ exports.holdForWarmup = holdForWarmup;
7
+ exports.shutdownRequestPending = shutdownRequestPending;
8
+ exports.beginShutdownConfirm = beginShutdownConfirm;
9
+ exports.needsShutdownConfirm = needsShutdownConfirm;
10
+ exports.cooldownPending = cooldownPending;
11
+ exports.TOGGLE_START = "projector_start";
12
+ exports.TOGGLE_SETTLE = "projector_settle";
13
+ exports.TOGGLE_SHUTDOWN_OBSERVE = "projector_shutdown_observe";
14
+ exports.TOGGLE_SHUTDOWN_CONFIRM = "projector_shutdown_confirm";
15
+ exports.TOGGLE_COOLDOWN = "projector_cooldown";
16
+ // Whether a toggle-power step is done, from the reading; undefined for an
17
+ // operation that isn't one of them.
18
+ function togglePowerSatisfied(operation, power) {
19
+ switch (operation) {
20
+ case exports.TOGGLE_START: return power === "on";
21
+ case exports.TOGGLE_SETTLE: return power === "on" || power === "standby";
22
+ case exports.TOGGLE_SHUTDOWN_OBSERVE:
23
+ case exports.TOGGLE_SHUTDOWN_CONFIRM:
24
+ case exports.TOGGLE_COOLDOWN: return power === "standby";
25
+ default: return undefined;
26
+ }
27
+ }
28
+ // When a started lamp may count as on: not before the minimum warm-up.
29
+ function startReadyAt(nowMs, timing) {
30
+ return nowMs + timing.minimumWarmupMs;
31
+ }
32
+ // Reading on during the minimum warm-up: when to look again, or null when
33
+ // the reading may stand.
34
+ function holdForWarmup(pending, power, nowMs) {
35
+ if (pending.operation !== exports.TOGGLE_START || pending.readyAt === undefined || power !== "on" || nowMs >= pending.readyAt)
36
+ return null;
37
+ return Math.min(pending.deadlineAt, pending.readyAt);
38
+ }
39
+ // The shutdown's first toggle: read the meter after shutdownConfirmMs.
40
+ function shutdownRequestPending(device, command, nowMs, timing) {
41
+ return {
42
+ device,
43
+ operation: exports.TOGGLE_SHUTDOWN_OBSERVE,
44
+ command,
45
+ attempt: 1,
46
+ retryable: false,
47
+ deadlineAt: nowMs + timing.shutdownConfirmMs + timing.queryTimeoutMs,
48
+ nextAt: nowMs + timing.shutdownConfirmMs
49
+ };
50
+ }
51
+ // Time to read the meter after the shutdown toggle: the step now waits for
52
+ // that reading, for at most queryTimeoutMs.
53
+ function beginShutdownConfirm(pending, nowMs, timing) {
54
+ pending.operation = exports.TOGGLE_SHUTDOWN_CONFIRM;
55
+ pending.nextAt = nowMs + timing.queryTimeoutMs;
56
+ pending.deadlineAt = pending.nextAt;
57
+ }
58
+ // Still on after the shutdown toggle: it wants the confirming toggle.
59
+ function needsShutdownConfirm(pending, power) {
60
+ return pending.operation === exports.TOGGLE_SHUTDOWN_CONFIRM && power === "on";
61
+ }
62
+ // After the confirming toggle: the cool-down, until it reads standby.
63
+ function cooldownPending(device, command, nowMs, timing) {
64
+ return {
65
+ device,
66
+ operation: exports.TOGGLE_COOLDOWN,
67
+ command,
68
+ attempt: 1,
69
+ retryable: false,
70
+ deadlineAt: nowMs + timing.cooldownMs,
71
+ nextAt: nowMs + timing.pollMs
72
+ };
73
+ }
74
+ //# sourceMappingURL=toggle-power.js.map
@@ -1,4 +1,5 @@
1
1
  export declare const IDENTIFIER: RegExp;
2
2
  export declare function areaId(area: string): string;
3
+ export declare function homeTopic(area: string, ...path: string[]): string;
3
4
  export declare function publishingArea(area: string, needed: boolean): string;
4
5
  export declare const REQUEST_ID: RegExp;
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.REQUEST_ID = exports.IDENTIFIER = void 0;
4
4
  exports.areaId = areaId;
5
+ exports.homeTopic = homeTopic;
5
6
  exports.publishingArea = publishingArea;
6
7
  // How areas and names become parts of MQTT topics and IDs. Shared by every
7
8
  // node that publishes, whether or not Home Assistant reads what it publishes.
@@ -16,6 +17,12 @@ exports.IDENTIFIER = /^[a-z][a-z0-9_-]*$/;
16
17
  function areaId(area) {
17
18
  return area.toLowerCase().replace(/[^a-z0-9_-]+/g, "_").replace(/^[_-]+|[_-]+$/g, "");
18
19
  }
20
+ // The one place a home/<area ID>/... topic is named, for every node that
21
+ // publishes under its area (or, for the house schedule, its name): the rest
22
+ // of the path follows as given.
23
+ function homeTopic(area, ...path) {
24
+ return ["home", areaId(area), ...path].join("/");
25
+ }
19
26
  // The area of a node that publishes under it, as typed. `needed` says
20
27
  // whether this node's publishing needs one at all.
21
28
  function publishingArea(area, needed) {
@@ -1,4 +1,4 @@
1
- import type { DisplayDevice, DisplayMessage } from "./display-mode-controller";
1
+ import type { DisplayDevice, DisplayMessage } from "../display-mode-controller";
2
2
  interface DeviceResponse {
3
3
  error?: unknown;
4
4
  result?: Array<{
@@ -48,6 +48,14 @@ async function responseJson(response, allowNull = false) {
48
48
  }
49
49
  return body;
50
50
  }
51
+ // The Shelly cover's states, as the display reads a screen.
52
+ const SCREEN_STATES = {
53
+ open: "open",
54
+ closed: "closed",
55
+ opening: "opening",
56
+ closing: "closing",
57
+ stopped: "stopped"
58
+ };
51
59
  class DisplayTransport {
52
60
  tvHost;
53
61
  tvPsk;
@@ -61,7 +69,10 @@ class DisplayTransport {
61
69
  if (!this.tvPsk)
62
70
  throw new Error("tvPsk is required");
63
71
  this.screenHost = host(options.screenHost, "screenHost");
64
- this.projectorMeterHost = host(options.projectorMeterHost, "projectorMeterHost");
72
+ // Optional: without it, the projector's power comes from the flow.
73
+ this.projectorMeterHost = String(options.projectorMeterHost || "").trim()
74
+ ? host(options.projectorMeterHost, "projectorMeterHost")
75
+ : "";
65
76
  this.timeoutMs = Math.max(250, Number(options.timeoutMs || 5000));
66
77
  this.fetch = options.fetch || globalThis.fetch;
67
78
  if (typeof this.fetch !== "function")
@@ -119,8 +130,15 @@ class DisplayTransport {
119
130
  }
120
131
  if (command.device === "screen" && command.operation === "query_position") {
121
132
  const body = await this.shellyGet(this.screenHost, "Cover.GetStatus?id=0");
122
- const position = body.current_pos;
123
- if (typeof position !== "number" || !Number.isFinite(position) || position < 0 || position > 100) {
133
+ const position = typeof body.current_pos === "number" && Number.isFinite(body.current_pos) &&
134
+ body.current_pos >= 0 && body.current_pos <= 100 ? body.current_pos : null;
135
+ // Normalised to open, closed, opening, closing or stopped. A screen
136
+ // that doesn't know its position (not calibrated) still says whether
137
+ // it is fully open or closed, or neither: enough for a screen opened
138
+ // by its own command, even one left part-way, which is then sent
139
+ // open or closed. A position out of range is no reading at all.
140
+ const state = SCREEN_STATES[String(body.state)] ?? "stopped";
141
+ if (body.current_pos !== undefined && body.current_pos !== null && position === null) {
124
142
  const error = new Error("Shelly cover reported no usable position");
125
143
  error.code = "invalid_screen_position";
126
144
  throw error;
@@ -130,17 +148,24 @@ class DisplayTransport {
130
148
  kind: "observed",
131
149
  device: "screen",
132
150
  position,
133
- state: String(body.state || "unknown"),
151
+ state,
134
152
  source: "shelly-cover",
135
153
  ...common
136
154
  }
137
155
  };
138
156
  }
139
- if (command.device === "screen" && command.operation === "set_position") {
140
- await this.shellyPost(this.screenHost, "Cover.GoToPosition", { id: 0, pos: command.position });
157
+ // Open or close: to the position the command carries, or with none,
158
+ // by the screen's own open and close.
159
+ if (command.device === "screen" && (command.operation === "open" || command.operation === "close")) {
160
+ if (typeof command.position === "number") {
161
+ await this.shellyPost(this.screenHost, "Cover.GoToPosition", { id: 0, pos: command.position });
162
+ }
163
+ else {
164
+ await this.shellyPost(this.screenHost, command.operation === "open" ? "Cover.Open" : "Cover.Close", { id: 0 });
165
+ }
141
166
  return null;
142
167
  }
143
- if (command.device === "projector" && command.operation === "query_power") {
168
+ if (command.device === "projector" && command.operation === "query_power" && this.projectorMeterHost) {
144
169
  const body = await this.shellyGet(this.projectorMeterHost, "Switch.GetStatus?id=1");
145
170
  const watts = body.apower;
146
171
  if (typeof watts !== "number" || !Number.isFinite(watts) || watts < 0) {
@@ -11,6 +11,14 @@ export type LightCommand = {
11
11
  color_temp?: number;
12
12
  transition?: number;
13
13
  };
14
+ export declare function zigbeeBrightness(percent: number): number;
15
+ export declare function zigbeeColorTemp(kelvin: number): number;
14
16
  export declare function lightCommand(state: string, style: LightStyle, transitionSeconds: number): LightCommand;
17
+ export declare function lightValues(values: Record<string, unknown>): {
18
+ values: Record<string, unknown>;
19
+ legacy: boolean;
20
+ superseded: string[];
21
+ invalid: string[];
22
+ };
15
23
  export declare function setsLightValues(command: Record<string, unknown>): boolean;
16
24
  export declare function alreadyStyled(style: LightStyle, report: LightReport | undefined): boolean;
@@ -1,7 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.readLightReport = readLightReport;
4
+ exports.zigbeeBrightness = zigbeeBrightness;
5
+ exports.zigbeeColorTemp = zigbeeColorTemp;
4
6
  exports.lightCommand = lightCommand;
7
+ exports.lightValues = lightValues;
5
8
  exports.setsLightValues = setsLightValues;
6
9
  exports.alreadyStyled = alreadyStyled;
7
10
  // A state report, or null when it carries no ON/OFF state.
@@ -11,12 +14,69 @@ function readLightReport(payload) {
11
14
  return null;
12
15
  return { on: state === "ON", brightness: payload.brightness ?? null, color_temp: payload.color_temp ?? null };
13
16
  }
17
+ // Brightness percent as Zigbee2MQTT's 1-254, and kelvin as mireds.
18
+ function zigbeeBrightness(percent) {
19
+ return Math.min(254, Math.max(1, Math.round(percent * 254 / 100)));
20
+ }
21
+ // Rounded after trimming float noise to 12 significant digits, so a mired
22
+ // value that is exactly n.5 in decimal rounds up as it always has, rather than
23
+ // down because its kelvin round trip left it a hair under.
24
+ function zigbeeColorTemp(kelvin) {
25
+ return Math.round(Number((1_000_000 / kelvin).toPrecision(12)));
26
+ }
27
+ function zigbeeStyle(style) {
28
+ return { brightness: zigbeeBrightness(style.brightnessPct), color_temp: zigbeeColorTemp(style.colorTempKelvin) };
29
+ }
14
30
  // A command for a light: OFF on its own, otherwise the state with a style
15
31
  // faded in over the transition.
16
32
  function lightCommand(state, style, transitionSeconds) {
17
33
  if (state === "OFF")
18
34
  return { state };
19
- return { state, ...style, transition: transitionSeconds };
35
+ return { state, ...zigbeeStyle(style), transition: transitionSeconds };
36
+ }
37
+ // A brightness percent or kelvin as a number: a number, or a finite numeric
38
+ // string; null otherwise.
39
+ function numberValue(value) {
40
+ const number = typeof value === "number" ? value : typeof value === "string" && value.trim() !== "" ? Number(value) : NaN;
41
+ return Number.isFinite(number) ? number : null;
42
+ }
43
+ // The package's own value fields and the Zigbee2MQTT field each becomes.
44
+ const NEUTRAL_FIELDS = { brightnessPct: "brightness", colorTempKelvin: "color_temp" };
45
+ // An intent's or profile's values as Zigbee2MQTT fields: brightnessPct and
46
+ // colorTempKelvin converted; anything else (an effect, say) passed on as it
47
+ // is. brightness and color_temp are Zigbee2MQTT's own units, accepted as
48
+ // they are during 5.x and reported as `legacy` so the node can warn; given
49
+ // with the new field too, the new one wins, whatever the order, and the old
50
+ // one is `superseded`. An unusable brightnessPct or colorTempKelvin is
51
+ // `invalid` and never reaches the device.
52
+ function lightValues(values) {
53
+ const converted = {};
54
+ const superseded = [];
55
+ const invalid = [];
56
+ let legacy = false;
57
+ const neutral = {};
58
+ for (const [field, device] of Object.entries(NEUTRAL_FIELDS)) {
59
+ if (!Object.hasOwn(values, field))
60
+ continue;
61
+ const number = numberValue(values[field]);
62
+ if (number === null || (field === "colorTempKelvin" && number <= 0))
63
+ invalid.push(field);
64
+ else
65
+ neutral[device] = field === "brightnessPct" ? zigbeeBrightness(number) : zigbeeColorTemp(number);
66
+ }
67
+ for (const [key, value] of Object.entries(values)) {
68
+ if (Object.hasOwn(NEUTRAL_FIELDS, key))
69
+ continue;
70
+ if (key === "brightness" || key === "color_temp") {
71
+ if (Object.hasOwn(neutral, key)) {
72
+ superseded.push(key);
73
+ continue;
74
+ }
75
+ legacy = true;
76
+ }
77
+ converted[key] = value;
78
+ }
79
+ return { values: { ...converted, ...neutral }, legacy, superseded, invalid };
20
80
  }
21
81
  // Command fields that set a light's values rather than just its power.
22
82
  const VALUE_FIELDS = [
@@ -29,8 +89,9 @@ function setsLightValues(command) {
29
89
  // Whether a light already shows a style, by its own latest report. A bulb
30
90
  // that missed a command reports something else, so it is not "styled".
31
91
  function alreadyStyled(style, report) {
92
+ const expected = zigbeeStyle(style);
32
93
  return report?.on === true &&
33
- Number(report.brightness) === style.brightness &&
34
- Number(report.color_temp) === style.color_temp;
94
+ Number(report.brightness) === expected.brightness &&
95
+ Number(report.color_temp) === expected.color_temp;
35
96
  }
36
97
  //# sourceMappingURL=z2m-light.js.map
@@ -32,6 +32,14 @@
32
32
  <script type="text/html" data-help-name="home-activity-lighting-controller">
33
33
  <p>Applies configuration-owned activity styles only to room lights that are already on and not manually owned.</p>
34
34
  <p>Input <code>msg.activityLighting</code> carries generation-scoped intent, observation, refresh, result or tick events. Output 1 emits standard <code>msg.lighting</code> intents for a room controller. Output 2 emits theatre <code>target_state</code> evidence. Room-light failure is optional degradation, not activity success.</p>
35
+ <p>Each profile is <code>{targets: [...], values: {...}}</code>, with <code>values</code> in the package's own units:
36
+ <code>brightnessPct</code> (0-100) and <code>colorTempKelvin</code>, for example
37
+ <code>{"tv": {"targets": ["main"], "values": {"brightnessPct": 25, "colorTempKelvin": 2500}}}</code>.
38
+ <code>brightnessPct</code> runs from 0 (the dimmest the light goes, not off) to 100, and
39
+ <code>colorTempKelvin</code> must be above 0; anything else is an invalid configuration. The room
40
+ controller converts them for the light, and a light's report (in its own units) is compared after the same
41
+ conversion. Zigbee2MQTT's <code>brightness</code> and <code>color_temp</code> still work during 5.x, with a
42
+ warning from the room controller.</p>
35
43
  <p>While a profile is active, its lights are overridden in the room controller under <b>Owner</b>
36
44
  (default <code>activity</code>), so circadian refresh leaves the activity style alone. When a new profile
37
45
  no longer includes a light, including a switch to an off profile with no targets, the node emits
@@ -1,6 +1,11 @@
1
1
  <script type="text/javascript">
2
2
  (function () {
3
3
  function on(value) { return value === true || value === "true"; }
4
+ function given(value) { return value !== undefined && value !== null && String(value).trim() !== ""; }
5
+ // A dB bound, or a bound saved before 5.0 in its place.
6
+ function volumeBound(value, legacy) {
7
+ return given(value) ? Number.isFinite(Number(value)) : given(legacy) && Number.isFinite(Number(legacy));
8
+ }
4
9
  RED.nodes.registerType("home-avr-controller", {
5
10
  category: "home automation",
6
11
  color: "#c7d9f1",
@@ -17,8 +22,17 @@
17
22
  sources: {value: "{\"shield\":\"SAT/CBL\",\"playstation\":\"GAME\"}", required: true, validate: function (v) { try { JSON.parse(v); return true; } catch (e) { return false; } }},
18
23
  retryMs: {value: 2000, required: true, validate: RED.validators.number()},
19
24
  maxAttempts: {value: 3, required: true, validate: RED.validators.number()},
20
- minVolume: {value: 0, required: true, validate: RED.validators.number()},
21
- maxVolume: {value: 60, required: true, validate: RED.validators.number()},
25
+ // In dB (the receiver's 80 is 0 dB). A flow saved before 5.0 has
26
+ // minVolume and maxVolume in the receiver's own 0-98 instead, which
27
+ // still work: the node isn't shown invalid for them, and the dialog
28
+ // fills these from them.
29
+ minVolumeDb: {value: -80, validate: function (v) { return volumeBound(v, this.minVolume); }},
30
+ maxVolumeDb: {value: -20, validate: function (v) { return volumeBound(v, this.maxVolume); }},
31
+ // The bounds before 5.0, with no form rows. Listed so the editor keeps
32
+ // them: it holds only the properties named here. Cleared once the
33
+ // dialog saves the dB ones.
34
+ minVolume: {value: ""},
35
+ maxVolume: {value: ""},
22
36
  // The receiver published nothing before these settings, so both start off.
23
37
  publishState: {value: false},
24
38
  discovery: {value: false},
@@ -33,6 +47,10 @@
33
47
  this.idScheme = "node";
34
48
  },
35
49
  oneditprepare: function () {
50
+ // A flow saved before 5.0: show its volume bounds in dB, so saving
51
+ // the dialog keeps them.
52
+ if (!given(this.minVolumeDb) && given(this.minVolume)) $("#node-input-minVolumeDb").val(Number(this.minVolume) - 80);
53
+ if (!given(this.maxVolumeDb) && given(this.maxVolume)) $("#node-input-maxVolumeDb").val(Number(this.maxVolume) - 80);
36
54
  $("#node-input-publishState").prop("checked", on(this.publishState));
37
55
  $("#node-input-discovery").prop("checked", on(this.discovery));
38
56
  // Discovery describes the published state, so it needs it.
@@ -45,6 +63,10 @@
45
63
  $("#node-input-publishState, #node-input-discovery").on("change", follow);
46
64
  follow();
47
65
  },
66
+ oneditsave: function () {
67
+ if (given($("#node-input-minVolumeDb").val())) this.minVolume = "";
68
+ if (given($("#node-input-maxVolumeDb").val())) this.maxVolume = "";
69
+ },
48
70
  inputs: 1,
49
71
  outputs: 3,
50
72
  outputLabels: ["Denon commands", "state and results", "MQTT publications"],
@@ -60,8 +82,8 @@
60
82
  <div class="form-row"><label for="node-input-sources">Sources</label><input type="text" id="node-input-sources"></div>
61
83
  <div class="form-row"><label for="node-input-retryMs">Retry milliseconds</label><input type="number" id="node-input-retryMs"></div>
62
84
  <div class="form-row"><label for="node-input-maxAttempts">Maximum attempts</label><input type="number" id="node-input-maxAttempts"></div>
63
- <div class="form-row"><label for="node-input-minVolume">Minimum volume</label><input type="number" step="0.5" id="node-input-minVolume"></div>
64
- <div class="form-row"><label for="node-input-maxVolume">Maximum volume</label><input type="number" step="0.5" id="node-input-maxVolume"></div>
85
+ <div class="form-row"><label for="node-input-minVolumeDb">Minimum volume (dB)</label><input type="number" step="0.5" id="node-input-minVolumeDb"></div>
86
+ <div class="form-row"><label for="node-input-maxVolumeDb">Maximum volume (dB)</label><input type="number" step="0.5" id="node-input-maxVolumeDb"></div>
65
87
  <div class="form-row"><label for="node-input-publishState">Publish state over MQTT</label><input type="checkbox" id="node-input-publishState" style="display:inline-block; width:auto;"></div>
66
88
  <div class="form-row"><label for="node-input-discovery">Home Assistant discovery</label><input type="checkbox" id="node-input-discovery" style="display:inline-block; width:auto;"> <span>(needs Publish state)</span></div>
67
89
  <div class="form-row"><label for="node-input-discoveryPrefix">Discovery prefix</label><input type="text" id="node-input-discoveryPrefix"></div>
@@ -71,7 +93,7 @@
71
93
  <p>Owns explicit power, main-zone, source and bounded volume commands for a Denon AVR.</p>
72
94
  <p>Send protocol observations as <code>msg.avr = {kind: "observed", line: msg.payload}</code>.</p>
73
95
  <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>
74
- <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>
96
+ <p>Send volume requests as <code>msg.avr = {kind: "volume", requestId, mode: "absolute", valueDb: -50}</code> or use <code>mode: "relative"</code> with a positive or negative change. Volume is in dB, as are the bounds, results and published state; the receiver's 80 is 0 dB. A <code>value</code> in the receiver's own 0-98 still works during 5.x, with a warning in the log. The controller applies configured bounds, accumulates rapid relative requests, confirms fresh <code>MV</code> evidence and releases ownership so external adjustments are preserved.</p>
75
97
  <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>
76
98
  <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>
77
99
  <h3>Volume results</h3>
@@ -89,7 +111,7 @@
89
111
  <code>home/&lt;area&gt;/receiver/power/state</code> (<code>ON</code> or <code>OFF</code>),
90
112
  <code>…/source/state</code> (the source name) and <code>…/volume/state</code>, with <code>online</code> or
91
113
  <code>offline</code> on <code>…/availability</code>.</dd>
92
- <dt>Home Assistant discovery</dt><dd>power and source sensors, and a volume number between <b>Minimum volume</b>
114
+ <dt>Home Assistant discovery</dt><dd>power and source sensors, and a volume number in dB between <b>Minimum volume</b>
93
115
  and <b>Maximum volume</b>. It needs <b>Publish state</b>. A volume set there arrives on
94
116
  <code>…/volume/set</code>; wire an MQTT in node on that topic into this node. Sets arriving within 0.3 seconds
95
117
  of each other (a slider, repeated taps) are settled to the last one, which becomes an ordinary absolute