#!/usr/bin/python
'''
    Copyright (C) 2016 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''

import rrdtool
import random
import gps
import time
import threading
import os.path

rrdFile = "/home/jlan11/public_html/gnuboat/webservice/data/log-webservice.rrd"
logPeriod = 1

# Copied from https://gist.github.com/wolfg1969/4653340
class GpsdPoller(threading.Thread):
  def __init__(self):
    threading.Thread.__init__(self)
    self._session = gps.gps(mode=gps.WATCH_ENABLE)
    self._currentValue = None
    self._running = True

  def latitude(self):
    return self._session.fix.latitude
   
  def longitude(self):
    return self._session.fix.longitude

  def speedOverGround(self):
    return self._session.fix.speed
   
  def gpsFix(self):
    return self._session.fix.mode
   
  def stop(self):
    self._running = False
   
  def run(self):
    try:
      while self._running:
        self._currentValue = self._session.next()
        time.sleep(float(logPeriod)/2.0)
    except StopIteration:
      pass

def createDatabase(databaseFile)
  rrdDataSources = [ 'DS:latitude:GAUGE:15:-90:90',
                     'DS:longitude:GAUGE:15:-180:180',
                     'DS:speedthroughwater:GAUGE:15:U:U',
                     'DS:speedoverground:GAUGE:15:U:U',
                     'DS:waterdepth:GAUGE:15:0:10000',
                     'DS:watertemperature:GAUGE:15:-10:50',
                     'DS:gpsfix:GAUGE:15:-999:3' ]

  rrdArchives = [ 'RRA:AVERAGE:0.5:1:60',
                  'RRA:AVERAGE:0.5:5:720',
                  'RRA:AVERAGE:0.5:15:1440',
                  'RRA:AVERAGE:0.5:30:1440',
                  'RRA:AVERAGE:0.5:60:1440' ]

  if not os.path.isfile(databaseFile):
    rrdtool.create(rrdFile,
                   "--start",
                   "N",
                   "--step",
                   "1",
                   rrdDataSources,
                   rrdArchives)

if __name__ == '__main__':
  createDatabase(rrdFile)

  gpsp = GpsdPoller()
  try:
    gpsp.start()
    print "Collecting data..."
    # gpsp now polls every .2 seconds for new data, storing it in self.current_value
    while True:
      # In the main thread, every 5 seconds print the current value
      time.sleep(logPeriod)
      latitude = gpsp.latitude()
      longitude = gpsp.longitude()
      speedThroughWater = random.randrange(0, 10)
      speedOverGround = gpsp.speedOverGround()
      waterDepth = random.randrange(1, 30) + 0.5;
      waterTemperature = random.randrange(15, 25) + 0.5;
      gpsFix = gpsp.gpsFix()
      rrdtool.update(rrdFile, "N:%s:%s:%s:%s:%s:%s:%s" % (latitude, longitude, speedThroughWater, speedOverGround, waterDepth, waterTemperature, gpsFix))
       
  except (KeyboardInterrupt, SystemExit): #when you press ctrl+c
    print "\nKilling Thread..."
    gpsp.stop()
    gpsp.join() # wait for the thread to finish what it's doing
  print "Done.\nExiting."
