ros2ws_cli_sub.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. import asyncio
  2. import websockets
  3. import json
  4. import signal
  5. import sys
  6. # --- 配置部分 ---
  7. SERVER_URI = "ws://localhost:3003" # 服务端的 IP 和端口
  8. RECONNECT_DELAY = 5 # 断线重连等待时间 (秒)
  9. class ROS2WSClient:
  10. def __init__(self, uri):
  11. self.uri = uri
  12. self.running = True
  13. # 设置信号处理,支持 Ctrl+C 优雅退出
  14. signal.signal(signal.SIGINT, self._signal_handler)
  15. signal.signal(signal.SIGTERM, self._signal_handler)
  16. def _signal_handler(self, sig, frame):
  17. """处理退出信号"""
  18. print("\n[Client] Exit signal received. Stopping...")
  19. self.running = False
  20. # 触发事件循环停止(如果在主循环中运行)
  21. loop = asyncio.get_event_loop()
  22. loop.call_soon_threadsafe(loop.stop)
  23. async def connect(self):
  24. """连接并保持会话,包含重连逻辑"""
  25. while self.running:
  26. try:
  27. print(f"[Client] Connecting to {self.uri}...")
  28. async with websockets.connect(self.uri) as websocket:
  29. print("[Client] Connected successfully!")
  30. # 连接成功后,进入监听循环
  31. await self.listen(websocket)
  32. except (websockets.exceptions.ConnectionClosedError,
  33. websockets.exceptions.ConnectionClosedOK,
  34. OSError) as e:
  35. if self.running:
  36. print(f"[Client] Connection lost: {e}")
  37. print(f"[Client] Reconnecting in {RECONNECT_DELAY} seconds...")
  38. await asyncio.sleep(RECONNECT_DELAY)
  39. else:
  40. break
  41. except Exception as e:
  42. print(f"[Client] Unexpected error: {e}")
  43. await asyncio.sleep(RECONNECT_DELAY)
  44. async def listen(self, websocket):
  45. """监听服务端发送的消息"""
  46. try:
  47. async for message in websocket:
  48. # 解析 JSON 数据
  49. try:
  50. data = json.loads(message)
  51. self.handle_message(data)
  52. except json.JSONDecodeError:
  53. print(f"[Client] Received non-JSON message: {message}")
  54. except websockets.exceptions.ConnectionClosed:
  55. # 连接关闭会在外层 connect 方法处理重连
  56. raise
  57. def handle_message(self, data):
  58. """处理不同类型的消息"""
  59. msg_type = data.get("type")
  60. if msg_type == "msg":
  61. # 处理 ROS 话题消息
  62. topic = data.get("topic")
  63. msg_type_str = data.get("msg_type")
  64. msg_data = data.get("data")
  65. # 可以在这里添加特定的业务逻辑,例如只打印特定话题
  66. if topic in ["/pose", "/plan", "/chassis/cmd_vel"]:
  67. print(f"\n[ROS Data] Topic: {topic}")
  68. print(f" Type: {msg_type_str}")
  69. # 格式化打印数据内容
  70. print(f" Content: {json.dumps(msg_data, indent=2, ensure_ascii=False)}")
  71. elif msg_type == "event":
  72. # 处理事件 (例如新话题发现)
  73. event_name = data.get("event")
  74. topic = data.get("topic")
  75. if event_name == "topic_discovered":
  76. print(f"[System] New topic discovered: {topic}")
  77. elif msg_type == "nodes_info":
  78. # 处理节点信息
  79. count = data.get("count")
  80. nodes = data.get("nodes")
  81. print(f"[System] Active nodes update: {count} nodes active.")
  82. # print(f" Nodes: {nodes}") # 如果想看所有节点,取消注释
  83. else:
  84. # 处理未知格式
  85. print(f"[Client] Unknown message type: {msg_type}")
  86. print(f" Payload: {data}")
  87. async def main():
  88. client = ROS2WSClient(SERVER_URI)
  89. try:
  90. await client.connect()
  91. except asyncio.CancelledError:
  92. print("[Client] Task cancelled.")
  93. finally:
  94. print("[Client] Shutdown complete.")
  95. if __name__ == '__main__':
  96. try:
  97. # Windows 下需设置默认事件循环策略 (如果遇到 ProactorEventLoop 相关错误)
  98. # if sys.platform == 'win32':
  99. # asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
  100. asyncio.run(main())
  101. except KeyboardInterrupt:
  102. print("[Client] Interrupted by user.")