@switchbot/homebridge-switchbot 5.0.0-beta.112 → 5.0.0-beta.113
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/MIGRATION.md +10 -0
- package/README.md +43 -0
- package/TODO.md +263 -0
- package/config.schema.json +27 -10
- package/dist/device-types.d.ts.map +1 -1
- package/dist/device-types.js +93 -63
- package/dist/device-types.js.map +1 -1
- package/dist/deviceFactory.d.ts.map +1 -1
- package/dist/deviceFactory.js +55 -33
- package/dist/deviceFactory.js.map +1 -1
- package/dist/devices/genericDevice.d.ts +12 -1
- package/dist/devices/genericDevice.d.ts.map +1 -1
- package/dist/devices/genericDevice.js +121 -1
- package/dist/devices/genericDevice.js.map +1 -1
- package/dist/errors.d.ts +5 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +51 -0
- package/dist/errors.js.map +1 -0
- package/dist/homebridge-ui/endpoints/devices.d.ts.map +1 -1
- package/dist/homebridge-ui/endpoints/devices.js +80 -1
- package/dist/homebridge-ui/endpoints/devices.js.map +1 -1
- package/dist/homebridge-ui/endpoints/discovery.d.ts.map +1 -1
- package/dist/homebridge-ui/endpoints/discovery.js +73 -41
- package/dist/homebridge-ui/endpoints/discovery.js.map +1 -1
- package/dist/homebridge-ui/public/css/styles.css +98 -0
- package/dist/homebridge-ui/public/index.html +57 -0
- package/dist/homebridge-ui/public/js/api.d.ts +24 -1
- package/dist/homebridge-ui/public/js/api.d.ts.map +1 -1
- package/dist/homebridge-ui/public/js/api.js +33 -2
- package/dist/homebridge-ui/public/js/api.js.map +1 -1
- package/dist/homebridge-ui/public/js/api.ts +52 -3
- package/dist/homebridge-ui/public/js/app.js +1503 -104
- package/dist/homebridge-ui/public/js/app.js.map +3 -3
- package/dist/homebridge-ui/public/js/app.ts +2 -1
- package/dist/homebridge-ui/public/js/devices.d.ts.map +1 -1
- package/dist/homebridge-ui/public/js/devices.js +2 -0
- package/dist/homebridge-ui/public/js/devices.js.map +1 -1
- package/dist/homebridge-ui/public/js/devices.ts +13 -1
- package/dist/homebridge-ui/public/js/discovery.d.ts +1 -0
- package/dist/homebridge-ui/public/js/discovery.d.ts.map +1 -1
- package/dist/homebridge-ui/public/js/discovery.js +1223 -126
- package/dist/homebridge-ui/public/js/discovery.js.map +1 -1
- package/dist/homebridge-ui/public/js/discovery.ts +1323 -145
- package/dist/homebridge-ui/public/js/modals.d.ts.map +1 -1
- package/dist/homebridge-ui/public/js/modals.js +42 -0
- package/dist/homebridge-ui/public/js/modals.js.map +1 -1
- package/dist/homebridge-ui/public/js/modals.ts +50 -1
- package/dist/homebridge-ui/public/js/render.d.ts +3 -0
- package/dist/homebridge-ui/public/js/render.d.ts.map +1 -1
- package/dist/homebridge-ui/public/js/render.js +311 -1
- package/dist/homebridge-ui/public/js/render.js.map +1 -1
- package/dist/homebridge-ui/public/js/render.ts +341 -2
- package/dist/platform.d.ts +1 -0
- package/dist/platform.d.ts.map +1 -1
- package/dist/platform.js +6 -2
- package/dist/platform.js.map +1 -1
- package/dist/switchbotClient.d.ts.map +1 -1
- package/dist/switchbotClient.js +51 -5
- package/dist/switchbotClient.js.map +1 -1
- package/docs/assets/highlight.css +9 -2
- package/docs/index.html +28 -2
- package/docs/variables/default.html +1 -1
- package/package.json +2 -2
- package/src/device-types.ts +95 -64
- package/src/deviceFactory.ts +55 -33
- package/src/devices/genericDevice.ts +113 -1
- package/src/errors.ts +43 -0
- package/src/homebridge-ui/endpoints/devices.ts +82 -1
- package/src/homebridge-ui/endpoints/discovery.ts +78 -44
- package/src/homebridge-ui/public/css/styles.css +98 -0
- package/src/homebridge-ui/public/index.html +57 -0
- package/src/homebridge-ui/public/js/api.ts +52 -3
- package/src/homebridge-ui/public/js/app.ts +2 -1
- package/src/homebridge-ui/public/js/devices.ts +13 -1
- package/src/homebridge-ui/public/js/discovery.ts +1323 -145
- package/src/homebridge-ui/public/js/modals.ts +50 -1
- package/src/homebridge-ui/public/js/render.ts +341 -2
- package/src/platform.ts +6 -2
- package/src/switchbotClient.ts +44 -9
- package/test/matter-integration.spec.ts +21 -0
- package/todo/COMPLETED.md +300 -0
- package/todo/TODO.md +80 -66
|
@@ -1,99 +1,516 @@
|
|
|
1
|
-
|
|
1
|
+
// Batch enable/disable helper (true module scope for UI access)
|
|
2
|
+
import { addDevicesInBulk, discoverDevices as apiDiscoverDevices, fetchBluetoothStatus,
|
|
3
|
+
// fetchDevices, // removed unused import
|
|
4
|
+
syncParentPluginConfigFromDisk, } from './api.js';
|
|
2
5
|
import { loadConfiguredDevices } from './devices.js';
|
|
3
6
|
import { uiLog } from './logger.js';
|
|
4
7
|
import { hideBusyUi, showBusyUi } from './modal.js';
|
|
5
|
-
import {
|
|
8
|
+
import { getDiscoveryPreferences, renderDiscoveredDevices, setDiscoveryPreferences } from './render.js';
|
|
6
9
|
import { toastError, toastInfo, toastSuccess, toastWarning } from './toast.js';
|
|
10
|
+
async function batchSetDeviceEnabled(selectedIds, enabled) {
|
|
11
|
+
// Fetch current config
|
|
12
|
+
const resp = await homebridge.request('/platform-config', {});
|
|
13
|
+
if (!resp || resp.success === false || !resp.data) {
|
|
14
|
+
throw new Error('Failed to load config');
|
|
15
|
+
}
|
|
16
|
+
const config = resp.data;
|
|
17
|
+
// Homebridge config may be an array of platforms, find SwitchBot
|
|
18
|
+
const configArr = Array.isArray(config) ? config : [config];
|
|
19
|
+
const platformIdx = configArr.findIndex((c) => (c.platform || c.name || '').toLowerCase().includes('switchbot'));
|
|
20
|
+
if (platformIdx === -1) {
|
|
21
|
+
throw new Error('SwitchBot platform config not found');
|
|
22
|
+
}
|
|
23
|
+
const platformConfig = configArr[platformIdx];
|
|
24
|
+
if (!Array.isArray(platformConfig.devices)) {
|
|
25
|
+
throw new TypeError('No devices array in config');
|
|
26
|
+
}
|
|
27
|
+
let changed = false;
|
|
28
|
+
for (const dev of platformConfig.devices) {
|
|
29
|
+
const id = String(dev.deviceId || dev.id || '').trim().toLowerCase();
|
|
30
|
+
if (selectedIds.has(id)) {
|
|
31
|
+
if (dev.enabled !== enabled) {
|
|
32
|
+
dev.enabled = enabled;
|
|
33
|
+
changed = true;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
if (changed) {
|
|
38
|
+
if (typeof homebridge.updatePluginConfig === 'function') {
|
|
39
|
+
await homebridge.updatePluginConfig(configArr);
|
|
40
|
+
}
|
|
41
|
+
else {
|
|
42
|
+
throw new TypeError('homebridge.updatePluginConfig is not available');
|
|
43
|
+
}
|
|
44
|
+
if (typeof homebridge.savePluginConfig === 'function') {
|
|
45
|
+
await homebridge.savePluginConfig();
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
7
49
|
function normalizeId(value) {
|
|
8
50
|
return String(value ?? '').trim().toLowerCase();
|
|
9
51
|
}
|
|
52
|
+
function dedupeById(devices) {
|
|
53
|
+
return devices.filter((d, index, arr) => !!d?.id && arr.findIndex(x => x?.id === d.id) === index);
|
|
54
|
+
}
|
|
55
|
+
function mergeDiscoveredDevices(existingDevices, incomingDevices) {
|
|
56
|
+
const deviceMap = new Map();
|
|
57
|
+
for (const d of dedupeById(existingDevices)) {
|
|
58
|
+
deviceMap.set(d.id, { ...d });
|
|
59
|
+
}
|
|
60
|
+
for (const d of dedupeById(incomingDevices)) {
|
|
61
|
+
const current = deviceMap.get(d.id);
|
|
62
|
+
if (current) {
|
|
63
|
+
const nextConnectionType = current.connectionType === d.connectionType
|
|
64
|
+
? current.connectionType
|
|
65
|
+
: 'Both';
|
|
66
|
+
deviceMap.set(d.id, {
|
|
67
|
+
...current,
|
|
68
|
+
...d,
|
|
69
|
+
connectionType: nextConnectionType,
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
else {
|
|
73
|
+
deviceMap.set(d.id, { ...d });
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return [...deviceMap.values()];
|
|
77
|
+
}
|
|
78
|
+
const DISCOVERY_GROUP_BY_KEY = 'discoveryGroupBy';
|
|
79
|
+
const DISCOVERY_GROUP_EXPANDED_KEY = 'discoveryGroupExpanded';
|
|
80
|
+
const DISCOVERY_BLE_SETTINGS_KEY = 'discoveryBleSettings';
|
|
81
|
+
const DISCOVERY_HIDE_ADDED_KEY = 'discoveryHideAdded';
|
|
82
|
+
const DISCOVERY_CACHE_KEY = 'discoveryCache';
|
|
83
|
+
const DISCOVERY_AUTO_REFRESH_KEY = 'discoveryAutoRefreshSeconds';
|
|
84
|
+
const DISCOVERY_CACHE_TTL_MS = 5 * 60 * 1000;
|
|
85
|
+
let discoveryAutoRefreshTimer = null;
|
|
86
|
+
let discoveryLastScannedTimer = null;
|
|
87
|
+
function setDiscoveryCache(devices) {
|
|
88
|
+
try {
|
|
89
|
+
const payload = { timestamp: Date.now(), devices };
|
|
90
|
+
localStorage.setItem(DISCOVERY_CACHE_KEY, JSON.stringify(payload));
|
|
91
|
+
}
|
|
92
|
+
catch (_e) {
|
|
93
|
+
// Ignore storage errors
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
function clearDiscoveryCache() {
|
|
97
|
+
try {
|
|
98
|
+
localStorage.removeItem(DISCOVERY_CACHE_KEY);
|
|
99
|
+
}
|
|
100
|
+
catch (_e) {
|
|
101
|
+
// Ignore storage errors
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
function getDiscoveryCache(validOnly = true) {
|
|
105
|
+
try {
|
|
106
|
+
const stored = localStorage.getItem(DISCOVERY_CACHE_KEY);
|
|
107
|
+
if (!stored) {
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
110
|
+
const payload = JSON.parse(stored);
|
|
111
|
+
if (!payload || !Array.isArray(payload.devices) || typeof payload.timestamp !== 'number') {
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
const age = Date.now() - payload.timestamp;
|
|
115
|
+
if (validOnly && age > DISCOVERY_CACHE_TTL_MS) {
|
|
116
|
+
return null;
|
|
117
|
+
}
|
|
118
|
+
return payload;
|
|
119
|
+
}
|
|
120
|
+
catch (_e) {
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
function getDiscoveryAutoRefreshSeconds() {
|
|
125
|
+
try {
|
|
126
|
+
const stored = localStorage.getItem(DISCOVERY_AUTO_REFRESH_KEY);
|
|
127
|
+
const value = Number(stored || 0);
|
|
128
|
+
return Number.isFinite(value) && value >= 0 ? value : 0;
|
|
129
|
+
}
|
|
130
|
+
catch (_e) {
|
|
131
|
+
return 0;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
function setDiscoveryAutoRefreshSeconds(value) {
|
|
135
|
+
try {
|
|
136
|
+
localStorage.setItem(DISCOVERY_AUTO_REFRESH_KEY, String(Math.max(0, value)));
|
|
137
|
+
}
|
|
138
|
+
catch (_e) {
|
|
139
|
+
// Ignore storage errors
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
function getDiscoveryHideAddedPreference() {
|
|
143
|
+
try {
|
|
144
|
+
return localStorage.getItem(DISCOVERY_HIDE_ADDED_KEY) === 'true';
|
|
145
|
+
}
|
|
146
|
+
catch (_e) {
|
|
147
|
+
return false;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
function setDiscoveryHideAddedPreference(value) {
|
|
151
|
+
try {
|
|
152
|
+
localStorage.setItem(DISCOVERY_HIDE_ADDED_KEY, String(value));
|
|
153
|
+
}
|
|
154
|
+
catch (_e) {
|
|
155
|
+
// Ignore storage errors
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
function formatElapsedShort(ms) {
|
|
159
|
+
const totalSeconds = Math.max(0, Math.floor(ms / 1000));
|
|
160
|
+
if (totalSeconds < 60) {
|
|
161
|
+
return `${totalSeconds}s ago`;
|
|
162
|
+
}
|
|
163
|
+
const minutes = Math.floor(totalSeconds / 60);
|
|
164
|
+
if (minutes < 60) {
|
|
165
|
+
return `${minutes}m ago`;
|
|
166
|
+
}
|
|
167
|
+
const hours = Math.floor(minutes / 60);
|
|
168
|
+
if (hours < 24) {
|
|
169
|
+
return `${hours}h ago`;
|
|
170
|
+
}
|
|
171
|
+
const days = Math.floor(hours / 24);
|
|
172
|
+
return `${days}d ago`;
|
|
173
|
+
}
|
|
174
|
+
function updateLastScannedStatus() {
|
|
175
|
+
const lastScannedStatus = document.getElementById('lastScannedStatus');
|
|
176
|
+
if (!lastScannedStatus) {
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
const cache = getDiscoveryCache(false);
|
|
180
|
+
if (!cache) {
|
|
181
|
+
lastScannedStatus.textContent = 'Last scanned: never';
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
const ageMs = Date.now() - cache.timestamp;
|
|
185
|
+
const timestampText = new Date(cache.timestamp).toLocaleString();
|
|
186
|
+
const stale = ageMs > DISCOVERY_CACHE_TTL_MS;
|
|
187
|
+
lastScannedStatus.textContent = stale
|
|
188
|
+
? `Last scanned: ${formatElapsedShort(ageMs)} (${timestampText}, cache expired)`
|
|
189
|
+
: `Last scanned: ${formatElapsedShort(ageMs)} (${timestampText})`;
|
|
190
|
+
}
|
|
191
|
+
async function renderCachedDiscoveryResults() {
|
|
192
|
+
const cache = getDiscoveryCache(true);
|
|
193
|
+
const list = document.getElementById('discoveredList');
|
|
194
|
+
if (!cache || !list || !cache.devices.length) {
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
list.style.display = 'block';
|
|
198
|
+
// Use type-safe property for window._discoverySelectedIds
|
|
199
|
+
if (!window._discoverySelectedIds) {
|
|
200
|
+
window._discoverySelectedIds = new Set();
|
|
201
|
+
}
|
|
202
|
+
await updateDiscoveryView(cache.devices, getDiscoveryPreferences(), getDiscoveryGroupByPreference(), getDiscoveryHideAddedPreference(), window._discoverySelectedIds);
|
|
203
|
+
}
|
|
204
|
+
function getDiscoveryBleSettings() {
|
|
205
|
+
try {
|
|
206
|
+
const stored = localStorage.getItem(DISCOVERY_BLE_SETTINGS_KEY);
|
|
207
|
+
if (!stored) {
|
|
208
|
+
return { bleEnabled: true, bleScanDurationSeconds: 5, bleTimeoutSeconds: 8 };
|
|
209
|
+
}
|
|
210
|
+
const parsed = JSON.parse(stored);
|
|
211
|
+
return {
|
|
212
|
+
bleEnabled: parsed?.bleEnabled !== false,
|
|
213
|
+
bleScanDurationSeconds: Math.max(3, Math.min(15, Number(parsed?.bleScanDurationSeconds || 5))),
|
|
214
|
+
bleTimeoutSeconds: Math.max(3, Math.min(30, Number(parsed?.bleTimeoutSeconds || 8))),
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
catch (_e) {
|
|
218
|
+
return { bleEnabled: true, bleScanDurationSeconds: 5, bleTimeoutSeconds: 8 };
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
function setDiscoveryBleSettings(settings) {
|
|
222
|
+
try {
|
|
223
|
+
localStorage.setItem(DISCOVERY_BLE_SETTINGS_KEY, JSON.stringify(settings));
|
|
224
|
+
}
|
|
225
|
+
catch (_e) {
|
|
226
|
+
// Ignore storage errors
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
export async function initializeDiscoverySettings() {
|
|
230
|
+
const scanSelect = document.getElementById('bleScanDurationSelect');
|
|
231
|
+
const timeoutInput = document.getElementById('bleTimeoutInput');
|
|
232
|
+
const disableBleCheckbox = document.getElementById('disableBleScanCheckbox');
|
|
233
|
+
const scanSetting = document.getElementById('bleScanSetting');
|
|
234
|
+
const timeoutSetting = document.getElementById('bleTimeoutSetting');
|
|
235
|
+
const bluetoothStatus = document.getElementById('bluetoothStatus');
|
|
236
|
+
const autoRefreshSelect = document.getElementById('autoRefreshIntervalSelect');
|
|
237
|
+
const refreshBtn = document.getElementById('refreshDiscoverBtn');
|
|
238
|
+
const current = getDiscoveryBleSettings();
|
|
239
|
+
if (scanSelect) {
|
|
240
|
+
scanSelect.value = String(current.bleScanDurationSeconds);
|
|
241
|
+
}
|
|
242
|
+
if (timeoutInput) {
|
|
243
|
+
timeoutInput.value = String(current.bleTimeoutSeconds);
|
|
244
|
+
}
|
|
245
|
+
if (disableBleCheckbox) {
|
|
246
|
+
disableBleCheckbox.checked = !current.bleEnabled;
|
|
247
|
+
}
|
|
248
|
+
if (autoRefreshSelect) {
|
|
249
|
+
autoRefreshSelect.value = String(getDiscoveryAutoRefreshSeconds());
|
|
250
|
+
}
|
|
251
|
+
const updateBleSettingVisibility = () => {
|
|
252
|
+
const disabled = !!disableBleCheckbox?.checked;
|
|
253
|
+
if (scanSetting) {
|
|
254
|
+
scanSetting.style.display = disabled ? 'none' : 'inline-flex';
|
|
255
|
+
}
|
|
256
|
+
if (timeoutSetting) {
|
|
257
|
+
timeoutSetting.style.display = disabled ? 'none' : 'inline-flex';
|
|
258
|
+
}
|
|
259
|
+
};
|
|
260
|
+
const persistFromControls = () => {
|
|
261
|
+
const next = {
|
|
262
|
+
bleEnabled: !(disableBleCheckbox?.checked ?? false),
|
|
263
|
+
bleScanDurationSeconds: Math.max(3, Math.min(15, Number(scanSelect?.value || 5))),
|
|
264
|
+
bleTimeoutSeconds: Math.max(3, Math.min(30, Number(timeoutInput?.value || 8))),
|
|
265
|
+
};
|
|
266
|
+
setDiscoveryBleSettings(next);
|
|
267
|
+
};
|
|
268
|
+
scanSelect?.addEventListener('change', persistFromControls);
|
|
269
|
+
timeoutInput?.addEventListener('change', persistFromControls);
|
|
270
|
+
disableBleCheckbox?.addEventListener('change', () => {
|
|
271
|
+
persistFromControls();
|
|
272
|
+
updateBleSettingVisibility();
|
|
273
|
+
});
|
|
274
|
+
updateBleSettingVisibility();
|
|
275
|
+
if (bluetoothStatus) {
|
|
276
|
+
const status = await fetchBluetoothStatus();
|
|
277
|
+
bluetoothStatus.textContent = status.available
|
|
278
|
+
? `Bluetooth: available (${status.message})`
|
|
279
|
+
: `Bluetooth: unavailable (${status.message})`;
|
|
280
|
+
}
|
|
281
|
+
updateLastScannedStatus();
|
|
282
|
+
if (discoveryLastScannedTimer) {
|
|
283
|
+
clearInterval(discoveryLastScannedTimer);
|
|
284
|
+
}
|
|
285
|
+
discoveryLastScannedTimer = setInterval(updateLastScannedStatus, 15000);
|
|
286
|
+
refreshBtn?.addEventListener('click', () => {
|
|
287
|
+
void discoverDevices();
|
|
288
|
+
});
|
|
289
|
+
const applyAutoRefresh = () => {
|
|
290
|
+
const seconds = Math.max(0, Number(autoRefreshSelect?.value || 0));
|
|
291
|
+
setDiscoveryAutoRefreshSeconds(seconds);
|
|
292
|
+
if (discoveryAutoRefreshTimer) {
|
|
293
|
+
clearInterval(discoveryAutoRefreshTimer);
|
|
294
|
+
discoveryAutoRefreshTimer = null;
|
|
295
|
+
}
|
|
296
|
+
if (seconds > 0) {
|
|
297
|
+
discoveryAutoRefreshTimer = setInterval(() => {
|
|
298
|
+
const discoverBtn = document.getElementById('discoverBtn');
|
|
299
|
+
if (!discoverBtn || discoverBtn.disabled || document.hidden) {
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
void discoverDevices();
|
|
303
|
+
}, seconds * 1000);
|
|
304
|
+
}
|
|
305
|
+
};
|
|
306
|
+
autoRefreshSelect?.addEventListener('change', applyAutoRefresh);
|
|
307
|
+
applyAutoRefresh();
|
|
308
|
+
await renderCachedDiscoveryResults();
|
|
309
|
+
}
|
|
310
|
+
function getDiscoveryGroupByPreference() {
|
|
311
|
+
try {
|
|
312
|
+
const stored = localStorage.getItem(DISCOVERY_GROUP_BY_KEY);
|
|
313
|
+
if (stored === 'hub' || stored === 'type') {
|
|
314
|
+
return stored;
|
|
315
|
+
}
|
|
316
|
+
return 'connection';
|
|
317
|
+
}
|
|
318
|
+
catch (_e) {
|
|
319
|
+
return 'connection';
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
function setDiscoveryGroupByPreference(groupBy) {
|
|
323
|
+
try {
|
|
324
|
+
localStorage.setItem(DISCOVERY_GROUP_BY_KEY, groupBy);
|
|
325
|
+
}
|
|
326
|
+
catch (_e) {
|
|
327
|
+
// Ignore storage errors
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
function getDiscoveryGroupExpandedState() {
|
|
331
|
+
try {
|
|
332
|
+
const stored = localStorage.getItem(DISCOVERY_GROUP_EXPANDED_KEY);
|
|
333
|
+
if (!stored) {
|
|
334
|
+
return {};
|
|
335
|
+
}
|
|
336
|
+
const parsed = JSON.parse(stored);
|
|
337
|
+
return typeof parsed === 'object' && parsed ? parsed : {};
|
|
338
|
+
}
|
|
339
|
+
catch (_e) {
|
|
340
|
+
return {};
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
function setDiscoveryGroupExpandedState(state) {
|
|
344
|
+
try {
|
|
345
|
+
localStorage.setItem(DISCOVERY_GROUP_EXPANDED_KEY, JSON.stringify(state));
|
|
346
|
+
}
|
|
347
|
+
catch (_e) {
|
|
348
|
+
// Ignore storage errors
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
function isDiscoveryGroupExpanded(groupKey) {
|
|
352
|
+
const state = getDiscoveryGroupExpandedState();
|
|
353
|
+
return state[groupKey] !== false;
|
|
354
|
+
}
|
|
355
|
+
function setDiscoveryGroupExpanded(groupKey, expanded) {
|
|
356
|
+
const state = getDiscoveryGroupExpandedState();
|
|
357
|
+
state[groupKey] = expanded;
|
|
358
|
+
setDiscoveryGroupExpandedState(state);
|
|
359
|
+
}
|
|
10
360
|
export async function discoverDevices() {
|
|
11
361
|
const btn = document.getElementById('discoverBtn');
|
|
362
|
+
const cancelBtn = document.getElementById('cancelDiscoverBtn');
|
|
12
363
|
const status = document.getElementById('discoverStatus');
|
|
364
|
+
const phaseProgress = document.getElementById('discoverPhaseProgress');
|
|
365
|
+
const phaseFill = document.getElementById('discoverPhaseFill');
|
|
366
|
+
const phaseLabel = document.getElementById('discoverPhaseLabel');
|
|
13
367
|
const list = document.getElementById('discoveredList');
|
|
14
368
|
const autoAddAll = document.getElementById('autoAddAllCheckbox')?.checked;
|
|
369
|
+
const scanSelect = document.getElementById('bleScanDurationSelect');
|
|
370
|
+
const timeoutInput = document.getElementById('bleTimeoutInput');
|
|
371
|
+
const disableBleCheckbox = document.getElementById('disableBleScanCheckbox');
|
|
15
372
|
if (!btn || !status || !list) {
|
|
16
373
|
return;
|
|
17
374
|
}
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
375
|
+
const spinnerFrames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
|
|
376
|
+
let spinnerIndex = 0;
|
|
377
|
+
const startedAt = Date.now();
|
|
378
|
+
let phaseStartedAt = startedAt;
|
|
379
|
+
let phase = 'Preparing discovery...';
|
|
380
|
+
let cancelled = false;
|
|
381
|
+
// --- Real-time RSSI polling additions ---
|
|
382
|
+
// Get BLE scan duration from settings or UI
|
|
383
|
+
const bleScanDurationSeconds = scanSelect ? Number(scanSelect.value) : 5;
|
|
384
|
+
const pollIntervalMs = 1000; // 1s polling
|
|
385
|
+
const scanEndTime = Date.now() + bleScanDurationSeconds * 1000;
|
|
386
|
+
const setPhase = (nextPhase) => {
|
|
387
|
+
phase = nextPhase;
|
|
388
|
+
phaseStartedAt = Date.now();
|
|
389
|
+
};
|
|
390
|
+
const getPhasePercent = (phaseName) => {
|
|
391
|
+
if (phaseName.includes('Scanning BLE')) {
|
|
392
|
+
return 35;
|
|
33
393
|
}
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
394
|
+
if (phaseName.includes('Fetching OpenAPI')) {
|
|
395
|
+
return 75;
|
|
396
|
+
}
|
|
397
|
+
if (phaseName.includes('Complete')) {
|
|
398
|
+
return 100;
|
|
399
|
+
}
|
|
400
|
+
return 10;
|
|
401
|
+
};
|
|
402
|
+
const renderProgress = () => {
|
|
403
|
+
const totalSeconds = Math.max(0, Math.floor((Date.now() - startedAt) / 1000));
|
|
404
|
+
const phaseSeconds = Math.max(0, Math.floor((Date.now() - phaseStartedAt) / 1000));
|
|
405
|
+
const frame = spinnerFrames[spinnerIndex % spinnerFrames.length];
|
|
406
|
+
spinnerIndex += 1;
|
|
407
|
+
status.textContent = `${frame} ${phase} (${phaseSeconds}s, ${totalSeconds}s total)`;
|
|
408
|
+
if (phaseProgress) {
|
|
409
|
+
phaseProgress.style.display = 'block';
|
|
410
|
+
}
|
|
411
|
+
if (phaseFill) {
|
|
412
|
+
phaseFill.style.width = `${getPhasePercent(phase)}%`;
|
|
413
|
+
}
|
|
414
|
+
if (phaseLabel) {
|
|
415
|
+
phaseLabel.textContent = phase;
|
|
416
|
+
}
|
|
417
|
+
};
|
|
418
|
+
const progressTimer = setInterval(renderProgress, 250);
|
|
419
|
+
let discoveredDevices = [];
|
|
420
|
+
const preferences = getDiscoveryPreferences();
|
|
421
|
+
let groupBy = getDiscoveryGroupByPreference();
|
|
422
|
+
let hideAdded = getDiscoveryHideAddedPreference();
|
|
423
|
+
let controlsInitialized = false;
|
|
424
|
+
// Use persistent selection state across renders
|
|
425
|
+
if (!window._discoverySelectedIds) {
|
|
426
|
+
window._discoverySelectedIds = new Set();
|
|
427
|
+
}
|
|
428
|
+
const selectedIds = window._discoverySelectedIds;
|
|
429
|
+
// --- Real-time RSSI polling loop ---
|
|
430
|
+
setPhase('Scanning BLE (real-time RSSI)');
|
|
431
|
+
let pollTimer = null;
|
|
432
|
+
const pollDiscovery = async () => {
|
|
433
|
+
if (cancelled || Date.now() > scanEndTime) {
|
|
434
|
+
if (pollTimer) {
|
|
435
|
+
clearInterval(pollTimer);
|
|
436
|
+
}
|
|
437
|
+
setPhase('Scan Complete');
|
|
438
|
+
// Final update
|
|
37
439
|
try {
|
|
38
|
-
const
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
rssi: d.rssi,
|
|
43
|
-
address: d.address,
|
|
44
|
-
model: d.model,
|
|
45
|
-
})));
|
|
46
|
-
uiLog.info('Bulk add response:', bulkResult);
|
|
47
|
-
if (!bulkResult || bulkResult.success === false) {
|
|
48
|
-
throw new Error(bulkResult?.data?.message || 'Bulk add failed');
|
|
49
|
-
}
|
|
50
|
-
const addedCount = bulkResult?.addedCount
|
|
51
|
-
?? bulkResult?.data?.addedCount
|
|
52
|
-
?? 0;
|
|
53
|
-
const skippedCount = bulkResult?.skippedCount
|
|
54
|
-
?? bulkResult?.data?.skippedCount
|
|
55
|
-
?? 0;
|
|
56
|
-
status.textContent = `✓ Added ${addedCount} device(s)${skippedCount > 0 ? ` (${skippedCount} skipped)` : ''}`;
|
|
57
|
-
if (addedCount > 0) {
|
|
58
|
-
toastSuccess(`Added ${addedCount} device(s)${skippedCount > 0 ? ` (${skippedCount} skipped)` : ''}`);
|
|
59
|
-
}
|
|
60
|
-
else if (skippedCount > 0) {
|
|
61
|
-
toastWarning(`No new devices were added (${skippedCount} skipped)`);
|
|
62
|
-
}
|
|
63
|
-
status.classList.remove('error');
|
|
64
|
-
list.style.display = 'none';
|
|
65
|
-
// Sync parent Homebridge form cache and auto-save to prevent cache overwrite
|
|
66
|
-
// Run sync when discovery returned devices (even if backend response shape changes)
|
|
67
|
-
if (devices.length > 0) {
|
|
68
|
-
const synced = await syncParentPluginConfigFromDisk(true);
|
|
69
|
-
status.textContent += synced
|
|
70
|
-
? ' - Config saved automatically.'
|
|
71
|
-
: ' - Warning: config may not persist until you close/reopen settings.';
|
|
72
|
-
if (synced) {
|
|
73
|
-
toastSuccess('Configuration synced and saved automatically');
|
|
74
|
-
}
|
|
75
|
-
else {
|
|
76
|
-
toastWarning('Configuration sync failed; close and reopen settings before Save');
|
|
77
|
-
}
|
|
78
|
-
}
|
|
440
|
+
const devices = await apiDiscoverDevices('ble');
|
|
441
|
+
discoveredDevices = mergeDiscoveredDevices(discoveredDevices, devices);
|
|
442
|
+
setDiscoveryCache(discoveredDevices);
|
|
443
|
+
await updateDiscoveryView(discoveredDevices, preferences, groupBy, hideAdded, selectedIds);
|
|
79
444
|
}
|
|
80
445
|
catch (e) {
|
|
81
|
-
uiLog.error('
|
|
82
|
-
status.textContent = `✗ Error: ${e instanceof Error ? e.message : 'Failed to add devices'}`;
|
|
83
|
-
status.classList.add('error');
|
|
84
|
-
toastError(e instanceof Error ? e.message : 'Failed to add devices');
|
|
446
|
+
uiLog.error('Final BLE poll failed:', e);
|
|
85
447
|
}
|
|
86
|
-
// Refresh the configured devices list
|
|
87
|
-
await loadConfiguredDevices();
|
|
88
448
|
return;
|
|
89
449
|
}
|
|
90
|
-
|
|
91
|
-
|
|
450
|
+
try {
|
|
451
|
+
const devices = await apiDiscoverDevices('ble');
|
|
452
|
+
discoveredDevices = mergeDiscoveredDevices(discoveredDevices, devices);
|
|
453
|
+
setDiscoveryCache(discoveredDevices);
|
|
454
|
+
await updateDiscoveryView(discoveredDevices, preferences, groupBy, hideAdded, selectedIds);
|
|
455
|
+
}
|
|
456
|
+
catch (e) {
|
|
457
|
+
uiLog.error('BLE poll failed:', e);
|
|
458
|
+
}
|
|
459
|
+
};
|
|
460
|
+
pollTimer = setInterval(pollDiscovery, pollIntervalMs);
|
|
461
|
+
// Initial poll
|
|
462
|
+
pollDiscovery();
|
|
463
|
+
// Batch enable/disable helper (moved to module scope for UI access)
|
|
464
|
+
async function batchSetDeviceEnabled(selectedIds, enabled) {
|
|
465
|
+
// Fetch current config
|
|
466
|
+
const resp = await homebridge.request('/platform-config', {});
|
|
467
|
+
if (!resp || resp.success === false || !resp.data) {
|
|
468
|
+
throw new Error('Failed to load config');
|
|
469
|
+
}
|
|
470
|
+
const config = resp.data;
|
|
471
|
+
// Homebridge config may be an array of platforms, find SwitchBot
|
|
472
|
+
const configArr = Array.isArray(config) ? config : [config];
|
|
473
|
+
const platformIdx = configArr.findIndex((c) => (c.platform || c.name || '').toLowerCase().includes('switchbot'));
|
|
474
|
+
if (platformIdx === -1) {
|
|
475
|
+
throw new Error('SwitchBot platform config not found');
|
|
476
|
+
}
|
|
477
|
+
const platformConfig = configArr[platformIdx];
|
|
478
|
+
if (!Array.isArray(platformConfig.devices)) {
|
|
479
|
+
throw new TypeError('No devices array in config');
|
|
480
|
+
}
|
|
481
|
+
let changed = false;
|
|
482
|
+
for (const dev of platformConfig.devices) {
|
|
483
|
+
const id = String(dev.deviceId || dev.id || '').trim().toLowerCase();
|
|
484
|
+
if (selectedIds.has(id)) {
|
|
485
|
+
if (dev.enabled !== enabled) {
|
|
486
|
+
dev.enabled = enabled;
|
|
487
|
+
changed = true;
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
if (changed) {
|
|
492
|
+
if (typeof homebridge.updatePluginConfig === 'function') {
|
|
493
|
+
await homebridge.updatePluginConfig(configArr);
|
|
494
|
+
}
|
|
495
|
+
else {
|
|
496
|
+
throw new TypeError('homebridge.updatePluginConfig is not available');
|
|
497
|
+
}
|
|
498
|
+
if (typeof homebridge.savePluginConfig === 'function') {
|
|
499
|
+
await homebridge.savePluginConfig();
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
const ensureDiscoveryControls = async () => {
|
|
504
|
+
if (controlsInitialized) {
|
|
505
|
+
return;
|
|
506
|
+
}
|
|
507
|
+
// Always use persistent selectedIds
|
|
508
|
+
if (!window._discoverySelectedIds) {
|
|
509
|
+
window._discoverySelectedIds = new Set();
|
|
510
|
+
}
|
|
511
|
+
const selectedIds = window._discoverySelectedIds;
|
|
92
512
|
const controlsDiv = document.createElement('div');
|
|
93
513
|
controlsDiv.style.cssText = 'margin-bottom: 12px; display: flex; gap: 12px; flex-wrap: wrap; align-items: center;';
|
|
94
|
-
// Load saved preferences
|
|
95
|
-
const preferences = getDiscoveryPreferences();
|
|
96
|
-
// Filter buttons
|
|
97
514
|
const filterLabel = document.createElement('label');
|
|
98
515
|
filterLabel.style.fontSize = '12px';
|
|
99
516
|
filterLabel.style.fontWeight = '500';
|
|
@@ -109,33 +526,30 @@ export async function discoverDevices() {
|
|
|
109
526
|
{ label: 'IR', value: 'ir' },
|
|
110
527
|
];
|
|
111
528
|
for (const option of filterOptions) {
|
|
112
|
-
const
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
529
|
+
const filterBtn = document.createElement('button');
|
|
530
|
+
filterBtn.textContent = option.label;
|
|
531
|
+
filterBtn.style.padding = '4px 8px';
|
|
532
|
+
filterBtn.style.fontSize = '11px';
|
|
533
|
+
filterBtn.style.borderRadius = '3px';
|
|
534
|
+
filterBtn.style.cursor = 'pointer';
|
|
535
|
+
filterBtn.style.border = preferences.connectionType === option.value ? '2px solid #007AFF' : '1px solid #ccc';
|
|
536
|
+
filterBtn.style.backgroundColor = preferences.connectionType === option.value ? '#f0f7ff' : '#fff';
|
|
537
|
+
filterBtn.style.color = preferences.connectionType === option.value ? '#1d4ed8' : '#374151';
|
|
538
|
+
filterBtn.onclick = () => {
|
|
122
539
|
preferences.connectionType = option.value;
|
|
123
540
|
setDiscoveryPreferences(preferences);
|
|
124
|
-
updateDiscoveryView(
|
|
125
|
-
|
|
126
|
-
for (const b of Array.from(filterGroup.querySelectorAll('button'))) {
|
|
127
|
-
;
|
|
541
|
+
void updateDiscoveryView(discoveredDevices, preferences, groupBy, hideAdded, selectedIds);
|
|
542
|
+
Array.prototype.forEach.call(filterGroup.querySelectorAll('button'), (b) => {
|
|
128
543
|
b.style.border = '1px solid #ccc';
|
|
129
544
|
b.style.backgroundColor = '#fff';
|
|
130
545
|
b.style.color = '#374151';
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
546
|
+
});
|
|
547
|
+
filterBtn.style.border = '2px solid #007AFF';
|
|
548
|
+
filterBtn.style.backgroundColor = '#f0f7ff';
|
|
549
|
+
filterBtn.style.color = '#1d4ed8';
|
|
135
550
|
};
|
|
136
|
-
filterGroup.appendChild(
|
|
551
|
+
filterGroup.appendChild(filterBtn);
|
|
137
552
|
}
|
|
138
|
-
// Sort dropdown
|
|
139
553
|
const sortLabel = document.createElement('label');
|
|
140
554
|
sortLabel.style.fontSize = '12px';
|
|
141
555
|
sortLabel.style.fontWeight = '500';
|
|
@@ -153,27 +567,73 @@ export async function discoverDevices() {
|
|
|
153
567
|
{ label: 'Connection', value: 'connection' },
|
|
154
568
|
];
|
|
155
569
|
for (const opt of sortOptions) {
|
|
156
|
-
const
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
sortSelect.appendChild(
|
|
570
|
+
const sortOption = document.createElement('option');
|
|
571
|
+
sortOption.value = opt.value;
|
|
572
|
+
sortOption.textContent = opt.label;
|
|
573
|
+
sortSelect.appendChild(sortOption);
|
|
160
574
|
}
|
|
161
575
|
sortSelect.onchange = () => {
|
|
162
576
|
preferences.sortBy = sortSelect.value;
|
|
163
577
|
setDiscoveryPreferences(preferences);
|
|
164
|
-
updateDiscoveryView(
|
|
578
|
+
void updateDiscoveryView(discoveredDevices, preferences, groupBy, hideAdded, selectedIds);
|
|
579
|
+
};
|
|
580
|
+
const groupLabel = document.createElement('label');
|
|
581
|
+
groupLabel.style.fontSize = '12px';
|
|
582
|
+
groupLabel.style.fontWeight = '500';
|
|
583
|
+
groupLabel.style.marginLeft = '8px';
|
|
584
|
+
groupLabel.textContent = 'Group:';
|
|
585
|
+
const groupSelect = document.createElement('select');
|
|
586
|
+
groupSelect.style.fontSize = '11px';
|
|
587
|
+
groupSelect.style.padding = '4px 8px';
|
|
588
|
+
groupSelect.style.borderRadius = '3px';
|
|
589
|
+
groupSelect.value = groupBy;
|
|
590
|
+
const groupOptions = [
|
|
591
|
+
{ label: 'Connection', value: 'connection' },
|
|
592
|
+
{ label: 'Hub', value: 'hub' },
|
|
593
|
+
{ label: 'Device Type', value: 'type' },
|
|
594
|
+
];
|
|
595
|
+
for (const opt of groupOptions) {
|
|
596
|
+
const groupOption = document.createElement('option');
|
|
597
|
+
groupOption.value = opt.value;
|
|
598
|
+
groupOption.textContent = opt.label;
|
|
599
|
+
groupSelect.appendChild(groupOption);
|
|
600
|
+
}
|
|
601
|
+
groupSelect.onchange = () => {
|
|
602
|
+
groupBy = groupSelect.value;
|
|
603
|
+
setDiscoveryGroupByPreference(groupBy);
|
|
604
|
+
void updateDiscoveryView(discoveredDevices, preferences, groupBy, hideAdded, selectedIds);
|
|
605
|
+
};
|
|
606
|
+
const hideAddedLabel = document.createElement('label');
|
|
607
|
+
hideAddedLabel.style.display = 'inline-flex';
|
|
608
|
+
hideAddedLabel.style.alignItems = 'center';
|
|
609
|
+
hideAddedLabel.style.gap = '4px';
|
|
610
|
+
hideAddedLabel.style.fontSize = '11px';
|
|
611
|
+
hideAddedLabel.style.marginLeft = '8px';
|
|
612
|
+
const hideAddedCheckbox = document.createElement('input');
|
|
613
|
+
hideAddedCheckbox.type = 'checkbox';
|
|
614
|
+
hideAddedCheckbox.checked = hideAdded;
|
|
615
|
+
hideAddedCheckbox.style.margin = '0';
|
|
616
|
+
hideAddedCheckbox.style.width = 'auto';
|
|
617
|
+
const hideAddedText = document.createElement('span');
|
|
618
|
+
hideAddedText.textContent = 'Hide Added';
|
|
619
|
+
hideAddedLabel.appendChild(hideAddedCheckbox);
|
|
620
|
+
hideAddedLabel.appendChild(hideAddedText);
|
|
621
|
+
hideAddedCheckbox.onchange = () => {
|
|
622
|
+
hideAdded = hideAddedCheckbox.checked;
|
|
623
|
+
setDiscoveryHideAddedPreference(hideAdded);
|
|
624
|
+
void updateDiscoveryView(discoveredDevices, preferences, groupBy, hideAdded, selectedIds);
|
|
165
625
|
};
|
|
166
|
-
// Search box
|
|
167
626
|
const searchInput = document.createElement('input');
|
|
168
627
|
searchInput.type = 'text';
|
|
169
628
|
searchInput.placeholder = 'Search by name, ID, or type...';
|
|
170
|
-
searchInput.style.fontSize = '
|
|
171
|
-
searchInput.style.padding = '
|
|
172
|
-
searchInput.style.borderRadius = '
|
|
629
|
+
searchInput.style.fontSize = '13px';
|
|
630
|
+
searchInput.style.padding = '8px 16px';
|
|
631
|
+
searchInput.style.borderRadius = '6px';
|
|
173
632
|
searchInput.style.border = '1px solid #ccc';
|
|
174
|
-
searchInput.style.flex = '1';
|
|
175
|
-
searchInput.style.minWidth = '
|
|
176
|
-
searchInput.style.maxWidth = '
|
|
633
|
+
searchInput.style.flex = '1 1 0%';
|
|
634
|
+
searchInput.style.minWidth = '120px';
|
|
635
|
+
searchInput.style.maxWidth = '100%';
|
|
636
|
+
searchInput.style.width = '100%';
|
|
177
637
|
searchInput.value = preferences.searchQuery;
|
|
178
638
|
let searchTimeout;
|
|
179
639
|
searchInput.oninput = () => {
|
|
@@ -181,19 +641,153 @@ export async function discoverDevices() {
|
|
|
181
641
|
searchTimeout = setTimeout(() => {
|
|
182
642
|
preferences.searchQuery = searchInput.value;
|
|
183
643
|
setDiscoveryPreferences(preferences);
|
|
184
|
-
updateDiscoveryView(
|
|
185
|
-
}, 300);
|
|
644
|
+
void updateDiscoveryView(discoveredDevices, preferences, groupBy, hideAdded, selectedIds);
|
|
645
|
+
}, 300);
|
|
646
|
+
};
|
|
647
|
+
// Shared style for all top action buttons (smaller, more compact)
|
|
648
|
+
const actionBtnStyle = {
|
|
649
|
+
fontSize: '16px',
|
|
650
|
+
padding: '10px 0',
|
|
651
|
+
borderRadius: '10px',
|
|
652
|
+
margin: '0 12px 0 0',
|
|
653
|
+
width: '100%',
|
|
654
|
+
maxWidth: '220px',
|
|
655
|
+
fontWeight: 'bold',
|
|
656
|
+
background: '#ef4444',
|
|
657
|
+
color: '#fff',
|
|
658
|
+
border: 'none',
|
|
659
|
+
cursor: 'pointer',
|
|
660
|
+
boxShadow: '0 2px 8px #0001',
|
|
661
|
+
transition: 'background 0.2s',
|
|
662
|
+
outline: 'none',
|
|
663
|
+
display: 'block',
|
|
186
664
|
};
|
|
187
|
-
//
|
|
665
|
+
// Add Selected button
|
|
666
|
+
const addSelectedBtn = document.createElement('button');
|
|
667
|
+
addSelectedBtn.textContent = 'Add Selected to Config';
|
|
668
|
+
Object.assign(addSelectedBtn.style, actionBtnStyle);
|
|
669
|
+
addSelectedBtn.disabled = true;
|
|
670
|
+
addSelectedBtn.onclick = async () => {
|
|
671
|
+
if (!selectedIds.size) {
|
|
672
|
+
return;
|
|
673
|
+
}
|
|
674
|
+
addSelectedBtn.disabled = true;
|
|
675
|
+
addSelectedBtn.textContent = 'Adding...';
|
|
676
|
+
try {
|
|
677
|
+
showBusyUi();
|
|
678
|
+
const selectedDevices = discoveredDevices.filter(d => selectedIds.has(normalizeId(d.id)));
|
|
679
|
+
const bulkResult = await addDevicesInBulk(selectedDevices.map(d => ({
|
|
680
|
+
deviceId: d.id,
|
|
681
|
+
name: d.name,
|
|
682
|
+
type: d.type,
|
|
683
|
+
rssi: d.rssi,
|
|
684
|
+
address: d.address,
|
|
685
|
+
model: d.model,
|
|
686
|
+
})));
|
|
687
|
+
uiLog.info('Batch add response:', bulkResult);
|
|
688
|
+
if (!bulkResult || bulkResult.success === false) {
|
|
689
|
+
throw new Error(bulkResult?.data?.message || 'Batch add failed');
|
|
690
|
+
}
|
|
691
|
+
const addedCount = bulkResult?.addedCount ?? bulkResult?.data?.addedCount ?? 0;
|
|
692
|
+
const skippedCount = bulkResult?.skippedCount ?? bulkResult?.data?.skippedCount ?? 0;
|
|
693
|
+
toastSuccess(`Added ${addedCount} device(s)${skippedCount > 0 ? ` (${skippedCount} skipped)` : ''}`);
|
|
694
|
+
await loadConfiguredDevices();
|
|
695
|
+
selectedIds.clear();
|
|
696
|
+
addSelectedBtn.disabled = true;
|
|
697
|
+
addSelectedBtn.textContent = 'Add Selected';
|
|
698
|
+
await updateDiscoveryView(discoveredDevices, preferences, groupBy, hideAdded, selectedIds);
|
|
699
|
+
}
|
|
700
|
+
catch (e) {
|
|
701
|
+
uiLog.error('Batch add error:', e);
|
|
702
|
+
toastError(e instanceof Error ? e.message : 'Failed to add devices');
|
|
703
|
+
addSelectedBtn.disabled = false;
|
|
704
|
+
addSelectedBtn.textContent = 'Add Selected';
|
|
705
|
+
}
|
|
706
|
+
finally {
|
|
707
|
+
hideBusyUi();
|
|
708
|
+
}
|
|
709
|
+
};
|
|
710
|
+
// Enable Selected button
|
|
711
|
+
const enableSelectedBtn = document.createElement('button');
|
|
712
|
+
enableSelectedBtn.textContent = 'Enable Selected';
|
|
713
|
+
Object.assign(enableSelectedBtn.style, actionBtnStyle);
|
|
714
|
+
enableSelectedBtn.disabled = true;
|
|
715
|
+
enableSelectedBtn.onclick = async () => {
|
|
716
|
+
if (!selectedIds.size) {
|
|
717
|
+
return;
|
|
718
|
+
}
|
|
719
|
+
enableSelectedBtn.disabled = true;
|
|
720
|
+
enableSelectedBtn.textContent = 'Enabling...';
|
|
721
|
+
try {
|
|
722
|
+
showBusyUi();
|
|
723
|
+
await batchSetDeviceEnabled(selectedIds, true);
|
|
724
|
+
toastSuccess('Selected devices enabled');
|
|
725
|
+
await loadConfiguredDevices();
|
|
726
|
+
enableSelectedBtn.disabled = true;
|
|
727
|
+
enableSelectedBtn.textContent = 'Enable Selected';
|
|
728
|
+
await updateDiscoveryView(discoveredDevices, preferences, groupBy, hideAdded, selectedIds);
|
|
729
|
+
}
|
|
730
|
+
catch (e) {
|
|
731
|
+
uiLog.error('Batch enable error:', e);
|
|
732
|
+
toastError(e instanceof Error ? e.message : 'Failed to enable devices');
|
|
733
|
+
enableSelectedBtn.disabled = false;
|
|
734
|
+
enableSelectedBtn.textContent = 'Enable Selected';
|
|
735
|
+
}
|
|
736
|
+
finally {
|
|
737
|
+
hideBusyUi();
|
|
738
|
+
}
|
|
739
|
+
};
|
|
740
|
+
// Disable Selected button
|
|
741
|
+
const disableSelectedBtn = document.createElement('button');
|
|
742
|
+
disableSelectedBtn.textContent = 'Disable Selected';
|
|
743
|
+
Object.assign(disableSelectedBtn.style, actionBtnStyle);
|
|
744
|
+
disableSelectedBtn.disabled = true;
|
|
745
|
+
disableSelectedBtn.onclick = async () => {
|
|
746
|
+
if (!selectedIds.size) {
|
|
747
|
+
return;
|
|
748
|
+
}
|
|
749
|
+
disableSelectedBtn.disabled = true;
|
|
750
|
+
disableSelectedBtn.textContent = 'Disabling...';
|
|
751
|
+
try {
|
|
752
|
+
showBusyUi();
|
|
753
|
+
await batchSetDeviceEnabled(selectedIds, false);
|
|
754
|
+
toastSuccess('Selected devices disabled');
|
|
755
|
+
await loadConfiguredDevices();
|
|
756
|
+
disableSelectedBtn.disabled = true;
|
|
757
|
+
disableSelectedBtn.textContent = 'Disable Selected';
|
|
758
|
+
await updateDiscoveryView(discoveredDevices, preferences, groupBy, hideAdded, selectedIds);
|
|
759
|
+
}
|
|
760
|
+
catch (e) {
|
|
761
|
+
uiLog.error('Batch disable error:', e);
|
|
762
|
+
toastError(e instanceof Error ? e.message : 'Failed to disable devices');
|
|
763
|
+
disableSelectedBtn.disabled = false;
|
|
764
|
+
disableSelectedBtn.textContent = 'Disable Selected';
|
|
765
|
+
}
|
|
766
|
+
finally {
|
|
767
|
+
hideBusyUi();
|
|
768
|
+
}
|
|
769
|
+
};
|
|
770
|
+
// Only add the filter/search controls
|
|
188
771
|
controlsDiv.appendChild(filterLabel);
|
|
189
772
|
controlsDiv.appendChild(filterGroup);
|
|
190
773
|
controlsDiv.appendChild(sortLabel);
|
|
191
774
|
controlsDiv.appendChild(sortSelect);
|
|
775
|
+
controlsDiv.appendChild(groupLabel);
|
|
776
|
+
controlsDiv.appendChild(groupSelect);
|
|
777
|
+
controlsDiv.appendChild(hideAddedLabel);
|
|
192
778
|
controlsDiv.appendChild(searchInput);
|
|
193
|
-
//
|
|
779
|
+
// Top row action buttons container
|
|
780
|
+
const topActionRow = document.createElement('div');
|
|
781
|
+
topActionRow.style.display = 'flex';
|
|
782
|
+
topActionRow.style.gap = '20px';
|
|
783
|
+
topActionRow.style.margin = '18px 0 10px 0';
|
|
784
|
+
topActionRow.style.justifyContent = 'flex-start';
|
|
785
|
+
topActionRow.appendChild(addSelectedBtn);
|
|
786
|
+
topActionRow.appendChild(enableSelectedBtn);
|
|
787
|
+
topActionRow.appendChild(disableSelectedBtn);
|
|
788
|
+
list.insertBefore(topActionRow, controlsDiv);
|
|
194
789
|
list.innerHTML = '';
|
|
195
790
|
list.appendChild(controlsDiv);
|
|
196
|
-
// Create or get the device list container
|
|
197
791
|
let deviceListContainer = document.getElementById('discoveredDevices');
|
|
198
792
|
if (!deviceListContainer) {
|
|
199
793
|
deviceListContainer = document.createElement('ul');
|
|
@@ -205,12 +799,183 @@ export async function discoverDevices() {
|
|
|
205
799
|
deviceListContainer.style.listStyle = 'none';
|
|
206
800
|
list.appendChild(deviceListContainer);
|
|
207
801
|
}
|
|
208
|
-
// Display discovery list
|
|
209
802
|
list.style.display = 'block';
|
|
210
|
-
|
|
211
|
-
|
|
803
|
+
controlsInitialized = true;
|
|
804
|
+
// Update action button enabled state based on selection
|
|
805
|
+
const updateActionButtons = () => {
|
|
806
|
+
const hasSelection = selectedIds.size > 0;
|
|
807
|
+
addSelectedBtn.disabled = !hasSelection;
|
|
808
|
+
enableSelectedBtn.disabled = !hasSelection;
|
|
809
|
+
disableSelectedBtn.disabled = !hasSelection;
|
|
810
|
+
};
|
|
811
|
+
// Listen for selection changes (selection is managed elsewhere, so poll)
|
|
812
|
+
setInterval(updateActionButtons, 300);
|
|
813
|
+
};
|
|
814
|
+
try {
|
|
815
|
+
const bleSettings = {
|
|
816
|
+
bleEnabled: !(disableBleCheckbox?.checked ?? false),
|
|
817
|
+
bleScanDurationSeconds: Math.max(3, Math.min(15, Number(scanSelect?.value || 5))),
|
|
818
|
+
bleTimeoutSeconds: Math.max(3, Math.min(30, Number(timeoutInput?.value || 8))),
|
|
819
|
+
};
|
|
820
|
+
setDiscoveryBleSettings(bleSettings);
|
|
821
|
+
showBusyUi();
|
|
822
|
+
btn.disabled = true;
|
|
823
|
+
btn.textContent = '🔍 Discovering...';
|
|
824
|
+
setPhase(bleSettings.bleEnabled ? 'Scanning BLE...' : 'Skipping BLE scan...');
|
|
825
|
+
renderProgress();
|
|
826
|
+
status.classList.remove('error');
|
|
827
|
+
const devicesFoundDisplay = document.getElementById('discoverDevicesFound');
|
|
828
|
+
if (devicesFoundDisplay) {
|
|
829
|
+
devicesFoundDisplay.style.display = 'none';
|
|
830
|
+
devicesFoundDisplay.classList.remove('discovery-scanning-pulse');
|
|
831
|
+
}
|
|
832
|
+
if (cancelBtn) {
|
|
833
|
+
cancelBtn.style.display = 'inline-block';
|
|
834
|
+
cancelBtn.disabled = false;
|
|
835
|
+
cancelBtn.onclick = () => {
|
|
836
|
+
cancelled = true;
|
|
837
|
+
const totalSeconds = Math.max(0, Math.floor((Date.now() - startedAt) / 1000));
|
|
838
|
+
status.textContent = `Discovery cancelled (${totalSeconds}s total)`;
|
|
839
|
+
if (phaseProgress) {
|
|
840
|
+
phaseProgress.style.display = 'none';
|
|
841
|
+
}
|
|
842
|
+
if (devicesFoundDisplay) {
|
|
843
|
+
devicesFoundDisplay.style.display = 'none';
|
|
844
|
+
devicesFoundDisplay.classList.remove('discovery-scanning-pulse');
|
|
845
|
+
}
|
|
846
|
+
cancelBtn.style.display = 'none';
|
|
847
|
+
btn.disabled = false;
|
|
848
|
+
btn.textContent = '🔍 Discover Devices';
|
|
849
|
+
hideBusyUi();
|
|
850
|
+
};
|
|
851
|
+
}
|
|
852
|
+
if (bleSettings.bleEnabled) {
|
|
853
|
+
const bleDevicesRaw = await apiDiscoverDevices('ble', bleSettings);
|
|
854
|
+
if (cancelled) {
|
|
855
|
+
return;
|
|
856
|
+
}
|
|
857
|
+
discoveredDevices = dedupeById(bleDevicesRaw);
|
|
858
|
+
uiLog.info('BLE discover response:', bleDevicesRaw);
|
|
859
|
+
// Update real-time device counter
|
|
860
|
+
if (devicesFoundDisplay && bleDevicesRaw.length > 0) {
|
|
861
|
+
devicesFoundDisplay.style.display = 'inline';
|
|
862
|
+
devicesFoundDisplay.classList.add('discovery-scanning-pulse');
|
|
863
|
+
devicesFoundDisplay.textContent = `📊 ${bleDevicesRaw.length} device(s) found (scanning...)`;
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
else {
|
|
867
|
+
discoveredDevices = [];
|
|
868
|
+
uiLog.info('BLE discovery skipped by user setting');
|
|
869
|
+
}
|
|
870
|
+
if (!autoAddAll && discoveredDevices.length > 0) {
|
|
871
|
+
await ensureDiscoveryControls();
|
|
872
|
+
await updateDiscoveryView(discoveredDevices, preferences, groupBy, hideAdded, selectedIds);
|
|
873
|
+
status.textContent = `Showing ${discoveredDevices.length} device(s) from BLE, fetching OpenAPI...`;
|
|
874
|
+
}
|
|
875
|
+
setPhase('Fetching OpenAPI...');
|
|
876
|
+
renderProgress();
|
|
877
|
+
try {
|
|
878
|
+
const openApiDevicesRaw = await apiDiscoverDevices('openapi');
|
|
879
|
+
if (cancelled) {
|
|
880
|
+
return;
|
|
881
|
+
}
|
|
882
|
+
uiLog.info('OpenAPI discover response:', openApiDevicesRaw);
|
|
883
|
+
discoveredDevices = mergeDiscoveredDevices(discoveredDevices, openApiDevicesRaw);
|
|
884
|
+
// Update device counter with merged count
|
|
885
|
+
if (devicesFoundDisplay && discoveredDevices.length > 0) {
|
|
886
|
+
devicesFoundDisplay.textContent = `📊 ${discoveredDevices.length} device(s) found (complete)`;
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
catch (openApiError) {
|
|
890
|
+
uiLog.warn('OpenAPI phase failed during discovery:', openApiError);
|
|
891
|
+
// Keep BLE results if available
|
|
892
|
+
if (!discoveredDevices.length) {
|
|
893
|
+
throw openApiError;
|
|
894
|
+
}
|
|
895
|
+
if (devicesFoundDisplay) {
|
|
896
|
+
devicesFoundDisplay.classList.remove('discovery-scanning-pulse');
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
setPhase('Complete');
|
|
900
|
+
renderProgress();
|
|
901
|
+
uiLog.info('Final merged discover response:', discoveredDevices);
|
|
902
|
+
if (!discoveredDevices.length) {
|
|
903
|
+
status.textContent = 'No devices found in your SwitchBot account';
|
|
904
|
+
toastInfo('No devices found in your SwitchBot account');
|
|
905
|
+
list.style.display = 'none';
|
|
906
|
+
if (devicesFoundDisplay) {
|
|
907
|
+
devicesFoundDisplay.style.display = 'none';
|
|
908
|
+
devicesFoundDisplay.classList.remove('discovery-scanning-pulse');
|
|
909
|
+
}
|
|
910
|
+
clearDiscoveryCache();
|
|
911
|
+
updateLastScannedStatus();
|
|
912
|
+
return;
|
|
913
|
+
}
|
|
914
|
+
// If auto-add is enabled, add all devices immediately using bulk endpoint
|
|
915
|
+
if (autoAddAll) {
|
|
916
|
+
status.textContent = `Auto-adding ${discoveredDevices.length} device(s)...`;
|
|
917
|
+
try {
|
|
918
|
+
const bulkResult = await addDevicesInBulk(discoveredDevices.map(d => ({
|
|
919
|
+
deviceId: d.id,
|
|
920
|
+
name: d.name,
|
|
921
|
+
type: d.type,
|
|
922
|
+
rssi: d.rssi,
|
|
923
|
+
address: d.address,
|
|
924
|
+
model: d.model,
|
|
925
|
+
})));
|
|
926
|
+
uiLog.info('Bulk add response:', bulkResult);
|
|
927
|
+
if (!bulkResult || bulkResult.success === false) {
|
|
928
|
+
throw new Error(bulkResult?.data?.message || 'Bulk add failed');
|
|
929
|
+
}
|
|
930
|
+
const addedCount = bulkResult?.addedCount
|
|
931
|
+
?? bulkResult?.data?.addedCount
|
|
932
|
+
?? 0;
|
|
933
|
+
const skippedCount = bulkResult?.skippedCount
|
|
934
|
+
?? bulkResult?.data?.skippedCount
|
|
935
|
+
?? 0;
|
|
936
|
+
status.textContent = `✓ Added ${addedCount} device(s)${skippedCount > 0 ? ` (${skippedCount} skipped)` : ''}`;
|
|
937
|
+
if (addedCount > 0) {
|
|
938
|
+
toastSuccess(`Added ${addedCount} device(s)${skippedCount > 0 ? ` (${skippedCount} skipped)` : ''}`);
|
|
939
|
+
}
|
|
940
|
+
else if (skippedCount > 0) {
|
|
941
|
+
toastWarning(`No new devices were added (${skippedCount} skipped)`);
|
|
942
|
+
}
|
|
943
|
+
status.classList.remove('error');
|
|
944
|
+
list.style.display = 'none';
|
|
945
|
+
// Sync parent Homebridge form cache and auto-save to prevent cache overwrite
|
|
946
|
+
// Run sync when discovery returned devices (even if backend response shape changes)
|
|
947
|
+
if (discoveredDevices.length > 0) {
|
|
948
|
+
const synced = await syncParentPluginConfigFromDisk(true);
|
|
949
|
+
status.textContent += synced
|
|
950
|
+
? ' - Config saved automatically.'
|
|
951
|
+
: ' - Warning: config may not persist until you close/reopen settings.';
|
|
952
|
+
if (synced) {
|
|
953
|
+
toastSuccess('Configuration synced and saved automatically');
|
|
954
|
+
}
|
|
955
|
+
else {
|
|
956
|
+
toastWarning('Configuration sync failed; close and reopen settings before Save');
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
catch (e) {
|
|
961
|
+
uiLog.error('Bulk add error:', e);
|
|
962
|
+
status.textContent = `✗ Error: ${e instanceof Error ? e.message : 'Failed to add devices'}`;
|
|
963
|
+
status.classList.add('error');
|
|
964
|
+
toastError(e instanceof Error ? e.message : 'Failed to add devices');
|
|
965
|
+
}
|
|
966
|
+
// Refresh the configured devices list
|
|
967
|
+
await loadConfiguredDevices();
|
|
968
|
+
return;
|
|
969
|
+
}
|
|
970
|
+
await ensureDiscoveryControls();
|
|
971
|
+
await updateDiscoveryView(discoveredDevices, preferences, groupBy, hideAdded, selectedIds);
|
|
972
|
+
setDiscoveryCache(discoveredDevices);
|
|
973
|
+
updateLastScannedStatus();
|
|
212
974
|
}
|
|
213
975
|
catch (e) {
|
|
976
|
+
if (cancelled) {
|
|
977
|
+
return;
|
|
978
|
+
}
|
|
214
979
|
uiLog.error('Discovery error:', e);
|
|
215
980
|
status.textContent = `Error: ${e instanceof Error ? e.message : 'Discovery failed'}`;
|
|
216
981
|
status.classList.add('error');
|
|
@@ -218,43 +983,375 @@ export async function discoverDevices() {
|
|
|
218
983
|
list.style.display = 'none';
|
|
219
984
|
}
|
|
220
985
|
finally {
|
|
986
|
+
clearInterval(progressTimer);
|
|
221
987
|
hideBusyUi();
|
|
988
|
+
if (phaseProgress) {
|
|
989
|
+
phaseProgress.style.display = 'none';
|
|
990
|
+
}
|
|
991
|
+
if (phaseFill) {
|
|
992
|
+
phaseFill.style.width = '0%';
|
|
993
|
+
}
|
|
994
|
+
if (phaseLabel) {
|
|
995
|
+
phaseLabel.textContent = '';
|
|
996
|
+
}
|
|
997
|
+
const devicesFoundDisplay = document.getElementById('discoverDevicesFound');
|
|
998
|
+
if (devicesFoundDisplay) {
|
|
999
|
+
devicesFoundDisplay.style.display = 'none';
|
|
1000
|
+
devicesFoundDisplay.classList.remove('discovery-scanning-pulse');
|
|
1001
|
+
}
|
|
222
1002
|
btn.disabled = false;
|
|
223
1003
|
btn.textContent = '🔍 Discover Devices';
|
|
1004
|
+
if (cancelBtn) {
|
|
1005
|
+
cancelBtn.disabled = false;
|
|
1006
|
+
cancelBtn.style.display = 'none';
|
|
1007
|
+
cancelBtn.onclick = null;
|
|
1008
|
+
}
|
|
224
1009
|
}
|
|
225
1010
|
}
|
|
226
1011
|
/**
|
|
227
1012
|
* Update discovery list with filtered and sorted devices
|
|
228
1013
|
*/
|
|
229
|
-
async function updateDiscoveryView(allDevices, preferences) {
|
|
230
|
-
//
|
|
231
|
-
const
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
1014
|
+
async function updateDiscoveryView(allDevices, preferences, groupBy, hideAdded, selectedIds) {
|
|
1015
|
+
// Compute visibleDevices based on filters and preferences
|
|
1016
|
+
const visibleDevices = allDevices
|
|
1017
|
+
.filter((d) => {
|
|
1018
|
+
// Hide already added devices if hideAdded is true
|
|
1019
|
+
if (hideAdded && d.added) {
|
|
1020
|
+
return false;
|
|
1021
|
+
}
|
|
1022
|
+
// Additional filtering logic can be added here based on preferences
|
|
1023
|
+
return true;
|
|
239
1024
|
});
|
|
1025
|
+
// Optionally sort devices if needed (sortDevices is imported but not used)
|
|
1026
|
+
// .sort((a, b) => a.name.localeCompare(b.name))
|
|
1027
|
+
// Set of already added device IDs
|
|
1028
|
+
const configuredIds = new Set(allDevices.filter(d => d.added).map(d => normalizeId(d.id)));
|
|
1029
|
+
// Batch import controls and selection logic are handled later in the file. Removed broken/duplicated code.
|
|
1030
|
+
const getConnectionGroup = (device) => {
|
|
1031
|
+
if (device?.isIR) {
|
|
1032
|
+
return 'IR';
|
|
1033
|
+
}
|
|
1034
|
+
const connectionType = String(device?.connectionType || '').toLowerCase();
|
|
1035
|
+
if (connectionType.includes('both')) {
|
|
1036
|
+
return 'Both';
|
|
1037
|
+
}
|
|
1038
|
+
if (connectionType.includes('ble')) {
|
|
1039
|
+
return 'BLE';
|
|
1040
|
+
}
|
|
1041
|
+
if (connectionType.includes('api')) {
|
|
1042
|
+
return 'OpenAPI';
|
|
1043
|
+
}
|
|
1044
|
+
return 'Unknown';
|
|
1045
|
+
};
|
|
1046
|
+
const getHubGroup = (device) => {
|
|
1047
|
+
const hub = String(device?.hubDeviceId || '').trim();
|
|
1048
|
+
return hub ? `Hub ${hub}` : 'No Hub';
|
|
1049
|
+
};
|
|
1050
|
+
const getTypeGroup = (device) => {
|
|
1051
|
+
const type = String(device?.type || '').trim();
|
|
1052
|
+
return type || 'Unknown Type';
|
|
1053
|
+
};
|
|
1054
|
+
const groupedDevices = new Map();
|
|
1055
|
+
for (const d of visibleDevices) {
|
|
1056
|
+
let group = getConnectionGroup(d);
|
|
1057
|
+
if (groupBy === 'hub') {
|
|
1058
|
+
group = getHubGroup(d);
|
|
1059
|
+
}
|
|
1060
|
+
else if (groupBy === 'type') {
|
|
1061
|
+
group = getTypeGroup(d);
|
|
1062
|
+
}
|
|
1063
|
+
const groupDevices = groupedDevices.get(group) || [];
|
|
1064
|
+
groupDevices.push(d);
|
|
1065
|
+
groupedDevices.set(group, groupDevices);
|
|
1066
|
+
}
|
|
1067
|
+
let orderedGroups = [];
|
|
1068
|
+
if (groupBy === 'hub') {
|
|
1069
|
+
const hubGroups = [...groupedDevices.keys()].filter(group => group !== 'No Hub').sort((a, b) => a.localeCompare(b));
|
|
1070
|
+
orderedGroups = groupedDevices.has('No Hub') ? [...hubGroups, 'No Hub'] : hubGroups;
|
|
1071
|
+
}
|
|
1072
|
+
else if (groupBy === 'type') {
|
|
1073
|
+
const typeGroups = [...groupedDevices.keys()].filter(group => group !== 'Unknown Type').sort((a, b) => a.localeCompare(b));
|
|
1074
|
+
orderedGroups = groupedDevices.has('Unknown Type') ? [...typeGroups, 'Unknown Type'] : typeGroups;
|
|
1075
|
+
}
|
|
1076
|
+
else {
|
|
1077
|
+
const groupOrder = ['Both', 'BLE', 'OpenAPI', 'IR', 'Unknown'];
|
|
1078
|
+
orderedGroups = groupOrder.filter(group => groupedDevices.has(group));
|
|
1079
|
+
}
|
|
1080
|
+
const container = document.createElement('div');
|
|
1081
|
+
container.id = 'discoveredDevices';
|
|
1082
|
+
container.className = 'discovery-groups';
|
|
1083
|
+
if (!visibleDevices.length) {
|
|
1084
|
+
const empty = document.createElement('div');
|
|
1085
|
+
empty.className = 'discovery-group-empty';
|
|
1086
|
+
empty.textContent = hideAdded
|
|
1087
|
+
? 'No devices match current filters (or all are already added).'
|
|
1088
|
+
: 'No devices match current filters.';
|
|
1089
|
+
container.appendChild(empty);
|
|
1090
|
+
}
|
|
1091
|
+
else {
|
|
1092
|
+
for (const groupName of orderedGroups) {
|
|
1093
|
+
const groupItems = groupedDevices.get(groupName);
|
|
1094
|
+
if (!groupItems?.length) {
|
|
1095
|
+
continue;
|
|
1096
|
+
}
|
|
1097
|
+
const groupSection = document.createElement('section');
|
|
1098
|
+
groupSection.className = 'discovery-group';
|
|
1099
|
+
const groupStorageKey = `${groupBy}:${groupName}`;
|
|
1100
|
+
let expanded = isDiscoveryGroupExpanded(groupStorageKey);
|
|
1101
|
+
const groupHeader = document.createElement('button');
|
|
1102
|
+
groupHeader.className = 'discovery-group-header-btn';
|
|
1103
|
+
groupHeader.type = 'button';
|
|
1104
|
+
const setGroupHeaderText = () => {
|
|
1105
|
+
const marker = expanded ? '▾' : '▸';
|
|
1106
|
+
groupHeader.textContent = `${marker} ${groupName} (${groupItems.length})`;
|
|
1107
|
+
};
|
|
1108
|
+
setGroupHeaderText();
|
|
1109
|
+
groupSection.appendChild(groupHeader);
|
|
1110
|
+
const groupList = await renderDiscoveredDevices(groupItems, {
|
|
1111
|
+
configuredIds,
|
|
1112
|
+
selectedIds,
|
|
1113
|
+
onToggleSelect: (device, selected) => {
|
|
1114
|
+
const id = normalizeId(device.id);
|
|
1115
|
+
if (selected) {
|
|
1116
|
+
selectedIds.add(id);
|
|
1117
|
+
}
|
|
1118
|
+
else {
|
|
1119
|
+
selectedIds.delete(id);
|
|
1120
|
+
}
|
|
1121
|
+
// Update Add Selected button state
|
|
1122
|
+
const btn = document.querySelector('button')?.parentElement?.querySelector('button');
|
|
1123
|
+
if (btn && btn.textContent?.includes('Add Selected')) {
|
|
1124
|
+
btn.disabled = selectedIds.size === 0;
|
|
1125
|
+
}
|
|
1126
|
+
},
|
|
1127
|
+
});
|
|
1128
|
+
if (!expanded) {
|
|
1129
|
+
groupList.style.display = 'none';
|
|
1130
|
+
}
|
|
1131
|
+
groupHeader.onclick = () => {
|
|
1132
|
+
expanded = !expanded;
|
|
1133
|
+
setDiscoveryGroupExpanded(groupStorageKey, expanded);
|
|
1134
|
+
setGroupHeaderText();
|
|
1135
|
+
groupList.style.display = expanded ? 'grid' : 'none';
|
|
1136
|
+
};
|
|
1137
|
+
groupSection.appendChild(groupList);
|
|
1138
|
+
container.appendChild(groupSection);
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
240
1141
|
// Replace or append the rendered list
|
|
241
1142
|
const existingList = document.getElementById('discoveredDevices');
|
|
242
1143
|
if (existingList && existingList.parentNode) {
|
|
243
|
-
existingList.replaceWith(
|
|
1144
|
+
existingList.replaceWith(container);
|
|
244
1145
|
}
|
|
245
1146
|
else {
|
|
246
1147
|
// Fallback: append to discovery list container
|
|
247
1148
|
const listContainer = document.getElementById('discoveredList');
|
|
248
1149
|
if (listContainer) {
|
|
249
|
-
listContainer.appendChild(
|
|
1150
|
+
listContainer.appendChild(container);
|
|
1151
|
+
}
|
|
1152
|
+
}
|
|
1153
|
+
// --- Batch Import Controls ---
|
|
1154
|
+
// Remove any duplicate 'Add Selected' buttons from legacy UI
|
|
1155
|
+
// Robust NodeList iteration: classic for loop to avoid formatter and transpiler issues
|
|
1156
|
+
const legacyAddSelectedBtns = [];
|
|
1157
|
+
const allBtns = document.querySelectorAll('button');
|
|
1158
|
+
for (let i = 0; i < allBtns.length; i++) {
|
|
1159
|
+
const btn = allBtns[i];
|
|
1160
|
+
if (btn.textContent && btn.textContent.trim() === 'Add Selected') {
|
|
1161
|
+
legacyAddSelectedBtns.push(btn);
|
|
1162
|
+
}
|
|
1163
|
+
}
|
|
1164
|
+
for (let i = 0; i < legacyAddSelectedBtns.length; i++) {
|
|
1165
|
+
legacyAddSelectedBtns[i].remove();
|
|
1166
|
+
}
|
|
1167
|
+
// Listen for selection changes to update batch button states
|
|
1168
|
+
function updateBatchButtonStates() {
|
|
1169
|
+
const addSelectedBtn = document.getElementById('addSelectedBtn');
|
|
1170
|
+
const enableSelectedBtn = document.querySelector('button')?.parentElement?.querySelector('button[aria-label="Enable Selected"]');
|
|
1171
|
+
const disableSelectedBtn = document.querySelector('button')?.parentElement?.querySelector('button[aria-label="Disable Selected"]');
|
|
1172
|
+
const hasSelection = selectedIds.size > 0;
|
|
1173
|
+
if (addSelectedBtn)
|
|
1174
|
+
addSelectedBtn.disabled = !hasSelection;
|
|
1175
|
+
if (enableSelectedBtn)
|
|
1176
|
+
enableSelectedBtn.disabled = !hasSelection;
|
|
1177
|
+
if (disableSelectedBtn)
|
|
1178
|
+
disableSelectedBtn.disabled = !hasSelection;
|
|
1179
|
+
}
|
|
1180
|
+
window.removeEventListener('discovery-selection-changed', updateBatchButtonStates);
|
|
1181
|
+
window.addEventListener('discovery-selection-changed', updateBatchButtonStates);
|
|
1182
|
+
// Add 'Add Selected to Config' button if not present, and align all red action buttons in a row
|
|
1183
|
+
let batchControls = document.getElementById('batchImportControls');
|
|
1184
|
+
if (!batchControls) {
|
|
1185
|
+
batchControls = document.createElement('div');
|
|
1186
|
+
batchControls.id = 'batchImportControls';
|
|
1187
|
+
batchControls.style.display = 'flex';
|
|
1188
|
+
batchControls.style.flexWrap = 'wrap';
|
|
1189
|
+
batchControls.style.alignItems = 'center';
|
|
1190
|
+
batchControls.style.gap = '18px';
|
|
1191
|
+
batchControls.style.margin = '8px 0 18px 0';
|
|
1192
|
+
batchControls.style.width = '100%';
|
|
1193
|
+
// Button container for horizontal alignment
|
|
1194
|
+
const buttonRow = document.createElement('div');
|
|
1195
|
+
buttonRow.style.display = 'flex';
|
|
1196
|
+
buttonRow.style.flexWrap = 'nowrap';
|
|
1197
|
+
buttonRow.style.alignItems = 'center';
|
|
1198
|
+
buttonRow.style.justifyContent = 'center';
|
|
1199
|
+
buttonRow.style.gap = '16px';
|
|
1200
|
+
buttonRow.style.width = '100%';
|
|
1201
|
+
// Add Selected to Config button
|
|
1202
|
+
const addSelectedBtn = document.createElement('button');
|
|
1203
|
+
addSelectedBtn.id = 'addSelectedBtn';
|
|
1204
|
+
addSelectedBtn.textContent = 'Add Selected to Config';
|
|
1205
|
+
addSelectedBtn.disabled = selectedIds.size === 0;
|
|
1206
|
+
addSelectedBtn.style.fontWeight = '600';
|
|
1207
|
+
// Shared style for all red action buttons
|
|
1208
|
+
const redButtonStyle = {
|
|
1209
|
+
width: '220px',
|
|
1210
|
+
padding: '12px 0',
|
|
1211
|
+
fontSize: '17px',
|
|
1212
|
+
marginBottom: '0',
|
|
1213
|
+
boxShadow: '0 2px 8px 0 rgba(220,38,38,0.10)',
|
|
1214
|
+
borderRadius: '8px',
|
|
1215
|
+
};
|
|
1216
|
+
Object.assign(addSelectedBtn.style, redButtonStyle);
|
|
1217
|
+
addSelectedBtn.style.background = '#ef4444';
|
|
1218
|
+
addSelectedBtn.style.color = 'white';
|
|
1219
|
+
addSelectedBtn.style.transition = 'background 0.2s, box-shadow 0.2s';
|
|
1220
|
+
addSelectedBtn.onmouseenter = function () {
|
|
1221
|
+
addSelectedBtn.style.background = '#dc2626';
|
|
1222
|
+
};
|
|
1223
|
+
addSelectedBtn.onmouseleave = function () {
|
|
1224
|
+
addSelectedBtn.style.background = '#ef4444';
|
|
1225
|
+
};
|
|
1226
|
+
addSelectedBtn.onclick = async () => {
|
|
1227
|
+
if (!selectedIds.size) {
|
|
1228
|
+
return;
|
|
1229
|
+
}
|
|
1230
|
+
addSelectedBtn.disabled = true;
|
|
1231
|
+
addSelectedBtn.textContent = 'Adding...';
|
|
1232
|
+
try {
|
|
1233
|
+
const selectedDevices = visibleDevices.filter(d => selectedIds.has(normalizeId(d.id)));
|
|
1234
|
+
const bulkResult = await addDevicesInBulk(selectedDevices.map(d => ({
|
|
1235
|
+
deviceId: d.id,
|
|
1236
|
+
name: d.name,
|
|
1237
|
+
type: d.type,
|
|
1238
|
+
rssi: d.rssi,
|
|
1239
|
+
address: d.address,
|
|
1240
|
+
model: d.model,
|
|
1241
|
+
})));
|
|
1242
|
+
uiLog.info('Batch add response:', bulkResult);
|
|
1243
|
+
if (!bulkResult || bulkResult.success === false) {
|
|
1244
|
+
throw new Error(bulkResult?.data?.message || 'Batch add failed');
|
|
1245
|
+
}
|
|
1246
|
+
const addedCount = bulkResult?.addedCount ?? bulkResult?.data?.addedCount ?? 0;
|
|
1247
|
+
const skippedCount = bulkResult?.skippedCount ?? bulkResult?.data?.skippedCount ?? 0;
|
|
1248
|
+
toastSuccess(`Added ${addedCount} device(s)${skippedCount > 0 ? ` (${skippedCount} skipped)` : ''}`);
|
|
1249
|
+
await loadConfiguredDevices();
|
|
1250
|
+
selectedIds.clear();
|
|
1251
|
+
addSelectedBtn.disabled = true;
|
|
1252
|
+
addSelectedBtn.textContent = 'Add Selected to Config';
|
|
1253
|
+
await updateDiscoveryView(allDevices, preferences, groupBy, hideAdded, selectedIds);
|
|
1254
|
+
}
|
|
1255
|
+
catch (e) {
|
|
1256
|
+
uiLog.error('Batch add error:', e);
|
|
1257
|
+
toastError(e instanceof Error ? e.message : 'Failed to add devices');
|
|
1258
|
+
addSelectedBtn.disabled = false;
|
|
1259
|
+
addSelectedBtn.textContent = 'Add Selected to Config';
|
|
1260
|
+
}
|
|
1261
|
+
};
|
|
1262
|
+
// Enable Selected button
|
|
1263
|
+
const enableSelectedBtn = document.createElement('button');
|
|
1264
|
+
enableSelectedBtn.textContent = 'Enable Selected';
|
|
1265
|
+
enableSelectedBtn.style.fontWeight = '600';
|
|
1266
|
+
Object.assign(enableSelectedBtn.style, redButtonStyle);
|
|
1267
|
+
enableSelectedBtn.style.background = '#ef4444';
|
|
1268
|
+
enableSelectedBtn.style.color = 'white';
|
|
1269
|
+
enableSelectedBtn.style.transition = 'background 0.2s, box-shadow 0.2s';
|
|
1270
|
+
enableSelectedBtn.onmouseenter = function () {
|
|
1271
|
+
enableSelectedBtn.style.background = '#dc2626';
|
|
1272
|
+
};
|
|
1273
|
+
enableSelectedBtn.onmouseleave = function () {
|
|
1274
|
+
enableSelectedBtn.style.background = '#ef4444';
|
|
1275
|
+
};
|
|
1276
|
+
enableSelectedBtn.disabled = selectedIds.size === 0;
|
|
1277
|
+
enableSelectedBtn.onclick = async () => {
|
|
1278
|
+
if (!selectedIds.size) {
|
|
1279
|
+
return;
|
|
1280
|
+
}
|
|
1281
|
+
enableSelectedBtn.disabled = true;
|
|
1282
|
+
try {
|
|
1283
|
+
showBusyUi();
|
|
1284
|
+
await batchSetDeviceEnabled(selectedIds, true);
|
|
1285
|
+
toastSuccess('Selected devices enabled');
|
|
1286
|
+
await loadConfiguredDevices();
|
|
1287
|
+
await updateDiscoveryView(allDevices, preferences, groupBy, hideAdded, selectedIds);
|
|
1288
|
+
}
|
|
1289
|
+
catch (e) {
|
|
1290
|
+
uiLog.error('Batch enable error:', e);
|
|
1291
|
+
toastError(e instanceof Error ? e.message : 'Failed to enable devices');
|
|
1292
|
+
}
|
|
1293
|
+
finally {
|
|
1294
|
+
hideBusyUi();
|
|
1295
|
+
enableSelectedBtn.disabled = false;
|
|
1296
|
+
}
|
|
1297
|
+
};
|
|
1298
|
+
// Disable Selected button
|
|
1299
|
+
const disableSelectedBtn = document.createElement('button');
|
|
1300
|
+
disableSelectedBtn.textContent = 'Disable Selected';
|
|
1301
|
+
disableSelectedBtn.style.fontWeight = '600';
|
|
1302
|
+
Object.assign(disableSelectedBtn.style, redButtonStyle);
|
|
1303
|
+
disableSelectedBtn.style.background = '#ef4444';
|
|
1304
|
+
disableSelectedBtn.style.color = 'white';
|
|
1305
|
+
disableSelectedBtn.style.transition = 'background 0.2s, box-shadow 0.2s';
|
|
1306
|
+
disableSelectedBtn.onmouseenter = function () {
|
|
1307
|
+
disableSelectedBtn.style.background = '#dc2626';
|
|
1308
|
+
};
|
|
1309
|
+
disableSelectedBtn.onmouseleave = function () {
|
|
1310
|
+
disableSelectedBtn.style.background = '#ef4444';
|
|
1311
|
+
};
|
|
1312
|
+
disableSelectedBtn.disabled = selectedIds.size === 0;
|
|
1313
|
+
disableSelectedBtn.onclick = async () => {
|
|
1314
|
+
if (!selectedIds.size) {
|
|
1315
|
+
return;
|
|
1316
|
+
}
|
|
1317
|
+
disableSelectedBtn.disabled = true;
|
|
1318
|
+
try {
|
|
1319
|
+
showBusyUi();
|
|
1320
|
+
await batchSetDeviceEnabled(selectedIds, false);
|
|
1321
|
+
toastSuccess('Selected devices disabled');
|
|
1322
|
+
await loadConfiguredDevices();
|
|
1323
|
+
await updateDiscoveryView(allDevices, preferences, groupBy, hideAdded, selectedIds);
|
|
1324
|
+
}
|
|
1325
|
+
catch (e) {
|
|
1326
|
+
uiLog.error('Batch disable error:', e);
|
|
1327
|
+
toastError(e instanceof Error ? e.message : 'Failed to disable devices');
|
|
1328
|
+
}
|
|
1329
|
+
finally {
|
|
1330
|
+
hideBusyUi();
|
|
1331
|
+
disableSelectedBtn.disabled = false;
|
|
1332
|
+
}
|
|
1333
|
+
};
|
|
1334
|
+
buttonRow.appendChild(addSelectedBtn);
|
|
1335
|
+
buttonRow.appendChild(enableSelectedBtn);
|
|
1336
|
+
buttonRow.appendChild(disableSelectedBtn);
|
|
1337
|
+
batchControls.appendChild(buttonRow);
|
|
1338
|
+
const listContainer = document.getElementById('discoveredList');
|
|
1339
|
+
if (listContainer) {
|
|
1340
|
+
listContainer.insertBefore(batchControls, listContainer.firstChild);
|
|
1341
|
+
}
|
|
1342
|
+
}
|
|
1343
|
+
else {
|
|
1344
|
+
// Update button state if already present
|
|
1345
|
+
const addSelectedBtn = document.getElementById('addSelectedBtn');
|
|
1346
|
+
if (addSelectedBtn) {
|
|
1347
|
+
addSelectedBtn.disabled = selectedIds.size === 0;
|
|
250
1348
|
}
|
|
251
1349
|
}
|
|
252
|
-
ul.id = 'discoveredDevices';
|
|
253
1350
|
// Update status with count
|
|
254
1351
|
const status = document.getElementById('discoverStatus');
|
|
255
1352
|
if (status) {
|
|
256
1353
|
const totalCount = allDevices.length;
|
|
257
|
-
const filteredCount =
|
|
1354
|
+
const filteredCount = visibleDevices.length;
|
|
258
1355
|
status.textContent = filteredCount === totalCount
|
|
259
1356
|
? `Found ${totalCount} device(s)`
|
|
260
1357
|
: `Showing ${filteredCount} of ${totalCount} device(s)`;
|