LabComm.py 22.2 KB
Newer Older
Anders Nilsson's avatar
Anders Nilsson committed
1
2
#!/usr/bin/python
#
3
# LabComm2014 packet has the following layout
Anders Nilsson's avatar
Anders Nilsson committed
4
5
#
#   +----+----+----+----+
Anders Blomdell's avatar
Anders Blomdell committed
6
7
8
#   | id                    (packed32)
#   +----+----+----+----+
#   | length                (packed32)
Anders Nilsson's avatar
Anders Nilsson committed
9
10
11
12
13
#   +----+----+----+----+
#   | data
#   | ...
#   +----+--
#
Sven Gestegård Robertz's avatar
Sven Gestegård Robertz committed
14
# LabComm2014 SAMPLE:
Anders Nilsson's avatar
Anders Nilsson committed
15
16
#
#   +----+----+----+----+
Anders Blomdell's avatar
Anders Blomdell committed
17
#   | id = 0x02             (packed32)
Anders Nilsson's avatar
Anders Nilsson committed
18
#   +----+----+----+----+
Anders Blomdell's avatar
Anders Blomdell committed
19
20
21
#   | length                (packed32)
#   +----+----+----+----+
#   | type number           (packed32)
Anders Nilsson's avatar
Anders Nilsson committed
22
23
24
25
#   +----+----+----+----+
#   | type name (UTF8)
#   | ...
#   +----+----+----+----+
Anders Blomdell's avatar
Anders Blomdell committed
26
27
28
29
30
31
#   | signature length      (packed32)
#   +----+----+----+----+
#   | type signature
#   | ...
#   +----+--
#
Sven Gestegård Robertz's avatar
Sven Gestegård Robertz committed
32
# LabComm2014 TYPE_DEF: (as SAMPLE_DEF, but signatures are hierarchical,
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#                             i.e., may contain references to other types
#
#   +----+----+----+----+
#   | id = 0x03             (packed32)
#   +----+----+----+----+
#   | length                (packed32)
#   +----+----+----+----+
#   | type number           (packed32)
#   +----+----+----+----+
#   | type name (UTF8)
#   | ...
#   +----+----+----+----+
#   | signature length      (packed32)
#   +----+----+----+----+
#   | type signature
#   | ...
#   +----+--
#
Sven Gestegård Robertz's avatar
Sven Gestegård Robertz committed
51
# LabComm2014 TYPE_BINDING
52
53
54
55
56
57
58
59
60
61
62
#
#   +----+----+----+----+
#   | id = 0x04             (packed32)
#   +----+----+----+----+
#   | length                (packed32)
#   +----+----+----+----+
#   | sample number         (packed32)
#   +----+----+----+----+
#   | type number           (packed32)
#   +----+----+----+----+
#
63
# LabComm2014 User data:
Anders Blomdell's avatar
Anders Blomdell committed
64
65
66
67
68
69
70
#
#   +----+----+----+----+
#   | id >= 0x00000040      (packed32)
#   +----+----+----+----+
#   | length                (packed32)
#   +----+----+----+----+
#   | user data
Anders Nilsson's avatar
Anders Nilsson committed
71
72
#   | ...
#   +----+--
Anders Blomdell's avatar
Anders Blomdell committed
73
74
75
#   
#
# LabComm2006 packets has the following layout
Anders Nilsson's avatar
Anders Nilsson committed
76
#
Anders Blomdell's avatar
Anders Blomdell committed
77
78
79
80
81
82
#   +----+----+----+----+
#   | id                |
#   +----+----+----+----+
#   | data
#   | ...
#   +----+--
Anders Nilsson's avatar
Anders Nilsson committed
83
#
84
# LabComm2006 SAMPLE_DEF:
Anders Nilsson's avatar
Anders Nilsson committed
85
86
87
88
89
90
91
92
93
#
#   +----+----+----+----+
#   | id = 0x00000002   |
#   +----+----+----+----+
#   | type number       |
#   +----+----+----+----+
#   | type name (UTF8)
#   | ...
#   +----+----+----+----+
Anders Blomdell's avatar
Anders Blomdell committed
94
#   | type signature
Anders Nilsson's avatar
Anders Nilsson committed
95
96
97
98
#   | ...
#   +----+--
#
#
Anders Blomdell's avatar
Anders Blomdell committed
99
# LabComm2006 User data:
Anders Nilsson's avatar
Anders Nilsson committed
100
101
#
#   +----+----+----+----+
Anders Blomdell's avatar
Anders Blomdell committed
102
#   | id >= 0x00000040  |
Anders Nilsson's avatar
Anders Nilsson committed
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
#   +----+----+----+----+
#   | user data
#   | ...
#   +----+--
#   

#??  | field1 name
#??  | (length + UTF8)...
#??  +----+----+----+----+
#??  | indices           |
#??  +----+----+----+----+
#??  | index1            | (0 -> variable size)
#??  +----+----+----+----+
#??  | ...
#??  +----+----+----+----+
#??  | indexN            |
#??  +----+----+----+----+
#??  | ...
#??  +----+----+----+----+
#??  | fieldN type       |
#??  +----+----+----+----+
#??  | ...
#??  +----+----+----+----+
#??  | END_TYPE          |
#??  +----+----+----+----+
#??
#??type = <user defined type>
#??
#??  +----+----+----+----+
#??  | type number       |
#??  +----+----+----+----+
#??  | field1 varindices |
#??  | ...               |
#??  +----+----+----+----+
#??  | field1 data       |
#??  | ...               |
#??  +----+----+----+----+
#??  | ...
#??  +----+----+----+----+
#??  | fieldN data       |
#??  | ...               |
#??  +----+----+----+----+
#  
#   
147
148
149
150
# type numbers and lengths do not have a fixed lenght, but are packed into 
# sequences of 7 bit chunks, represented in bytes with the high bit meaning 
# that more data is to come.
 
151
import types
Anders Nilsson's avatar
Anders Nilsson committed
152
153
import struct as packer

154
DEFAULT_VERSION = "LabComm2014"
155

156
# Allowed packet tags
157
158
i_VERSION     = 0x01
i_SAMPLE_DEF  = 0x02
159
160
i_TYPE_DEF    = 0x03
i_TYPE_BINDING= 0x04
161
162
i_PRAGMA      = 0x3f
i_USER        = 0x40 # ..0xffffffff
163

164
# Predefined types
165
166
i_ARRAY       = 0x10
i_STRUCT      = 0x11
167

168
169
170
171
172
173
174
175
i_BOOLEAN     = 0x20 
i_BYTE        = 0x21
i_SHORT       = 0x22
i_INTEGER     = 0x23
i_LONG        = 0x24
i_FLOAT       = 0x25
i_DOUBLE      = 0x26
i_STRING      = 0x27
176
177
178


# Version testing
179
def usePacketLength(version):
180
    return version in [ None, "LabComm2014" ]
181
182
183
184

class length_encoder:
    def __init__(self, encoder):
        self.encoder = encoder
185
        self.version = encoder.version
186
187
188
        self.data = ""

    def write(self, data):
189
        self.data += data
190
191

    def __enter__(self):
192
        return Encoder(self, None)
193
194

    def __exit__(self, type, value, traceback):
195
196
197
        if usePacketLength(self.version):
             self.encoder.encode_packed32(len(self.data))
        self.encoder.pack("%ds" % len(self.data), self.data)
198

Anders Nilsson's avatar
Anders Nilsson committed
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
def indent(i, s):
    return ("\n%s" % (" " * i)).join(s.split("\n"))

#
# Primitive types
#
class primitive(object):
    def decode_decl(self, decoder):
        return self

class BOOLEAN(primitive):
    def encode_decl(self, encoder):
        return encoder.encode_type(i_BOOLEAN)

    def encode(self, encoder, value):
        return encoder.encode_boolean(value)
    
    def decode(self, decoder, obj=None):
        return decoder.decode_boolean()

    def new_instance(self):
        return False

    def __repr__(self):
        return "labcomm.BOOLEAN()"

class BYTE(primitive):
    def encode_decl(self, encoder):
        return encoder.encode_type(i_BYTE)

    def encode(self, encoder, value):
        return encoder.encode_byte(value)
    
    def decode(self, decoder, obj=None):
        return decoder.decode_byte()
    
    def new_instance(self):
        return 0

    def __repr__(self):
        return "labcomm.BYTE()"

class SHORT(primitive):
    def encode_decl(self, encoder):
        return encoder.encode_type(i_SHORT)

    def encode(self, encoder, value):
        return encoder.encode_short(value)
    
    def decode(self, decoder, obj=None):
        return decoder.decode_short()
    
    def new_instance(self):
        return 0

    def __repr__(self):
        return "labcomm.SHORT()"

class INTEGER(primitive):
    def encode_decl(self, encoder):
        return encoder.encode_type(i_INTEGER)

    def encode(self, encoder, value):
        return encoder.encode_int(value)
    
    def decode(self, decoder, obj=None):
        return decoder.decode_int()
    
    def new_instance(self):
        return 0

    def __repr__(self):
        return "labcomm.INTEGER()"

class LONG(primitive):
    def encode_decl(self, encoder):
        return encoder.encode_type(i_LONG)

    def encode(self, encoder, value):
        return encoder.encode_long(value)
    
    def decode(self, decoder, obj=None):
        return decoder.decode_long()
    
    def new_instance(self):
        return long(0)

    def __repr__(self):
        return "labcomm.LONG()"

class FLOAT(primitive):
    def encode_decl(self, encoder):
        return encoder.encode_type(i_FLOAT)

    def encode(self, encoder, value):
        return encoder.encode_float(value)
    
    def decode(self, decoder, obj=None):
        return decoder.decode_float()
    
    def new_instance(self):
        return 0.0

    def __repr__(self):
        return "labcomm.FLOAT()"

class DOUBLE(primitive):
    def encode_decl(self, encoder):
        return encoder.encode_type(i_DOUBLE)

    def encode(self, encoder, value):
        return encoder.encode_double(value)
    
    def decode(self, decoder, obj=None):
        return decoder.decode_double()
    
    def new_instance(self):
        return 0.0

    def __repr__(self):
        return "labcomm.DOUBLE()"

class STRING(primitive):
    def encode_decl(self, encoder):
        return encoder.encode_type(i_STRING)

    def encode(self, encoder, value):
        return encoder.encode_string(value)
    
    def decode(self, decoder, obj=None):
        return decoder.decode_string()
    
    def new_instance(self):
        return ""

    def __repr__(self):
        return "labcomm.STRING()"

#
# Aggregate types
#
340
class sample(object):
Anders Nilsson's avatar
Anders Nilsson committed
341
342
343
344
    def __init__(self, name, decl):
        self.name = name
        self.decl = decl

345
    def encode_decl(self, encoder):
346
        encoder.encode_type(i_SAMPLE_DEF)
347
348
349
350
351
        with length_encoder(encoder) as e1:
            e1.encode_type(encoder.decl_to_index[self])
            e1.encode_string(self.name)
            with length_encoder(e1) as e2:
                self.decl.encode_decl(e2)
Anders Nilsson's avatar
Anders Nilsson committed
352
353
354
355
356
357
358

    def encode(self, encoder, object):
        self.decl.encode(encoder, object)

    def decode_decl(self, decoder):
        index = decoder.decode_type_number()
        name = decoder.decode_string()
359
360
        if usePacketLength(decoder.version):
            length = decoder.decode_packed32()
Anders Nilsson's avatar
Anders Nilsson committed
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
        decl = decoder.decode_decl()
        result = self.__class__.__new__(self.__class__)
        result.__init__(name, decl)
        decoder.add_decl(result, index)
        return result

    def decode(self, decoder, obj=None):
        obj = decoder.create_object(self.name)
        obj = self.decl.decode(decoder, obj)
        return obj

    def new_instance(self):
        return self.decl.new_instance()

    def __repr__(self):
376
        return "sample('%s', %s)" % (self.name, self.decl)
Anders Nilsson's avatar
Anders Nilsson committed
377
378
379
380
381
382
383
384
385


class array(object):
    def __init__(self, indices, decl):
        self.indices = indices
        self.decl = decl
        
    def encode_decl(self, encoder):
        encoder.encode_type(i_ARRAY)
386
        encoder.encode_packed32(len(self.indices))
Anders Nilsson's avatar
Anders Nilsson committed
387
        for i in self.indices:
388
            encoder.encode_packed32(i)
Anders Nilsson's avatar
Anders Nilsson committed
389
390
        encoder.encode_type_number(self.decl)

391
392
393
394
    def min_max_shape(self, l, depth, shape):
        if isinstance(l, types.StringTypes):
            return shape
        try:
Anders Nilsson's avatar
Anders Nilsson committed
395
396
397
            length = len(l)
            if len(shape) <= depth:
                shape.append((length, length))
398
                pass
Anders Nilsson's avatar
Anders Nilsson committed
399
400
401
402
403
            else:
                (low, high) = shape[depth]
                low = min(low, length)
                high = max(high, length)
                shape[depth] = (low, high)
404
                pass
Anders Nilsson's avatar
Anders Nilsson committed
405
406
            for e in l:
                shape = self.min_max_shape(e, depth + 1, shape)
407
408
409
410
                pass
            pass
        except TypeError:
            pass
Anders Nilsson's avatar
Anders Nilsson committed
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
        return shape    

    def shape(self, l):
        shape = self.min_max_shape(l, 0, [])
        result = []
        for (low, high) in shape:
            if low != high:
                raise Exception("Non rectangular shape %s" % shape)
            result.append(low)
        return result

    
    def encode_indices(self, encoder, value):
        depth = len(self.indices)
        shape = self.shape(value)
        #if len(shape) != len(self.indices):
        if len(shape) < len(self.indices):
            raise Exception("Actual dimension %s differs from declared %s" %
                            (shape, self.indices))
        for i in range(len(self.indices)):
            if self.indices[i] == 0:
432
                encoder.encode_packed32(shape[i])
Anders Nilsson's avatar
Anders Nilsson committed
433
434
435
436
437
438
            elif self.indices[i] != shape[i]:
                raise Exception("Actual dimension %d in %s differs from %s" %
                                (i, shape, self.indices))
        return depth

    def encode_value(self, encoder, value, depth):
439
440
        # if depth and isinstance(value, list):
        if depth:
Anders Nilsson's avatar
Anders Nilsson committed
441
442
443
444
445
446
447
448
449
450
            for e in value:
                self.encode_value(encoder, e, depth - 1)
        else:
            self.decl.encode(encoder, value)
    
    def encode(self, encoder, value):
        depth = self.encode_indices(encoder, value)
        self.encode_value(encoder, value, depth)

    def decode_decl(self, decoder):
451
        n_indices = decoder.decode_packed32()
Anders Nilsson's avatar
Anders Nilsson committed
452
453
        indices = []
        for i in range(n_indices):
454
            index = decoder.decode_packed32()
Anders Nilsson's avatar
Anders Nilsson committed
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
            indices.append(index)
        elem_decl = decoder.decode_decl()
        return array(indices, elem_decl)

    def decode_value(self, decoder, indices):
        if not len(indices):
            result = self.decl.decode(decoder)
        else:
            result = []
            for i in range(indices[0]):
                result.append(self.decode_value(decoder, indices[1:]))
        return result

    def decode(self, decoder, obj=None):
        indices = []
        for i in self.indices:
            if i == 0:
472
                i = decoder.decode_packed32()
Anders Nilsson's avatar
Anders Nilsson committed
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
            indices.append(i)
        return self.decode_value(decoder, indices)

    def new_instance_value(self, indices):
        if not len(indices):
            result = self.decl.new_instance()
        else:
            result = []
            for i in range(indices[0]):
                result.append(self.new_instance_value(indices[1:]))
        return result
    
    def new_instance(self):
        indices = []
        for i in self.indices:
            if i == 0:
489
                i = decoder.decode_packed32()
Anders Nilsson's avatar
Anders Nilsson committed
490
491
492
493
494
495
496
497
498
499
500
501
502
            indices.append(i)
        return self.new_instance_value(indices)
    
    def __repr__(self):
        return "labcomm.array(%s,\n    %s)" % (
            self.indices, indent(4, self.decl.__repr__()))
    
class struct:
    def __init__(self, field):
        self.field = field

    def encode_decl(self, encoder):
        encoder.encode_type(i_STRUCT)
503
        encoder.encode_packed32(len(self.field))
Anders Nilsson's avatar
Anders Nilsson committed
504
505
506
507
508
509
510
511
512
513
514
        for (name, decl) in self.field:
            encoder.encode_string(name)
            encoder.encode_type_number(decl)
            #type.encode_decl(encoder)

    def encode(self, encoder, obj):
        if isinstance(obj, dict):
            for (name, decl) in self.field:
                decl.encode(encoder, obj[name])
        else:
            for (name, decl) in self.field:
Anders Blomdell's avatar
Anders Blomdell committed
515
                decl.encode(encoder, getattr(obj, name))
Anders Nilsson's avatar
Anders Nilsson committed
516
517

    def decode_decl(self, decoder):
518
        n_field = decoder.decode_packed32()
Anders Nilsson's avatar
Anders Nilsson committed
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
        field = []
        for i in range(n_field):
            name = decoder.decode_string()
            decl = decoder.decode_decl()
            field.append((name, decl))
        return struct(field)

    def decode(self, decoder, obj=None):
        if obj == None:
            obj = decoder.create_object()
        for (name, decl) in self.field:
            obj.__setattr__(name, decl.decode(decoder))
        return obj

    def new_instance(self):
        result = anonymous_object()
        for (name, decl) in self.field:
            result.__setattr__(name, decl.new_instance())
        return result
    
    def __repr__(self):
        delim = ""
        result = "labcomm.struct(["
        for (name, decl) in self.field:
            result += "%s\n  ('%s', %s)" % (delim, name, decl)
            delim = ","
        result += "\n])"
        return result

548
SAMPLE_DEF = sample(None, None)
Anders Nilsson's avatar
Anders Nilsson committed
549
550
551
552

ARRAY = array(None, None)
STRUCT = struct({})

553
class anonymous_object(dict):
Anders Nilsson's avatar
Anders Nilsson committed
554
555
556
557
    def __setattr__(self, name, value):
        if name.startswith("_"):
            super(anonymous_object, self).__setattr__(name, value)
        else:
558
            self[name] = value
Anders Nilsson's avatar
Anders Nilsson committed
559
560
561
562
563

    def __getattr__(self, name):
        if name.startswith("_"):
            return super(anonymous_object, self).__getattr__(name)
        else:
564
            return self[name]
Anders Nilsson's avatar
Anders Nilsson committed
565
566
567
568
569
570
571
572
573
574
575
576

class Codec(object):
    def __init__(self):
        self.type_to_name = {}
        self.name_to_type = {}
        self.index_to_decl = {}
        self.decl_to_index = {}
        self.name_to_decl = {}
        self.decl_index = i_USER
        self.predefined_types()

    def predefined_types(self):
577
        self.add_decl(SAMPLE_DEF, i_SAMPLE_DEF)
Anders Nilsson's avatar
Anders Nilsson committed
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611

        self.add_decl(ARRAY, i_ARRAY)
        self.add_decl(STRUCT, i_STRUCT)

        self.add_decl(BOOLEAN(), i_BOOLEAN)
        self.add_decl(BYTE(), i_BYTE)
        self.add_decl(SHORT(), i_SHORT)
        self.add_decl(INTEGER(), i_INTEGER)
        self.add_decl(LONG(), i_LONG)
        self.add_decl(FLOAT(), i_FLOAT)
        self.add_decl(DOUBLE(), i_DOUBLE)
        self.add_decl(STRING(), i_STRING)
        
    def add_decl(self, decl, index=0):
        if index == 0:
            index = self.decl_index
            self.decl_index += 1
        self.index_to_decl[index] = decl
        self.decl_to_index[decl] = index
        try:
            self.name_to_decl[decl.name] = decl
        except:
            pass
        
    def add_binding(self, name, decl):
        self.type_to_name[decl] = name
        self.name_to_type[name] = decl

    def samples(self):
        result = []
        index = self.index_to_decl.keys()
        index.sort()
        for i in index:
            e = self.index_to_decl[i]
612
            if i >= i_USER and isinstance(e, sample):
Anders Nilsson's avatar
Anders Nilsson committed
613
614
615
616
617
                result.append(e)
        return result
        

class Encoder(Codec):
618
    def __init__(self, writer, version=DEFAULT_VERSION):
Anders Nilsson's avatar
Anders Nilsson committed
619
620
        super(Encoder, self).__init__()
        self.writer = writer
621
        self.version = version
622
        if self.version in [ "LabComm2014" ]:
623
624
625
626
627
628
629
            self.encode_type(i_VERSION)
            with length_encoder(self) as e:
                e.encode_string(version)
        elif self.version in [ None,  "LabComm2006" ]:
            pass
        else:
            raise Exception("Unsupported labcomm version %s" % self.version)    
Anders Nilsson's avatar
Anders Nilsson committed
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644

    def pack(self, format, *args):
        self.writer.write(packer.pack(format, *args))

    def add_decl(self, decl, index=0):
        super(Encoder, self).add_decl(decl, index)
        if index == 0:
            decl.encode_decl(self)
            self.writer.mark()
 
    def encode(self, object, decl=None):
        if decl == None:
            name = self.type_to_name[object.__class__]
            decl = self.name_to_decl[name]
        self.encode_type_number(decl)
645
646
647
        with length_encoder(self) as e:
            decl.encode(e, object)
#        decl.encode(self, object)
Anders Nilsson's avatar
Anders Nilsson committed
648
649
650
651
652
653
654
655
        self.writer.mark()

    def encode_type_number(self, decl):
        try:
            self.encode_type(self.decl_to_index[decl])
        except KeyError:
            decl.encode_decl(self)
            
656
    def encode_packed32(self, v):
657
        if self.version in [ None, "LabComm2014" ]:
658
659
            v = v & 0xffffffff
            tmp = [ v & 0x7f ]
660
            v = v >> 7
661
662
663
664
665
666
667
668
669
670
            while v:
                tmp.append(v & 0x7f | 0x80)
                v = v >> 7
            for c in reversed(tmp):
                self.encode_byte(c) 
        elif self.version == "LabComm2006" :
            v = v & 0xffffffff
            self.encode_int(v)
        else :
            raise Exception("Unsupported labcomm version %s" % self.version)
671

Anders Nilsson's avatar
Anders Nilsson committed
672
    def encode_type(self, index):
Sven Robertz's avatar
Sven Robertz committed
673
674
        self.encode_packed32(index)
#        self.pack("!i", index)
Anders Nilsson's avatar
Anders Nilsson committed
675
676
677
678
679
680
681
682
            
    def encode_boolean(self, v):
        if v:
            self.pack("!b", 1)
        else:
            self.pack("!b", 0)

    def encode_byte(self, v):
683
        self.pack("!B", v)
Anders Nilsson's avatar
Anders Nilsson committed
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701

    def encode_short(self, v):
        self.pack("!h", v)

    def encode_int(self, v):
        self.pack("!i", v)

    def encode_long(self, v):
        self.pack("!q", v)

    def encode_float(self, v):
        self.pack("!f", v)

    def encode_double(self, v):
        self.pack("!d", v)

    def encode_string(self, v):
        s = v.encode("utf8")
Sven Robertz's avatar
Sven Robertz committed
702
703
704
	self.encode_packed32(len(s));
	self.pack("%ds" % len(s),s)
#        self.pack("!i%ds" % len(s), len(s), s)
Anders Nilsson's avatar
Anders Nilsson committed
705
706

class Decoder(Codec):
707
    def __init__(self, reader, version=DEFAULT_VERSION):
Anders Nilsson's avatar
Anders Nilsson committed
708
709
        super(Decoder, self).__init__()
        self.reader = reader
710
        self.version = version
Anders Nilsson's avatar
Anders Nilsson committed
711
712
713
714
715
716
717
718
719
720
721
722
723
724
        
    def unpack(self, format):
        size = packer.calcsize(format)
        data = ""
        while len(data) < size:
            data += self.reader.read(size - len(data))
        result = packer.unpack(format, data)
        return result[0]

    def decode_decl(self):
        index = self.decode_type_number()
        result = self.index_to_decl[index]
        if index < i_USER:
            result = result.decode_decl(self)
725
726
        else:
            raise Exception('Should not be used')
Anders Nilsson's avatar
Anders Nilsson committed
727
728
        return result

729
730
731
732
    def skip(self, length):
        for _ in xrange(length):
            self.decode_byte()

Anders Nilsson's avatar
Anders Nilsson committed
733
    def decode(self):
734
735
736
737
738
739
740
741
742
743
744
        while True:
            index = self.decode_type_number()
            if usePacketLength(self.version):
                length = self.decode_packed32()
            if index != i_VERSION:
                break
            else:
                other_version = self.decode_string()  
                if self.version != other_version:
                    raise Exception("LabComm version mismatch %s != %s" %
                                    (version, other_version))
745
        if index == i_SAMPLE_DEF:
746
747
            decl = self.index_to_decl[index].decode_decl(self)
            value = None
748
749
750
751
752
753
        elif index == i_TYPE_DEF:
            print "Got type_def, skipping %d bytes" % length
            self.skip(length)
        elif index == i_TYPE_BINDING:
            print "Got type_binding, skipping %d bytes" % length
            self.skip(length)
Anders Nilsson's avatar
Anders Nilsson committed
754
        else:
755
            decl = self.index_to_decl[index]
Anders Nilsson's avatar
Anders Nilsson committed
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
            value = decl.decode(self)
        self.reader.mark(value, decl)
        return (value, decl)

    def create_object(self, name=None):
        if isinstance(self, primitive):
            result = None
        else:
            try:
                decl = self.name_to_type[name]
                result = decl.__new__(decl)
                result.__init__()
            except KeyError:
                result = anonymous_object()

        return result
    
773
    def decode_packed32(self):
774
        if self.version in [ "LabComm2013", "LabComm2014" ] :
775
776
777
778
779
780
781
782
783
784
785
            result = 0
            while True:
                tmp = self.decode_byte()
                result = (result << 7) | (tmp & 0x7f)
                if (tmp & 0x80) == 0:
                    break
            return result
        elif self.version == "LabComm2006" :
            return self.decode_int()
        else :
            raise Exception("Unsupported labcomm version %s" % self.version)
786

Anders Nilsson's avatar
Anders Nilsson committed
787
    def decode_type_number(self):
788
        return self.decode_packed32()
Anders Nilsson's avatar
Anders Nilsson committed
789
790
791
792
793
        
    def decode_boolean(self):
        return self.unpack("!b") != 0
    
    def decode_byte(self):
794
        return self.unpack("!B")
Anders Nilsson's avatar
Anders Nilsson committed
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
    
    def decode_short(self):
        return self.unpack("!h")
    
    def decode_int(self):
        return self.unpack("!i")
    
    def decode_long(self):
        return self.unpack("!q")
    
    def decode_float(self):
        return self.unpack("!f")
    
    def decode_double(self):
        return self.unpack("!d")
    
    def decode_string(self):
812
        length =  self.decode_packed32()
Anders Nilsson's avatar
Anders Nilsson committed
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
        return self.unpack("!%ds" % length).decode("utf8")


class signature_reader:
    def __init__(self, signature):
        self.signature = packer.pack("!%db" % len(signature), *signature)

    def read(self, count):
        result = self.signature[0:count]
        self.signature = self.signature[count:]
        return result
        
def decl_from_signature(signature):
    decoder = Decoder(signature_reader(signature))
    t = decoder.decode_decl()
    return t