// manager_wifi_load.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; } try { window.termAppend = termAppend; if (window.ITCRemote) { window.ITCRemote.termAppend = termAppend; // opcional, por consistencia } } catch(e) {console.log('No terminal de Debug')} let __lastDeviceInfo = null; let infoRetryTimer = null; let flagYaInfo = false; let intentosRefreshInfo = 0; // --------------------------------------------------------- // Pintar JSON de info en la pestaña // --------------------------------------------------------- function fillDeviceInfoUI(d, hashOverride) { const hashToUse = hashOverride || d.hash; $('#hash2').text(hashToUse ?? '—'); $('#hash').text(hashToUse ?? '—'); $('#pcb2').text(d.pcb ?? '—'); $('#fw2').text(d.fw ?? d.firmware ?? '—'); $('#accX').text(d.accX?.toFixed?.(2) ?? d.accX ?? '—'); $('#accY').text(d.accY?.toFixed?.(2) ?? d.accY ?? '—'); $('#accZ').text(d.accZ?.toFixed?.(2) ?? d.accZ ?? '—'); $('#gyrX').text(d.gyrX?.toFixed?.(2) ?? d.gyrX ?? '—'); $('#gyrY').text(d.gyrY?.toFixed?.(2) ?? d.gyrY ?? '—'); $('#gyrZ').text(d.gyrZ?.toFixed?.(2) ?? d.gyrZ ?? '—'); $('#angleX').text(d.angleX?.toFixed?.(2) ?? d.angleX ?? '—'); $('#angleY').text(d.angleY?.toFixed?.(2) ?? d.angleY ?? '—'); $('#angleZ').text(d.angleZ?.toFixed?.(2) ?? d.angleZ ?? '—'); $('#magnX').text(d.magnX ?? '—'); $('#magnY').text(d.magnY ?? '—'); $('#magnZ').text(d.magnZ ?? '—'); $('#temp').text(d.temp != null ? Number(d.temp).toFixed(2) + ' °C' : '—'); $('#volt').html( d.volt != null //? calcBateria(Number(d.volt)) + '%
(' + Number(d.volt).toFixed(2) + ' V)' ? calcBateria(Number(d.volt)) + '%' : '—' ); $('#wfid').text(d.wfid ?? d.ssid ?? '—'); $('#ip').text(d.ip ?? '—'); $('#ippub').text(d.ippub ?? '—'); $('#mac').text(d.mac ?? '—'); $('#sigq').text(d.sigq != null ? d.sigq + ' dBm' : '—'); $('#subnet').text(d.subnet ?? '—'); $('#gateway').text(d.gateway ?? '—'); $('#dns1').text(d.dns1 ?? '—'); $('#dns2').text(d.dns2 ?? '—'); $('#id').text(d.id ?? '—'); $('#ref').text(d.ref ?? '—'); $('#pcb').text(d.pcb ?? '—'); $('#fw').text(d.fw ?? d.firmware ?? '—'); $('#app').text(d.app ?? '—'); $('#ac_client').text(d.ac_client ?? '—'); $('#ver').text(d.ver ?? '—'); $('#lang').text(d.lang ?? '—'); $('#email').text(d.email ?? '—'); $('#email_last').text(d.email_last ?? '—'); $('#toff').text(d.toff ?? '—'); $('#skin').text((d.skin != null && d.skin !== '') ? d.skin : 'itc'); // DEBUG MODE if (d.debug != null) { const isDebug = String(d.debug) === '1'; $('#mododebug') .text(isDebug ? 'ON' : 'OFF') .removeClass('text-danger text-success') .addClass(isDebug ? 'text-success' : 'text-danger'); const $debugNav = $('#debugTabNav'); const $debugPane = $('#tab-terminal'); if ($debugNav.length && $debugPane.length) { if (isDebug) { $debugNav.removeClass('d-none'); $debugPane.removeClass('d-none'); } else { // Si estaba activo, volver a Info if ($debugPane.hasClass('active')) { $('#info-tab').tab('show'); } $debugNav.addClass('d-none'); $debugPane.addClass('d-none'); } } window.termAppend('> Conectado a ' + hashToUse); window.termAppend('> [INFO] Recibido JSON: ' + JSON.stringify(d)); } else { $('#mododebug').text('—'); } if (d.app === 'angle') { $('#img-app').attr('src','../../img/angle/caja-angle2.jpg'); } else if (d.app === 'laser') { $('#img-app').attr('src','../../img/laser/mando-laser.jpg'); } // Guarda también en currentDevice R.setCurrentDevice(hashToUse, d); } // --------------------------------------------------------- // Pedir info por API y pintar // --------------------------------------------------------- async function requestInfoAndFillAPI(timeoutMs = 6000) { const hash = R.getCurrentHash(); if (!hash) throw new Error('No hay hash del dispositivo (currentDevice / hash2 / hash).'); try { const info = await R.sendDeviceCommand({ hash, request: 'info', timeoutMs }); __lastDeviceInfo = info; fillDeviceInfoUI(info, hash); // Validación positiva de hash if (info.hash) { $('#btnDeviceCfg').prop('disabled', false); if (typeof $('#btnLoadWifis').click === 'function') { $('#btnLoadWifis').click(); $('#btnLoadSync').click(); const appVal = ($('#app').text() || '').trim(); const sSSID = ($('#wfid').text() || '').trim(); fnLoadFirmApp(appVal, sSSID); //Cargar Versiones Actualizacion R.refreshCalibrationInfo(); } } else { // Respuesta rara/incompleta → lo trato como error lógico lanzarErrorConexion('La respuesta del dispositivo no contiene HASH válido.'); } return info; } catch (err) { // Aquí caes SIEMPRE en caso de timeout, error HTTP, JSON mal, etc. console.warn('❌ Error en requestInfoAndFillAPI:', err); lanzarErrorConexion(err.message || 'Error al comunicarse con el dispositivo.'); throw err; // por si el que llama quiere seguir sabiendo que falló } } function lanzarErrorConexion(msg) { // 1) Marcar desconectado a nivel de estado if (typeof R.setConnected === 'function') { R.setConnected(false); } // 2) Ocultar app y mostrar gate $('#appSection').addClass('hidden'); $('#gateSection').removeClass('hidden'); // 3) Mostrar error en el gate const $alert = $('#gateAlert'); if ($alert.length) { $alert .removeClass() .addClass('alert small mt-3 d-block alert-danger') .text('Se ha perdido la conexión con el dispositivo: ' + msg); } // 4) (Opcional) limpiar hash en el input para forzar nueva conexión const $hashInput = $('#hashInput'); if ($hashInput.length) { $hashInput.focus(); } } function mostrarMensajePantalla(msg, tipo) { // tipo: 'error', 'success', 'info' var $alert = $('#factoryAlert'); if ($alert.length) { var clases = 'alert small mt-3 d-block '; if (tipo === 'error') { clases = clases + 'alert-danger'; } else if (tipo === 'success') { clases = clases + 'alert-success'; } else { clases = clases + 'alert-info'; } $alert .removeClass() .addClass(clases) .text(msg); } else { // Por si aún no tienes el div en pantalla console.log('AVISO:', msg); } } function hasValidDeviceInfo() { const hashVal = ($('#hash2').text() || '').trim(); const pcbVal = ($('#pcb').text() || '').trim(); return ( hashVal && hashVal !== '—' && pcbVal && pcbVal !== '—' ); } // --------------------------------------------------------- // BOTÓN REFRESCAR INFO // --------------------------------------------------------- $(document).on('click', '#btnRefreshInfo', async function () { flagYaInfo = false; async function tryUpdateInfo() { if (flagYaInfo) return false; try { await requestInfoAndFillAPI(6000); const hashVal = ($('#hash2').text() || '').trim(); if (hashVal && hashVal !== '—') { intentosRefreshInfo = 0; console.log('✅ Info completa, hash informado:', hashVal); $('#btnDeviceCfg').prop('disabled', false); flagYaInfo = true; if (infoRetryTimer) { clearInterval(infoRetryTimer); infoRetryTimer = null; console.log('🟢 Timer detenido: ya hay hash válido'); } // enganchar resto de pestañas como hacías if (typeof $('#btnLoadWifis').click === 'function') { $('#btnLoadWifis').click(); $('#btnLoadSync').click(); const appVal = ($('#app').text() || '').trim(); const sSSID = ($('#wfid').text() || '').trim(); fnLoadFirmApp(appVal, sSSID); //Cargar Versiones Actualizacion R.refreshCalibrationInfo(); } const appVal = ($('#app').text() || '').trim(); const sSSID = ($('#wfid').text() || '').trim(); if (typeof window.fnLoadFirmApp === 'function') { window.fnLoadFirmApp(appVal, sSSID); } } else { intentosRefreshInfo++; console.log('⚠️ Hash aún no informado, se repetirá...'); if (intentosRefreshInfo > 3) window.location.reload(); } } catch (e) { console.warn('⚠️', e?.message || e); } } const initialHash = R.getCurrentHash(); if (!initialHash) { console.log('🔁 Hash vacío: iniciando reintentos cada 20s...'); await tryUpdateInfo(); infoRetryTimer = setInterval(tryUpdateInfo, 20000); } else { console.log('ℹ️ Hash ya informado, solo una lectura.'); await tryUpdateInfo(); } }); // --------------------------------------------------------- // FACTORY RESET POR API (REQUEST: "factory") // --------------------------------------------------------- $(document).on('change', '#chkFactoryAck', function () { $('#btnFactoryConfirm').prop('disabled', !this.checked); }); $(document).on('click', '#btnFactoryConfirm', async function () { const $btn = $(this); const $spin = $btn.find('.spinner-border'); const hash = R.getCurrentHash(); if (!hash) { mostrarMensajePantalla('No hay hash de dispositivo para enviar "factory".', 'warning'); return; } $btn.prop('disabled', true); $('#btnFactoryCancel').prop('disabled', true); $spin.removeClass('d-none'); try { await R.sendDeviceCommand({ hash, request: 'factory', timeoutMs: 10000 }); $('#factoryModal').modal('hide'); console.log('🛠 Restablecimiento de fábrica ordenado. El dispositivo se reiniciará.'); console.log('🔁 La página se recargará automáticamente en 10 segundos...'); setTimeout(() => { window.location.reload(); }, 10000); } catch (err) { mostrarMensajePantalla('Error: ' + (err?.message || err), 'error'); } finally { $spin.addClass('d-none'); $('#chkFactoryAck').prop('checked', false); $('#btnFactoryCancel').prop('disabled', false); $btn.prop('disabled', true); } }); // --------------------------------------------------------- // CONFIGURAR DISPOSITIVO (setcfg# por API) // --------------------------------------------------------- function fillDeviceCfgFormFromInfo() { const info = __lastDeviceInfo || {}; const pcbVal = (info.pcb != null ? String(info.pcb) : ($('#pcb').text() || '')).trim(); const appVal = (info.app != null ? String(info.app) : ($('#app').text() || '')).trim(); const verVal = (info.ver != null ? String(info.ver) : ($('#ver').text() || '')).trim(); const langVal = (info.lang != null ? String(info.lang) : ($('#lang').text() || '')).trim(); const skinVal = (info.skin != null ? String(info.skin) : ($('#skin').text() || '')).trim(); const debugVal = (info.debug != null ? String(info.debug) : '0'); $('#cfgPcb').val(pcbVal && pcbVal !== '—' ? pcbVal : ''); $('#cfgApp').val(appVal && appVal !== '—' ? appVal : ''); $('#cfgVer').val(verVal && verVal !== '—' ? verVal : ''); $('#cfgLang').val(langVal && langVal !== '—' ? langVal : ''); $('#cfgSkin').val(skinVal && skinVal !== '—' && skinVal !== 'itc' ? skinVal : ''); $('#cfgDebug').val(debugVal === '1' ? '1' : '0'); } $('#deviceCfgModal').on('show.bs.modal', async function () { const $btnSave = $('#btnDeviceCfgSave'); $btnSave.prop('disabled', true); try { if (!hasValidDeviceInfo()) { try { await requestInfoAndFillAPI(6000); } catch (e) { console.warn('No se pudo obtener info antes de abrir el modal:', e?.message || e); } } fillDeviceCfgFormFromInfo(); if (hasValidDeviceInfo()) { $btnSave.prop('disabled', false); } } catch (e) { console.warn(e); } }); $('#deviceCfgModal').on('hidden.bs.modal', function () { // opcional: limpiar // $('#frmDeviceCfg')[0].reset(); }); $(document).on('click', '#btnDeviceCfgSave', async function () { const $btn = $(this); $btn.prop('disabled', true); const hash = R.getCurrentHash(); if (!hash) { mostrarMensajePantalla('No hay hash del dispositivo (no se puede enviar setcfg).', 'warning'); $btn.prop('disabled', false); return; } const pcb = $('#cfgPcb').val(); const app = $('#cfgApp').val(); const ver = $('#cfgVer').val(); const lang = $('#cfgLang').val(); const skin = $('#cfgSkin').val(); const debug = parseInt($('#cfgDebug').val(), 10) || 0; const cfg = { pcb, app, ver, lang, skin, debug }; const line = 'setcfg#' + JSON.stringify(cfg); $btn.html( '' + 'Reiniciando...' ); try { await R.sendDeviceCommand({ hash, request: line, timeoutMs: 8000 }); console.log('⚙️ Configuración enviada por API:', line); setTimeout(function () { window.location.reload(); }, 2000); } catch (e) { mostrarMensajePantalla('Error enviando configuración: ' + (e?.message || e), 'error'); $btn.text('Guardar'); $btn.prop('disabled', false); } }); // --------------------------------------------------------- // Exportar helpers por si se quieren usar desde fuera // --------------------------------------------------------- R.fillDeviceInfoUI = fillDeviceInfoUI; R.requestInfoAndFill = requestInfoAndFillAPI; })(window, jQuery);