Changeset 7be94aa for src/common/bin


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
Location:
src/common/bin
Files:
3 edited

Legend:

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

    rda2be70 r7be94aa  
    4040# -999 is a workaround, as long gdal python api does not handle addAlpha
    4141colors = {
    42         -999: "255 255 255",
    43         0: "0 0 139",
    44         2: "30 144 255",
    45         6: "173 216 230",
    46         10: "240 248 255"
     42    -999: "255 255 255",
     43    0: "0 0 139",
     44    2: "30 144 255",
     45    6: "173 216 230",
     46    10: "240 248 255"
    4747}
    4848input_epsg = 'EPSG:4326'
    4949target_nodata_value = -999.0
    5050target_zoomlevel = 19
    51 density_min = 10 # number of points per density_base squaremetres needed to set a value different from nodata
    52 density_base = 100 # squaremetre used as base for density_min
     51density_min = 10  # number of points per density_base squaremetres needed to set a value different from nodata
     52density_base = 100  # squaremetre used as base for density_min
     53
    5354
    5455class CsvCallback:
    55         def __init__(self, output_file):
    56                 self._output_file = output_file
    57                 self._stage = None
    58                 self._resultsets = 0
    59                
    60         def count(self):
    61                 return self._resultsets
    62                
    63         def stage_set(self, stage):
    64                 self._stage = stage
    65 
    66         def callback(self, dataset):
    67                 if self._stage is None:
    68                         print("No stage set! Skipping dataset...")
    69                         return
    70                 # only add points with a water depth set
    71                 if dataset.water_depth() is None:
    72                         return
    73                 water_depth = dataset.water_depth() - self._stage
    74                 self._output_file.writerow({"lon": dataset.longitude(), "lat": dataset.latitude(), "water_depth": water_depth})
    75                 self._resultsets += 1
     56    def __init__(self, output_file):
     57        self._output_file = output_file
     58        self._stage = None
     59        self._resultsets = 0
     60
     61    def count(self):
     62        return self._resultsets
     63
     64    def stage_set(self, stage):
     65        self._stage = stage
     66
     67    def callback(self, dataset):
     68        if self._stage is None:
     69            print("No stage set! Skipping dataset...")
     70            return
     71        # only add points with a water depth set
     72        if dataset.water_depth() is None:
     73            return
     74        water_depth = dataset.water_depth() - self._stage
     75        self._output_file.writerow({
     76            "lon": dataset.longitude(),
     77            "lat": dataset.latitude(),
     78            "water_depth": water_depth
     79        })
     80        self._resultsets += 1
     81
    7682
    7783def tile_width(zoomlevel):
    78         tile_size = 256
    79         tiles = math.sqrt(tile_number(zoomlevel))
    80         return {"tile_size": tile_size, "longitude": 360.0/tiles, "latitude": 180.0/tiles}
     84    tile_size = 256
     85    tiles = math.sqrt(tile_number(zoomlevel))
     86    return {
     87        "tile_size": tile_size,
     88        "longitude": 360.0 / tiles,
     89        "latitude": 180.0 / tiles
     90    }
     91
    8192
    8293def tile_number(zoomlevel):
    83         return 2**(zoomlevel*2)
     94    return 2**(zoomlevel * 2)
     95
    8496
    8597def main(argv):
    86         global color, input_epsg, target_nodata_value, target_zoomlevel, density_min, density_base
    87 
    88         input_file_path = None
    89         output_directory = None
    90         statistics = False
    91         tile_sizes = [256]
    92         skip_empty = True
    93        
    94         gdal.UseExceptions()
    95 
    96         parser = argparse.ArgumentParser(description='Generates the digital terrain model from gnuboat logfiles')
    97         parser.add_argument('input_file', metavar='input_file_path', type=str,
    98                                                 help='JSON file with logfiles and correction data to be processed')
    99         parser.add_argument('output_directory', metavar='output_directory', type=str,
    100                                                 help='Write the Digital Terrain Model into this directory (output)')
    101         parser.add_argument('-v', '--verbose', dest='statistics', action='store_true',
    102                                                 help='Print some statistics of the input and result datasets')
    103         parser.add_argument('-p', '--points-min', dest='points_min', type=int, default=density_min,
    104                                                 help='Minimum points per {} squaremetre is needed to create a valid depth information'.format(density_base))
    105         parser.add_argument('-z', '--zoomlevels', dest='zoom_range', nargs=2, default=[10, 19], type=int,
    106                                                 help='Creates tiles for the specified range of zoomlevels')
    107         parser.add_argument('--high-res', dest='high_res', action='store_true',
    108                                                 help='Creates tiles with 512 pixel per tile additionally to the 256 pixel per tile tiles')
    109         parser.add_argument('-m', '--raster_file_max', dest='raster_file_size_max', default=1024, type=int,
    110                                                 help='Maximum size of temporary raster Tifs for tile generation in MB')
    111         parser.add_argument('-k', '--keep-empty', dest='skip_empty', action='store_false',
    112                                                 help='Do not skip empty tiles (=move only one empty tile into place), when moving tiles into target directory')
    113         arguments = parser.parse_args(argv)
    114 
    115         if arguments.input_file is None:
    116                 print('ERROR: No input file specified')
    117                 sys.exit(2)
    118         elif not os.path.exists(arguments.input_file):
    119                 print('ERROR: Specified input file does not exists: {}'.format(arguments.input_file))
    120                 sys.exit(3)
    121         else:
    122                 input_file_path = arguments.input_file
    123                
    124         if arguments.output_directory is None:
    125                 print('ERROR: No output file specified')
    126                 sys.exit(2)
    127         else:
    128                 output_directory = arguments.output_directory
    129        
    130         if arguments.statistics is not None:
    131                 statistics = arguments.statistics
    132                
    133         if arguments.points_min is not None:
    134                 density_min = arguments.points_min
    135        
    136         if arguments.zoom_range is not None:
    137                 zoom_range = arguments.zoom_range
    138        
    139         if arguments.high_res is not None and arguments.high_res:
    140                 tile_sizes.append(512)
    141                
    142         if arguments.raster_file_size_max is not None:
    143                 raster_file_size_max = arguments.raster_file_size_max
    144                
    145         if arguments.skip_empty is not None and not arguments.skip_empty:
    146                 skip_empty = arguments.skip_empty
    147                
    148         # create temporary directory
    149         temp_directory = tempfile.mkdtemp(prefix='gnuboat-log-analyser')
    150 
    151         with open(input_file_path, 'r') as input_file:
    152                 logfiles = json.load(input_file)
    153        
    154         source_data_layer = "tmp_corrected_joined_points"
    155         corrected_joined_point_cloud_file_path = os.path.join(temp_directory, "{}.csv".format(source_data_layer))
    156         try:
    157                 output_file = open(corrected_joined_point_cloud_file_path, 'w')
    158         except IOError as error:
    159                 print('ERROR: Could not open the output file for the corrected, joined point cloud: {}'.format(error))
    160                 sys.exit(4)
    161         output_file_csv = None
    162         fields = ['lon', 'lat', 'water_depth']
    163         output_file_csv = csv.DictWriter(output_file, delimiter=',', quotechar='"',
    164                                                                                 fieldnames=fields)
    165         output_file_csv.writeheader()
    166         csv_callback = CsvCallback(output_file_csv)
    167         log_handler = loghandler.LogHandler()
    168 
    169         print("Correcting and combining {} log files".format(len(logfiles)))
    170         for logfile in logfiles:
    171                 gaugeHeight = logfile["gaugeHeight"]
    172                 referenceWaterLevelGaugeHeight = logfile["referenceWaterLevelGaugeHeight"]
    173                 log_file_path = logfile["file"]
    174                
    175                 # building the log file path
    176                 if not os.path.isabs(log_file_path):
    177                         log_file_path = "{}/{}".format(os.path.dirname(input_file_path), log_file_path)
    178                 # check stage
    179                 try:
    180                         gaugeHeight = float(gaugeHeight)
    181                 except ValueError:
    182                         print("gaugeHeight is not convertible into float for file {}. Skipping the file".format(log_file_path))
    183                         continue
    184                 try:
    185                         referenceWaterLevelGaugeHeight = float(referenceWaterLevelGaugeHeight)
    186                 except ValueError:
    187                         print("referenceWaterLevelGaugeHeight is not convertible into float for file {}. Skipping the file".format(log_file_path))
    188                         continue
    189                 # parse, correct and append log file
    190                 difference = referenceWaterLevelGaugeHeight - gaugeHeight
    191                 csv_callback.stage_set(difference)
    192                 result = log_handler.gnuboat_read_file(log_file_path, csv_callback.callback)
    193                 if result.messages():
    194                         print('\n'.join(result.errors()))
    195                 if not result.success():
    196                         sys.exit(5)
    197                
    198                 print("  {} correct and joined with difference {:.3f}m".format(log_file_path, difference))
    199         output_file.close()
    200         print ('  Processed {} points'.format(csv_callback.count()))
    201 
    202         # create ogr file info
    203         source_xml_file = os.path.join(temp_directory, '{}.vrt'.format(source_data_layer))
    204         try:
    205                 output_file = open(source_xml_file, 'wb')
    206         except IOError as error:
    207                 print('ERROR: Could not open the output file for the ogr data source description: {}'.format(error))
    208                 sys.exit(4)
    209         xml_data_source = ET.Element("OGRVRTDataSource")
    210         xml_layer = ET.SubElement(xml_data_source, "OGRVRTLayer", {"name": source_data_layer})
    211         xml_source = ET.SubElement(xml_layer, "SrcDataSource", {'relativeToVRT': "1"})
    212         xml_source.text = corrected_joined_point_cloud_file_path
    213         xml_geometry_type = ET.SubElement(xml_layer, "GeometryType")
    214         xml_geometry_type.text = "wkbPoint"
    215         xml_layer_system = ET.SubElement(xml_layer, "LayerSRS")
    216         xml_layer_system.text = input_epsg
    217         xml_geometry_field = ET.SubElement(xml_layer, "GeometryField", {"encoding": "PointFromColumns", "x": "lon", "y": "lat", "z": "water_depth"})
    218         xml_tree = ET.ElementTree(xml_data_source)
    219         xml_tree.write(output_file, encoding="UTF-8", xml_declaration=False)
    220         output_file.close()
    221        
    222         # create csvt file
    223         try:
    224                 output_file_csvt = open(os.path.join(temp_directory, '{}.csvt'.format(source_data_layer)), 'w')
    225         except IOError as error:
    226                 print('ERROR: Could not open the output file for the ogr data source description: {}'.format(error))
    227                 sys.exit(6)
    228         output_file_csvt.write('"Real","Real","Real"')
    229         output_file_csvt.close()
    230                
    231         # preparing output_directory
    232         if os.path.exists(output_directory):
    233                 for root, dirs, files in os.walk(output_directory):
    234                         for f in files:
    235                                 os.unlink(os.path.join(root, f))
    236                         for d in dirs:
    237                                 shutil.rmtree(os.path.join(root, d))
    238         else:
    239                 os.makedirs(output_directory)
    240        
    241         # get source boundaries (Envelope / Extent)
    242         datasource = ogr.Open(source_xml_file)
    243         if datasource is None:
    244                 raise FileNotFoundError('Could not open input file {}'.format(source_xml_file))
    245         if datasource.GetLayerCount() < 1:
    246                 raise ReferenceError('No layers in input file')
    247         source_layer = datasource.GetLayerByIndex(0)
    248         source_x_min, source_x_max, source_y_min, source_y_max = source_layer.GetExtent()
    249 
    250         tilegen = tilegenerator.TileGenerator(tile_sizes = tile_sizes, densities = [density_min], density_base = density_base, debug=statistics)
    251         slices = tilegen.slices(source_xml_file, tilegenerator.ZoomRange(zoom_range[0], zoom_range[1]), raster_file_size_max = raster_file_size_max * 1024 * 1024 * 8)
    252         slices_count = len(slices)
    253         print('Generated {} slices for rastering'.format(slices_count))
    254        
    255         t1_start = process_time()
    256         print('Rastering slices and generating tiles')
    257         with progressbar.ProgressBar(max_value=slices_count, redirect_stdout=True) as bar:
    258                 i = 1
    259                 for tile_slice in slices:
    260                         if statistics:
    261                                 print(' Generating tiles for slice {} in {}'.format(i, temp_directory))
    262                         result_paths = tilegen.run(source_xml_file, temp_directory, tile_slice)
    263                         for path in result_paths:
    264                                 tilegen.move_tiles_in_place(path.path, os.path.join(output_directory, path.prefixes['density'], path.prefixes['tile_size']), skip_empty = skip_empty)
    265                         bar.update(i)
    266                         i += 1
    267         t1_stop = process_time()
    268         print('  Tooks {:.2f} hours'.format((t1_stop - t1_start) / 60 / 60))
    269 
    270         # delete temporary directory
    271         shutil.rmtree(temp_directory)
    272        
    273         print('Generated tiles in {}'.format(output_directory))
    274 
    275         sys.exit(0)
     98    global color, input_epsg, target_nodata_value, target_zoomlevel, density_min, density_base
     99
     100    input_file_path = None
     101    output_directory = None
     102    statistics = False
     103    tile_sizes = [256]
     104    skip_empty = True
     105
     106    gdal.UseExceptions()
     107
     108    parser = argparse.ArgumentParser(
     109        description='Generates the digital terrain model from gnuboat logfiles'
     110    )
     111    parser.add_argument(
     112        'input_file',
     113        metavar='input_file_path',
     114        type=str,
     115        help='JSON file with logfiles and correction data to be processed'
     116    )
     117    parser.add_argument(
     118        'output_directory',
     119        metavar='output_directory',
     120        type=str,
     121        help='Write the Digital Terrain Model into this directory (output)'
     122    )
     123    parser.add_argument(
     124        '-v',
     125        '--verbose',
     126        dest='statistics',
     127        action='store_true',
     128        help='Print some statistics of the input and result datasets'
     129    )
     130    parser.add_argument(
     131        '-p',
     132        '--points-min',
     133        dest='points_min',
     134        type=int,
     135        default=density_min,
     136        help=
     137        'Minimum points per {} squaremetre is needed to create a valid depth information'
     138        .format(density_base)
     139    )
     140    parser.add_argument(
     141        '-z',
     142        '--zoomlevels',
     143        dest='zoom_range',
     144        nargs=2,
     145        default=[10, 19],
     146        type=int,
     147        help='Creates tiles for the specified range of zoomlevels'
     148    )
     149    parser.add_argument(
     150        '--high-res',
     151        dest='high_res',
     152        action='store_true',
     153        help=
     154        'Creates tiles with 512 pixel per tile additionally to the 256 pixel per tile tiles'
     155    )
     156    parser.add_argument(
     157        '-m',
     158        '--raster_file_max',
     159        dest='raster_file_size_max',
     160        default=1024,
     161        type=int,
     162        help='Maximum size of temporary raster Tifs for tile generation in MB'
     163    )
     164    parser.add_argument(
     165        '-k',
     166        '--keep-empty',
     167        dest='skip_empty',
     168        action='store_false',
     169        help=
     170        'Do not skip empty tiles (=move only one empty tile into place), when moving tiles into target directory'
     171    )
     172    arguments = parser.parse_args(argv)
     173
     174    if arguments.input_file is None:
     175        print('ERROR: No input file specified')
     176        sys.exit(2)
     177    elif not os.path.exists(arguments.input_file):
     178        print(
     179            'ERROR: Specified input file does not exists: {}'.format(
     180                arguments.input_file
     181            )
     182        )
     183        sys.exit(3)
     184    else:
     185        input_file_path = arguments.input_file
     186
     187    if arguments.output_directory is None:
     188        print('ERROR: No output file specified')
     189        sys.exit(2)
     190    else:
     191        output_directory = arguments.output_directory
     192
     193    if arguments.statistics is not None:
     194        statistics = arguments.statistics
     195
     196    if arguments.points_min is not None:
     197        density_min = arguments.points_min
     198
     199    if arguments.zoom_range is not None:
     200        zoom_range = arguments.zoom_range
     201
     202    if arguments.high_res is not None and arguments.high_res:
     203        tile_sizes.append(512)
     204
     205    if arguments.raster_file_size_max is not None:
     206        raster_file_size_max = arguments.raster_file_size_max
     207
     208    if arguments.skip_empty is not None and not arguments.skip_empty:
     209        skip_empty = arguments.skip_empty
     210
     211    # create temporary directory
     212    temp_directory = tempfile.mkdtemp(prefix='gnuboat-log-analyser')
     213
     214    with open(input_file_path, 'r') as input_file:
     215        logfiles = json.load(input_file)
     216
     217    source_data_layer = "tmp_corrected_joined_points"
     218    corrected_joined_point_cloud_file_path = os.path.join(
     219        temp_directory, "{}.csv".format(source_data_layer)
     220    )
     221    try:
     222        output_file = open(corrected_joined_point_cloud_file_path, 'w')
     223    except IOError as error:
     224        print(
     225            'ERROR: Could not open the output file for the corrected, joined point cloud: {}'
     226            .format(error)
     227        )
     228        sys.exit(4)
     229    output_file_csv = None
     230    fields = ['lon', 'lat', 'water_depth']
     231    output_file_csv = csv.DictWriter(
     232        output_file, delimiter=',', quotechar='"', fieldnames=fields
     233    )
     234    output_file_csv.writeheader()
     235    csv_callback = CsvCallback(output_file_csv)
     236    log_handler = loghandler.LogHandler()
     237
     238    print("Correcting and combining {} log files".format(len(logfiles)))
     239    for logfile in logfiles:
     240        gaugeHeight = logfile["gaugeHeight"]
     241        referenceWaterLevelGaugeHeight = logfile[
     242            "referenceWaterLevelGaugeHeight"]
     243        log_file_path = logfile["file"]
     244
     245        # building the log file path
     246        if not os.path.isabs(log_file_path):
     247            log_file_path = "{}/{}".format(
     248                os.path.dirname(input_file_path), log_file_path
     249            )
     250        # check stage
     251        try:
     252            gaugeHeight = float(gaugeHeight)
     253        except ValueError:
     254            print(
     255                "gaugeHeight is not convertible into float for file {}. Skipping the file"
     256                .format(log_file_path)
     257            )
     258            continue
     259        try:
     260            referenceWaterLevelGaugeHeight = float(
     261                referenceWaterLevelGaugeHeight
     262            )
     263        except ValueError:
     264            print(
     265                "referenceWaterLevelGaugeHeight is not convertible into float for file {}. Skipping the file"
     266                .format(log_file_path)
     267            )
     268            continue
     269        # parse, correct and append log file
     270        difference = referenceWaterLevelGaugeHeight - gaugeHeight
     271        csv_callback.stage_set(difference)
     272        result = log_handler.gnuboat_read_file(
     273            log_file_path, csv_callback.callback
     274        )
     275        if result.messages():
     276            print('\n'.join(result.errors()))
     277        if not result.success():
     278            sys.exit(5)
     279
     280        print(
     281            "  {} correct and joined with difference {:.3f}m".format(
     282                log_file_path, difference
     283            )
     284        )
     285    output_file.close()
     286    print('  Processed {} points'.format(csv_callback.count()))
     287
     288    # create ogr file info
     289    source_xml_file = os.path.join(
     290        temp_directory, '{}.vrt'.format(source_data_layer)
     291    )
     292    try:
     293        output_file = open(source_xml_file, 'wb')
     294    except IOError as error:
     295        print(
     296            'ERROR: Could not open the output file for the ogr data source description: {}'
     297            .format(error)
     298        )
     299        sys.exit(4)
     300    xml_data_source = ET.Element("OGRVRTDataSource")
     301    xml_layer = ET.SubElement(
     302        xml_data_source, "OGRVRTLayer", {"name": source_data_layer}
     303    )
     304    xml_source = ET.SubElement(
     305        xml_layer, "SrcDataSource", {'relativeToVRT': "1"}
     306    )
     307    xml_source.text = corrected_joined_point_cloud_file_path
     308    xml_geometry_type = ET.SubElement(xml_layer, "GeometryType")
     309    xml_geometry_type.text = "wkbPoint"
     310    xml_layer_system = ET.SubElement(xml_layer, "LayerSRS")
     311    xml_layer_system.text = input_epsg
     312    xml_geometry_field = ET.SubElement(
     313        xml_layer, "GeometryField", {
     314            "encoding": "PointFromColumns",
     315            "x": "lon",
     316            "y": "lat",
     317            "z": "water_depth"
     318        }
     319    )
     320    xml_tree = ET.ElementTree(xml_data_source)
     321    xml_tree.write(output_file, encoding="UTF-8", xml_declaration=False)
     322    output_file.close()
     323
     324    # create csvt file
     325    try:
     326        output_file_csvt = open(
     327            os.path.join(temp_directory, '{}.csvt'.format(source_data_layer)),
     328            'w'
     329        )
     330    except IOError as error:
     331        print(
     332            'ERROR: Could not open the output file for the ogr data source description: {}'
     333            .format(error)
     334        )
     335        sys.exit(6)
     336    output_file_csvt.write('"Real","Real","Real"')
     337    output_file_csvt.close()
     338
     339    # preparing output_directory
     340    if os.path.exists(output_directory):
     341        for root, dirs, files in os.walk(output_directory):
     342            for f in files:
     343                os.unlink(os.path.join(root, f))
     344            for d in dirs:
     345                shutil.rmtree(os.path.join(root, d))
     346    else:
     347        os.makedirs(output_directory)
     348
     349    # get source boundaries (Envelope / Extent)
     350    datasource = ogr.Open(source_xml_file)
     351    if datasource is None:
     352        raise FileNotFoundError(
     353            'Could not open input file {}'.format(source_xml_file)
     354        )
     355    if datasource.GetLayerCount() < 1:
     356        raise ReferenceError('No layers in input file')
     357    source_layer = datasource.GetLayerByIndex(0)
     358    source_x_min, source_x_max, source_y_min, source_y_max = source_layer.GetExtent(
     359    )
     360
     361    tilegen = tilegenerator.TileGenerator(
     362        tile_sizes=tile_sizes,
     363        densities=[density_min],
     364        density_base=density_base,
     365        debug=statistics
     366    )
     367    slices = tilegen.slices(
     368        source_xml_file,
     369        tilegenerator.ZoomRange(zoom_range[0], zoom_range[1]),
     370        raster_file_size_max=raster_file_size_max * 1024 * 1024 * 8
     371    )
     372    slices_count = len(slices)
     373    print('Generated {} slices for rastering'.format(slices_count))
     374
     375    t1_start = process_time()
     376    print('Rastering slices and generating tiles')
     377    with progressbar.ProgressBar(
     378        max_value=slices_count, redirect_stdout=True
     379    ) as bar:
     380        i = 1
     381        for tile_slice in slices:
     382            if statistics:
     383                print(
     384                    ' Generating tiles for slice {} in {}'.format(
     385                        i, temp_directory
     386                    )
     387                )
     388            result_paths = tilegen.run(
     389                source_xml_file, temp_directory, tile_slice
     390            )
     391            for path in result_paths:
     392                tilegen.move_tiles_in_place(
     393                    path.path,
     394                    os.path.join(
     395                        output_directory, path.prefixes['density'],
     396                        path.prefixes['tile_size']
     397                    ),
     398                    skip_empty=skip_empty
     399                )
     400            bar.update(i)
     401            i += 1
     402    t1_stop = process_time()
     403    print('  Tooks {:.2f} hours'.format((t1_stop - t1_start) / 60 / 60))
     404
     405    # delete temporary directory
     406    shutil.rmtree(temp_directory)
     407
     408    print('Generated tiles in {}'.format(output_directory))
     409
     410    sys.exit(0)
     411
    276412
    277413if __name__ == "__main__":
    278         main(sys.argv[1:])
     414    main(sys.argv[1:])
  • 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:])
  • src/common/bin/gnuboat-log-uploader

    rda2be70 r7be94aa  
    2424import argparse
    2525
     26
    2627class Log:
    27         """
     28    """
    2829                Workaround for @dataclass, until python 3.7 is available in main distros
    2930        """
    30         def __init__(self, water_id, device_id, gauge_id, gauge_height, comment, logfile):
    31                 self.water_id = water_id
    32                 self.device_id = device_id
    33                 self.gauge_id = gauge_id
    34                 self.gauge_height = gauge_height
    35                 self.comment = comment
    36                 self.logfile = logfile
    37                
    38         def log_creation(self):
    39                 return {
    40                         'water': self.water_id,
    41                         'device': self.device_id,
    42                         'gauge': self.gauge_id,
    43                         'gaugeHeight': self.gauge_height,
    44                         'comment': self.comment
    45                 }
     31    def __init__(
     32        self, water_id, device_id, gauge_id, gauge_height, comment, logfile
     33    ):
     34        self.water_id = water_id
     35        self.device_id = device_id
     36        self.gauge_id = gauge_id
     37        self.gauge_height = gauge_height
     38        self.comment = comment
     39        self.logfile = logfile
     40
     41    def log_creation(self):
     42        return {
     43            'water': self.water_id,
     44            'device': self.device_id,
     45            'gauge': self.gauge_id,
     46            'gaugeHeight': self.gauge_height,
     47            'comment': self.comment
     48        }
     49
    4650
    4751def to_int(value_string):
    48         try:
    49                 return int(value_string)
    50         except:
    51                 return None
     52    try:
     53        return int(value_string)
     54    except:
     55        return None
     56
    5257
    5358def to_float(value_string):
    54         try:
    55                 return float(value_string)
    56         except:
    57                 return None
     59    try:
     60        return float(value_string)
     61    except:
     62        return None
     63
    5864
    5965def header(api_key):
    60         return {
    61                 'X-API-KEY': api_key
    62         #       'Content-type': 'multipart/form-data'
    63         }
     66    return {
     67        'X-API-KEY': api_key
     68        #       'Content-type': 'multipart/form-data'
     69    }
     70
    6471
    6572def create_log(log, url, api_key):
    66         response = requests.post(url,
    67                 json = log.log_creation(),
    68                 headers = header(api_key)
    69         )
    70        
    71         if response.status_code != 200:
    72                 print('ERROR: Could not create LogMetaData for logfile {}'.format(log.logfile))
    73                 print('  Response status code: {}'.format(response.status_code))
    74                 print('  Response:             \n{}'.format(response.text))
    75                 print('  Request headers:      {}'.format(response.request.headers))
    76                 print('  Request body:         {}'.format(response.request.body))
    77                 sys.exit(5)
    78                
    79         data = response.json()
    80         if not 'logId' in data:
    81                 print('ERROR: No log id returned')
    82                 sys.exit(6)
    83         return data["logId"]
     73    response = requests.post(
     74        url, json=log.log_creation(), headers=header(api_key)
     75    )
     76
     77    if response.status_code != 200:
     78        print(
     79            'ERROR: Could not create LogMetaData for logfile {}'.format(
     80                log.logfile
     81            )
     82        )
     83        print('  Response status code: {}'.format(response.status_code))
     84        print('  Response:             \n{}'.format(response.text))
     85        print('  Request headers:      {}'.format(response.request.headers))
     86        print('  Request body:         {}'.format(response.request.body))
     87        sys.exit(5)
     88
     89    data = response.json()
     90    if not 'logId' in data:
     91        print('ERROR: No log id returned')
     92        sys.exit(6)
     93    return data["logId"]
     94
    8495
    8596def upload_log(log_id, log, url, api_key):
    86         fileContent = open(log.logfile, 'rb')
    87         headers = header(api_key)
    88         headers["Accept"] = "application/json"
    89         response = requests.post(
    90                 "{}/{}".format(url, log_id),
    91                 data = fileContent,
    92                 headers = headers
    93         )
    94         if response.status_code != 200:
    95                 print('ERROR: Could not upload log for logfile {}'.format(log.logfile))
    96                 print("Response status code: {}".format(response.status_code))
    97                 print("Response:             \n{}".format(response.text))
    98                 sys.exit(7)
     97    fileContent = open(log.logfile, 'rb')
     98    headers = header(api_key)
     99    headers["Accept"] = "application/json"
     100    response = requests.post(
     101        "{}/{}".format(url, log_id), data=fileContent, headers=headers
     102    )
     103    if response.status_code != 200:
     104        print('ERROR: Could not upload log for logfile {}'.format(log.logfile))
     105        print("Response status code: {}".format(response.status_code))
     106        print("Response:             \n{}".format(response.text))
     107        sys.exit(7)
     108
    99109
    100110def main(argv):
    101         input_file_path = None
    102         url = None
    103         api_key = None
    104        
    105         parser = argparse.ArgumentParser(description='Uploads logfiles to GNUBoat server')
    106         parser.add_argument('input_file', metavar='input_file_path', type=str,
    107                                                 help='JSON file with water, gauge, device, logfiles and correction data to be processed')
    108         parser.add_argument('-s', '--server', dest='server', type=str,
    109                         help='Server host and port to upload the logsfiles to')
    110         parser.add_argument('-k', '--api-key', dest='api_key', type=str,
    111                         help='API Key for authorisation')
    112         arguments = parser.parse_args(argv)
    113        
    114         if arguments.input_file is None:
    115                 print('ERROR: No input file specified')
    116                 sys.exit(2)
    117         elif not os.path.exists(arguments.input_file):
    118                 print('ERROR: Specified input file does not exists: {}'.format(arguments.input_file))
    119                 sys.exit(3)
    120         else:
    121                 input_file_path = arguments.input_file
    122        
    123         if arguments.server is None:
    124                 print('ERROR: No server specified')
    125                 sys.exit(2)
    126         else:
    127                 url = 'http://{}/mapservice/v1/logs'.format(arguments.server)
    128                
    129         if arguments.api_key is None:
    130                 print('ERROR: No API key specified')
    131                 sys.exit(2)
    132         else:
    133                 api_key = arguments.api_key
    134                
    135         logs_checked = []
    136         print('Checking input from {}'.format(input_file_path))
    137         with open(input_file_path, 'r') as input_file:
    138                 logs = json.load(input_file)
    139                 for log in logs:
    140                         if not 'water' in log:
    141                                 print('ERROR: No water in log {}'.format(json.dumps(log)))
    142                                 sys.exit(4)
    143                         water_id = to_int(log['water'])
    144                         if not water_id:
    145                                 print('ERROR: Could not convert water to int {}'.format(log['water']))
    146                                 sys.exit(4)
    147                        
    148                         if not 'gauge' in log:
    149                                 print('ERROR: No gauge in log {}'.format(json.dumps(log)))
    150                                 sys.exit(4)
    151                         gauge_id = to_int(log['gauge'])
    152                         if not gauge_id:
    153                                 print('ERROR: Could not convert gauge to int {}'.format(log['gauge']))
    154                                 sys.exit(4)
    155                                
    156                         if not 'device' in log:
    157                                 print('ERROR: No device in log {}'.format(json.dumps(log)))
    158                                 sys.exit(4)
    159                         device_id = to_int(log['device'])
    160                         if not device_id:
    161                                 print('ERROR: Could not convert device to int {}'.format(log['device']))
    162                                 sys.exit(4)
    163                                
    164                         if not 'gaugeHeight' in log:
    165                                 print('ERROR: No gaugeHeight in log {}'.format(json.dumps(log)))
    166                                 sys.exit(4)
    167                         gauge_height = to_float(log['gaugeHeight'])
    168                         if not gauge_height:
    169                                 print('ERROR: Could not convert gaugeHeight to float {}'.format(log['gaugeHeight']))
    170                                 sys.exit(4)
    171                                
    172                         if not 'file' in log:
    173                                 print('ERROR: No file in log {}'.format(json.dumps(log)))
    174                                 sys.exit(4)
    175                                
    176                         comment = ''
    177                         if 'comment' in log:
    178                                 comment = log['comment']
    179                        
    180                         logfile = os.path.join(os.path.dirname(__file__), log['file'])
    181                         if not os.path.exists(logfile):
    182                                 logfile_rel = os.path.join(os.path.dirname(input_file_path), log['file'])
    183                                 if not os.path.exists(logfile_rel):
    184                                         print('ERROR: Logfile not found at {} or {}'.format(logfile, logfile_rel))
    185                                         sys.exit(4)
    186                                 else:
    187                                         logfile = logfile_rel
    188                         logs_checked.append(Log(water_id, device_id, gauge_id, gauge_height, comment, logfile))
    189        
    190         print('Uploading {} logs'.format(len(logs_checked)))
    191         for log in logs_checked:
    192                 log_id = create_log(log, url, api_key)
    193                 upload_log(log_id, log, url, api_key)
    194                 print(' Finished {}'.format(log.logfile))
     111    input_file_path = None
     112    url = None
     113    api_key = None
     114
     115    parser = argparse.ArgumentParser(
     116        description='Uploads logfiles to GNUBoat server'
     117    )
     118    parser.add_argument(
     119        'input_file',
     120        metavar='input_file_path',
     121        type=str,
     122        help=
     123        'JSON file with water, gauge, device, logfiles and correction data to be processed'
     124    )
     125    parser.add_argument(
     126        '-s',
     127        '--server',
     128        dest='server',
     129        type=str,
     130        help='Server host and port to upload the logsfiles to'
     131    )
     132    parser.add_argument(
     133        '-k',
     134        '--api-key',
     135        dest='api_key',
     136        type=str,
     137        help='API Key for authorisation'
     138    )
     139    arguments = parser.parse_args(argv)
     140
     141    if arguments.input_file is None:
     142        print('ERROR: No input file specified')
     143        sys.exit(2)
     144    elif not os.path.exists(arguments.input_file):
     145        print(
     146            'ERROR: Specified input file does not exists: {}'.format(
     147                arguments.input_file
     148            )
     149        )
     150        sys.exit(3)
     151    else:
     152        input_file_path = arguments.input_file
     153
     154    if arguments.server is None:
     155        print('ERROR: No server specified')
     156        sys.exit(2)
     157    else:
     158        url = 'http://{}/mapservice/v1/logs'.format(arguments.server)
     159
     160    if arguments.api_key is None:
     161        print('ERROR: No API key specified')
     162        sys.exit(2)
     163    else:
     164        api_key = arguments.api_key
     165
     166    logs_checked = []
     167    print('Checking input from {}'.format(input_file_path))
     168    with open(input_file_path, 'r') as input_file:
     169        logs = json.load(input_file)
     170        for log in logs:
     171            if not 'water' in log:
     172                print('ERROR: No water in log {}'.format(json.dumps(log)))
     173                sys.exit(4)
     174            water_id = to_int(log['water'])
     175            if not water_id:
     176                print(
     177                    'ERROR: Could not convert water to int {}'.format(
     178                        log['water']
     179                    )
     180                )
     181                sys.exit(4)
     182
     183            if not 'gauge' in log:
     184                print('ERROR: No gauge in log {}'.format(json.dumps(log)))
     185                sys.exit(4)
     186            gauge_id = to_int(log['gauge'])
     187            if not gauge_id:
     188                print(
     189                    'ERROR: Could not convert gauge to int {}'.format(
     190                        log['gauge']
     191                    )
     192                )
     193                sys.exit(4)
     194
     195            if not 'device' in log:
     196                print('ERROR: No device in log {}'.format(json.dumps(log)))
     197                sys.exit(4)
     198            device_id = to_int(log['device'])
     199            if not device_id:
     200                print(
     201                    'ERROR: Could not convert device to int {}'.format(
     202                        log['device']
     203                    )
     204                )
     205                sys.exit(4)
     206
     207            if not 'gaugeHeight' in log:
     208                print(
     209                    'ERROR: No gaugeHeight in log {}'.format(json.dumps(log))
     210                )
     211                sys.exit(4)
     212            gauge_height = to_float(log['gaugeHeight'])
     213            if not gauge_height:
     214                print(
     215                    'ERROR: Could not convert gaugeHeight to float {}'.format(
     216                        log['gaugeHeight']
     217                    )
     218                )
     219                sys.exit(4)
     220
     221            if not 'file' in log:
     222                print('ERROR: No file in log {}'.format(json.dumps(log)))
     223                sys.exit(4)
     224
     225            comment = ''
     226            if 'comment' in log:
     227                comment = log['comment']
     228
     229            logfile = os.path.join(os.path.dirname(__file__), log['file'])
     230            if not os.path.exists(logfile):
     231                logfile_rel = os.path.join(
     232                    os.path.dirname(input_file_path), log['file']
     233                )
     234                if not os.path.exists(logfile_rel):
     235                    print(
     236                        'ERROR: Logfile not found at {} or {}'.format(
     237                            logfile, logfile_rel
     238                        )
     239                    )
     240                    sys.exit(4)
     241                else:
     242                    logfile = logfile_rel
     243            logs_checked.append(
     244                Log(
     245                    water_id, device_id, gauge_id, gauge_height, comment,
     246                    logfile
     247                )
     248            )
     249
     250    print('Uploading {} logs'.format(len(logs_checked)))
     251    for log in logs_checked:
     252        log_id = create_log(log, url, api_key)
     253        upload_log(log_id, log, url, api_key)
     254        print(' Finished {}'.format(log.logfile))
     255
    195256
    196257if __name__ == "__main__":
    197         main(sys.argv[1:])
     258    main(sys.argv[1:])
Note: See TracChangeset for help on using the changeset viewer.