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

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)
except KeyboardInterrupt:
pass
Ctrl.quit()
image_processor.destroy()
sys.exit()
print("\n程序被用户中断")
except Exception as e:
print(f"发生错误: {e}")
finally:
print("正在清理资源...")
Ctrl.quit()
image_processor.destroy()
print("程序已退出")
sys.exit()
class Robot_Ctrl(object):

View File

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