8 Server

In the last lesson, we talked about the client requesting the service, and then the server providing the service. In this lesson, we will talk about how the server implements the service.

8.1 C++ language implementation

8.1.1 Implementation steps

  1. initialize the ROS node
  2. create a Server instance
  3. wait for the service request in a loop, enter the callback function
  4. complete the functional processing of the service in the callback function, and feedback the response data

8.1.2 Switch to the ~/catkin_ws/src/learning_server/src directory, create a new .cpp file, name it turtle_vel_command_server, and paste the code below into it

turtle_vel_command_server.cpp

  1. program flow chart

image-20220427143845105

  1. configure in CMakelist.txt, under the build area, add the following content
  1. Compile the code in the workspace directory
  1. run the program
  1. Screenshot of running effect

image-20220225114532861

  1. program description

First, after running the little turtle node, you can enter rosservice list in the terminal to see what the current services are. The results are as follows

image-20220219112052144

Then, we run the turtle_vel_command_server program, and then enter the rosservice list, we will find an additional turtle_vel_command_server, as shown in the following figure

image-20220225114746807

Then, we call this service by entering rosservice call /turtle_vel_command_server in the terminal, and we will find that the small turtle moves in a circle. If the service is called again, the small 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, it will issue a speed command, and if it is False, no command will be issued.

8.2 Python language implementation

8.2.1 Switch to the ~/catkin_ws/src/learning_server directory, create a new script folder, cut it in, create a new py file, name it turtle_vel_command_server, and paste the code below into it

turtle_vel_command_server.py

  1. program flow chart

image-20220427143957140

  1. run the program
  1. The program operation effect and program description are consistent with the effect realized by C++.