// manager_wifi_ota.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; } // Reutilizamos la configuración genérica const API_CFG = R.API_CFG; const sleep = R.sleep; // Timeouts específicos solo para OTA const OTA_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutos para toda la operación OTA const OTA_POLL_MS = 800; // intervalo entre polls de progreso // --------------------------------------------------------- // UI OTA: splash / status / progress // --------------------------------------------------------- function showSplash(show) { try { $('#btnOtaUrlFlash').prop('disabled', show); const s = document.getElementById('otaUrlSplash'); const f = document.getElementById('otaUrlForm'); if (s) s.style.display = show ? '' : 'none'; if (f) f.style.display = show ? 'none' : ''; } catch (e) {} } function setOtaUrlBusy(on) { $('#btnOtaUrlFlash,#otaVersion').prop('disabled', !!on); } /** tone: 'warning' | 'danger' | 'success' | 'info' | 'secondary' | ... */ function setOtaUrlStatus(text, tone) { if (!tone) tone = 'secondary'; const el = document.getElementById('otaUrlStatus'); if (!el) return; const allowed = { warning:1,danger:1,success:1,info:1, secondary:1,primary:1,light:1,dark:1 }; const t = allowed[tone] ? tone : 'secondary'; el.className = 'alert alert-' + t + ' small mb-3'; el.textContent = text; } function setOtaUrlProgress(pct) { const bar = document.getElementById('otaUrlProgress'); if (!bar) return; const v = Math.max(0, Math.min(100, Math.round(pct))); bar.style.width = v + '%'; bar.setAttribute('aria-valuenow', String(v)); bar.textContent = v + '%'; } // --------------------------------------------------------- // WRAPPERS OTA -> reutilizan apiInsertRequest / apiQueryResponse // --------------------------------------------------------- async function apiInsertRequestOta(hash, request) { // Para OTA no necesitamos esperar mucho aquí; es solo el INSERT return R.apiInsertRequest(hash, request); } async function apiQueryResponseOta(hash, numId) { return R.apiQueryResponse(hash, numId); } // --------------------------------------------------------- // PROGRESO OTA: interpretar JSON del terminal // Formato típico: // {"ota":"progress","rec":513740,"exp":1191232,"pct":43} // {"ota":"done","ok":1} // --------------------------------------------------------- function extractPctFromResponse(resp) { if (!resp || typeof resp !== 'object') return null; // Caso directo: viene "pct" if (resp.ota === 'progress' && typeof resp.pct === 'number') { return resp.pct; } // Fallback por si en alguna versión no envías pct pero sí rec/exp if (resp.ota === 'progress' && typeof resp.rec === 'number' && typeof resp.exp === 'number' && resp.exp > 0) { return Math.round((resp.rec * 100) / resp.exp); } return null; } // --------------------------------------------------------- // BUCLE DE POLL OTA (pide progreso por API) // --------------------------------------------------------- let __otaPolling = null; // { hash, numId, startedAt, lastPct, finished } async function startOtaPolling(hash, numId, timeoutMs) { if (__otaPolling && !__otaPolling.finished) { console.warn('[OTA/API] Ya hay un OTA polling en marcha, se ignora la nueva llamada.'); return; } __otaPolling = { hash: hash, numId: numId, startedAt: Date.now(), lastPct: 0, finished: false }; const maxMs = timeoutMs || OTA_TIMEOUT_MS; // ← aquí fuerza a ~5 min const pollMs = OTA_POLL_MS; // ← intervalo entre consultas setOtaUrlBusy(true); setOtaUrlProgress(0); setOtaUrlStatus('OTA iniciada. Esperando progreso del dispositivo…', 'info'); try { while (true) { const now = Date.now(); if (now - __otaPolling.startedAt > maxMs) { throw new Error('Timeout OTA (' + maxMs + ' ms)'); } const { hasResponse, responseObj } = await apiQueryResponseOta(hash, numId); if (hasResponse && responseObj) { // 1) Progreso const pct = extractPctFromResponse(responseObj); if (pct != null) { __otaPolling.lastPct = pct; setOtaUrlProgress(pct); setOtaUrlStatus('Descargando firmware… (' + pct + '%)', 'info'); } // 2) Fin OTA: {"ota":"done","ok":1} if (responseObj.ota === 'done') { if (Number(responseObj.ok) === 1) { setOtaUrlProgress(100); setOtaUrlStatus('OTA completada. El dispositivo se reiniciará en 30 segundos.', 'success'); __otaPolling.finished = true; var remaining = 30; var countdownInterval = setInterval(function () { remaining = remaining - 1; setOtaUrlStatus( 'OTA completada. El dispositivo se reiniciará en ' + remaining + ' segundos.', 'success' ); if (remaining <= 0) { clearInterval(countdownInterval); } }, 1000); setTimeout(function () { setOtaUrlBusy(false); window.location.reload(); }, 30000); return; } else { var errMsg = responseObj.msg || 'OTA finalizada con error en el dispositivo.'; throw new Error(errMsg); } } // 3) Error explícito: {"ota":"error","msg":"..."} if (responseObj.ota === 'error') { const errMsg2 = responseObj.msg || 'Error OTA en el dispositivo.'; throw new Error(errMsg2); } } await sleep(pollMs); } } catch (err) { console.warn('[OTA/API] Error en polling OTA:', err); __otaPolling.finished = true; setOtaUrlStatus('Error OTA: ' + (err.message || err), 'danger'); setOtaUrlBusy(false); } } // --------------------------------------------------------- // CATÁLOGO FIRMWARE (REST_QUERY -> itc_fw_catalog.sql) // --------------------------------------------------------- window.REST_QUERY = window.REST_QUERY || '/rest/services/query/ITC/CONS01?type=json&rquser=api'; window.itc_firmware_app = window.itc_firmware_app || { IDENT: 'itc_fw_catalog.sql' }; function normalizeCatalog(response) { const rows = Array.isArray(response) ? response : (response && Array.isArray(response.rows)) ? response.rows : []; return rows.map(function (r) { return { ver_app: String(r.ver_app || '').trim(), url : String(r.url || '').trim(), date : r.date || '', date_fmt: r.date_fmt || '', comment: String(r.comment || '').trim() }; }).filter(function (r) { return r.ver_app && r.url && /^http(s)?:\/\//i.test(r.url); }); } function fillVersionSelect(items) { const $sel = $('#otaVersion'); $sel.empty(); /* items.sort(function (a, b) { if (a.date_fmt && b.date_fmt) return (a.date_fmt < b.date_fmt) ? 1 : -1; return (a.ver_app < b.ver_app) ? 1 : -1; }); */ items.forEach(function (it) { $sel.append( $('