参考:
Bilibili@Autolabor
特点:
在一个事件的执行过程中,服务端可以持续反馈机器人当前的状态信息,同时当该过程执行结束时服务端返回执行结果
使用场景:
通信模型基于请求响应机制,执行事件需要一定时间,可以考虑Action通信
1、编写 .action文件
# 目标 goal
int32 num
---
# 最终响应 result
int32 result
---
# 连续反馈变量 feedback
float64 progress_bar
2、修改CMakelist.txt
# 添加
add_action_files{FILESAddInts.action
}
generate_messages{DEPENDENCIESactionlib_msgsstd_msgs
}
catkin_package{CATKIN_DEPENDS actionlib actionlib_msgs roscpp rospy std_msgs
}
3、编译生成中间文件 AddIntsAction.h
#include "ros/ros.h"
#include "actionlib/server/simple_action_server.h"
#include "编译生成的中间文件AddIntsAction.h"typedef actionlib::SimpleActionServer Server;// 回调函数
void cb(const demo01_action::AddIntsGoalConstPtr &goal,Server* server){//解析提交的目标值int goal_num = goalPtr -> num;ROS_INFO("Goal num is %d",num);//产生连续反馈ros::Rate rate(10); //10 Hzint result = 0;for (int i=1;i<=goal_num;i++) {result += i;rate.sleep();demo01_action::AddIntsFeedback fb;fb.progress_bar = i/(double)goal_num;server->publishFeedback(fb)}//发送最终结果demo01_action::AddIntsResult rsult;rsult.result = result;server->setSuccessded(rsult);
}int main(int argc, char *argv[])
{ros::init(argc,argv,"addInts_server");ros::NodeHandle nh;//由于他太长了,所以可以考虑typedef//下面两句话意思一致,二选一即可actionlib::SimpleActionServer server(nh,话题名,回调函数,自动启动); Server server(nh,话题名,boost::bind(&cb,_1,&server),自动启动);server.start();//如果auto_start为false,则需要这个函数启动服务ROS_INFO(“Server activated!”)ros::spin();return 0;
}
#include "ros/ros.h"
#include "actionlib/client/simple_action_client.h"
#include "demo01_action/AddIntsAction.h"
void done_cb(const actionlib::SimpleClientGoalState &state,const demo01_action::AddIntsResultConstPtr &result)
{//判断响应状态是否成功if(state.state_ == state.SUCCEEDED){ROS_INFO("Response succeed, result = %d",result->result);}else{ROS_INFO("Response failed");}
}
//激活回调
void active_cb()
{ROS_INFO("Connection has been set!");
}
//连续反馈的回调
void feedback_cb(const demo01_action::AddIntsFeedbackConstPtr &feedback)
{ROS_INFO("Processing:%.2f",feedback->progress_bar);
}
int main(int argc, char *argv[])
{ros::init(argc,argv,"addInts_Client");ros::NodeHandle nh;actionlib::SimpleActionClient client(nh,话题"addInts");//等待服务端启动client.waitForServer();ROS_INFO("Waiting for server")//发送目标数据demo01_action::AddIntsGoal goal;goal.num=100;client.sendGoal(goal,&done_cb,&active_cb,&feedback_cb);ros::spin();return 0;
}