Changeset 8fd7454 for src/python/bin


Ignore:
Timestamp:
Dec 10, 2017, 4:32:57 PM (9 years ago)
Author:
Joachim Langenbach <joachim.langenbach@…>
Branches:
debian/bullseye, debian/jessie
Children:
ce5244e
Parents:
c810990 (diff), 8ef59a1 (diff)
Note: this is a merge changeset, the changes displayed below correspond to the merge itself.
Use the (diff) links above to see all the changes relative to each parent.
Message:

Merge branch 'debian/jessie' of ​https://svn.engsas.de/gnuboat into debian/jessie

Location:
src/python/bin
Files:
2 added
2 edited

Legend:

Unmodified
Added
Removed
  • src/python/bin/gnuboat

    rc810990 r8fd7454  
    2727from pytz import timezone
    2828import pytz
    29 import getopt
     29import argparse
    3030import sys
    3131import pynmea2
     32import traceback
     33import math
    3234
    3335from gnuboat import daemon
    … …  
    4345logdir = "/var/log/gnuboat"
    4446logperiod = 2
     47logverbose = False
     48logsystemtime = False
    4549displayperiod = 5
    4650
    … …  
    4852nmeafile = None
    4953nmeaFileDate = None
    50 
    51 
    52 def rraRows(duration, resolution, step):
    53     return int(round(float(duration) / rraSteps(resolution, float(step)) / float(step)))
    54 
    55 
    56 def rraSteps(resolution, step):
    57     return int(round(float(resolution) / float(step)))
    58 
    59 
    60 def createDatabase(databaseFile):
    61     rrdDataSources = ['DS:latitude:GAUGE:15:-90:90',
    62                       'DS:longitude:GAUGE:15:-180:180',
    63                       'DS:speedthroughwater:GAUGE:15:U:U',
    64                       'DS:speedoverground:GAUGE:15:U:U',
    65                       'DS:waterdepth:GAUGE:15:0:10000',
    66                       'DS:watertemperature:GAUGE:15:-10:50',
    67                       'DS:gpsfix:GAUGE:15:-999:3']
    68 
    69     step = logperiod
    70     # durations: each archive should contain values for in seconds
    71     archives = [
    72         {"duration": 240, "resolution": 2},
    73         {"duration": 3600, "resolution": 10},
    74         {"duration": 86400, "resolution": 60},
    75     ]
    76     rrdArchives = []
    77     for i in range(0, len(archives)):
    78         rrdArchives += ['RRA:AVERAGE:0.5:%d:%d' % (rraSteps(archives[i]["resolution"], step), rraRows(
    79             archives[i]["duration"], archives[i]["resolution"], step))]
    80 
    81     if not os.path.isfile(databaseFile):
    82         rrdtool.create(databaseFile,
    83                        "--start",
    84                        "N",
    85                        "--step",
    86                        str(step),
    87                        rrdDataSources,
    88                        rrdArchives)
    8954
    9055
    … …  
    10469            os.system("sudo shutdown -h now")
    10570
    106 
    107 def usage():
    108     print "Usage of gnuboat daemon:"
    109     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]"
    110     print ""
    111     print "  -h --help              Display this help"
    112     print "  -r --rrdfile           Path to the rrd database used by the webservice to serve the clients"
    113     print "  -s --shutdownfile      Path to the shutdown request file, used by the webservice to request a shutdown of the system running gnuboat"
    114     print "  -l --logperiod         Time in seconds to update the logs"
    115     print "  -d --displayperiod     Timein seconds to update the display"
    116     print "  -o --output            Directory where the log files are stored (e.g. the NMEA0183 log files)"
    117 
    11871def log(gpsFix, gpsTime, gpsStatus, latitude, latitudeDirection, longitude,
    119         longitudeDirection, courseOverGround, speedOverGround, waterDepth, waterDepthValid):
     72        longitudeDirection, courseOverGround, speedOverGround, waterDepth, waterTemperature, transducerValid, logVerbose, logSystemTime):
    12073    global logdir
    12174    global nmeafile
    12275    global nmeaFileDate
    123    
     76
    12477    # Only log, if we have a gps fix
    12578    if gpsFix < 2:
    126         return
     79        if not logVerbose:
     80            return
     81        gpsStatus = 'V'
     82        mode = 'N'
     83        if gpsTime is None:
     84            gpsTime = datetime.datetime.utcnow()
    12785   
    12886    nmeaFileDateShould = datetime.datetime.utcnow().strftime("%Y-%m-%d")
    … …  
    13391        try:
    13492            nmeaFileDate = nmeaFileDateShould
    135             nmeaLogFile = "nmea0183-%s.log" % nmeaFileDate
    136             nmeafile = open("%s/%s" % (logdir, nmeaLogFile), 'a', 0)
     93            nmeaLogFile = 'nmea0183-{}.log'.format(nmeaFileDate)
     94            nmeafile = open('{}/{}'.format(logdir, nmeaLogFile), 'a', 0)
    13795        except IOError as error:
    138             print "Could not open the logfile: %s" % error
     96            print('Could not open the logfile: {}'.format(error))
    13997            sys.exit(2)
    140                
    141     nmeafile.write("%s\r\n" % str(pynmea2.RMC('GN', 'RMC',
    142                                               (gpsTime.strftime("%H%M%S"), gpsStatus, '$%04.3f' % latitude,
    143                                                latitudeDirection, '$%05.3f' % longitude, longitudeDirection,
    144                                                '$%02.1f' % speedOverGround, '$%02.1f' % courseOverGround,
    145                                                gpsTime.strftime("%d%m%y"), '', '', mode))))
    146     if waterDepthValid:
    147         nmeafile.write("%s\r\n" % str(pynmea2.DPT('SD', 'DPT', ('%02.2f' % waterDepth, '00.00'))))
     98
     99    latitude = degreesDecimalToNmea(latitude)
     100    longitude = degreesDecimalToNmea(longitude)
     101
     102    logsystemtime = ""
     103    if logsystemtime:
     104        logsystemtime = '{}: '.format(datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"))
     105       
     106    try:
     107        nmeafile.write('{}{}\r\n'.format(logsystemtime, str(pynmea2.RMC('GN', 'RMC',
     108                                                     (gpsTime.strftime("%H%M%S"), gpsStatus,
     109                                                     '{:02d}{:07.4f}'.format(latitude['degrees'], latitude['minutes']),
     110                                                     latitudeDirection,
     111                                                     '{:03d}{:07.4f}'.format(longitude['degrees'], longitude['minutes']),
     112                                                     longitudeDirection,
     113                                                     '{:04.1f}'.format(speedOverGround), '{:04.1f}'.format(courseOverGround),
     114                                                     gpsTime.strftime("%d%m%y"), '', '', mode)))))
     115        if transducerValid:
     116            nmeafile.write('{}{}\r\n'.format(logsystemtime, str(pynmea2.DPT('SD', 'DPT', ('{:05.2f}'.format(waterDepth), '00.00')))))
     117            nmeafile.write('{}{}\r\n'.format(logsystemtime, str(pynmea2.MTW('YX', 'MTW', ('{:04.1f}'.format(waterTemperature), 'C')))))
     118    except:
     119        print('Failed writing to logfile {}'.format(nmeaLogFile))
     120        print(traceback.format_exc())
     121
     122def degreesDecimalToNmea(decimalDegrees):
     123    degrees = int(math.floor(decimalDegrees))
     124    minutes = 60.0 * (decimalDegrees - degrees)
     125    return { 'degrees': degrees, 'minutes': minutes}
    148126
    149127def main(argv):
    … …  
    151129    global shutdownfile
    152130    global logperiod
     131    global logverbose
     132    global logsystemtime
    153133    global displayperiod
    154134    global logdir
    155135    global nmeafile
    156136
    157     try:
    158         opts, args = getopt.getopt(argv, "hr:s:l:d:o:", [
    159                                    "help", "rrdfile=", "shutdownfile=", "logperiod=", "displayperiod=", "output="])
    160     except getopt.GetoptError:
    161         usage()
    162         sys.exit(2)
    163 
    164     for option, argument in opts:
    165         if option == ("-h", "--help"):
    166             usage()
    167             sys.exit()
    168         elif option in ("-r", "--rrdfile"):
    169             rrdfile = argument
    170         elif option in ("-s", "--shutdownfile"):
    171             shutdownfile = argument
    172         elif option in ("-l", "--logperiod"):
    173             logperiod = argument
    174         elif option in ("-d", "--displayperiod"):
    175             displayperiod = argument
    176         elif option in ("-o", "--output"):
    177             logdir = argument
    178         else:
    179             assert False, "unhandled option"
     137    parser = argparse.ArgumentParser(description='Collects the data from canboat and gpsd and writes them to the rrd database and the nmea log file')
     138    parser.add_argument('-r', '--rrdfile', dest='rrd_file', metavar='rrd_file', type=str,
     139                        help='Path to the rrd database used by the webservice to serve the clients', default=rrdfile)
     140    parser.add_argument('-s', '--shutdownfile', dest='shutdown_file', metavar='shutdown_file', type=str,
     141                        help='Path to the shutdown request file, used by the webservice to request a shutdown of the system running gnuboat', default=shutdownfile)
     142    parser.add_argument('-lp', '--logperiod', dest='log_period', metavar='log_period', type=int,
     143                        help='Time in seconds to update the logs', default=logperiod)
     144    parser.add_argument('-lv', '--log-verbose', action='store_true', dest='log_verbose',
     145                        help='Log verbose information to nmea log file (Enables -ls and adds RMC sentences, with invalid GPS state, on non fixes (Default off)')
     146    parser.add_argument('-ls', '--log-system-time', action='store_true', dest='log_system_time',
     147                        help='Add to enable prefixing every logline with the system time (Default off)')
     148    parser.add_argument('-d', '--displayperiod', dest='display_period', metavar='display_period', type=int,
     149                        help='Time in seconds to update the display', default=displayperiod)
     150    parser.add_argument('-o', '--output', dest='output', metavar='output', type=str,
     151                        help='Directory where the log files are stored (e.g. the NMEA0183 log files)', default=logdir)
     152    arguments = parser.parse_args(argv)
     153   
     154    if arguments.rrd_file is not None:
     155        rrdfile = arguments.rrd_file
     156    if arguments.shutdown_file is not None:
     157        shutdownfile = arguments.shutdown_file
     158    if arguments.log_period is not None:
     159        logperiod = arguments.log_period   
     160    if arguments.log_verbose is not None:
     161        logverbose = arguments.log_verbose
     162        logsystemtime = True
     163    if arguments.log_system_time is not None and arguments.log_verbose is None:
     164        logsystemtime = arguments.log_system_time
     165    if arguments.display_period is not None:
     166        displayperiod = arguments.display_period
     167    if arguments.output is not None:
     168        logdir = arguments.output
    180169
    181170    if not os.path.exists(os.path.dirname(rrdfile)):
    182         print "rrd database directory not found %s" % os.path.dirname(rrdfile)
    183         print ""
    184         usage()
     171        print('rrd database directory not found {}'.format(os.path.dirname(rrdfile)))
     172        parser.print_help()
    185173        sys.exit(2)
    186174
    187175    if not os.path.exists(os.path.dirname(shutdownfile)):
    188         print "Shutdown request directory not found %s" % os.path.dirname(shutdownfile)
    189         print ""
    190         usage()
     176        print('Shutdown request directory not found {}'.format(os.path.dirname(shutdownfile)))
     177        parser.print_help()
    191178        sys.exit(2)
    192179
    193180    if logperiod < 1:
    194         print "Log period must be >= 1"
    195         print ""
    196         usage()
     181        print('Log period must be >= 1')
     182        parser.print_help()
    197183        sys.exit(2)
    198184
    199185    if displayperiod < 1 or displayperiod < logperiod:
    200         print "Display period must be >= 1 and could not be faster than log period"
    201         print ""
    202         usage()
    203         sys.exit(2)
    204 
    205     createDatabase(rrdfile)
     186        print('Display period must be >= 1 and could not be faster than log period')
     187        parser.print_help()
     188        sys.exit(2)
     189
     190    daemon.rrd_create_database(rrdfile, logperiod)
     191
     192    if os.path.isfile(shutdownfile):
     193        os.remove(shutdownfile)
    206194
    207195    displayHandler = daemon.DisplayHandler(displayperiod)
    … …  
    220208            speedThroughWater = n2kd.speedThroughWater()
    221209            speedOverGround = gpsp.speedOverGround()
     210            courseOverGround = gpsp.courseOverGround()
    222211            waterDepth = n2kd.waterDepth()
    223212            waterTemperature = n2kd.waterTemperature()
    … …  
    225214
    226215            # update rrd database for the webservice
    227             rrdtool.update(rrdfile, "N:%s:%s:%s:%s:%s:%s:%s" % (
    228                 latitude, longitude, speedThroughWater, speedOverGround, waterDepth, waterTemperature, gpsFix))
     216            daemon.rrd_update(rrdfile, 'N:{}:{}:{}:{}:{}:{}:{}:{}'.format(
     217                latitude, longitude, speedThroughWater, speedOverGround, courseOverGround, waterDepth, waterTemperature, gpsFix))
    229218
    230219            # append to log
    231220            log(gpsFix, gpsp.timeUtc(), gpsp.status(), latitude, gpsp.latitudeDirection(),
    232                 longitude, gpsp.longitudeDirection(), gpsp.courseOverGround(), speedOverGround,
    233                 waterDepth, n2kd.waterDepthValid())
     221                longitude, gpsp.longitudeDirection(), courseOverGround, speedOverGround,
     222                waterDepth, waterTemperature, n2kd.waterDepthValid(), logverbose, logsystemtime)
    234223           
    235224            # display data
    236225            displayHandler.setValues(
    237                 speedThroughWater, speedOverGround, waterDepth, waterTemperature, gpsFix)
     226                speedThroughWater, speedOverGround, courseOverGround, waterDepth, waterTemperature, gpsFix)
    238227
    239228            # check for shutdown request
  • src/python/bin/gnuboat-splashscreen

    rc810990 r8fd7454  
    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 %s not found" % image
    68         print ""
     67        print("Image {} not found".format(image))
    6968        usage()
    7069        sys.exit(2)
    7170
    7271    if not epdEnabled:
    73         print "Could not initialize EPD or PIL python packages"
     72        print("Could not initialize EPD or PIL python packages")
    7473        sys.exit(2)
    7574
Note: See TracChangeset for help on using the changeset viewer.