@switchbot/homebridge-switchbot 5.2.9-beta.0 → 5.2.9

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/config.schema.json +29 -0
  2. package/dist/SwitchBotMatterPlatform.js +1 -1
  3. package/dist/SwitchBotMatterPlatform.js.map +1 -1
  4. package/dist/deviceFactory.js +1 -1
  5. package/dist/deviceFactory.js.map +1 -1
  6. package/dist/devices/genericDevice.d.ts +2 -0
  7. package/dist/devices/genericDevice.d.ts.map +1 -1
  8. package/dist/devices/genericDevice.js +573 -123
  9. package/dist/devices/genericDevice.js.map +1 -1
  10. package/dist/homebridge-ui/endpoints/discovery.d.ts.map +1 -1
  11. package/dist/homebridge-ui/endpoints/discovery.js +2 -0
  12. package/dist/homebridge-ui/endpoints/discovery.js.map +1 -1
  13. package/dist/homebridge-ui/homebridge-ui/endpoints/discovery.js +2 -0
  14. package/dist/homebridge-ui/homebridge-ui/endpoints/discovery.js.map +1 -1
  15. package/dist/homebridge-ui/public/index.html +12 -2
  16. package/dist/homebridge-ui/public/js/advanced-settings.d.ts +4 -1
  17. package/dist/homebridge-ui/public/js/advanced-settings.d.ts.map +1 -1
  18. package/dist/homebridge-ui/public/js/advanced-settings.js +21 -11
  19. package/dist/homebridge-ui/public/js/advanced-settings.js.map +1 -1
  20. package/dist/homebridge-ui/public/js/advanced-settings.ts +23 -11
  21. package/dist/homebridge-ui/public/js/api.d.ts.map +1 -1
  22. package/dist/homebridge-ui/public/js/api.js +21 -7
  23. package/dist/homebridge-ui/public/js/api.js.map +1 -1
  24. package/dist/homebridge-ui/public/js/api.ts +21 -7
  25. package/dist/homebridge-ui/public/js/app.js +78 -20
  26. package/dist/homebridge-ui/public/js/app.js.map +2 -2
  27. package/dist/homebridge-ui/public/js/credentials.d.ts.map +1 -1
  28. package/dist/homebridge-ui/public/js/credentials.js +9 -3
  29. package/dist/homebridge-ui/public/js/credentials.js.map +1 -1
  30. package/dist/homebridge-ui/public/js/credentials.ts +9 -3
  31. package/dist/homebridge-ui/public/js/devices-delete.d.ts.map +1 -1
  32. package/dist/homebridge-ui/public/js/devices-delete.js +6 -2
  33. package/dist/homebridge-ui/public/js/devices-delete.js.map +1 -1
  34. package/dist/homebridge-ui/public/js/devices-delete.ts +6 -2
  35. package/dist/homebridge-ui/public/js/devices.d.ts.map +1 -1
  36. package/dist/homebridge-ui/public/js/devices.js +3 -1
  37. package/dist/homebridge-ui/public/js/devices.js.map +1 -1
  38. package/dist/homebridge-ui/public/js/devices.ts +3 -1
  39. package/dist/homebridge-ui/public/js/discovery.d.ts.map +1 -1
  40. package/dist/homebridge-ui/public/js/discovery.js +89 -25
  41. package/dist/homebridge-ui/public/js/discovery.js.map +1 -1
  42. package/dist/homebridge-ui/public/js/discovery.ts +89 -25
  43. package/dist/homebridge-ui/public/js/modals.d.ts.map +1 -1
  44. package/dist/homebridge-ui/public/js/modals.js +15 -5
  45. package/dist/homebridge-ui/public/js/modals.js.map +1 -1
  46. package/dist/homebridge-ui/public/js/modals.ts +15 -5
  47. package/dist/homebridge-ui/public/js/render.d.ts.map +1 -1
  48. package/dist/homebridge-ui/public/js/render.js +67 -17
  49. package/dist/homebridge-ui/public/js/render.js.map +1 -1
  50. package/dist/homebridge-ui/public/js/render.ts +67 -17
  51. package/dist/homebridge-ui/public/js/toast.d.ts.map +1 -1
  52. package/dist/homebridge-ui/public/js/toast.js +6 -2
  53. package/dist/homebridge-ui/public/js/toast.js.map +1 -1
  54. package/dist/homebridge-ui/public/js/toast.ts +6 -2
  55. package/dist/homebridge-ui/settings.js.map +1 -1
  56. package/dist/homebridge-ui/switchbotClient.js +4 -0
  57. package/dist/homebridge-ui/switchbotClient.js.map +1 -1
  58. package/dist/settings.d.ts +1 -0
  59. package/dist/settings.d.ts.map +1 -1
  60. package/dist/settings.js.map +1 -1
  61. package/dist/switchbotClient.d.ts +1 -0
  62. package/dist/switchbotClient.d.ts.map +1 -1
  63. package/dist/switchbotClient.js +4 -0
  64. package/dist/switchbotClient.js.map +1 -1
  65. package/docs/variables/default.html +1 -1
  66. package/package.json +9 -9
  67. package/src/SwitchBotMatterPlatform.ts +1 -1
  68. package/src/deviceFactory.ts +1 -1
  69. package/src/devices/genericDevice.ts +572 -134
  70. package/src/homebridge-ui/endpoints/discovery.ts +2 -0
  71. package/src/homebridge-ui/public/index.html +12 -2
  72. package/src/homebridge-ui/public/js/advanced-settings.ts +23 -11
  73. package/src/homebridge-ui/public/js/api.ts +21 -7
  74. package/src/homebridge-ui/public/js/credentials.ts +9 -3
  75. package/src/homebridge-ui/public/js/devices-delete.ts +6 -2
  76. package/src/homebridge-ui/public/js/devices.ts +3 -1
  77. package/src/homebridge-ui/public/js/discovery.ts +89 -25
  78. package/src/homebridge-ui/public/js/modals.ts +15 -5
  79. package/src/homebridge-ui/public/js/render.ts +67 -17
  80. package/src/homebridge-ui/public/js/toast.ts +6 -2
  81. package/src/settings.ts +1 -0
  82. package/src/switchbotClient.ts +5 -0
  83. package/test/client/node-switchbot-commands.spec.ts +44 -8
  84. package/test/client/switchbot-client-debounce.spec.ts +24 -3
  85. package/test/client/switchbot-client-discovery.spec.ts +26 -5
  86. package/test/client/switchbot-client-keys.spec.ts +30 -7
  87. package/test/client/switchbot-client-openapi.spec.ts +6 -1
  88. package/test/client/switchbotClient.spec.ts +30 -6
  89. package/test/device/bot-hap.spec.ts +131 -22
  90. package/test/device/curtain-ble-position.spec.ts +46 -0
  91. package/test/device/deviceBase.spec.ts +6 -1
  92. package/test/device/deviceFactory-edge.spec.ts +12 -2
  93. package/test/device/deviceFactory.spec.ts +6 -1
  94. package/test/device/fan-swing.spec.ts +9 -2
  95. package/test/device/genericDevice-blepoll.spec.ts +17 -3
  96. package/test/device/getstate-cache.spec.ts +37 -6
  97. package/test/device/getstate-returns-status.spec.ts +65 -13
  98. package/test/device/lock-users.spec.ts +24 -7
  99. package/test/device/matter-descriptors.spec.ts +6 -1
  100. package/test/device/matter-device-state.spec.ts +6 -1
  101. package/test/device/meter-battery.spec.ts +86 -14
  102. package/test/device/meter-co2.spec.ts +65 -10
  103. package/test/device/model-identities.spec.ts +6 -1
  104. package/test/device/water-detector-battery.spec.ts +19 -3
  105. package/test/device/water-detector-leak.spec.ts +6 -1
  106. package/test/helpers/matter-harness.ts +21 -4
  107. package/test/platform/accessory-restore.spec.ts +18 -3
  108. package/test/platform/hap-cache-restart.spec.ts +66 -13
  109. package/test/platform/matter-childbridge.spec.ts +16 -3
  110. package/test/platform/matter-integration.spec.ts +6 -1
  111. package/test/platform/matter-registration.spec.ts +47 -10
  112. package/test/platform/platform-edge.spec.ts +13 -3
  113. package/test/platform/platform.integration.spec.ts +16 -3
  114. package/test/utils/utils.spec.ts +42 -8
  115. package/.github/npm-version-script-esm.js +0 -103
@@ -24,6 +24,7 @@ export function registerDiscoveryEndpoint(server: HomebridgePluginUiServer) {
24
24
  enableRetry: true,
25
25
  enableCircuitBreaker: true,
26
26
  enableConnectionIntelligence: true,
27
+ logLevel: platform.nodeSwitchBotLogLevel,
27
28
  })
28
29
 
29
30
  await switchbot.discover({ timeout: 1000 })
@@ -70,6 +71,7 @@ export function registerDiscoveryEndpoint(server: HomebridgePluginUiServer) {
70
71
  enableRetry: true,
71
72
  enableCircuitBreaker: true,
72
73
  enableConnectionIntelligence: true,
74
+ logLevel: platform.nodeSwitchBotLogLevel,
73
75
  })
74
76
 
75
77
  const deviceMap = new Map<string, any>()
@@ -140,6 +140,17 @@
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>
143
154
  <div class="form-group">
144
155
  <label for="blePollingEnabled">
145
156
  <input type="checkbox" id="blePollingEnabled" /> Enable BLE Polling Fallback
@@ -204,7 +215,6 @@
204
215
  <input type="number" id="co2AbnormalThreshold" min="400" max="5000" step="1" value="1000" />
205
216
  <small>Meter Pro (CO2) only. At or above this level HomeKit reports carbon dioxide as detected. Default: 1000.</small>
206
217
  </div>
207
- <button type="button" id="saveAdvancedSettingsBtn">Save Advanced Settings</button>
208
218
  <div id="advancedSettingsStatus" style="margin-top: 8px; font-size: 12px;"></div>
209
219
  </form>
210
220
  </div>
@@ -213,4 +223,4 @@
213
223
  <script type="module" src="js/advanced-settings.js"></script>
214
224
  </body>
215
225
 
216
- </html>
226
+ </html>
@@ -27,6 +27,7 @@ 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)
30
31
  ;(document.getElementById('blePollingEnabled') as HTMLInputElement).checked = config.blePollingEnabled !== false
31
32
  ;(document.getElementById('blePollIntervalMs') as HTMLInputElement).value = String(config.blePollIntervalMs ?? 600000)
32
33
  ;(document.getElementById('co2AbnormalThreshold') as HTMLInputElement).value = String(config.co2AbnormalThreshold ?? 1000)
@@ -35,9 +36,9 @@ async function loadAdvancedSettings(): Promise<void> {
35
36
  }
36
37
  }
37
38
 
38
- async function saveAdvancedSettings(): Promise<void> {
39
+ async function syncAdvancedSettings(): Promise<void> {
39
40
  const status = document.getElementById('advancedSettingsStatus') as HTMLElement
40
- status.textContent = 'Saving...'
41
+ status.textContent = 'Updating pending settings...'
41
42
  try {
42
43
  if (typeof homebridge.getPluginConfig !== 'function') {
43
44
  throw new TypeError('homebridge.getPluginConfig is not available')
@@ -66,6 +67,7 @@ async function saveAdvancedSettings(): Promise<void> {
66
67
  config.enableMatter = (document.getElementById('enableMatter') as HTMLInputElement).checked
67
68
  config.preferMatter = (document.getElementById('preferMatter') as HTMLInputElement).checked
68
69
  config.enableBLE = (document.getElementById('enableBLE') as HTMLInputElement).checked
70
+ config.nodeSwitchBotLogLevel = Number((document.getElementById('nodeSwitchBotLogLevel') as HTMLSelectElement).value)
69
71
  config.blePollingEnabled = (document.getElementById('blePollingEnabled') as HTMLInputElement).checked
70
72
  config.blePollIntervalMs = Number((document.getElementById('blePollIntervalMs') as HTMLInputElement).value) || 600000
71
73
  config.co2AbnormalThreshold = Number((document.getElementById('co2AbnormalThreshold') as HTMLInputElement).value) || 1000
@@ -76,21 +78,31 @@ async function saveAdvancedSettings(): Promise<void> {
76
78
  } else {
77
79
  throw new TypeError('homebridge.updatePluginConfig is not available')
78
80
  }
79
- if (typeof homebridge.savePluginConfig === 'function') {
80
- await homebridge.savePluginConfig()
81
- }
82
- status.textContent = 'Settings saved!'
81
+ status.textContent = 'Changes ready. Click Save to apply them.'
83
82
  } catch (e: any) {
84
- status.textContent = `Failed to save: ${e && e.message ? e.message : e}`
83
+ status.textContent = `Failed to update settings: ${e && e.message
84
+ ? e.message
85
+ : e}`
86
+ throw e
85
87
  }
86
88
  }
87
89
 
90
+ let pendingUpdate: Promise<void> = Promise.resolve()
91
+ let latestChange = 0
92
+
93
+ function queueAdvancedSettingsUpdate(): void {
94
+ const change = ++latestChange
95
+ homebridge.disableSaveButton?.()
96
+ pendingUpdate = pendingUpdate.catch(() => {}).then(syncAdvancedSettings).then(() => {
97
+ if (change === latestChange) {
98
+ homebridge.enableSaveButton?.()
99
+ }
100
+ }).catch(() => {})
101
+ }
102
+
88
103
  document.addEventListener('DOMContentLoaded', () => {
89
104
  if (document.getElementById('advancedSettingsCard')) {
90
105
  loadAdvancedSettings()
91
- const btn = document.getElementById('saveAdvancedSettingsBtn')
92
- if (btn) {
93
- btn.onclick = saveAdvancedSettings
94
- }
106
+ document.getElementById('advancedSettingsForm')?.addEventListener('change', queueAdvancedSettingsUpdate)
95
107
  }
96
108
  })
@@ -10,13 +10,17 @@ export async function fetchDevices(): Promise<any[]> {
10
10
  throw new TypeError('Homebridge UI API not available')
11
11
  }
12
12
  const configArr = await homebridge.getPluginConfig()
13
- const config = Array.isArray(configArr) && configArr.length > 0 ? configArr.find(isSwitchBotPlatformConfig) : null
13
+ const config = Array.isArray(configArr) && configArr.length > 0
14
+ ? configArr.find(isSwitchBotPlatformConfig)
15
+ : null
14
16
  if (!config || !Array.isArray(config.devices)) {
15
17
  return []
16
18
  }
17
19
  return config.devices
18
20
  } catch (e) {
19
- const msg = e instanceof Error ? e.message : String(e)
21
+ const msg = e instanceof Error
22
+ ? e.message
23
+ : String(e)
20
24
  uiLog.error('Error fetching devices:', msg)
21
25
  return []
22
26
  }
@@ -195,7 +199,9 @@ export async function addDevice(
195
199
  throw new TypeError('Homebridge UI API not available')
196
200
  }
197
201
  const configArr = await homebridge.getPluginConfig()
198
- const idx = Array.isArray(configArr) ? configArr.findIndex(isSwitchBotPlatformConfig) : -1
202
+ const idx = Array.isArray(configArr)
203
+ ? configArr.findIndex(isSwitchBotPlatformConfig)
204
+ : -1
199
205
  if (idx === -1) {
200
206
  throw new Error('SwitchBot config not found')
201
207
  }
@@ -244,7 +250,9 @@ export async function addDevicesInBulk(
244
250
  }
245
251
 
246
252
  export function normalizeBulkAddDevicesResponse(resp: any): any {
247
- const payload = resp?.data && typeof resp.data === 'object' ? resp.data : resp
253
+ const payload = resp?.data && typeof resp.data === 'object'
254
+ ? resp.data
255
+ : resp
248
256
  const addedCount = Number(payload?.addedCount ?? payload?.added ?? 0)
249
257
  const skippedCount = Number(payload?.skippedCount ?? payload?.skipped ?? 0)
250
258
  const updatedCount = Number(payload?.updatedCount ?? payload?.updated ?? 0)
@@ -275,7 +283,9 @@ export async function updateDevice(
275
283
  throw new TypeError('Homebridge UI API not available')
276
284
  }
277
285
  const configArr = await homebridge.getPluginConfig()
278
- const idx = Array.isArray(configArr) ? configArr.findIndex(isSwitchBotPlatformConfig) : -1
286
+ const idx = Array.isArray(configArr)
287
+ ? configArr.findIndex(isSwitchBotPlatformConfig)
288
+ : -1
279
289
  if (idx === -1) {
280
290
  throw new Error('SwitchBot config not found')
281
291
  }
@@ -309,7 +319,9 @@ export async function deleteDevice(deviceId: string): Promise<any> {
309
319
  throw new TypeError('Homebridge UI API not available')
310
320
  }
311
321
  const configArr = await homebridge.getPluginConfig()
312
- const idx = Array.isArray(configArr) ? configArr.findIndex(isSwitchBotPlatformConfig) : -1
322
+ const idx = Array.isArray(configArr)
323
+ ? configArr.findIndex(isSwitchBotPlatformConfig)
324
+ : -1
313
325
  if (idx === -1) {
314
326
  throw new Error('SwitchBot config not found')
315
327
  }
@@ -339,7 +351,9 @@ export async function deleteAllDevices(): Promise<any> {
339
351
  }
340
352
  const configArr = await homebridge.getPluginConfig()
341
353
  // Find or create the SwitchBot config block
342
- let idx = Array.isArray(configArr) ? configArr.findIndex(isSwitchBotPlatformConfig) : -1
354
+ let idx = Array.isArray(configArr)
355
+ ? configArr.findIndex(isSwitchBotPlatformConfig)
356
+ : -1
343
357
  if (idx === -1) {
344
358
  // If not found, create a new config block for SwitchBot
345
359
  const newBlock = { platform: 'SwitchBot', devices: [] }
@@ -9,7 +9,9 @@ export async function loadCredentialStatus(): Promise<void> {
9
9
  return
10
10
  }
11
11
  const configArr = await homebridge.getPluginConfig()
12
- const config = Array.isArray(configArr) && configArr.length > 0 ? configArr[0] : {}
12
+ const config = Array.isArray(configArr) && configArr.length > 0
13
+ ? configArr[0]
14
+ : {}
13
15
  const token = config.openApiToken || ''
14
16
  const secret = config.openApiSecret || ''
15
17
 
@@ -94,9 +96,13 @@ export async function saveCredentials(): Promise<void> {
94
96
  }, 3000)
95
97
  } catch (e) {
96
98
  uiLog.error('Save error:', e)
97
- saveStatus.textContent = `Error: ${e instanceof Error ? e.message : 'Failed to save'}`
99
+ saveStatus.textContent = `Error: ${e instanceof Error
100
+ ? e.message
101
+ : 'Failed to save'}`
98
102
  saveStatus.classList.add('error')
99
- toastError(e instanceof Error ? e.message : 'Failed to save credentials')
103
+ toastError(e instanceof Error
104
+ ? e.message
105
+ : 'Failed to save credentials')
100
106
  } finally {
101
107
  hideBusyUi()
102
108
  saveBtn.disabled = false
@@ -101,7 +101,9 @@ export async function deleteDeviceFromConfig(deviceId: string, deviceName: strin
101
101
  toastSuccess(`Device "${deviceName || deviceId}" deleted successfully`)
102
102
  } catch (e) {
103
103
  uiLog.error('Delete error:', e)
104
- toastError(e instanceof Error ? e.message : 'Failed to delete device')
104
+ toastError(e instanceof Error
105
+ ? e.message
106
+ : 'Failed to delete device')
105
107
  } finally {
106
108
  hideBusyUi()
107
109
  }
@@ -220,7 +222,9 @@ export async function deleteAllDevicesFromConfig(): Promise<void> {
220
222
  toastSuccess(`Removed ${deletedCount} device(s) successfully`)
221
223
  } catch (e) {
222
224
  uiLog.error('Delete all error:', e)
223
- toastError(e instanceof Error ? e.message : 'Failed to delete all devices')
225
+ toastError(e instanceof Error
226
+ ? e.message
227
+ : 'Failed to delete all devices')
224
228
  } finally {
225
229
  hideBusyUi()
226
230
  }
@@ -74,7 +74,9 @@ export async function addDeviceToConfig(device: any, options: { refresh?: boolea
74
74
 
75
75
  return { added: !alreadyExists }
76
76
  } catch (e) {
77
- const msg = e instanceof Error ? e.message : String(e)
77
+ const msg = e instanceof Error
78
+ ? e.message
79
+ : String(e)
78
80
  uiLog.error('Add device error:', msg)
79
81
  const status = document.getElementById('discoverStatus')
80
82
  if (status) {
@@ -56,7 +56,9 @@ function mergeDiscoveredDevices(existingDevices: any[], incomingDevices: any[]):
56
56
  }
57
57
  }
58
58
 
59
- const merged = [...deviceMap.values()]
59
+ const merged = [
60
+ ...deviceMap.values(),
61
+ ]
60
62
  // Log merged device structure for debugging
61
63
  if (merged.length > 0) {
62
64
  console.warn('[SwitchBot][Discovery][mergeDiscoveredDevices] Merged device sample:', merged[0])
@@ -92,7 +94,10 @@ interface DiscoveryCachePayload {
92
94
 
93
95
  function setDiscoveryCache(devices: any[]): void {
94
96
  try {
95
- const payload: DiscoveryCachePayload = { timestamp: Date.now(), devices }
97
+ const payload: DiscoveryCachePayload = {
98
+ timestamp: Date.now(),
99
+ devices,
100
+ }
96
101
  localStorage.setItem(DISCOVERY_CACHE_KEY, JSON.stringify(payload))
97
102
  } catch (_e) {
98
103
  // Ignore storage errors
@@ -131,7 +136,9 @@ function getDiscoveryAutoRefreshSeconds(): number {
131
136
  try {
132
137
  const stored = localStorage.getItem(DISCOVERY_AUTO_REFRESH_KEY)
133
138
  const value = Number(stored || 0)
134
- return Number.isFinite(value) && value >= 0 ? value : 0
139
+ return Number.isFinite(value) && value >= 0
140
+ ? value
141
+ : 0
135
142
  } catch (_e) {
136
143
  return 0
137
144
  }
@@ -367,7 +374,9 @@ function getDiscoveryGroupExpandedState(): Record<string, boolean> {
367
374
  return {}
368
375
  }
369
376
  const parsed = JSON.parse(stored)
370
- return typeof parsed === 'object' && parsed ? parsed : {}
377
+ return typeof parsed === 'object' && parsed
378
+ ? parsed
379
+ : {}
371
380
  } catch (_e) {
372
381
  return {}
373
382
  }
@@ -418,7 +427,18 @@ export async function discoverDevices(): Promise<void> {
418
427
  return
419
428
  }
420
429
 
421
- const spinnerFrames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
430
+ const spinnerFrames = [
431
+ '⠋',
432
+ '⠙',
433
+ '⠹',
434
+ '⠸',
435
+ '⠼',
436
+ '⠴',
437
+ '⠦',
438
+ '⠧',
439
+ '⠇',
440
+ '⠏',
441
+ ]
422
442
  let spinnerIndex = 0
423
443
  const startedAt = Date.now()
424
444
  let phaseStartedAt = startedAt
@@ -486,7 +506,9 @@ export async function discoverDevices(): Promise<void> {
486
506
  throw new TypeError('homebridge.getPluginConfig is not available')
487
507
  }
488
508
  const configArr = await homebridge.getPluginConfig()
489
- const platformIdx = Array.isArray(configArr) ? configArr.findIndex(c => (c.platform || c.name || '').toLowerCase().includes('switchbot')) : -1
509
+ const platformIdx = Array.isArray(configArr)
510
+ ? configArr.findIndex(c => (c.platform || c.name || '').toLowerCase().includes('switchbot'))
511
+ : -1
490
512
  if (platformIdx === -1) {
491
513
  throw new Error('SwitchBot platform config not found')
492
514
  }
@@ -594,9 +616,15 @@ export async function discoverDevices(): Promise<void> {
594
616
  filterBtn.style.fontSize = '11px'
595
617
  filterBtn.style.borderRadius = '3px'
596
618
  filterBtn.style.cursor = 'pointer'
597
- filterBtn.style.border = preferences.connectionType === option.value ? '2px solid #007AFF' : '1px solid #ccc'
598
- filterBtn.style.backgroundColor = preferences.connectionType === option.value ? '#f0f7ff' : '#fff'
599
- filterBtn.style.color = preferences.connectionType === option.value ? '#1d4ed8' : '#374151'
619
+ filterBtn.style.border = preferences.connectionType === option.value
620
+ ? '2px solid #007AFF'
621
+ : '1px solid #ccc'
622
+ filterBtn.style.backgroundColor = preferences.connectionType === option.value
623
+ ? '#f0f7ff'
624
+ : '#fff'
625
+ filterBtn.style.color = preferences.connectionType === option.value
626
+ ? '#1d4ed8'
627
+ : '#374151'
600
628
 
601
629
  filterBtn.onclick = () => {
602
630
  preferences.connectionType = option.value
@@ -786,7 +814,9 @@ export async function discoverDevices(): Promise<void> {
786
814
  }
787
815
  const addedCount = bulkResult?.addedCount ?? bulkResult?.data?.addedCount ?? 0
788
816
  const skippedCount = bulkResult?.skippedCount ?? bulkResult?.data?.skippedCount ?? 0
789
- toastSuccess(`Added ${addedCount} device(s)${skippedCount > 0 ? ` (${skippedCount} skipped)` : ''}`)
817
+ toastSuccess(`Added ${addedCount} device(s)${skippedCount > 0
818
+ ? ` (${skippedCount} skipped)`
819
+ : ''}`)
790
820
  await loadConfiguredDevices()
791
821
  selectedIds.clear()
792
822
  addSelectedBtn.disabled = true
@@ -794,7 +824,9 @@ export async function discoverDevices(): Promise<void> {
794
824
  await updateDiscoveryView(discoveredDevices, preferences, groupBy, hideAdded, selectedIds)
795
825
  } catch (e) {
796
826
  uiLog.error('Batch add error:', e)
797
- toastError(e instanceof Error ? e.message : 'Failed to add devices')
827
+ toastError(e instanceof Error
828
+ ? e.message
829
+ : 'Failed to add devices')
798
830
  addSelectedBtn.disabled = false
799
831
  addSelectedBtn.textContent = 'Add Selected'
800
832
  } finally {
@@ -823,7 +855,9 @@ export async function discoverDevices(): Promise<void> {
823
855
  await updateDiscoveryView(discoveredDevices, preferences, groupBy, hideAdded, selectedIds)
824
856
  } catch (e) {
825
857
  uiLog.error('Batch enable error:', e)
826
- toastError(e instanceof Error ? e.message : 'Failed to enable devices')
858
+ toastError(e instanceof Error
859
+ ? e.message
860
+ : 'Failed to enable devices')
827
861
  enableSelectedBtn.disabled = false
828
862
  enableSelectedBtn.textContent = 'Enable Selected'
829
863
  } finally {
@@ -852,7 +886,9 @@ export async function discoverDevices(): Promise<void> {
852
886
  await updateDiscoveryView(discoveredDevices, preferences, groupBy, hideAdded, selectedIds)
853
887
  } catch (e) {
854
888
  uiLog.error('Batch disable error:', e)
855
- toastError(e instanceof Error ? e.message : 'Failed to disable devices')
889
+ toastError(e instanceof Error
890
+ ? e.message
891
+ : 'Failed to disable devices')
856
892
  disableSelectedBtn.disabled = false
857
893
  disableSelectedBtn.textContent = 'Disable Selected'
858
894
  } finally {
@@ -1027,9 +1063,13 @@ export async function discoverDevices(): Promise<void> {
1027
1063
  = bulkResult?.skippedCount
1028
1064
  ?? bulkResult?.data?.skippedCount
1029
1065
  ?? 0
1030
- status.textContent = `✓ Added ${addedCount} device(s)${skippedCount > 0 ? ` (${skippedCount} skipped)` : ''}`
1066
+ status.textContent = `✓ Added ${addedCount} device(s)${skippedCount > 0
1067
+ ? ` (${skippedCount} skipped)`
1068
+ : ''}`
1031
1069
  if (addedCount > 0) {
1032
- toastSuccess(`Added ${addedCount} device(s)${skippedCount > 0 ? ` (${skippedCount} skipped)` : ''}`)
1070
+ toastSuccess(`Added ${addedCount} device(s)${skippedCount > 0
1071
+ ? ` (${skippedCount} skipped)`
1072
+ : ''}`)
1033
1073
  } else if (skippedCount > 0) {
1034
1074
  toastWarning(`No new devices were added (${skippedCount} skipped)`)
1035
1075
  }
@@ -1052,9 +1092,13 @@ export async function discoverDevices(): Promise<void> {
1052
1092
  }
1053
1093
  } catch (e) {
1054
1094
  uiLog.error('Bulk add error:', e)
1055
- status.textContent = `✗ Error: ${e instanceof Error ? e.message : 'Failed to add devices'}`
1095
+ status.textContent = `✗ Error: ${e instanceof Error
1096
+ ? e.message
1097
+ : 'Failed to add devices'}`
1056
1098
  status.classList.add('error')
1057
- toastError(e instanceof Error ? e.message : 'Failed to add devices')
1099
+ toastError(e instanceof Error
1100
+ ? e.message
1101
+ : 'Failed to add devices')
1058
1102
  }
1059
1103
 
1060
1104
  // Refresh the configured devices list
@@ -1068,9 +1112,13 @@ export async function discoverDevices(): Promise<void> {
1068
1112
  updateLastScannedStatus()
1069
1113
  } catch (e) {
1070
1114
  uiLog.error('Discovery error:', e)
1071
- status.textContent = `Error: ${e instanceof Error ? e.message : 'Discovery failed'}`
1115
+ status.textContent = `Error: ${e instanceof Error
1116
+ ? e.message
1117
+ : 'Discovery failed'}`
1072
1118
  status.classList.add('error')
1073
- toastError(e instanceof Error ? e.message : 'Discovery failed')
1119
+ toastError(e instanceof Error
1120
+ ? e.message
1121
+ : 'Discovery failed')
1074
1122
  list.style.display = 'none'
1075
1123
  } finally {
1076
1124
  clearInterval(progressTimer)
@@ -1144,7 +1192,9 @@ async function updateDiscoveryView(
1144
1192
 
1145
1193
  const getHubGroup = (device: any): string => {
1146
1194
  const hub = String(device?.hubDeviceId || '').trim()
1147
- return hub ? `Hub ${hub}` : 'No Hub'
1195
+ return hub
1196
+ ? `Hub ${hub}`
1197
+ : 'No Hub'
1148
1198
  }
1149
1199
 
1150
1200
  const getTypeGroup = (device: any): string => {
@@ -1168,13 +1218,27 @@ async function updateDiscoveryView(
1168
1218
 
1169
1219
  let orderedGroups: string[] = []
1170
1220
  if (groupBy === 'hub') {
1171
- const hubGroups = [...groupedDevices.keys()].filter(group => group !== 'No Hub').sort((a, b) => a.localeCompare(b))
1172
- orderedGroups = groupedDevices.has('No Hub') ? [...hubGroups, 'No Hub'] : hubGroups
1221
+ const hubGroups = [
1222
+ ...groupedDevices.keys(),
1223
+ ].filter(group => group !== 'No Hub').sort((a, b) => a.localeCompare(b))
1224
+ orderedGroups = groupedDevices.has('No Hub')
1225
+ ? [...hubGroups, 'No Hub']
1226
+ : hubGroups
1173
1227
  } else if (groupBy === 'type') {
1174
- const typeGroups = [...groupedDevices.keys()].filter(group => group !== 'Unknown Type').sort((a, b) => a.localeCompare(b))
1175
- orderedGroups = groupedDevices.has('Unknown Type') ? [...typeGroups, 'Unknown Type'] : typeGroups
1228
+ const typeGroups = [
1229
+ ...groupedDevices.keys(),
1230
+ ].filter(group => group !== 'Unknown Type').sort((a, b) => a.localeCompare(b))
1231
+ orderedGroups = groupedDevices.has('Unknown Type')
1232
+ ? [...typeGroups, 'Unknown Type']
1233
+ : typeGroups
1176
1234
  } else {
1177
- const groupOrder = ['Both', 'BLE', 'OpenAPI', 'IR', 'Unknown']
1235
+ const groupOrder = [
1236
+ 'Both',
1237
+ 'BLE',
1238
+ 'OpenAPI',
1239
+ 'IR',
1240
+ 'Unknown',
1241
+ ]
1178
1242
  orderedGroups = groupOrder.filter(group => groupedDevices.has(group))
1179
1243
  }
1180
1244
 
@@ -149,7 +149,11 @@ 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.charAt(0).toUpperCase() + val.slice(1)
152
+ opt.text = val === 'ble'
153
+ ? 'BLE'
154
+ : val === 'openapi'
155
+ ? 'OpenAPI'
156
+ : 'Auto'
153
157
  opt.selected = (device.connectionPreference || 'auto') === val
154
158
  connectionPrefSelect.appendChild(opt)
155
159
  })
@@ -496,7 +500,7 @@ export async function editDevice(device: any): Promise<void> {
496
500
 
497
501
  const nameInput = document.createElement('input')
498
502
  nameInput.type = 'text'
499
- nameInput.value = device.name || device.id
503
+ nameInput.value = device.configDeviceName || device.name || ''
500
504
  nameInput.style.width = '100%'
501
505
  nameInput.style.marginBottom = '12px'
502
506
  nameInput.style.padding = '8px 10px'
@@ -568,7 +572,11 @@ export async function editDevice(device: any): Promise<void> {
568
572
  ;['auto', 'ble', 'openapi'].forEach((val) => {
569
573
  const opt = document.createElement('option')
570
574
  opt.value = val
571
- opt.text = val.charAt(0).toUpperCase() + val.slice(1)
575
+ opt.text = val === 'ble'
576
+ ? 'BLE'
577
+ : val === 'openapi'
578
+ ? 'OpenAPI'
579
+ : 'Auto'
572
580
  opt.selected = (device.connectionPreference || 'auto') === val
573
581
  connectionPrefSelect.appendChild(opt)
574
582
  })
@@ -670,7 +678,7 @@ export async function editDevice(device: any): Promise<void> {
670
678
  const { renderDeviceList } = await import('./render.js')
671
679
 
672
680
  const params = {
673
- deviceId: device.id,
681
+ deviceId: device.deviceId,
674
682
  configDeviceName: nameInput.value || undefined,
675
683
  configDeviceType: typeSelect.value,
676
684
  connectionPreference: connectionPrefSelect.value,
@@ -723,7 +731,9 @@ export async function editDevice(device: any): Promise<void> {
723
731
  div.remove()
724
732
  } catch (e) {
725
733
  uiLog.error('Update error:', e)
726
- errorMessage.textContent = `Error: ${e instanceof Error ? e.message : 'Failed to update device'}`
734
+ errorMessage.textContent = `Error: ${e instanceof Error
735
+ ? e.message
736
+ : 'Failed to update device'}`
727
737
  errorMessage.style.display = 'block'
728
738
  }
729
739
  }
@@ -240,7 +240,9 @@ function createConnectionTestControls(device: any): HTMLElement {
240
240
  status.textContent = `✓ ${method} · ${measuredLatency}ms`
241
241
  status.style.color = '#16a34a'
242
242
  } else {
243
- const detail = result?.message ? ` · ${result.message}` : ''
243
+ const detail = result?.message
244
+ ? ` · ${result.message}`
245
+ : ''
244
246
  status.textContent = `✗ Failed · ${measuredLatency}ms${detail}`
245
247
  status.style.color = '#dc2626'
246
248
  }
@@ -264,7 +266,9 @@ function formatLastSeen(value: any): string {
264
266
  }
265
267
  try {
266
268
  const date = new Date(value)
267
- return Number.isNaN(date.getTime()) ? String(value) : date.toLocaleString()
269
+ return Number.isNaN(date.getTime())
270
+ ? String(value)
271
+ : date.toLocaleString()
268
272
  } catch (_e) {
269
273
  return String(value)
270
274
  }
@@ -310,16 +314,52 @@ export function renderDeviceDetailsPanel(device: any): HTMLElement {
310
314
  }
311
315
 
312
316
  const rows: Array<{ label: string, value: string, copyable?: boolean }> = [
313
- { label: 'Name', value: String(device?.name || device?.configDeviceName || 'N/A') },
314
- { label: 'Device ID', value: String(device?.id || device?.deviceId || 'N/A'), copyable: !!(device?.id || device?.deviceId) },
315
- { label: 'MAC Address', value: String(device?.address || 'N/A'), copyable: !!device?.address },
316
- { label: 'Device Type', value: String(device?.type || device?.configDeviceType || 'N/A') },
317
- { label: 'Model', value: String(device?.model || 'N/A') },
318
- { label: 'Hub ID', value: String(device?.hubDeviceId || 'N/A') },
319
- { label: 'Battery', value: device?.battery !== undefined && device?.battery !== null ? `${device.battery}%` : 'N/A' },
320
- { label: 'Firmware', value: String(device?.version || device?.firmware || 'N/A') },
321
- { label: 'Cloud Service', value: device?.enabled === false ? 'Disabled' : 'Enabled' },
322
- { label: 'Last Seen', value: formatLastSeen(device?.lastSeen || device?.lastseen || device?.updatedAt) },
317
+ {
318
+ label: 'Name',
319
+ value: String(device?.name || device?.configDeviceName || 'N/A'),
320
+ },
321
+ {
322
+ label: 'Device ID',
323
+ value: String(device?.id || device?.deviceId || 'N/A'),
324
+ copyable: !!(device?.id || device?.deviceId),
325
+ },
326
+ {
327
+ label: 'MAC Address',
328
+ value: String(device?.address || 'N/A'),
329
+ copyable: !!device?.address,
330
+ },
331
+ {
332
+ label: 'Device Type',
333
+ value: String(device?.type || device?.configDeviceType || 'N/A'),
334
+ },
335
+ {
336
+ label: 'Model',
337
+ value: String(device?.model || 'N/A'),
338
+ },
339
+ {
340
+ label: 'Hub ID',
341
+ value: String(device?.hubDeviceId || 'N/A'),
342
+ },
343
+ {
344
+ label: 'Battery',
345
+ value: device?.battery !== undefined && device?.battery !== null
346
+ ? `${device.battery}%`
347
+ : 'N/A',
348
+ },
349
+ {
350
+ label: 'Firmware',
351
+ value: String(device?.version || device?.firmware || 'N/A'),
352
+ },
353
+ {
354
+ label: 'Cloud Service',
355
+ value: device?.enabled === false
356
+ ? 'Disabled'
357
+ : 'Enabled',
358
+ },
359
+ {
360
+ label: 'Last Seen',
361
+ value: formatLastSeen(device?.lastSeen || device?.lastseen || device?.updatedAt),
362
+ },
323
363
  ]
324
364
 
325
365
  for (const row of rows) {
@@ -497,7 +537,9 @@ export function renderDeviceDetailsPanel(device: any): HTMLElement {
497
537
  value.style.overflowWrap = 'anywhere'
498
538
  value.style.wordBreak = 'break-word'
499
539
  value.style.textAlign = 'right'
500
- value.textContent = typeof device[key] === 'object' ? JSON.stringify(device[key]) : String(device[key])
540
+ value.textContent = typeof device[key] === 'object'
541
+ ? JSON.stringify(device[key])
542
+ : String(device[key])
501
543
 
502
544
  line.appendChild(label)
503
545
  line.appendChild(value)
@@ -671,7 +713,9 @@ export async function renderDiscoveredDevices(
671
713
  = d.battery < 10
672
714
  ? 'background: #dc2626; color: white; padding: 1px 6px; border-radius: 3px; font-size: 10px; font-weight: 600; margin-left: 6px;'
673
715
  : 'background: #fbbf24; color: #111; padding: 1px 6px; border-radius: 3px; font-size: 10px; font-weight: 600; margin-left: 6px;'
674
- batteryWarn.title = d.battery < 10 ? 'Battery critically low' : 'Battery low'
716
+ batteryWarn.title = d.battery < 10
717
+ ? 'Battery critically low'
718
+ : 'Battery low'
675
719
  nameContainer.appendChild(batteryWarn)
676
720
  }
677
721
 
@@ -1012,9 +1056,15 @@ export function renderDeviceList(list: any[]): void {
1012
1056
 
1013
1057
  const deviceIdentifier = d.deviceId || d.id
1014
1058
  const id = `ID: ${deviceIdentifier}`
1015
- const typeText = d.configDeviceType || d.type ? `Type: ${d.configDeviceType || d.type}` : ''
1016
- const connText = d.connectionPreference ? `Conn: ${d.connectionPreference}` : ''
1017
- const roomText = d.room ? `Room: ${d.room}` : ''
1059
+ const typeText = d.configDeviceType || d.type
1060
+ ? `Type: ${d.configDeviceType || d.type}`
1061
+ : ''
1062
+ const connText = d.connectionPreference
1063
+ ? `Conn: ${d.connectionPreference}`
1064
+ : ''
1065
+ const roomText = d.room
1066
+ ? `Room: ${d.room}`
1067
+ : ''
1018
1068
  meta.textContent = [id, typeText, connText, roomText].filter(Boolean).join(' | ')
1019
1069
 
1020
1070
  info.appendChild(nameContainer)