优化主程序异常处理,添加资源清理逻辑;在图像处理器中引入多线程支持,改进图像订阅的运行机制。

This commit is contained in:
Havoc 2025-05-12 01:04:51 +08:00
parent 9f57cfc479
commit 33bd61ddb9
2 changed files with 23 additions and 8 deletions

14
main.py
View File

@ -37,11 +37,15 @@ def main():
time.sleep(100) time.sleep(100)
except KeyboardInterrupt: except KeyboardInterrupt:
pass print("\n程序被用户中断")
except Exception as e:
Ctrl.quit() print(f"发生错误: {e}")
image_processor.destroy() finally:
sys.exit() print("正在清理资源...")
Ctrl.quit()
image_processor.destroy()
print("程序已退出")
sys.exit()
class Robot_Ctrl(object): class Robot_Ctrl(object):

View File

@ -7,6 +7,7 @@ from cv_bridge import CvBridge
import cv2 import cv2
from rclpy.qos import QoSProfile, QoSReliabilityPolicy, QoSHistoryPolicy from rclpy.qos import QoSProfile, QoSReliabilityPolicy, QoSHistoryPolicy
from qreader import QReader from qreader import QReader
from threading import Thread
class ImageSubscriber(Node): class ImageSubscriber(Node):
@ -43,14 +44,24 @@ class ImageProcessor:
rclpy.init() rclpy.init()
self.image_subscriber = ImageSubscriber() self.image_subscriber = ImageSubscriber()
self.qreader = QReader() self.qreader = QReader()
self.spin_thread = None
self.running = True
def run(self): def run(self):
self.spin_thread = Thread(target=self._spin)
self.spin_thread.start()
def _spin(self):
try: try:
rclpy.spin(self.image_subscriber) while self.running:
except KeyboardInterrupt: rclpy.spin_once(self.image_subscriber, timeout_sec=0.1)
pass except Exception as e:
print(f"Spin thread error: {e}")
def destroy(self): def destroy(self):
self.running = False
if self.spin_thread:
self.spin_thread.join()
self.image_subscriber.destroy_node() self.image_subscriber.destroy_node()
rclpy.shutdown() rclpy.shutdown()