// manager_wifi_wifis.js (function (window, $) { 'use strict'; const R = window.ITCRemote; if (!R) { console.error('ITCRemote no está definido. Asegúrate de cargar manager_wifi.js antes.'); return; } // --------------------------------------------------------- // ESTADO // --------------------------------------------------------- let wifiList = []; // [{ ssid, password }] let selectedIndex = -1; // Redes escaneadas let scannedWifiList = []; // [{ ssid, rssi, chan, enc, bssid, idx }] // --------------------------------------------------------- // HELPERS UI // --------------------------------------------------------- function maskPassword(pwd) { if (!pwd) return ''; if (pwd.length <= 4) return '•'.repeat(pwd.length); return pwd.slice(0, 2) + '•'.repeat(Math.max(0, pwd.length - 4)) + pwd.slice(-2); } function wifiSignalLevel(rssi) { // RSSI son negativos: -30 muy fuerte, -90 muy débil if (rssi >= -50) return 'strong'; // Muy buena if (rssi >= -70) return 'medium'; // Aceptable return 'weak'; // Débil } function sortByRssiDesc(nets) { // Ordenar de mayor a menor (menos negativo primero) return (nets || []).slice().sort((a, b) => (b.rssi ?? -999) - (a.rssi ?? -999)); } function refreshWifiTable() { const $tbody = $('#tblWifisBody'); $tbody.empty(); wifiList.forEach((item, idx) => { const $tr = $( '' + '' + '' + '' + (idx + 1) + '' + '' ); $tr.find('.ssid').text(item.ssid); $tr.find('.pwd').text(maskPassword(item.password)); if (idx === selectedIndex) $tr.addClass('selected'); $tbody.append($tr); }); const hasSel = selectedIndex >= 0 && selectedIndex < wifiList.length; $('#btnWifiUp').prop('disabled', !hasSel || selectedIndex === 0); $('#btnWifiDown').prop('disabled', !hasSel || selectedIndex === wifiList.length - 1); $('#btnWifiDel').prop('disabled', !hasSel); } function renderScannedWifiList() { const $list = $('#lstScannedWifi'); const $empty = $('#scanWifiEmpty'); if (!$list.length) return; // Borra los items anteriores (pero no el mensaje vacío) $list.find('li.scan-item').remove(); console.log('🔎 scannedWifiList:', scannedWifiList); if (!Array.isArray(scannedWifiList) || !scannedWifiList.length) { $empty.show(); return; } $empty.hide(); scannedWifiList.forEach(function (net, idx) { const level = wifiSignalLevel(net.rssi || -100); const ssid = net.ssid || ''; const rssi = (net.rssi !== undefined) ? net.rssi : '?'; const chan = (net.chan !== undefined) ? net.chan : '?'; const $li = $('
  • ') .addClass('list-group-item d-flex align-items-center justify-content-between scan-item') .attr('data-idx', idx); const $info = $('
    ') .addClass('me-2 flex-grow-1 text-truncate'); const $ssidLine = $('
    ') .addClass('fw-semibold text-truncate') .text(ssid); const $detailLine = $('
    ') .addClass('small text-muted') .text('RSSI ' + rssi + ' dBm · Canal ' + chan); $info.append($ssidLine, $detailLine); const $iconWrapper = $('
    ') .addClass('ms-2 wifi-badge wifi-signal-icon wifi-signal-' + level) .append($('').addClass('fas fa-wifi')); $li.append($info, $iconWrapper); $list.append($li); }); } function selectRowByIndex(idx) { selectedIndex = (idx >= 0 && idx < wifiList.length) ? idx : -1; refreshWifiTable(); } function setWifiBusy(on, label) { const $card = $('#wifiCard'); if (on) { if (!$card.hasClass('busy')) { $card.addClass('busy').attr('aria-busy','true'); const $ov = $('
    '); if (label) $ov.find('.spinner_wifi').attr('title', label); $card.append($ov); } } else { $card.removeClass('busy').attr('aria-busy','false'); $card.find('.busy-overlay').remove(); } const disabled = !!on; $('#btnWifiUp, #btnWifiDown, #btnWifiDel, #btnSendWifi, #btnLoadWifis') .prop('disabled', disabled); $('#wifiSsid, #wifiPass, #togglePass').prop('disabled', disabled); } function startReloadCountdown(sec = 30, labelBase = 'Reiniciando dispositivo...') { var left = sec; // Mostrar mensaje claro en la alerta var $alert = $('#wifiAlert'); if ($alert.length) { $alert .removeClass('d-none alert-info alert-success alert-warning alert-danger') .addClass('alert-success') .text(labelBase + ' (' + left + 's)'); } // Activar overlay y spinner setWifiBusy(true, labelBase + ' (' + left + 's)'); // Intervalo cada 1s var iv = setInterval(function() { left = left - 1; // Actualizar alerta if ($alert.length) { $alert.text(labelBase + ' (' + left + 's)'); } // Actualizar spinner (tooltip) var $ov = $('#wifiCard .busy-overlay .spinner_wifi'); if ($ov.length) { $ov.attr('title', labelBase + ' (' + left + 's)'); } // Fin y recarga if (left <= 0) { clearInterval(iv); window.location.reload(); } }, 1000); } // --------------------------------------------------------- // LECTURA DE CREDENCIALES DESDE EL DISPOSITIVO (API) // --------------------------------------------------------- async function requestCredentialsAndFill(timeoutMs = 8000) { const hash = R.getCurrentHash(); if (!hash) { throw new Error('No hay hash del dispositivo para leer credenciales WiFi.'); } // Aquí usamos el mismo comando que antes por COM, pero enviado por API: // getjson#credentials const resp = await R.sendDeviceCommand({ hash, request: 'getjson#credentials', timeoutMs }); // resp puede ser: // 1) un array directo: [ {ssid,password}, ... ] // 2) un objeto con una propiedad: { creds: [...]} / { wifis: [...] } / etc. let arr = []; if (Array.isArray(resp)) { arr = resp; } else if (Array.isArray(resp.creds)) { arr = resp.creds; } else if (Array.isArray(resp.credentials)) { arr = resp.credentials; } else if (Array.isArray(resp.wifis)) { arr = resp.wifis; } else { console.warn('Respuesta de credenciales desconocida:', resp); throw new Error('Respuesta de credenciales WiFi no válida.'); } wifiList = arr.map(x => ({ ssid: String(x?.ssid || '').trim(), password: String(x?.password || '') })); selectedIndex = wifiList.length ? 0 : -1; refreshWifiTable(); return wifiList; } // --------------------------------------------------------- // ESCANEO DE REDES WiFi (API) // --------------------------------------------------------- async function requestWifiScanAndFill(timeoutMs = 20000) { const hash = R.getCurrentHash(); if (!hash) { throw new Error('No hay hash del dispositivo para escanear WiFi.'); } // Igual que antes por COM, pero por API: // wifiscan const resp = await R.sendDeviceCommand({ hash, request: 'wifiscan', timeoutMs }); // Esperamos algo tipo: { count: n, nets: [...] } let nets = []; if (Array.isArray(resp.nets)) { nets = resp.nets; } else if (Array.isArray(resp.wifis)) { nets = resp.wifis; } else { console.warn('Respuesta de escaneo WiFi desconocida:', resp); throw new Error('Respuesta de escaneo WiFi no válida.'); } scannedWifiList = sortByRssiDesc(nets); renderScannedWifiList(); return scannedWifiList; } // --------------------------------------------------------- // ENVÍO DE CREDENCIALES WiFi AL DISPOSITIVO (API) // --------------------------------------------------------- function buildCredsFromState() { if (Array.isArray(wifiList) && wifiList.length) { return wifiList .filter(w => (w?.ssid || '').trim() !== '') .map(w => ({ ssid: String(w.ssid).trim(), password: String(w.password || '') })); } return []; } function buildCredsFromTable() { const arr = []; $('#tblWifisBody tr').each(function () { const idx = parseInt($(this).attr('data-index'), 10); const ssid = ($(this).find('.ssid').text() || '').trim(); const realPwd = (Array.isArray(wifiList) && wifiList[idx] && typeof wifiList[idx].password === 'string') ? wifiList[idx].password : ($(this).find('.pwd').text() || '').trim(); if (ssid) arr.push({ ssid, password: realPwd }); }); return arr; } async function sendWifiCredentialsToDevice() { const hash = R.getCurrentHash(); if (!hash) { throw new Error('No hay hash del dispositivo para guardar WiFi.'); } hideWifiAlert(); let creds = buildCredsFromState(); if (!creds.length) creds = buildCredsFromTable(); if (!creds.length) { showWifiAlert('No hay redes WiFi para guardar.', 'warning'); return false; } const jsonStr = JSON.stringify(creds); const cmd = 'setjson#credentials#' + jsonStr; console.log('📦 WiFi JSON length:', jsonStr.length); console.log('📦 WiFi JSON preview:', jsonStr.slice(0, 120) + (jsonStr.length > 120 ? '…' : '')); console.log('📤 CMD (request):', cmd.slice(0, 200) + (cmd.length > 200 ? '…' : '')); // Enviamos el comando completo como REQUEST por API const resp = await R.sendDeviceCommand({ hash, request: cmd, timeoutMs: 8000 }); console.log('✅ Respuesta dispositivo (guardar WiFi):', resp); // Opcional: si el firmware devuelve algo tipo {result:1,connected:0|1} if (resp && typeof resp === 'object' && 'result' in resp) { if (resp.result === 1) { if (resp.connected === 1) { showWifiAlert('WiFi guardadas y conexión iniciada con la red principal. El dispositivo se reiniciará en 30 segundos.', 'success'); } else { showWifiAlert('WiFi guardadas correctamente. El dispositivo se reiniciará en 30 segundos.', 'success'); } return true; } else { showWifiAlert('El dispositivo devolvió un error al guardar las WiFi.', 'danger'); return false; } } return true; } // --------------------------------------------------------- // EVENTOS UI // --------------------------------------------------------- // Click en fila de la tabla $(document).on('click', '#tblWifisBody tr', function (e) { e.preventDefault(); const idx = parseInt($(this).attr('data-index'), 10); selectRowByIndex(idx); }); // Mostrar/ocultar contraseña del formulario $('#togglePass').on('click', function () { const $pass = $('#wifiPass'); const isPwd = $pass.attr('type') === 'password'; $pass.attr('type', isPwd ? 'text' : 'password'); $(this).find('i').toggleClass('fa-eye fa-eye-slash'); }); // Alta de WiFi (añadir al final) $('#frmWifi').on('submit', function (e) { e.preventDefault(); const ssid = ($('#wifiSsid').val() || '').trim(); const password = ($('#wifiPass').val() || '').trim(); if (!ssid) { $('#wifiSsid').focus(); return; } const idxExist = wifiList.findIndex(w => w.ssid === ssid); if (idxExist >= 0) { wifiList.splice(idxExist, 1); } wifiList.push({ ssid, password }); $('#wifiSsid').val(''); $('#wifiPass').val(''); selectRowByIndex(wifiList.length - 1); }); // Subir fila seleccionada $('#btnWifiUp').on('click', function () { if (selectedIndex <= 0) return; const tmp = wifiList[selectedIndex]; wifiList[selectedIndex] = wifiList[selectedIndex - 1]; wifiList[selectedIndex - 1] = tmp; selectRowByIndex(selectedIndex - 1); }); // Bajar fila seleccionada $('#btnWifiDown').on('click', function () { if (selectedIndex < 0 || selectedIndex >= wifiList.length - 1) return; const tmp = wifiList[selectedIndex]; wifiList[selectedIndex] = wifiList[selectedIndex + 1]; wifiList[selectedIndex + 1] = tmp; selectRowByIndex(selectedIndex + 1); }); // Eliminar fila seleccionada $('#btnWifiDel').on('click', function () { if (selectedIndex < 0) return; wifiList.splice(selectedIndex, 1); const newSel = Math.min(selectedIndex, wifiList.length - 1); selectRowByIndex(newSel); }); // Cargar credenciales desde el dispositivo $(document).on('click', '#btnLoadWifis', async function (e) { e.preventDefault(); hideWifiAlert(); setWifiBusy(true, 'Cargando WiFis...'); const $btn = $(this).prop('disabled', true); try { await requestCredentialsAndFill(8000); } catch (err) { console.warn('⚠️ Error cargando WiFis:', err?.message || err); showWifiAlert('No se pudieron cargar las WiFis: ' + (err.message || err), 'danger'); } finally { $btn.prop('disabled', false); setWifiBusy(false); } }); // Escanear redes WiFi $(document).on('click', '#btnScanWifi', async function (e) { e.preventDefault(); const $btn = $(this); const $icon = $btn.find('i'); $btn.prop('disabled', true); $icon.addClass('fa-spin'); try { await requestWifiScanAndFill(20000); } catch (err) { console.warn('⚠️ Error en wifiscan:', err); showWifiAlert('No se pudieron leer las redes WiFi: ' + (err.message || err), 'danger'); } finally { $btn.prop('disabled', false); $icon.removeClass('fa-spin'); } }); // Clic en una red escaneada → copiar SSID al input $(document).on('click', '#lstScannedWifi li.scan-item', function () { const idx = parseInt($(this).attr('data-idx'), 10); const net = scannedWifiList[idx]; if (!net) return; $('#wifiSsid').val(net.ssid || ''); $('#wifiPass').focus(); }); // Guardar credenciales WiFi en el dispositivo $(document).on('click', '#btnSendWifi', async function (e) { e.preventDefault(); setWifiBusy(true, 'Guardando WiFis...'); const $btn = $(this).prop('disabled', true); let ok = false; try { const saved = await sendWifiCredentialsToDevice(); if (!saved) { return; // ok sigue siendo false } ok = true; // Si todo fue bien, cuenta atrás y recarga startReloadCountdown(30, 'Guardado OK. Reiniciando dispositivo...'); // NO hace falta return; aunque lo pongas, finally igual se ejecuta } catch (err) { console.warn(err); showWifiAlert('No se pudieron guardar las WiFis: ' + (err.message || err), 'danger'); } finally { // Solo si NO ha ido bien: quitamos overlay y reactivamos botón if (!ok) { setWifiBusy(false); $btn.prop('disabled', false); } } }); // Inicialización $(function () { refreshWifiTable(); }); function showWifiAlert(message, type = 'info') { const $alert = $('#wifiAlert'); if (!$alert.length) return; $alert .removeClass('d-none alert-info alert-success alert-warning alert-danger') .addClass('alert-' + type) .text(message); } function hideWifiAlert() { const $alert = $('#wifiAlert'); if (!$alert.length) return; $alert .addClass('d-none') .text(''); } })(window, jQuery);