forked from ratal/mdfreader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mdfinfo4.py
1540 lines (1365 loc) · 65 KB
/
mdfinfo4.py
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
""" Measured Data Format blocks paser for version 4.x
Platform and python version
----------------------------------------
With Unix and Windows for python 2.6+ and 3.2+
Created on Sun Dec 15 12:57:28 2013
:Author: `Aymeric Rateau <https://github.com/ratal/mdfreader>`__
Dependencies
-------------------
- Python >2.6, >3.2 <http://www.python.org>
- Numpy >1.6 <http://numpy.scipy.org>
Attributes
--------------
PythonVersion : float
Python version currently running, needed for compatibility of both python 2.6+ and 3.2+
mdfinfo4 module
--------------------------
"""
from __future__ import print_function
from struct import calcsize, unpack, pack
from sys import version_info, stderr
from numpy import sort, zeros
import time
from xml.etree.ElementTree import Element, SubElement, Comment, tostring, XMLParser, XML, register_namespace
PythonVersion = version_info
PythonVersion = PythonVersion[0]
# datatypes
LINK = '<Q'
REAL = '<d'
BOOL = '<h'
UINT8 = '<B'
BYTE = '<c'
INT16 = '<h'
UINT16 = '<H'
UINT32 = '<I'
INT32 = '<i'
UINT64 = '<Q'
INT64 = '<q'
CHAR = '<c'
class MDFBlock(dict):
"""MDFBlock base class for the MDF related block classes
Methods
------------
loadHeader(fid, pointer)
reads block's header and put in class dict
mdfblockread( fid, type, count )
converts a byte array of length count to a given data type
mdfblockreadCHAR( fid, count )
reads a character chain of length count encoded in latin.
mdfblockreadBYTE( fid, count )
reads an array of UTF-8 encoded bytes
"""
def __init__(self):
""" MDFBlock constructor.
Reserves header keys in class dict (id, reserved,link_count,pointer)
"""
self['id'] = {}
self['reserved'] = {}
self['length'] = {}
self['link_count'] = {}
self['pointer'] = 0
def loadHeader(self, fid, pointer):
""" reads block's header and put in class dict
Parameters
----------------
fid : float
file identifier
pointer : int
position of block in file
"""
# All blocks have the same header
if pointer != 0 and pointer is not None:
fid.seek(pointer)
self['id'] = self.mdfblockreadCHAR(fid, 4)
self['reserved'] = self.mdfblockreadBYTE(fid, 4)
self['length'] = self.mdfblockread(fid, UINT64, 1)
self['link_count'] = self.mdfblockread(fid, UINT64, 1)
self['pointer'] = pointer
def writeHeader(self, fid, Id, block_length, link_count):
""" Writes header of a block
Parameters
----------------
fid : float
file identifier
Id : str
4 character id of block, for instance '##HD'
block_length : int
total block length
link_count : int
number of links in the block
Returns
-------
(block_length_pointer, link_count_pointer)
"""
# make sure beginning of block starts with a multiple of 8 position
current_position = fid.tell()
remain = current_position % 8
if not remain == 0:
current_position = current_position - remain + 8
fid.seek(current_position)
self.writeChar(fid, Id)
self.writeChar(fid, '\0' * 4) # reserved
block_length_pointer = fid.tell()
fid.write(pack(UINT64, block_length)) # block size
link_count_pointer = fid.tell()
fid.write(pack(UINT64, link_count)) # number of links
return current_position
@staticmethod
def mdfblockread(fid, type, count):
""" converts a byte array of length count to a given data type
Parameters
----------------
type : str
C format data type
count : int
number of elements to sequentially read
Returns
-----------
array of values of 'type' parameter
"""
value = fid.read(calcsize(type) * count)
if value:
if count == 1:
return unpack(type, value)[0]
else:
if '<' in type or '>' in type:
endian = type[0]
type = type.strip('<>')
return list(unpack(endian+count*type, value))
else:
return list(unpack(count*type, value))
else:
return None
@staticmethod
def mdfblockreadCHAR(fid, count):
""" reads a character chain of length count encoded in latin. Removes trailing 0
Parameters
----------------
count : int
number of characters to read
Returns
-----------
a string of length count
"""
if PythonVersion < 3:
return fid.read(count).rstrip(b'\x00')
else:
return fid.read(count).decode('iso8859-1', 'replace').rstrip('\x00')
@staticmethod
def writeChar(fid, value, size=None):
""" Writes a char in a block
Parameters
----------------
fid : float
file identifier
value : str
char value to write
size : int
size that should take this char
"""
if size is None:
temp = value
else:
if len(value) > size:
temp = value[:size]
else:
temp = value + '\0' * (size - len(value))
temp += '\0'
if PythonVersion >= 3:
temp = temp.encode('latin1', 'replace')
fid.write(pack('<' + str(len(temp)) + 's', temp))
@staticmethod
def mdfblockreadBYTE(fid, count):
""" reads an array of UTF-8 encoded bytes. Removes trailing 0
Parameters
----------------
count : int
number of bytes to read
Returns
-----------
bytes array of length count
"""
# UTF-8 encoded bytes
if PythonVersion < 3:
return fid.read(count).decode('UTF-8', 'ignore').rstrip(b'\x00')
else:
return fid.read(count).decode('UTF-8', 'ignore').rstrip('\x00')
@staticmethod
def writePointer(fid, pointer, value):
""" Writes a value at pointer position and comes back to orgianl position
Parameters
----------------
fid : float
file identifier
pointer : float
pointer where to write value
value : int
value to write (LINK)
"""
currentPosition = fid.tell()
fid.seek(pointer)
fid.write(pack(LINK, value))
fid.seek(currentPosition)
class IDBlock(MDFBlock):
""" reads or writes ID Block
"""
def __init__(self, fid=None):
if fid is not None:
self.read(fid)
def read(self, fid):
""" reads IDBlock
"""
fid.seek(0)
self['id_file'] = self.mdfblockreadCHAR(fid, 8)
self['id_vers'] = self.mdfblockreadCHAR(fid, 8)
self['id_prog'] = self.mdfblockreadCHAR(fid, 8)
self['id_reserved1'] = self.mdfblockreadBYTE(fid, 4)
self['id_ver'] = self.mdfblockread(fid, UINT16, 1)
self['id_reserved2'] = self.mdfblockreadBYTE(fid, 30)
self['id_unfi_flags'] = self.mdfblockread(fid, UINT16, 1)
self['id_custom_unfi_flags'] = self.mdfblockread(fid, UINT16, 1)
# treatment of unfinalised file
if self['id_ver'] > 410 and 'UnFin' in self['id_file']:
print(' /!\ unfinalised file', file=stderr)
if self['id_unfi_flags'] & 1:
print('Update of cycle counters for CG/CA blocks required', file=stderr)
if self['id_unfi_flags'] & (1 << 1):
print('Update of cycle counters for SR blocks required', file=stderr)
if self['id_unfi_flags'] & (1 << 2):
print('Update of length for last DT block required', file=stderr)
if self['id_unfi_flags'] & (1 << 3):
print('Update of length for last RD block required', file=stderr)
if self['id_unfi_flags'] & (1 << 4):
print('Update of last DL block in each chained list of DL blocks required', file=stderr)
if self['id_unfi_flags'] & (1 << 5):
print('Update of cg_data_bytes and cg_inval_bytes in VLSD CG block required', file=stderr)
if self['id_unfi_flags'] & (1 << 6):
print('Update of offset values for VLSD channel required in case a VLSD CG block is used', file=stderr)
def write(self, fid):
""" Writes IDBlock
"""
self.writeChar(fid, 'MDF ')
self.writeChar(fid, '4.11 ')
self.writeChar(fid, 'MDFreadr')
fid.write(pack(UINT32, 0)) # reserved
fid.write(pack(UINT16, 411)) # version 4.11
self.writeChar(fid, '\0' * 30) # reserved
fid.write(pack(UINT16, 0)) # finalisation flag
fid.write(pack(UINT16, 0)) # custom finalisation flag
class HDBlock(MDFBlock):
""" reads Header block and save in class dict
"""
def __init__(self, fid=None, pointer=64):
if fid is not None:
self.read(fid)
def read(self, fid=None, pointer=64):
# block header
self.loadHeader(fid, pointer)
# header block
self['hd_dg_first'] = self.mdfblockread(fid, LINK, 1)
self['hd_fh_first'] = self.mdfblockread(fid, LINK, 1)
self['hd_ch_first'] = self.mdfblockread(fid, LINK, 1)
self['hd_at_first'] = self.mdfblockread(fid, LINK, 1)
self['hd_ev_first'] = self.mdfblockread(fid, LINK, 1)
self['hd_md_comment'] = self.mdfblockread(fid, LINK, 1)
self['hd_start_time_ns'] = self.mdfblockread(fid, UINT64, 1)
self['hd_tz_offset_min'] = self.mdfblockread(fid, INT16, 1)
self['hd_dst_offset_min'] = self.mdfblockread(fid, INT16, 1)
self['hd_time_flags'] = self.mdfblockread(fid, UINT8, 1)
self['hd_time_class'] = self.mdfblockread(fid, UINT8, 1)
self['hd_flags'] = self.mdfblockread(fid, UINT8, 1)
self['hd_reserved'] = self.mdfblockreadBYTE(fid, 1)
self['hd_start_angle_rad'] = self.mdfblockread(fid, REAL, 1)
self['hd_start_distance'] = self.mdfblockread(fid, REAL, 1)
if self['hd_md_comment']: # if comments exist
self['Comment'] = CommentBlock(fid, self['hd_md_comment'], 'HD')
def write(self, fid):
# write block header
self.writeHeader(fid, '##HD', 104, 6)
# link section
pointers = {}
pointers['HD'] = {}
pointers['HD']['DG'] = fid.tell()
fid.write(pack(LINK, 0)) # first Data group pointer
pointers['HD']['FH'] = fid.tell()
fid.write(pack(LINK, 0)) # first file history block pointer
pointers['HD']['CH'] = fid.tell()
fid.write(pack(LINK, 0)) # pointer to hierarchy Block file
pointers['HD']['AT'] = fid.tell()
fid.write(pack(LINK, 0)) # pointer to attachment Block
pointers['HD']['EV'] = fid.tell()
fid.write(pack(LINK, 0)) # pointer to event Block
pointers['HD']['MD'] = fid.tell()
fid.write(pack(LINK, 0)) # pointer to comment Block
# data section
fid.write(pack(UINT64, int(time.time()*1E9))) # time in ns
fid.write(pack(INT16, int(time.timezone/60))) # timezone offset in min
fid.write(pack(INT16, int(time.daylight*60))) # time daylight offest in min
fid.write(pack(UINT8, 2)) # time flags
fid.write(pack(UINT8, 0)) # time class
fid.write(pack(UINT8, 0)) # hd flags
self.writeChar(fid, '\0') # reserved
fid.write(pack(REAL, 0)) # start angle in radians
fid.write(pack(REAL, 0)) # start distance in meters
# writes Header comments
#temp = CommentBlock()
#pointers.update(temp.write(fid))
return pointers
class FHBlock(MDFBlock):
""" reads File History block and save in class dict
"""
def __init__(self, fid=None, pointer=None):
if fid is not None:
self.read(fid, pointer)
def read(self, fid, pointer):
# block header
self.loadHeader(fid, pointer)
# history block
self['fh_fh_next'] = self.mdfblockread(fid, LINK, 1)
self['fh_md_comment'] = self.mdfblockread(fid, LINK, 1)
self['fh_time_ns'] = self.mdfblockread(fid, UINT64, 1)
self['fh_tz_offset_min'] = self.mdfblockread(fid, INT16, 1)
self['fh_dst_offset_min'] = self.mdfblockread(fid, INT16, 1)
self['fh_time_flags'] = self.mdfblockread(fid, UINT8, 1)
self['fh_reserved'] = self.mdfblockreadBYTE(fid, 3)
if self['fh_md_comment']: # comments exist
self['Comment'] = CommentBlock(fid, self['fh_md_comment'], 'FH')
def write(self, fid):
# write block header
self.writeHeader(fid, '##FH', 56, 2)
# link section
pointers = {}
pointers['FH'] = {}
pointers['FH']['FH'] = fid.tell()
fid.write(pack(LINK, 0)) # No next FH
pointers['FH']['MD'] = fid.tell()
fid.write(pack(LINK, 0)) # comment block
# data section
fid.write(pack(UINT64, int(time.time()*1E9))) # time in ns
fid.write(pack(INT16, int(time.timezone/60))) # timezone offset in min
fid.write(pack(INT16, int(time.daylight*60))) # time daylight offest in min
fid.write(pack(UINT8, 2)) # time flags
self.writeChar(fid, '\0' * 3) # reserved
return pointers
class CHBlock(MDFBlock):
""" reads Channel Hierarchy block and saves in class dict
"""
def __init__(self, fid, pointer):
# block header
self.loadHeader(fid, pointer)
# Channel hierarchy block
self['ch_ch_next'] = self.mdfblockread(fid, LINK, 1)
self['ch_ch_first'] = self.mdfblockread(fid, LINK, 1)
self['ch_tx_name'] = self.mdfblockread(fid, LINK, 1)
self['ch_md_comment'] = self.mdfblockread(fid, LINK, 1)
self['ch_element'] = self.mdfblockread(fid, LINK, (self['link_count'] - 4) / 3)
# data section
self['ch_element_count'] = self.mdfblockread(fid, LINK, 1)
self['ch_type'] = self.mdfblockread(fid, UINT8, 1)
self['ch_reserved'] = self.mdfblockreadBYTE(fid, 3)
if self['ch_md_comment']: # comments exist
self['Comment'] = CommentBlock(fid, self['ch_md_comment'])
if self['ch_tx_name']: # text block containing name of hierarchy level
self['ch_name_level'] = CommentBlock(fid, self['ch_tx_name'])
class CommentBlock(MDFBlock):
""" reads or writes Comment block and saves in class dict
"""
def __init__(self, fid=None, pointer=None, MDType=None):
self.namespace = '{http://www.asam.net/mdf/v4}'
if fid is not None:
self.read(fid, pointer, MDType)
def read(self, fid, pointer, MDType=None):
""" reads Comment block and saves in class dict
Notes
--------
Can read xml (MD metadata) or text (TX) comments from several kind of blocks
"""
if pointer > 0:
# block header
self.loadHeader(fid, pointer)
if self['id'] in ('##MD', b'##MD'):
# Metadata block
self['Comment'] = self.mdfblockreadBYTE(fid, self['length'] - 24) # [:-1] # removes normal 0 at end
utf8parser = XMLParser(encoding="utf-8")
try:
self['xml_tree'] = XML(self['Comment'].encode('utf-8'), parser=utf8parser)
self['xml'] = elementTreeToDict(self['xml_tree'])
# specific action per comment block type, extracts specific tags from xml
if MDType == 'CN': # channel comment
self['description'] = self.extractXmlField(self['xml_tree'], 'TX')
self['names'] = self.extractXmlField(self['xml_tree'], 'names')
self['linker_name'] = self.extractXmlField(self['xml_tree'], 'linker_name')
self['linker_address'] = self.extractXmlField(self['xml_tree'], 'linker_address')
self['address'] = self.extractXmlField(self['xml_tree'], 'address')
self['axis_monotony'] = self.extractXmlField(self['xml_tree'], 'axis_monotony')
self['raster'] = self.extractXmlField(self['xml_tree'], 'raster')
self['formula'] = self.extractXmlField(self['xml_tree'], 'formula')
elif MDType == 'unit': # channel comment
self['unit'] = self.extractXmlField(self['xml_tree'], 'TX')
elif MDType == 'HD': # header comment
self['TX'] = self.extractXmlField(self['xml_tree'], 'TX')
tmp = self['xml_tree'].find(self.namespace + 'common_properties')
if tmp is None:
tmp = self['xml_tree'].find('common_properties')
if tmp is not None:
for t in tmp:
self[t.attrib['name']] = t.text
elif MDType == 'FH': # File History comment
self['TX'] = self.extractXmlField(self['xml_tree'], 'TX')
self['tool_id'] = self.extractXmlField(self['xml_tree'], 'tool_id')
self['tool_vendor'] = self.extractXmlField(self['xml_tree'], 'tool_vendor')
self['tool_version'] = self.extractXmlField(self['xml_tree'], 'tool_version')
self['user_name'] = self.extractXmlField(self['xml_tree'], 'user_name')
elif MDType == 'SI':
self['TX'] = self.extractXmlField(self['xml_tree'], 'TX')
self['names'] = self.extractXmlField(self['xml_tree'], 'names')
self['path'] = self.extractXmlField(self['xml_tree'], 'path')
self['bus'] = self.extractXmlField(self['xml_tree'], 'bus')
self['protocol'] = self.extractXmlField(self['xml_tree'], 'protocol')
elif MDType == 'CC':
self['TX'] = self.extractXmlField(self['xml_tree'], 'TX')
self['names'] = self.extractXmlField(self['xml_tree'], 'names')
self['ho:COMPU_METHOD'] = self.extractXmlField(self['xml_tree'], 'ho:COMPU_METHOD')
self['formula'] = self.extractXmlField(self['xml_tree'], 'formula')
else:
if MDType is not None:
print('No recognized MDType', file=stderr)
print(MDType, file=stderr)
except:
print('problem parsing metadata for ' + MDType + ' block', file=stderr)
print(self['Comment'], file=stderr)
elif self['id'] in ('##TX', b'##TX'):
if MDType == 'CN': # channel comment
self['name'] = self.mdfblockreadBYTE(fid, self['length'] - 24)
else:
self['Comment'] = self.mdfblockreadBYTE(fid, self['length'] - 24)
def extractXmlField(self, xml_tree, field):
""" Extract Xml field from a xml tree
Parameters
----------------
xml_tree : xml tree from xml.etree.ElementTree
field : str
Returns
-----------
field value in xml tree
"""
ret = xml_tree.findtext(self.namespace + field)
if ret is None:
ret = xml_tree.findtext(field)
return ret
def write(self, fid, data, MDType):
if MDType == 'TX':
data = data.encode('utf-8', 'replace')
data += b'\0'
# make sure block is multiple of 8
data_lentgth = len(data)
remain = data_lentgth % 8
if not remain == 0:
data += b'\0' * (8 - (remain % 8))
block_start = self.writeHeader(fid, '##TX', 24 + len(data), 0)
fid.write(data)
else:
register_namespace('', 'http://www.asam.net/mdf/v4')
if MDType == 'HD':
root = Element('HDcomment')
root.set('xmlns', 'http://www.asam.net/mdf/v4')
TX = SubElement(root, 'TX')
TX.text = data['comment']
common_properties = SubElement(root, 'common_properties')
e = SubElement(common_properties, 'e', attrib={'name':'subject'})
e.text = data['subject']
e = SubElement(common_properties, 'e', attrib={'name':'project'})
e.text = data['project']
e = SubElement(common_properties, 'e', attrib={'name':'department'})
e.text = data['organisation']
e = SubElement(common_properties, 'e', attrib={'name':'author'})
e.text = data['author']
elif MDType == 'CN':
pass
elif MDType == 'FH':
root = Element('FHcomment')
root.set('xmlns', 'http://www.asam.net/mdf/v4')
TX = SubElement(root, 'TX')
TX.text = data['comment']
tool_id = SubElement(root, 'tool_id')
tool_id.text = 'mdfreader'
tool_vendor = SubElement(root, 'tool_vendor')
tool_vendor.text = 'mdfreader is under GPL V3'
tool_version = SubElement(root, 'tool_version')
tool_version.text = '2.2'
data = tostring(root)
data += b'\0'
# make sure block is multiple of 8
data_lentgth = len(data)
remain = data_lentgth % 8
if not remain == 0:
data += b'\0' * (8 - (remain % 8))
self.writeHeader(fid, '##MD', 24 + len(data), 0)
block_start = fid.write(data)
return block_start
def elementTreeToDict(element):
""" converts xml tree into dictionnary
Parameters
----------------
element : xml tree from xml.etree.ElementTree
Returns
-----------
dict of xml tree flattened
"""
node = dict()
text = getattr(element, 'text', None)
if text is not None:
node['text'] = text
node.update(element.items()) # element's attributes
child_nodes = {}
for child in element: # element's children
child_nodes.setdefault(child, []).append(elementTreeToDict(child))
# convert all single-element lists into non-lists
for key, value in child_nodes.items():
if len(value) == 1:
child_nodes[key] = value[0]
node.update(child_nodes.items())
return node
class DGBlock(MDFBlock):
""" reads Data Group block and saves in class dict
"""
def __init__(self, fid=None, pointer=None):
if fid is not None:
self.read(fid, pointer)
def read(self, fid, pointer):
# block header
self.loadHeader(fid, pointer)
# Data Group block : Links
self['dg_dg_next'] = self.mdfblockread(fid, LINK, 1)
self['dg_cg_first'] = self.mdfblockread(fid, LINK, 1)
self['dg_data'] = self.mdfblockread(fid, LINK, 1)
self['dg_md_comment'] = self.mdfblockread(fid, LINK, 1)
# data section
self['dg_rec_id_size'] = self.mdfblockread(fid, UINT8, 1)
self['dg_reserved'] = self.mdfblockreadBYTE(fid, 7)
if self['dg_md_comment']: # comments exist
self['Comment'] = CommentBlock(fid, self['dg_md_comment'])
def write(self, fid):
pointers = {}
# write block header
pointers['block_start'] = self.writeHeader(fid, '##DG', 64, 4)
# link section
pointers['DG'] = fid.tell()
fid.write(pack(LINK, 0)) # Next Data group pointer
pointers['CG'] = fid.tell()
fid.write(pack(LINK, 0)) # first channel group block pointer
pointers['data'] = fid.tell()
fid.write(pack(LINK, 0)) # data block pointer
pointers['TX'] = fid.tell()
fid.write(pack(LINK, 0)) # comment block pointer
# data section
fid.write(pack(UINT8, 0)) # no recordID
self.writeChar(fid, '\0' * 7) # reserved
return pointers
class CGBlock(MDFBlock):
""" reads Channel Group block and saves in class dict
"""
def __init__(self, fid=None, pointer=None):
if fid is not None:
self.read(fid, pointer)
def read(self, fid, pointer):
# block header
self.loadHeader(fid, pointer)
# Channel Group block : Links
self['cg_cg_next'] = self.mdfblockread(fid, LINK, 1)
self['cg_cn_first'] = self.mdfblockread(fid, LINK, 1)
self['cg_tx_acq_name'] = self.mdfblockread(fid, LINK, 1)
self['cg_si_acq_source'] = self.mdfblockread(fid, LINK, 1)
self['cg_sr_first'] = self.mdfblockread(fid, LINK, 1)
self['cg_md_comment'] = self.mdfblockread(fid, LINK, 1)
# data section
self['cg_record_id'] = self.mdfblockread(fid, UINT64, 1)
self['cg_cycle_count'] = self.mdfblockread(fid, UINT64, 1)
self['cg_flags'] = self.mdfblockread(fid, UINT16, 1)
self['cg_path_separator'] = self.mdfblockread(fid, UINT16, 1)
self['cg_reserved'] = self.mdfblockreadBYTE(fid, 4)
self['cg_data_bytes'] = self.mdfblockread(fid, UINT32, 1)
self['cg_invalid_bytes'] = self.mdfblockread(fid, UINT32, 1)
if self['cg_md_comment']: # comments exist
self['Comment'] = CommentBlock(fid, self['cg_md_comment'])
if self['cg_tx_acq_name']: # comments exist
self['acq_name'] = CommentBlock(fid, self['cg_tx_acq_name'])
def write(self, fid, cg_cycle_count, cg_data_bytes):
pointers = {}
# write block header
pointers['block_start'] = self.writeHeader(fid, '##CG', 104, 6)
# link section
pointers['CG'] = fid.tell()
fid.write(pack(LINK, 0)) # Next channel group pointer
pointers['CN'] = fid.tell()
fid.write(pack(LINK, 0)) # first channel block pointer
pointers['ACN'] = fid.tell()
fid.write(pack(LINK, 0)) # acquisition name pointer
pointers['ACS'] = fid.tell()
fid.write(pack(LINK, 0)) # acquisition source pointer
pointers['SR'] = fid.tell()
fid.write(pack(LINK, 0)) # sample reduction pointer
pointers['TX'] = fid.tell()
fid.write(pack(LINK, 0)) # comment pointer
# data section
fid.write(pack(UINT64, 0)) # no recordID
fid.write(pack(UINT64, cg_cycle_count)) # cycle count
fid.write(pack(UINT16, 0)) # no flags
fid.write(pack(UINT16, 0)) # no character specified for path separator
self.writeChar(fid, '\0' * 4) # reserved
pointers['cg_data_bytes'] = fid.tell()
fid.write(pack(UINT32, cg_data_bytes)) # number of bytes taken by data in record
fid.write(pack(UINT32, 0)) # no invalid bytes
return pointers
class CNBlock(MDFBlock):
""" reads Channel block and saves in class dict
"""
def __init__(self, fid=None, pointer=None):
if fid is not None:
self.read(fid, pointer)
def read(self, fid, pointer):
if pointer != 0 and pointer is not None:
fid.seek(pointer)
self['pointer'] = pointer
self['id'] = self.mdfblockreadCHAR(fid, 4)
self['reserved'] = self.mdfblockreadBYTE(fid, 4)
self['length'] = self.mdfblockread(fid, UINT64, 1)
self['link_count'] = self.mdfblockread(fid, UINT64, 1)
# data section
fid.seek(pointer + self['length'] - 72)
self['cn_type'] = self.mdfblockread(fid, UINT8, 1)
self['cn_sync_type'] = self.mdfblockread(fid, UINT8, 1)
self['cn_data_type'] = self.mdfblockread(fid, UINT8, 1)
self['cn_bit_offset'] = self.mdfblockread(fid, UINT8, 1)
self['cn_byte_offset'] = self.mdfblockread(fid, UINT32, 1)
self['cn_bit_count'] = self.mdfblockread(fid, UINT32, 1)
self['cn_flags'] = self.mdfblockread(fid, UINT32, 1)
self['cn_invalid_bit_pos'] = self.mdfblockread(fid, UINT32, 1)
self['cn_precision'] = self.mdfblockread(fid, UINT8, 1)
self['cn_reserved'] = self.mdfblockreadBYTE(fid, 1)
self['cn_attachment_count'] = self.mdfblockread(fid, UINT16, 1)
self['cn_val_range_min'] = self.mdfblockread(fid, REAL, 1)
self['cn_val_range_max'] = self.mdfblockread(fid, REAL, 1)
self['cn_limit_min'] = self.mdfblockread(fid, REAL, 1)
self['cn_limit_max'] = self.mdfblockread(fid, REAL, 1)
self['cn_limit_ext_min'] = self.mdfblockread(fid, REAL, 1)
self['cn_limit_ext_max'] = self.mdfblockread(fid, REAL, 1)
# Channel Group block : Links
fid.seek(pointer + 24)
self['cn_cn_next'] = self.mdfblockread(fid, LINK, 1)
self['cn_composition'] = self.mdfblockread(fid, LINK, 1)
self['cn_tx_name'] = self.mdfblockread(fid, LINK, 1)
self['cn_si_source'] = self.mdfblockread(fid, LINK, 1)
self['cn_cc_conversion'] = self.mdfblockread(fid, LINK, 1)
self['cn_data'] = self.mdfblockread(fid, LINK, 1)
self['cn_md_unit'] = self.mdfblockread(fid, LINK, 1)
self['cn_md_comment'] = self.mdfblockread(fid, LINK, 1)
if self['cn_attachment_count'] > 0:
self['cn_at_reference'] = self.mdfblockread(fid, LINK, self['cn_attachment_count'])
self['attachment'] = {}
if self['cn_attachment_count'] > 1:
for at in range(self['cn_attachment_count']):
self['attachment'][at] = ATBlock(fid, self['cn_at_reference'][at])
else:
self['attachment'][0] = ATBlock(fid, self['cn_at_reference'])
if self['link_count'] > (8 + self['cn_attachment_count']):
self['cn_default_x'] = self.mdfblockread(fid, LINK, 3)
else:
self['cn_default_x'] = None
if self['cn_md_comment']: # comments exist
self['Comment'] = CommentBlock(fid, self['cn_md_comment'], MDType='CN')
if self['cn_md_unit']: # comments exist
self['unit'] = CommentBlock(fid, self['cn_md_unit'], 'unit')
if self['cn_tx_name']: # comments exist
self['name'] = CommentBlock(fid, self['cn_tx_name'], MDType='CN')['name']
self['name'] = self['name'].replace(':','')
def write(self, fid):
pointers = {}
# write block header
pointers['block_start'] = self.writeHeader(fid, '##CN', 160, 8) # no attachement and default X
# link section
pointers['CN'] = fid.tell()
fid.write(pack(LINK, 0)) # Next channel block pointer
pointers['CN_Comp'] = fid.tell()
fid.write(pack(LINK, 0)) # composition of channel pointer
pointers['TX'] = fid.tell()
fid.write(pack(LINK, 0)) # TXBlock pointer for channel name
pointers['SI'] = fid.tell()
fid.write(pack(LINK, 0)) # source SIBlock pointer
pointers['CC'] = fid.tell()
fid.write(pack(LINK, 0)) # Conversion Channel CCBlock pointer
pointers['data'] = fid.tell()
fid.write(pack(LINK, 0)) # channel data pointer
pointers['Unit'] = fid.tell()
fid.write(pack(LINK, 0)) # channel unit comment block pointer
pointers['Comment'] = fid.tell()
fid.write(pack(LINK, 0)) # channel comment block pointer
# no attachment and default X pointers
# data section
fid.write(pack(UINT8, self['cn_type'])) # channel type, 0 normal, 2 master
fid.write(pack(UINT8, self['cn_sync_type'])) # sync type, 0 None, 1 time, 2 angle, 3 distance, 4 index
fid.write(pack(UINT8, self['cn_data_type'])) # data type
fid.write(pack(UINT8, self['cn_bit_offset'])) # bit offset
fid.write(pack(UINT32, self['cn_byte_offset'])) # byte offset
fid.write(pack(UINT32, self['cn_bit_count'])) # bit count
fid.write(pack(UINT32, 0)) # no flags
fid.write(pack(UINT32, 0)) # no flags
fid.write(pack(UINT8, 0)) # precision
self.writeChar(fid, '\0') # reserved
fid.write(pack(UINT16, 0)) # attachments count
fid.write(pack(REAL, 0)) # val range min
fid.write(pack(REAL, 0)) # val range max
fid.write(pack(REAL, 0)) # val limit min
fid.write(pack(REAL, 0)) # val limit max
fid.write(pack(REAL, 0)) # val limit ext min
fid.write(pack(REAL, 0)) # val limit ext max
return pointers
class CCBlock(MDFBlock):
""" reads Channel Conversion block and saves in class dict
"""
def __init__(self, fid=None, pointer=None):
if fid is not None:
self.read(fid, pointer)
def read(self, fid, pointer):
# block header
if pointer != 0 and pointer is not None:
fid.seek(pointer)
self['id'] = self.mdfblockreadCHAR(fid, 4)
self['reserved'] = self.mdfblockreadBYTE(fid, 4)
self['length'] = self.mdfblockread(fid, UINT64, 1)
self['link_count'] = self.mdfblockread(fid, UINT64, 1)
# Channel Conversion block : Links
self['cc_tx_name'] = self.mdfblockread(fid, LINK, 1)
self['cc_md_unit'] = self.mdfblockread(fid, LINK, 1)
self['cc_md_comment'] = self.mdfblockread(fid, LINK, 1)
self['cc_cc_inverse'] = self.mdfblockread(fid, LINK, 1)
self['cc_ref'] = self.mdfblockread(fid, LINK, self['link_count'] - 4)
# data section
self['cc_type'] = self.mdfblockread(fid, UINT8, 1)
self['cc_precision'] = self.mdfblockread(fid, UINT8, 1)
self['cc_flags'] = self.mdfblockread(fid, UINT16, 1)
self['cc_ref_count'] = self.mdfblockread(fid, UINT16, 1)
self['cc_val_count'] = self.mdfblockread(fid, UINT16, 1)
self['cc_phy_range_min'] = self.mdfblockread(fid, REAL, 1)
self['cc_phy_range_max'] = self.mdfblockread(fid, REAL, 1)
if self['cc_val_count']:
self['cc_val'] = self.mdfblockread(fid, REAL, self['cc_val_count'])
if self['cc_type'] == 3: # reads Algebraic formula
self['cc_ref'] = CommentBlock(fid, self['cc_ref'])
elif self['cc_type']in (7, 8, 9, 10): # text list
for i in range(self['cc_ref_count']):
fid.seek(self['cc_ref'][i])
ID = self.mdfblockreadCHAR(fid, 4) # find if TX/MD or another CCBlock
if ID in ('##TX', '##MD', b'##TX', b'##MD'): # for algebraic formulae
temp = CommentBlock(fid, self['cc_ref'][i])
self['cc_ref'][i] = temp['Comment']
elif ID in ('##CC', b'##CC'): # for table conversion
# much more complicated nesting conversions !!!
self['cc_ref'][i] = CCBlock(fid, self['cc_ref'][i])['name']['Comment']
if self['cc_md_comment']: # comments exist
self['Comment'] = CommentBlock(fid, self['cc_md_comment'], MDType='CC')
if self['cc_md_unit']: # comments exist
self['unit'] = CommentBlock(fid, self['cc_md_unit'])
if self['cc_tx_name']: # comments exist
self['name'] = CommentBlock(fid, self['cc_tx_name'])
else: # no conversion
self['cc_type'] = 0
class CABlock(MDFBlock):
""" reads Channel Array block and saves in class dict
"""
def __init__(self, fid, pointer):
# block header
if pointer != 0 and pointer is not None:
fid.seek(pointer)
self['id'] = self.mdfblockreadCHAR(fid, 4)
self['reserved'] = self.mdfblockreadBYTE(fid, 4)
self['length'] = self.mdfblockread(fid, UINT64, 1)
self['link_count'] = self.mdfblockread(fid, UINT64, 1)
# reads data section
fid.seek(pointer + 24 + self['link_count'] * 8)
self['ca_type'] = self.mdfblockread(fid, UINT8, 1)
self['ca_storage'] = self.mdfblockread(fid, UINT8, 1)
self['ca_ndim'] = self.mdfblockread(fid, UINT16, 1)
self['ca_flags'] = int(self.mdfblockread(fid, UINT32, 1))
self['ca_byte_offset_base'] = self.mdfblockread(fid, INT32, 1)
self['ca_invalid_bit_pos_base'] = self.mdfblockread(fid, UINT32, 1)
self['ca_dim_size'] = self.mdfblockread(fid, UINT64, self['ca_ndim'])
try: # more than one dimension, processing dict
self['SNd'] = 0
self['PNd'] = 1
for x in self['ca_dim_size']:
self['SNd'] += x
self['PNd'] *= x
except: # only one dimension, processing int
self['SNd'] = self['ca_dim_size']
self['PNd'] = self['SNd']
if 1 << 5 & self['ca_flags']: # bit5
self['ca_axis_value'] = self.mdfblockread(fid, REAL, self['SNd'])
if self['ca_storage'] >= 1:
self['ca_cycle_count'] = self.mdfblockread(fid, UINT64, self['PNd'])
# Channel Conversion block : Links
fid.seek(pointer + 24)
self['ca_composition'] = self.mdfblockread(fid, LINK, 1) # point to CN for array of structures or CA for array of array
if self['ca_storage'] == 2:
self['ca_data'] = self.mdfblockread(fid, LINK, self['PNd'])
if 1 << 0 & self['ca_flags']: # bit 0
self['ca_dynamic_size'] = self.mdfblockread(fid, LINK, self['ca_ndim'] * 3)
if 1 << 1 & self['ca_flags']: # bit 1
self['ca_input_quantity'] = self.mdfblockread(fid, LINK, self['ca_ndim'] * 3)
if 1 << 2 & self['ca_flags']: # bit 2
self['ca_output_quantity'] = self.mdfblockread(fid, LINK, 3)
if 1 << 3 & self['ca_flags']: # bit 3
self['ca_comparison_quantity'] = self.mdfblockread(fid, LINK, 3)
if 1 << 4 & self['ca_flags']: # bit 4
self['ca_cc_axis_conversion'] = self.mdfblockread(fid, LINK, self['ca_ndim'])
if 1 << 4 & self['ca_flags'] and not 1 << 5 & self['ca_flags']: # bit 4 and 5
self['ca_axis'] = self.mdfblockread(fid, LINK, self['ca_ndim'] * 3)
# nested arrays
if self['ca_composition']:
self['CABlock'] = CABlock(fid, self['ca_composition'])
class ATBlock(MDFBlock):
""" reads Attachment block and saves in class dict
"""
def __init__(self, fid, pointer):
# block header
if pointer != 0 and pointer is not None:
fid.seek(pointer)
self['id'] = self.mdfblockreadCHAR(fid, 4)
self['reserved'] = self.mdfblockreadBYTE(fid, 4)
self['length'] = self.mdfblockread(fid, UINT64, 1)
self['link_count'] = self.mdfblockread(fid, UINT64, 1)
# links
self['at_at_next'] = self.mdfblockread(fid, LINK, 1)
self['at_tx_filename'] = self.mdfblockread(fid, LINK, 1)
self['at_tx_mimetype'] = self.mdfblockread(fid, LINK, 1)
self['at_md_comment'] = self.mdfblockread(fid, LINK, 1)
# data
self['at_flags'] = self.mdfblockread(fid, UINT16, 1)
self['at_creator_index'] = self.mdfblockread(fid, UINT16, 1)
self['at_reserved'] = self.mdfblockreadBYTE(fid, 4)
self['at_md5_checksum'] = self.mdfblockreadBYTE(fid, 16)
self['at_original_size'] = self.mdfblockread(fid, UINT64, 1)
self['at_embedded_size'] = self.mdfblockread(fid, UINT64, 1)
if self['at_embedded_size'] > 0:
self['at_embedded_data'] = self.mdfblockreadBYTE(fid, self['at_embedded_size'])
if self['at_md_comment']: # comments exist
self['Comment'] = CommentBlock(fid, self['at_md_comment'])
class EVBlock(MDFBlock):
""" reads Event block and saves in class dict
"""
def __init__(self, fid, pointer):
# block header
if pointer != 0 and pointer is not None:
fid.seek(pointer)
self['id'] = self.mdfblockreadCHAR(fid, 4)
self['reserved'] = self.mdfblockreadBYTE(fid, 4)
self['length'] = self.mdfblockread(fid, UINT64, 1)
self['link_count'] = self.mdfblockread(fid, UINT64, 1)
# data section
fid.seek(pointer + self['length'] - 32)
self['ev_type'] = self.mdfblockread(fid, UINT8, 1)
self['ev_sync_type'] = self.mdfblockread(fid, UINT8, 1)
self['ev_range_type'] = self.mdfblockread(fid, UINT8, 1)
self['ev_cause'] = self.mdfblockread(fid, UINT8, 1)
if self['ev_cause'] == 0:
self['ev_cause'] = 'OTHER'
elif self['ev_cause'] == 1:
self['ev_cause'] == 'ERROR'
elif self['ev_cause'] == 2:
self['ev_cause'] == 'TOOL'
elif self['ev_cause'] == 3:
self['ev_cause'] == 'SCRIPT'
elif self['ev_cause'] == 4:
self['ev_cause'] == 'USER'
self['ev_flags'] = self.mdfblockread(fid, UINT8, 1)
self['at_reserved'] = self.mdfblockreadBYTE(fid, 3)
self['ev_scope_count'] = self.mdfblockread(fid, UINT32, 1)
self['ev_attachment_count'] = self.mdfblockread(fid, UINT16, 1)
self['ev_creator_index'] = self.mdfblockread(fid, UINT16, 1)
self['ev_sync_base_value'] = self.mdfblockread(fid, UINT64, 1)
self['ev_sync_factor'] = self.mdfblockread(fid, REAL, 1)
# link section
fid.seek(pointer + 24)
self['ev_ev_next'] = self.mdfblockread(fid, LINK, 1)
self['ev_ev_parent'] = self.mdfblockread(fid, LINK, 1)
self['ev_ev_range'] = self.mdfblockread(fid, LINK, 1)
self['ev_tx_name'] = self.mdfblockread(fid, LINK, 1)
self['ev_md_comment'] = self.mdfblockread(fid, LINK, 1)
self['ev_scope'] = self.mdfblockread(fid, LINK, self['ev_scope_count'])
# post treatment