| [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 |
|
|---|
| 20 | import os
|
|---|
| 21 | import argparse
|
|---|
| 22 | import sys
|
|---|
| 23 | import pynmea2
|
|---|
| 24 | from enum import Enum
|
|---|
| 25 | import csv
|
|---|
| [6fbf790] | 26 | import re
|
|---|
| 27 | import tempfile
|
|---|
| 28 | import subprocess
|
|---|
| [df8c58a] | 29 |
|
|---|
| 30 | class Format(Enum):
|
|---|
| 31 | CSV = 1
|
|---|
| [6fbf790] | 32 | NMEA0183 = 2
|
|---|
| 33 | GPX = 3
|
|---|
| [df8c58a] | 34 |
|
|---|
| [6fbf790] | 35 | regex_nmea_sentence = re.compile(r"^([^\$!]{0,})([\$!]{1}[\w]{2}[\w]{3}[^\*]+\*[\da-zA-Z]+)$")
|
|---|
| [26f77a6] | 36 | regex_nmea_sentence_without_checksum = re.compile(r"^([^\$!]{0,})([\$!]{1}[\w]{2}[\w]{3}[^\*]+)\*[\da-zA-Z]+$")
|
|---|
| 37 | regex_nmea_position_latitude = re.compile(r"^([0-9]{2})([0-9]{2}\.[0-9]+)$")
|
|---|
| 38 | regex_nmea_position_longitude = re.compile(r"^([0-9]{3})([0-9]{2}\.[0-9]+)$")
|
|---|
| [df8c58a] | 39 |
|
|---|
| 40 | def 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:
|
|---|
| [23fa354] | 47 | print('INFO: Failed to convert value from line {} into numeric: {}\n Message: {}'.format(current_row, string, error))
|
|---|
| [df8c58a] | 48 | return 0
|
|---|
| 49 |
|
|---|
| [26f77a6] | 50 | def nmeaLatitudeToDecimalDegrees(nmea_value, current_row):
|
|---|
| 51 | global regex_nmea_position_latitude
|
|---|
| [6fbf790] | 52 |
|
|---|
| 53 | if toFloat(nmea_value, current_row) == 0:
|
|---|
| 54 | return 0
|
|---|
| 55 |
|
|---|
| [26f77a6] | 56 | matches = regex_nmea_position_latitude.match(nmea_value)
|
|---|
| [6fbf790] | 57 | if matches is None:
|
|---|
| [26f77a6] | 58 | print('INFO: Failed to convert latitude position value from line {} into decimal degrees: {}'.format(current_row, nmea_value))
|
|---|
| [6fbf790] | 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 |
|
|---|
| [26f77a6] | 64 | def 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 |
|
|---|
| 78 | def convertToCsv(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time):
|
|---|
| [6fbf790] | 79 | global regex_nmea_sentence
|
|---|
| [26f77a6] | 80 | global regex_nmea_sentence_without_checksum
|
|---|
| [6fbf790] | 81 |
|
|---|
| 82 | try:
|
|---|
| 83 | output_file = open(output_file_path, 'w', 0)
|
|---|
| 84 | except IOError as error:
|
|---|
| [b45e75d] | 85 | print('ERROR: Could not open the output file: {}'.format(error))
|
|---|
| [6fbf790] | 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:
|
|---|
| [b45e75d] | 100 | print('ERROR: Could not open the input file: {}'.format(error))
|
|---|
| [6fbf790] | 101 | sys.exit(3)
|
|---|
| 102 | current_row = 1
|
|---|
| 103 | last_row = None
|
|---|
| 104 | for line in input_file:
|
|---|
| 105 | line = line.strip()
|
|---|
| [26f77a6] | 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
|
|---|
| [6fbf790] | 112 | if matches is None:
|
|---|
| [b45e75d] | 113 | print('INFO: Failed to parse nmea sentence ({}) at line {}\n'.format(line, current_row))
|
|---|
| [6fbf790] | 114 | if not errors_ignore:
|
|---|
| 115 | input_file.close()
|
|---|
| 116 | output_file.close()
|
|---|
| 117 | sys.exit(4)
|
|---|
| 118 | else:
|
|---|
| [26f77a6] | 119 | nmea_sentence = pynmea2.parse(matches.group(2), check=pynmea_parse_check)
|
|---|
| [6fbf790] | 120 | if nmea_sentence.sentence_type == 'RMC':
|
|---|
| 121 | if last_row is not None:
|
|---|
| 122 | output_file_csv.writerow(last_row)
|
|---|
| [b45e75d] | 123 | last_row = {'datetime': '{} {}'.format(nmea_sentence.datestamp, nmea_sentence.timestamp),
|
|---|
| [6fbf790] | 124 | 'gps_status': nmea_sentence.status,
|
|---|
| [26f77a6] | 125 | 'latitude': nmeaLatitudeToDecimalDegrees(nmea_sentence.lat, current_row),
|
|---|
| [6fbf790] | 126 | 'latitude_direction': nmea_sentence.lat_dir,
|
|---|
| [26f77a6] | 127 | 'longitude': nmeaLongitudeToDecimalDegrees(nmea_sentence.lon, current_row),
|
|---|
| [6fbf790] | 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}
|
|---|
| [23fa354] | 133 | elif nmea_sentence.sentence_type == 'DPT' and last_row is not None:
|
|---|
| 134 | last_row['water_depth'] = toFloat(nmea_sentence.depth, current_row)
|
|---|
| [6fbf790] | 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 |
|
|---|
| [26f77a6] | 143 | def convertToNmea0183(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time):
|
|---|
| [6fbf790] | 144 | global regex_nmea_sentence
|
|---|
| [26f77a6] | 145 | global regex_nmea_sentence_without_checksum
|
|---|
| [6fbf790] | 146 |
|
|---|
| 147 | try:
|
|---|
| 148 | output_file = open(output_file_path, 'w', 0)
|
|---|
| 149 | except IOError as error:
|
|---|
| [b45e75d] | 150 | print('ERROR: Could not open the output file: {}'.format(error))
|
|---|
| [6fbf790] | 151 | sys.exit(3)
|
|---|
| 152 |
|
|---|
| 153 | # reading input file
|
|---|
| 154 | try:
|
|---|
| 155 | input_file = open(input_file_path, 'r')
|
|---|
| 156 | except IOError as error:
|
|---|
| [b45e75d] | 157 | print('ERROR: Could not open the input file: {}'.format(error))
|
|---|
| [6fbf790] | 158 | sys.exit(3)
|
|---|
| 159 | current_row = 1
|
|---|
| 160 | last_row = None
|
|---|
| 161 | for line in input_file:
|
|---|
| 162 | line = line.strip()
|
|---|
| [26f77a6] | 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
|
|---|
| [6fbf790] | 169 | if matches is None:
|
|---|
| [b45e75d] | 170 | print('INFO: Failed to parse nmea sentence ({}) at line {}\n'.format(line, current_row))
|
|---|
| [6fbf790] | 171 | if not errors_ignore:
|
|---|
| 172 | input_file.close()
|
|---|
| 173 | output_file.close()
|
|---|
| 174 | sys.exit(4)
|
|---|
| 175 | else:
|
|---|
| [26f77a6] | 176 | nmea_sentence = pynmea2.parse(matches.group(2), check=pynmea_parse_check)
|
|---|
| [6fbf790] | 177 | output_string = str(nmea_sentence)
|
|---|
| 178 | if not strip_time and matches.group(1):
|
|---|
| [b45e75d] | 179 | output_string = '{}{}'.format(matches.group(1), output_string)
|
|---|
| 180 | output_file.write('{}\r\n'.format(str(output_string)))
|
|---|
| [6fbf790] | 181 | output_file.close()
|
|---|
| 182 | input_file.close()
|
|---|
| 183 |
|
|---|
| [26f77a6] | 184 | def convertToGpx(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time):
|
|---|
| [6fbf790] | 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)
|
|---|
| [26f77a6] | 188 | convertToNmea0183(input_file_path, nmea_without_timestamp_file_path, errors_ignore, checksums_fix, True)
|
|---|
| [6fbf790] | 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 |
|
|---|
| [df8c58a] | 193 | def main(argv):
|
|---|
| [6fbf790] | 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 |
|
|---|
| [df8c58a] | 201 | formats = []
|
|---|
| 202 | for file_format in Format:
|
|---|
| 203 | formats.append(file_format.name)
|
|---|
| 204 |
|
|---|
| [b45e75d] | 205 | parser = argparse.ArgumentParser(description='Convert gnuboat logfiles into other formats')
|
|---|
| [df8c58a] | 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')
|
|---|
| [0c14082] | 208 | parser.add_argument('-i', '--ignore-errors', dest='errors_ignore', action='store_false',
|
|---|
| 209 | help='Ignore any errors reading the log file')
|
|---|
| [26f77a6] | 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)')
|
|---|
| [df8c58a] | 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)')
|
|---|
| [6fbf790] | 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')
|
|---|
| [df8c58a] | 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:
|
|---|
| [b45e75d] | 227 | print('ERROR: Invalid input format specified: {}'.format(arguments.output_format))
|
|---|
| [df8c58a] | 228 | sys.exit(1)
|
|---|
| 229 |
|
|---|
| 230 | if arguments.errors_ignore is not None:
|
|---|
| 231 | errors_ignore = arguments.errors_ignore
|
|---|
| [6fbf790] | 232 |
|
|---|
| [26f77a6] | 233 | if arguments.checksums_fix is not None:
|
|---|
| 234 | checksums_fix = arguments.checksums_fix
|
|---|
| 235 |
|
|---|
| [6fbf790] | 236 | if arguments.strip_time is not None:
|
|---|
| 237 | strip_time = arguments.strip_time
|
|---|
| [df8c58a] | 238 |
|
|---|
| 239 | if arguments.input_file is None:
|
|---|
| [b45e75d] | 240 | print('ERROR: No input file specified')
|
|---|
| [df8c58a] | 241 | sys.exit(2)
|
|---|
| [26f77a6] | 242 | #elif not os.path.exists(arguments.input_file):
|
|---|
| [b45e75d] | 243 | print('ERROR: Specified input file does not exists: {}'.format(arguments.input_file))
|
|---|
| [df8c58a] | 244 | sys.exit(3)
|
|---|
| 245 | else:
|
|---|
| 246 | input_file_path = arguments.input_file
|
|---|
| 247 |
|
|---|
| 248 | if arguments.output_file is None:
|
|---|
| [b45e75d] | 249 | print('ERROR: No output file specified')
|
|---|
| [df8c58a] | 250 | sys.exit(2)
|
|---|
| 251 | elif not os.path.exists(os.path.dirname(arguments.output_file)):
|
|---|
| [b45e75d] | 252 | print('ERROR: Specified directory of output file does not exists: {}'.format(arguments.output_file))
|
|---|
| [df8c58a] | 253 | sys.exit(3)
|
|---|
| 254 | else:
|
|---|
| 255 | output_file_path = arguments.output_file
|
|---|
| 256 |
|
|---|
| [6fbf790] | 257 | if output_format == Format.CSV.value:
|
|---|
| [26f77a6] | 258 | convertToCsv(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time)
|
|---|
| [6fbf790] | 259 | elif output_format == Format.NMEA0183.value:
|
|---|
| [26f77a6] | 260 | convertToNmea0183(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time)
|
|---|
| [6fbf790] | 261 | elif output_format == Format.GPX.value:
|
|---|
| [26f77a6] | 262 | convertToGpx(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time)
|
|---|
| [6fbf790] | 263 | else:
|
|---|
| [b45e75d] | 264 | print('ERROR: Undefined output format!\n')
|
|---|
| [6fbf790] | 265 | sys.exit(1)
|
|---|
| [df8c58a] | 266 |
|
|---|
| 267 | sys.exit(0)
|
|---|
| 268 |
|
|---|
| 269 | if __name__ == "__main__":
|
|---|
| 270 | main(sys.argv[1:])
|
|---|