当前位置:网站首页>ROS notes (07) - Implementation of client and server
ROS notes (07) - Implementation of client and server
2022-06-26 04:40:00 【wohu1104】
Service communication is also ROS A very common communication mode in , Service communication is based on request response pattern , It's a response mechanism . That is to say : A node A To another node B Send a request ,B Receive and process the request and generate a response. The result is returned to A. For example, the following scenes :
During the robot patrol , The control system analyzes the sensor data and finds suspicious objects or people … At this time, you need to take photos and keep them .
In the above scenario , Service communication is used .
A node needs to send a photographing request to the camera node , The camera node processes the request , And return the processing result
Similar to the above applications , Service communication is more suitable for those who require timeliness 、 Application scenarios with certain logical processing .
Service communication is simpler than topic communication , The theoretical model is shown in the figure below , There are three roles involved in the model :
ROS master( managers )Server( Server side )Client( client )
ROS Master Responsible for keeping Server and Client Registered information , And match the same topic Server And Client , help Server And Client Establishing a connection , After the connection is established ,Client Send request information ,Server Return response information .
1. client
1.1 Client model
The client model is as follows :
1.2 Create Feature Pack
Be careful : Must be in Of the workspace src Create a function package under the directory .
$ cd ros_demo/src/
$ catkin_create_pkg service_client roscpp rospy std_msgs geometry_msgs turtlesim
1.3 Client code
client.py Code
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# The routine will request /spawn service , Service data type turtlesim::Spawn
import sys
import rospy
from turtlesim.srv import Spawn
def turtle_spawn():
# ROS Node initialization
rospy.init_node('turtle_spawn')
# Find out /spawn After service , Create a service client , The connection name is /spawn Of service
rospy.wait_for_service('/spawn')
try:
add_turtle = rospy.ServiceProxy('/spawn', Spawn)
# Request service call , Enter request data
response = add_turtle(2.0, 2.0, 0.0, "turtle2")
return response.name
except rospy.ServiceException, e:
print "Service call failed: %s"%e
if __name__ == "__main__":
# The service calls and displays the call result
print "Spwan turtle successfully [name:%s]" %(turtle_spawn())
2. Server side
2.1 Server model

2.2 Server code
server.py Content :
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# The routine will execute /turtle_command service , Service data type std_srvs/Trigger
import rospy
import thread,time
from geometry_msgs.msg import Twist
from std_srvs.srv import Trigger, TriggerResponse
pubCommand = False;
turtle_vel_pub = rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size=10)
def command_thread():
while True:
if pubCommand:
vel_msg = Twist()
vel_msg.linear.x = 0.5
vel_msg.angular.z = 0.2
turtle_vel_pub.publish(vel_msg)
time.sleep(0.1)
def commandCallback(req):
global pubCommand
pubCommand = bool(1-pubCommand)
# Display request data
rospy.loginfo("Publish turtle velocity command![%d]", pubCommand)
# Feedback data
return TriggerResponse(1, "Change turtle command state!")
def turtle_command_server():
# ROS Node initialization
rospy.init_node('turtle_command_server')
# Create a file called /turtle_command Of server, Register callback function commandCallback
s = rospy.Service('/turtle_command', Trigger, commandCallback)
# Loop waiting for callback function
print "Ready to receive turtle command."
thread.start_new_thread(command_thread, ())
rospy.spin()
if __name__ == "__main__":
turtle_command_server()
3. Run code
3.1 Running client
$ cd ~/catkin_ws
$ catkin_make
$ source devel/setup.bash
$ rescore
$ rosrun turtlesim turtlesim_node
$ rosrun service_client client.py
Running results :
$ rosrun service_client client.py
Spwan turtle successfully [name:turtle2]

3.2 Running server
$ cd ~/catkin_ws
$ catkin_make
$ source devel/setup.bash
$ rescore
$ rosrun turtlesim turtlesim_node
Open two new command line terminals respectively , Execute the following command
$ rosrun service_client server.py
Ready to receive turtle command.
[INFO] [1655691376.455429]: Publish turtle velocity command![1]
[INFO] [1655691386.447185]: Publish turtle velocity command![0]
[INFO] [1655703701.212224]: Publish turtle velocity command![1]
[INFO] [1655703752.681859]: Publish turtle velocity command![0]
$ rosservice call /turtle_command "{}"
success: True
message: "Change turtle command state!"
$ rosservice call /turtle_command "{}"
success: True
message: "Change turtle command state!"

边栏推荐
- Your requirements could not be resolved
- Nabicat连接:本地Mysql&&云服务Mysql以及报错
- 1.14 learning summary
- Install SVN in Pagoda and build SVN version Library
- Guide de la pompe de données Oracle
- Group by and order by are used together
- OSS CDN alicloud configuration method
- Introduction to markdown grammar
- 08_SpingBoot 集成Redis
- Sort query
猜你喜欢
随机推荐
Multipass中文文档-提高挂载性能
An unexpected attempt (Imperial CMS list template filters spaces and newlines in smalltext introduction)
小程序中实现视频通话及互动直播功能
The select option in laravel admin contains a large amount of data
Navicat connects the pit of shardingsphere sub table and sub library plug-ins
[geek challenge 2019] rce me
Alipay failed to verify the signature (sandbox test indicates fishing risk?) [original]
[H5 development] 03- take you hand in hand to improve H5 development - single submission vs batch submission with a common interface
Oracle 数据泵导表
Solution to composer error could not find package
Navicat connects the pit of shardingsphere sub table and sub library plug-ins
Mobile terminal pull-down loading pull-down loading data
做软件测试学历重要还是能力重要
Multipass中文文档-远程使用Multipass
1.12 learning summary
22.2.8
Laravel file stream download file
Laravel framework Alipay payment fails to receive asynchronous callback request [original]
1.17 learning summary
Database design (I)

![Notes on enterprise wechat development [original]](/img/66/cd83f4f86b7c42921db45f07957c15.jpg)
![[geek challenge 2019] rce me](/img/92/978c54fb42391198300c76ae92893d.jpg)






