Keypoints
- ROS Client
#include <ros/ros.h>
#include <turtlesim/Spawn.h>
int main(int argc, char **argv)
{
// Initialize the ROS system and become a node.
ros::init(argc, argv, "turtle_spawn");
ros::NodeHandle nh;
// Wait for the service to appear. Otherwise, the client will stop here.
ros::service::waitForService("/spawn");
// Create a service client object. Name the client as add_turtle. <> is the type of service. "/spawn" is the name of service.
ros::ServiceClient add_turtle = nh.serviceClient<turtlesim::Spawn>("/spawn");
// Initialize the service object. Name it as srv.
turtlesim::Spawn srv;
srv.request.x = 2.0;
srv.request.y = 2.0;
srv.request.name = "Leo";
// Call the service.
ROS_INGO("Call service to spawn turtle Leo [x: %0.6f, y: %0.6f, name: %s]", srv.request.x, srv.request.y, srv.request.name.c_str());
add_turtle.call(srv); // Wait for the response from the service. If the service is not available, the client will wait forever and stop here. So, client/server is synchronous.
// Print the service response.
ROS_INFO("Spawn turtle successfully [name: %s]", srv.response.name.c_str());
return 0;
}
add_executable(turtle_spawn src/turtle_spawn.cpp) ## compile the cpp file turtle_spawncpp into an executable file turtle_spawn in /rosleaning/devel/lib/learning_service/turtle_spawn
target_link_libraries(turtle_spawn ${catkin_LIBRARIES}) ## link the executable file turtle_spawn with the libraries in catkin_LIBRARIES
catkin_make
to compile the cpp filesource devel/setup.bash
roscore
to start the master noderosrun turtlesim turtlesim_node
to start the turtlesim noderosrun learning_service turtle_spawn
to start the client node#!/usr/bin/env python
# -*- coding: utf-8 -*-
import rospy
import sys
from turtlesim.srv import Spawn
def turtle_spawn():
# Initialize the ROS system and become a node.
rospy.init_node('turtle_spawn')
# Wait for the service to appear. Otherwise, the client will stop here.
rospy.wait_for_service('/spawn')
try:
add_turtle = rospy.ServiceProxy('/spawn', Spawn) # Create a service client object. Name the client as add_turtle. Spawn is the type of service. "/spawn" is the name of service.
# Call the service. Input the parameters.
response = add_turtle(2.0, 2.0, 0.0, "Leo") # Wait for the response from the service. If the service is not available, the client will wait forever and stop here. So, client/server is synchronous.
return response.name
except rospy.ServiceException, e:
print ("Service call failed: %s"%e)
if __name__ == "__main__":
print ("Spawn turtle successfully [name: %s]" % turtle_spawn())
chmod +x turtle_spawn.py
or right click the file -> properties -> permissions -> allow executing file as program