Go to the documentation of this file.00001 from rosbridge_library.internal.ros_loader import get_service_class
00002 from rosbridge_library.internal import message_conversion
00003 from rosbridge_library.capability import Capability
00004 import rospy
00005 import time
00006
00007
00008 class AdvertisedServiceHandler():
00009
00010 id_counter = 1
00011 responses = {}
00012
00013 def __init__(self, service_name, service_type, protocol):
00014 self.service_name = service_name
00015 self.service_type = service_type
00016 self.protocol = protocol
00017
00018 self.service_handle = rospy.Service(service_name, get_service_class(service_type), self.handle_request)
00019
00020 def next_id(self):
00021 id = self.id_counter
00022 self.id_counter += 1
00023 return id
00024
00025 def handle_request(self, req):
00026
00027 request_id = "service_request:" + self.service_name + ":" + str(self.next_id())
00028
00029
00030 request_message = {
00031 "op": "call_service",
00032 "id": request_id,
00033 "service": self.service_name,
00034 "args": message_conversion.extract_values(req)
00035 }
00036 self.protocol.send(request_message)
00037
00038
00039 while request_id not in self.responses.keys():
00040 time.sleep(0)
00041
00042 resp = self.responses[request_id]
00043 del self.responses[request_id]
00044 return resp
00045
00046
00047 class AdvertiseService(Capability):
00048
00049 advertise_service_msg_fields = [(True, "service", (str, unicode)), (True, "type", (str, unicode))]
00050
00051 def __init__(self, protocol):
00052
00053 Capability.__init__(self, protocol)
00054
00055
00056 protocol.register_operation("advertise_service", self.advertise_service)
00057
00058 def advertise_service(self, message):
00059
00060 service_name = message["service"]
00061
00062
00063 if service_name in self.protocol.external_service_list.keys():
00064 self.protocol.log("warn", "Duplicate service advertised. Overwriting %s." % service_name)
00065 self.protocol.external_service_list[service_name].service_handle.shutdown("Duplicate advertiser.")
00066 del self.protocol.external_service_list[service_name]
00067
00068
00069 service_type = message["type"]
00070 service_handler = AdvertisedServiceHandler(service_name, service_type, self.protocol)
00071 self.protocol.external_service_list[service_name] = service_handler
00072 self.protocol.log("info", "Advertised service %s." % service_name)