SimpleActionServer端(Python)

SimpleActionServer端创建流程

1. 初始化ROS,创建节点

1
rospy.init_node(nodeName)

2. 创建Action的Server端

1
2
server = actionlib.SimpleActionServer(actionName, CountNumberAction, execute_cb=callback, auto_start=False)
server.start()

Tip

我们需要引入actionlib这个依赖库,添加头文件依赖

import actionlib

actionlib.SimpleActionServer: Action的Server端对应的类。

第一个参数:当前action的名称

第二个参数:接收的Action消息类型

第三个参数:是client端访问server端的回调

第四个参数:是否自动开启server

3. Server端的业务逻辑

server端的业务逻辑,主要是用于处理client请求的回调。用于结果反馈和过程反馈,提供简单示例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
def callback(goal):
    rospy.loginfo(goal)
    # 获得请求数据
    max = goal.max
    duration = goal.duration

    rate = rospy.Rate(1.0 / duration)
    count = 0
    while not rospy.is_shutdown() and count < max:
        feedback = CountNumberFeedback()
        feedback.percent = count * 100.0 / max
        server.publish_feedback(feedback)

        rate.sleep()
        count += 1

    # 发送结果
    result = CountNumberResult(count=count)
    server.set_succeeded(result)

完整代码

 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
#!/usr/bin/env python
# coding:utf-8

import rospy
import actionlib
from actionlib import GoalStatus
from demo_actions.msg import CountNumberAction, CountNumberResult, CountNumberFeedback

server = None

def callback(goal):
    rospy.loginfo(goal)
    # 获得请求数据
    max = goal.max
    duration = goal.duration

    rate = rospy.Rate(1.0 / duration)
    count = 0
    while not rospy.is_shutdown() and count < max:
        feedback = CountNumberFeedback()
        feedback.percent = count * 100.0 / max
        server.publish_feedback(feedback)

        rate.sleep()
        count += 1

    # 发送结果
    result = CountNumberResult(count=count)
    server.set_succeeded(result)


if __name__ == '__main__':
    nodeName = "CountNumberServer"
    actionName = "/count_number"

    # 创建节点
    rospy.init_node(nodeName)

    # 创建Action的服务端
    server = actionlib.SimpleActionServer(actionName, CountNumberAction, execute_cb=callback, auto_start=False)
    server.start()

    # 开启轮询器阻塞线程
    rospy.spin()

调试Server端

调试server端主要是查看server端是否能接收到请求,并根据请求数据处理相应的业务逻辑,然后返回处理好的结果。

在这里,我们只需要模拟client端发送请求就可以了。

在这里,我们需要模拟以下情况:

  • client端发送Goal
  • client端接收到的Feedback反馈
  • client端接收到的Result反馈

ROS提供了命令行工具和图形化工具供我们调试开发。

1. 通过ros命令进行调试

client端接收到的Feedback反馈

1
rosttopic echo /count_number/feedback

client端接收到的Result反馈

1
rostopic echo /count_number/result

client端发送Goal

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
rostopic pub /count_number/goal demo_actions/CountNumberActionGoal "header:
  seq: 0
  stamp:
    secs: 0
    nsecs: 0
  frame_id: ''
goal_id:
  stamp:
    secs: 0
    nsecs: 0
  id: ''
goal:
  max: 1000
  duration: 0.1"

2. 通过rqt工具进行调试

client端接收到的Feedback反馈

1
rosrun rqt_topic rqt_topic

client端接收到的Result反馈

1
rosrun rqt_topic rqt_topic

client端发送Goal

1
rosrun rqt_publisher rqt_publisher