Files
OnEverControl/backend/app/services/hardware_service.py
T

368 lines
14 KiB
Python

# ==============================================================================
# Servicio de Integración de Hardware Industrial (ST1660 / pdtmdl)
# ==============================================================================
import time
from typing import Tuple, Dict, Any, Optional
from app.core.database import db_session
ASCII_STX = "\x02" # Start of text
ASCII_EOF = "\x03" # End of file
def calcular_checksum(comando: str) -> str:
"""Calcula el checksum de 2 dígitos hexadecimales idéntico a VB6 Protocolo.cls."""
raw = comando.encode("latin-1", errors="ignore")
checksum = 0
for b in raw:
checksum = (checksum + b) & 0xFF
checksum = ((0xFF - checksum) + 1) & 0xFF
return f"{checksum:02X}"
def formatear_comando_hardware(direccion: int, comando_payload: str) -> str:
"""Genera la trama física: STX + Addr(2) + Payload + CS(2) + EOF."""
direccion_str = f"{direccion:02d}"
base = f"{ASCII_STX}{direccion_str}{comando_payload}"
cs = calcular_checksum(base)
return f"{base}{cs}{ASCII_EOF}"
class HardwareService:
@staticmethod
def obtener_info_modulo(modulo_id: int) -> Optional[Dict[str, Any]]:
"""Obtiene address, tipo y configuración del módulo desde la tabla `mdl`."""
query = """
SELECT m.ModuloID, m.Nombre, m.Address, m.ModuloEntradaID, m.ModuloSalidaID,
m.duracion_pulso, m.ValidacionTicket
FROM mdl m
WHERE m.ModuloID = %s
"""
with db_session() as conn:
cursor = conn.cursor(as_dict=True)
cursor.execute(query, (modulo_id,))
return cursor.fetchone()
@classmethod
def obtener_tipo_acceso(cls, modulo_id: int) -> int:
"""
Obtiene el tipo_acceso_id (CategoriaID = 15 de MdlCatVal) resolviendo si
es un módulo virtual hacia su módulo físico asociado (ModuloEntradaID o ModuloSalidaID).
Valores estándar de CatVal (Cat 15):
1: Puerta
2: Molinete
7: Molinete Club
3: Barrera de Estado
4: Controlado
5: Barrera Pulso
6: Barrera Doble Pulso
"""
if not modulo_id:
return 0
mdl = cls.obtener_info_modulo(modulo_id)
if not mdl:
return 0
cat_map = {}
try:
with db_session() as conn:
cursor = conn.cursor()
cursor.execute(
"SELECT CategoriaID, ValorID FROM MdlCatVal WHERE ModuloID = %s",
(modulo_id,),
)
cat_map = {row[0]: row[1] for row in cursor.fetchall()}
except Exception:
pass
tipo_modulo_id = cat_map.get(2, 0)
sentido_id = cat_map.get(4, 0)
nombre_upper = (mdl.get("Nombre") or "").upper()
target_id = modulo_id
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"]
target_cat_map = {}
if target_id != modulo_id:
try:
with db_session() as conn:
cursor = conn.cursor()
cursor.execute(
"SELECT CategoriaID, ValorID FROM MdlCatVal WHERE ModuloID = %s",
(target_id,),
)
target_cat_map = {row[0]: row[1] for row in cursor.fetchall()}
except Exception:
pass
else:
target_cat_map = cat_map
tipo_acceso = target_cat_map.get(15) or cat_map.get(15, 3)
return int(tipo_acceso)
@classmethod
def es_acceso_peatonal(cls, modulo_id: int) -> bool:
"""
Devuelve True si el acceso está configurado como Puerta (1), Molinete (2) o Molinete Club (7).
Idéntico a pct_view.py:2862 (`tipo_acc_mod in (1, 2, 7)`).
"""
tipo_acceso = cls.obtener_tipo_acceso(modulo_id)
return tipo_acceso in (1, 2, 7)
@classmethod
def encolar_apertura(
cls, modulo_id: int, ticket_id: int = 0, sin_ticket: bool = False
) -> 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 de inmediato.
Aplica exactamente las mismas reglas de vinculación virtual, tipo de acceso,
firmware (PARK vs PASS) y despacho de ticket T9 que el puesto de control de escritorio.
"""
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"}
# 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 CategoriaID, ValorID FROM MdlCatVal WHERE ModuloID = %s",
(modulo_id,),
)
cat_map = {row[0]: row[1] for row in cursor.fetchall()}
except Exception:
pass
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
# 3. Categorías del módulo destino físico
target_cat_map = {}
if target_id != modulo_id:
try:
with db_session() as conn:
cursor = conn.cursor()
cursor.execute(
"SELECT CategoriaID, ValorID FROM MdlCatVal WHERE ModuloID = %s",
(target_id,),
)
target_cat_map = {row[0]: row[1] for row in cursor.fetchall()}
except Exception:
pass
else:
target_cat_map = cat_map
address = target_mdl.get("Address", 1)
duracion = target_mdl.get("duracion_pulso") or 500
# CategoriaID 2: 1 = PASS (Access), 5 = PARK
is_pass = (target_cat_map.get(2, 0) == 1)
# CategoriaID 15: Tipo Acceso (1: Puerta, 2/7: Molinete / Molinete Club, 3: Barrera Estado, 5: Barrera Pulso, 6: Barrera Doble Pulso)
tipo_acceso = target_cat_map.get(15) or cat_map.get(15, 3)
# CategoriaID 3: Tipo Identificación (1: Proximidad / Tótem Ticket)
tipo_identificacion = cat_map.get(3, 0) or target_cat_map.get(3, 0)
# 4. Mapeo de comando según firmware y tipo de acceso (idéntico a pct_repository.py de OemspotPySYS)
if is_pass:
if tipo_acceso == 1: # Puerta
dur_ds = max(1, duracion // 100)
payload = f"V6{dur_ds:02d}"
elif tipo_acceso in (2, 7): # Molinete / Molinete Club
payload = "V5"
elif tipo_acceso == 3: # Barrera Estado
payload = "V9"
elif tipo_acceso == 6: # Barrera Doble Pulso
payload = "V8"
else: # Barrera Pulso (5) o Controlado (4) o Default
payload = "V3"
else:
# ST1660 PARK (o Default)
if tipo_acceso == 1: # Puerta
payload = "O6"
elif tipo_acceso in (2, 7): # Molinete / Molinete Club
payload = "O5"
elif tipo_acceso == 3: # Barrera Estado
payload = "O1"
elif tipo_acceso == 6: # Barrera Doble Pulso
payload = "O8"
else: # Barrera Pulso (5) o Controlado (4) o Default
payload = "O3"
trama_comando = formatear_comando_hardware(address, payload)
sql_insert = """
INSERT INTO pdtmdl (PdtMdlID, ModuloID, Comando, Inmediato, Extra)
VALUES ((SELECT COALESCE(MAX(PdtMdlID), 0) + 1 FROM pdtmdl), %s, %s, 1, %s)
"""
extra_info = str(ticket_id or 0)[:20]
trama_ticket = None
with db_session() as conn:
cursor = conn.cursor()
# Encolar para la placa física real (ej: Modulo 100009 con Addr 20)
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
if target_id != modulo_id:
cursor.execute(sql_insert, (modulo_id, trama_comando, extra_info))
# Tótem de tickets / código de barras si corresponde y no es sin_ticket (regla exacta de OemspotPySYS)
if not sin_ticket and tipo_identificacion == 1 and ticket_id > 0:
trama_ticket = formatear_comando_hardware(address, "T9")
cursor.execute(sql_insert, (target_id, trama_ticket, 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,
"tipo_acceso": tipo_acceso,
"is_pass": is_pass,
"payload": payload,
"comando_trama": trama_comando,
"trama_ticket": trama_ticket,
"latencia_ms": round(latencia, 2),
}
@classmethod
def encolar_cierre(cls, modulo_id: int, ticket_id: int = 0) -> Tuple[bool, Dict[str, Any]]:
"""
Encola un comando de cierre forzado de barrera/molinete en la tabla `pdtmdl`
con tramas C0..C6 según tipo_acceso y firmware (PASS vs PARK).
Paridad 1:1 con pct_repository.py:encolar_comando_cierre_modulo (v1.2.3).
"""
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"}
cat_map = {}
try:
with db_session() as conn:
cursor = conn.cursor()
cursor.execute(
"SELECT CategoriaID, ValorID FROM MdlCatVal WHERE ModuloID = %s",
(modulo_id,),
)
cat_map = {row[0]: row[1] for row in cursor.fetchall()}
except Exception:
pass
tipo_modulo_id = cat_map.get(2, 0)
sentido_id = cat_map.get(4, 0)
nombre_upper = (mdl.get("Nombre") or "").upper()
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
target_cat_map = {}
if target_id != modulo_id:
try:
with db_session() as conn:
cursor = conn.cursor()
cursor.execute(
"SELECT CategoriaID, ValorID FROM MdlCatVal WHERE ModuloID = %s",
(target_id,),
)
target_cat_map = {row[0]: row[1] for row in cursor.fetchall()}
except Exception:
pass
else:
target_cat_map = cat_map
address = target_mdl.get("Address", 1)
is_pass = (target_cat_map.get(2, 0) == 1)
tipo_acceso = target_cat_map.get(15) or cat_map.get(15, 3)
if is_pass:
if tipo_acceso == 1:
payload = "C4"
elif tipo_acceso in (2, 7):
payload = "C2"
elif tipo_acceso in (3, 4):
payload = "C1"
elif tipo_acceso == 6:
payload = "C0"
else:
payload = "C3"
else:
if tipo_acceso == 1:
payload = "C6"
elif tipo_acceso in (2, 7):
payload = "C5"
elif tipo_acceso in (3, 4):
payload = "C1"
elif tipo_acceso == 6:
payload = "C0"
else:
payload = "C3"
trama_comando = formatear_comando_hardware(address, payload)
sql_insert = """
INSERT INTO pdtmdl (PdtMdlID, ModuloID, Comando, Inmediato, Extra)
VALUES ((SELECT COALESCE(MAX(PdtMdlID), 0) + 1 FROM pdtmdl), %s, %s, 1, %s)
"""
extra_info = str(ticket_id or 0)[:20]
with db_session() as conn:
cursor = conn.cursor()
cursor.execute(sql_insert, (target_id, trama_comando, extra_info))
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,
"tipo_acceso": tipo_acceso,
"is_pass": is_pass,
"payload": payload,
"comando_trama": trama_comando,
"latencia_ms": round(latencia, 2),
}