extctrl2014.py 13.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
#!/usr/bin/python

import random
import struct
import StringIO
import time
import threading

#
# Packet format
#
#   +----+----+----+----+----+----+
#   | destination                    (6 bytes)
#   +----+----+----+----+----+----+
#   | source                         (6 bytes)
#   +----+----+
#   | eth_type                       (2 bytes 'EX')
#   +----+
#   | kind+flags                     (1 byte)
#   +....+
#   | channel                        (packed32)
#   +----+----+----+----+
#   | cookie                         (uint32, XOR of both first_indices)
#   +----+----+----+----+
#   | index                          (uint32)
#   +....+
#   | frag_num                       (packed32)
#   +....+
#   | frag_length                    (packed32)
#   +....+
#   | data
#   +
#

flag_MASK =           0x07
flag_LAST_FRAG =      0x01
flag_NEED_ACK =       0x02
flag_IS_ACK =         0x04
kind_MASK =           0x30
kind_INIT =           0x10
kind_DATA =           0x20

class UnexpectedFragment(Exception):

    pass

class Decoder(object):

    def __init__(self, data):
        self.buf = StringIO.StringIO(data)

    def read(self, count):
        return self.buf.read(count)
    
    def unpack(self, format):
        size = struct.calcsize(format)
        data = self.buf.read(size)
        result = struct.unpack(format, data)
        return result[0]

    def decode_uint32(self):
        return self.unpack("!I")

    def decode_byte(self):
        return self.unpack("!B")
    
    def decode_packed32(self):
        result = 0
        while True:
            tmp = self.decode_byte()
            result = (result << 7) | (tmp & 0x7f)
            if (tmp & 0x80) == 0:
                break
        return result

class Encoder(object):

    def __init__(self):
        self.buf = StringIO.StringIO()
   
    def __repr__(self):
        return "Codec([%s])" % (" ".join(
            map(lambda b: "0x%2.2x" % ord(b), self.getvalue())))

    def getvalue(self):
        return self.buf.getvalue()
    
    def write(self, data):
        self.buf.write(data)
        
    def pack(self, format, *args):
        self.buf.write(struct.pack(format, *args))

    def encode_uint32(self, value):
        self.pack("!I", value)

    def encode_byte(self, value):
        self.pack("!B", value)
    
    def encode_packed32(self, value):
        value = value & 0xffffffff
        tmp = [ value & 0x7f ]
        value = value >> 7
        while value:
            tmp.append(value & 0x7f | 0x80)
            value= value >> 7
            pass
        for c in reversed(tmp):
            self.encode_byte(c) 
            pass
        pass

class Fragmenter(Encoder):

    def __init__(self, destination, flags, channel, cookie, index):
        super(Fragmenter, self).__init__()
        self.destination = destination
        self.flags = flags
        self.cookie = cookie
        self.channel = channel
        self.index = index

    def fragments(self, max_length=1480):
        data = self.getvalue()
        fragment_number = 0
        while len(data) > 0 or fragment_number == 0:
            length = min(len(data), max(1, max_length))
            remaining = data[length:]
            data = data[0:length]
            fragment = Encoder()
            fragment.write(self.destination)
            fragment.write('\x00\x00\x00\x00\x00\x00')
            fragment.write('EX')
            if len(remaining) == 0:
                fragment.encode_byte(self.flags | flag_LAST_FRAG)
            else:
                fragment.encode_byte(self.flags)
            fragment.encode_packed32(self.channel)
            fragment.encode_uint32(self.cookie)
            fragment.encode_uint32(self.index)
            fragment.encode_packed32(fragment_number)
            fragment.encode_packed32(length)
            fragment.write(data)
            yield fragment
            data = remaining
            fragment_number += 1
            
    def __repr__(self):
        return "Fragmenter([%s])" % (" ".join(
            map(lambda b: "0x%2.2x" % ord(b), self.getvalue())))

class Packet:

    def __init__(self, data):
        buf = Decoder(data)
        self.destination = buf.read(6)
        self.source = buf.read(6)
        self.eth_type = buf.read(2)
        flags = buf.decode_byte()
        self.flags = flags & flag_MASK
        self.kind = flags & kind_MASK
        self.channel = buf.decode_packed32()
        self.cookie = buf.decode_uint32()
        self.index = buf.decode_uint32()
        self.frag_num = buf.decode_packed32()
        frag_length = buf.decode_packed32()
        self.data = buf.read(frag_length)

    def join(self, other):
        if self.destination != other.destination:
            return None
        if self.source != other.source:
            return None
        if self.kind != other.kind:
            return None
        if self.channel != other.channel:
            return None
        if self.cookie != other.cookie:
            return None
        if self.index != other.index:
            return None
        if self.frag_num + 1 != other.frag_num:
            return None
        self.flags = other.flags
        self.frag_num = other.frag_num
        self.data += other.data
        return self
        
    def __repr__(self):
        return "Packet(%s %s %d index=%x flags=%x kind=%x data='%s'" % (
            ":".join(map(lambda b: "%02.2x" % ord(b), self.destination)),
            ":".join(map(lambda b: "%02.2x" % ord(b), self.source)),
            self.channel,
            self.index,
            self.flags,
            self.kind,
            "".join(map(lambda b: "\\x%02.2x" % ord(b), self.data)),
       )

class ExtCtrl(object):

    def __init__(self, ethernet, channel, controller=None, robot=None,
                 max_retries=1000, max_length=1480):
        if len(filter(None, [ robot, controller])) != 1:
            raise Exception('Either robot(%s) or controller(%s) '
                            'should be defined' %
                            (robot, controller))
        else:
            self.other = filter(None, [ robot, controller])[0]
        self.ethernet = ethernet
        self.channel = channel
        self.controller = controller
        self.robot = robot
        self.max_retries = max_retries
        self.max_length = max_length
        self.read_data = list()
        self.cond = threading.Condition()
        self.local_index = random.randint(0,2**32-1)
        self.remote_index = None
        self.cookie = None
        self.ack = None
        t = threading.Thread(target=self.recv_loop)
        t.daemon = True
        t.start()
        if self.controller:
            self.send_INIT()
        elif self.robot:
            self.await_INIT()
        

    def recv_loop(self):
        ack = None
        data = None
        while True:
            fragment = Packet(self.ethernet.recv(2000))

            # Sanity check fragment
            if fragment.eth_type != 'EX':
                continue
            if fragment.source != self.other:
                continue
            if fragment.channel != self.channel:
                continue
            if fragment.cookie != 0 and fragment.cookie != self.cookie:
                continue

            # Join fragments
            if fragment.flags & flag_IS_ACK != 0:
                if fragment.frag_num == 0:
                    ack = fragment
                elif ack != None:
                    ack = ack.join(fragment)
                else:
                    ack = None
                packet = ack
            else:
                if fragment.frag_num == 0:
                    data = fragment
                elif data != None:
                    data = data.join(fragment)
                else:
                    data = None
                packet = data

            if packet == None:
                # Join failed
                continue
            if fragment.flags & flag_LAST_FRAG == 0:
                # Await more fragments
                continue
            
            if packet.flags & flag_IS_ACK != 0:
                with self.cond:
                    if packet.index == self.ack:
                        self.ack = None
                        self.cond.notify_all()
                    if packet.kind == kind_INIT and self.remote_index == None:
                        decoder = Decoder(packet.data)
                        with self.cond:
                            self.remote_index = decoder.decode_uint32()
                            self.cookie = self.remote_index ^ self.local_index
                            self.cond.notify_all()
            elif packet.kind == kind_INIT:
                remote_index = packet.index
                if self.remote_index == None:
                    # Save 
                    with self.cond:
                        self.remote_index = remote_index
                        self.cookie = self.remote_index ^ self.local_index
                        self.cond.notify_all()                        
                if remote_index == self.remote_index:
                    # ACK first INIT or its resends
                    self.send_INIT_ACK()
            elif packet.kind == kind_DATA:
                if self.remote_index != packet.index:
                    with self.cond:
                        self.remote_index = packet.index
                        self.read_data.extend(packet.data)
                        self.cond.notify_all()
                if packet.flags & flag_NEED_ACK:
                    self.send_ACK(packet)

    def retries(self, index, timeout=1):
        with self.cond:
            self.ack = index
        i = 0
        while i < self.max_retries:
            yield i
            i += 1
            with self.cond:
                if self.ack == index:
                    self.cond.wait(timeout)
                if self.ack != index:
                    raise StopIteration()
        raise Exception()

    def await_INIT(self):
        with self.cond:
            while self.cookie == None:
                self.cond.wait(1)

    def send_INIT(self):
        flags = kind_INIT | flag_NEED_ACK
        fragmenter = Fragmenter(destination=self.other,
                                channel=self.channel,
                                flags=flags,
                                cookie=0,
                                index=self.local_index)
        for i in self.retries(self.local_index):
            for f in fragmenter.fragments(max_length=self.max_length):
                self.ethernet.send(f.getvalue())
        self.local_index += 1

    def send_INIT_ACK(self):
        flags = kind_INIT | flag_IS_ACK
        fragmenter = Fragmenter(destination=self.other,
                                channel=self.channel,
                                flags=flags,
                                cookie=0,
                                index=self.remote_index)
        fragmenter.encode_uint32(self.local_index)
        for f in fragmenter.fragments(max_length=self.max_length):
            self.ethernet.send(f.getvalue())
        
    def send_ACK(self, packet):
        flags = packet.kind | flag_IS_ACK
        fragmenter = Fragmenter(destination=self.other,
                                channel=self.channel,
                                flags=flags,
                                cookie=packet.cookie,
                                index=packet.index)
        for f in fragmenter.fragments(max_length=self.max_length):
            self.ethernet.send(f.getvalue())
        
    def send_DATA_with_ack(self, data):
        flags = kind_DATA | flag_NEED_ACK
        fragmenter = Fragmenter(destination=self.other,
                                channel=self.channel,
                                flags=flags,
                                cookie=self.cookie,
                                index=self.local_index)
        fragmenter.write(data)
        for i in self.retries(self.local_index):
            for f in fragmenter.fragments(max_length=self.max_length):
                self.ethernet.send(f.getvalue())
        self.local_index += 1

    def send_DATA(self, data):
        flags = kind_DATA
        fragmenter = Fragmenter(destination=self.other,
                                channel=self.channel,
                                flags=flags,
                                cookie=self.cookie,
                                index=self.local_index)
        fragmenter.write(data)
        for f in fragmenter.fragments(max_length=self.max_length):
            self.ethernet.send(f.getvalue())
        self.local_index += 1

    def writer(self):
        class Writer:
            def __init__(self, extctrl):
                self.extctrl = extctrl
                
            def mark_begin(self, decl, value):
                self.data = ""

            def mark_end(self, decl, value):
                if value == None:
                    self.extctrl.send_DATA_with_ack(data=self.data)
                else:
                    self.extctrl.send_DATA(data=self.data)
                
            def write(self, data):
                self.data += data
                pass
                
        return Writer(self)
    
    def reader(self):
        class Reader:
            def __init__(self, extctrl):
                self.extctrl = extctrl
                
            def mark(self, decl, value):
                pass

            def read(self, count):
                with self.extctrl.cond:
                    while len(self.extctrl.read_data) == 0:
                        self.extctrl.cond.wait()
                    data = self.extctrl.read_data[0:count]
                    self.extctrl.read_data = self.extctrl.read_data[count:]
                    return ''.join(data)
                
        return Reader(self)