Changeset 2cf9b0b for src/daemon


Ignore:
Timestamp:
Jul 21, 2016, 8:27:37 AM (10 years ago)
Author:
Joachim Langenbach <joachim.langenbach@…>
Branches:
0.5, app-cordova, debian/bullseye, debian/jessie, master
Children:
d9af413, fefafdf
Parents:
1d2acb7 (diff), 09adf3e (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:

Pulled upstream

Merge branch 'master' of ​https://svn.falaba.de/gnuboat

Location:
src/daemon
Files:
1 added
1 edited

Legend:

Unmodified
Added
Removed
  • src/daemon/gnuboat

    r1d2acb7 r2cf9b0b  
    11#!/usr/bin/python
     2# -*- coding: utf-8 -*-
    23'''
    34    Copyright (C) 2016 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
    … …  
    2223import time
    2324import threading
    24 import os.path
    25 
    26 rrdFile = "/home/jlan11/public_html/gnuboat/webservice/data/log-webservice.rrd"
    27 logPeriod = 1
     25import re
     26import os
     27import dateutil.parser
     28import datetime
     29from pytz import timezone
     30import pytz
     31import getopt
     32import sys
     33from EPD import EPD
     34from PIL import Image
     35from PIL import ImageDraw
     36from PIL import ImageFont
     37
     38WHITE=1
     39BLACK=0
     40marginVertical = 10
     41marginHorizontal = marginVertical
     42
     43# default values for command line arguments
     44rrdfile = "/var/www/html/webservice/data/log-webservice.rrd"
     45shutdownfile = "/var/spool/gnuboat/shutdown.request"
     46logperiod = 1
     47displayperiod = 5
     48
     49shutdownRequested = None
    2850
    2951# Copied from https://gist.github.com/wolfg1969/4653340
    … …  
    5173   
    5274  def run(self):
     75    global logperiod
    5376    try:
    5477      while self._running:
    5578        self._currentValue = self._session.next()
    56         time.sleep(float(logPeriod)/2.0)
     79        time.sleep(float(logperiod)/2.0)
    5780    except StopIteration:
    5881      pass
    5982
    60 def createDatabase(databaseFile)
     83def createDatabase(databaseFile):
    6184  rrdDataSources = [ 'DS:latitude:GAUGE:15:-90:90',
    6285                     'DS:longitude:GAUGE:15:-180:180',
    … …  
    7497
    7598  if not os.path.isfile(databaseFile):
    76     rrdtool.create(rrdFile,
     99    rrdtool.create(databaseFile,
    77100                   "--start",
    78101                   "N",
    … …  
    82105                   rrdArchives)
    83106
    84 if __name__ == '__main__':
    85   createDatabase(rrdFile)
     107def displayValues(epd, speedThroughWater, speedOverGround, waterDepth, waterTemperature, gpsFix):
     108  # requires dejavu package!!!!
     109  fontValues = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf', 34)
     110  fontTitles = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', 24)
     111
     112  # initially set all white background
     113  image = Image.new('1', epd.size, WHITE)
     114  width, height = image.size
     115
     116  rowHeightTitles = 25
     117  rowHeightValues = float(height - 2 * rowHeightTitles - 3 * marginVertical) / 2.0
     118  columnWidthUnit = 30
     119  columnWidthValues = int(float(width - 3 * marginHorizontal - 2 * columnWidthUnit) / 2.0)
     120
     121  draw = ImageDraw.Draw(image)
     122  # draw.rectangle((0, 0, width, height), fill=WHITE, outline=WHITE)
     123
     124  x = marginHorizontal
     125  y = marginVertical
     126  draw.text((x, y), "STW", fill=BLACK, font=fontTitles)
     127  draw.text((x, y + rowHeightTitles), str(speedThroughWater), fill=BLACK, font=fontValues)
     128  draw.text((x + columnWidthValues, y + rowHeightTitles * 1.4), "kts", fill=BLACK, font=fontTitles)
     129
     130  x = x + marginHorizontal + columnWidthValues + columnWidthUnit
     131  draw.text((x, y), "SOG", fill=BLACK, font=fontTitles)
     132  draw.text((x, y + rowHeightTitles), str(speedOverGround), fill=BLACK, font=fontValues)
     133  draw.text((x + columnWidthValues, y + rowHeightTitles * 1.4), "kts", fill=BLACK, font=fontTitles)
     134
     135  x = marginHorizontal
     136  y = y + rowHeightTitles + rowHeightValues + marginVertical
     137  draw.text((x, y), "Depth", fill=BLACK, font=fontTitles)
     138  draw.text((x, y + rowHeightTitles), str(waterDepth), fill=BLACK, font=fontValues)
     139  draw.text((x + int(float(columnWidthValues) / 1.5), y + rowHeightTitles * 1.4), "m", fill=BLACK, font=fontTitles)
     140
     141  x = x + marginHorizontal + columnWidthValues + columnWidthUnit
     142  draw.text((x, y), "Water", fill=BLACK, font=fontTitles)
     143  draw.text((x, y + rowHeightTitles), str(waterTemperature), fill=BLACK, font=fontValues)
     144  draw.text((x + int(float(columnWidthValues) / 1.5), y + rowHeightTitles * 1.4), "C", fill=BLACK, font=fontTitles)
     145
     146  x = int((x + marginHorizontal + columnWidthValues) * 0.93)
     147  draw.text((x, y), "Fix", fill=BLACK, font=fontTitles)
     148  draw.text((x, y + rowHeightTitles), str(gpsFix), fill=BLACK, font=fontValues)
     149 
     150  epd.display(image)
     151  epd.update()
     152
     153def checkShutdownRequest(shutdownFile):
     154  global shutdownRequested
     155  # have look for new shutdown requests
     156  if os.path.isfile(shutdownFile):
     157    with open(shutdownFile, "r") as fileHandler:
     158      shutdownStart = fileHandler.read().strip()
     159    os.remove(shutdownFile)
     160    shutdownRequested = dateutil.parser.parse(shutdownStart)
     161  # check existing shutdown requests
     162  if shutdownRequested is not None:
     163    currentTime = datetime.datetime.now()
     164    currentTime = currentTime.replace(tzinfo=pytz.utc)
     165    if (currentTime - shutdownRequested) > datetime.timedelta(seconds = 0):
     166      os.system("sudo shutdown -h now")
     167
     168def usage():
     169  print "Usage of gnuboat daemon:"
     170  print "  gnuboat -r PATH_TO_RRD_DATABAE_FILE -s PATH_TO_SHUTDOWN_REQUEST_FILE [-l [LOG_UPDATE_PERIOD] [-d DISPLAY_UPDATE_PERIOD]"
     171  print ""
     172  print "  -h --help              Display this help"
     173  print "  -r --rrdfile           Path to the rrd database used by the webservice to serve the clients"
     174  print "  -s --shutdownfile      Path to the shutdown request file, used by the webservice to request a shutdown of the system running gnuboat"
     175  print "  -l --logperiod         Time in seconds to update the logs"
     176  print "  -d --displayperiod     Timein seconds to update the display"
     177
     178def main(argv):
     179  global rrdfile
     180  global shutdownfile
     181  global logperiod
     182  global displayperiod
     183
     184  try:                               
     185    opts, args = getopt.getopt(argv, "hr:s:l:d:", ["help", "rrdfile=", "shutdownfile=", "logperiod=", "displayperiod="])
     186  except getopt.GetoptError:           
     187    usage()                         
     188    sys.exit(2)
     189
     190  for option, argument in opts:
     191    if option == ("-h", "--help"):
     192      usage()
     193      sys.exit()
     194    elif option in ("-r", "--rrdfile"):
     195       rrdfile = argument
     196    elif option in ("-s", "--shutdownfile"):
     197      shutdownfile = argument
     198    elif option in ("-l", "--logperiod"):
     199      logperiod = argument
     200    elif option in ("-d", "--displayperiod"):
     201      displayperiod = argument
     202    else:
     203      assert False, "unhandled option"
     204
     205  if not os.path.exists(os.path.dirname(rrdfile)):
     206    print "rrd database directory not found %s" % os.path.dirname(rrdfile)
     207    print ""
     208    usage()
     209    sys.exit(2)
     210
     211  if not os.path.exists(os.path.dirname(shutdownfile)):
     212    print "Shutdown request directory not found %s" % os.path.dirname(shutdownfile)
     213    print ""
     214    usage()
     215    sys.exit(2)
     216
     217  if logperiod < 1:
     218    print "Log period must be >= 1"
     219    print ""
     220    usage()
     221    sys.exit(2)
     222
     223  if displayperiod < 1 or displayperiod < logperiod:
     224    print "Display period must be >= 1 and could not be faster than log period"
     225    print ""
     226    usage()
     227    sys.exit(2)
     228
     229  createDatabase(rrdfile)
     230
     231  epd = EPD()
     232  epd.clear()
    86233
    87234  gpsp = GpsdPoller()
    88235  try:
    89236    gpsp.start()
    90     print "Collecting data..."
    91237    # gpsp now polls every .2 seconds for new data, storing it in self.current_value
    92238    while True:
    93       # In the main thread, every 5 seconds print the current value
    94       time.sleep(logPeriod)
     239      # In the main thread, every logPeriod seconds print the current value
     240      time.sleep(logperiod)
    95241      latitude = gpsp.latitude()
    96242      longitude = gpsp.longitude()
    … …  
    100246      waterTemperature = random.randrange(15, 25) + 0.5;
    101247      gpsFix = gpsp.gpsFix()
    102       rrdtool.update(rrdFile, "N:%s:%s:%s:%s:%s:%s:%s" % (latitude, longitude, speedThroughWater, speedOverGround, waterDepth, waterTemperature, gpsFix))
     248     
     249      # update rrd database for the webservice
     250      rrdtool.update(rrdfile, "N:%s:%s:%s:%s:%s:%s:%s" % (latitude, longitude, speedThroughWater, speedOverGround, waterDepth, waterTemperature, gpsFix))
     251      # update display, if needed
     252      if round(time.time(),0) % displayperiod == 0:
     253        displayValues(epd, speedThroughWater, speedOverGround, waterDepth, waterTemperature, gpsFix)
     254      #check for shutdown request
     255      checkShutdownRequest(shutdownfile)
    103256       
    104257  except (KeyboardInterrupt, SystemExit): #when you press ctrl+c
    105     print "\nKilling Thread..."
    106258    gpsp.stop()
    107259    gpsp.join() # wait for the thread to finish what it's doing
    108   print "Done.\nExiting."
     260
     261if __name__ == "__main__":
     262  main(sys.argv[1:])
Note: See TracChangeset for help on using the changeset viewer.