Ros服务通讯方式实现
思路:
1.服务分为客户端(Client)和服务器(Server),客户端用于发送请求,服务器接受请求后执行回调函数并回复客户端。
2.Client端程序实现发送/Spawn请求生成新的小乌龟,并得到回复
3.Server端实现接受自定义/turtle_command请求,回复并创建Publisher向/turtel1/cmd_vel话题发布消息
Client
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time:2021/9/12 下午5:01
# @Author:ljt
import rospy
import numpy as np
from turtlesim.srv import Spawn
def turtle_spawn(num):
#初始化节点
rospy.init_node('turtle_spawn')
#等待开启服务‘/spawn’
rospy.wait_for_service('/spawn')
#定义客户端
add_turtle=rospy.ServiceProxy('/spawn',Spawn)
x=np.random.rand(2)*11
#客户端发送消息并等待回复(回复为response)
response=add_turtle(x[0],x[1],0.0,'turtle'+str(num))
return response.name
if __name__=='__main__':
n=3
for i in range(2,n+1):
print('Spawn turtle successfully [name:{0}]'.\
format(turtle_spawn(i)))
Server
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time:2021/9/12 下午9:41
# @Author:ljt
import rospy
from std_srvs.srv import Trigger,TriggerResponse
from geometry_msgs.msg import Twist
import thread
global Flag
def Publisher_topic():
rate=rospy.Rate(10)
print("I'm working!")
while(1):
if (Flag):
publish=rospy.Publisher('/turtle1/cmd_vel',Twist,queue_size=10)
msg=Twist()
msg.linear.x=0.2
msg.angular.z=0.5
publish.publish(msg)
rate.sleep()
def CallbackFunction(msg):
global Flag
Flag=bool(1-Flag)
print('Response has completed!')
return TriggerResponse(1,'TriggerResponce')
def turtle_command():
rospy.init_node('turtel_command',anonymous=True)
server=rospy.Service('/turtle_command',Trigger,CallbackFunction)
thread.start_new_thread(Publisher_topic,())
rospy.spin()
if __name__=='__main__':
Flag=False
turtle_command()
备注:
rospy.spin()为循环等待接受请求,需开设另一个线程用于创建平Publisher并发布话题
thread.start_new_thread(Function,())
publisher单次发布需要在发布前等待3s以上,subscriber才能接,主要是等待Publisher的定义及设置完成。