Changeset 6f09609 for src/python/bin


Ignore:
Timestamp:
Aug 6, 2017, 3:53:21 PM (9 years ago)
Author:
Joachim Langenbach <joachim.langenbach@…>
Branches:
0.5, app-cordova, debian/bullseye, debian/jessie, master
Children:
37d2e9d, 8befa17, d51c76c
Parents:
1efcac7
Message:

Make Python files pep8 compliant

Location:
src/python/bin
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • src/python/bin/gnuboat

    r1efcac7 r6f09609  
    3333from gnuboat import daemon
    3434
    35 WHITE=1
    36 BLACK=0
     35WHITE = 1
     36BLACK = 0
    3737marginVertical = 10
    3838marginHorizontal = marginVertical
    … …  
    4848nmeafile = None
    4949
     50
    5051def rraRows(duration, resolution, step):
    5152    return int(round(float(duration) / rraSteps(resolution, float(step)) / float(step)))
    5253
     54
    5355def rraSteps(resolution, step):
    5456    return int(round(float(resolution) / float(step)))
    5557
     58
    5659def createDatabase(databaseFile):
    57   rrdDataSources = [ 'DS:latitude:GAUGE:15:-90:90',
    58                      'DS:longitude:GAUGE:15:-180:180',
    59                      'DS:speedthroughwater:GAUGE:15:U:U',
    60                      'DS:speedoverground:GAUGE:15:U:U',
    61                      'DS:waterdepth:GAUGE:15:0:10000',
    62                      'DS:watertemperature:GAUGE:15:-10:50',
    63                      'DS:gpsfix:GAUGE:15:-999:3' ]
    64 
    65   step = logperiod
    66   # durations: each archive should contain values for in seconds
    67   archives = [
    68     {"duration": 240, "resolution": 2},
    69     {"duration": 3600, "resolution": 10},
    70     {"duration": 86400, "resolution": 60},
    71   ]
    72   rrdArchives = []
    73   for i in range(0, len(archives)):
    74     rrdArchives += ['RRA:AVERAGE:0.5:%d:%d' % (rraSteps(archives[i]["resolution"], step), rraRows(archives[i]["duration"], archives[i]["resolution"], step))]
    75 
    76   if not os.path.isfile(databaseFile):
    77     rrdtool.create(databaseFile,
    78                    "--start",
    79                    "N",
    80                    "--step",
    81                    str(step),
    82                    rrdDataSources,
    83                    rrdArchives)
     60    rrdDataSources = ['DS:latitude:GAUGE:15:-90:90',
     61                      'DS:longitude:GAUGE:15:-180:180',
     62                      'DS:speedthroughwater:GAUGE:15:U:U',
     63                      'DS:speedoverground:GAUGE:15:U:U',
     64                      'DS:waterdepth:GAUGE:15:0:10000',
     65                      'DS:watertemperature:GAUGE:15:-10:50',
     66                      'DS:gpsfix:GAUGE:15:-999:3']
     67
     68    step = logperiod
     69    # durations: each archive should contain values for in seconds
     70    archives = [
     71        {"duration": 240, "resolution": 2},
     72        {"duration": 3600, "resolution": 10},
     73        {"duration": 86400, "resolution": 60},
     74    ]
     75    rrdArchives = []
     76    for i in range(0, len(archives)):
     77        rrdArchives += ['RRA:AVERAGE:0.5:%d:%d' % (rraSteps(archives[i]["resolution"], step), rraRows(
     78            archives[i]["duration"], archives[i]["resolution"], step))]
     79
     80    if not os.path.isfile(databaseFile):
     81        rrdtool.create(databaseFile,
     82                       "--start",
     83                       "N",
     84                       "--step",
     85                       str(step),
     86                       rrdDataSources,
     87                       rrdArchives)
     88
    8489
    8590def checkShutdownRequest(shutdownFile):
    86   global shutdownRequested
    87   # have look for new shutdown requests
    88   if os.path.isfile(shutdownFile):
    89     with open(shutdownFile, "r") as fileHandler:
    90       shutdownStart = fileHandler.read().strip()
    91     os.remove(shutdownFile)
    92     shutdownRequested = dateutil.parser.parse(shutdownStart)
    93   # check existing shutdown requests
    94   if shutdownRequested is not None:
    95     currentTime = datetime.datetime.now()
    96     currentTime = currentTime.replace(tzinfo=pytz.utc)
    97     if (currentTime - shutdownRequested) > datetime.timedelta(seconds = 0):
    98       os.system("sudo shutdown -h now")
     91    global shutdownRequested
     92    # have look for new shutdown requests
     93    if os.path.isfile(shutdownFile):
     94        with open(shutdownFile, "r") as fileHandler:
     95            shutdownStart = fileHandler.read().strip()
     96        os.remove(shutdownFile)
     97        shutdownRequested = dateutil.parser.parse(shutdownStart)
     98    # check existing shutdown requests
     99    if shutdownRequested is not None:
     100        currentTime = datetime.datetime.now()
     101        currentTime = currentTime.replace(tzinfo=pytz.utc)
     102        if (currentTime - shutdownRequested) > datetime.timedelta(seconds=0):
     103            os.system("sudo shutdown -h now")
     104
    99105
    100106def usage():
    101   print "Usage of gnuboat daemon:"
    102   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]"
    103   print ""
    104   print "  -h --help              Display this help"
    105   print "  -r --rrdfile           Path to the rrd database used by the webservice to serve the clients"
    106   print "  -s --shutdownfile      Path to the shutdown request file, used by the webservice to request a shutdown of the system running gnuboat"
    107   print "  -l --logperiod         Time in seconds to update the logs"
    108   print "  -d --displayperiod     Timein seconds to update the display"
    109   print "  -o --output            File where the NMEA1983 log is stored"
     107    print "Usage of gnuboat daemon:"
     108    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]"
     109    print ""
     110    print "  -h --help              Display this help"
     111    print "  -r --rrdfile           Path to the rrd database used by the webservice to serve the clients"
     112    print "  -s --shutdownfile      Path to the shutdown request file, used by the webservice to request a shutdown of the system running gnuboat"
     113    print "  -l --logperiod         Time in seconds to update the logs"
     114    print "  -d --displayperiod     Timein seconds to update the display"
     115    print "  -o --output            File where the NMEA1983 log is stored"
     116
    110117
    111118def main(argv):
    112   global rrdfile
    113   global shutdownfile
    114   global logperiod
    115   global displayperiod
    116   global logfile
    117   global nmeafile
    118  
    119   try:                               
    120     opts, args = getopt.getopt(argv, "hr:s:l:d:o:", ["help", "rrdfile=", "shutdownfile=", "logperiod=", "displayperiod=", "output="])
    121   except getopt.GetoptError:           
    122     usage()                         
    123     sys.exit(2)
    124 
    125   for option, argument in opts:
    126     if option == ("-h", "--help"):
    127       usage()
    128       sys.exit()
    129     elif option in ("-r", "--rrdfile"):
    130        rrdfile = argument
    131     elif option in ("-s", "--shutdownfile"):
    132       shutdownfile = argument
    133     elif option in ("-l", "--logperiod"):
    134       logperiod = argument
    135     elif option in ("-d", "--displayperiod"):
    136       displayperiod = argument
    137     elif option in ("-o", "--output"):
    138       logfile = argument
    139     else:
    140       assert False, "unhandled option"
    141 
    142   if not os.path.exists(os.path.dirname(rrdfile)):
    143     print "rrd database directory not found %s" % os.path.dirname(rrdfile)
    144     print ""
    145     usage()
    146     sys.exit(2)
    147 
    148   if not os.path.exists(os.path.dirname(shutdownfile)):
    149     print "Shutdown request directory not found %s" % os.path.dirname(shutdownfile)
    150     print ""
    151     usage()
    152     sys.exit(2)
    153 
    154   if logperiod < 1:
    155     print "Log period must be >= 1"
    156     print ""
    157     usage()
    158     sys.exit(2)
    159 
    160   if displayperiod < 1 or displayperiod < logperiod:
    161     print "Display period must be >= 1 and could not be faster than log period"
    162     print ""
    163     usage()
    164     sys.exit(2)
    165 
    166   createDatabase(rrdfile)
    167 
    168   try:
    169     nmeafile = open(logfile, 'a', 0)
    170   except IOError as error:
    171     print "Could not open the logfile: %s" % error
    172     sys.exit(2)
    173 
    174   displayHandler = daemon.DisplayHandler(displayperiod)
    175 
    176   gpsp = daemon.GpsdPoller(logperiod)
    177   n2kd = daemon.N2kdPoller(logperiod)
    178   try:
    179     gpsp.start()
    180     n2kd.start()
    181     while True:
    182       # In the main thread, every logPeriod seconds print the current value
    183       time.sleep(logperiod)
    184       latitude = gpsp.latitude()
    185       longitude = gpsp.longitude()
    186       speedThroughWater = n2kd.speedThroughWater()
    187       speedOverGround = gpsp.speedOverGround()
    188       waterDepth = n2kd.waterDepth()
    189       waterTemperature = n2kd.waterTemperature()
    190       gpsFix = gpsp.gpsFix()
    191            
    192       # update rrd database for the webservice
    193       rrdtool.update(rrdfile, "N:%s:%s:%s:%s:%s:%s:%s" % (latitude, longitude, speedThroughWater, speedOverGround, waterDepth, waterTemperature, gpsFix))
    194      
    195       # append to log
    196       if gpsp.gpsFix() >= 2:
    197         timeUtc = gpsp.timeUtc()
    198         status = gpsp.status()
    199         latitudeDirection = gpsp.latitudeDirection()
    200         longitudeDirection = gpsp.longitudeDirection()
    201         courseOverGround = gpsp.courseOverGround()
    202        
    203         mode = 'N'
    204         if gpsFix >= 2:
    205           mode = 'A'
    206        
    207         nmeafile.write("%s\r\n" % str(pynmea2.RMC('GN', 'RMC',
    208                       ( timeUtc.strftime("%H%M%S"), status, '$%04.3f' % latitude,
    209                         latitudeDirection, '$%05.3f' % longitude, longitudeDirection,
    210                         '$%02.1f' % speedOverGround, '$%02.1f' % courseOverGround,
    211                         timeUtc.strftime("%d%m%y"), '', '', mode ))))
    212         if n2kd.waterDepthValid():
    213           nmeafile.write("%\r\n" % str(pynmea2.DPT('SD', 'DPT',
    214                         ( '%02.2f' % waterDepth, '00.00' ))))
    215      
    216       # display data
    217       displayHandler.setValues(speedThroughWater, speedOverGround, waterDepth, waterTemperature, gpsFix)
    218      
    219       #check for shutdown request
    220       checkShutdownRequest(shutdownfile)
    221        
    222   except (KeyboardInterrupt, SystemExit): #when you press ctrl+c
    223     if nmeafile:
    224       nmeafile.close()
    225     if gpsp.ident is not None:
    226       gpsp.stop()
    227       gpsp.join() # wait for the thread to finish what it's doing
    228     if n2kd.ident is not None:
    229       n2kd.stop()
    230       n2kd.join()
    231     if displayHandler.ident is not None:
    232       displayHandler.stop()
    233       displayHandler.join() # wait for the thread to finish what it's doing
     119    global rrdfile
     120    global shutdownfile
     121    global logperiod
     122    global displayperiod
     123    global logfile
     124    global nmeafile
     125
     126    try:
     127        opts, args = getopt.getopt(argv, "hr:s:l:d:o:", [
     128                                   "help", "rrdfile=", "shutdownfile=", "logperiod=", "displayperiod=", "output="])
     129    except getopt.GetoptError:
     130        usage()
     131        sys.exit(2)
     132
     133    for option, argument in opts:
     134        if option == ("-h", "--help"):
     135            usage()
     136            sys.exit()
     137        elif option in ("-r", "--rrdfile"):
     138            rrdfile = argument
     139        elif option in ("-s", "--shutdownfile"):
     140            shutdownfile = argument
     141        elif option in ("-l", "--logperiod"):
     142            logperiod = argument
     143        elif option in ("-d", "--displayperiod"):
     144            displayperiod = argument
     145        elif option in ("-o", "--output"):
     146            logfile = argument
     147        else:
     148            assert False, "unhandled option"
     149
     150    if not os.path.exists(os.path.dirname(rrdfile)):
     151        print "rrd database directory not found %s" % os.path.dirname(rrdfile)
     152        print ""
     153        usage()
     154        sys.exit(2)
     155
     156    if not os.path.exists(os.path.dirname(shutdownfile)):
     157        print "Shutdown request directory not found %s" % os.path.dirname(shutdownfile)
     158        print ""
     159        usage()
     160        sys.exit(2)
     161
     162    if logperiod < 1:
     163        print "Log period must be >= 1"
     164        print ""
     165        usage()
     166        sys.exit(2)
     167
     168    if displayperiod < 1 or displayperiod < logperiod:
     169        print "Display period must be >= 1 and could not be faster than log period"
     170        print ""
     171        usage()
     172        sys.exit(2)
     173
     174    createDatabase(rrdfile)
     175
     176    try:
     177        nmeafile = open(logfile, 'a', 0)
     178    except IOError as error:
     179        print "Could not open the logfile: %s" % error
     180        sys.exit(2)
     181
     182    displayHandler = daemon.DisplayHandler(displayperiod)
     183
     184    gpsp = daemon.GpsdPoller(logperiod)
     185    n2kd = daemon.N2kdPoller(logperiod)
     186    try:
     187        gpsp.start()
     188        n2kd.start()
     189        while True:
     190            # In the main thread, every logPeriod seconds print the current
     191            # value
     192            time.sleep(logperiod)
     193            latitude = gpsp.latitude()
     194            longitude = gpsp.longitude()
     195            speedThroughWater = n2kd.speedThroughWater()
     196            speedOverGround = gpsp.speedOverGround()
     197            waterDepth = n2kd.waterDepth()
     198            waterTemperature = n2kd.waterTemperature()
     199            gpsFix = gpsp.gpsFix()
     200
     201            # update rrd database for the webservice
     202            rrdtool.update(rrdfile, "N:%s:%s:%s:%s:%s:%s:%s" % (
     203                latitude, longitude, speedThroughWater, speedOverGround, waterDepth, waterTemperature, gpsFix))
     204
     205            # append to log
     206            if gpsp.gpsFix() >= 2:
     207                timeUtc = gpsp.timeUtc()
     208                status = gpsp.status()
     209                latitudeDirection = gpsp.latitudeDirection()
     210                longitudeDirection = gpsp.longitudeDirection()
     211                courseOverGround = gpsp.courseOverGround()
     212
     213                mode = 'N'
     214                if gpsFix >= 2:
     215                    mode = 'A'
     216
     217                nmeafile.write("%s\r\n" % str(pynmea2.RMC('GN', 'RMC',
     218                                                          (timeUtc.strftime("%H%M%S"), status, '$%04.3f' % latitude,
     219                                                           latitudeDirection, '$%05.3f' % longitude, longitudeDirection,
     220                                                           '$%02.1f' % speedOverGround, '$%02.1f' % courseOverGround,
     221                                                           timeUtc.strftime("%d%m%y"), '', '', mode))))
     222                if n2kd.waterDepthValid():
     223                    nmeafile.write("%\r\n" % str(pynmea2.DPT('SD', 'DPT',
     224                                                             ('%02.2f' % waterDepth, '00.00'))))
     225
     226            # display data
     227            displayHandler.setValues(
     228                speedThroughWater, speedOverGround, waterDepth, waterTemperature, gpsFix)
     229
     230            # check for shutdown request
     231            checkShutdownRequest(shutdownfile)
     232
     233    except (KeyboardInterrupt, SystemExit):  # when you press ctrl+c
     234        if nmeafile:
     235            nmeafile.close()
     236        if gpsp.ident is not None:
     237            gpsp.stop()
     238            gpsp.join()  # wait for the thread to finish what it's doing
     239        if n2kd.ident is not None:
     240            n2kd.stop()
     241            n2kd.join()
     242        if displayHandler.ident is not None:
     243            displayHandler.stop()
     244            # wait for the thread to finish what it's doing
     245            displayHandler.join()
    234246
    235247if __name__ == "__main__":
    236   main(sys.argv[1:])
     248    main(sys.argv[1:])
  • src/python/bin/gnuboat-splashscreen

    r1efcac7 r6f09609  
    2121import getopt
    2222try:
    23   from PIL import Image
    24   from PIL import ImageOps
    25   from EPD import EPD
    26   epdEnabled = True
     23    from PIL import Image
     24    from PIL import ImageOps
     25    from EPD import EPD
     26    epdEnabled = True
    2727except:
    28   epdEnabled = False
     28    epdEnabled = False
     29
    2930
    3031def displayImage(epd, imageFilePath):
    31   image = Image.open(imageFilePath)
    32   image = ImageOps.grayscale(image)
    33   imageResized = image.resize((epd.width, epd.height))
    34   imageBlackWhite = imageResized.convert("1", dither=Image.FLOYDSTEINBERG)
    35   epd.display(imageBlackWhite)
    36   epd.update()
     32    image = Image.open(imageFilePath)
     33    image = ImageOps.grayscale(image)
     34    imageResized = image.resize((epd.width, epd.height))
     35    imageBlackWhite = imageResized.convert("1", dither=Image.FLOYDSTEINBERG)
     36    epd.display(imageBlackWhite)
     37    epd.update()
     38
    3739
    3840def usage():
    39   print "Usage of gnuboat-splashscreen:"
    40   print "  gnuboat-splashscreen [-h] -i PATH_TO_IMAGE_TO_DISPLAY"
    41   print ""
    42   print "  -h --help    Print this help"
    43   print "  -i --image   Path to the image, which should be displayed"
    44   sys.exit()
     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"
     46    sys.exit()
    4547
    46 def main(argv):                     
    47   image = ""                 
    48   try:                               
    49     opts, args = getopt.getopt(argv, "hi:", ["help", "image="])
    50   except getopt.GetoptError:           
    51     usage()                         
    52     sys.exit(2)
    5348
    54   for option, argument in opts:
    55     if option == ("-h", "--help"):
    56       usage()
    57       sys.exit()
    58     elif option in ("-i", "--image"):
    59        image = argument
    60     else:
    61       assert False, "unhandled option"
     49def main(argv):
     50    image = ""
     51    try:
     52        opts, args = getopt.getopt(argv, "hi:", ["help", "image="])
     53    except getopt.GetoptError:
     54        usage()
     55        sys.exit(2)
    6256
    63   if not os.path.exists(image):
    64     print "Image %s not found" % image
    65     print ""
    66     usage()
    67     sys.exit(2)
     57    for option, argument in opts:
     58        if option == ("-h", "--help"):
     59            usage()
     60            sys.exit()
     61        elif option in ("-i", "--image"):
     62            image = argument
     63        else:
     64            assert False, "unhandled option"
    6865
    69   if not epdEnabled:
    70     print "Could not initialize EPD or PIL python packages"
    71     sys.exit(2)
     66    if not os.path.exists(image):
     67        print "Image %s not found" % image
     68        print ""
     69        usage()
     70        sys.exit(2)
    7271
    73   epd = EPD()
    74   epd.clear()
    75   displayImage(epd, image)
     72    if not epdEnabled:
     73        print "Could not initialize EPD or PIL python packages"
     74        sys.exit(2)
     75
     76    epd = EPD()
     77    epd.clear()
     78    displayImage(epd, image)
    7679
    7780if __name__ == "__main__":
    78   main(sys.argv[1:])
     81    main(sys.argv[1:])
Note: See TracChangeset for help on using the changeset viewer.