-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp-modular.js
More file actions
2708 lines (2351 loc) · 80.6 KB
/
Copy pathapp-modular.js
File metadata and controls
2708 lines (2351 loc) · 80.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Main Application Entry Point
* Orchestrates all modules and initializes the application
*
* This is a SIMPLIFIED version showing the modular architecture.
* The full UI controller implementation would be much larger.
*/
import { ConnectionManager, ConnectionType } from "./js/connection-manager.js";
import {
COMMANDS,
DEVICE_PROFILES,
DEVICE_TYPES,
KNOWN_FIRMWARE,
LOG_CLASSES,
STORAGE_KEYS,
} from "./js/constants.js";
import { EditModalManager } from "./js/edit-modal.js";
import { AudioConverter, FileManager } from "./js/file-manager.js";
import {
buildCommand,
bytesToHex,
clamp,
deviceSpeedToUI,
escapeHtml,
uiSpeedToDevice,
} from "./js/protocol.js";
import { ProtocolParser } from "./js/protocol-parser.js";
import { StateManager } from "./js/state-manager.js";
import { TransferModalManager } from "./js/transfer-modal.js";
/**
* Simple Logger
*/
class Logger {
constructor(logElement, autoscrollElement) {
this.logElement = logElement;
this.autoscrollElement = autoscrollElement;
this.filterCallback = null;
}
setFilterCallback(callback) {
this.filterCallback = callback;
}
log(message, className = LOG_CLASSES.NORMAL) {
if (!this.logElement) return;
const div = document.createElement("div");
div.className = `line ${className}`;
const time = new Date().toLocaleTimeString();
div.textContent = `[${time}] ${message}`;
this.logElement.appendChild(div);
// Apply filter to the new line
if (this.filterCallback) {
this.filterCallback();
}
// Auto-scroll if enabled
if (!this.autoscrollElement || this.autoscrollElement.checked) {
this.logElement.scrollTop = this.logElement.scrollHeight;
}
}
}
/**
* Simple UI Helper
*/
const $ = (selector) => document.querySelector(selector);
/**
* Set progress display
*/
function setProgress(idx, total) {
const pct = total ? Math.round((idx / total) * 100) : 0;
const progText = $("#progText");
const progPct = $("#progPct");
const progBar = $("#progBar");
if (progText) progText.textContent = `${idx} / ${total}`;
if (progPct) progPct.textContent = `${pct}%`;
if (progBar) progBar.style.width = `${pct}%`;
}
/**
* Main Application
*/
class SkellyApp {
constructor() {
try {
console.log("SkellyApp initializing...");
// Initialize logger
this.logger = new Logger($("#log"), $("#chkAutoscroll"));
this.logger.setFilterCallback(() => this.applyLogFilter());
console.log("Logger created");
// Initialize state manager
this.state = new StateManager();
console.log("State manager created");
// Initialize play state tracking
this.playState = {
serial: null,
playing: false,
duration: 0,
startTime: null,
timerInterval: null,
};
// Initialize connection manager (wraps both BLE and REST proxy)
this.connection = new ConnectionManager(
this.state,
this.logger.log.bind(this.logger),
);
console.log("Connection manager created");
// Initialize file manager with progress callback
this.fileManager = new FileManager(
this.connection,
this.state,
this.logger.log.bind(this.logger),
(current, total) => setProgress(current, total),
);
console.log("File manager created");
// Initialize audio converter
this.audioConverter = new AudioConverter(
this.logger.log.bind(this.logger),
);
console.log("Audio converter created");
// Initialize edit modal manager (before parser so we can pass callback)
this.editModal = new EditModalManager(
this.connection,
this.state,
this.fileManager,
this.logger.log.bind(this.logger),
);
// Initialize transfer modal manager
this.transferModal = new TransferModalManager(
this.connection,
this.state,
this.fileManager,
this.audioConverter,
this.logger.log.bind(this.logger),
);
this.transferModal.setReplaceSuccessHandler(() => this.editModal.close());
this.editModal.setReplaceFileHandler((filename) => {
this.transferModal.open("replace", filename);
});
console.log("Edit modal manager created");
// Initialize protocol parser with callbacks
this.parser = new ProtocolParser(
this.state,
this.fileManager,
this.logger.log.bind(this.logger),
this.handlePlayPauseMessage.bind(this),
this.editModal.handleDeleteConfirmation.bind(this.editModal),
);
console.log("Protocol parser created");
// Register protocol parser with connection manager
this.connection.onNotification((hex, bytes) => {
this.parser.parse(hex, bytes);
});
console.log("Notification handler registered");
// Subscribe to state changes
this.subscribeToStateChanges();
console.log("State subscriptions registered");
// Initialize UI
this.initializeUI();
console.log("UI initialized");
// Set initial UI state
this.updateDeviceUI(this.state.device);
this.updateFilesTable();
this.transferModal.updateButtons(this.state.transfer);
console.log("Initial UI state set");
console.log("Application initialized successfully");
this.logger.log("Application initialized", LOG_CLASSES.WARNING);
} catch (error) {
console.error("Failed to initialize application:", error);
console.error("Error stack:", error.stack);
alert("Failed to initialize application. Check console for details.");
throw error;
}
}
/**
* Subscribe to state changes
*/
subscribeToStateChanges() {
// Device state changes
this.state.subscribe("device", (device) => {
this.updateDeviceUI(device);
});
// Live status changes
this.state.subscribe("live", (live) => {
this.updateLiveUI(live);
});
// File list changes
this.state.subscribe("files", () => {
this.updateFilesTable();
});
}
/**
* Initialize UI and event handlers
*/
initializeUI() {
console.log("Initializing UI...");
// Initial disconnected state
document.body.classList.add("disconnected");
// Connection controls
const btnConnect = $("#btnConnect");
const btnDisconnect = $("#btnDisconnect");
if (btnConnect) {
console.log("Binding connect button");
btnConnect.addEventListener("click", () => {
console.log("Connect button clicked");
this.handleConnect();
});
} else {
console.error("Connect button not found!");
}
if (btnDisconnect) {
btnDisconnect.addEventListener("click", () => this.handleDisconnect());
} else {
console.error("Disconnect button not found!");
}
// Log controls
const btnClearLog = $("#btnClearLog");
if (btnClearLog) {
btnClearLog.addEventListener("click", () => {
const logEl = $("#log");
if (logEl) logEl.innerHTML = "";
});
}
const btnSaveLog = $("#btnSaveLog");
if (btnSaveLog) {
btnSaveLog.addEventListener("click", () => {
this.saveLog();
});
}
this.initializeWarningModal();
this.initializeFirmwareWarningModal();
this.initializeConnectionModal();
this.initializeDeviceTypeControl();
this.initializeAdvancedMenu();
this.initializeLogFilter();
this.initializeQueryButtons();
this.initializeMediaControls();
this.initializeFileControls();
this.initializeLiveControls();
// Check for Web Bluetooth support
if (!ConnectionManager.isWebBluetoothAvailable()) {
console.error("Web Bluetooth not supported");
this.logger.log(
"Web Bluetooth not supported. For direct BLE, use Chrome/Edge. For other browsers, use the REST Server Proxy: https://github.com/martinecker/SkellyUltra/tree/main/custom_components/skelly_ultra/skelly_ultra_srv",
LOG_CLASSES.WARNING,
);
// Don't show blocking alert - REST proxy is available as alternative
console.log("REST Server Proxy can be used as an alternative");
} else {
console.log("Web Bluetooth API is available");
// Check for secure context (HTTPS or localhost)
if (!window.isSecureContext) {
console.error(
"Not in secure context - Web Bluetooth requires HTTPS or localhost",
);
this.logger.log(
"Web Bluetooth requires HTTPS or localhost for direct BLE. Use HTTPS or the REST Server Proxy.",
LOG_CLASSES.WARNING,
);
} else {
console.log("Running in secure context");
}
}
console.log("UI initialization complete");
// Apply persisted device profile on startup
const startupDeviceType =
localStorage.getItem(STORAGE_KEYS.DEVICE_TYPE) || DEVICE_TYPES.SKELLY;
this.state.setDeviceType(startupDeviceType);
this.applyDeviceProfile(startupDeviceType);
}
/**
* Initialize device type dropdown (post-connect override)
*/
initializeDeviceTypeControl() {
const deviceTypeSelect = $("#deviceTypeSelect");
if (!deviceTypeSelect) return;
// Sync with persisted value
const saved =
localStorage.getItem(STORAGE_KEYS.DEVICE_TYPE) || DEVICE_TYPES.SKELLY;
deviceTypeSelect.value = saved;
deviceTypeSelect.addEventListener("change", () => {
const newType = deviceTypeSelect.value;
const oldType = this.state.deviceType;
if (newType === oldType) return;
const apply = () => {
localStorage.setItem(STORAGE_KEYS.DEVICE_TYPE, newType);
this.state.setDeviceType(newType);
this.applyDeviceProfile(newType);
};
const modal = $("#deviceTypeChangeModal");
if (!modal) {
apply();
return;
}
const newName = DEVICE_PROFILES[newType]?.uiName ?? newType;
const oldName = DEVICE_PROFILES[oldType]?.uiName ?? oldType;
const msg = $("#deviceTypeChangeMsgDetail");
if (msg) {
msg.textContent = `You are switching from "${oldName}" to "${newName}".`;
}
modal.classList.remove("hidden");
const onConfirm = () => {
modal.classList.add("hidden");
cleanup();
apply();
};
const onCancel = () => {
modal.classList.add("hidden");
cleanup();
// Revert select back to the current type
deviceTypeSelect.value = oldType;
};
const cleanup = () => {
$("#deviceTypeChangeConfirm")?.removeEventListener("click", onConfirm);
$("#deviceTypeChangeCancel")?.removeEventListener("click", onCancel);
};
$("#deviceTypeChangeConfirm")?.addEventListener("click", onConfirm);
$("#deviceTypeChangeCancel")?.addEventListener("click", onCancel);
});
}
/**
* Apply a device profile — rebuilds the movement grids and reconfigures all
* profile-driven UI elements (lights, eye section, file table columns, etc.)
* @param {string} deviceType - one of DEVICE_TYPES
*/
applyDeviceProfile(deviceType) {
const profile = DEVICE_PROFILES[deviceType];
if (!profile) return;
// Sync the post-connect dropdown
const deviceTypeSelect = $("#deviceTypeSelect");
if (deviceTypeSelect) deviceTypeSelect.value = deviceType;
// Rebuild movement grids
for (const gridId of ["liveMove", "edMove"]) {
const grid = $(`#${gridId}`);
if (!grid) continue;
grid.innerHTML = "";
profile.movements.forEach(({ part, label, icon, bit }) => {
const btn = document.createElement("button");
btn.className = "iconToggle";
btn.dataset.part = part;
btn.dataset.bit = String(bit);
btn.title = label;
const img = document.createElement("img");
img.src = icon;
img.alt = label;
img.style.width = "36px";
img.style.height = "36px";
btn.appendChild(img);
grid.appendChild(btn);
});
}
// Re-bind live movement grid handlers
this.bindMovementGrid("liveMove");
// Re-bind edit modal movement handlers
this.editModal?.initializeMovementControls();
// Show/hide eye sections
const hasEyeImage = profile.hasEyeImage;
for (const id of ["liveEyeSection", "editEyeSection"]) {
const el = $(`#${id}`);
if (el) el.style.display = hasEyeImage ? "" : "none";
}
// Show/hide Light 1 group
const hasLight1 = profile.lights.length > 1;
for (const id of ["liveLight1Group", "editLight1Group"]) {
const el = $(`#${id}`);
if (el) el.style.display = hasLight1 ? "" : "none";
}
// Update Light 0 label
const light0 = profile.lights[0];
const light0Label = light0 ? light0.label : "Light";
for (const id of ["liveLight0Label", "editLight0Label"]) {
const el = $(`#${id}`);
if (el) el.textContent = light0Label;
}
// Repopulate effect mode selects
const modeSelects = [
"light1EffectMode",
"light0EffectMode",
"edLight1EffectMode",
"edLight0EffectMode",
];
for (const selectId of modeSelects) {
const sel = $(`#${selectId}`);
if (!sel) continue;
const current = sel.value;
sel.innerHTML = "";
profile.lightModes.forEach(({ value, label }) => {
const opt = document.createElement("option");
opt.value = String(value);
opt.textContent = label;
sel.appendChild(opt);
});
// Try to restore previously selected value; fall back to first option
sel.value = current;
if (!sel.value) sel.value = String(profile.lightModes[0].value);
}
// Update files table column visibility and labels
const light1 = profile.lights[1];
const light1Label = light1 ? light1.label : "Light 1";
const filesLight1Col = $("#filesLight1Col");
if (filesLight1Col) {
filesLight1Col.style.display = hasLight1 ? "" : "none";
filesLight1Col.textContent = light1Label;
}
const filesEyeCol = $("#filesEyeCol");
if (filesEyeCol) filesEyeCol.style.display = hasEyeImage ? "" : "none";
const filesLight0Col = $("#filesLight0Col");
if (filesLight0Col) filesLight0Col.textContent = light0Label;
// Keep body cell classes in sync — add/remove display style via dynamic <style>
let dynStyle = document.getElementById("_profileColStyle");
if (!dynStyle) {
dynStyle = document.createElement("style");
dynStyle.id = "_profileColStyle";
document.head.appendChild(dynStyle);
}
const rules = [];
if (!hasLight1) rules.push("td.col-light1 { display: none; }");
if (!hasEyeImage) rules.push("td.col-eye { display: none; }");
dynStyle.textContent = rules.join("\n");
}
/**
* Bind click handlers for a live movement grid.
* Buttons must already be in the DOM with data-part and data-bit attributes.
* @param {string} gridId
*/
bindMovementGrid(gridId) {
const grid = document.getElementById(gridId);
if (!grid) return;
const allBtn = grid.querySelector('[data-part="all"]');
const partBtns = Array.from(
grid.querySelectorAll('[data-part]:not([data-part="all"])'),
);
const sendMovementCommand = async () => {
if (!this.connection.isConnected()) return;
if (allBtn?.classList.contains("selected")) {
await this.connection.send(
buildCommand(COMMANDS.SET_MOVEMENT, "FF00000000", 8),
);
this.logger.log("Applied movement: all");
} else {
let bitfield = 0;
partBtns.forEach((btn) => {
if (btn.classList.contains("selected")) {
bitfield |= parseInt(btn.dataset.bit || "0", 10);
}
});
if (bitfield > 0) {
const bitfieldHex = bitfield
.toString(16)
.padStart(2, "0")
.toUpperCase();
await this.connection.send(
buildCommand(COMMANDS.SET_MOVEMENT, `${bitfieldHex}00000000`, 8),
);
const parts = partBtns
.filter((b) => b.classList.contains("selected"))
.map((b) => b.dataset.part);
this.logger.log(`Applied movement: ${parts.join(", ")}`);
} else {
await this.connection.send(
buildCommand(COMMANDS.SET_MOVEMENT, "0000000000", 8),
);
this.logger.log("Disabled movement");
}
}
};
allBtn?.addEventListener("click", () => {
allBtn.classList.toggle("selected");
if (allBtn.classList.contains("selected")) {
partBtns.forEach((btn) => {
btn.classList.remove("selected");
});
}
sendMovementCommand();
});
partBtns.forEach((btn) => {
btn.addEventListener("click", () => {
btn.classList.toggle("selected");
allBtn?.classList.remove("selected");
sendMovementCommand();
});
});
}
/**
* Initialize warning modal
*/
initializeWarningModal() {
const riskModal = $("#riskModal");
const showRisk = () => riskModal?.classList.remove("hidden");
const hideRisk = () => riskModal?.classList.add("hidden");
window.addEventListener("load", () => {
if (!localStorage.getItem(STORAGE_KEYS.RISK_ACK)) {
showRisk();
}
});
$("#riskAccept")?.addEventListener("click", () => {
localStorage.setItem(STORAGE_KEYS.RISK_ACK, "1");
hideRisk();
});
$("#riskCancel")?.addEventListener("click", () => {
window.location.href = "about:blank";
});
}
initializeFirmwareWarningModal() {
$("#fwWarningOk")?.addEventListener("click", () => {
$("#fwWarningModal")?.classList.add("hidden");
});
}
/**
* Initialize connection modal
*/
initializeConnectionModal() {
const connectModal = $("#connectModal");
const connectFilterDefault = $("#connectFilterDefault");
const connectDefaultDevice = $("#connectDefaultDevice");
const connectAllDevices = $("#connectAllDevices");
const connectionTypeDirect = $("#connectionTypeDirect");
const connectionTypeRest = $("#connectionTypeRest");
const restUrlContainer = $("#restUrlContainer");
const restServerUrl = $("#restServerUrl");
const webBluetoothWarning = $("#webBluetoothWarning");
const connectionTypeDirectLabel = $("#connectionTypeDirectLabel");
// Check Web Bluetooth availability
const isWebBluetoothAvailable = ConnectionManager.isWebBluetoothAvailable();
// Load saved preferences
const savedConnectionType =
localStorage.getItem(STORAGE_KEYS.CONNECTION_TYPE) || "direct";
const savedRestUrl =
localStorage.getItem(STORAGE_KEYS.REST_URL) || "http://localhost:8765";
const savedDeviceType =
localStorage.getItem(STORAGE_KEYS.DEVICE_TYPE) || DEVICE_TYPES.SKELLY;
// Restore saved device type in dropdown
if (connectDefaultDevice) {
connectDefaultDevice.value = savedDeviceType;
}
// Handle Web Bluetooth unavailability
if (!isWebBluetoothAvailable) {
if (webBluetoothWarning) webBluetoothWarning.style.display = "block";
if (connectionTypeDirect) connectionTypeDirect.disabled = true;
if (connectionTypeDirectLabel) {
connectionTypeDirectLabel.style.opacity = "0.5";
connectionTypeDirectLabel.style.cursor = "not-allowed";
}
if (connectionTypeRest) connectionTypeRest.checked = true;
} else {
if (savedConnectionType === "rest" && connectionTypeRest) {
connectionTypeRest.checked = true;
} else if (connectionTypeDirect) {
connectionTypeDirect.checked = true;
}
}
if (restServerUrl) {
restServerUrl.value = savedRestUrl;
}
// Show/hide REST URL input based on connection type
const updateConnectionTypeUI = () => {
if (restUrlContainer) {
restUrlContainer.style.display = connectionTypeRest?.checked
? "block"
: "none";
}
};
connectionTypeDirect?.addEventListener("change", updateConnectionTypeUI);
connectionTypeRest?.addEventListener("change", updateConnectionTypeUI);
// Enable/disable device dropdown based on radio selection
const updateFilterState = () => {
const isDefault = connectFilterDefault?.checked;
if (connectDefaultDevice) connectDefaultDevice.disabled = !isDefault;
};
connectFilterDefault?.addEventListener("change", updateFilterState);
connectAllDevices?.addEventListener("change", updateFilterState);
// Initialize state
updateConnectionTypeUI();
updateFilterState();
// Close modal function
const closeModal = () => {
connectModal?.classList.add("hidden");
};
// Cancel button
$("#connectCancel")?.addEventListener("click", closeModal);
// Escape key to close modal
document.addEventListener("keydown", (e) => {
if (e.key === "Escape" && !connectModal?.classList.contains("hidden")) {
closeModal();
}
});
// Connect button
$("#connectOk")?.addEventListener("click", async () => {
connectModal?.classList.add("hidden");
// Determine connection type
const connectionType = connectionTypeRest?.checked
? ConnectionType.REST_PROXY
: ConnectionType.DIRECT_BLE;
// Get REST URL if needed
const restUrl = restServerUrl?.value || "http://localhost:8765";
// Determine filter value and device type
let nameFilter = "";
let deviceType = savedDeviceType;
if (connectFilterDefault?.checked) {
// Default name filter — device type comes directly from the dropdown
const selectedOption =
connectDefaultDevice?.value || DEVICE_TYPES.SKELLY;
// "skelly_old" is the legacy "Animated Skelly" BLE name; treat as skelly device type
if (selectedOption === "skelly_old") {
deviceType = DEVICE_TYPES.SKELLY;
nameFilter = "Animated Skelly";
} else {
deviceType = selectedOption;
nameFilter = DEVICE_PROFILES[deviceType]?.defaultBleName || "";
}
}
// All devices: nameFilter stays '', deviceType stays last persisted
// Persist preferences
localStorage.setItem(STORAGE_KEYS.CONNECTION_TYPE, connectionType);
localStorage.setItem(STORAGE_KEYS.DEVICE_TYPE, deviceType);
if (connectionType === ConnectionType.REST_PROXY) {
localStorage.setItem(STORAGE_KEYS.REST_URL, restUrl);
}
// Apply device profile immediately so the UI is correct before connection completes
this.state.setDeviceType(deviceType);
this.applyDeviceProfile(deviceType);
// For REST proxy, show device selection modal
if (connectionType === ConnectionType.REST_PROXY) {
await this.showDeviceSelectionModal(restUrl, nameFilter);
} else {
await this.performConnection({ connectionType, restUrl, nameFilter });
}
});
}
/**
* Show device selection modal for REST proxy
*/
async showDeviceSelectionModal(restUrl, nameFilter) {
const deviceSelectModal = $("#deviceSelectModal");
const deviceList = $("#deviceList");
const deviceSelectStatus = $("#deviceSelectStatus");
const deviceSelectCancel = $("#deviceSelectCancel");
const deviceSelectRescan = $("#deviceSelectRescan");
if (!deviceSelectModal || !deviceList) return;
// Show modal
deviceSelectModal.classList.remove("hidden");
// Scan function
const scanForDevices = async () => {
try {
deviceList.innerHTML = "";
deviceSelectStatus.textContent = "Scanning for devices...";
// Use connection.restProxy to scan
const devices = await this.connection.restProxy.scanDevices(
restUrl,
nameFilter,
10,
);
if (devices.length === 0) {
deviceSelectStatus.textContent = "No devices found";
deviceList.innerHTML =
'<p style="padding: 20px; text-align: center; color: #6b7280;">No devices discovered. Try rescanning or check if devices are powered on.</p>';
return;
}
deviceSelectStatus.textContent = `Found ${devices.length} device${devices.length > 1 ? "s" : ""}:`;
// Create device list
devices.forEach((device) => {
const deviceItem = document.createElement("div");
deviceItem.style.cssText =
"padding: 12px; margin: 8px 0; background: #1f2937; border: 1px solid #374151; border-radius: 8px; cursor: pointer; transition: all 0.2s;";
deviceItem.innerHTML = `
<div style="font-weight: 500;">${escapeHtml(device.name || "Unknown Device")}</div>
<div style="font-size: 11px; color: #9ca3af; margin-top: 4px;">${escapeHtml(device.address)}</div>
<div style="font-size: 11px; color: #6b7280;">Signal: ${device.rssi} dBm</div>
`;
deviceItem.addEventListener("mouseenter", () => {
deviceItem.style.background = "#374151";
deviceItem.style.borderColor = "#3b82f6";
});
deviceItem.addEventListener("mouseleave", () => {
deviceItem.style.background = "#1f2937";
deviceItem.style.borderColor = "#374151";
});
deviceItem.addEventListener("click", async () => {
deviceSelectModal.classList.add("hidden");
await this.performConnection({
connectionType: ConnectionType.REST_PROXY,
restUrl,
deviceAddress: device.address,
});
});
deviceList.appendChild(deviceItem);
});
} catch (error) {
console.error("Device scan error:", error);
deviceSelectStatus.textContent = "Scan failed";
deviceList.innerHTML = `<p style="padding: 20px; text-align: center; color: #ef4444;">${escapeHtml(error.message)}</p>`;
}
};
// Cancel button
const cancelHandler = () => {
deviceSelectModal.classList.add("hidden");
};
// Rescan button
const rescanHandler = () => {
scanForDevices();
};
// Add event listeners
deviceSelectCancel.removeEventListener("click", cancelHandler);
deviceSelectCancel.addEventListener("click", cancelHandler);
deviceSelectRescan.removeEventListener("click", rescanHandler);
deviceSelectRescan.addEventListener("click", rescanHandler);
// Escape key to close
const escapeHandler = (e) => {
if (
e.key === "Escape" &&
!deviceSelectModal.classList.contains("hidden")
) {
deviceSelectModal.classList.add("hidden");
}
};
document.removeEventListener("keydown", escapeHandler);
document.addEventListener("keydown", escapeHandler);
// Start initial scan
await scanForDevices();
}
/**
* Initialize advanced menu
*/
initializeAdvancedMenu() {
const advMenu = $("#advMenu");
const advRaw = $("#advRaw");
const advFEDC = $("#advFEDC");
const advFileDetails = $("#advFileDetails");
// Load saved state
advRaw.checked = localStorage.getItem(STORAGE_KEYS.ADV_RAW) === "1";
advFEDC.checked = localStorage.getItem(STORAGE_KEYS.ADV_FEDC) === "1";
advFileDetails.checked =
localStorage.getItem(STORAGE_KEYS.SHOW_FILE_DETAILS) === "1";
// Toggle menu
$("#btnAdvanced")?.addEventListener("click", (e) => {
e.stopPropagation();
advMenu?.classList.toggle("hidden");
});
// Close menu on outside click
document.addEventListener("click", (e) => {
if (!e.target.closest(".menuwrap")) {
advMenu?.classList.add("hidden");
}
});
// Save state on change
[advRaw, advFEDC, advFileDetails].forEach((el) => {
el?.addEventListener("change", () => {
localStorage.setItem(STORAGE_KEYS.ADV_RAW, advRaw.checked ? "1" : "0");
localStorage.setItem(
STORAGE_KEYS.ADV_FEDC,
advFEDC.checked ? "1" : "0",
);
localStorage.setItem(
STORAGE_KEYS.SHOW_FILE_DETAILS,
advFileDetails.checked ? "1" : "0",
);
this.applyAdvancedVisibility();
});
});
this.applyAdvancedVisibility();
}
/**
* Apply advanced feature visibility
*/
applyAdvancedVisibility() {
const advRaw = $("#advRaw");
const advFileDetails = $("#advFileDetails");
$("#advRawBlock")?.classList.toggle("hidden", !advRaw?.checked);
// Toggle detail columns visibility
const showDetails = advFileDetails?.checked;
document.querySelectorAll(".detail-column").forEach((col) => {
col.style.display = showDetails ? "" : "none";
});
}
/**
* Initialize log filter menu
*/
initializeLogFilter() {
const logFilterMenu = $("#logFilterMenu");
const logFilterNormal = $("#logFilterNormal");
const logFilterWarning = $("#logFilterWarning");
const logFilterTx = $("#logFilterTx");
const logFilterRx = $("#logFilterRx");
// Load saved state (default to all checked)
logFilterNormal.checked =
localStorage.getItem(STORAGE_KEYS.LOG_FILTER_NORMAL) !== "0";
logFilterWarning.checked =
localStorage.getItem(STORAGE_KEYS.LOG_FILTER_WARNING) !== "0";
logFilterTx.checked =
localStorage.getItem(STORAGE_KEYS.LOG_FILTER_TX) !== "0";
logFilterRx.checked =
localStorage.getItem(STORAGE_KEYS.LOG_FILTER_RX) !== "0";
// Toggle menu
$("#btnLogFilter")?.addEventListener("click", (e) => {
e.stopPropagation();
logFilterMenu?.classList.toggle("hidden");
});
// Close menu on outside click
document.addEventListener("click", (e) => {
if (!e.target.closest(".menuwrap") || e.target.closest("#advMenu")) {
logFilterMenu?.classList.add("hidden");
}
});
// Save state and apply filter on change
[logFilterNormal, logFilterWarning, logFilterTx, logFilterRx].forEach(
(el) => {
el?.addEventListener("change", () => {
localStorage.setItem(
STORAGE_KEYS.LOG_FILTER_NORMAL,
logFilterNormal.checked ? "1" : "0",
);
localStorage.setItem(
STORAGE_KEYS.LOG_FILTER_WARNING,
logFilterWarning.checked ? "1" : "0",
);
localStorage.setItem(
STORAGE_KEYS.LOG_FILTER_TX,
logFilterTx.checked ? "1" : "0",
);
localStorage.setItem(
STORAGE_KEYS.LOG_FILTER_RX,
logFilterRx.checked ? "1" : "0",
);
this.applyLogFilter();
});
},
);
this.applyLogFilter();
}
/**
* Apply log filter visibility
*/
applyLogFilter() {
const logFilterNormal = $("#logFilterNormal");
const logFilterWarning = $("#logFilterWarning");
const logFilterTx = $("#logFilterTx");
const logFilterRx = $("#logFilterRx");
const logEl = $("#log");
if (!logEl) return;
// Apply filter to all log lines
logEl.querySelectorAll(".line").forEach((line) => {
const classes = line.classList;
let visible = true;
if (classes.contains("warn") && !logFilterWarning?.checked) {
visible = false;
} else if (classes.contains("tx") && !logFilterTx?.checked) {
visible = false;
} else if (classes.contains("rx") && !logFilterRx?.checked) {
visible = false;
} else if (
!classes.contains("warn") &&
!classes.contains("tx") &&
!classes.contains("rx") &&
!logFilterNormal?.checked
) {
visible = false;
}
line.style.display = visible ? "" : "none";
});
}
/**
* Initialize query buttons
*/
initializeQueryButtons() {
document.querySelectorAll("[data-q]").forEach((btn) => {
btn.addEventListener("click", async () => {
if (!this.connection.isConnected()) {
this.logger.log("Not connected", LOG_CLASSES.WARNING);
return;
}
const tag = btn.getAttribute("data-q");
await this.connection.send(buildCommand(tag, "", 8));
});
});
// Get All button - executes all query commands in sequence
$("#btnGetAll")?.addEventListener("click", async () => {
if (!this.connection.isConnected()) {