ros1 Basic Learning 07 - Simulate the client to generate a little turtle and the service request to generate a little turtle

1. Topic model

The Sever side is the turtle simulator/turtlesim, and the Client side is the program to be implemented. It serves as the node of Response and generates Request requests and sends them to the Server side. The Server generates a turtle after receiving the Request request, and returns a Response to the Client to determine whether the turtle generation is successful. The name of the Service is /spawn, and the data structure for intermediate message transmission is turtlesim::Spawn. ROS Master is responsible for managing nodes.

How to generate a little turtle:
The first way:
You can generate a second little turtle with the following command

rosservice call /spawn 4 4 0 turtle2

turtle2 is the name of the little turtle

Insert image description here

The second type:

2. Create function packages

Create a new feature package learning_service

cd ~/catkin_ws/src
catkin_create_pkg learning_service roscpp rospy std_msgs geometry_msgs turtlesim

Insert image description here

3. Create client client code

Create a new file turtle_spawn.cpp in learning_service/src

/**
 * 该例程将请求/spawn服务,服务数据类型turtlesim::Spawn
 */

#include <ros/ros.h>
#include <turtlesim/Spawn.h>

int main(int argc, char** argv)
{
    
    
    // 初始化ROS节点
	ros::init(argc, argv, "turtle_spawn");

    // 创建节点句柄
	ros::NodeHandle node;

    // 发现/spawn服务后,创建一个服务客户端,连接名为/spawn的service
	ros::service::waitForService("/spawn");
	ros::ServiceClient add_turtle = node.serviceClient<turtlesim::Spawn>("/spawn");

    // 初始化turtlesim::Spawn的请求数据
	turtlesim::Spawn srv;
	srv.request.x = 2.0;
	srv.request.y = 2.0;
	srv.request.name = "turtle2";

    // 请求服务调用
	ROS_INFO("Call service to spwan turtle[x:%0.6f, y:%0.6f, name:%s]", 
			 srv.request.x, srv.request.y, srv.request.name.c_str());

	add_turtle.call(srv);

	// 显示服务调用结果
	ROS_INFO("Spwan turtle successfully [name:%s]", srv.response.name.c_str());

	return 0;
};

4. Configure CMakeLists.txt compilation rules:

add_executable(turtle_spawn src/turtle_spawn.cpp)
target_link_libraries(turtle_spawn ${
    
    catkin_LIBRARIES})

Compile:

cd ~/catkin_ws
catkin_make

If there are permission issues, switch to the root user to continue execution.

Five tests

Start the ros main service

roscore

Insert image description here

Start the service of Little Turtle

rosrun turtlesim turtlesim_node

Insert image description here

Start the model client service

rosrun learning_service turtle_spawn

running result:

Insert image description here

As you can see from the picture, the little turtle below is generated by starting the model client.

Guess you like

Origin blog.csdn.net/hai411741962/article/details/134317957