feat(reception): add multi-serial scanner for up to 4 COM ports and universal Argentine DNI parser (v3.8.52)
This commit is contained in:
@@ -1,186 +1,307 @@
|
||||
/**
|
||||
* serial-scanner.js — Módulo de Lector Óptico y Escáner QR por Puerto Serie (COM)
|
||||
* 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.
|
||||
* 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/
|
||||
* 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 SerialBarcodeScanner {
|
||||
constructor(options = {}) {
|
||||
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._initDisconnectListener();
|
||||
this._initGlobalDisconnectListener();
|
||||
}
|
||||
|
||||
isSupported() {
|
||||
return typeof navigator !== 'undefined' && 'serial' in navigator;
|
||||
}
|
||||
|
||||
_initDisconnectListener() {
|
||||
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) => {
|
||||
if (this.port && event.target === this.port) {
|
||||
this._notifyStatus('DISCONNECTED', 'Puerto serie desconectado físicamente.');
|
||||
this.disconnect();
|
||||
const disconnectedSlot = this.slots.find(s => s.port === event.target);
|
||||
if (disconnectedSlot) {
|
||||
this.disconnectSlot(disconnectedSlot.id, 'Dispositivo serie desconectado físicamente.');
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
_notifyStatus(status, message, details = {}) {
|
||||
_notifyStatus(slot, message, extra = {}) {
|
||||
if (typeof this.onStatusChanged === 'function') {
|
||||
this.onStatusChanged({ status, message, ...details });
|
||||
this.onStatusChanged({
|
||||
slotId: slot.id,
|
||||
slotName: slot.name,
|
||||
status: slot.status,
|
||||
message: message || '',
|
||||
baudRate: slot.baudRate,
|
||||
totalConnected: this.getConnectedCount(),
|
||||
...extra
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async autoConnectIfAuthorized() {
|
||||
if (!this.isSupported()) return false;
|
||||
/**
|
||||
* 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) {
|
||||
this.port = ports[0];
|
||||
await this._openPort();
|
||||
return true;
|
||||
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('[SerialScanner] Autoconnect notice:', err.message);
|
||||
console.warn('[MultiSerialScanner] Error consultando puertos autorizados:', err);
|
||||
return 0;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
async requestAndConnect(baudRate = null) {
|
||||
/**
|
||||
* 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á soportada en este navegador. Utiliza Google Chrome o Microsoft Edge.');
|
||||
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) {
|
||||
this.baudRate = parseInt(baudRate, 10) || 9600;
|
||||
slot.baudRate = parseInt(baudRate, 10) || 9600;
|
||||
}
|
||||
|
||||
// Desconectar puerto previo si estuviera activo
|
||||
if (this.port) {
|
||||
await this.disconnect();
|
||||
// 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 COM
|
||||
this.port = await navigator.serial.requestPort();
|
||||
await this._openPort();
|
||||
return this.port;
|
||||
// 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 _openPort() {
|
||||
if (!this.port) return;
|
||||
async _openPortOnSlot(slot) {
|
||||
if (!slot || !slot.port) return;
|
||||
|
||||
await this.port.open({
|
||||
baudRate: this.baudRate,
|
||||
await slot.port.open({
|
||||
baudRate: slot.baudRate,
|
||||
dataBits: 8,
|
||||
stopBits: 1,
|
||||
parity: 'none',
|
||||
bufferSize: 1024
|
||||
bufferSize: 2048
|
||||
});
|
||||
|
||||
this.keepReading = true;
|
||||
this._notifyStatus('CONNECTED', `Puerto serie conectado a ${this.baudRate} baudios.`, {
|
||||
baudRate: this.baudRate
|
||||
});
|
||||
slot.keepReading = true;
|
||||
slot.status = 'CONNECTED';
|
||||
this._notifyStatus(slot, `Lector COM conectado a ${slot.baudRate} baudios.`);
|
||||
|
||||
this._startReadingLoop();
|
||||
this._startReadingLoop(slot);
|
||||
}
|
||||
|
||||
async _startReadingLoop() {
|
||||
while (this.port && this.port.readable && this.keepReading) {
|
||||
async _startReadingLoop(slot) {
|
||||
while (slot.port && slot.port.readable && slot.keepReading) {
|
||||
const textDecoder = new TextDecoderStream();
|
||||
this.readableStreamClosed = this.port.readable.pipeTo(textDecoder.writable);
|
||||
this.reader = textDecoder.readable.getReader();
|
||||
slot.readableStreamClosed = slot.port.readable.pipeTo(textDecoder.writable);
|
||||
slot.reader = textDecoder.readable.getReader();
|
||||
|
||||
try {
|
||||
while (this.keepReading) {
|
||||
const { value, done } = await this.reader.read();
|
||||
while (slot.keepReading) {
|
||||
const { value, done } = await slot.reader.read();
|
||||
if (done) break;
|
||||
if (value) {
|
||||
this._handleIncomingText(value);
|
||||
this._handleIncomingText(slot, value);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (this.keepReading) {
|
||||
console.error('[SerialScanner] Error en lectura serie:', error);
|
||||
if (slot.keepReading) {
|
||||
console.error(`[MultiSerialScanner] Error en lectura de slot ${slot.id}:`, error);
|
||||
if (typeof this.onError === 'function') {
|
||||
this.onError(error);
|
||||
this.onError(error, slot);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
this.reader.releaseLock();
|
||||
slot.reader.releaseLock();
|
||||
} catch (e) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_handleIncomingText(chunk) {
|
||||
this.buffer += chunk;
|
||||
_handleIncomingText(slot, chunk) {
|
||||
slot.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]+/);
|
||||
// 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(rawCode);
|
||||
this._dispatchCode(slot, rawCode);
|
||||
}
|
||||
}
|
||||
this.buffer = parts[parts.length - 1];
|
||||
slot.buffer = parts[parts.length - 1];
|
||||
}
|
||||
}
|
||||
|
||||
_dispatchCode(code) {
|
||||
// Normalizar scancodes si fuera necesario
|
||||
_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);
|
||||
this.onCodeScanned(cleanCode, {
|
||||
slotId: slot.id,
|
||||
slotName: slot.name,
|
||||
timestamp: slot.lastScannedAt
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async disconnect() {
|
||||
this.keepReading = false;
|
||||
async disconnectSlot(slotId, reason = 'Desconectado por el usuario') {
|
||||
const slot = this.getSlot(slotId);
|
||||
if (!slot) return;
|
||||
|
||||
if (this.reader) {
|
||||
slot.keepReading = false;
|
||||
slot.status = 'DISCONNECTED';
|
||||
|
||||
if (slot.reader) {
|
||||
try {
|
||||
await this.reader.cancel();
|
||||
await slot.reader.cancel();
|
||||
} catch (e) {}
|
||||
this.reader = null;
|
||||
slot.reader = null;
|
||||
}
|
||||
|
||||
if (this.readableStreamClosed) {
|
||||
if (slot.readableStreamClosed) {
|
||||
try {
|
||||
await this.readableStreamClosed.catch(() => {});
|
||||
await slot.readableStreamClosed.catch(() => {});
|
||||
} catch (e) {}
|
||||
this.readableStreamClosed = null;
|
||||
slot.readableStreamClosed = null;
|
||||
}
|
||||
|
||||
if (this.port) {
|
||||
if (slot.port) {
|
||||
try {
|
||||
await this.port.close();
|
||||
await slot.port.close();
|
||||
} catch (e) {}
|
||||
this.port = null;
|
||||
slot.port = null;
|
||||
}
|
||||
|
||||
this.buffer = '';
|
||||
this._notifyStatus('DISCONNECTED', 'Puerto serie desconectado.');
|
||||
slot.buffer = '';
|
||||
this._notifyStatus(slot, reason);
|
||||
}
|
||||
|
||||
async disconnectAll() {
|
||||
for (const slot of this.slots) {
|
||||
if (slot.isConnected()) {
|
||||
await this.disconnectSlot(slot.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Exportar al objeto global de ventana
|
||||
window.SerialBarcodeScanner = SerialBarcodeScanner;
|
||||
// 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);
|
||||
|
||||
Reference in New Issue
Block a user