@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
@@ -1,652 +1,16 @@
1
- /* eslint-disable no-console */
2
- import { HomebridgePluginUiServer, RequestError } from '@homebridge/plugin-ui-utils'
3
- import fs from 'node:fs/promises'
1
+ import { HomebridgePluginUiServer } from '@homebridge/plugin-ui-utils'
4
2
 
5
- const server = new HomebridgePluginUiServer()
6
-
7
- function getDevicesRef(platform: any): any[] {
8
- if (!platform || typeof platform !== 'object') {
9
- return []
10
- }
11
-
12
- if (Array.isArray(platform.devices)) {
13
- return platform.devices
14
- }
15
-
16
- platform.devices = []
17
- return platform.devices
18
- }
19
-
20
- function getDeviceArrays(platform: any): any[][] {
21
- const rootDevices = getDevicesRef(platform)
22
- return [rootDevices]
23
- }
24
-
25
- function getAllDevices(platform: any): any[] {
26
- const all = getDevicesRef(platform)
27
- const seen = new Set<string>()
28
-
29
- return all.filter((d: any) => {
30
- const id = String(d?.deviceId ?? d?.id ?? '').trim().toLowerCase()
31
- if (!id || seen.has(id)) {
32
- return false
33
- }
34
- seen.add(id)
35
- return true
36
- })
37
- }
38
-
39
- function getCredential(platform: any, key: 'openApiToken' | 'openApiSecret') {
40
- return platform?.[key]
41
- }
42
-
43
- function setCredential(platform: any, key: 'openApiToken' | 'openApiSecret', value: string) {
44
- if (!platform || typeof platform !== 'object') {
45
- return
46
- }
47
-
48
- platform[key] = value
49
- }
50
-
51
- // Helper function to find the SwitchBot platform config
52
- async function getSwitchBotPlatformConfig() {
53
- const cfgPath = server.homebridgeConfigPath
54
- if (!cfgPath) {
55
- throw new Error('HOMEBRIDGE_CONFIG_PATH not set')
56
- }
57
-
58
- const raw = await fs.readFile(cfgPath, 'utf8')
59
- const cfg = JSON.parse(raw)
60
- const platforms = Array.isArray(cfg.platforms) ? cfg.platforms : []
61
-
62
- console.log('[SwitchBot UI] getSwitchBotPlatformConfig - Found', platforms.length, 'platform(s)')
63
- platforms.forEach((p: any, i: number) => {
64
- console.log(`[SwitchBot UI] Platform ${i}:`, p.platform || p.name)
65
- })
66
-
67
- const candidates = platforms.filter((p: any) => {
68
- const platformName = p.platform || p.name || ''
69
- return !!platformName && (/switchbot/i.test(String(platformName)) || String(platformName).toLowerCase() === '@switchbot/homebridge-switchbot')
70
- })
71
-
72
- console.log('[SwitchBot UI] Found', candidates.length, 'SwitchBot candidate(s)')
73
-
74
- const platform = candidates.find((p: any) => {
75
- const name = String(p.platform || '').toLowerCase()
76
- return name === 'switchbot' || name === '@switchbot/homebridge-switchbot'
77
- }) ?? candidates[0]
78
-
79
- if (platform) {
80
- console.log('[SwitchBot UI] Selected platform:', platform.platform || platform.name)
81
- return { config: cfg, platform, cfgPath }
82
- }
83
-
84
- throw new Error('SwitchBot platform not found in config')
85
- }
86
-
87
- server.onRequest('/devices', async () => {
88
- try {
89
- const cfgPath = server.homebridgeConfigPath
90
- if (!cfgPath) {
91
- throw new Error('HOMEBRIDGE_CONFIG_PATH not set')
92
- }
93
-
94
- const raw = await fs.readFile(cfgPath, 'utf8')
95
- const cfg = JSON.parse(raw)
96
- const found: Array<{ id: string, name?: string, type?: string, connectionPreference?: string, room?: string }> = []
97
-
98
- const platforms = Array.isArray(cfg.platforms) ? cfg.platforms : []
99
- for (const p of platforms) {
100
- try {
101
- const platformName = p.platform || p.name || ''
102
- // Match known SwitchBot platform identifiers
103
- if (!platformName || !/switchbot/i.test(String(platformName))) {
104
- continue
105
- }
106
-
107
- const devices = getAllDevices(p)
108
- for (const d of devices) {
109
- const id = d.deviceId ?? d.id
110
- if (!id) {
111
- continue
112
- }
113
-
114
- found.push({
115
- id,
116
- name: d.configDeviceName ?? d.name ?? d.deviceName,
117
- type: d.configDeviceType ?? d.type ?? d.deviceType,
118
- connectionPreference: d.connectionPreference ?? d.connection ?? 'auto',
119
- room: d.room || d.location || undefined,
120
- })
121
- }
122
- } catch (e) {
123
- // ignore malformed platform entries
124
- }
125
- }
126
-
127
- console.log('[SwitchBot UI] GET /devices - Found', found.length, 'devices in', cfgPath)
128
- return { success: true, data: found }
129
- } catch (e) {
130
- console.error('[SwitchBot UI] Error in /devices:', e)
131
- throw new RequestError('Failed to read Homebridge config', e)
132
- }
133
- })
134
-
135
- server.onRequest('/platform-config', async () => {
136
- try {
137
- const { platform } = await getSwitchBotPlatformConfig()
138
- return {
139
- success: true,
140
- data: JSON.parse(JSON.stringify(platform)),
141
- }
142
- } catch (e) {
143
- console.error('[SwitchBot UI] Error in /platform-config:', e)
144
- throw new RequestError('Failed to read platform config', e)
145
- }
146
- })
147
-
148
- server.onRequest('/discover', async () => {
149
- try {
150
- const { platform } = await getSwitchBotPlatformConfig()
151
-
152
- console.log('[SwitchBot UI] GET /discover - Platform config:', Object.keys(platform))
153
-
154
- const token = getCredential(platform, 'openApiToken') || platform.token
155
- if (!token) {
156
- console.error('[SwitchBot UI] No API token found in platform config')
157
- throw new Error('OpenAPI token not configured. Please save your credentials first.')
158
- }
159
-
160
- console.log('[SwitchBot UI] GET /discover - Fetching devices from SwitchBot API')
161
-
162
- const url = 'https://api.switch-bot.com/v1.0/devices'
163
- const opts = {
164
- headers: {
165
- Authorization: token,
166
- },
167
- }
168
-
169
- console.log('[SwitchBot UI] GET /discover - Making request to', url)
170
- const resp = await fetch(url, opts)
171
-
172
- console.log('[SwitchBot UI] GET /discover - API response status:', resp.status)
173
-
174
- if (!resp.ok) {
175
- const errorText = await resp.text()
176
- console.error('[SwitchBot UI] API error response:', errorText)
177
- throw new Error(`SwitchBot API returned ${resp.status}: ${errorText}`)
178
- }
179
-
180
- const data = await resp.json()
181
- console.log('[SwitchBot UI] GET /discover - Full API response:', JSON.stringify(data, null, 2))
182
-
183
- // Handle different response formats
184
- let devices: any[] = []
185
- if (Array.isArray(data)) {
186
- devices = data
187
- } else if (Array.isArray(data.body)) {
188
- devices = data.body
189
- } else if (Array.isArray(data.devices)) {
190
- devices = data.devices
191
- } else if (data.body && typeof data.body === 'object') {
192
- // Sometimes the response has devices listed within body
193
- const bodyKeys = Object.keys(data.body)
194
- if (bodyKeys.includes('deviceList')) {
195
- devices = Array.isArray(data.body.deviceList) ? data.body.deviceList : []
196
- } else if (bodyKeys.includes('devices')) {
197
- devices = Array.isArray(data.body.devices) ? data.body.devices : []
198
- }
199
- }
200
-
201
- if (!Array.isArray(devices)) {
202
- console.warn('[SwitchBot UI] Could not find devices array in API response. Response keys:', Object.keys(data), 'Body keys:', data.body ? Object.keys(data.body) : 'N/A')
203
- devices = []
204
- }
205
-
206
- const discovered = devices.map((d: any) => ({
207
- id: d.deviceId || d.id,
208
- name: d.deviceName || d.name,
209
- type: d.deviceType || d.type || 'unknown',
210
- model: d.deviceModel || d.model,
211
- enabled: d.enableCloudService !== false,
212
- }))
213
-
214
- console.log('[SwitchBot UI] GET /discover - Found', discovered.length, 'devices from API')
215
- return { success: true, data: discovered }
216
- } catch (e) {
217
- console.error('[SwitchBot UI] Error in /discover:', e instanceof Error ? e.message : String(e))
218
- throw new RequestError(`Failed to discover devices: ${e instanceof Error ? e.message : String(e)}`, e)
219
- }
220
- })
221
-
222
- server.onRequest('/add-device', async (body: any) => {
223
- try {
224
- const { deviceId, name, type } = body
225
-
226
- if (!deviceId) {
227
- throw new Error('Device ID is required')
228
- }
229
-
230
- const { config, platform, cfgPath } = await getSwitchBotPlatformConfig()
231
-
232
- console.log('[SwitchBot UI] ========== /add-device REQUEST ==========')
233
- console.log('[SwitchBot UI] Request body:', JSON.stringify(body, null, 2))
234
- console.log('[SwitchBot UI] Config file path:', cfgPath)
235
- console.log('[SwitchBot UI] Platform type:', typeof platform)
236
- console.log('[SwitchBot UI] Platform.platform:', platform.platform)
237
- console.log('[SwitchBot UI] Platform.name:', platform.name)
238
- console.log('[SwitchBot UI] Platform object keys:', Object.keys(platform).slice(0, 10))
239
- console.log('[SwitchBot UI] Platform.devices type:', typeof platform.devices)
240
- console.log('[SwitchBot UI] Platform.devices length:', (platform.devices || []).length)
241
- if (platform.devices && platform.devices.length > 0) {
242
- console.log('[SwitchBot UI] Existing devices:', JSON.stringify(platform.devices.slice(0, 3), null, 2))
243
- }
244
-
245
- const deviceArrays = getDeviceArrays(platform)
246
- console.log('[SwitchBot UI] Device arrays:', deviceArrays.length, '- first array length:', deviceArrays[0]?.length)
247
-
248
- const allDevices = getAllDevices(platform)
249
- console.log('[SwitchBot UI] All devices (deduplicated):', allDevices.length)
250
-
251
- // Check if already exists
252
- const normalizedDeviceId = String(deviceId).trim().toLowerCase()
253
- const exists = allDevices.some((d: any) => String(d.deviceId ?? d.id ?? '').trim().toLowerCase() === normalizedDeviceId)
254
- if (exists) {
255
- console.log('[SwitchBot UI] Device already exists:', deviceId)
256
- return {
257
- success: true,
258
- data: {
259
- message: 'Device already in config',
260
- alreadyExists: true,
261
- },
262
- }
263
- }
264
-
265
- // Add device
266
- let addCount = 0
267
- for (const ref of deviceArrays) {
268
- const refHasDevice = ref.some((d: any) => String(d.deviceId ?? d.id ?? '').trim().toLowerCase() === normalizedDeviceId)
269
- if (!refHasDevice) {
270
- const newDevice = {
271
- deviceId,
272
- configDeviceName: name,
273
- configDeviceType: type,
274
- }
275
- console.log('[SwitchBot UI] Creating device object:', JSON.stringify(newDevice, null, 2))
276
- ref.push(newDevice)
277
- console.log('[SwitchBot UI] ✓ Device pushed to array. Array is now length:', ref.length)
278
- console.log('[SwitchBot UI] Array after push:', JSON.stringify(ref.map((d: any) => d.deviceId), null, 2))
279
- addCount++
280
- }
281
- }
282
-
283
- if (addCount === 0) {
284
- console.warn('[SwitchBot UI] Device was not added to any array')
285
- return {
286
- success: false,
287
- data: { message: 'Failed to add device to config' },
288
- }
289
- }
290
-
291
- console.log('[SwitchBot UI] About to serialize and save config')
292
- console.log('[SwitchBot UI] Config.platforms length:', config.platforms.length)
293
- console.log('[SwitchBot UI] Target platform devices before stringify:', JSON.stringify(platform.devices, null, 2))
294
-
295
- // Save config with fsync to ensure write completes before Homebridge caches it
296
- const configJson = JSON.stringify(config, null, 2)
297
- console.log('[SwitchBot UI] ✓ Config serialized - size:', configJson.length, 'bytes')
298
-
299
- // Use atomic write with fsync to prevent race conditions
300
- const fileHandle = await fs.open(cfgPath, 'w')
301
- try {
302
- await fileHandle.writeFile(configJson, 'utf8')
303
- await fileHandle.sync() // Force flush to disk BEFORE closing
304
- console.log('[SwitchBot UI] ✓✓ File written and synced to disk')
305
- } finally {
306
- await fileHandle.close()
307
- }
308
-
309
- // Verify device is in the platform config
310
- console.log('[SwitchBot UI] Verifying device was added...')
311
- const verifyDevices = platform.devices || []
312
- console.log('[SwitchBot UI] Platform now has', verifyDevices.length, 'devices')
313
-
314
- const deviceFound = verifyDevices.some((d: any) => String(d.deviceId ?? d.id ?? '').trim().toLowerCase() === normalizedDeviceId)
315
- console.log('[SwitchBot UI] Device found in platform?', deviceFound)
316
-
317
- if (!deviceFound) {
318
- console.error('[SwitchBot UI] ❌ VERIFICATION FAILED!')
319
- console.error('[SwitchBot UI] Expected to find deviceId:', normalizedDeviceId)
320
- console.error('[SwitchBot UI] But platform contains:', JSON.stringify(verifyDevices.map((d: any) => d.deviceId || d.id), null, 2))
321
- throw new Error('Device was not added to platform config')
322
- }
323
-
324
- console.log('[SwitchBot UI] ✓✓ Device successfully added and verified')
325
- console.log('[SwitchBot UI] ========== /add-device SUCCESS ==========')
3
+ import { registerConfigEndpoints } from './endpoints/config.js'
4
+ import { registerCredentialsEndpoint } from './endpoints/credentials.js'
5
+ import { registerDeviceEndpoints } from './endpoints/devices.js'
6
+ import { registerDiscoveryEndpoint } from './endpoints/discovery.js'
326
7
 
327
- return {
328
- success: true,
329
- data: {
330
- message: `Device "${name}" added successfully`,
331
- alreadyExists: false,
332
- added: true,
333
- },
334
- }
335
- } catch (e) {
336
- console.error('[SwitchBot UI] ❌❌ ERROR in /add-device:', e instanceof Error ? e.message : String(e))
337
- if (e instanceof Error) {
338
- console.error('[SwitchBot UI] Stack trace:', e.stack)
339
- }
340
- throw new RequestError(`Failed to add device: ${e instanceof Error ? e.message : String(e)}`, e)
341
- }
342
- })
343
-
344
- server.onRequest('/add-devices', async (body: any) => {
345
- try {
346
- const { devices } = body
347
-
348
- if (!Array.isArray(devices) || devices.length === 0) {
349
- throw new Error('Devices array is required and must not be empty')
350
- }
351
-
352
- console.log('[SwitchBot UI] POST /add-devices - Starting bulk add for', devices.length, 'device(s)')
353
-
354
- const { config, platform, cfgPath } = await getSwitchBotPlatformConfig()
355
-
356
- console.log('[SwitchBot UI] POST /add-devices - Config path:', cfgPath)
357
- console.log('[SwitchBot UI] POST /add-devices - Platform name:', platform.platform || platform.name)
358
- console.log('[SwitchBot UI] POST /add-devices - Current device count in platform:', (platform.devices || []).length)
359
-
360
- const deviceArrays = getDeviceArrays(platform)
361
- const allDevices = getAllDevices(platform)
362
-
363
- console.log('[SwitchBot UI] POST /add-devices - Existing devices in config:', allDevices.map((d: any) => d.deviceId || d.id).join(', '))
364
-
365
- let addedCount = 0
366
- let skippedCount = 0
367
- const results: Array<Record<string, any>> = []
368
-
369
- for (const { deviceId, name, type } of devices) {
370
- if (!deviceId) {
371
- results.push({ deviceId: '?', success: false, message: 'Device ID is required' })
372
- skippedCount++
373
- continue
374
- }
375
-
376
- const normalizedDeviceId = String(deviceId).trim().toLowerCase()
377
- const exists = allDevices.some((d: any) => String(d.deviceId ?? d.id ?? '').trim().toLowerCase() === normalizedDeviceId)
378
-
379
- if (exists) {
380
- console.log('[SwitchBot UI] Device already exists:', deviceId)
381
- results.push({ deviceId, success: true, message: 'Already in config', alreadyExists: true })
382
- skippedCount++
383
- continue
384
- }
385
-
386
- // Add device
387
- let addedToArray = false
388
- for (const ref of deviceArrays) {
389
- const refHasDevice = ref.some((d: any) => String(d.deviceId ?? d.id ?? '').trim().toLowerCase() === normalizedDeviceId)
390
- if (!refHasDevice) {
391
- const newDevice = {
392
- deviceId,
393
- configDeviceName: name,
394
- configDeviceType: type,
395
- }
396
- ref.push(newDevice)
397
- console.log('[SwitchBot UI] Pushed device to array:', deviceId, '- Array now has', ref.length, 'devices')
398
- addedToArray = true
399
- }
400
- }
401
-
402
- if (addedToArray) {
403
- results.push({ deviceId, success: true, message: `Device "${name}" added` })
404
- addedCount++
405
- } else {
406
- results.push({ deviceId, success: false, message: 'Failed to add device' })
407
- skippedCount++
408
- }
409
- }
410
-
411
- console.log('[SwitchBot UI] POST /add-devices - Processing complete. Added:', addedCount, 'Skipped:', skippedCount)
412
- console.log('[SwitchBot UI] POST /add-devices - Platform.devices after additions:', (platform.devices || []).length)
413
-
414
- // Save config with fsync
415
- const configJson = JSON.stringify(config, null, 2)
416
- console.log(`[SwitchBot UI] Writing bulk config to file (size: ${configJson.length} bytes, devices: ${addedCount})`)
417
-
418
- const fileHandle = await fs.open(cfgPath, 'w')
419
- try {
420
- await fileHandle.writeFile(configJson, 'utf8')
421
- await fileHandle.sync()
422
- console.log('[SwitchBot UI] ✓ Config file written and synced')
423
- } finally {
424
- await fileHandle.close()
425
- }
426
-
427
- console.log('[SwitchBot UI] Bulk device add completed: Added', addedCount, 'Skipped', skippedCount)
428
-
429
- return {
430
- success: true,
431
- data: {
432
- message: `Added ${addedCount} device(s)${skippedCount > 0 ? ` (${skippedCount} skipped)` : ''}`,
433
- addedCount,
434
- skippedCount,
435
- results,
436
- },
437
- }
438
- } catch (e) {
439
- console.error('[SwitchBot UI] Error in /add-devices:', e)
440
- throw new RequestError(`Failed to add devices: ${e instanceof Error ? e.message : String(e)}`, e)
441
- }
442
- })
443
-
444
- server.onRequest('/update-device', async (body: any) => {
445
- try {
446
- const { deviceId, configDeviceName, configDeviceType, connectionPreference, room } = body
447
-
448
- console.log('[SwitchBot UI] POST /update-device - Full request body:', JSON.stringify(body, null, 2))
449
-
450
- if (!deviceId) {
451
- throw new Error('Device ID is required')
452
- }
453
-
454
- const { config, platform, cfgPath } = await getSwitchBotPlatformConfig()
455
-
456
- console.log('[SwitchBot UI] POST /update-device - Updating device:', deviceId)
457
- console.log('[SwitchBot UI] Parameters - name:', configDeviceName, 'type:', configDeviceType, 'pref:', connectionPreference, 'room:', room)
458
-
459
- const deviceArrays = getDeviceArrays(platform)
460
- const devices = getAllDevices(platform)
461
- const normalizedDeviceId = String(deviceId).trim().toLowerCase()
462
- const device = devices.find((d: any) => String(d.deviceId ?? d.id ?? '').trim().toLowerCase() === normalizedDeviceId)
463
- if (!device) {
464
- console.error('[SwitchBot UI] Device not found. Available devices:', devices.map((d: any) => d.deviceId ?? d.id))
465
- throw new Error('Device not found in config')
466
- }
467
-
468
- console.log('[SwitchBot UI] Found device before update:', JSON.stringify(device, null, 2))
469
-
470
- // Update properties in all config branches
471
- for (const ref of deviceArrays) {
472
- for (const entry of ref) {
473
- const entryId = String(entry.deviceId ?? entry.id ?? '').trim().toLowerCase()
474
- if (entryId !== normalizedDeviceId) {
475
- continue
476
- }
477
-
478
- if (configDeviceName !== undefined && configDeviceName !== null && String(configDeviceName).trim() !== '') {
479
- entry.configDeviceName = configDeviceName
480
- }
481
- if (configDeviceType !== undefined && configDeviceType !== null && String(configDeviceType).trim() !== '') {
482
- entry.configDeviceType = configDeviceType
483
- }
484
- if (connectionPreference !== undefined) {
485
- entry.connectionPreference = connectionPreference
486
- }
487
- if (room !== undefined) {
488
- entry.room = room || undefined
489
- }
490
- }
491
- }
492
-
493
- if (configDeviceName !== undefined && configDeviceName !== null && String(configDeviceName).trim() !== '') {
494
- console.log('[SwitchBot UI] ✓ Updated configDeviceName to:', configDeviceName)
495
- }
496
- if (configDeviceType !== undefined && configDeviceType !== null && String(configDeviceType).trim() !== '') {
497
- console.log('[SwitchBot UI] ✓ Updated configDeviceType to:', configDeviceType)
498
- }
499
- if (connectionPreference !== undefined) {
500
- console.log('[SwitchBot UI] ✓ Updated connectionPreference to:', connectionPreference)
501
- }
502
- if (room !== undefined) {
503
- console.log('[SwitchBot UI] ✓ Updated room to:', room)
504
- }
505
-
506
- console.log('[SwitchBot UI] Device after updates:', JSON.stringify(device, null, 2))
507
-
508
- // Save config with fsync
509
- const configJson = JSON.stringify(config, null, 2)
510
- console.log(`[SwitchBot UI] Writing config to file (size: ${configJson.length} bytes)`)
511
-
512
- const fileHandle = await fs.open(cfgPath, 'w')
513
- try {
514
- await fileHandle.writeFile(configJson, 'utf8')
515
- await fileHandle.sync()
516
- console.log('[SwitchBot UI] ✓ Config file written and synced')
517
- } finally {
518
- await fileHandle.close()
519
- }
520
-
521
- console.log('[SwitchBot UI] Device updated successfully:', deviceId)
522
-
523
- return {
524
- success: true,
525
- data: { message: `Device updated successfully - type: ${configDeviceType || device.configDeviceType}` },
526
- }
527
- } catch (e) {
528
- console.error('[SwitchBot UI] Error in /update-device:', e instanceof Error ? e.message : String(e), e)
529
- throw new RequestError(`Failed to update device: ${e instanceof Error ? e.message : String(e)}`, e)
530
- }
531
- })
532
-
533
- server.onRequest('/delete-device', async (body: any) => {
534
- try {
535
- const { deviceId } = body
536
-
537
- if (!deviceId) {
538
- throw new Error('Device ID is required')
539
- }
540
-
541
- const { config, platform, cfgPath } = await getSwitchBotPlatformConfig()
542
-
543
- console.log('[SwitchBot UI] POST /delete-device - Deleting:', deviceId)
544
-
545
- const deviceArrays = getDeviceArrays(platform)
546
- const normalizedDeviceId = String(deviceId).trim().toLowerCase()
547
- const allDevices = getAllDevices(platform)
548
- const existing = allDevices.find((d: any) => String(d.deviceId ?? d.id ?? '').trim().toLowerCase() === normalizedDeviceId)
549
- if (!existing) {
550
- throw new Error('Device not found in config')
551
- }
552
-
553
- const deviceName = existing.configDeviceName || deviceId
554
- let removedCount = 0
555
- for (const ref of deviceArrays) {
556
- for (let i = ref.length - 1; i >= 0; i--) {
557
- const id = String(ref[i]?.deviceId ?? ref[i]?.id ?? '').trim().toLowerCase()
558
- if (id === normalizedDeviceId) {
559
- ref.splice(i, 1)
560
- removedCount++
561
- }
562
- }
563
- }
564
-
565
- if (!removedCount) {
566
- throw new Error('Device not found in config')
567
- }
568
-
569
- // Save config with fsync
570
- const configJson = JSON.stringify(config, null, 2)
571
- const fileHandle = await fs.open(cfgPath, 'w')
572
- try {
573
- await fileHandle.writeFile(configJson, 'utf8')
574
- await fileHandle.sync()
575
- console.log('[SwitchBot UI] ✓ Config file written and synced')
576
- } finally {
577
- await fileHandle.close()
578
- }
579
-
580
- console.log('[SwitchBot UI] Device deleted successfully:', deviceId)
581
-
582
- return {
583
- success: true,
584
- data: { message: `Device "${deviceName}" removed from config` },
585
- }
586
- } catch (e) {
587
- console.error('[SwitchBot UI] Error in /delete-device:', e)
588
- throw new RequestError('Failed to delete device', e)
589
- }
590
- })
591
-
592
- server.onRequest('/credentials', async (body: any) => {
593
- try {
594
- // Handle both GET and POST requests
595
- if (!body || Object.keys(body).length === 0) {
596
- // GET request - return current status
597
- const { platform } = await getSwitchBotPlatformConfig()
598
-
599
- const token = getCredential(platform, 'openApiToken')
600
- const secret = getCredential(platform, 'openApiSecret')
601
- const status = {
602
- hasToken: !!token,
603
- hasSecret: !!secret,
604
- tokenLength: token ? String(token).length : 0,
605
- secretLength: secret ? String(secret).length : 0,
606
- }
607
-
608
- console.log('[SwitchBot UI] GET /credentials - Status:', status)
609
- return { success: true, data: status }
610
- } else {
611
- // POST request - save credentials
612
- const { token, secret } = body
613
-
614
- if (!token || !secret) {
615
- throw new Error('Token and secret are required')
616
- }
617
-
618
- const { config, platform, cfgPath } = await getSwitchBotPlatformConfig()
619
-
620
- console.log('[SwitchBot UI] POST /credentials - Saving to platform:', platform.platform || platform.name)
621
- console.log('[SwitchBot UI] Config path:', cfgPath)
622
- console.log('[SwitchBot UI] Token length:', token.length, 'Secret length:', secret.length)
623
-
624
- // Save token and secret
625
- setCredential(platform, 'openApiToken', token)
626
- setCredential(platform, 'openApiSecret', secret)
627
-
628
- // Write config with fsync
629
- const configJson = JSON.stringify(config, null, 2)
630
- const fileHandle = await fs.open(cfgPath, 'w')
631
- try {
632
- await fileHandle.writeFile(configJson, 'utf8')
633
- await fileHandle.sync()
634
- console.log('[SwitchBot UI] ✓ Credentials saved and synced to disk')
635
- } finally {
636
- await fileHandle.close()
637
- }
8
+ const server = new HomebridgePluginUiServer()
638
9
 
639
- return {
640
- success: true,
641
- data: { message: 'Credentials saved successfully' },
642
- }
643
- }
644
- } catch (e) {
645
- console.error('[SwitchBot UI] Error in /credentials:', e)
646
- throw new RequestError('Failed to handle credentials request', e)
647
- }
648
- })
10
+ // Register all endpoints
11
+ registerConfigEndpoints(server)
12
+ registerDiscoveryEndpoint(server)
13
+ registerDeviceEndpoints(server)
14
+ registerCredentialsEndpoint(server)
649
15
 
650
16
  server.ready()
651
-
652
- export default server