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

debian/bullseye
Last change on this file since 26d66d8 was ea6eba1, checked in by Joachim Langenbach <joachim.langenbach@…>, 8 years ago
  • Transfered all code related to parsing gnuboat log files into a new module datahandler
  • datahandler/loghandler.py: Code to write and parse gnuboat log files
  • datahandler/logdataset.py: Object, which holds a complete dataset from gnuboat log files
  • updated gnuboat-log-converter to use the loghandler module
  • updated gnuboat daemon to use the loghandler module
  • Property mode set to 100755
File size: 7.3 KB
RevLine 
[df8c58a]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
[6fbf790]26import tempfile
27import subprocess
[df8c58a]28
[ea6eba1]29from gnuboat.datahandler import loghandler, logdataset
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:
45 output_file = open(output_file_path, 'w', 0)
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()
60 log_handler.gnuboat_read(input_file_path, csv_callback.callback, checksums_fix, errors_ignore)
[6fbf790]61 output_file.close()
62
[26f77a6]63def convertToNmea0183(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time):
[6fbf790]64 try:
65 output_file = open(output_file_path, 'w', 0)
66 except IOError as error:
[b45e75d]67 print('ERROR: Could not open the output file: {}'.format(error))
[6fbf790]68 sys.exit(3)
69
70 # reading input file
71 try:
72 input_file = open(input_file_path, 'r')
73 except IOError as error:
[b45e75d]74 print('ERROR: Could not open the input file: {}'.format(error))
[6fbf790]75 sys.exit(3)
[ea6eba1]76
77 log_handler = loghandler.LogHandler()
[6fbf790]78 current_row = 1
79 last_row = None
80 for line in input_file:
[ea6eba1]81 nmea_sentence = log_handler.parse_nmea_sentence(line, checksums_fix)
82 if nmea_sentence is None:
83 print('INFO: Failed to parse nmea sentence ({}) at line {}'.format(line.strip(), current_row))
[6fbf790]84 if not errors_ignore:
85 input_file.close()
86 output_file.close()
87 sys.exit(4)
88 else:
[ea6eba1]89 output_string = str(nmea_sentence['nmea_sentence'])
90 if not strip_time and nmea_sentence['log_timestamp']:
91 output_string = '{}{}'.format(nmea_sentence['log_timestamp'], output_string)
[b45e75d]92 output_file.write('{}\r\n'.format(str(output_string)))
[ea6eba1]93 current_row += 1
[6fbf790]94 output_file.close()
95 input_file.close()
96
[26f77a6]97def convertToGpx(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time):
[6fbf790]98 # make sure, nmea input file, does not have timestamps in front of the nmea
99 # sentences
100 [nmea_without_timestamps_handle, nmea_without_timestamp_file_path] = tempfile.mkstemp(text=True)
[26f77a6]101 convertToNmea0183(input_file_path, nmea_without_timestamp_file_path, errors_ignore, checksums_fix, True)
[6fbf790]102
103 subprocess.call(['gpsbabel', '-i', 'nmea', '-f', nmea_without_timestamp_file_path, '-o', 'gpx', '-F', output_file_path])
104 os.remove(nmea_without_timestamp_file_path)
105
[df8c58a]106def main(argv):
[6fbf790]107 input_file_path = None
108 output_file_path = None
109 output_format_option = None
110 output_format = Format.CSV
111 errors_ignore = False
112 strip_time = False
[ea6eba1]113
[df8c58a]114 formats = []
115 for file_format in Format:
116 formats.append(file_format.name)
117
[b45e75d]118 parser = argparse.ArgumentParser(description='Convert gnuboat logfiles into other formats')
[df8c58a]119 parser.add_argument('-f', '--format', dest='output_format', metavar='output_format', type=str,
120 help='Format of the output file.', choices=formats, default='CSV')
[0c14082]121 parser.add_argument('-i', '--ignore-errors', dest='errors_ignore', action='store_false',
122 help='Ignore any errors reading the log file')
[26f77a6]123 parser.add_argument('-c', '--checksums-fix', dest='checksums_fix', action='store_true',
124 help='Ignore all checksums (and replace them with a new correct one, if needed)')
[df8c58a]125 parser.add_argument('input_file', metavar='input_file_path', type=str,
126 help='File to be converted (input)')
127 parser.add_argument('output_file', metavar='output_file_path', type=str,
128 help='Write the converted content to file (output)')
[6fbf790]129 parser.add_argument('--strip-time', dest='strip_time', action='store_true',
130 help='Removes timestamp in front of the nmea sentence, if it is there')
[df8c58a]131 arguments = parser.parse_args(argv)
132
133 if arguments.output_format is not None:
134 format_found = False
135 for file_format in Format:
136 if file_format.name == arguments.output_format:
137 output_format = file_format.value
138 format_found = True
139 if not format_found:
[b45e75d]140 print('ERROR: Invalid input format specified: {}'.format(arguments.output_format))
[df8c58a]141 sys.exit(1)
142
143 if arguments.errors_ignore is not None:
144 errors_ignore = arguments.errors_ignore
[6fbf790]145
[26f77a6]146 if arguments.checksums_fix is not None:
147 checksums_fix = arguments.checksums_fix
148
[6fbf790]149 if arguments.strip_time is not None:
150 strip_time = arguments.strip_time
[df8c58a]151
152 if arguments.input_file is None:
[b45e75d]153 print('ERROR: No input file specified')
[df8c58a]154 sys.exit(2)
[26f77a6]155 #elif not os.path.exists(arguments.input_file):
[b45e75d]156 print('ERROR: Specified input file does not exists: {}'.format(arguments.input_file))
[df8c58a]157 sys.exit(3)
158 else:
159 input_file_path = arguments.input_file
160
161 if arguments.output_file is None:
[b45e75d]162 print('ERROR: No output file specified')
[df8c58a]163 sys.exit(2)
164 elif not os.path.exists(os.path.dirname(arguments.output_file)):
[b45e75d]165 print('ERROR: Specified directory of output file does not exists: {}'.format(arguments.output_file))
[df8c58a]166 sys.exit(3)
167 else:
168 output_file_path = arguments.output_file
169
[6fbf790]170 if output_format == Format.CSV.value:
[26f77a6]171 convertToCsv(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time)
[6fbf790]172 elif output_format == Format.NMEA0183.value:
[26f77a6]173 convertToNmea0183(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time)
[6fbf790]174 elif output_format == Format.GPX.value:
[26f77a6]175 convertToGpx(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time)
[6fbf790]176 else:
[b45e75d]177 print('ERROR: Undefined output format!\n')
[6fbf790]178 sys.exit(1)
[df8c58a]179
180 sys.exit(0)
181
182if __name__ == "__main__":
183 main(sys.argv[1:])
Note: See TracBrowser for help on using the repository browser.