运行handle.py程序,启动服务节点,调用服务节点控制程序的启动和关闭,本例为启动和关闭一个python程序(每隔一秒打印hello,world),运行截图如下:
一、创建服务节点
handle.py
import rclpy
from rclpy.node import Node
from std_srvs.srv import SetBool
import subprocess
class ProgramControlNode(Node):
def __init__(self):
super().__init__('program_control_node')
self.srv = self.create_service(SetBool, 'control_program', self.control_program_callback)
self.process = None
def control_program_callback(self, request, response):
if request.data: # 启动 Python 程序
if self.process is None: # 确保没有进程正在运行
self.get_logger().info('Starting Python program...')
self.process = subprocess.Popen(["python3", "/home/wl/Desktop/test_ros_service/sevice.py"]) # 替换为你的 Python 脚本路径
response.success = True
response.message = "Python program started."
else:
response.success = False
response.message = "Python program is already running."
else: # 关闭 Python 程序
if self.process is not None:
self.get_logger().info('Stopping Python program...')
self.process.terminate()
self.process.wait()
self.process = None
response.success = True
response.message = "Python program stopped."
else:
response.success = False
response.message = "No Python program is running."
return response
def main(args=None):
rclpy.init(args=args)
node = ProgramControlNode()
rclpy.spin(node)
rclpy.shutdown()
if __name__ == '__main__':
main()
二、编写python程序
sevice.py
这里每隔一秒循环打印“Hello, World!"
import time
while True:
print("Hello, World!")
time.sleep(1)
三、执行ros2服务节点
python3 handle.py
四、调用服务,控制程序启动和关闭
# 启动程序
ros2 service call /control_program std_srvs/srv/SetBool "{data: true}"
# 关闭程序
ros2 service call /control_program std_srvs/srv/SetBool "{data: false}"