Changes in / [20d6392:6b3dd00]


Ignore:
Location:
src/python
Files:
7 edited

Legend:

Unmodified
Added
Removed
  • src/python/bin/gnuboat

    r20d6392 r6b3dd00  
    6767        if (currentTime - shutdownRequested) > datetime.timedelta(seconds=0):
    6868            os.system("sudo shutdown -h now")
     69
     70
     71def usage():
     72    print "Usage of gnuboat daemon:"
     73    print "  gnuboat -r PATH_TO_RRD_DATABAE_FILE -s PATH_TO_SHUTDOWN_REQUEST_FILE [-l [LOG_UPDATE_PERIOD] [-d DISPLAY_UPDATE_PERIOD] [-o PATH_TO_NMEA1983_LOG]"
     74    print ""
     75    print "  -h  --help              Display this help"
     76    print "  -r  --rrdfile           Path to the rrd database used by the webservice to serve the clients"
     77    print "  -s  --shutdownfile      Path to the shutdown request file, used by the webservice to request a shutdown of the system running gnuboat"
     78    print "  -l  --logperiod         Time in seconds to update the logs"
     79    print "  -lv --log-verbose       Log verbose information to nmea log file (Enables -ls and adds RMC sentences, with invalid GPS state, on non fixes"
     80    print "  -ls --log-system-time   Add to enable prefixing every logline with the system time (Default off)"
     81    print "  -d  --displayperiod     Timein seconds to update the display"
     82    print "  -o  --output            Directory where the log files are stored (e.g. the NMEA0183 log files)"
    6983
    7084def log(gpsFix, gpsTime, gpsStatus, latitude, latitudeDirection, longitude,
    … …  
    90104        try:
    91105            nmeaFileDate = nmeaFileDateShould
    92             nmeaLogFile = 'nmea0183-{}.log'.format(nmeaFileDate)
    93             nmeafile = open('{}/{}'.format(logdir, nmeaLogFile), 'a', 0)
     106            nmeaLogFile = "nmea0183-%s.log" % nmeaFileDate
     107            nmeafile = open("%s/%s" % (logdir, nmeaLogFile), 'a', 0)
    94108        except IOError as error:
    95             print('Could not open the logfile: {}'.format(error))
     109            print "Could not open the logfile: %s" % error
    96110            sys.exit(2)
    97111
    … …  
    101115    logsystemtime = ""
    102116    if logsystemtime:
    103         logsystemtime = '{}: '.format(datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"))
     117        logsystemtime = "%s:" datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
    104118       
    105119    try:
    106         nmeafile.write('{}{}\r\n'.format(logsystemtime, str(pynmea2.RMC('GN', 'RMC',
     120        nmeafile.write("%s%s\r\n" % (logsystemtime, str(pynmea2.RMC('GN', 'RMC',
    107121                                                     (gpsTime.strftime("%H%M%S"), gpsStatus,
    108                                                      '{:02d}{:s}'.format(latitude['degrees'], latitude['minutes']),
     122                                                     '%02d%s' % (latitude['degrees'], latitude['minutes'])
    109123                                                     latitudeDirection,
    110                                                      '{:03d}{:s}'.format(longitude['degrees'], longitude['minutes']),
     124                                                     '%03d%s' % (longitude['degrees'], longitude['minutes']),
    111125                                                     longitudeDirection,
    112                                                      '{:04.1f}'.format(speedOverGround), '{:04.1f}'.format(courseOverGround),
     126                                                     '%04.1f' % speedOverGround, '%04.1f' % courseOverGround,
    113127                                                     gpsTime.strftime("%d%m%y"), '', '', mode)))))
    114128        if transducerValid:
    115             nmeafile.write('{}{}\r\n'.format(logsystemtime, str(pynmea2.DPT('SD', 'DPT', ('{:05.2f}'.format(waterDepth, '00.00'))))))
    116             nmeafile.write('{}{}\r\n'.format(logsystemtime, str(pynmea2.MTW('YX', 'MTW', ('{:04.1f}'.format(waterTemperature, 'C'))))))
     129            nmeafile.write("%s%s\r\n" % (logsystemtime, str(pynmea2.DPT('SD', 'DPT', ('%05.2f' % waterDepth, '00.00')))))
     130            nmeafile.write("%s%s\r\n" % (logsystemtime, str(pynmea2.MTW('YX', 'MTW', ('%04.1f' % waterTemperature, 'C')))))
    117131    except:
    118         print('Failed writing to logfile {}'.format(nmeaLogFile))
     132        print "Failed writing to logfile %s" % nmeaLogFile
    119133        print(traceback.format_exc())
    120134
    … …  
    134148    global nmeafile
    135149
    136     parser = argparse.ArgumentParser(description='Collects the data from canboat and gpsd and writes them to the rrd database and the nmea log file')
     150    parser = argparse.ArgumentParser(description="Collects the data from canboat and gpsd and writes them to the rrd database and the nmea log file")
    137151    parser.add_argument('-r', '--rrdfile', dest='rrd_file', metavar='rrd_file', type=str,
    138152                        help='Path to the rrd database used by the webservice to serve the clients', default=rrdfile)
    … …  
    168182
    169183    if not os.path.exists(os.path.dirname(rrdfile)):
    170         print('rrd database directory not found {}'.format(os.path.dirname(rrdfile)))
    171         parser.print_help()
     184        print "rrd database directory not found %s" % os.path.dirname(rrdfile)
     185        print ""
     186        usage()
    172187        sys.exit(2)
    173188
    174189    if not os.path.exists(os.path.dirname(shutdownfile)):
    175         print('Shutdown request directory not found {}'.format(os.path.dirname(shutdownfile)))
    176         parser.print_help()
     190        print "Shutdown request directory not found %s" % os.path.dirname(shutdownfile)
     191        print ""
     192        usage()
    177193        sys.exit(2)
    178194
    179195    if logperiod < 1:
    180         print('Log period must be >= 1')
    181         parser.print_help()
     196        print "Log period must be >= 1"
     197        print ""
     198        usage()
    182199        sys.exit(2)
    183200
    184201    if displayperiod < 1 or displayperiod < logperiod:
    185         print('Display period must be >= 1 and could not be faster than log period')
    186         parser.print_help()
     202        print "Display period must be >= 1 and could not be faster than log period"
     203        print ""
     204        usage()
    187205        sys.exit(2)
    188206
    … …  
    213231
    214232            # update rrd database for the webservice
    215             daemon.rrd_update(rrdfile, 'N:{:s}:{:s}:{:s}:{:s}:{:s}:{:s}:{:s}:{:s}'.format(
     233            daemon.rrd_update(rrdfile, "N:%s:%s:%s:%s:%s:%s:%s:%s" % (
    216234                latitude, longitude, speedThroughWater, speedOverGround, courseOverGround, waterDepth, waterTemperature, gpsFix))
    217235
  • src/python/bin/gnuboat-data-generator

    r20d6392 r6b3dd00  
    4646    global logperiod
    4747
    48     parser = argparse.ArgumentParser(description='Generates test data for gnuboat webservice and fills the rrd database')
     48    parser = argparse.ArgumentParser(description="Generates test data for gnuboat webservice and fills the rrd database")
    4949    parser.add_argument('-f', '--file', dest='rrd_database', metavar='rrd_database', type=str,
    5050                        help='File path of the rrd database to fill', default="/var/lib/gnuboat/gnuboat.rrd")
    … …  
    7878
    7979    if not os.path.exists(os.path.dirname(rrdfile)):
    80         print('rrd database directory not found {}'.format(os.path.dirname(rrdfile)))
     80        print "rrd database directory not found %s" % os.path.dirname(rrdfile)
     81        print ""
    8182        parser.print_help()
    8283        sys.exit(2)
    … …  
    8687       
    8788    if os.path.isfile(rrdfile):
    88         print('Removing old database {}'.format(rrdfile))
     89        print "Removing old database %s" % rrdfile
    8990        os.remove(rrdfile)
    9091
    91     print('Creating {}'.format(rrdfile))
     92    print "Creating %s" % rrdfile
    9293    daemon.rrd_create_database(rrdfile, logperiod, str(start_time))
    9394   
    94     print('Filling database inside [{}, {}] --> [{}, {}]...'.format(latitude_min, longitude_min, latitude_max, longitude_max))
     95    print "Filling database inside [%s, %s] --> [%s,%s]..." % (latitude_min, longitude_min, latitude_max, longitude_max)
    9596    for current_time in xrange(timestamp - duration, timestamp, logperiod):
    9697        latitude = random.uniform(latitude_min, latitude_max)
    … …  
    103104        gpsFix = 3
    104105        # update rrd database for the webservice
    105         daemon.rrd_update(rrdfile, '{:s}:{:s}:{:s}:{:s}:{:s}:{:s}:{:s}:{:s}:{:s}'.format(
     106        daemon.rrd_update(rrdfile, "%s:%s:%s:%s:%s:%s:%s:%s:%s" % (
    106107                       current_time, latitude, longitude, speedThroughWater, speedOverGround, courseOverGround, waterDepth, waterTemperature, gpsFix))
    107108
  • src/python/bin/gnuboat-log-converter

    r20d6392 r6b3dd00  
    4343           return int(string)
    4444        except ValueError as error:
    45            print('INFO: Failed to convert value from line %s into numeric: {:s}\n      Message: {:s}'.format(current_row, string, error))
     45           print 'INFO: Failed to convert value from line %s into numeric: %s\n      Message: %s' % (current_row, string, error)
    4646           return 0
    4747
    … …  
    5454    matches = regex_nmea_position.match(nmea_value)
    5555    if matches is None:
    56         print('INFO: Failed to convert position value from line {:s} into decimal degrees: {:s}'.format(current_row, nmea_value))
     56        print 'INFO: Failed to convert position value from line %s into decimal degrees: %s' % (current_row, nmea_value)
    5757        return
    5858    decimalDegrees = toFloat(matches.group(1), current_row)
    … …  
    6666        output_file = open(output_file_path, 'w', 0)
    6767    except IOError as error:
    68         print('ERROR: Could not open the output file: {}'.format(error))
     68        print "ERROR: Could not open the output file: %s" % error
    6969        sys.exit(3)
    7070
    … …  
    8181        input_file = open(input_file_path, 'r')
    8282    except IOError as error:
    83         print('ERROR: Could not open the input file: {}'.format(error))
     83        print "ERROR: Could not open the input file: %s" % error
    8484        sys.exit(3)
    8585    current_row = 1
    … …  
    8989        matches = regex_nmea_sentence.match(line)
    9090        if matches is None:
    91             print('INFO: Failed to parse nmea sentence ({}) at line {}\n'.format(line, current_row))
     91            print 'INFO: Failed to parse nmea sentence (%s) at line %s\n' % (line, current_row)
    9292            if not errors_ignore:
    9393                input_file.close()
    … …  
    9999                if last_row is not None:
    100100                    output_file_csv.writerow(last_row)
    101                 last_row = {'datetime': '{} {}'.format(nmea_sentence.datestamp, nmea_sentence.timestamp),
     101                last_row = {'datetime': '%s %s' % (nmea_sentence.datestamp, nmea_sentence.timestamp),
    102102                            'gps_status': nmea_sentence.status,
    103103                            'latitude': nmeaToDecimalDegrees(nmea_sentence.lat, current_row),
    … …  
    125125        output_file = open(output_file_path, 'w', 0)
    126126    except IOError as error:
    127         print('ERROR: Could not open the output file: {}'.format(error))
     127        print "ERROR: Could not open the output file: %s" % error
    128128        sys.exit(3)
    129129
    … …  
    132132        input_file = open(input_file_path, 'r')
    133133    except IOError as error:
    134         print('ERROR: Could not open the input file: {}'.format(error))
     134        print "ERROR: Could not open the input file: %s" % error
    135135        sys.exit(3)
    136136    current_row = 1
    … …  
    140140        matches = regex_nmea_sentence.match(line)
    141141        if matches is None:
    142             print('INFO: Failed to parse nmea sentence ({}) at line {}\n'.format(line, current_row))
     142            print 'INFO: Failed to parse nmea sentence (%s) at line %s\n' % (line, current_row)
    143143            if not errors_ignore:
    144144                input_file.close()
    … …  
    149149            output_string = str(nmea_sentence)
    150150            if not strip_time and matches.group(1):
    151                 output_string = '{}{}'.format(matches.group(1), output_string)
    152             output_file.write('{}\r\n'.format(str(output_string)))
     151                output_string = '%s%s' % (matches.group(1), output_string)
     152            output_file.write("%s\r\n" % str(output_string))
    153153    output_file.close()
    154154    input_file.close()
    … …  
    177177      formats.append(file_format.name)
    178178
    179     parser = argparse.ArgumentParser(description='Convert gnuboat logfiles into other formats')
     179    parser = argparse.ArgumentParser(description="Convert gnuboat logfiles into other formats")
    180180    parser.add_argument('-f', '--format', dest='output_format', metavar='output_format', type=str,
    181181                        help='Format of the output file.', choices=formats, default='CSV')
    … …  
    197197               format_found = True
    198198        if not format_found:
    199             print('ERROR: Invalid input format specified: {}'.format(arguments.output_format))
     199            print 'ERROR: Invalid input format specified: %s' % arguments.output_format
    200200            sys.exit(1)
    201201
    … …  
    207207           
    208208    if arguments.input_file is None:
    209         print('ERROR: No input file specified')
     209        print 'ERROR: No input file specified'
    210210        sys.exit(2)
    211211    elif not os.path.exists(arguments.input_file):
    212         print('ERROR: Specified input file does not exists: {}'.format(arguments.input_file))
     212        print 'ERROR: Specified input file does not exists: %s' % arguments.input_file
    213213        sys.exit(3)
    214214    else:
    … …  
    216216       
    217217    if arguments.output_file is None:
    218         print('ERROR: No output file specified')
     218        print 'ERROR: No output file specified'
    219219        sys.exit(2)
    220220    elif not os.path.exists(os.path.dirname(arguments.output_file)):
    221         print('ERROR: Specified directory of output file does not exists: {}'.format(arguments.output_file))
     221        print 'ERROR: Specified directory of output file does not exists: %s' % arguments.output_file
    222222        sys.exit(3)
    223223    else:
    … …  
    231231        convertToGpx(input_file_path, output_file_path, errors_ignore, strip_time)
    232232    else:
    233         print('ERROR: Undefined output format!\n')
     233        print "ERROR: Undefined output format!\n";
    234234        sys.exit(1)
    235235
  • src/python/bin/gnuboat-splashscreen

    r20d6392 r6b3dd00  
    3939
    4040def usage():
    41     print("Usage of gnuboat-splashscreen:")
    42     print("  gnuboat-splashscreen [-h] -i PATH_TO_IMAGE_TO_DISPLAY")
    43     print("")
    44     print("  -h --help    Print this help")
    45     print("  -i --image   Path to the image, which should be displayed")
     41    print "Usage of gnuboat-splashscreen:"
     42    print "  gnuboat-splashscreen [-h] -i PATH_TO_IMAGE_TO_DISPLAY"
     43    print ""
     44    print "  -h --help    Print this help"
     45    print "  -i --image   Path to the image, which should be displayed"
    4646    sys.exit()
    4747
    … …  
    6565
    6666    if not os.path.exists(image):
    67         print("Image {} not found".format(image))
     67        print "Image %s not found" % image
     68        print ""
    6869        usage()
    6970        sys.exit(2)
    7071
    7172    if not epdEnabled:
    72         print("Could not initialize EPD or PIL python packages")
     73        print "Could not initialize EPD or PIL python packages"
    7374        sys.exit(2)
    7475
  • src/python/gnuboat/daemon/gpsdpoller.py

    r20d6392 r6b3dd00  
    4747
    4848    def latitudeDirection(self):
    49         return 'N'
     49        return "N"
    5050
    5151    def longitude(self):
    … …  
    5555
    5656    def longitudeDirection(self):
    57         return 'E'
     57        return "E"
    5858
    5959    def speedOverGround(self):
    … …  
    7474    def status(self):
    7575        if self._currentValue == None or self.gpsFix() < 2:
    76             return 'V'
    77         return 'A'
     76            return "V"
     77        return "A"
    7878
    7979    def timeUtc(self):
    … …  
    9696                    break
    9797                except:
    98                     print('Failed to read gpsd data')
    99                     print(traceback.format_exc())
     98                    print 'Failed to read gpsd data'
     99                    print traceback.format_exc()
    100100                    self._currentValue = None
    101101        except StopIteration:
  • src/python/gnuboat/daemon/n2kdpoller.py

    r20d6392 r6b3dd00  
    6969        except socket.error as error:
    7070            if not self._connectErrorPrinted:
    71                 print('Failed to connect to n2kd server at {}:{}: {}'.format(self._serverHost, self._serverPort, error))
     71                print 'Failed to connect to n2kd server at %s:%s: %s' % (self._serverHost, self._serverPort, error)
    7272                self._connectErrorPrinted = True
    7373            self._waterDepthValid = False
    7474            return
    7575        if self._connectErrorPrinted:
    76             print('Connected to n2kd server at {}:{}'.format(self._serverHost, self._serverPort))
     76            print "Connected to n2kd server at %s:%s" % (self._serverHost, self._serverPort)
    7777            self._connectErrorPrinted = False
    7878
    … …  
    8282                data = n2kdSocket.recv(1024)
    8383            except:
    84                 print('Failed to update n2kd data')
    85                 print(traceback.format_exc())
     84                print 'Failed to update n2kd data'
     85                print traceback.format_exc()
    8686                self._waterDepthValid = False
    8787            if not data:
    … …  
    9292            data = json.loads(response)
    9393        except ValueError as error:
    94             print('Failed to decode json: {}'.format(error))
     94            print "Failed to decode json: %s" % error
    9595
    9696        descriptions = [
    … …  
    100100            entryKeys = data[key].keys()
    101101            if len(entryKeys) != 2:
    102                 print('Malformed json n2kd response? {}'.format(response))
     102                print "Malformed json n2kd response? %s" % response
    103103            else:
    104104                if data[key]["description"] in descriptions:
    … …  
    106106                    lineKeys = data[key][entryKey].keys()
    107107                    if "fields" not in lineKeys:
    108                         print('No fields entry. Malformed json n2kd response in {}'.format(data[key][entryKey]))
     108                        print "No fields entry. Malformed json n2kd response in %s" % data[key][entryKey]
    109109                    else:
    110110                        fields = data[key][entryKey]["fields"]
    … …  
    116116                        # try speed
    117117                        if "Speed Water Referenced" in fields:
    118                             self._speedThroughWater = fields["Speed Water Referenced"]
     118                            self._speedThroughWater = fields[
     119                                "Speed Water Referenced"]
    119120                        # try sea temperature
    120121                        if "Temperature Source" in fields and "Temperature" in fields:
    … …  
    128129
    129130    def _serverUrl(self):
    130         return 'http://{}:{:d}/'.format(self._serverHost, self._serverPort)
     131        return "http://%s:%d/" % (self._serverHost, self._serverPort)
    131132
    132133    def stop(self):
  • src/python/gnuboat/daemon/rrdhandler.py

    r20d6392 r6b3dd00  
    4040    rrd_archives = []
    4141    for i in range(0, len(archives)):
    42         rrd_archives += ['RRA:AVERAGE:0.5:{:d}:{:d}'.format(_steps(archives[i]["resolution"], step), _rows(
     42        rrd_archives += ['RRA:AVERAGE:0.5:%d:%d' % (_steps(archives[i]["resolution"], step), _rows(
    4343        archives[i]["duration"], archives[i]["resolution"], step))]
    4444
    … …  
    5656        rrdtool.update(rrdfile, value_string)
    5757    except:
    58         print('Failed to update rrd database {} with values\n  {}'.format(rrdfile, value_string))
    59         print(traceback.format_exc())
     58        print 'Failed to update rrd database %s with values\n  %s' % (rrdfile, value_string)
     59        print traceback.format_exc()
    6060
    6161def _rows(duration, resolution, step):
Note: See TracChangeset for help on using the changeset viewer.