source: src/common/bin/gnuboat-log-converter@ 7a831c3

debian/bullseye
Last change on this file since 7a831c3 was 9af0638, checked in by Joachim Langenbach <joachim.langenbach@…>, 7 years ago

Created new python gnuboat_common package, with functions used by gnuboat and mapservice

  • Property mode set to 100755
File size: 7.4 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
31class Format(Enum):
32 CSV = 1
33 NMEA0183 = 2
34 GPX = 3
35
36class CsvCallback:
37 def __init__(self, output_file):
38 self._output_file = output_file
39
40 def callback(self, dataset):
41 self._output_file.writerow(dataset.to_dict())
42
43def convertToCsv(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time):
44 try:
45 output_file = open(output_file_path, 'w')
46 except IOError as error:
47 print('ERROR: Could not open the output file: {}'.format(error))
48 sys.exit(3)
49
50 output_file_csv = None
51 fields = ['datetime', 'gps_status', 'latitude', 'latitude_direction', 'longitude',
52 'longitude_direction', 'speed_over_ground', 'course_over_ground' ,
53 'water_depth', 'water_temperature']
54 output_file_csv = csv.DictWriter(output_file, delimiter=' ', quotechar='"',
55 quoting=csv.QUOTE_NONNUMERIC, fieldnames=fields)
56 output_file_csv.writeheader()
57
58 csv_callback = CsvCallback(output_file_csv)
59 log_handler = loghandler.LogHandler()
60 result = log_handler.gnuboat_read_file(input_file_path, csv_callback.callback, checksums_fix, errors_ignore)
61 if result.messages():
62 print('\n'.join(result.errors()))
63 output_file.close()
64
65def convertToNmea0183(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time):
66 try:
67 output_file = open(output_file_path, 'w')
68 except IOError as error:
69 print('ERROR: Could not open the output file: {}'.format(error))
70 sys.exit(3)
71
72 # reading input file
73 try:
74 input_file = open(input_file_path, 'r')
75 except IOError as error:
76 print('ERROR: Could not open the input file: {}'.format(error))
77 sys.exit(3)
78
79 log_handler = loghandler.LogHandler()
80 current_row = 1
81 last_row = None
82 for line in input_file:
83 nmea_sentence = log_handler.parse_nmea_sentence(line, checksums_fix)
84 if nmea_sentence is None:
85 print('INFO: Failed to parse nmea sentence ({}) at line {}'.format(line.strip(), current_row))
86 if not errors_ignore:
87 input_file.close()
88 output_file.close()
89 sys.exit(4)
90 else:
91 output_string = str(nmea_sentence['nmea_sentence'])
92 if not strip_time and nmea_sentence['log_timestamp']:
93 output_string = '{}{}'.format(nmea_sentence['log_timestamp'], output_string)
94 output_file.write('{}\r\n'.format(str(output_string)))
95 current_row += 1
96 output_file.close()
97 input_file.close()
98
99def convertToGpx(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time):
100 # make sure, nmea input file, does not have timestamps in front of the nmea
101 # sentences
102 [nmea_without_timestamps_handle, nmea_without_timestamp_file_path] = tempfile.mkstemp(text=True)
103 convertToNmea0183(input_file_path, nmea_without_timestamp_file_path, errors_ignore, checksums_fix, True)
104
105 subprocess.call(['gpsbabel', '-i', 'nmea', '-f', nmea_without_timestamp_file_path, '-o', 'gpx', '-F', output_file_path])
106 os.remove(nmea_without_timestamp_file_path)
107
108def main(argv):
109 input_file_path = None
110 output_file_path = None
111 output_format_option = None
112 output_format = Format.CSV
113 errors_ignore = False
114 strip_time = False
115
116 formats = []
117 for file_format in Format:
118 formats.append(file_format.name)
119
120 parser = argparse.ArgumentParser(description='Convert gnuboat logfiles into other formats')
121 parser.add_argument('-f', '--format', dest='output_format', type=str,
122 help='Format of the output file.', choices=formats, default='CSV')
123 parser.add_argument('-i', '--ignore-errors', dest='errors_ignore', action='store_false',
124 help='Ignore any errors reading the log file')
125 parser.add_argument('-c', '--checksums-fix', dest='checksums_fix', action='store_true',
126 help='Ignore all checksums (and replace them with a new correct one, if needed)')
127 parser.add_argument('input_file', metavar='input_file_path', type=str,
128 help='File to be converted (input)')
129 parser.add_argument('output_file', metavar='output_file_path', type=str,
130 help='Write the converted content to file (output)')
131 parser.add_argument('--strip-time', dest='strip_time', action='store_true',
132 help='Removes timestamp in front of the nmea sentence, if it is there')
133 arguments = parser.parse_args(argv)
134
135 if arguments.output_format is not None:
136 format_found = False
137 for file_format in Format:
138 if file_format.name == arguments.output_format:
139 output_format = file_format.value
140 format_found = True
141 if not format_found:
142 print('ERROR: Invalid input format specified: {}'.format(arguments.output_format))
143 sys.exit(1)
144
145 if arguments.errors_ignore is not None:
146 errors_ignore = arguments.errors_ignore
147
148 if arguments.checksums_fix is not None:
149 checksums_fix = arguments.checksums_fix
150
151 if arguments.strip_time is not None:
152 strip_time = arguments.strip_time
153
154 if arguments.input_file is None:
155 print('ERROR: No input file specified')
156 sys.exit(2)
157 #elif not os.path.exists(arguments.input_file):
158 print('ERROR: Specified input file does not exists: {}'.format(arguments.input_file))
159 sys.exit(3)
160 else:
161 input_file_path = arguments.input_file
162
163 if arguments.output_file is None:
164 print('ERROR: No output file specified')
165 sys.exit(2)
166 elif not os.path.exists(os.path.dirname(arguments.output_file)):
167 print('ERROR: Specified directory of output file does not exists: {}'.format(arguments.output_file))
168 sys.exit(3)
169 else:
170 output_file_path = arguments.output_file
171
172 if output_format == Format.CSV.value:
173 convertToCsv(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time)
174 elif output_format == Format.NMEA0183.value:
175 convertToNmea0183(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time)
176 elif output_format == Format.GPX.value:
177 convertToGpx(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time)
178 else:
179 print('ERROR: Undefined output format!\n')
180 sys.exit(1)
181
182 sys.exit(0)
183
184if __name__ == "__main__":
185 main(sys.argv[1:])
Note: See TracBrowser for help on using the repository browser.