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,826 @@
1
+ /**
2
+ * Base entity class for exposing Home Assistant entities to Matter.
3
+ */
4
+ import { MatterbridgeEndpoint } from "matterbridge";
5
+ import { OnOff, LevelControl, ColorControl, FanControl, OccupancySensing, BooleanState, TemperatureMeasurement, RelativeHumidityMeasurement, } from "matterbridge/matter/clusters";
6
+ import { MatterbridgeOnOffServer, MatterbridgeFanControlServer, } from "matterbridge/behaviors";
7
+ import { BasicInformationServer, BridgedDeviceBasicInformationServer, } from "matterbridge/matter/behaviors";
8
+ import { isUnavailable } from "../utils/ha-state.js";
9
+ import { safeSetAttribute, safeUpdateAttribute, } from "../utils/matter-attributes.js";
10
+ import { hasColorTemperatureCapability } from "../device-registry.js";
11
+ import { getMatterSerialNumber, getHaDeviceModel, getHaDeviceManufacturer, MATTER_BRIDGE_VENDOR_ID, } from "../utils/matter-device-identity.js";
12
+ import { lightColor } from "../utils/light-color.js";
13
+ import { isFanOn, fanPercentage, fanDirection, haDirectionToMatter, matterDirectionToHa, haStateToFanMode, snapToPhysicalLevel, withinHysteresis, FAN_MODE_SEQUENCE, hasFanDirection, hasFanSpeed, hasFanAuto, getFanSpeedCount, getFanModeSequence, getFanControlFeatures, fanSpeed, } from "../converters/fan.converter.js";
14
+ import { lightConverter } from "../converters/light.converter.js";
15
+ export class BaseEntity {
16
+ platform;
17
+ entityId;
18
+ state;
19
+ binarySensorLatchTimeout;
20
+ lastCommands = new Map();
21
+ deviceType;
22
+ isDifferent(attribute, requested, actual) {
23
+ if (attribute === "hs_color") {
24
+ if (!requested || !actual)
25
+ return true;
26
+ return (Math.abs(requested[0] - actual[0]) > 3 ||
27
+ Math.abs(requested[1] - actual[1]) > 2);
28
+ }
29
+ if (attribute === "xy_color") {
30
+ if (!requested || !actual)
31
+ return true;
32
+ return (Math.abs(requested[0] - actual[0]) > 0.01 ||
33
+ Math.abs(requested[1] - actual[1]) > 0.01);
34
+ }
35
+ if (attribute === "brightness") {
36
+ return Math.abs(requested - actual) > 5;
37
+ }
38
+ if (attribute === "fan_percentage") {
39
+ return !withinHysteresis(requested, actual);
40
+ }
41
+ if (attribute === "color_temp") {
42
+ return Math.abs(requested - actual) > 10;
43
+ }
44
+ return requested !== actual;
45
+ }
46
+ shouldIgnoreStateUpdate(attribute, haValue, windowMs = 3000) {
47
+ const key = `${this.entityId}:${attribute}`;
48
+ const last = this.lastCommands.get(key);
49
+ if (!last)
50
+ return false;
51
+ const elapsed = Date.now() - last.timestamp;
52
+ if (elapsed > windowMs) {
53
+ this.lastCommands.delete(key);
54
+ return false;
55
+ }
56
+ if (this.isDifferent(attribute, last.value, haValue)) {
57
+ this.platform.log.debug(`[${this.entityId}] Reconciling HA feedback for ${attribute} (req=${JSON.stringify(last.value)}, got=${JSON.stringify(haValue)})`);
58
+ this.lastCommands.delete(key);
59
+ return false; // Force reconciliation
60
+ }
61
+ return true; // Ignore, within window and matches
62
+ }
63
+ setCommandLockout(attribute, value) {
64
+ this.lastCommands.set(`${this.entityId}:${attribute}`, {
65
+ value,
66
+ timestamp: Date.now(),
67
+ });
68
+ }
69
+ haUpdateDepth = 0;
70
+ lastSyncedFan = { on: false, pct: 0 };
71
+ /** True while HA-originated changes are being written into this endpoint. */
72
+ get isUpdatingFromHa() {
73
+ return this.haUpdateDepth > 0;
74
+ }
75
+ hasColorControl(endpoint = this.endpoint) {
76
+ const hasClusterServer = endpoint.hasClusterServer;
77
+ if (typeof hasClusterServer === "function") {
78
+ return hasClusterServer.call(endpoint, ColorControl);
79
+ }
80
+ const hasAttributeServer = endpoint.hasAttributeServer;
81
+ return (typeof hasAttributeServer === "function" &&
82
+ hasAttributeServer.call(endpoint, ColorControl.id, "colorMode"));
83
+ }
84
+ getMatterSerialNumber() {
85
+ return getMatterSerialNumber(this.platform, this.entityId);
86
+ }
87
+ endpoint;
88
+ applyMatterbridgeFirmware(endpoint = this.endpoint) {
89
+ const version = String(this.platform.matterbridge?.matterbridgeVersion ??
90
+ "Matterbridge");
91
+ const [major = 0, minor = 0, patch = 0] = version
92
+ .split(/[-+.]/)
93
+ .map((part) => Number.parseInt(part, 10) || 0);
94
+ endpoint.softwareVersion = Math.min(0xffffffff, major * 1_000_000 + minor * 1_000 + patch);
95
+ endpoint.softwareVersionString = version.startsWith("Matterbridge")
96
+ ? version
97
+ : `Matterbridge ${version}`;
98
+ }
99
+ constructor(platform, state, deviceType) {
100
+ this.platform = platform;
101
+ this.entityId = state.entity_id;
102
+ this.state = state;
103
+ this.deviceType = deviceType;
104
+ }
105
+ getRequiredClusterIds() {
106
+ const [domain] = this.entityId.split(".");
107
+ const clusters = [];
108
+ if (domain === "light" ||
109
+ domain === "switch" ||
110
+ domain === "media_player" ||
111
+ domain === "vacuum") {
112
+ const supportedModes = this.state.attributes.supported_color_modes ?? [];
113
+ const hasBrightness = supportedModes.includes("brightness") ||
114
+ this.state.attributes.brightness !== undefined;
115
+ const isOnOffProfile = this.deviceType.code === 0x0100 || this.deviceType.code === 0x010a;
116
+ const realColorModes = ["hs", "xy", "rgb", "rgbw", "rgbww", "color_temp"];
117
+ const hasColorCapability = supportedModes.some((m) => realColorModes.includes(m)) ||
118
+ hasColorTemperatureCapability(this.state.attributes);
119
+ const isColorProfile = this.deviceType.code === 0x010c || this.deviceType.code === 0x010d;
120
+ if ((hasBrightness || hasColorCapability) && !isOnOffProfile) {
121
+ clusters.push(LevelControl.id);
122
+ }
123
+ if (hasColorCapability && isColorProfile) {
124
+ clusters.push(ColorControl.id);
125
+ }
126
+ }
127
+ return clusters;
128
+ }
129
+ async createEndpoint() {
130
+ const rawName = this.state.attributes.friendly_name ?? this.entityId;
131
+ const uniqueName = rawName.substring(0, 32).trim();
132
+ this.endpoint = new MatterbridgeEndpoint([this.deviceType], {
133
+ id: this.entityId.replaceAll(".", "_"),
134
+ mode: "server",
135
+ });
136
+ const [domain] = this.entityId.split(".");
137
+ this.endpoint.deviceType = this.deviceType.code;
138
+ this.endpoint.deviceName = uniqueName;
139
+ this.endpoint.uniqueId = this.entityId.replaceAll(".", "_");
140
+ this.endpoint.serialNumber = this.getMatterSerialNumber();
141
+ this.endpoint.vendorId = MATTER_BRIDGE_VENDOR_ID;
142
+ this.endpoint.vendorName = getHaDeviceManufacturer(this.platform, this.entityId);
143
+ this.endpoint.productId = 0x8000;
144
+ this.endpoint.productName = getHaDeviceModel(this.platform, this.entityId, this.deviceType.name);
145
+ this.endpoint.createDefaultBasicInformationClusterServer(uniqueName, this.endpoint.serialNumber, MATTER_BRIDGE_VENDOR_ID, this.endpoint.vendorName, 0x8000, this.endpoint.productName);
146
+ this.applyMatterbridgeFirmware();
147
+ const isFanProfile = this.deviceType.code === 0x002b ||
148
+ this.deviceType.name.toLowerCase() === "fan";
149
+ const hasDirectionSupport = hasFanDirection(this.state);
150
+ const hasSpeedSupport = hasFanSpeed(this.state);
151
+ if (domain === "fan" && isFanProfile) {
152
+ const on = isFanOn(this.state);
153
+ const pct = fanPercentage(this.state);
154
+ const speedMax = getFanSpeedCount(this.state);
155
+ const speed = fanSpeed(pct, speedMax);
156
+ const fanMode = haStateToFanMode(this.state);
157
+ const fanFeatures = getFanControlFeatures(this.state);
158
+ const fanModeSequence = getFanModeSequence(this.state);
159
+ this.platform.log.debug(`[${this.entityId}] Fan init: state=${this.state.state}, on=${on}, pct=${pct}, speed=${speed}/${speedMax}, sequence=${fanModeSequence}, speedSupport=${hasSpeedSupport}, dir=${this.state.attributes.direction ?? "N/A"}`);
160
+ if (hasSpeedSupport) {
161
+ const fanClusterBehavior = MatterbridgeFanControlServer.with(...fanFeatures);
162
+ const fanStateConfig = {
163
+ fanMode,
164
+ fanModeSequence,
165
+ percentSetting: pct,
166
+ percentCurrent: pct,
167
+ speedMax,
168
+ speedSetting: speed,
169
+ speedCurrent: speed,
170
+ };
171
+ if (hasDirectionSupport) {
172
+ fanStateConfig.airflowDirection = haDirectionToMatter(fanDirection(this.state));
173
+ }
174
+ this.endpoint.behaviors.require(fanClusterBehavior, fanStateConfig);
175
+ }
176
+ else {
177
+ // Pure On/Off fan (e.g. smart switch configured as fan) — use default FanControl server without MultiSpeed
178
+ this.endpoint.createDefaultFanControlClusterServer(fanMode, FAN_MODE_SEQUENCE);
179
+ }
180
+ }
181
+ else if (domain === "light" ||
182
+ domain === "switch" ||
183
+ domain === "media_player" ||
184
+ domain === "vacuum" ||
185
+ domain === "fan") {
186
+ const isLighting = domain === "light" ||
187
+ this.deviceType.name.toLowerCase().includes("light");
188
+ this.endpoint.behaviors.require(isLighting
189
+ ? MatterbridgeOnOffServer.with(OnOff.Feature.Lighting)
190
+ : MatterbridgeOnOffServer.with());
191
+ }
192
+ const clusters = this.getRequiredClusterIds();
193
+ if (clusters.length > 0) {
194
+ this.endpoint.addClusterServers(clusters);
195
+ }
196
+ this.endpoint.addRequiredClusterServers();
197
+ await this.addCustomClusterServers();
198
+ this.registerCommandHandlers();
199
+ return this.endpoint;
200
+ }
201
+ adoptEndpoint(endpoint) {
202
+ this.endpoint = endpoint;
203
+ if (endpoint.commandHandler &&
204
+ endpoint.commandHandler.handler?.length === 0) {
205
+ this.registerCommandHandlers(endpoint);
206
+ }
207
+ }
208
+ addCustomClusterServers() {
209
+ return;
210
+ }
211
+ serviceDebounceTimers = new Map();
212
+ cancelDebouncedService(service) {
213
+ const key = `${this.entityId}:${service}`;
214
+ const pending = this.serviceDebounceTimers.get(key);
215
+ if (pending) {
216
+ clearTimeout(pending);
217
+ this.serviceDebounceTimers.delete(key);
218
+ }
219
+ }
220
+ assertOnline() {
221
+ if (isUnavailable(this.state)) {
222
+ this.platform.log?.warn?.(`[${this.entityId}] Rejecting Matter command: device is unavailable/offline in Home Assistant.`);
223
+ throw new Error(`[${this.entityId}] Device is unavailable/offline`);
224
+ }
225
+ }
226
+ callServiceDebounced(domain, service, data, delayMs = 60) {
227
+ if (isUnavailable(this.state)) {
228
+ this.platform.log?.warn?.(`[${this.entityId}] Ignored debounced ${domain}.${service}: device is unavailable/offline in Home Assistant.`);
229
+ return;
230
+ }
231
+ if (service === "turn_on") {
232
+ this.cancelDebouncedService("turn_off");
233
+ }
234
+ else if (service === "turn_off") {
235
+ this.cancelDebouncedService("turn_on");
236
+ }
237
+ const key = `${this.entityId}:${service}`;
238
+ const existing = this.serviceDebounceTimers.get(key);
239
+ if (existing)
240
+ clearTimeout(existing);
241
+ if (delayMs <= 0) {
242
+ this.serviceDebounceTimers.delete(key);
243
+ if (data !== undefined) {
244
+ void this.platform.ha.callService(domain, service, this.entityId, data);
245
+ }
246
+ else {
247
+ void this.platform.ha.callService(domain, service, this.entityId);
248
+ }
249
+ return;
250
+ }
251
+ const timer = setTimeout(() => {
252
+ this.serviceDebounceTimers.delete(key);
253
+ if (isUnavailable(this.state)) {
254
+ this.platform.log?.warn?.(`[${this.entityId}] Ignored delayed ${domain}.${service}: device transitioned to unavailable.`);
255
+ return;
256
+ }
257
+ if (data !== undefined) {
258
+ void this.platform.ha.callService(domain, service, this.entityId, data);
259
+ }
260
+ else {
261
+ void this.platform.ha.callService(domain, service, this.entityId);
262
+ }
263
+ }, delayMs);
264
+ this.serviceDebounceTimers.set(key, timer);
265
+ }
266
+ registerCommandHandlers(_endpoint) {
267
+ const [domain] = this.entityId.split(".");
268
+ if (domain === "light" ||
269
+ domain === "switch" ||
270
+ domain === "fan" ||
271
+ domain === "media_player" ||
272
+ domain === "vacuum") {
273
+ this.endpoint.addCommandHandler("on", async () => {
274
+ this.assertOnline();
275
+ if (domain === "vacuum")
276
+ await this.platform.ha.callService(domain, "start", this.entityId);
277
+ else if (domain === "light") {
278
+ this.setCommandLockout("onOff", true);
279
+ this.cancelDebouncedService("turn_off");
280
+ this.callServiceDebounced(domain, "turn_on", undefined, 0);
281
+ }
282
+ else if (domain === "fan") {
283
+ if (isFanOn(this.state))
284
+ return;
285
+ this.setCommandLockout("fan_state", "on");
286
+ await this.platform.ha.callService(domain, "turn_on", this.entityId);
287
+ }
288
+ else
289
+ await this.platform.ha.callService(domain, "turn_on", this.entityId);
290
+ });
291
+ this.endpoint.addCommandHandler("off", async () => {
292
+ this.assertOnline();
293
+ if (domain === "vacuum")
294
+ await this.platform.ha.callService(domain, "return_to_base", this.entityId);
295
+ else if (domain === "light") {
296
+ this.setCommandLockout("onOff", false);
297
+ this.cancelDebouncedService("turn_on");
298
+ this.callServiceDebounced(domain, "turn_off", undefined, 0);
299
+ }
300
+ else if (domain === "fan") {
301
+ if (!isFanOn(this.state))
302
+ return;
303
+ this.setCommandLockout("fan_state", "off");
304
+ await this.platform.ha.callService(domain, "turn_off", this.entityId);
305
+ }
306
+ else
307
+ await this.platform.ha.callService(domain, "turn_off", this.entityId);
308
+ });
309
+ if (domain === "fan" &&
310
+ hasFanSpeed(this.state) &&
311
+ this.endpoint.hasAttributeServer(FanControl.id, "percentCurrent")) {
312
+ // ── Fan speed (percentage) handler ───────────────────────────────────
313
+ this.endpoint.addCommandHandler("FanControl.step", async (data) => {
314
+ this.assertOnline();
315
+ if (this.isUpdatingFromHa)
316
+ return;
317
+ if (!hasFanSpeed(this.state))
318
+ return;
319
+ const direction = data?.request?.direction ?? data?.direction;
320
+ const current = isFanOn(this.state) ? fanPercentage(this.state) : 0;
321
+ const speedMax = getFanSpeedCount(this.state);
322
+ const delta = direction === FanControl.StepDirection.Increase ? 10 : -10;
323
+ const next = snapToPhysicalLevel(Math.max(0, Math.min(100, current + delta)), speedMax);
324
+ this.platform.log.debug(`[${this.entityId}] FanControl.step: dir=${direction}, current=${current}%, next=${next}%`);
325
+ if (next === 0) {
326
+ if (!isFanOn(this.state))
327
+ return;
328
+ this.setCommandLockout("fan_state", "off");
329
+ await this.platform.ha.callService("fan", "turn_off", this.entityId);
330
+ }
331
+ else {
332
+ if (isFanOn(this.state) && withinHysteresis(next, current))
333
+ return;
334
+ this.setCommandLockout("fan_percentage", next);
335
+ this.setCommandLockout("fan_state", "on");
336
+ await this.platform.ha.callService("fan", "set_percentage", this.entityId, { percentage: next });
337
+ }
338
+ });
339
+ this.endpoint.subscribeAttribute(FanControl.id, "percentSetting", async (newValue) => {
340
+ if (this.isUpdatingFromHa)
341
+ return;
342
+ if (!hasFanSpeed(this.state))
343
+ return;
344
+ if (typeof newValue === "number") {
345
+ const currentOn = isFanOn(this.state);
346
+ const currentPct = currentOn ? fanPercentage(this.state) : 0;
347
+ const speedMax = getFanSpeedCount(this.state);
348
+ const next = snapToPhysicalLevel(newValue, speedMax);
349
+ // Anti-echo filter: if this matches what was just synced from HA, ignore
350
+ if (next === 0 && !this.lastSyncedFan.on)
351
+ return;
352
+ if (this.lastSyncedFan.on && withinHysteresis(next, this.lastSyncedFan.pct))
353
+ return;
354
+ this.platform.log.debug(`[${this.entityId}] FanControl.percentSetting changed: ${newValue}% -> snapped ${next}% (currentOn=${currentOn}, currentPct=${currentPct}%)`);
355
+ if (next === 0) {
356
+ if (!currentOn)
357
+ return;
358
+ this.setCommandLockout("fan_state", "off");
359
+ await this.platform.ha.callService("fan", "turn_off", this.entityId);
360
+ }
361
+ else {
362
+ if (currentOn && withinHysteresis(next, currentPct))
363
+ return;
364
+ this.setCommandLockout("fan_percentage", next);
365
+ this.setCommandLockout("fan_state", "on");
366
+ await this.platform.ha.callService("fan", "set_percentage", this.entityId, { percentage: next });
367
+ }
368
+ }
369
+ });
370
+ if (this.endpoint.hasAttributeServer(FanControl.id, "fanMode")) {
371
+ this.endpoint.subscribeAttribute(FanControl.id, "fanMode", async (newMode) => {
372
+ if (this.isUpdatingFromHa)
373
+ return;
374
+ if (typeof newMode === "number") {
375
+ this.platform.log.debug(`[${this.entityId}] FanControl.fanMode changed: ${newMode}`);
376
+ if (newMode === FanControl.FanMode.Auto && hasFanAuto(this.state)) {
377
+ await this.platform.ha.callService("fan", "set_preset_mode", this.entityId, { preset_mode: "auto" });
378
+ }
379
+ }
380
+ });
381
+ }
382
+ }
383
+ // ── Fan direction handler ────────────────────────────────────────────
384
+ if (domain === "fan" &&
385
+ this.endpoint.hasAttributeServer(FanControl.id, "airflowDirection")) {
386
+ this.endpoint.addCommandHandler("FanControl.changeDirection", async (data) => {
387
+ this.assertOnline();
388
+ const mattDir = data?.request?.airflowDirection ??
389
+ data?.airflowDirection ??
390
+ FanControl.AirflowDirection.Forward;
391
+ const haDir = matterDirectionToHa(mattDir);
392
+ this.setCommandLockout("fan_direction", haDir);
393
+ this.platform.log.debug(`[${this.entityId}] FanControl direction → HA: ${haDir}`);
394
+ await this.platform.ha.callService("fan", "set_direction", this.entityId, { direction: haDir });
395
+ });
396
+ }
397
+ if (this.endpoint.hasAttributeServer(LevelControl.id, "currentLevel")) {
398
+ this.endpoint.addCommandHandler("moveToLevel", async (data) => {
399
+ this.assertOnline();
400
+ const level = data?.request?.level ?? data?.level;
401
+ if (typeof level === "number") {
402
+ const haBrightness = lightConverter.toHaBrightness(level);
403
+ this.setCommandLockout("brightness", haBrightness);
404
+ this.callServiceDebounced(domain, "turn_on", { brightness: haBrightness }, 0);
405
+ }
406
+ });
407
+ this.endpoint.addCommandHandler("moveToLevelWithOnOff", async (data) => {
408
+ this.assertOnline();
409
+ const level = data?.request?.level ?? data?.level;
410
+ if (typeof level === "number") {
411
+ if (level === 0) {
412
+ this.setCommandLockout("onOff", false);
413
+ this.cancelDebouncedService("turn_on");
414
+ this.callServiceDebounced(domain, "turn_off", undefined, 0);
415
+ }
416
+ else if (level === 1) {
417
+ // Apple Home dimming to off sends level 1 before off. Debounce by 60ms so off can cancel it.
418
+ this.setCommandLockout("brightness", 1);
419
+ this.callServiceDebounced(domain, "turn_on", { brightness: 1 }, 60);
420
+ }
421
+ else {
422
+ const haBrightness = lightConverter.toHaBrightness(level);
423
+ this.setCommandLockout("brightness", haBrightness);
424
+ this.callServiceDebounced(domain, "turn_on", { brightness: haBrightness }, 0);
425
+ }
426
+ }
427
+ });
428
+ }
429
+ if (domain === "light" && this.hasColorControl(this.endpoint)) {
430
+ const sendColor = async (payload) => {
431
+ this.assertOnline();
432
+ if (payload.hs_color)
433
+ this.setCommandLockout("hs_color", payload.hs_color);
434
+ if (payload.xy_color)
435
+ this.setCommandLockout("xy_color", payload.xy_color);
436
+ if (payload.color_temp)
437
+ this.setCommandLockout("color_temp", payload.color_temp);
438
+ await this.platform.ha.callService("light", "turn_on", this.entityId, payload);
439
+ };
440
+ const currentHs = () => lightColor.getHsColor(this.state) ?? [0, 100];
441
+ this.endpoint.addCommandHandler("moveToHueAndSaturation", async (data) => {
442
+ const req = data?.request ?? data;
443
+ if (typeof req?.hue === "number" &&
444
+ typeof req?.saturation === "number") {
445
+ const hs = [
446
+ lightColor.matterHueToHa(req.hue),
447
+ lightColor.matterSatToHa(req.saturation),
448
+ ];
449
+ const payload = lightColor.buildColorPayload(this.state.attributes.supported_color_modes ?? [], this.state.attributes.color_mode, { hs });
450
+ await sendColor(payload);
451
+ }
452
+ });
453
+ this.endpoint.addCommandHandler("moveToHue", async (data) => {
454
+ const req = data?.request ?? data;
455
+ if (typeof req?.hue === "number") {
456
+ const [, sat] = currentHs();
457
+ const hs = [
458
+ lightColor.matterHueToHa(req.hue),
459
+ sat,
460
+ ];
461
+ const payload = lightColor.buildColorPayload(this.state.attributes.supported_color_modes ?? [], this.state.attributes.color_mode, { hs });
462
+ await sendColor(payload);
463
+ }
464
+ });
465
+ this.endpoint.addCommandHandler("stepHue", async (data) => {
466
+ const req = data?.request ?? data;
467
+ if (typeof req?.stepSize === "number") {
468
+ const [hue, sat] = currentHs();
469
+ const sign = req.stepMode === 1 ? -1 : 1; // 1 = down, 0 = up per cluster spec usually, wait 3.10.4 spec 1 is down
470
+ const newHue = lightColor.normalizeHue(hue + sign * lightColor.matterHueToHa(req.stepSize));
471
+ const hs = [newHue, sat];
472
+ const payload = lightColor.buildColorPayload(this.state.attributes.supported_color_modes ?? [], this.state.attributes.color_mode, { hs });
473
+ await sendColor(payload);
474
+ }
475
+ });
476
+ this.endpoint.addCommandHandler("enhancedMoveToHue", async (data) => {
477
+ const req = data?.request ?? data;
478
+ if (typeof req?.enhancedHue === "number") {
479
+ const [, sat] = currentHs();
480
+ const hs = [
481
+ lightColor.matterEnhancedHueToHa(req.enhancedHue),
482
+ sat,
483
+ ];
484
+ const payload = lightColor.buildColorPayload(this.state.attributes.supported_color_modes ?? [], this.state.attributes.color_mode, { hs });
485
+ await sendColor(payload);
486
+ }
487
+ });
488
+ this.endpoint.addCommandHandler("enhancedMoveHue", async (data) => {
489
+ // Handled same as moveHue if direction provided, usually controller doesn't send move without stop
490
+ });
491
+ this.endpoint.addCommandHandler("enhancedStepHue", async (data) => {
492
+ const req = data?.request ?? data;
493
+ if (typeof req?.stepSize === "number") {
494
+ const [hue, sat] = currentHs();
495
+ const sign = req.stepMode === 1 ? -1 : 1;
496
+ const newHue = lightColor.normalizeHue(hue + sign * lightColor.matterEnhancedHueToHa(req.stepSize));
497
+ const hs = [newHue, sat];
498
+ const payload = lightColor.buildColorPayload(this.state.attributes.supported_color_modes ?? [], this.state.attributes.color_mode, { hs });
499
+ await sendColor(payload);
500
+ }
501
+ });
502
+ this.endpoint.addCommandHandler("moveToSaturation", async (data) => {
503
+ const req = data?.request ?? data;
504
+ if (typeof req?.saturation === "number") {
505
+ const [hue] = currentHs();
506
+ const hs = [
507
+ hue,
508
+ lightColor.matterSatToHa(req.saturation),
509
+ ];
510
+ const payload = lightColor.buildColorPayload(this.state.attributes.supported_color_modes ?? [], this.state.attributes.color_mode, { hs });
511
+ await sendColor(payload);
512
+ }
513
+ });
514
+ this.endpoint.addCommandHandler("stepSaturation", async (data) => {
515
+ const req = data?.request ?? data;
516
+ if (typeof req?.stepSize === "number") {
517
+ const [hue, sat] = currentHs();
518
+ const sign = req.stepMode === 1 ? -1 : 1;
519
+ const newSat = Math.max(0, Math.min(100, sat + sign * lightColor.matterSatToHa(req.stepSize)));
520
+ const hs = [hue, newSat];
521
+ const payload = lightColor.buildColorPayload(this.state.attributes.supported_color_modes ?? [], this.state.attributes.color_mode, { hs });
522
+ await sendColor(payload);
523
+ }
524
+ });
525
+ this.endpoint.addCommandHandler("moveToColor", async (data) => {
526
+ const req = data?.request ?? data;
527
+ if (typeof req?.colorX === "number" &&
528
+ typeof req?.colorY === "number") {
529
+ const xy = lightColor.matterXyToHa(req.colorX, req.colorY);
530
+ const payload = lightColor.buildColorPayload(this.state.attributes.supported_color_modes ?? [], this.state.attributes.color_mode, { xy });
531
+ await sendColor(payload);
532
+ }
533
+ });
534
+ this.endpoint.addCommandHandler("moveToColorTemperature", async (data) => {
535
+ const req = data?.request ?? data;
536
+ if (typeof req?.colorTemperatureMireds === "number" &&
537
+ req.colorTemperatureMireds > 0) {
538
+ const rawMireds = req.colorTemperatureMireds;
539
+ const mireds = lightColor.clampMireds(rawMireds, this.state.attributes);
540
+ const payload = lightColor.buildColorPayload(this.state.attributes.supported_color_modes ?? [], this.state.attributes.color_mode, { mireds });
541
+ const usesKelvin = this.state.attributes.color_temp_kelvin !== undefined ||
542
+ this.state.attributes.min_color_temp_kelvin !== undefined ||
543
+ this.state.attributes.max_color_temp_kelvin !== undefined;
544
+ if (usesKelvin) {
545
+ const kelvin = lightColor.clampKelvin(lightColor.miredsToKelvin(mireds), this.state.attributes);
546
+ this.setCommandLockout("color_temp", mireds);
547
+ await this.platform.ha.callService("light", "turn_on", this.entityId, { color_temp_kelvin: kelvin });
548
+ }
549
+ else {
550
+ await sendColor(payload);
551
+ }
552
+ }
553
+ });
554
+ }
555
+ }
556
+ }
557
+ async syncInitialState() {
558
+ await this.updateState(this.state, true);
559
+ }
560
+ clampLevel(rawLevel, isInitialSync = false) {
561
+ if (isInitialSync)
562
+ return Math.min(254, Math.max(1, rawLevel));
563
+ try {
564
+ const minLevel = this.endpoint.getAttribute?.(LevelControl.id, "minLevel") ?? 1;
565
+ const maxLevel = this.endpoint.getAttribute?.(LevelControl.id, "maxLevel") ??
566
+ 254;
567
+ const lo = Math.max(1, minLevel);
568
+ const hi = Math.min(254, maxLevel);
569
+ return Math.min(hi, Math.max(lo, rawLevel));
570
+ }
571
+ catch {
572
+ return Math.min(254, Math.max(1, rawLevel));
573
+ }
574
+ }
575
+ async setReachability(reachable) {
576
+ const ep = this.endpoint;
577
+ if (!ep)
578
+ return;
579
+ try {
580
+ // 1. ServerNode reachability (individual accessory in mode: 'server')
581
+ const serverNode = ep.serverNode;
582
+ if (serverNode && typeof serverNode.setStateOf === "function") {
583
+ await serverNode.setStateOf(BasicInformationServer, { reachable });
584
+ }
585
+ // 2. Bridged / child endpoint reachability
586
+ if (typeof ep.setStateOf === "function") {
587
+ try {
588
+ await ep.setStateOf(BridgedDeviceBasicInformationServer, { reachable });
589
+ }
590
+ catch { }
591
+ }
592
+ // 3. Update reachable attribute on cluster servers if present
593
+ if (typeof ep.setAttribute === "function") {
594
+ if (ep.hasAttributeServer?.(0x0028, "reachable")) {
595
+ await ep.setAttribute(0x0028, "reachable", reachable, this.platform.log);
596
+ }
597
+ if (ep.hasAttributeServer?.(0x0039, "reachable")) {
598
+ await ep.setAttribute(0x0039, "reachable", reachable, this.platform.log);
599
+ }
600
+ }
601
+ // 4. Actively emit Matter subscription updates to controllers (Apple Home)
602
+ if (typeof ep.updateAttribute === "function") {
603
+ if (ep.hasAttributeServer?.(0x0039, "reachable")) {
604
+ await ep.updateAttribute(0x0039, "reachable", reachable, this.platform.log);
605
+ }
606
+ if (ep.hasAttributeServer?.(0x0028, "reachable")) {
607
+ await ep.updateAttribute(0x0028, "reachable", reachable, this.platform.log);
608
+ }
609
+ }
610
+ this.platform.log?.debug?.(`[${this.entityId}] Updated Matter reachability to ${reachable}`);
611
+ }
612
+ catch (err) {
613
+ this.platform.log?.debug?.(`[${this.entityId}] Could not update reachability to ${reachable}: ${err}`);
614
+ }
615
+ }
616
+ async updateState(newState, isInitialSync = false) {
617
+ this.haUpdateDepth++;
618
+ try {
619
+ this.state = newState;
620
+ if (!this.endpoint)
621
+ return;
622
+ const [domain] = this.entityId.split(".");
623
+ const updateFn = isInitialSync ? safeSetAttribute : safeUpdateAttribute;
624
+ if (domain === "light" ||
625
+ domain === "switch" ||
626
+ domain === "fan" ||
627
+ domain === "media_player" ||
628
+ domain === "vacuum") {
629
+ const isOn = domain === "vacuum"
630
+ ? newState.state === "cleaning"
631
+ : domain === "fan"
632
+ ? isFanOn(newState)
633
+ : newState.state === "on";
634
+ const beforeLevel = this.endpoint?.hasAttributeServer?.(LevelControl.id, "currentLevel")
635
+ ? this.endpoint.getAttribute(LevelControl.id, "currentLevel")
636
+ : undefined;
637
+ const beforeOnOff = this.endpoint?.hasAttributeServer?.(OnOff.id, "onOff")
638
+ ? this.endpoint.getAttribute(OnOff.id, "onOff")
639
+ : undefined;
640
+ if (domain === "light" && isOn) {
641
+ if (newState.attributes.brightness !== undefined) {
642
+ if (!isInitialSync &&
643
+ this.shouldIgnoreStateUpdate("brightness", newState.attributes.brightness)) {
644
+ this.platform.log.debug(`[${this.entityId}] Ignoring HA brightness state update due to recent command lockout`);
645
+ }
646
+ else {
647
+ const raw = lightConverter.toLevel(newState.attributes.brightness);
648
+ const level = this.clampLevel(raw, isInitialSync);
649
+ await updateFn(this.endpoint, LevelControl.id, "currentLevel", level, this.platform.log);
650
+ }
651
+ }
652
+ if (this.hasColorControl()) {
653
+ const attrs = newState.attributes;
654
+ const colorMode = attrs.color_mode;
655
+ const range = lightColor.getMiredsRange(attrs);
656
+ await updateFn(this.endpoint, ColorControl.id, "colorTempPhysicalMinMireds", range.minMireds, this.platform.log);
657
+ await updateFn(this.endpoint, ColorControl.id, "colorTempPhysicalMaxMireds", range.maxMireds, this.platform.log);
658
+ await updateFn(this.endpoint, ColorControl.id, "coupleColorTempMinMireds", range.minMireds, this.platform.log);
659
+ await updateFn(this.endpoint, ColorControl.id, "coupleColorTempMaxMireds", range.maxMireds, this.platform.log);
660
+ const minPhys = this.endpoint.state?.colorControl
661
+ ?.colorTempPhysicalMinMireds ?? range.minMireds;
662
+ const maxPhys = this.endpoint.state?.colorControl
663
+ ?.colorTempPhysicalMaxMireds ?? range.maxMireds;
664
+ const rawMireds = attrs.color_temp ??
665
+ (attrs.color_temp_kelvin
666
+ ? lightColor.kelvinToMireds(attrs.color_temp_kelvin)
667
+ : undefined);
668
+ const mireds = rawMireds !== undefined
669
+ ? lightColor.clampMireds(rawMireds, attrs, {
670
+ minMireds: minPhys,
671
+ maxMireds: maxPhys,
672
+ })
673
+ : undefined;
674
+ const xy = Array.isArray(attrs.xy_color) && attrs.xy_color.length >= 2
675
+ ? attrs.xy_color
676
+ : undefined;
677
+ const hs = lightColor.getHsColor(newState);
678
+ if (mireds !== undefined &&
679
+ (colorMode === "color_temp" || (!hs && !xy))) {
680
+ if (!isInitialSync &&
681
+ this.shouldIgnoreStateUpdate("color_temp", mireds)) {
682
+ this.platform.log.debug(`[${this.entityId}] Ignoring HA color_temp state update due to recent command lockout`);
683
+ }
684
+ else {
685
+ await updateFn(this.endpoint, ColorControl.id, "colorTemperatureMireds", mireds, this.platform.log);
686
+ await updateFn(this.endpoint, ColorControl.id, "colorMode", ColorControl.ColorMode.ColorTemperatureMireds, this.platform.log);
687
+ }
688
+ }
689
+ else if (xy && (colorMode === "xy" || !hs)) {
690
+ if (!isInitialSync &&
691
+ this.shouldIgnoreStateUpdate("xy_color", xy)) {
692
+ this.platform.log.debug(`[${this.entityId}] Ignoring HA xy_color state update due to recent command lockout`);
693
+ }
694
+ else {
695
+ const matterXy = lightColor.haXyToMatter(xy[0], xy[1]);
696
+ await updateFn(this.endpoint, ColorControl.id, "currentX", matterXy[0], this.platform.log);
697
+ await updateFn(this.endpoint, ColorControl.id, "currentY", matterXy[1], this.platform.log);
698
+ await updateFn(this.endpoint, ColorControl.id, "colorMode", ColorControl.ColorMode.CurrentXAndCurrentY, this.platform.log);
699
+ }
700
+ }
701
+ else if (hs) {
702
+ if (!isInitialSync &&
703
+ this.shouldIgnoreStateUpdate("hs_color", hs)) {
704
+ this.platform.log.debug(`[${this.entityId}] Ignoring HA hs_color state update due to recent command lockout`);
705
+ }
706
+ else {
707
+ await updateFn(this.endpoint, ColorControl.id, "currentHue", lightColor.haHueToMatter(hs[0]), this.platform.log);
708
+ await updateFn(this.endpoint, ColorControl.id, "enhancedCurrentHue", lightColor.haHueToMatterEnhanced(hs[0]), this.platform.log);
709
+ await updateFn(this.endpoint, ColorControl.id, "currentSaturation", lightColor.haSatToMatter(hs[1]), this.platform.log);
710
+ await updateFn(this.endpoint, ColorControl.id, "colorMode", ColorControl.ColorMode.CurrentHueAndCurrentSaturation, this.platform.log);
711
+ if (this.endpoint.hasAttributeServer(ColorControl.id, "enhancedColorMode")) {
712
+ await updateFn(this.endpoint, ColorControl.id, "enhancedColorMode", ColorControl.EnhancedColorMode
713
+ .EnhancedCurrentHueAndCurrentSaturation, this.platform.log);
714
+ }
715
+ }
716
+ }
717
+ }
718
+ }
719
+ await updateFn(this.endpoint, OnOff.id, "onOff", isOn, this.platform.log);
720
+ if (domain === "light") {
721
+ const afterLevel = this.endpoint?.hasAttributeServer?.(LevelControl.id, "currentLevel")
722
+ ? this.endpoint.getAttribute(LevelControl.id, "currentLevel")
723
+ : undefined;
724
+ const afterOnOff = this.endpoint?.hasAttributeServer?.(OnOff.id, "onOff")
725
+ ? this.endpoint.getAttribute(OnOff.id, "onOff")
726
+ : undefined;
727
+ this.platform.log.debug(`[LIGHT TRACE][${this.entityId}] HA state: ${newState.state} | HA brightness: ${newState.attributes.brightness ?? "undefined"} | ` +
728
+ `Matter CurrentLevel before: ${beforeLevel} -> after: ${afterLevel} | ` +
729
+ `Matter OnOff before: ${beforeOnOff} -> after: ${afterOnOff} | ` +
730
+ `source: ${isInitialSync ? "initialSync" : "haEvent"} | transaction/handler: updateState`);
731
+ }
732
+ if (domain === "fan" &&
733
+ this.endpoint.hasAttributeServer(FanControl.id, "fanMode")) {
734
+ const speedSupported = hasFanSpeed(newState);
735
+ const speedMax = getFanSpeedCount(newState);
736
+ const pct = isOn ? fanPercentage(newState) : 0;
737
+ const speed = isOn ? fanSpeed(pct, speedMax) : 0;
738
+ const newFanMode = haStateToFanMode(newState);
739
+ this.lastSyncedFan = { on: isOn, pct };
740
+ this.platform.log.debug(`[${this.entityId}] Fan state update: state=${newState.state}, on=${isOn}, pct=${pct}, speed=${speed}, fanMode=${newFanMode}, speedSupported=${speedSupported}, direction=${newState.attributes.direction ?? "N/A"}, oscillating=${newState.attributes.oscillating ?? "N/A"}, preset=${newState.attributes.preset_mode ?? "N/A"}`);
741
+ if (speedSupported &&
742
+ this.endpoint.hasAttributeServer(FanControl.id, "percentCurrent")) {
743
+ // Percentage / speed update with hysteresis and lockout
744
+ if (!isInitialSync &&
745
+ this.shouldIgnoreStateUpdate("fan_percentage", pct)) {
746
+ this.platform.log.debug(`[${this.entityId}] Ignoring HA fan_percentage update due to command lockout (pct=${pct})`);
747
+ }
748
+ else {
749
+ await updateFn(this.endpoint, FanControl.id, "percentSetting", pct, this.platform.log);
750
+ await updateFn(this.endpoint, FanControl.id, "percentCurrent", pct, this.platform.log);
751
+ if (this.endpoint.hasAttributeServer(FanControl.id, "speedCurrent")) {
752
+ await updateFn(this.endpoint, FanControl.id, "speedSetting", speed, this.platform.log);
753
+ await updateFn(this.endpoint, FanControl.id, "speedCurrent", speed, this.platform.log);
754
+ }
755
+ }
756
+ }
757
+ // FanMode update
758
+ await updateFn(this.endpoint, FanControl.id, "fanMode", newFanMode, this.platform.log);
759
+ // AirflowDirection update (only when HA exposes direction)
760
+ if (this.endpoint.hasAttributeServer(FanControl.id, "airflowDirection")) {
761
+ const dir = fanDirection(newState);
762
+ if (dir !== undefined) {
763
+ if (!isInitialSync &&
764
+ this.shouldIgnoreStateUpdate("fan_direction", dir)) {
765
+ this.platform.log.debug(`[${this.entityId}] Ignoring HA direction update due to command lockout (dir=${dir})`);
766
+ }
767
+ else {
768
+ const matterDir = haDirectionToMatter(dir);
769
+ await updateFn(this.endpoint, FanControl.id, "airflowDirection", matterDir, this.platform.log);
770
+ this.platform.log.debug(`[${this.entityId}] Fan direction synced: HA=${dir} → Matter=${matterDir}`);
771
+ }
772
+ }
773
+ }
774
+ }
775
+ }
776
+ else if (domain === "binary_sensor") {
777
+ const active = ["on", "open", "detected", "true"].includes(newState.state.toLowerCase());
778
+ const updateMatter = async (isActive) => {
779
+ if (!this.endpoint)
780
+ return;
781
+ if (this.endpoint.hasAttributeServer(OccupancySensing.id, "occupancy")) {
782
+ await updateFn(this.endpoint, OccupancySensing.id, "occupancy", { occupied: isActive }, this.platform.log);
783
+ }
784
+ else if (this.endpoint.hasAttributeServer(BooleanState.id, "stateValue")) {
785
+ await updateFn(this.endpoint, BooleanState.id, "stateValue", isActive, this.platform.log);
786
+ }
787
+ };
788
+ if (active) {
789
+ if (this.binarySensorLatchTimeout) {
790
+ clearTimeout(this.binarySensorLatchTimeout);
791
+ this.binarySensorLatchTimeout = undefined;
792
+ }
793
+ await updateMatter(true);
794
+ }
795
+ else {
796
+ if (isInitialSync) {
797
+ await updateMatter(false);
798
+ }
799
+ else {
800
+ if (!this.binarySensorLatchTimeout) {
801
+ this.binarySensorLatchTimeout = setTimeout(async () => {
802
+ this.binarySensorLatchTimeout = undefined;
803
+ await updateMatter(false);
804
+ }, 3000);
805
+ }
806
+ }
807
+ }
808
+ }
809
+ else if (domain === "sensor") {
810
+ const numeric = parseFloat(newState.state);
811
+ if (!isNaN(numeric) && this.endpoint) {
812
+ if (this.endpoint.hasAttributeServer(TemperatureMeasurement.id, "measuredValue")) {
813
+ await updateFn(this.endpoint, TemperatureMeasurement.id, "measuredValue", Math.round(numeric * 100), this.platform.log);
814
+ }
815
+ else if (this.endpoint.hasAttributeServer(RelativeHumidityMeasurement.id, "measuredValue")) {
816
+ await updateFn(this.endpoint, RelativeHumidityMeasurement.id, "measuredValue", Math.round(numeric * 100), this.platform.log);
817
+ }
818
+ }
819
+ }
820
+ }
821
+ finally {
822
+ this.haUpdateDepth--;
823
+ }
824
+ }
825
+ }
826
+ //# sourceMappingURL=base.entity.js.map