From 4a3105adfc936893babf07cfc0c713ec628a455f Mon Sep 17 00:00:00 2001 From: zqc <835569504@qq.com> Date: Sun, 21 Dec 2025 20:43:33 +0800 Subject: [PATCH] =?UTF-8?q?=E5=B0=86rtsp=E9=9B=86=E6=88=90=E5=88=B0FastAPI?= =?UTF-8?q?=E5=A3=B0=E6=98=8E=E5=91=A8=E6=9C=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/app.py | 16 +++++++++++++ src/config.py | 2 ++ src/rtsp/service.py | 55 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 73 insertions(+) create mode 100644 src/rtsp/service.py diff --git a/src/app.py b/src/app.py index 8c8bb8d..c0e6aa8 100644 --- a/src/app.py +++ b/src/app.py @@ -28,6 +28,7 @@ from src.api.errors import ( from src.config import settings from src.database.connection import init_database from src.database.connection import db_manager +from src.rtsp.service import rtsp_server # 生命周期管理 @@ -53,10 +54,25 @@ async def lifespan(app: FastAPI): else: print("❌ 数据库连接失败") + # 启动 RTSP 服务(如果启用) + if settings.RTSP_ENABLED: + print("📹 启动 RTSP 服务...") + rtsp_server.start() + # 将 RTSP 服务实例保存到应用状态 + app.state.rtsp_server = rtsp_server + else: + print("⚠️ RTSP 服务未启用") + yield # 关闭时 print("🛑 algorithm service stopped...") + + # 停止 RTSP 服务 + if settings.RTSP_ENABLED: + print("🛑 停止 RTSP 服务...") + rtsp_server.stop() + db_manager.close() diff --git a/src/config.py b/src/config.py index b722354..dac011a 100644 --- a/src/config.py +++ b/src/config.py @@ -13,6 +13,8 @@ from pydantic_core.core_schema import FieldValidationInfo class Settings(BaseSettings): """应用配置类""" + RTSP_ENABLED: bool = True + # API配置 API_V1_PREFIX: str = "/api/v1" PROJECT_NAME: str = "algorithm-service" diff --git a/src/rtsp/service.py b/src/rtsp/service.py new file mode 100644 index 0000000..562e536 --- /dev/null +++ b/src/rtsp/service.py @@ -0,0 +1,55 @@ +""" +RTSP 服务模块 - 简洁版本,直接使用原始服务 +""" + +import threading +from src.rtsp_service_ws_1217 import RTSPService + + +class SimpleRTSPServer: + """RTSP 服务管理器 - 简洁包装器""" + + def __init__(self): + self.is_running = False + self.service = None + self.thread = None + + def start(self): + """启动 RTSP 服务""" + if self.is_running: + return + + print("🚀 启动 RTSP 服务...") + + # 创建原始服务实例 + self.service = RTSPService(config_path="config.yaml") + + # 在新线程中启动服务 + self.thread = threading.Thread( + target=self.service.start, + daemon=True + ) + self.thread.start() + + self.is_running = True + print("✅ RTSP 服务启动完成") + + def stop(self): + """停止 RTSP 服务""" + if not self.is_running: + return + + print("🛑 停止 RTSP 服务...") + + if self.service: + self.service.stop() + + if self.thread: + self.thread.join(timeout=5.0) + + self.is_running = False + print("✅ RTSP 服务已停止") + + +# 创建全局实例 +rtsp_server = SimpleRTSPServer() \ No newline at end of file