feat: 连接 URL 自动拼接设备号并区分连接失败原因

- server.url 作为通道基地址,设备号统一由 device.id 拼接,消除两处配置不一致的可能
- 断线日志区分「网络不通」与「被服务器拒绝(设备未注册/token 错误)」
- 配置文件补充逐项中文注释
- 移除 PID 文件逻辑

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2026-08-27 15:03:39 +08:00
co-authored by Claude
parent 68751c2354
commit 86bbe8ef5a
3 changed files with 44 additions and 26 deletions
-15
View File
@@ -8,13 +8,11 @@ hospital-agent.exe PyInstaller 打包后)
职责:
1. WebSocket 主动连接 B 端管理服务器(注册/心跳/命令)
2. 守护主程序(健康探测 + 宕机拉起)
3. 写 PID 文件(pid/hospital-agent.pid
由 WinSW/NSSM Windows 服务守护本进程。
"""
import logging
import os
import signal
import sys
import threading
@@ -43,9 +41,6 @@ def run():
config = AgentConfig.load()
log.info("Agent 启动:deviceId=%s, server=%s", config.device_id, config.server_url)
# 写 PID 文件
_write_pid_file()
# 组装组件(延迟导入避免环)
from agent.dispatcher import CommandDispatcher
from agent.process_guard import ProcessGuard
@@ -81,15 +76,5 @@ def _shutdown(signum, frame):
sys.exit(0)
def _write_pid_file():
"""写 PID 文件(pid/hospital-agent.pid)。"""
try:
os.makedirs("pid", exist_ok=True)
with open(os.path.join("pid", "hospital-agent.pid"), "w", encoding="utf-8") as f:
f.write(str(os.getpid()))
except Exception as e:
log.warning("PID 文件写入失败:%s", e)
if __name__ == "__main__":
run()
+10 -3
View File
@@ -58,7 +58,8 @@ class AgentClient:
def _connect(self):
"""建立 WebSocket 连接(阻塞直到连接断开,内部自行调度重连)。"""
url = self.config.server_url
# server.url 为通道基地址(以 /medical/agentSocket/ 结尾),设备号统一由 device.id 拼接
url = self.config.server_url.rstrip("/") + "/" + self.config.device_id
log.info("连接管理服务器:%s", url)
headers = [
@@ -86,12 +87,18 @@ class AgentClient:
def on_close(ws, code, reason):
self._connected = False
log.info("连接关闭:code=%s, reason=%s", code, reason)
# 区分失败类型:1000/1001 为正常关闭;其他关闭码(如 1008 策略拒绝)多为设备未注册或 token 错误
if code in (1000, 1001):
log.info("连接关闭:code=%s, reason=%s", code, reason)
elif reason:
log.warning("连接被服务器拒绝(设备未注册或 token 错误):code=%s, reason=%s", code, reason)
else:
log.warning("连接被服务器关闭:code=%s(设备未注册或 token 错误)", code)
self._schedule_reconnect()
def on_error(ws, error):
self._connected = False
log.warning("连接失败%s,将重连", error)
log.warning("网络不通(无法连接管理服务器)%s,将重连", error)
# websocket-client 出错后必定回调 on_close,重连由 on_close 统一调度
# 此处不重复调度,避免双重重连