indigo-matter-bridge 0.5.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,1373 @@
1
+ /**
2
+ * Role → matter.js endpoint construction, the §4.2 unit conversions, and the
3
+ * cluster-change listeners that turn ecosystem writes into `command` events.
4
+ *
5
+ * Everything Matter-shaped about a *bridged child* lives here: one table entry
6
+ * per role, carrying its device type, its `set_state` writer and its command
7
+ * listeners, so the converter for a role sits next to the cluster it feeds
8
+ * (§4.2's "exactly one converter per role, in the node").
9
+ *
10
+ * E3 implemented the relay/dimmer/colour roles; **E4 completes the v1 table**
11
+ * with the sensors, `thermostat`, `doorLock` and `windowCovering`. Every §4.2
12
+ * role now has a definition, and {@link SUPPORTED_ROLES} is derived from the
13
+ * table rather than hand-kept, so the {@link UNSUPPORTED_ROLE_DETAILS} refusal
14
+ * survives only as the gate a *future* enum addition would trip.
15
+ *
16
+ * Two kinds of role live here, and they use different machinery:
17
+ *
18
+ * * **Attribute-driven** roles (everything E3 built, plus every sensor and the
19
+ * thermostat) report ecosystem intent through {@link WatchSpec}s on the
20
+ * cluster attributes an ecosystem writes.
21
+ * * **Invocation-driven** roles (`doorLock`, `windowCovering`) cannot: their
22
+ * ecosystem-facing surface is *commands*, and matter.js's stock servers
23
+ * answer those by writing the state themselves. Both are overridden here so
24
+ * the write never happens — see {@link IndigoDoorLockServer} and
25
+ * {@link IndigoWindowCoveringServer} — and they reach their `command` sink
26
+ * through {@link COMMAND_SINKS}.
27
+ */
28
+ import { Endpoint, Logger, VendorId } from "@matter/main";
29
+ import { BridgedDeviceBasicInformationServer } from "@matter/main/behaviors/bridged-device-basic-information";
30
+ import { ColorControlServer } from "@matter/main/behaviors/color-control";
31
+ import { DoorLockServer } from "@matter/main/behaviors/door-lock";
32
+ import { OccupancySensingServer } from "@matter/main/behaviors/occupancy-sensing";
33
+ import { ThermostatServer } from "@matter/main/behaviors/thermostat";
34
+ import { MovementDirection, MovementType, WindowCoveringServer } from "@matter/main/behaviors/window-covering";
35
+ import { ColorControl } from "@matter/main/clusters/color-control";
36
+ import { DoorLock } from "@matter/main/clusters/door-lock";
37
+ import { Thermostat } from "@matter/main/clusters/thermostat";
38
+ import { ColorTemperatureLightDevice } from "@matter/main/devices/color-temperature-light";
39
+ import { ContactSensorDevice } from "@matter/main/devices/contact-sensor";
40
+ import { DimmableLightDevice } from "@matter/main/devices/dimmable-light";
41
+ import { DoorLockDevice } from "@matter/main/devices/door-lock";
42
+ import { ExtendedColorLightDevice } from "@matter/main/devices/extended-color-light";
43
+ import { FlowSensorDevice } from "@matter/main/devices/flow-sensor";
44
+ import { HumiditySensorDevice } from "@matter/main/devices/humidity-sensor";
45
+ import { LightSensorDevice } from "@matter/main/devices/light-sensor";
46
+ import { OccupancySensorDevice } from "@matter/main/devices/occupancy-sensor";
47
+ import { OnOffLightDevice } from "@matter/main/devices/on-off-light";
48
+ import { OnOffPlugInUnitDevice } from "@matter/main/devices/on-off-plug-in-unit";
49
+ import { PressureSensorDevice } from "@matter/main/devices/pressure-sensor";
50
+ import { TemperatureSensorDevice } from "@matter/main/devices/temperature-sensor";
51
+ import { ThermostatDevice } from "@matter/main/devices/thermostat";
52
+ import { WindowCoveringDevice } from "@matter/main/devices/window-covering";
53
+ import { Status, StatusResponseError } from "@matter/main/types";
54
+ import { describeErrorWithStack, ErrorCode, ProtocolError, Role, } from "./protocol.js";
55
+ /**
56
+ * Clamping is silent by design at the protocol boundary (§4.2 says the node
57
+ * owns bounds), but a value that had to be clamped is the fingerprint of a
58
+ * plugin-side unit bug, so it is worth a debug line naming what moved.
59
+ */
60
+ const logger = Logger.get("indigo-matter-endpoints");
61
+ /** Bridged Device Basic Information `UniqueID`, stable across restarts. */
62
+ export function uniqueIdFor(indigoDeviceId) {
63
+ return `indigo-${indigoDeviceId}`;
64
+ }
65
+ /**
66
+ * `Endpoint.id` derivation — the identity key of BRIDGE_PROTOCOL §4.1/§6.3.
67
+ * Deliberately the *same* value as {@link uniqueIdFor}: one derivation means the
68
+ * two can never drift apart, and §6.3's one-way identity flow reads directly.
69
+ * matter.js keys persisted endpoint numbers on this string alone (PRD §4.3), so
70
+ * it must never be reused or mutated.
71
+ */
72
+ export const endpointIdFor = uniqueIdFor;
73
+ /**
74
+ * `SerialNumber` must differ from `UniqueID` (Matter rejects equal values), so
75
+ * the device id goes in bare here and prefixed there.
76
+ */
77
+ export function serialNumberFor(indigoDeviceId) {
78
+ return String(indigoDeviceId);
79
+ }
80
+ // ---------------------------------------------------------------------------
81
+ // §4.2 unit conversions
82
+ // ---------------------------------------------------------------------------
83
+ /** Matter LevelControl and ColorControl 8-bit ranges. */
84
+ export const MATTER_LEVEL_MAX = 254;
85
+ /** §4.2: mireds are clamped to the range we advertise as physically supported. */
86
+ export const MIREDS_MIN = 153;
87
+ export const MIREDS_MAX = 500;
88
+ /** Matter `CurrentHue` spans 0-254 for a full 0-360° turn. */
89
+ export const HUE_DEGREES_MAX = 360;
90
+ function clamp(value, min, max) {
91
+ return Math.min(max, Math.max(min, value));
92
+ }
93
+ /**
94
+ * {@link clamp}, but says so. Only the *inbound* clamp of each converter uses
95
+ * this: the outbound one exists to satisfy the type range and can never fire
96
+ * once the input is already in range, so logging it would only ever be noise.
97
+ */
98
+ function clampLogged(value, min, max, what) {
99
+ const clamped = clamp(value, min, max);
100
+ if (clamped !== value) {
101
+ logger.debug(`Clamped ${what} ${value} to ${clamped} (supported range ${min}-${max})`);
102
+ }
103
+ return clamped;
104
+ }
105
+ /**
106
+ * Round half **up**, meaning toward +∞ — `Math.floor(v + 0.5)`, which is also
107
+ * exactly what `Math.round` does. §4.2's "round-half-up" for level/position is
108
+ * the same rule, so the two agree on every value.
109
+ *
110
+ * The distinction is not academic any more: an earlier version of this comment
111
+ * called it "round half away from zero" and excused itself on the grounds that
112
+ * "every quantity here is non-negative". Since E4 that is false —
113
+ * {@link celsiusToMatter} carries signed temperatures, and a signed unit is the
114
+ * only place the two rules differ. Half-up means a negative exact-half rounds
115
+ * *toward zero*: −5.005 °C is −500.5 in centidegrees and comes out as **−500**
116
+ * (−5.00 °C), not −501. That is a hundredth of a degree in the warmer
117
+ * direction, which is the behaviour, not an accident — but it must be the
118
+ * documented behaviour, because a reader who believed the old comment would
119
+ * expect −501 and go looking for a bug.
120
+ */
121
+ function roundHalfUp(value) {
122
+ return Math.floor(value + 0.5);
123
+ }
124
+ /**
125
+ * Indigo 0-100 → Matter 0-254 (§4.2). 0 maps to 0 exactly, so "off" survives
126
+ * the conversion rather than becoming the dimmest on-level.
127
+ */
128
+ export function percentToMatter(percent) {
129
+ return clamp(roundHalfUp((clampLogged(percent, 0, 100, "percentage") * MATTER_LEVEL_MAX) / 100), 0, MATTER_LEVEL_MAX);
130
+ }
131
+ /** Matter 0-254 → Indigo 0-100. Inverse of {@link percentToMatter} for all 101 inputs. */
132
+ export function matterToPercent(level) {
133
+ return clamp(roundHalfUp((clamp(level, 0, MATTER_LEVEL_MAX) * 100) / MATTER_LEVEL_MAX), 0, 100);
134
+ }
135
+ /**
136
+ * The value actually written to `currentLevel`.
137
+ *
138
+ * The Lighting feature constrains `currentLevel` to 1-254 on all four lighting
139
+ * device types (verified against the 0.17.8 device definitions, which `alter`
140
+ * the attribute to `min: 1`), so a literal 0 fails validation. Writing 1
141
+ * instead is lossless at the protocol boundary: {@link matterToPercent}(1) is 0.
142
+ *
143
+ * Note that this does **not** also write OnOff false: {@link levelPatch} never
144
+ * touches the OnOff cluster. Turning a light off at 0% is the plugin's call —
145
+ * it owns the Indigo device's on/off state and sends `onOff` in the same
146
+ * `set_state` when it means it (§4.2 lists them as independent state keys).
147
+ */
148
+ export function percentToCurrentLevel(percent) {
149
+ return Math.max(1, percentToMatter(percent));
150
+ }
151
+ /** §4.2: colour temperature is clamped to the advertised physical bounds. */
152
+ export function clampMireds(mireds) {
153
+ return clampLogged(roundHalfUp(mireds), MIREDS_MIN, MIREDS_MAX, "colour temperature (mireds)");
154
+ }
155
+ /** Indigo hue 0-360° → Matter `CurrentHue` 0-254. */
156
+ export function degreesToMatterHue(degrees) {
157
+ return clamp(roundHalfUp((clampLogged(degrees, 0, HUE_DEGREES_MAX, "hue (degrees)") * MATTER_LEVEL_MAX) / HUE_DEGREES_MAX), 0, MATTER_LEVEL_MAX);
158
+ }
159
+ /**
160
+ * Matter `CurrentHue` 0-254 → Indigo hue 0-360°.
161
+ *
162
+ * Not an exact inverse, and cannot be: 361 degrees do not fit in 255 steps, so
163
+ * a round trip is accurate to within one Matter step (~1.42°). Level and
164
+ * saturation *do* round-trip exactly because 254 steps span only 101 values.
165
+ */
166
+ export function matterHueToDegrees(hue) {
167
+ return clamp(roundHalfUp((clamp(hue, 0, MATTER_LEVEL_MAX) * HUE_DEGREES_MAX) / MATTER_LEVEL_MAX), 0, HUE_DEGREES_MAX);
168
+ }
169
+ // ---------------------------------------------------------------------------
170
+ // §4.2 unit conversions — E4 (sensors, thermostat, covering)
171
+ //
172
+ // Every scale below was read off the matter.js 0.17.8 typings rather than the
173
+ // Matter spec PDF, because two of them are NOT what the §4.2 key names suggest:
174
+ // `pressureKPa` is carried on the wire in **0.1 kPa** and `flowM3h` in
175
+ // **0.1 m³/h** ("MeasuredValue = 10 x value"), while temperature and humidity
176
+ // use the 100x scale. Getting those two backwards is a factor-of-ten error that
177
+ // still renders plausibly in an ecosystem, so the constants are named for the
178
+ // multiplier and the doc text is quoted at each one.
179
+ // ---------------------------------------------------------------------------
180
+ /** Matter's 100x scale: 0.01 °C (temperature) and 0.01 % (relative humidity). */
181
+ export const CENTI = 100;
182
+ /** Matter's 10x scale: 0.1 kPa (pressure) and 0.1 m³/h (flow). */
183
+ export const DECI = 10;
184
+ const INT16_MIN = -32768;
185
+ const INT16_MAX = 32767;
186
+ const UINT16_MAX = 65535;
187
+ /**
188
+ * TemperatureMeasurement/Thermostat floor. The model's own
189
+ * `MinMeasuredValue` default is -27315, i.e. -273.15 °C — which is also the
190
+ * only place the 0.01 °C unit is stated at all, since the `.d.ts` doc comment
191
+ * for `measuredValue` gives no unit.
192
+ */
193
+ export const TEMPERATURE_CENTI_MIN = -27315;
194
+ /** RelativeHumidityMeasurement: "MeasuredValue = 100 x water content", 0-10000. */
195
+ export const HUMIDITY_CENTI_MAX = 10_000;
196
+ /**
197
+ * IlluminanceMeasurement's measurable band.
198
+ *
199
+ * "MeasuredValue = 10,000 x log10(illuminance) + 1, where 1 lx <= illuminance
200
+ * <= 3.576 Mlx, corresponding to a MeasuredValue in the range 1 to 0xFFFE …
201
+ * 0 indicates a value of illuminance that is too low to be measured."
202
+ */
203
+ export const ILLUMINANCE_MIN = 1;
204
+ export const ILLUMINANCE_MAX = 0xfffe;
205
+ /** The lux reading below which Matter's own answer is the 0 sentinel, not a value. */
206
+ export const ILLUMINANCE_LUX_MIN = 1;
207
+ /**
208
+ * WindowCovering percent100ths. **0 is fully OPEN and 10000 is fully CLOSED** —
209
+ * the exact inverse of §4.2's `position`, where 100 is open. See
210
+ * {@link positionToPercent100ths}.
211
+ */
212
+ export const PERCENT100THS_OPEN = 0;
213
+ export const PERCENT100THS_CLOSED = 10_000;
214
+ /** §4.2 `temperatureC`/`localTemperatureC`/setpoints → Matter 0.01 °C. */
215
+ export function celsiusToMatter(celsius) {
216
+ return clamp(roundHalfUp(celsius * CENTI), TEMPERATURE_CENTI_MIN, INT16_MAX);
217
+ }
218
+ /**
219
+ * The setpoint band this bridge advertises, in Matter centidegrees: **0 °C to
220
+ * 50 °C**.
221
+ *
222
+ * matter.js applies the Thermostat cluster's own defaults when these limits are
223
+ * not seeded, and those defaults are a *product* claim, not a protocol one:
224
+ * heating 7–30 °C and cooling 16–32 °C, i.e. the range of a typical American
225
+ * wall thermostat. A bridge has no such range — it is fronting whatever the
226
+ * user exported — and the defaults reject values that are entirely routine in
227
+ * the houses this plugin runs in:
228
+ *
229
+ * * **5 °C frost protection.** Below `minHeatSetpointLimit` (700), so every
230
+ * push of it failed `CONSTRAINT_ERROR` (status 135);
231
+ * * **a heat-only thermostat.** Indigo reports `coolSetpoint` 0 on one, which
232
+ * is below `minCoolSetpointLimit` (1600), so *every* `set_state` from such a
233
+ * device failed — the common case, not an edge.
234
+ *
235
+ * And the failure did not settle: the write threw, nothing in Indigo changed,
236
+ * so the next `deviceUpdated` computed the same diff and pushed the same
237
+ * rejected value again, forever.
238
+ *
239
+ * 0–50 °C spans domestic heating, cooling and frost protection with room to
240
+ * spare, and is narrow enough that {@link clampSetpoint} still catches a
241
+ * genuine unit error (a °F thermostat pushing 68 lands on 50 with a debug line
242
+ * naming it, rather than being silently believed).
243
+ */
244
+ export const SETPOINT_CENTI_MIN = 0;
245
+ export const SETPOINT_CENTI_MAX = 5000;
246
+ /**
247
+ * A §4.2 setpoint, in the band this bridge advertises.
248
+ *
249
+ * Mirrors {@link clampMireds}: the limits above are what the cluster *says* it
250
+ * accepts, and a value outside them is refused by matter.js with a
251
+ * `CONSTRAINT_ERROR` that fails the whole `set_state`. Clamping keeps the
252
+ * ecosystem showing the nearest thing to the truth we are allowed to say, and
253
+ * the debug line is the fingerprint of the plugin-side unit bug that produced
254
+ * it.
255
+ */
256
+ export function clampSetpoint(celsius) {
257
+ return clampLogged(celsiusToMatter(celsius), SETPOINT_CENTI_MIN, SETPOINT_CENTI_MAX, "thermostat setpoint (0.01 °C)");
258
+ }
259
+ /** Matter 0.01 °C → °C. Exact for every value {@link celsiusToMatter} produces. */
260
+ export function matterToCelsius(centi) {
261
+ return centi / CENTI;
262
+ }
263
+ /** §4.2 `humidityPct` → Matter 0.01 %, clamped to the cluster's 0-100 % domain. */
264
+ export function humidityToMatter(percent) {
265
+ return clamp(roundHalfUp(clampLogged(percent, 0, 100, "humidity (%)") * CENTI), 0, HUMIDITY_CENTI_MAX);
266
+ }
267
+ /** Matter 0.01 % → %. */
268
+ export function matterToHumidity(centi) {
269
+ return centi / CENTI;
270
+ }
271
+ /**
272
+ * §4.2 `lux` → IlluminanceMeasurement's logarithmic `measuredValue`.
273
+ *
274
+ * Sub-lux readings become the literal 0 the cluster defines as "too low to be
275
+ * measured" rather than being clamped up to 1: log10 of 0 is -Infinity, and 1
276
+ * would be a claim of exactly 1 lx that the sensor never made. Above the band
277
+ * the value clamps to 0xFFFE (≈3.576 Mlx), which no indoor sensor reaches.
278
+ */
279
+ export function luxToMatter(lux) {
280
+ if (!(lux >= ILLUMINANCE_LUX_MIN)) {
281
+ return 0;
282
+ }
283
+ return clamp(roundHalfUp(10_000 * Math.log10(lux) + 1), ILLUMINANCE_MIN, ILLUMINANCE_MAX);
284
+ }
285
+ /**
286
+ * The inverse of {@link luxToMatter}, for the round-trip property test and for
287
+ * anyone reading a captured frame. 0 has no lux to return — it is the
288
+ * "too dark to measure" sentinel — so it maps to 0, not to 10^(-1/10000).
289
+ */
290
+ export function matterToLux(measured) {
291
+ if (measured <= 0) {
292
+ return 0;
293
+ }
294
+ return 10 ** ((clamp(measured, ILLUMINANCE_MIN, ILLUMINANCE_MAX) - 1) / 10_000);
295
+ }
296
+ /**
297
+ * §4.2 `pressureKPa` → PressureMeasurement's **0.1 kPa** `measuredValue`
298
+ * ("Indicates the pressure in kPa as follows: MeasuredValue = 10 x Pressure
299
+ * [kPa]"). 0.1 kPa is 1 hPa, which is why the inbound handler
300
+ * (`matter_handlers/sensors.py`) can call its own conversion an identity while
301
+ * this one is a multiply — inbound reports hPa, §4.2 states kPa.
302
+ */
303
+ export function kilopascalsToMatter(kilopascals) {
304
+ return clamp(roundHalfUp(kilopascals * DECI), INT16_MIN, INT16_MAX);
305
+ }
306
+ /** Matter 0.1 kPa → kPa. */
307
+ export function matterToKilopascals(deci) {
308
+ return deci / DECI;
309
+ }
310
+ /**
311
+ * §4.2 `flowM3h` → FlowMeasurement's **0.1 m³/h** `measuredValue` ("Indicates
312
+ * the flow in m^3/h as follows: MeasuredValue = 10 x Flow"). The attribute is
313
+ * `uint16`, so a negative flow is not representable and clamps to 0.
314
+ */
315
+ export function cubicMetresPerHourToMatter(flow) {
316
+ return clamp(roundHalfUp(flow * DECI), 0, UINT16_MAX);
317
+ }
318
+ /** Matter 0.1 m³/h → m³/h. */
319
+ export function matterToCubicMetresPerHour(deci) {
320
+ return deci / DECI;
321
+ }
322
+ /**
323
+ * §4.2 `position` (0-100, **100 = open**) → Matter `…LiftPercent100ths`
324
+ * (0 = fully open, 10000 = fully closed).
325
+ *
326
+ * **This is an inversion, and it is the single most dangerous line in E4.** The
327
+ * two conventions are exact opposites and both are "percent", so a missing
328
+ * inversion produces a blind that is fully shut when the ecosystem says open
329
+ * and vice versa — a bug that looks like wiring, not like software. Verified
330
+ * against the 0.17.8 typings rather than assumed: `upOrOpen()` documents
331
+ * "TargetPositionLiftPercent100ths attribute shall be set to 0.00%",
332
+ * `downOrClose()` documents 100.00%, and the server's own constants are
333
+ * `WC_PERCENT100THS_MIN_OPEN = 0` / `WC_PERCENT100THS_MAX_CLOSED = 1e4`.
334
+ *
335
+ * §4.2's `position` is the *inbound* convention (`matter_handlers/
336
+ * window_covering.py` maps the same Matter attribute onto an Indigo brightness
337
+ * where 100 is open), so both directions of this plugin agree on what 100
338
+ * means. Per-export polarity (`options.invert`) is applied **plugin-side**,
339
+ * before the value reaches this protocol: by the time a `position` is on the
340
+ * wire it always means "100 = open", whatever the physical device does.
341
+ *
342
+ * Rounded like every sibling converter. §4.2 types `position` as an integer, so
343
+ * the multiply is exact for every lawful input — but `…LiftPercent100ths` is a
344
+ * `uint16` and matter.js validates it, so a fractional position arriving from a
345
+ * newer plugin (or from a handler that stopped rounding) would fail the write
346
+ * outright rather than losing a fraction of a percent. Rounding here is the
347
+ * same "the node owns the wire conversion" rule the other twelve follow.
348
+ */
349
+ export function positionToPercent100ths(position) {
350
+ return roundHalfUp((100 - clampLogged(position, 0, 100, "covering position")) * 100);
351
+ }
352
+ /** Matter `…LiftPercent100ths` → §4.2 `position` (100 = open). Inverse of the above. */
353
+ export function percent100thsToPosition(percent100ths) {
354
+ return clamp(100 - roundHalfUp(clamp(percent100ths, PERCENT100THS_OPEN, PERCENT100THS_CLOSED) / 100), 0, 100);
355
+ }
356
+ /**
357
+ * §4.2 `systemMode` ⇄ Matter `SystemModeEnum`, the mapping §4.2 says the node
358
+ * owns. `Auto` is 1 and there is **no 2** in the enum, so the table is written
359
+ * out rather than derived from an index.
360
+ */
361
+ const SYSTEM_MODE_TO_MATTER = {
362
+ off: Thermostat.SystemMode.Off,
363
+ heat: Thermostat.SystemMode.Heat,
364
+ cool: Thermostat.SystemMode.Cool,
365
+ auto: Thermostat.SystemMode.Auto,
366
+ };
367
+ /**
368
+ * The reverse table.
369
+ *
370
+ * Deliberately **not** total over `SystemModeEnum`: an ecosystem may write
371
+ * `EmergencyHeat`, `Precooling`, `FanOnly`, `Dry` or `Sleep`, none of which are
372
+ * in §4.2's four-value domain. Those become `undefined` here and the watcher
373
+ * reports nothing, which is the honest answer — inventing "heat" for
374
+ * `EmergencyHeat` would have the plugin tell Indigo something the user did not
375
+ * ask for.
376
+ */
377
+ const MATTER_TO_SYSTEM_MODE = new Map(Object.entries(SYSTEM_MODE_TO_MATTER).map(([mode, value]) => [value, mode]));
378
+ /** §4.2 `systemMode` string → the Matter enum, or `undefined` if not in the domain. */
379
+ export function systemModeToMatter(mode) {
380
+ return typeof mode === "string" ? SYSTEM_MODE_TO_MATTER[mode] : undefined;
381
+ }
382
+ /** Matter `SystemModeEnum` → §4.2 `systemMode`, or `undefined` outside the domain. */
383
+ export function matterToSystemMode(value) {
384
+ return typeof value === "number" ? MATTER_TO_SYSTEM_MODE.get(value) : undefined;
385
+ }
386
+ // ---------------------------------------------------------------------------
387
+ // The role table
388
+ // ---------------------------------------------------------------------------
389
+ /** Matter behaviour ids, as they key `Endpoint.state` / `Endpoint.eventsOf`. */
390
+ const ON_OFF = "onOff";
391
+ const LEVEL_CONTROL = "levelControl";
392
+ const COLOR_CONTROL = "colorControl";
393
+ const BRIDGED_INFO = "bridgedDeviceBasicInformation";
394
+ const OCCUPANCY_SENSING = "occupancySensing";
395
+ const BOOLEAN_STATE = "booleanState";
396
+ const TEMPERATURE_MEASUREMENT = "temperatureMeasurement";
397
+ const RELATIVE_HUMIDITY_MEASUREMENT = "relativeHumidityMeasurement";
398
+ const ILLUMINANCE_MEASUREMENT = "illuminanceMeasurement";
399
+ const PRESSURE_MEASUREMENT = "pressureMeasurement";
400
+ const FLOW_MEASUREMENT = "flowMeasurement";
401
+ const THERMOSTAT = "thermostat";
402
+ const DOOR_LOCK = "doorLock";
403
+ const WINDOW_COVERING = "windowCovering";
404
+ /**
405
+ * `Endpoint.id` → the §5 `command` sink for that endpoint.
406
+ *
407
+ * `doorLock` and `windowCovering` answer *invocations*, so their reporting path
408
+ * runs inside a matter.js behaviour rather than an observable callback — and a
409
+ * behaviour is constructed by matter.js from a type, with no way to close over
410
+ * the per-endpoint `emit` the way {@link watchCommands} does for the attribute
411
+ * roles. This map is that closure, keyed on the one identifier a behaviour can
412
+ * always reach (`this.endpoint.id`, which {@link endpointIdFor} makes a pure
413
+ * function of `indigoDeviceId`).
414
+ *
415
+ * Registration and teardown both live in {@link watchCommands} so the lifetime
416
+ * is identical to the observable listeners': one place removes both, and a
417
+ * removed endpoint cannot keep reporting.
418
+ */
419
+ const COMMAND_SINKS = new Map();
420
+ /**
421
+ * Raise a §5 `command` from inside a behaviour override.
422
+ *
423
+ * Never throws once a sink exists. This runs inside matter.js's handling of a
424
+ * remote invocation; a throw there would fail the ecosystem's command — which
425
+ * is arguably correct — but the failure modes worth guarding are "the endpoint
426
+ * was removed a microsecond ago" and "the plugin's socket closed mid-command",
427
+ * neither of which the ecosystem can do anything with. Mirrors the same
428
+ * decision in {@link watchCommands}.
429
+ *
430
+ * **`failWithoutSink` is the deliberate exception, and it is for `doorLock`
431
+ * only.** A missing sink means the plugin is gone (Indigo reloading it, the
432
+ * socket down mid-invocation) so the command reaches nothing at all. For a lamp
433
+ * that is a warn-and-return: the ecosystem shows the light on, the next attach
434
+ * pushes the truth back, and nobody was misled about anything that matters. For
435
+ * a **lock** it is different in kind — Home reports "Unlocked", the user walks
436
+ * away, and the bolt never moved. There is no protocol frame for "your command
437
+ * was dropped" (the plugin cannot be told about invocations that arrived while
438
+ * it was away; that is a §3.1 addition, noted in `docs/HANDOVER.md` and
439
+ * deliberately not made here), so failing the invocation is the only way the
440
+ * truth reaches the person standing at the door. A Matter status error makes
441
+ * Home say the accessory did not respond, which is exactly what happened.
442
+ */
443
+ function emitCommand(endpointId, command, args, failWithoutSink = false) {
444
+ const sink = COMMAND_SINKS.get(endpointId);
445
+ if (sink === undefined) {
446
+ logger.warn(`Dropped ${command} for ${endpointId}: no command sink is registered for that endpoint`);
447
+ if (failWithoutSink) {
448
+ throw new StatusResponseError(`${command} cannot be delivered: the Indigo plugin is not connected to this bridge`, Status.Failure);
449
+ }
450
+ return;
451
+ }
452
+ try {
453
+ sink.emit({ indigoDeviceId: sink.indigoDeviceId, command, args });
454
+ }
455
+ catch (error) {
456
+ try {
457
+ sink.log(`Dropped ${command} for endpoint ${sink.indigoDeviceId}: ${describeErrorWithStack(error)}`);
458
+ }
459
+ catch {
460
+ // The logger itself failed; there is nowhere left to report.
461
+ }
462
+ }
463
+ }
464
+ /**
465
+ * DoorLock, with the auto-confirmation removed.
466
+ *
467
+ * matter.js's stock `lockDoor`/`unlockDoor` set `lockState` themselves and emit
468
+ * a `LockOperation` event. For a *bridge* that is exactly the behaviour PRD §7
469
+ * forbids — "never auto-confirm destructive state changes": the ecosystem would
470
+ * show the door locked the instant it asked, whether or not Indigo, the Z-Wave
471
+ * mesh and the actual bolt agreed. So neither override calls `super`, and
472
+ * neither touches state. `lockState` moves only when the plugin pushes a
473
+ * `set_state {"locked": …}` having watched the real Indigo device — which is
474
+ * also why the lock's §4.2 vocabulary has no `command` for state.
475
+ *
476
+ * The features are stripped with a bare `.with()`. The class doc claims that is
477
+ * already the default; it is not — the stock server enables `pinCredential`,
478
+ * `rfidCredential`, `user`, the schedules and `unbolting`, which would have the
479
+ * bridge advertise a credential database it has no way to honour.
480
+ *
481
+ * Two things the stock server does that this one still must, and does
482
+ * elsewhere: it **fails** an invocation it cannot deliver (the `true` argument
483
+ * to {@link emitCommand} — see there for why a lock is the one role that gets
484
+ * that), and it emits the spec-mandatory `LockOperation` event. The event is
485
+ * raised from {@link emitLockOperation}, on the plugin's `set_state` rather
486
+ * than on the invocation, because that is when the bolt actually moved.
487
+ */
488
+ class IndigoDoorLockServer extends DoorLockServer.with() {
489
+ lockDoor() {
490
+ emitCommand(this.endpoint.id, "lock", {}, true);
491
+ }
492
+ unlockDoor() {
493
+ emitCommand(this.endpoint.id, "unlock", {}, true);
494
+ }
495
+ }
496
+ /**
497
+ * WindowCovering, with the instant-snap movement replaced by a `command` event.
498
+ *
499
+ * matter.js's own doc says of the default: "The default implementation logs and
500
+ * immediately updates current position to the target positions. This is
501
+ * probably not desirable for a real device so do not invoke
502
+ * `super.handleMovement()` from your implementation." A bridge is exactly that
503
+ * case — the blind takes seconds and Indigo is the only thing that knows where
504
+ * it actually got to — so this override reports and returns, and
505
+ * `currentPositionLiftPercent100ths` follows the plugin's `set_state`.
506
+ *
507
+ * Only **Lift** is wired: §4.2 has one `position` key and no tilt vocabulary.
508
+ *
509
+ * **What a stop does here, end to end, because it is not what it looks like.**
510
+ * `handleStopMovement` settles `targetPosition…` onto `currentPosition…` so the
511
+ * ecosystem stops animating the blind, and reports `stopMotion` to the plugin.
512
+ * That settled position is the *last one Indigo told us*, not where the blind
513
+ * came to rest — the node has no way to know that, and neither does Indigo
514
+ * until the driver reports the move finished. The true position arrives on the
515
+ * next `set_state`, which is also when the accessory stops showing a number
516
+ * that was only ever a statement about the request. And on the plugin side a
517
+ * dimmer-modelled covering has no stop action at all
518
+ * (`export_handlers.WindowCoveringExport._stop_motion`), so for the common case
519
+ * the blind keeps travelling to its original target and the "settled" position
520
+ * is superseded within seconds.
521
+ */
522
+ class IndigoWindowCoveringServer extends WindowCoveringServer.with("Lift", "PositionAwareLift") {
523
+ handleMovement(type, _reversed, direction, targetPercent100ths) {
524
+ if (type !== MovementType.Lift) {
525
+ return;
526
+ }
527
+ emitCommand(this.endpoint.id, "goToPosition", {
528
+ position: movementPosition(direction, targetPercent100ths),
529
+ });
530
+ }
531
+ handleStopMovement() {
532
+ emitCommand(this.endpoint.id, "stopMotion", {});
533
+ // Unlike handleMovement, super() is wanted here: all it does is settle
534
+ // `targetPosition…` onto `currentPosition…` so the ecosystem stops
535
+ // rendering the blind as in motion. That is a statement about the
536
+ // *request*, not a claim about where the blind ended up.
537
+ return super.handleStopMovement();
538
+ }
539
+ }
540
+ /**
541
+ * The §4.2 `position` a movement request means.
542
+ *
543
+ * **`targetPercent100ths` wins whenever it is present, and with
544
+ * `PositionAwareLift` enabled it always is** — matter.js throws
545
+ * "Target position must be defined for position aware lift" otherwise. The
546
+ * `direction` argument is derived by matter.js from current-vs-target and is
547
+ * therefore *not* a substitute: `goToLiftPercentage(3000)` on an open blind
548
+ * arrives as `Close`, and reading the direction alone would report "shut it
549
+ * completely" for a request to move it to 70% open. (This was the first
550
+ * implementation, and the probe caught it.)
551
+ *
552
+ * `Open`/`Close` are the fallback for the non-position-aware feature set, which
553
+ * this bridge does not enable but which a future `.with()` change could. They
554
+ * are unambiguous ends of travel, so they map to 100 and 0 directly.
555
+ */
556
+ function movementPosition(direction, targetPercent100ths) {
557
+ if (typeof targetPercent100ths === "number") {
558
+ return percent100thsToPosition(targetPercent100ths);
559
+ }
560
+ return direction === MovementDirection.Open ? 100 : 0;
561
+ }
562
+ /**
563
+ * Colour attributes matter.js requires up front.
564
+ *
565
+ * `colorMode`, `enhancedColorMode`, `colorCapabilities`,
566
+ * `coupleColorTempToLevelMinMireds` and `startUpColorTemperatureMireds` are all
567
+ * mandatory-on-conformance for a ColorControl server with the CT feature, and
568
+ * matter.js 0.17.8 refuses to initialise the behaviour without them (verified:
569
+ * the endpoint fails construction with a `conformance` error naming each in
570
+ * turn). Nothing in the matter.js docs says so — the typings mark them
571
+ * optional, which is why they are pinned here with a reason rather than
572
+ * discovered again.
573
+ */
574
+ function colorControlDefaults(hueSaturation) {
575
+ return {
576
+ colorMode: ColorControl.ColorMode.ColorTemperatureMireds,
577
+ enhancedColorMode: ColorControl.EnhancedColorMode.ColorTemperatureMireds,
578
+ colorCapabilities: { colorTemperature: true, xy: true, hueSaturation },
579
+ colorTempPhysicalMinMireds: MIREDS_MIN,
580
+ colorTempPhysicalMaxMireds: MIREDS_MAX,
581
+ coupleColorTempToLevelMinMireds: MIREDS_MIN,
582
+ startUpColorTemperatureMireds: null,
583
+ ...(hueSaturation ? { currentHue: 0, currentSaturation: 0 } : {}),
584
+ };
585
+ }
586
+ /**
587
+ * The LevelControl state every level-bearing role starts from.
588
+ *
589
+ * `managedTransitionTimeHandling` is pinned `false` rather than left to
590
+ * matter.js's default because the echo guard depends on it. With managed
591
+ * transitions ON, matter.js drives a `moveToLevel` to its target in steps of
592
+ * its own making, and those steps are written by matter.js itself — i.e. in an
593
+ * *offline* context. {@link isEcosystemChange} would read every one of them as
594
+ * our own write and drop it, so an ecosystem dimming a lamp would move the
595
+ * Matter attribute and the plugin would never learn the level changed at all.
596
+ * Unmanaged, the remote `moveToLevel` lands as one attribute change in a remote
597
+ * context, which is exactly what §4.2's `setLevel` is supposed to report.
598
+ *
599
+ * 0.17.8 already defaults it to `false` (`LevelControlServer.State`), so this
600
+ * pin changes no behaviour today — it is here so that a future default flip
601
+ * cannot silently sever the whole `setLevel` command family.
602
+ */
603
+ const LEVEL_CONTROL_INITIAL = { currentLevel: 1, managedTransitionTimeHandling: false };
604
+ /**
605
+ * Why a lawful §4.2 role can still be refused.
606
+ *
607
+ * `unknown_role` would be a lie (the role *is* in the v1 enum) and silently
608
+ * skipping the export would be worse — the user selected the device and would
609
+ * see nothing appear. So it is an `internal` refusal that names the version.
610
+ *
611
+ * **Unreachable for every v1 role as of E4**, and kept anyway: `ROLE_DEFINITIONS`
612
+ * is `Record<RoleValue, …>`, so a role added to the enum without a definition is
613
+ * a compile error here and a clean refusal in a node that was built before the
614
+ * enum grew — which is precisely the PM-B skew case (§2), where an old node
615
+ * serves a newer plugin.
616
+ */
617
+ export const UNSUPPORTED_ROLE_DETAILS = (role) => `role ${role} is in the v1 enum but not implemented by this bridge version`;
618
+ function numberOr(value, fallback) {
619
+ return typeof value === "number" && Number.isFinite(value) ? value : fallback;
620
+ }
621
+ /** `onOff` → §4.2 `onOff {"value": bool}`. Shared by every role that has it. */
622
+ const WATCH_ON_OFF = {
623
+ behavior: ON_OFF,
624
+ attribute: "onOff",
625
+ command: value => ({ command: "onOff", args: { value: value === true } }),
626
+ };
627
+ /**
628
+ * `currentLevel` → §4.2 `setLevel {"level": 0-100}`. Matter's `moveToLevel`,
629
+ * `step`, `move` and the Lighting on/off transitions all land here as an
630
+ * attribute change, which is why one listener covers the whole command family.
631
+ */
632
+ const WATCH_LEVEL = {
633
+ behavior: LEVEL_CONTROL,
634
+ attribute: "currentLevel",
635
+ command: value => typeof value === "number" ? { command: "setLevel", args: { level: matterToPercent(value) } } : undefined,
636
+ };
637
+ const WATCH_COLOR_TEMP = {
638
+ behavior: COLOR_CONTROL,
639
+ attribute: "colorTemperatureMireds",
640
+ command: value => typeof value === "number"
641
+ ? { command: "setColorTemp", args: { colorTempMireds: clampMireds(value) } }
642
+ : undefined,
643
+ };
644
+ /**
645
+ * Hue and saturation are one §4.2 command (`setColor` carries both), so each
646
+ * observable reads its partner out of the endpoint's current state. Matter
647
+ * changes them in one transaction for `moveToHueAndSaturation`, which yields two
648
+ * events and therefore two `setColor` emissions with the same final values —
649
+ * harmless (the plugin applies the same colour twice) and much simpler than
650
+ * coalescing.
651
+ */
652
+ const WATCH_HUE = {
653
+ behavior: COLOR_CONTROL,
654
+ attribute: "currentHue",
655
+ command: (value, state) => ({
656
+ command: "setColor",
657
+ args: {
658
+ hue: matterHueToDegrees(numberOr(value, 0)),
659
+ saturation: matterToPercent(numberOr(state.currentSaturation, 0)),
660
+ },
661
+ }),
662
+ };
663
+ const WATCH_SATURATION = {
664
+ behavior: COLOR_CONTROL,
665
+ attribute: "currentSaturation",
666
+ command: (value, state) => ({
667
+ command: "setColor",
668
+ args: {
669
+ hue: matterHueToDegrees(numberOr(state.currentHue, 0)),
670
+ saturation: matterToPercent(numberOr(value, 0)),
671
+ },
672
+ }),
673
+ };
674
+ function onOffPatch(states) {
675
+ return typeof states.onOff === "boolean" ? { [ON_OFF]: { onOff: states.onOff } } : {};
676
+ }
677
+ function levelPatch(states) {
678
+ if (typeof states.level !== "number") {
679
+ return {};
680
+ }
681
+ return { [LEVEL_CONTROL]: { currentLevel: percentToCurrentLevel(states.level) } };
682
+ }
683
+ /**
684
+ * Colour patch, including the `colorMode` bookkeeping Matter requires.
685
+ *
686
+ * An ecosystem reads `colorMode` to decide which attributes to believe. Indigo
687
+ * devices happily report hue/saturation *and* a colour temperature at the same
688
+ * time (the fixture `set_state_extended_color_light` does exactly that), so a
689
+ * rule is needed: hue/saturation win when present, because a user who set a
690
+ * colour expects to see that colour, not the white point left over from before.
691
+ */
692
+ function colorPatch(states, hueSaturation) {
693
+ const color = {};
694
+ if (typeof states.colorTempMireds === "number") {
695
+ color.colorTemperatureMireds = clampMireds(states.colorTempMireds);
696
+ color.colorMode = ColorControl.ColorMode.ColorTemperatureMireds;
697
+ color.enhancedColorMode = ColorControl.EnhancedColorMode.ColorTemperatureMireds;
698
+ }
699
+ if (hueSaturation) {
700
+ let touched = false;
701
+ if (typeof states.hue === "number") {
702
+ color.currentHue = degreesToMatterHue(states.hue);
703
+ touched = true;
704
+ }
705
+ if (typeof states.saturation === "number") {
706
+ color.currentSaturation = percentToMatter(states.saturation);
707
+ touched = true;
708
+ }
709
+ if (touched) {
710
+ color.colorMode = ColorControl.ColorMode.CurrentHueAndCurrentSaturation;
711
+ color.enhancedColorMode = ColorControl.EnhancedColorMode.CurrentHueAndCurrentSaturation;
712
+ }
713
+ }
714
+ return Object.keys(color).length > 0 ? { [COLOR_CONTROL]: color } : {};
715
+ }
716
+ /**
717
+ * A sensor's whole `set_state` vocabulary: one key, one attribute, one scale.
718
+ *
719
+ * Sensors emit no commands (§4.2), so a role factory for one is entirely
720
+ * described by "which behaviour, which key, which converter" — which is what
721
+ * this builds, rather than five near-identical hand-written entries whose only
722
+ * differences would be easy to transpose.
723
+ */
724
+ function measuredValuePatch(behavior, key, convert) {
725
+ return states => typeof states[key] === "number" && Number.isFinite(states[key])
726
+ ? { [behavior]: { measuredValue: convert(states[key]) } }
727
+ : {};
728
+ }
729
+ /** As {@link measuredValuePatch}, for the two boolean sensors. */
730
+ function booleanStatePatch(behavior, key, attribute, convert) {
731
+ return states => typeof states[key] === "boolean" ? { [behavior]: { [attribute]: convert(states[key]) } } : {};
732
+ }
733
+ /**
734
+ * The thermostat patch. Every key is independent (§3.4 state maps are partial),
735
+ * and an unmappable `systemMode` is simply not consumed — which
736
+ * {@link statePatchOrRefuse} turns into `malformed_args` when it was the only
737
+ * key sent, and silently ignores when it rode alongside a setpoint.
738
+ */
739
+ function thermostatPatch(states) {
740
+ const thermostat = {};
741
+ if (typeof states.localTemperatureC === "number") {
742
+ thermostat.localTemperature = celsiusToMatter(states.localTemperatureC);
743
+ }
744
+ if (typeof states.heatingSetpointC === "number") {
745
+ thermostat.occupiedHeatingSetpoint = clampSetpoint(states.heatingSetpointC);
746
+ }
747
+ if (typeof states.coolingSetpointC === "number") {
748
+ thermostat.occupiedCoolingSetpoint = clampSetpoint(states.coolingSetpointC);
749
+ }
750
+ const systemMode = systemModeToMatter(states.systemMode);
751
+ if (systemMode !== undefined) {
752
+ thermostat.systemMode = systemMode;
753
+ }
754
+ return Object.keys(thermostat).length > 0 ? { [THERMOSTAT]: thermostat } : {};
755
+ }
756
+ /**
757
+ * The covering patch, and the one place the §4.2 → Matter inversion is applied
758
+ * on the push side.
759
+ *
760
+ * `target` is written alongside `current` on purpose: an ecosystem renders a
761
+ * covering as *moving* while the two differ, so pushing only the current
762
+ * position would leave a blind that has finished travelling animating forever.
763
+ */
764
+ function windowCoveringPatch(states) {
765
+ if (typeof states.position !== "number") {
766
+ return {};
767
+ }
768
+ const percent100ths = positionToPercent100ths(states.position);
769
+ return {
770
+ [WINDOW_COVERING]: {
771
+ currentPositionLiftPercent100ths: percent100ths,
772
+ targetPositionLiftPercent100ths: percent100ths,
773
+ },
774
+ };
775
+ }
776
+ /** `locked: true` → `LockState.Locked`. Mirrors `matter_handlers/door_lock.py`. */
777
+ function doorLockPatch(states) {
778
+ return typeof states.locked === "boolean"
779
+ ? { [DOOR_LOCK]: { lockState: states.locked ? DoorLock.LockState.Locked : DoorLock.LockState.Unlocked } }
780
+ : {};
781
+ }
782
+ /**
783
+ * Raise the spec-mandatory `LockOperation` event when a push moved the bolt.
784
+ *
785
+ * Matter requires a DoorLock server to report operations as events, and
786
+ * ecosystems use them for their activity history and for lock notifications —
787
+ * Home's "the front door was unlocked" line is this event, not the `lockState`
788
+ * attribute. {@link IndigoDoorLockServer} removed matter.js's emission along
789
+ * with its auto-confirmation, which was right (the stock server fires it the
790
+ * instant the *command* arrives, i.e. before Indigo, the mesh or the bolt have
791
+ * agreed on anything) but left the bridge silent where the spec says it must
792
+ * speak.
793
+ *
794
+ * So it is raised **here**, on the plugin's `set_state`, which is the moment
795
+ * the bolt is known to have actually moved. That is the honest timing and it is
796
+ * the only timing a bridge can offer.
797
+ *
798
+ * `operationSource` is `Unspecified`, not `Manual` or `Remote`, and every id
799
+ * field is null. By the time Indigo reports a lock state change, what caused it
800
+ * — an ecosystem command we forwarded, a key in the door, a schedule in another
801
+ * plugin — has been flattened into one boolean. The enum has a value for "we do
802
+ * not know" and using it beats naming a source we would be guessing at; the
803
+ * `fabricIndex`/`sourceNode` "shall NOT be null" rule applies only to
804
+ * `operationSource: Remote`, which is exactly the claim we are declining to
805
+ * make.
806
+ */
807
+ async function emitLockOperation(endpoint, patch, before) {
808
+ const next = patch[DOOR_LOCK]?.lockState;
809
+ const previous = before[DOOR_LOCK]?.lockState;
810
+ if (next === undefined || next === previous) {
811
+ return;
812
+ }
813
+ await endpoint.act(agent => {
814
+ agent.get(IndigoDoorLockServer).events.lockOperation.emit({
815
+ lockOperationType: next === DoorLock.LockState.Locked
816
+ ? DoorLock.LockOperationType.Lock
817
+ : DoorLock.LockOperationType.Unlock,
818
+ operationSource: DoorLock.OperationSource.Unspecified,
819
+ userIndex: null,
820
+ fabricIndex: null,
821
+ sourceNode: null,
822
+ credentials: null,
823
+ }, agent.context);
824
+ });
825
+ }
826
+ /** `occupiedHeatingSetpoint` → §4.2 `setHeatingSetpoint {"valueC": float}`. */
827
+ const WATCH_HEATING_SETPOINT = {
828
+ behavior: THERMOSTAT,
829
+ attribute: "occupiedHeatingSetpoint",
830
+ command: value => typeof value === "number"
831
+ ? { command: "setHeatingSetpoint", args: { valueC: matterToCelsius(value) } }
832
+ : undefined,
833
+ };
834
+ const WATCH_COOLING_SETPOINT = {
835
+ behavior: THERMOSTAT,
836
+ attribute: "occupiedCoolingSetpoint",
837
+ command: value => typeof value === "number"
838
+ ? { command: "setCoolingSetpoint", args: { valueC: matterToCelsius(value) } }
839
+ : undefined,
840
+ };
841
+ /**
842
+ * `systemMode` → §4.2 `setSystemMode {"mode": str}`.
843
+ *
844
+ * A mode outside §4.2's four values reports nothing (see
845
+ * {@link MATTER_TO_SYSTEM_MODE}). The attribute has still moved, so the
846
+ * ecosystem and Indigo now disagree — but the plugin's next push corrects the
847
+ * ecosystem, whereas a fabricated `"heat"` would have Indigo act on something
848
+ * nobody asked for.
849
+ */
850
+ const WATCH_SYSTEM_MODE = {
851
+ behavior: THERMOSTAT,
852
+ attribute: "systemMode",
853
+ command: value => {
854
+ const mode = matterToSystemMode(value);
855
+ return mode === undefined ? undefined : { command: "setSystemMode", args: { mode } };
856
+ },
857
+ };
858
+ /**
859
+ * The thermostat features we enable, and why each is needed.
860
+ *
861
+ * `Heating`/`Cooling` are what make `occupiedHeatingSetpoint` and
862
+ * `occupiedCoolingSetpoint` exist at all; `AutoMode` is what makes
863
+ * `SystemMode.Auto` — §4.2's `"auto"` — a legal value. Everything else is off:
864
+ * the stock `ThermostatServer` turns on `Occupancy` and `Presets` as well, and
865
+ * `Presets` in particular advertises a scheduling surface a bridge cannot honour.
866
+ */
867
+ const THERMOSTAT_FEATURES = ["Heating", "Cooling", "AutoMode"];
868
+ /**
869
+ * Thermostat attributes matter.js will not default for us.
870
+ *
871
+ * `systemMode` and `controlSequenceOfOperation` are plain mandatory attributes
872
+ * with no marker in the typings, but endpoint construction hard-fails without
873
+ * them ("Conformance \"M\": Matter requires you to set this attribute") because
874
+ * matter.js's `selectDefaultValue` has no fallback for enum metatypes. Same
875
+ * class of trap as {@link colorControlDefaults}, found the same way — by
876
+ * building the endpoint and reading the error.
877
+ *
878
+ * `CoolingAndHeating` is the sequence that matches the feature set above; the
879
+ * initial `Off` is a statement about knowing nothing yet, and the plugin's
880
+ * first `set_state` replaces it.
881
+ *
882
+ * **The setpoint limits and the deadband are seeded for the same reason the
883
+ * enums are — matter.js's fallback is wrong for a bridge — but they fail far
884
+ * more quietly, so they are worth their own paragraph.**
885
+ *
886
+ * The four `abs…SetpointLimit` attributes are a *manufacturer* claim about a
887
+ * physical thermostat's capability, and the `min…`/`max…` pair is the user
888
+ * narrowing it. Left unset, matter.js applies the cluster defaults (7–30 °C
889
+ * heating, 16–32 °C cooling) and enforces them, which is a claim this bridge
890
+ * has no business making about someone else's hardware — see
891
+ * {@link SETPOINT_CENTI_MIN}. All eight are seeded so the advertised band and
892
+ * {@link clampSetpoint} are the same band, stated once.
893
+ *
894
+ * `minSetpointDeadBand` is the AutoMode rule that heating and cooling stay at
895
+ * least N apart, and its default is 2 °C. **matter.js does not refuse a write
896
+ * that breaks it — it silently rewrites the other setpoint** (per the spec:
897
+ * "the value of OccupiedHeatingSetpoint shall be adjusted"). Pushing a
898
+ * thermostat Indigo reports as heat 21 / cool 21 therefore left the node
899
+ * holding heat 19, an offline write that raises no `command` event, so the
900
+ * plugin never learned and never corrected: the ecosystem showed a setpoint
901
+ * two degrees below the real one, permanently, with nothing in any log. A
902
+ * bridge does not schedule anything and has no HVAC of its own to protect from
903
+ * short-cycling, so the honest deadband is 0 — report what Indigo says, exactly.
904
+ */
905
+ function thermostatDefaults() {
906
+ return {
907
+ systemMode: Thermostat.SystemMode.Off,
908
+ controlSequenceOfOperation: Thermostat.ControlSequenceOfOperation.CoolingAndHeating,
909
+ absMinHeatSetpointLimit: SETPOINT_CENTI_MIN,
910
+ absMaxHeatSetpointLimit: SETPOINT_CENTI_MAX,
911
+ minHeatSetpointLimit: SETPOINT_CENTI_MIN,
912
+ maxHeatSetpointLimit: SETPOINT_CENTI_MAX,
913
+ absMinCoolSetpointLimit: SETPOINT_CENTI_MIN,
914
+ absMaxCoolSetpointLimit: SETPOINT_CENTI_MAX,
915
+ minCoolSetpointLimit: SETPOINT_CENTI_MIN,
916
+ maxCoolSetpointLimit: SETPOINT_CENTI_MAX,
917
+ minSetpointDeadBand: 0,
918
+ };
919
+ }
920
+ /**
921
+ * DoorLock attributes matter.js will not default for us.
922
+ *
923
+ * `lockType` and `operatingMode` are the same enum-default trap as the
924
+ * thermostat's: mandatory, unmarked in the typings, and a hard
925
+ * `Conformance "M"` failure at construction if absent.
926
+ *
927
+ * `lockType` is `Other` rather than `DeadBolt`: the bridge is exporting an
928
+ * Indigo relay whose real mechanism nothing in the device model records, and
929
+ * claiming a deadbolt would be a guess an ecosystem might render as fact.
930
+ *
931
+ * Note what is deliberately *not* here. With the stock (all-features)
932
+ * `DoorLockServer`, `wrongCodeEntryLimit` and `userCodeTemporaryDisableTime`
933
+ * default to `0` and fail their own `1 to 255` constraint, so they have to be
934
+ * seeded — but under `DoorLockServer.with()` the PIN/RFID features are gone and
935
+ * setting them fails the *opposite* way (`Conformance "PIN | RID": Matter does
936
+ * not allow you to set this attribute`). Stripping the features is what makes
937
+ * both attributes go away, and that is the only reason this function is short.
938
+ */
939
+ function doorLockDefaults() {
940
+ return {
941
+ lockType: DoorLock.LockType.Other,
942
+ operatingMode: DoorLock.OperatingMode.Normal,
943
+ actuatorEnabled: true,
944
+ };
945
+ }
946
+ const ROLE_DEFINITIONS = {
947
+ [Role.onOffPlugInUnit]: {
948
+ deviceType: () => OnOffPlugInUnitDevice.with(BridgedDeviceBasicInformationServer),
949
+ initialState: () => ({}),
950
+ statePatch: onOffPatch,
951
+ watch: [WATCH_ON_OFF],
952
+ },
953
+ [Role.onOffLight]: {
954
+ deviceType: () => OnOffLightDevice.with(BridgedDeviceBasicInformationServer),
955
+ initialState: () => ({}),
956
+ statePatch: onOffPatch,
957
+ watch: [WATCH_ON_OFF],
958
+ },
959
+ [Role.dimmableLight]: {
960
+ deviceType: () => DimmableLightDevice.with(BridgedDeviceBasicInformationServer),
961
+ initialState: () => ({ [LEVEL_CONTROL]: { ...LEVEL_CONTROL_INITIAL } }),
962
+ statePatch: states => ({ ...onOffPatch(states), ...levelPatch(states) }),
963
+ watch: [WATCH_ON_OFF, WATCH_LEVEL],
964
+ },
965
+ [Role.colorTemperatureLight]: {
966
+ deviceType: () => ColorTemperatureLightDevice.with(BridgedDeviceBasicInformationServer),
967
+ initialState: () => ({
968
+ [LEVEL_CONTROL]: { ...LEVEL_CONTROL_INITIAL },
969
+ [COLOR_CONTROL]: { ...colorControlDefaults(false), colorTemperatureMireds: MIREDS_MIN },
970
+ }),
971
+ statePatch: states => ({ ...onOffPatch(states), ...levelPatch(states), ...colorPatch(states, false) }),
972
+ watch: [WATCH_ON_OFF, WATCH_LEVEL, WATCH_COLOR_TEMP],
973
+ },
974
+ [Role.extendedColorLight]: {
975
+ // matter.js 0.17.8 builds ExtendedColorLightDevice with
976
+ // `ColorControlServer.with("Xy", "ColorTemperature")` — no HueSaturation
977
+ // — so `currentHue`/`currentSaturation` would not exist and §4.2's
978
+ // hue/saturation vocabulary would be unimplementable. The Matter spec
979
+ // makes HS mandatory for device type 0x010D, so this override restores
980
+ // conformance rather than extending it.
981
+ deviceType: () => ExtendedColorLightDevice.with(BridgedDeviceBasicInformationServer, ColorControlServer.with("HueSaturation", "Xy", "ColorTemperature")),
982
+ initialState: () => ({
983
+ [LEVEL_CONTROL]: { ...LEVEL_CONTROL_INITIAL },
984
+ [COLOR_CONTROL]: { ...colorControlDefaults(true), colorTemperatureMireds: MIREDS_MIN },
985
+ }),
986
+ statePatch: states => ({ ...onOffPatch(states), ...levelPatch(states), ...colorPatch(states, true) }),
987
+ watch: [WATCH_ON_OFF, WATCH_LEVEL, WATCH_COLOR_TEMP, WATCH_HUE, WATCH_SATURATION],
988
+ },
989
+ // -- E4: sensors. Read-only in Matter, so every `watch` is empty by
990
+ // design (§4.2 gives them no commands), not by omission.
991
+ [Role.occupancySensor]: {
992
+ // OccupancySensorDevice ships WITHOUT its cluster, and an
993
+ // OccupancySensingServer with no modality feature logs "features need
994
+ // to be set based on the detector type" and derives nothing. Indigo
995
+ // does not record how a binary sensor detects, and PIR is what almost
996
+ // every Indigo motion sensor is, so it is declared rather than left
997
+ // blank — the alternative is an accessory ecosystems cannot categorise.
998
+ deviceType: () => OccupancySensorDevice.with(BridgedDeviceBasicInformationServer, OccupancySensingServer.with("PassiveInfrared")),
999
+ initialState: () => ({}),
1000
+ // `occupancy` is a bitmap whose bit 0 is the whole meaning — matter.js
1001
+ // models it as `{occupied?: boolean}`, so the conversion is a wrap.
1002
+ statePatch: booleanStatePatch(OCCUPANCY_SENSING, "occupied", "occupancy", occupied => ({ occupied })),
1003
+ watch: [],
1004
+ },
1005
+ [Role.contactSensor]: {
1006
+ deviceType: () => ContactSensorDevice.with(BridgedDeviceBasicInformationServer),
1007
+ initialState: () => ({}),
1008
+ // §4.2 `contact` is "true = closed" and BooleanState's `stateValue` is
1009
+ // documented "in a Contact Sensor device type, FALSE=open or no
1010
+ // contact, TRUE=closed or contact" — the same polarity, so no inversion.
1011
+ statePatch: booleanStatePatch(BOOLEAN_STATE, "contact", "stateValue", contact => contact),
1012
+ watch: [],
1013
+ },
1014
+ [Role.temperatureSensor]: {
1015
+ deviceType: () => TemperatureSensorDevice.with(BridgedDeviceBasicInformationServer),
1016
+ initialState: () => ({}),
1017
+ statePatch: measuredValuePatch(TEMPERATURE_MEASUREMENT, "temperatureC", celsiusToMatter),
1018
+ watch: [],
1019
+ },
1020
+ [Role.humiditySensor]: {
1021
+ // `HumiditySensorDevice`, not `RelativeHumiditySensorDevice` — the
1022
+ // device type is named for the reading, the behaviour id for the cluster.
1023
+ deviceType: () => HumiditySensorDevice.with(BridgedDeviceBasicInformationServer),
1024
+ initialState: () => ({}),
1025
+ statePatch: measuredValuePatch(RELATIVE_HUMIDITY_MEASUREMENT, "humidityPct", humidityToMatter),
1026
+ watch: [],
1027
+ },
1028
+ [Role.lightSensor]: {
1029
+ deviceType: () => LightSensorDevice.with(BridgedDeviceBasicInformationServer),
1030
+ initialState: () => ({}),
1031
+ statePatch: measuredValuePatch(ILLUMINANCE_MEASUREMENT, "lux", luxToMatter),
1032
+ watch: [],
1033
+ },
1034
+ [Role.pressureSensor]: {
1035
+ deviceType: () => PressureSensorDevice.with(BridgedDeviceBasicInformationServer),
1036
+ initialState: () => ({}),
1037
+ statePatch: measuredValuePatch(PRESSURE_MEASUREMENT, "pressureKPa", kilopascalsToMatter),
1038
+ watch: [],
1039
+ },
1040
+ [Role.flowSensor]: {
1041
+ deviceType: () => FlowSensorDevice.with(BridgedDeviceBasicInformationServer),
1042
+ initialState: () => ({}),
1043
+ statePatch: measuredValuePatch(FLOW_MEASUREMENT, "flowM3h", cubicMetresPerHourToMatter),
1044
+ watch: [],
1045
+ },
1046
+ // -- E4: the two-way roles.
1047
+ [Role.thermostat]: {
1048
+ // ThermostatDevice ships without its cluster, and the bare
1049
+ // ThermostatServer would enable Occupancy and Presets too.
1050
+ deviceType: () => ThermostatDevice.with(BridgedDeviceBasicInformationServer, ThermostatServer.with(...THERMOSTAT_FEATURES)),
1051
+ initialState: () => ({ [THERMOSTAT]: thermostatDefaults() }),
1052
+ statePatch: thermostatPatch,
1053
+ // Ecosystems change a thermostat by *writing the setpoint attributes*,
1054
+ // not by invoking a command (`setpointRaiseLower` exists but Apple,
1055
+ // Google and Alexa all write), so the attribute watchers cover the
1056
+ // whole §4.2 command family — the same reason one `currentLevel`
1057
+ // watcher covers `moveToLevel`, `step` and `move`.
1058
+ watch: [WATCH_HEATING_SETPOINT, WATCH_COOLING_SETPOINT, WATCH_SYSTEM_MODE],
1059
+ },
1060
+ [Role.doorLock]: {
1061
+ deviceType: () => DoorLockDevice.with(BridgedDeviceBasicInformationServer, IndigoDoorLockServer),
1062
+ initialState: () => ({ [DOOR_LOCK]: doorLockDefaults() }),
1063
+ statePatch: doorLockPatch,
1064
+ afterApply: emitLockOperation,
1065
+ // `lockState` is deliberately NOT watched. It only ever moves because
1066
+ // we pushed it (the overrides never write it), so a watcher would see
1067
+ // nothing an ecosystem did — and if it ever did fire it would echo our
1068
+ // own push straight back as a `lock`/`unlock`.
1069
+ watch: [],
1070
+ },
1071
+ [Role.windowCovering]: {
1072
+ deviceType: () => WindowCoveringDevice.with(BridgedDeviceBasicInformationServer, IndigoWindowCoveringServer),
1073
+ initialState: () => ({}),
1074
+ statePatch: windowCoveringPatch,
1075
+ // Same reasoning as doorLock: the position attributes move only under
1076
+ // our own `set_state`, because handleMovement no longer writes them.
1077
+ watch: [],
1078
+ },
1079
+ };
1080
+ /**
1081
+ * The §4.2 roles this bridge version can construct — **all of them, as of E4**.
1082
+ *
1083
+ * Derived from the table rather than listed, so the two cannot disagree: a role
1084
+ * added to the §4.2 enum without a definition is refused at runtime by
1085
+ * {@link definitionFor} and caught at compile time by `Record<RoleValue, …>`.
1086
+ */
1087
+ export const SUPPORTED_ROLES = Object.keys(ROLE_DEFINITIONS);
1088
+ export function isSupportedRole(role) {
1089
+ return ROLE_DEFINITIONS[role] !== undefined;
1090
+ }
1091
+ function definitionFor(role) {
1092
+ const definition = ROLE_DEFINITIONS[role];
1093
+ if (definition === undefined) {
1094
+ throw new ProtocolError(ErrorCode.internal, UNSUPPORTED_ROLE_DETAILS(role));
1095
+ }
1096
+ return definition;
1097
+ }
1098
+ /**
1099
+ * Merge two behaviour-keyed patches one level deep.
1100
+ *
1101
+ * A plain spread is wrong here and fails loudly: `{...defaults, ...patch}`
1102
+ * *replaces* the whole `colorControl` object, dropping the mandatory
1103
+ * `colorCapabilities`/`colorTempPhysicalMinMireds`/… that
1104
+ * {@link colorControlDefaults} supplies, and matter.js then refuses to
1105
+ * construct the endpoint with a bare "Behaviors have errors". Merging per
1106
+ * behaviour is what lets a spec's initial `states` coexist with them.
1107
+ */
1108
+ function mergeBehaviors(...patches) {
1109
+ const merged = {};
1110
+ for (const patch of patches) {
1111
+ for (const [behavior, values] of Object.entries(patch)) {
1112
+ merged[behavior] = { ...merged[behavior], ...values };
1113
+ }
1114
+ }
1115
+ return merged;
1116
+ }
1117
+ /**
1118
+ * The Bridged Device Basic Information every child carries (PRD §5.3).
1119
+ *
1120
+ * **Every field below is optional in the cluster** (verified against
1121
+ * `@matter/types` 0.17.8's `bridged-device-basic-information.d.ts`: only
1122
+ * `reachable` is mandatory) — but populating the identity set is what
1123
+ * matterbridge does and what ecosystems render as an accessory's manufacturer,
1124
+ * model and firmware detail. Left off, those panes read blank or "Unknown",
1125
+ * which is a worse answer than "simons-plugins" for something that genuinely is
1126
+ * a software bridge.
1127
+ *
1128
+ * Note the cluster's optional set is NOT BasicInformation's: it has no
1129
+ * `productId`, no `partNumber`, no `capabilityMinima`. Nothing outside the list
1130
+ * above is added here for that reason.
1131
+ */
1132
+ function bridgedInfoFor(spec, identity) {
1133
+ return {
1134
+ nodeLabel: spec.label,
1135
+ productName: identity.productName,
1136
+ productLabel: spec.label,
1137
+ serialNumber: serialNumberFor(spec.indigoDeviceId),
1138
+ uniqueId: uniqueIdFor(spec.indigoDeviceId),
1139
+ reachable: spec.reachable,
1140
+ // Branded, not a bare number: matter.js validates the tag at write time,
1141
+ // and the root node's BasicInformation already goes through VendorId().
1142
+ vendorName: identity.vendorName,
1143
+ vendorId: VendorId(identity.vendorId),
1144
+ // A bridge has no hardware, so this is a constant rather than an
1145
+ // invention — but the attributes are what an ecosystem reads for the
1146
+ // "Version" row, and an absent one renders as blank.
1147
+ hardwareVersion: identity.hardwareVersion,
1148
+ hardwareVersionString: identity.hardwareVersionString,
1149
+ // The bridge node's own version, same derivation the root node uses, so
1150
+ // an ecosystem showing a child's firmware and the bridge's own agree.
1151
+ softwareVersion: identity.softwareVersion,
1152
+ softwareVersionString: identity.softwareVersionString,
1153
+ // Optional on bridged devices, and matter.js only lets
1154
+ // `increaseConfigurationVersion` run when an initial value exists — so
1155
+ // it is seeded here rather than discovered as a throw on the first bump.
1156
+ //
1157
+ // **An INITIAL value, not the live one, and that distinction was
1158
+ // measured rather than assumed** (0.17.8, `registry.test.ts`
1159
+ // "restores a bridged accessory's ConfigurationVersion"). The data model
1160
+ // suggests otherwise: the bridged cluster's attribute carries no `N`
1161
+ // quality (`bridged-device-basic-information.element.js`), unlike the
1162
+ // root's, and `BridgedDeviceBasicInformationServer` extends only
1163
+ // `uniqueId` to be persistent — which reads as "matter.js will not
1164
+ // remember this, so every restart resets the accessory to 1". It does
1165
+ // remember it: the value is written to its own store as
1166
+ // `root.parts.aggregator.parts.<id>.bridgedDeviceBasicInformation.configurationVersion`
1167
+ // and restored over whatever is seeded here. So this constant applies
1168
+ // only the first time an endpoint id is ever created, and nothing needs
1169
+ // to persist it alongside the endpoint numbers.
1170
+ configurationVersion: 1,
1171
+ };
1172
+ }
1173
+ /**
1174
+ * Build the bridged child endpoint for one spec. Not yet added to a parent;
1175
+ * `Endpoint.id` is fixed at construction and is the identity matter.js keys its
1176
+ * persisted endpoint number on.
1177
+ */
1178
+ export function createEndpoint(spec, identity) {
1179
+ const definition = definitionFor(spec.role);
1180
+ return new Endpoint(definition.deviceType(), {
1181
+ id: endpointIdFor(spec.indigoDeviceId),
1182
+ ...mergeBehaviors({ [BRIDGED_INFO]: bridgedInfoFor(spec, identity) }, definition.initialState(), statePatchOrRefuse(spec.role, spec.states)),
1183
+ });
1184
+ }
1185
+ /**
1186
+ * Which of the given keys this role's converter would not consume.
1187
+ *
1188
+ * Derived by running the converter on one key at a time rather than from a
1189
+ * second table of key names and types, because a second table is a thing that
1190
+ * can disagree with the first: every §4.2 state key contributes to the patch
1191
+ * independently (there is no key that is only meaningful alongside another), so
1192
+ * "did the converter produce anything from this key alone" *is* the definition
1193
+ * of "consumed", and it cannot drift from {@link RoleDefinition.statePatch}.
1194
+ *
1195
+ * This catches a misspelt key, a key belonging to another role, and a key of
1196
+ * the wrong type (`{"onOff": "true"}`) with the same test — all three are
1197
+ * cases the patch builders skip.
1198
+ */
1199
+ export function rejectedStateKeys(role, states) {
1200
+ const { statePatch } = definitionFor(role);
1201
+ return Object.keys(states).filter(key => Object.keys(statePatch({ [key]: states[key] })).length === 0);
1202
+ }
1203
+ /**
1204
+ * Apply a §3.4 `set_state` as a local (offline-context) write.
1205
+ *
1206
+ * An empty `states` is a lawful no-op and succeeds. Keys the role does not
1207
+ * speak are a different thing entirely: answering `{}` to
1208
+ * `{"level": 55}` on an `onOffLight` reports success for a write that never
1209
+ * happened, and the symptom the user sees — the ecosystem showing stale state —
1210
+ * is indistinguishable from a bridge that is simply down. So a `states` that
1211
+ * yields *nothing at all* is `malformed_args` naming the keys that were
1212
+ * dropped.
1213
+ *
1214
+ * A *partly* consumed `states` still succeeds, and that asymmetry is deliberate:
1215
+ * the plugin and the node version-skew across a release (PM-B keeps an old node
1216
+ * running), so a newer plugin sending a key this bridge does not know yet
1217
+ * alongside keys it does must still apply the ones it understands.
1218
+ */
1219
+ export async function applyStates(endpoint, role, states) {
1220
+ const patch = statePatchOrRefuse(role, states);
1221
+ if (Object.keys(patch).length === 0) {
1222
+ return;
1223
+ }
1224
+ const { afterApply } = definitionFor(role);
1225
+ if (afterApply === undefined) {
1226
+ await endpoint.set(patch);
1227
+ return;
1228
+ }
1229
+ // Read before the write, or "did this actually change anything" cannot be
1230
+ // answered — and only for the one role that asks, so no other push pays for
1231
+ // a state copy it would ignore. Keyed by behaviour like the patch itself,
1232
+ // and derived from the patch's own keys rather than a second table of
1233
+ // role → behaviour that could drift from `statePatch`.
1234
+ //
1235
+ // **Spread, not the object.** `stateOf` hands back a live view: hold onto it
1236
+ // across `set()` and "before" reads back as "after", every comparison finds
1237
+ // nothing changed, and the event this exists to raise never fires. Caught by
1238
+ // the LockOperation test, which is the only thing that would ever notice.
1239
+ const before = {};
1240
+ for (const behavior of Object.keys(patch)) {
1241
+ before[behavior] = { ...endpoint.stateOf(behavior) };
1242
+ }
1243
+ await endpoint.set(patch);
1244
+ await afterApply(endpoint, patch, before);
1245
+ }
1246
+ /**
1247
+ * The role's state patch, refusing a `states` that produced nothing from
1248
+ * something. Shared by {@link applyStates} and {@link createEndpoint} so a set
1249
+ * of keys refused on update is not quietly accepted on create — an `attach`
1250
+ * reconcile runs both paths and they must agree on what is lawful.
1251
+ */
1252
+ function statePatchOrRefuse(role, states) {
1253
+ const patch = definitionFor(role).statePatch(states);
1254
+ if (Object.keys(states).length > 0 && Object.keys(patch).length === 0) {
1255
+ throw new ProtocolError(ErrorCode.malformedArgs, `role ${role} consumed none of the states given; ` +
1256
+ `rejected key(s): ${rejectedStateKeys(role, states).join(", ")} (§4.2)`);
1257
+ }
1258
+ return patch;
1259
+ }
1260
+ /** §3.5 / PRD §5.3 — `Reachable` tracks the Indigo device's enabled state. */
1261
+ export async function applyReachable(endpoint, reachable) {
1262
+ await endpoint.set({ [BRIDGED_INFO]: { reachable } });
1263
+ }
1264
+ /** §4.1 — `NodeLabel` follows the export's display name. */
1265
+ export async function applyLabel(endpoint, label) {
1266
+ await endpoint.set({ [BRIDGED_INFO]: { nodeLabel: label, productLabel: label } });
1267
+ }
1268
+ /**
1269
+ * True when a cluster change came from our own `set_state` rather than from an
1270
+ * ecosystem (§6.4). matter.js runs local agent writes in a `LocalActorContext`,
1271
+ * whose `offline` is the literal `true`; a remote (network) action carries a
1272
+ * `RemoteActorContext` with `offline` absent or `false`.
1273
+ *
1274
+ * **Assumes matter.js is not managing transitions.** Anything matter.js writes
1275
+ * on its own behalf — notably the intermediate steps of a managed LevelControl
1276
+ * transition — is offline too, and would be swallowed here as if we had written
1277
+ * it. That is why {@link LEVEL_CONTROL_INITIAL} pins
1278
+ * `managedTransitionTimeHandling: false`: the guard can only tell "us" from
1279
+ * "them" while matter.js itself is not a third writer.
1280
+ *
1281
+ * Exported because it is the whole echo guard, and a pure predicate is testable
1282
+ * without persuading a real Matter stack to originate a remote write.
1283
+ */
1284
+ export function isEcosystemChange(context) {
1285
+ return context?.offline !== true;
1286
+ }
1287
+ /**
1288
+ * Subscribe the role's cluster-change listeners, register its command sink, and
1289
+ * return the teardown for both.
1290
+ *
1291
+ * The teardown matters: a removed endpoint whose observables still hold our
1292
+ * handler would keep emitting `command` events for a device the plugin no
1293
+ * longer exports, and would keep the closure (and the endpoint) alive. The
1294
+ * {@link COMMAND_SINKS} entry is registered and removed here for exactly the
1295
+ * same reason — the invocation-driven roles have no observables at all, so this
1296
+ * is the *only* thing standing between a removed lock and a `command` event for
1297
+ * a device the plugin has forgotten.
1298
+ *
1299
+ * Throws if a watched observable is missing. That is a role-definition contract
1300
+ * violation — this table and the device type it names have to agree — and the
1301
+ * alternative is worse than a crash: skipping the subscription leaves the
1302
+ * accessory fully controllable in the ecosystem while every command it produces
1303
+ * goes nowhere, with nothing in any log to say so. Failing at construction
1304
+ * means any endpoint-building test catches a matter.js rename or a feature
1305
+ * regression the first time it runs.
1306
+ */
1307
+ export function watchCommands(endpoint, spec, emit, log = () => { }) {
1308
+ const teardown = [];
1309
+ const endpointId = endpointIdFor(spec.indigoDeviceId);
1310
+ COMMAND_SINKS.set(endpointId, { indigoDeviceId: spec.indigoDeviceId, emit, log });
1311
+ teardown.push(() => COMMAND_SINKS.delete(endpointId));
1312
+ const unwatch = () => {
1313
+ for (const off of teardown) {
1314
+ off();
1315
+ }
1316
+ teardown.length = 0;
1317
+ };
1318
+ try {
1319
+ subscribe(endpoint, spec, emit, log, teardown);
1320
+ }
1321
+ catch (error) {
1322
+ // The sink is already registered by this point, and the caller's only
1323
+ // recovery is to close the endpoint — which would leave the sink behind
1324
+ // holding a reference to a dead endpoint's emitter.
1325
+ unwatch();
1326
+ throw error;
1327
+ }
1328
+ return unwatch;
1329
+ }
1330
+ /** {@link watchCommands}'s observable half, extracted so its throws can unwind the sink. */
1331
+ function subscribe(endpoint, spec, emit, log, teardown) {
1332
+ for (const watch of definitionFor(spec.role).watch) {
1333
+ const events = endpoint.eventsOf(watch.behavior);
1334
+ const observable = events[`${watch.attribute}$Changed`];
1335
+ if (observable === undefined) {
1336
+ throw new ProtocolError(ErrorCode.internal, `endpoint ${spec.indigoDeviceId} (${spec.role}): matter.js exposes no ` +
1337
+ `${watch.behavior}.${watch.attribute}$Changed observable, so this role's command family ` +
1338
+ "could never be reported");
1339
+ }
1340
+ const handler = (...args) => {
1341
+ // Everything below runs *inside* matter.js's observable, which is
1342
+ // itself inside the commit of a remote write. A throw here does not
1343
+ // fail the write — it escapes as an unhandled rejection, and this
1344
+ // process exits on those, so one bad payload would take the whole
1345
+ // bridge down and every exported accessory with it. Mirrors the
1346
+ // fabricsChanged hardening in node.ts: log, never rethrow.
1347
+ try {
1348
+ const [value, , context] = args;
1349
+ if (!isEcosystemChange(context)) {
1350
+ return;
1351
+ }
1352
+ const state = endpoint.stateOf(watch.behavior);
1353
+ const command = watch.command(value, state);
1354
+ if (command === undefined) {
1355
+ return;
1356
+ }
1357
+ emit({ indigoDeviceId: spec.indigoDeviceId, command: command.command, args: command.args });
1358
+ }
1359
+ catch (error) {
1360
+ try {
1361
+ log(`Dropped a ${watch.behavior}.${watch.attribute} change for endpoint ` +
1362
+ `${spec.indigoDeviceId}: ${describeErrorWithStack(error)}`);
1363
+ }
1364
+ catch {
1365
+ // The logger itself failed; there is nowhere left to report.
1366
+ }
1367
+ }
1368
+ };
1369
+ observable.on(handler);
1370
+ teardown.push(() => observable.off(handler));
1371
+ }
1372
+ }
1373
+ //# sourceMappingURL=endpoints.js.map