matter-all-in-one-addon 1.8.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (244) hide show
  1. package/README.md +183 -0
  2. package/dist/camera/ai/camera-ai-detector.d.ts +44 -0
  3. package/dist/camera/ai/camera-ai-detector.js +329 -0
  4. package/dist/camera/ai/camera-ai-detector.js.map +1 -0
  5. package/dist/camera/camera-capabilities.d.ts +13 -0
  6. package/dist/camera/camera-capabilities.js +186 -0
  7. package/dist/camera/camera-capabilities.js.map +1 -0
  8. package/dist/camera/camera-source-resolver.d.ts +18 -0
  9. package/dist/camera/camera-source-resolver.js +187 -0
  10. package/dist/camera/camera-source-resolver.js.map +1 -0
  11. package/dist/camera/camera-types.d.ts +124 -0
  12. package/dist/camera/camera-types.js +8 -0
  13. package/dist/camera/camera-types.js.map +1 -0
  14. package/dist/camera/cameraui/cameraui-client.d.ts +54 -0
  15. package/dist/camera/cameraui/cameraui-client.js +698 -0
  16. package/dist/camera/cameraui/cameraui-client.js.map +1 -0
  17. package/dist/camera/cameraui/cameraui-homekit-bridge.d.ts +21 -0
  18. package/dist/camera/cameraui/cameraui-homekit-bridge.js +343 -0
  19. package/dist/camera/cameraui/cameraui-homekit-bridge.js.map +1 -0
  20. package/dist/camera/cameraui/cameraui-storage.d.ts +17 -0
  21. package/dist/camera/cameraui/cameraui-storage.js +916 -0
  22. package/dist/camera/cameraui/cameraui-storage.js.map +1 -0
  23. package/dist/camera/cameraui/cameraui-types.d.ts +89 -0
  24. package/dist/camera/cameraui/cameraui-types.js +5 -0
  25. package/dist/camera/cameraui/cameraui-types.js.map +1 -0
  26. package/dist/camera/homekit/ffmpeg-helper.d.ts +88 -0
  27. package/dist/camera/homekit/ffmpeg-helper.js +673 -0
  28. package/dist/camera/homekit/ffmpeg-helper.js.map +1 -0
  29. package/dist/camera/homekit/fmp4-parser.d.ts +48 -0
  30. package/dist/camera/homekit/fmp4-parser.js +156 -0
  31. package/dist/camera/homekit/fmp4-parser.js.map +1 -0
  32. package/dist/camera/homekit/hevc-eligibility.d.ts +16 -0
  33. package/dist/camera/homekit/hevc-eligibility.js +153 -0
  34. package/dist/camera/homekit/hevc-eligibility.js.map +1 -0
  35. package/dist/camera/homekit/homekit-camera-recording.delegate.d.ts +73 -0
  36. package/dist/camera/homekit/homekit-camera-recording.delegate.js +445 -0
  37. package/dist/camera/homekit/homekit-camera-recording.delegate.js.map +1 -0
  38. package/dist/camera/homekit/homekit-camera-stream.delegate.d.ts +47 -0
  39. package/dist/camera/homekit/homekit-camera-stream.delegate.js +833 -0
  40. package/dist/camera/homekit/homekit-camera-stream.delegate.js.map +1 -0
  41. package/dist/camera/homekit/homekit-camera.accessory.d.ts +53 -0
  42. package/dist/camera/homekit/homekit-camera.accessory.js +697 -0
  43. package/dist/camera/homekit/homekit-camera.accessory.js.map +1 -0
  44. package/dist/camera/matter/camera-endpoint.builder.d.ts +7 -0
  45. package/dist/camera/matter/camera-endpoint.builder.js +127 -0
  46. package/dist/camera/matter/camera-endpoint.builder.js.map +1 -0
  47. package/dist/camera/matter/camera-session-manager.d.ts +46 -0
  48. package/dist/camera/matter/camera-session-manager.js +120 -0
  49. package/dist/camera/matter/camera-session-manager.js.map +1 -0
  50. package/dist/camera/matter/camera-webrtc-adapter.d.ts +62 -0
  51. package/dist/camera/matter/camera-webrtc-adapter.js +298 -0
  52. package/dist/camera/matter/camera-webrtc-adapter.js.map +1 -0
  53. package/dist/camera/motion/ffmpeg-motion-detector.d.ts +46 -0
  54. package/dist/camera/motion/ffmpeg-motion-detector.js +200 -0
  55. package/dist/camera/motion/ffmpeg-motion-detector.js.map +1 -0
  56. package/dist/camera/nest/nest-camera-adapter.d.ts +38 -0
  57. package/dist/camera/nest/nest-camera-adapter.js +109 -0
  58. package/dist/camera/nest/nest-camera-adapter.js.map +1 -0
  59. package/dist/camera/scrypted/scrypted-camera-card.d.ts +39 -0
  60. package/dist/camera/scrypted/scrypted-camera-card.js +38 -0
  61. package/dist/camera/scrypted/scrypted-camera-card.js.map +1 -0
  62. package/dist/camera/scrypted/scrypted-camera-detail.d.ts +33 -0
  63. package/dist/camera/scrypted/scrypted-camera-detail.js +34 -0
  64. package/dist/camera/scrypted/scrypted-camera-detail.js.map +1 -0
  65. package/dist/camera/scrypted/scrypted-camera-discovery-adapter.d.ts +17 -0
  66. package/dist/camera/scrypted/scrypted-camera-discovery-adapter.js +24 -0
  67. package/dist/camera/scrypted/scrypted-camera-discovery-adapter.js.map +1 -0
  68. package/dist/camera/scrypted/scrypted-camera-normalizer.d.ts +44 -0
  69. package/dist/camera/scrypted/scrypted-camera-normalizer.js +44 -0
  70. package/dist/camera/scrypted/scrypted-camera-normalizer.js.map +1 -0
  71. package/dist/camera/scrypted/scrypted-camera-policy.d.ts +11 -0
  72. package/dist/camera/scrypted/scrypted-camera-policy.js +13 -0
  73. package/dist/camera/scrypted/scrypted-camera-policy.js.map +1 -0
  74. package/dist/camera/scrypted/scrypted-camera-presentation.d.ts +13 -0
  75. package/dist/camera/scrypted/scrypted-camera-presentation.js +23 -0
  76. package/dist/camera/scrypted/scrypted-camera-presentation.js.map +1 -0
  77. package/dist/camera/scrypted/scrypted-client-discovery-adapter.d.ts +6 -0
  78. package/dist/camera/scrypted/scrypted-client-discovery-adapter.js +12 -0
  79. package/dist/camera/scrypted/scrypted-client-discovery-adapter.js.map +1 -0
  80. package/dist/camera/scrypted/scrypted-client.d.ts +152 -0
  81. package/dist/camera/scrypted/scrypted-client.js +1170 -0
  82. package/dist/camera/scrypted/scrypted-client.js.map +1 -0
  83. package/dist/camera/scrypted/scrypted-crypto.d.ts +21 -0
  84. package/dist/camera/scrypted/scrypted-crypto.js +90 -0
  85. package/dist/camera/scrypted/scrypted-crypto.js.map +1 -0
  86. package/dist/camera/scrypted/scrypted-discovery-provider.d.ts +9 -0
  87. package/dist/camera/scrypted/scrypted-discovery-provider.js +25 -0
  88. package/dist/camera/scrypted/scrypted-discovery-provider.js.map +1 -0
  89. package/dist/camera/scrypted/scrypted-homekit-bridge.d.ts +12 -0
  90. package/dist/camera/scrypted/scrypted-homekit-bridge.js +214 -0
  91. package/dist/camera/scrypted/scrypted-homekit-bridge.js.map +1 -0
  92. package/dist/camera/scrypted/scrypted-matter-bridge.d.ts +36 -0
  93. package/dist/camera/scrypted/scrypted-matter-bridge.js +226 -0
  94. package/dist/camera/scrypted/scrypted-matter-bridge.js.map +1 -0
  95. package/dist/camera/scrypted/scrypted-reconnect-manager.d.ts +40 -0
  96. package/dist/camera/scrypted/scrypted-reconnect-manager.js +353 -0
  97. package/dist/camera/scrypted/scrypted-reconnect-manager.js.map +1 -0
  98. package/dist/camera/scrypted/scrypted-runtime-connector.d.ts +7 -0
  99. package/dist/camera/scrypted/scrypted-runtime-connector.js +17 -0
  100. package/dist/camera/scrypted/scrypted-runtime-connector.js.map +1 -0
  101. package/dist/camera/scrypted/scrypted-runtime-facade.d.ts +13 -0
  102. package/dist/camera/scrypted/scrypted-runtime-facade.js +29 -0
  103. package/dist/camera/scrypted/scrypted-runtime-facade.js.map +1 -0
  104. package/dist/camera/scrypted/scrypted-runtime-ingest.d.ts +5 -0
  105. package/dist/camera/scrypted/scrypted-runtime-ingest.js +54 -0
  106. package/dist/camera/scrypted/scrypted-runtime-ingest.js.map +1 -0
  107. package/dist/camera/scrypted/scrypted-storage.d.ts +95 -0
  108. package/dist/camera/scrypted/scrypted-storage.js +698 -0
  109. package/dist/camera/scrypted/scrypted-storage.js.map +1 -0
  110. package/dist/camera/scrypted/scrypted-stream-validator.d.ts +46 -0
  111. package/dist/camera/scrypted/scrypted-stream-validator.js +412 -0
  112. package/dist/camera/scrypted/scrypted-stream-validator.js.map +1 -0
  113. package/dist/camera/scrypted/scrypted-types.d.ts +354 -0
  114. package/dist/camera/scrypted/scrypted-types.js +6 -0
  115. package/dist/camera/scrypted/scrypted-types.js.map +1 -0
  116. package/dist/converters/binary_sensor.converter.d.ts +18 -0
  117. package/dist/converters/binary_sensor.converter.js +21 -0
  118. package/dist/converters/binary_sensor.converter.js.map +1 -0
  119. package/dist/converters/camera.converter.d.ts +18 -0
  120. package/dist/converters/camera.converter.js +24 -0
  121. package/dist/converters/camera.converter.js.map +1 -0
  122. package/dist/converters/climate.converter.d.ts +21 -0
  123. package/dist/converters/climate.converter.js +55 -0
  124. package/dist/converters/climate.converter.js.map +1 -0
  125. package/dist/converters/cover.converter.d.ts +14 -0
  126. package/dist/converters/cover.converter.js +22 -0
  127. package/dist/converters/cover.converter.js.map +1 -0
  128. package/dist/converters/energy_tariff.converter.d.ts +10 -0
  129. package/dist/converters/energy_tariff.converter.js +12 -0
  130. package/dist/converters/energy_tariff.converter.js.map +1 -0
  131. package/dist/converters/fan.converter.d.ts +233 -0
  132. package/dist/converters/fan.converter.js +353 -0
  133. package/dist/converters/fan.converter.js.map +1 -0
  134. package/dist/converters/index.d.ts +14 -0
  135. package/dist/converters/index.js +15 -0
  136. package/dist/converters/index.js.map +1 -0
  137. package/dist/converters/light.converter.d.ts +26 -0
  138. package/dist/converters/light.converter.js +36 -0
  139. package/dist/converters/light.converter.js.map +1 -0
  140. package/dist/converters/lock.converter.d.ts +20 -0
  141. package/dist/converters/lock.converter.js +29 -0
  142. package/dist/converters/lock.converter.js.map +1 -0
  143. package/dist/converters/sensor.converter.d.ts +18 -0
  144. package/dist/converters/sensor.converter.js +33 -0
  145. package/dist/converters/sensor.converter.js.map +1 -0
  146. package/dist/converters/soil_sensor.converter.d.ts +14 -0
  147. package/dist/converters/soil_sensor.converter.js +21 -0
  148. package/dist/converters/soil_sensor.converter.js.map +1 -0
  149. package/dist/converters/vacuum.converter.d.ts +168 -0
  150. package/dist/converters/vacuum.converter.js +288 -0
  151. package/dist/converters/vacuum.converter.js.map +1 -0
  152. package/dist/device-profiles.d.ts +14 -0
  153. package/dist/device-profiles.js +245 -0
  154. package/dist/device-profiles.js.map +1 -0
  155. package/dist/device-registry.d.ts +58 -0
  156. package/dist/device-registry.js +288 -0
  157. package/dist/device-registry.js.map +1 -0
  158. package/dist/entities/base.entity.d.ts +40 -0
  159. package/dist/entities/base.entity.js +826 -0
  160. package/dist/entities/base.entity.js.map +1 -0
  161. package/dist/entities/camera.entity.d.ts +48 -0
  162. package/dist/entities/camera.entity.js +127 -0
  163. package/dist/entities/camera.entity.js.map +1 -0
  164. package/dist/entities/closure.entity.d.ts +9 -0
  165. package/dist/entities/closure.entity.js +52 -0
  166. package/dist/entities/closure.entity.js.map +1 -0
  167. package/dist/entities/composite-device.entity.d.ts +61 -0
  168. package/dist/entities/composite-device.entity.js +986 -0
  169. package/dist/entities/composite-device.entity.js.map +1 -0
  170. package/dist/entities/cooktop.entity.d.ts +20 -0
  171. package/dist/entities/cooktop.entity.js +59 -0
  172. package/dist/entities/cooktop.entity.js.map +1 -0
  173. package/dist/entities/energy_tariff.entity.d.ts +7 -0
  174. package/dist/entities/energy_tariff.entity.js +32 -0
  175. package/dist/entities/energy_tariff.entity.js.map +1 -0
  176. package/dist/entities/humidifier.entity.d.ts +27 -0
  177. package/dist/entities/humidifier.entity.js +187 -0
  178. package/dist/entities/humidifier.entity.js.map +1 -0
  179. package/dist/entities/lock.entity.d.ts +12 -0
  180. package/dist/entities/lock.entity.js +58 -0
  181. package/dist/entities/lock.entity.js.map +1 -0
  182. package/dist/entities/media-player.entity.d.ts +13 -0
  183. package/dist/entities/media-player.entity.js +52 -0
  184. package/dist/entities/media-player.entity.js.map +1 -0
  185. package/dist/entities/oven.entity.d.ts +20 -0
  186. package/dist/entities/oven.entity.js +112 -0
  187. package/dist/entities/oven.entity.js.map +1 -0
  188. package/dist/entities/pet_feeder.entity.d.ts +28 -0
  189. package/dist/entities/pet_feeder.entity.js +67 -0
  190. package/dist/entities/pet_feeder.entity.js.map +1 -0
  191. package/dist/entities/soil_sensor.entity.d.ts +7 -0
  192. package/dist/entities/soil_sensor.entity.js +40 -0
  193. package/dist/entities/soil_sensor.entity.js.map +1 -0
  194. package/dist/entities/vacuum.entity.d.ts +37 -0
  195. package/dist/entities/vacuum.entity.js +352 -0
  196. package/dist/entities/vacuum.entity.js.map +1 -0
  197. package/dist/frontend/assets/index-DPXu3al2.js +26 -0
  198. package/dist/frontend/assets/index-DalMl4eS.css +1 -0
  199. package/dist/frontend/assets/logo-B_gEBugV.png +0 -0
  200. package/dist/frontend/index.html +14 -0
  201. package/dist/frontend/logo.png +0 -0
  202. package/dist/homeAssistant.d.ts +1268 -0
  203. package/dist/homeAssistant.js +1623 -0
  204. package/dist/homeAssistant.js.map +1 -0
  205. package/dist/homekit.compat.d.ts +40 -0
  206. package/dist/homekit.compat.js +43 -0
  207. package/dist/homekit.compat.js.map +1 -0
  208. package/dist/index.d.ts +7 -0
  209. package/dist/index.js +31 -0
  210. package/dist/index.js.map +1 -0
  211. package/dist/mqtt/mqtt-client.d.ts +33 -0
  212. package/dist/mqtt/mqtt-client.js +138 -0
  213. package/dist/mqtt/mqtt-client.js.map +1 -0
  214. package/dist/mqtt/mqtt.entity.d.ts +30 -0
  215. package/dist/mqtt/mqtt.entity.js +286 -0
  216. package/dist/mqtt/mqtt.entity.js.map +1 -0
  217. package/dist/platform.d.ts +318 -0
  218. package/dist/platform.js +6144 -0
  219. package/dist/platform.js.map +1 -0
  220. package/dist/proxy.d.ts +1 -0
  221. package/dist/proxy.js +226 -0
  222. package/dist/proxy.js.map +1 -0
  223. package/dist/utils/ha-discovery.d.ts +30 -0
  224. package/dist/utils/ha-discovery.js +175 -0
  225. package/dist/utils/ha-discovery.js.map +1 -0
  226. package/dist/utils/ha-state.d.ts +48 -0
  227. package/dist/utils/ha-state.js +21 -0
  228. package/dist/utils/ha-state.js.map +1 -0
  229. package/dist/utils/light-color.d.ts +63 -0
  230. package/dist/utils/light-color.js +213 -0
  231. package/dist/utils/light-color.js.map +1 -0
  232. package/dist/utils/log-buffer.d.ts +13 -0
  233. package/dist/utils/log-buffer.js +50 -0
  234. package/dist/utils/log-buffer.js.map +1 -0
  235. package/dist/utils/matter-attributes.d.ts +13 -0
  236. package/dist/utils/matter-attributes.js +35 -0
  237. package/dist/utils/matter-attributes.js.map +1 -0
  238. package/dist/utils/matter-device-identity.d.ts +22 -0
  239. package/dist/utils/matter-device-identity.js +70 -0
  240. package/dist/utils/matter-device-identity.js.map +1 -0
  241. package/dist/utils/thread-credentials.d.ts +22 -0
  242. package/dist/utils/thread-credentials.js +29 -0
  243. package/dist/utils/thread-credentials.js.map +1 -0
  244. package/package.json +80 -0
@@ -0,0 +1,986 @@
1
+ /**
2
+ * One Matter ServerNode containing multiple endpoints that belong to the same
3
+ * Home Assistant device registry entry. The root endpoint is the primary
4
+ * capability (lock, fan, or configured entity); remaining compatible entities are child
5
+ * endpoints and therefore share its QR code and fabrics.
6
+ *
7
+ * v1.2.11 — Critical fix: child endpoint clusters (LevelControl, ColorControl)
8
+ * are now declared upfront in addChildDeviceTypeWithClusterServer() instead of
9
+ * being added post-hoc with addClusterServers(). Matter controllers (Apple Home,
10
+ * Google Home) read the Descriptor cluster at commissioning time to discover
11
+ * endpoint capabilities; clusters added after endpoint creation are not visible.
12
+ */
13
+ import { MatterbridgeEndpoint } from "matterbridge";
14
+ import { BooleanState, ColorControl, FanControl, LevelControl, OccupancySensing, RelativeHumidityMeasurement, TemperatureMeasurement, OnOff, DoorLock, } from "matterbridge/matter/clusters";
15
+ import { MatterbridgeOnOffServer, MatterbridgeFanControlServer, } from "matterbridge/behaviors";
16
+ import { BasicInformationServer, } from "matterbridge/matter/behaviors";
17
+ import { safeSetAttribute, safeUpdateAttribute, } from "../utils/matter-attributes.js";
18
+ import { isUnavailable } from "../utils/ha-state.js";
19
+ import { getDeviceTypeForEntity, getLightDeviceType, hasColorTemperatureCapability, } from "../device-registry.js";
20
+ import { getMatterSerialNumber, getHaDeviceModel, getHaDeviceManufacturer, MATTER_BRIDGE_VENDOR_ID, } from "../utils/matter-device-identity.js";
21
+ import { lightColor } from "../utils/light-color.js";
22
+ import { isFanOn, fanPercentage, fanDirection, haDirectionToMatter, matterDirectionToHa, haStateToFanMode, snapToPhysicalLevel, FAN_MODE_SEQUENCE, FAN_SPEED_MAX, hasFanDirection, hasFanSpeed, hasFanAuto, getFanSpeedCount, getFanModeSequence, getFanControlFeatures, fanSpeed, withinHysteresis, } from "../converters/fan.converter.js";
23
+ import { lightConverter } from "../converters/light.converter.js";
24
+ import { cameraConverter } from "../converters/camera.converter.js";
25
+ function endpointId(entityId) {
26
+ return entityId.replaceAll(".", "_");
27
+ }
28
+ function isOn(state) {
29
+ return state.state === "on";
30
+ }
31
+ function isFanProfile(deviceType) {
32
+ return deviceType.code === 0x002b || deviceType.name.toLowerCase() === "fan";
33
+ }
34
+ function lightClusterIds(state, deviceType) {
35
+ const clusters = [OnOff.id];
36
+ const modes = state.attributes.supported_color_modes ?? [];
37
+ const hasBrightness = modes.includes("brightness") || state.attributes.brightness !== undefined;
38
+ const hasColorTemp = hasColorTemperatureCapability(state.attributes);
39
+ const hasRgb = modes.some((m) => ["hs", "xy", "rgb", "rgbw", "rgbww"].includes(m));
40
+ const isOnOffProfile = deviceType.code === 0x0100 || deviceType.code === 0x010a;
41
+ const isColorProfile = deviceType.code === 0x010c || deviceType.code === 0x010d;
42
+ if ((hasBrightness || hasColorTemp || hasRgb) && !isOnOffProfile)
43
+ clusters.push(LevelControl.id);
44
+ if ((hasColorTemp || hasRgb) && isColorProfile)
45
+ clusters.push(ColorControl.id);
46
+ return clusters;
47
+ }
48
+ function toMatterLevel(brightness) {
49
+ return lightConverter.toLevel(brightness);
50
+ }
51
+ export class CompositeDeviceEntity {
52
+ platform;
53
+ deviceId;
54
+ name;
55
+ members;
56
+ primaryEntityIdOverride;
57
+ endpoint;
58
+ endpoints = new Map();
59
+ states = new Map();
60
+ lastCommands = new Map();
61
+ lastSyncedFan = new Map();
62
+ isDifferent(attribute, requested, actual) {
63
+ if (attribute === "hs_color") {
64
+ if (!requested || !actual)
65
+ return true;
66
+ return (Math.abs(requested[0] - actual[0]) > 3 ||
67
+ Math.abs(requested[1] - actual[1]) > 2);
68
+ }
69
+ if (attribute === "xy_color") {
70
+ if (!requested || !actual)
71
+ return true;
72
+ return (Math.abs(requested[0] - actual[0]) > 0.01 ||
73
+ Math.abs(requested[1] - actual[1]) > 0.01);
74
+ }
75
+ if (attribute === "brightness") {
76
+ return Math.abs(requested - actual) > 5;
77
+ }
78
+ if (attribute === "fan_percentage") {
79
+ return !withinHysteresis(requested, actual);
80
+ }
81
+ if (attribute === "color_temp") {
82
+ return Math.abs(requested - actual) > 10;
83
+ }
84
+ return requested !== actual;
85
+ }
86
+ shouldIgnoreStateUpdate(entityId, attribute, haValue, windowMs = 3000) {
87
+ const key = `${entityId}:${attribute}`;
88
+ const last = this.lastCommands.get(key);
89
+ if (!last)
90
+ return false;
91
+ const elapsed = Date.now() - last.timestamp;
92
+ if (elapsed > windowMs) {
93
+ this.lastCommands.delete(key);
94
+ return false;
95
+ }
96
+ if (this.isDifferent(attribute, last.value, haValue)) {
97
+ this.platform.log.debug(`[${entityId}] Reconciling HA feedback for ${attribute} (req=${JSON.stringify(last.value)}, got=${JSON.stringify(haValue)})`);
98
+ this.lastCommands.delete(key);
99
+ return false;
100
+ }
101
+ return true;
102
+ }
103
+ setCommandLockout(entityId, attribute, value) {
104
+ this.lastCommands.set(`${entityId}:${attribute}`, {
105
+ value,
106
+ timestamp: Date.now(),
107
+ });
108
+ }
109
+ constructor(platform, deviceId, name, members, primaryEntityIdOverride) {
110
+ this.platform = platform;
111
+ this.deviceId = deviceId;
112
+ this.name = name;
113
+ this.members = members;
114
+ this.primaryEntityIdOverride = primaryEntityIdOverride;
115
+ members.forEach((member) => this.states.set(member.entityId, member.state));
116
+ }
117
+ get primaryEntityId() {
118
+ if (this.primaryEntityIdOverride &&
119
+ this.members.some((m) => m.entityId === this.primaryEntityIdOverride)) {
120
+ return this.primaryEntityIdOverride;
121
+ }
122
+ return (this.members.find((m) => m.entityId.startsWith("camera."))?.entityId ??
123
+ this.members.find((m) => m.entityId.startsWith("lock."))?.entityId ??
124
+ this.members.find((m) => m.entityId.startsWith("humidifier."))
125
+ ?.entityId ??
126
+ this.members.find((m) => m.entityId.startsWith("fan."))?.entityId ??
127
+ this.members.find((m) => m.entityId.startsWith("climate."))?.entityId ??
128
+ this.members.find((m) => m.entityId.startsWith("vacuum."))?.entityId ??
129
+ this.members[0].entityId);
130
+ }
131
+ async setReachability(reachable) {
132
+ const ep = this.endpoint;
133
+ if (!ep)
134
+ return;
135
+ try {
136
+ const serverNode = ep.serverNode;
137
+ if (serverNode && typeof serverNode.setStateOf === "function") {
138
+ await serverNode.setStateOf(BasicInformationServer, { reachable });
139
+ }
140
+ if (typeof ep.setAttribute === "function") {
141
+ if (ep.hasAttributeServer?.(0x0028, "reachable")) {
142
+ await ep.setAttribute(0x0028, "reachable", reachable, this.platform.log);
143
+ }
144
+ if (ep.hasAttributeServer?.(0x0039, "reachable")) {
145
+ await ep.setAttribute(0x0039, "reachable", reachable, this.platform.log);
146
+ }
147
+ }
148
+ if (typeof ep.updateAttribute === "function") {
149
+ if (ep.hasAttributeServer?.(0x0039, "reachable")) {
150
+ await ep.updateAttribute(0x0039, "reachable", reachable, this.platform.log);
151
+ }
152
+ if (ep.hasAttributeServer?.(0x0028, "reachable")) {
153
+ await ep.updateAttribute(0x0028, "reachable", reachable, this.platform.log);
154
+ }
155
+ }
156
+ this.platform.log?.debug?.(`[Composite:${this.deviceId}] Updated Matter reachability to ${reachable}`);
157
+ }
158
+ catch (err) {
159
+ this.platform.log?.debug?.(`[Composite:${this.deviceId}] Could not update reachability to ${reachable}: ${err}`);
160
+ }
161
+ }
162
+ async createEndpoint() {
163
+ const primary = this.members.find((m) => m.entityId === this.primaryEntityId);
164
+ const primaryType = this.typeFor(primary);
165
+ this.platform.log.notice("[Composite] group_by_device_id=true");
166
+ this.platform.log.notice(`[Composite] Found HA device_id: ${this.deviceId}`);
167
+ this.platform.log.notice(`[Composite] Composite candidate: ${this.members.map((m) => m.entityId).join(" + ")}`);
168
+ this.platform.log.notice(`[Composite] Primary entity: ${primary.entityId}`);
169
+ this.platform.log.notice(`[Composite] Creating ServerNode composite accessory: ${this.name}`);
170
+ this.platform.log.notice(`[Composite] Endpoint 1 (root): ${primaryType.name} → ${primary.entityId}`);
171
+ this.endpoint = new MatterbridgeEndpoint([primaryType], {
172
+ id: `device_${this.deviceId}`,
173
+ mode: "server",
174
+ });
175
+ this.configureRootIdentity(this.endpoint, primaryType, primary.entityId);
176
+ await this.addRootClusters(this.endpoint, primary);
177
+ this.addCommandHandlers(this.endpoint, primary);
178
+ this.endpoints.set(primary.entityId, this.endpoint);
179
+ let endpointIndex = 2;
180
+ for (const member of this.members) {
181
+ if (member.entityId === primary.entityId)
182
+ continue;
183
+ const [domain] = member.entityId.split(".");
184
+ const memberType = this.typeFor(member);
185
+ const clusterIds = this.computeClusterIds(member);
186
+ if (domain === "light") {
187
+ this.logLightCapabilities(member, memberType, clusterIds, primary.entityId);
188
+ }
189
+ else {
190
+ this.platform.log.notice(`[Composite] Integrated endpoint: ${member.entityId} (${memberType.name})`);
191
+ }
192
+ this.platform.log.notice(`[Composite] Endpoint ${endpointIndex}: ${memberType.name} → ${member.entityId}`);
193
+ endpointIndex++;
194
+ const child = this.endpoint.addChildDeviceTypeWithClusterServer(endpointId(member.entityId), memberType, clusterIds);
195
+ const childFriendlyName = (member.state.attributes.friendly_name ??
196
+ (domain === "light"
197
+ ? "Luz"
198
+ : domain === "fan"
199
+ ? "Ventilador"
200
+ : memberType.name))
201
+ .substring(0, 32)
202
+ .trim();
203
+ child.deviceName = childFriendlyName;
204
+ child.nodeLabel = childFriendlyName;
205
+ this.addCommandHandlers(child, member);
206
+ this.endpoints.set(member.entityId, child);
207
+ }
208
+ this.platform.log.notice(`[Composite] QR generated for composite node: ${this.name}`);
209
+ this.platform.log.notice(`[Composite] Descriptor endpoints: [${this.members.map((m) => `${m.entityId}`).join(", ")}]`);
210
+ return this.endpoint;
211
+ }
212
+ adoptEndpoint(endpoint) {
213
+ this.endpoint = endpoint;
214
+ this.endpoints.clear();
215
+ for (const member of this.members) {
216
+ const memberEndpoint = member.entityId === this.primaryEntityId
217
+ ? endpoint
218
+ : (endpoint.getChildEndpointById(endpointId(member.entityId)) ??
219
+ endpoint.getChildEndpointByOriginalId(endpointId(member.entityId)));
220
+ if (!memberEndpoint) {
221
+ this.platform.log.warn(`[Composite] Retained node is missing endpoint ${member.entityId}; preserving the node without fabric reset.`);
222
+ continue;
223
+ }
224
+ this.endpoints.set(member.entityId, memberEndpoint);
225
+ if (memberEndpoint.commandHandler &&
226
+ memberEndpoint.commandHandler.handler?.length === 0) {
227
+ this.addCommandHandlers(memberEndpoint, member);
228
+ }
229
+ }
230
+ }
231
+ async syncInitialState() {
232
+ await Promise.all(this.members.map((m) => this.updateEntity(m.entityId, m.state, true)));
233
+ }
234
+ haUpdateDepth = new Map();
235
+ isUpdatingFromHa(entityId) {
236
+ return (this.haUpdateDepth.get(entityId) ?? 0) > 0;
237
+ }
238
+ async updateEntity(entityId, state, initial = false) {
239
+ this.states.set(entityId, state);
240
+ const endpoint = this.endpoints.get(entityId);
241
+ if (!endpoint)
242
+ return;
243
+ const [domain] = entityId.split(".");
244
+ const update = initial ? safeSetAttribute : safeUpdateAttribute;
245
+ this.haUpdateDepth.set(entityId, (this.haUpdateDepth.get(entityId) ?? 0) + 1);
246
+ try {
247
+ if (domain === "fan") {
248
+ const on = isFanOn(state);
249
+ await update(endpoint, OnOff.id, "onOff", on, this.platform.log);
250
+ if (!endpoint.hasAttributeServer(FanControl.id, "fanMode"))
251
+ return;
252
+ const hasSpeed = hasFanSpeed(state);
253
+ const speedMax = getFanSpeedCount(state);
254
+ const pct = on ? fanPercentage(state) : 0;
255
+ const speed = on ? fanSpeed(pct, speedMax) : 0;
256
+ const fanMode = haStateToFanMode(state);
257
+ this.lastSyncedFan.set(entityId, { on, pct });
258
+ this.platform.log.debug(`[Composite][${entityId}] Fan update: state=${state.state}, on=${on}, pct=${pct}, speed=${speed}/${speedMax}, fanMode=${fanMode}, speedSupport=${hasSpeed}, dir=${state.attributes.direction ?? "N/A"}, osc=${state.attributes.oscillating ?? "N/A"}, preset=${state.attributes.preset_mode ?? "N/A"}`);
259
+ if (hasSpeed &&
260
+ endpoint.hasAttributeServer(FanControl.id, "percentCurrent")) {
261
+ if (!initial &&
262
+ this.shouldIgnoreStateUpdate(entityId, "fan_percentage", pct)) {
263
+ this.platform.log.debug(`[Composite][${entityId}] Ignoring fan_percentage update (lockout)`);
264
+ }
265
+ else {
266
+ await update(endpoint, FanControl.id, "percentCurrent", pct, this.platform.log);
267
+ await update(endpoint, FanControl.id, "percentSetting", pct, this.platform.log);
268
+ if (endpoint.hasAttributeServer(FanControl.id, "speedCurrent")) {
269
+ await update(endpoint, FanControl.id, "speedSetting", speed, this.platform.log);
270
+ await update(endpoint, FanControl.id, "speedCurrent", speed, this.platform.log);
271
+ }
272
+ }
273
+ }
274
+ await update(endpoint, FanControl.id, "fanMode", fanMode, this.platform.log);
275
+ // Sync AirflowDirection if the cluster supports it
276
+ if (endpoint.hasAttributeServer(FanControl.id, "airflowDirection")) {
277
+ const dir = fanDirection(state);
278
+ if (dir !== undefined) {
279
+ if (!initial &&
280
+ this.shouldIgnoreStateUpdate(entityId, "fan_direction", dir)) {
281
+ this.platform.log.debug(`[Composite][${entityId}] Ignoring fan_direction update (lockout)`);
282
+ }
283
+ else {
284
+ const matterDir = haDirectionToMatter(dir);
285
+ await update(endpoint, FanControl.id, "airflowDirection", matterDir, this.platform.log);
286
+ }
287
+ }
288
+ }
289
+ return;
290
+ }
291
+ if (domain === "camera") {
292
+ const on = cameraConverter.isCameraOn(state);
293
+ await update(endpoint, OnOff.id, "onOff", on, this.platform.log);
294
+ return;
295
+ }
296
+ if (domain === "lock") {
297
+ const matterState = this.toLockState(state);
298
+ await update(endpoint, DoorLock.id, "lockState", matterState, this.platform.log);
299
+ return;
300
+ }
301
+ if (domain === "light" || domain === "switch") {
302
+ const isEntityOn = isOn(state);
303
+ const beforeLevel = endpoint.hasAttributeServer(LevelControl.id, "currentLevel")
304
+ ? endpoint.getAttribute(LevelControl.id, "currentLevel")
305
+ : undefined;
306
+ const beforeOnOff = endpoint.hasAttributeServer(OnOff.id, "onOff")
307
+ ? endpoint.getAttribute(OnOff.id, "onOff")
308
+ : undefined;
309
+ if (domain === "light" && isEntityOn) {
310
+ if (typeof state.attributes.brightness === "number") {
311
+ if (!initial &&
312
+ this.shouldIgnoreStateUpdate(entityId, "brightness", state.attributes.brightness)) {
313
+ this.platform.log.debug(`[${entityId}] Ignoring HA brightness state update due to recent command lockout`);
314
+ }
315
+ else {
316
+ await update(endpoint, LevelControl.id, "currentLevel", toMatterLevel(state.attributes.brightness), this.platform.log);
317
+ }
318
+ }
319
+ const attrs = state.attributes;
320
+ const colorMode = attrs.color_mode;
321
+ const range = lightColor.getMiredsRange(attrs);
322
+ await update(endpoint, ColorControl.id, "colorTempPhysicalMinMireds", range.minMireds, this.platform.log);
323
+ await update(endpoint, ColorControl.id, "colorTempPhysicalMaxMireds", range.maxMireds, this.platform.log);
324
+ await update(endpoint, ColorControl.id, "coupleColorTempMinMireds", range.minMireds, this.platform.log);
325
+ await update(endpoint, ColorControl.id, "coupleColorTempMaxMireds", range.maxMireds, this.platform.log);
326
+ const minPhys = endpoint.state?.colorControl?.colorTempPhysicalMinMireds ??
327
+ range.minMireds;
328
+ const maxPhys = endpoint.state?.colorControl?.colorTempPhysicalMaxMireds ??
329
+ range.maxMireds;
330
+ const rawMireds = attrs.color_temp ??
331
+ (attrs.color_temp_kelvin
332
+ ? lightColor.kelvinToMireds(attrs.color_temp_kelvin)
333
+ : undefined);
334
+ const mireds = rawMireds !== undefined
335
+ ? lightColor.clampMireds(rawMireds, attrs, {
336
+ minMireds: minPhys,
337
+ maxMireds: maxPhys,
338
+ })
339
+ : undefined;
340
+ const xy = Array.isArray(attrs.xy_color) && attrs.xy_color.length >= 2
341
+ ? attrs.xy_color
342
+ : undefined;
343
+ const hs = lightColor.getHsColor(state);
344
+ if (mireds !== undefined &&
345
+ (colorMode === "color_temp" || (!hs && !xy))) {
346
+ if (!initial &&
347
+ this.shouldIgnoreStateUpdate(entityId, "color_temp", mireds)) {
348
+ this.platform.log.debug(`[${entityId}] Ignoring HA color_temp state update due to recent command lockout`);
349
+ }
350
+ else {
351
+ await update(endpoint, ColorControl.id, "colorTemperatureMireds", mireds, this.platform.log);
352
+ await update(endpoint, ColorControl.id, "colorMode", ColorControl.ColorMode.ColorTemperatureMireds, this.platform.log);
353
+ }
354
+ }
355
+ else if (xy && (colorMode === "xy" || !hs)) {
356
+ if (!initial &&
357
+ this.shouldIgnoreStateUpdate(entityId, "xy_color", xy)) {
358
+ this.platform.log.debug(`[${entityId}] Ignoring HA xy_color state update due to recent command lockout`);
359
+ }
360
+ else {
361
+ const matterXy = lightColor.haXyToMatter(xy[0], xy[1]);
362
+ await update(endpoint, ColorControl.id, "currentX", matterXy[0], this.platform.log);
363
+ await update(endpoint, ColorControl.id, "currentY", matterXy[1], this.platform.log);
364
+ await update(endpoint, ColorControl.id, "colorMode", ColorControl.ColorMode.CurrentXAndCurrentY, this.platform.log);
365
+ }
366
+ }
367
+ else if (hs) {
368
+ if (!initial &&
369
+ this.shouldIgnoreStateUpdate(entityId, "hs_color", hs)) {
370
+ this.platform.log.debug(`[${entityId}] Ignoring HA hs_color state update due to recent command lockout`);
371
+ }
372
+ else {
373
+ await update(endpoint, ColorControl.id, "currentHue", lightColor.haHueToMatter(hs[0]), this.platform.log);
374
+ await update(endpoint, ColorControl.id, "enhancedCurrentHue", lightColor.haHueToMatterEnhanced(hs[0]), this.platform.log);
375
+ await update(endpoint, ColorControl.id, "currentSaturation", lightColor.haSatToMatter(hs[1]), this.platform.log);
376
+ await update(endpoint, ColorControl.id, "colorMode", ColorControl.ColorMode.CurrentHueAndCurrentSaturation, this.platform.log);
377
+ if (endpoint.hasAttributeServer(ColorControl.id, "enhancedColorMode")) {
378
+ await update(endpoint, ColorControl.id, "enhancedColorMode", ColorControl.EnhancedColorMode
379
+ .EnhancedCurrentHueAndCurrentSaturation, this.platform.log);
380
+ }
381
+ }
382
+ }
383
+ }
384
+ await update(endpoint, OnOff.id, "onOff", isEntityOn, this.platform.log);
385
+ if (domain === "light") {
386
+ const afterLevel = endpoint.hasAttributeServer(LevelControl.id, "currentLevel")
387
+ ? endpoint.getAttribute(LevelControl.id, "currentLevel")
388
+ : undefined;
389
+ const afterOnOff = endpoint.hasAttributeServer(OnOff.id, "onOff")
390
+ ? endpoint.getAttribute(OnOff.id, "onOff")
391
+ : undefined;
392
+ this.platform.log.debug(`[LIGHT TRACE][${entityId}] HA state: ${state.state} | HA brightness: ${state.attributes.brightness ?? "undefined"} | ` +
393
+ `Matter CurrentLevel before: ${beforeLevel} -> after: ${afterLevel} | ` +
394
+ `Matter OnOff before: ${beforeOnOff} -> after: ${afterOnOff} | ` +
395
+ `source: ${initial ? "initialSync" : "haEvent"} | transaction/handler: updateEntity`);
396
+ }
397
+ return;
398
+ }
399
+ const deviceClass = state.attributes.device_class;
400
+ if (domain === "sensor") {
401
+ const numeric = Number(state.state);
402
+ if (!Number.isFinite(numeric))
403
+ return;
404
+ if (deviceClass === "temperature") {
405
+ await update(endpoint, TemperatureMeasurement.id, "measuredValue", Math.round(numeric * 100), this.platform.log);
406
+ }
407
+ else if (deviceClass === "humidity") {
408
+ await update(endpoint, RelativeHumidityMeasurement.id, "measuredValue", Math.round(numeric * 100), this.platform.log);
409
+ }
410
+ return;
411
+ }
412
+ if (domain === "binary_sensor") {
413
+ const active = ["on", "open", "detected", "true"].includes(state.state.toLowerCase());
414
+ if (deviceClass === "motion" || deviceClass === "occupancy") {
415
+ await update(endpoint, OccupancySensing.id, "occupancy", { occupied: active }, this.platform.log);
416
+ }
417
+ else {
418
+ await update(endpoint, BooleanState.id, "stateValue", active, this.platform.log);
419
+ }
420
+ }
421
+ }
422
+ finally {
423
+ const current = this.haUpdateDepth.get(entityId) ?? 1;
424
+ if (current <= 1) {
425
+ this.haUpdateDepth.delete(entityId);
426
+ }
427
+ else {
428
+ this.haUpdateDepth.set(entityId, current - 1);
429
+ }
430
+ }
431
+ }
432
+ typeFor(member) {
433
+ const [domain] = member.entityId.split(".");
434
+ if (domain === "light") {
435
+ return getLightDeviceType(member.state.attributes);
436
+ }
437
+ return (member.deviceType ??
438
+ getDeviceTypeForEntity(domain, member.state.attributes.device_class, member.state.attributes));
439
+ }
440
+ computeClusterIds(member) {
441
+ const [domain] = member.entityId.split(".");
442
+ // Camera: published as on/off (power/privacy state).
443
+ // CameraAvStreamManagement (0x0551) and WebRtcTransportProvider (0x0553)
444
+ // are NOT added here because Matterbridge's addClusterServers() does not
445
+ // handle them, which would crash addRequiredClusterServers().
446
+ if (domain === "camera")
447
+ return [OnOff.id];
448
+ if (domain === "light")
449
+ return lightClusterIds(member.state, this.typeFor(member));
450
+ if (domain === "switch")
451
+ return [];
452
+ if (domain === "fan") {
453
+ return isFanProfile(this.typeFor(member)) ? [FanControl.id] : [];
454
+ }
455
+ if (domain === "lock")
456
+ return [DoorLock.id];
457
+ if (domain === "sensor") {
458
+ const deviceClass = member.state.attributes.device_class;
459
+ if (deviceClass === "temperature")
460
+ return [TemperatureMeasurement.id];
461
+ if (deviceClass === "humidity")
462
+ return [RelativeHumidityMeasurement.id];
463
+ }
464
+ if (domain === "binary_sensor") {
465
+ const deviceClass = member.state.attributes.device_class;
466
+ if (deviceClass === "motion" || deviceClass === "occupancy")
467
+ return [OccupancySensing.id];
468
+ return [BooleanState.id];
469
+ }
470
+ return [];
471
+ }
472
+ configureRootIdentity(endpoint, type, primaryEntityId) {
473
+ const nodeName = this.name.substring(0, 32).trim();
474
+ endpoint.deviceType = type.code;
475
+ endpoint.deviceName = nodeName;
476
+ endpoint.nodeLabel = nodeName;
477
+ endpoint.uniqueId = `device_${this.deviceId}`.substring(0, 32);
478
+ endpoint.serialNumber = getMatterSerialNumber(this.platform, primaryEntityId);
479
+ endpoint.vendorId = MATTER_BRIDGE_VENDOR_ID;
480
+ endpoint.vendorName = getHaDeviceManufacturer(this.platform, primaryEntityId);
481
+ endpoint.productId = 0x8000;
482
+ endpoint.productName = getHaDeviceModel(this.platform, primaryEntityId, type.name);
483
+ const version = String(this.platform.matterbridge?.matterbridgeVersion ??
484
+ "Matterbridge");
485
+ const [major = 0, minor = 0, patch = 0] = version
486
+ .split(/[-+.]/)
487
+ .map((part) => Number.parseInt(part, 10) || 0);
488
+ endpoint.softwareVersion = Math.min(0xffffffff, major * 1_000_000 + minor * 1_000 + patch);
489
+ endpoint.softwareVersionString = version.startsWith("Matterbridge")
490
+ ? version
491
+ : `Matterbridge ${version}`;
492
+ endpoint.createDefaultBasicInformationClusterServer(nodeName, endpoint.serialNumber, endpoint.vendorId, endpoint.vendorName, endpoint.productId, endpoint.productName, endpoint.softwareVersion, endpoint.softwareVersionString);
493
+ }
494
+ async addRootClusters(endpoint, member) {
495
+ const [domain] = member.entityId.split(".");
496
+ if (domain === "camera") {
497
+ endpoint.behaviors.require(MatterbridgeOnOffServer.with());
498
+ endpoint.addRequiredClusterServers();
499
+ return;
500
+ }
501
+ if (domain === "fan") {
502
+ if (!isFanProfile(this.typeFor(member))) {
503
+ endpoint.behaviors.require(MatterbridgeOnOffServer.with());
504
+ endpoint.addRequiredClusterServers();
505
+ return;
506
+ }
507
+ const on = isFanOn(member.state);
508
+ const pct = fanPercentage(member.state);
509
+ const speedMax = getFanSpeedCount(member.state);
510
+ const speed = fanSpeed(pct, speedMax);
511
+ const fanMode = haStateToFanMode(member.state);
512
+ const hasDir = hasFanDirection(member.state);
513
+ const hasSpeed = hasFanSpeed(member.state);
514
+ const fanFeatures = getFanControlFeatures(member.state);
515
+ const fanModeSequence = getFanModeSequence(member.state);
516
+ this.platform.log.debug(`[Composite] Fan root init: ${member.entityId}, on=${on}, pct=${pct}, speed=${speed}/${speedMax}, sequence=${fanModeSequence}, speedSupport=${hasSpeed}, dir=${member.state.attributes.direction ?? "N/A"}`);
517
+ if (hasSpeed) {
518
+ const fanClusterBehavior = MatterbridgeFanControlServer.with(...fanFeatures);
519
+ const fanStateConfig = {
520
+ fanMode,
521
+ fanModeSequence,
522
+ percentSetting: pct,
523
+ percentCurrent: pct,
524
+ speedMax,
525
+ speedSetting: speed,
526
+ speedCurrent: speed,
527
+ };
528
+ if (hasDir) {
529
+ fanStateConfig.airflowDirection = haDirectionToMatter(fanDirection(member.state));
530
+ }
531
+ endpoint.behaviors.require(fanClusterBehavior, fanStateConfig);
532
+ }
533
+ else {
534
+ endpoint.createDefaultFanControlClusterServer(fanMode, FAN_MODE_SEQUENCE);
535
+ }
536
+ endpoint.addRequiredClusterServers();
537
+ return;
538
+ }
539
+ if (domain === "lock") {
540
+ const matterState = this.toLockState(member.state);
541
+ endpoint.createDefaultDoorLockClusterServer(matterState, DoorLock.LockType.DeadBolt);
542
+ endpoint.addRequiredClusterServers();
543
+ await safeSetAttribute(endpoint, DoorLock.id, "actuatorEnabled", true, this.platform.log);
544
+ await safeSetAttribute(endpoint, DoorLock.id, "operatingMode", DoorLock.OperatingMode.Normal, this.platform.log);
545
+ await safeSetAttribute(endpoint, DoorLock.id, "supportedOperatingModes", {
546
+ normal: true,
547
+ vacation: false,
548
+ privacy: false,
549
+ noRemoteLockUnlock: false,
550
+ passage: false,
551
+ }, this.platform.log);
552
+ return;
553
+ }
554
+ if (domain === "light" || domain === "switch") {
555
+ const isLighting = domain === "light";
556
+ endpoint.behaviors.require(isLighting
557
+ ? MatterbridgeOnOffServer.with(OnOff.Feature.Lighting)
558
+ : MatterbridgeOnOffServer.with());
559
+ endpoint.addRequiredClusterServers();
560
+ }
561
+ }
562
+ serviceDebounceTimers = new Map();
563
+ cancelDebouncedService(entityId, domain, service) {
564
+ const key = `${entityId}:${domain}.${service}`;
565
+ const pending = this.serviceDebounceTimers.get(key);
566
+ if (pending) {
567
+ clearTimeout(pending);
568
+ this.serviceDebounceTimers.delete(key);
569
+ }
570
+ }
571
+ assertMemberOnline(entityId, member) {
572
+ const currentState = this.states.get(entityId) ?? member.state;
573
+ if (isUnavailable(currentState)) {
574
+ this.platform.log.warn(`[Composite:${this.deviceId}][${entityId}] Rejecting Matter command: member is unavailable/offline in Home Assistant.`);
575
+ throw new Error(`[Composite:${this.deviceId}][${entityId}] Member is unavailable/offline`);
576
+ }
577
+ }
578
+ callServiceDebounced(entityId, domain, service, data, delayMs = 60) {
579
+ const currentSt = this.states.get(entityId);
580
+ if (isUnavailable(currentSt)) {
581
+ this.platform.log.warn(`[Composite:${this.deviceId}][${entityId}] Ignored debounced ${domain}.${service}: member is unavailable in Home Assistant.`);
582
+ return;
583
+ }
584
+ if (service === "turn_on") {
585
+ this.cancelDebouncedService(entityId, domain, "turn_off");
586
+ }
587
+ else if (service === "turn_off") {
588
+ this.cancelDebouncedService(entityId, domain, "turn_on");
589
+ }
590
+ const key = `${entityId}:${domain}.${service}`;
591
+ const existing = this.serviceDebounceTimers.get(key);
592
+ if (existing)
593
+ clearTimeout(existing);
594
+ if (delayMs <= 0) {
595
+ this.serviceDebounceTimers.delete(key);
596
+ if (data !== undefined) {
597
+ void this.platform.ha.callService(domain, service, entityId, data);
598
+ }
599
+ else {
600
+ void this.platform.ha.callService(domain, service, entityId);
601
+ }
602
+ return;
603
+ }
604
+ const timer = setTimeout(() => {
605
+ this.serviceDebounceTimers.delete(key);
606
+ const st = this.states.get(entityId);
607
+ if (isUnavailable(st)) {
608
+ this.platform.log.warn(`[Composite:${this.deviceId}][${entityId}] Ignored delayed ${domain}.${service}: member transitioned to unavailable.`);
609
+ return;
610
+ }
611
+ if (data !== undefined) {
612
+ void this.platform.ha.callService(domain, service, entityId, data);
613
+ }
614
+ else {
615
+ void this.platform.ha.callService(domain, service, entityId);
616
+ }
617
+ }, delayMs);
618
+ this.serviceDebounceTimers.set(key, timer);
619
+ }
620
+ addCommandHandlers(endpoint, member) {
621
+ const [domain] = member.entityId.split(".");
622
+ const entityId = member.entityId;
623
+ if (domain === "camera") {
624
+ endpoint.addCommandHandler("on", async () => {
625
+ this.assertMemberOnline(entityId, member);
626
+ this.setCommandLockout(entityId, "camera_state", "on");
627
+ this.platform.log.debug(`[Composite][${entityId}] → HA camera turn_on`);
628
+ await this.platform.ha.callService("camera", "turn_on", entityId);
629
+ });
630
+ endpoint.addCommandHandler("off", async () => {
631
+ this.assertMemberOnline(entityId, member);
632
+ this.setCommandLockout(entityId, "camera_state", "off");
633
+ this.platform.log.debug(`[Composite][${entityId}] → HA camera turn_off`);
634
+ await this.platform.ha.callService("camera", "turn_off", entityId);
635
+ });
636
+ return;
637
+ }
638
+ if (domain === "fan") {
639
+ endpoint.addCommandHandler("on", async () => {
640
+ this.assertMemberOnline(entityId, member);
641
+ const currentState = this.states.get(entityId) ?? member.state;
642
+ if (isFanOn(currentState))
643
+ return;
644
+ this.setCommandLockout(entityId, "fan_state", "on");
645
+ this.platform.log.debug(`[Composite][${entityId}] → HA fan turn_on`);
646
+ await this.platform.ha.callService("fan", "turn_on", entityId);
647
+ });
648
+ endpoint.addCommandHandler("off", async () => {
649
+ this.assertMemberOnline(entityId, member);
650
+ const currentState = this.states.get(entityId) ?? member.state;
651
+ if (!isFanOn(currentState))
652
+ return;
653
+ this.setCommandLockout(entityId, "fan_state", "off");
654
+ this.platform.log.debug(`[Composite][${entityId}] → HA fan turn_off`);
655
+ await this.platform.ha.callService("fan", "turn_off", entityId);
656
+ });
657
+ const hasSpeed = hasFanSpeed(member.state);
658
+ if (hasSpeed &&
659
+ endpoint.hasAttributeServer(FanControl.id, "percentCurrent")) {
660
+ endpoint.addCommandHandler("FanControl.step", async (data) => {
661
+ if (this.isUpdatingFromHa(entityId))
662
+ return;
663
+ const currentState = this.states.get(entityId) ?? member.state;
664
+ if (!hasFanSpeed(currentState))
665
+ return;
666
+ const direction = data?.request?.direction ?? data?.direction;
667
+ const current = isFanOn(currentState) ? fanPercentage(currentState) : 0;
668
+ const speedMax = getFanSpeedCount(currentState);
669
+ const delta = direction === FanControl.StepDirection.Increase ? 10 : -10;
670
+ const next = snapToPhysicalLevel(Math.max(0, Math.min(100, current + delta)), speedMax);
671
+ this.platform.log.debug(`[Composite][${entityId}] FanControl.step: dir=${direction}, current=${current}%, next=${next}%`);
672
+ if (next === 0) {
673
+ if (!isFanOn(currentState))
674
+ return;
675
+ this.setCommandLockout(entityId, "fan_state", "off");
676
+ await this.platform.ha.callService("fan", "turn_off", entityId);
677
+ }
678
+ else {
679
+ if (isFanOn(currentState) && withinHysteresis(next, current))
680
+ return;
681
+ this.setCommandLockout(entityId, "fan_percentage", next);
682
+ this.setCommandLockout(entityId, "fan_state", "on");
683
+ await this.platform.ha.callService("fan", "set_percentage", entityId, { percentage: next });
684
+ }
685
+ });
686
+ endpoint.subscribeAttribute(FanControl.id, "percentSetting", async (newValue) => {
687
+ if (this.isUpdatingFromHa(entityId))
688
+ return;
689
+ const currentState = this.states.get(entityId) ?? member.state;
690
+ if (!hasFanSpeed(currentState))
691
+ return;
692
+ if (typeof newValue === "number") {
693
+ const currentOn = isFanOn(currentState);
694
+ const currentPct = currentOn ? fanPercentage(currentState) : 0;
695
+ const speedMax = currentState
696
+ ? getFanSpeedCount(currentState)
697
+ : FAN_SPEED_MAX;
698
+ const next = snapToPhysicalLevel(newValue, speedMax);
699
+ // Anti-echo filter: if this value matches what was just synced from HA, ignore
700
+ const synced = this.lastSyncedFan.get(entityId);
701
+ if (synced) {
702
+ if (next === 0 && !synced.on)
703
+ return;
704
+ if (synced.on && withinHysteresis(next, synced.pct))
705
+ return;
706
+ }
707
+ this.platform.log.debug(`[Composite][${entityId}] FanControl.percentSetting changed: ${newValue}% -> snapped ${next}% (currentOn=${currentOn}, currentPct=${currentPct}%)`);
708
+ if (next === 0) {
709
+ if (!currentOn)
710
+ return;
711
+ this.setCommandLockout(entityId, "fan_state", "off");
712
+ await this.platform.ha.callService("fan", "turn_off", entityId);
713
+ }
714
+ else {
715
+ if (currentOn && withinHysteresis(next, currentPct))
716
+ return;
717
+ this.setCommandLockout(entityId, "fan_percentage", next);
718
+ this.setCommandLockout(entityId, "fan_state", "on");
719
+ await this.platform.ha.callService("fan", "set_percentage", entityId, { percentage: next });
720
+ }
721
+ }
722
+ });
723
+ if (endpoint.hasAttributeServer(FanControl.id, "fanMode")) {
724
+ endpoint.subscribeAttribute(FanControl.id, "fanMode", async (newMode) => {
725
+ if (this.isUpdatingFromHa(entityId))
726
+ return;
727
+ if (typeof newMode === "number") {
728
+ this.platform.log.debug(`[Composite][${entityId}] FanControl.fanMode changed: ${newMode}`);
729
+ if (newMode === FanControl.FanMode.Auto) {
730
+ const currentState = this.states.get(entityId);
731
+ if (currentState && hasFanAuto(currentState)) {
732
+ await this.platform.ha.callService("fan", "set_preset_mode", entityId, { preset_mode: "auto" });
733
+ }
734
+ }
735
+ }
736
+ });
737
+ }
738
+ }
739
+ if (endpoint.hasAttributeServer(FanControl.id, "airflowDirection")) {
740
+ endpoint.addCommandHandler("FanControl.changeDirection", async (data) => {
741
+ this.assertMemberOnline(entityId, member);
742
+ const mattDir = data?.request?.airflowDirection ??
743
+ data?.airflowDirection ??
744
+ FanControl.AirflowDirection.Forward;
745
+ const haDir = matterDirectionToHa(mattDir);
746
+ this.setCommandLockout(entityId, "fan_direction", haDir);
747
+ this.platform.log.debug(`[Composite][${entityId}] FanControl direction → HA: ${haDir}`);
748
+ await this.platform.ha.callService("fan", "set_direction", entityId, { direction: haDir });
749
+ });
750
+ }
751
+ return;
752
+ }
753
+ if (domain === "lock") {
754
+ endpoint.addCommandHandler("lockDoor", async () => {
755
+ this.assertMemberOnline(entityId, member);
756
+ await this.platform.ha.callService("lock", "lock", entityId);
757
+ });
758
+ endpoint.addCommandHandler("unlockDoor", async () => {
759
+ this.assertMemberOnline(entityId, member);
760
+ await this.platform.ha.callService("lock", "unlock", entityId);
761
+ });
762
+ return;
763
+ }
764
+ if (domain === "light") {
765
+ const sendColor = async (payload) => {
766
+ this.assertMemberOnline(entityId, member);
767
+ if (payload.hs_color)
768
+ this.setCommandLockout(entityId, "hs_color", payload.hs_color);
769
+ if (payload.xy_color)
770
+ this.setCommandLockout(entityId, "xy_color", payload.xy_color);
771
+ if (payload.color_temp)
772
+ this.setCommandLockout(entityId, "color_temp", payload.color_temp);
773
+ await this.platform.ha.callService("light", "turn_on", entityId, payload);
774
+ };
775
+ const currentHs = () => lightColor.getHsColor(this.states.get(entityId)) ?? [0, 100];
776
+ endpoint.addCommandHandler("on", async () => {
777
+ this.assertMemberOnline(entityId, member);
778
+ this.setCommandLockout(entityId, "onOff", true);
779
+ this.cancelDebouncedService(entityId, "light", "turn_off");
780
+ this.callServiceDebounced(entityId, "light", "turn_on", undefined, 0);
781
+ });
782
+ endpoint.addCommandHandler("off", async () => {
783
+ this.assertMemberOnline(entityId, member);
784
+ this.setCommandLockout(entityId, "onOff", false);
785
+ this.cancelDebouncedService(entityId, "light", "turn_on");
786
+ this.callServiceDebounced(entityId, "light", "turn_off", undefined, 0);
787
+ });
788
+ if (endpoint.hasAttributeServer(LevelControl.id, "currentLevel")) {
789
+ endpoint.addCommandHandler("moveToLevel", async (data) => {
790
+ this.assertMemberOnline(entityId, member);
791
+ const level = data?.level ?? data?.request?.level;
792
+ if (typeof level === "number") {
793
+ const haBrightness = lightConverter.toHaBrightness(level);
794
+ this.setCommandLockout(entityId, "brightness", haBrightness);
795
+ this.callServiceDebounced(entityId, "light", "turn_on", { brightness: haBrightness }, 0);
796
+ }
797
+ });
798
+ endpoint.addCommandHandler("moveToLevelWithOnOff", async (data) => {
799
+ this.assertMemberOnline(entityId, member);
800
+ const level = data?.level ?? data?.request?.level;
801
+ if (typeof level === "number") {
802
+ if (level === 0) {
803
+ this.setCommandLockout(entityId, "onOff", false);
804
+ this.cancelDebouncedService(entityId, "light", "turn_on");
805
+ this.callServiceDebounced(entityId, "light", "turn_off", undefined, 0);
806
+ }
807
+ else if (level === 1) {
808
+ // Apple Home dimming to off sends level 1 before off. Debounce by 60ms so off can cancel it.
809
+ this.setCommandLockout(entityId, "brightness", 1);
810
+ this.callServiceDebounced(entityId, "light", "turn_on", { brightness: 1 }, 60);
811
+ }
812
+ else {
813
+ const haBrightness = lightConverter.toHaBrightness(level);
814
+ this.setCommandLockout(entityId, "brightness", haBrightness);
815
+ this.callServiceDebounced(entityId, "light", "turn_on", { brightness: haBrightness }, 0);
816
+ }
817
+ }
818
+ });
819
+ }
820
+ if (endpoint.hasAttributeServer(ColorControl.id, "colorMode")) {
821
+ endpoint.addCommandHandler("moveToColorTemperature", async (data) => {
822
+ const rawMireds = data?.colorTemperatureMireds ??
823
+ data?.request?.colorTemperatureMireds;
824
+ if (typeof rawMireds === "number" && rawMireds > 0) {
825
+ const state = this.states.get(entityId);
826
+ const minPhys = endpoint.state?.colorControl
827
+ ?.colorTempPhysicalMinMireds;
828
+ const maxPhys = endpoint.state?.colorControl
829
+ ?.colorTempPhysicalMaxMireds;
830
+ const mireds = lightColor.clampMireds(rawMireds, state.attributes, { minMireds: minPhys, maxMireds: maxPhys });
831
+ const payload = lightColor.buildColorPayload(state.attributes.supported_color_modes ?? [], state.attributes.color_mode, { mireds });
832
+ const usesKelvin = state.attributes.color_temp_kelvin !== undefined ||
833
+ state.attributes.min_color_temp_kelvin !== undefined ||
834
+ state.attributes.max_color_temp_kelvin !== undefined;
835
+ if (usesKelvin) {
836
+ const kelvin = lightColor.clampKelvin(lightColor.miredsToKelvin(mireds), state.attributes);
837
+ this.setCommandLockout(entityId, "color_temp", mireds);
838
+ await this.platform.ha.callService("light", "turn_on", entityId, { color_temp_kelvin: kelvin });
839
+ }
840
+ else {
841
+ await sendColor(payload);
842
+ }
843
+ }
844
+ });
845
+ endpoint.addCommandHandler("moveToHueAndSaturation", async (data) => {
846
+ const req = data?.request ?? data;
847
+ if (typeof req?.hue === "number" &&
848
+ typeof req?.saturation === "number") {
849
+ const state = this.states.get(entityId);
850
+ const hs = [
851
+ lightColor.matterHueToHa(req.hue),
852
+ lightColor.matterSatToHa(req.saturation),
853
+ ];
854
+ const payload = lightColor.buildColorPayload(state.attributes.supported_color_modes ?? [], state.attributes.color_mode, { hs });
855
+ await sendColor(payload);
856
+ }
857
+ });
858
+ endpoint.addCommandHandler("moveToHue", async (data) => {
859
+ const req = data?.request ?? data;
860
+ if (typeof req?.hue === "number") {
861
+ const state = this.states.get(entityId);
862
+ const [, sat] = currentHs();
863
+ const hs = [
864
+ lightColor.matterHueToHa(req.hue),
865
+ sat,
866
+ ];
867
+ const payload = lightColor.buildColorPayload(state.attributes.supported_color_modes ?? [], state.attributes.color_mode, { hs });
868
+ await sendColor(payload);
869
+ }
870
+ });
871
+ endpoint.addCommandHandler("stepHue", async (data) => {
872
+ const req = data?.request ?? data;
873
+ if (typeof req?.stepSize === "number") {
874
+ const state = this.states.get(entityId);
875
+ const [hue, sat] = currentHs();
876
+ const sign = req.stepMode === 1 ? -1 : 1;
877
+ const newHue = lightColor.normalizeHue(hue + sign * lightColor.matterHueToHa(req.stepSize));
878
+ const hs = [newHue, sat];
879
+ const payload = lightColor.buildColorPayload(state.attributes.supported_color_modes ?? [], state.attributes.color_mode, { hs });
880
+ await sendColor(payload);
881
+ }
882
+ });
883
+ endpoint.addCommandHandler("enhancedMoveToHue", async (data) => {
884
+ const req = data?.request ?? data;
885
+ if (typeof req?.enhancedHue === "number") {
886
+ const state = this.states.get(entityId);
887
+ const [, sat] = currentHs();
888
+ const hs = [
889
+ lightColor.matterEnhancedHueToHa(req.enhancedHue),
890
+ sat,
891
+ ];
892
+ const payload = lightColor.buildColorPayload(state.attributes.supported_color_modes ?? [], state.attributes.color_mode, { hs });
893
+ await sendColor(payload);
894
+ }
895
+ });
896
+ endpoint.addCommandHandler("enhancedStepHue", async (data) => {
897
+ const req = data?.request ?? data;
898
+ if (typeof req?.stepSize === "number") {
899
+ const state = this.states.get(entityId);
900
+ const [hue, sat] = currentHs();
901
+ const sign = req.stepMode === 1 ? -1 : 1;
902
+ const newHue = lightColor.normalizeHue(hue + sign * lightColor.matterEnhancedHueToHa(req.stepSize));
903
+ const hs = [newHue, sat];
904
+ const payload = lightColor.buildColorPayload(state.attributes.supported_color_modes ?? [], state.attributes.color_mode, { hs });
905
+ await sendColor(payload);
906
+ }
907
+ });
908
+ endpoint.addCommandHandler("moveToSaturation", async (data) => {
909
+ const req = data?.request ?? data;
910
+ if (typeof req?.saturation === "number") {
911
+ const state = this.states.get(entityId);
912
+ const [hue] = currentHs();
913
+ const hs = [
914
+ hue,
915
+ lightColor.matterSatToHa(req.saturation),
916
+ ];
917
+ const payload = lightColor.buildColorPayload(state.attributes.supported_color_modes ?? [], state.attributes.color_mode, { hs });
918
+ await sendColor(payload);
919
+ }
920
+ });
921
+ endpoint.addCommandHandler("stepSaturation", async (data) => {
922
+ const req = data?.request ?? data;
923
+ if (typeof req?.stepSize === "number") {
924
+ const state = this.states.get(entityId);
925
+ const [hue, sat] = currentHs();
926
+ const sign = req.stepMode === 1 ? -1 : 1;
927
+ const newSat = Math.max(0, Math.min(100, sat + sign * lightColor.matterSatToHa(req.stepSize)));
928
+ const hs = [hue, newSat];
929
+ const payload = lightColor.buildColorPayload(state.attributes.supported_color_modes ?? [], state.attributes.color_mode, { hs });
930
+ await sendColor(payload);
931
+ }
932
+ });
933
+ endpoint.addCommandHandler("moveToColor", async (data) => {
934
+ const req = data?.request ?? data;
935
+ if (typeof req?.colorX === "number" &&
936
+ typeof req?.colorY === "number") {
937
+ const state = this.states.get(entityId);
938
+ const xy = lightColor.matterXyToHa(req.colorX, req.colorY);
939
+ const payload = lightColor.buildColorPayload(state.attributes.supported_color_modes ?? [], state.attributes.color_mode, { xy });
940
+ await sendColor(payload);
941
+ }
942
+ });
943
+ }
944
+ return;
945
+ }
946
+ if (domain === "switch") {
947
+ endpoint.addCommandHandler("on", async () => {
948
+ await this.platform.ha.callService("switch", "turn_on", entityId);
949
+ });
950
+ endpoint.addCommandHandler("off", async () => {
951
+ await this.platform.ha.callService("switch", "turn_off", entityId);
952
+ });
953
+ }
954
+ }
955
+ toLockState(state) {
956
+ return ["locked", "locking"].includes(state.state)
957
+ ? DoorLock.LockState.Locked
958
+ : DoorLock.LockState.Unlocked;
959
+ }
960
+ logLightCapabilities(member, memberType, clusterIds, primaryId) {
961
+ const modes = member.state.attributes.supported_color_modes ?? [];
962
+ const hasBrightness = modes.includes("brightness") ||
963
+ member.state.attributes.brightness !== undefined;
964
+ const hasColorTemp = modes.includes("color_temp") ||
965
+ member.state.attributes.color_temp !== undefined ||
966
+ member.state.attributes.color_temp_kelvin !== undefined;
967
+ const hasRgb = modes.some((m) => ["hs", "xy", "rgb", "rgbw", "rgbww"].includes(m));
968
+ const clusterNames = [
969
+ "OnOff",
970
+ ...(clusterIds.includes(LevelControl.id) ? ["LevelControl"] : []),
971
+ ...(clusterIds.includes(ColorControl.id) ? ["ColorControl"] : []),
972
+ ];
973
+ this.platform.log.notice(`[Composite] Detected HA light capabilities for ${member.entityId}:`);
974
+ this.platform.log.notice(`[Composite] supported_color_modes=${JSON.stringify(modes)}`);
975
+ this.platform.log.notice(`[Composite] brightness=${hasBrightness}, color_temp=${hasColorTemp}, rgb/hs/xy=${hasRgb}`);
976
+ this.platform.log.notice(`[Composite] Selected Matter type: ${memberType.name}`);
977
+ this.platform.log.notice(`[Composite] Clusters: ${clusterNames.join(", ")}`);
978
+ const minK = member.state.attributes.min_color_temp_kelvin;
979
+ const maxK = member.state.attributes.max_color_temp_kelvin;
980
+ if (minK || maxK) {
981
+ this.platform.log.notice(`[Composite] Color temp range: ${minK ?? "?"}K–${maxK ?? "?"}K (${minK ? lightColor.kelvinToMireds(minK) : "?"}–${maxK ? lightColor.kelvinToMireds(maxK) : "?"} mireds)`);
982
+ }
983
+ this.platform.log.notice(`[Composite] Integrated into composite node: ${primaryId}`);
984
+ }
985
+ }
986
+ //# sourceMappingURL=composite-device.entity.js.map