@switchbot/homebridge-switchbot 5.2.8 → 5.2.9-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.github/npm-version-script-esm.js +103 -0
- package/config.schema.json +0 -29
- package/dist/SwitchBotMatterPlatform.d.ts +2 -0
- package/dist/SwitchBotMatterPlatform.d.ts.map +1 -1
- package/dist/SwitchBotMatterPlatform.js +29 -10
- package/dist/SwitchBotMatterPlatform.js.map +1 -1
- package/dist/deviceFactory.js +1 -1
- package/dist/deviceFactory.js.map +1 -1
- package/dist/devices/genericDevice.d.ts +0 -2
- package/dist/devices/genericDevice.d.ts.map +1 -1
- package/dist/devices/genericDevice.js +10 -60
- package/dist/devices/genericDevice.js.map +1 -1
- package/dist/homebridge-ui/endpoints/discovery.d.ts.map +1 -1
- package/dist/homebridge-ui/endpoints/discovery.js +0 -2
- package/dist/homebridge-ui/endpoints/discovery.js.map +1 -1
- package/dist/homebridge-ui/homebridge-ui/endpoints/discovery.js +0 -2
- package/dist/homebridge-ui/homebridge-ui/endpoints/discovery.js.map +1 -1
- package/dist/homebridge-ui/public/index.html +2 -12
- package/dist/homebridge-ui/public/js/advanced-settings.d.ts +1 -4
- package/dist/homebridge-ui/public/js/advanced-settings.d.ts.map +1 -1
- package/dist/homebridge-ui/public/js/advanced-settings.js +11 -19
- package/dist/homebridge-ui/public/js/advanced-settings.js.map +1 -1
- package/dist/homebridge-ui/public/js/advanced-settings.ts +11 -21
- package/dist/homebridge-ui/public/js/app.js +4 -4
- package/dist/homebridge-ui/public/js/app.js.map +2 -2
- package/dist/homebridge-ui/public/js/modals.js +4 -4
- package/dist/homebridge-ui/public/js/modals.js.map +1 -1
- package/dist/homebridge-ui/public/js/modals.ts +4 -4
- package/dist/homebridge-ui/settings.js.map +1 -1
- package/dist/homebridge-ui/switchbotClient.js +41 -8
- package/dist/homebridge-ui/switchbotClient.js.map +1 -1
- package/dist/settings.d.ts +0 -1
- package/dist/settings.d.ts.map +1 -1
- package/dist/settings.js.map +1 -1
- package/dist/switchbotClient.d.ts +15 -6
- package/dist/switchbotClient.d.ts.map +1 -1
- package/dist/switchbotClient.js +41 -8
- package/dist/switchbotClient.js.map +1 -1
- package/docs/variables/default.html +1 -1
- package/package.json +2 -2
- package/src/SwitchBotMatterPlatform.ts +28 -9
- package/src/deviceFactory.ts +1 -1
- package/src/devices/genericDevice.ts +10 -57
- package/src/homebridge-ui/endpoints/discovery.ts +0 -2
- package/src/homebridge-ui/public/index.html +2 -12
- package/src/homebridge-ui/public/js/advanced-settings.ts +11 -21
- package/src/homebridge-ui/public/js/modals.ts +4 -4
- package/src/settings.ts +0 -1
- package/src/switchbotClient.ts +52 -9
- package/test/client/switchbot-client-keys.spec.ts +59 -0
- package/test/platform/matter-registration.spec.ts +68 -0
- package/test/device/curtain-ble-position.spec.ts +0 -34
|
@@ -37,6 +37,8 @@ export class SwitchBotMatterPlatform {
|
|
|
37
37
|
devices: any[] = []
|
|
38
38
|
/** Map of accessory UUID to accessory object */
|
|
39
39
|
accessories: Map<string, any>
|
|
40
|
+
/** UUIDs this process has registered with Homebridge's Matter server */
|
|
41
|
+
private readonly registeredMatterUUIDs = new Set<string>()
|
|
40
42
|
/** Hash of last loaded config for change detection */
|
|
41
43
|
private lastConfigHash: string = ''
|
|
42
44
|
/** Interval for periodic config reload */
|
|
@@ -125,8 +127,8 @@ export class SwitchBotMatterPlatform {
|
|
|
125
127
|
_raw: raw,
|
|
126
128
|
}
|
|
127
129
|
const type: string = normalizeTypeForMatter(d.type)
|
|
128
|
-
const deviceOpts: any = { id: d.id, type, name: d.name, encryptionKey: d.encryptionKey, keyId: d.keyId, log: this.log }
|
|
129
|
-
this.log.debug(`[Matter] Device options for ${d.name ?? d.id}:`, JSON.stringify(deviceOpts, null, 2))
|
|
130
|
+
const deviceOpts: any = { id: d.id, type, deviceType: d.type, name: d.name, encryptionKey: d.encryptionKey, keyId: d.keyId, log: this.log }
|
|
131
|
+
this.log.debug(`[Matter/Debug] Device options for ${d.name ?? d.id}:`, JSON.stringify(deviceOpts, null, 2))
|
|
130
132
|
const matterSupported = !!DEVICE_MATTER_SUPPORTED[(type || '').toLowerCase()]
|
|
131
133
|
const matterAvailable = !!(this.api?.isMatterAvailable?.() && this.api?.isMatterEnabled?.())
|
|
132
134
|
const matterEnabled = matterAvailable || !!this.config.enableMatter
|
|
@@ -268,16 +270,32 @@ export class SwitchBotMatterPlatform {
|
|
|
268
270
|
this.log.warn(`Matter accessory creation failed for ${d.id} (${type})`, e)
|
|
269
271
|
}
|
|
270
272
|
}
|
|
271
|
-
if (accessoriesToRegister.length
|
|
273
|
+
if (accessoriesToRegister.length === 0) {
|
|
274
|
+
this.log.info('No Matter accessories to register')
|
|
275
|
+
return
|
|
276
|
+
}
|
|
277
|
+
// Register each accessory on its own so one failure does not drop the rest. Accessories already
|
|
278
|
+
// registered by this process (a config reload) are updated instead: Homebridge throws
|
|
279
|
+
// "already registered" when registering them again. Cache-restored accessories are registered
|
|
280
|
+
// so Homebridge attaches their handlers.
|
|
281
|
+
let registered = 0
|
|
282
|
+
for (const accessory of accessoriesToRegister) {
|
|
283
|
+
const uuid = accessory.UUID || accessory.uuid
|
|
272
284
|
try {
|
|
273
|
-
|
|
274
|
-
|
|
285
|
+
if (this.registeredMatterUUIDs.has(uuid)) {
|
|
286
|
+
if (typeof matterApi.updatePlatformAccessories === 'function') {
|
|
287
|
+
await matterApi.updatePlatformAccessories([accessory])
|
|
288
|
+
}
|
|
289
|
+
} else {
|
|
290
|
+
await matterApi.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [accessory])
|
|
291
|
+
this.registeredMatterUUIDs.add(uuid)
|
|
292
|
+
registered++
|
|
293
|
+
}
|
|
275
294
|
} catch (e) {
|
|
276
|
-
this.log.warn(
|
|
295
|
+
this.log.warn(`Failed to register Matter accessory ${accessory.displayName || uuid}`, e)
|
|
277
296
|
}
|
|
278
|
-
} else {
|
|
279
|
-
this.log.info('No Matter accessories to register')
|
|
280
297
|
}
|
|
298
|
+
this.log.info(`Registered ${registered} Matter accessory(ies) with Homebridge`)
|
|
281
299
|
}
|
|
282
300
|
|
|
283
301
|
/**
|
|
@@ -339,10 +357,11 @@ export class SwitchBotMatterPlatform {
|
|
|
339
357
|
// Unregister removed accessories from Homebridge (Matter API)
|
|
340
358
|
if (accessoriesToRemove.length > 0 && this.api && (this.api as any).matter && (this.api as any).matter.unregisterPlatformAccessories) {
|
|
341
359
|
try {
|
|
342
|
-
(this.api as any).matter.unregisterPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, accessoriesToRemove.map(a => a.accessory))
|
|
360
|
+
await (this.api as any).matter.unregisterPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, accessoriesToRemove.map(a => a.accessory))
|
|
343
361
|
this.log.info(`Unregistered ${accessoriesToRemove.length} Matter accessory(ies) removed from config`)
|
|
344
362
|
for (const { uuid } of accessoriesToRemove) {
|
|
345
363
|
this.accessories.delete(uuid)
|
|
364
|
+
this.registeredMatterUUIDs.delete(uuid)
|
|
346
365
|
}
|
|
347
366
|
} catch (e) {
|
|
348
367
|
this.log.warn('Failed to unregister removed Matter accessories', e)
|
package/src/deviceFactory.ts
CHANGED
|
@@ -150,7 +150,7 @@ export async function createDevice(opts: DeviceOptions, cfg: SwitchBotPluginConf
|
|
|
150
150
|
// Always pass the logger to both device opts and config
|
|
151
151
|
const logger = log || (cfg as any)?.logger || (cfg as any)?.log
|
|
152
152
|
if (opts && opts.name && logger && typeof logger.info === 'function') {
|
|
153
|
-
logger.
|
|
153
|
+
logger.info(`[Matter/Debug] createDevice: Passing opts for ${opts.name}:`, JSON.stringify(opts, null, 2))
|
|
154
154
|
}
|
|
155
155
|
// Reuse existing client when provided via config to avoid creating
|
|
156
156
|
// a new SwitchBotClient per device (which can be expensive).
|
|
@@ -67,19 +67,10 @@ export class GenericDevice extends DeviceBase {
|
|
|
67
67
|
if (!this.log) {
|
|
68
68
|
throw new Error('Device requires a logger (Homebridge logger) in opts or cfg')
|
|
69
69
|
}
|
|
70
|
-
//
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
if (dev && typeof dev.setKey === 'function') {
|
|
75
|
-
dev.setKey({
|
|
76
|
-
encryptionKey: opts.encryptionKey,
|
|
77
|
-
keyId: opts.keyId || undefined,
|
|
78
|
-
})
|
|
79
|
-
}
|
|
80
|
-
} catch (e) {
|
|
81
|
-
// ignore if device not found or setKey not available
|
|
82
|
-
}
|
|
70
|
+
// BLE encryption key (relay switches, locks, air purifiers, bulbs): the client applies it to the
|
|
71
|
+
// node-switchbot device when that device is discovered.
|
|
72
|
+
if (opts.encryptionKey && typeof this.client?.setDeviceKey === 'function') {
|
|
73
|
+
this.client.setDeviceKey(opts.id, { encryptionKey: opts.encryptionKey, keyId: opts.keyId || undefined })
|
|
83
74
|
}
|
|
84
75
|
// BLE polling config: allow override via opts.blePollingEnabled/blePollIntervalMs or cfg.blePollingEnabled/blePollIntervalMs
|
|
85
76
|
this._blePollingEnabled = opts?.blePollingEnabled ?? cfg?.blePollingEnabled ?? true
|
|
@@ -625,8 +616,6 @@ export class CurtainDevice extends GenericDevice {
|
|
|
625
616
|
private lastTargetPosition = 0
|
|
626
617
|
private positionState = 2
|
|
627
618
|
private preferLocalPositionUntil = 0
|
|
628
|
-
private lastAdvertisement?: object
|
|
629
|
-
private positionBeforeCommand?: number
|
|
630
619
|
|
|
631
620
|
private clampHomeKitPosition(position: number): number {
|
|
632
621
|
return Math.max(0, Math.min(100, Math.round(Number(position))))
|
|
@@ -641,21 +630,6 @@ export class CurtainDevice extends GenericDevice {
|
|
|
641
630
|
}
|
|
642
631
|
|
|
643
632
|
private async getPositionForHomeKit(): Promise<number> {
|
|
644
|
-
const device = this.client?.getCachedDevice?.(this.opts.id)
|
|
645
|
-
if (device?.hasBLE?.()) {
|
|
646
|
-
const advertisement = device.getInfo?.()?.bleServiceData
|
|
647
|
-
if (advertisement && advertisement !== this.lastAdvertisement) {
|
|
648
|
-
this.lastAdvertisement = advertisement
|
|
649
|
-
if (typeof advertisement.position === 'number' && Number.isFinite(advertisement.position)) {
|
|
650
|
-
const position = this.toHomeKitPosition(advertisement.position)
|
|
651
|
-
if (this.positionBeforeCommand === undefined || position !== this.positionBeforeCommand) {
|
|
652
|
-
this.lastKnownPosition = position
|
|
653
|
-
this.lastTargetPosition = position
|
|
654
|
-
}
|
|
655
|
-
}
|
|
656
|
-
}
|
|
657
|
-
return this.lastKnownPosition
|
|
658
|
-
}
|
|
659
633
|
if (Date.now() < this.preferLocalPositionUntil) {
|
|
660
634
|
return this.lastKnownPosition
|
|
661
635
|
}
|
|
@@ -663,9 +637,6 @@ export class CurtainDevice extends GenericDevice {
|
|
|
663
637
|
this.getState(),
|
|
664
638
|
new Promise(resolve => setTimeout(resolve, 1000)),
|
|
665
639
|
])
|
|
666
|
-
if (Date.now() < this.preferLocalPositionUntil) {
|
|
667
|
-
return this.lastKnownPosition
|
|
668
|
-
}
|
|
669
640
|
if (typeof state?.position === 'number') {
|
|
670
641
|
this.lastKnownPosition = this.toHomeKitPosition(Number(state.position))
|
|
671
642
|
this.lastTargetPosition = this.lastKnownPosition
|
|
@@ -681,8 +652,7 @@ export class CurtainDevice extends GenericDevice {
|
|
|
681
652
|
characteristics: {
|
|
682
653
|
CurrentPosition: {
|
|
683
654
|
get: async () => {
|
|
684
|
-
|
|
685
|
-
return this.lastKnownPosition
|
|
655
|
+
return this.getPositionForHomeKit()
|
|
686
656
|
},
|
|
687
657
|
},
|
|
688
658
|
PositionState: {
|
|
@@ -690,34 +660,17 @@ export class CurtainDevice extends GenericDevice {
|
|
|
690
660
|
},
|
|
691
661
|
TargetPosition: {
|
|
692
662
|
get: async () => {
|
|
693
|
-
|
|
663
|
+
await this.getPositionForHomeKit()
|
|
694
664
|
return this.lastTargetPosition
|
|
695
665
|
},
|
|
696
666
|
set: async (v: any) => {
|
|
697
667
|
const position = this.clampHomeKitPosition(Number(v))
|
|
698
|
-
const bleDevice = this.client?.getCachedDevice?.(this.opts.id)
|
|
699
|
-
if (bleDevice?.hasBLE?.()) {
|
|
700
|
-
await this.getPositionForHomeKit()
|
|
701
|
-
}
|
|
702
|
-
const previousPosition = this.lastKnownPosition
|
|
703
668
|
this.lastTargetPosition = position
|
|
704
669
|
this.positionState = position > this.lastKnownPosition ? 1 : position < this.lastKnownPosition ? 0 : 2
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
}
|
|
710
|
-
this.lastKnownPosition = position
|
|
711
|
-
if (bleDevice?.hasBLE?.()) {
|
|
712
|
-
this.positionBeforeCommand = previousPosition
|
|
713
|
-
}
|
|
714
|
-
this.preferLocalPositionUntil = Date.now() + 30000
|
|
715
|
-
} catch (error) {
|
|
716
|
-
this.lastTargetPosition = this.lastKnownPosition
|
|
717
|
-
throw error
|
|
718
|
-
} finally {
|
|
719
|
-
this.positionState = 2
|
|
720
|
-
}
|
|
670
|
+
await this.setState({ position: this.toSwitchBotPosition(position) })
|
|
671
|
+
this.lastKnownPosition = position
|
|
672
|
+
this.preferLocalPositionUntil = Date.now() + 30000
|
|
673
|
+
this.positionState = 2
|
|
721
674
|
},
|
|
722
675
|
refreshAfterSet: ['CurrentPosition', 'TargetPosition', 'PositionState'],
|
|
723
676
|
},
|
|
@@ -24,7 +24,6 @@ export function registerDiscoveryEndpoint(server: HomebridgePluginUiServer) {
|
|
|
24
24
|
enableRetry: true,
|
|
25
25
|
enableCircuitBreaker: true,
|
|
26
26
|
enableConnectionIntelligence: true,
|
|
27
|
-
logLevel: platform.nodeSwitchBotLogLevel,
|
|
28
27
|
})
|
|
29
28
|
|
|
30
29
|
await switchbot.discover({ timeout: 1000 })
|
|
@@ -71,7 +70,6 @@ export function registerDiscoveryEndpoint(server: HomebridgePluginUiServer) {
|
|
|
71
70
|
enableRetry: true,
|
|
72
71
|
enableCircuitBreaker: true,
|
|
73
72
|
enableConnectionIntelligence: true,
|
|
74
|
-
logLevel: platform.nodeSwitchBotLogLevel,
|
|
75
73
|
})
|
|
76
74
|
|
|
77
75
|
const deviceMap = new Map<string, any>()
|
|
@@ -140,17 +140,6 @@
|
|
|
140
140
|
</label>
|
|
141
141
|
<small>Enable or disable BLE (Bluetooth Low Energy) support. If disabled, only OpenAPI (cloud) will be used.</small>
|
|
142
142
|
</div>
|
|
143
|
-
<div class="form-group">
|
|
144
|
-
<label for="nodeSwitchBotLogLevel">Node-SwitchBot Log Level</label>
|
|
145
|
-
<select id="nodeSwitchBotLogLevel" style="font-size: 14px; margin-right: 5px;">
|
|
146
|
-
<option value="0">None</option>
|
|
147
|
-
<option value="1">Error</option>
|
|
148
|
-
<option value="2">Warning</option>
|
|
149
|
-
<option value="3">Info</option>
|
|
150
|
-
<option value="4">Debug</option>
|
|
151
|
-
</select>
|
|
152
|
-
<small>Controls logs from the Node-SwitchBot library. Default: Warning.</small>
|
|
153
|
-
</div>
|
|
154
143
|
<div class="form-group">
|
|
155
144
|
<label for="blePollingEnabled">
|
|
156
145
|
<input type="checkbox" id="blePollingEnabled" /> Enable BLE Polling Fallback
|
|
@@ -215,6 +204,7 @@
|
|
|
215
204
|
<input type="number" id="co2AbnormalThreshold" min="400" max="5000" step="1" value="1000" />
|
|
216
205
|
<small>Meter Pro (CO2) only. At or above this level HomeKit reports carbon dioxide as detected. Default: 1000.</small>
|
|
217
206
|
</div>
|
|
207
|
+
<button type="button" id="saveAdvancedSettingsBtn">Save Advanced Settings</button>
|
|
218
208
|
<div id="advancedSettingsStatus" style="margin-top: 8px; font-size: 12px;"></div>
|
|
219
209
|
</form>
|
|
220
210
|
</div>
|
|
@@ -223,4 +213,4 @@
|
|
|
223
213
|
<script type="module" src="js/advanced-settings.js"></script>
|
|
224
214
|
</body>
|
|
225
215
|
|
|
226
|
-
</html>
|
|
216
|
+
</html>
|
|
@@ -27,7 +27,6 @@ async function loadAdvancedSettings(): Promise<void> {
|
|
|
27
27
|
;(document.getElementById('enableMatter') as HTMLInputElement).checked = !!config.enableMatter
|
|
28
28
|
;(document.getElementById('preferMatter') as HTMLInputElement).checked = !!config.preferMatter
|
|
29
29
|
;(document.getElementById('enableBLE') as HTMLInputElement).checked = config.enableBLE !== false
|
|
30
|
-
;(document.getElementById('nodeSwitchBotLogLevel') as HTMLSelectElement).value = String(config.nodeSwitchBotLogLevel ?? 2)
|
|
31
30
|
;(document.getElementById('blePollingEnabled') as HTMLInputElement).checked = config.blePollingEnabled !== false
|
|
32
31
|
;(document.getElementById('blePollIntervalMs') as HTMLInputElement).value = String(config.blePollIntervalMs ?? 600000)
|
|
33
32
|
;(document.getElementById('co2AbnormalThreshold') as HTMLInputElement).value = String(config.co2AbnormalThreshold ?? 1000)
|
|
@@ -36,9 +35,9 @@ async function loadAdvancedSettings(): Promise<void> {
|
|
|
36
35
|
}
|
|
37
36
|
}
|
|
38
37
|
|
|
39
|
-
async function
|
|
38
|
+
async function saveAdvancedSettings(): Promise<void> {
|
|
40
39
|
const status = document.getElementById('advancedSettingsStatus') as HTMLElement
|
|
41
|
-
status.textContent = '
|
|
40
|
+
status.textContent = 'Saving...'
|
|
42
41
|
try {
|
|
43
42
|
if (typeof homebridge.getPluginConfig !== 'function') {
|
|
44
43
|
throw new TypeError('homebridge.getPluginConfig is not available')
|
|
@@ -67,7 +66,6 @@ async function syncAdvancedSettings(): Promise<void> {
|
|
|
67
66
|
config.enableMatter = (document.getElementById('enableMatter') as HTMLInputElement).checked
|
|
68
67
|
config.preferMatter = (document.getElementById('preferMatter') as HTMLInputElement).checked
|
|
69
68
|
config.enableBLE = (document.getElementById('enableBLE') as HTMLInputElement).checked
|
|
70
|
-
config.nodeSwitchBotLogLevel = Number((document.getElementById('nodeSwitchBotLogLevel') as HTMLSelectElement).value)
|
|
71
69
|
config.blePollingEnabled = (document.getElementById('blePollingEnabled') as HTMLInputElement).checked
|
|
72
70
|
config.blePollIntervalMs = Number((document.getElementById('blePollIntervalMs') as HTMLInputElement).value) || 600000
|
|
73
71
|
config.co2AbnormalThreshold = Number((document.getElementById('co2AbnormalThreshold') as HTMLInputElement).value) || 1000
|
|
@@ -78,29 +76,21 @@ async function syncAdvancedSettings(): Promise<void> {
|
|
|
78
76
|
} else {
|
|
79
77
|
throw new TypeError('homebridge.updatePluginConfig is not available')
|
|
80
78
|
}
|
|
81
|
-
|
|
79
|
+
if (typeof homebridge.savePluginConfig === 'function') {
|
|
80
|
+
await homebridge.savePluginConfig()
|
|
81
|
+
}
|
|
82
|
+
status.textContent = 'Settings saved!'
|
|
82
83
|
} catch (e: any) {
|
|
83
|
-
status.textContent = `Failed to
|
|
84
|
-
throw e
|
|
84
|
+
status.textContent = `Failed to save: ${e && e.message ? e.message : e}`
|
|
85
85
|
}
|
|
86
86
|
}
|
|
87
87
|
|
|
88
|
-
let pendingUpdate: Promise<void> = Promise.resolve()
|
|
89
|
-
let latestChange = 0
|
|
90
|
-
|
|
91
|
-
function queueAdvancedSettingsUpdate(): void {
|
|
92
|
-
const change = ++latestChange
|
|
93
|
-
homebridge.disableSaveButton?.()
|
|
94
|
-
pendingUpdate = pendingUpdate.catch(() => {}).then(syncAdvancedSettings).then(() => {
|
|
95
|
-
if (change === latestChange) {
|
|
96
|
-
homebridge.enableSaveButton?.()
|
|
97
|
-
}
|
|
98
|
-
}).catch(() => {})
|
|
99
|
-
}
|
|
100
|
-
|
|
101
88
|
document.addEventListener('DOMContentLoaded', () => {
|
|
102
89
|
if (document.getElementById('advancedSettingsCard')) {
|
|
103
90
|
loadAdvancedSettings()
|
|
104
|
-
document.getElementById('
|
|
91
|
+
const btn = document.getElementById('saveAdvancedSettingsBtn')
|
|
92
|
+
if (btn) {
|
|
93
|
+
btn.onclick = saveAdvancedSettings
|
|
94
|
+
}
|
|
105
95
|
}
|
|
106
96
|
})
|
|
@@ -149,7 +149,7 @@ export async function importDiscoveredDevice(device: any): Promise<ImportDiscove
|
|
|
149
149
|
['auto', 'ble', 'openapi'].forEach((val) => {
|
|
150
150
|
const opt = document.createElement('option')
|
|
151
151
|
opt.value = val
|
|
152
|
-
opt.text = val
|
|
152
|
+
opt.text = val.charAt(0).toUpperCase() + val.slice(1)
|
|
153
153
|
opt.selected = (device.connectionPreference || 'auto') === val
|
|
154
154
|
connectionPrefSelect.appendChild(opt)
|
|
155
155
|
})
|
|
@@ -496,7 +496,7 @@ export async function editDevice(device: any): Promise<void> {
|
|
|
496
496
|
|
|
497
497
|
const nameInput = document.createElement('input')
|
|
498
498
|
nameInput.type = 'text'
|
|
499
|
-
nameInput.value = device.
|
|
499
|
+
nameInput.value = device.name || device.id
|
|
500
500
|
nameInput.style.width = '100%'
|
|
501
501
|
nameInput.style.marginBottom = '12px'
|
|
502
502
|
nameInput.style.padding = '8px 10px'
|
|
@@ -568,7 +568,7 @@ export async function editDevice(device: any): Promise<void> {
|
|
|
568
568
|
;['auto', 'ble', 'openapi'].forEach((val) => {
|
|
569
569
|
const opt = document.createElement('option')
|
|
570
570
|
opt.value = val
|
|
571
|
-
opt.text = val
|
|
571
|
+
opt.text = val.charAt(0).toUpperCase() + val.slice(1)
|
|
572
572
|
opt.selected = (device.connectionPreference || 'auto') === val
|
|
573
573
|
connectionPrefSelect.appendChild(opt)
|
|
574
574
|
})
|
|
@@ -670,7 +670,7 @@ export async function editDevice(device: any): Promise<void> {
|
|
|
670
670
|
const { renderDeviceList } = await import('./render.js')
|
|
671
671
|
|
|
672
672
|
const params = {
|
|
673
|
-
deviceId: device.
|
|
673
|
+
deviceId: device.id,
|
|
674
674
|
configDeviceName: nameInput.value || undefined,
|
|
675
675
|
configDeviceType: typeSelect.value,
|
|
676
676
|
connectionPreference: connectionPrefSelect.value,
|
package/src/settings.ts
CHANGED
package/src/switchbotClient.ts
CHANGED
|
@@ -12,14 +12,28 @@ export interface ISwitchBotClient {
|
|
|
12
12
|
getDevice: (id: string) => Promise<any>
|
|
13
13
|
getDevices: () => Promise<any[]>
|
|
14
14
|
setDeviceState: (id: string, body: any) => Promise<any>
|
|
15
|
+
setDeviceKey?: (id: string, key: DeviceKey) => void
|
|
15
16
|
destroy: () => Promise<void>
|
|
16
17
|
}
|
|
17
18
|
|
|
19
|
+
/** BLE encryption key for a device (relay switches, locks, air purifiers, bulbs...) */
|
|
20
|
+
export interface DeviceKey {
|
|
21
|
+
encryptionKey: string
|
|
22
|
+
keyId?: string
|
|
23
|
+
}
|
|
24
|
+
|
|
18
25
|
/**
|
|
19
26
|
* Thin wrapper around node-switchbot v4.0.0+
|
|
20
27
|
* Leverages upstream resilience features (retry, circuit breaker, connection intelligence)
|
|
21
28
|
* while maintaining plugin-specific features like write debouncing and OpenAPI fallback.
|
|
22
29
|
*/
|
|
30
|
+
const APPLIED_KEY = Symbol('appliedDeviceKey')
|
|
31
|
+
|
|
32
|
+
/** Compare ids case-insensitively and without MAC separators */
|
|
33
|
+
function normalizeDeviceId(id: string): string {
|
|
34
|
+
return String(id).replace(/[:-]/g, '').toLowerCase()
|
|
35
|
+
}
|
|
36
|
+
|
|
23
37
|
export class SwitchBotClient implements ISwitchBotClient {
|
|
24
38
|
private cfg: SwitchBotPluginConfig
|
|
25
39
|
private client: SwitchBot | null = null
|
|
@@ -27,6 +41,8 @@ export class SwitchBotClient implements ISwitchBotClient {
|
|
|
27
41
|
private discoveryCacheTtlMs = 30_000
|
|
28
42
|
private lastDiscoveryAt = 0
|
|
29
43
|
private discoveryInFlight?: Promise<any[]>
|
|
44
|
+
/** Keys by device id, applied to the node-switchbot device whenever it is looked up */
|
|
45
|
+
private deviceKeys = new Map<string, DeviceKey>()
|
|
30
46
|
private logger: import('homebridge').Logger
|
|
31
47
|
private pendingWrites: Map<string, { timer: any, body: any, resolvers: Array<{ resolve: (v: any) => void, reject: (e: any) => void }> }> = new Map()
|
|
32
48
|
|
|
@@ -65,7 +81,6 @@ export class SwitchBotClient implements ISwitchBotClient {
|
|
|
65
81
|
enableBLE: this.cfg.enableBLE !== false, // Use config value, default true
|
|
66
82
|
scanTimeout,
|
|
67
83
|
...rawNodeClientConfig,
|
|
68
|
-
logLevel: this.cfg.nodeSwitchBotLogLevel ?? rawNodeClientConfig.logLevel,
|
|
69
84
|
})
|
|
70
85
|
this.lastDiscoveryAt = 0
|
|
71
86
|
this.logger?.info?.('SwitchBot client initialized with native resilience features')
|
|
@@ -75,7 +90,41 @@ export class SwitchBotClient implements ISwitchBotClient {
|
|
|
75
90
|
}
|
|
76
91
|
}
|
|
77
92
|
|
|
93
|
+
/**
|
|
94
|
+
* Set the BLE encryption key for a device. The node-switchbot device may not exist yet (it is
|
|
95
|
+
* created by discovery), so the key is kept and applied each time the device is looked up.
|
|
96
|
+
*/
|
|
97
|
+
setDeviceKey(id: string, key: DeviceKey): void {
|
|
98
|
+
if (!id || !key?.encryptionKey) {
|
|
99
|
+
return
|
|
100
|
+
}
|
|
101
|
+
this.deviceKeys.set(normalizeDeviceId(id), key)
|
|
102
|
+
this.applyDeviceKey(this.getManagedDevice(id))
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
private applyDeviceKey(device: any): any {
|
|
106
|
+
if (!device || typeof device.setKey !== 'function' || this.deviceKeys.size === 0) {
|
|
107
|
+
return device
|
|
108
|
+
}
|
|
109
|
+
const info = typeof device.getInfo === 'function' ? device.getInfo() : device
|
|
110
|
+
const ids = [device.id, info?.id, info?.mac, info?.address, info?.deviceId].filter(Boolean).map(normalizeDeviceId)
|
|
111
|
+
const key = ids.map(i => this.deviceKeys.get(i)).find(Boolean)
|
|
112
|
+
if (key && device[APPLIED_KEY] !== key) {
|
|
113
|
+
try {
|
|
114
|
+
device.setKey({ encryptionKey: key.encryptionKey, keyId: key.keyId || undefined })
|
|
115
|
+
device[APPLIED_KEY] = key
|
|
116
|
+
} catch (e: any) {
|
|
117
|
+
this.logger?.warn?.(`[${device.id}] Invalid BLE encryption key: ${e?.message ?? e}`)
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return device
|
|
121
|
+
}
|
|
122
|
+
|
|
78
123
|
async getDevice(id: string): Promise<any> {
|
|
124
|
+
return this.applyDeviceKey(await this.findDevice(id))
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
private async findDevice(id: string): Promise<any> {
|
|
79
128
|
if (this.client) {
|
|
80
129
|
try {
|
|
81
130
|
const fromManager = this.getManagedDevice(id)
|
|
@@ -110,18 +159,12 @@ export class SwitchBotClient implements ISwitchBotClient {
|
|
|
110
159
|
throw new SwitchbotOperationError('No SwitchBot client available', 'no_client')
|
|
111
160
|
}
|
|
112
161
|
|
|
113
|
-
getCachedDevice(id: string): any {
|
|
114
|
-
return this.getManagedDevice(id)
|
|
115
|
-
}
|
|
116
|
-
|
|
117
162
|
async getDevices(): Promise<any[]> {
|
|
118
163
|
if (this.client) {
|
|
119
164
|
try {
|
|
120
165
|
const fromManager = this.getManagedDevices()
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
}
|
|
124
|
-
return await this.ensureDiscovered(false)
|
|
166
|
+
const devices = fromManager.length > 0 ? fromManager : await this.ensureDiscovered(false)
|
|
167
|
+
return devices.map(device => this.applyDeviceKey(device))
|
|
125
168
|
} catch (e) {
|
|
126
169
|
this.logger?.warn?.('Client getDevices failed:', e)
|
|
127
170
|
throw e
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest'
|
|
2
|
+
|
|
3
|
+
import { SwitchBotClient } from '../../src/switchbotClient'
|
|
4
|
+
|
|
5
|
+
const logger = { info: () => {}, warn: vi.fn(), error: () => {}, debug: () => {} }
|
|
6
|
+
|
|
7
|
+
function client(devices: any[]) {
|
|
8
|
+
const c = new SwitchBotClient({ logger } as any)
|
|
9
|
+
;(c as any).client = {
|
|
10
|
+
discover: vi.fn(async () => devices),
|
|
11
|
+
devices: { get: (id: string) => devices.find(d => d.id === id), list: () => devices },
|
|
12
|
+
}
|
|
13
|
+
return c
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function device(id: string, mac?: string) {
|
|
17
|
+
return { id, setKey: vi.fn(), getInfo: () => ({ id, mac }) }
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// genericDevice used to call client.devices.get(), which the plugin's client wrapper does not have,
|
|
21
|
+
// so BLE encryption keys were never passed to node-switchbot.
|
|
22
|
+
describe('switchBotClient device keys', () => {
|
|
23
|
+
it('applies a key set before the device is discovered', async () => {
|
|
24
|
+
const devices: any[] = []
|
|
25
|
+
const c = client(devices)
|
|
26
|
+
c.setDeviceKey('AA:BB:CC:DD:EE:FF', { encryptionKey: '0'.repeat(32), keyId: 'ab' })
|
|
27
|
+
const relay = device('aabbccddeeff', 'AA:BB:CC:DD:EE:FF')
|
|
28
|
+
devices.push(relay)
|
|
29
|
+
await c.getDevice('aabbccddeeff')
|
|
30
|
+
expect(relay.setKey).toHaveBeenCalledWith({ encryptionKey: '0'.repeat(32), keyId: 'ab' })
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
it('applies a key immediately when the device already exists, and only once', async () => {
|
|
34
|
+
const relay = device('relay-1')
|
|
35
|
+
const c = client([relay])
|
|
36
|
+
c.setDeviceKey('relay-1', { encryptionKey: '1'.repeat(32), keyId: '01' })
|
|
37
|
+
await c.getDevice('relay-1')
|
|
38
|
+
await c.getDevices()
|
|
39
|
+
expect(relay.setKey).toHaveBeenCalledOnce()
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
it('logs and continues when node-switchbot rejects the key', async () => {
|
|
43
|
+
const relay = device('relay-2')
|
|
44
|
+
relay.setKey.mockImplementation(() => {
|
|
45
|
+
throw new Error('bad key')
|
|
46
|
+
})
|
|
47
|
+
const c = client([relay])
|
|
48
|
+
c.setDeviceKey('relay-2', { encryptionKey: 'nope' })
|
|
49
|
+
await expect(c.getDevice('relay-2')).resolves.toBe(relay)
|
|
50
|
+
expect(logger.warn).toHaveBeenCalled()
|
|
51
|
+
})
|
|
52
|
+
|
|
53
|
+
it('leaves devices without setKey (node-switchbot 5.x) alone', async () => {
|
|
54
|
+
const plain = { id: 'plain' }
|
|
55
|
+
const c = client([plain])
|
|
56
|
+
c.setDeviceKey('plain', { encryptionKey: '2'.repeat(32) })
|
|
57
|
+
await expect(c.getDevice('plain')).resolves.toBe(plain)
|
|
58
|
+
})
|
|
59
|
+
})
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest'
|
|
2
|
+
|
|
3
|
+
import { SwitchBotMatterPlatform } from '../../src/SwitchBotMatterPlatform.js'
|
|
4
|
+
|
|
5
|
+
function makeApi(failFor?: string) {
|
|
6
|
+
const registered = new Set<string>()
|
|
7
|
+
const matter = {
|
|
8
|
+
uuid: { generate: (id: string) => `uuid-${id}` },
|
|
9
|
+
deviceTypes: {},
|
|
10
|
+
registerPlatformAccessories: vi.fn(async (_p: string, _n: string, accessories: any[]) => {
|
|
11
|
+
for (const a of accessories) {
|
|
12
|
+
if (a.UUID === failFor) {
|
|
13
|
+
throw new Error('boom')
|
|
14
|
+
}
|
|
15
|
+
if (registered.has(a.UUID)) {
|
|
16
|
+
throw new Error(`Matter accessory with UUID ${a.UUID} is already registered`)
|
|
17
|
+
}
|
|
18
|
+
registered.add(a.UUID)
|
|
19
|
+
}
|
|
20
|
+
}),
|
|
21
|
+
updatePlatformAccessories: vi.fn(async () => {}),
|
|
22
|
+
unregisterPlatformAccessories: vi.fn(async () => {}),
|
|
23
|
+
}
|
|
24
|
+
return { api: { matter, on: vi.fn() } as any, matter }
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function created(name: string) {
|
|
28
|
+
return {
|
|
29
|
+
created: { createAccessory: async () => ({ name, clusters: { onOff: { onOff: false } } }) },
|
|
30
|
+
d: { id: name, name },
|
|
31
|
+
type: 'plug',
|
|
32
|
+
useMatter: true,
|
|
33
|
+
matterAvailable: true,
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const log = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn(), success: vi.fn() } as any
|
|
38
|
+
|
|
39
|
+
describe('matter accessory registration', () => {
|
|
40
|
+
it('updates instead of re-registering on a second load (config reload)', async () => {
|
|
41
|
+
const { api, matter } = makeApi()
|
|
42
|
+
const platform = new SwitchBotMatterPlatform(log, { platform: 'SwitchBot' } as any, api)
|
|
43
|
+
await platform.registerMatterAccessories([created('a')])
|
|
44
|
+
await platform.registerMatterAccessories([created('a')])
|
|
45
|
+
expect(matter.registerPlatformAccessories).toHaveBeenCalledTimes(1)
|
|
46
|
+
expect(matter.updatePlatformAccessories).toHaveBeenCalledTimes(1)
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
it('registers cache-restored accessories so handlers attach', async () => {
|
|
50
|
+
const { api, matter } = makeApi()
|
|
51
|
+
const platform = new SwitchBotMatterPlatform(log, { platform: 'SwitchBot' } as any, api)
|
|
52
|
+
platform.configureMatterAccessory({ UUID: 'uuid-a', displayName: 'a', context: { deviceId: 'a' }, _restoredFromCache: true })
|
|
53
|
+
await platform.registerMatterAccessories([created('a')])
|
|
54
|
+
expect(matter.registerPlatformAccessories).toHaveBeenCalledTimes(1)
|
|
55
|
+
expect(matter.registerPlatformAccessories.mock.calls[0][2][0].handlers).toBeDefined()
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
it('one failing accessory does not stop the others', async () => {
|
|
59
|
+
const { api, matter } = makeApi('uuid-a')
|
|
60
|
+
const platform = new SwitchBotMatterPlatform(log, { platform: 'SwitchBot' } as any, api)
|
|
61
|
+
await platform.registerMatterAccessories([created('a'), created('b')])
|
|
62
|
+
const uuids = matter.registerPlatformAccessories.mock.calls.map(c => c[2][0].UUID)
|
|
63
|
+
expect(uuids).toEqual(['uuid-a', 'uuid-b'])
|
|
64
|
+
// 'a' failed, so it is registered (not updated) on the next attempt
|
|
65
|
+
await platform.registerMatterAccessories([created('a')])
|
|
66
|
+
expect(matter.registerPlatformAccessories).toHaveBeenCalledTimes(3)
|
|
67
|
+
})
|
|
68
|
+
})
|
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it, vi } from 'vitest'
|
|
2
|
-
|
|
3
|
-
import { CurtainDevice } from '../../src/devices/genericDevice'
|
|
4
|
-
|
|
5
|
-
describe('curtain BLE position', () => {
|
|
6
|
-
it('keeps a commanded position when an old advertisement reappears', async () => {
|
|
7
|
-
let advertisement = { position: 39 }
|
|
8
|
-
const nodeDevice = {
|
|
9
|
-
hasBLE: () => true,
|
|
10
|
-
getInfo: () => ({ bleServiceData: advertisement }),
|
|
11
|
-
}
|
|
12
|
-
const client = { getCachedDevice: () => nodeDevice }
|
|
13
|
-
const log = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }
|
|
14
|
-
const curtain = new CurtainDevice({ id: 'curtain', type: 'Curtain', log, blePollingEnabled: false }, { _client: client, log } as any)
|
|
15
|
-
const getState = vi.spyOn(curtain, 'getState')
|
|
16
|
-
vi.spyOn(curtain, 'setState').mockResolvedValue(true)
|
|
17
|
-
const characteristics = curtain.createHAPAccessory({}).services[0].characteristics
|
|
18
|
-
|
|
19
|
-
expect(await characteristics.CurrentPosition.get()).toBe(61)
|
|
20
|
-
await characteristics.TargetPosition.set(69)
|
|
21
|
-
expect(await characteristics.CurrentPosition.get()).toBe(69)
|
|
22
|
-
|
|
23
|
-
advertisement = { position: 39 }
|
|
24
|
-
expect(await characteristics.CurrentPosition.get()).toBe(69)
|
|
25
|
-
expect(await characteristics.TargetPosition.get()).toBe(69)
|
|
26
|
-
|
|
27
|
-
advertisement = { position: 31 }
|
|
28
|
-
expect(await characteristics.CurrentPosition.get()).toBe(69)
|
|
29
|
-
|
|
30
|
-
advertisement = { position: 39 }
|
|
31
|
-
expect(await characteristics.CurrentPosition.get()).toBe(69)
|
|
32
|
-
expect(getState).not.toHaveBeenCalled()
|
|
33
|
-
})
|
|
34
|
-
})
|