Python on ROS - (1) - Service & Client

Services:

ROSServices are defined bysrv files, which contains a request message and a response message. These are identical to the messages used with ROSTopics (see rospy message overview). rospy converts these srv files into Python source code and creates three classes that you need to be familiar with: service definitions, request messages, and response messages. The names of these classes come directly from thesrv filename:

my_package/srv/Foo.srvmy_package.srv.Foo

my_package/srv/Foo.srvmy_package.srv.FooRequest

my_package/srv/Foo.srv my_package.srv.FooResponse

       srv : http://wiki.ros.org/srv

A service description file consists of a request and aresponsemsg type, separated by'---'. Any two.msg files concatenated together with a'---' are a legal service description.

Client Library Support

In Python, the generated Python service type file (e.g.foo_srvs.srv.Foo) provides nearly all the information you might want about a.srv file. You can examine the __slots__ and_slot_types and other fields to introspect information about the request and reply Messages. Foradvanced users, theroslib.srvs module in theroslib Package provides basic support for parsing.srv files in Python. This library is only recommended for those implementing service generators.

Creating a ROS msg and srv

Reference article: 如何创建使用ros的service?Python版


  • Notes
    • Files we need to create
      1.  filename.srv file; This file is used to define the input(request message) and output(response message) for this service class. rospy converts thesesrv files into Python source code and creates three classes that you need to be familiar with: service definitions, request messages, and response messages. The names of these classes come directly from thesrv filename.
      2.  server.py file; This file is to create a service.
      3. client.py file; This file is to produce a request for the service.
  • SRV file (e.g WordCount.srv and AddTwoInts.srv in the package of 'py_package')
    • This file usually locate in the 'srv' folder of your package. So when we use this srv, we can using following code in the server.py to import three classes (WordCount,WordCountRequest,WordCountResponse) (if pyLint prompt error for this line that can not find the py_package.srv, we ignore it. If using python command to run this file and an error of 'ImportError: No module named py_package.srv',then try with 'source devel/setup.bash'  at first in your terminal where running the python command, if error still shows again ,then try catkin_make to rebuild again not just with roboware's builder tool because it sometimes does not work well . Here the py_pacakge.srv is the path of srv folder rather than a srv file)
from  py_package.srv  import  AddTwoInts,AddTwoIntsResponse,WordCount,WordCountResponse

    • AddTwoInts.srv
int64  a
int64  b
---
int64  sum

  • WordCount.srv
string  words
---
uint32  count

  • server.py

from  py_package.srv  import  AddTwoInts,AddTwoIntsResponse,WordCount,WordCountResponse
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   handle_word_count ( req ):
         print   "Return [%s] " % (req.words)
         return  WordCountResponse( len (req.words.split()))
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."
    w = rospy.Service( 'word_count' ,WordCount,handle_word_count)
     print   "Ready to count the length."
    rospy.spin()

if   __name__  ==  "__main__" :
    add_two_ints_server()


  • client.py
#!/usr/bin/env python

import  sys
import  rospy
from  py_package.srv  import  AddTwoInts,WordCount

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 add_two_ints call failed: %s" %e
def   count_length_words ( words ):
    rospy.wait_for_service( 'word_count' )
     try :
        word_counter = rospy.ServiceProxy( 'word_count' ,WordCount)
        word_count = word_counter(words)
         print  words, '->' ,word_count.count
         return  word_count.count
     except  rospy.ServiceException,e:
         print   "Service word_count 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 ])
        words =  ' ' .join(sys.argv[ 3 :])
     else :
         print  usage()
        sys.exit( 1 )
     print   "Requesting %s+%s" %(x, y)
     print   "%s + %s = %s" %(x, y, add_two_ints_client(x, y))
     print   "The count of \' %s \'is %s " %(words,count_length_words(words))


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值