diff --git a/backend/app/services/hardware_service.py b/backend/app/services/hardware_service.py index e410c27..4da3c5e 100644 --- a/backend/app/services/hardware_service.py +++ b/backend/app/services/hardware_service.py @@ -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), } diff --git a/frontend/src/components/scanner/CameraScannerModal.tsx b/frontend/src/components/scanner/CameraScannerModal.tsx index f78a522..dda3548 100644 --- a/frontend/src/components/scanner/CameraScannerModal.tsx +++ b/frontend/src/components/scanner/CameraScannerModal.tsx @@ -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 = ({ }) => { const videoRef = useRef(null); const streamRef = useRef(null); - const zxingReaderRef = useRef(null); const fileInputRef = useRef(null); + const timerRef = useRef(null); + const zxingReaderRef = useRef(null); + const canvasRef = useRef(null); const [hasCamera, setHasCamera] = useState(true); const [insecureContextWarning, setInsecureContextWarning] = useState(false); @@ -33,8 +42,9 @@ export const CameraScannerModal: React.FC = ({ const [manualText, setManualText] = useState(''); const [availableDevices, setAvailableDevices] = useState([]); const [selectedDeviceId, setSelectedDeviceId] = useState(''); + const [activeCameraLabel, setActiveCameraLabel] = useState(''); - // 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 = ({ ]); 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 = ({ 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 = ({ [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 => { + // 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) => { @@ -225,30 +281,31 @@ export const CameraScannerModal: React.FC = ({ 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 = ({ }); 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 = ({ 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 = ({ }} >
- 📷 + 📷
-

+

Escanear DNI Argentino (Cámara / PDF417)

- Soporta DNI tarjeta, PDF417, QR digital y fotos nativas + {activeCameraLabel ? `Cámara: ${activeCameraLabel}` : 'Soporta DNI tarjeta, PDF417, QR digital y fotos'}
@@ -366,7 +423,7 @@ export const CameraScannerModal: React.FC = ({ style={{ position: 'relative', width: '100%', - height: '310px', + height: '320px', backgroundColor: '#000', display: 'flex', alignItems: 'center', @@ -378,6 +435,7 @@ export const CameraScannerModal: React.FC = ({ <>