fix(hardware-camera): resolucion de modulos virtuales a fisicos para WPC y escaneo robusto de webcam

This commit is contained in:
Carlos Tello
2026-10-14 00:51:56 -03:00
parent e949df134b
commit 2b40677dae
2 changed files with 248 additions and 161 deletions
+42 -13
View File
@@ -46,32 +46,51 @@ class HardwareService:
def encolar_apertura(cls, modulo_id: int, ticket_id: int = 0) -> Tuple[bool, Dict[str, Any]]:
"""
Encola un comando de apertura de barrera/molinete en la tabla `pdtmdl`
para que OnEverWPC lo despache al bus RS-485 físico en < 50ms.
para que OnEverWPC lo despache al bus RS-485 físico de inmediato.
Resuelve automáticamente módulos virtuales (98, 97) hacia sus placas físicas (20, 21).
"""
t_start = time.perf_counter()
mdl = cls.obtener_info_modulo(modulo_id)
if not mdl:
return False, {"error": f"Módulo {modulo_id} no encontrado en base de datos"}
address = mdl.get("Address", 1)
duracion = mdl.get("duracion_pulso") or 500
# Verificamos si es variante PASS (Access) o PARK (Default)
is_pass = False
# 1. Obtener categorías de MdlCatVal para verificar si es Módulo Virtual (Cat 2 = 6) y Sentido (Cat 4)
cat_map = {}
try:
with db_session() as conn:
cursor = conn.cursor()
cursor.execute(
"SELECT ValorID FROM MdlCatVal WHERE ModuloID = %s AND CategoriaID = 2",
"SELECT CategoriaID, ValorID FROM MdlCatVal WHERE ModuloID = %s",
(modulo_id,),
)
row = cursor.fetchone()
is_pass = (row is not None and int(row[0]) == 1)
cat_map = {row[0]: row[1] for row in cursor.fetchall()}
except Exception:
is_pass = False
pass
# Determinación del payload de pulso según protocolo
payload = "V3" if is_pass else "O3"
tipo_modulo_id = cat_map.get(2, 0)
sentido_id = cat_map.get(4, 0)
nombre_upper = (mdl.get("Nombre") or "").upper()
# 2. Si es Módulo Virtual (tipo 6 o dirección virtual >= 90), resolver el módulo físico real
target_id = modulo_id
target_mdl = mdl
if tipo_modulo_id == 6 or mdl.get("Address", 0) >= 90:
if (sentido_id == 1 or "ENTRADA" in nombre_upper or "INGRESO" in nombre_upper) and mdl.get("ModuloEntradaID"):
target_id = mdl["ModuloEntradaID"]
elif (sentido_id == 2 or "SALIDA" in nombre_upper or "EGRESO" in nombre_upper) and mdl.get("ModuloSalidaID"):
target_id = mdl["ModuloSalidaID"]
if target_id != modulo_id:
fisico = cls.obtener_info_modulo(target_id)
if fisico:
target_mdl = fisico
address = target_mdl.get("Address", 1)
duracion = target_mdl.get("duracion_pulso") or 500
# 3. Comando universal de apertura por pulso de barrera (O3)
payload = "O3"
trama_comando = formatear_comando_hardware(address, payload)
sql_insert = """
@@ -82,13 +101,23 @@ class HardwareService:
with db_session() as conn:
cursor = conn.cursor()
cursor.execute(sql_insert, (modulo_id, trama_comando, extra_info))
# Encolar para la placa física real (ej: Modulo 100009 con Addr 20 o Modulo 100013 con Addr 21)
cursor.execute(sql_insert, (target_id, trama_comando, extra_info))
# Si el módulo llamado era virtual, encolar también una entrada con el ID virtual
# pero con la trama física, garantizando compatibilidad con cualquier hilo de sondeo
if target_id != modulo_id:
cursor.execute(sql_insert, (modulo_id, trama_comando, extra_info))
latencia = (time.perf_counter() - t_start) * 1000
return True, {
"modulo_id": modulo_id,
"modulo_solicitado": modulo_id,
"modulo_fisico_target": target_id,
"address": address,
"address_fisico": address,
"payload": payload,
"comando_trama": trama_comando,
"latencia_ms": round(latencia, 2),
}
@@ -1,10 +1,17 @@
// ==============================================================================
// Modal de Escaneo Óptico con Cámara para Tablets (Android) y Windows
// Soporte de Video en Vivo (WebRTC) + ZXing Library (PDF417 / QR) + Captura de Foto Nativa
// Soporte de Video en Vivo (WebRTC) + ZXing Core Engine (PDF417 / QR) + Captura Nativa
// Cumple con el sistema de diseño OnEver (C:\Workspace\OemspotPySYS\styles\design_system.py)
// ==============================================================================
import React, { useEffect, useRef, useState, useCallback } from 'react';
import { BrowserMultiFormatReader, BarcodeFormat, DecodeHintType } from '@zxing/library';
import {
MultiFormatReader,
BarcodeFormat,
DecodeHintType,
RGBLuminanceSource,
BinaryBitmap,
HybridBinarizer,
} from '@zxing/library';
import { accessApi } from '../../api/accessApi';
import { DNIParsedResult } from '../../types';
@@ -21,8 +28,10 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
}) => {
const videoRef = useRef<HTMLVideoElement | null>(null);
const streamRef = useRef<MediaStream | null>(null);
const zxingReaderRef = useRef<BrowserMultiFormatReader | null>(null);
const fileInputRef = useRef<HTMLInputElement | null>(null);
const timerRef = useRef<number | null>(null);
const zxingReaderRef = useRef<MultiFormatReader | null>(null);
const canvasRef = useRef<HTMLCanvasElement | null>(null);
const [hasCamera, setHasCamera] = useState<boolean>(true);
const [insecureContextWarning, setInsecureContextWarning] = useState<boolean>(false);
@@ -33,8 +42,9 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
const [manualText, setManualText] = useState<string>('');
const [availableDevices, setAvailableDevices] = useState<MediaDeviceInfo[]>([]);
const [selectedDeviceId, setSelectedDeviceId] = useState<string>('');
const [activeCameraLabel, setActiveCameraLabel] = useState<string>('');
// Inicializar lector ZXing configurado para DNI Argentino (PDF417 + QR + Code128)
// Inicializar motor ZXing configurado para DNI Argentino (PDF417 + QR + Code128)
useEffect(() => {
const hints = new Map();
hints.set(DecodeHintType.POSSIBLE_FORMATS, [
@@ -44,33 +54,26 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
]);
hints.set(DecodeHintType.TRY_HARDER, true);
zxingReaderRef.current = new BrowserMultiFormatReader(hints, 250);
const reader = new MultiFormatReader();
reader.setHints(hints);
zxingReaderRef.current = reader;
return () => {
if (zxingReaderRef.current) {
try {
zxingReaderRef.current.reset();
} catch {
// Cleanup
}
}
};
// Crear canvas offscreen reutilizable
const offscreenCanvas = document.createElement('canvas');
canvasRef.current = offscreenCanvas;
}, []);
const stopCamera = useCallback(() => {
if (zxingReaderRef.current) {
try {
zxingReaderRef.current.reset();
} catch {
// Ignorar
}
if (timerRef.current) {
window.clearInterval(timerRef.current);
timerRef.current = null;
}
if (streamRef.current) {
streamRef.current.getTracks().forEach((track) => {
try {
track.stop();
} catch {
// Ignorar
// Cleanup seguro
}
});
streamRef.current = null;
@@ -92,7 +95,7 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
onScanSuccess(res);
onClose();
} else {
setErrorMsg(`Código detectado pero no es un DNI argentino válido (${rawText.slice(0, 30)}...).`);
setErrorMsg(`Código detectado pero no corresponde a un DNI argentino válido (${rawText.slice(0, 30)}...).`);
}
} catch (err: any) {
setErrorMsg(err.message || 'Error al interpretar el código escaneado.');
@@ -103,110 +106,163 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
[isProcessing, stopCamera, onScanSuccess, onClose]
);
const startCamera = useCallback(async (deviceIdToUse?: string) => {
setErrorMsg(null);
setHasCamera(true);
// Verificar si el navegador permite acceso a mediaDevices
const isSecure = window.isSecureContext || window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
setHasCamera(false);
if (!isSecure) {
setInsecureContextWarning(true);
setErrorMsg(
'El navegador bloqueó la cámara porque la conexión es HTTP sobre red local. Utilice el botón "📷 Tomar Foto con Cámara" para escanear sin restricciones de seguridad.'
);
} else {
setErrorMsg('Dispositivo de video no soportado o bloqueado por el sistema operativo.');
}
return;
}
try {
// 1. Obtener lista de cámaras disponibles si es posible
try {
const devices = await navigator.mediaDevices.enumerateDevices();
const videoDevices = devices.filter((d) => d.kind === 'videoinput');
setAvailableDevices(videoDevices);
} catch {
// En algunos navegadores enumerateDevices requiere haber abierto stream previo
// Decodificar un buffer ImageData mediante ZXing y BarcodeDetector
const decodeFrame = useCallback(
async (ctx: CanvasRenderingContext2D, width: number, height: number): Promise<boolean> => {
// 1. Probar BarcodeDetector nativo si está presente en el navegador (acelerado por GPU)
if ('BarcodeDetector' in window) {
try {
const detector = new (window as any).BarcodeDetector({
formats: ['pdf417', 'qr_code', 'code_128'],
});
const barcodes = await detector.detect(ctx.canvas);
if (barcodes.length > 0 && barcodes[0].rawValue) {
handleDecodedString(barcodes[0].rawValue);
return true;
}
} catch {
// Continuar con ZXing como motor primario
}
}
// 2. Definir constraints (con fallback para Windows laptop vs Android tablet)
let stream: MediaStream | null = null;
// 2. Probar decodificador ZXing sobre los píxeles directos
if (zxingReaderRef.current) {
try {
const imgData = ctx.getImageData(0, 0, width, height);
const luminanceSource = new RGBLuminanceSource(imgData.data, width, height);
const binaryBitmap = new BinaryBitmap(new HybridBinarizer(luminanceSource));
const result = zxingReaderRef.current.decode(binaryBitmap);
if (result && result.getText()) {
handleDecodedString(result.getText());
return true;
}
} catch {
// NotFoundException en cada frame sin código
}
}
return false;
},
[handleDecodedString]
);
const startCamera = useCallback(
async (deviceIdToUse?: string) => {
setErrorMsg(null);
setHasCamera(true);
const isSecure =
window.isSecureContext ||
window.location.hostname === 'localhost' ||
window.location.hostname === '127.0.0.1';
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
setHasCamera(false);
if (!isSecure) {
setInsecureContextWarning(true);
setErrorMsg(
'El navegador bloqueó la cámara en vivo porque la conexión es HTTP sobre red local. Utilice el botón "📸 Capturar Foto de DNI" o ingrese por HTTPS en el puerto 8443.'
);
} else {
setErrorMsg('Dispositivo de video no soportado o bloqueado en este sistema.');
}
return;
}
try {
// Intento 1: Cámara trasera de tablet / dispositivo específico
const videoConstraints: MediaTrackConstraints = deviceIdToUse
? { deviceId: { exact: deviceIdToUse } }
let stream: MediaStream | null = null;
// Estrategia de Constraints flexible:
// Intento 1: Dispositivo seleccionado o cámara trasera
const constraints1: MediaStreamConstraints = deviceIdToUse
? { video: { deviceId: { exact: deviceIdToUse } }, audio: false }
: {
facingMode: { ideal: 'environment' },
width: { ideal: 1280 },
height: { ideal: 720 },
video: {
facingMode: { ideal: 'environment' },
width: { ideal: 1280 },
height: { ideal: 720 },
},
audio: false,
};
stream = await navigator.mediaDevices.getUserMedia({
video: videoConstraints,
audio: false,
});
} catch {
// Intento 2: Fallback simple para webcam de PC Windows o cámara estándar
try {
stream = await navigator.mediaDevices.getUserMedia(constraints1);
} catch {
// Intento 2: Fallback incondicional para webcams Windows / laptop estándar
stream = await navigator.mediaDevices.getUserMedia({
video: true,
audio: false,
});
} catch (innerErr: any) {
throw innerErr;
}
if (!stream) {
throw new Error('No se pudo obtener el flujo de video.');
}
streamRef.current = stream;
// Identificar etiqueta de la cámara activa
const videoTrack = stream.getVideoTracks()[0];
if (videoTrack) {
setActiveCameraLabel(videoTrack.label || 'Cámara activa');
const capabilities = videoTrack.getCapabilities?.() as any;
if (capabilities && capabilities.torch) {
setSupportsTorch(true);
}
}
// Enumerar dispositivos disponibles (ahora con permisos ya otorgados)
try {
const allDevices = await navigator.mediaDevices.enumerateDevices();
const vInputs = allDevices.filter((d) => d.kind === 'videoinput');
setAvailableDevices(vInputs);
} catch {
// Ignorar si falla enumeración
}
if (videoRef.current) {
videoRef.current.srcObject = stream;
videoRef.current.onloadedmetadata = () => {
videoRef.current?.play().catch(() => {});
};
}
// Iniciar loop de escaneo periódico cada 200ms
if (timerRef.current) window.clearInterval(timerRef.current);
timerRef.current = window.setInterval(async () => {
if (!videoRef.current || videoRef.current.readyState < 2 || isProcessing) return;
const video = videoRef.current;
const canvas = canvasRef.current;
if (!canvas) return;
const width = video.videoWidth || 640;
const height = video.videoHeight || 480;
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d', { willReadFrequently: true });
if (!ctx) return;
ctx.drawImage(video, 0, 0, width, height);
await decodeFrame(ctx, width, height);
}, 200);
} catch (err: any) {
setHasCamera(false);
const name = err.name || '';
if (name === 'NotAllowedError' || name === 'PermissionDeniedError') {
setErrorMsg('Permiso de cámara denegado. Permita el acceso en el candado del navegador.');
} else if (name === 'NotFoundError' || name === 'DevicesNotFoundError') {
setErrorMsg('No se detectó ninguna cámara web conectada al equipo.');
} else if (name === 'NotReadableError') {
setErrorMsg('La cámara está siendo usada por otra aplicación en Windows.');
} else {
setErrorMsg(`Error al iniciar cámara: ${err.message || 'Error desconocido'}`);
}
}
if (!stream) {
throw new Error('No se pudo inicializar el flujo de video.');
}
streamRef.current = stream;
if (videoRef.current) {
videoRef.current.srcObject = stream;
await videoRef.current.play();
}
// Detectar soporte para linterna (torch)
const track = stream.getVideoTracks()[0];
const capabilities = track.getCapabilities?.() as any;
if (capabilities && capabilities.torch) {
setSupportsTorch(true);
}
// Iniciar decodificación continua con ZXing sobre el elemento video
if (zxingReaderRef.current && videoRef.current) {
zxingReaderRef.current.decodeFromVideoElementContinuously(
videoRef.current,
(result: any) => {
if (result) {
const text = result.getText?.() || result.text;
if (text) {
handleDecodedString(text);
}
}
}
);
}
} catch (err: any) {
setHasCamera(false);
const name = err.name || '';
if (name === 'NotAllowedError' || name === 'PermissionDeniedError') {
setErrorMsg('Permiso de cámara denegado. Habilite el acceso en la barra del navegador.');
} else if (name === 'NotFoundError' || name === 'DevicesNotFoundError') {
setErrorMsg('No se detectó ninguna cámara conectada al dispositivo.');
} else if (name === 'NotReadableError') {
setErrorMsg('La cámara está siendo usada por otra aplicación en Windows.');
} else {
setErrorMsg(`No se pudo iniciar la cámara: ${err.message || 'Error desconocido'}`);
}
}
}, [handleDecodedString]);
},
[decodeFrame, isProcessing]
);
// Manejador de captura de foto nativa (funciona sin HTTPS en tablets Android)
const handlePhotoCaptured = async (e: React.ChangeEvent<HTMLInputElement>) => {
@@ -225,30 +281,31 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
return;
}
// Crear imagen temporal para decodificar con ZXing
const img = new Image();
img.src = dataUrl;
img.onload = async () => {
try {
if (zxingReaderRef.current) {
const result = await zxingReaderRef.current.decodeFromImageElement(img);
if (result && result.getText()) {
handleDecodedString(result.getText());
return;
}
}
} catch {
// ZXing no pudo decodificar directo; intentar OCR / backend fallback
const canvas = canvasRef.current || document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d', { willReadFrequently: true });
if (!ctx) {
setIsProcessing(false);
return;
}
// Si el código no fue legible directo de la foto, avisar al usuario
setErrorMsg('No se pudo detectar el código de barras en la foto. Intente con mejor iluminación o acerque el código.');
setIsProcessing(false);
ctx.drawImage(img, 0, 0, img.width, img.height);
const detected = await decodeFrame(ctx, img.width, img.height);
if (!detected) {
setErrorMsg(
'No se detectó el código de barras en la foto. Acerque el DNI con buena iluminación o ingréselo manualmente.'
);
setIsProcessing(false);
}
};
};
reader.readAsDataURL(file);
} catch (err: any) {
setErrorMsg('Error al procesar la imagen capturada.');
} catch {
setErrorMsg('Error al procesar la imagen seleccionada.');
setIsProcessing(false);
}
};
@@ -275,7 +332,7 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
});
setTorchEnabled(nextState);
} catch {
// Ignorar si el dispositivo rechaza el comando
// Ignorar si el dispositivo no soporta linterna
}
};
@@ -310,7 +367,7 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
className="card"
style={{
width: '100%',
maxWidth: '620px',
maxWidth: '640px',
backgroundColor: 'var(--bg-sidebar)',
borderRadius: '10px',
overflow: 'hidden',
@@ -332,13 +389,13 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: '0.65rem' }}>
<span style={{ fontSize: '1.3rem' }}>📷</span>
<span style={{ fontSize: '1.4rem' }}>📷</span>
<div>
<h2 style={{ fontSize: '1.05rem', fontWeight: 700, margin: 0, color: 'var(--text-1)' }}>
<h2 style={{ fontSize: '1.1rem', fontWeight: 700, margin: 0, color: 'var(--text-1)' }}>
Escanear DNI Argentino (Cámara / PDF417)
</h2>
<span style={{ fontSize: '0.75rem', color: 'var(--text-3)' }}>
Soporta DNI tarjeta, PDF417, QR digital y fotos nativas
{activeCameraLabel ? `Cámara: ${activeCameraLabel}` : 'Soporta DNI tarjeta, PDF417, QR digital y fotos'}
</span>
</div>
</div>
@@ -366,7 +423,7 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
style={{
position: 'relative',
width: '100%',
height: '310px',
height: '320px',
backgroundColor: '#000',
display: 'flex',
alignItems: 'center',
@@ -378,6 +435,7 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
<>
<video
ref={videoRef}
autoPlay
playsInline
muted
style={{
@@ -411,18 +469,18 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
border: '1px solid var(--border)',
}}
>
Ubique el código PDF417 o QR aquí
Ubique el código de barras PDF417 o QR aquí
</span>
</div>
</>
) : (
<div style={{ padding: '2rem', textAlign: 'center', color: 'var(--text-2)', maxWidth: '480px' }}>
<div style={{ fontSize: '2.5rem', marginBottom: '0.75rem' }}>📷</div>
<p style={{ fontWeight: 600, color: 'var(--text-1)' }}>Cámara en vivo no inicializada</p>
<p style={{ fontWeight: 600, color: 'var(--text-1)' }}>Cámara en vivo no disponible</p>
<p style={{ fontSize: '0.825rem', marginTop: '0.5rem', color: 'var(--text-3)' }}>
{insecureContextWarning
? 'En red local sin HTTPS, el navegador restringe el streaming continuo. Puede usar la opción de Foto Nativa debajo que opera directamente sin restricciones.'
: 'Puede tomar una foto directa o ingresar el código manualmente abajo.'}
? 'En red local sin HTTPS, el navegador restringe el streaming continuo. Utilice el botón "📸 Capturar Foto de DNI" que abre la cámara de su dispositivo directamente sin restricciones.'
: 'Puede capturar una foto o escribir el DNI abajo.'}
</p>
</div>
)}
@@ -470,7 +528,7 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
{/* Barra de Acciones y Controles Táctiles */}
<div style={{ padding: '1rem', display: 'flex', flexDirection: 'column', gap: '0.75rem', backgroundColor: 'var(--bg-sidebar)' }}>
{/* Selector de cámara si hay múltiples dispositivos */}
{/* Selector de cámara si hay múltiples dispositivos detectados */}
{availableDevices.length > 1 && (
<div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
<span style={{ fontSize: '0.75rem', color: 'var(--text-2)', fontWeight: 600 }}>CÁMARA:</span>
@@ -478,19 +536,19 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
className="input-touch"
value={selectedDeviceId}
onChange={(e) => setSelectedDeviceId(e.target.value)}
style={{ minHeight: '36px', fontSize: '0.85rem' }}
style={{ minHeight: '38px', fontSize: '0.85rem' }}
>
<option value="">(Automática / Trasera)</option>
{availableDevices.map((d) => (
<option key={d.deviceId} value={d.deviceId}>
{d.label || `Cámara ${d.deviceId.slice(0, 6)}...`}
<option value="">(Automática / Principal)</option>
{availableDevices.map((d, idx) => (
<option key={d.deviceId || idx} value={d.deviceId}>
{d.label || `Cámara ${idx + 1}`}
</option>
))}
</select>
</div>
)}
{/* Botones principales: Foto Nativa (Universal) + Linterna */}
{/* Botones principales: Foto Nativa (Universal) + Linterna + Cancelar */}
<div style={{ display: 'flex', gap: '0.65rem' }}>
<input
type="file"
@@ -505,7 +563,7 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
type="button"
className="btn btn-primary"
onClick={() => fileInputRef.current?.click()}
style={{ flex: 1, minHeight: '44px' }}
style={{ flex: 1, minHeight: '46px' }}
title="Abre la cámara nativa de Android / Windows para fotografiar el DNI"
>
📸 Capturar Foto de DNI
@@ -516,7 +574,7 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
type="button"
className="btn btn-secondary"
onClick={toggleTorch}
style={{ minHeight: '44px', padding: '0 0.85rem' }}
style={{ minHeight: '46px', padding: '0 0.85rem' }}
>
{torchEnabled ? '🔦 Apagar' : '💡 Linterna'}
</button>
@@ -529,7 +587,7 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
stopCamera();
onClose();
}}
style={{ minHeight: '44px', padding: '0 1rem' }}
style={{ minHeight: '46px', padding: '0 1rem' }}
>
Cancelar
</button>