import os import time from datetime import datetime import cv2 import config from camara import CamaraRTSP from detector_movimiento import DetectorMovimiento from notificador import disparar_webhook_alexa, enviar_telegram USAR_YOLO = False if USAR_YOLO: from detector_persona import DetectorPersona def dentro_de_franja_horaria() -> bool: hora_actual = datetime.now().hour inicio = config.HORA_INICIO fin = config.HORA_FIN if inicio < fin: return inicio <= hora_actual < fin return hora_actual >= inicio or hora_actual < fin def main(): if not config.CAMARAS: print("No hay cámaras configuradas en .env") return os.makedirs(config.SNAPSHOT_DIR, exist_ok=True) camaras = [CamaraRTSP(c["rtsp"], c["nombre"]) for c in config.CAMARAS] detectores = [] ultima_alerta = {} for i, c in enumerate(config.CAMARAS): detectores.append(DetectorPersona() if USAR_YOLO else DetectorMovimiento()) ultima_alerta[i] = 0 print("Sistema de vigilancia iniciado. Franja activa: " f"{config.HORA_INICIO}:00 - {config.HORA_FIN}:00") while True: if not dentro_de_franja_horaria(): time.sleep(30) continue for i, cam in enumerate(camaras): frame = cam.leer_frame() if frame is None: continue detector = detectores[i] detectado = ( detector.hay_persona(frame) if USAR_YOLO else detector.hay_movimiento(frame) ) ahora = time.time() if detectado and (ahora - ultima_alerta[i] > config.COOLDOWN): ts = datetime.now().strftime("%Y%m%d_%H%M%S") ruta = os.path.join( config.SNAPSHOT_DIR, f"snapshot_{cam.nombre}_{ts}.jpg" ) cv2_ok = True try: cv2.imwrite(ruta, frame) except Exception as e: cv2_ok = False print(f"[{cam.nombre}] Error guardando snapshot: {e}") tipo = "persona" if USAR_YOLO else "movimiento" texto = f"⚠️ Detección de {tipo} en {cam.nombre} - {ts}" if cv2_ok: enviar_telegram(ruta, texto) disparar_webhook_alexa(texto) ultima_alerta[i] = ahora print(texto) time.sleep(0.5) if __name__ == "__main__": main()