source: src/common/bin/gnuboat-log-converter@ 3db3d13

debian/bullseye
Last change on this file since 3db3d13 was 7be94aa, checked in by Joachim Langenbach <joachim.langenbach@…>, 7 years ago
  • Added yapf style config (src/python-style.yapf)
    • Updated all files to the yapf formatted version
  • Property mode set to 100755
File size: 7.9 KB
Line 
1#!/usr/bin/python
2# -*- coding: utf-8 -*-
3'''
4 Copyright (C) 2016 - 2020 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 tempfile
27import subprocess
28
29from gnuboat_common.datahandler import loghandler, logdataset
30
31
32class Format(Enum):
33 CSV = 1
34 NMEA0183 = 2
35 GPX = 3
36
37
38class CsvCallback:
39 def __init__(self, output_file):
40 self._output_file = output_file
41
42 def callback(self, dataset):
43 self._output_file.writerow(dataset.to_dict())
44
45
46def convertToCsv(
47 input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time
48):
49 try:
50 output_file = open(output_file_path, 'w')
51 except IOError as error:
52 print('ERROR: Could not open the output file: {}'.format(error))
53 sys.exit(3)
54
55 output_file_csv = None
56 fields = [
57 'datetime', 'gps_status', 'latitude', 'latitude_direction',
58 'longitude', 'longitude_direction', 'speed_over_ground',
59 'course_over_ground', 'water_depth', 'water_temperature'
60 ]
61 output_file_csv = csv.DictWriter(
62 output_file,
63 delimiter=' ',
64 quotechar='"',
65 quoting=csv.QUOTE_NONNUMERIC,
66 fieldnames=fields
67 )
68 output_file_csv.writeheader()
69
70 csv_callback = CsvCallback(output_file_csv)
71 log_handler = loghandler.LogHandler()
72 result = log_handler.gnuboat_read_file(
73 input_file_path, csv_callback.callback, checksums_fix, errors_ignore
74 )
75 if result.messages():
76 print('\n'.join(result.errors()))
77 output_file.close()
78
79
80def convertToNmea0183(
81 input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time
82):
83 try:
84 output_file = open(output_file_path, 'w')
85 except IOError as error:
86 print('ERROR: Could not open the output file: {}'.format(error))
87 sys.exit(3)
88
89 # reading input file
90 try:
91 input_file = open(input_file_path, 'r')
92 except IOError as error:
93 print('ERROR: Could not open the input file: {}'.format(error))
94 sys.exit(3)
95
96 log_handler = loghandler.LogHandler()
97 current_row = 1
98 last_row = None
99 for line in input_file:
100 nmea_sentence = log_handler.parse_nmea_sentence(line, checksums_fix)
101 if nmea_sentence is None:
102 print(
103 'INFO: Failed to parse nmea sentence ({}) at line {}'.format(
104 line.strip(), current_row
105 )
106 )
107 if not errors_ignore:
108 input_file.close()
109 output_file.close()
110 sys.exit(4)
111 else:
112 output_string = str(nmea_sentence['nmea_sentence'])
113 if not strip_time and nmea_sentence['log_timestamp']:
114 output_string = '{}{}'.format(
115 nmea_sentence['log_timestamp'], output_string
116 )
117 output_file.write('{}\r\n'.format(str(output_string)))
118 current_row += 1
119 output_file.close()
120 input_file.close()
121
122
123def convertToGpx(
124 input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time
125):
126 # make sure, nmea input file, does not have timestamps in front of the nmea
127 # sentences
128 [nmea_without_timestamps_handle,
129 nmea_without_timestamp_file_path] = tempfile.mkstemp(text=True)
130 convertToNmea0183(
131 input_file_path, nmea_without_timestamp_file_path, errors_ignore,
132 checksums_fix, True
133 )
134
135 subprocess.call([
136 'gpsbabel', '-i', 'nmea', '-f', nmea_without_timestamp_file_path, '-o',
137 'gpx', '-F', output_file_path
138 ])
139 os.remove(nmea_without_timestamp_file_path)
140
141
142def main(argv):
143 input_file_path = None
144 output_file_path = None
145 output_format_option = None
146 output_format = Format.CSV
147 errors_ignore = False
148 strip_time = False
149
150 formats = []
151 for file_format in Format:
152 formats.append(file_format.name)
153
154 parser = argparse.ArgumentParser(
155 description='Convert gnuboat logfiles into other formats'
156 )
157 parser.add_argument(
158 '-f',
159 '--format',
160 dest='output_format',
161 type=str,
162 help='Format of the output file.',
163 choices=formats,
164 default='CSV'
165 )
166 parser.add_argument(
167 '-i',
168 '--ignore-errors',
169 dest='errors_ignore',
170 action='store_false',
171 help='Ignore any errors reading the log file'
172 )
173 parser.add_argument(
174 '-c',
175 '--checksums-fix',
176 dest='checksums_fix',
177 action='store_true',
178 help=
179 'Ignore all checksums (and replace them with a new correct one, if needed)'
180 )
181 parser.add_argument(
182 'input_file',
183 metavar='input_file_path',
184 type=str,
185 help='File to be converted (input)'
186 )
187 parser.add_argument(
188 'output_file',
189 metavar='output_file_path',
190 type=str,
191 help='Write the converted content to file (output)'
192 )
193 parser.add_argument(
194 '--strip-time',
195 dest='strip_time',
196 action='store_true',
197 help='Removes timestamp in front of the nmea sentence, if it is there'
198 )
199 arguments = parser.parse_args(argv)
200
201 if arguments.output_format is not None:
202 format_found = False
203 for file_format in Format:
204 if file_format.name == arguments.output_format:
205 output_format = file_format.value
206 format_found = True
207 if not format_found:
208 print(
209 'ERROR: Invalid input format specified: {}'.format(
210 arguments.output_format
211 )
212 )
213 sys.exit(1)
214
215 if arguments.errors_ignore is not None:
216 errors_ignore = arguments.errors_ignore
217
218 if arguments.checksums_fix is not None:
219 checksums_fix = arguments.checksums_fix
220
221 if arguments.strip_time is not None:
222 strip_time = arguments.strip_time
223
224 if arguments.input_file is None:
225 print('ERROR: No input file specified')
226 sys.exit(2)
227 #elif not os.path.exists(arguments.input_file):
228 print(
229 'ERROR: Specified input file does not exists: {}'.format(
230 arguments.input_file
231 )
232 )
233 sys.exit(3)
234 else:
235 input_file_path = arguments.input_file
236
237 if arguments.output_file is None:
238 print('ERROR: No output file specified')
239 sys.exit(2)
240 elif not os.path.exists(os.path.dirname(arguments.output_file)):
241 print(
242 'ERROR: Specified directory of output file does not exists: {}'.
243 format(arguments.output_file)
244 )
245 sys.exit(3)
246 else:
247 output_file_path = arguments.output_file
248
249 if output_format == Format.CSV.value:
250 convertToCsv(
251 input_file_path, output_file_path, errors_ignore, checksums_fix,
252 strip_time
253 )
254 elif output_format == Format.NMEA0183.value:
255 convertToNmea0183(
256 input_file_path, output_file_path, errors_ignore, checksums_fix,
257 strip_time
258 )
259 elif output_format == Format.GPX.value:
260 convertToGpx(
261 input_file_path, output_file_path, errors_ignore, checksums_fix,
262 strip_time
263 )
264 else:
265 print('ERROR: Undefined output format!\n')
266 sys.exit(1)
267
268 sys.exit(0)
269
270
271if __name__ == "__main__":
272 main(sys.argv[1:])
Note: See TracBrowser for help on using the repository browser.