-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathsimrad_parsers.py
2041 lines (1588 loc) · 86.8 KB
/
simrad_parsers.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
# National Oceanic and Atmospheric Administration (NOAA)
# Alaskan Fisheries Science Center (AFSC)
# Resource Assessment and Conservation Engineering (RACE)
# Midwater Assessment and Conservation Engineering (MACE)
# THIS SOFTWARE AND ITS DOCUMENTATION ARE CONSIDERED TO BE IN THE PUBLIC DOMAIN
# AND THUS ARE AVAILABLE FOR UNRESTRICTED PUBLIC USE. THEY ARE FURNISHED "AS IS."
# THE AUTHORS, THE UNITED STATES GOVERNMENT, ITS INSTRUMENTALITIES, OFFICERS,
# EMPLOYEES, AND AGENTS MAKE NO WARRANTY, EXPRESS OR IMPLIED, AS TO THE USEFULNESS
# OF THE SOFTWARE AND DOCUMENTATION FOR ANY PURPOSE. THEY ASSUME NO RESPONSIBILITY
# (1) FOR THE USE OF THE SOFTWARE AND DOCUMENTATION; OR (2) TO PROVIDE TECHNICAL
# SUPPORT TO USERS.
"""
.. module:: echolab2.instruments.util.simrad_parsers
:synopsis: Parsers for Simrad raw file datagrams
| Developed by: Zac Berkowitz <[email protected]> under contract for
| National Oceanic and Atmospheric Administration (NOAA)
| Alaska Fisheries Science Center (AFSC)
| Midwater Assesment and Conservation Engineering Group (MACE)
|
|
| Authors:
| Zac Berkowitz <[email protected]>
| Rick Towler <[email protected]>
| Maintained by:
| Rick Towler <[email protected]>
"""
import sys
import struct
import re
import numpy as np
from collections import OrderedDict
from lxml import etree as ET
from .date_conversion import nt_to_unix
__all__ = ['SimradNMEAParser', 'SimradDepthParser', 'SimradBottomParser',
'SimradAnnotationParser', 'SimradConfigParser', 'SimradRawParser',
'SimradFILParser', 'SimradXMLParser', 'SimradMRUParser']
class _SimradDatagramParser(object):
'''
'''
def __init__(self, header_type, header_formats):
self._id = header_type
self._headers = header_formats
self._versions = list(header_formats.keys())
def header_fmt(self, version=0):
return '=' + ''.join([x[1] for x in self._headers[version]])
def header_size(self, version=0):
return struct.calcsize(self.header_fmt(version))
def header_fields(self, version=0):
return [x[0] for x in self._headers[version]]
def header(self, version=0):
return self._headers[version][:]
def validate_data_header(self, data):
if isinstance(data, dict):
type_ = data['type'][:3]
version = int(data['type'][3])
elif isinstance(data, str):
type_ = data[:3]
version = int(data[3])
elif isinstance(data, unicode):
data = str(data)
type_ = data[:3]
version = int(data[3])
else:
raise TypeError('Expected a dict or str')
if type_ != self._id:
raise ValueError('Expected data of type %s, not %s' %(self._id, type_))
if version not in self._versions:
raise ValueError('No parser available for type %s version %d' %(self._id, version))
return type_, version
def from_string(self, raw_string, bytes_read):
header = raw_string[:4]
header = header.decode()
id_, version = self.validate_data_header(header)
return self._unpack_contents(raw_string, bytes_read, version=version)
def to_string(self, data={}):
id_, version = self.validate_data_header(data)
datagram_content_str = self._pack_contents(data, version=version)
return self.finalize_datagram(datagram_content_str)
def _unpack_contents(self, raw_string='', version=0):
raise NotImplementedError
def _pack_contents(self, data={}, version=0):
raise NotImplementedError
@classmethod
def finalize_datagram(cls, datagram_content_str):
datagram_size = len(datagram_content_str)
final_fmt = '=l%dsl' % (datagram_size)
return struct.pack(final_fmt, datagram_size, datagram_content_str, datagram_size)
class SimradUnknownParser(_SimradDatagramParser):
'''
Parser for unknown datagram types. This parser only extracts the type
and timestampand returns the remainder of the data unparsed.
type: string == 'DEP0'
low_date: long uint representing LSBytes of 64bit NT date
high_date: long uint representing MSBytes of 64bit NT date
timestamp: datetime.datetime object of NT date, assumed to be UTC
data: bytearray containing the unknown datagram contents
'''
def __init__(self, dg_type):
headers = {0: [('type', '4s'),
('low_date', 'L'),
('high_date', 'L')
]
}
_SimradDatagramParser.__init__(self, dg_type, headers)
def _unpack_contents(self, raw_string, bytes_read, version):
'''
'''
header_values = struct.unpack(self.header_fmt(version), raw_string[:self.header_size(version)])
data = {}
for indx, field in enumerate(self.header_fields(version)):
data[field] = header_values[indx]
if isinstance(data[field], bytes):
data[field] = data[field].decode()
data['timestamp'] = nt_to_unix((data['low_date'], data['high_date']))
data['timestamp'] = data['timestamp'].replace(tzinfo=None)
data['bytes_read'] = bytes_read
data['data'] = raw_string[self.header_size(version):]
return data
def _pack_contents(self, data, version):
datagram_fmt = self.header_fmt(version)
datagram_contents = []
for field in self.header_fields(version):
if isinstance(data[field], str):
data[field] = data[field].encode('latin_1')
datagram_contents.append(data[field])
datagram_fmt += '%ds' % (len(data['data']))
datagram_contents.append(data['data'])
return struct.pack(datagram_fmt, *datagram_contents)
class SimradDepthParser(_SimradDatagramParser):
'''
ER60 Depth Detection datagram (from .bot files) contain the following keys:
type: string == 'DEP0'
low_date: long uint representing LSBytes of 64bit NT date
high_date: long uint representing MSBytes of 64bit NT date
timestamp: datetime.datetime object of NT date, assumed to be UTC
transceiver_count: [long uint] with number of tranceivers
depth: [float], one value for each active channel
reflectivity: [float], one value for each active channel
unused: [float], unused value for each active channel
The following methods are defined:
from_string(str): parse a raw ER60 Depth datagram
(with leading/trailing datagram size stripped)
to_string(): Returns the datagram as a raw string (including leading/trailing size fields)
ready for writing to disk
'''
def __init__(self):
headers = {0: [('type', '4s'),
('low_date', 'L'),
('high_date', 'L'),
('transceiver_count', 'L')
]
}
_SimradDatagramParser.__init__(self, "DEP", headers)
def _unpack_contents(self, raw_string, bytes_read, version):
'''
'''
header_values = struct.unpack(self.header_fmt(version), raw_string[:self.header_size(version)])
data = {}
for indx, field in enumerate(self.header_fields(version)):
data[field] = header_values[indx]
if isinstance(data[field], bytes):
data[field] = data[field].decode()
data['timestamp'] = nt_to_unix((data['low_date'], data['high_date']))
data['timestamp'] = data['timestamp'].replace(tzinfo=None)
data['bytes_read'] = bytes_read
if version == 0:
data_fmt = '=3f'
data_size = struct.calcsize(data_fmt)
data['depth'] = np.zeros((data['transceiver_count'],))
data['reflectivity'] = np.zeros((data['transceiver_count'],))
data['unused'] = np.zeros((data['transceiver_count'],))
buf_indx = self.header_size(version)
for indx in range(data['transceiver_count']):
d, r, u = struct.unpack(data_fmt, raw_string[buf_indx:buf_indx + data_size])
data['depth'][indx] = d
data['reflectivity'][indx] = r
data['unused'][indx] = u
buf_indx += data_size
return data
def _pack_contents(self, data, version):
datagram_fmt = self.header_fmt(version)
datagram_contents = []
if version == 0:
lengths = [len(data['depth']), len(data['reflectivity']), len(data['unused']), data['transceiver_count']]
if len(set(lengths)) != 1:
min_indx = min(lengths)
# log.warning('Data lengths mismatched: d:%d, r:%d, u:%d, t:%d',
# *lengths)
# log.warning(' Using minimum value: %d', min_indx)
data['transceiver_count'] = min_indx
else:
min_indx = data['transceiver_count']
for field in self.header_fields(version):
if isinstance(data[field], str):
data[field] = data[field].encode('latin_1')
datagram_contents.append(data[field])
datagram_fmt += '%df' % (3*data['transceiver_count'])
for indx in range(data['transceiver_count']):
datagram_contents.extend([data['depth'][indx], data['reflectivity'][indx], data['unused'][indx]])
return struct.pack(datagram_fmt, *datagram_contents)
class SimradBottomParser(_SimradDatagramParser):
'''
Bottom Detection datagram contains the following keys:
type: string == 'BOT0'
low_date: long uint representing LSBytes of 64bit NT date
high_date: long uint representing MSBytes of 64bit NT date
datetime: datetime.datetime object of NT date converted to UTC
transceiver_count: long uint with number of tranceivers
depth: [float], one value for each active channel
The following methods are defined:
from_string(str): parse a raw ER60 Bottom datagram
(with leading/trailing datagram size stripped)
to_string(): Returns the datagram as a raw string (including leading/trailing size fields)
ready for writing to disk
'''
def __init__(self):
headers = {0: [('type', '4s'),
('low_date', 'L'),
('high_date', 'L'),
('transceiver_count', 'L')
]
}
_SimradDatagramParser.__init__(self, "BOT", headers)
def _unpack_contents(self, raw_string, bytes_read, version):
'''
'''
header_values = struct.unpack(self.header_fmt(version), raw_string[:self.header_size(version)])
data = {}
for indx, field in enumerate(self.header_fields(version)):
data[field] = header_values[indx]
if isinstance(data[field], bytes):
data[field] = data[field].decode()
data['timestamp'] = nt_to_unix((data['low_date'], data['high_date']))
data['timestamp'] = data['timestamp'].replace(tzinfo=None)
data['bytes_read'] = bytes_read
if version == 0:
depth_fmt = '=%dd' %(data['transceiver_count'],)
depth_size = struct.calcsize(depth_fmt)
buf_indx = self.header_size(version)
data['depth'] = np.fromiter(struct.unpack(depth_fmt, raw_string[buf_indx:buf_indx + depth_size]), 'float')
return data
def _pack_contents(self, data, version):
datagram_fmt = self.header_fmt(version)
datagram_contents = []
if version == 0:
if len(data['depth']) != data['transceiver_count']:
# log.warning('# of depth values %d does not match transceiver count %d',
# len(data['depth']), data['transceiver_count'])
data['transceiver_count'] = len(data['depth'])
for field in self.header_fields(version):
if isinstance(data[field], str):
data[field] = data[field].encode('latin_1')
datagram_contents.append(data[field])
datagram_fmt += '%dd' % (data['transceiver_count'])
datagram_contents.extend(data['depth'])
return struct.pack(datagram_fmt, *datagram_contents)
class SimradAnnotationParser(_SimradDatagramParser):
'''
ER60 NMEA datagram contains the following keys:
type: string == 'TAG0'
low_date: long uint representing LSBytes of 64bit NT date
high_date: long uint representing MSBytes of 64bit NT date
timestamp: datetime.datetime object of NT date, assumed to be UTC
text: Annotation
The following methods are defined:
from_string(str): parse a raw ER60 Annotation datagram
(with leading/trailing datagram size stripped)
to_string(): Returns the datagram as a raw string (including leading/trailing size fields)
ready for writing to disk
'''
def __init__(self):
headers = {0: [('type', '4s'),
('low_date', 'L'),
('high_date', 'L')
]
}
_SimradDatagramParser.__init__(self, "TAG", headers)
def _unpack_contents(self, raw_string, bytes_read, version):
'''
'''
header_values = struct.unpack(self.header_fmt(version), raw_string[:self.header_size(version)])
data = {}
for indx, field in enumerate(self.header_fields(version)):
data[field] = header_values[indx]
if isinstance(data[field], bytes):
data[field] = data[field].decode()
data['timestamp'] = nt_to_unix((data['low_date'], data['high_date']))
data['timestamp'] = data['timestamp'].replace(tzinfo=None)
data['bytes_read'] = bytes_read
if version == 0:
if (sys.version_info.major > 2):
data['text'] = str(raw_string[self.header_size(version):].strip(b'\x00'), 'ascii', errors='replace')
else:
data['text'] = unicode(raw_string[self.header_size(version):].strip('\x00'), 'ascii', errors='replace')
return data
def _pack_contents(self, data, version):
datagram_fmt = self.header_fmt(version)
datagram_contents = []
if version == 0:
for field in self.header_fields(version):
if isinstance(data[field], str):
data[field] = data[field].encode('latin_1')
datagram_contents.append(data[field])
if data['text'][-1] != '\x00':
tmp_string = data['text'] + '\x00'
else:
tmp_string = data['text']
#Pad with more nulls to 4-byte word boundry if necessary
if len(tmp_string) % 4:
tmp_string += '\x00' * (4 - (len(tmp_string) % 4))
# handle Python 3 strings
tmp_string = tmp_string.encode('latin_1')
datagram_fmt += '%ds' % (len(tmp_string))
datagram_contents.append(tmp_string)
return struct.pack(datagram_fmt, *datagram_contents)
class SimradNMEAParser(_SimradDatagramParser):
'''
ER60 NMEA datagram contains the following keys:
type: string == 'NME0'
low_date: long uint representing LSBytes of 64bit NT date
high_date: long uint representing MSBytes of 64bit NT date
timestamp: datetime.datetime object of NT date, assumed to be UTC
nmea_string: full (original) NMEA string
The following methods are defined:
from_string(str): parse a raw ER60 NMEA datagram
(with leading/trailing datagram size stripped)
to_string(): Returns the datagram as a raw string (including leading/trailing size fields)
ready for writing to disk
'''
nmea_head_re = re.compile('\$[A-Za-z]{5},')
def __init__(self):
headers = {0: [('type', '4s'),
('low_date', 'L'),
('high_date', 'L')
]
}
_SimradDatagramParser.__init__(self, "NME", headers)
def _unpack_contents(self, raw_string, bytes_read, version):
'''
Parses the NMEA string provided in raw_string
:param raw_string: Raw NMEA strin (i.e. '$GPZDA,160012.71,11,03,2004,-1,00*7D')
:type raw_string: str
:returns: None
'''
header_values = struct.unpack(self.header_fmt(version), raw_string[:self.header_size(version)])
data = {}
for indx, field in enumerate(self.header_fields(version)):
data[field] = header_values[indx]
if isinstance(data[field], bytes):
data[field] = data[field].decode()
data['timestamp'] = nt_to_unix((data['low_date'], data['high_date']))
data['timestamp'] = data['timestamp'].replace(tzinfo=None)
data['bytes_read'] = bytes_read
if version == 0:
if (sys.version_info.major > 2):
data['nmea_string'] = str(raw_string[self.header_size(version):].strip(b'\x00'), 'ascii', errors='replace')
else:
data['nmea_string'] = unicode(raw_string[self.header_size(version):].strip('\x00'), 'ascii', errors='replace')
if self.nmea_head_re.match(data['nmea_string'][:7]) is not None:
data['nmea_talker'] = data['nmea_string'][1:3]
data['nmea_type'] = data['nmea_string'][3:6]
else:
data['nmea_talker'] = ''
data['nmea_type'] = 'UNKNOWN'
return data
def _pack_contents(self, data, version):
datagram_fmt = self.header_fmt(version)
datagram_contents = []
if version == 0:
for field in self.header_fields(version):
if isinstance(data[field], str):
data[field] = data[field].encode('latin_1')
datagram_contents.append(data[field])
if data['nmea_string'][-1] != '\x00':
tmp_string = data['nmea_string'] + '\x00'
else:
tmp_string = data['nmea_string']
#Pad with more nulls to 4-byte word boundry if necessary
if len(tmp_string) % 4:
tmp_string += '\x00' * (4 - (len(tmp_string) % 4))
datagram_fmt += '%ds' % (len(tmp_string))
#Convert to python string if needed
if isinstance(tmp_string, str):
tmp_string = tmp_string.encode('ascii', errors='replace')
datagram_contents.append(tmp_string)
return struct.pack(datagram_fmt, *datagram_contents)
class SimradMRUParser(_SimradDatagramParser):
'''
EK80 MRU datagram contains the following keys:
type: string == 'MRU0'
low_date: long uint representing LSBytes of 64bit NT date
high_date: long uint representing MSBytes of 64bit NT date
timestamp: datetime.datetime object of NT date, assumed to be UTC
heave: float
roll : float
pitch: float
heading: float
The following methods are defined:
from_string(str): parse a raw EK800 MRU datagram
(with leading/trailing datagram size stripped)
to_string(): Returns the datagram as a raw string (including leading/trailing size fields)
ready for writing to disk
'''
def __init__(self):
headers = {0: [('type', '4s'),
('low_date', 'L'),
('high_date', 'L'),
('heave', 'f'),
('roll', 'f'),
('pitch', 'f'),
('heading', 'f'),
]
}
_SimradDatagramParser.__init__(self, "MRU", headers)
def _unpack_contents(self, raw_string, bytes_read, version):
'''
Unpacks the data in raw_string into dictionary containing MRU data
:param raw_string:
:type raw_string: str
:returns: None
'''
header_values = struct.unpack(self.header_fmt(version), raw_string[:self.header_size(version)])
data = {}
for indx, field in enumerate(self.header_fields(version)):
data[field] = header_values[indx]
if isinstance(data[field], bytes):
data[field] = data[field].decode()
data['timestamp'] = nt_to_unix((data['low_date'], data['high_date']))
data['timestamp'] = data['timestamp'].replace(tzinfo=None)
data['bytes_read'] = bytes_read
return data
def _pack_contents(self, data, version):
datagram_fmt = self.header_fmt(version)
datagram_contents = []
if version == 0:
for field in self.header_fields(version):
if isinstance(data[field], str):
data[field] = data[field].encode('latin_1')
datagram_contents.append(data[field])
return struct.pack(datagram_fmt, *datagram_contents)
class SimradIDXParser(_SimradDatagramParser):
'''
ER60/EK80 IDX datagram contains the following keys:
type: string == 'IDX0'
low_date: long uint representing LSBytes of 64bit NT date
high_date: long uint representing MSBytes of 64bit NT date
timestamp: datetime.datetime object of NT date, assumed to be UTC
ping_number: int
distance : float
latitude: float
longitude: float
file_offset: int
The following methods are defined:
from_string(str): parse a raw ER60/EK80 IDX datagram
(with leading/trailing datagram size stripped)
to_string(): Returns the datagram as a raw string (including leading/trailing size fields)
ready for writing to disk
'''
def __init__(self):
headers = {0: [('type', '4s'),
('low_date', 'L'),
('high_date', 'L'),
#('dummy', 'L'), # There are 4 extra bytes in this datagram
('ping_number', 'L'),
('distance', 'd'),
('latitude', 'd'),
('longitude', 'd'),
('file_offset', 'L'),
]
}
_SimradDatagramParser.__init__(self, "IDX", headers)
def _unpack_contents(self, raw_string, bytes_read, version):
'''
Unpacks the data in raw_string into dictionary containing IDX data
:param raw_string:
:type raw_string: str
:returns: None
'''
header_values = struct.unpack(self.header_fmt(version), raw_string[:self.header_size(version)])
data = {}
for indx, field in enumerate(self.header_fields(version)):
data[field] = header_values[indx]
if isinstance(data[field], bytes):
data[field] = data[field].decode()
data['timestamp'] = nt_to_unix((data['low_date'], data['high_date']))
data['timestamp'] = data['timestamp'].replace(tzinfo=None)
data['bytes_read'] = bytes_read
return data
def _pack_contents(self, data, version):
datagram_fmt = self.header_fmt(version)
datagram_contents = []
if version == 0:
for field in self.header_fields(version):
if isinstance(data[field], str):
data[field] = data[field].encode('latin_1')
datagram_contents.append(data[field])
return struct.pack(datagram_fmt, *datagram_contents)
class SimradXMLParser(_SimradDatagramParser):
'''
EK80 XML datagram contains the following keys:
type: string == 'XML0'
low_date: long uint representing LSBytes of 64bit NT date
high_date: long uint representing MSBytes of 64bit NT date
timestamp: datetime.datetime object of NT date, assumed to be UTC
subtype: string representing Simrad XML datagram type: configuration, environment, or parameter
[subtype]: dict containing the data specific to the XML subtype.
The following methods are defined:
from_string(str): parse a raw EK80 XML datagram
(with leading/trailing datagram size stripped)
to_string(): Returns the datagram as a raw string (including leading/trailing size fields)
ready for writing to disk
'''
# define the XML parsing options - here we define dictionaries for the various xml datagram
# types. When parsing that datagram, these dictionaries are used to inform the parser about
# type conversion, name wrangling, and delimiter.
#
# the dicts are in the form:
# 'XMLParamName':[converted type,'fieldname', 'parse char']
#
# For example: 'PulseDurationFM':[float,'pulse_duration_fm',';']
#
# will result in a return dictionary field named 'pulse_duration_fm' that contains a list
# of float values parsed from a string that uses ';' to separate values. If the parse
# char is empty, the field is not parsed.
#
# The switch to OrderedDict was required to ensure that when writing files, the generated
# XML follows the original XML parameter ordering.
# These parameters are the known parameters for the transceiver XML tag
transceiver_xml_map = OrderedDict({
'TransceiverName':[str,'transceiver_name',''],
'EthernetAddress':[str,'ethernet_address',''],
'IPAddress':[str,'ip_address',''],
'Version':[str,'transceiver_version',''],
'TransceiverSoftwareVersion':[str,'transceiver_software_version',''],
'TransceiverNumber':[int,'transceiver_number',''],
'MarketSegment':[str,'market_segment',''],
'TransceiverType':[str,'transceiver_type',''],
'SerialNumber':[str,'serial_number',''],
'Impedance':[int,'impedance',''],
'Multiplexing':[int,'multiplexing',''],
'RxSampleFrequency':[float,'rx_sample_frequency','']})
channel_xml_map = OrderedDict({
'ChannelID':[str,'channel_id',''],
'ChannelIdShort':[str,'channel_id_short',''],
'MaxTxPowerTransceiver':[int,'max_tx_power_transceiver',''],
'PulseDuration':[float,'pulse_duration',';'],
'PulseDurationFM':[float,'pulse_duration_fm',';'],
'HWChannelConfiguration':[str,'hw_channel_configuration','']})
channel_xdcr_xml_map = OrderedDict({
'TransducerName':[str,'transducer_name',''],
'SerialNumber':[str,'transducer_serial_number',''],
'Frequency':[float,'transducer_frequency',''],
'FrequencyMinimum':[float,'transducer_frequency_minimum',''],
'FrequencyMaximum':[float,'transducer_frequency_maximum',''],
'BeamType':[int,'transducer_beam_type',''],
'EquivalentBeamAngle':[float,'equivalent_beam_angle',''],
'Gain':[float,'gain',';'],
'SaCorrection':[float,'sa_correction',';'],
'MaxTxPowerTransducer':[float,'max_tx_power_transducer',''],
'BeamWidthAlongship':[float,'beam_width_alongship',''],
'BeamWidthAthwartship':[float,'beam_width_athwartship',''],
'AngleSensitivityAlongship':[float,'angle_sensitivity_alongship',''],
'AngleSensitivityAthwartship':[float,'angle_sensitivity_athwartship',''],
'AngleOffsetAlongship':[float,'angle_offset_alongship',''],
'AngleOffsetAthwartship':[float,'angle_offset_athwartship',''],
'DirectivityDropAt2XBeamWidth':[float,'directivity_drop_at_2x_beam_width','']})
xdcrs_xdcr_xml_map = OrderedDict({
'TransducerName':[str,'transducer_name',''],
'TransducerMounting':[str,'transducer_mounting',''],
'TransducerCustomName':[str,'transducer_custom_name',''],
'TransducerSerialNumber':[str,'transducer_serial_number',''],
'TransducerOrientation':[str,'transducer_orientation',''],
'TransducerOffsetX':[float,'transducer_offset_x',''],
'TransducerOffsetY':[float,'transducer_offset_y',''],
'TransducerOffsetZ':[float,'transducer_offset_z',''],
'TransducerAlphaX':[float,'transducer_alpha_x',''],
'TransducerAlphaY':[float,'transducer_alpha_y',''],
'TransducerAlphaZ':[float,'transducer_alpha_z','']})
header_xml_map = OrderedDict({
'Copyright':[str,'copyright',''],
'ApplicationName':[str,'application_name',''],
'Version':[str,'application_version',''],
'FileFormatVersion':[str,'file_format_version',''],
'TimeBias':[str,'time_bias','']})
#env_xdcr_xml_map = OrderedDict({
# 'SoundSpeed':[float,'transducer_sound_speed','']})
environment_xml_map = OrderedDict({
'Depth':[float,'depth',''],
'Acidity':[float,'acidity',''],
'Salinity':[float,'salinity',''],
'SoundSpeed':[float,'sound_speed',''],
'Temperature':[float,'temperature',''],
'Latitude':[float,'latitude',''],
'SoundVelocityProfile':[float,'sound_velocity_profile',';'],
'SoundVelocitySource':[str,'sound_velocity_source',''],
'DropKeelOffset':[float,'drop_keel_offset',''],
'DropKeelOffsetIsManual':[int,'drop_keel_offset_is_manual',''],
'WaterLevelDraft':[float,'water_level_draft',''],
'WaterLevelDraftIsManual':[int,'water_level_draft_is_manual','']})
parameter_xml_map = OrderedDict({
'PingId':[str,'ping_id',''],
'ChannelID':[str,'channel_id',''],
'ChannelMode':[int,'channel_mode',''],
'PulseForm':[int,'pulse_form',''],
'Frequency':[float,'frequency',''],
'FrequencyStart':[float,'frequency_start',''],
'FrequencyEnd':[float,'frequency_end',''],
'PulseDuration':[float,'pulse_duration',''],
'EffectivePulseDuration':[float,'effective_pulse_duration',''],
'PulseLength':[float,'pulse_length',''],
'SampleInterval':[float,'sample_interval',''],
'TransmitPower':[float,'transmit_power',''],
'Slope':[float,'slope',''],
'SoundVelocity':[float,'sound_velocity','']})
freq_param_xml_map = OrderedDict({
'Frequency':[float,'frequency',''],
'Gain':[float,'gain',''],
'Impedance':[float,'impedance',''],
'Phase':[float,'phase',''],
'BeamWidthAlongship':[float,'beam_width_alongship',''],
'BeamWidthAthwartship':[float,'beam_width_athwartship',''],
'AngleOffsetAlongship':[float,'angle_offset_alongship',''],
'AngleOffsetAthwartship':[float,'angle_offset_athwartship','']})
def __init__(self):
headers = {0: [('type', '4s'),
('low_date', 'L'),
('high_date', 'L')
]
}
_SimradDatagramParser.__init__(self, "XML", headers)
def _unpack_contents(self, raw_string, bytes_read, version):
'''
Parses the XML string provided in raw_string
:param raw_string: Raw XML string
:type raw_string: str
:returns: Dictionary containing parsed XML data where the keys are the XML
parameter names. Note that the names are converted from CamelCase
to lower case with "_" to follow the pyEcholab naming convention.
'''
def dict_to_dict(xml_dict, data_dict, parse_opts):
'''
dict_to_dict appends the xml value dicts to a provided dictionary
and along the way converts the key name to conform to the project's
naming convention and optionally parses and or converts values as
specified in the parse_opts dictionary.
'''
for k in xml_dict:
# check if we're parsing this key/value
if k in parse_opts:
# try to parse the string
if (parse_opts[k][2]):
try:
data = xml_dict[k].split(parse_opts[k][2])
except:
# bad or empty parse chararacter(s) provided
data = xml_dict[k]
else:
# no parse char provided - nothing to parse
data = xml_dict[k]
# Try to convert to specified type
if isinstance(data, list):
# Lists are returned as numpy arrays
for i in range(len(data)):
try:
data[i] = parse_opts[k][0](data[i])
except:
pass
# Determine the array type
if parse_opts[k][0] == int:
dtype = np.int32
elif parse_opts[k][0] == float:
dtype = np.float32
else:
dtype = np.string_
# and create the array
data = np.array(data, dtype=dtype)
else:
data = parse_opts[k][0](data)
# and add the value to the provided dict
data_dict[parse_opts[k][1]] = data
# unpack the header data
data = {}
header_values = struct.unpack(self.header_fmt(version), raw_string[:self.header_size(version)])
for indx, field in enumerate(self.header_fields(version)):
data[field] = header_values[indx]
if isinstance(data[field], bytes):
data[field] = data[field].decode()
# add the unix timestanp and bytes read
data['timestamp'] = nt_to_unix((data['low_date'], data['high_date']))
data['timestamp'] = data['timestamp'].replace(tzinfo=None)
data['bytes_read'] = bytes_read
# parse the datagram based on the version
if version == 0:
xml_string = raw_string[self.header_size(version):].strip(b'\x00')
# get the ElementTree element
root_node = ET.fromstring(xml_string)
# get the XML message type
data['subtype'] = root_node.tag.lower()
# create the dictionary that contains the message data
data[data['subtype']] = {}
# parse it
if data['subtype'] == 'configuration':
#print(xml_string.decode('utf-8'))
# Check for the Transducers section - This section contains the
# mounting information about the transducers attached to the system.
# This section was added in later raw file versions and doesn't
# exist in all files.
transducer_map = {}
transducers_node = root_node.find('./Transducers')
if transducers_node is not None:
# Node exists, create a mapping of name to attributes we'll
# use below to map the attributes to the xdcrs connected to
# each transceiver.
for xdcrs_node in transducers_node.iter('Transducer'):
transducer_map[xdcrs_node.get('TransducerName')] = xdcrs_node.attrib
# Parse the Transceiver section
xcvrs_node = root_node.find('./Transceivers')
for xcvr_node in xcvrs_node.iter('Transceiver'):
# Get the transceiver attributes
xcvr_attributes = xcvr_node.attrib
# parse the Channel section -- this works with multiple channels under 1 transceiver
for channel_node in xcvr_node.iter('Channel'):
# Get this channel's attributes
channel_attributes = channel_node.attrib
channel_id = channel_attributes['ChannelID']
# create the configuration dict for this channel
data['configuration'][channel_id] = {}
# Save the raw XML string - needed when writing because we don't parse
# the whole configuration with certain configuration strings
data['configuration'][channel_id]['raw_xml'] = xml_string
# add the transceiver data to the config dict (this is
# replicated for all channels configured for this transceiver)
dict_to_dict(xcvr_attributes, data['configuration'][channel_id],
self.transceiver_xml_map)
# add the general channel data to the config dict
dict_to_dict(channel_attributes, data['configuration'][channel_id],
self.channel_xml_map)
# Get this channel's transducer params
transducer_node = channel_node.find('./Transducer')
transducer_attributes = transducer_node.attrib
# add the channel transducer attributes
dict_to_dict(transducer_attributes, data['configuration'][channel_id],
self.channel_xdcr_xml_map)