// ====================================================================== // 🧠 ITCUsbAgent Manager + Sniffer JSON (ESP32 "info") // ====================================================================== let __lastDeviceInfo = null; // --- Utilidad UI mínima (opcional) --- function fillDeviceInfoUI(d){ $('#hash2').text(d.hash ?? '—'); $('#pcb2').text(d.pcb ?? '—'); $('#fw2').text(d.fw ?? '—'); $('#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 ?? '—'); $('#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 ?? '—'); $('#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 ?? '—'); $('#hash').text(d.hash ?? '—'); $('#skin').text((d.skin!=null && d.skin!=='') ? d.skin : 'itc'); 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'); } } // ====================================================================== // 🧩 FUNCIONES DE PARSEO JSON // ====================================================================== function findEndOfFirstJson(s){ const start = s.indexOf('{'); if (start < 0) return -1; let depth = 0, inStr = false, esc = false; for (let i = start; i < s.length; i++){ const ch = s[i]; if (inStr){ if (esc){ esc = false; continue; } if (ch === '\\'){ esc = true; continue; } if (ch === '"'){ inStr = false; continue; } }else{ if (ch === '"'){ inStr = true; continue; } if (ch === '{') depth++; else if (ch === '}'){ depth--; if (depth === 0) return i; } } } return -1; } function extractFirstCompleteJson(s){ const end = findEndOfFirstJson(s); if (end < 0) return null; const start = s.indexOf('{'); if (start < 0 || start > end) return null; try { return JSON.parse(s.slice(start, end+1)); } catch { return null; } } // 👉 Registramos nuestro parser como helper global para waitJsonFromLog window.extractFirstCompleteJsonAny = window.extractFirstCompleteJsonAny || extractFirstCompleteJson; // ====================================================================== // 🧩 FUNCIÓN PRINCIPAL PARA PEDIR Y LEER INFO (SIN LOG) // ====================================================================== async function requestInfoAndFill(timeoutMs = 5000){ const waitJsonFromLog = window.waitJsonFromLog; if (typeof waitJsonFromLog !== 'function') { throw new Error('waitJsonFromLog no disponible (manager.js no inicializado)'); } // Opcional: si quieres aislar cada lectura, puedes limpiar el buffer if (typeof window.__sniffBuf === 'string') { window.__sniffBuf = ''; } // Preparamos la promesa: nos vale "cualquier" JSON que llegue const waitJson = waitJsonFromLog( (o) => o && typeof o === 'object', // predicado: cualquier objeto JSON timeoutMs ); // Envía "info" por serie usando el mismo mecanismo que el monitor const $tx = $('#tx'); const prev = $tx.val(); $tx.val('info'); try { sendLine(); } finally { $tx.val(prev); } // Esperamos a que llegue el JSON por el COM (sin mirar el log) const obj = await waitJson; __lastDeviceInfo = obj; fillDeviceInfoUI(obj); return obj; } // ====================================================================== // 🧩 BOTÓN REFRESCAR INFO // ====================================================================== let infoRetryTimer = null; // referencia al intervalo let flagYaInfo = false; let intentosRefreshInfo = 0; $(document).on('click', '#btnRefreshInfo', async function() { flagYaInfo = false; //Si doy al botón // función que ejecuta la lectura y verifica si hash ya está informado async function tryUpdateInfo() { if (flagYaInfo) return false; try { const data = await requestInfoAndFill(6000); const hashVal = ($('#hash2').text() || '').trim(); if (hashVal && hashVal !== '—') { intentosRefreshInfo = 0; console.log('✅ Info completa, hash informado:', hashVal); $('#btnDeviceCfg').prop('disabled', false); flagYaInfo = true; try { clearInterval(infoRetryTimer); infoRetryTimer = null; console.log('🟢 Timer detenido: ya hay hash válido'); } catch(e) { console.warn('⚠️', e?.message || e); } $('#btnLoadWifis').click(); //Refresco Wifis const appVal = ($('#app').text() || '').trim(); const sSSID = ($('#wfid').text() || '').trim(); fnLoadFirmApp(appVal, sSSID); //Cargar Versiones Actualizacion refreshCalibrationInfo(); } else { intentosRefreshInfo = intentosRefreshInfo + 1; console.log('⚠️ Hash aún no informado, se repetirá...'); if (intentosRefreshInfo > 3) window.location.reload(); } } catch (e) { console.warn('⚠️', e?.message || e); } } // comprueba si el hash está vacío antes de iniciar const initialHash = ($('#hash2').text() || '').trim(); if (initialHash === '—' || initialHash === '') { console.log('🔁 Hash vacío: iniciando reintentos cada 20s...'); // ejecuta inmediatamente la primera vez await tryUpdateInfo(); // programa los reintentos cada 20 segundos infoRetryTimer = setInterval(tryUpdateInfo, 20000); } else { console.log('ℹ️ Hash ya informado, solo una lectura.'); await tryUpdateInfo(); // solo una vez } }); // === Enviar comando por serie usando tu propia función sendLine() === function sendViaAgent(line){ const $tx = $('#tx'); const prev = $tx.val(); $tx.val(line); try { sendLine(); // usa tu infraestructura del Agent if (typeof log === 'function') log('➡️ ' + line + '\n'); return true; } catch(e){ console.warn(e); return false; } finally { $tx.val(prev); } } // === Gestionar checkbox del modal === $(document).on('change', '#chkFactoryAck', function(){ $('#btnFactoryConfirm').prop('disabled', !this.checked); }); // === Acción principal de confirmación === $(document).on('click', '#btnFactoryConfirm', async function(){ const $btn = $(this); const $spin = $btn.find('.spinner-border'); // Estado “ocupado” $btn.prop('disabled', true); $('#btnFactoryCancel').prop('disabled', true); $spin.removeClass('d-none'); try { // 1️⃣ Enviar el comando "factory" const ok = sendViaAgent('factory'); if (!ok) throw new Error('No se pudo enviar el comando por serie'); // 2️⃣ Cerrar modal y avisar $('#factoryModal').modal('hide'); if (typeof log === 'function') { log('🛠 Restablecimiento de fábrica ordenado. El dispositivo se reiniciará.\n'); log('🔁 La página se recargará automáticamente en 10 segundos...\n'); } // 3️⃣ Esperar 10 s y recargar la página setTimeout(() => { window.location.reload(); }, 10000); } catch(err) { alert('Error: ' + (err?.message || err)); } finally { // Reset UI por si se reabre el modal después $spin.addClass('d-none'); $('#chkFactoryAck').prop('checked', false); $('#btnFactoryCancel').prop('disabled', false); $btn.prop('disabled', true); } }); function fillDeviceCfgFormFromInfo() { // Preferimos el último JSON recibido; si no, tiramos de la UI 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'); } // helper para saber si la info del tab está ya "bien cargada" function hasValidDeviceInfo() { const hashVal = ($('#hash2').text() || '').trim(); const pcbVal = ($('#pcb').text() || '').trim(); return ( hashVal && hashVal !== '—' && pcbVal && pcbVal !== '—' ); } // Cuando se abre la modal de configuración de dispositivo $('#deviceCfgModal').on('show.bs.modal', async function () { // 1) deshabilitar botón guardar mientras no tengamos datos buenos const $btnSave = $('#btnDeviceCfgSave'); $btnSave.prop('disabled', true); try { // 2) Si NO hay info válida en la pestaña, la pedimos ahora if (!hasValidDeviceInfo()) { try { await requestInfoAndFill(6000); // vuelve a llamar a "info" } catch (e) { console.warn('No se pudo obtener info antes de abrir el modal:', e?.message || e); } } // 3) Rellenar campos a partir de la info disponible (DOM + __lastDeviceInfo) fillDeviceCfgFormFromInfo(); // 4) Si ya tenemos info decente, habilitamos el botón if (hasValidDeviceInfo()) { $btnSave.prop('disabled', false); } } catch (e) { console.warn(e); // si hay error, lo dejamos deshabilitado } }); // Opcional: al cerrar el modal, limpiar estados si quieres $('#deviceCfgModal').on('hidden.bs.modal', function () { // si quieres limpiar campos: // $('#frmDeviceCfg')[0].reset(); }); // Guardar configuración de dispositivo $(document).on('click', '#btnDeviceCfgSave', function () { const $btn = $(this); $btn.prop('disabled', true); // evitar doble click // 1) Leer valores del formulario const pcb = $('#cfgPcb').val(); // "4" const app = $('#cfgApp').val(); // "angle" | "laser" const ver = $('#cfgVer').val(); // "1".."5" const lang = $('#cfgLang').val(); // "es" | "en" const skin = $('#cfgSkin').val(); // "" (itc) | "rema" const debug = parseInt($('#cfgDebug').val(), 10) || 0; // 0 ó 1 // 2) Construir el objeto de configuración const cfg = { pcb: pcb, app: app, ver: ver, lang: lang, skin: skin, // "" = itc por defecto en el firmware debug: debug }; // 3) Enviar por el Agent: setcfg# const line = 'setcfg#' + JSON.stringify(cfg); sendViaAgent(line); // Opcional: log visual en el monitor if (typeof log === 'function') { log('⚙️ Enviando configuración: ' + line + '\n'); } // 4) NO cerrar el modal, solo cambiar el texto del botón $btn.html( '' + 'Reiniciando...' ); // 5) Recargar la página a los 2 segundos setTimeout(function () { window.location.reload(); }, 2000); });