// manager_wifi.js (function (window) { 'use strict'; // --------------------------------------------------------- // CONFIGURACIÓN API // --------------------------------------------------------- const API_CFG = { INSERT_URL: REST_INSERT, QUERY_URL: REST_QUERY, DEFAULT_TIMEOUT_MS: 3000, // 3 segundos DEFAULT_POLL_MS: 800 // cada 800 ms pregunta si hay respuesta }; const SESSION_ID = (typeof jspSessionId !== 'undefined') ? jspSessionId : ''; // --------------------------------------------------------- // ESTADO DE CONEXIÓN // --------------------------------------------------------- let _connected = false; function setConnected(flag) { _connected = !!flag; try { if (_connected) { sessionStorage.setItem('itcConnected', '1'); } else { sessionStorage.removeItem('itcConnected'); sessionStorage.removeItem('itcHash'); } } catch (e) { // por si sessionStorage no está disponible (modo privado raro, etc.) console.warn('No se pudo usar sessionStorage:', e); } updateDisconnectButton(); } function isConnected() { return _connected; } // --------------------------------------------------------- function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } // --------------------------------------------------------- // LLAMADAS REST BÁSICAS // --------------------------------------------------------- /** * Inserta una petición (INSERT/INS01) y devuelve { numId, raw }. * @param {string} hash * @param {string} request */ async function apiInsertRequest(hash, request) { let sFncIdent = "request"; let sRequest = request; const isLogin = (request === 'login'); if (isLogin) { // Para login usamos SQL especial pero seguimos enviando REQUEST = "info" sFncIdent = "login"; sRequest = "info"; } const body = { IDENT: "itc_devices_terminal_ins_"+sFncIdent+".sql", SESSION_ID: SESSION_ID, HASH: hash, REQUEST: sRequest }; const res = await fetch(API_CFG.INSERT_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }); if (!res.ok) { throw new Error('Error HTTP en INSERT: ' + res.status); } const json = await res.json(); if (json.result !== 1 || !json.rows || !json.rows.length) { throw new Error('INSERT sin filas o result != 1'); } const row = json.rows[0]; let numId = row.num_id || row.NUM_ID; if (!numId) { if (isLogin) { numId = 1; // CASO ESPECIAL LOGIN: num_id de la respuesta será siempre 1 } else { throw new Error('INSERT no devolvió NUM_ID'); } } return { numId, raw: json }; } /** * Consulta una respuesta por SESSION_ID + HASH + NUM_ID * y devuelve { hasResponse, responseObj, raw }. */ async function apiQueryResponse(hash, numId) { const body = { _INT_ORDEN_CAMPO: "1", _INT_ORDEN_CRITERIO: "DESC", IDENT: "itc_devices_terminal_response.sql", SESSION_ID: SESSION_ID, HASH: hash, NUM_ID: String(numId) }; const res = await fetch(API_CFG.QUERY_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }); if (!res.ok) { throw new Error('Error HTTP en QUERY: ' + res.status); } const json = await res.json(); if (!json.rows || !json.rows.length) { return { hasResponse: false, responseObj: null, raw: json }; } const row = json.rows[0]; const respStr = row.response || row.RESPONSE; if (!respStr) { return { hasResponse: false, responseObj: null, raw: json }; } let responseObj; try { responseObj = JSON.parse(respStr); } catch (e) { throw new Error('No se pudo parsear JSON de response: ' + e.message); } return { hasResponse: true, responseObj, raw: json }; } /** * Envía una instrucción al dispositivo y espera la respuesta. * opts: { hash, request, timeoutMs?, pollMs? } */ async function sendDeviceCommand(opts) { const hash = opts.hash; const request = opts.request; const timeoutMs = opts.timeoutMs || API_CFG.DEFAULT_TIMEOUT_MS; const pollMs = opts.pollMs || API_CFG.DEFAULT_POLL_MS; const { numId } = await apiInsertRequest(hash, request); const start = Date.now(); while (true) { const now = Date.now(); if (now - start > timeoutMs) { setConnected(false); //throw new Error('Timeout esperando respuesta del dispositivo (' + timeoutMs + ' ms)'); throw new Error('Timeout esperando respuesta del dispositivo'); } const { hasResponse, responseObj } = await apiQueryResponse(hash, numId); if (hasResponse) { setConnected(true); return responseObj; } await sleep(pollMs); } } // --------------------------------------------------------- // Helpers de dispositivo actual // --------------------------------------------------------- function setCurrentDevice(hash, info) { window.currentDevice = { hash, info }; setConnected(true); try { sessionStorage.setItem('itcHash', hash); } catch (e) { console.warn('No se pudo guardar hash en sessionStorage:', e); } } function getCurrentDevice() { return window.currentDevice || {}; } function getCurrentHash() { if (window.currentDevice && window.currentDevice.hash) { return window.currentDevice.hash; } const h2 = (document.getElementById('hash2')?.textContent || '').trim(); const h = h2 || (document.getElementById('hash')?.textContent || '').trim(); if (!h || h === '—') return null; return h; } // --------------------------------------------------------- // Desconectar dispositivo (logout) // --------------------------------------------------------- function disconnectDevice() { // Limpiar estado en memoria window.currentDevice = null; // Esto ya borra itcConnected e itcHash del sessionStorage setConnected(false); // Limpiar labels de hash si existen var h1 = document.getElementById('hash'); if (h1) { h1.textContent = '—'; } var h2 = document.getElementById('hash2'); if (h2) { h2.textContent = '—'; } // Ocultar sección app y mostrar pantalla de login (gate) var appSection = document.getElementById('appSection'); var gateSection = document.getElementById('gateSection'); if (appSection) { appSection.classList.add('hidden'); } if (gateSection) { gateSection.classList.remove('hidden'); } // Limpiar input de hash y enfocar var hashInput = document.getElementById('hashInput'); if (hashInput) { hashInput.value = ''; hashInput.focus(); } } function updateDisconnectButton() { var btn = document.getElementById('btnDisconnect'); if (!btn) return; if (isConnected()) { btn.classList.remove('d-none'); } else { btn.classList.add('d-none'); } } /** * Inserta un registro de calibración en BBDD. * @param {Object} p * @param {string} p.hash * @param {string} p.app * @param {string} p.tecnico * @param {string} p.sistema * @param {string} p.notas * @returns {Promise<{ok:boolean, raw:any}>} */ async function apiInsertCalibration(p) { const body = { IDENT: "itc_devices_calibration_ins.sql", SESSION_ID: SESSION_ID, HASH: p.hash || '', APP: p.app || '', TECNICO: p.tecnico || '', SISTEMA: p.sistema || '', NOTAS: p.notas || '' }; const res = await fetch(API_CFG.INSERT_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }); if (!res.ok) { throw new Error('Error HTTP en INSERT CALIBRATION: ' + res.status); } const json = await res.json(); // aquí depende de tu API: normalmente result=1 => OK if (json.result !== 1) { throw new Error('INSERT CALIBRATION result != 1'); } return { ok: true, raw: json }; } /** * Consulta calibración por HASH * Devuelve { rows, raw } * @param {string} hash */ async function apiQueryCalibration(hash) { const body = { _INT_ORDEN_CAMPO: "1", _INT_ORDEN_CRITERIO: "DESC", IDENT: "itc_devices_calibration.sql", HASH: hash }; const res = await fetch(API_CFG.QUERY_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }); if (!res.ok) { throw new Error('Error HTTP en QUERY CALIBRATION: ' + res.status); } const json = await res.json(); const rows = (json && json.rows) ? json.rows : []; return { rows, raw: json }; } // --------------------------------------------------------- // Export al espacio global // --------------------------------------------------------- window.ITCRemote = { API_CFG, SESSION_ID, sleep, apiInsertRequest, apiQueryResponse, sendDeviceCommand, setCurrentDevice, getCurrentDevice, getCurrentHash, setConnected, isConnected, disconnectDevice, updateDisconnectButton, apiInsertCalibration, apiQueryCalibration }; })(window); document.addEventListener('DOMContentLoaded', function () { if (window.ITCRemote && ITCRemote.updateDisconnectButton) { ITCRemote.updateDisconnectButton(); } });