1.scripts/add_two_ints_server.py

来源:互联网 发布:java手机开发工具 编辑:程序博客网 时间:2024/06/07 18:24

1.scripts/add_two_ints_server.py

#!/usr/bin/env pythonfrom beginner_tutorials.srv import *import rospydef handle_add_two_ints(req):    print "Returning [%s + %s = %s]"%(req.a, req.b, (req.a + req.b))    return AddTwoIntsResponse(req.a + req.b)def add_two_ints_server():    rospy.init_node('add_two_ints_server')    s = rospy.Service('add_two_ints', AddTwoInts, handle_add_two_ints)    print "Ready to add two ints."    rospy.spin()if __name__ == "__main__":    add_two_ints_server()

2. scripts/add_two_ints_client.py

#!/usr/bin/env pythonimport sysimport rospyfrom beginner_tutorials.srv import *def add_two_ints_client(x, y):    rospy.wait_for_service('add_two_ints')    try:        add_two_ints = rospy.ServiceProxy('add_two_ints', AddTwoInts)        resp1 = add_two_ints(x, y)        return resp1.sum    except rospy.ServiceException, e:        print "Service call failed: %s"%edef usage():    return "%s [x y]"%sys.argv[0]if __name__ == "__main__":    if len(sys.argv) == 3:        x = int(sys.argv[1])        y = int(sys.argv[2])    else:        print usage()        sys.exit(1)    print "Requesting %s+%s"%(x, y)    print "%s + %s = %s"%(x, y, add_two_ints_client(x, y))

3.rosed beginner_tutorials talker.py

#!/usr/bin/env python# license removed for brevityimport rospyfrom std_msgs.msg import Stringdef talker():    pub = rospy.Publisher('chatter', String, queue_size=10)    rospy.init_node('talker', anonymous=True)    rate = rospy.Rate(10) # 10hz    while not rospy.is_shutdown():        hello_str = "hello world %s" % rospy.get_time()        rospy.loginfo(hello_str)        pub.publish(hello_str)        rate.sleep()if __name__ == '__main__':    try:        talker()    except rospy.ROSInterruptException:        pass

4.Download the listener.py

#!/usr/bin/env pythonimport rospyfrom std_msgs.msg import Stringdef callback(data):    rospy.loginfo(rospy.get_caller_id() + "I heard %s", data.data)    def listener():    # In ROS, nodes are uniquely named. If two nodes with the same    # node are launched, the previous one is kicked off. The    # anonymous=True flag means that rospy will choose a unique    # name for our 'listener' node so that multiple listeners can    # run simultaneously.    rospy.init_node('listener', anonymous=True)    rospy.Subscriber("chatter", String, callback)    # spin() simply keeps python from exiting until this node is stopped    rospy.spin()if __name__ == '__main__':    listener()



原创粉丝点击