yahboom
HomeLearn
Solution
Blog
Online Store
About Us
EN/中文
Raspberry Pi 4B📖
1.Preparation before use
  • 1.1 Download image
  • 1.2 Write image into SD card
  • 1.3 Start up Raspberry Pi
  • 1.4 Linux common commands
  • 1.5 Precautions
2.Basic course
  • 2.1 Log into Raspberry Pi system
  • 2.2 Change password and root account
  • 2.3 Remote transfer file
  • 2.4 Backup image file
  • 2.5 Fixing Raspberry Pi IP
  • 2.6 Set screen keep on
  • 2.7 Get Pi temperature
  • 2.8 Connect WIFI
  • 2.9 Modify Pi time
  • 2.10 Set the boot self-starting program
3.Expand course
  • 3.1 Serial port communicates with external devices
  • 3.2 2.Serial port login Pi
  • 3.3 Configured as a router
  • 3.4 Install Jupyter Lab
  • 3.5 Install Jupyter Widgets
  • 3.6 More Detail for Widgets
  • 3.7 Install OpenCV
  • 3.8 Install Tensorflow
4.Programming course
C language
  • 1.Development environment
  • 2.Print Hello World
  • 3.Pin output level
  • 4.Read pin level
  • 5.PWM output
Python language
  • 1.Development environment
  • 2.Print basic usage
  • 3.Pin output level
  • 4.Read pin level
  • 5.PWM output
5.AI vision course
A.Getting started with OpenCV
  • 6.Picture Rotation
  • 1.Introduction of OpenCV
  • 2.OpenCV image read and display
  • 3.OpenCV image write
  • 4.OpenCV image quality
  • 5.OpenCV pixel operation
B.OpenCV Geometric transformat
  • 1.Picture Zoom
  • 2.Picture Cut
  • 3.Picture Shift
  • 4.Picture Mirroring
  • 5.Affine Map
  • 7.Perspective Transformation
C.OpenCV picture processing
  • 1.Grayscale processing
  • 2.Image Binarization
  • 3.Edge detection
  • 4.Drawing line segment
  • 5.Drawing rectangle circle
  • 6.Drawing text picture
D.OpenCV image beautification
  • 1.Histogram of color pictures
  • 2.Histogram equalization
  • 3.Image restoration
  • 4.Brightness enhancement
  • 5.Skin whitening
  • 6.Gaussian mean filtering
  • 7.Median filtering
F.AI Advanced Course (Ubuntu system)
  • 1. QR code
  • 2. Human posture estimation
  • 3. Target detection
  • 4. Mediapipe development
  • 5. yolov4-tiny
E.Install TensorFlow
  • Install TensorFlow
6.ROS1 coursenew
Basic Course
  • 1.ROS introduction
  • 2.Project file structure
  • 3.Common commands and tools
  • 4.Publisher
  • 5.Subscribers
  • 6.Customize topic messages and use
  • 7.Client
  • 8.Server
  • 9.Custom service messages and usage
  • 10.TF release and monitoring
Visual Image Processing
  • 1. AR vision
  • 2. AR QR code
  • 3. ROS+Opencv foundation
  • 4. ROS+Opencv application
  • 5. MediaPipe development
7.ROS2 coursenew
Docker Course
  • 1.Overview and installation
  • 2.Common commands
  • 3.Understand and publish images
  • 4.Hardware interaction data processing
  • 5.Enter docker container
  • 6.Update docker images
Basic Course
  • 1.Introduction to ROS2
  • 2.Commands and tools
  • 3.ROS2 Topic communications
  • 4.ROS2 service communications
  • 5.ROS2launch file starts
OpenCV Course
  • 1.OpenCV Basic Course
  • 2.ROS+opencv application
  • 3.QR code recognition
  • 4.AR Vision
  • 5.Mediapipe
8.Accessories installation
  • 1. Installation of heat sink
  • 2. Wiring of cooling fan
  • 3. Double fan armor case Installation
  • 4. Argon NEO aluminum case installation
  • 5. Argon ONE aluminum alloy case installation
  • 6. Metal shell with built-in fan installation
  • 7. Acrylic case with cooling fan installation
  • 8. White-red ABS protective case installation
Download
  • Tools
  • C_code
  • Python code
  • ROS System
Download ZIP

Welcome to Raspberry Pi 4B repository

4.ROS2 service communications

ROS2 service communications

Service communication is one of the communication methods of ROS2 nodes, which is different from topic communication in that service communication has a feedback mechanism, which will feedback the results of the service. Therefore, service communication is mostly used in programs that need feedback results, such as the routine of a baby turtle, calling the Spawn service to generate a turtle, and after the service is completed (after the turtle is generated), the turtle's name will be printed. Next, it is explained how to use the Python language to achieve service communication between nodes.

1、Create a new feature pack

src new function package in the previously created workspace directory, terminal input,

cd ~/ros2_ws/src
ros2 pkg create --build-type ament_python service_pkg

image-20230504104704846

2、Write server-side python files

2.1、Program source code

Create a new file, named server_demo.py,

xxxxxxxxxx
cd ~/ros2_ws/src/service_pkg/service_pkg
gedit server_demo.py

Copy the following sections into the file,

​x
#Import the relevant library files
import rclpy
from rclpy.node import Node
from example_interfaces.srv import AddTwoInts

class Service_Server(Node):
    def __init__(self,name):
        super().__init__(name)
        #To create a server, use create_service function, and the parameters passed in are:
        #The data type of the service data, the name of the service, and the service callback function (that is, the content of the service)
        self.srv = self.create_service(AddTwoInts, '/add_two_ints', self.Add2Ints_callback)
    #The content of the service callback function here is to add two integer numbers and return the result of the addition
    def Add2Ints_callback(self,request,response):
        response.sum = request.a + request.b
        print("response.sum = ",response.sum)
        return response
def main():
    rclpy.init()
    server_demo = Service_Server("publisher_node")
    rclpy.spin(server_demo)

Focus on the service callback function, Add2Ints_callback, in addition to self, there are also request and response, request is the parameter required by the service, and response is the feedback result of the service. request.a and request.b are the content of the request part, response.sum is the content of the response part, here first look at the AddTwoInts type of data is how, you can use the following command to view,

xxxxxxxxxx
ros2 interface show example_interfaces/srv/AddTwoInts

image-20230504110250103

--- The section divides this type of data into two parts, the upper side represents the request and the lower side represents the response. Then the variables in each domain, such as int64 a and int64 b, all the parameters passed in need to specify what the value of a and b is. Similarly, the result of the feedback also needs to specify what the value of sum is.

2.2、Modify the setup.py file

terminal input,

xxxxxxxxxx
cd ~/ros2_ws/src/service_pkg
gedit setup.py

Locate the location as shown in the image below,

image-20230504110847633

Add the following to 'console_scripts': [].

xxxxxxxxxx
'server_demo = service_pkg.server_demo:main'

2.3、Compile the workspace

xxxxxxxxxx
cd ~/ros2_ws
colcon build

After the compilation is completed, refresh the environment variables of the workspace.

xxxxxxxxxx
source ~/ros2_ws/install/setup.bash

2.4、Run the program

terminal input,

xxxxxxxxxx
ros2 run service_pkg server_demo 

After running, because the service is not called, there is no feedback data, you can call the service through the command line, first query what services are currently available, terminal input,

xxxxxxxxxx
ros2 service list

image-20230504111607795

/add_two_ints is the service we need to call, call it through the following command, terminal input,

xxxxxxxxxx
ros2 service call /add_two_ints example_interfaces/srv/AddTwoInts "{a: 1,b: 4}"

Here we assign the value of a to 1 and the value of b to 4, that is, call the service to calculate the sum of 1 and 4,

image-20230504111848803

As can be seen from the above figure, after calling the service, the result of the feedback is 5, and the terminal running the server also prints the value of the feedback.

3、Write a client python file

3.1、Program source code

Create a new file, named client_demo.py,

xxxxxxxxxx
cd ~/ros2_ws/srcservice_pkg/service_pkg
gedit client_demo.py

Copy the following into it,

xxxxxxxxxx
#Import the relevant libraries
import rclpy
from rclpy.node import Node
from example_interfaces.srv import AddTwoInts

class Service_Client(Node):
    def __init__(self,name):
        super().__init__(name)
        #To create a client, you use create_client function, and the parameters passed in are the data type of the service data and the topic name of the service
        self.client = self.create_client(AddTwoInts,'/add_two_ints')
        #Cycle through and wait for the server side to start successfully
        while not self.client.wait_for_service(timeout_sec=1.0):
            print("service not available, waiting again...")
        #Create a data object for the service request
        self.request = AddTwoInts.Request()
        
    def send_request(self): 
        self.request.a = 10
        self.request.b = 90
        #Send a service request
        self.future = self.client.call_async(self.request)
        
def main():
    rclpy.init() #Node initialization
    service_client = Service_Client("client_node") #Create an object
    service_client.send_request() #Send a service request
    while rclpy.ok():
        rclpy.spin_once(service_client)
        #Determine whether the data processing is complete
        if service_client.future.done():
            try:
                #Get service feedback information and print it
                response = service_client.future.result()
                print("Result = ",response.sum)
            except Exception as e:
                service_client.get_logger().info('Service call failed %r' % (e,))
            
        break

3.2、Modify the setup.py file

terminal input,

xxxxxxxxxx
cd ~/ros2_ws/src/topic_pkg
gedit setup.py

Locate the location as shown in the image below,

image-20230504143449133

Add the following to 'console_scripts': [],

xxxxxxxxxx
'client_demo = service_pkg.client_demo:main'

image-20230504143713966

3.3、Compile the workspace

xxxxxxxxxx
cd ~/ros2_ws
colcon build

After the compilation is completed, refresh the environment variables of the workspace.

xxxxxxxxxx
source ~/ros2_ws/install/setup.bash

3.4、Run the program

terminal input,

xxxxxxxxxx
#Start the server
ros2 run service_pkg server_demo
#Start the client
ros2 run service_pkg client_demo

image-20230504144109703

First run the server, then run the client, the client provides a=10, b=90, the server summes, the result is 100, and the result is printed at the two terminals.

ROS2 Topic communications
ROS2launch file starts

COMPANY

  • About us
  • Team Style
  • Blog

LEARNING & EXPLORATION

  • Tutorials
  • Edge AI hardware
  • Educational robots
  • Embedded intelligent hardware

WHERE TO BUY

  • Yahboom Online Store
  • Amazon
  • Alibaba
  • AliExpress
  • Mercado

TECHNOLOGY SUPPORT

  • Email: support@yahboom.com

BE A DISTRIBUTOR

  • Email: sales@yahboom.com
QR Code
QR Code

Copyright © 2017-2026 Yahboom. All Rights Reserved.

EN/中文