1082 lines
43 KiB
JavaScript
1082 lines
43 KiB
JavaScript
// ==========================================
|
|
// 1. GLOBAL STATE & CONFIGURATION
|
|
// ==========================================
|
|
let deviceSettings = { keyMapMain: {} };
|
|
let originalSettings = null;
|
|
|
|
// Debug flags
|
|
const DEBUG_FORCE_CALC_MODE_ON_CONNECT = false;
|
|
const DEBUG_LOGGING = false;
|
|
|
|
function getDeepDelta(orig, current) {
|
|
if (!orig) return current;
|
|
let delta = {};
|
|
for (let key in current) {
|
|
if (typeof current[key] === 'object' && current[key] !== null && !Array.isArray(current[key])) {
|
|
let subDelta = getDeepDelta(orig[key] || {}, current[key]);
|
|
if (Object.keys(subDelta).length > 0) {
|
|
delta[key] = subDelta;
|
|
}
|
|
} else {
|
|
if (JSON.stringify(orig[key]) !== JSON.stringify(current[key])) {
|
|
delta[key] = current[key];
|
|
}
|
|
}
|
|
}
|
|
return delta;
|
|
}
|
|
let isKeyboardEnabled = true;
|
|
let isPaintingMode = false;
|
|
let currentPaintColor = '#00ff00';
|
|
let currentEditingKeyChar = null;
|
|
const EVENT = {};
|
|
const ESP32_IP = "192.168.3.1";
|
|
|
|
// ==========================================
|
|
// 2. DOM ELEMENTS
|
|
// ==========================================
|
|
const DOM = {};
|
|
function cacheDOM() {
|
|
DOM.displayContainer = document.getElementById('display');
|
|
DOM.tglButton = document.getElementById('key-tgl');
|
|
DOM.kbToggle = document.getElementById('kb-enable-toggle');
|
|
DOM.kbModeSelect = document.getElementById('kb-mode-select');
|
|
DOM.kbLockToggle = document.getElementById('kb-lock-toggle');
|
|
DOM.deviceContainer = document.querySelector('.device-container');
|
|
|
|
// Terminal
|
|
DOM.termInput = document.getElementById('term-input');
|
|
DOM.termSendBtn = document.getElementById('term-send-btn');
|
|
DOM.termOutput = document.getElementById('term-output');
|
|
DOM.wsStatus = document.getElementById('ws-status');
|
|
|
|
// Context Menu
|
|
DOM.ctxMenu = document.getElementById('key-context-menu');
|
|
DOM.ctxLabel = document.getElementById('ctx-key-label');
|
|
DOM.ctxSelect = document.getElementById('ctx-hid-select');
|
|
DOM.ctxSelectMod = document.getElementById('ctx-hid-select-mod');
|
|
DOM.ctxCalcSelect = document.getElementById('ctx-calc-select');
|
|
DOM.ctxCalcModSelect = document.getElementById('ctx-calc-mod-select');
|
|
DOM.ctxSaveBtn = document.getElementById('ctx-save-btn');
|
|
|
|
// Global Settings
|
|
DOM.screenBrInput = document.getElementById('screen-brightness');
|
|
DOM.screenBrVal = document.getElementById('val-screen-br');
|
|
DOM.keyBrInput = document.getElementById('keyboard-brightness');
|
|
DOM.keyBrVal = document.getElementById('val-keypad-br');
|
|
DOM.globalSaveBtn = document.getElementById('global-save-btn');
|
|
DOM.globalRevertBtn = document.getElementById('global-revert-btn');
|
|
|
|
// System Config
|
|
DOM.sysMdns = document.getElementById('sys-mdns');
|
|
DOM.sysUsbMfg = document.getElementById('sys-usb-mfg');
|
|
DOM.sysUsbProd = document.getElementById('sys-usb-prod');
|
|
DOM.sysUsbSerial = document.getElementById('sys-usb-serial');
|
|
DOM.sysUsbRndis = document.getElementById('sys-usb-rndis');
|
|
DOM.sysUsbHid = document.getElementById('sys-usb-hid');
|
|
DOM.sysBleName = document.getElementById('sys-ble-name');
|
|
DOM.sysMacAddr = document.getElementById('sys-mac-addr');
|
|
DOM.sysDeviceIp = document.getElementById('sys-device-ip');
|
|
|
|
// Lighting Studio
|
|
DOM.rgbModeSelect = document.getElementById('rgb-mode-select');
|
|
DOM.rgbSpeedInput = document.getElementById('rgb-speed');
|
|
DOM.rgbSpeedVal = document.getElementById('val-rgb-speed');
|
|
DOM.panelSpeed = document.getElementById('panel-speed');
|
|
DOM.rgbGlobalColorInput = document.getElementById('rgb-global-color');
|
|
DOM.rgbPaintColorInput = document.getElementById('rgb-paint-color');
|
|
DOM.panelGlobalColor = document.getElementById('panel-global-color');
|
|
DOM.panelPaintMode = document.getElementById('panel-paint-mode');
|
|
}
|
|
|
|
// ==========================================
|
|
// 3. KEY MAPPING DEFINITIONS
|
|
// ==========================================
|
|
class VirtualKey {
|
|
constructor(id, char, codes, ledIndex) {
|
|
this.id = id;
|
|
this.char = char;
|
|
this.codes = codes;
|
|
this.ledIndex = ledIndex;
|
|
// element is assigned in cacheDOM
|
|
}
|
|
}
|
|
|
|
const keyMapping = {
|
|
'key-0': new VirtualKey('key-0', '0', ['Numpad0'], 10),
|
|
'key-1': new VirtualKey('key-1', '1', ['Numpad1'], 15),
|
|
'key-2': new VirtualKey('key-2', '2', ['Numpad2'], 11),
|
|
'key-3': new VirtualKey('key-3', '3', ['Numpad3'], 6),
|
|
'key-4': new VirtualKey('key-4', '4', ['Numpad4'], 16),
|
|
'key-5': new VirtualKey('key-5', '5', ['Numpad5'], 12),
|
|
'key-6': new VirtualKey('key-6', '6', ['Numpad6'], 7),
|
|
'key-7': new VirtualKey('key-7', '7', ['Numpad7'], 17),
|
|
'key-8': new VirtualKey('key-8', '8', ['Numpad8'], 13),
|
|
'key-9': new VirtualKey('key-9', '9', ['Numpad9'], 8),
|
|
'key-dot': new VirtualKey('key-dot', '.', ['NumpadDecimal'], 5),
|
|
'key-enter': new VirtualKey('key-enter', 'e', ['NumpadEnter'], 0),
|
|
'key-plus': new VirtualKey('key-plus', '+', ['NumpadAdd'], 1),
|
|
'key-minus': new VirtualKey('key-minus', '-', ['NumpadSubtract'], 4),
|
|
'key-star': new VirtualKey('key-star', '*', ['NumpadMultiply'], 9),
|
|
'key-slash': new VirtualKey('key-slash', '/', ['NumpadDivide'], 14),
|
|
'key-numlock': new VirtualKey('key-numlock', 'n', ['NumLock'], 18),
|
|
'key-red': new VirtualKey('key-red', 'r', [], 2),
|
|
'key-org': new VirtualKey('key-org', 'o', [], 3),
|
|
};
|
|
|
|
// ==========================================
|
|
// 4. WEBSOCKET LOGIC
|
|
// ==========================================
|
|
let ws;
|
|
|
|
function initWebSocket() {
|
|
const wsHost = (location.hostname === "127.0.0.1" || location.hostname === "localhost")
|
|
? ESP32_IP
|
|
: location.host;
|
|
|
|
ws = new WebSocket(`ws://${wsHost}/ws`);
|
|
ws.binaryType = "arraybuffer";
|
|
|
|
ws.onopen = () => {
|
|
console.log('WebSocket connection established.');
|
|
updateWSStatus(true);
|
|
ws.send(MessagePack.encode({
|
|
event: EVENT.EVT_REQUEST_FULL_STATE
|
|
}));
|
|
|
|
if (DEBUG_FORCE_CALC_MODE_ON_CONNECT) {
|
|
setTimeout(() => {
|
|
if (DOM.kbModeSelect) DOM.kbModeSelect.value = "3";
|
|
if (DOM.kbLockToggle) DOM.kbLockToggle.checked = true;
|
|
|
|
ws.send(MessagePack.encode({
|
|
event: EVENT.EVT_SET_MCU_KEYBOARD_MODE,
|
|
mode: 3,
|
|
lock: true
|
|
}));
|
|
|
|
console.log("DEBUG: Forced Calculator mode & lock on connect.");
|
|
}, 100);
|
|
}
|
|
};
|
|
|
|
ws.onclose = () => {
|
|
console.log('WebSocket connection closed. Reconnecting in 1s...');
|
|
updateWSStatus(false);
|
|
setTimeout(initWebSocket, 1000);
|
|
};
|
|
|
|
ws.onerror = (error) => {
|
|
console.error('WebSocket error:', error);
|
|
updateWSStatus(false);
|
|
// onerror will usually trigger onclose immediately after, so no need to call reconnect here
|
|
};
|
|
|
|
ws.onmessage = (event) => {
|
|
if (event.data instanceof ArrayBuffer) {
|
|
const data = MessagePack.decode(new Uint8Array(event.data));
|
|
if (DEBUG_LOGGING) console.log(data);
|
|
|
|
switch(data.event) {
|
|
case EVENT.EVT_TERMINAL_MCU_TO_WEB: {
|
|
const textToDisplay = data.textToDisplay;
|
|
appendTerminalLine('rx', textToDisplay);
|
|
break;
|
|
}
|
|
case EVENT.EVT_KEY_DOWN_MCU: {
|
|
const keyChar = data.keyChar;
|
|
const keyObj = Object.values(keyMapping).find(k => k.char === keyChar);
|
|
if(keyObj) {
|
|
keyObj.element.classList.add("pressed");
|
|
}
|
|
break;
|
|
}
|
|
case EVENT.EVT_KEY_UP_MCU: {
|
|
const keyChar = data.keyChar;
|
|
const keyObj = Object.values(keyMapping).find(k => k.char === keyChar);
|
|
if(keyObj) {
|
|
keyObj.element.classList.remove("pressed");
|
|
}
|
|
break;
|
|
}
|
|
case EVENT.EVT_DISPLAY_INDEX:
|
|
if (data.index !== undefined && data.value !== undefined) {
|
|
setDigitSegments(data.index, data.value);
|
|
}
|
|
break;
|
|
case EVENT.EVT_DISPLAY_ALL:
|
|
if (data.values && data.values.length) {
|
|
for (let i = 0; i < data.values.length && i < 12; i++) {
|
|
setDigitSegments(i, data.values[i]);
|
|
}
|
|
}
|
|
break;
|
|
case EVENT.EVT_DISPLAY_CLEAR:
|
|
clearDisplay();
|
|
break;
|
|
case EVENT.EVT_RGB_INDEX:
|
|
if (data.index !== undefined && data.r !== undefined && data.g !== undefined && data.b !== undefined) {
|
|
setKeyLED(data.index, `rgb(${data.r}, ${data.g}, ${data.b})`);
|
|
}
|
|
break;
|
|
case EVENT.EVT_RGB_ALL:
|
|
if (data.colors && data.colors.length) {
|
|
for (let i = 0; i < data.colors.length / 3; i++) {
|
|
const r = data.colors[i * 3];
|
|
const g = data.colors[i * 3 + 1];
|
|
const b = data.colors[i * 3 + 2];
|
|
setKeyLED(i, `rgb(${r}, ${g}, ${b})`);
|
|
}
|
|
}
|
|
break;
|
|
case EVENT.EVT_RGB_CLEAR:
|
|
Object.values(keyMapping).forEach(keyObj => {
|
|
if (keyObj.element) {
|
|
keyObj.element.style.removeProperty('--led-color');
|
|
keyObj.element.classList.remove('led-on');
|
|
}
|
|
});
|
|
break;
|
|
case EVENT.EVT_UPDATE_SETTINGS_FROM_MCU:
|
|
reloadSettings();
|
|
break;
|
|
case EVENT.EVT_SET_WEB_KEYBOARD_MODE:
|
|
if (DOM.kbModeSelect) {
|
|
DOM.kbModeSelect.value = data.mode;
|
|
}
|
|
if (DOM.kbLockToggle) {
|
|
DOM.kbLockToggle.checked = data.lock;
|
|
}
|
|
break;
|
|
case EVENT.EVT_SYSTEM_STATUS:
|
|
if (document.getElementById('diag-usb')) {
|
|
const usbEl = document.getElementById('diag-usb');
|
|
usbEl.innerText = data.usb ? "Ready" : "Not Ready";
|
|
usbEl.style.color = data.usb ? "#4CAF50" : "#ff4d4d";
|
|
|
|
const bleEl = document.getElementById('diag-ble');
|
|
bleEl.innerText = data.ble ? "Connected" : "Disconnected";
|
|
bleEl.style.color = data.ble ? "#4CAF50" : "#ff4d4d";
|
|
|
|
document.getElementById('diag-batt').innerText = data.battery + "%";
|
|
|
|
const chgEl = document.getElementById('diag-charging');
|
|
chgEl.innerText = data.charging ? "Charging" : "Discharging";
|
|
chgEl.style.color = data.charging ? "#FFC107" : "#fff";
|
|
|
|
let heapText = (data.heap / 1024).toFixed(1) + " KB";
|
|
if(data.totalHeap && data.totalHeap > 0) {
|
|
let pct = Math.round((data.heap / data.totalHeap) * 100);
|
|
heapText += ` (${pct}%)`;
|
|
}
|
|
document.getElementById('diag-heap').innerText = heapText;
|
|
|
|
const totalSecs = Math.floor(data.uptime / 1000);
|
|
const hrs = Math.floor(totalSecs / 3600);
|
|
const mins = Math.floor((totalSecs % 3600) / 60);
|
|
const secs = totalSecs % 60;
|
|
document.getElementById('diag-uptime').innerText =
|
|
`${hrs.toString().padStart(2, '0')}:${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
|
|
|
|
if (data.pollingRate !== undefined) {
|
|
document.getElementById('diag-polling').innerText = data.pollingRate + " Hz";
|
|
}
|
|
if (data.cpuLoad !== undefined) {
|
|
document.getElementById('diag-cpu').innerText = data.cpuLoad.toFixed(1) + " %";
|
|
}
|
|
}
|
|
break;
|
|
case EVENT.EVT_OS_LED_STATE:
|
|
const leds = data.leds;
|
|
const numLockLed = document.getElementById("led-numlock");
|
|
if (numLockLed) {
|
|
if (leds & 0x01) { // Bit 0 is NumLock
|
|
numLockLed.style.background = "#4ade80";
|
|
numLockLed.style.boxShadow = "0 0 8px #4ade80, inset 0 1px 3px rgba(0,0,0,0.5)";
|
|
} else {
|
|
numLockLed.style.background = "#444";
|
|
numLockLed.style.boxShadow = "inset 0 1px 3px rgba(0,0,0,0.5)";
|
|
}
|
|
}
|
|
break;
|
|
default:
|
|
console.warn(`unknown event type sent ${data.event}`);
|
|
}
|
|
}
|
|
};
|
|
}
|
|
|
|
function updateWSStatus(connected) {
|
|
if (!DOM.wsStatus) return;
|
|
if (connected) {
|
|
DOM.wsStatus.innerText = "Connected";
|
|
DOM.wsStatus.className = "ws-status connected";
|
|
} else {
|
|
DOM.wsStatus.innerText = "Disconnected";
|
|
DOM.wsStatus.className = "ws-status disconnected";
|
|
}
|
|
}
|
|
|
|
// ==========================================
|
|
// 5. HARDWARE EMULATION LOGIC
|
|
// ==========================================
|
|
function initDisplay() {
|
|
if (!DOM.displayContainer) return;
|
|
|
|
const svgTemplate = `
|
|
<polygon class="seg a" points="14,4 46,4 50,8 42,16 18,16 10,8" />
|
|
<polygon class="seg b" points="52,10 56,14 56,44 52,48 44,40 44,18" />
|
|
<polygon class="seg c" points="52,52 56,56 56,86 52,90 44,82 44,60" />
|
|
<polygon class="seg d" points="14,96 46,96 50,92 42,84 18,84 10,92" />
|
|
<polygon class="seg e" points="4,56 8,52 16,60 16,82 8,90 4,86" />
|
|
<polygon class="seg f" points="4,14 8,10 16,18 16,40 8,48 4,44" />
|
|
<polygon class="seg g" points="10,50 18,42 42,42 50,50 42,58 18,58" />
|
|
<circle class="seg dp" cx="64" cy="92" r="6" />
|
|
`;
|
|
|
|
for (let i = 11; i >= 0; i--) {
|
|
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
|
|
svg.setAttribute('class', 'digit');
|
|
svg.setAttribute('id', `digit-${i}`);
|
|
svg.setAttribute('viewBox', '0 0 75 100');
|
|
svg.innerHTML = svgTemplate;
|
|
DOM.displayContainer.appendChild(svg);
|
|
}
|
|
}
|
|
|
|
function setDigitSegments(index, hexValue) {
|
|
const digitElement = document.getElementById(`digit-${index}`);
|
|
if (!digitElement) return;
|
|
|
|
const segments = ['g', 'f', 'e', 'd', 'c', 'b', 'a', 'dp'];
|
|
segments.forEach((segClass, bitIndex) => {
|
|
const segElement = digitElement.querySelector(`.seg.${segClass}`);
|
|
if (segElement) {
|
|
if ((hexValue & (1 << bitIndex)) !== 0) {
|
|
segElement.classList.add('lit');
|
|
} else {
|
|
segElement.classList.remove('lit');
|
|
}
|
|
}
|
|
});
|
|
}
|
|
|
|
function clearDisplay() {
|
|
for (let i = 0; i < 12; i++) {
|
|
setDigitSegments(i, 0x00);
|
|
}
|
|
}
|
|
|
|
function setToggleState(isOn) {
|
|
if (!DOM.tglButton) return;
|
|
if (isOn) {
|
|
DOM.tglButton.classList.add('active');
|
|
} else {
|
|
DOM.tglButton.classList.remove('active');
|
|
}
|
|
}
|
|
|
|
function getToggleState() {
|
|
if (!DOM.tglButton) return false;
|
|
return DOM.tglButton.classList.contains('active');
|
|
}
|
|
|
|
function setKeyLED(ledIndex, ledColor) {
|
|
const keyObj = Object.values(keyMapping).find(k => k.ledIndex === ledIndex);
|
|
if (keyObj && keyObj.element) {
|
|
keyObj.element.style.setProperty('--led-color', ledColor);
|
|
keyObj.element.classList.add('led-on');
|
|
}
|
|
}
|
|
|
|
// ==========================================
|
|
// 6. KEYBOARD & INPUT HANDLERS
|
|
// ==========================================
|
|
function handleKeyboardPress(event) {
|
|
if (!isKeyboardEnabled || event.target.tagName === 'INPUT') return;
|
|
|
|
const keyObj = Object.values(keyMapping).find(k => k.codes.includes(event.code));
|
|
if (keyObj) {
|
|
keyObj.element.classList.add('pressed');
|
|
handleKeyPressDown(keyObj.char);
|
|
}
|
|
}
|
|
|
|
function handleKeyboardRelease(event) {
|
|
if (!isKeyboardEnabled || event.target.tagName === 'INPUT') return;
|
|
|
|
const keyObj = Object.values(keyMapping).find(k => k.codes.includes(event.code));
|
|
if (keyObj) {
|
|
keyObj.element.classList.remove('pressed');
|
|
handleKeyPressUp(keyObj.char);
|
|
}
|
|
}
|
|
|
|
function handleVirtualKeyDown(event) {
|
|
if (event.button !== undefined && event.button !== 0) return; // Only process left clicks
|
|
const keyId = event.currentTarget.id;
|
|
const keyObj = keyMapping[keyId];
|
|
if (!keyObj) return;
|
|
|
|
// Visual feedback
|
|
keyObj.element.classList.add('pressed');
|
|
|
|
if (isPaintingMode) {
|
|
if (keyObj.ledIndex !== undefined && deviceSettings.rgbModes && deviceSettings.rgbModes["4"]) {
|
|
const hexColor = currentPaintColor.replace('#', '');
|
|
deviceSettings.rgbModes["4"].colors[keyObj.ledIndex] = hexColor;
|
|
|
|
// Visually show the configured color on the UI
|
|
keyObj.element.style.setProperty('--paint-color', currentPaintColor);
|
|
if (DEBUG_LOGGING) console.log(`Configured key ${keyObj.char} (LED ${keyObj.ledIndex}) to color #${hexColor}`);
|
|
}
|
|
} else {
|
|
handleKeyPressDown(keyObj.char);
|
|
}
|
|
}
|
|
|
|
function handleVirtualKeyUp(event) {
|
|
if (event.button !== undefined && event.button !== 0) return; // Only process left clicks
|
|
const keyId = event.currentTarget.id;
|
|
const keyObj = keyMapping[keyId];
|
|
if (!keyObj) return;
|
|
|
|
// Prevent duplicate events if mouseup and mouseleave both fire
|
|
if (!keyObj.element.classList.contains('pressed')) return;
|
|
|
|
// Remove visual feedback
|
|
keyObj.element.classList.remove('pressed');
|
|
|
|
if (!isPaintingMode) {
|
|
handleKeyPressUp(keyObj.char);
|
|
}
|
|
}
|
|
|
|
function handleKeyPressDown(char) {
|
|
const payload = {
|
|
event: EVENT.EVT_KEY_DOWN_WEB,
|
|
char: char.charCodeAt(0),
|
|
modifier: getToggleState()
|
|
}
|
|
if(ws && ws.readyState === WebSocket.OPEN) {
|
|
ws.send(MessagePack.encode(payload));
|
|
}
|
|
}
|
|
|
|
function handleKeyPressUp(char) {
|
|
const payload = {
|
|
event: EVENT.EVT_KEY_UP_WEB,
|
|
char: char.charCodeAt(0)
|
|
}
|
|
if (ws && ws.readyState === WebSocket.OPEN) {
|
|
ws.send(MessagePack.encode(payload));
|
|
}
|
|
}
|
|
|
|
function handleContextMenu(event, button) {
|
|
event.preventDefault();
|
|
|
|
const keyObj = Object.values(keyMapping).find(k => k.id === button.id);
|
|
if (!keyObj || !keyObj.char) return;
|
|
|
|
currentEditingKeyChar = keyObj.char;
|
|
DOM.ctxLabel.innerText = currentEditingKeyChar;
|
|
|
|
DOM.ctxSelect.value = (deviceSettings.keyMapMain && deviceSettings.keyMapMain[currentEditingKeyChar])
|
|
? deviceSettings.keyMapMain[currentEditingKeyChar] : "0x00";
|
|
|
|
DOM.ctxSelectMod.value = (deviceSettings.keyMapModifier && deviceSettings.keyMapModifier[currentEditingKeyChar])
|
|
? deviceSettings.keyMapModifier[currentEditingKeyChar] : "0x00";
|
|
|
|
DOM.ctxCalcSelect.value = (deviceSettings.keyMapCalcMain && deviceSettings.keyMapCalcMain[currentEditingKeyChar])
|
|
? deviceSettings.keyMapCalcMain[currentEditingKeyChar] : "0x00";
|
|
|
|
DOM.ctxCalcModSelect.value = (deviceSettings.keyMapCalcModifier && deviceSettings.keyMapCalcModifier[currentEditingKeyChar])
|
|
? deviceSettings.keyMapCalcModifier[currentEditingKeyChar] : "0x00";
|
|
|
|
DOM.ctxMenu.classList.remove('hidden');
|
|
|
|
let x = event.pageX;
|
|
let y = event.pageY;
|
|
const viewportBottom = window.scrollY + window.innerHeight;
|
|
const viewportRight = window.scrollX + window.innerWidth;
|
|
|
|
if (x + DOM.ctxMenu.offsetWidth > viewportRight) {
|
|
x = viewportRight - DOM.ctxMenu.offsetWidth - 10;
|
|
}
|
|
if (y + DOM.ctxMenu.offsetHeight > viewportBottom) {
|
|
y = viewportBottom - DOM.ctxMenu.offsetHeight - 10;
|
|
}
|
|
|
|
DOM.ctxMenu.style.left = `${x}px`;
|
|
DOM.ctxMenu.style.top = `${y}px`;
|
|
}
|
|
|
|
// ==========================================
|
|
// 7. SETTINGS & LIGHTING LOGIC
|
|
// ==========================================
|
|
function setRGBMode(modeId) {
|
|
if (!deviceSettings.rgbModes) return;
|
|
modeId = parseInt(modeId);
|
|
deviceSettings.selectedRGBMode = modeId;
|
|
|
|
if (DOM.rgbModeSelect) DOM.rgbModeSelect.value = modeId;
|
|
|
|
if (DOM.panelSpeed) {
|
|
DOM.panelSpeed.classList.toggle('hidden', modeId >= 2);
|
|
if (deviceSettings.rgbModes[modeId]) {
|
|
const globalSpeed = deviceSettings.rgbSpeed !== undefined ? deviceSettings.rgbSpeed : 100;
|
|
if (DOM.rgbSpeedInput) DOM.rgbSpeedInput.value = globalSpeed;
|
|
if (DOM.rgbSpeedVal) DOM.rgbSpeedVal.innerText = globalSpeed;
|
|
}
|
|
}
|
|
|
|
if (DOM.panelGlobalColor) DOM.panelGlobalColor.classList.toggle('hidden', modeId !== 3);
|
|
if (DOM.panelPaintMode) DOM.panelPaintMode.classList.toggle('hidden', modeId !== 4);
|
|
|
|
isPaintingMode = (modeId === 4);
|
|
if (DOM.deviceContainer) {
|
|
if (isPaintingMode) {
|
|
DOM.deviceContainer.classList.add('is-painting');
|
|
DOM.deviceContainer.classList.add('show-paint-colors');
|
|
} else {
|
|
DOM.deviceContainer.classList.remove('is-painting');
|
|
DOM.deviceContainer.classList.remove('show-paint-colors');
|
|
}
|
|
}
|
|
}
|
|
|
|
function reloadSettings() {
|
|
fetch('settings.json')
|
|
.then(response => {
|
|
if (!response.ok) throw new Error("Network response was not ok");
|
|
return response.json();
|
|
})
|
|
.then(data => {
|
|
deviceSettings = data;
|
|
originalSettings = JSON.parse(JSON.stringify(deviceSettings));
|
|
|
|
if (deviceSettings.screenBrightness !== undefined && DOM.screenBrInput) {
|
|
DOM.screenBrInput.value = deviceSettings.screenBrightness;
|
|
DOM.screenBrVal.innerText = deviceSettings.screenBrightness;
|
|
}
|
|
|
|
if (deviceSettings.mdnsName !== undefined && DOM.sysMdns) DOM.sysMdns.value = deviceSettings.mdnsName;
|
|
if (deviceSettings.usbManufacturer !== undefined && DOM.sysUsbMfg) DOM.sysUsbMfg.value = deviceSettings.usbManufacturer;
|
|
if (deviceSettings.usbProduct !== undefined && DOM.sysUsbProd) DOM.sysUsbProd.value = deviceSettings.usbProduct;
|
|
if (deviceSettings.usbSerialNumber !== undefined && DOM.sysUsbSerial) DOM.sysUsbSerial.value = deviceSettings.usbSerialNumber;
|
|
if (deviceSettings.usbRndisInterface !== undefined && DOM.sysUsbRndis) DOM.sysUsbRndis.value = deviceSettings.usbRndisInterface;
|
|
if (deviceSettings.usbHidInterface !== undefined && DOM.sysUsbHid) DOM.sysUsbHid.value = deviceSettings.usbHidInterface;
|
|
if (deviceSettings.bleName !== undefined && DOM.sysBleName) DOM.sysBleName.value = deviceSettings.bleName;
|
|
if (deviceSettings.macAddress !== undefined && DOM.sysMacAddr) DOM.sysMacAddr.value = deviceSettings.macAddress;
|
|
if (deviceSettings.deviceIP !== undefined && DOM.sysDeviceIp) DOM.sysDeviceIp.value = deviceSettings.deviceIP;
|
|
if (deviceSettings.keyboardBrightness !== undefined && DOM.keyBrInput) {
|
|
DOM.keyBrInput.value = deviceSettings.keyboardBrightness;
|
|
DOM.keyBrVal.innerText = deviceSettings.keyboardBrightness;
|
|
}
|
|
|
|
if (DOM.rgbModeSelect && deviceSettings.rgbModes) {
|
|
DOM.rgbModeSelect.innerHTML = '';
|
|
for (const [id, modeObj] of Object.entries(deviceSettings.rgbModes)) {
|
|
const option = document.createElement('option');
|
|
option.value = id;
|
|
option.textContent = modeObj.name;
|
|
DOM.rgbModeSelect.appendChild(option);
|
|
}
|
|
}
|
|
|
|
if (deviceSettings.selectedRGBMode !== undefined) {
|
|
setRGBMode(deviceSettings.selectedRGBMode);
|
|
}
|
|
|
|
if (deviceSettings.rgbModes && deviceSettings.rgbModes["3"] && deviceSettings.rgbModes["3"].color) {
|
|
DOM.rgbGlobalColorInput.value = '#' + deviceSettings.rgbModes["3"].color;
|
|
}
|
|
|
|
if (deviceSettings.rgbModes && deviceSettings.rgbModes["4"] && deviceSettings.rgbModes["4"].colors) {
|
|
deviceSettings.rgbModes["4"].colors.forEach((hexColor, index) => {
|
|
const keyObj = Object.values(keyMapping).find(k => k.ledIndex === index);
|
|
if (keyObj && keyObj.element) {
|
|
keyObj.element.style.setProperty('--paint-color', '#' + hexColor);
|
|
}
|
|
});
|
|
}
|
|
|
|
updateMacroDropdowns();
|
|
console.log("Settings loaded from littleFS:", deviceSettings);
|
|
})
|
|
.catch(err => console.warn("Failed to load settings:", err));
|
|
}
|
|
|
|
// ==========================================
|
|
// 8. TERMINAL LOGIC
|
|
// ==========================================
|
|
let terminalHistory = [];
|
|
let terminalHistoryIndex = -1;
|
|
let currentTermInput = "";
|
|
|
|
function appendTerminalLine(type, message) {
|
|
if (!DOM.termOutput) return;
|
|
|
|
const line = document.createElement('div');
|
|
line.className = `term-line ${type}`;
|
|
|
|
const prefix = document.createElement('span');
|
|
prefix.className = 'prefix';
|
|
prefix.innerText = type === 'tx' ? 'TX:' : 'RX:';
|
|
|
|
line.appendChild(prefix);
|
|
line.appendChild(document.createTextNode(` ${message}`));
|
|
|
|
DOM.termOutput.appendChild(line);
|
|
DOM.termOutput.scrollTop = DOM.termOutput.scrollHeight;
|
|
}
|
|
|
|
function handleTerminalSend() {
|
|
const message = DOM.termInput.value.trim();
|
|
if (message === '') return;
|
|
|
|
if (terminalHistory.length === 0 || terminalHistory[terminalHistory.length - 1] !== message) {
|
|
terminalHistory.push(message);
|
|
}
|
|
terminalHistoryIndex = terminalHistory.length;
|
|
|
|
if (message.toLowerCase() === 'clear' || message.toLowerCase() === 'cls') {
|
|
DOM.termOutput.innerHTML = '';
|
|
DOM.termInput.value = '';
|
|
return;
|
|
}
|
|
|
|
appendTerminalLine('tx', message);
|
|
DOM.termInput.value = '';
|
|
|
|
const payload = {
|
|
event: EVENT.EVT_TERMINAL_WEB_TO_MCU,
|
|
textToDisplay: message
|
|
}
|
|
if(ws && ws.readyState === WebSocket.OPEN) {
|
|
ws.send(MessagePack.encode(payload));
|
|
}
|
|
}
|
|
|
|
// ==========================================
|
|
// 9. INITIALIZATION & EVENT ATTACHMENT
|
|
// ==========================================
|
|
function attachEventListeners() {
|
|
// TGL Button
|
|
if (DOM.tglButton) {
|
|
DOM.tglButton.addEventListener('click', () => {
|
|
DOM.tglButton.classList.toggle('active');
|
|
});
|
|
}
|
|
|
|
// Keyboard Layout Keys (Mouse Events)
|
|
Object.values(keyMapping).forEach((keyObj) => {
|
|
keyObj.element = document.getElementById(keyObj.id);
|
|
if (keyObj.element) {
|
|
// Using mousedown/mouseup to emulate physical hardware pressing
|
|
keyObj.element.addEventListener('mousedown', handleVirtualKeyDown);
|
|
keyObj.element.addEventListener('mouseup', handleVirtualKeyUp);
|
|
// Catch edge case where mouse leaves the button before releasing
|
|
keyObj.element.addEventListener('mouseleave', handleVirtualKeyUp);
|
|
}
|
|
});
|
|
|
|
// Global Key Listeners
|
|
document.addEventListener('keydown', handleKeyboardPress);
|
|
document.addEventListener('keyup', handleKeyboardRelease);
|
|
|
|
// PC Keyboard Toggle
|
|
if (DOM.kbToggle) {
|
|
DOM.kbToggle.addEventListener('change', (e) => {
|
|
isKeyboardEnabled = e.target.checked;
|
|
});
|
|
}
|
|
|
|
const btnResetBle = document.getElementById('btn-reset-ble');
|
|
if (btnResetBle) {
|
|
btnResetBle.addEventListener('click', (e) => {
|
|
e.preventDefault();
|
|
if (confirm("This will erase all Bluetooth pairings from the keyboard and restart it. You will also need to 'Forget' the keyboard on your PC/Phone. Proceed?")) {
|
|
const toSend = { event: EVENT.EVT_CLEAR_BLE_BONDS };
|
|
ws.send(JSON.stringify(toSend));
|
|
}
|
|
});
|
|
}
|
|
|
|
const sendKeyboardMode = () => {
|
|
if (!DOM.kbModeSelect || !DOM.kbLockToggle) return;
|
|
const payload = {
|
|
event: EVENT.EVT_SET_MCU_KEYBOARD_MODE,
|
|
mode: parseInt(DOM.kbModeSelect.value),
|
|
lock: DOM.kbLockToggle.checked
|
|
};
|
|
if (ws && ws.readyState === WebSocket.OPEN) {
|
|
ws.send(MessagePack.encode(payload));
|
|
}
|
|
};
|
|
|
|
if (DOM.kbModeSelect) {
|
|
DOM.kbModeSelect.addEventListener('change', () => {
|
|
if (DOM.kbLockToggle) {
|
|
DOM.kbLockToggle.checked = true;
|
|
}
|
|
sendKeyboardMode();
|
|
});
|
|
}
|
|
|
|
if (DOM.kbLockToggle) {
|
|
DOM.kbLockToggle.addEventListener('change', sendKeyboardMode);
|
|
}
|
|
|
|
// Context Menu
|
|
document.querySelectorAll('.key').forEach(button => {
|
|
button.addEventListener('contextmenu', (e) => handleContextMenu(e, button));
|
|
});
|
|
|
|
document.addEventListener('click', (event) => {
|
|
if (DOM.ctxMenu && !DOM.ctxMenu.contains(event.target)) {
|
|
DOM.ctxMenu.classList.add('hidden');
|
|
}
|
|
});
|
|
|
|
if (DOM.ctxSaveBtn) {
|
|
DOM.ctxSaveBtn.addEventListener('click', () => {
|
|
if (currentEditingKeyChar) {
|
|
if (!deviceSettings.keyMapMain) deviceSettings.keyMapMain = {};
|
|
if (!deviceSettings.keyMapModifier) deviceSettings.keyMapModifier = {};
|
|
if (!deviceSettings.keyMapCalcMain) deviceSettings.keyMapCalcMain = {};
|
|
if (!deviceSettings.keyMapCalcModifier) deviceSettings.keyMapCalcModifier = {};
|
|
deviceSettings.keyMapMain[currentEditingKeyChar] = DOM.ctxSelect.value;
|
|
deviceSettings.keyMapModifier[currentEditingKeyChar] = DOM.ctxSelectMod.value;
|
|
deviceSettings.keyMapCalcMain[currentEditingKeyChar] = DOM.ctxCalcSelect.value;
|
|
deviceSettings.keyMapCalcModifier[currentEditingKeyChar] = DOM.ctxCalcModSelect.value;
|
|
}
|
|
DOM.ctxMenu.classList.add('hidden');
|
|
});
|
|
}
|
|
|
|
// Terminal
|
|
if (DOM.termSendBtn && DOM.termInput) {
|
|
DOM.termSendBtn.addEventListener('click', handleTerminalSend);
|
|
DOM.termInput.addEventListener('keydown', (e) => {
|
|
if (e.key === 'Enter') {
|
|
handleTerminalSend();
|
|
} else if (e.key === 'ArrowUp') {
|
|
e.preventDefault();
|
|
if (terminalHistoryIndex > 0) {
|
|
if (terminalHistoryIndex === terminalHistory.length) {
|
|
currentTermInput = DOM.termInput.value;
|
|
}
|
|
terminalHistoryIndex--;
|
|
DOM.termInput.value = terminalHistory[terminalHistoryIndex];
|
|
}
|
|
} else if (e.key === 'ArrowDown') {
|
|
e.preventDefault();
|
|
if (terminalHistoryIndex < terminalHistory.length - 1) {
|
|
terminalHistoryIndex++;
|
|
DOM.termInput.value = terminalHistory[terminalHistoryIndex];
|
|
} else if (terminalHistoryIndex === terminalHistory.length - 1) {
|
|
terminalHistoryIndex++;
|
|
DOM.termInput.value = currentTermInput;
|
|
}
|
|
}
|
|
});
|
|
}
|
|
|
|
// Settings Inputs
|
|
// System Modal Logic
|
|
const sysBtnOpen = document.getElementById('btn-open-sys-config');
|
|
const sysModalOverlay = document.getElementById('sys-modal-overlay');
|
|
const sysBtnClose = document.getElementById('sys-modal-close');
|
|
const sysBtnApply = document.getElementById('sys-modal-apply');
|
|
|
|
if (sysBtnOpen && sysModalOverlay) {
|
|
sysBtnOpen.addEventListener('click', () => {
|
|
sysModalOverlay.classList.remove('hidden');
|
|
});
|
|
}
|
|
|
|
const closeSysModal = () => {
|
|
if (sysModalOverlay) sysModalOverlay.classList.add('hidden');
|
|
};
|
|
|
|
if (sysBtnClose) sysBtnClose.addEventListener('click', closeSysModal);
|
|
if (sysModalOverlay) sysModalOverlay.addEventListener('click', (e) => {
|
|
if (e.target === sysModalOverlay) closeSysModal();
|
|
});
|
|
|
|
if (sysBtnApply) {
|
|
sysBtnApply.addEventListener('click', () => {
|
|
closeSysModal();
|
|
if (DOM.globalSaveBtn) DOM.globalSaveBtn.click();
|
|
});
|
|
}
|
|
|
|
if (DOM.screenBrInput) {
|
|
DOM.screenBrInput.addEventListener('input', (e) => {
|
|
DOM.screenBrVal.innerText = e.target.value;
|
|
deviceSettings.screenBrightness = parseInt(e.target.value);
|
|
});
|
|
}
|
|
|
|
if (DOM.keyBrInput) {
|
|
DOM.keyBrInput.addEventListener('input', (e) => {
|
|
DOM.keyBrVal.innerText = e.target.value;
|
|
deviceSettings.keyboardBrightness = parseInt(e.target.value);
|
|
});
|
|
}
|
|
|
|
if (DOM.globalSaveBtn) {
|
|
DOM.globalSaveBtn.addEventListener('click', () => {
|
|
const ipRegex = /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/;
|
|
if (DOM.sysDeviceIp && !ipRegex.test(DOM.sysDeviceIp.value)) {
|
|
alert("Invalid IP Address format. Please correct it before saving.");
|
|
return;
|
|
}
|
|
const macRegex = /^[0-9A-Fa-f]{12}$/;
|
|
if (DOM.sysMacAddr && !macRegex.test(DOM.sysMacAddr.value)) {
|
|
alert("Invalid MAC Address format. Must be 12 hex characters without colons.");
|
|
return;
|
|
}
|
|
|
|
const delta = getDeepDelta(originalSettings, deviceSettings);
|
|
if (Object.keys(delta).length === 0) {
|
|
console.log("No changes to save.");
|
|
return;
|
|
}
|
|
|
|
const requiresRestart = ['mdnsName', 'usbManufacturer', 'usbProduct', 'usbSerialNumber', 'usbRndisInterface', 'usbHidInterface', 'bleName', 'macAddress', 'deviceIP'].some(key => key in delta);
|
|
|
|
console.log("Preparing to send config delta to ESP32...", delta);
|
|
const payload = {
|
|
event: EVENT.EVT_UPDATE_SETTINGS_FROM_WEB,
|
|
settings: delta
|
|
};
|
|
if(ws && ws.readyState === WebSocket.OPEN) {
|
|
ws.send(MessagePack.encode(payload));
|
|
originalSettings = JSON.parse(JSON.stringify(deviceSettings));
|
|
if (requiresRestart) {
|
|
alert("System Settings saved!\n\nPlease restart your ESP32 for the changes to apply.");
|
|
}
|
|
}
|
|
});
|
|
}
|
|
|
|
if (DOM.globalRevertBtn) {
|
|
DOM.globalRevertBtn.addEventListener('click', () => {
|
|
reloadSettings();
|
|
});
|
|
}
|
|
|
|
if (DOM.sysMdns) DOM.sysMdns.addEventListener('input', (e) => { deviceSettings.mdnsName = e.target.value; });
|
|
if (DOM.sysUsbMfg) DOM.sysUsbMfg.addEventListener('input', (e) => { deviceSettings.usbManufacturer = e.target.value; });
|
|
if (DOM.sysUsbProd) DOM.sysUsbProd.addEventListener('input', (e) => { deviceSettings.usbProduct = e.target.value; });
|
|
if (DOM.sysUsbSerial) DOM.sysUsbSerial.addEventListener('input', (e) => { deviceSettings.usbSerialNumber = e.target.value; });
|
|
if (DOM.sysUsbRndis) DOM.sysUsbRndis.addEventListener('input', (e) => { deviceSettings.usbRndisInterface = e.target.value; });
|
|
if (DOM.sysUsbHid) DOM.sysUsbHid.addEventListener('input', (e) => { deviceSettings.usbHidInterface = e.target.value; });
|
|
if (DOM.sysBleName) DOM.sysBleName.addEventListener('input', (e) => { deviceSettings.bleName = e.target.value; });
|
|
if (DOM.sysMacAddr) DOM.sysMacAddr.addEventListener('input', (e) => { deviceSettings.macAddress = e.target.value.toUpperCase(); });
|
|
if (DOM.sysDeviceIp) DOM.sysDeviceIp.addEventListener('input', (e) => { deviceSettings.deviceIP = e.target.value; });
|
|
|
|
// Lighting Studio
|
|
if (DOM.rgbModeSelect) {
|
|
DOM.rgbModeSelect.addEventListener('change', (e) => setRGBMode(e.target.value));
|
|
}
|
|
|
|
if (DOM.rgbSpeedInput) {
|
|
DOM.rgbSpeedInput.addEventListener('input', (e) => {
|
|
DOM.rgbSpeedVal.innerText = e.target.value;
|
|
if (deviceSettings) {
|
|
deviceSettings.rgbSpeed = parseInt(e.target.value);
|
|
queueSettingsUpdate();
|
|
}
|
|
});
|
|
}
|
|
|
|
if (DOM.rgbGlobalColorInput) {
|
|
DOM.rgbGlobalColorInput.addEventListener('input', (e) => {
|
|
if (!deviceSettings.rgbModes["3"]) deviceSettings.rgbModes["3"] = {};
|
|
deviceSettings.rgbModes["3"].color = e.target.value.replace('#', '');
|
|
});
|
|
}
|
|
|
|
if (DOM.rgbPaintColorInput) {
|
|
DOM.rgbPaintColorInput.addEventListener('input', (e) => {
|
|
currentPaintColor = e.target.value;
|
|
});
|
|
}
|
|
}
|
|
|
|
function fetchEventsAndInit() {
|
|
if (typeof HID_CODES !== 'undefined' && DOM.ctxSelect && DOM.ctxSelectMod) {
|
|
for (const [hexCode, name] of Object.entries(HID_CODES)) {
|
|
const option1 = document.createElement('option');
|
|
option1.value = hexCode;
|
|
option1.textContent = `${hexCode} - ${name}`;
|
|
DOM.ctxSelect.appendChild(option1);
|
|
|
|
const option2 = document.createElement('option');
|
|
option2.value = hexCode;
|
|
option2.textContent = `${hexCode} - ${name}`;
|
|
DOM.ctxSelectMod.appendChild(option2);
|
|
}
|
|
}
|
|
|
|
if (typeof CALC_CODES !== 'undefined' && DOM.ctxCalcSelect && DOM.ctxCalcModSelect) {
|
|
for (const [hexCode, obj] of Object.entries(CALC_CODES)) {
|
|
const option1 = document.createElement('option');
|
|
option1.value = hexCode;
|
|
option1.textContent = `${hexCode} - ${obj.name}`;
|
|
DOM.ctxCalcSelect.appendChild(option1);
|
|
|
|
const option2 = document.createElement('option');
|
|
option2.value = hexCode;
|
|
option2.textContent = `${hexCode} - ${obj.name}`;
|
|
DOM.ctxCalcModSelect.appendChild(option2);
|
|
}
|
|
}
|
|
|
|
return fetch('events.h')
|
|
.then(response => response.text())
|
|
.then(text => {
|
|
text.split('\n').forEach(line => {
|
|
const match = line.match(/#define\s+(\w+)\s+(\d+)/);
|
|
if (match) EVENT[match[1]] = parseInt(match[2]);
|
|
});
|
|
console.log("Loaded Macros:", EVENT);
|
|
})
|
|
.catch(err => console.warn("Failed to load events.h:", err));
|
|
}
|
|
|
|
async function init() {
|
|
cacheDOM();
|
|
initDisplay();
|
|
attachEventListeners();
|
|
await fetchEventsAndInit();
|
|
reloadSettings();
|
|
initWebSocket();
|
|
}
|
|
|
|
// Start everything when the DOM is fully loaded
|
|
document.addEventListener('DOMContentLoaded', init);function updateMacroDropdowns() {
|
|
if (!deviceSettings.macros) return;
|
|
|
|
const selects = [DOM.ctxSelect, DOM.ctxSelectMod, DOM.ctxCalcSelect, DOM.ctxCalcModSelect];
|
|
|
|
selects.forEach(select => {
|
|
if (!select) return;
|
|
|
|
Array.from(select.options).forEach(opt => {
|
|
const val = parseInt(opt.value, 16);
|
|
if (val >= 0xB0 && val <= 0xB7) {
|
|
opt.remove();
|
|
}
|
|
});
|
|
|
|
deviceSettings.macros.forEach((macro, i) => {
|
|
if (macro.active) {
|
|
const hexCode = "0x" + (0xB0 + i).toString(16).toUpperCase();
|
|
const name = macro.name || `Macro ${i + 1}`;
|
|
const option = document.createElement('option');
|
|
option.value = hexCode;
|
|
option.textContent = `${hexCode} - ${name}`;
|
|
select.appendChild(option);
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
// Debug utility to export current settings from the console
|
|
window.exportSettingsJSON = function() {
|
|
if (typeof deviceSettings === 'undefined' || !deviceSettings) {
|
|
console.error("No device settings available to export.");
|
|
return;
|
|
}
|
|
const jsonStr = JSON.stringify(deviceSettings, null, 2);
|
|
const blob = new Blob([jsonStr], { type: "application/json" });
|
|
const url = URL.createObjectURL(blob);
|
|
const a = document.createElement('a');
|
|
a.href = url;
|
|
a.download = 'settings.json';
|
|
document.body.appendChild(a);
|
|
a.click();
|
|
document.body.removeChild(a);
|
|
URL.revokeObjectURL(url);
|
|
console.log("Settings exported to settings.json. You can place this file in your /data folder.");
|
|
};
|
|
|
|
// OTA Upload Logic
|
|
document.addEventListener('DOMContentLoaded', () => {
|
|
const btnUpload = document.getElementById('btn-ota-upload');
|
|
const fileInput = document.getElementById('ota-file-input');
|
|
const typeSelect = document.getElementById('ota-type-select');
|
|
const progressContainer = document.getElementById('ota-progress-container');
|
|
const progressBar = document.getElementById('ota-progress-bar');
|
|
const statusText = document.getElementById('ota-status-text');
|
|
|
|
if (btnUpload && fileInput) {
|
|
btnUpload.addEventListener('click', () => {
|
|
const file = fileInput.files[0];
|
|
if (!file) {
|
|
alert("Please select a .bin file first.");
|
|
return;
|
|
}
|
|
|
|
const type = typeSelect.value;
|
|
|
|
if (type === 'fs') {
|
|
const confirmed = confirm("WARNING: Uploading a new LittleFS filesystem image will permanently delete all existing data on the device (settings, macros, etc.).\n\nAre you sure you want to proceed?");
|
|
if (!confirmed) return;
|
|
}
|
|
|
|
const url = `/update?type=${type}`;
|
|
|
|
btnUpload.disabled = true;
|
|
fileInput.disabled = true;
|
|
typeSelect.disabled = true;
|
|
progressContainer.style.display = 'block';
|
|
progressBar.style.width = '0%';
|
|
statusText.textContent = `Uploading ${type === 'fw' ? 'Firmware' : 'Filesystem'}... 0%`;
|
|
|
|
const xhr = new XMLHttpRequest();
|
|
xhr.open('POST', url, true);
|
|
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
|
|
|
|
xhr.upload.onprogress = (e) => {
|
|
if (e.lengthComputable) {
|
|
const percentComplete = Math.round((e.loaded / e.total) * 100);
|
|
progressBar.style.width = percentComplete + '%';
|
|
statusText.textContent = `Uploading... ${percentComplete}%`;
|
|
}
|
|
};
|
|
|
|
xhr.onload = () => {
|
|
if (xhr.status === 200) {
|
|
statusText.textContent = "Upload successful! Device is rebooting...";
|
|
progressBar.style.background = '#10b981'; // Green
|
|
setTimeout(() => {
|
|
window.location.reload();
|
|
}, 5000);
|
|
} else {
|
|
statusText.textContent = `Upload failed: ${xhr.responseText}`;
|
|
progressBar.style.background = '#ef4444'; // Red
|
|
btnUpload.disabled = false;
|
|
fileInput.disabled = false;
|
|
typeSelect.disabled = false;
|
|
}
|
|
};
|
|
|
|
xhr.onerror = () => {
|
|
statusText.textContent = "Upload failed! Network error.";
|
|
progressBar.style.background = '#ef4444';
|
|
btnUpload.disabled = false;
|
|
fileInput.disabled = false;
|
|
typeSelect.disabled = false;
|
|
};
|
|
|
|
xhr.send(file);
|
|
});
|
|
}
|
|
});
|