1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
|
import rospy import threading import time import signal import sys from std_msgs.msg import String, Int32 from geometry_msgs.msg import Twist
class RobustNode: def __init__(self, node_name): """节点初始化""" self.node_name = node_name self.is_initialized = False self.is_running = False self.is_shutting_down = False self.worker_threads = [] self.shutdown_event = threading.Event() self.stats = { 'start_time': None, 'messages_processed': 0, 'errors_count': 0, 'uptime': 0 } self._setup_signal_handlers() self._initialize_ros_node() def _setup_signal_handlers(self): """设置信号处理器""" signal.signal(signal.SIGINT, self._signal_handler) signal.signal(signal.SIGTERM, self._signal_handler) def _signal_handler(self, signum, frame): """信号处理器""" rospy.logwarn(f"Received signal {signum}, initiating shutdown...") self.shutdown() def _initialize_ros_node(self): """初始化ROS节点""" try: rospy.init_node(self.node_name, anonymous=False) self.robot_name = rospy.get_param('~robot_name', 'default_robot') self.publish_rate = rospy.get_param('~publish_rate', 10.0) self.enable_debug = rospy.get_param('~debug', False) rospy.loginfo(f"Node {self.node_name} initialized successfully") rospy.loginfo(f"Robot name: {self.robot_name}") rospy.loginfo(f"Publish rate: {self.publish_rate} Hz") self.is_initialized = True except Exception as e: rospy.logerr(f"Failed to initialize ROS node: {e}") raise def setup_publishers(self): """设置发布者""" try: self.cmd_vel_pub = rospy.Publisher('/cmd_vel', Twist, queue_size=1) self.status_pub = rospy.Publisher('/status', String, queue_size=10) self.counter_pub = rospy.Publisher('/counter', Int32, queue_size=10) rospy.loginfo("Publishers initialized") except Exception as e: rospy.logerr(f"Failed to setup publishers: {e}") raise def setup_subscribers(self): """设置订阅者""" try: self.status_sub = rospy.Subscriber('/status', String, self.status_callback) self.emergency_sub = rospy.Subscriber('/emergency_stop', String, self.emergency_callback) rospy.loginfo("Subscribers initialized") except Exception as e: rospy.logerr(f"Failed to setup subscribers: {e}") raise def status_callback(self, msg): """状态消息回调""" try: self.stats['messages_processed'] += 1 rospy.loginfo(f"Received status: {msg.data}") except Exception as e: self.stats['errors_count'] += 1 rospy.logerr(f"Error in status callback: {e}") def emergency_callback(self, msg): """紧急停止回调""" rospy.logwarn(f"Emergency stop received: {msg.data}") self.shutdown() def start(self): """启动节点""" if not self.is_initialized: raise RuntimeError("Node not initialized") try: self.setup_publishers() self.setup_subscribers() self._start_worker_threads() self.is_running = True self.stats['start_time'] = time.time() rospy.loginfo(f"Node {self.node_name} started successfully") except Exception as e: rospy.logerr(f"Failed to start node: {e}") self.cleanup() raise def _start_worker_threads(self): """启动工作线程""" status_thread = threading.Thread(target=self._status_worker, daemon=True) status_thread.start() self.worker_threads.append(status_thread) counter_thread = threading.Thread(target=self._counter_worker, daemon=True) counter_thread.start() self.worker_threads.append(counter_thread) stats_thread = threading.Thread(target=self._stats_worker, daemon=True) stats_thread.start() self.worker_threads.append(stats_thread) rospy.loginfo(f"Started {len(self.worker_threads)} worker threads") def _status_worker(self): """状态发布工作线程""" rate = rospy.Rate(self.publish_rate) while not self.shutdown_event.is_set() and not rospy.is_shutdown(): try: status_msg = String() status_msg.data = f"Node {self.node_name} running, uptime: {self._get_uptime():.1f}s" self.status_pub.publish(status_msg) rate.sleep() except Exception as e: self.stats['errors_count'] += 1 rospy.logerr(f"Error in status worker: {e}") def _counter_worker(self): """计数器工作线程""" rate = rospy.Rate(1.0) counter = 0 while not self.shutdown_event.is_set() and not rospy.is_shutdown(): try: counter_msg = Int32() counter_msg.data = counter self.counter_pub.publish(counter_msg) counter += 1 rate.sleep() except Exception as e: self.stats['errors_count'] += 1 rospy.logerr(f"Error in counter worker: {e}") def _stats_worker(self): """统计信息工作线程""" rate = rospy.Rate(0.5) while not self.shutdown_event.is_set() and not rospy.is_shutdown(): try: uptime = self._get_uptime() self.stats['uptime'] = uptime if self.enable_debug: rospy.loginfo(f"Node Stats - Uptime: {uptime:.1f}s, " f"Messages: {self.stats['messages_processed']}, " f"Errors: {self.stats['errors_count']}") rate.sleep() except Exception as e: rospy.logerr(f"Error in stats worker: {e}") def _get_uptime(self): """获取运行时间""" if self.stats['start_time']: return time.time() - self.stats['start_time'] return 0.0 def run(self): """运行节点主循环""" if not self.is_running: raise RuntimeError("Node not started") try: rospy.loginfo(f"Node {self.node_name} entering main loop") rospy.spin() except rospy.ROSInterruptException: rospy.loginfo("Received ROS interrupt") except Exception as e: rospy.logerr(f"Error in main loop: {e}") self.stats['errors_count'] += 1 finally: self.shutdown() def shutdown(self): """关闭节点""" if self.is_shutting_down: return self.is_shutting_down = True rospy.loginfo(f"Shutting down node {self.node_name}...") try: self.shutdown_event.set() for thread in self.worker_threads: if thread.is_alive(): thread.join(timeout=2.0) final_status = String() final_status.data = f"Node {self.node_name} shutting down" try: self.status_pub.publish(final_status) except: pass self.cleanup() self.is_running = False rospy.loginfo(f"Node {self.node_name} shutdown complete") except Exception as e: rospy.logerr(f"Error during shutdown: {e}") def cleanup(self): """清理资源""" try: if hasattr(self, 'cmd_vel_pub'): self.cmd_vel_pub.unregister() if hasattr(self, 'status_pub'): self.status_pub.unregister() if hasattr(self, 'counter_pub'): self.counter_pub.unregister() uptime = self._get_uptime() rospy.loginfo(f"Final stats - Uptime: {uptime:.1f}s, " f"Messages: {self.stats['messages_processed']}, " f"Errors: {self.stats['errors_count']}") except Exception as e: rospy.logerr(f"Error during cleanup: {e}") def get_node_info(self): """获取节点信息""" return { 'name': self.node_name, 'is_initialized': self.is_initialized, 'is_running': self.is_running, 'is_shutting_down': self.is_shutting_down, 'uptime': self._get_uptime(), 'stats': self.stats.copy() }
if __name__ == '__main__': try: node = RobustNode('robust_example_node') node.start() node.run() except KeyboardInterrupt: rospy.loginfo("Keyboard interrupt received") except Exception as e: rospy.logerr(f"Node error: {e}") finally: if 'node' in locals(): node.shutdown()
|