ROS入门记录 [4]

    xiaoxiao2021-04-05  43

    Tutorial——Beginner Level 1

    15. Writing a Simple Service and Client (Python)

    写一个service node

    $ roscd beginner_tutorials $ vi scripts/add_two_ints_server.py $ chmod +x scripts/add_two_ints_server.py

    add_two_ints_server.py的内容,解释链接

    #!/usr/bin/env python from beginner_tutorials.srv import * import rospy def 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()

    写一个client node

    $ vi scripts/add_two_ints_client.py $ chmod +x scripts/add_two_ints_client.py

    add_two_ints_client.py的内容,解释链接

    #!/usr/bin/env python import sys import rospy from 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"%e def 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))

    Build and Try

    # 启动service节点 $ cd ~/catkin_ws $ . devel/setup.bash $ rosrun beginner_tutorials add_two_ints_server.py # 在新的terminal窗口启动client节点 $ cd ~/catkin_ws $ . devel/setup.bash $ rosrun beginner_tutorials add_two_ints_client.py 4 5 # 可以得到4 + 5 = 9
    转载请注明原文地址: https://ju.6miu.com/read-666367.html

    最新回复(0)