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

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

server

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]

client_d

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!"

server

原网站

版权声明
本文为[wohu1104]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206260435218395.html