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,353 @@
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 } from "@matter/main";
29
+ import { Thermostat } from "@matter/main/clusters/thermostat";
30
+ import { type CommandEventData, type EndpointSpec, type RoleValue } from "./protocol.js";
31
+ /** Bridged Device Basic Information `UniqueID`, stable across restarts. */
32
+ export declare function uniqueIdFor(indigoDeviceId: number): string;
33
+ /**
34
+ * `Endpoint.id` derivation — the identity key of BRIDGE_PROTOCOL §4.1/§6.3.
35
+ * Deliberately the *same* value as {@link uniqueIdFor}: one derivation means the
36
+ * two can never drift apart, and §6.3's one-way identity flow reads directly.
37
+ * matter.js keys persisted endpoint numbers on this string alone (PRD §4.3), so
38
+ * it must never be reused or mutated.
39
+ */
40
+ export declare const endpointIdFor: typeof uniqueIdFor;
41
+ /**
42
+ * `SerialNumber` must differ from `UniqueID` (Matter rejects equal values), so
43
+ * the device id goes in bare here and prefixed there.
44
+ */
45
+ export declare function serialNumberFor(indigoDeviceId: number): string;
46
+ /** Matter LevelControl and ColorControl 8-bit ranges. */
47
+ export declare const MATTER_LEVEL_MAX = 254;
48
+ /** §4.2: mireds are clamped to the range we advertise as physically supported. */
49
+ export declare const MIREDS_MIN = 153;
50
+ export declare const MIREDS_MAX = 500;
51
+ /** Matter `CurrentHue` spans 0-254 for a full 0-360° turn. */
52
+ export declare const HUE_DEGREES_MAX = 360;
53
+ /**
54
+ * Indigo 0-100 → Matter 0-254 (§4.2). 0 maps to 0 exactly, so "off" survives
55
+ * the conversion rather than becoming the dimmest on-level.
56
+ */
57
+ export declare function percentToMatter(percent: number): number;
58
+ /** Matter 0-254 → Indigo 0-100. Inverse of {@link percentToMatter} for all 101 inputs. */
59
+ export declare function matterToPercent(level: number): number;
60
+ /**
61
+ * The value actually written to `currentLevel`.
62
+ *
63
+ * The Lighting feature constrains `currentLevel` to 1-254 on all four lighting
64
+ * device types (verified against the 0.17.8 device definitions, which `alter`
65
+ * the attribute to `min: 1`), so a literal 0 fails validation. Writing 1
66
+ * instead is lossless at the protocol boundary: {@link matterToPercent}(1) is 0.
67
+ *
68
+ * Note that this does **not** also write OnOff false: {@link levelPatch} never
69
+ * touches the OnOff cluster. Turning a light off at 0% is the plugin's call —
70
+ * it owns the Indigo device's on/off state and sends `onOff` in the same
71
+ * `set_state` when it means it (§4.2 lists them as independent state keys).
72
+ */
73
+ export declare function percentToCurrentLevel(percent: number): number;
74
+ /** §4.2: colour temperature is clamped to the advertised physical bounds. */
75
+ export declare function clampMireds(mireds: number): number;
76
+ /** Indigo hue 0-360° → Matter `CurrentHue` 0-254. */
77
+ export declare function degreesToMatterHue(degrees: number): number;
78
+ /**
79
+ * Matter `CurrentHue` 0-254 → Indigo hue 0-360°.
80
+ *
81
+ * Not an exact inverse, and cannot be: 361 degrees do not fit in 255 steps, so
82
+ * a round trip is accurate to within one Matter step (~1.42°). Level and
83
+ * saturation *do* round-trip exactly because 254 steps span only 101 values.
84
+ */
85
+ export declare function matterHueToDegrees(hue: number): number;
86
+ /** Matter's 100x scale: 0.01 °C (temperature) and 0.01 % (relative humidity). */
87
+ export declare const CENTI = 100;
88
+ /** Matter's 10x scale: 0.1 kPa (pressure) and 0.1 m³/h (flow). */
89
+ export declare const DECI = 10;
90
+ /**
91
+ * TemperatureMeasurement/Thermostat floor. The model's own
92
+ * `MinMeasuredValue` default is -27315, i.e. -273.15 °C — which is also the
93
+ * only place the 0.01 °C unit is stated at all, since the `.d.ts` doc comment
94
+ * for `measuredValue` gives no unit.
95
+ */
96
+ export declare const TEMPERATURE_CENTI_MIN = -27315;
97
+ /** RelativeHumidityMeasurement: "MeasuredValue = 100 x water content", 0-10000. */
98
+ export declare const HUMIDITY_CENTI_MAX = 10000;
99
+ /**
100
+ * IlluminanceMeasurement's measurable band.
101
+ *
102
+ * "MeasuredValue = 10,000 x log10(illuminance) + 1, where 1 lx <= illuminance
103
+ * <= 3.576 Mlx, corresponding to a MeasuredValue in the range 1 to 0xFFFE …
104
+ * 0 indicates a value of illuminance that is too low to be measured."
105
+ */
106
+ export declare const ILLUMINANCE_MIN = 1;
107
+ export declare const ILLUMINANCE_MAX = 65534;
108
+ /** The lux reading below which Matter's own answer is the 0 sentinel, not a value. */
109
+ export declare const ILLUMINANCE_LUX_MIN = 1;
110
+ /**
111
+ * WindowCovering percent100ths. **0 is fully OPEN and 10000 is fully CLOSED** —
112
+ * the exact inverse of §4.2's `position`, where 100 is open. See
113
+ * {@link positionToPercent100ths}.
114
+ */
115
+ export declare const PERCENT100THS_OPEN = 0;
116
+ export declare const PERCENT100THS_CLOSED = 10000;
117
+ /** §4.2 `temperatureC`/`localTemperatureC`/setpoints → Matter 0.01 °C. */
118
+ export declare function celsiusToMatter(celsius: number): number;
119
+ /**
120
+ * The setpoint band this bridge advertises, in Matter centidegrees: **0 °C to
121
+ * 50 °C**.
122
+ *
123
+ * matter.js applies the Thermostat cluster's own defaults when these limits are
124
+ * not seeded, and those defaults are a *product* claim, not a protocol one:
125
+ * heating 7–30 °C and cooling 16–32 °C, i.e. the range of a typical American
126
+ * wall thermostat. A bridge has no such range — it is fronting whatever the
127
+ * user exported — and the defaults reject values that are entirely routine in
128
+ * the houses this plugin runs in:
129
+ *
130
+ * * **5 °C frost protection.** Below `minHeatSetpointLimit` (700), so every
131
+ * push of it failed `CONSTRAINT_ERROR` (status 135);
132
+ * * **a heat-only thermostat.** Indigo reports `coolSetpoint` 0 on one, which
133
+ * is below `minCoolSetpointLimit` (1600), so *every* `set_state` from such a
134
+ * device failed — the common case, not an edge.
135
+ *
136
+ * And the failure did not settle: the write threw, nothing in Indigo changed,
137
+ * so the next `deviceUpdated` computed the same diff and pushed the same
138
+ * rejected value again, forever.
139
+ *
140
+ * 0–50 °C spans domestic heating, cooling and frost protection with room to
141
+ * spare, and is narrow enough that {@link clampSetpoint} still catches a
142
+ * genuine unit error (a °F thermostat pushing 68 lands on 50 with a debug line
143
+ * naming it, rather than being silently believed).
144
+ */
145
+ export declare const SETPOINT_CENTI_MIN = 0;
146
+ export declare const SETPOINT_CENTI_MAX = 5000;
147
+ /**
148
+ * A §4.2 setpoint, in the band this bridge advertises.
149
+ *
150
+ * Mirrors {@link clampMireds}: the limits above are what the cluster *says* it
151
+ * accepts, and a value outside them is refused by matter.js with a
152
+ * `CONSTRAINT_ERROR` that fails the whole `set_state`. Clamping keeps the
153
+ * ecosystem showing the nearest thing to the truth we are allowed to say, and
154
+ * the debug line is the fingerprint of the plugin-side unit bug that produced
155
+ * it.
156
+ */
157
+ export declare function clampSetpoint(celsius: number): number;
158
+ /** Matter 0.01 °C → °C. Exact for every value {@link celsiusToMatter} produces. */
159
+ export declare function matterToCelsius(centi: number): number;
160
+ /** §4.2 `humidityPct` → Matter 0.01 %, clamped to the cluster's 0-100 % domain. */
161
+ export declare function humidityToMatter(percent: number): number;
162
+ /** Matter 0.01 % → %. */
163
+ export declare function matterToHumidity(centi: number): number;
164
+ /**
165
+ * §4.2 `lux` → IlluminanceMeasurement's logarithmic `measuredValue`.
166
+ *
167
+ * Sub-lux readings become the literal 0 the cluster defines as "too low to be
168
+ * measured" rather than being clamped up to 1: log10 of 0 is -Infinity, and 1
169
+ * would be a claim of exactly 1 lx that the sensor never made. Above the band
170
+ * the value clamps to 0xFFFE (≈3.576 Mlx), which no indoor sensor reaches.
171
+ */
172
+ export declare function luxToMatter(lux: number): number;
173
+ /**
174
+ * The inverse of {@link luxToMatter}, for the round-trip property test and for
175
+ * anyone reading a captured frame. 0 has no lux to return — it is the
176
+ * "too dark to measure" sentinel — so it maps to 0, not to 10^(-1/10000).
177
+ */
178
+ export declare function matterToLux(measured: number): number;
179
+ /**
180
+ * §4.2 `pressureKPa` → PressureMeasurement's **0.1 kPa** `measuredValue`
181
+ * ("Indicates the pressure in kPa as follows: MeasuredValue = 10 x Pressure
182
+ * [kPa]"). 0.1 kPa is 1 hPa, which is why the inbound handler
183
+ * (`matter_handlers/sensors.py`) can call its own conversion an identity while
184
+ * this one is a multiply — inbound reports hPa, §4.2 states kPa.
185
+ */
186
+ export declare function kilopascalsToMatter(kilopascals: number): number;
187
+ /** Matter 0.1 kPa → kPa. */
188
+ export declare function matterToKilopascals(deci: number): number;
189
+ /**
190
+ * §4.2 `flowM3h` → FlowMeasurement's **0.1 m³/h** `measuredValue` ("Indicates
191
+ * the flow in m^3/h as follows: MeasuredValue = 10 x Flow"). The attribute is
192
+ * `uint16`, so a negative flow is not representable and clamps to 0.
193
+ */
194
+ export declare function cubicMetresPerHourToMatter(flow: number): number;
195
+ /** Matter 0.1 m³/h → m³/h. */
196
+ export declare function matterToCubicMetresPerHour(deci: number): number;
197
+ /**
198
+ * §4.2 `position` (0-100, **100 = open**) → Matter `…LiftPercent100ths`
199
+ * (0 = fully open, 10000 = fully closed).
200
+ *
201
+ * **This is an inversion, and it is the single most dangerous line in E4.** The
202
+ * two conventions are exact opposites and both are "percent", so a missing
203
+ * inversion produces a blind that is fully shut when the ecosystem says open
204
+ * and vice versa — a bug that looks like wiring, not like software. Verified
205
+ * against the 0.17.8 typings rather than assumed: `upOrOpen()` documents
206
+ * "TargetPositionLiftPercent100ths attribute shall be set to 0.00%",
207
+ * `downOrClose()` documents 100.00%, and the server's own constants are
208
+ * `WC_PERCENT100THS_MIN_OPEN = 0` / `WC_PERCENT100THS_MAX_CLOSED = 1e4`.
209
+ *
210
+ * §4.2's `position` is the *inbound* convention (`matter_handlers/
211
+ * window_covering.py` maps the same Matter attribute onto an Indigo brightness
212
+ * where 100 is open), so both directions of this plugin agree on what 100
213
+ * means. Per-export polarity (`options.invert`) is applied **plugin-side**,
214
+ * before the value reaches this protocol: by the time a `position` is on the
215
+ * wire it always means "100 = open", whatever the physical device does.
216
+ *
217
+ * Rounded like every sibling converter. §4.2 types `position` as an integer, so
218
+ * the multiply is exact for every lawful input — but `…LiftPercent100ths` is a
219
+ * `uint16` and matter.js validates it, so a fractional position arriving from a
220
+ * newer plugin (or from a handler that stopped rounding) would fail the write
221
+ * outright rather than losing a fraction of a percent. Rounding here is the
222
+ * same "the node owns the wire conversion" rule the other twelve follow.
223
+ */
224
+ export declare function positionToPercent100ths(position: number): number;
225
+ /** Matter `…LiftPercent100ths` → §4.2 `position` (100 = open). Inverse of the above. */
226
+ export declare function percent100thsToPosition(percent100ths: number): number;
227
+ /** §4.2 `systemMode` string → the Matter enum, or `undefined` if not in the domain. */
228
+ export declare function systemModeToMatter(mode: unknown): Thermostat.SystemMode | undefined;
229
+ /** Matter `SystemModeEnum` → §4.2 `systemMode`, or `undefined` outside the domain. */
230
+ export declare function matterToSystemMode(value: unknown): string | undefined;
231
+ /**
232
+ * Why a lawful §4.2 role can still be refused.
233
+ *
234
+ * `unknown_role` would be a lie (the role *is* in the v1 enum) and silently
235
+ * skipping the export would be worse — the user selected the device and would
236
+ * see nothing appear. So it is an `internal` refusal that names the version.
237
+ *
238
+ * **Unreachable for every v1 role as of E4**, and kept anyway: `ROLE_DEFINITIONS`
239
+ * is `Record<RoleValue, …>`, so a role added to the enum without a definition is
240
+ * a compile error here and a clean refusal in a node that was built before the
241
+ * enum grew — which is precisely the PM-B skew case (§2), where an old node
242
+ * serves a newer plugin.
243
+ */
244
+ export declare const UNSUPPORTED_ROLE_DETAILS: (role: RoleValue) => string;
245
+ /**
246
+ * The §4.2 roles this bridge version can construct — **all of them, as of E4**.
247
+ *
248
+ * Derived from the table rather than listed, so the two cannot disagree: a role
249
+ * added to the §4.2 enum without a definition is refused at runtime by
250
+ * {@link definitionFor} and caught at compile time by `Record<RoleValue, …>`.
251
+ */
252
+ export declare const SUPPORTED_ROLES: readonly RoleValue[];
253
+ export declare function isSupportedRole(role: RoleValue): boolean;
254
+ /**
255
+ * Who the bridge says it is, on every child accessory it publishes.
256
+ *
257
+ * The values are the *bridge's* — they are not per-device, and there is nothing
258
+ * per-device to put there: Indigo does not tell us who made a relay. Passed in
259
+ * rather than imported so this module keeps no dependency on {@link ../node},
260
+ * which imports it.
261
+ */
262
+ export interface BridgedIdentity {
263
+ vendorName: string;
264
+ vendorId: number;
265
+ productName: string;
266
+ hardwareVersion: number;
267
+ hardwareVersionString: string;
268
+ softwareVersion: number;
269
+ softwareVersionString: string;
270
+ }
271
+ /**
272
+ * Build the bridged child endpoint for one spec. Not yet added to a parent;
273
+ * `Endpoint.id` is fixed at construction and is the identity matter.js keys its
274
+ * persisted endpoint number on.
275
+ */
276
+ export declare function createEndpoint(spec: EndpointSpec, identity: BridgedIdentity): Endpoint;
277
+ /**
278
+ * Which of the given keys this role's converter would not consume.
279
+ *
280
+ * Derived by running the converter on one key at a time rather than from a
281
+ * second table of key names and types, because a second table is a thing that
282
+ * can disagree with the first: every §4.2 state key contributes to the patch
283
+ * independently (there is no key that is only meaningful alongside another), so
284
+ * "did the converter produce anything from this key alone" *is* the definition
285
+ * of "consumed", and it cannot drift from {@link RoleDefinition.statePatch}.
286
+ *
287
+ * This catches a misspelt key, a key belonging to another role, and a key of
288
+ * the wrong type (`{"onOff": "true"}`) with the same test — all three are
289
+ * cases the patch builders skip.
290
+ */
291
+ export declare function rejectedStateKeys(role: RoleValue, states: Record<string, unknown>): string[];
292
+ /**
293
+ * Apply a §3.4 `set_state` as a local (offline-context) write.
294
+ *
295
+ * An empty `states` is a lawful no-op and succeeds. Keys the role does not
296
+ * speak are a different thing entirely: answering `{}` to
297
+ * `{"level": 55}` on an `onOffLight` reports success for a write that never
298
+ * happened, and the symptom the user sees — the ecosystem showing stale state —
299
+ * is indistinguishable from a bridge that is simply down. So a `states` that
300
+ * yields *nothing at all* is `malformed_args` naming the keys that were
301
+ * dropped.
302
+ *
303
+ * A *partly* consumed `states` still succeeds, and that asymmetry is deliberate:
304
+ * the plugin and the node version-skew across a release (PM-B keeps an old node
305
+ * running), so a newer plugin sending a key this bridge does not know yet
306
+ * alongside keys it does must still apply the ones it understands.
307
+ */
308
+ export declare function applyStates(endpoint: Endpoint, role: RoleValue, states: Record<string, unknown>): Promise<void>;
309
+ /** §3.5 / PRD §5.3 — `Reachable` tracks the Indigo device's enabled state. */
310
+ export declare function applyReachable(endpoint: Endpoint, reachable: boolean): Promise<void>;
311
+ /** §4.1 — `NodeLabel` follows the export's display name. */
312
+ export declare function applyLabel(endpoint: Endpoint, label: string): Promise<void>;
313
+ /**
314
+ * True when a cluster change came from our own `set_state` rather than from an
315
+ * ecosystem (§6.4). matter.js runs local agent writes in a `LocalActorContext`,
316
+ * whose `offline` is the literal `true`; a remote (network) action carries a
317
+ * `RemoteActorContext` with `offline` absent or `false`.
318
+ *
319
+ * **Assumes matter.js is not managing transitions.** Anything matter.js writes
320
+ * on its own behalf — notably the intermediate steps of a managed LevelControl
321
+ * transition — is offline too, and would be swallowed here as if we had written
322
+ * it. That is why {@link LEVEL_CONTROL_INITIAL} pins
323
+ * `managedTransitionTimeHandling: false`: the guard can only tell "us" from
324
+ * "them" while matter.js itself is not a third writer.
325
+ *
326
+ * Exported because it is the whole echo guard, and a pure predicate is testable
327
+ * without persuading a real Matter stack to originate a remote write.
328
+ */
329
+ export declare function isEcosystemChange(context: unknown): boolean;
330
+ /**
331
+ * Subscribe the role's cluster-change listeners, register its command sink, and
332
+ * return the teardown for both.
333
+ *
334
+ * The teardown matters: a removed endpoint whose observables still hold our
335
+ * handler would keep emitting `command` events for a device the plugin no
336
+ * longer exports, and would keep the closure (and the endpoint) alive. The
337
+ * {@link COMMAND_SINKS} entry is registered and removed here for exactly the
338
+ * same reason — the invocation-driven roles have no observables at all, so this
339
+ * is the *only* thing standing between a removed lock and a `command` event for
340
+ * a device the plugin has forgotten.
341
+ *
342
+ * Throws if a watched observable is missing. That is a role-definition contract
343
+ * violation — this table and the device type it names have to agree — and the
344
+ * alternative is worse than a crash: skipping the subscription leaves the
345
+ * accessory fully controllable in the ecosystem while every command it produces
346
+ * goes nowhere, with nothing in any log to say so. Failing at construction
347
+ * means any endpoint-building test catches a matter.js rename or a feature
348
+ * regression the first time it runs.
349
+ */
350
+ export declare function watchCommands(endpoint: Endpoint, spec: {
351
+ indigoDeviceId: number;
352
+ role: RoleValue;
353
+ }, emit: (data: CommandEventData) => void, log?: (message: string) => void): () => void;