10.ROS service server

In the previous tutorial, we talked about how to write a client node program, so this program will explain how to write a server node. The server has a service callback function, which can be compared to the callback function of a topic subscriber. After receiving the request for service, describe the specific service content in the service callback function, and then return a response value.

10.1 Create a server

The general creation steps are as follows:

10.2 C++ version

10.2.1 Writing source code

In the src folder of the function package learn_server, create a C++ file (the file suffix is .cpp), name it turtle_vel_command_server.cpp, and paste the following content into turtle_vel_command_server.cpp.

10.2.2 Modify CMakeLists.txt file

Configure in CMakelist.txt, under the build area, add the following content,

10.2.3 Compile

Terminal input,

image-20231024094607120

After the compilation is passed, you need to re-source the current environment variables to find or update the program. Enter in the terminal.

10.2.4 Running the program

Open roscore,

Run the little turtle node program,

Run the server node,

Calling a service,

Program running instructions:

First, after running the Little Turtle node, you can enter rosservice list in the terminal to see what services are currently available. The results are as follows:

image-20231024094707528

Then, we run the turtle_vel_command_server program and enter rosservice list, and we will find that there is an additional turtle_vel_command, as shown in the figure below,

image-20231024094824003

Then, we call this service by entering rosservice call /turtle_vel_command in the terminal, and we will find that the little turtle makes a circular motion. If we call the service again, the little turtle stops moving. This is because in the service callback function, we invert the value of pubvel and then feed it back. The main function will judge the value of pubvel. If it is True, the speed command will be issued. If it is False, no command will be issued.

image-20231024095011574

 

10.3 Python version

10.3.1 Writing source code

Create a new scripts folder under the function package learn_service, then create a new python file (file suffix .py) in this scripts folder, name it turtle_vel_command_server.py, copy and paste the following program code into the turtle_vel_command_server.py file,

10.3.2 Running the program

Open roscore,

Run the little turtle node program,

Run the server node,

Calling a service,

Enter rosservice call /turtle_vel_command in the terminal to call this service. You will find that the little turtle moves in a circle. If you call the service again, the little turtle stops moving.

image-20231024100444523