protocol.py
Go to the documentation of this file.
00001 # Software License Agreement (BSD License)
00002 #
00003 # Copyright (c) 2012, Willow Garage, Inc.
00004 # All rights reserved.
00005 #
00006 # Redistribution and use in source and binary forms, with or without
00007 # modification, are permitted provided that the following conditions
00008 # are met:
00009 #
00010 #  * Redistributions of source code must retain the above copyright
00011 #    notice, this list of conditions and the following disclaimer.
00012 #  * Redistributions in binary form must reproduce the above
00013 #    copyright notice, this list of conditions and the following
00014 #    disclaimer in the documentation and/or other materials provided
00015 #    with the distribution.
00016 #  * Neither the name of Willow Garage, Inc. nor the names of its
00017 #    contributors may be used to endorse or promote products derived
00018 #    from this software without specific prior written permission.
00019 #
00020 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
00021 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
00022 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
00023 # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
00024 # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
00025 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
00026 # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
00027 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
00028 # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
00029 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
00030 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
00031 # POSSIBILITY OF SUCH DAMAGE.
00032 
00033 import rospy
00034 import time
00035 from rosbridge_library.internal.exceptions import InvalidArgumentException
00036 from rosbridge_library.internal.exceptions import MissingArgumentException
00037 
00038 #from rosbridge_library.internal.pngcompression import encode
00039 from rosbridge_library.capabilities.fragmentation import Fragmentation
00040 from rosbridge_library.util import json, bson
00041 
00042 
00043 def is_number(s):
00044     try:
00045         float(s)
00046         return True
00047     except ValueError:
00048         return False
00049         
00050 def has_binary(d):
00051     if type(d)==bson.Binary:
00052         return True
00053     if type(d)==dict:
00054         for k,v in d.items():
00055             if has_binary(v):
00056                 return True
00057     return False                
00058 
00059 class Protocol:
00060     """ The interface for a single client to interact with ROS.
00061 
00062     See rosbridge_protocol for the default protocol used by rosbridge
00063 
00064     The lifecycle for a Protocol instance is as follows:
00065     - Pass incoming messages from the client to incoming
00066     - Propagate outgoing messages to the client by overriding outgoing
00067     - Call finish to clean up resources when the client is finished
00068 
00069     """
00070 
00071     # fragment_size can be set per client (each client has its own instance of protocol)
00072     # ..same for other parameters
00073     fragment_size = None
00074     png = None
00075     # buffer used to gather partial JSON-objects (could be caused by small tcp-buffers or similar..)
00076     buffer = ""
00077     old_buffer = ""
00078     busy = False
00079     # if this is too low, ("simple")clients network stacks will get flooded (when sending fragments of a huge message..)
00080     # .. depends on message_size/bandwidth/performance/client_limits/...
00081     # !! this might be related to (or even be avoided by using) throttle_rate !!
00082     delay_between_messages = 0
00083     # global list of non-ros advertised services
00084     external_service_list = {}
00085     # Use only BSON for the whole communication if the server has been started with bson_only_mode:=True
00086     bson_only_mode = False
00087 
00088     parameters = None
00089 
00090     def __init__(self, client_id):
00091         """ Keyword arguments:
00092         client_id -- a unique ID for this client to take.  Uniqueness is
00093         important otherwise there will be conflicts between multiple clients
00094         with shared resources
00095 
00096         """
00097         self.client_id = client_id
00098         self.capabilities = []
00099         self.operations = {}
00100 
00101         if self.parameters:
00102             self.fragment_size = self.parameters["max_message_size"]
00103             self.delay_between_messages = self.parameters["delay_between_messages"]
00104             self.bson_only_mode = self.parameters.get('bson_only_mode', False)
00105 
00106     # added default message_string="" to allow recalling incoming until buffer is empty without giving a parameter
00107     # --> allows to get rid of (..or minimize) delay between client-side sends
00108     def incoming(self, message_string=""):
00109         """ Process an incoming message from the client
00110 
00111         Keyword arguments:
00112         message_string -- the wire-level message sent by the client
00113 
00114         """
00115         self.buffer = self.buffer + message_string
00116         msg = None
00117 
00118         # take care of having multiple JSON-objects in receiving buffer
00119         # ..first, try to load the whole buffer as a JSON-object
00120         try:
00121             msg = self.deserialize(self.buffer)
00122             self.buffer = ""
00123 
00124         # if loading whole object fails try to load part of it (from first opening bracket "{" to next closing bracket "}"
00125         # .. this causes Exceptions on "inner" closing brackets --> so I suppressed logging of deserialization errors
00126         except Exception as e:
00127             if self.bson_only_mode:
00128                 # Since BSON should be used in conjunction with a network handler
00129                 # that receives exactly one full BSON message.
00130                 # This will then be passed to self.deserialize and shouldn't cause any
00131                 # exceptions because of fragmented messages (broken or invalid messages might still be sent tough)
00132                 self.log("error", "Exception in deserialization of BSON")
00133 
00134             else:
00135                 # TODO: handling of partial/multiple/broken json data in incoming buffer
00136                 # this way is problematic when json contains nested json-objects ( e.g. { ... { "config": [0,1,2,3] } ...  } )
00137                 # .. if outer json is not fully received, stepping through opening brackets will find { "config" : ... } as a valid json object
00138                 # .. and pass this "inner" object to rosbridge and throw away the leading part of the "outer" object..
00139                 # solution for now:
00140                 # .. check for "op"-field. i can still imagine cases where a nested message ( e.g. complete service_response fits into the data field of a fragment..)
00141                 # .. would cause trouble, but if a response fits as a whole into a fragment, simply do not pack it into a fragment.
00142                 #
00143                 # --> from that follows current limitiation:
00144                 #     fragment data must NOT (!) contain a complete json-object that has an "op-field"
00145                 #
00146                 # an alternative solution would be to only check from first opening bracket and have a time out on data in input buffer.. (to handle broken data)
00147                 opening_brackets = [i for i, letter in enumerate(self.buffer) if letter == '{']
00148                 closing_brackets = [i for i, letter in enumerate(self.buffer) if letter == '}']
00149 
00150                 for start in opening_brackets:
00151                     for end in closing_brackets:
00152                         try:
00153                             msg = self.deserialize(self.buffer[start:end+1])
00154                             if msg.get("op",None) != None:
00155                                 # TODO: check if throwing away leading data like this is okay.. loops look okay..
00156                                 self.buffer = self.buffer[end+1:len(self.buffer)]
00157                                 # jump out of inner loop if json-decode succeeded
00158                                 break
00159                         except Exception as e:
00160                             # debug json-decode errors with this line
00161                             #print e
00162                             pass
00163                     # if load was successfull --> break outer loop, too.. -> no need to check if json begins at a "later" opening bracket..
00164                     if msg != None:
00165                         break
00166 
00167         # if decoding of buffer failed .. simply return
00168         if msg is None:
00169             return
00170 
00171         # process fields JSON-message object that "control" rosbridge
00172         mid = None
00173         if "id" in msg:
00174             mid = msg["id"]
00175         if "op" not in msg:
00176             if "receiver" in msg:
00177                 self.log("error", "Received a rosbridge v1.0 message.  Please refer to rosbridge.org for the correct format of rosbridge v2.0 messages.  Original message was: %s" % message_string)
00178             else:
00179                 self.log("error", "Received a message without an op.  All messages require 'op' field with value one of: %s.  Original message was: %s" % (list(self.operations.keys()), message_string), mid)
00180             return
00181         op = msg["op"]
00182         if op not in self.operations:
00183             self.log("error", "Unknown operation: %s.  Allowed operations: %s" % (op, list(self.operations.keys())), mid)
00184             return
00185         # this way a client can change/overwrite it's active values anytime by just including parameter field in any message sent to rosbridge
00186         #  maybe need to be improved to bind parameter values to specific operation..
00187         if "fragment_size" in msg.keys():
00188             self.fragment_size = msg["fragment_size"]
00189             #print "fragment size set to:", self.fragment_size
00190         if "message_intervall" in msg.keys() and is_number(msg["message_intervall"]):
00191             self.delay_between_messages = msg["message_intervall"]
00192         if "png" in msg.keys():
00193             self.png = msg["msg"]
00194 
00195         # now try to pass message to according operation
00196         try:
00197             self.operations[op](msg)
00198         except Exception as exc:
00199             self.log("error", "%s: %s" % (op, str(exc)), mid)
00200 
00201         # if anything left in buffer .. re-call self.incoming
00202         # TODO: check what happens if we have "garbage" on tcp-stack --> infinite loop might be triggered! .. might get out of it when next valid JSON arrives since only data after last 'valid' closing bracket is kept
00203         if len(self.buffer) > 0:
00204             # try to avoid infinite loop..
00205             if self.old_buffer != self.buffer:
00206                 self.old_buffer = self.buffer
00207                 self.incoming()
00208 
00209 
00210 
00211     def outgoing(self, message):
00212         """ Pass an outgoing message to the client.  This method should be
00213         overridden.
00214 
00215         Keyword arguments:
00216         message -- the wire-level message to send to the client
00217 
00218         """
00219         pass
00220 
00221     def send(self, message, cid=None):
00222         """ Called internally in preparation for sending messages to the client
00223 
00224         This method pre-processes the message then passes it to the overridden
00225         outgoing method.
00226 
00227         Keyword arguments:
00228         message -- a dict of message values to be marshalled and sent
00229         cid     -- (optional) an associated id
00230 
00231         """
00232         serialized = self.serialize(message, cid)
00233         if serialized is not None:
00234             if self.png == "png":
00235                 # TODO: png compression on outgoing messages
00236                 # encode message
00237                 pass
00238 
00239             fragment_list = None
00240             if self.fragment_size != None and len(serialized) > self.fragment_size:
00241                 mid = message.get("id", None)
00242 
00243                 # TODO: think about splitting into fragments that have specified size including header-fields!
00244                 # --> estimate header size --> split content into fragments that have the requested overall size, rather than requested content size
00245                 fragment_list = Fragmentation(self).fragment(message, self.fragment_size, mid )
00246 
00247             # fragment list not empty -> send fragments
00248             if fragment_list != None:
00249                 for fragment in fragment_list:
00250                     if self.bson_only_mode:
00251                         self.outgoing(bson.BSON.encode(fragment))
00252                     else:
00253                         self.outgoing(json.dumps(fragment))
00254                     # okay to use delay here (sender's send()-function) because rosbridge is sending next request only to service provider when last one had finished)
00255                     #  --> if this was not the case this delay needed to be implemented in service-provider's (meaning message receiver's) send_message()-function in rosbridge_tcp.py)
00256                     time.sleep(self.delay_between_messages)
00257             # else send message as it is
00258             else:
00259                 self.outgoing(serialized)
00260                 time.sleep(self.delay_between_messages)
00261 
00262     def finish(self):
00263         """ Indicate that the client is finished and clean up resources.
00264 
00265         All clients should call this method after disconnecting.
00266 
00267         """
00268         for capability in self.capabilities:
00269             capability.finish()
00270 
00271     def serialize(self, msg, cid=None):
00272         """ Turns a dictionary of values into the appropriate wire-level
00273         representation.
00274 
00275         Default behaviour uses JSON.  Override to use a different container.
00276 
00277         Keyword arguments:
00278         msg -- the dictionary of values to serialize
00279         cid -- (optional) an ID associated with this.  Will be logged on err.
00280 
00281         Returns a JSON string representing the dictionary
00282         """
00283         try:
00284             if has_binary(msg) or self.bson_only_mode:
00285                 return bson.BSON.encode(msg)
00286             else:    
00287                 return json.dumps(msg)
00288         except:
00289             if cid is not None:
00290                 # Only bother sending the log message if there's an id
00291                 self.log("error", "Unable to serialize %s message to client"
00292                          % msg["op"], cid)
00293             return None
00294 
00295     def deserialize(self, msg, cid=None):
00296 
00297         """ Turns the wire-level representation into a dictionary of values
00298 
00299         Default behaviour assumes JSON. Override to use a different container.
00300 
00301         Keyword arguments:
00302         msg -- the wire-level message to deserialize
00303         cid -- (optional) an ID associated with this.  Is logged on error
00304 
00305         Returns a dictionary of values
00306 
00307         """
00308         try:
00309             if self.bson_only_mode:
00310                 bson_message = bson.BSON(msg)
00311                 return bson_message.decode()
00312             else:
00313                 return json.loads(msg)
00314         except Exception as e:
00315             # if we did try to deserialize whole buffer .. first try to let self.incoming check for multiple/partial json-decodes before logging error
00316             # .. this means, if buffer is not == msg --> we tried to decode part of buffer
00317 
00318             # TODO: implement a way to have a final Exception when nothing works out to decode (multiple/broken/partial JSON..)
00319 
00320             # supressed logging of exception on json-decode to keep rosbridge-logs "clean", otherwise console logs would get spammed for every failed json-decode try
00321 #            if msg != self.buffer:
00322 #                error_msg = "Unable to deserialize message from client: %s"  % msg
00323 #                error_msg += "\nException was: " +str(e)
00324 #
00325 #                self.log("error", error_msg, cid)
00326 
00327             # re-raise Exception to allow handling outside of deserialize function instead of returning None
00328             raise
00329             #return None
00330 
00331     def register_operation(self, opcode, handler):
00332         """ Register a handler for an opcode
00333 
00334         Keyword arguments:
00335         opcode  -- the opcode to register this handler for
00336         handler -- a callback function to call for messages with this opcode
00337 
00338         """
00339         self.operations[opcode] = handler
00340 
00341     def unregister_operation(self, opcode):
00342         """ Unregister a handler for an opcode
00343 
00344         Keyword arguments:
00345         opcode -- the opcode to unregister the handler for
00346 
00347         """
00348         if opcode in self.operations:
00349             del self.operations[opcode]
00350 
00351     def add_capability(self, capability_class):
00352         """ Add a capability to the protocol.
00353 
00354         This method is for convenience; assumes the default capability
00355         constructor
00356 
00357         Keyword arguments:
00358         capability_class -- the class of the capability to add
00359 
00360         """
00361         self.capabilities.append(capability_class(self))
00362 
00363     def log(self, level, message, lid=None):
00364         """ Log a message to the client.  By default just sends to stdout
00365 
00366         Keyword arguments:
00367         level   -- the logger level of this message
00368         message -- the string message to send to the user
00369         lid     -- an associated for this log message
00370 
00371         """
00372         stdout_formatted_msg = None
00373         if lid is not None:
00374             stdout_formatted_msg = "[Client %s] [id: %s] %s" % (self.client_id, lid, message)
00375         else:
00376             stdout_formatted_msg = "[Client %s] %s" % (self.client_id, message)
00377 
00378         if level == "error" or level == "err":
00379             rospy.logerr(stdout_formatted_msg)
00380         elif level == "warning" or level == "warn":
00381             rospy.logwarn(stdout_formatted_msg)
00382         elif level == "info" or level == "information":
00383             rospy.loginfo(stdout_formatted_msg)
00384         else:
00385             rospy.logdebug(stdout_formatted_msg)


rosbridge_library
Author(s): Jonathan Mace
autogenerated on Thu Jun 6 2019 21:51:43