服务端
import time, thread
import rospy
from geometry_msgs.msg import Twist
from std_srvs.srv import Trigger, TriggerResponse
pubcommand = False
tpub = rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size=10)
def command_thread():
while True:
if pubcommand:
v = Twist()
v.linear.x = 0.5
v.angular.z = 0.5
tpub.publish(v)
time.sleep(0.1)
def callback(req):
global pubcommand
pubcommand = bool(1 - pubcommand)
rospy.loginfo("call the callback! %s", pubcommand)
return TriggerResponse(1, "change!")
def simpleservice():
rospy.init_node('sxcservice')
s = rospy.Service('/turtle_command', Trigger, callback)
print 'wait!!'
thread.start_new_thread(command_thread, ())
rospy.spin()
if __name__ == '__main__':
simpleservice()
客户端
import rospy
from turtlesim.srv import Spawn
def turtle_spawn():
rospy.init_node('addturtle')
rospy.wait_for_service('/spawn')
try:
add_turtle = rospy.ServiceProxy('/spawn', Spawn)
response = add_turtle(2, 2, 0, 'sxc')
return response.name
except rospy.ServiceException, e:
print e
if __name__ == '__main__':
rospy.loginfo("creat turtle,name: %s", (turtle_spawn()))