source: src/common/bin/gnuboat-log-converter@ 8f3d1dd

debian/bullseye
Last change on this file since 8f3d1dd 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
RevLine 
[df8c58a]1#!/usr/bin/python
2# -*- coding: utf-8 -*-
3'''
[9af0638]4 Copyright (C) 2016 - 2020 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
[df8c58a]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
[6fbf790]26import tempfile
27import subprocess
[df8c58a]28
[9af0638]29from gnuboat_common.datahandler import loghandler, logdataset
[ea6eba1]30
[df8c58a]31class Format(Enum):
32 CSV = 1
[6fbf790]33 NMEA0183 = 2
34 GPX = 3
[df8c58a]35
[ea6eba1]36class CsvCallback:
37 def __init__(self, output_file):
38 self._output_file = output_file
[df8c58a]39
[ea6eba1]40 def callback(self, dataset):
41 self._output_file.writerow(dataset.to_dict())
[26f77a6]42
43def convertToCsv(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time):
[6fbf790]44 try:
[aa68798]45 output_file = open(output_file_path, 'w')
[6fbf790]46 except IOError as error:
[b45e75d]47 print('ERROR: Could not open the output file: {}'.format(error))
[6fbf790]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
[ea6eba1]58 csv_callback = CsvCallback(output_file_csv)
59 log_handler = loghandler.LogHandler()
[9af0638]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()))
[6fbf790]63 output_file.close()
64
[26f77a6]65def convertToNmea0183(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time):
[6fbf790]66 try:
[aa68798]67 output_file = open(output_file_path, 'w')
[6fbf790]68 except IOError as error:
[b45e75d]69 print('ERROR: Could not open the output file: {}'.format(error))
[6fbf790]70 sys.exit(3)
71
72 # reading input file
73 try:
74 input_file = open(input_file_path, 'r')
75 except IOError as error:
[b45e75d]76 print('ERROR: Could not open the input file: {}'.format(error))
[6fbf790]77 sys.exit(3)
[ea6eba1]78
79 log_handler = loghandler.LogHandler()
[6fbf790]80 current_row = 1
81 last_row = None
82 for line in input_file:
[ea6eba1]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))
[6fbf790]86 if not errors_ignore:
87 input_file.close()
88 output_file.close()
89 sys.exit(4)
90 else:
[ea6eba1]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)
[b45e75d]94 output_file.write('{}\r\n'.format(str(output_string)))
[ea6eba1]95 current_row += 1
[6fbf790]96 output_file.close()
97 input_file.close()
98
[26f77a6]99def convertToGpx(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time):
[6fbf790]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)
[26f77a6]103 convertToNmea0183(input_file_path, nmea_without_timestamp_file_path, errors_ignore, checksums_fix, True)
[6fbf790]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
[df8c58a]108def main(argv):
[6fbf790]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
[ea6eba1]115
[df8c58a]116 formats = []
117 for file_format in Format:
118 formats.append(file_format.name)
119
[b45e75d]120 parser = argparse.ArgumentParser(description='Convert gnuboat logfiles into other formats')
[aaaaa2e]121 parser.add_argument('-f', '--format', dest='output_format', type=str,
[df8c58a]122 help='Format of the output file.', choices=formats, default='CSV')
[0c14082]123 parser.add_argument('-i', '--ignore-errors', dest='errors_ignore', action='store_false',
124 help='Ignore any errors reading the log file')
[26f77a6]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)')
[df8c58a]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)')
[6fbf790]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')
[df8c58a]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:
[b45e75d]142 print('ERROR: Invalid input format specified: {}'.format(arguments.output_format))
[df8c58a]143 sys.exit(1)
144
145 if arguments.errors_ignore is not None:
146 errors_ignore = arguments.errors_ignore
[6fbf790]147
[26f77a6]148 if arguments.checksums_fix is not None:
149 checksums_fix = arguments.checksums_fix
150
[6fbf790]151 if arguments.strip_time is not None:
152 strip_time = arguments.strip_time
[df8c58a]153
154 if arguments.input_file is None:
[b45e75d]155 print('ERROR: No input file specified')
[df8c58a]156 sys.exit(2)
[26f77a6]157 #elif not os.path.exists(arguments.input_file):
[b45e75d]158 print('ERROR: Specified input file does not exists: {}'.format(arguments.input_file))
[df8c58a]159 sys.exit(3)
160 else:
161 input_file_path = arguments.input_file
162
163 if arguments.output_file is None:
[b45e75d]164 print('ERROR: No output file specified')
[df8c58a]165 sys.exit(2)
166 elif not os.path.exists(os.path.dirname(arguments.output_file)):
[b45e75d]167 print('ERROR: Specified directory of output file does not exists: {}'.format(arguments.output_file))
[df8c58a]168 sys.exit(3)
169 else:
170 output_file_path = arguments.output_file
171
[6fbf790]172 if output_format == Format.CSV.value:
[26f77a6]173 convertToCsv(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time)
[6fbf790]174 elif output_format == Format.NMEA0183.value:
[26f77a6]175 convertToNmea0183(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time)
[6fbf790]176 elif output_format == Format.GPX.value:
[26f77a6]177 convertToGpx(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time)
[6fbf790]178 else:
[b45e75d]179 print('ERROR: Undefined output format!\n')
[6fbf790]180 sys.exit(1)
[df8c58a]181
182 sys.exit(0)
183
184if __name__ == "__main__":
185 main(sys.argv[1:])
Note: See TracBrowser for help on using the repository browser.