source: src/python/bin/gnuboat-log-converter@ 26f77a6

0.5 debian/bullseye debian/jessie
Last change on this file since 26f77a6 was 26f77a6, checked in by Joachim Langenbach <joachim.langenbach@…>, 9 years ago
  • Fixed wrong nmea 0183 position formats. They are now (d: degrees, m: minutes):
    • Latitude: ddmm.mmmm
    • Longitude: dddmm.mmmm
  • Added checkums-fix to gnuboat-log-converter to fix checksums of nmea sentences during conversion, if needed
  • Property mode set to 100755
File size: 11.3 KB
Line 
1#!/usr/bin/python
2# -*- coding: utf-8 -*-
3'''
4 Copyright (C) 2016 - 2017 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
5
6 This program is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
18'''
19
20import os
21import argparse
22import sys
23import pynmea2
24from enum import Enum
25import csv
26import re
27import tempfile
28import subprocess
29
30class Format(Enum):
31 CSV = 1
32 NMEA0183 = 2
33 GPX = 3
34
35regex_nmea_sentence = re.compile(r"^([^\$!]{0,})([\$!]{1}[\w]{2}[\w]{3}[^\*]+\*[\da-zA-Z]+)$")
36regex_nmea_sentence_without_checksum = re.compile(r"^([^\$!]{0,})([\$!]{1}[\w]{2}[\w]{3}[^\*]+)\*[\da-zA-Z]+$")
37regex_nmea_position_latitude = re.compile(r"^([0-9]{2})([0-9]{2}\.[0-9]+)$")
38regex_nmea_position_longitude = re.compile(r"^([0-9]{3})([0-9]{2}\.[0-9]+)$")
39
40def toFloat(string, current_row):
41 try:
42 return float(string)
43 except ValueError as error:
44 try:
45 return int(string)
46 except ValueError as error:
47 print('INFO: Failed to convert value from line {} into numeric: {}\n Message: {}'.format(current_row, string, error))
48 return 0
49
50def nmeaLatitudeToDecimalDegrees(nmea_value, current_row):
51 global regex_nmea_position_latitude
52
53 if toFloat(nmea_value, current_row) == 0:
54 return 0
55
56 matches = regex_nmea_position_latitude.match(nmea_value)
57 if matches is None:
58 print('INFO: Failed to convert latitude position value from line {} into decimal degrees: {}'.format(current_row, nmea_value))
59 return
60 decimalDegrees = toFloat(matches.group(1), current_row)
61 decimalMinutes = toFloat(matches.group(2), current_row)
62 return decimalDegrees + (decimalMinutes / 60.0)
63
64def nmeaLongitudeToDecimalDegrees(nmea_value, current_row):
65 global regex_nmea_position_longitude
66
67 if toFloat(nmea_value, current_row) == 0:
68 return 0
69
70 matches = regex_nmea_position_longitude.match(nmea_value)
71 if matches is None:
72 print('INFO: Failed to convert longitude position value from line {} into decimal degrees: {}'.format(current_row, nmea_value))
73 return
74 decimalDegrees = toFloat(matches.group(1), current_row)
75 decimalMinutes = toFloat(matches.group(2), current_row)
76 return decimalDegrees + (decimalMinutes / 60.0)
77
78def convertToCsv(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time):
79 global regex_nmea_sentence
80 global regex_nmea_sentence_without_checksum
81
82 try:
83 output_file = open(output_file_path, 'w', 0)
84 except IOError as error:
85 print('ERROR: Could not open the output file: {}'.format(error))
86 sys.exit(3)
87
88 output_file_csv = None
89 fields = ['datetime', 'gps_status', 'latitude', 'latitude_direction', 'longitude',
90 'longitude_direction', 'speed_over_ground', 'course_over_ground' ,
91 'water_depth', 'water_temperature']
92 output_file_csv = csv.DictWriter(output_file, delimiter=' ', quotechar='"',
93 quoting=csv.QUOTE_NONNUMERIC, fieldnames=fields)
94 output_file_csv.writeheader()
95
96 # reading input file
97 try:
98 input_file = open(input_file_path, 'r')
99 except IOError as error:
100 print('ERROR: Could not open the input file: {}'.format(error))
101 sys.exit(3)
102 current_row = 1
103 last_row = None
104 for line in input_file:
105 line = line.strip()
106 if checksums_fix:
107 matches = regex_nmea_sentence_without_checksum.match(line)
108 pynmea_parse_check = False
109 else:
110 matches = regex_nmea_sentence.match(line)
111 pynmea_parse_check = True
112 if matches is None:
113 print('INFO: Failed to parse nmea sentence ({}) at line {}\n'.format(line, current_row))
114 if not errors_ignore:
115 input_file.close()
116 output_file.close()
117 sys.exit(4)
118 else:
119 nmea_sentence = pynmea2.parse(matches.group(2), check=pynmea_parse_check)
120 if nmea_sentence.sentence_type == 'RMC':
121 if last_row is not None:
122 output_file_csv.writerow(last_row)
123 last_row = {'datetime': '{} {}'.format(nmea_sentence.datestamp, nmea_sentence.timestamp),
124 'gps_status': nmea_sentence.status,
125 'latitude': nmeaLatitudeToDecimalDegrees(nmea_sentence.lat, current_row),
126 'latitude_direction': nmea_sentence.lat_dir,
127 'longitude': nmeaLongitudeToDecimalDegrees(nmea_sentence.lon, current_row),
128 'longitude_direction': nmea_sentence.lon_dir,
129 'speed_over_ground': toFloat(nmea_sentence.spd_over_grnd, current_row),
130 'course_over_ground': toFloat(nmea_sentence.true_course, current_row),
131 'water_depth': None,
132 'water_temperature': None}
133 elif nmea_sentence.sentence_type == 'DPT' and last_row is not None:
134 last_row['water_depth'] = toFloat(nmea_sentence.depth, current_row)
135 elif nmea_sentence.sentence_type == 'MTW' and last_row is not None:
136 last_row['water_temperature'] = toFloat(nmea_sentence.temperature, current_row)
137 current_row += 1
138 if last_row is not None:
139 output_file_csv.writerow(last_row)
140 output_file.close()
141 input_file.close()
142
143def convertToNmea0183(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time):
144 global regex_nmea_sentence
145 global regex_nmea_sentence_without_checksum
146
147 try:
148 output_file = open(output_file_path, 'w', 0)
149 except IOError as error:
150 print('ERROR: Could not open the output file: {}'.format(error))
151 sys.exit(3)
152
153 # reading input file
154 try:
155 input_file = open(input_file_path, 'r')
156 except IOError as error:
157 print('ERROR: Could not open the input file: {}'.format(error))
158 sys.exit(3)
159 current_row = 1
160 last_row = None
161 for line in input_file:
162 line = line.strip()
163 if checksums_fix:
164 matches = regex_nmea_sentence_without_checksum.match(line)
165 pynmea_parse_check = False
166 else:
167 matches = regex_nmea_sentence.match(line)
168 pynmea_parse_check = True
169 if matches is None:
170 print('INFO: Failed to parse nmea sentence ({}) at line {}\n'.format(line, current_row))
171 if not errors_ignore:
172 input_file.close()
173 output_file.close()
174 sys.exit(4)
175 else:
176 nmea_sentence = pynmea2.parse(matches.group(2), check=pynmea_parse_check)
177 output_string = str(nmea_sentence)
178 if not strip_time and matches.group(1):
179 output_string = '{}{}'.format(matches.group(1), output_string)
180 output_file.write('{}\r\n'.format(str(output_string)))
181 output_file.close()
182 input_file.close()
183
184def convertToGpx(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time):
185 # make sure, nmea input file, does not have timestamps in front of the nmea
186 # sentences
187 [nmea_without_timestamps_handle, nmea_without_timestamp_file_path] = tempfile.mkstemp(text=True)
188 convertToNmea0183(input_file_path, nmea_without_timestamp_file_path, errors_ignore, checksums_fix, True)
189
190 subprocess.call(['gpsbabel', '-i', 'nmea', '-f', nmea_without_timestamp_file_path, '-o', 'gpx', '-F', output_file_path])
191 os.remove(nmea_without_timestamp_file_path)
192
193def main(argv):
194 input_file_path = None
195 output_file_path = None
196 output_format_option = None
197 output_format = Format.CSV
198 errors_ignore = False
199 strip_time = False
200
201 formats = []
202 for file_format in Format:
203 formats.append(file_format.name)
204
205 parser = argparse.ArgumentParser(description='Convert gnuboat logfiles into other formats')
206 parser.add_argument('-f', '--format', dest='output_format', metavar='output_format', type=str,
207 help='Format of the output file.', choices=formats, default='CSV')
208 parser.add_argument('-i', '--ignore-errors', dest='errors_ignore', action='store_false',
209 help='Ignore any errors reading the log file')
210 parser.add_argument('-c', '--checksums-fix', dest='checksums_fix', action='store_true',
211 help='Ignore all checksums (and replace them with a new correct one, if needed)')
212 parser.add_argument('input_file', metavar='input_file_path', type=str,
213 help='File to be converted (input)')
214 parser.add_argument('output_file', metavar='output_file_path', type=str,
215 help='Write the converted content to file (output)')
216 parser.add_argument('--strip-time', dest='strip_time', action='store_true',
217 help='Removes timestamp in front of the nmea sentence, if it is there')
218 arguments = parser.parse_args(argv)
219
220 if arguments.output_format is not None:
221 format_found = False
222 for file_format in Format:
223 if file_format.name == arguments.output_format:
224 output_format = file_format.value
225 format_found = True
226 if not format_found:
227 print('ERROR: Invalid input format specified: {}'.format(arguments.output_format))
228 sys.exit(1)
229
230 if arguments.errors_ignore is not None:
231 errors_ignore = arguments.errors_ignore
232
233 if arguments.checksums_fix is not None:
234 checksums_fix = arguments.checksums_fix
235
236 if arguments.strip_time is not None:
237 strip_time = arguments.strip_time
238
239 if arguments.input_file is None:
240 print('ERROR: No input file specified')
241 sys.exit(2)
242 #elif not os.path.exists(arguments.input_file):
243 print('ERROR: Specified input file does not exists: {}'.format(arguments.input_file))
244 sys.exit(3)
245 else:
246 input_file_path = arguments.input_file
247
248 if arguments.output_file is None:
249 print('ERROR: No output file specified')
250 sys.exit(2)
251 elif not os.path.exists(os.path.dirname(arguments.output_file)):
252 print('ERROR: Specified directory of output file does not exists: {}'.format(arguments.output_file))
253 sys.exit(3)
254 else:
255 output_file_path = arguments.output_file
256
257 if output_format == Format.CSV.value:
258 convertToCsv(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time)
259 elif output_format == Format.NMEA0183.value:
260 convertToNmea0183(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time)
261 elif output_format == Format.GPX.value:
262 convertToGpx(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time)
263 else:
264 print('ERROR: Undefined output format!\n')
265 sys.exit(1)
266
267 sys.exit(0)
268
269if __name__ == "__main__":
270 main(sys.argv[1:])
Note: See TracBrowser for help on using the repository browser.