Changeset 37d2e9d


Ignore:
Timestamp:
Aug 6, 2017, 4:14:09 PM (9 years ago)
Author:
Joachim Langenbach <joachim.langenbach@…>
Branches:
debian/bullseye, debian/jessie
Children:
ed8bca8
Parents:
e715793 (diff), 6f09609 (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.
git-author:
Joachim Langenbach <joachim.langenbach@…> (08/06/17 15:54:08)
git-committer:
Joachim Langenbach <joachim.langenbach@…> (08/06/17 16:14:09)
Message:

Merge branch 'master' into debian/jessie

Files:
1 deleted
9 edited
1 moved

Legend:

Unmodified
Added
Removed
  • .gitignore

    re715793 r37d2e9d  
    44
    55# Setuptools distribution folder.
    6 /dist/
     6dist/
    77
    88# Python egg metadata, regenerated from source files by setuptools.
    9 /*.egg-info
     9*.egg-info
  • debian/control

    re715793 r37d2e9d  
    33Priority: optional
    44Maintainer: EngSaS - Joachim Langenbach <info@engsas.de>
    5 Build-Depends: debhelper (>= 9), lsb-release, dh-python, dh-systemd (>= 1.5), python-all, python3-all, python-all-dbg, python3-all-dbg, phing, php-pear
     5Build-Depends: debhelper (>= 9), lsb-release, dh-python, dh-systemd (>= 1.5), python-all, python3-all, python-all-dbg, python-rrdtool, python2-pynmea2, python3-pynmea2, python3-all-dbg, phing, php-pear
    66Standards-Version: 3.9.6
    77Homepage: https://trac.falaba.de/gnuboat
    … …  
    99Vcs-Browser: https://trac.falaba.de/gnuboat/browser
    1010X-Python-Version: >= 2.6
    11 X-Python3-Version: >= 3.2
     11#X-Python3-Version: >= 3.2
    1212
    1313Package: gnuboat-webserver
    1414Architecture: all
    15 Depends: ${misc:Depends}, php5-rrd, php5-json, php5-mysql, python2-gnuboat | python3-gnuboat
     15Depends: ${misc:Depends}, php5-rrd, php5-json, php5-mysql, python-gnuboat | python3-gnuboat
    1616Description: GNUBoat server with log daemon and webservice
    1717 The GNUBoat server drives a webservice, serving clients,
    … …  
    2424 Display data from GNUBoat server in a browser.
    2525
    26 Package: python2-gnuboat
     26Package: python-gnuboat
     27Section: python
    2728Architecture: all
    28 Depends: ${misc:Depends}, ${python:Depends}, python-pil, python-dateutil, python-tz, python-rrdtool, python-pynmea2, gpsd, n2kd-scripts, n2kd-bin
     29Depends: ${misc:Depends}, ${python:Depends}, python-pil, python-dateutil, python-tz, python-rrdtool, python2-pynmea2, gpsd, n2kd-scripts, n2kd-bin, gnuboat-daemon-config
    2930Recommends: python-epd
    3031Description: GNUBoat logging daemon
    … …  
    3233 the display.
    3334
    34 Package: python3-gnuboat
     35#Package: python3-gnuboat
     36#Section: python
     37#Architecture: all
     38#Depends: ${misc:Depends}, ${python3:Depends}, python3-pil, python3-dateutil, python3-tz, python3-rrdtool, python3-pynmea2, gpsd, n2kd-scripts, n2kd-bin, gnuboat-daemon-config
     39#Recommends: python-epd
     40#Description: GNUBoat logging daemon
     41# The GNUBoat daemon provides a daemon to collect data, optionally drives
     42# the display.
     43
     44Package: gnuboat-daemon-config
     45Depends: ${misc:Depends}
    3546Architecture: all
    36 Depends: ${misc:Depends}, ${python:Depends}, python-pil, python-dateutil, python-tz, python-rrdtool, python-pynmea2, gpsd, n2kd-scripts, n2kd-bin
    37 Recommends: python-epd
    38 Description: GNUBoat logging daemon
     47Recommends: python-gnuboat | python3-gnuboat
     48Description: GNUBoat logging daemon config files
    3949 The GNUBoat daemon provides a daemon to collect data, optionally drives
    4050 the display.
     51 .
     52 This package installs the needed config files.
    4153
    4254Package: gnuboat-puppet
    … …  
    5466 This package adds the gnuboat repository and the
    5567 needed trusted keyring to apt.
    56  .
    5768
  • debian/gnuboat-jessie.postinst

    re715793 r37d2e9d  
    11#!/bin/bash
     2
     3set -e
    24
    35# Set up any specific permissions needed...
  • setup.py

    re715793 r37d2e9d  
    2020from setuptools import setup, find_packages
    2121
    22 def read(fname):
    23   return open(os.path.join(os.path.dirname(__file__), fname)).read()
     22readme = open('src/python/README', 'r')
     23README_TEXT = readme.read()
     24readme.close()
    2425
    2526setup(
    26   name = "gnuboat",
    27   version = "0.4.0",
    28   maintainer = "EngSaS - Langenbach",
    29   maintainer_email = "info@engsas.de",
    30   description = ("Tools to run gnuboat daemon"),
    31   license = "GNU General Public License v3 or later (GPLv3+)",
    32   keywords = "",
    33   url = "http://trac.falaba.de/gnuboat",
     27  name="gnuboat",
     28  version="0.4.6",
     29  maintainer="EngSaS - Langenbach",
     30  maintainer_email="info@engsas.de",
     31  description=("Tools to run gnuboat daemon"),
     32  license="GNU General Public License v3 or later (GPLv3+)",
     33  keywords="",
     34  url="http://trac.falaba.de/gnuboat",
    3435  package_dir={'': 'src/python'},
    3536  packages=find_packages("src/python"),
    3637  scripts=["src/python/bin/gnuboat", "src/python/bin/gnuboat-splashscreen"],
    37   long_description=read('src/python/README'),
     38  long_description=README_TEXT,
    3839  install_requires=[
    3940    "rrdtool",
  • src/python/bin/gnuboat

    re715793 r37d2e9d  
    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

    re715793 r37d2e9d  
    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:])
  • src/python/gnuboat/daemon/displayhandler.py

    re715793 r37d2e9d  
    2121
    2222try:
    23   from EPD import EPD
    24   from PIL import Image
    25   from PIL import ImageDraw
    26   from PIL import ImageFont
    27   epdEnabled = True
     23    from EPD import EPD
     24    from PIL import Image
     25    from PIL import ImageDraw
     26    from PIL import ImageFont
     27    epdEnabled = True
    2828except:
    29   epdEnabled = False
     29    epdEnabled = False
    3030
    3131"""@class DisplayHandler
    3232"""
     33
     34
    3335class DisplayHandler(threading.Thread):
    34   def __init__(self, displayperiod):
    35     threading.Thread.__init__(self)
    36     try:
    37       self._epd = EPD()
    38     except:
    39       epdEnabled = False
    40       return
    41     self._epd.clear()
    42     self._updatePeriod = displayperiod
    43     self._running = True
    44     self._speedThroughWater = None
    45     self._speedOverGround = None
    46     self._waterDepth = None
    47     self._waterTemperature = None
    48     self._gpsFix = None
    49    
    50   def setSpeedThroughWater(self, speed):
    51     self._speedThroughWater = speed
    5236
    53   def setSpeedOverGround(self, speed):
    54     self._speedOverGround = speed
    55    
    56   def setWaterDepth(self, depth):
    57     self._waterDepth = depth
    58    
    59   def setWaterTemperature(self, temperature):
    60     self._waterTemperature = temperature
     37    def __init__(self, displayperiod):
     38        threading.Thread.__init__(self)
     39        try:
     40            self._epd = EPD()
     41        except:
     42            epdEnabled = False
     43            return
     44        self._epd.clear()
     45        self._updatePeriod = displayperiod
     46        self._running = True
     47        self._speedThroughWater = None
     48        self._speedOverGround = None
     49        self._waterDepth = None
     50        self._waterTemperature = None
     51        self._gpsFix = None
    6152
    62   def setGpsFix(self, fix):
    63     self._gpsFix = fix
    64    
    65   def setValues(self, speedThroughWater, speedOverGround, waterDepth, waterTemperature, gpsFix):
    66     self.setSpeedThroughWater(speedThroughWater)
    67     self.setSpeedOverGround(speedOverGround)
    68     self.setWaterDepth(waterDepth)
    69     self.setWaterTemperature(waterTemperature)
    70     self.setGpsFix(gpsFix)
     53    def setSpeedThroughWater(self, speed):
     54        self._speedThroughWater = speed
    7155
    72   def stop(self):
    73     self._running = False
    74    
    75   def run(self):
    76     if not epdEnabled:
    77       return
    78     try:
    79       while self._running:
    80         self.displayValues(self._epd, self._speedThroughWater, self._speedOverGround, self._waterDepth, self._waterTemperature, self._gpsFix)
    81         time.sleep(self._updatePeriod)
    82     except StopIteration:
    83       pass
     56    def setSpeedOverGround(self, speed):
     57        self._speedOverGround = speed
    8458
    85   def displayValues(epd, speedThroughWater, speedOverGround, waterDepth, waterTemperature, gpsFix):
    86     if not epdEnabled:
    87       return
     59    def setWaterDepth(self, depth):
     60        self._waterDepth = depth
    8861
    89     # requires dejavu package!!!!
    90     fontValues = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf', 34)
    91     fontTitles = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', 24)
     62    def setWaterTemperature(self, temperature):
     63        self._waterTemperature = temperature
    9264
    93     # initially set all white background
    94     image = Image.new('1', epd.size, WHITE)
    95     width, height = image.size
     65    def setGpsFix(self, fix):
     66        self._gpsFix = fix
    9667
    97     rowHeightTitles = 25
    98     rowHeightValues = float(height - 2 * rowHeightTitles - 3 * marginVertical) / 2.0
    99     columnWidthUnit = 30
    100     columnWidthValues = int(float(width - 3 * marginHorizontal - 2 * columnWidthUnit) / 2.0)
     68    def setValues(self, speedThroughWater, speedOverGround, waterDepth, waterTemperature, gpsFix):
     69        self.setSpeedThroughWater(speedThroughWater)
     70        self.setSpeedOverGround(speedOverGround)
     71        self.setWaterDepth(waterDepth)
     72        self.setWaterTemperature(waterTemperature)
     73        self.setGpsFix(gpsFix)
    10174
    102     draw = ImageDraw.Draw(image)
    103     # draw.rectangle((0, 0, width, height), fill=WHITE, outline=WHITE)
     75    def stop(self):
     76        self._running = False
    10477
    105     x = marginHorizontal
    106     y = marginVertical
    107     draw.text((x, y), "STW", fill=BLACK, font=fontTitles)
    108     if speedThroughWater is not None:
    109       draw.text((x, y + rowHeightTitles), str(speedThroughWater), fill=BLACK, font=fontValues)
    110     draw.text((x + columnWidthValues, y + rowHeightTitles * 1.4), "kts", fill=BLACK, font=fontTitles)
     78    def run(self):
     79        if not epdEnabled:
     80            return
     81        try:
     82            while self._running:
     83                self.displayValues(self._epd, self._speedThroughWater, self._speedOverGround,
     84                                   self._waterDepth, self._waterTemperature, self._gpsFix)
     85                time.sleep(self._updatePeriod)
     86        except StopIteration:
     87            pass
    11188
    112     x = x + marginHorizontal + columnWidthValues + columnWidthUnit
    113     draw.text((x, y), "SOG", fill=BLACK, font=fontTitles)
    114     if speedOverGround is not None:
    115       draw.text((x, y + rowHeightTitles), str(speedOverGround), fill=BLACK, font=fontValues)
    116     draw.text((x + columnWidthValues, y + rowHeightTitles * 1.4), "kts", fill=BLACK, font=fontTitles)
     89    def displayValues(epd, speedThroughWater, speedOverGround, waterDepth, waterTemperature, gpsFix):
     90        if not epdEnabled:
     91            return
    11792
    118     x = marginHorizontal
    119     y = y + rowHeightTitles + rowHeightValues + marginVertical
    120     draw.text((x, y), "Depth", fill=BLACK, font=fontTitles)
    121     if waterDepth is not None:
    122       draw.text((x, y + rowHeightTitles), str(waterDepth), fill=BLACK, font=fontValues)
    123     draw.text((x + int(float(columnWidthValues) / 1.5), y + rowHeightTitles * 1.4), "m", fill=BLACK, font=fontTitles)
     93        # requires dejavu package!!!!
     94        fontValues = ImageFont.truetype(
     95            '/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf', 34)
     96        fontTitles = ImageFont.truetype(
     97            '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', 24)
    12498
    125     x = x + marginHorizontal + columnWidthValues + columnWidthUnit
    126     draw.text((x, y), "Water", fill=BLACK, font=fontTitles)
    127     if waterTemperature is not None:
    128       draw.text((x, y + rowHeightTitles), str(waterTemperature), fill=BLACK, font=fontValues)
    129     draw.text((x + int(float(columnWidthValues) / 1.5), y + rowHeightTitles * 1.4), "C", fill=BLACK, font=fontTitles)
     99        # initially set all white background
     100        image = Image.new('1', epd.size, WHITE)
     101        width, height = image.size
    130102
    131     x = int((x + marginHorizontal + columnWidthValues) * 0.93)
    132     draw.text((x, y), "Fix", fill=BLACK, font=fontTitles)
    133     if gpsFix is not None:
    134       draw.text((x, y + rowHeightTitles), str(gpsFix), fill=BLACK, font=fontValues)
    135  
    136     epd.display(image)
    137     epd.update()
     103        rowHeightTitles = 25
     104        rowHeightValues = float(
     105            height - 2 * rowHeightTitles - 3 * marginVertical) / 2.0
     106        columnWidthUnit = 30
     107        columnWidthValues = int(
     108            float(width - 3 * marginHorizontal - 2 * columnWidthUnit) / 2.0)
     109
     110        draw = ImageDraw.Draw(image)
     111        # draw.rectangle((0, 0, width, height), fill=WHITE, outline=WHITE)
     112
     113        x = marginHorizontal
     114        y = marginVertical
     115        draw.text((x, y), "STW", fill=BLACK, font=fontTitles)
     116        if speedThroughWater is not None:
     117            draw.text(
     118                (x, y + rowHeightTitles), str(speedThroughWater), fill=BLACK, font=fontValues)
     119        draw.text((x + columnWidthValues, y + rowHeightTitles * 1.4),
     120                  "kts", fill=BLACK, font=fontTitles)
     121
     122        x = x + marginHorizontal + columnWidthValues + columnWidthUnit
     123        draw.text((x, y), "SOG", fill=BLACK, font=fontTitles)
     124        if speedOverGround is not None:
     125            draw.text((x, y + rowHeightTitles), str(speedOverGround),
     126                      fill=BLACK, font=fontValues)
     127        draw.text((x + columnWidthValues, y + rowHeightTitles * 1.4),
     128                  "kts", fill=BLACK, font=fontTitles)
     129
     130        x = marginHorizontal
     131        y = y + rowHeightTitles + rowHeightValues + marginVertical
     132        draw.text((x, y), "Depth", fill=BLACK, font=fontTitles)
     133        if waterDepth is not None:
     134            draw.text(
     135                (x, y + rowHeightTitles), str(waterDepth), fill=BLACK, font=fontValues)
     136        draw.text((x + int(float(columnWidthValues) / 1.5),
     137                   y + rowHeightTitles * 1.4), "m", fill=BLACK, font=fontTitles)
     138
     139        x = x + marginHorizontal + columnWidthValues + columnWidthUnit
     140        draw.text((x, y), "Water", fill=BLACK, font=fontTitles)
     141        if waterTemperature is not None:
     142            draw.text(
     143                (x, y + rowHeightTitles), str(waterTemperature), fill=BLACK, font=fontValues)
     144        draw.text((x + int(float(columnWidthValues) / 1.5),
     145                   y + rowHeightTitles * 1.4), "C", fill=BLACK, font=fontTitles)
     146
     147        x = int((x + marginHorizontal + columnWidthValues) * 0.93)
     148        draw.text((x, y), "Fix", fill=BLACK, font=fontTitles)
     149        if gpsFix is not None:
     150            draw.text(
     151                (x, y + rowHeightTitles), str(gpsFix), fill=BLACK, font=fontValues)
     152
     153        epd.display(image)
     154        epd.update()
    138155
    139156if __name__ == "__main__":
  • src/python/gnuboat/daemon/gpsdpoller.py

    re715793 r37d2e9d  
    2424
    2525# Copied from https://gist.github.com/wolfg1969/4653340
     26
     27
    2628class GpsdPoller(threading.Thread):
    27   def __init__(self, logperiod):
    28     threading.Thread.__init__(self)
    29     try:
    30       self._session = gps.gps(mode=gps.WATCH_ENABLE)
    31     except:
    32       self._session = None
    33       self._running = False
    34       return
    35     self._currentValue = None
    36     self._running = True
    37     self._logperiod = logperiod
    3829
    39   def latitude(self):
    40     if self._session == None or self.gpsFix() < 2:
    41       return 0
    42     return self._session.fix.latitude
    43    
    44   def latitudeDirection(self):
    45     return "N"
    46    
    47   def longitude(self):
    48     if self._session == None or self.gpsFix() < 2:
    49       return 0
    50     return self._session.fix.longitude
     30    def __init__(self, logperiod):
     31        threading.Thread.__init__(self)
     32        try:
     33            self._session = gps.gps(mode=gps.WATCH_ENABLE)
     34        except:
     35            self._session = None
     36            self._running = False
     37            return
     38        self._currentValue = None
     39        self._running = True
     40        self._logperiod = logperiod
    5141
    52   def longitudeDirection(self):
    53     return "E"
     42    def latitude(self):
     43        if self._session == None or self.gpsFix() < 2:
     44            return 0
     45        return self._session.fix.latitude
    5446
    55   def speedOverGround(self):
    56     if self._session == None or self.gpsFix() < 2:
    57       return 0
    58     return self._session.fix.speed
     47    def latitudeDirection(self):
     48        return "N"
    5949
    60   def courseOverGround(self):
    61     if self._session == None or self.gpsFix() < 2:
    62       return 0
    63     return self._session.fix.track
    64    
    65   def gpsFix(self):
    66     if self._session == None:
    67       return 0
    68     return self._session.fix.mode
     50    def longitude(self):
     51        if self._session == None or self.gpsFix() < 2:
     52            return 0
     53        return self._session.fix.longitude
    6954
    70   def status(self):
    71     if self._session == None or self.gpsFix() < 2:
    72       return "V"
    73     return "A"
     55    def longitudeDirection(self):
     56        return "E"
    7457
    75   def timeUtc(self):
    76     if self._session == None or self.gpsFix() < 2:
    77       return None
    78     currentTime = self._session.fix.time
    79     if isinstance(currentTime, float):
    80       return datetime.datetime.fromtimestamp(currentTime)
    81     return dateutil.parser.parse(self._session.fix.time)
     58    def speedOverGround(self):
     59        if self._session == None or self.gpsFix() < 2:
     60            return 0
     61        return self._session.fix.speed
    8262
    83   def stop(self):
    84     self._running = False
    85    
    86   def run(self):
    87     try:
    88       while self._running:
    89         self._currentValue = self._session.next()
    90         time.sleep(float(self._logperiod)/2.0)
    91     except StopIteration:
    92       pass
     63    def courseOverGround(self):
     64        if self._session == None or self.gpsFix() < 2:
     65            return 0
     66        return self._session.fix.track
     67
     68    def gpsFix(self):
     69        if self._session == None:
     70            return 0
     71        return self._session.fix.mode
     72
     73    def status(self):
     74        if self._session == None or self.gpsFix() < 2:
     75            return "V"
     76        return "A"
     77
     78    def timeUtc(self):
     79        if self._session == None or self.gpsFix() < 2:
     80            return None
     81        currentTime = self._session.fix.time
     82        if isinstance(currentTime, float):
     83            return datetime.datetime.fromtimestamp(currentTime)
     84        return dateutil.parser.parse(self._session.fix.time)
     85
     86    def stop(self):
     87        self._running = False
     88
     89    def run(self):
     90        try:
     91            while self._running:
     92                self._currentValue = self._session.next()
     93                time.sleep(float(self._logperiod) / 2.0)
     94        except StopIteration:
     95            pass
    9396
    9497if __name__ == "__main__":
  • src/python/gnuboat/daemon/n2kdpoller.py

    re715793 r37d2e9d  
    2424"""@class N2kdPoller
    2525"""
     26
     27
    2628class N2kdPoller(threading.Thread):
    27   def __init__(self, logperiod):
    28     threading.Thread.__init__(self)
    29     self._serverHost = "127.0.0.1"
    30     self._serverPort = 2597
    31     self._timeout = 1.5
    32     self._speedThroughWater = 0
    33     self._distanceLog = 0
    34     self._distanceLogTrip = 0
    35     self._waterDepth = 0
    36     self._waterDepthValid = False
    37     self._waterTemperature = 0
    38     self._running = True
    39     self._logperiod = logperiod
    40     self._connectErrorPrinted = False
    4129
    42   def speedThroughWater(self):
    43     return self._speedThroughWater
    44    
    45   def distanceLog(self):
    46     return self._distanceLog
     30    def __init__(self, logperiod):
     31        threading.Thread.__init__(self)
     32        self._serverHost = "127.0.0.1"
     33        self._serverPort = 2597
     34        self._timeout = 1.5
     35        self._speedThroughWater = 0
     36        self._distanceLog = 0
     37        self._distanceLogTrip = 0
     38        self._waterDepth = 0
     39        self._waterDepthValid = False
     40        self._waterTemperature = 0
     41        self._running = True
     42        self._logperiod = logperiod
     43        self._connectErrorPrinted = False
    4744
    48   def distanceLogTrip(self):
    49     return self._distanceLogTrip
     45    def speedThroughWater(self):
     46        return self._speedThroughWater
    5047
    51   def waterDepth(self):
    52     return self._waterDepth
     48    def distanceLog(self):
     49        return self._distanceLog
    5350
    54   def waterDepthValid(self):
    55     return self._waterDepthValid
    56    
    57   def waterTemperature(self):
    58     return self._waterTemperature
     51    def distanceLogTrip(self):
     52        return self._distanceLogTrip
    5953
    60   def _loadData(self):
    61     n2kdSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    62     n2kdSocket.settimeout(float(self._logperiod)/2.0)
    63     try:
    64       n2kdSocket.connect((self._serverHost, self._serverPort))
    65     except socket.error as error:
    66       if not self._connectErrorPrinted:
    67         print "Failed to connect to n2kd server at %s:%s: %s" % (self._serverHost, self._serverPort, error)
    68         self._connectErrorPrinted = True
    69       self._waterDepthValid = False
    70       return
    71     if self._connectErrorPrinted:
    72       print "Connected to n2kd server at %s:%s: %s" % (self._serverHost, self._serverPort, error)
    73       self._connectErrorPrinted = False
     54    def waterDepth(self):
     55        return self._waterDepth
    7456
    75     response = ""
    76     while 1:
    77       data = n2kdSocket.recv(1024)
    78       if not data:
    79         break
    80       response += data
    81     n2kdSocket.close()
    82     data = json.loads(response)
    83    
    84     descriptions = [ "Water Depth", "Speed", "Environmental Parameters", "Distance Log" ]
    85    
    86     for key in data:
    87       entryKeys = data[key].keys()
    88       if len(entryKeys) != 2:
    89         print "Malformed json n2kd response? %s" % response
    90       else:
    91         if data[key]["description"] in descriptions:
    92           entryKey = entryKeys[1]
    93           lineKeys = data[key][entryKey].keys()
    94           if "fields" not in lineKeys:
    95             print "No fields entry. Malformed json n2kd response in %s" % data[key][entryKey]
    96           else:
    97             fields = data[key][entryKey]["fields"]
    98             # try water depth (NEED TO APPLY OFFSET?)
    99             if "Depth" in fields:
    100               if data[key][entryKey]["description"] == "Water Depth":
    101                 self._waterDepth = fields["Depth"]
    102                 self._waterDepthValid = True
    103             # try speed
    104             if "Speed Water Referenced" in fields:
    105               self._speedThroughWater = fields["Speed Water Referenced"]
    106             # try sea temperature
    107             if "Temperature Source" in fields and "Temperature" in fields:
    108               if fields["Temperature Source"] == "Sea Temperature":
    109                 self._waterTemperature = fields["Temperature"]
    110             # try log
    111             if "Log" in fields:
    112               self._distanceLog = fields["Log"]
    113             if "Trip Log" in fields:
    114               self._distanceLogTrip = fields["Trip Log"]
    115              
    116   def _serverUrl(self):
    117     return "http://%s:%d/" % (self._serverHost, self._serverPort)
    118    
    119   def stop(self):
    120     self._running = False
    121    
    122   def run(self):
    123     try:
    124       while self._running:
    125         self._loadData()
    126         time.sleep(float(self._logperiod)/2.0)
    127     except StopIteration:
    128       pass
     57    def waterDepthValid(self):
     58        return self._waterDepthValid
     59
     60    def waterTemperature(self):
     61        return self._waterTemperature
     62
     63    def _loadData(self):
     64        n2kdSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     65        n2kdSocket.settimeout(float(self._logperiod) / 2.0)
     66        try:
     67            n2kdSocket.connect((self._serverHost, self._serverPort))
     68        except socket.error as error:
     69            if not self._connectErrorPrinted:
     70                print "Failed to connect to n2kd server at %s:%s: %s" % (self._serverHost, self._serverPort, error)
     71                self._connectErrorPrinted = True
     72            self._waterDepthValid = False
     73            return
     74        if self._connectErrorPrinted:
     75            print "Connected to n2kd server at %s:%s: %s" % (self._serverHost, self._serverPort, error)
     76            self._connectErrorPrinted = False
     77
     78        response = ""
     79        while 1:
     80            data = n2kdSocket.recv(1024)
     81            if not data:
     82                break
     83            response += data
     84        n2kdSocket.close()
     85        data = json.loads(response)
     86
     87        descriptions = [
     88            "Water Depth", "Speed", "Environmental Parameters", "Distance Log"]
     89
     90        for key in data:
     91            entryKeys = data[key].keys()
     92            if len(entryKeys) != 2:
     93                print "Malformed json n2kd response? %s" % response
     94            else:
     95                if data[key]["description"] in descriptions:
     96                    entryKey = entryKeys[1]
     97                    lineKeys = data[key][entryKey].keys()
     98                    if "fields" not in lineKeys:
     99                        print "No fields entry. Malformed json n2kd response in %s" % data[key][entryKey]
     100                    else:
     101                        fields = data[key][entryKey]["fields"]
     102                        # try water depth (NEED TO APPLY OFFSET?)
     103                        if "Depth" in fields:
     104                            if data[key][entryKey]["description"] == "Water Depth":
     105                                self._waterDepth = fields["Depth"]
     106                                self._waterDepthValid = True
     107                        # try speed
     108                        if "Speed Water Referenced" in fields:
     109                            self._speedThroughWater = fields[
     110                                "Speed Water Referenced"]
     111                        # try sea temperature
     112                        if "Temperature Source" in fields and "Temperature" in fields:
     113                            if fields["Temperature Source"] == "Sea Temperature":
     114                                self._waterTemperature = fields["Temperature"]
     115                        # try log
     116                        if "Log" in fields:
     117                            self._distanceLog = fields["Log"]
     118                        if "Trip Log" in fields:
     119                            self._distanceLogTrip = fields["Trip Log"]
     120
     121    def _serverUrl(self):
     122        return "http://%s:%d/" % (self._serverHost, self._serverPort)
     123
     124    def stop(self):
     125        self._running = False
     126
     127    def run(self):
     128        try:
     129            while self._running:
     130                self._loadData()
     131                time.sleep(float(self._logperiod) / 2.0)
     132        except StopIteration:
     133            pass
    129134
    130135if __name__ == "__main__":
Note: See TracChangeset for help on using the changeset viewer.