@switchbot/homebridge-switchbot 5.0.0-beta.1 → 5.0.0-beta.10

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 (110) hide show
  1. package/dist/devices-matter/ColorLightAccessory.d.ts +3 -1
  2. package/dist/devices-matter/ColorLightAccessory.d.ts.map +1 -1
  3. package/dist/devices-matter/ColorLightAccessory.js +35 -36
  4. package/dist/devices-matter/ColorLightAccessory.js.map +1 -1
  5. package/dist/devices-matter/ColorTemperatureLightAccessory.d.ts +3 -1
  6. package/dist/devices-matter/ColorTemperatureLightAccessory.d.ts.map +1 -1
  7. package/dist/devices-matter/ColorTemperatureLightAccessory.js +32 -37
  8. package/dist/devices-matter/ColorTemperatureLightAccessory.js.map +1 -1
  9. package/dist/devices-matter/ContactSensorAccessory.d.ts +3 -1
  10. package/dist/devices-matter/ContactSensorAccessory.d.ts.map +1 -1
  11. package/dist/devices-matter/ContactSensorAccessory.js +16 -13
  12. package/dist/devices-matter/ContactSensorAccessory.js.map +1 -1
  13. package/dist/devices-matter/DimmableLightAccessory.d.ts +3 -1
  14. package/dist/devices-matter/DimmableLightAccessory.d.ts.map +1 -1
  15. package/dist/devices-matter/DimmableLightAccessory.js +24 -27
  16. package/dist/devices-matter/DimmableLightAccessory.js.map +1 -1
  17. package/dist/devices-matter/DoorLockAccessory.d.ts +3 -1
  18. package/dist/devices-matter/DoorLockAccessory.d.ts.map +1 -1
  19. package/dist/devices-matter/DoorLockAccessory.js +25 -22
  20. package/dist/devices-matter/DoorLockAccessory.js.map +1 -1
  21. package/dist/devices-matter/ExtendedColorLightAccessory.d.ts +3 -1
  22. package/dist/devices-matter/ExtendedColorLightAccessory.d.ts.map +1 -1
  23. package/dist/devices-matter/ExtendedColorLightAccessory.js +40 -41
  24. package/dist/devices-matter/ExtendedColorLightAccessory.js.map +1 -1
  25. package/dist/devices-matter/FanAccessory.d.ts +3 -1
  26. package/dist/devices-matter/FanAccessory.d.ts.map +1 -1
  27. package/dist/devices-matter/FanAccessory.js +31 -23
  28. package/dist/devices-matter/FanAccessory.js.map +1 -1
  29. package/dist/devices-matter/HumiditySensorAccessory.d.ts +3 -1
  30. package/dist/devices-matter/HumiditySensorAccessory.d.ts.map +1 -1
  31. package/dist/devices-matter/HumiditySensorAccessory.js +16 -15
  32. package/dist/devices-matter/HumiditySensorAccessory.js.map +1 -1
  33. package/dist/devices-matter/LeakSensorAccessory.d.ts +3 -1
  34. package/dist/devices-matter/LeakSensorAccessory.d.ts.map +1 -1
  35. package/dist/devices-matter/LeakSensorAccessory.js +16 -13
  36. package/dist/devices-matter/LeakSensorAccessory.js.map +1 -1
  37. package/dist/devices-matter/LightSensorAccessory.d.ts +3 -1
  38. package/dist/devices-matter/LightSensorAccessory.d.ts.map +1 -1
  39. package/dist/devices-matter/LightSensorAccessory.js +16 -15
  40. package/dist/devices-matter/LightSensorAccessory.js.map +1 -1
  41. package/dist/devices-matter/OccupancySensorAccessory.d.ts +3 -1
  42. package/dist/devices-matter/OccupancySensorAccessory.d.ts.map +1 -1
  43. package/dist/devices-matter/OccupancySensorAccessory.js +17 -21
  44. package/dist/devices-matter/OccupancySensorAccessory.js.map +1 -1
  45. package/dist/devices-matter/OnOffLightAccessory.d.ts +3 -1
  46. package/dist/devices-matter/OnOffLightAccessory.d.ts.map +1 -1
  47. package/dist/devices-matter/OnOffLightAccessory.js +22 -21
  48. package/dist/devices-matter/OnOffLightAccessory.js.map +1 -1
  49. package/dist/devices-matter/OnOffOutletAccessory.d.ts +3 -3
  50. package/dist/devices-matter/OnOffOutletAccessory.d.ts.map +1 -1
  51. package/dist/devices-matter/OnOffOutletAccessory.js +24 -27
  52. package/dist/devices-matter/OnOffOutletAccessory.js.map +1 -1
  53. package/dist/devices-matter/OnOffSwitchAccessory.d.ts +3 -1
  54. package/dist/devices-matter/OnOffSwitchAccessory.d.ts.map +1 -1
  55. package/dist/devices-matter/OnOffSwitchAccessory.js +18 -19
  56. package/dist/devices-matter/OnOffSwitchAccessory.js.map +1 -1
  57. package/dist/devices-matter/RoboticVacuumAccessory.d.ts +3 -1
  58. package/dist/devices-matter/RoboticVacuumAccessory.d.ts.map +1 -1
  59. package/dist/devices-matter/RoboticVacuumAccessory.js +77 -145
  60. package/dist/devices-matter/RoboticVacuumAccessory.js.map +1 -1
  61. package/dist/devices-matter/TemperatureSensorAccessory.d.ts +3 -1
  62. package/dist/devices-matter/TemperatureSensorAccessory.d.ts.map +1 -1
  63. package/dist/devices-matter/TemperatureSensorAccessory.js +18 -15
  64. package/dist/devices-matter/TemperatureSensorAccessory.js.map +1 -1
  65. package/dist/devices-matter/ThermostatAccessory.d.ts +3 -1
  66. package/dist/devices-matter/ThermostatAccessory.d.ts.map +1 -1
  67. package/dist/devices-matter/ThermostatAccessory.js +37 -29
  68. package/dist/devices-matter/ThermostatAccessory.js.map +1 -1
  69. package/dist/devices-matter/VenetianBlindAccessory.d.ts +3 -1
  70. package/dist/devices-matter/VenetianBlindAccessory.d.ts.map +1 -1
  71. package/dist/devices-matter/VenetianBlindAccessory.js +39 -40
  72. package/dist/devices-matter/VenetianBlindAccessory.js.map +1 -1
  73. package/dist/devices-matter/WindowBlindAccessory.d.ts +3 -1
  74. package/dist/devices-matter/WindowBlindAccessory.d.ts.map +1 -1
  75. package/dist/devices-matter/WindowBlindAccessory.js +36 -37
  76. package/dist/devices-matter/WindowBlindAccessory.js.map +1 -1
  77. package/dist/index.d.ts.map +1 -1
  78. package/dist/index.js +26 -1
  79. package/dist/index.js.map +1 -1
  80. package/dist/platform-hap.d.ts.map +1 -1
  81. package/dist/platform-hap.js +13 -1
  82. package/dist/platform-hap.js.map +1 -1
  83. package/dist/platform-matter.d.ts +45 -0
  84. package/dist/platform-matter.d.ts.map +1 -1
  85. package/dist/platform-matter.js +607 -2
  86. package/dist/platform-matter.js.map +1 -1
  87. package/docs/variables/default.html +1 -1
  88. package/package.json +1 -1
  89. package/src/devices-matter/ColorLightAccessory.ts +37 -40
  90. package/src/devices-matter/ColorTemperatureLightAccessory.ts +35 -41
  91. package/src/devices-matter/ContactSensorAccessory.ts +18 -14
  92. package/src/devices-matter/DimmableLightAccessory.ts +26 -30
  93. package/src/devices-matter/DoorLockAccessory.ts +28 -24
  94. package/src/devices-matter/ExtendedColorLightAccessory.ts +43 -47
  95. package/src/devices-matter/FanAccessory.ts +33 -25
  96. package/src/devices-matter/HumiditySensorAccessory.ts +18 -16
  97. package/src/devices-matter/LeakSensorAccessory.ts +18 -14
  98. package/src/devices-matter/LightSensorAccessory.ts +18 -16
  99. package/src/devices-matter/OccupancySensorAccessory.ts +18 -22
  100. package/src/devices-matter/OnOffLightAccessory.ts +23 -23
  101. package/src/devices-matter/OnOffOutletAccessory.ts +25 -31
  102. package/src/devices-matter/OnOffSwitchAccessory.ts +20 -21
  103. package/src/devices-matter/RoboticVacuumAccessory.ts +79 -156
  104. package/src/devices-matter/TemperatureSensorAccessory.ts +20 -16
  105. package/src/devices-matter/ThermostatAccessory.ts +39 -34
  106. package/src/devices-matter/VenetianBlindAccessory.ts +41 -44
  107. package/src/devices-matter/WindowBlindAccessory.ts +37 -39
  108. package/src/index.ts +27 -1
  109. package/src/platform-hap.ts +12 -1
  110. package/src/platform-matter.ts +647 -2
@@ -5,9 +5,12 @@ import type {
5
5
  MatterAccessory,
6
6
  SerializedMatterAccessory,
7
7
  } from 'homebridge'
8
+ import type { bodyChange, device } from 'node-switchbot'
8
9
 
9
10
  import type { SwitchBotPlatformConfig } from './settings.js'
10
11
 
12
+ import { SwitchBotBLE, SwitchBotOpenAPI } from 'node-switchbot'
13
+
11
14
  import {
12
15
  ColorLightAccessory,
13
16
  ColorTemperatureLightAccessory,
@@ -32,7 +35,7 @@ import {
32
35
  WindowBlindAccessory,
33
36
  } from './devices-matter/index.js'
34
37
  import { PLATFORM_NAME, PLUGIN_NAME } from './settings.js'
35
- import { cleanDeviceConfig } from './utils.js'
38
+ import { cleanDeviceConfig, formatDeviceIdAsMac, hs2rgb, rgb2hs, sleep } from './utils.js'
36
39
 
37
40
  /**
38
41
  * MatterPlatform
@@ -47,6 +50,13 @@ export class SwitchBotMatterPlatform implements DynamicPlatformPlugin {
47
50
 
48
51
  // Track restored Matter cached accessories
49
52
  public readonly matterAccessories: Map<string, SerializedMatterAccessory> = new Map()
53
+ // node-switchbot clients
54
+ private switchBotAPI?: SwitchBotOpenAPI
55
+ private switchBotBLE?: SwitchBotBLE
56
+ // discovered devices cache
57
+ private discoveredDevices: device[] = []
58
+ // BLE event handlers keyed by device MAC (formatted)
59
+ private bleEventHandler: { [x: string]: (context: any) => void } = {}
50
60
 
51
61
  constructor(
52
62
  public readonly log: Logging,
@@ -87,10 +97,616 @@ export class SwitchBotMatterPlatform implements DynamicPlatformPlugin {
87
97
  // Register Matter accessories when Homebridge has finished launching
88
98
  this.api.on('didFinishLaunching', () => {
89
99
  this.log.debug('Executed didFinishLaunching callback')
100
+ // Initialize SwitchBot API clients
101
+ try {
102
+ if (this.config.credentials?.token && this.config.credentials?.secret) {
103
+ this.switchBotAPI = new SwitchBotOpenAPI(this.config.credentials.token, this.config.credentials.secret, this.config.options?.hostname)
104
+ // forward basic logs
105
+ if (!this.config.options?.disableLogsforOpenAPI && this.switchBotAPI?.on) {
106
+ this.switchBotAPI.on('log', (l: any) => this.log.debug('[SwitchBot OpenAPI]', l.message))
107
+ }
108
+ } else {
109
+ this.log.debug('SwitchBot OpenAPI credentials not provided; cloud devices will be skipped')
110
+ }
111
+ } catch (e: any) {
112
+ this.log.error('Failed to initialize SwitchBot OpenAPI:', e?.message ?? e)
113
+ }
114
+
115
+ try {
116
+ this.switchBotBLE = new SwitchBotBLE()
117
+ if (!this.config.options?.disableLogsforBLE && this.switchBotBLE?.on) {
118
+ this.switchBotBLE.on('log', (l: any) => this.log.debug('[SwitchBot BLE]', l.message))
119
+ }
120
+ } catch (e: any) {
121
+ this.log.error('Failed to initialize SwitchBot BLE client:', e?.message ?? e)
122
+ }
123
+
124
+ // If BLE scanning is enabled, start scanning and route advertisements to registered handlers
125
+ if (this.config.options?.BLE && this.switchBotBLE) {
126
+ const ble = this.switchBotBLE
127
+ ;(async () => {
128
+ try {
129
+ await ble.startScan()
130
+ } catch (e: any) {
131
+ this.log.error(`Failed to start BLE scanning: ${e?.message ?? e}`)
132
+ }
133
+
134
+ // route advertisements to our handlers
135
+ ble.onadvertisement = async (ad: any) => {
136
+ try {
137
+ const mac = (ad.address || '').toLowerCase()
138
+ const handler = this.bleEventHandler[mac]
139
+ if (handler) {
140
+ await handler(ad.serviceData)
141
+ }
142
+ } catch (e: any) {
143
+ this.log.error(`Failed to handle BLE advertisement: ${e?.message ?? e}`)
144
+ }
145
+ }
146
+ })()
147
+ }
148
+
149
+ // perform device discovery from SwitchBot OpenAPI (if configured)
150
+ void this.discoverDevices()
151
+
90
152
  this.registerMatterAccessories()
91
153
  })
92
154
  }
93
155
 
156
+ /**
157
+ * Normalize a deviceId for matching (uppercase alphanumerics only)
158
+ */
159
+ private normalizeDeviceId(deviceId: string) {
160
+ return (deviceId ?? '').toUpperCase().replace(/[^A-Z0-9]+/g, '')
161
+ }
162
+
163
+ /**
164
+ * Merge two arrays by deviceId. For each item in a1 (user-provided devices list),
165
+ * find matching item in a2 (discovered devices) and merge them with user overrides last.
166
+ */
167
+ private mergeByDeviceId(a1: { deviceId: string }[], a2: any[]) {
168
+ return a1.map((itm) => {
169
+ const matchingItem = a2.find(item => this.normalizeDeviceId(item.deviceId) === this.normalizeDeviceId(itm.deviceId))
170
+ return Object.assign({}, matchingItem, itm)
171
+ })
172
+ }
173
+
174
+ /**
175
+ * Merge discovered devices with deviceConfig (per deviceType) and per-device overrides
176
+ * from `config.options.devices`, matching the behavior used in platform-hap.
177
+ */
178
+ private async mergeDiscoveredDevices(discovered: device[]): Promise<any[]> {
179
+ // If there's no device config or per-device config, return discovered as-is
180
+ if (!this.config.options?.devices && !this.config.options?.deviceConfig) {
181
+ return discovered
182
+ }
183
+
184
+ // Step 1: Assign missing deviceType from configDeviceType and merge deviceType-level configs
185
+ const devicesWithTypeConfig = await Promise.all(discovered.map(async (deviceObj) => {
186
+ if (!deviceObj.deviceType) {
187
+ deviceObj.deviceType = (deviceObj as any).configDeviceType !== undefined ? (deviceObj as any).configDeviceType : 'Unknown'
188
+ this.log.debug(`API missing deviceType for ${deviceObj.deviceId}, using configDeviceType: ${(deviceObj as any).configDeviceType}`)
189
+ }
190
+ const deviceTypeConfig = this.config.options?.deviceConfig?.[deviceObj.deviceType] || {}
191
+ return Object.assign({}, deviceObj, deviceTypeConfig)
192
+ }))
193
+
194
+ // Merge per-device overrides by matching deviceId
195
+ const merged = this.mergeByDeviceId(this.config.options?.devices ?? [], devicesWithTypeConfig ?? [])
196
+
197
+ // For any entries in merged (which are based on config.options.devices), ensure final per-device merges include deviceId-specific config
198
+ const final: any[] = []
199
+ for (const device of merged) {
200
+ const deviceIdConfig = this.config.options?.devices?.[device.deviceId] || {}
201
+ const deviceWithConfig = Object.assign({}, device, deviceIdConfig)
202
+ final.push(deviceWithConfig)
203
+ }
204
+
205
+ // Also include any discovered devices that weren't present in the user devices list
206
+ const userDeviceIds = new Set((this.config.options?.devices || []).map((d: any) => this.normalizeDeviceId(d.deviceId)))
207
+ for (const d of devicesWithTypeConfig) {
208
+ if (!userDeviceIds.has(this.normalizeDeviceId(d.deviceId))) {
209
+ final.push(d)
210
+ }
211
+ }
212
+
213
+ return final
214
+ }
215
+
216
+ /**
217
+ * Select effective connection type for a device: prefer explicit device.connectionType,
218
+ * otherwise prefer BLE when platform BLE is enabled and device provides a BLE model/id.
219
+ */
220
+ private chooseConnectionType(deviceObj: any): 'BLE' | 'OpenAPI' {
221
+ if (deviceObj?.connectionType) {
222
+ return deviceObj.connectionType === 'BLE' ? 'BLE' : 'OpenAPI'
223
+ }
224
+ // If platform BLE is enabled and we have a bleModel or deviceId that formats to a MAC, prefer BLE
225
+ if (this.config.options?.BLE && (deviceObj?.bleModel || formatDeviceIdAsMac(deviceObj?.deviceId))) {
226
+ return 'BLE'
227
+ }
228
+ return 'OpenAPI'
229
+ }
230
+
231
+ /**
232
+ * Map a SwitchBot device object to a MatterAccessory using the device-specific
233
+ * Matter accessory classes in `src/devices-matter`.
234
+ */
235
+ private async createAccessoryFromDevice(dev: device): Promise<MatterAccessory<Record<string, unknown>> | undefined> {
236
+ // Basic metadata
237
+ const displayName = dev.deviceName ?? dev.deviceId ?? 'SwitchBot Device'
238
+ const serial = dev.deviceId ?? 'unknown'
239
+ const manufacturer = 'SwitchBot'
240
+ const model = dev.deviceType ?? 'SwitchBot'
241
+ const firmware = (dev as any).firmware ?? (dev as any).version ?? '0.0.0'
242
+
243
+ // Helper to build a default opts object consumed by the matter device classes
244
+ const baseOpts = {
245
+ uuid: this.api.matter.uuid.generate(serial),
246
+ displayName,
247
+ serialNumber: serial,
248
+ manufacturer,
249
+ model,
250
+ firmwareRevision: String(firmware),
251
+ hardwareRevision: '1.0.0',
252
+ deviceId: dev.deviceId,
253
+ context: { deviceId: dev.deviceId },
254
+ }
255
+
256
+ // Small helper to wrap common OpenAPI on/off commands
257
+ // Helper to send an OpenAPI command
258
+ const sendOpenAPI = async (command: string, parameter = 'default') => {
259
+ const bodyChange: bodyChange = { command, parameter, commandType: 'command' }
260
+ return this.retryCommand(dev, bodyChange, this.config.options?.maxRetries ?? 1, this.config.options?.delayBetweenRetries ?? 1000)
261
+ }
262
+
263
+ // Helper to send a BLE action if Platform BLE is enabled and switchBotBLE exists
264
+ const sendBLE = async (methodName: string, ...args: any[]) => {
265
+ // Provide a small retry loop for flaky BLE operations
266
+ if (!this.switchBotBLE) {
267
+ throw new Error('Platform BLE not available')
268
+ }
269
+ const id = formatDeviceIdAsMac(dev.deviceId)
270
+ const maxRetries = (this.config.options as any)?.bleRetries ?? 2
271
+ const retryDelay = (this.config.options as any)?.bleRetryDelay ?? 500
272
+ let attempt = 0
273
+ while (attempt < maxRetries) {
274
+ try {
275
+ const list = await this.switchBotBLE.discover({ model: (dev as any).bleModel, id })
276
+ if (!Array.isArray(list) || list.length === 0) {
277
+ throw new Error('BLE device not found')
278
+ }
279
+ const deviceInst: any = list[0]
280
+ if (typeof deviceInst[methodName] !== 'function') {
281
+ throw new TypeError(`BLE method ${methodName} not available on device`)
282
+ }
283
+ return await deviceInst[methodName](...args)
284
+ } catch (e: any) {
285
+ attempt++
286
+ if (attempt >= maxRetries) {
287
+ throw e
288
+ }
289
+ this.log.debug(`BLE ${methodName} attempt ${attempt} failed for ${dev.deviceId}: ${e?.message ?? e}, retrying in ${retryDelay}ms`)
290
+ await sleep(retryDelay)
291
+ }
292
+ }
293
+ throw new Error('BLE operation failed')
294
+ }
295
+
296
+ const makeOnOffHandlers = (uuid: string, connectionType: 'BLE' | 'OpenAPI') => ({
297
+ onOff: {
298
+ on: async () => {
299
+ try {
300
+ if (connectionType === 'BLE' && this.switchBotBLE) {
301
+ await sendBLE('turnOn')
302
+ } else {
303
+ await sendOpenAPI('turnOn')
304
+ }
305
+ await this.api.matter.updateAccessoryState(uuid, this.api.matter.clusterNames.OnOff, { onOff: true })
306
+ } catch (e: any) {
307
+ this.log.error(`Failed to turn on device ${dev.deviceId}: ${e?.message ?? e}`)
308
+ }
309
+ },
310
+ off: async () => {
311
+ try {
312
+ if (connectionType === 'BLE' && this.switchBotBLE) {
313
+ await sendBLE('turnOff')
314
+ } else {
315
+ await sendOpenAPI('turnOff')
316
+ }
317
+ await this.api.matter.updateAccessoryState(uuid, this.api.matter.clusterNames.OnOff, { onOff: false })
318
+ } catch (e: any) {
319
+ this.log.error(`Failed to turn off device ${dev.deviceId}: ${e?.message ?? e}`)
320
+ }
321
+ },
322
+ },
323
+ })
324
+
325
+ // Mapping from SwitchBot deviceType -> constructor (expanded for parity with HAP)
326
+ const mapping: { [key: string]: any } = {
327
+ // Plugs / Outlets
328
+ 'Plug': OnOffOutletAccessory,
329
+ 'Plug Mini (US)': OnOffOutletAccessory,
330
+ 'Plug Mini (JP)': OnOffOutletAccessory,
331
+ 'Plug Mini': OnOffOutletAccessory,
332
+ 'WoPlug': OnOffOutletAccessory,
333
+
334
+ // Lighting
335
+ 'Color Bulb': ColorLightAccessory,
336
+ 'Color Bulb Mini': ColorLightAccessory,
337
+ 'Ceiling Light': ColorTemperatureLightAccessory,
338
+ 'Ceiling Light Pro': ColorTemperatureLightAccessory,
339
+ 'Strip Light': ExtendedColorLightAccessory,
340
+ 'Light Strip': ExtendedColorLightAccessory,
341
+ 'Light Strip Plus': ExtendedColorLightAccessory,
342
+ 'Strip Light Pro': ExtendedColorLightAccessory,
343
+ 'Dimmable Light': DimmableLightAccessory,
344
+
345
+ // Robot Vacuums
346
+ 'K10+': RoboticVacuumAccessory,
347
+ 'K10+ Pro': RoboticVacuumAccessory,
348
+ 'WoSweeper': RoboticVacuumAccessory,
349
+ 'WoSweeperMini': RoboticVacuumAccessory,
350
+ 'Robot Vacuum Cleaner S1': RoboticVacuumAccessory,
351
+ 'Robot Vacuum Cleaner S1 Plus': RoboticVacuumAccessory,
352
+ 'Robot Vacuum Cleaner S10': RoboticVacuumAccessory,
353
+ 'Robot Vacuum Cleaner S1 Pro': RoboticVacuumAccessory,
354
+ 'Robot Vacuum Cleaner S1 Mini': RoboticVacuumAccessory,
355
+
356
+ // Locks
357
+ 'Smart Lock': DoorLockAccessory,
358
+ 'Smart Lock Pro': DoorLockAccessory,
359
+
360
+ // Sensors
361
+ 'Motion Sensor': OccupancySensorAccessory,
362
+ 'Contact Sensor': ContactSensorAccessory,
363
+ 'Water Detector': LeakSensorAccessory,
364
+ 'Meter': TemperatureSensorAccessory,
365
+ 'MeterPlus': TemperatureSensorAccessory,
366
+ 'MeterPro': TemperatureSensorAccessory,
367
+ 'WoIOSensor': TemperatureSensorAccessory,
368
+ 'Air Purifier PM2.5': HumiditySensorAccessory,
369
+ 'Air Purifier Table PM2.5': HumiditySensorAccessory,
370
+ 'Air Purifier': HumiditySensorAccessory,
371
+ 'Air Purifier VOC': HumiditySensorAccessory,
372
+ 'Air Purifier Table VOC': HumiditySensorAccessory,
373
+
374
+ // Fans
375
+ 'Battery Circulator Fan': FanAccessory,
376
+
377
+ // Curtains / Blinds
378
+ 'Blind Tilt': VenetianBlindAccessory,
379
+ 'Curtain': WindowBlindAccessory,
380
+ 'Curtain2': WindowBlindAccessory,
381
+ 'Curtain3': WindowBlindAccessory,
382
+ 'Curtain 2': WindowBlindAccessory,
383
+ 'WoRollerShade': WindowBlindAccessory,
384
+ 'Roller Shade': WindowBlindAccessory,
385
+ 'Venetian Blind': VenetianBlindAccessory,
386
+
387
+ // Switches / Relays
388
+ 'Relay Switch 1': OnOffSwitchAccessory,
389
+ 'Relay Switch 1PM': OnOffSwitchAccessory,
390
+ 'Relay Switch 2': OnOffSwitchAccessory,
391
+ 'Relay Switch 3': OnOffSwitchAccessory,
392
+
393
+ // Misc / hubs / other
394
+ 'Hub 2': undefined,
395
+ 'Hub 3': undefined,
396
+ 'Hub Mini': undefined,
397
+ 'Bot': OnOffSwitchAccessory,
398
+ 'Smart Bot': OnOffSwitchAccessory,
399
+ 'Humidifier': HumiditySensorAccessory,
400
+ 'Humidifier2': HumiditySensorAccessory,
401
+ 'Thermostat': ThermostatAccessory,
402
+ 'Water Heater': ThermostatAccessory,
403
+ }
404
+
405
+ const Ctor = mapping[dev.deviceType ?? '']
406
+ if (!Ctor) {
407
+ this.log.debug(`No Matter mapping for deviceType='${dev.deviceType}', deviceId=${dev.deviceId}`)
408
+ return undefined
409
+ }
410
+
411
+ // Build opts and handlers tailored for basic capabilities
412
+ const uuid = baseOpts.uuid
413
+ const handlers: Record<string, any> = {}
414
+
415
+ // Choose connection type for this device (BLE vs OpenAPI)
416
+ const connectionType = this.chooseConnectionType(dev)
417
+
418
+ // On/Off common
419
+ handlers.onOff = makeOnOffHandlers(uuid, connectionType).onOff
420
+
421
+ // If this is a light, add brightness and color handlers
422
+ if (['Color Bulb', 'Ceiling Light', 'Ceiling Light Pro', 'Strip Light', 'Dimmable Light'].includes(dev.deviceType ?? '')) {
423
+ // levelControl
424
+ handlers.levelControl = {
425
+ moveToLevelWithOnOff: async (request: any) => {
426
+ try {
427
+ const level = request.level as number
428
+ const percent = Math.round((level / 254) * 100)
429
+ if (connectionType === 'BLE' && this.switchBotBLE) {
430
+ await sendBLE('setBrightness', percent)
431
+ } else {
432
+ await sendOpenAPI('setBrightness', `${percent}`)
433
+ }
434
+ await this.api.matter.updateAccessoryState(uuid, this.api.matter.clusterNames.LevelControl, { currentLevel: level })
435
+ } catch (e: any) {
436
+ this.log.error(`Failed to set brightness for ${dev.deviceId}: ${e?.message ?? e}`)
437
+ }
438
+ },
439
+ }
440
+
441
+ // colorControl
442
+ handlers.colorControl = {
443
+ moveToHueAndSaturationLogic: async (request: any) => {
444
+ try {
445
+ const hue = request.hue as number
446
+ const saturation = request.saturation as number
447
+ const [r, g, b] = hs2rgb(Math.round((hue / 254) * 360), Math.round((saturation / 254) * 100))
448
+ if (connectionType === 'BLE' && this.switchBotBLE) {
449
+ await sendBLE('setRGB', Number(request.level ?? 100), r, g, b)
450
+ } else {
451
+ await sendOpenAPI('setColor', `${r}:${g}:${b}`)
452
+ }
453
+ await this.api.matter.updateAccessoryState(uuid, this.api.matter.clusterNames.ColorControl, { currentHue: hue, currentSaturation: saturation })
454
+ } catch (e: any) {
455
+ this.log.error(`Failed to set hue/sat for ${dev.deviceId}: ${e?.message ?? e}`)
456
+ }
457
+ },
458
+ moveToColorLogic: async (request: any) => {
459
+ try {
460
+ // MoveToColor gives colorX/colorY values; convert to approximate RGB by mapping to 0-255 scale
461
+ const colorX = request.colorX as number
462
+ const colorY = request.colorY as number
463
+ // Naive conversion: map X/Y into RGB via hue approximation (not colorimetrically accurate)
464
+ const hueApprox = Math.round((colorX / 65535) * 360)
465
+ const satApprox = Math.round((colorY / 65535) * 100)
466
+ const [r, g, b] = hs2rgb(hueApprox, satApprox)
467
+ if (connectionType === 'BLE' && this.switchBotBLE) {
468
+ await sendBLE('setRGB', Number(request.level ?? 100), r, g, b)
469
+ } else {
470
+ await sendOpenAPI('setColor', `${r}:${g}:${b}`)
471
+ }
472
+ await this.api.matter.updateAccessoryState(uuid, this.api.matter.clusterNames.ColorControl, { currentX: colorX, currentY: colorY })
473
+ } catch (e: any) {
474
+ this.log.error(`Failed to set XY color for ${dev.deviceId}: ${e?.message ?? e}`)
475
+ }
476
+ },
477
+ }
478
+
479
+ // color temperature — map to kelvin and send setColorTemperature
480
+ handlers.colorTemperature = {
481
+ moveToColorTemperature: async (request: any) => {
482
+ try {
483
+ const kelvin = Math.round(1000000 / Number(request.colorTemperature))
484
+ if (connectionType === 'BLE' && this.switchBotBLE) {
485
+ await sendBLE('setColorTemperature', kelvin)
486
+ } else {
487
+ await sendOpenAPI('setColorTemperature', `${kelvin}`)
488
+ }
489
+ await this.api.matter.updateAccessoryState(uuid, this.api.matter.clusterNames.ColorControl, { currentX: request.colorX ?? 0, currentY: request.colorY ?? 0 })
490
+ } catch (e: any) {
491
+ this.log.error(`Failed to set color temperature for ${dev.deviceId}: ${e?.message ?? e}`)
492
+ }
493
+ },
494
+ }
495
+ }
496
+
497
+ const opts = Object.assign({}, baseOpts, { handlers })
498
+
499
+ // Instantiate the device class and return its serialized accessory
500
+ const instance = new Ctor(this.api, this.log, opts)
501
+
502
+ // Register BLE->Matter push handler for this device's MAC (if BLE scanning is active)
503
+ try {
504
+ const mac = formatDeviceIdAsMac(dev.deviceId).toLowerCase()
505
+ // Handler receives advertisement/serviceData when BLE scan events arrive
506
+ this.bleEventHandler[mac] = async (serviceData?: any) => {
507
+ const uuidLocal = baseOpts.uuid
508
+
509
+ // First try model-specific / normalized parsing of BLE advertisement
510
+ try {
511
+ const parsed = this.parseAdvertisementForDevice(dev, serviceData)
512
+ if (parsed) {
513
+ // Power
514
+ if (parsed.power !== undefined) {
515
+ await this.api.matter.updateAccessoryState(uuidLocal, this.api.matter.clusterNames.OnOff, { onOff: Boolean(parsed.power) })
516
+ }
517
+
518
+ // Brightness
519
+ if (parsed.brightness !== undefined) {
520
+ const level = Math.round((Number(parsed.brightness) / 100) * 254)
521
+ await this.api.matter.updateAccessoryState(uuidLocal, this.api.matter.clusterNames.LevelControl, { currentLevel: level })
522
+ }
523
+
524
+ // Color
525
+ if (parsed.color !== undefined) {
526
+ const { r, g, b } = parsed.color
527
+ const [h, s] = rgb2hs(r, g, b)
528
+ await this.api.matter.updateAccessoryState(uuidLocal, this.api.matter.clusterNames.ColorControl, { currentHue: Math.round((h / 360) * 254), currentSaturation: Math.round((s / 100) * 254) })
529
+ }
530
+
531
+ // If we parsed something from serviceData prefer it and return early
532
+ if (serviceData) {
533
+ return
534
+ }
535
+ }
536
+ } catch (e: any) {
537
+ this.log.debug(`BLE advertisement parsing failed for ${dev.deviceId}: ${e?.message ?? e}`)
538
+ }
539
+
540
+ // Fallback to OpenAPI getDeviceStatus when serviceData is not present or parsing failed
541
+ if (!this.switchBotAPI) {
542
+ return
543
+ }
544
+ try {
545
+ const { response, statusCode } = await this.switchBotAPI.getDeviceStatus(dev.deviceId, this.config.credentials?.token, this.config.credentials?.secret)
546
+ if (!(statusCode === 100 || statusCode === 200)) {
547
+ return
548
+ }
549
+ const respAny: any = response
550
+ const body = respAny?.body ?? respAny
551
+ const status = body?.status ?? body
552
+
553
+ // On/Off
554
+ if (status?.power !== undefined) {
555
+ const on = (String(status.power).toLowerCase() === 'on' || Number(status.power) === 1)
556
+ await this.api.matter.updateAccessoryState(uuidLocal, this.api.matter.clusterNames.OnOff, { onOff: on })
557
+ }
558
+
559
+ // Brightness
560
+ if (status?.brightness !== undefined) {
561
+ const level = Math.round((Number(status.brightness) / 100) * 254)
562
+ await this.api.matter.updateAccessoryState(uuidLocal, this.api.matter.clusterNames.LevelControl, { currentLevel: level })
563
+ }
564
+
565
+ // Color
566
+ if (status?.color !== undefined) {
567
+ const color = String(status.color)
568
+ let r = 0
569
+ let g = 0
570
+ let b = 0
571
+ if (color.includes(':')) {
572
+ const parts = color.split(':').map(Number)
573
+ ;[r, g, b] = parts
574
+ } else if (color.startsWith('#')) {
575
+ const hex = color.replace('#', '')
576
+ r = Number.parseInt(hex.substring(0, 2), 16)
577
+ g = Number.parseInt(hex.substring(2, 4), 16)
578
+ b = Number.parseInt(hex.substring(4, 6), 16)
579
+ }
580
+ const [h, s] = rgb2hs(r, g, b)
581
+ await this.api.matter.updateAccessoryState(uuidLocal, this.api.matter.clusterNames.ColorControl, { currentHue: Math.round((h / 360) * 254), currentSaturation: Math.round((s / 100) * 254) })
582
+ }
583
+ } catch (e: any) {
584
+ this.log.debug(`BLE push handler failed for ${dev.deviceId}: ${e?.message ?? e}`)
585
+ }
586
+ }
587
+ } catch (e: any) {
588
+ this.log.debug(`Failed to register BLE handler for ${dev.deviceId}: ${e?.message ?? e}`)
589
+ }
590
+
591
+ return instance.toAccessory()
592
+ }
593
+
594
+ /**
595
+ * Discover devices via SwitchBot OpenAPI and cache them for later use
596
+ */
597
+ private async discoverDevices(): Promise<void> {
598
+ if (!this.switchBotAPI) {
599
+ this.log.debug('SwitchBot OpenAPI not configured; skipping discovery')
600
+ return
601
+ }
602
+
603
+ try {
604
+ const { response, statusCode } = await this.switchBotAPI.getDevices()
605
+ this.log.debug(`SwitchBot getDevices response status: ${statusCode}`)
606
+ if (statusCode === 100 || statusCode === 200) {
607
+ const deviceList = Array.isArray(response?.body?.deviceList) ? response.body.deviceList : []
608
+ this.discoveredDevices = deviceList
609
+ this.log.info(`Discovered ${deviceList.length} SwitchBot device(s) from OpenAPI`)
610
+ for (const d of deviceList) {
611
+ this.log.debug(` - ${d.deviceName} (${d.deviceType}) id=${d.deviceId}`)
612
+ }
613
+ } else {
614
+ this.log.warn(`SwitchBot getDevices returned status ${statusCode}`)
615
+ }
616
+ } catch (e: any) {
617
+ this.log.error('Failed to discover SwitchBot devices:', e?.message ?? e)
618
+ }
619
+ }
620
+
621
+ /**
622
+ * Retry wrapper for control commands using SwitchBot OpenAPI
623
+ */
624
+ async retryCommand(deviceObj: device, bodyChange: bodyChange, maxRetries = 1, delayBetweenRetries = 1000): Promise<{ response: any, statusCode: number }> {
625
+ let retryCount = 0
626
+ while (retryCount < maxRetries) {
627
+ try {
628
+ if (!this.switchBotAPI) {
629
+ throw new Error('SwitchBot OpenAPI not initialized')
630
+ }
631
+ const { response, statusCode } = await this.switchBotAPI.controlDevice(
632
+ deviceObj.deviceId,
633
+ bodyChange.command,
634
+ bodyChange.parameter,
635
+ bodyChange.commandType as import('node-switchbot').commandType | undefined,
636
+ this.config.credentials?.token,
637
+ this.config.credentials?.secret,
638
+ )
639
+ return { response, statusCode }
640
+ } catch (e: any) {
641
+ this.log.debug(`retryCommand error: ${e?.message ?? e}`)
642
+ }
643
+ retryCount++
644
+
645
+ await sleep(delayBetweenRetries)
646
+ }
647
+ return { response: {}, statusCode: 500 }
648
+ }
649
+
650
+ /**
651
+ * Parse BLE advertisement/serviceData into normalized fields for a given device.
652
+ * Returns null when serviceData is falsy or parsing fails.
653
+ */
654
+ private parseAdvertisementForDevice(dev: device, serviceData?: any) {
655
+ if (!serviceData) {
656
+ return null
657
+ }
658
+ try {
659
+ const sd = serviceData
660
+ const result: any = {}
661
+
662
+ // Power/on state - supports multiple field names used by different models
663
+ const power = sd.power ?? sd.on ?? sd.p
664
+ if (power !== undefined) {
665
+ result.power = (String(power).toLowerCase() === 'on' || Number(power) === 1)
666
+ }
667
+
668
+ // Brightness (0-100)
669
+ const brightness = sd.brightness ?? sd.b
670
+ if (brightness !== undefined) {
671
+ result.brightness = Number(brightness)
672
+ }
673
+
674
+ // Color - could be 'r:g:b', '#rrggbb' or 'rrggbb'
675
+ const color = sd.color ?? sd.rgb ?? sd.c
676
+ if (color !== undefined) {
677
+ let r = 0
678
+ let g = 0
679
+ let b = 0
680
+ const c = String(color)
681
+ if (c.includes(':')) {
682
+ const parts = c.split(':').map(Number)
683
+ ;[r, g, b] = parts
684
+ } else if (c.startsWith('#')) {
685
+ const hex = c.replace('#', '')
686
+ r = Number.parseInt(hex.substring(0, 2), 16)
687
+ g = Number.parseInt(hex.substring(2, 4), 16)
688
+ b = Number.parseInt(hex.substring(4, 6), 16)
689
+ } else if (/^[0-9a-f]{6}$/i.test(c)) {
690
+ r = Number.parseInt(c.substring(0, 2), 16)
691
+ g = Number.parseInt(c.substring(2, 4), 16)
692
+ b = Number.parseInt(c.substring(4, 6), 16)
693
+ }
694
+ result.color = { r, g, b }
695
+ }
696
+
697
+ // Battery (some devices use battery or batt)
698
+ const battery = sd.battery ?? sd.batt
699
+ if (battery !== undefined) {
700
+ result.battery = Number(battery)
701
+ }
702
+
703
+ return result
704
+ } catch (e: any) {
705
+ this.log.debug(`parseAdvertisementForDevice failed for ${dev.deviceId}: ${e?.message ?? e}`)
706
+ return null
707
+ }
708
+ }
709
+
94
710
  /**
95
711
  * Required for DynamicPlatformPlugin
96
712
  * Called when homebridge restores cached accessories from disk at startup
@@ -123,7 +739,36 @@ export class SwitchBotMatterPlatform implements DynamicPlatformPlugin {
123
739
  // Remove accessories that are disabled in config
124
740
  await this.removeDisabledAccessories()
125
741
 
126
- // Register devices by Matter specification sections
742
+ // If we discovered real SwitchBot devices via OpenAPI, map and register them
743
+ if (this.discoveredDevices && this.discoveredDevices.length > 0) {
744
+ this.log.info(`Registering ${this.discoveredDevices.length} discovered SwitchBot device(s) as Matter accessories`)
745
+ const accessories: Array<MatterAccessory<Record<string, unknown>>> = []
746
+
747
+ // Merge device config (deviceConfig per deviceType and per-device overrides) to match HAP behavior
748
+ const devicesToProcess = await this.mergeDiscoveredDevices(this.discoveredDevices)
749
+
750
+ for (const dev of devicesToProcess) {
751
+ try {
752
+ const acc = await this.createAccessoryFromDevice(dev)
753
+ if (acc) {
754
+ accessories.push(acc)
755
+ }
756
+ } catch (e: any) {
757
+ this.log.error(`Failed to create Matter accessory for ${dev.deviceId}: ${e?.message ?? e}`)
758
+ }
759
+ }
760
+ if (accessories.length > 0) {
761
+ this.log.info(`✓ Registered ${accessories.length} discovered device(s)`)
762
+ for (const acc of accessories) {
763
+ this.log.info(` - ${acc.displayName}`)
764
+ }
765
+ await this.api.matter.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, accessories)
766
+ return
767
+ }
768
+ this.log.info('No discovered devices were mapped to Matter accessories; falling back to example sections')
769
+ }
770
+
771
+ // Register example/demo devices by Matter specification sections
127
772
  await this.registerSection4Lighting()
128
773
  await this.registerSection5SmartPlugs()
129
774
  await this.registerSection6Switches()