@switchbot/homebridge-switchbot 5.0.0-beta.108 → 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 -624
  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 -624
  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,189 @@
1
+ // API wrapper functions for communicating with the Homebridge UI server
2
+ import './types.js'
3
+ import { uiLog } from './logger.js'
4
+
5
+ function isSwitchBotPlatformConfig(block: any): boolean {
6
+ const platformName = String(block?.platform || block?.name || '').toLowerCase()
7
+ return (
8
+ platformName === 'switchbot'
9
+ || platformName === '@switchbot/homebridge-switchbot'
10
+ || platformName.includes('switchbot')
11
+ )
12
+ }
13
+
14
+ export async function syncParentPluginConfigFromDisk(autoSave = false): Promise<boolean> {
15
+ try {
16
+ if (
17
+ typeof homebridge.getPluginConfig !== 'function'
18
+ || typeof homebridge.updatePluginConfig !== 'function'
19
+ ) {
20
+ uiLog.warn('Parent config sync API not available')
21
+ return false
22
+ }
23
+
24
+ const diskResp = await homebridge.request('/platform-config', {})
25
+ if (!diskResp || diskResp.success === false || !diskResp.data) {
26
+ uiLog.warn('Failed to fetch fresh platform config from disk')
27
+ return false
28
+ }
29
+
30
+ const pluginConfigBlocks = await homebridge.getPluginConfig()
31
+ if (!Array.isArray(pluginConfigBlocks) || !pluginConfigBlocks.length) {
32
+ uiLog.warn('No plugin config blocks returned from Homebridge')
33
+ return false
34
+ }
35
+
36
+ const index = pluginConfigBlocks.findIndex(block => isSwitchBotPlatformConfig(block))
37
+ if (index < 0) {
38
+ uiLog.warn('SwitchBot platform block not found in Homebridge plugin config')
39
+ return false
40
+ }
41
+
42
+ pluginConfigBlocks[index] = diskResp.data
43
+ await homebridge.updatePluginConfig(pluginConfigBlocks)
44
+
45
+ // Auto-save to disk if requested - prevents parent UI from overwriting with stale cache
46
+ if (autoSave && typeof homebridge.savePluginConfig === 'function') {
47
+ uiLog.info('Auto-saving config to disk...')
48
+ await homebridge.savePluginConfig()
49
+ uiLog.info('Config saved successfully')
50
+ }
51
+
52
+ return true
53
+ } catch (e) {
54
+ uiLog.warn('Failed to sync parent plugin config cache:', e)
55
+ return false
56
+ }
57
+ }
58
+
59
+ export async function fetchCredentialStatus(): Promise<any> {
60
+ try {
61
+ const resp = await homebridge.request('/credentials', {})
62
+ uiLog.info('Load credentials response:', resp)
63
+
64
+ if (!resp || resp.success === false) {
65
+ uiLog.error('Failed to load credentials:', resp)
66
+ return null
67
+ }
68
+
69
+ return resp.data || {}
70
+ } catch (e) {
71
+ uiLog.error('Error loading credentials:', e)
72
+ return null
73
+ }
74
+ }
75
+
76
+ export async function saveCredentials(token: string, secret: string): Promise<any> {
77
+ try {
78
+ uiLog.info('Saving credentials...')
79
+ const resp = await homebridge.request('/credentials', { token, secret })
80
+ uiLog.info('Save response:', resp)
81
+
82
+ if (!resp || resp.success === false) {
83
+ throw new Error(resp?.message || 'Save failed')
84
+ }
85
+
86
+ return resp.data || resp
87
+ } catch (e) {
88
+ throw e
89
+ }
90
+ }
91
+
92
+ export async function fetchDevices(): Promise<any[]> {
93
+ try {
94
+ const resp = await homebridge.request('/devices', {})
95
+ if (!resp || resp.success === false) { throw new Error(resp?.data?.message || 'request failed') }
96
+ return resp.data || []
97
+ } catch (e) {
98
+ uiLog.error('Error fetching devices:', e)
99
+ return []
100
+ }
101
+ }
102
+
103
+ export async function discoverDevices(): Promise<any[]> {
104
+ try {
105
+ const resp = await homebridge.request('/discover', {})
106
+ uiLog.info('Discover response:', resp)
107
+
108
+ if (!resp || resp.success === false) {
109
+ throw new Error(resp?.data?.message || 'Discovery failed')
110
+ }
111
+
112
+ return resp.data || []
113
+ } catch (e) {
114
+ throw e
115
+ }
116
+ }
117
+
118
+ export async function addDevice(deviceId: string, name: string, type: string): Promise<any> {
119
+ try {
120
+ uiLog.info('Adding device to config:', { deviceId, name, type })
121
+ const resp = await homebridge.request('/add-device', { deviceId, name, type })
122
+ uiLog.info('Add device response:', resp)
123
+
124
+ if (!resp || resp.success === false) {
125
+ throw new Error(resp?.data?.message || 'Failed to add device')
126
+ }
127
+
128
+ return resp.data || resp
129
+ } catch (e) {
130
+ throw e
131
+ }
132
+ }
133
+
134
+ export async function addDevicesInBulk(
135
+ devices: Array<{ deviceId: string, name: string, type: string }>,
136
+ ): Promise<any> {
137
+ try {
138
+ const resp = await homebridge.request('/add-devices', { devices })
139
+ uiLog.info('Bulk add response:', resp)
140
+
141
+ if (!resp || resp.success === false) {
142
+ throw new Error(resp?.data?.message || 'Bulk add failed')
143
+ }
144
+
145
+ return resp.data || resp
146
+ } catch (e) {
147
+ throw e
148
+ }
149
+ }
150
+
151
+ export async function updateDevice(
152
+ deviceId: string,
153
+ configDeviceName?: string,
154
+ configDeviceType?: string,
155
+ ): Promise<any> {
156
+ try {
157
+ const params: any = { deviceId }
158
+ if (configDeviceName) { params.configDeviceName = configDeviceName }
159
+ if (configDeviceType) { params.configDeviceType = configDeviceType }
160
+
161
+ uiLog.info('[Update Device] Sending update request with params:', params)
162
+ const resp = await homebridge.request('/update-device', params)
163
+ uiLog.info('[Update Device] Update response:', resp)
164
+
165
+ if (!resp || resp.success === false) {
166
+ throw new Error(resp?.data?.message || 'Failed to update device')
167
+ }
168
+
169
+ return resp.data || resp
170
+ } catch (e) {
171
+ throw e
172
+ }
173
+ }
174
+
175
+ export async function deleteDevice(deviceId: string): Promise<any> {
176
+ try {
177
+ uiLog.info('Sending delete request for deviceId:', deviceId)
178
+ const resp = await homebridge.request('/delete-device', { deviceId })
179
+ uiLog.info('Delete response:', resp)
180
+
181
+ if (!resp || resp.success === false) {
182
+ throw new Error(resp?.data?.message || 'Failed to delete device')
183
+ }
184
+
185
+ return resp.data || resp
186
+ } catch (e) {
187
+ throw e
188
+ }
189
+ }
@@ -0,0 +1,21 @@
1
+ import { loadCredentialStatus, saveCredentials } from './credentials.js'
2
+ import { loadConfiguredDevices } from './devices.js'
3
+ // Wire up global event handlers
4
+ import { discoverDevices } from './discovery.js';
5
+
6
+ (window as any).loadCredentialStatus = loadCredentialStatus
7
+ ;(window as any).saveCredentials = saveCredentials
8
+ ;(window as any).discoverDevices = discoverDevices
9
+
10
+ // Initialize on page load
11
+ async function init(): Promise<void> {
12
+ await loadCredentialStatus()
13
+ const list = await loadConfiguredDevices()
14
+ }
15
+
16
+ // Run initialization when DOM is ready
17
+ if (document.readyState === 'loading') {
18
+ document.addEventListener('DOMContentLoaded', init)
19
+ } else {
20
+ init()
21
+ }
@@ -0,0 +1 @@
1
+ export { DEVICE_TYPES } from '../../../device-types.js'
@@ -0,0 +1,100 @@
1
+ import { fetchCredentialStatus as apiFetchCredentialStatus, saveCredentials as apiSaveCredentials, syncParentPluginConfigFromDisk } from './api.js'
2
+ import { uiLog } from './logger.js'
3
+ import { hideBusyUi, showBusyUi } from './modal.js'
4
+ import { toastError, toastSuccess, toastWarning } from './toast.js'
5
+
6
+ export async function loadCredentialStatus(): Promise<void> {
7
+ try {
8
+ const creds = await apiFetchCredentialStatus()
9
+
10
+ if (!creds) {
11
+ uiLog.error('Failed to load credentials')
12
+ return
13
+ }
14
+
15
+ const tokenStatus = document.getElementById('tokenStatus')
16
+ const secretStatus = document.getElementById('secretStatus')
17
+
18
+ if (!tokenStatus || !secretStatus) { return }
19
+
20
+ if (creds.hasToken) {
21
+ tokenStatus.textContent = `✓ Configured (${creds.tokenLength} characters)`
22
+ tokenStatus.classList.add('ok')
23
+ } else {
24
+ tokenStatus.textContent = 'Not configured'
25
+ tokenStatus.classList.remove('ok')
26
+ }
27
+
28
+ if (creds.hasSecret) {
29
+ secretStatus.textContent = `✓ Configured (${creds.secretLength} characters)`
30
+ secretStatus.classList.add('ok')
31
+ } else {
32
+ secretStatus.textContent = 'Not configured'
33
+ secretStatus.classList.remove('ok')
34
+ }
35
+ } catch (e) {
36
+ uiLog.error('Error loading credentials:', e)
37
+ }
38
+ }
39
+
40
+ export async function saveCredentials(): Promise<void> {
41
+ const token = (document.getElementById('token') as HTMLInputElement)?.value
42
+ const secret = (document.getElementById('secret') as HTMLInputElement)?.value
43
+ const saveStatus = document.getElementById('saveStatus')
44
+ const saveBtn = document.getElementById('saveBtn') as HTMLButtonElement
45
+
46
+ if (!saveStatus || !saveBtn) { return }
47
+
48
+ if (!token || !secret) {
49
+ saveStatus.textContent = 'Please enter both token and secret'
50
+ saveStatus.classList.add('error')
51
+ toastWarning('Please enter both token and secret')
52
+ return
53
+ }
54
+
55
+ try {
56
+ showBusyUi()
57
+ saveBtn.disabled = true
58
+ saveBtn.textContent = 'Saving...'
59
+ uiLog.info('Saving credentials...')
60
+
61
+ const result = await apiSaveCredentials(token, secret)
62
+ uiLog.info('Save response:', result)
63
+
64
+ const message = result?.message || 'Credentials saved successfully'
65
+ saveStatus.textContent = `✓ ${message}`
66
+ saveStatus.classList.remove('error')
67
+ saveStatus.classList.add('success-msg')
68
+ toastSuccess(message)
69
+
70
+ const synced = await syncParentPluginConfigFromDisk(true)
71
+ if (synced) {
72
+ saveStatus.textContent += ' - Config saved automatically.'
73
+ toastSuccess('Configuration synced and saved automatically')
74
+ } else {
75
+ toastWarning('Credentials saved, but configuration sync failed')
76
+ }
77
+
78
+ // Clear inputs after successful save
79
+ ;(document.getElementById('token') as HTMLInputElement).value = ''
80
+ ;(document.getElementById('secret') as HTMLInputElement).value = ''
81
+
82
+ // Reload status to verify save
83
+ setTimeout(() => loadCredentialStatus(), 500)
84
+
85
+ // Clear status message
86
+ setTimeout(() => {
87
+ saveStatus.textContent = ''
88
+ saveStatus.classList.remove('success-msg')
89
+ }, 3000)
90
+ } catch (e) {
91
+ uiLog.error('Save error:', e)
92
+ saveStatus.textContent = `Error: ${e instanceof Error ? e.message : 'Failed to save'}`
93
+ saveStatus.classList.add('error')
94
+ toastError(e instanceof Error ? e.message : 'Failed to save credentials')
95
+ } finally {
96
+ hideBusyUi()
97
+ saveBtn.disabled = false
98
+ saveBtn.textContent = 'Save Credentials'
99
+ }
100
+ }
@@ -0,0 +1,113 @@
1
+ import { deleteDevice as apiDeleteDevice, syncParentPluginConfigFromDisk, fetchDevices } from './api.js'
2
+ import { uiLog } from './logger.js'
3
+ import { hideBusyUi, showBusyUi } from './modal.js'
4
+ import { renderDeviceList } from './render.js'
5
+ import { toastError, toastSuccess, toastWarning } from './toast.js'
6
+
7
+ async function confirmDeleteDialog(deviceNameOrId: string): Promise<boolean> {
8
+ return new Promise((resolve) => {
9
+ const overlay = document.createElement('div')
10
+ overlay.style.position = 'fixed'
11
+ overlay.style.top = '0'
12
+ overlay.style.left = '0'
13
+ overlay.style.width = '100%'
14
+ overlay.style.height = '100%'
15
+ overlay.style.background = 'rgba(0,0,0,0.6)'
16
+ overlay.style.display = 'flex'
17
+ overlay.style.alignItems = 'center'
18
+ overlay.style.justifyContent = 'center'
19
+ overlay.style.zIndex = '10000'
20
+
21
+ const modal = document.createElement('div')
22
+ modal.style.background = getComputedStyle(document.body).backgroundColor
23
+ modal.style.color = getComputedStyle(document.body).color
24
+ modal.style.padding = '20px'
25
+ modal.style.borderRadius = '10px'
26
+ modal.style.minWidth = '340px'
27
+ modal.style.maxWidth = '90vw'
28
+ modal.style.boxShadow = '0 12px 40px rgba(0,0,0,0.35)'
29
+
30
+ const title = document.createElement('h3')
31
+ title.textContent = 'Delete Device'
32
+ title.style.margin = '0 0 10px 0'
33
+
34
+ const message = document.createElement('p')
35
+ message.textContent = `Remove "${deviceNameOrId}" from configuration?`
36
+ message.style.margin = '0 0 16px 0'
37
+
38
+ const actions = document.createElement('div')
39
+ actions.style.display = 'flex'
40
+ actions.style.justifyContent = 'flex-end'
41
+ actions.style.gap = '8px'
42
+
43
+ const cancelBtn = document.createElement('button')
44
+ cancelBtn.textContent = 'Cancel'
45
+ cancelBtn.style.background = '#6b7280'
46
+
47
+ const deleteBtn = document.createElement('button')
48
+ deleteBtn.textContent = 'Delete'
49
+ deleteBtn.style.background = '#ef4444'
50
+
51
+ const cleanup = (result: boolean) => {
52
+ overlay.remove()
53
+ resolve(result)
54
+ }
55
+
56
+ cancelBtn.onclick = () => cleanup(false)
57
+ deleteBtn.onclick = () => cleanup(true)
58
+ overlay.addEventListener('click', (event) => {
59
+ if (event.target === overlay) {
60
+ cleanup(false)
61
+ }
62
+ })
63
+
64
+ actions.appendChild(cancelBtn)
65
+ actions.appendChild(deleteBtn)
66
+ modal.appendChild(title)
67
+ modal.appendChild(message)
68
+ modal.appendChild(actions)
69
+ overlay.appendChild(modal)
70
+ document.body.appendChild(overlay)
71
+ })
72
+ }
73
+
74
+ export async function deleteDeviceFromConfig(deviceId: string, deviceName: string): Promise<void> {
75
+ uiLog.info('Delete button clicked for device:', deviceId, deviceName)
76
+
77
+ const confirmed = await confirmDeleteDialog(deviceName || deviceId)
78
+ if (!confirmed) {
79
+ uiLog.info('Delete cancelled by user')
80
+ return
81
+ }
82
+
83
+ try {
84
+ showBusyUi()
85
+ uiLog.info('Sending delete request for deviceId:', deviceId)
86
+ const resp = await apiDeleteDevice(deviceId)
87
+ uiLog.info('Delete response:', resp)
88
+
89
+ if (!resp || resp.success === false) {
90
+ throw new Error(resp?.data?.message || 'Failed to delete device')
91
+ }
92
+
93
+ uiLog.info('Syncing parent config from disk...')
94
+ const synced = await syncParentPluginConfigFromDisk(true)
95
+ if (!synced) {
96
+ toastWarning('Device deleted, but configuration sync failed')
97
+ }
98
+
99
+ uiLog.info('Refreshing device list...')
100
+ // Refresh device list
101
+ const list = await fetchDevices()
102
+ uiLog.info('Rendering devices:', list.length)
103
+ renderDeviceList(list)
104
+
105
+ uiLog.info('✓ Device deleted successfully')
106
+ toastSuccess(`Device "${deviceName || deviceId}" deleted successfully`)
107
+ } catch (e) {
108
+ uiLog.error('Delete error:', e)
109
+ toastError(e instanceof Error ? e.message : 'Failed to delete device')
110
+ } finally {
111
+ hideBusyUi()
112
+ }
113
+ }
@@ -0,0 +1,78 @@
1
+ import { addDevice, fetchDevices, syncParentPluginConfigFromDisk } from './api.js'
2
+ import { uiLog } from './logger.js'
3
+ import { hideBusyUi, showBusyUi } from './modal.js'
4
+ import { renderDeviceList } from './render.js'
5
+ import { toastError, toastInfo, toastSuccess, toastWarning } from './toast.js'
6
+
7
+ export async function addDeviceToConfig(device: any, options: { refresh?: boolean, showStatus?: boolean } = {}): Promise<{ added: boolean }> {
8
+ const { refresh = true, showStatus = true } = options
9
+
10
+ try {
11
+ showBusyUi()
12
+ uiLog.info('Adding device to config:', device)
13
+ const resp = await addDevice(device.id, device.name, device.type)
14
+ uiLog.info('Add device response:', resp)
15
+
16
+ if (!resp || resp.success === false) {
17
+ throw new Error(resp?.data?.message || 'Failed to add device')
18
+ }
19
+
20
+ const alreadyExists = !!resp?.alreadyExists
21
+ const message
22
+ = resp?.message
23
+ || (alreadyExists
24
+ ? `Device "${device.name}" already in config`
25
+ : `Device "${device.name}" added successfully!`)
26
+
27
+ if (alreadyExists) {
28
+ toastInfo(message)
29
+ } else {
30
+ toastSuccess(message)
31
+ }
32
+
33
+ if (showStatus) {
34
+ const status = document.getElementById('discoverStatus')
35
+ if (status) {
36
+ status.textContent = (alreadyExists ? '• ' : '✓ ') + message
37
+ status.classList.remove('error')
38
+ status.classList.add('success-msg')
39
+
40
+ // Sync parent Homebridge form cache and auto-save to prevent cache overwrite
41
+ if (!alreadyExists) {
42
+ const synced = await syncParentPluginConfigFromDisk(true)
43
+ status.textContent += synced
44
+ ? ' - Config saved automatically.'
45
+ : ' - Warning: config may not persist until you close/reopen settings.'
46
+
47
+ if (synced) {
48
+ toastSuccess('Configuration synced and saved automatically')
49
+ } else {
50
+ toastWarning('Configuration sync failed; close and reopen settings before Save')
51
+ }
52
+ }
53
+ }
54
+ }
55
+
56
+ if (refresh) {
57
+ await loadConfiguredDevices()
58
+ }
59
+
60
+ return { added: !alreadyExists }
61
+ } catch (e) {
62
+ uiLog.error('Add device error:', e)
63
+ const status = document.getElementById('discoverStatus')
64
+ if (status) {
65
+ status.textContent = `✗ Error: ${e instanceof Error ? e.message : 'Failed to add device'}`
66
+ status.classList.add('error')
67
+ }
68
+ toastError(e instanceof Error ? e.message : 'Failed to add device')
69
+ return { added: false }
70
+ } finally {
71
+ hideBusyUi()
72
+ }
73
+ }
74
+
75
+ export async function loadConfiguredDevices(): Promise<void> {
76
+ const list = await fetchDevices()
77
+ renderDeviceList(list)
78
+ }
@@ -0,0 +1,123 @@
1
+ import {
2
+ addDevicesInBulk,
3
+ discoverDevices as apiDiscoverDevices,
4
+ fetchDevices,
5
+ syncParentPluginConfigFromDisk,
6
+ } from './api.js'
7
+ import { loadConfiguredDevices } from './devices.js'
8
+ import { uiLog } from './logger.js'
9
+ import { hideBusyUi, showBusyUi } from './modal.js'
10
+ import { renderDiscoveredDevices } from './render.js'
11
+ import { toastError, toastInfo, toastSuccess, toastWarning } from './toast.js'
12
+
13
+ export async function discoverDevices(): Promise<void> {
14
+ const btn = document.getElementById('discoverBtn') as HTMLButtonElement
15
+ const status = document.getElementById('discoverStatus')
16
+ const list = document.getElementById('discoveredList')
17
+ const autoAddAll = (document.getElementById('autoAddAllCheckbox') as HTMLInputElement)?.checked
18
+
19
+ if (!btn || !status || !list) { return }
20
+
21
+ try {
22
+ showBusyUi()
23
+ btn.disabled = true
24
+ btn.textContent = '🔍 Discovering...'
25
+ status.textContent = 'Searching SwitchBot account...'
26
+ status.classList.remove('error')
27
+
28
+ const devicesRaw = await apiDiscoverDevices()
29
+ uiLog.info('Discover response:', devicesRaw)
30
+
31
+ // Deduplicate by device ID
32
+ const devices = devicesRaw.filter((d, index, arr) => !!d?.id && arr.findIndex(x => x?.id === d.id) === index)
33
+
34
+ if (!devices.length) {
35
+ status.textContent = 'No devices found in your SwitchBot account'
36
+ toastInfo('No devices found in your SwitchBot account')
37
+ list.style.display = 'none'
38
+ return
39
+ }
40
+
41
+ // If auto-add is enabled, add all devices immediately using bulk endpoint
42
+ if (autoAddAll) {
43
+ status.textContent = `Auto-adding ${devices.length} device(s)...`
44
+
45
+ try {
46
+ const bulkResult = await addDevicesInBulk(
47
+ devices.map(d => ({
48
+ deviceId: d.id,
49
+ name: d.name,
50
+ type: d.type,
51
+ })),
52
+ )
53
+ uiLog.info('Bulk add response:', bulkResult)
54
+
55
+ if (!bulkResult || bulkResult.success === false) {
56
+ throw new Error(bulkResult?.data?.message || 'Bulk add failed')
57
+ }
58
+
59
+ const addedCount
60
+ = bulkResult?.addedCount
61
+ ?? bulkResult?.data?.addedCount
62
+ ?? 0
63
+ const skippedCount
64
+ = bulkResult?.skippedCount
65
+ ?? bulkResult?.data?.skippedCount
66
+ ?? 0
67
+ status.textContent = `✓ Added ${addedCount} device(s)${skippedCount > 0 ? ` (${skippedCount} skipped)` : ''}`
68
+ if (addedCount > 0) {
69
+ toastSuccess(`Added ${addedCount} device(s)${skippedCount > 0 ? ` (${skippedCount} skipped)` : ''}`)
70
+ } else if (skippedCount > 0) {
71
+ toastWarning(`No new devices were added (${skippedCount} skipped)`)
72
+ }
73
+ status.classList.remove('error')
74
+ list.style.display = 'none'
75
+
76
+ // Sync parent Homebridge form cache and auto-save to prevent cache overwrite
77
+ // Run sync when discovery returned devices (even if backend response shape changes)
78
+ if (devices.length > 0) {
79
+ const synced = await syncParentPluginConfigFromDisk(true)
80
+ status.textContent += synced
81
+ ? ' - Config saved automatically.'
82
+ : ' - Warning: config may not persist until you close/reopen settings.'
83
+
84
+ if (synced) {
85
+ toastSuccess('Configuration synced and saved automatically')
86
+ } else {
87
+ toastWarning('Configuration sync failed; close and reopen settings before Save')
88
+ }
89
+ }
90
+ } catch (e) {
91
+ uiLog.error('Bulk add error:', e)
92
+ status.textContent = `✗ Error: ${e instanceof Error ? e.message : 'Failed to add devices'}`
93
+ status.classList.add('error')
94
+ toastError(e instanceof Error ? e.message : 'Failed to add devices')
95
+ }
96
+
97
+ // Refresh the configured devices list
98
+ await loadConfiguredDevices()
99
+ return
100
+ }
101
+
102
+ status.textContent = `Found ${devices.length} device(s)`
103
+ const ul = await renderDiscoveredDevices(devices)
104
+ document.getElementById('discoveredDevices')?.replaceWith(ul)
105
+ ul.id = 'discoveredDevices'
106
+ list.style.display = 'block'
107
+ } catch (e) {
108
+ uiLog.error('Discovery error:', e)
109
+ status.textContent = `Error: ${e instanceof Error ? e.message : 'Discovery failed'}`
110
+ status.classList.add('error')
111
+ toastError(e instanceof Error ? e.message : 'Discovery failed')
112
+ list.style.display = 'none'
113
+ } finally {
114
+ hideBusyUi()
115
+ btn.disabled = false
116
+ btn.textContent = '🔍 Discover Devices'
117
+ }
118
+ }
119
+
120
+ export async function addDeviceToConfig(device: any): Promise<void> {
121
+ const { addDeviceToConfig: addDevice } = await import('./devices.js')
122
+ await addDevice(device)
123
+ }
@@ -0,0 +1,11 @@
1
+ export const uiLog = {
2
+ info: (message: string, ...parameters: any[]): void => {
3
+ console.warn('[SwitchBot UI]', message, ...parameters)
4
+ },
5
+ warn: (message: string, ...parameters: any[]): void => {
6
+ console.warn('[SwitchBot UI]', message, ...parameters)
7
+ },
8
+ error: (message: string, ...parameters: any[]): void => {
9
+ console.error('[SwitchBot UI]', message, ...parameters)
10
+ },
11
+ }
@@ -0,0 +1,28 @@
1
+ import './types.js'
2
+ import { uiLog } from './logger.js'
3
+
4
+ function callUiMethod(name: keyof HomebridgePluginUiAPI): void {
5
+ try {
6
+ const value = homebridge?.[name]
7
+ if (typeof value === 'function') {
8
+ const fn = value as () => void
9
+ fn()
10
+ }
11
+ } catch (e) {
12
+ uiLog.warn(`Homebridge UI method ${String(name)} failed:`, e)
13
+ }
14
+ }
15
+
16
+ export function showBusyUi(): void {
17
+ callUiMethod('disableSaveButton')
18
+ callUiMethod('showSpinner')
19
+ }
20
+
21
+ export function hideBusyUi(): void {
22
+ callUiMethod('hideSpinner')
23
+ callUiMethod('enableSaveButton')
24
+ }
25
+
26
+ export function closeSettingsModal(): void {
27
+ callUiMethod('closeSettings')
28
+ }