| 
									
										
										
										
											2025-09-02 18:51:50 +08:00
										 |  |  |  | import asyncio | 
					
						
							| 
									
										
										
										
											2025-09-03 16:27:53 +08:00
										 |  |  |  | import datetime | 
					
						
							| 
									
										
										
										
											2025-09-02 18:51:50 +08:00
										 |  |  |  | import json | 
					
						
							| 
									
										
										
										
											2025-09-03 17:02:22 +08:00
										 |  |  |  | import os | 
					
						
							| 
									
										
										
										
											2025-09-02 18:51:50 +08:00
										 |  |  |  | from contextlib import asynccontextmanager | 
					
						
							| 
									
										
										
										
											2025-09-09 16:30:12 +08:00
										 |  |  |  | from typing import Dict, Optional | 
					
						
							| 
									
										
										
										
											2025-09-04 12:29:27 +08:00
										 |  |  |  | from service.device_service import update_online_status_by_ip, increment_alarm_count_by_ip | 
					
						
							|  |  |  |  | from service.device_action_service import add_device_action | 
					
						
							|  |  |  |  | from schema.device_action_schema import DeviceActionCreate | 
					
						
							| 
									
										
										
										
											2025-09-09 16:30:12 +08:00
										 |  |  |  | from core.all import detect, load_model | 
					
						
							| 
									
										
										
										
											2025-09-02 18:51:50 +08:00
										 |  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-03 17:02:22 +08:00
										 |  |  |  | import cv2 | 
					
						
							| 
									
										
										
										
											2025-09-03 16:27:53 +08:00
										 |  |  |  | import numpy as np | 
					
						
							|  |  |  |  | from fastapi import WebSocket, APIRouter, WebSocketDisconnect, FastAPI | 
					
						
							| 
									
										
										
										
											2025-09-03 17:02:22 +08:00
										 |  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  | # 配置常量 | 
					
						
							|  |  |  |  | HEARTBEAT_INTERVAL = 30  # 心跳检查间隔(秒) | 
					
						
							| 
									
										
										
										
											2025-09-03 17:02:22 +08:00
										 |  |  |  | HEARTBEAT_TIMEOUT = 600  # 客户端超时阈值(秒) | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  | WS_ENDPOINT = "/ws"  # WebSocket端点路径 | 
					
						
							|  |  |  |  | FRAME_QUEUE_SIZE = 1  # 帧队列大小限制 | 
					
						
							|  |  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-04 12:29:27 +08:00
										 |  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-09 16:30:12 +08:00
										 |  |  |  | # 工具函数: 获取格式化时间字符串 | 
					
						
							| 
									
										
										
										
											2025-09-04 17:29:52 +08:00
										 |  |  |  | def get_current_time_str() -> str: | 
					
						
							|  |  |  |  |     return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") | 
					
						
							|  |  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-04 17:29:52 +08:00
										 |  |  |  | def get_current_time_file_str() -> str: | 
					
						
							|  |  |  |  |     return datetime.datetime.now().strftime("%Y%m%d_%H%M%S_%f") | 
					
						
							|  |  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  | 
 | 
					
						
							|  |  |  |  | # 客户端连接封装 | 
					
						
							| 
									
										
										
										
											2025-09-02 18:51:50 +08:00
										 |  |  |  | class ClientConnection: | 
					
						
							|  |  |  |  |     def __init__(self, websocket: WebSocket, client_ip: str): | 
					
						
							|  |  |  |  |         self.websocket = websocket | 
					
						
							| 
									
										
										
										
											2025-09-10 08:57:56 +08:00
										 |  |  |  |         self.client_ip = client_ip  # 已初始化客户端IP,用于传递给detect | 
					
						
							| 
									
										
										
										
											2025-09-03 16:27:53 +08:00
										 |  |  |  |         self.last_heartbeat = datetime.datetime.now() | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  |         self.frame_queue = asyncio.Queue(maxsize=FRAME_QUEUE_SIZE) | 
					
						
							| 
									
										
										
										
											2025-09-04 12:29:27 +08:00
										 |  |  |  |         self.consumer_task: Optional[asyncio.Task] = None | 
					
						
							| 
									
										
										
										
											2025-09-04 17:08:25 +08:00
										 |  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-02 18:51:50 +08:00
										 |  |  |  |     def update_heartbeat(self): | 
					
						
							| 
									
										
										
										
											2025-09-09 16:30:12 +08:00
										 |  |  |  |         """更新心跳时间""" | 
					
						
							| 
									
										
										
										
											2025-09-02 18:51:50 +08:00
										 |  |  |  |         self.last_heartbeat = datetime.datetime.now() | 
					
						
							|  |  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-03 16:27:53 +08:00
										 |  |  |  |     def is_alive(self) -> bool: | 
					
						
							| 
									
										
										
										
											2025-09-09 16:30:12 +08:00
										 |  |  |  |         """判断客户端是否存活""" | 
					
						
							|  |  |  |  |         timeout_seconds = (datetime.datetime.now() - self.last_heartbeat).total_seconds() | 
					
						
							|  |  |  |  |         return timeout_seconds < HEARTBEAT_TIMEOUT | 
					
						
							| 
									
										
										
										
											2025-09-02 18:51:50 +08:00
										 |  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-03 17:08:28 +08:00
										 |  |  |  |     def start_consumer(self): | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  |         """启动帧消费任务""" | 
					
						
							| 
									
										
										
										
											2025-09-03 17:08:28 +08:00
										 |  |  |  |         self.consumer_task = asyncio.create_task(self.consume_frames()) | 
					
						
							|  |  |  |  |         return self.consumer_task | 
					
						
							|  |  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-04 12:29:27 +08:00
										 |  |  |  |     async def send_frame_permit(self): | 
					
						
							| 
									
										
										
										
											2025-09-09 16:30:12 +08:00
										 |  |  |  |         """发送帧发送许可信号""" | 
					
						
							| 
									
										
										
										
											2025-09-03 18:05:34 +08:00
										 |  |  |  |         try: | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  |             frame_permit_msg = { | 
					
						
							| 
									
										
										
										
											2025-09-04 12:29:27 +08:00
										 |  |  |  |                 "type": "frame", | 
					
						
							|  |  |  |  |                 "timestamp": get_current_time_str(), | 
					
						
							|  |  |  |  |                 "client_ip": self.client_ip | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  |             } | 
					
						
							|  |  |  |  |             await self.websocket.send_json(frame_permit_msg) | 
					
						
							| 
									
										
										
										
											2025-09-09 16:30:12 +08:00
										 |  |  |  |             print(f"[{get_current_time_str()}] 客户端{self.client_ip}: 已发送帧发送许可信号") | 
					
						
							| 
									
										
										
										
											2025-09-03 18:05:34 +08:00
										 |  |  |  |         except Exception as e: | 
					
						
							| 
									
										
										
										
											2025-09-08 17:34:23 +08:00
										 |  |  |  |             print(f"[{get_current_time_str()}] 客户端{self.client_ip}: 帧许可信号发送失败 - {str(e)}") | 
					
						
							| 
									
										
										
										
											2025-09-03 18:05:34 +08:00
										 |  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-03 17:08:28 +08:00
										 |  |  |  |     async def consume_frames(self) -> None: | 
					
						
							| 
									
										
										
										
											2025-09-09 16:30:12 +08:00
										 |  |  |  |         """消费队列中的帧并处理""" | 
					
						
							| 
									
										
										
										
											2025-09-03 17:08:28 +08:00
										 |  |  |  |         try: | 
					
						
							|  |  |  |  |             while True: | 
					
						
							| 
									
										
										
										
											2025-09-09 16:30:12 +08:00
										 |  |  |  |                 # 取出帧并立即发送下一帧许可 | 
					
						
							| 
									
										
										
										
											2025-09-03 17:08:28 +08:00
										 |  |  |  |                 frame_data = await self.frame_queue.get() | 
					
						
							| 
									
										
										
										
											2025-09-09 16:30:12 +08:00
										 |  |  |  |                 await self.send_frame_permit() | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-03 17:08:28 +08:00
										 |  |  |  |                 try: | 
					
						
							|  |  |  |  |                     await self.process_frame(frame_data) | 
					
						
							|  |  |  |  |                 finally: | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  |                     self.frame_queue.task_done() | 
					
						
							|  |  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-03 17:08:28 +08:00
										 |  |  |  |         except asyncio.CancelledError: | 
					
						
							| 
									
										
										
										
											2025-09-08 17:34:23 +08:00
										 |  |  |  |             print(f"[{get_current_time_str()}] 客户端{self.client_ip}: 帧消费任务已取消") | 
					
						
							| 
									
										
										
										
											2025-09-03 17:08:28 +08:00
										 |  |  |  |         except Exception as e: | 
					
						
							| 
									
										
										
										
											2025-09-08 17:34:23 +08:00
										 |  |  |  |             print(f"[{get_current_time_str()}] 客户端{self.client_ip}: 帧消费逻辑错误 - {str(e)}") | 
					
						
							| 
									
										
										
										
											2025-09-03 17:08:28 +08:00
										 |  |  |  | 
 | 
					
						
							|  |  |  |  |     async def process_frame(self, frame_data: bytes) -> None: | 
					
						
							| 
									
										
										
										
											2025-09-10 08:57:56 +08:00
										 |  |  |  |         """处理单帧图像数据(核心修改:detect函数传入 client_ip + img 双参数)""" | 
					
						
							| 
									
										
										
										
											2025-09-09 16:30:12 +08:00
										 |  |  |  |         # 二进制转OpenCV图像 | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  |         nparr = np.frombuffer(frame_data, np.uint8) | 
					
						
							|  |  |  |  |         img = cv2.imdecode(nparr, cv2.IMREAD_COLOR) | 
					
						
							|  |  |  |  |         if img is None: | 
					
						
							| 
									
										
										
										
											2025-09-08 17:34:23 +08:00
										 |  |  |  |             print(f"[{get_current_time_str()}] 客户端{self.client_ip}: 无法解析图像数据") | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  |             return | 
					
						
							|  |  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-03 17:08:28 +08:00
										 |  |  |  |         try: | 
					
						
							| 
									
										
										
										
											2025-09-10 08:57:56 +08:00
										 |  |  |  |             # -------------------------- 核心修改:按要求传入参数(1.client_ip 2.img) -------------------------- | 
					
						
							|  |  |  |  |             # detect函数参数顺序:第一个为client_ip,第二个为图像数据img | 
					
						
							|  |  |  |  |             # 保持返回值解包(是否违规, 结果数据, 检测器类型)不变 | 
					
						
							| 
									
										
										
										
											2025-09-09 16:30:12 +08:00
										 |  |  |  |             has_violation, data, detector_type = await asyncio.to_thread( | 
					
						
							| 
									
										
										
										
											2025-09-10 08:57:56 +08:00
										 |  |  |  |                 detect,                  # 调用检测函数 | 
					
						
							|  |  |  |  |                 self.client_ip,          # 第一个参数:客户端IP(新增,按需求顺序) | 
					
						
							|  |  |  |  |                 img                      # 第二个参数:图像数据(原参数,调整顺序) | 
					
						
							| 
									
										
										
										
											2025-09-09 16:30:12 +08:00
										 |  |  |  |             ) | 
					
						
							|  |  |  |  |             # ------------------------------------------------------------------------------------- | 
					
						
							|  |  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-10 08:57:56 +08:00
										 |  |  |  |             # 打印检测结果(包含客户端IP,与传入参数对应) | 
					
						
							| 
									
										
										
										
											2025-09-08 18:10:49 +08:00
										 |  |  |  |             print(f"[{get_current_time_str()}] 客户端{self.client_ip}: 检测结果 - " | 
					
						
							| 
									
										
										
										
											2025-09-09 16:30:12 +08:00
										 |  |  |  |                   f"违规: {has_violation}, 类型: {detector_type}, 数据: {data}") | 
					
						
							| 
									
										
										
										
											2025-09-08 18:10:49 +08:00
										 |  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-10 08:57:56 +08:00
										 |  |  |  |             # 处理违规逻辑(逻辑不变,基于detect返回结果执行) | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  |             if has_violation: | 
					
						
							| 
									
										
										
										
											2025-09-08 18:10:49 +08:00
										 |  |  |  |                 print(f"[{get_current_time_str()}] 客户端{self.client_ip}: 检测到违规 - " | 
					
						
							|  |  |  |  |                       f"类型: {detector_type}, 详情: {data}") | 
					
						
							| 
									
										
										
										
											2025-09-04 12:29:27 +08:00
										 |  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-09 16:30:12 +08:00
										 |  |  |  |                 # 违规次数+1 | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  |                 try: | 
					
						
							|  |  |  |  |                     await asyncio.to_thread(increment_alarm_count_by_ip, self.client_ip) | 
					
						
							| 
									
										
										
										
											2025-09-08 17:34:23 +08:00
										 |  |  |  |                     print(f"[{get_current_time_str()}] 客户端{self.client_ip}: 违规次数已+1") | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  |                 except Exception as e: | 
					
						
							| 
									
										
										
										
											2025-09-08 17:34:23 +08:00
										 |  |  |  |                     print(f"[{get_current_time_str()}] 客户端{self.client_ip}: 违规次数更新失败 - {str(e)}") | 
					
						
							| 
									
										
										
										
											2025-09-04 17:08:25 +08:00
										 |  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-09 16:30:12 +08:00
										 |  |  |  |                 # 发送危险通知 | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  |                 danger_msg = { | 
					
						
							| 
									
										
										
										
											2025-09-04 12:29:27 +08:00
										 |  |  |  |                     "type": "danger", | 
					
						
							|  |  |  |  |                     "timestamp": get_current_time_str(), | 
					
						
							| 
									
										
										
										
											2025-09-09 16:30:12 +08:00
										 |  |  |  |                     "client_ip": self.client_ip, | 
					
						
							|  |  |  |  |                     "detail": data | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  |                 } | 
					
						
							|  |  |  |  |                 await self.websocket.send_json(danger_msg) | 
					
						
							| 
									
										
										
										
											2025-09-03 17:08:28 +08:00
										 |  |  |  |             else: | 
					
						
							| 
									
										
										
										
											2025-09-08 17:34:23 +08:00
										 |  |  |  |                 print(f"[{get_current_time_str()}] 客户端{self.client_ip}: 未检测到违规") | 
					
						
							| 
									
										
										
										
											2025-09-09 16:30:12 +08:00
										 |  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-03 17:08:28 +08:00
										 |  |  |  |         except Exception as e: | 
					
						
							| 
									
										
										
										
											2025-09-08 17:34:23 +08:00
										 |  |  |  |             print(f"[{get_current_time_str()}] 客户端{self.client_ip}: 图像处理错误 - {str(e)}") | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-02 18:51:50 +08:00
										 |  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  | # 全局状态管理 | 
					
						
							| 
									
										
										
										
											2025-09-02 18:51:50 +08:00
										 |  |  |  | connected_clients: Dict[str, ClientConnection] = {} | 
					
						
							|  |  |  |  | heartbeat_task: Optional[asyncio.Task] = None | 
					
						
							|  |  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-09 16:30:12 +08:00
										 |  |  |  | # 心跳检查任务 | 
					
						
							| 
									
										
										
										
											2025-09-02 18:51:50 +08:00
										 |  |  |  | async def heartbeat_checker(): | 
					
						
							|  |  |  |  |     while True: | 
					
						
							| 
									
										
										
										
											2025-09-04 12:29:27 +08:00
										 |  |  |  |         current_time = get_current_time_str() | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  |         timeout_ips = [ip for ip, conn in connected_clients.items() if not conn.is_alive()] | 
					
						
							|  |  |  |  | 
 | 
					
						
							|  |  |  |  |         if timeout_ips: | 
					
						
							| 
									
										
										
										
											2025-09-08 17:34:23 +08:00
										 |  |  |  |             print(f"[{current_time}] 心跳检查: {len(timeout_ips)}个客户端超时(IP: {timeout_ips})") | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  |             for ip in timeout_ips: | 
					
						
							|  |  |  |  |                 try: | 
					
						
							|  |  |  |  |                     conn = connected_clients[ip] | 
					
						
							|  |  |  |  |                     if conn.consumer_task and not conn.consumer_task.done(): | 
					
						
							|  |  |  |  |                         conn.consumer_task.cancel() | 
					
						
							|  |  |  |  |                     await conn.websocket.close(code=1008, reason="心跳超时") | 
					
						
							|  |  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-09 16:30:12 +08:00
										 |  |  |  |                     # 标记离线 | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  |                     try: | 
					
						
							|  |  |  |  |                         await asyncio.to_thread(update_online_status_by_ip, ip, 0) | 
					
						
							|  |  |  |  |                         action_data = DeviceActionCreate(client_ip=ip, action=0) | 
					
						
							|  |  |  |  |                         await asyncio.to_thread(add_device_action, action_data) | 
					
						
							| 
									
										
										
										
											2025-09-08 17:34:23 +08:00
										 |  |  |  |                         print(f"[{current_time}] 客户端{ip}: 已标记为离线并记录操作") | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  |                     except Exception as e: | 
					
						
							| 
									
										
										
										
											2025-09-08 17:34:23 +08:00
										 |  |  |  |                         print(f"[{current_time}] 客户端{ip}: 离线状态更新失败 - {str(e)}") | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  |                 finally: | 
					
						
							|  |  |  |  |                     connected_clients.pop(ip, None) | 
					
						
							|  |  |  |  |         else: | 
					
						
							| 
									
										
										
										
											2025-09-08 17:34:23 +08:00
										 |  |  |  |             print(f"[{current_time}] 心跳检查: {len(connected_clients)}个客户端在线") | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-03 16:27:53 +08:00
										 |  |  |  |         await asyncio.sleep(HEARTBEAT_INTERVAL) | 
					
						
							| 
									
										
										
										
											2025-09-02 18:51:50 +08:00
										 |  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  | 
 | 
					
						
							|  |  |  |  | # 应用生命周期管理 | 
					
						
							| 
									
										
										
										
											2025-09-02 18:51:50 +08:00
										 |  |  |  | @asynccontextmanager | 
					
						
							|  |  |  |  | async def lifespan(app: FastAPI): | 
					
						
							|  |  |  |  |     global heartbeat_task | 
					
						
							|  |  |  |  |     heartbeat_task = asyncio.create_task(heartbeat_checker()) | 
					
						
							| 
									
										
										
										
											2025-09-08 17:34:23 +08:00
										 |  |  |  |     print(f"[{get_current_time_str()}] 全局心跳检查任务启动(任务ID: {id(heartbeat_task)})") | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  |     yield | 
					
						
							| 
									
										
										
										
											2025-09-02 18:51:50 +08:00
										 |  |  |  |     if heartbeat_task and not heartbeat_task.done(): | 
					
						
							|  |  |  |  |         heartbeat_task.cancel() | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  |         try: | 
					
						
							|  |  |  |  |             await heartbeat_task | 
					
						
							|  |  |  |  |             print(f"[{get_current_time_str()}] 全局心跳检查任务已取消") | 
					
						
							|  |  |  |  |         except asyncio.CancelledError: | 
					
						
							|  |  |  |  |             pass | 
					
						
							|  |  |  |  | 
 | 
					
						
							|  |  |  |  | 
 | 
					
						
							|  |  |  |  | # 消息处理工具函数 | 
					
						
							|  |  |  |  | async def send_heartbeat_ack(conn: ClientConnection): | 
					
						
							|  |  |  |  |     try: | 
					
						
							|  |  |  |  |         heartbeat_ack_msg = { | 
					
						
							|  |  |  |  |             "type": "heart", | 
					
						
							|  |  |  |  |             "timestamp": get_current_time_str(), | 
					
						
							|  |  |  |  |             "client_ip": conn.client_ip | 
					
						
							|  |  |  |  |         } | 
					
						
							|  |  |  |  |         await conn.websocket.send_json(heartbeat_ack_msg) | 
					
						
							| 
									
										
										
										
											2025-09-08 17:34:23 +08:00
										 |  |  |  |         print(f"[{get_current_time_str()}] 客户端{conn.client_ip}: 已发送心跳确认") | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  |         return True | 
					
						
							|  |  |  |  |     except Exception as e: | 
					
						
							|  |  |  |  |         connected_clients.pop(conn.client_ip, None) | 
					
						
							| 
									
										
										
										
											2025-09-08 17:34:23 +08:00
										 |  |  |  |         print(f"[{get_current_time_str()}] 客户端{conn.client_ip}: 心跳确认发送失败 - {str(e)}") | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  |         return False | 
					
						
							|  |  |  |  | 
 | 
					
						
							|  |  |  |  | 
 | 
					
						
							|  |  |  |  | async def handle_text_msg(conn: ClientConnection, text: str): | 
					
						
							|  |  |  |  |     try: | 
					
						
							|  |  |  |  |         msg = json.loads(text) | 
					
						
							|  |  |  |  |         if msg.get("type") == "heart": | 
					
						
							|  |  |  |  |             conn.update_heartbeat() | 
					
						
							|  |  |  |  |             await send_heartbeat_ack(conn) | 
					
						
							|  |  |  |  |         else: | 
					
						
							| 
									
										
										
										
											2025-09-08 17:34:23 +08:00
										 |  |  |  |             print(f"[{get_current_time_str()}] 客户端{conn.client_ip}: 未知文本消息类型({msg.get('type')})") | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  |     except json.JSONDecodeError: | 
					
						
							| 
									
										
										
										
											2025-09-08 17:34:23 +08:00
										 |  |  |  |         print(f"[{get_current_time_str()}] 客户端{conn.client_ip}: 无效JSON文本消息") | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  | 
 | 
					
						
							|  |  |  |  | 
 | 
					
						
							|  |  |  |  | async def handle_binary_msg(conn: ClientConnection, data: bytes): | 
					
						
							|  |  |  |  |     try: | 
					
						
							|  |  |  |  |         conn.frame_queue.put_nowait(data) | 
					
						
							| 
									
										
										
										
											2025-09-08 17:34:23 +08:00
										 |  |  |  |         print(f"[{get_current_time_str()}] 客户端{conn.client_ip}: 图像数据({len(data)}字节)已加入队列") | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  |     except asyncio.QueueFull: | 
					
						
							| 
									
										
										
										
											2025-09-08 17:34:23 +08:00
										 |  |  |  |         print(f"[{get_current_time_str()}] 客户端{conn.client_ip}: 帧队列已满、丢弃当前图像数据") | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-02 18:51:50 +08:00
										 |  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  | # WebSocket路由配置 | 
					
						
							| 
									
										
										
										
											2025-09-04 12:29:27 +08:00
										 |  |  |  | ws_router = APIRouter() | 
					
						
							| 
									
										
										
										
											2025-09-03 17:08:28 +08:00
										 |  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-03 16:27:53 +08:00
										 |  |  |  | @ws_router.websocket(WS_ENDPOINT) | 
					
						
							| 
									
										
										
										
											2025-09-02 18:51:50 +08:00
										 |  |  |  | async def websocket_endpoint(websocket: WebSocket): | 
					
						
							| 
									
										
										
										
											2025-09-10 08:57:56 +08:00
										 |  |  |  |     load_model()  # 加载检测模型(仅在连接建立时加载一次,避免重复加载) | 
					
						
							| 
									
										
										
										
											2025-09-02 18:51:50 +08:00
										 |  |  |  |     await websocket.accept() | 
					
						
							| 
									
										
										
										
											2025-09-04 12:29:27 +08:00
										 |  |  |  |     client_ip = websocket.client.host if websocket.client else "unknown_ip" | 
					
						
							|  |  |  |  |     current_time = get_current_time_str() | 
					
						
							| 
									
										
										
										
											2025-09-08 17:34:23 +08:00
										 |  |  |  |     print(f"[{current_time}] 客户端{client_ip}: WebSocket连接已建立") | 
					
						
							| 
									
										
										
										
											2025-09-04 12:29:27 +08:00
										 |  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-04 17:33:20 +08:00
										 |  |  |  |     is_online_updated = False | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-02 18:51:50 +08:00
										 |  |  |  |     try: | 
					
						
							| 
									
										
										
										
											2025-09-10 08:57:56 +08:00
										 |  |  |  |         # 处理重复连接(同一IP断开旧连接) | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  |         if client_ip in connected_clients: | 
					
						
							|  |  |  |  |             old_conn = connected_clients[client_ip] | 
					
						
							|  |  |  |  |             if old_conn.consumer_task and not old_conn.consumer_task.done(): | 
					
						
							|  |  |  |  |                 old_conn.consumer_task.cancel() | 
					
						
							|  |  |  |  |             await old_conn.websocket.close(code=1008, reason="同一IP新连接建立") | 
					
						
							|  |  |  |  |             connected_clients.pop(client_ip) | 
					
						
							| 
									
										
										
										
											2025-09-08 17:34:23 +08:00
										 |  |  |  |             print(f"[{current_time}] 客户端{client_ip}: 已关闭旧连接") | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-10 08:57:56 +08:00
										 |  |  |  |         # 注册新连接(绑定client_ip和WebSocket) | 
					
						
							| 
									
										
										
										
											2025-09-03 16:27:53 +08:00
										 |  |  |  |         new_conn = ClientConnection(websocket, client_ip) | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  |         connected_clients[client_ip] = new_conn | 
					
						
							| 
									
										
										
										
											2025-09-10 08:57:56 +08:00
										 |  |  |  |         new_conn.start_consumer()  # 启动帧消费任务 | 
					
						
							|  |  |  |  |         await new_conn.send_frame_permit()  # 发送首次帧许可 | 
					
						
							| 
									
										
										
										
											2025-09-03 17:08:28 +08:00
										 |  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-10 08:57:56 +08:00
										 |  |  |  |         # 标记客户端上线 | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  |         try: | 
					
						
							|  |  |  |  |             await asyncio.to_thread(update_online_status_by_ip, client_ip, 1) | 
					
						
							|  |  |  |  |             action_data = DeviceActionCreate(client_ip=client_ip, action=1) | 
					
						
							|  |  |  |  |             await asyncio.to_thread(add_device_action, action_data) | 
					
						
							| 
									
										
										
										
											2025-09-08 17:34:23 +08:00
										 |  |  |  |             print(f"[{current_time}] 客户端{client_ip}: 已标记为在线并记录操作") | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  |             is_online_updated = True | 
					
						
							|  |  |  |  |         except Exception as e: | 
					
						
							| 
									
										
										
										
											2025-09-08 17:34:23 +08:00
										 |  |  |  |             print(f"[{current_time}] 客户端{client_ip}: 上线状态更新失败 - {str(e)}") | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-08 17:34:23 +08:00
										 |  |  |  |         print(f"[{current_time}] 客户端{client_ip}: 新连接注册成功、在线数: {len(connected_clients)}") | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-10 08:57:56 +08:00
										 |  |  |  |         # 消息循环(持续接收客户端消息) | 
					
						
							| 
									
										
										
										
											2025-09-02 18:51:50 +08:00
										 |  |  |  |         while True: | 
					
						
							| 
									
										
										
										
											2025-09-03 16:27:53 +08:00
										 |  |  |  |             data = await websocket.receive() | 
					
						
							|  |  |  |  |             if "text" in data: | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  |                 await handle_text_msg(new_conn, data["text"]) | 
					
						
							| 
									
										
										
										
											2025-09-03 16:27:53 +08:00
										 |  |  |  |             elif "bytes" in data: | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  |                 await handle_binary_msg(new_conn, data["bytes"]) | 
					
						
							| 
									
										
										
										
											2025-09-02 18:51:50 +08:00
										 |  |  |  | 
 | 
					
						
							|  |  |  |  |     except WebSocketDisconnect as e: | 
					
						
							| 
									
										
										
										
											2025-09-08 17:34:23 +08:00
										 |  |  |  |         print(f"[{get_current_time_str()}] 客户端{client_ip}: 主动断开连接(代码: {e.code})") | 
					
						
							| 
									
										
										
										
											2025-09-02 18:51:50 +08:00
										 |  |  |  |     except Exception as e: | 
					
						
							| 
									
										
										
										
											2025-09-08 17:34:23 +08:00
										 |  |  |  |         print(f"[{get_current_time_str()}] 客户端{client_ip}: 连接异常 - {str(e)[:50]}") | 
					
						
							| 
									
										
										
										
											2025-09-02 18:51:50 +08:00
										 |  |  |  |     finally: | 
					
						
							| 
									
										
										
										
											2025-09-10 08:57:56 +08:00
										 |  |  |  |         # 清理资源(断开后标记离线+删除连接) | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  |         if client_ip in connected_clients: | 
					
						
							|  |  |  |  |             conn = connected_clients[client_ip] | 
					
						
							|  |  |  |  |             if conn.consumer_task and not conn.consumer_task.done(): | 
					
						
							|  |  |  |  |                 conn.consumer_task.cancel() | 
					
						
							|  |  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2025-09-10 08:57:56 +08:00
										 |  |  |  |             # 仅当上线状态更新成功时,才执行离线更新 | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  |             if is_online_updated: | 
					
						
							|  |  |  |  |                 try: | 
					
						
							|  |  |  |  |                     await asyncio.to_thread(update_online_status_by_ip, client_ip, 0) | 
					
						
							|  |  |  |  |                     action_data = DeviceActionCreate(client_ip=client_ip, action=0) | 
					
						
							|  |  |  |  |                     await asyncio.to_thread(add_device_action, action_data) | 
					
						
							| 
									
										
										
										
											2025-09-08 17:34:23 +08:00
										 |  |  |  |                     print(f"[{get_current_time_str()}] 客户端{client_ip}: 断开后已标记为离线") | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  |                 except Exception as e: | 
					
						
							| 
									
										
										
										
											2025-09-08 17:34:23 +08:00
										 |  |  |  |                     print(f"[{get_current_time_str()}] 客户端{client_ip}: 断开后离线更新失败 - {str(e)}") | 
					
						
							| 
									
										
										
										
											2025-09-04 22:59:27 +08:00
										 |  |  |  | 
 | 
					
						
							|  |  |  |  |             connected_clients.pop(client_ip, None) | 
					
						
							| 
									
										
										
										
											2025-09-08 18:10:49 +08:00
										 |  |  |  |         print(f"[{get_current_time_str()}] 客户端{client_ip}: 资源已清理、在线数: {len(connected_clients)}") |