Files
assist/start_dashboard.py

156 lines
5.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""
TSP智能助手综合管理平台
"""
import sys
import os
import logging
import threading
import asyncio
from datetime import datetime
# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
def setup_logging(start_time: str):
"""设置日志,按启动时间创建子目录"""
# 日志根目录
log_root = "logs"
# 以启动时间命名的子目录(避免路径中的空格和冒号)
safe_start_time = start_time.replace(" ", "_").replace(":", "-")
log_dir = os.path.join(log_root, safe_start_time)
os.makedirs(log_dir, exist_ok=True)
log_file_path = os.path.join(log_dir, "dashboard.log")
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
handlers=[
logging.FileHandler(log_file_path, encoding="utf-8"),
logging.StreamHandler(),
],
)
def start_websocket_server():
"""启动WebSocket服务器"""
try:
from src.web.websocket_server import WebSocketServer
server = WebSocketServer(host="localhost", port=8765)
server.run()
except Exception as e:
print(f"WebSocket服务器启动失败: {e}")
def start_feishu_longconn_service():
"""启动飞书长连接服务"""
try:
import logging
logger = logging.getLogger("feishu_longconn")
logger.info("=" * 80)
logger.info("🚀 启动飞书长连接服务(后台线程)")
logger.info("=" * 80)
from src.integrations.feishu_longconn_service import get_feishu_longconn_service
service = get_feishu_longconn_service()
service.start() # 这会阻塞当前线程
except Exception as e:
print(f"❌ 飞书长连接服务启动失败: {e}")
import traceback
traceback.print_exc()
def check_database_connection():
"""检查数据库连接"""
try:
from src.core.database import db_manager
if db_manager.check_connection():
print("✓ 数据库连接正常")
return True
else:
print("✗ 数据库连接失败,请检查数据库配置和网络连接。")
return False
except Exception as e:
print(f"✗ 数据库连接检查出错: {e}")
return False
def main():
"""主函数"""
print("=" * 60)
print("TSP智能助手 - 综合管理平台")
print("=" * 60)
start_time = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
print(f"启动时间: {start_time}")
print()
# 设置日志(日志目录按启动时间区分)
setup_logging(start_time)
logger = logging.getLogger(__name__)
try:
# 检查必要目录
os.makedirs("logs", exist_ok=True)
os.makedirs("data", exist_ok=True)
logger.info("正在启动TSP智能助手综合管理平台...")
# 检查数据库连接
if not check_database_connection():
logger.error("数据库连接失败,退出启动")
print("请根据日志检查数据库配置和网络连接。")
sys.exit(1) # 数据库连接失败时直接退出
# 跳过系统检查,直接启动(避免重复初始化)
logger.info("跳过系统检查,直接启动服务...")
# 导入并启动Flask应用
from src.web.app import app
from src.config.unified_config import get_config
# 获取配置
config = get_config()
print()
print("访问地址:")
print(f" 主页: http://localhost:{config.server.port}")
print(f" 预警管理: http://localhost:{config.server.port}/alerts")
print(f" 实时对话: http://localhost:{config.server.port}/chat")
print(f" WebSocket: ws://localhost:{config.server.websocket_port}")
print()
print("🤖 飞书长连接服务: 已在后台启动")
print()
print("按 Ctrl+C 停止服务")
print("=" * 60)
# 在单独线程中启动WebSocket服务器
websocket_thread = threading.Thread(target=start_websocket_server, daemon=True)
websocket_thread.start()
# 在单独线程中启动飞书长连接服务已添加消息去重可与Webhook共存
feishu_thread = threading.Thread(target=start_feishu_longconn_service, daemon=True)
feishu_thread.start()
# 等待飞书服务初始化
import time
time.sleep(2)
# 启动Flask应用
app.run(
debug=config.server.debug,
host=config.server.host,
port=config.server.port,
threaded=True,
use_reloader=False # 禁用重载器避免重复启动WebSocket服务器
)
except KeyboardInterrupt:
print("\n正在停止服务...")
logger.info("用户手动停止服务")
except Exception as e:
print(f"启动失败: {e}")
logger.error(f"启动失败: {e}")
sys.exit(1)
if __name__ == "__main__":
main()