Index: src/daemon/gnuboat
===================================================================
--- src/daemon/gnuboat	(revision 4ab1c0a91ed95286baef2a370dcab7a9e7d0d756)
+++ src/daemon/gnuboat	(revision 4ab1c0a91ed95286baef2a370dcab7a9e7d0d756)
@@ -0,0 +1,108 @@
+#!/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."
Index: src/webapp/webclient/css/main.css
===================================================================
--- src/webapp/webclient/css/main.css	(revision f8dfbe72eeba7737d98e56167476b6ab0a8c9391)
+++ src/webapp/webclient/css/main.css	(revision 4ab1c0a91ed95286baef2a370dcab7a9e7d0d756)
@@ -72,5 +72,5 @@
 	position: absolute;
 	top: 2mm;
-	left: 28mm;
+	left: 30mm;
 }
 
@@ -81,5 +81,5 @@
 }
 
-#display #gps {
+#display #gpsfix {
 	position: absolute;
 	top: 21mm;
@@ -90,5 +90,5 @@
 	position: absolute;
 	top: 21mm;
-	left: 28mm;
+	left: 30mm;
 }
 
Index: src/webapp/webclient/javascript/main.js
===================================================================
--- src/webapp/webclient/javascript/main.js	(revision f8dfbe72eeba7737d98e56167476b6ab0a8c9391)
+++ src/webapp/webclient/javascript/main.js	(revision 4ab1c0a91ed95286baef2a370dcab7a9e7d0d756)
@@ -21,5 +21,4 @@
 
 var map;
-var points = [];
 var polyline;
 
@@ -29,21 +28,42 @@
 
 function displayDataSet(data){
-	$("#display #speedthroughwater #value").text(data["speedthroughwater"].toString());
-	$("#display #speedoverground #value").text(data["speedoverground"].toString());
-	$("#display #waterdepth #value").text(data["waterdepth"].toString());
-	$("#display #watertemperature #value").text(Math.round(data["watertemperature"]).toString());
-	$("#display #gps #value").text(data["gpsfix"]);
+	if(!("lastvalid" in data)){
+			console.log("No last valid values given!");
+	}
+	else{
+		var lastValid = data["lastvalid"];
+		var keys = ["speedthroughwater", "speedoverground", "waterdepth", "watertemperature", "gpsfix"];
+		for(var i = 0; i < keys.length; i++){
+			var key = keys[i];
+			var value = lastValid[key];
+			if($.isNumeric(value)){
+				if(key == "watertemperature"){
+					value = Math.round(value);
+				}
+				$("#display #"+ keys[i] +" #value").text(value.toString());
+			}
+			else if(key == "gpsfix"){
+				$("#display #"+ keys[i] +" #value").text(value);
+			}
+		}
+	}
 	
-	var latitude = data["latitude"];
-	var longitude = data["longitude"];
-	if(latitude && longitude){
+	if(!("track" in data)){
+			console.log("No track given!");
+	}
+	else{
+		var track = data["track"];
+		var points = [];
+		for(var time in track){
+			points.push(new L.latLng(track[time]["latitude"], track[time]["longitude"]));
+		}
 		if(points.length > 0){
-			var lastPoint = points[points.length - 1];
-			if(lastPoint.lat != latitude || lastPoint.lng != longitude){
-				points.push(new L.latLng(latitude, longitude));
-				console.log(points);
+			if(!polyline){
+				polyline = L.polyline(points, {color: 'red'}).addTo(map);
+			}
+			else{
 				polyline.setLatLngs(points);
-				map.fitBounds(polyline.getBounds());
 			}
+			map.fitBounds(polyline.getBounds());
 		}
 	}
@@ -80,8 +100,4 @@
 		attribution: 'undefined',opacity: 0.85
 		}).addTo(map);
-		
-	points.push(new L.latLng(47.5914051, 10.710862));
-	points.push(new L.latLng(47.576667, 10.735278));
-	polyline = L.polyline(points, {color: 'red'}).addTo(map);
 }
 
Index: src/webapp/webclient/root/index.php
===================================================================
--- src/webapp/webclient/root/index.php	(revision f8dfbe72eeba7737d98e56167476b6ab0a8c9391)
+++ src/webapp/webclient/root/index.php	(revision 4ab1c0a91ed95286baef2a370dcab7a9e7d0d756)
@@ -83,5 +83,5 @@
 			<span id="value">-</span>&#176;C
 		</div>
-		<div id="gps">
+		<div id="gpsfix">
 			<h2>Fix</h2>
 			<span id="value">-</span>
Index: src/webapp/webservice/inc/Config.php
===================================================================
--- src/webapp/webservice/inc/Config.php	(revision 4ab1c0a91ed95286baef2a370dcab7a9e7d0d756)
+++ src/webapp/webservice/inc/Config.php	(revision 4ab1c0a91ed95286baef2a370dcab7a9e7d0d756)
@@ -0,0 +1,57 @@
+<?php
+/*
+    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/>.
+*/
+
+$configFile = __DIR__ ."../config/config.php";
+if(file_exists($configFile))
+	include($configFile);
+else{
+	error_log("No config file ". $configFile ." not found!");
+	$config = array();
+}
+
+/**
+ * @brief Loads the configuration from webservice/config/config.php (if file exists) and provides the settings for usage
+ */
+class Config {
+	public function __construct(){
+		global $config;
+		$this->_config = $config;
+	}
+
+	public function databaseFile(){
+		return $this->dataDirectory() ."log-webservice.rrd";
+	}
+	
+	public function dataDirectory(){
+		if(array_key_exists("datadirectory", $this->_config))
+			return addTrailingSlash($this->_config["datadirectory"]);
+		return __DIR__ ."/../data/";
+	}
+	
+	private static function addTrailingSlash($path){
+		$length = strlen($path);
+		if(substr($path, $length - 1, 1) != "/"){
+			return $path ."/";
+		}
+		return $path;
+	}
+	
+	private $_config;
+}
+
+?>
Index: src/webapp/webservice/index.php
===================================================================
--- src/webapp/webservice/index.php	(revision f8dfbe72eeba7737d98e56167476b6ab0a8c9391)
+++ src/webapp/webservice/index.php	(revision 4ab1c0a91ed95286baef2a370dcab7a9e7d0d756)
@@ -17,115 +17,107 @@
 */
 
-/**
-  * The GPSD parts are adepted from the gpsd.php script deployed with GPSD package!
-  */
+require_once(__DIR__ ."/inc/Config.php");
+$config = new Config();
+$dbFile = $config->databaseFile();
 
-$gpsdHost = "localhost";
-$gpsdPort = "2947";
+// configure roundings per value (key) and precision (value)
+$configRound = array
+(
+	"latitude" => 5,
+	"longitude" => 5,
+	"speedthroughwater" => 1,
+	"speedoverground" => 1,
+	"waterdepth" => 1,
+	"watertemperature" => 1,
+);
 
-set_time_limit(3);
-ini_set('max_execution_time', 3);
+$debug = 0;
+if(array_key_exists("debug", $_GET))
+	$debug = $_GET["debug"];
 
-function readGpsd(){
-	global $gpsdHost, $gpsdPort;
+if($debug == 0)
+	header('Content-Type: application/json');
 
-	
-	$speedOverGround = "-";
-	$gpsfix = "-";
-	$latitude = "";
-	$longitude = "";
-	$errno = "";
-	$errstr = "";
-	
-	$sock = @fsockopen($gpsdHost, $gpsdPort, $errno, $errstr, 2);
-	if(!$sock){
-		$speedOverGround = "-";
-		$gpsfix = -1; 
-	}
-	@fwrite($sock, "?WATCH={\"enable\":true}\n");
-	usleep(1000);
-	@fwrite($sock, "?POLL;\n");
-	usleep(1000);
-	for($tries = 0; $tries < 10; $tries++){
-		$response = @fread($sock, 2000); # SKY can be pretty big
-		if (preg_match('/{"class":"POLL".+}/i', $response, $m)){
-			$response = $m[0];
-			break;
+$result["lastvalid"] = array();
+$result["track"] = array();
+
+// Fetch entries of the last 12hours
+$data = rrd_fetch($dbFile, array( "AVERAGE", "--start", "-12h"));
+if($data === false){
+	echo json_encode($result);
+	$message = "Could not open rrd database ". $dbFile; 
+	if($debug > 0)
+		echo $message;
+	else
+		error_log($message);
+	exit;
+}
+
+if($debug > 2){
+	echo "<pre>";
+	var_dump($data);
+	echo "</pre>";
+}
+
+$data = $data["data"];
+
+// transform them into json format
+$i = 0;
+$lastTime = -1;
+$keys = array_keys($data);
+if(count($keys) < 0 ){
+	error_log("No keys in fetched rrd data from ". $dbFile);
+	echo json_encode("");
+	exit;
+}
+for($i = 0; $i < count($data[$keys[0]]); $i++){
+	$time = array_keys($data[$keys[0]])[$i];
+	$allValid = true;
+	$tmp = array();
+	foreach($keys as $key){
+		if($key == "gpsfix"){
+			switch($data[$key][$time]){
+				case 1:
+					$tmp[$key] = "2D";
+					break;
+				case 2:
+					$tmp[$key] = "3D";
+					break;
+				default:
+					$tmp[$key] = "-";
+			}
+		}
+		else{
+			$tmp[$key] = $data[$key][$time];
+			if(!is_numeric($tmp[$key]) || is_nan($tmp[$key])){
+				$allValid = false;
+			}
+			elseif(array_key_exists($key, $configRound) && is_integer($configRound[$key]))
+				$tmp[$key] = round($tmp[$key], $configRound[$key]);
 		}
 	}
-	@fclose($sock);
-	if(!$response){
-		$speedOverGround = "-";
-		$gpsfix = -2; 
+	// only add the timeframe to the track, if the values are valid and we had a gps fix at that time
+	if($allValid && $tmp["gpsfix"] != "-"){
+		$result["track"][$time] = $tmp;
+		$lastTime = $time;
 	}
 	else{
-		$data = json_decode($response, true);
-		if ($data['class'] != 'POLL'){
-			$speedOverGround = "-";
-			$gpsfix = -3; 
-		}
-		if(!array_key_exists('tpv', $data) && is_array($data['tpv'])){
-			$speedOverGround = "-";
-			$gpsfix = -4;
-		}
-		$tpv = $data['tpv'][0];
-
-		if(!array_key_exists('mode', $tpv)){
-			$gpsfix = -5;
-		}
-		else{
-			switch($tpv['mode']){
-				case 1:
-					$gpsfix = "2D";
-					break;
-				case 2:
-					$gpsfix = "3D";
-					break;
-				default:
-					$gpsfix = "-";
-			}
-		}
-		
-		if(!array_key_exists('speed', $tpv)){
-			$speedOverGround = "-1";
-		}
-		else{
-			$speedOverGround = $tpv['speed'];
-		}
-		
-		if(!array_key_exists('lat', $tpv)){
-			$latitude = "";
-		}
-		else{
-			$latitude = $tpv['lat'];
-		}
-		if(!array_key_exists('lon', $tpv)){
-			$longitude = "";
-		}
-		else{
-			$longitude = $tpv['lon'];
+		if($debug > 0){
+			echo "Failed <pre>";
+			var_dump($tmp);
+			echo "</pre>\n";
 		}
 	}
-	
-	return array("speedOverGround" => $speedOverGround, "gpsfix" => $gpsfix, "latitude" => $latitude, "longitude" => $longitude);
+}
+if($lastTime > -1){
+	$result["lastvalid"] = $result["track"][$lastTime];
 }
 
-
-
-mt_srand((double) microtime() * 1000000);
-
-$result = array();
-
-$gpsdResult = readGpsd();
-
-$result["speedthroughwater"] = mt_rand(0, 10);
-$result["speedoverground"] = $gpsdResult["speedOverGround"];
-$result["waterdepth"] = mt_rand(1, 30) + 0.5;
-$result["watertemperature"] = mt_rand(15, 25) + 0.5;
-$result["gpsfix"] = $gpsdResult["gpsfix"];
-$result["latitude"] = $gpsdResult["latitude"];
-$result["longitude"] = $gpsdResult["longitude"];
-
-echo json_encode($result);
+if($debug > 0){
+	echo json_encode($result,  JSON_PRETTY_PRINT);
+}
+else{
+	echo json_encode($result);
+}
 
 ?>
