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