当前位置:网站首页>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!"

边栏推荐
- 1.16 learning summary
- 0622-马棕榈跌9%
- JWT token authentication verification
- Motivational skills for achieving goals
- Modify the number of Oracle connections
- Numpy general function
- How can the intelligent transformation path of manufacturing enterprises be broken due to talent shortage and high cost?
- numpy 数据输入输出
- Physical design of database design (2)
- PIP batch complete uninstall package
猜你喜欢

Physical design of database design (2)

How to use the configured slave data source for the scheduled task configuration class scheduleconfig

SixTool-多功能多合一代挂助手源码
![PHP design function getmaxstr to find the longest symmetric string in a string - [original]](/img/45/d8dae9e605a2f411683db7a2d40d0b.jpg)
PHP design function getmaxstr to find the longest symmetric string in a string - [original]

Use of better scroll

Install Damon database

Resolve PHP is not an internal or external command

PHP small factory moves bricks for three years - interview series - my programming life

How can the intelligent transformation path of manufacturing enterprises be broken due to talent shortage and high cost?

ROS 笔记(07)— 客户端 Client 和服务端 Server 的实现
随机推荐
Rdkit chemical formula molecular formula search
Laravel access error could not be opened
numpy 数据输入输出
Fastadmin always prompts sqlstate[23000]: integrity constraint violation: 1052 column 'ID' in order clause is am
企业的产品服务怎么进行口碑营销?口碑营销可以找人代做吗?
Advanced learning of MySQL (learning from Shang Silicon Valley teacher Zhou Yang)
08_ Spingboot integrated redis
6、 Project practice --- identifying cats and dogs
小程序中实现视频通话及互动直播功能
PIP batch complete uninstall package
numpy 索引及切片
Multipass中文文档-提高挂载性能
2022.2.15
2022.1.24
Resolve PHP is not an internal or external command
Clean up photo SCR virus / iframekill injection removal /iframekill removal photo scr
TP5 distinct method paging problem
Gateway can not connect to tcp://127.0.0.1: Connection refused
1.21 learning summary
PHP has the problem of using strtotime to obtain time in months and months [original]