Ignore:
Timestamp:
Apr 11, 2020, 4:46:15 PM (7 years ago)
Author:
Joachim Langenbach <joachim.langenbach@…>
Branches:
debian/bullseye, master
Children:
3db3d13
Parents:
da2be70
Message:
  • Added yapf style config (src/python-style.yapf)
    • Updated all files to the yapf formatted version
File:
1 edited

Legend:

Unmodified
Added
Removed
  • src/common/bin/gnuboat-log-converter

    rda2be70 r7be94aa  
    2929from gnuboat_common.datahandler import loghandler, logdataset
    3030
     31
    3132class Format(Enum):
    3233    CSV = 1
    … …  
    3435    GPX = 3
    3536
     37
    3638class CsvCallback:
    3739    def __init__(self, output_file):
    … …  
    4143        self._output_file.writerow(dataset.to_dict())
    4244
    43 def convertToCsv(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time):
     45
     46def convertToCsv(
     47    input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time
     48):
    4449    try:
    4550        output_file = open(output_file_path, 'w')
    … …  
    4954
    5055    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    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    )
    5668    output_file_csv.writeheader()
    5769
    5870    csv_callback = CsvCallback(output_file_csv)
    5971    log_handler = loghandler.LogHandler()
    60     result = log_handler.gnuboat_read_file(input_file_path, csv_callback.callback, checksums_fix, errors_ignore)
     72    result = log_handler.gnuboat_read_file(
     73        input_file_path, csv_callback.callback, checksums_fix, errors_ignore
     74    )
    6175    if result.messages():
    6276        print('\n'.join(result.errors()))
    6377    output_file.close()
    6478
    65 def convertToNmea0183(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time):
     79
     80def convertToNmea0183(
     81    input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time
     82):
    6683    try:
    6784        output_file = open(output_file_path, 'w')
    … …  
    7693        print('ERROR: Could not open the input file: {}'.format(error))
    7794        sys.exit(3)
    78        
     95
    7996    log_handler = loghandler.LogHandler()
    8097    current_row = 1
    … …  
    83100        nmea_sentence = log_handler.parse_nmea_sentence(line, checksums_fix)
    84101        if nmea_sentence is None:
    85             print('INFO: Failed to parse nmea sentence ({}) at line {}'.format(line.strip(), current_row))
     102            print(
     103                'INFO: Failed to parse nmea sentence ({}) at line {}'.format(
     104                    line.strip(), current_row
     105                )
     106            )
    86107            if not errors_ignore:
    87108                input_file.close()
    … …  
    91112            output_string = str(nmea_sentence['nmea_sentence'])
    92113            if not strip_time and nmea_sentence['log_timestamp']:
    93                 output_string = '{}{}'.format(nmea_sentence['log_timestamp'], output_string)
     114                output_string = '{}{}'.format(
     115                    nmea_sentence['log_timestamp'], output_string
     116                )
    94117            output_file.write('{}\r\n'.format(str(output_string)))
    95118        current_row += 1
    96119    output_file.close()
    97120    input_file.close()
    98    
    99 def convertToGpx(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time):
     121
     122
     123def convertToGpx(
     124    input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time
     125):
    100126    # make sure, nmea input file, does not have timestamps in front of the nmea
    101127    # 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])
     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    ])
    106139    os.remove(nmea_without_timestamp_file_path)
     140
    107141
    108142def main(argv):
    … …  
    116150    formats = []
    117151    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')
     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    )
    133199    arguments = parser.parse_args(argv)
    134    
     200
    135201    if arguments.output_format is not None:
    136202        format_found = False
    137203        for file_format in Format:
    138204            if file_format.name == arguments.output_format:
    139                output_format = file_format.value
    140                format_found = True
     205                output_format = file_format.value
     206                format_found = True
    141207        if not format_found:
    142             print('ERROR: Invalid input format specified: {}'.format(arguments.output_format))
     208            print(
     209                'ERROR: Invalid input format specified: {}'.format(
     210                    arguments.output_format
     211                )
     212            )
    143213            sys.exit(1)
    144214
    145215    if arguments.errors_ignore is not None:
    146216        errors_ignore = arguments.errors_ignore
    147        
     217
    148218    if arguments.checksums_fix is not None:
    149219        checksums_fix = arguments.checksums_fix
    150        
     220
    151221    if arguments.strip_time is not None:
    152222        strip_time = arguments.strip_time
    153            
     223
    154224    if arguments.input_file is None:
    155225        print('ERROR: No input file specified')
    156226        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))
     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        )
    159233        sys.exit(3)
    160234    else:
    161235        input_file_path = arguments.input_file
    162        
     236
    163237    if arguments.output_file is None:
    164238        print('ERROR: No output file specified')
    165239        sys.exit(2)
    166240    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))
     241        print(
     242            'ERROR: Specified directory of output file does not exists: {}'.
     243            format(arguments.output_file)
     244        )
    168245        sys.exit(3)
    169246    else:
    170247        output_file_path = arguments.output_file
    171248
    172     if output_format == Format.CSV.value:
    173         convertToCsv(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time)
     249    if output_format == Format.CSV.value:
     250        convertToCsv(
     251            input_file_path, output_file_path, errors_ignore, checksums_fix,
     252            strip_time
     253        )
    174254    elif output_format == Format.NMEA0183.value:
    175         convertToNmea0183(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time)
     255        convertToNmea0183(
     256            input_file_path, output_file_path, errors_ignore, checksums_fix,
     257            strip_time
     258        )
    176259    elif output_format == Format.GPX.value:
    177         convertToGpx(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time)
     260        convertToGpx(
     261            input_file_path, output_file_path, errors_ignore, checksums_fix,
     262            strip_time
     263        )
    178264    else:
    179265        print('ERROR: Undefined output format!\n')
    … …  
    182268    sys.exit(0)
    183269
     270
    184271if __name__ == "__main__":
    185272    main(sys.argv[1:])
Note: See TracChangeset for help on using the changeset viewer.