Creating the ROS action client
In this section, we will discuss the workings of an action client. demo_action_client.cpp is the action client node that will send the goal value consisting of a number which is the goal. The client is getting the goal value from the command-line arguments. The first command-line argument of the client is the goal value, and the second is the time of completion for this task.
The goal value will be sent to the server and the client will wait until the given time, in seconds. After waiting, the client will check whether it completed or not; if it is not complete, the client will preempt the action.
The client code is a bit lengthy, so we will discuss the important sections of the code:
#include <actionlib/client/simple_action_client.h> #include <actionlib/client/terminal_state.h> #include "mastering_ros_demo_pkg/Demo_actionAction.h"
In the action client, we need to include actionlib/client/simple_action_client.h to get the action client APIs, which are used to implement action clients:
actionlib::SimpleActionClient<mastering_ros_demo_pkg::Demo_actionAction> ac("demo_action", true);
This will create an action client instance:
ac.waitForServer();
This line will wait for an infinite time if there is no action server running on the system. It will exit only when there is an action server running on the system:
mastering_ros_demo_pkg::Demo_actionGoal goal; goal.count = atoi(argv[1]); ac.sendGoal(goal);
Create an instance of a goal, and send the goal value from the first command line argument:
bool finished_before_timeout = ac.waitForResult(ros::Duration(atoi(argv[2])));
This line will wait for the result from the server until the given seconds:
ac.cancelGoal();
If it is not finished, it will preempt the action.