393 lines
14 KiB
JavaScript
393 lines
14 KiB
JavaScript
/**
|
|
* 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 con reconexión física plug-and-play automática.
|
|
* 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.bufferTimeout = null;
|
|
this.status = 'DISCONNECTED'; // 'DISCONNECTED' | 'CONNECTED' | 'ERROR'
|
|
this.lastCode = '';
|
|
this.lastScannedAt = null;
|
|
this.usbInfo = null;
|
|
}
|
|
|
|
isConnected() {
|
|
return this.status === 'CONNECTED' && this.port !== null;
|
|
}
|
|
}
|
|
|
|
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._initGlobalListeners();
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
_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 = {}) {
|
|
if (typeof this.onStatusChanged === 'function') {
|
|
this.onStatusChanged({
|
|
slotId: slot.id,
|
|
slotName: slot.name,
|
|
status: slot.status,
|
|
message: message || '',
|
|
baudRate: slot.baudRate,
|
|
totalConnected: this.getConnectedCount(),
|
|
usbInfo: slot.usbInfo,
|
|
...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 < 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 = port;
|
|
await this._openPortOnSlot(slot);
|
|
connectedCount++;
|
|
} catch (err) {
|
|
console.warn(`[MultiSerialScanner] Reconexión automática de slot ${slot.id} falló:`, err.message);
|
|
slot.port = null;
|
|
slot.status = 'DISCONNECTED';
|
|
}
|
|
}
|
|
}
|
|
return connectedCount;
|
|
} catch (err) {
|
|
console.warn('[MultiSerialScanner] Error consultando puertos autorizados:', err);
|
|
return 0;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Solicita al operador seleccionar un dispositivo serie COM o re-asigna uno autorizado libre.
|
|
*/
|
|
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);
|
|
}
|
|
|
|
// 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;
|
|
}
|
|
|
|
async _openPortOnSlot(slot) {
|
|
if (!slot || !slot.port) return;
|
|
|
|
// 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';
|
|
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;
|
|
|
|
// 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++) {
|
|
const rawCode = parts[i].trim();
|
|
if (rawCode.length >= 2) {
|
|
this._dispatchCode(slot, rawCode);
|
|
}
|
|
}
|
|
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) {
|
|
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();
|
|
|
|
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.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;
|
|
}
|
|
|
|
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);
|