@switchbot/homebridge-switchbot 5.0.0-beta.107 → 5.0.0-beta.109

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 (148) hide show
  1. package/TODO.md +564 -0
  2. package/config.schema.json +100 -25
  3. package/dist/device-types.d.ts +15 -0
  4. package/dist/device-types.d.ts.map +1 -0
  5. package/dist/device-types.js +145 -0
  6. package/dist/device-types.js.map +1 -0
  7. package/dist/deviceFactory.d.ts +1 -1
  8. package/dist/deviceFactory.d.ts.map +1 -1
  9. package/dist/deviceFactory.js +55 -17
  10. package/dist/deviceFactory.js.map +1 -1
  11. package/dist/devices/genericDevice.d.ts +1 -1
  12. package/dist/devices/genericDevice.d.ts.map +1 -1
  13. package/dist/devices/genericDevice.js +4 -2
  14. package/dist/devices/genericDevice.js.map +1 -1
  15. package/dist/homebridge-ui/endpoints/config.d.ts +6 -0
  16. package/dist/homebridge-ui/endpoints/config.d.ts.map +1 -0
  17. package/dist/homebridge-ui/endpoints/config.js +73 -0
  18. package/dist/homebridge-ui/endpoints/config.js.map +1 -0
  19. package/dist/homebridge-ui/endpoints/credentials.d.ts +6 -0
  20. package/dist/homebridge-ui/endpoints/credentials.d.ts.map +1 -0
  21. package/dist/homebridge-ui/endpoints/credentials.js +65 -0
  22. package/dist/homebridge-ui/endpoints/credentials.js.map +1 -0
  23. package/dist/homebridge-ui/endpoints/devices.d.ts +6 -0
  24. package/dist/homebridge-ui/endpoints/devices.d.ts.map +1 -0
  25. package/dist/homebridge-ui/endpoints/devices.js +285 -0
  26. package/dist/homebridge-ui/endpoints/devices.js.map +1 -0
  27. package/dist/homebridge-ui/endpoints/discovery.d.ts +7 -0
  28. package/dist/homebridge-ui/endpoints/discovery.d.ts.map +1 -0
  29. package/dist/homebridge-ui/endpoints/discovery.js +171 -0
  30. package/dist/homebridge-ui/endpoints/discovery.js.map +1 -0
  31. package/dist/homebridge-ui/public/index.html +144 -588
  32. package/dist/homebridge-ui/public/js/api.d.ts +15 -0
  33. package/dist/homebridge-ui/public/js/api.d.ts.map +1 -0
  34. package/dist/homebridge-ui/public/js/api.js +164 -0
  35. package/dist/homebridge-ui/public/js/api.js.map +1 -0
  36. package/dist/homebridge-ui/public/js/api.ts +189 -0
  37. package/dist/homebridge-ui/public/js/app.d.ts +2 -0
  38. package/dist/homebridge-ui/public/js/app.d.ts.map +1 -0
  39. package/dist/homebridge-ui/public/js/app.js +1069 -0
  40. package/dist/homebridge-ui/public/js/app.js.map +7 -0
  41. package/dist/homebridge-ui/public/js/app.ts +21 -0
  42. package/dist/homebridge-ui/public/js/constants.d.ts +2 -0
  43. package/dist/homebridge-ui/public/js/constants.d.ts.map +1 -0
  44. package/dist/homebridge-ui/public/js/constants.js +2 -0
  45. package/dist/homebridge-ui/public/js/constants.js.map +1 -0
  46. package/dist/homebridge-ui/public/js/constants.ts +1 -0
  47. package/dist/homebridge-ui/public/js/credentials.d.ts +3 -0
  48. package/dist/homebridge-ui/public/js/credentials.d.ts.map +1 -0
  49. package/dist/homebridge-ui/public/js/credentials.js +96 -0
  50. package/dist/homebridge-ui/public/js/credentials.js.map +1 -0
  51. package/dist/homebridge-ui/public/js/credentials.ts +100 -0
  52. package/dist/homebridge-ui/public/js/devices-delete.d.ts +2 -0
  53. package/dist/homebridge-ui/public/js/devices-delete.d.ts.map +1 -0
  54. package/dist/homebridge-ui/public/js/devices-delete.js +99 -0
  55. package/dist/homebridge-ui/public/js/devices-delete.js.map +1 -0
  56. package/dist/homebridge-ui/public/js/devices-delete.ts +113 -0
  57. package/dist/homebridge-ui/public/js/devices.d.ts +8 -0
  58. package/dist/homebridge-ui/public/js/devices.d.ts.map +1 -0
  59. package/dist/homebridge-ui/public/js/devices.js +71 -0
  60. package/dist/homebridge-ui/public/js/devices.js.map +1 -0
  61. package/dist/homebridge-ui/public/js/devices.ts +78 -0
  62. package/dist/homebridge-ui/public/js/discovery.d.ts +3 -0
  63. package/dist/homebridge-ui/public/js/discovery.d.ts.map +1 -0
  64. package/dist/homebridge-ui/public/js/discovery.js +107 -0
  65. package/dist/homebridge-ui/public/js/discovery.js.map +1 -0
  66. package/dist/homebridge-ui/public/js/discovery.ts +123 -0
  67. package/dist/homebridge-ui/public/js/logger.d.ts +6 -0
  68. package/dist/homebridge-ui/public/js/logger.d.ts.map +1 -0
  69. package/dist/homebridge-ui/public/js/logger.js +12 -0
  70. package/dist/homebridge-ui/public/js/logger.js.map +1 -0
  71. package/dist/homebridge-ui/public/js/logger.ts +11 -0
  72. package/dist/homebridge-ui/public/js/modal.d.ts +5 -0
  73. package/dist/homebridge-ui/public/js/modal.d.ts.map +1 -0
  74. package/dist/homebridge-ui/public/js/modal.js +26 -0
  75. package/dist/homebridge-ui/public/js/modal.js.map +1 -0
  76. package/dist/homebridge-ui/public/js/modal.ts +28 -0
  77. package/dist/homebridge-ui/public/js/modals.d.ts +2 -0
  78. package/dist/homebridge-ui/public/js/modals.d.ts.map +1 -0
  79. package/dist/homebridge-ui/public/js/modals.js +132 -0
  80. package/dist/homebridge-ui/public/js/modals.js.map +1 -0
  81. package/dist/homebridge-ui/public/js/modals.ts +153 -0
  82. package/dist/homebridge-ui/public/js/render.d.ts +6 -0
  83. package/dist/homebridge-ui/public/js/render.d.ts.map +1 -0
  84. package/dist/homebridge-ui/public/js/render.js +166 -0
  85. package/dist/homebridge-ui/public/js/render.js.map +1 -0
  86. package/dist/homebridge-ui/public/js/render.ts +190 -0
  87. package/dist/homebridge-ui/public/js/toast.d.ts +6 -0
  88. package/dist/homebridge-ui/public/js/toast.d.ts.map +1 -0
  89. package/dist/homebridge-ui/public/js/toast.js +29 -0
  90. package/dist/homebridge-ui/public/js/toast.js.map +1 -0
  91. package/dist/homebridge-ui/public/js/toast.ts +37 -0
  92. package/dist/homebridge-ui/public/js/types.d.ts +23 -0
  93. package/dist/homebridge-ui/public/js/types.d.ts.map +1 -0
  94. package/dist/homebridge-ui/public/js/types.js +2 -0
  95. package/dist/homebridge-ui/public/js/types.js.map +1 -0
  96. package/dist/homebridge-ui/public/js/types.ts +26 -0
  97. package/dist/homebridge-ui/server.d.ts +1 -3
  98. package/dist/homebridge-ui/server.d.ts.map +1 -1
  99. package/dist/homebridge-ui/server.js +10 -561
  100. package/dist/homebridge-ui/server.js.map +1 -1
  101. package/dist/homebridge-ui/utils/config-parser.d.ts +35 -0
  102. package/dist/homebridge-ui/utils/config-parser.d.ts.map +1 -0
  103. package/dist/homebridge-ui/utils/config-parser.js +87 -0
  104. package/dist/homebridge-ui/utils/config-parser.js.map +1 -0
  105. package/dist/homebridge-ui/utils/logger.d.ts +7 -0
  106. package/dist/homebridge-ui/utils/logger.d.ts.map +1 -0
  107. package/dist/homebridge-ui/utils/logger.js +17 -0
  108. package/dist/homebridge-ui/utils/logger.js.map +1 -0
  109. package/dist/platform.d.ts.map +1 -1
  110. package/dist/platform.js +6 -2
  111. package/dist/platform.js.map +1 -1
  112. package/dist/switchbotClient.d.ts.map +1 -1
  113. package/dist/switchbotClient.js +2 -0
  114. package/dist/switchbotClient.js.map +1 -1
  115. package/docs/variables/default.html +1 -1
  116. package/eslint.config.js +5 -0
  117. package/nodemon.json +2 -2
  118. package/package.json +20 -10
  119. package/scripts/build-ui.js +36 -0
  120. package/scripts/free-dev-ports.mjs +105 -0
  121. package/scripts/sync-device-types.mjs +28 -0
  122. package/src/device-types.ts +145 -0
  123. package/src/deviceFactory.ts +71 -31
  124. package/src/devices/genericDevice.ts +5 -2
  125. package/src/homebridge-ui/endpoints/config.ts +79 -0
  126. package/src/homebridge-ui/endpoints/credentials.ts +74 -0
  127. package/src/homebridge-ui/endpoints/devices.ts +321 -0
  128. package/src/homebridge-ui/endpoints/discovery.ts +191 -0
  129. package/src/homebridge-ui/public/index.html +144 -588
  130. package/src/homebridge-ui/public/js/api.ts +189 -0
  131. package/src/homebridge-ui/public/js/app.ts +21 -0
  132. package/src/homebridge-ui/public/js/constants.ts +1 -0
  133. package/src/homebridge-ui/public/js/credentials.ts +100 -0
  134. package/src/homebridge-ui/public/js/devices-delete.ts +113 -0
  135. package/src/homebridge-ui/public/js/devices.ts +78 -0
  136. package/src/homebridge-ui/public/js/discovery.ts +123 -0
  137. package/src/homebridge-ui/public/js/logger.ts +11 -0
  138. package/src/homebridge-ui/public/js/modal.ts +28 -0
  139. package/src/homebridge-ui/public/js/modals.ts +153 -0
  140. package/src/homebridge-ui/public/js/render.ts +190 -0
  141. package/src/homebridge-ui/public/js/toast.ts +37 -0
  142. package/src/homebridge-ui/public/js/types.ts +26 -0
  143. package/src/homebridge-ui/server.ts +11 -647
  144. package/src/homebridge-ui/utils/config-parser.ts +108 -0
  145. package/src/homebridge-ui/utils/logger.ts +17 -0
  146. package/src/platform.ts +6 -2
  147. package/src/switchbotClient.ts +2 -0
  148. package/switchbot-homebridge-switchbot-5.0.0.tgz +0 -0
@@ -0,0 +1,321 @@
1
+ import type { HomebridgePluginUiServer } from '@homebridge/plugin-ui-utils'
2
+
3
+ import { RequestError } from '@homebridge/plugin-ui-utils'
4
+ import fs from 'node:fs/promises'
5
+
6
+ import { getAllDevices, getDeviceArrays, getSwitchBotPlatformConfig } from '../utils/config-parser.js'
7
+ import { uiLog } from '../utils/logger.js'
8
+
9
+ /**
10
+ * Register device CRUD endpoints
11
+ */
12
+ export function registerDeviceEndpoints(server: HomebridgePluginUiServer) {
13
+ /**
14
+ * POST /add-device - Add a single device to config
15
+ */
16
+ server.onRequest('/add-device', async (body: any) => {
17
+ try {
18
+ const { deviceId, name, type } = body
19
+
20
+ if (!deviceId) {
21
+ throw new Error('Device ID is required')
22
+ }
23
+
24
+ const { cfg, platform, cfgPath } = await getSwitchBotPlatformConfig(server)
25
+
26
+ uiLog.info('POST /add-device - Request received')
27
+ uiLog.debug(`POST /add-device - Request body: ${JSON.stringify(body)}`)
28
+ uiLog.debug(`POST /add-device - Config file path: ${cfgPath}`)
29
+
30
+ const deviceArrays = getDeviceArrays(platform)
31
+ const allDevices = getAllDevices(platform)
32
+
33
+ const normalizedDeviceId = String(deviceId).trim().toLowerCase()
34
+ const exists = allDevices.some((d: any) => String(d.deviceId ?? d.id ?? '').trim().toLowerCase() === normalizedDeviceId)
35
+ if (exists) {
36
+ uiLog.info(`POST /add-device - Device already exists: ${deviceId}`)
37
+ return {
38
+ success: true,
39
+ data: {
40
+ message: 'Device already in config',
41
+ alreadyExists: true,
42
+ },
43
+ }
44
+ }
45
+
46
+ let addCount = 0
47
+ for (const ref of deviceArrays) {
48
+ const refHasDevice = ref.some((d: any) => String(d.deviceId ?? d.id ?? '').trim().toLowerCase() === normalizedDeviceId)
49
+ if (!refHasDevice) {
50
+ const newDevice = {
51
+ deviceId,
52
+ configDeviceName: name,
53
+ configDeviceType: type,
54
+ }
55
+ ref.push(newDevice)
56
+ addCount++
57
+ }
58
+ }
59
+
60
+ if (!addCount) {
61
+ return {
62
+ success: false,
63
+ data: { message: 'Failed to add device to config' },
64
+ }
65
+ }
66
+
67
+ const configJson = JSON.stringify(cfg, null, 2)
68
+ const fileHandle = await fs.open(cfgPath, 'w')
69
+ try {
70
+ await fileHandle.writeFile(configJson, 'utf8')
71
+ await fileHandle.sync()
72
+ } finally {
73
+ await fileHandle.close()
74
+ }
75
+
76
+ // Notify Homebridge UI that config changed
77
+ server.pushEvent('configChanged', { source: 'switchbot-plugin' })
78
+ uiLog.debug('POST /add-device - Sent configChanged event to UI')
79
+
80
+ return {
81
+ success: true,
82
+ data: {
83
+ message: `Device "${name}" added successfully`,
84
+ alreadyExists: false,
85
+ added: true,
86
+ },
87
+ }
88
+ } catch (e) {
89
+ uiLog.error(`Error in /add-device: ${e instanceof Error ? e.message : String(e)}`)
90
+ throw new RequestError(`Failed to add device: ${e instanceof Error ? e.message : String(e)}`, e)
91
+ }
92
+ })
93
+
94
+ /**
95
+ * POST /add-devices - Add multiple devices to config (bulk add)
96
+ */
97
+ server.onRequest('/add-devices', async (body: any) => {
98
+ try {
99
+ const { devices } = body
100
+
101
+ if (!Array.isArray(devices) || devices.length === 0) {
102
+ throw new Error('Devices array is required and must not be empty')
103
+ }
104
+
105
+ const { cfg, platform, cfgPath } = await getSwitchBotPlatformConfig(server)
106
+ uiLog.debug(`POST /add-devices - Received ${devices.length} device(s) to add`)
107
+ uiLog.debug(`POST /add-devices - Config path: ${cfgPath}`)
108
+
109
+ const deviceArrays = getDeviceArrays(platform)
110
+ const allDevices = getAllDevices(platform)
111
+
112
+ uiLog.debug(`POST /add-devices - Device arrays count: ${deviceArrays.length}, existing devices: ${allDevices.length}`)
113
+ uiLog.debug(`POST /add-devices - Platform.devices exists: ${!!platform.devices}, length: ${platform.devices?.length || 0}`)
114
+
115
+ let addedCount = 0
116
+ let skippedCount = 0
117
+ const results: Array<Record<string, any>> = []
118
+
119
+ for (const { deviceId, name, type } of devices) {
120
+ if (!deviceId) {
121
+ results.push({ deviceId: '?', success: false, message: 'Device ID is required' })
122
+ skippedCount++
123
+ continue
124
+ }
125
+
126
+ const normalizedDeviceId = String(deviceId).trim().toLowerCase()
127
+ const exists = allDevices.some((d: any) => String(d.deviceId ?? d.id ?? '').trim().toLowerCase() === normalizedDeviceId)
128
+
129
+ if (exists) {
130
+ uiLog.debug(`POST /add-devices - Device already exists: ${deviceId}`)
131
+ results.push({ deviceId, success: true, message: 'Already in config', alreadyExists: true })
132
+ skippedCount++
133
+ continue
134
+ }
135
+
136
+ let addedToArray = false
137
+ for (const ref of deviceArrays) {
138
+ const refHasDevice = ref.some((d: any) => String(d.deviceId ?? d.id ?? '').trim().toLowerCase() === normalizedDeviceId)
139
+ if (!refHasDevice) {
140
+ const newDevice = {
141
+ deviceId,
142
+ configDeviceName: name,
143
+ configDeviceType: type,
144
+ }
145
+ ref.push(newDevice)
146
+ addedToArray = true
147
+ uiLog.debug(`POST /add-devices - Added device to array: ${deviceId} (${name}, ${type})`)
148
+ }
149
+ }
150
+
151
+ if (addedToArray) {
152
+ results.push({ deviceId, success: true, message: `Device "${name}" added` })
153
+ addedCount++
154
+ } else {
155
+ uiLog.warn(`POST /add-devices - Failed to add device: ${deviceId}`)
156
+ results.push({ deviceId, success: false, message: 'Failed to add device' })
157
+ skippedCount++
158
+ }
159
+ }
160
+
161
+ uiLog.info(`POST /add-devices - Adding ${addedCount} devices to config: ${cfgPath}`)
162
+ const configJson = JSON.stringify(cfg, null, 2)
163
+ const fileHandle = await fs.open(cfgPath, 'w')
164
+ try {
165
+ await fileHandle.writeFile(configJson, 'utf8')
166
+ await fileHandle.sync()
167
+ uiLog.info(`POST /add-devices - Config file written successfully`)
168
+ } finally {
169
+ await fileHandle.close()
170
+ }
171
+
172
+ // Notify Homebridge UI that config changed to prevent cache overwrite
173
+ server.pushEvent('configChanged', { source: 'switchbot-plugin' })
174
+ uiLog.debug('POST /add-devices - Sent configChanged event to UI')
175
+
176
+ return {
177
+ success: true,
178
+ data: {
179
+ message: `Added ${addedCount} device(s)${skippedCount > 0 ? ` (${skippedCount} skipped)` : ''}`,
180
+ addedCount,
181
+ skippedCount,
182
+ results,
183
+ },
184
+ }
185
+ } catch (e) {
186
+ const errorMsg = e instanceof Error ? e.message : String(e)
187
+ uiLog.error(`Error in /add-devices: ${errorMsg}`)
188
+ if (e instanceof Error && e.stack) {
189
+ uiLog.debug(`Stack trace: ${e.stack}`)
190
+ }
191
+ throw new RequestError(`Failed to add devices: ${errorMsg}`, e)
192
+ }
193
+ })
194
+
195
+ /**
196
+ * POST /update-device - Update existing device in config
197
+ */
198
+ server.onRequest('/update-device', async (body: any) => {
199
+ try {
200
+ const { deviceId, configDeviceName, configDeviceType, connectionPreference, room } = body
201
+
202
+ if (!deviceId) {
203
+ throw new Error('Device ID is required')
204
+ }
205
+
206
+ const { cfg, platform, cfgPath } = await getSwitchBotPlatformConfig(server)
207
+ const deviceArrays = getDeviceArrays(platform)
208
+ const devices = getAllDevices(platform)
209
+
210
+ const normalizedDeviceId = String(deviceId).trim().toLowerCase()
211
+ const device = devices.find((d: any) => String(d.deviceId ?? d.id ?? '').trim().toLowerCase() === normalizedDeviceId)
212
+ if (!device) {
213
+ throw new Error('Device not found in config')
214
+ }
215
+
216
+ for (const ref of deviceArrays) {
217
+ for (const entry of ref) {
218
+ const entryId = String(entry.deviceId ?? entry.id ?? '').trim().toLowerCase()
219
+ if (entryId !== normalizedDeviceId) {
220
+ continue
221
+ }
222
+
223
+ if (configDeviceName !== undefined && configDeviceName !== null && String(configDeviceName).trim() !== '') {
224
+ entry.configDeviceName = configDeviceName
225
+ }
226
+ if (configDeviceType !== undefined && configDeviceType !== null && String(configDeviceType).trim() !== '') {
227
+ entry.configDeviceType = configDeviceType
228
+ }
229
+ if (connectionPreference !== undefined) {
230
+ entry.connectionPreference = connectionPreference
231
+ }
232
+ if (room !== undefined) {
233
+ entry.room = room || undefined
234
+ }
235
+ }
236
+ }
237
+
238
+ const configJson = JSON.stringify(cfg, null, 2)
239
+ const fileHandle = await fs.open(cfgPath, 'w')
240
+ try {
241
+ await fileHandle.writeFile(configJson, 'utf8')
242
+ await fileHandle.sync()
243
+ } finally {
244
+ await fileHandle.close()
245
+ }
246
+
247
+ // Notify Homebridge UI that config changed
248
+ server.pushEvent('configChanged', { source: 'switchbot-plugin' })
249
+ uiLog.debug('POST /update-device - Sent configChanged event to UI')
250
+
251
+ return {
252
+ success: true,
253
+ data: { message: `Device updated successfully - type: ${configDeviceType || device.configDeviceType}` },
254
+ }
255
+ } catch (e) {
256
+ uiLog.error(`Error in /update-device: ${e instanceof Error ? e.message : String(e)}`)
257
+ throw new RequestError(`Failed to update device: ${e instanceof Error ? e.message : String(e)}`, e)
258
+ }
259
+ })
260
+
261
+ /**
262
+ * POST /delete-device - Remove device from config
263
+ */
264
+ server.onRequest('/delete-device', async (body: any) => {
265
+ try {
266
+ const { deviceId } = body
267
+ uiLog.info(`POST /delete-device - Requested deviceId: ${deviceId ?? 'undefined'}`)
268
+
269
+ if (!deviceId) {
270
+ throw new Error('Device ID is required')
271
+ }
272
+
273
+ const { cfg, platform, cfgPath } = await getSwitchBotPlatformConfig(server)
274
+ const deviceArrays = getDeviceArrays(platform)
275
+ const normalizedDeviceId = String(deviceId).trim().toLowerCase()
276
+ const allDevices = getAllDevices(platform)
277
+
278
+ const existing = allDevices.find((d: any) => String(d.deviceId ?? d.id ?? '').trim().toLowerCase() === normalizedDeviceId)
279
+ if (!existing) {
280
+ throw new Error('Device not found in config')
281
+ }
282
+
283
+ const deviceName = existing.configDeviceName || deviceId
284
+ let removedCount = 0
285
+ for (const ref of deviceArrays) {
286
+ for (let i = ref.length - 1; i >= 0; i--) {
287
+ const id = String(ref[i]?.deviceId ?? ref[i]?.id ?? '').trim().toLowerCase()
288
+ if (id === normalizedDeviceId) {
289
+ ref.splice(i, 1)
290
+ removedCount++
291
+ }
292
+ }
293
+ }
294
+
295
+ if (!removedCount) {
296
+ throw new Error('Device not found in config')
297
+ }
298
+
299
+ const configJson = JSON.stringify(cfg, null, 2)
300
+ const fileHandle = await fs.open(cfgPath, 'w')
301
+ try {
302
+ await fileHandle.writeFile(configJson, 'utf8')
303
+ await fileHandle.sync()
304
+ } finally {
305
+ await fileHandle.close()
306
+ }
307
+
308
+ // Notify Homebridge UI that config changed
309
+ server.pushEvent('configChanged', { source: 'switchbot-plugin' })
310
+ uiLog.debug('DELETE /delete-device - Sent configChanged event to UI')
311
+
312
+ return {
313
+ success: true,
314
+ data: { message: `Device "${deviceName}" removed from config` },
315
+ }
316
+ } catch (e) {
317
+ uiLog.error(`Error in /delete-device: ${e instanceof Error ? e.message : String(e)}`)
318
+ throw new RequestError('Failed to delete device', e)
319
+ }
320
+ })
321
+ }
@@ -0,0 +1,191 @@
1
+ import type { HomebridgePluginUiServer } from '@homebridge/plugin-ui-utils'
2
+
3
+ import { RequestError } from '@homebridge/plugin-ui-utils'
4
+
5
+ import { getCredential, getSwitchBotPlatformConfig } from '../utils/config-parser.js'
6
+ import { uiLog } from '../utils/logger.js'
7
+
8
+ /**
9
+ * Register discovery endpoint
10
+ * Discovers SwitchBot devices via BLE and OpenAPI
11
+ */
12
+ export function registerDiscoveryEndpoint(server: HomebridgePluginUiServer) {
13
+ server.onRequest('/discover', async () => {
14
+ try {
15
+ const { platform } = await getSwitchBotPlatformConfig(server)
16
+
17
+ uiLog.debug(`GET /discover - Platform config keys: ${Object.keys(platform).join(', ')}`)
18
+
19
+ const token = getCredential(platform, 'openApiToken') || platform.token
20
+ const secret = getCredential(platform, 'openApiSecret') || platform.secret
21
+
22
+ const hasOpenAPICredentials = !!token
23
+
24
+ if (!hasOpenAPICredentials) {
25
+ uiLog.warn('GET /discover - No OpenAPI credentials found, will attempt BLE-only discovery')
26
+ } else {
27
+ uiLog.info('GET /discover - Using OpenAPI credentials for discovery')
28
+ }
29
+
30
+ // Import and initialize node-switchbot
31
+ const { SwitchBot } = await import('node-switchbot')
32
+ const switchbot = new SwitchBot({
33
+ token: token || undefined,
34
+ secret: secret || undefined,
35
+ enableBLE: true,
36
+ enableFallback: true,
37
+ enableRetry: true,
38
+ })
39
+
40
+ const deviceMap = new Map<string, any>()
41
+
42
+ // 1. Try BLE discovery first (with timeout)
43
+ uiLog.info('GET /discover - Starting BLE scan...')
44
+ try {
45
+ const bleTimeout = 8000 // 8 second timeout for BLE scan
46
+ const bleDiscoveryPromise = switchbot.discover({ timeout: 5000 }) // 5 second scan timeout
47
+ const bleDevices = await Promise.race([
48
+ bleDiscoveryPromise,
49
+ new Promise<any[]>(resolve => setTimeout(resolve, bleTimeout, [])),
50
+ ])
51
+
52
+ if (Array.isArray(bleDevices) && bleDevices.length > 0) {
53
+ uiLog.info(`GET /discover - Found ${bleDevices.length} BLE devices`)
54
+ for (const [index, d] of bleDevices.entries()) {
55
+ const info = typeof d?.getInfo === 'function' ? d.getInfo() : undefined
56
+ const id = d?.id
57
+ || (typeof d?.getId === 'function' ? d.getId() : undefined)
58
+ || info?.id
59
+
60
+ const mac = d?.mac
61
+ || (typeof d?.getMAC === 'function' ? d.getMAC() : undefined)
62
+ || info?.mac
63
+
64
+ if (!id) {
65
+ uiLog.warn(`GET /discover - BLE device at index ${index} has no id, skipping`)
66
+ continue
67
+ }
68
+
69
+ const connectionTypes = Array.isArray(info?.connectionTypes) ? info.connectionTypes : []
70
+ const isHybrid = connectionTypes.includes('api')
71
+
72
+ deviceMap.set(id, {
73
+ id,
74
+ name: d?.name || (typeof d?.getName === 'function' ? d.getName() : undefined) || info?.name || d?.deviceName || id,
75
+ type: d?.deviceType || (typeof d?.getDeviceType === 'function' ? d.getDeviceType() : undefined) || info?.deviceType || d?.type || d?.model || 'unknown',
76
+ model: info?.model || d?.model || d?.deviceModel,
77
+ address: mac,
78
+ connectionType: isHybrid ? 'Both' : 'BLE',
79
+ rssi: info?.rssi || d?.rssi,
80
+ })
81
+ }
82
+ } else {
83
+ uiLog.info('GET /discover - No BLE devices found or scan timed out')
84
+ }
85
+ } catch (bleErr) {
86
+ uiLog.warn(`GET /discover - BLE discovery failed: ${bleErr instanceof Error ? bleErr.message : String(bleErr)}`)
87
+ // Continue with OpenAPI even if BLE fails
88
+ }
89
+
90
+ // 2. Get devices from OpenAPI (only if credentials are available)
91
+ if (hasOpenAPICredentials) {
92
+ uiLog.info('GET /discover - Fetching devices from OpenAPI...')
93
+ try {
94
+ const apiClient = switchbot.getAPIClient()
95
+ if (!apiClient) {
96
+ throw new Error('API client not available - token/secret may be missing')
97
+ }
98
+ const apiData = await apiClient.getDevices()
99
+ uiLog.debug(`GET /discover - OpenAPI response: ${JSON.stringify(apiData)}`)
100
+
101
+ // Parse physical devices - apiData is DeviceListResponse with deviceList and infraredRemoteList
102
+ const devices = apiData.deviceList || []
103
+ const irDevices = apiData.infraredRemoteList || []
104
+
105
+ uiLog.info(`GET /discover - Found ${devices.length} OpenAPI physical devices and ${irDevices.length} IR devices`)
106
+
107
+ // Process physical devices from OpenAPI
108
+ for (const d of devices) {
109
+ const id = d.deviceId
110
+ if (!id) {
111
+ continue
112
+ }
113
+
114
+ const existing = deviceMap.get(id)
115
+ if (existing) {
116
+ // Device found via both BLE and OpenAPI
117
+ existing.connectionType = 'Both'
118
+ existing.name = d.deviceName || existing.name
119
+ existing.type = d.deviceType || existing.type
120
+ // Note: APIDevice doesn't have a model property
121
+ existing.enabled = d.enableCloudService !== false
122
+ existing.hubDeviceId = d.hubDeviceId
123
+ } else {
124
+ // Device only found via OpenAPI
125
+ deviceMap.set(id, {
126
+ id,
127
+ name: d.deviceName || id,
128
+ type: d.deviceType || 'unknown',
129
+ enabled: d.enableCloudService !== false,
130
+ hubDeviceId: d.hubDeviceId,
131
+ connectionType: 'OpenAPI',
132
+ })
133
+ }
134
+ }
135
+
136
+ // Process IR devices (OpenAPI only)
137
+ for (const d of irDevices) {
138
+ const id = d.deviceId
139
+ if (!id) {
140
+ continue
141
+ }
142
+
143
+ deviceMap.set(id, {
144
+ id,
145
+ name: d.deviceName || id,
146
+ type: d.remoteType || 'unknown',
147
+ enabled: true,
148
+ hubDeviceId: d.hubDeviceId,
149
+ connectionType: 'OpenAPI',
150
+ isIR: true,
151
+ })
152
+ }
153
+ } catch (apiErr) {
154
+ uiLog.error(`GET /discover - OpenAPI discovery failed: ${apiErr instanceof Error ? apiErr.message : String(apiErr)}`)
155
+ // If we have BLE devices, we can still return those
156
+ if (deviceMap.size === 0) {
157
+ throw apiErr
158
+ }
159
+ }
160
+ } else {
161
+ uiLog.info('GET /discover - Skipping OpenAPI discovery (no credentials configured)')
162
+ }
163
+
164
+ const normalizedBleDevices = [...deviceMap.values()].filter(d => d.connectionType === 'BLE' || d.connectionType === 'Both')
165
+ const firstNormalizedBleId = normalizedBleDevices[0]?.id || 'none'
166
+ uiLog.info(`GET /discover - Normalized BLE devices: ${normalizedBleDevices.length} (firstId: ${firstNormalizedBleId})`)
167
+
168
+ // Check if we found any devices
169
+ if (deviceMap.size === 0) {
170
+ const errorMsg = hasOpenAPICredentials
171
+ ? 'No devices found via BLE or OpenAPI. Make sure devices are powered on and in range.'
172
+ : 'No devices found via BLE. OpenAPI credentials not configured. Please save your credentials in settings to discover cloud-connected devices, or ensure BLE devices are powered on and in range.'
173
+ uiLog.error(`GET /discover - ${errorMsg}`)
174
+ throw new Error(errorMsg)
175
+ }
176
+
177
+ // Convert map to array
178
+ const allDiscovered = [...deviceMap.values()]
179
+
180
+ const bleCount = allDiscovered.filter(d => d.connectionType === 'BLE').length
181
+ const apiCount = allDiscovered.filter(d => d.connectionType === 'OpenAPI').length
182
+ const bothCount = allDiscovered.filter(d => d.connectionType === 'Both').length
183
+
184
+ uiLog.info(`GET /discover - Total: ${allDiscovered.length} devices (BLE: ${bleCount}, OpenAPI: ${apiCount}, Both: ${bothCount})`)
185
+ return { success: true, data: allDiscovered }
186
+ } catch (e) {
187
+ uiLog.error(`Error in /discover: ${e instanceof Error ? e.message : String(e)}`)
188
+ throw new RequestError(`Failed to discover devices: ${e instanceof Error ? e.message : String(e)}`, e)
189
+ }
190
+ })
191
+ }