Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033 from rosbridge_library.capability import Capability
00034
00035
00036 class Fragmentation(Capability):
00037 """ The Fragmentation capability doesn't define any incoming operation
00038 handlers, but provides methods to fragment outgoing messages """
00039
00040 fragmentation_seed = 0
00041
00042 def __init__(self, protocol):
00043
00044 Capability.__init__(self, protocol)
00045
00046 def fragment(self, message, fragment_size, mid=None):
00047 """ Serializes the provided message, then splits the serialized
00048 message according to fragment_size, then sends the fragments.
00049
00050 If the size of the message is less than the fragment size, then
00051 the original message is returned rather than a single fragment
00052
00053 Since fragmentation is typically only used for very large messages,
00054 this method returns a generator for fragments rather than a list
00055
00056 Keyword Arguments
00057 message -- the message dict object to be fragmented
00058 fragment_size -- the max size for the fragments
00059 mid -- (optional) if provided, the fragment messages
00060 will be given this id. Otherwise an id will be auto-generated.
00061
00062 Returns a generator of message dict objects representing the fragments
00063 """
00064
00065 if mid is None:
00066 mid = self.fragmentation_seed
00067 self.fragmentation_seed = self.fragmentation_seed + 1
00068
00069 serialized = self.protocol.serialize(message, mid)
00070
00071 if serialized is None:
00072 return []
00073
00074 message_length = len(serialized)
00075 if message_length <= fragment_size:
00076 return [message]
00077
00078 return self._fragment_generator(serialized, fragment_size, mid)
00079
00080 def _fragment_generator(self, msg, size, mid):
00081 """ Returns a generator of fragment messages """
00082 total = ((len(msg)-1) / size) + 1
00083 n = 0
00084 for i in range(0, len(msg), size):
00085 fragment = msg[i:i+size]
00086 yield self._create_fragment(fragment, n, total, mid)
00087 n = n + 1
00088
00089 def _create_fragment(self, fragment, num, total, mid):
00090 """ Given a string fragment of the original message, creates
00091 the appropriate fragment message """
00092 return {
00093 "op": "fragment",
00094 "id": mid,
00095 "data": fragment,
00096 "num": num,
00097 "total": total
00098 }