/** * 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). * Especificación: specs/013-escaner-qr-puerto-com-serial/ */ (function(window) { 'use strict'; class SerialSlot { constructor(id, name, options = {}) { this.id = id; this.name = name || `Lector ${id}`; this.baudRate = options.baudRate || 9600; this.port = null; this.reader = null; this.readableStreamClosed = null; this.keepReading = false; this.buffer = ''; this.status = 'DISCONNECTED'; // 'DISCONNECTED' | 'CONNECTED' | 'ERROR' this.lastCode = ''; this.lastScannedAt = null; } isConnected() { return this.status === 'CONNECTED' && this.port !== null && Boolean(this.port.readable); } } class MultiSerialBarcodeScanner { constructor(options = {}) { this.maxSlots = 4; this.slots = [ new SerialSlot(1, 'Lector 1 (Paso Principal)', options), new SerialSlot(2, 'Lector 2 (Molinete / Acceso)', options), new SerialSlot(3, 'Lector 3 (Mesa Bedelía)', options), new SerialSlot(4, 'Lector 4 (Auxiliar / Puesto 2)', options) ]; this.onCodeScanned = options.onCodeScanned || null; this.onStatusChanged = options.onStatusChanged || null; this.onError = options.onError || null; this._initGlobalDisconnectListener(); } isSupported() { return typeof navigator !== 'undefined' && 'serial' in navigator; } getSlots() { return this.slots; } getSlot(slotId) { return this.slots.find(s => s.id === slotId) || null; } getConnectedCount() { 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.'); } }); } } _notifyStatus(slot, message, extra = {}) { if (typeof this.onStatusChanged === 'function') { this.onStatusChanged({ slotId: slot.id, slotName: slot.name, status: slot.status, message: message || '', baudRate: slot.baudRate, totalConnected: this.getConnectedCount(), ...extra }); } } /** * Reabre automáticamente los puertos previamente autorizados por el usuario en esta terminal. */ async autoConnectAuthorizedPorts() { if (!this.isSupported()) return 0; try { const ports = await navigator.serial.getPorts(); 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()) { try { slot.port = ports[i]; await this._openPortOnSlot(slot); connectedCount++; } catch (err) { console.warn(`[MultiSerialScanner] Autoconnect slot ${slot.id} notice:`, err.message); } } } return connectedCount; } catch (err) { console.warn('[MultiSerialScanner] Error consultando puertos autorizados:', err); return 0; } } /** * Solicita al operador seleccionar un dispositivo serie COM y lo asigna al slot especificado. */ async requestAndConnectSlot(slotId, baudRate = null) { if (!this.isSupported()) { throw new Error('La Web Serial API no está disponible en este navegador. Utiliza Google Chrome o Microsoft Edge en Windows.'); } const slot = this.getSlot(slotId); if (!slot) { throw new Error(`Slot #${slotId} no válido (debe ser entre 1 y ${this.maxSlots}).`); } if (baudRate) { slot.baudRate = parseInt(baudRate, 10) || 9600; } // Si el slot ya estaba conectado, liberarlo previamente if (slot.isConnected()) { 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; await this._openPortOnSlot(slot); return slot; } async _openPortOnSlot(slot) { if (!slot || !slot.port) return; await slot.port.open({ baudRate: slot.baudRate, dataBits: 8, stopBits: 1, parity: 'none', bufferSize: 2048 }); slot.keepReading = true; slot.status = 'CONNECTED'; this._notifyStatus(slot, `Lector COM conectado a ${slot.baudRate} baudios.`); this._startReadingLoop(slot); } async _startReadingLoop(slot) { while (slot.port && slot.port.readable && slot.keepReading) { const textDecoder = new TextDecoderStream(); slot.readableStreamClosed = slot.port.readable.pipeTo(textDecoder.writable); slot.reader = textDecoder.readable.getReader(); try { while (slot.keepReading) { const { value, done } = await slot.reader.read(); if (done) break; if (value) { this._handleIncomingText(slot, value); } } } catch (error) { if (slot.keepReading) { console.error(`[MultiSerialScanner] Error en lectura de slot ${slot.id}:`, error); if (typeof this.onError === 'function') { this.onError(error, slot); } } } finally { try { slot.reader.releaseLock(); } catch (e) {} } } } _handleIncomingText(slot, chunk) { slot.buffer += chunk; // Delimitadores habituales de lectores y pistolas ópticas (\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++) { const rawCode = parts[i].trim(); if (rawCode.length >= 2) { this._dispatchCode(slot, rawCode); } } slot.buffer = parts[parts.length - 1]; } } _dispatchCode(slot, code) { // Normalizar 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(); if (typeof this.onCodeScanned === 'function') { this.onCodeScanned(cleanCode, { slotId: slot.id, slotName: slot.name, timestamp: slot.lastScannedAt }); } } async disconnectSlot(slotId, reason = 'Desconectado por el usuario') { const slot = this.getSlot(slotId); if (!slot) return; slot.keepReading = false; slot.status = 'DISCONNECTED'; if (slot.reader) { try { await slot.reader.cancel(); } catch (e) {} slot.reader = null; } if (slot.readableStreamClosed) { try { await slot.readableStreamClosed.catch(() => {}); } catch (e) {} slot.readableStreamClosed = null; } if (slot.port) { try { await slot.port.close(); } catch (e) {} slot.port = null; } slot.buffer = ''; this._notifyStatus(slot, reason); } async disconnectAll() { for (const slot of this.slots) { if (slot.isConnected()) { await this.disconnectSlot(slot.id); } } } } // Compatibilidad hacia atrás para código que instancie SerialBarcodeScanner directamente class SerialBarcodeScannerCompat { constructor(options = {}) { this.multi = new MultiSerialBarcodeScanner({ ...options, onCodeScanned: (code, info) => { if (typeof options.onCodeScanned === 'function') { options.onCodeScanned(code, info); } }, onStatusChanged: (evt) => { if (typeof options.onStatusChanged === 'function') { options.onStatusChanged(evt); } } }); } isSupported() { return this.multi.isSupported(); } async autoConnectIfAuthorized() { const count = await this.multi.autoConnectAuthorizedPorts(); return count > 0; } async requestAndConnect(baudRate = null) { return await this.multi.requestAndConnectSlot(1, baudRate); } async disconnect() { await this.multi.disconnectSlot(1); } } // Exportar al objeto global window.MultiSerialBarcodeScanner = MultiSerialBarcodeScanner; window.SerialBarcodeScanner = SerialBarcodeScannerCompat; })(window);