Commit a312f601 authored by Mathias Haage's avatar Mathias Haage
Browse files

Add dispatch service with client

parent efc12089
Pipeline #2155 skipped
#!/usr/bin/env python
import sys
import rospy
from grafchart.srv import *
def dispatch_client(context):
rospy.wait_for_service('dispatch')
try:
dispatch = rospy.ServiceProxy('dispatch', DispatchService)
resp1 = dispatch(context)
return resp1.response
except rospy.ServiceException, e:
print "Service call failed: %s"%e
def usage():
return "%s [context]"%sys.argv[0]
if __name__ == "__main__":
if len(sys.argv) == 2:
context = sys.argv[1]
else:
print usage()
sys.exit(1)
print "Dispatching %s"%(context)
print "Response %s"%(dispatch_client(context))
#!/usr/bin/env python
from grafchart.srv import *
import rospy
# ----------------------------------------------------------
def addtwoints(context):
reply = {}
rospy.wait_for_service('add_two_ints')
try:
add_two_ints = rospy.ServiceProxy('add_two_ints', TestService2)
resp1 = add_two_ints(int(context['x']), int(context['y']))
reply['sum'] = resp1.sum
except rospy.ServiceException, e:
print "Service call failed: %s"%e
return reply
def appendstring(context):
reply = {}
rospy.wait_for_service('string2string')
try:
string2string = rospy.ServiceProxy('string2string', TestService1)
resp1 = string2string(context['a'])
reply['b'] = resp1.b
except rospy.ServiceException, e:
reply['error'] = e
print "Service call failed: %s"%e
return reply
# ----------------------------------------------------------
fmap = []
fmap += [("addtwoints", addtwoints)]
fmap += [("appendstring", appendstring)]
registry = dict(fmap)
# ----------------------------------------------------------
# Comma-separated string with key=value pairs.
# I.e. a=12,b=3,c=hello
def string2dict(s):
values = dict(kv.split("=") for kv in s.split(","))
return values
def dict2string(d):
s = ""
first = True
for k in d:
v = d[k]
if first:
s += "%s=%s"%(str(k),str(v))
first = False
else:
s += ",%s=%s"%(str(k),str(v))
return s
def handle_dispatch(req):
print "Dispatching [%s]"%(req.request,)
try:
context = string2dict(req.request)
reply = dict2string(registry[context["call"]](context))
print "Reply [%s]"%(reply,)
except Exception as e:
reply = "error=%s"%(str(e),)
print "Error [%s]"%(reply,)
return DispatchServiceResponse(reply)
def dispatch_server():
rospy.init_node('dispatch_service')
s = rospy.Service('dispatch', DispatchService, handle_dispatch)
print "Ready to dispatch."
rospy.spin()
if __name__ == "__main__":
dispatch_server()
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment