通过ros2服务来控制程序的启动和关闭

运行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}"

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值