feat(com-moodle): enhance COM reconnect/disconnect lifecycle and update Moodle URL and password RAG knowledge (v3.8.53)
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"version": "3.8.52",
|
||||
"version": "3.8.53",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* serial-scanner.js — Módulo Multi-Lector Óptico y Escáner QR por Puerto Serie (COM)
|
||||
* Específico para navegadores Chromium (Google Chrome, Microsoft Edge, Opera, Brave) en entornos Windows.
|
||||
* Soporta hasta 4 lectores seriales concurrentes mediante la Web Serial API (navigator.serial).
|
||||
* Soporta hasta 4 lectores seriales concurrentes con reconexión física plug-and-play automática.
|
||||
* Especificación: specs/013-escaner-qr-puerto-com-serial/
|
||||
*/
|
||||
|
||||
@@ -18,13 +18,15 @@
|
||||
this.readableStreamClosed = null;
|
||||
this.keepReading = false;
|
||||
this.buffer = '';
|
||||
this.bufferTimeout = null;
|
||||
this.status = 'DISCONNECTED'; // 'DISCONNECTED' | 'CONNECTED' | 'ERROR'
|
||||
this.lastCode = '';
|
||||
this.lastScannedAt = null;
|
||||
this.usbInfo = null;
|
||||
}
|
||||
|
||||
isConnected() {
|
||||
return this.status === 'CONNECTED' && this.port !== null && Boolean(this.port.readable);
|
||||
return this.status === 'CONNECTED' && this.port !== null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,7 +44,7 @@
|
||||
this.onStatusChanged = options.onStatusChanged || null;
|
||||
this.onError = options.onError || null;
|
||||
|
||||
this._initGlobalDisconnectListener();
|
||||
this._initGlobalListeners();
|
||||
}
|
||||
|
||||
isSupported() {
|
||||
@@ -61,15 +63,32 @@
|
||||
return this.slots.filter(s => s.isConnected()).length;
|
||||
}
|
||||
|
||||
_initGlobalDisconnectListener() {
|
||||
if (this.isSupported()) {
|
||||
navigator.serial.addEventListener('disconnect', (event) => {
|
||||
const disconnectedSlot = this.slots.find(s => s.port === event.target);
|
||||
if (disconnectedSlot) {
|
||||
this.disconnectSlot(disconnectedSlot.id, 'Dispositivo serie desconectado físicamente.');
|
||||
_initGlobalListeners() {
|
||||
if (!this.isSupported()) return;
|
||||
|
||||
// Detección de desconexión física de cable USB / Serial
|
||||
navigator.serial.addEventListener('disconnect', (event) => {
|
||||
const disconnectedSlot = this.slots.find(s => s.port === event.target);
|
||||
if (disconnectedSlot) {
|
||||
console.info(`[MultiSerialScanner] Lector ${disconnectedSlot.id} desconectado físicamente.`);
|
||||
this.disconnectSlot(disconnectedSlot.id, 'Dispositivo serie desconectado físicamente.');
|
||||
}
|
||||
});
|
||||
|
||||
// Detección de conexión física / re-enchufe de cable USB previamente autorizado
|
||||
navigator.serial.addEventListener('connect', async (event) => {
|
||||
console.info('[MultiSerialScanner] Nuevo dispositivo serie detectado en Windows.');
|
||||
// Encontrar el primer slot libre y reconectar automáticamente
|
||||
const freeSlot = this.slots.find(s => !s.isConnected());
|
||||
if (freeSlot) {
|
||||
try {
|
||||
freeSlot.port = event.target;
|
||||
await this._openPortOnSlot(freeSlot);
|
||||
} catch (err) {
|
||||
console.warn(`[MultiSerialScanner] Error auto-conectando dispositivo enchufado a slot ${freeSlot.id}:`, err);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
_notifyStatus(slot, message, extra = {}) {
|
||||
@@ -81,6 +100,7 @@
|
||||
message: message || '',
|
||||
baudRate: slot.baudRate,
|
||||
totalConnected: this.getConnectedCount(),
|
||||
usbInfo: slot.usbInfo,
|
||||
...extra
|
||||
});
|
||||
}
|
||||
@@ -97,15 +117,24 @@
|
||||
if (!ports || ports.length === 0) return 0;
|
||||
|
||||
let connectedCount = 0;
|
||||
for (let i = 0; i < Math.min(ports.length, this.maxSlots); i++) {
|
||||
const slot = this.slots[i];
|
||||
if (!slot.isConnected()) {
|
||||
for (let i = 0; i < ports.length && i < this.maxSlots; i++) {
|
||||
const port = ports[i];
|
||||
// Si el puerto ya está conectado en algún slot, saltarlo
|
||||
if (this.slots.some(s => s.port === port && s.isConnected())) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Encontrar el primer slot libre
|
||||
const slot = this.slots.find(s => !s.isConnected());
|
||||
if (slot) {
|
||||
try {
|
||||
slot.port = ports[i];
|
||||
slot.port = port;
|
||||
await this._openPortOnSlot(slot);
|
||||
connectedCount++;
|
||||
} catch (err) {
|
||||
console.warn(`[MultiSerialScanner] Autoconnect slot ${slot.id} notice:`, err.message);
|
||||
console.warn(`[MultiSerialScanner] Reconexión automática de slot ${slot.id} falló:`, err.message);
|
||||
slot.port = null;
|
||||
slot.status = 'DISCONNECTED';
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -117,7 +146,7 @@
|
||||
}
|
||||
|
||||
/**
|
||||
* Solicita al operador seleccionar un dispositivo serie COM y lo asigna al slot especificado.
|
||||
* Solicita al operador seleccionar un dispositivo serie COM o re-asigna uno autorizado libre.
|
||||
*/
|
||||
async requestAndConnectSlot(slotId, baudRate = null) {
|
||||
if (!this.isSupported()) {
|
||||
@@ -138,9 +167,25 @@
|
||||
await this.disconnectSlot(slot.id);
|
||||
}
|
||||
|
||||
// Despliega el diálogo nativo de Windows para seleccionar dispositivo serie COM
|
||||
const port = await navigator.serial.requestPort();
|
||||
slot.port = port;
|
||||
// 1. Verificar si hay un puerto previamente autorizado por el navegador que no esté asignado
|
||||
const authorizedPorts = await navigator.serial.getPorts();
|
||||
const unassignedPort = authorizedPorts.find(p => !this.slots.some(s => s.port === p && s.isConnected()));
|
||||
|
||||
let portToUse = null;
|
||||
if (unassignedPort) {
|
||||
try {
|
||||
portToUse = unassignedPort;
|
||||
slot.port = portToUse;
|
||||
await this._openPortOnSlot(slot);
|
||||
return slot;
|
||||
} catch (e) {
|
||||
console.info('[MultiSerialScanner] Puerto autorizado ocupado, solicitando selección nueva...');
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Si no hay autorizados libres, solicitar permiso explícito al usuario en Windows
|
||||
portToUse = await navigator.serial.requestPort();
|
||||
slot.port = portToUse;
|
||||
await this._openPortOnSlot(slot);
|
||||
return slot;
|
||||
}
|
||||
@@ -148,13 +193,23 @@
|
||||
async _openPortOnSlot(slot) {
|
||||
if (!slot || !slot.port) return;
|
||||
|
||||
await slot.port.open({
|
||||
baudRate: slot.baudRate,
|
||||
dataBits: 8,
|
||||
stopBits: 1,
|
||||
parity: 'none',
|
||||
bufferSize: 2048
|
||||
});
|
||||
// Obtener información de hardware USB si está disponible
|
||||
try {
|
||||
slot.usbInfo = slot.port.getInfo ? slot.port.getInfo() : null;
|
||||
} catch (e) {
|
||||
slot.usbInfo = null;
|
||||
}
|
||||
|
||||
// Si el puerto no está abierto, abrirlo
|
||||
if (!slot.port.readable) {
|
||||
await slot.port.open({
|
||||
baudRate: slot.baudRate,
|
||||
dataBits: 8,
|
||||
stopBits: 1,
|
||||
parity: 'none',
|
||||
bufferSize: 2048
|
||||
});
|
||||
}
|
||||
|
||||
slot.keepReading = true;
|
||||
slot.status = 'CONNECTED';
|
||||
@@ -195,7 +250,13 @@
|
||||
_handleIncomingText(slot, chunk) {
|
||||
slot.buffer += chunk;
|
||||
|
||||
// Delimitadores habituales de lectores y pistolas ópticas (\r, \n)
|
||||
// Resetear timeout de flush automático
|
||||
if (slot.bufferTimeout) {
|
||||
clearTimeout(slot.bufferTimeout);
|
||||
slot.bufferTimeout = null;
|
||||
}
|
||||
|
||||
// 1. Delimitadores estándar de retorno de carro o salto de línea (\r, \n)
|
||||
if (slot.buffer.includes('\n') || slot.buffer.includes('\r')) {
|
||||
const parts = slot.buffer.split(/[\r\n]+/);
|
||||
for (let i = 0; i < parts.length - 1; i++) {
|
||||
@@ -206,10 +267,26 @@
|
||||
}
|
||||
slot.buffer = parts[parts.length - 1];
|
||||
}
|
||||
|
||||
// 2. Timeout de seguridad: Si pasan 120ms sin nuevos caracteres y el buffer tiene longitud razonable, despachar
|
||||
if (slot.buffer.trim().length >= 4) {
|
||||
slot.bufferTimeout = setTimeout(() => {
|
||||
const code = slot.buffer.trim();
|
||||
if (code.length >= 4) {
|
||||
this._dispatchCode(slot, code);
|
||||
slot.buffer = '';
|
||||
}
|
||||
}, 120);
|
||||
}
|
||||
}
|
||||
|
||||
_dispatchCode(slot, code) {
|
||||
// Normalizar tolerante de scancodes si el lector traduce : a Ñ en teclados en español
|
||||
if (slot.bufferTimeout) {
|
||||
clearTimeout(slot.bufferTimeout);
|
||||
slot.bufferTimeout = null;
|
||||
}
|
||||
|
||||
// Normalización tolerante de scancodes si el lector traduce : a Ñ en teclados en español
|
||||
const cleanCode = code.replace(/Ñ/g, ':').replace(/ñ/g, ':');
|
||||
slot.lastCode = cleanCode;
|
||||
slot.lastScannedAt = new Date();
|
||||
@@ -230,10 +307,18 @@
|
||||
slot.keepReading = false;
|
||||
slot.status = 'DISCONNECTED';
|
||||
|
||||
if (slot.bufferTimeout) {
|
||||
clearTimeout(slot.bufferTimeout);
|
||||
slot.bufferTimeout = null;
|
||||
}
|
||||
|
||||
if (slot.reader) {
|
||||
try {
|
||||
await slot.reader.cancel();
|
||||
} catch (e) {}
|
||||
try {
|
||||
slot.reader.releaseLock();
|
||||
} catch (e) {}
|
||||
slot.reader = null;
|
||||
}
|
||||
|
||||
|
||||
+3
-3
@@ -86,9 +86,9 @@ const env = nunjucks.configure(path.join(__dirname, '../views'), {
|
||||
});
|
||||
|
||||
// Versiones institucionales del sistema
|
||||
const APP_VERSION = '3.8.52';
|
||||
const FRONTEND_VERSION = '3.8.52';
|
||||
const BACKEND_VERSION = '3.8.52';
|
||||
const APP_VERSION = '3.8.53';
|
||||
const FRONTEND_VERSION = '3.8.53';
|
||||
const BACKEND_VERSION = '3.8.53';
|
||||
|
||||
env.addGlobal('app_version', APP_VERSION);
|
||||
env.addGlobal('frontend_version', FRONTEND_VERSION);
|
||||
|
||||
@@ -82,14 +82,22 @@
|
||||
<span class="small fw-bold text-uppercase text-muted">
|
||||
<i class="bi bi-usb-symbol me-1 text-primary"></i> Lectores Serie COM (Hasta 4)
|
||||
</span>
|
||||
<div class="d-flex align-items-center gap-1">
|
||||
<span class="badge bg-secondary-subtle text-secondary rounded-pill px-2 py-1 small" id="comGlobalBadge">
|
||||
<i class="bi bi-circle-fill text-muted me-1" style="font-size: 0.5rem;"></i> 0 / 4 Activos
|
||||
</span>
|
||||
<button type="button" class="btn btn-xs btn-link text-decoration-none p-0 text-muted" title="Reconectar autorizados" onclick="reconnectAuthorizedComPorts()">
|
||||
<i class="bi bi-arrow-clockwise"></i>
|
||||
</button>
|
||||
</div>
|
||||
<span class="badge bg-secondary-subtle text-secondary rounded-pill px-2 py-1 small" id="comGlobalBadge">
|
||||
<i class="bi bi-circle-fill text-muted me-1" style="font-size: 0.5rem;"></i> 0 / 4 Activos
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<!-- Botones de Acción Rápida Global -->
|
||||
<div class="d-flex align-items-center gap-2 mb-3">
|
||||
<button type="button" class="btn btn-sm btn-primary rounded-pill px-3 py-1 flex-grow-1 shadow-xs" id="btnQuickConnectCOM" onclick="handleQuickConnectCOM()">
|
||||
<i class="bi bi-usb-plug-fill me-1"></i> Conectar Lector COM
|
||||
</button>
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary rounded-pill px-2 py-1" title="Reconectar lectores autorizados" onclick="reconnectAuthorizedComPorts()">
|
||||
<i class="bi bi-arrow-clockwise"></i>
|
||||
</button>
|
||||
<button type="button" class="btn btn-sm btn-outline-danger rounded-pill px-2 py-1" title="Desconectar todos los puertos COM" onclick="handleDisconnectAllCOM()">
|
||||
<i class="bi bi-power"></i>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Grilla de los 4 Slots de Lectores Seriales -->
|
||||
@@ -430,6 +438,23 @@
|
||||
}
|
||||
}
|
||||
|
||||
async function handleQuickConnectCOM() {
|
||||
if (!multiScanner) initSerialScanner();
|
||||
if (!multiScanner.isSupported()) {
|
||||
alert('La Web Serial API no está disponible en este navegador. Utiliza Google Chrome o Microsoft Edge en entornos Windows.');
|
||||
return;
|
||||
}
|
||||
// Buscar el primer slot disponible
|
||||
const freeSlot = multiScanner.slots.find(s => !s.isConnected());
|
||||
const targetSlotId = freeSlot ? freeSlot.id : 1;
|
||||
await handleConnectSlot(targetSlotId);
|
||||
}
|
||||
|
||||
async function handleDisconnectAllCOM() {
|
||||
if (!multiScanner) return;
|
||||
await multiScanner.disconnectAll();
|
||||
}
|
||||
|
||||
async function reconnectAuthorizedComPorts() {
|
||||
if (!multiScanner) initSerialScanner();
|
||||
if (multiScanner && multiScanner.isSupported()) {
|
||||
|
||||
Reference in New Issue
Block a user