/** * serial-scanner.js — Módulo de Lector Óptico y Escáner QR por Puerto Serie (COM) * Específico para navegadores Chromium (Google Chrome, Microsoft Edge, Opera, Brave) en entornos Windows. * Utiliza la Web Serial API (navigator.serial) para lectura directa y en segundo plano sin requerir foco. * Espec: specs/013-escaner-qr-puerto-com-serial/ */ (function(window) { 'use strict'; class SerialBarcodeScanner { constructor(options = {}) { this.baudRate = options.baudRate || 9600; this.port = null; this.reader = null; this.readableStreamClosed = null; this.keepReading = false; this.buffer = ''; this.onCodeScanned = options.onCodeScanned || null; this.onStatusChanged = options.onStatusChanged || null; this.onError = options.onError || null; this._initDisconnectListener(); } isSupported() { return typeof navigator !== 'undefined' && 'serial' in navigator; } _initDisconnectListener() { if (this.isSupported()) { navigator.serial.addEventListener('disconnect', (event) => { if (this.port && event.target === this.port) { this._notifyStatus('DISCONNECTED', 'Puerto serie desconectado físicamente.'); this.disconnect(); } }); } } _notifyStatus(status, message, details = {}) { if (typeof this.onStatusChanged === 'function') { this.onStatusChanged({ status, message, ...details }); } } async autoConnectIfAuthorized() { if (!this.isSupported()) return false; try { const ports = await navigator.serial.getPorts(); if (ports && ports.length > 0) { this.port = ports[0]; await this._openPort(); return true; } } catch (err) { console.warn('[SerialScanner] Autoconnect notice:', err.message); } return false; } async requestAndConnect(baudRate = null) { if (!this.isSupported()) { throw new Error('La Web Serial API no está soportada en este navegador. Utiliza Google Chrome o Microsoft Edge.'); } if (baudRate) { this.baudRate = parseInt(baudRate, 10) || 9600; } // Desconectar puerto previo si estuviera activo if (this.port) { await this.disconnect(); } // Despliega el diálogo nativo de Windows para seleccionar dispositivo COM this.port = await navigator.serial.requestPort(); await this._openPort(); return this.port; } async _openPort() { if (!this.port) return; await this.port.open({ baudRate: this.baudRate, dataBits: 8, stopBits: 1, parity: 'none', bufferSize: 1024 }); this.keepReading = true; this._notifyStatus('CONNECTED', `Puerto serie conectado a ${this.baudRate} baudios.`, { baudRate: this.baudRate }); this._startReadingLoop(); } async _startReadingLoop() { while (this.port && this.port.readable && this.keepReading) { const textDecoder = new TextDecoderStream(); this.readableStreamClosed = this.port.readable.pipeTo(textDecoder.writable); this.reader = textDecoder.readable.getReader(); try { while (this.keepReading) { const { value, done } = await this.reader.read(); if (done) break; if (value) { this._handleIncomingText(value); } } } catch (error) { if (this.keepReading) { console.error('[SerialScanner] Error en lectura serie:', error); if (typeof this.onError === 'function') { this.onError(error); } } } finally { try { this.reader.releaseLock(); } catch (e) {} } } } _handleIncomingText(chunk) { this.buffer += chunk; // Detectar delimitadores de fin de línea habituales en pistolas ópticas (\r, \n) if (this.buffer.includes('\n') || this.buffer.includes('\r')) { const parts = this.buffer.split(/[\r\n]+/); for (let i = 0; i < parts.length - 1; i++) { const rawCode = parts[i].trim(); if (rawCode.length >= 2) { this._dispatchCode(rawCode); } } this.buffer = parts[parts.length - 1]; } } _dispatchCode(code) { // Normalizar scancodes si fuera necesario const cleanCode = code.replace(/Ñ/g, ':').replace(/ñ/g, ':'); if (typeof this.onCodeScanned === 'function') { this.onCodeScanned(cleanCode); } } async disconnect() { this.keepReading = false; if (this.reader) { try { await this.reader.cancel(); } catch (e) {} this.reader = null; } if (this.readableStreamClosed) { try { await this.readableStreamClosed.catch(() => {}); } catch (e) {} this.readableStreamClosed = null; } if (this.port) { try { await this.port.close(); } catch (e) {} this.port = null; } this.buffer = ''; this._notifyStatus('DISCONNECTED', 'Puerto serie desconectado.'); } } // Exportar al objeto global de ventana window.SerialBarcodeScanner = SerialBarcodeScanner; })(window);