刷新url暂时测试通过

This commit is contained in:
zqc
2026-01-23 11:45:23 +08:00
parent 14a07782e3
commit 06432daf2c
3 changed files with 97 additions and 33 deletions

View File

@@ -16,6 +16,7 @@ import websockets
from dataclasses import dataclass
from typing import Dict, Any, Tuple, List
from datetime import datetime
from test_cam import get_camera_preview_url
# -------------------------- Kadian 检测相关导入 --------------------------
from npu_yolo_onnx_person_car_phone import YOLOv8_ONNX # 主检测模型(人/车/后备箱/手机)
@@ -52,6 +53,7 @@ ws_clients_2 = set() # 新增第二个WebSocket客户端集合
class CameraConfig:
id: int
name: str
index: str
rtsp_url: str
@@ -452,13 +454,35 @@ class RTSPCaptureWorker(threading.Thread):
self.stop_event = stop_event
# 添加重连计数器
self.reconnect_count = 0
self.max_reconnects = 10
self.max_reconnects = 5
self.rtsp_url = ""
def run(self):
while not self.stop_event.is_set() and self.reconnect_count < self.max_reconnects:
while not self.stop_event.is_set():
try:
if self.reconnect_count >= self.max_reconnects:
print(f"[WARN] RTSP: {self.camera_cfg.name} reach max reconnects, refresh url")
self.reconnect_count = 0
new_url = self.refresh_video_url()
if new_url:
self.rtsp_url = new_url
else:
print(f"[ERROR] refresh RTSP URL is empty, do nothing")
# 检查rtsp_url是否为空或None如果是则重新获取
if not self.rtsp_url:
print(f"[WARN] RTSP URL is empty, refreshing...")
new_url = self.refresh_video_url()
if new_url:
self.rtsp_url = new_url
else:
print(f"[ERROR] RTSP URL is still empty, retrying in 5 seconds")
time.sleep(5)
continue
# 方法1使用TCP传输更稳定
rtsp_url = self.camera_cfg.rtsp_url
rtsp_url = self.rtsp_url
if "?" not in rtsp_url:
rtsp_url += "?transport=tcp" # 强制TCP传输
else:
@@ -478,12 +502,12 @@ class RTSPCaptureWorker(threading.Thread):
# cap.set(cv2.CAP_PROP_HW_ACCELERATION, cv2.VIDEO_ACCELERATION_ANY)
if not cap.isOpened():
print(f"[ERROR] Cannot open RTSP: {self.camera_cfg.rtsp_url}")
print(f"[ERROR] Cannot open RTSP: {self.rtsp_url}")
time.sleep(2)
self.reconnect_count += 1
continue
print(f"[INFO] Successfully opened RTSP: {self.camera_cfg.name}")
print(f"[INFO] Successfully opened RTSP: {self.name}")
self.reconnect_count = 0 # 重置重连计数
# # 设置帧率(可选)
@@ -535,6 +559,34 @@ class RTSPCaptureWorker(threading.Thread):
if self.reconnect_count >= self.max_reconnects:
print(f"[ERROR] Max reconnects reached for {self.camera_cfg.name}, stopping.")
def refresh_video_url(self):
"""
重新通过视频ID获取视频URL调用test_cam.py中的get_camera_preview_url方法
返回:
str: 新的视频URL如果获取失败则返回None
"""
try:
# 获取视频IDcamera_cfg.index
video_id = self.camera_cfg.index
# 调用test_cam.py中的函数
result = get_camera_preview_url(video_id)
# 解析结果与test_cam.py相同
if 'data' in result and 'url' in result['data']:
new_url = result['data']['url']
print(f"[INFO] get rtsp url success, URL: {new_url}")
return new_url
else:
print(f"[ERROR] get rtsp url failed: {result}")
return None
except Exception as e:
print(f"[ERROR] get rtsp url error: {str(e)}")
return None
# ========================= 帧处理线程 =========================
class FrameProcessorWorker(threading.Thread):
@@ -646,7 +698,7 @@ class RTSPService:
def __init__(self, config_path: str = "config.yaml"):
with open(config_path, "r", encoding="utf-8") as f:
cfg = yaml.safe_load(f)
self.cameras = [CameraConfig(id=c["id"], name=c.get("name", f"cam_{c['id']}"), rtsp_url=c["rtsp_url"])
self.cameras = [CameraConfig(id=c["id"], name=c.get("name", f"cam_{c['id']}"), index = c["index"], rtsp_url=c["rtsp_url"])
for c in cfg.get("cameras", [])]
self.stop_event = threading.Event()