import asyncio import websockets import json import signal import sys # --- 配置部分 --- SERVER_URI = "ws://localhost:3003" # 服务端的 IP 和端口 RECONNECT_DELAY = 5 # 断线重连等待时间 (秒) class ROS2WSClient: def __init__(self, uri): self.uri = uri self.running = True # 设置信号处理,支持 Ctrl+C 优雅退出 signal.signal(signal.SIGINT, self._signal_handler) signal.signal(signal.SIGTERM, self._signal_handler) def _signal_handler(self, sig, frame): """处理退出信号""" print("\n[Client] Exit signal received. Stopping...") self.running = False # 触发事件循环停止(如果在主循环中运行) loop = asyncio.get_event_loop() loop.call_soon_threadsafe(loop.stop) async def connect(self): """连接并保持会话,包含重连逻辑""" while self.running: try: print(f"[Client] Connecting to {self.uri}...") async with websockets.connect(self.uri) as websocket: print("[Client] Connected successfully!") # 连接成功后,进入监听循环 await self.listen(websocket) except (websockets.exceptions.ConnectionClosedError, websockets.exceptions.ConnectionClosedOK, OSError) as e: if self.running: print(f"[Client] Connection lost: {e}") print(f"[Client] Reconnecting in {RECONNECT_DELAY} seconds...") await asyncio.sleep(RECONNECT_DELAY) else: break except Exception as e: print(f"[Client] Unexpected error: {e}") await asyncio.sleep(RECONNECT_DELAY) async def listen(self, websocket): """监听服务端发送的消息""" try: async for message in websocket: # 解析 JSON 数据 try: data = json.loads(message) self.handle_message(data) except json.JSONDecodeError: print(f"[Client] Received non-JSON message: {message}") except websockets.exceptions.ConnectionClosed: # 连接关闭会在外层 connect 方法处理重连 raise def handle_message(self, data): """处理不同类型的消息""" msg_type = data.get("type") if msg_type == "msg": # 处理 ROS 话题消息 topic = data.get("topic") msg_type_str = data.get("msg_type") msg_data = data.get("data") # 可以在这里添加特定的业务逻辑,例如只打印特定话题 if topic in ["/pose", "/plan", "/chassis/cmd_vel"]: print(f"\n[ROS Data] Topic: {topic}") print(f" Type: {msg_type_str}") # 格式化打印数据内容 print(f" Content: {json.dumps(msg_data, indent=2, ensure_ascii=False)}") elif msg_type == "event": # 处理事件 (例如新话题发现) event_name = data.get("event") topic = data.get("topic") if event_name == "topic_discovered": print(f"[System] New topic discovered: {topic}") elif msg_type == "nodes_info": # 处理节点信息 count = data.get("count") nodes = data.get("nodes") print(f"[System] Active nodes update: {count} nodes active.") # print(f" Nodes: {nodes}") # 如果想看所有节点,取消注释 else: # 处理未知格式 print(f"[Client] Unknown message type: {msg_type}") print(f" Payload: {data}") async def main(): client = ROS2WSClient(SERVER_URI) try: await client.connect() except asyncio.CancelledError: print("[Client] Task cancelled.") finally: print("[Client] Shutdown complete.") if __name__ == '__main__': try: # Windows 下需设置默认事件循环策略 (如果遇到 ProactorEventLoop 相关错误) # if sys.platform == 'win32': # asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) asyncio.run(main()) except KeyboardInterrupt: print("[Client] Interrupted by user.")