Index: src/gnuboat/common/__init__.py
===================================================================
--- src/gnuboat/common/__init__.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ src/gnuboat/common/__init__.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -16,5 +16,2 @@
     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 '''
-from gnuboat.common.datahandler.loghandler import LogHandler
-from gnuboat.common.datahandler.logdataset import LogDataset
-from gnuboat.common.spatial.tilegenerator import TileGenerator
Index: src/gnuboat/common/bin/gnuboat-log-analyser
===================================================================
--- src/gnuboat/common/bin/gnuboat-log-analyser	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ src/gnuboat/common/bin/gnuboat-log-analyser	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -35,6 +35,9 @@
 from time import process_time
 
-from gnuboat_common.datahandler import loghandler, logdataset
-from gnuboat_common.spatial import tilegenerator
+from gnuboat.common.datahandler import (
+    log_handler as loghandler,
+    log_dataset,
+)
+from gnuboat.common.spatial import tile_generator
 
 # -999 is a workaround, as long gdal python api does not handle addAlpha
@@ -238,6 +241,6 @@
     print("Correcting and combining {} log files".format(len(logfiles)))
     for logfile in logfiles:
-        gaugeHeight = logfile["gaugeHeight"]
-        referenceWaterLevelGaugeHeight = logfile[
+        gauge_height = logfile["gaugeHeight"]
+        reference_water_level_gauge_height = logfile[
             "referenceWaterLevelGaugeHeight"]
         log_file_path = logfile["file"]
@@ -250,5 +253,5 @@
         # check stage
         try:
-            gaugeHeight = float(gaugeHeight)
+            gauge_height = float(gauge_height)
         except ValueError:
             print(
@@ -258,6 +261,6 @@
             continue
         try:
-            referenceWaterLevelGaugeHeight = float(
-                referenceWaterLevelGaugeHeight
+            reference_water_level_gauge_height = float(
+                reference_water_level_gauge_height
             )
         except ValueError:
@@ -268,5 +271,5 @@
             continue
         # parse, correct and append log file
-        difference = referenceWaterLevelGaugeHeight - gaugeHeight
+        difference = reference_water_level_gauge_height - gauge_height
         csv_callback.stage_set(difference)
         result = log_handler.gnuboat_read_file(
@@ -359,5 +362,5 @@
     )
 
-    tilegen = tilegenerator.TileGenerator(
+    tilegen = tile_generator.TileGenerator(
         tile_sizes=tile_sizes,
         densities=[density_min],
@@ -367,5 +370,5 @@
     slices = tilegen.slices(
         source_xml_file,
-        tilegenerator.ZoomRange(zoom_range[0], zoom_range[1]),
+        tile_generator.ZoomRange(zoom_range[0], zoom_range[1]),
         raster_file_size_max=raster_file_size_max * 1024 * 1024 * 8
     )
Index: src/gnuboat/common/bin/gnuboat-log-converter
===================================================================
--- src/gnuboat/common/bin/gnuboat-log-converter	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ src/gnuboat/common/bin/gnuboat-log-converter	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -27,5 +27,8 @@
 import subprocess
 
-from gnuboat_common.datahandler import loghandler, logdataset
+from gnuboat.common.datahandler import (
+    log_handler as loghandler,
+    log_dataset,
+)
 
 
@@ -44,5 +47,5 @@
 
 
-def convertToCsv(
+def convert_to_csv(
     input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time
 ):
@@ -57,5 +60,6 @@
         'datetime', 'gps_status', 'latitude', 'latitude_direction',
         'longitude', 'longitude_direction', 'speed_over_ground',
-        'course_over_ground', 'water_depth', 'water_temperature'
+        'course_over_ground', 'water_depth', 'water_temperature',
+        'error_horizontal', 'error_vertical', 'error_spherical'
     ]
     output_file_csv = csv.DictWriter(
@@ -78,5 +82,5 @@
 
 
-def convertToNmea0183(
+def convert_to_nmea0183(
     input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time
 ):
@@ -121,5 +125,5 @@
 
 
-def convertToGpx(
+def convert_to_gpx(
     input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time
 ):
@@ -128,5 +132,5 @@
     [nmea_without_timestamps_handle,
      nmea_without_timestamp_file_path] = tempfile.mkstemp(text=True)
-    convertToNmea0183(
+    convert_to_nmea0183(
         input_file_path, nmea_without_timestamp_file_path, errors_ignore,
         checksums_fix, True
@@ -248,15 +252,15 @@
 
     if output_format == Format.CSV.value:
-        convertToCsv(
+        convert_to_csv(
             input_file_path, output_file_path, errors_ignore, checksums_fix,
             strip_time
         )
     elif output_format == Format.NMEA0183.value:
-        convertToNmea0183(
+        convert_to_nmea0183(
             input_file_path, output_file_path, errors_ignore, checksums_fix,
             strip_time
         )
     elif output_format == Format.GPX.value:
-        convertToGpx(
+        convert_to_gpx(
             input_file_path, output_file_path, errors_ignore, checksums_fix,
             strip_time
Index: src/gnuboat/common/datahandler/__init__.py
===================================================================
--- src/gnuboat/common/datahandler/__init__.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ src/gnuboat/common/datahandler/__init__.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -16,7 +16,2 @@
     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 '''
-
-from .loghandler import LogHandler
-from .logdataset import LogDataset
-
-__all__ = ["loghandler", "logdataset"]
Index: src/gnuboat/common/datahandler/log_dataset.py
===================================================================
--- src/gnuboat/common/datahandler/log_dataset.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/common/datahandler/log_dataset.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,177 @@
+# -*- coding: utf-8 -*-
+'''
+    Copyright (C) 2016 - 2020 EngSaS - 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/>.
+'''
+
+from datetime import datetime, timezone
+from collections import namedtuple
+
+Location = namedtuple('Location', 'latitude longitude')
+"""@class Dataset of a log entry
+"""
+
+
+class LogDataset:
+    def __init__(
+        self,
+        datetime=None,
+        gps_status=None,
+        latitude=None,
+        latitude_direction=None,
+        longitude=None,
+        longitude_direction=None,
+        speed_over_ground=None,
+        course_over_ground=None,
+        water_depth=None,
+        water_temperature=None,
+        error_horizontal=None,
+        error_vertical=None,
+        error_spherical=None,
+    ):
+        self._datetime = datetime
+        self._gps_status = gps_status
+        self._latitude = latitude
+        self._latitude_direction = latitude_direction
+        self._longitude = longitude
+        self._longitude_direction = longitude_direction
+        self._speed_over_ground = speed_over_ground
+        self._course_over_ground = course_over_ground
+        self._water_depth = water_depth
+        self._water_temperature = water_temperature
+        self._error_horizontal = error_horizontal
+        self._error_vertical = error_vertical
+        self._error_spherical = error_spherical
+
+    def datetime(self):
+        return self._datetime
+
+    def datetime_object(self):
+        if self.datetime() is None:
+            return None
+        return datetime.strptime(self.datetime(), "%Y-%m-%d %H:%M:%S").replace(
+            tzinfo=timezone.utc
+        )
+
+    def datetime_set(self, datetime):
+        self._datetime = datetime
+
+    def gps_status(self):
+        return self._gps_status
+
+    def gps_status_set(self, status):
+        self._gps_status = status
+
+    def latitude(self):
+        return self._latitude
+
+    def latitude_set(self, latitude):
+        self._latitude = latitude
+
+    def latitude_direction(self):
+        return self._latitude_direction
+
+    def latitude_direction_set(self, direction):
+        self._latitude_direction = direction
+
+    def longitude(self):
+        return self._longitude
+
+    def longitude_set(self, longitude):
+        self._longitude = longitude
+
+    def longitude_direction(self):
+        return self._longitude_direction
+
+    def longitude_direction_set(self, direction):
+        self._longitude_direction = direction
+
+    def location(self):
+        if self.latitude_direction() is None:
+            return None
+        elif self.latitude_direction() == 'N':
+            latitude = self.latitude()
+        elif self.latitude_direction() == 'S':
+            latitude = -1.0 * self.latitude()
+        else:
+            return None
+        if self.longitude_direction() is None:
+            return None
+        elif self.longitude_direction() == 'E':
+            longitude = self.longitude()
+        elif self.longitude_direction() == 'W':
+            longitude = -1.0 * self.longitude()
+        else:
+            return None
+        return Location(latitude, longitude)
+
+    def error_horizontal(self):
+        return self._error_horizontal
+
+    def error_horizontal_set(self, error_in_metre):
+        self._error_horizontal = error_in_metre
+
+    def error_vertical(self):
+        return self._error_vertical
+
+    def error_vertical_set(self, error_in_metre):
+        self._error_vertical = error_in_metre
+
+    def error_spherical(self):
+        return self._error_spherical
+
+    def error_spherical_set(self, error_in_metre):
+        self._error_spherical = error_in_metre
+
+    def speed_over_ground(self):
+        return self._speed_over_ground
+
+    def speed_over_ground_set(self, speed):
+        self._speed_over_ground = speed
+
+    def course_over_ground(self):
+        return self._course_over_ground
+
+    def course_over_ground_set(self, course):
+        self._course_over_ground = course
+
+    def water_depth(self):
+        return self._water_depth
+
+    def water_depth_set(self, depth):
+        self._water_depth = depth
+
+    def water_temperature(self):
+        return self._water_temperature
+
+    def water_temperature_set(self, temperature):
+        self._water_temperature = temperature
+
+    def to_dict(self):
+        return {
+            'datetime': self.datetime(),
+            'gps_status': self.gps_status(),
+            'latitude': self.latitude(),
+            'latitude_direction': self.latitude_direction(),
+            'longitude': self.longitude(),
+            'longitude_direction': self.longitude_direction(),
+            'speed_over_ground': self.speed_over_ground(),
+            'course_over_ground': self.course_over_ground(),
+            'water_depth': self.water_depth(),
+            'water_temperature': self.water_temperature(),
+            'error_horizontal': self.error_horizontal(),
+            'error_vertical': self.error_vertical(),
+            'error_spherical': self.error_spherical(),
+        }
Index: src/gnuboat/common/datahandler/log_handler.py
===================================================================
--- src/gnuboat/common/datahandler/log_handler.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/common/datahandler/log_handler.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,379 @@
+# -*- coding: utf-8 -*-
+'''
+    Copyright (C) 2016 - 2020 EngSaS - 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 re
+import pynmea2
+import datetime
+from pytz import timezone
+import math
+from pathlib import Path
+
+from gnuboat.common.datahandler import log_dataset
+
+
+class LogParsingResult:
+    def __init__(self):
+        self._success = False
+        self._errors = []
+
+    def error_add(self, error):
+        self._errors.append(error)
+
+    def errors(self):
+        return self._errors
+
+    def messages(self):
+        if len(self._errors) > 0:
+            return True
+        return False
+
+    def succeeded(self, status):
+        self._success = status
+
+    def success(self):
+        return self._success
+
+
+"""@class LogHandler
+"""
+
+
+class LogHandler:
+    def __init__(self, log_directory=None):
+        self._regex_nmea_sentence = re.compile(
+            r"^([^\$!]{0,})([\$!]{1}[\w]{2}[\w]{3}[^\*]+\*[\da-zA-Z]+)$"
+        )
+        self._regex_nmea_sentence_without_checksum = re.compile(
+            r"^([^\$!]{0,})([\$!]{1}[\w]{2}[\w]{3}[^\*]+)\*[\da-zA-Z]+$"
+        )
+        self._regex_nmea_position_latitude = re.compile(
+            r"^([0-9]{2})([0-9]{2}\.[0-9]+)$"
+        )
+        self._regex_nmea_position_longitude = re.compile(
+            r"^([0-9]{3})([0-9]{2}\.[0-9]+)$"
+        )
+        if isinstance(log_directory, Path):
+            self._log_directory = log_directory
+        elif log_directory is None:
+            self._log_directory = None
+        else:
+            self._log_directory = Path(log_directory)
+        self._nmea_file = None
+        self._nmea_file_date = None
+
+    def gnuboat_write(
+        self, gps_fix, gps_time, dataset, transducer_valid, log_verbose,
+        log_system_time
+    ):
+        # Only log, if we have a gps fix
+        if gps_fix < 2:
+            if not log_verbose:
+                return
+            gps_status = 'V'
+            mode = 'N'
+            if gps_time is None:
+                gps_time = datetime.datetime.utcnow()
+
+        nmea_file_date_should = datetime.datetime.utcnow().strftime("%Y-%m-%d")
+        mode = 'A'
+        if (self._nmea_file is None or self._nmea_file_date is None or
+                self._nmea_file_date != nmea_file_date_should):
+            if self._nmea_file:
+                self._nmea_file.close()
+            self._nmea_file_date = nmea_file_date_should
+            nmea_log_file = 'nmea0183-{}.log'.format(self._nmea_file_date)
+            if self._log_directory is not None:
+                nmea_log_file = self._log_directory.joinpath(nmea_log_file)
+            try:
+                self._nmea_file = open(nmea_log_file, 'a', 1)
+            except IOError as error:
+                print('Could not open the logfile: {}'.format(error))
+                return False
+        else:
+            nmea_log_file = self._nmea_file.name
+
+        latitude = self._degrees_decimal_to_nmea(dataset.latitude())
+        longitude = self._degrees_decimal_to_nmea(dataset.longitude())
+
+        logsystemtime = ""
+        if log_system_time:
+            logsystemtime = '{}: '.format(
+                datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
+            )
+
+        try:
+            self._nmea_file.write(
+                '{}{}\r\n'.format(
+                    logsystemtime,
+                    str(
+                        pynmea2.RMC(
+                            'GN', 'RMC', (
+                                gps_time.strftime("%H%M%S"),
+                                dataset.gps_status(), '{:02d}{:07.4f}'.format(
+                                    latitude['degrees'], latitude['minutes']
+                                ), dataset.latitude_direction(),
+                                '{:03d}{:07.4f}'.format(
+                                    longitude['degrees'], longitude['minutes']
+                                ), dataset.longitude_direction(),
+                                '{:04.1f}'.format(dataset.speed_over_ground()),
+                                '{:04.1f}'.format(
+                                    dataset.course_over_ground()
+                                ), gps_time.strftime("%d%m%y"), '', '', mode
+                            )
+                        )
+                    )
+                )
+            )
+            if transducer_valid:
+                self._nmea_file.write(
+                    '{}{}\r\n'.format(
+                        logsystemtime,
+                        str(
+                            pynmea2.DPT(
+                                'SD', 'DPT', (
+                                    '{:05.2f}'.format(dataset.water_depth()
+                                                      ), '00.00'
+                                )
+                            )
+                        )
+                    )
+                )
+                self._nmea_file.write(
+                    '{}{}\r\n'.format(
+                        logsystemtime,
+                        str(
+                            pynmea2.MTW(
+                                'YX', 'MTW', (
+                                    '{:04.1f}'.format(
+                                        dataset.water_temperature()
+                                    ), 'C'
+                                )
+                            )
+                        )
+                    )
+                )
+            if dataset.error_horizontal() is not None:
+                error_horizontal = dataset.error_horizontal()
+                if dataset.error_vertical() is not None:
+                    error_vertical = dataset.error_vertical()
+                else:
+                    error_vertical = 999
+                if dataset.error_spherical() is not None:
+                    error_spherical = dataset.error_spherical()
+                else:
+                    error_spherical = 999
+                self._nmea_file.write(
+                    '{}{}\r\n'.format(
+                        logsystemtime,
+                        str(
+                            pynmea2.GRME(
+                                'PG', 'RME', (
+                                    '{:.1f}'.format(error_horizontal), 'M',
+                                    '{:.1f}'.format(error_vertical), 'M',
+                                    '{:.1f}'.format(error_spherical), 'M',
+                                )
+                            )
+                        )
+                    )
+                )
+            return True
+        except Exception as e:
+            print('Failed writing to logfile {}'.format(nmea_log_file))
+            print(repr(e))
+            return False
+        return False
+
+    def gnuboat_close(self):
+        if self._nmea_file:
+            self._nmea_file.close()
+
+    def parse_nmea_sentence(self, line, checksum_ingore=False):
+        line = line.strip()
+        if checksum_ingore:
+            matches = self._regex_nmea_sentence_without_checksum.match(line)
+        else:
+            matches = self._regex_nmea_sentence.match(line)
+        if matches is None:
+            return None
+        return {
+            'log_timestamp':
+                matches.group(1),
+            'nmea_sentence':
+                pynmea2.parse(matches.group(2), not checksum_ingore)
+        }
+
+    def gnuboat_read_file(
+        self,
+        input_file_path,
+        callback,
+        checksums_fix=False,
+        errors_ignore=False
+    ):
+        """
+            Reads the original gnuboat log files and calls a callable function
+            on all complete LogDataset callback must be of a function wich
+            excepts the LogDataset as a parameter.
+        """
+        result = LogParsingResult()
+
+        # reading input file
+        try:
+            input_file = open(input_file_path, 'r')
+        except IOError as error:
+            result.error_add(
+                'ERROR: Could not open the input file: {}'.format(error)
+            )
+            result.succeeded(False)
+            return result
+        result = self.gnuboat_read(
+            input_file, callback, checksums_fix, errors_ignore=False
+        )
+        input_file.close()
+        return result
+
+    def gnuboat_read(
+        self, input_list, callback, checksums_fix=False, errors_ignore=False
+    ):
+        """
+            Reads the original gnuboat log from input_list and calls a callable
+            function on all complete LogDataset callback must be of a function
+            wich excepts the LogDataset as a parameter.
+        """
+        result = LogParsingResult()
+
+        current_row = 1
+        last_row = None
+        for line in input_list:
+            nmea_sentence = self.parse_nmea_sentence(line, checksums_fix)
+            if nmea_sentence is None:
+                result.error_add(
+                    'INFO: Failed to parse nmea sentence ({}) at line {}'.
+                    format(line.strip(), current_row)
+                )
+                if not errors_ignore:
+                    result.succeeded(False)
+                    return result
+            else:
+                nmea_sentence = nmea_sentence['nmea_sentence']
+                if nmea_sentence.sentence_type == 'RMC':
+                    if last_row is not None:
+                        callback(last_row)
+                    last_row = log_dataset.LogDataset()
+                    last_row.datetime_set(
+                        '{} {}'.format(
+                            nmea_sentence.datestamp, nmea_sentence.timestamp
+                        )
+                    )
+                    last_row.gps_status_set(nmea_sentence.status)
+                    last_row.latitude_set(
+                        self._nmea_latitude_to_decimal_degrees(
+                            nmea_sentence.lat, current_row
+                        )
+                    )
+                    last_row.latitude_direction_set(nmea_sentence.lat_dir)
+                    last_row.longitude_set(
+                        self._nmea_longitude_to_decimal_degrees(
+                            nmea_sentence.lon, current_row
+                        )
+                    )
+                    last_row.longitude_direction_set(nmea_sentence.lon_dir)
+                    last_row.speed_over_ground_set(
+                        self._to_float(
+                            nmea_sentence.spd_over_grnd, current_row
+                        )
+                    )
+                    last_row.course_over_ground_set(
+                        self._to_float(nmea_sentence.true_course, current_row)
+                    )
+                    last_row.water_depth_set(None)
+                    last_row.water_temperature_set(None)
+                elif (nmea_sentence.sentence_type == 'DPT' and
+                      last_row is not None):
+                    last_row.water_depth_set(
+                        self._to_float(nmea_sentence.depth, current_row)
+                    )
+                elif (nmea_sentence.sentence_type == 'MTW' and
+                      last_row is not None):
+                    last_row.water_temperature_set(
+                        self._to_float(nmea_sentence.temperature, current_row)
+                    )
+                elif (nmea_sentence.sentence_type == 'PGRME' and
+                      last_row is not None):
+                    last_row.error_horizontal_set(
+                        self._to_float(nmea_sentence.hpe, current_row)
+                    )
+                    last_row.error_vertical_set(
+                        self._to_float(nmea_sentence.vpe, current_row)
+                    )
+                    last_row.error_spherical_set(
+                        self._to_float(nmea_sentence.osepe, current_row)
+                    )
+            current_row += 1
+        if last_row is not None:
+            callback(last_row)
+        result.succeeded(True)
+        return result
+
+    def _to_float(self, string, current_row):
+        try:
+            return float(string)
+        except ValueError as error:
+            try:
+                return int(string)
+            except ValueError as error:
+                print(
+                    ('INFO: Failed to convert value from line '
+                     '{} into numeric: {}\n      Message: {}').format(
+                        current_row, string, error)
+                )
+                return 0
+
+    def _nmea_latitude_to_decimal_degrees(self, nmea_value, current_row):
+        if self._to_float(nmea_value, current_row) == 0:
+            return 0
+
+        matches = self._regex_nmea_position_latitude.match(nmea_value)
+        if matches is None:
+            print(
+                ('INFO: Failed to convert latitude position value from line '
+                 '{} into decimal degrees: {}').format(current_row, nmea_value)
+            )
+            return
+        decimal_degrees = self._to_float(matches.group(1), current_row)
+        decimal_minutes = self._to_float(matches.group(2), current_row)
+        return decimal_degrees + (decimal_minutes / 60.0)
+
+    def _nmea_longitude_to_decimal_degrees(self, nmea_value, current_row):
+        if self._to_float(nmea_value, current_row) == 0:
+            return 0
+
+        matches = self._regex_nmea_position_longitude.match(nmea_value)
+        if matches is None:
+            print(
+                ('INFO: Failed to convert longitude position value from line '
+                 '{} into decimal degrees: {}').format(current_row, nmea_value)
+            )
+            return
+        decimal_degrees = self._to_float(matches.group(1), current_row)
+        decimal_minutes = self._to_float(matches.group(2), current_row)
+        return decimal_degrees + (decimal_minutes / 60.0)
+
+    def _degrees_decimal_to_nmea(self, decimal_degrees):
+        degrees = int(math.floor(decimal_degrees))
+        minutes = 60.0 * (decimal_degrees - degrees)
+        return {'degrees': degrees, 'minutes': minutes}
Index: src/gnuboat/common/datahandler/logdataset.py
===================================================================
--- src/gnuboat/common/datahandler/logdataset.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ 	(revision )
@@ -1,177 +1,0 @@
-# -*- coding: utf-8 -*-
-'''
-    Copyright (C) 2016 - 2018 EngSaS - 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/>.
-'''
-
-from datetime import datetime, timezone
-from collections import namedtuple
-
-Location = namedtuple('Location', 'latitude longitude')
-"""@class Dataset of a log entry
-"""
-
-
-class LogDataset:
-    def __init__(
-        self,
-        datetime=None,
-        gps_status=None,
-        latitude=None,
-        latitude_direction=None,
-        longitude=None,
-        longitude_direction=None,
-        speed_over_ground=None,
-        course_over_ground=None,
-        water_depth=None,
-        water_temperature=None,
-        error_horizontal=None,
-        error_vertical=None,
-        error_spherical=None,
-    ):
-        self._datetime = datetime
-        self._gps_status = gps_status
-        self._latitude = latitude
-        self._latitude_direction = latitude_direction
-        self._longitude = longitude
-        self._longitude_direction = longitude_direction
-        self._speed_over_ground = speed_over_ground
-        self._course_over_ground = course_over_ground
-        self._water_depth = water_depth
-        self._water_temperature = water_temperature
-        self._error_horizontal = error_horizontal
-        self._error_vertical = error_vertical
-        self._error_spherical = error_spherical
-
-    def datetime(self):
-        return self._datetime
-
-    def datetime_object(self):
-        if self.datetime() is None:
-            return None
-        return datetime.strptime(self.datetime(), "%Y-%m-%d %H:%M:%S").replace(
-            tzinfo=timezone.utc
-        )
-
-    def datetime_set(self, datetime):
-        self._datetime = datetime
-
-    def gps_status(self):
-        return self._gps_status
-
-    def gps_status_set(self, status):
-        self._gps_status = status
-
-    def latitude(self):
-        return self._latitude
-
-    def latitude_set(self, latitude):
-        self._latitude = latitude
-
-    def latitude_direction(self):
-        return self._latitude_direction
-
-    def latitude_direction_set(self, direction):
-        self._latitude_direction = direction
-
-    def longitude(self):
-        return self._longitude
-
-    def longitude_set(self, longitude):
-        self._longitude = longitude
-
-    def longitude_direction(self):
-        return self._longitude_direction
-
-    def longitude_direction_set(self, direction):
-        self._longitude_direction = direction
-
-    def location(self):
-        if self.latitude_direction() is None:
-            return None
-        elif self.latitude_direction() == 'N':
-            latitude = self.latitude()
-        elif self.latitude_direction() == 'S':
-            latitude = -1.0 * self.latitude()
-        else:
-            return None
-        if self.longitude_direction() is None:
-            return None
-        elif self.longitude_direction() == 'E':
-            longitude = self.longitude()
-        elif self.longitude_direction() == 'W':
-            longitude = -1.0 * self.longitude()
-        else:
-            return None
-        return Location(latitude, longitude)
-
-    def error_horizontal(self):
-        return self._error_horizontal
-
-    def error_horizontal_set(self, error_in_metre):
-        self._error_horizontal = error_in_metre
-
-    def error_vertical(self):
-        return self._error_vertical
-
-    def error_vertical_set(self, error_in_metre):
-        self._error_vertical = error_in_metre
-
-    def error_spherical(self):
-        return self._error_spherical
-
-    def error_spherical_set(self, error_in_metre):
-        self._error_spherical = error_in_metre
-
-    def speed_over_ground(self):
-        return self._speed_over_ground
-
-    def speed_over_ground_set(self, speed):
-        self._speed_over_ground = speed
-
-    def course_over_ground(self):
-        return self._course_over_ground
-
-    def course_over_ground_set(self, course):
-        self._course_over_ground = course
-
-    def water_depth(self):
-        return self._water_depth
-
-    def water_depth_set(self, depth):
-        self._water_depth = depth
-
-    def water_temperature(self):
-        return self._water_temperature
-
-    def water_temperature_set(self, temperature):
-        self._water_temperature = temperature
-
-    def to_dict(self):
-        return {
-            'datetime': self.datetime(),
-            'gps_status': self.gps_status(),
-            'latitude': self.latitude(),
-            'latitude_direction': self.latitude_direction(),
-            'longitude': self.longitude(),
-            'longitude_direction': self.longitude_direction(),
-            'speed_over_ground': self.speed_over_ground(),
-            'course_over_ground': self.course_over_ground(),
-            'water_depth': self.water_depth(),
-            'water_temperature': self.water_temperature(),
-            'error_horizontal': self.error_horizontal(),
-            'error_vertical': self.error_vertical(),
-            'error_spherical': self.error_spherical(),
-        }
Index: src/gnuboat/common/datahandler/loghandler.py
===================================================================
--- src/gnuboat/common/datahandler/loghandler.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ 	(revision )
@@ -1,379 +1,0 @@
-# -*- coding: utf-8 -*-
-'''
-    Copyright (C) 2016 - 2020 EngSaS - 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 re
-import pynmea2
-import datetime
-from pytz import timezone
-import math
-from pathlib import Path
-
-from gnuboat.common.datahandler import logdataset
-
-
-class LogParsingResult:
-    def __init__(self):
-        self._success = False
-        self._errors = []
-
-    def error_add(self, error):
-        self._errors.append(error)
-
-    def errors(self):
-        return self._errors
-
-    def messages(self):
-        if len(self._errors) > 0:
-            return True
-        return False
-
-    def succeeded(self, status):
-        self._success = status
-
-    def success(self):
-        return self._success
-
-
-"""@class LogHandler
-"""
-
-
-class LogHandler:
-    def __init__(self, log_directory=None):
-        self._regex_nmea_sentence = re.compile(
-            r"^([^\$!]{0,})([\$!]{1}[\w]{2}[\w]{3}[^\*]+\*[\da-zA-Z]+)$"
-        )
-        self._regex_nmea_sentence_without_checksum = re.compile(
-            r"^([^\$!]{0,})([\$!]{1}[\w]{2}[\w]{3}[^\*]+)\*[\da-zA-Z]+$"
-        )
-        self._regex_nmea_position_latitude = re.compile(
-            r"^([0-9]{2})([0-9]{2}\.[0-9]+)$"
-        )
-        self._regex_nmea_position_longitude = re.compile(
-            r"^([0-9]{3})([0-9]{2}\.[0-9]+)$"
-        )
-        if isinstance(log_directory, Path):
-            self._log_directory = log_directory
-        elif log_directory is None:
-            self._log_directory = None
-        else:
-            self._log_directory = Path(log_directory)
-        self._nmea_file = None
-        self._nmea_file_date = None
-
-    def gnuboat_write(
-        self, gps_fix, gps_time, dataset, transducer_valid, log_verbose,
-        log_system_time
-    ):
-        # Only log, if we have a gps fix
-        if gps_fix < 2:
-            if not log_verbose:
-                return
-            gps_status = 'V'
-            mode = 'N'
-            if gps_time is None:
-                gps_time = datetime.datetime.utcnow()
-
-        nmea_file_date_should = datetime.datetime.utcnow().strftime("%Y-%m-%d")
-        mode = 'A'
-        if (self._nmea_file is None or self._nmea_file_date is None or
-                self._nmea_file_date != nmea_file_date_should):
-            if self._nmea_file:
-                self._nmea_file.close()
-            self._nmea_file_date = nmea_file_date_should
-            nmea_log_file = 'nmea0183-{}.log'.format(self._nmea_file_date)
-            if self._log_directory is not None:
-                nmea_log_file = self._log_directory.joinpath(nmea_log_file)
-            try:
-                self._nmea_file = open(nmea_log_file, 'a', 1)
-            except IOError as error:
-                print('Could not open the logfile: {}'.format(error))
-                return False
-        else:
-            nmea_log_file = self._nmea_file.name
-
-        latitude = self._degreesDecimalToNmea(dataset.latitude())
-        longitude = self._degreesDecimalToNmea(dataset.longitude())
-
-        logsystemtime = ""
-        if log_system_time:
-            logsystemtime = '{}: '.format(
-                datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
-            )
-
-        try:
-            self._nmea_file.write(
-                '{}{}\r\n'.format(
-                    logsystemtime,
-                    str(
-                        pynmea2.RMC(
-                            'GN', 'RMC', (
-                                gps_time.strftime("%H%M%S"),
-                                dataset.gps_status(), '{:02d}{:07.4f}'.format(
-                                    latitude['degrees'], latitude['minutes']
-                                ), dataset.latitude_direction(),
-                                '{:03d}{:07.4f}'.format(
-                                    longitude['degrees'], longitude['minutes']
-                                ), dataset.longitude_direction(),
-                                '{:04.1f}'.format(dataset.speed_over_ground()),
-                                '{:04.1f}'.format(
-                                    dataset.course_over_ground()
-                                ), gps_time.strftime("%d%m%y"), '', '', mode
-                            )
-                        )
-                    )
-                )
-            )
-            if transducer_valid:
-                self._nmea_file.write(
-                    '{}{}\r\n'.format(
-                        logsystemtime,
-                        str(
-                            pynmea2.DPT(
-                                'SD', 'DPT', (
-                                    '{:05.2f}'.format(dataset.water_depth()
-                                                      ), '00.00'
-                                )
-                            )
-                        )
-                    )
-                )
-                self._nmea_file.write(
-                    '{}{}\r\n'.format(
-                        logsystemtime,
-                        str(
-                            pynmea2.MTW(
-                                'YX', 'MTW', (
-                                    '{:04.1f}'.format(
-                                        dataset.water_temperature()
-                                    ), 'C'
-                                )
-                            )
-                        )
-                    )
-                )
-            if dataset.error_horizontal() is not None:
-                error_horizontal = dataset.error_horizontal()
-                if dataset.error_vertical() is not None:
-                    error_vertical = dataset.error_vertical()
-                else:
-                    error_vertical = 999
-                if dataset.error_spherical() is not None:
-                    error_spherical = dataset.error_spherical()
-                else:
-                    error_spherical = 999
-                self._nmea_file.write(
-                    '{}{}\r\n'.format(
-                        logsystemtime,
-                        str(
-                            pynmea2.GRME(
-                                'PG', 'RME', (
-                                    '{:.1f}'.format(error_horizontal), 'M',
-                                    '{:.1f}'.format(error_vertical), 'M',
-                                    '{:.1f}'.format(error_spherical), 'M',
-                                )
-                            )
-                        )
-                    )
-                )
-            return True
-        except Exception as e:
-            print('Failed writing to logfile {}'.format(nmea_log_file))
-            print(repr(e))
-            return False
-        return False
-
-    def gnuboat_close(self):
-        if self._nmea_file:
-            self._nmea_file.close()
-
-    def parse_nmea_sentence(self, line, checksum_ingore=False):
-        line = line.strip()
-        if checksum_ingore:
-            matches = self._regex_nmea_sentence_without_checksum.match(line)
-        else:
-            matches = self._regex_nmea_sentence.match(line)
-        if matches is None:
-            return None
-        return {
-            'log_timestamp':
-                matches.group(1),
-            'nmea_sentence':
-                pynmea2.parse(matches.group(2), not checksum_ingore)
-        }
-
-    def gnuboat_read_file(
-        self,
-        input_file_path,
-        callback,
-        checksums_fix=False,
-        errors_ignore=False
-    ):
-        """
-            Reads the original gnuboat log files and calls a callable function
-            on all complete LogDataset callback must be of a function wich
-            excepts the LogDataset as a parameter.
-        """
-        result = LogParsingResult()
-
-        # reading input file
-        try:
-            input_file = open(input_file_path, 'r')
-        except IOError as error:
-            result.error_add(
-                'ERROR: Could not open the input file: {}'.format(error)
-            )
-            result.succeeded(False)
-            return result
-        result = self.gnuboat_read(
-            input_file, callback, checksums_fix, errors_ignore=False
-        )
-        input_file.close()
-        return result
-
-    def gnuboat_read(
-        self, input_list, callback, checksums_fix=False, errors_ignore=False
-    ):
-        """
-            Reads the original gnuboat log from input_list and calls a callable
-            function on all complete LogDataset callback must be of a function
-            wich excepts the LogDataset as a parameter.
-        """
-        result = LogParsingResult()
-
-        current_row = 1
-        last_row = None
-        for line in input_list:
-            nmea_sentence = self.parse_nmea_sentence(line, checksums_fix)
-            if nmea_sentence is None:
-                result.error_add(
-                    'INFO: Failed to parse nmea sentence ({}) at line {}'.
-                    format(line.strip(), current_row)
-                )
-                if not errors_ignore:
-                    result.succeeded(False)
-                    return result
-            else:
-                nmea_sentence = nmea_sentence['nmea_sentence']
-                if nmea_sentence.sentence_type == 'RMC':
-                    if last_row is not None:
-                        callback(last_row)
-                    last_row = logdataset.LogDataset()
-                    last_row.datetime_set(
-                        '{} {}'.format(
-                            nmea_sentence.datestamp, nmea_sentence.timestamp
-                        )
-                    )
-                    last_row.gps_status_set(nmea_sentence.status)
-                    last_row.latitude_set(
-                        self._nmeaLatitudeToDecimalDegrees(
-                            nmea_sentence.lat, current_row
-                        )
-                    )
-                    last_row.latitude_direction_set(nmea_sentence.lat_dir)
-                    last_row.longitude_set(
-                        self._nmeaLongitudeToDecimalDegrees(
-                            nmea_sentence.lon, current_row
-                        )
-                    )
-                    last_row.longitude_direction_set(nmea_sentence.lon_dir)
-                    last_row.speed_over_ground_set(
-                        self._to_float(
-                            nmea_sentence.spd_over_grnd, current_row
-                        )
-                    )
-                    last_row.course_over_ground_set(
-                        self._to_float(nmea_sentence.true_course, current_row)
-                    )
-                    last_row.water_depth_set(None)
-                    last_row.water_temperature_set(None)
-                elif (nmea_sentence.sentence_type == 'DPT' and
-                      last_row is not None):
-                    last_row.water_depth_set(
-                        self._to_float(nmea_sentence.depth, current_row)
-                    )
-                elif (nmea_sentence.sentence_type == 'MTW' and
-                      last_row is not None):
-                    last_row.water_temperature_set(
-                        self._to_float(nmea_sentence.temperature, current_row)
-                    )
-                elif (nmea_sentence.sentence_type == 'PGRME' and
-                      last_row is not None):
-                    last_row.error_horizontal_set(
-                        self._to_float(nmea_sentence.hpe, current_row)
-                    )
-                    last_row.error_vertical_set(
-                        self._to_float(nmea_sentence.vpe, current_row)
-                    )
-                    last_row.error_spherical_set(
-                        self._to_float(nmea_sentence.osepe, current_row)
-                    )
-            current_row += 1
-        if last_row is not None:
-            callback(last_row)
-        result.succeeded(True)
-        return result
-
-    def _to_float(self, string, current_row):
-        try:
-            return float(string)
-        except ValueError as error:
-            try:
-                return int(string)
-            except ValueError as error:
-                print(
-                    ('INFO: Failed to convert value from line '
-                     '{} into numeric: {}\n      Message: {}').format(
-                        current_row, string, error)
-                )
-                return 0
-
-    def _nmeaLatitudeToDecimalDegrees(self, nmea_value, current_row):
-        if self._to_float(nmea_value, current_row) == 0:
-            return 0
-
-        matches = self._regex_nmea_position_latitude.match(nmea_value)
-        if matches is None:
-            print(
-                ('INFO: Failed to convert latitude position value from line '
-                 '{} into decimal degrees: {}').format(current_row, nmea_value)
-            )
-            return
-        decimalDegrees = self._to_float(matches.group(1), current_row)
-        decimalMinutes = self._to_float(matches.group(2), current_row)
-        return decimalDegrees + (decimalMinutes / 60.0)
-
-    def _nmeaLongitudeToDecimalDegrees(self, nmea_value, current_row):
-        if self._to_float(nmea_value, current_row) == 0:
-            return 0
-
-        matches = self._regex_nmea_position_longitude.match(nmea_value)
-        if matches is None:
-            print(
-                ('INFO: Failed to convert longitude position value from line '
-                 '{} into decimal degrees: {}').format(current_row, nmea_value)
-            )
-            return
-        decimalDegrees = self._to_float(matches.group(1), current_row)
-        decimalMinutes = self._to_float(matches.group(2), current_row)
-        return decimalDegrees + (decimalMinutes / 60.0)
-
-    def _degreesDecimalToNmea(self, decimalDegrees):
-        degrees = int(math.floor(decimalDegrees))
-        minutes = 60.0 * (decimalDegrees - degrees)
-        return {'degrees': degrees, 'minutes': minutes}
Index: src/gnuboat/common/datahandler/rrd_handler.py
===================================================================
--- src/gnuboat/common/datahandler/rrd_handler.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/common/datahandler/rrd_handler.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,76 @@
+# -*- coding: utf-8 -*-
+'''
+    Copyright (C) 2016 - 2020 EngSaS - 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 os
+from pathlib import Path
+
+import gnuboat.common.datahandler.rrd_schema as rrdschema
+
+
+def rrd_create_database(database_file, logperiod, start_time='N'):
+    rrd_data_sources = [
+        '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:courseoverground:GAUGE:15:U:U', 'DS:waterdepth:GAUGE:15:0:10000',
+        'DS:watertemperature:GAUGE:15:-10:50', 'DS:gpsfix:GAUGE:15:-999:3'
+    ]
+
+    step = logperiod
+    # durations: each archive should contain values for in seconds
+    archives = rrdschema.archives
+    rrd_archives = []
+    for i in range(0, len(archives)):
+        rrd_archives += [
+            'RRA:AVERAGE:0.5:{:d}:{:d}'.format(
+                _steps(archives[i].resolution, step),
+                _rows(
+                    archives[i].duration, archives[i].resolution, step
+                )
+            )
+        ]
+    if not isinstance(database_file, Path):
+        database_file = Path(database_file)
+    if not database_file.is_file():
+        rrdtool.create(
+            str(database_file.resolve()), "--start", start_time,
+            "--step", str(step), rrd_data_sources, rrd_archives
+        )
+
+
+def rrd_update(rrdfile, value_string):
+    try:
+        if isinstance(rrdfile, Path):
+            rrdfile = str(rrdfile.resolve())
+        rrdtool.update(rrdfile, value_string)
+    except Exception as e:
+        print(
+            'Failed to update rrd database {} with values\n  {}'.format(
+                rrdfile, value_string
+            )
+        )
+
+
+def _rows(duration, resolution, step):
+    return int(
+        round(float(duration) / _steps(resolution, float(step)) / float(step))
+    )
+
+
+def _steps(resolution, step):
+    return int(round(float(resolution) / float(step)))
Index: src/gnuboat/common/datahandler/rrd_schema.py
===================================================================
--- src/gnuboat/common/datahandler/rrd_schema.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/common/datahandler/rrd_schema.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,43 @@
+'''
+    Copyright (C) 2017 - 2020 EngSaS - 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/>.
+'''
+
+try:
+    from dataclasses import dataclass
+
+    @dataclass
+    class RrdArchive:
+        """
+            Describes an RRD Archive.
+            Durations and resolution are in seconds
+        """
+        duration: int
+        resolution: int
+except:
+    class RrdArchive:
+        """
+            Describes an RRD Archive.
+            Durations and resolution are in seconds
+        """
+        def __init__(self, duration, resolution):
+            self.duration = duration
+            self.resolution = resolution
+
+archives = [
+    RrdArchive(240, 2),
+    RrdArchive(3600, 10),
+    RrdArchive(86400, 60),
+]
Index: src/gnuboat/common/datahandler/rrdhandler.py
===================================================================
--- src/gnuboat/common/datahandler/rrdhandler.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ 	(revision )
@@ -1,76 +1,0 @@
-# -*- coding: utf-8 -*-
-'''
-    Copyright (C) 2016 - 2020 EngSaS - 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 os
-from pathlib import Path
-
-import gnuboat.common.datahandler.rrdschema as rrdschema
-
-
-def rrd_create_database(database_file, logperiod, start_time='N'):
-    rrd_data_sources = [
-        '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:courseoverground:GAUGE:15:U:U', 'DS:waterdepth:GAUGE:15:0:10000',
-        'DS:watertemperature:GAUGE:15:-10:50', 'DS:gpsfix:GAUGE:15:-999:3'
-    ]
-
-    step = logperiod
-    # durations: each archive should contain values for in seconds
-    archives = rrdschema.archives
-    rrd_archives = []
-    for i in range(0, len(archives)):
-        rrd_archives += [
-            'RRA:AVERAGE:0.5:{:d}:{:d}'.format(
-                _steps(archives[i].resolution, step),
-                _rows(
-                    archives[i].duration, archives[i].resolution, step
-                )
-            )
-        ]
-    if not isinstance(database_file, Path):
-        database_file = Path(database_file)
-    if not database_file.is_file():
-        rrdtool.create(
-            str(database_file.resolve()), "--start", start_time,
-            "--step", str(step), rrd_data_sources, rrd_archives
-        )
-
-
-def rrd_update(rrdfile, value_string):
-    try:
-        if isinstance(rrdfile, Path):
-            rrdfile = str(rrdfile.resolve())
-        rrdtool.update(rrdfile, value_string)
-    except Exception as e:
-        print(
-            'Failed to update rrd database {} with values\n  {}'.format(
-                rrdfile, value_string
-            )
-        )
-
-
-def _rows(duration, resolution, step):
-    return int(
-        round(float(duration) / _steps(resolution, float(step)) / float(step))
-    )
-
-
-def _steps(resolution, step):
-    return int(round(float(resolution) / float(step)))
Index: src/gnuboat/common/datahandler/rrdschema.py
===================================================================
--- src/gnuboat/common/datahandler/rrdschema.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ 	(revision )
@@ -1,43 +1,0 @@
-'''
-    Copyright (C) 2017 - 2020 EngSaS - 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/>.
-'''
-
-try:
-    from dataclasses import dataclass
-
-    @dataclass
-    class RrdArchive:
-        """
-            Describes an RRD Archive.
-            Durations and resolution are in seconds
-        """
-        duration: int
-        resolution: int
-except:
-    class RrdArchive:
-        """
-            Describes an RRD Archive.
-            Durations and resolution are in seconds
-        """
-        def __init__(self, duration, resolution):
-            self.duration = duration
-            self.resolution = resolution
-
-archives = [
-    RrdArchive(240, 2),
-    RrdArchive(3600, 10),
-    RrdArchive(86400, 60),
-]
Index: src/gnuboat/common/spatial/__init__.py
===================================================================
--- src/gnuboat/common/spatial/__init__.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ src/gnuboat/common/spatial/__init__.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -16,6 +16,2 @@
     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 '''
-
-from .tilegenerator import TileGenerator
-
-__all__ = ["tilegenerator"]
Index: src/gnuboat/common/spatial/tile_generator.py
===================================================================
--- src/gnuboat/common/spatial/tile_generator.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/common/spatial/tile_generator.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,660 @@
+# -*- coding: utf-8 -*-
+'''
+    Copyright (C) 2020 EngSaS - 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 mercantile
+from osgeo import ogr
+from osgeo import gdal
+from osgeo import gdalconst
+import tempfile
+import os
+import shutil
+import subprocess
+import math
+import copy
+from pathlib import Path
+from PIL import Image
+
+try:
+    from dataclasses import dataclass
+
+    @dataclass
+    class ResultPath:
+        """
+            path: Absolute path of the created results
+            prefixes: Dict with meaningful prefixes in the path. e.g.
+            {'tile_size': '512', 'density': '10_100'}
+        """
+        path: str
+        prefixes: dict
+
+except ImportError:
+    # Workaround for @dataclass, until python 3.7 is available in
+    # main distros
+    class ResultPath:
+        """
+            path: Absolute path of the created results
+            prefixes: Dict with meaningful prefixes in the path. e.g.
+            {'tile_size': '512', 'density': '10_100'}
+        """
+        def __init__(self, path, prefixes):
+            self.path = path
+            self.prefixes = prefixes
+
+
+class ZoomRange(dict):
+    def __init__(self, minimum, maximum):
+        super(ZoomRange, self).__init__({
+            'minimum': minimum,
+            'maximum': maximum
+        })
+
+    def minimum(self):
+        return self['minimum']
+
+    def maximum(self):
+        return self['maximum']
+
+    def from_dict(dictionary):
+        return ZoomRange(dictionary['minimum'], dictionary['maximum'])
+
+
+class LngLatBbox(dict):
+    def __init__(self, west, south, east, north):
+        super(LngLatBbox, self).__init__({
+            'west': west,
+            'south': south,
+            'east': east,
+            'north': north
+        })
+
+    def west(self):
+        return self['west']
+
+    def south(self):
+        return self['south']
+
+    def east(self):
+        return self['east']
+
+    def north(self):
+        return self['north']
+
+    def to_mercantile_bbox(self):
+        return mercantile.LngLatBbox(
+            self.west(), self.south(), self.east(), self.north()
+        )
+
+    def from_mercantile_bbox(mercantile_bbox):
+        return LngLatBbox(
+            mercantile_bbox.west, mercantile_bbox.south, mercantile_bbox.east,
+            mercantile_bbox.north
+        )
+
+    def from_dict(dictionary):
+        if dictionary is None:
+            return None
+        return LngLatBbox(
+            dictionary['west'], dictionary['south'], dictionary['east'],
+            dictionary['north']
+        )
+
+
+class RasterSlice(dict):
+    """
+        lng_lat_box: LngLatBbox
+        zoom_range: ZoomRange
+        tile_size: The tile size in Pixel,
+        grid_width: The width of the resulting rastr
+        grid_height:  The height of the resulting rastr
+
+        It's derived from dict to be json serialisable
+    """
+    def __init__(
+        self, lng_lat_box, zoom_range, tile_size, grid_width, grid_height
+    ):
+        super(RasterSlice, self).__init__({
+            'lng_lat_box': lng_lat_box,
+            'zoom_range': zoom_range,
+            'tile_size': tile_size,
+            'grid_width': grid_width,
+            'grid_height': grid_height
+        })
+
+    def lng_lat_bbox(self):
+        return self['lng_lat_box']
+
+    def zoom_range(self):
+        return self['zoom_range']
+
+    def tile_size(self):
+        return self['tile_size']
+
+    def grid_width(self):
+        return self['grid_width']
+
+    def grid_height(self):
+        return self['grid_height']
+
+    def from_dict(dictionary):
+        if dictionary is None:
+            return None
+        return RasterSlice(
+            LngLatBbox.from_dict(dictionary['lng_lat_box']),
+            ZoomRange.from_dict(dictionary['zoom_range']),
+            dictionary['tile_size'], dictionary['grid_width'],
+            dictionary['grid_height']
+        )
+
+
+class TileGenerator:
+    """
+        - tile_sizes = Array of tile sizes in pixel, which should be rendered
+        - zoom_range = Range of zooms, tiles are created for
+        - densities = Array with counts of data points per density_base, where
+          tiles are created for
+        - density_base = Radios of circle as a datum plane for the densities
+          values
+        - nodata_value = Value used for pixels without valid data
+    """
+    def __init__(
+        self,
+        tile_sizes=[256, 512],
+        densities=[10, 100],
+        density_base=100,
+        nodata_value=-999.0,
+        debug=False
+    ):
+        self._tile_sizes = tile_sizes
+        self._densities = densities
+        self._density_base = density_base
+        self._nodata_value = nodata_value
+        self._debug = debug
+
+        # -999 is a workaround, as long gdal python api does not handle
+        # addAlpha
+        self._colors = {
+            -999: '255 255 255',
+            0: '0 0 139',
+            2: '30 144 255',
+            6: '173 216 230',
+            10: '240 248 255'
+        }
+
+        ogr.UseExceptions()
+
+    def fit_extent_to_tiles(self, lng_lat_box, zoom_range):
+        """
+            Enlarges the extent (given by lng_lat_box) to the borders of the
+            tiles lng_lat_box is of Type LngLatBbox
+        """
+        tile_bounding = mercantile.bounding_tile(
+            lng_lat_box.west(), lng_lat_box.south(), lng_lat_box.east(),
+            lng_lat_box.north()
+        )
+        if tile_bounding.z > zoom_range.minimum():
+            return LngLatBbox.from_mercantile_bbox(
+                mercantile.bounds(
+                    mercantile.parent(
+                        tile_bounding, zoom=zoom_range.minimum()
+                    )
+                )
+            )
+        else:
+            return LngLatBbox.from_mercantile_bbox(
+                mercantile.bounds(tile_bounding)
+            )
+
+    def slices(
+        self,
+        input_file,
+        zoom_range,
+        tile_sizes=None,
+        raster_file_size_max=1024 * 1024 * 1024 * 8
+    ):
+        """
+            Slice the complete area of input_file into smaller pieces,
+            so that each created raster file is smaller than
+            raster_file_size_max and cut into pieces at the borders of
+            tiles and not thorugh tiles. It returns an array of latitude
+            longitude boxes representaing the borders, per slice.
+        """
+        if tile_sizes is None:
+            tile_sizes = self._tile_sizes
+
+        datasource = self._datasource_open(input_file)
+        source_layer = datasource.GetLayerByIndex(0)
+        west, east, south, north = source_layer.GetExtent()
+
+        raster_slices = []
+        for tile_size in tile_sizes:
+            # fitting to tile borders
+            lng_lat_box = self.fit_extent_to_tiles(
+                LngLatBbox(west, south, east, north), zoom_range
+            )
+            # The lng_lat_box is exactly on the border between tiles.
+            # Since there are rounding errors, we move the corner edges
+            # a very little bit (about a few mm) into the tile. This makes
+            # sure, that we only get those tiles returned, which are really
+            # in the lng_lat_box.
+            tiles_zoom_min = mercantile.tiles(
+                lng_lat_box.west() + 1 * 10**-7,
+                lng_lat_box.south() + 1 * 10**-7,
+                lng_lat_box.east() - 1 * 10**-7,
+                lng_lat_box.north() - 1 * 10**-7, zoom_range.minimum()
+            )
+
+            # calculating size of raster file for GDT_Float32 = 32bits
+            delta_zoom = math.floor(
+                math.log(raster_file_size_max / (tile_size**2 * 32)) /
+                math.log(4)
+            )
+            steps = math.floor(
+                (zoom_range.maximum() - zoom_range.minimum()) / delta_zoom
+            )
+            zoom_steps = []
+            step = zoom_range.minimum()
+            while step < zoom_range.maximum():
+                zoom_steps.append(step)
+                step += delta_zoom + 1
+            for tile in tiles_zoom_min:
+                raster_slices += self._slice_tile(
+                    tile, zoom_steps, zoom_range.maximum(), tile_size,
+                    source_layer
+                )
+        return raster_slices
+
+    def _slice_tile(
+        self,
+        parent_tile,
+        zoom_steps,
+        zoom_total_max,
+        tile_size,
+        source_layer,
+        tiles_with_geometry=True
+    ):
+        if len(zoom_steps) < 1:
+            raise ValueError('No zoomsteps given to slice tile generation')
+        zoom_min = zoom_steps[0]
+        if len(zoom_steps) < 2:
+            zoom_max = zoom_total_max
+        else:
+            zoom_max = zoom_steps[1] - 1
+
+        raster_slices = []
+        lng_lat_box = mercantile.bounds(parent_tile)
+        width = math.sqrt(4**(zoom_max - zoom_min)) * tile_size
+        if width != round(width):
+            raise ValueError('Found a slice, with incomplete tiles')
+        raster_slice = RasterSlice(
+            LngLatBbox.from_mercantile_bbox(lng_lat_box),
+            ZoomRange(zoom_min, zoom_max), tile_size, width, width
+        )
+        raster_slices.append(raster_slice)
+        if len(zoom_steps) > 1:
+            zoom_steps_new = copy.deepcopy(zoom_steps)
+            zoom_steps_new.pop(0)
+            zoom_min_new = zoom_steps_new[0]
+            for child in mercantile.children(parent_tile, zoom=zoom_min_new):
+                # test, if tile has geometry
+                lng_lat_box = mercantile.bounds(child)
+                source_layer.SetSpatialFilterRect(
+                    lng_lat_box.west, lng_lat_box.south, lng_lat_box.east,
+                    lng_lat_box.north
+                )
+                if source_layer.GetNextFeature() or not tiles_with_geometry:
+                    raster_slices += self._slice_tile(
+                        child,
+                        zoom_steps_new,
+                        zoom_total_max,
+                        tile_size,
+                        source_layer,
+                        tiles_with_geometry=tiles_with_geometry
+                    )
+                source_layer.SetSpatialFilter(None)
+        return raster_slices
+
+    def run(
+        self,
+        input_file,
+        output_directory,
+        tile_slice,
+        densities=None,
+        density_base=None,
+        nodata_value=None
+    ):
+        """
+            Runs all nescessary steps to create the tiles.
+            All default parameters equal to none are replaced by the one
+            of the object input_file = vrt source file used as a base for
+            all steps to creating the tiles. Returns an array of paths with
+            the created tiles if successfull
+        """
+        if densities is None:
+            densities = self._densities
+        if density_base is None:
+            density_base = self._density_base
+        if nodata_value is None:
+            nodata_value = self._nodata_value
+
+        # get source boundaries (Envelope / Extent)
+        datasource = self._datasource_open(input_file)
+        source_layer = datasource.GetLayerByIndex(0)
+        (source_x_min, source_x_max,
+         source_y_min, source_y_max) = source_layer.GetExtent()
+        source_layer_name = source_layer.GetName()
+
+        # define density information for gridding algorithm
+        lon_metre_max = 60 * 1852 * math.cos(
+            math.radians(min(source_y_min, source_y_max))
+        )  # metre / degree
+        lat_metre_max = 111694  # metre / degree
+        circle_radius = math.sqrt(density_base) / math.pi
+        radius_x = circle_radius / lon_metre_max
+        radius_y = circle_radius / lat_metre_max
+
+        tile_result_paths = []
+        for density_min in densities:
+            gridding_algorithm = ('average:radius1={}:radius2={}:angle=0.0:'
+                                  'min_points={}:nodata={}').format(
+                radius_x, radius_y, density_min, nodata_value
+            )
+            if self._debug:
+                print(
+                    "Run for density {} and {} tile size:".format(
+                        density_min, tile_slice.tile_size()
+                    )
+                )
+                print("  Statistics:")
+                print(
+                    "    Found {} Points".format(
+                        source_layer.GetFeatureCount()
+                    )
+                )
+                print(
+                    "    Min density per squaredegree: {}".format(
+                        density_min * density_base / lon_metre_max /
+                        lat_metre_max
+                    )
+                )
+                print(
+                    "    Min density per pixel: {}".format(
+                        density_min * density_base /
+                        (degree_per_pixel_lon * lon_metre_max) /
+                        (degree_per_pixel_lat * lat_metre_max)
+                    )
+                )
+                print("    gridding algorithm {}".format(gridding_algorithm))
+
+            # create the grid data
+            raster_file = self.raster_create(
+                input_file, source_layer_name, tile_slice, gridding_algorithm
+            )
+            # hillshade
+            hillshade_file = self.hillshade_create(raster_file)
+            # color relief
+            color_relief_file = self.color_relief_create(raster_file)
+            # slopeshade
+            slopeshade_file = os.path.join(
+                output_directory, 'water_depth_slopeshade.tif'
+            )
+            slopeshade_file = self.slopeshade_create(
+                raster_file, slopeshade_file
+            )
+            # merge color relief and hillshade
+            merged_file = os.path.join(
+                output_directory,
+                'water_depth_{}_{}.tif'.format(density_min, density_base)
+            )
+            self.merge_color_relief_hillshade(
+                color_relief_file, hillshade_file, merged_file
+            )
+            # create the tiles
+            title = ('GNUBoat {} datasets per {} squaremetre, '
+                     'Tilesize: {}').format(
+                density_min, density_base, tile_slice.tile_size()
+            )
+            prefix_density = '{}_{}'.format(density_min, density_base)
+            tiles_output = os.path.join(
+                output_directory,
+                '{}/{}'.format(prefix_density, tile_slice.tile_size())
+            )
+            self.tiles_create(
+                merged_file,
+                title,
+                tile_slice.tile_size(),
+                tiles_output,
+                zoom_range=tile_slice.zoom_range()
+            )
+            tile_result_paths.append(
+                ResultPath(
+                    tiles_output, {
+                        'tile_size': str(tile_slice.tile_size()),
+                        'density': prefix_density
+                    }
+                )
+            )
+        return tile_result_paths
+
+    def raster_create(
+        self,
+        input_file,
+        layers,
+        tile_slice,
+        gridding_algorithm,
+        nodata_value=None,
+        output_file='/vsimem/water_depth.tif'
+    ):
+        """
+            Rastering the data from source file into a tif.
+            The input should be a vrt source file.
+            The function returns the path to the generated tif file.
+        """
+        if nodata_value is None:
+            nodata_value = self._nodata_value
+
+        grid_options = gdal.GridOptions(
+            outputType=gdal.GDT_Float32,
+            format="GTiff",
+            width=tile_slice.grid_width(),
+            height=tile_slice.grid_height(),
+            outputSRS="WGS84",
+            outputBounds=[
+                tile_slice.lng_lat_bbox().west(),
+                tile_slice.lng_lat_bbox().north(),
+                tile_slice.lng_lat_bbox().east(),
+                tile_slice.lng_lat_bbox().south()
+            ],
+            noData=nodata_value,
+            layers=layers,
+            spatFilter=(
+                tile_slice.lng_lat_bbox().west(),
+                tile_slice.lng_lat_bbox().south(),
+                tile_slice.lng_lat_bbox().east(),
+                tile_slice.lng_lat_bbox().north()
+            ),
+            algorithm=gridding_algorithm
+        )
+        gdal.Grid(output_file, input_file, options=grid_options)
+        return output_file
+
+    def hillshade_create(
+        self, input_file, output_file='/vsimem/water_depth_hillshade.tif'
+    ):
+        """
+            Creates the hillshade from a raster tif file and returns the path
+            to the resulting tif file
+        """
+        gdal.DEMProcessing(
+            output_file,
+            input_file,
+            "hillshade",
+            options=gdal.DEMProcessingOptions(format="GTiff", zFactor=-1)
+        )
+        return output_file
+
+    def color_relief_create(
+        self,
+        input_file,
+        output_file='/vsimem/water_depth_color_relief.tif',
+        colors=None
+    ):
+        """
+            Creates the color relief from a raster tif and returns
+            the path to the resulting tif file
+        """
+        if colors is None:
+            colors = self._colors
+
+        gdal_file_color_relief_config = tempfile.NamedTemporaryFile(
+            mode='w', suffix='txt'
+        )
+        for depth in colors:
+            gdal_file_color_relief_config.write(
+                "{} {}\n".format(depth, colors[depth])
+            )
+        gdal_file_color_relief_config.flush()
+        gdal.DEMProcessing(
+            output_file,
+            input_file,
+            "color-relief",
+            options=gdal.DEMProcessingOptions(
+                format="GTiff",
+                colorFilename=gdal_file_color_relief_config.name
+            ),
+            addAlpha=True
+        )
+        gdal_file_color_relief_config.close()
+        return output_file
+
+    def slopeshade_create(self, input_file, output_file):
+        gdal_file_slopeshade_tmp = "/vsimem/tmp_water_depth_slopeshade.tif"
+        gdal_file_slopeshade_config = tempfile.NamedTemporaryFile(
+            mode='w', suffix='txt'
+        )
+        gdal_file_slopeshade_config.write("0 255 255 255\n")
+        gdal_file_slopeshade_config.write("90 0 0 0\n")
+        gdal_file_slopeshade_config.write("270 0 0 0\n")
+        gdal_file_slopeshade_config.write("360 255 255 255\n")
+        gdal_file_slopeshade_config.flush()
+        gdal.DEMProcessing(
+            gdal_file_slopeshade_tmp,
+            input_file,
+            "slope",
+            options=gdal.DEMProcessingOptions(format="GTiff"),
+            slopeFormat='degree',
+            zeroForFlat=True,
+            addAlpha=True
+        )
+        gdal.DEMProcessing(
+            output_file,
+            gdal_file_slopeshade_tmp,
+            "color-relief",
+            options=gdal.DEMProcessingOptions(
+                format="GTiff", colorFilename=gdal_file_slopeshade_config.name
+            ),
+            addAlpha=True
+        )
+        gdal_file_slopeshade_config.close()
+        return output_file
+
+    def merge_color_relief_hillshade(
+        self, input_color_relief_file, input_hillshade_file, output_file
+    ):
+        # dstNodata is a workaround for not working addAlpha in color-relief
+        gdal.Warp(
+            output_file, [input_color_relief_file, input_hillshade_file],
+            options=gdal.WarpOptions(
+                format='GTiff', dstAlpha=False, dstNodata="255 255 255"
+            )
+        )
+        return output_file
+
+    def tiles_create(
+        self, input_file, title, tile_size, output_directory, zoom_range
+    ):
+        tile_zoom_option = '{}-{}'.format(
+            zoom_range.minimum(), zoom_range.maximum()
+        )
+        # using the patched (tilesize) gdal2tiles.py script here, until the
+        # upstream version mades it in the distros
+        subprocess.run([
+            'gdal2tiles-gnuboat.py', '-q', '-w', 'none',
+            '--tilesize={}'.format(tile_size), '-z', tile_zoom_option,
+            '-t', title, input_file, output_directory],
+            check=True,
+            stdout=subprocess.PIPE,
+            stderr=subprocess.PIPE)
+
+    def move_tiles_in_place(self, source_path, target_path, skip_empty=True):
+        """
+            Moves the generated tiles from the source_path into the
+            target_path. It moves file per file, so that the tiles are
+            going to be integrated into an existing folder. If
+            skip_emtpy = True only one empty tile is copied to the
+            top level directory. All other empty tiles are not moved
+            into target_path.
+        """
+        copied_empty_tile = False
+
+        src_path = Path(source_path)
+        trg_path = Path(target_path)
+        empty_tile = trg_path.joinpath('empty_tile.png')
+        for path in Path(source_path).rglob('*.png'):
+            # Substract source_path from path and make it relative to
+            # target_path
+            relative = path.relative_to(src_path)
+            relative_path = trg_path.joinpath(relative)
+            if self._tile_is_empty(path) and skip_empty:
+                if not copied_empty_tile:
+                    if not empty_tile.parent.exists():
+                        os.makedirs(empty_tile.parent)
+                    shutil.copy(path, empty_tile)
+                    copied_empty_tile = True
+            else:
+                if not relative_path.parent.exists():
+                    os.makedirs(relative_path.parent)
+                shutil.copy(path, relative_path)
+
+    def _datasource_open(self, source_file):
+        datasource = ogr.Open(source_file)
+        if datasource is None:
+            raise FileNotFoundError(
+                'Could not open input file {}'.format(source_file)
+            )
+        if datasource.GetLayerCount() < 1:
+            raise ReferenceError('No layers in input file')
+        return datasource
+
+    def _tile_is_empty(self, tile_file_path):
+        is_empty = True
+        colors_tmp = set()
+        colors_tmp_transparent = set()
+
+        img = Image.open(tile_file_path)
+        # calculate histogram for blue channel
+        colors_img = img.getcolors(256)
+        if not colors_img:
+            return False
+        else:
+            for color in colors_img:
+                color_hex = ''.join(
+                    '{:02X}'.format(value) for value in color[1]
+                )
+                if color[1][3] != 0:
+                    return False
+        return True
Index: src/gnuboat/common/spatial/tilegenerator.py
===================================================================
--- src/gnuboat/common/spatial/tilegenerator.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ 	(revision )
@@ -1,691 +1,0 @@
-# -*- coding: utf-8 -*-
-'''
-    Copyright (C) 2020 EngSaS - 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 mercantile
-from osgeo import ogr
-from osgeo import gdal
-from osgeo import gdalconst
-import tempfile
-import os
-import shutil
-import subprocess
-import math
-import copy
-from pathlib import Path
-from PIL import Image
-
-try:
-    from dataclasses import dataclass
-
-    @dataclass
-    class ResultPath:
-        """
-            path: Absolute path of the created results
-            prefixes: Dict with meaningful prefixes in the path. e.g.
-            {'tile_size': '512', 'density': '10_100'}
-        """
-        path: str
-        prefixes: dict
-
-except ImportError:
-    # Workaround for @dataclass, until python 3.7 is available in
-    # main distros
-    class ResultPath:
-        """
-            path: Absolute path of the created results
-            prefixes: Dict with meaningful prefixes in the path. e.g.
-            {'tile_size': '512', 'density': '10_100'}
-        """
-        def __init__(self, path, prefixes):
-            self.path = path
-            self.prefixes = prefixes
-
-
-class ZoomRange(dict):
-    def __init__(self, minimum, maximum):
-        super(ZoomRange, self).__init__({
-            'minimum': minimum,
-            'maximum': maximum
-        })
-
-    def minimum(self):
-        return self['minimum']
-
-    def maximum(self):
-        return self['maximum']
-
-    def from_dict(dictionary):
-        return ZoomRange(dictionary['minimum'], dictionary['maximum'])
-
-
-class LngLatBbox(dict):
-    def __init__(self, west, south, east, north):
-        super(LngLatBbox, self).__init__({
-            'west': west,
-            'south': south,
-            'east': east,
-            'north': north
-        })
-
-    def west(self):
-        return self['west']
-
-    def south(self):
-        return self['south']
-
-    def east(self):
-        return self['east']
-
-    def north(self):
-        return self['north']
-
-    def to_mercantile_bbox(self):
-        return mercantile.LngLatBbox(
-            self.west(), self.south(), self.east(), self.north()
-        )
-
-    def from_mercantile_bbox(mercantile_bbox):
-        return LngLatBbox(
-            mercantile_bbox.west, mercantile_bbox.south, mercantile_bbox.east,
-            mercantile_bbox.north
-        )
-
-    def from_dict(dictionary):
-        if dictionary is None:
-            return None
-        return LngLatBbox(
-            dictionary['west'], dictionary['south'], dictionary['east'],
-            dictionary['north']
-        )
-
-
-class RasterSlice(dict):
-    """
-        lng_lat_box: LngLatBbox
-        zoom_range: ZoomRange
-        tile_size: The tile size in Pixel,
-        grid_width: The width of the resulting rastr
-        grid_height:  The height of the resulting rastr
-
-        It's derived from dict to be json serialisable
-    """
-    def __init__(
-        self, lng_lat_box, zoom_range, tile_size, grid_width, grid_height
-    ):
-        super(RasterSlice, self).__init__({
-            'lng_lat_box': lng_lat_box,
-            'zoom_range': zoom_range,
-            'tile_size': tile_size,
-            'grid_width': grid_width,
-            'grid_height': grid_height
-        })
-
-    def lng_lat_bbox(self):
-        return self['lng_lat_box']
-
-    def zoom_range(self):
-        return self['zoom_range']
-
-    def tile_size(self):
-        return self['tile_size']
-
-    def grid_width(self):
-        return self['grid_width']
-
-    def grid_height(self):
-        return self['grid_height']
-
-    def from_dict(dictionary):
-        if dictionary is None:
-            return None
-        return RasterSlice(
-            LngLatBbox.from_dict(dictionary['lng_lat_box']),
-            ZoomRange.from_dict(dictionary['zoom_range']),
-            dictionary['tile_size'], dictionary['grid_width'],
-            dictionary['grid_height']
-        )
-
-
-class TileGenerator:
-    """
-        - tile_sizes = Array of tile sizes in pixel, which should be rendered
-        - zoom_range = Range of zooms, tiles are created for
-        - densities = Array with counts of data points per density_base, where
-          tiles are created for
-        - density_base = Radios of circle as a datum plane for the densities
-          values
-        - nodata_value = Value used for pixels without valid data
-    """
-    def __init__(
-        self,
-        tile_sizes=[256, 512],
-        densities=[10, 100],
-        density_base=100,
-        nodata_value=-999.0,
-        debug=False
-    ):
-        self._tile_sizes = tile_sizes
-        self._densities = densities
-        self._density_base = density_base
-        self._nodata_value = nodata_value
-        self._debug = debug
-
-        # -999 is a workaround, as long gdal python api does not handle
-        # addAlpha
-        self._colors = {
-            -999: '255 255 255',
-            0: '0 0 139',
-            2: '30 144 255',
-            6: '173 216 230',
-            10: '240 248 255'
-        }
-
-        ogr.UseExceptions()
-
-    def fit_extent_to_tiles(self, lng_lat_box, zoom_range):
-        """
-            Enlarges the extent (given by lng_lat_box) to the borders of the
-            tiles lng_lat_box is of Type LngLatBbox
-        """
-        tile_bounding = mercantile.bounding_tile(
-            lng_lat_box.west(), lng_lat_box.south(), lng_lat_box.east(),
-            lng_lat_box.north()
-        )
-        if tile_bounding.z > zoom_range.minimum():
-            return LngLatBbox.from_mercantile_bbox(
-                mercantile.bounds(
-                    mercantile.parent(
-                        tile_bounding, zoom=zoom_range.minimum()
-                    )
-                )
-            )
-        else:
-            return LngLatBbox.from_mercantile_bbox(
-                mercantile.bounds(tile_bounding)
-            )
-
-    def slices(
-        self,
-        input_file,
-        zoom_range,
-        tile_sizes=None,
-        raster_file_size_max=1024 * 1024 * 1024 * 8
-    ):
-        """
-            Slice the complete area of input_file into smaller pieces,
-            so that each created raster file is smaller than
-            raster_file_size_max and cut into pieces at the borders of
-            tiles and not thorugh tiles. It returns an array of latitude
-            longitude boxes representaing the borders, per slice.
-        """
-        if tile_sizes is None:
-            tile_sizes = self._tile_sizes
-
-        datasource = self._datasource_open(input_file)
-        source_layer = datasource.GetLayerByIndex(0)
-        west, east, south, north = source_layer.GetExtent()
-
-        raster_slices = []
-        for tile_size in tile_sizes:
-            # fitting to tile borders
-            lng_lat_box = self.fit_extent_to_tiles(
-                LngLatBbox(west, south, east, north), zoom_range
-            )
-            # The lng_lat_box is exactly on the border between tiles.
-            # Since there are rounding errors, we move the corner edges
-            # a very little bit (about a few mm) into the tile. This makes
-            # sure, that we only get those tiles returned, which are really
-            # in the lng_lat_box.
-            tiles_zoom_min = mercantile.tiles(
-                lng_lat_box.west() + 1 * 10**-7,
-                lng_lat_box.south() + 1 * 10**-7,
-                lng_lat_box.east() - 1 * 10**-7,
-                lng_lat_box.north() - 1 * 10**-7, zoom_range.minimum()
-            )
-
-            # calculating size of raster file for GDT_Float32 = 32bits
-            delta_zoom = math.floor(
-                math.log(raster_file_size_max / (tile_size**2 * 32)) /
-                math.log(4)
-            )
-            steps = math.floor(
-                (zoom_range.maximum() - zoom_range.minimum()) / delta_zoom
-            )
-            zoom_steps = []
-            step = zoom_range.minimum()
-            while step < zoom_range.maximum():
-                zoom_steps.append(step)
-                step += delta_zoom + 1
-            for tile in tiles_zoom_min:
-                raster_slices += self._slice_tile(
-                    tile, zoom_steps, zoom_range.maximum(), tile_size,
-                    source_layer
-                )
-        return raster_slices
-
-    def _slice_tile(
-        self,
-        parent_tile,
-        zoom_steps,
-        zoom_total_max,
-        tile_size,
-        source_layer,
-        tiles_with_geometry=True
-    ):
-        if len(zoom_steps) < 1:
-            raise ValueError('No zoomsteps given to slice tile generation')
-        zoom_min = zoom_steps[0]
-        if len(zoom_steps) < 2:
-            zoom_max = zoom_total_max
-        else:
-            zoom_max = zoom_steps[1] - 1
-
-        raster_slices = []
-        lng_lat_box = mercantile.bounds(parent_tile)
-        width = math.sqrt(4**(zoom_max - zoom_min)) * tile_size
-        if width != round(width):
-            raise ValueError('Found a slice, with incomplete tiles')
-        raster_slice = RasterSlice(
-            LngLatBbox.from_mercantile_bbox(lng_lat_box),
-            ZoomRange(zoom_min, zoom_max), tile_size, width, width
-        )
-        raster_slices.append(raster_slice)
-        if len(zoom_steps) > 1:
-            zoom_steps_new = copy.deepcopy(zoom_steps)
-            zoom_steps_new.pop(0)
-            zoom_min_new = zoom_steps_new[0]
-            for child in mercantile.children(parent_tile, zoom=zoom_min_new):
-                # test, if tile has geometry
-                lng_lat_box = mercantile.bounds(child)
-                source_layer.SetSpatialFilterRect(
-                    lng_lat_box.west, lng_lat_box.south, lng_lat_box.east,
-                    lng_lat_box.north
-                )
-                if source_layer.GetNextFeature() or not tiles_with_geometry:
-                    raster_slices += self._slice_tile(
-                        child,
-                        zoom_steps_new,
-                        zoom_total_max,
-                        tile_size,
-                        source_layer,
-                        tiles_with_geometry=tiles_with_geometry
-                    )
-                source_layer.SetSpatialFilter(None)
-        return raster_slices
-
-    def run(
-        self,
-        input_file,
-        output_directory,
-        tile_slice,
-        densities=None,
-        density_base=None,
-        nodata_value=None
-    ):
-        """
-            Runs all nescessary steps to create the tiles.
-            All default parameters equal to none are replaced by the one
-            of the object input_file = vrt source file used as a base for
-            all steps to creating the tiles. Returns an array of paths with
-            the created tiles if successfull
-        """
-        if densities is None:
-            densities = self._densities
-        if density_base is None:
-            density_base = self._density_base
-        if nodata_value is None:
-            nodata_value = self._nodata_value
-
-        # get source boundaries (Envelope / Extent)
-        datasource = self._datasource_open(input_file)
-        source_layer = datasource.GetLayerByIndex(0)
-        (source_x_min, source_x_max,
-         source_y_min, source_y_max) = source_layer.GetExtent()
-        source_layer_name = source_layer.GetName()
-
-        # define density information for gridding algorithm
-        lon_metre_max = 60 * 1852 * math.cos(
-            math.radians(min(source_y_min, source_y_max))
-        )  # metre / degree
-        lat_metre_max = 111694  # metre / degree
-        circle_radius = math.sqrt(density_base) / math.pi
-        radius_x = circle_radius / lon_metre_max
-        radius_y = circle_radius / lat_metre_max
-
-        tile_result_paths = []
-        for density_min in densities:
-            gridding_algorithm = ('average:radius1={}:radius2={}:angle=0.0:'
-                                  'min_points={}:nodata={}').format(
-                radius_x, radius_y, density_min, nodata_value
-            )
-            if self._debug:
-                print(
-                    "Run for density {} and {} tile size:".format(
-                        density_min, tile_slice.tile_size()
-                    )
-                )
-                print("  Statistics:")
-                print(
-                    "    Found {} Points".format(
-                        source_layer.GetFeatureCount()
-                    )
-                )
-                print(
-                    "    Min density per squaredegree: {}".format(
-                        density_min * density_base / lon_metre_max /
-                        lat_metre_max
-                    )
-                )
-                print(
-                    "    Min density per pixel: {}".format(
-                        density_min * density_base /
-                        (degree_per_pixel_lon * lon_metre_max) /
-                        (degree_per_pixel_lat * lat_metre_max)
-                    )
-                )
-                print("    gridding algorithm {}".format(gridding_algorithm))
-
-            # create the grid data
-            raster_file = self.raster_create(
-                input_file, source_layer_name, tile_slice, gridding_algorithm
-            )
-            # hillshade
-            hillshade_file = self.hillshade_create(raster_file)
-            # color relief
-            color_relief_file = self.color_relief_create(raster_file)
-            # slopeshade
-            slopeshade_file = os.path.join(
-                output_directory, 'water_depth_slopeshade.tif'
-            )
-            slopeshade_file = self.slopeshade_create(
-                raster_file, slopeshade_file
-            )
-            # merge color relief and hillshade
-            merged_file = os.path.join(
-                output_directory,
-                'water_depth_{}_{}.tif'.format(density_min, density_base)
-            )
-            self.merge_color_relief_hillshade(
-                color_relief_file, hillshade_file, merged_file
-            )
-            # create the tiles
-            title = ('GNUBoat {} datasets per {} squaremetre, '
-                     'Tilesize: {}').format(
-                density_min, density_base, tile_slice.tile_size()
-            )
-            prefix_density = '{}_{}'.format(density_min, density_base)
-            tiles_output = os.path.join(
-                output_directory,
-                '{}/{}'.format(prefix_density, tile_slice.tile_size())
-            )
-            self.tiles_create(
-                merged_file,
-                title,
-                tile_slice.tile_size(),
-                tiles_output,
-                zoom_range=tile_slice.zoom_range()
-            )
-            tile_result_paths.append(
-                ResultPath(
-                    tiles_output, {
-                        'tile_size': str(tile_slice.tile_size()),
-                        'density': prefix_density
-                    }
-                )
-            )
-        return tile_result_paths
-
-    def raster_create(
-        self,
-        input_file,
-        layers,
-        tile_slice,
-        gridding_algorithm,
-        nodata_value=None,
-        output_file='/vsimem/water_depth.tif'
-    ):
-        """
-            Rastering the data from source file into a tif.
-            The input should be a vrt source file.
-            The function returns the path to the generated tif file.
-        """
-        if nodata_value is None:
-            nodata_value = self._nodata_value
-
-        grid_options = gdal.GridOptions(
-            outputType=gdal.GDT_Float32,
-            format="GTiff",
-            width=tile_slice.grid_width(),
-            height=tile_slice.grid_height(),
-            outputSRS="WGS84",
-            outputBounds=[
-                tile_slice.lng_lat_bbox().west(),
-                tile_slice.lng_lat_bbox().north(),
-                tile_slice.lng_lat_bbox().east(),
-                tile_slice.lng_lat_bbox().south()
-            ],
-            noData=nodata_value,
-            layers=layers,
-            spatFilter=(
-                tile_slice.lng_lat_bbox().west(),
-                tile_slice.lng_lat_bbox().south(),
-                tile_slice.lng_lat_bbox().east(),
-                tile_slice.lng_lat_bbox().north()
-            ),
-            algorithm=gridding_algorithm
-        )
-        gdal.Grid(output_file, input_file, options=grid_options)
-        return output_file
-
-    def hillshade_create(
-        self, input_file, output_file='/vsimem/water_depth_hillshade.tif'
-    ):
-        """
-            Creates the hillshade from a raster tif file and returns the path
-            to the resulting tif file
-        """
-        gdal.DEMProcessing(
-            output_file,
-            input_file,
-            "hillshade",
-            options=gdal.DEMProcessingOptions(format="GTiff", zFactor=-1)
-        )
-        return output_file
-
-    def color_relief_create(
-        self,
-        input_file,
-        output_file='/vsimem/water_depth_color_relief.tif',
-        colors=None
-    ):
-        """
-            Creates the color relief from a raster tif and returns
-            the path to the resulting tif file
-        """
-        if colors is None:
-            colors = self._colors
-
-        gdal_file_color_relief_config = tempfile.NamedTemporaryFile(
-            mode='w', suffix='txt'
-        )
-        for depth in colors:
-            gdal_file_color_relief_config.write(
-                "{} {}\n".format(depth, colors[depth])
-            )
-        gdal_file_color_relief_config.flush()
-        gdal.DEMProcessing(
-            output_file,
-            input_file,
-            "color-relief",
-            options=gdal.DEMProcessingOptions(
-                format="GTiff",
-                colorFilename=gdal_file_color_relief_config.name
-            ),
-            addAlpha=True
-        )
-        gdal_file_color_relief_config.close()
-        return output_file
-
-    def slopeshade_create(self, input_file, output_file):
-        gdal_file_slopeshade_tmp = "/vsimem/tmp_water_depth_slopeshade.tif"
-        gdal_file_slopeshade_config = tempfile.NamedTemporaryFile(
-            mode='w', suffix='txt'
-        )
-        gdal_file_slopeshade_config.write("0 255 255 255\n")
-        gdal_file_slopeshade_config.write("90 0 0 0\n")
-        gdal_file_slopeshade_config.write("270 0 0 0\n")
-        gdal_file_slopeshade_config.write("360 255 255 255\n")
-        gdal_file_slopeshade_config.flush()
-        gdal.DEMProcessing(
-            gdal_file_slopeshade_tmp,
-            input_file,
-            "slope",
-            options=gdal.DEMProcessingOptions(format="GTiff"),
-            slopeFormat='degree',
-            zeroForFlat=True,
-            addAlpha=True
-        )
-        gdal.DEMProcessing(
-            output_file,
-            gdal_file_slopeshade_tmp,
-            "color-relief",
-            options=gdal.DEMProcessingOptions(
-                format="GTiff", colorFilename=gdal_file_slopeshade_config.name
-            ),
-            addAlpha=True
-        )
-        gdal_file_slopeshade_config.close()
-        return output_file
-
-    def merge_color_relief_hillshade(
-        self, input_color_relief_file, input_hillshade_file, output_file
-    ):
-        # dstNodata is a workaround for not working addAlpha in color-relief
-        gdal.Warp(
-            output_file, [input_color_relief_file, input_hillshade_file],
-            options=gdal.WarpOptions(
-                format='GTiff', dstAlpha=False, dstNodata="255 255 255"
-            )
-        )
-        return output_file
-
-    def tiles_create(
-        self, input_file, title, tile_size, output_directory, zoom_range
-    ):
-        tile_zoom_option = '{}-{}'.format(
-            zoom_range.minimum(), zoom_range.maximum()
-        )
-        # using the patched (tilesize) gdal2tiles.py script here, until the
-        # upstream version mades it in the distros
-        subprocess.run([
-            'gdal2tiles-gnuboat.py', '-q', '-w', 'none',
-            '--tilesize={}'.format(tile_size), '-z', tile_zoom_option,
-            '-t', title, input_file, output_directory],
-            check=True,
-            stdout=subprocess.PIPE,
-            stderr=subprocess.PIPE)
-
-    def move_tiles_in_place(self, source_path, target_path, skip_empty=True):
-        """
-            Moves the generated tiles from the source_path into the
-            target_path. It moves file per file, so that the tiles are
-            going to be integrated into an existing folder. If
-            skip_emtpy = True only one empty tile is copied to the
-            top level directory. All other empty tiles are not moved
-            into target_path.
-        """
-        copied_empty_tile = False
-
-        src_path = Path(source_path)
-        trg_path = Path(target_path)
-        empty_tile = trg_path.joinpath('empty_tile.png')
-        for path in Path(source_path).rglob('*.png'):
-            # Substract source_path from path and make it relative to
-            # target_path
-            relative = path.relative_to(src_path)
-            relative_path = trg_path.joinpath(relative)
-            if self._tile_is_empty(path) and skip_empty:
-                if not copied_empty_tile:
-                    if not empty_tile.parent.exists():
-                        os.makedirs(empty_tile.parent)
-                    shutil.copy(path, empty_tile)
-                    copied_empty_tile = True
-            else:
-                if not relative_path.parent.exists():
-                    os.makedirs(relative_path.parent)
-                shutil.copy(path, relative_path)
-
-    def _datasource_open(self, source_file):
-        datasource = ogr.Open(source_file)
-        if datasource is None:
-            raise FileNotFoundError(
-                'Could not open input file {}'.format(source_file)
-            )
-        if datasource.GetLayerCount() < 1:
-            raise ReferenceError('No layers in input file')
-        return datasource
-
-    def _tile_is_empty(self, tile_file_path):
-        is_empty = True
-        colors_tmp = set()
-        colors_tmp_transparent = set()
-
-        img = Image.open(tile_file_path)
-        # calculate histogram for blue channel
-        colors_img = img.getcolors(256)
-        if not colors_img:
-            return False
-        else:
-            for color in colors_img:
-                color_hex = ''.join(
-                    '{:02X}'.format(value) for value in color[1]
-                )
-                if color[1][3] != 0:
-                    return False
-        return True
-
-    # def contours_create():
-    # @todo Cut Tifs / warp
-    # contour_input = gdal.Open(gdal_file, gdalconst.GA_ReadOnly)
-    # contour_input_band = contour_input.GetRasterBand(1)
-    # Generate layer to save Contourlines in
-    # contour_output = ogr.GetDriverByName("ESRI Shapefile")
-    #    .CreateDataSource(gdal_file_contours)
-    # proj = osr.SpatialReference()
-    # proj.SetWellKnownGeogCS(input_epsg)
-    # for depth in colors:
-    # contour_layer = contour_output.CreateLayer('contour_{}_{}_{}'
-    #    .format(density_min, density_base, depth), srs = proj)
-    # field_definition = ogr.FieldDefn("ID", ogr.OFTInteger)
-    # contour_layer.CreateField(field_definition)
-    # field_definition = ogr.FieldDefn("elev", ogr.OFTReal)
-    # contour_layer.CreateField(field_definition)
-    # Generate Contourlines
-    # gdal.ContourGenerate(contour_input_band, depth, 0, [], 0, 0,
-    #    contour_layer, 0, 1)
-    # contour_output = None
-    # del contour_output
-    # print("  Created contour lines {}".format(gdal_file_contours))
-
-    # def crop():
-    #  cropping the tifs
-    # gdal.Warp('/tmp/gnuboat/test.tif', gdal_file_color_relief,
-    #    options = gdal.WarpOptions(format = 'GTiff', dstAlpha = True,
-    #        srcNodata = "255 255 255", dstNodata = target_nodata_value,
-    #        cutlineDSName = '/tmp/gnuboat/c contours/contour-0.shp',
-    #        cutlineLayer="contour-0", cropToCutline=True))
Index: src/gnuboat/common/tests/test_config.py
===================================================================
--- src/gnuboat/common/tests/test_config.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ src/gnuboat/common/tests/test_config.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -21,5 +21,5 @@
 import os
 
-from gnuboat.common.webservice import Config as configure
+from gnuboat.common.webservice import config as configure
 
 
Index: src/gnuboat/common/tests/test_tile_generator.py
===================================================================
--- src/gnuboat/common/tests/test_tile_generator.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/common/tests/test_tile_generator.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,393 @@
+'''
+    Copyright (C) 2020 EngSaS - 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 pytest
+import os
+import tempfile
+import xml.etree.ElementTree as ET
+import mercantile
+import math
+import shutil
+from osgeo import gdal
+from osgeo import ogr
+from osgeo import osr
+
+from gnuboat.common.spatial import tile_generator as tilegenerator
+
+
+def compare_lng_lat_bbox(left, right):
+    assert math.isclose(left.east(), right.east(), rel_tol=10**-7), \
+        '{:.7f} != {:.7f} vs. West {} != {}'.format(
+            left.east(), right.east(), left.west(), right.west())
+    assert math.isclose(left.south(), right.south(), rel_tol=10**-7), \
+        '{:.7f} != {:.7f}'.format(left.south(), right.south())
+    assert math.isclose(left.west(), right.west(), rel_tol=10**-7), \
+        '{:.7f} != {:.7f}'.format(left.west(), right.west())
+    assert math.isclose(left.north(), right.north(), rel_tol=10**-7), \
+        '{:.7f} != {:.7f}'.format(left.north(), right.north())
+
+
+@pytest.mark.parametrize(
+    "data, result", [
+        ({
+            'lng_lat_bbox':
+                tilegenerator.LngLatBbox(
+                    10.041963, 48.427407, 10.043652, 48.428932
+                ),
+            'zoom_range':
+                tilegenerator.ZoomRange(18, 19)
+        },
+         tilegenerator.LngLatBbox(10.041504, 48.427378, 10.044250, 48.429200)),
+        ({
+            'lng_lat_bbox':
+                tilegenerator.LngLatBbox(
+                    10.041963, 48.427407, 10.043652, 48.428932
+                ),
+            'zoom_range':
+                tilegenerator.ZoomRange(14, 19)
+        },
+         tilegenerator.LngLatBbox(10.041504, 48.414619, 10.063477, 48.429200)),
+        ({
+            'lng_lat_bbox':
+                tilegenerator.LngLatBbox(
+                    10.041963, 48.427407, 10.043652, 48.428932
+                ),
+            'zoom_range':
+                tilegenerator.ZoomRange(17, 19)
+        },
+         tilegenerator.LngLatBbox(10.041504, 48.427378, 10.044250, 48.429200)),
+        ({
+            'lng_lat_bbox':
+                tilegenerator.LngLatBbox(
+                    10.041963, 48.427407, 10.043652, 48.428932
+                ),
+            'zoom_range':
+                tilegenerator.ZoomRange(10, 19)
+        }, tilegenerator.LngLatBbox(9.843750, 48.224673, 10.195312,
+                                    48.458352)),
+    ]
+)
+def test_fit_extent_to_tiles(data, result):
+    tilegen = tilegenerator.TileGenerator()
+    tile = tilegen.fit_extent_to_tiles(
+        data['lng_lat_bbox'], data['zoom_range']
+    )
+    compare_lng_lat_bbox(tile, result)
+
+
+@pytest.mark.parametrize(
+    "data, result_slices", [
+        ({
+            'tile_sizes': [256],
+            'zoom_range':
+                tilegenerator.ZoomRange(14, 19),
+            'file_size':
+                4 * 1024 * 1024 * 8,
+            'datasource':
+                os.path.join(os.path.dirname(__file__), 'data/slice-log2.csv'),
+            'layer':
+                'slice-log2'
+        }, [
+            tilegenerator.RasterSlice(
+                tilegenerator.LngLatBbox(
+                    10.041504, 48.414619, 10.063477, 48.429200
+                ), tilegenerator.ZoomRange(14, 16), 256, 1024, 1024
+            ),
+            tilegenerator.RasterSlice(
+                tilegenerator.LngLatBbox(
+                    10.041504, 48.427378, 10.044250, 48.429200
+                ), tilegenerator.ZoomRange(17, 19), 256, 1024, 1024
+            )
+        ]),
+        ({
+            'tile_sizes': [256],
+            'zoom_range':
+                tilegenerator.ZoomRange(10, 19),
+            'file_size':
+                64 * 1024 * 1024 * 8,
+            'datasource':
+                os.path.join(os.path.dirname(__file__), 'data/slice-log2.csv'),
+            'layer':
+                'slice-log2'
+        }, [
+            tilegenerator.RasterSlice(
+                tilegenerator.LngLatBbox(
+                    9.843750, 48.224673, 10.195312, 48.458352
+                ), tilegenerator.ZoomRange(10, 14), 256, 4096, 4096
+            ),
+            tilegenerator.RasterSlice(
+                tilegenerator.LngLatBbox(
+                    10.041504, 48.421910, 10.052490, 48.429200
+                ), tilegenerator.ZoomRange(15, 19), 256, 4096, 4096
+            )
+        ]),
+        ({
+            'tile_sizes': [512],
+            'zoom_range':
+                tilegenerator.ZoomRange(10, 19),
+            'file_size':
+                256 * 1024 * 1024 * 8,
+            'datasource':
+                os.path.join(os.path.dirname(__file__), 'data/slice-log2.csv'),
+            'layer':
+                'slice-log2'
+        }, [
+            tilegenerator.RasterSlice(
+                tilegenerator.LngLatBbox(
+                    9.843750, 48.224673, 10.195312, 48.458352
+                ), tilegenerator.ZoomRange(10, 15), 512, 8192, 8192
+            ),
+            tilegenerator.RasterSlice(
+                tilegenerator.LngLatBbox(
+                    10.041504, 48.421910, 10.052490, 48.429200
+                ), tilegenerator.ZoomRange(16, 19), 512, 8192, 8192
+            )
+        ]),
+        ({
+            'tile_sizes': [512],
+            'zoom_range':
+                tilegenerator.ZoomRange(10, 19),
+            'file_size':
+                64 * 1024 * 1024 * 8,
+            'datasource':
+                os.path.join(os.path.dirname(__file__), 'data/slice-log2.csv'),
+            'layer':
+                'slice-log2'
+        }, [
+            tilegenerator.RasterSlice(
+                tilegenerator.LngLatBbox(
+                    9.843750, 48.224673, 10.195312, 48.458352
+                ), tilegenerator.ZoomRange(10, 13), 512, 4096, 4096
+            ),
+            tilegenerator.RasterSlice(
+                tilegenerator.LngLatBbox(
+                    10.041504, 48.414619, 10.063477, 48.429200
+                ), tilegenerator.ZoomRange(14, 17), 512, 4096, 4096
+            ),
+            tilegenerator.RasterSlice(
+                tilegenerator.LngLatBbox(
+                    10.041504, 48.428289, 10.042877, 48.429200
+                ), tilegenerator.ZoomRange(18, 19), 512, 1024, 1024
+            ),
+            tilegenerator.RasterSlice(
+                tilegenerator.LngLatBbox(
+                    10.042877, 48.428289, 10.044250, 48.429200
+                ), tilegenerator.ZoomRange(18, 19), 512, 1024, 1024
+            ),
+            tilegenerator.RasterSlice(
+                tilegenerator.LngLatBbox(
+                    10.042877, 48.427378, 10.044250, 48.428289
+                ), tilegenerator.ZoomRange(18, 19), 512, 1024, 1024
+            ),
+            tilegenerator.RasterSlice(
+                tilegenerator.LngLatBbox(
+                    10.041504, 48.427378, 10.042877, 48.428289
+                ), tilegenerator.ZoomRange(18, 19), 512, 1024, 1024
+            )
+        ]),
+    ]
+)
+def test_slicing(data, result_slices):
+    datasource_vrt = os.path.join(
+        os.path.dirname(__file__), 'data/slice-log2.vrt'
+    )
+    tilegen = tilegenerator.TileGenerator()
+    slices = tilegen.slices(
+        datasource_vrt,
+        data['zoom_range'],
+        tile_sizes=data['tile_sizes'],
+        raster_file_size_max=data['file_size']
+    )
+
+    assert len(slices) == len(result_slices)
+    for i in range(len(slices)):
+        compare_lng_lat_bbox(
+            slices[i].lng_lat_bbox(), result_slices[i].lng_lat_bbox()
+        )
+        assert slices[i].zoom_range(), result_slices[i].zoom_range()
+        assert slices[i].tile_size(), result_slices[i].tile_size()
+        assert slices[i].grid_width(), result_slices[i].grid_width()
+        assert slices[i].grid_height(), result_slices[i].grid_height()
+
+
+@pytest.mark.slow
+@pytest.mark.parametrize(
+    "tile_slice", [(
+        tilegenerator.RasterSlice(
+            tilegenerator.LngLatBbox(
+                10.041504, 48.428289, 10.042877, 48.429200
+            ), tilegenerator.ZoomRange(18, 19), 512, 1024, 1024
+        )
+    ),
+                   (
+                       tilegenerator.RasterSlice(
+                           tilegenerator.LngLatBbox(
+                               9.843750, 48.224673, 10.195312, 48.458352
+                           ), tilegenerator.ZoomRange(10, 15), 512, 8192, 8192
+                       )
+                   )]
+)
+def test_rastering(tile_slice):
+    output = tempfile.NamedTemporaryFile(
+        mode='wb', prefix='gnuboat-test', suffix='.tif', delete=False
+    )
+    output.close()
+    output = os.path.join(tempfile.gettempdir(), output.name)
+
+    datasource_vrt = os.path.join(
+        os.path.dirname(__file__), 'data/slice-log2.vrt'
+    )
+
+    datasource = ogr.Open(datasource_vrt)
+    source_layer = datasource.GetLayerByIndex(0)
+    (source_x_min, source_x_max,
+     source_y_min, source_y_max) = source_layer.GetExtent()
+    source_layer_name = source_layer.GetName()
+    lon_metre_max = 60 * 1852 * math.cos(
+        math.radians(min(source_y_min, source_y_max))
+    )  # metre / degree
+    lat_metre_max = 111694  # metre / degree
+    circle_radius = math.sqrt(100) / math.pi
+    radius_x = circle_radius / lon_metre_max
+    radius_y = circle_radius / lat_metre_max
+
+    tilegen = tilegenerator.TileGenerator()
+    gridding_algorithm = ('average:radius1={}:radius2={}:angle=0.0:'
+                          'min_points={}:nodata={}').format(
+        radius_x, radius_y, 10, -999
+    )
+    raster_file = tilegen.raster_create(
+        datasource_vrt,
+        'slice-log2',
+        tile_slice,
+        gridding_algorithm,
+        output_file=output
+    )
+
+    assert os.path.exists(raster_file)
+    try:
+        datasource_gtiff = gdal.Open(raster_file)
+        assert datasource_gtiff.RasterXSize == tile_slice.grid_width()
+        assert datasource_gtiff.RasterYSize == tile_slice.grid_height()
+        assert datasource_gtiff.RasterCount == 1
+
+        # Top (north) left (west) corner of the image
+        corner = datasource_gtiff.GetGeoTransform()
+        assert math.isclose(
+            corner[0],
+            tile_slice.lng_lat_bbox().west(), rel_tol=1 * 10**-7
+        )
+        assert math.isclose(
+            corner[3],
+            tile_slice.lng_lat_bbox().north(), rel_tol=1 * 10**-7
+        )
+
+        # Reference system
+        assert 'AUTHORITY["EPSG","4326"]' in datasource_gtiff.GetProjection()
+    finally:
+        os.remove(raster_file)
+
+
+@pytest.mark.slow
+@pytest.mark.parametrize(
+    "data, result", [({
+        'tile_slice':
+            tilegenerator.RasterSlice(
+                tilegenerator.LngLatBbox(
+                    10.041504, 48.421910, 10.052490, 48.429200
+                ), tilegenerator.ZoomRange(15, 19), 256, 4096, 4096
+            ),
+        'densities': [10],
+        'density_base':
+            100,
+        'nodata_value': -999,
+        'skip_empty':
+            True
+    }, {
+        'result_paths':
+            1,
+        'files': [
+            'empty_tile.png', '19/276769/342974.png', '19/276769/342973.png',
+            '19/276769/342972.png', '19/276770/342974.png',
+            '19/276770/342973.png', '19/276770/342972.png',
+            '19/276771/342973.png', '18/138384/171487.png',
+            '18/138384/171486.png', '18/138385/171487.png',
+            '18/138385/171486.png', '17/69192/85743.png', '16/34596/42871.png',
+            '15/17298/21435.png'
+        ]
+    }),
+                     ({
+                         'tile_slice':
+                             tilegenerator.RasterSlice(
+                                 tilegenerator.LngLatBbox(
+                                     10.041504, 48.421910, 10.052490, 48.429200
+                                 ), tilegenerator.ZoomRange(15, 19), 512,
+                                 16384, 16384
+                             ),
+                         'densities': [10],
+                         'density_base':
+                             100,
+                         'nodata_value': -999,
+                         'skip_empty':
+                             True
+                     }, {
+                         'result_paths':
+                             1,
+                         'files': [
+                             'empty_tile.png', '19/276769/342974.png',
+                             '19/276769/342973.png', '19/276769/342972.png',
+                             '19/276770/342974.png', '19/276770/342973.png',
+                             '19/276770/342972.png', '19/276771/342973.png',
+                             '18/138384/171487.png', '18/138384/171486.png',
+                             '18/138385/171487.png', '18/138385/171486.png',
+                             '17/69192/85743.png', '16/34596/42871.png',
+                             '15/17298/21435.png'
+                         ]
+                     })]
+)
+def test_run(data, result):
+    temp_directory = tempfile.mkdtemp(prefix='gnuboat-test_run')
+    temp_directory_target = tempfile.mkdtemp(prefix='gnuboat-test_run')
+
+    datasource_vrt = os.path.join(
+        os.path.dirname(__file__), 'data/slice-log2.vrt'
+    )
+    tilegen = tilegenerator.TileGenerator()
+    result_paths = tilegen.run(
+        datasource_vrt,
+        temp_directory,
+        data['tile_slice'],
+        densities=data['densities'],
+        density_base=data['density_base'],
+        nodata_value=data['nodata_value']
+    )
+    try:
+        assert len(result_paths) == result['result_paths']
+
+        for path in result_paths:
+            tilegen.move_tiles_in_place(
+                path.path, temp_directory_target, data['skip_empty']
+            )
+            for result_file in result['files']:
+                assert os.path.isfile(
+                    os.path.join(temp_directory_target, result_file)
+                ), 'Tile {} not found in {}'.format(
+                    result_file, temp_directory_target
+                )
+    finally:
+        shutil.rmtree(temp_directory)
+        shutil.rmtree(temp_directory_target)
Index: src/gnuboat/common/tests/test_tilegenerator.py
===================================================================
--- src/gnuboat/common/tests/test_tilegenerator.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ 	(revision )
@@ -1,393 +1,0 @@
-'''
-    Copyright (C) 2020 EngSaS - 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 pytest
-import os
-import tempfile
-import xml.etree.ElementTree as ET
-import mercantile
-import math
-import shutil
-from osgeo import gdal
-from osgeo import ogr
-from osgeo import osr
-
-from gnuboat.common.spatial import tilegenerator
-
-
-def compare_lng_lat_bbox(left, right):
-    assert math.isclose(left.east(), right.east(), rel_tol=10**-7), \
-        '{:.7f} != {:.7f} vs. West {} != {}'.format(
-            left.east(), right.east(), left.west(), right.west())
-    assert math.isclose(left.south(), right.south(), rel_tol=10**-7), \
-        '{:.7f} != {:.7f}'.format(left.south(), right.south())
-    assert math.isclose(left.west(), right.west(), rel_tol=10**-7), \
-        '{:.7f} != {:.7f}'.format(left.west(), right.west())
-    assert math.isclose(left.north(), right.north(), rel_tol=10**-7), \
-        '{:.7f} != {:.7f}'.format(left.north(), right.north())
-
-
-@pytest.mark.parametrize(
-    "data, result", [
-        ({
-            'lng_lat_bbox':
-                tilegenerator.LngLatBbox(
-                    10.041963, 48.427407, 10.043652, 48.428932
-                ),
-            'zoom_range':
-                tilegenerator.ZoomRange(18, 19)
-        },
-         tilegenerator.LngLatBbox(10.041504, 48.427378, 10.044250, 48.429200)),
-        ({
-            'lng_lat_bbox':
-                tilegenerator.LngLatBbox(
-                    10.041963, 48.427407, 10.043652, 48.428932
-                ),
-            'zoom_range':
-                tilegenerator.ZoomRange(14, 19)
-        },
-         tilegenerator.LngLatBbox(10.041504, 48.414619, 10.063477, 48.429200)),
-        ({
-            'lng_lat_bbox':
-                tilegenerator.LngLatBbox(
-                    10.041963, 48.427407, 10.043652, 48.428932
-                ),
-            'zoom_range':
-                tilegenerator.ZoomRange(17, 19)
-        },
-         tilegenerator.LngLatBbox(10.041504, 48.427378, 10.044250, 48.429200)),
-        ({
-            'lng_lat_bbox':
-                tilegenerator.LngLatBbox(
-                    10.041963, 48.427407, 10.043652, 48.428932
-                ),
-            'zoom_range':
-                tilegenerator.ZoomRange(10, 19)
-        }, tilegenerator.LngLatBbox(9.843750, 48.224673, 10.195312,
-                                    48.458352)),
-    ]
-)
-def test_fit_extent_to_tiles(data, result):
-    tilegen = tilegenerator.TileGenerator()
-    tile = tilegen.fit_extent_to_tiles(
-        data['lng_lat_bbox'], data['zoom_range']
-    )
-    compare_lng_lat_bbox(tile, result)
-
-
-@pytest.mark.parametrize(
-    "data, result_slices", [
-        ({
-            'tile_sizes': [256],
-            'zoom_range':
-                tilegenerator.ZoomRange(14, 19),
-            'file_size':
-                4 * 1024 * 1024 * 8,
-            'datasource':
-                os.path.join(os.path.dirname(__file__), 'data/slice-log2.csv'),
-            'layer':
-                'slice-log2'
-        }, [
-            tilegenerator.RasterSlice(
-                tilegenerator.LngLatBbox(
-                    10.041504, 48.414619, 10.063477, 48.429200
-                ), tilegenerator.ZoomRange(14, 16), 256, 1024, 1024
-            ),
-            tilegenerator.RasterSlice(
-                tilegenerator.LngLatBbox(
-                    10.041504, 48.427378, 10.044250, 48.429200
-                ), tilegenerator.ZoomRange(17, 19), 256, 1024, 1024
-            )
-        ]),
-        ({
-            'tile_sizes': [256],
-            'zoom_range':
-                tilegenerator.ZoomRange(10, 19),
-            'file_size':
-                64 * 1024 * 1024 * 8,
-            'datasource':
-                os.path.join(os.path.dirname(__file__), 'data/slice-log2.csv'),
-            'layer':
-                'slice-log2'
-        }, [
-            tilegenerator.RasterSlice(
-                tilegenerator.LngLatBbox(
-                    9.843750, 48.224673, 10.195312, 48.458352
-                ), tilegenerator.ZoomRange(10, 14), 256, 4096, 4096
-            ),
-            tilegenerator.RasterSlice(
-                tilegenerator.LngLatBbox(
-                    10.041504, 48.421910, 10.052490, 48.429200
-                ), tilegenerator.ZoomRange(15, 19), 256, 4096, 4096
-            )
-        ]),
-        ({
-            'tile_sizes': [512],
-            'zoom_range':
-                tilegenerator.ZoomRange(10, 19),
-            'file_size':
-                256 * 1024 * 1024 * 8,
-            'datasource':
-                os.path.join(os.path.dirname(__file__), 'data/slice-log2.csv'),
-            'layer':
-                'slice-log2'
-        }, [
-            tilegenerator.RasterSlice(
-                tilegenerator.LngLatBbox(
-                    9.843750, 48.224673, 10.195312, 48.458352
-                ), tilegenerator.ZoomRange(10, 15), 512, 8192, 8192
-            ),
-            tilegenerator.RasterSlice(
-                tilegenerator.LngLatBbox(
-                    10.041504, 48.421910, 10.052490, 48.429200
-                ), tilegenerator.ZoomRange(16, 19), 512, 8192, 8192
-            )
-        ]),
-        ({
-            'tile_sizes': [512],
-            'zoom_range':
-                tilegenerator.ZoomRange(10, 19),
-            'file_size':
-                64 * 1024 * 1024 * 8,
-            'datasource':
-                os.path.join(os.path.dirname(__file__), 'data/slice-log2.csv'),
-            'layer':
-                'slice-log2'
-        }, [
-            tilegenerator.RasterSlice(
-                tilegenerator.LngLatBbox(
-                    9.843750, 48.224673, 10.195312, 48.458352
-                ), tilegenerator.ZoomRange(10, 13), 512, 4096, 4096
-            ),
-            tilegenerator.RasterSlice(
-                tilegenerator.LngLatBbox(
-                    10.041504, 48.414619, 10.063477, 48.429200
-                ), tilegenerator.ZoomRange(14, 17), 512, 4096, 4096
-            ),
-            tilegenerator.RasterSlice(
-                tilegenerator.LngLatBbox(
-                    10.041504, 48.428289, 10.042877, 48.429200
-                ), tilegenerator.ZoomRange(18, 19), 512, 1024, 1024
-            ),
-            tilegenerator.RasterSlice(
-                tilegenerator.LngLatBbox(
-                    10.042877, 48.428289, 10.044250, 48.429200
-                ), tilegenerator.ZoomRange(18, 19), 512, 1024, 1024
-            ),
-            tilegenerator.RasterSlice(
-                tilegenerator.LngLatBbox(
-                    10.042877, 48.427378, 10.044250, 48.428289
-                ), tilegenerator.ZoomRange(18, 19), 512, 1024, 1024
-            ),
-            tilegenerator.RasterSlice(
-                tilegenerator.LngLatBbox(
-                    10.041504, 48.427378, 10.042877, 48.428289
-                ), tilegenerator.ZoomRange(18, 19), 512, 1024, 1024
-            )
-        ]),
-    ]
-)
-def test_slicing(data, result_slices):
-    datasource_vrt = os.path.join(
-        os.path.dirname(__file__), 'data/slice-log2.vrt'
-    )
-    tilegen = tilegenerator.TileGenerator()
-    slices = tilegen.slices(
-        datasource_vrt,
-        data['zoom_range'],
-        tile_sizes=data['tile_sizes'],
-        raster_file_size_max=data['file_size']
-    )
-
-    assert len(slices) == len(result_slices)
-    for i in range(len(slices)):
-        compare_lng_lat_bbox(
-            slices[i].lng_lat_bbox(), result_slices[i].lng_lat_bbox()
-        )
-        assert slices[i].zoom_range(), result_slices[i].zoom_range()
-        assert slices[i].tile_size(), result_slices[i].tile_size()
-        assert slices[i].grid_width(), result_slices[i].grid_width()
-        assert slices[i].grid_height(), result_slices[i].grid_height()
-
-
-@pytest.mark.slow
-@pytest.mark.parametrize(
-    "tile_slice", [(
-        tilegenerator.RasterSlice(
-            tilegenerator.LngLatBbox(
-                10.041504, 48.428289, 10.042877, 48.429200
-            ), tilegenerator.ZoomRange(18, 19), 512, 1024, 1024
-        )
-    ),
-                   (
-                       tilegenerator.RasterSlice(
-                           tilegenerator.LngLatBbox(
-                               9.843750, 48.224673, 10.195312, 48.458352
-                           ), tilegenerator.ZoomRange(10, 15), 512, 8192, 8192
-                       )
-                   )]
-)
-def test_rastering(tile_slice):
-    output = tempfile.NamedTemporaryFile(
-        mode='wb', prefix='gnuboat-test', suffix='.tif', delete=False
-    )
-    output.close()
-    output = os.path.join(tempfile.gettempdir(), output.name)
-
-    datasource_vrt = os.path.join(
-        os.path.dirname(__file__), 'data/slice-log2.vrt'
-    )
-
-    datasource = ogr.Open(datasource_vrt)
-    source_layer = datasource.GetLayerByIndex(0)
-    (source_x_min, source_x_max,
-     source_y_min, source_y_max) = source_layer.GetExtent()
-    source_layer_name = source_layer.GetName()
-    lon_metre_max = 60 * 1852 * math.cos(
-        math.radians(min(source_y_min, source_y_max))
-    )  # metre / degree
-    lat_metre_max = 111694  # metre / degree
-    circle_radius = math.sqrt(100) / math.pi
-    radius_x = circle_radius / lon_metre_max
-    radius_y = circle_radius / lat_metre_max
-
-    tilegen = tilegenerator.TileGenerator()
-    gridding_algorithm = ('average:radius1={}:radius2={}:angle=0.0:'
-                          'min_points={}:nodata={}').format(
-        radius_x, radius_y, 10, -999
-    )
-    raster_file = tilegen.raster_create(
-        datasource_vrt,
-        'slice-log2',
-        tile_slice,
-        gridding_algorithm,
-        output_file=output
-    )
-
-    assert os.path.exists(raster_file)
-    try:
-        datasource_gtiff = gdal.Open(raster_file)
-        assert datasource_gtiff.RasterXSize == tile_slice.grid_width()
-        assert datasource_gtiff.RasterYSize == tile_slice.grid_height()
-        assert datasource_gtiff.RasterCount == 1
-
-        # Top (north) left (west) corner of the image
-        corner = datasource_gtiff.GetGeoTransform()
-        assert math.isclose(
-            corner[0],
-            tile_slice.lng_lat_bbox().west(), rel_tol=1 * 10**-7
-        )
-        assert math.isclose(
-            corner[3],
-            tile_slice.lng_lat_bbox().north(), rel_tol=1 * 10**-7
-        )
-
-        # Reference system
-        assert 'AUTHORITY["EPSG","4326"]' in datasource_gtiff.GetProjection()
-    finally:
-        os.remove(raster_file)
-
-
-@pytest.mark.slow
-@pytest.mark.parametrize(
-    "data, result", [({
-        'tile_slice':
-            tilegenerator.RasterSlice(
-                tilegenerator.LngLatBbox(
-                    10.041504, 48.421910, 10.052490, 48.429200
-                ), tilegenerator.ZoomRange(15, 19), 256, 4096, 4096
-            ),
-        'densities': [10],
-        'density_base':
-            100,
-        'nodata_value': -999,
-        'skip_empty':
-            True
-    }, {
-        'result_paths':
-            1,
-        'files': [
-            'empty_tile.png', '19/276769/342974.png', '19/276769/342973.png',
-            '19/276769/342972.png', '19/276770/342974.png',
-            '19/276770/342973.png', '19/276770/342972.png',
-            '19/276771/342973.png', '18/138384/171487.png',
-            '18/138384/171486.png', '18/138385/171487.png',
-            '18/138385/171486.png', '17/69192/85743.png', '16/34596/42871.png',
-            '15/17298/21435.png'
-        ]
-    }),
-                     ({
-                         'tile_slice':
-                             tilegenerator.RasterSlice(
-                                 tilegenerator.LngLatBbox(
-                                     10.041504, 48.421910, 10.052490, 48.429200
-                                 ), tilegenerator.ZoomRange(15, 19), 512,
-                                 16384, 16384
-                             ),
-                         'densities': [10],
-                         'density_base':
-                             100,
-                         'nodata_value': -999,
-                         'skip_empty':
-                             True
-                     }, {
-                         'result_paths':
-                             1,
-                         'files': [
-                             'empty_tile.png', '19/276769/342974.png',
-                             '19/276769/342973.png', '19/276769/342972.png',
-                             '19/276770/342974.png', '19/276770/342973.png',
-                             '19/276770/342972.png', '19/276771/342973.png',
-                             '18/138384/171487.png', '18/138384/171486.png',
-                             '18/138385/171487.png', '18/138385/171486.png',
-                             '17/69192/85743.png', '16/34596/42871.png',
-                             '15/17298/21435.png'
-                         ]
-                     })]
-)
-def test_run(data, result):
-    temp_directory = tempfile.mkdtemp(prefix='gnuboat-test_run')
-    temp_directory_target = tempfile.mkdtemp(prefix='gnuboat-test_run')
-
-    datasource_vrt = os.path.join(
-        os.path.dirname(__file__), 'data/slice-log2.vrt'
-    )
-    tilegen = tilegenerator.TileGenerator()
-    result_paths = tilegen.run(
-        datasource_vrt,
-        temp_directory,
-        data['tile_slice'],
-        densities=data['densities'],
-        density_base=data['density_base'],
-        nodata_value=data['nodata_value']
-    )
-    try:
-        assert len(result_paths) == result['result_paths']
-
-        for path in result_paths:
-            tilegen.move_tiles_in_place(
-                path.path, temp_directory_target, data['skip_empty']
-            )
-            for result_file in result['files']:
-                assert os.path.isfile(
-                    os.path.join(temp_directory_target, result_file)
-                ), 'Tile {} not found in {}'.format(
-                    result_file, temp_directory_target
-                )
-    finally:
-        shutil.rmtree(temp_directory)
-        shutil.rmtree(temp_directory_target)
Index: src/gnuboat/common/webservice/Config.py
===================================================================
--- src/gnuboat/common/webservice/Config.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ 	(revision )
@@ -1,40 +1,0 @@
-'''
-    Copyright (C) 2020 EngSaS - 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 yaml
-
-
-def config_from_file(config_file, config):
-    config_from_file = yaml.safe_load(open(config_file))
-
-    for entry in config_from_file:
-        setattr(config, entry, config_from_file[entry])
-
-    return config
-
-
-def config_get(config_object, option, default_value):
-    """
-        Returns the value of option in config_object object.
-        If config_object has no attribute option, it returns
-        default_value
-    """
-    if hasattr(config_object, option):
-        return getattr(config_object, option)
-    if isinstance(config_object, dict) and option in config_object:
-        return config_object[option]
-    return default_value
Index: src/gnuboat/common/webservice/HttpErrors.py
===================================================================
--- src/gnuboat/common/webservice/HttpErrors.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ 	(revision )
@@ -1,155 +1,0 @@
-'''
-    Copyright (C) 2019 - 2020 EngSaS - 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/>.
-'''
-
-from werkzeug.exceptions import (
-    BadRequest, Unauthorized, NotFound, InternalServerError,
-    RequestEntityTooLarge, GatewayTimeout, BadGateway
-)
-from connexion.exceptions import ProblemException
-
-
-class GnuboatBadRequest(ProblemException, BadRequest):
-    def __init__(
-        self,
-        type="bad-request",
-        title=None,
-        detail=None,
-        instance=None,
-        **kwargs
-    ):
-        super(GnuboatBadRequest, self).__init__(
-            status=400,
-            title="Bad Request",
-            detail=detail,
-            type=type,
-            instance=instance,
-            **kwargs
-        )
-
-
-class GnuboatUnauthorized(ProblemException, Unauthorized):
-    def __init__(
-        self,
-        type="unauthorized",
-        title="Access denied",
-        detail="You need to login to access the requested resource",
-        instance=None,
-        **kwargs
-    ):
-        super(GnuboatUnauthorized, self).__init__(
-            status=401,
-            title=title,
-            detail=detail,
-            type=type,
-            instance=instance,
-            **kwargs
-        )
-
-
-class GnuboatNotFound(ProblemException, NotFound):
-    def __init__(
-        self,
-        type="not-found",
-        title="Resouce not found",
-        detail="The requested resource was not found",
-        instance=None,
-        **kwargs
-    ):
-        super(GnuboatNotFound, self).__init__(
-            status=404,
-            title=title,
-            detail=detail,
-            type=type,
-            instance=instance,
-            **kwargs
-        )
-
-
-class GnuboatPayloadToLarge(ProblemException, RequestEntityTooLarge):
-    def __init__(
-        self,
-        type="paylod-to-large",
-        title=None,
-        detail=None,
-        instance=None,
-        **kwargs
-    ):
-        super(GnuboatPayloadToLarge, self).__init__(
-            status=413,
-            title="Payload To Large Error",
-            detail=detail,
-            type=type,
-            instance=instance,
-            **kwargs
-        )
-
-
-class GnuboatInternalServerError(ProblemException, InternalServerError):
-    def __init__(
-        self,
-        type="internal-server-error",
-        title=None,
-        detail=None,
-        instance=None,
-        **kwargs
-    ):
-        super(GnuboatInternalServerError, self).__init__(
-            status=500,
-            title="Internal Server Error",
-            detail=detail,
-            type=type,
-            instance=instance,
-            **kwargs
-        )
-
-
-class GnuboatGatewayTimeout(ProblemException, GatewayTimeout):
-    def __init__(
-        self,
-        type="gateway-timeout",
-        title=None,
-        detail=None,
-        instance=None,
-        **kwargs
-    ):
-        super(GnuboatGatewayTimeout, self).__init__(
-            status=504,
-            title="Gateway Timeout",
-            detail=detail,
-            type=type,
-            instance=instance,
-            **kwargs
-        )
-
-
-class GnuboatBadGateway(ProblemException, BadGateway):
-    def __init__(
-        self,
-        type="bad-gateway",
-        title=None,
-        detail=None,
-        instance=None,
-        **kwargs
-    ):
-        super(GnuboatBadGateway, self).__init__(
-            status=502,
-            title="Bad Gateway",
-            detail=detail,
-            type=type,
-            instance=instance,
-            **kwargs
-        )
Index: src/gnuboat/common/webservice/config.py
===================================================================
--- src/gnuboat/common/webservice/config.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/common/webservice/config.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,40 @@
+'''
+    Copyright (C) 2020 EngSaS - 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 yaml
+
+
+def config_from_file(config_file, config):
+    config_from_file = yaml.safe_load(open(config_file))
+
+    for entry in config_from_file:
+        setattr(config, entry, config_from_file[entry])
+
+    return config
+
+
+def config_get(config_object, option, default_value):
+    """
+        Returns the value of option in config_object object.
+        If config_object has no attribute option, it returns
+        default_value
+    """
+    if hasattr(config_object, option):
+        return getattr(config_object, option)
+    if isinstance(config_object, dict) and option in config_object:
+        return config_object[option]
+    return default_value
Index: src/gnuboat/common/webservice/http_errors.py
===================================================================
--- src/gnuboat/common/webservice/http_errors.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/common/webservice/http_errors.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,155 @@
+'''
+    Copyright (C) 2019 - 2020 EngSaS - 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/>.
+'''
+
+from werkzeug.exceptions import (
+    BadRequest, Unauthorized, NotFound, InternalServerError,
+    RequestEntityTooLarge, GatewayTimeout, BadGateway
+)
+from connexion.exceptions import ProblemException
+
+
+class GnuboatBadRequest(ProblemException, BadRequest):
+    def __init__(
+        self,
+        type="bad-request",
+        title=None,
+        detail=None,
+        instance=None,
+        **kwargs
+    ):
+        super(GnuboatBadRequest, self).__init__(
+            status=400,
+            title="Bad Request",
+            detail=detail,
+            type=type,
+            instance=instance,
+            **kwargs
+        )
+
+
+class GnuboatUnauthorized(ProblemException, Unauthorized):
+    def __init__(
+        self,
+        type="unauthorized",
+        title="Access denied",
+        detail="You need to login to access the requested resource",
+        instance=None,
+        **kwargs
+    ):
+        super(GnuboatUnauthorized, self).__init__(
+            status=401,
+            title=title,
+            detail=detail,
+            type=type,
+            instance=instance,
+            **kwargs
+        )
+
+
+class GnuboatNotFound(ProblemException, NotFound):
+    def __init__(
+        self,
+        type="not-found",
+        title="Resouce not found",
+        detail="The requested resource was not found",
+        instance=None,
+        **kwargs
+    ):
+        super(GnuboatNotFound, self).__init__(
+            status=404,
+            title=title,
+            detail=detail,
+            type=type,
+            instance=instance,
+            **kwargs
+        )
+
+
+class GnuboatPayloadToLarge(ProblemException, RequestEntityTooLarge):
+    def __init__(
+        self,
+        type="paylod-to-large",
+        title=None,
+        detail=None,
+        instance=None,
+        **kwargs
+    ):
+        super(GnuboatPayloadToLarge, self).__init__(
+            status=413,
+            title="Payload To Large Error",
+            detail=detail,
+            type=type,
+            instance=instance,
+            **kwargs
+        )
+
+
+class GnuboatInternalServerError(ProblemException, InternalServerError):
+    def __init__(
+        self,
+        type="internal-server-error",
+        title=None,
+        detail=None,
+        instance=None,
+        **kwargs
+    ):
+        super(GnuboatInternalServerError, self).__init__(
+            status=500,
+            title="Internal Server Error",
+            detail=detail,
+            type=type,
+            instance=instance,
+            **kwargs
+        )
+
+
+class GnuboatGatewayTimeout(ProblemException, GatewayTimeout):
+    def __init__(
+        self,
+        type="gateway-timeout",
+        title=None,
+        detail=None,
+        instance=None,
+        **kwargs
+    ):
+        super(GnuboatGatewayTimeout, self).__init__(
+            status=504,
+            title="Gateway Timeout",
+            detail=detail,
+            type=type,
+            instance=instance,
+            **kwargs
+        )
+
+
+class GnuboatBadGateway(ProblemException, BadGateway):
+    def __init__(
+        self,
+        type="bad-gateway",
+        title=None,
+        detail=None,
+        instance=None,
+        **kwargs
+    ):
+        super(GnuboatBadGateway, self).__init__(
+            status=502,
+            title="Bad Gateway",
+            detail=detail,
+            type=type,
+            instance=instance,
+            **kwargs
+        )
Index: src/gnuboat/device/Config.py
===================================================================
--- src/gnuboat/device/Config.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ 	(revision )
@@ -1,47 +1,0 @@
-'''
-    Copyright (C) 2020 EngSaS - 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/>.
-'''
-
-
-class Config(object):
-    DEBUG = False
-    TESTING = False
-    # Every LOG_PERIOD seconds, a log entry is written to the logfile
-    LOG_PERIOD = 2
-    LOG_VERBOSE = None
-    LOG_SYSTEMTIME = False
-    # Every DISPLAY_PERIOD seconds, the display is updated
-    DISPLAY_PERIOD = 5
-
-
-class ProductionConfig(Config):
-    DEVICE_DATABASE = '/var/lib/gnuboat/gnuboat.rrd'
-    LOG_DIRECTORY = '/var/log/gnuboat'
-
-
-class DevelopmentConfig(Config):
-    DEBUG = True
-    DEMO = True
-    DEVICE_DATABASE = '/tmp/gnuboat-device.rrd'
-    LOG_DIRECTORY = '/tmp/gnuboat-device/logs'
-
-
-class TestingConfig(DevelopmentConfig):
-    """
-        Configuration for testing purposes only (like tox/nosetests)
-    """
-    TESTING = True
-    DEBUG = False
Index: src/gnuboat/device/bin/gnuboat-data-generator
===================================================================
--- src/gnuboat/device/bin/gnuboat-data-generator	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ src/gnuboat/device/bin/gnuboat-data-generator	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -25,5 +25,5 @@
 import os
 
-from gnuboat.device.daemon import rrdhandler as rrdhandler
+from gnuboat.common.datahandler import rrd_handler as rrdhandler
 
 # default values for command line arguments
Index: src/gnuboat/device/bin/gnuboat-splashscreen
===================================================================
--- src/gnuboat/device/bin/gnuboat-splashscreen	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ src/gnuboat/device/bin/gnuboat-splashscreen	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -24,14 +24,14 @@
     from PIL import ImageOps
     from EPD import EPD
-    epdEnabled = True
+    epd_enabled = True
 except:
-    epdEnabled = False
+    epd_enabled = False
 
 
-def displayImage(epd, imageFilePath):
+def display_image(epd, imageFilePath):
     image = Image.open(imageFilePath)
     image = ImageOps.grayscale(image)
-    imageResized = image.resize((epd.width, epd.height))
-    imageBlackWhite = imageResized.convert("1", dither=Image.FLOYDSTEINBERG)
+    image_resized = image.resize((epd.width, epd.height))
+    imageBlackWhite = image_resized.convert("1", dither=Image.FLOYDSTEINBERG)
     epd.display(imageBlackWhite)
     epd.update()
@@ -69,5 +69,5 @@
         sys.exit(2)
 
-    if not epdEnabled:
+    if not epd_enabled:
         print("Could not initialize EPD or PIL python packages")
         sys.exit(2)
@@ -75,5 +75,5 @@
     epd = EPD()
     epd.clear()
-    displayImage(epd, image)
+    display_image(epd, image)
 
 
Index: src/gnuboat/device/config.py
===================================================================
--- src/gnuboat/device/config.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/device/config.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,47 @@
+'''
+    Copyright (C) 2020 EngSaS - 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/>.
+'''
+
+
+class Config(object):
+    DEBUG = False
+    TESTING = False
+    # Every LOG_PERIOD seconds, a log entry is written to the logfile
+    LOG_PERIOD = 2
+    LOG_VERBOSE = None
+    LOG_SYSTEMTIME = False
+    # Every DISPLAY_PERIOD seconds, the display is updated
+    DISPLAY_PERIOD = 5
+
+
+class ProductionConfig(Config):
+    DEVICE_DATABASE = '/var/lib/gnuboat/gnuboat.rrd'
+    LOG_DIRECTORY = '/var/log/gnuboat'
+
+
+class DevelopmentConfig(Config):
+    DEBUG = True
+    DEMO = True
+    DEVICE_DATABASE = '/tmp/gnuboat-device.rrd'
+    LOG_DIRECTORY = '/tmp/gnuboat-device/logs'
+
+
+class TestingConfig(DevelopmentConfig):
+    """
+        Configuration for testing purposes only (like tox/nosetests)
+    """
+    TESTING = True
+    DEBUG = False
Index: src/gnuboat/device/daemon/Daemon.py
===================================================================
--- src/gnuboat/device/daemon/Daemon.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ 	(revision )
@@ -1,294 +1,0 @@
-# -*- coding: utf-8 -*-
-'''
-    Copyright (C) 2016 - 2020 EngSaS - 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 os
-import argparse
-import sys
-from werkzeug.utils import import_string
-import time
-import threading
-from pathlib import Path
-
-from gnuboat.device.daemon import (
-    n2kdpoller as n2kdpoller,
-    gpsdpoller as gpsdpoller,
-    displayhandler as displayhandler,
-)
-from gnuboat.common.datahandler import loghandler, logdataset, rrdhandler
-from gnuboat.common.webservice.Config import (
-    config_from_file, config_get
-)
-
-WHITE = 1
-BLACK = 0
-margin_vertical = 10
-margin_horizontal = margin_vertical
-
-
-class Daemon(threading.Thread):
-    def __init__(
-                self, rrd_file, log_directory,
-                gpsd_host='127.0.0.1', gpsd_port=2947,
-                n2kd_host='127.0.0.1', n2kd_port=2597,
-                log_period=1, log_systemtime=False,
-                log_verbose=False, display_period=5
-            ):
-        super().__init__()
-
-        if isinstance(rrd_file, Path):
-            self._rrd_file = rrd_file
-        else:
-            self._rrd_file = Path(rrd_file)
-        if isinstance(log_directory, Path):
-            self._log_directory = log_directory
-        else:
-            self._log_directory = Path(log_directory)
-        self._gpsd_host = gpsd_host
-        self._gpsd_port = gpsd_port
-        self._n2kd_host = n2kd_host
-        self._n2kd_port = n2kd_port
-        self._log_period = log_period
-        self._log_systemtime = log_systemtime
-        self._log_verbose = log_verbose
-        self._display_period = display_period
-        self._running = True
-
-    def log_directory(self):
-        return self._log_directory
-
-    def rrd_database_file(self):
-        return self._rrd_file
-
-    def shutdown(self):
-        self._running = False
-        print("Shutting down")
-
-    def run(self):
-        rrdhandler.rrd_create_database(self._rrd_file, self._log_period)
-
-        display_handler = displayhandler.DisplayHandler(
-            self._display_period, margin_horizontal, margin_vertical,
-            BLACK, WHITE
-        )
-        log_handler = loghandler.LogHandler(self._log_directory)
-
-        gpsd = gpsdpoller.GpsdPoller(host=self._gpsd_host,
-                                     port=self._gpsd_port)
-        n2kd = n2kdpoller.N2kdPoller(
-            host=self._n2kd_host, port=self._n2kd_port,
-            log_period=self._log_period
-        )
-        try:
-            gpsd.start()
-            n2kd.start()
-            while self._running:
-                # In the main thread, every logPeriod seconds print the
-                # current value
-                time.sleep(self._log_period)
-                latitude = gpsd.latitude()
-                longitude = gpsd.longitude()
-                speed_through_water = n2kd.speed_through_water()
-                speed_over_ground = gpsd.speed_over_ground()
-                course_over_ground = gpsd.course_over_ground()
-                water_depth = n2kd.water_depth()
-                water_temperature = n2kd.water_temperature()
-                gps_fix = gpsd.gps_fix()
-
-                # update rrd database for the webservice
-                rrdhandler.rrd_update(
-                    self._rrd_file, 'N:{}:{}:{}:{}:{}:{}:{}:{}'.format(
-                        latitude, longitude, speed_through_water,
-                        speed_over_ground, course_over_ground, water_depth,
-                        water_temperature, gps_fix
-                    )
-                )
-
-                # append to log
-                dataset = logdataset.LogDataset(
-                    None, gpsd.status(),
-                    latitude, gpsd.latitude_direction(), longitude,
-                    gpsd.longitude_direction(), course_over_ground,
-                    speed_over_ground, water_depth, water_temperature,
-                    gpsd.error_horizontal_position(),
-                    gpsd.error_vertical_position(),
-                    gpsd.error_spherical_position()
-                )
-                if not log_handler.gnuboat_write(
-                    gps_fix, gpsd.time_utc(), dataset,
-                    n2kd.water_depth_valid(), self._log_verbose,
-                    self._log_systemtime
-                ):
-                    print('Could not write dataset to log')
-
-                # display data
-                display_handler.setValues(
-                    speed_through_water, speed_over_ground, course_over_ground,
-                    water_depth, water_temperature, gps_fix
-                )
-                time.sleep(0.5)
-        except (KeyboardInterrupt, SystemExit):  # when you press ctrl+c
-            self._stop_childs(log_handler, gpsd, n2kd, display_handler)
-            return False
-        self._stop_childs(log_handler, gpsd, n2kd, display_handler)
-        return True
-
-    def _stop_childs(self, log_handler, gpsd, n2kd, display_handler):
-        if log_handler:
-            log_handler.gnuboat_close()
-        gpsd.stop()
-        gpsd.join(5)  # wait for the thread to finish what it's doing
-        n2kd.stop()
-        n2kd.join(5)
-
-
-def load_config_object(config_name):
-    return import_string(
-        'gnuboat.device.Config.{}Config'.format(config_name)
-    )
-
-
-def main():
-    # determine requested configuration
-    config_file = '/etc/gnuboat/device.conf'
-    if 'FLASK_ENV' in os.environ and os.environ['FLASK_ENV']:
-        config_object = load_config_object(os.environ['FLASK_ENV'].title())
-    elif os.path.isfile(config_file):
-        from gnuboat.common.webservice import Config as configure
-        config_object = configure.config_from_file(
-            config_file,
-            load_config_object('')
-        )
-    else:
-        config_object = load_config_object('Production')
-
-    log_handler = None
-    rrd_file = config_get(config_object, 'DEVICE_DATABASE', None)
-    log_directory = config_get(config_object, 'LOG_DIRECTORY', None)
-    log_period = config_get(config_object, 'LOG_PERIOD', 2)
-    log_verbose = config_get(config_object, 'LOG_VERBOSE', False)
-    log_systemtime = config_get(config_object, 'LOG_SYSTEMTIME', False)
-    display_period = config_get(config_object, 'DISPLAY_PERIOD', 5)
-    gpsd_host = config_get(config_object, 'GPSD_HOST', 'localhost')
-    gpsd_port = config_get(config_object, 'GPSD_PORT', '2947')
-
-    parser = argparse.ArgumentParser(
-        description=('Collects the data from canboat and gpsd and writes '
-                     'them to the rrd database and the nmea log file')
-    )
-    parser.add_argument(
-        '-r',
-        '--rrdfile',
-        dest='rrd_file',
-        metavar='DEVICE_DATABASE',
-        type=str,
-        help=('Path to the rrd database used by the deviceservice to '
-              'serve the clients'),
-        default=rrd_file,
-    )
-    parser.add_argument(
-        '-lp',
-        '--logperiod',
-        dest='log_period',
-        metavar='log_period',
-        type=int,
-        help='Time in seconds to update the logs',
-        default=log_period,
-    )
-    parser.add_argument(
-        '-lv',
-        '--log-verbose',
-        action='store_true',
-        dest='log_verbose',
-        help=('Log verbose information to nmea log file (Enables -ls and '
-              'adds RMC sentences, with invalid GPS state, on non fixes'),
-        default=log_verbose,
-    )
-    parser.add_argument(
-        '-ls',
-        '--log-system-time',
-        action='store_true',
-        dest='log_systemtime',
-        help='Add to enable prefixing every logline with the system time',
-        default=log_systemtime
-    )
-    parser.add_argument(
-        '-d',
-        '--displayperiod',
-        dest='display_period',
-        metavar='display_period',
-        type=int,
-        help='Time in seconds to update the display',
-        default=display_period,
-    )
-    parser.add_argument(
-        'log_directory',
-        metavar='log_directory',
-        nargs='?',
-        type=str,
-        help=('Directory where the log files are stored '
-              '(e.g. the NMEA0183 log files)'),
-        default=log_directory
-    )
-    arguments = parser.parse_args(sys.argv)
-
-    if arguments.rrd_file is not None:
-        rrd_file = arguments.rrd_file
-    if rrd_file is None:
-        print('Please specify a rrd database file')
-        sys.exit(2)
-    if arguments.log_period is not None:
-        log_period = arguments.log_period
-    if arguments.log_verbose is not None:
-        log_verbose = arguments.log_verbose
-        log_systemtime = True
-    if arguments.log_systemtime is not None and log_verbose is False:
-        log_systemtime = arguments.log_systemtime
-    if arguments.display_period is not None:
-        display_period = arguments.display_period
-    if arguments.log_directory is not None:
-        log_directory = arguments.log_directory
-
-    if not os.path.exists(os.path.dirname(rrd_file)):
-        print(
-            'rrd database directory not found {}'.format(
-                os.path.dirname(rrd_file)
-            )
-        )
-        parser.print_help()
-        sys.exit(2)
-
-    if log_period < 1:
-        print('Log period must be >= 1')
-        parser.print_help()
-        sys.exit(2)
-
-    if display_period < 1 or display_period < log_period:
-        print(('Display period must be >= 1 and could not '
-               'be faster than log period'))
-        parser.print_help()
-        sys.exit(2)
-    daemon = Daemon(
-        rrd_file, log_directory,
-        gpsd_host=gpsd_host, gpsd_port=gpsd_port,
-        log_period=log_period,
-        log_systemtime=log_systemtime, log_verbose=log_verbose,
-        display_period=display_period,
-    )
-    if daemon.run():
-        sys.exit(0)
-    sys.exit(1)
Index: src/gnuboat/device/daemon/daemon.py
===================================================================
--- src/gnuboat/device/daemon/daemon.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/device/daemon/daemon.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,301 @@
+# -*- coding: utf-8 -*-
+'''
+    Copyright (C) 2016 - 2020 EngSaS - 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 os
+import argparse
+import sys
+from werkzeug.utils import import_string
+import time
+import threading
+from pathlib import Path
+
+from gnuboat.device.daemon import (
+    n2kd_poller as n2kdpoller,
+    gpsd_poller as gpsdpoller,
+    display_handler as displayhandler,
+)
+from gnuboat.common.datahandler import (
+    log_handler as loghandler,
+    log_dataset as logdataset,
+    rrd_handler as rrdhandler
+)
+from gnuboat.common.webservice.config import (
+    config_from_file, config_get
+)
+
+WHITE = 1
+BLACK = 0
+margin_vertical = 10
+margin_horizontal = margin_vertical
+
+
+class Daemon(threading.Thread):
+    def __init__(
+                self, rrd_file, log_directory,
+                gpsd_host='127.0.0.1', gpsd_port=2947,
+                n2kd_host='127.0.0.1', n2kd_port=2597,
+                log_period=1, log_systemtime=False,
+                log_verbose=False, display_period=5
+            ):
+        super().__init__()
+
+        if isinstance(rrd_file, Path):
+            self._rrd_file = rrd_file
+        else:
+            self._rrd_file = Path(rrd_file)
+        if isinstance(log_directory, Path):
+            self._log_directory = log_directory
+        else:
+            self._log_directory = Path(log_directory)
+        self._gpsd_host = gpsd_host
+        self._gpsd_port = gpsd_port
+        self._n2kd_host = n2kd_host
+        self._n2kd_port = n2kd_port
+        self._log_period = log_period
+        self._log_systemtime = log_systemtime
+        self._log_verbose = log_verbose
+        self._display_period = display_period
+        self._running = True
+
+    def log_directory(self):
+        return self._log_directory
+
+    def rrd_database_file(self):
+        return self._rrd_file
+
+    def shutdown(self):
+        self._running = False
+        print("Shutting down")
+
+    def run(self):
+        rrdhandler.rrd_create_database(self._rrd_file, self._log_period)
+
+        display_handler = displayhandler.DisplayHandler(
+            self._display_period, margin_horizontal, margin_vertical,
+            BLACK, WHITE
+        )
+        log_handler = loghandler.LogHandler(self._log_directory)
+
+        gpsd = gpsdpoller.GpsdPoller(host=self._gpsd_host,
+                                     port=self._gpsd_port)
+        n2kd = n2kdpoller.N2kdPoller(
+            host=self._n2kd_host, port=self._n2kd_port,
+            log_period=self._log_period
+        )
+        try:
+            gpsd.start()
+            n2kd.start()
+            while self._running:
+                # In the main thread, every logPeriod seconds print the
+                # current value
+                time.sleep(self._log_period)
+                latitude = gpsd.latitude()
+                longitude = gpsd.longitude()
+                speed_through_water = n2kd.speed_through_water()
+                speed_over_ground = gpsd.speed_over_ground()
+                course_over_ground = gpsd.course_over_ground()
+                water_depth = n2kd.water_depth()
+                water_temperature = n2kd.water_temperature()
+                gps_fix = gpsd.gps_fix()
+
+                # update rrd database for the webservice
+                rrdhandler.rrd_update(
+                    self._rrd_file, 'N:{}:{}:{}:{}:{}:{}:{}:{}'.format(
+                        latitude, longitude, speed_through_water,
+                        speed_over_ground, course_over_ground, water_depth,
+                        water_temperature, gps_fix
+                    )
+                )
+
+                # append to log
+                dataset = logdataset.LogDataset(
+                    None, gpsd.status(),
+                    latitude, gpsd.latitude_direction(), longitude,
+                    gpsd.longitude_direction(), course_over_ground,
+                    speed_over_ground, water_depth, water_temperature,
+                    gpsd.error_horizontal_position(),
+                    gpsd.error_vertical_position(),
+                    gpsd.error_spherical_position()
+                )
+                if not log_handler.gnuboat_write(
+                    gps_fix, gpsd.time_utc(), dataset,
+                    n2kd.water_depth_valid(), self._log_verbose,
+                    self._log_systemtime
+                ):
+                    print('Could not write dataset to log')
+
+                # display data
+                display_handler.setValues(
+                    speed_through_water, speed_over_ground, course_over_ground,
+                    water_depth, water_temperature, gps_fix
+                )
+                time.sleep(0.5)
+        except (KeyboardInterrupt, SystemExit):  # when you press ctrl+c
+            self._stop_childs(log_handler, gpsd, n2kd, display_handler)
+            return False
+        self._stop_childs(log_handler, gpsd, n2kd, display_handler)
+        return True
+
+    def _stop_childs(self, log_handler, gpsd, n2kd, display_handler):
+        if log_handler:
+            log_handler.gnuboat_close()
+        gpsd.stop()
+        gpsd.join(5)  # wait for the thread to finish what it's doing
+        n2kd.stop()
+        n2kd.join(5)
+
+
+def load_config_object(config_name):
+    return import_string(
+        'gnuboat.device.Config.{}Config'.format(config_name)
+    )
+
+
+def main():
+    # determine requested configuration
+    config_file = '/etc/gnuboat/device.conf'
+    if 'FLASK_ENV' in os.environ and os.environ['FLASK_ENV']:
+        config_object = load_config_object(os.environ['FLASK_ENV'].title())
+    elif os.path.isfile(config_file):
+        from gnuboat.common.webservice import Config as configure
+        config_object = configure.config_from_file(
+            config_file,
+            load_config_object('')
+        )
+    else:
+        config_object = load_config_object('Production')
+
+    log_handler = None
+    rrd_file = config_get(config_object, 'DEVICE_DATABASE', None)
+    log_directory = config_get(config_object, 'LOG_DIRECTORY', None)
+    log_period = config_get(config_object, 'LOG_PERIOD', 2)
+    log_verbose = config_get(config_object, 'LOG_VERBOSE', False)
+    log_systemtime = config_get(config_object, 'LOG_SYSTEMTIME', False)
+    display_period = config_get(config_object, 'DISPLAY_PERIOD', 5)
+    gpsd_host = config_get(config_object, 'GPSD_HOST', '127.0.0.1')
+    gpsd_port = config_get(config_object, 'GPSD_PORT', 2947)
+    n2kd_host = config_get(config_object, 'N2KD_HOST', '127.0.0.1')
+    n2kd_port = config_get(config_object, 'N2KD_PORT', 2597)
+
+    parser = argparse.ArgumentParser(
+        description=('Collects the data from canboat and gpsd and writes '
+                     'them to the rrd database and the nmea log file')
+    )
+    parser.add_argument(
+        '-r',
+        '--rrdfile',
+        dest='rrd_file',
+        metavar='DEVICE_DATABASE',
+        type=str,
+        help=('Path to the rrd database used by the deviceservice to '
+              'serve the clients'),
+        default=rrd_file,
+    )
+    parser.add_argument(
+        '-lp',
+        '--logperiod',
+        dest='log_period',
+        metavar='log_period',
+        type=int,
+        help='Time in seconds to update the logs',
+        default=log_period,
+    )
+    parser.add_argument(
+        '-lv',
+        '--log-verbose',
+        action='store_true',
+        dest='log_verbose',
+        help=('Log verbose information to nmea log file (Enables -ls and '
+              'adds RMC sentences, with invalid GPS state, on non fixes'),
+        default=log_verbose,
+    )
+    parser.add_argument(
+        '-ls',
+        '--log-system-time',
+        action='store_true',
+        dest='log_systemtime',
+        help='Add to enable prefixing every logline with the system time',
+        default=log_systemtime
+    )
+    parser.add_argument(
+        '-d',
+        '--displayperiod',
+        dest='display_period',
+        metavar='display_period',
+        type=int,
+        help='Time in seconds to update the display',
+        default=display_period,
+    )
+    parser.add_argument(
+        'log_directory',
+        metavar='log_directory',
+        nargs='?',
+        type=str,
+        help=('Directory where the log files are stored '
+              '(e.g. the NMEA0183 log files)'),
+        default=log_directory
+    )
+    arguments = parser.parse_args(sys.argv)
+
+    if arguments.rrd_file is not None:
+        rrd_file = arguments.rrd_file
+    if rrd_file is None:
+        print('Please specify a rrd database file')
+        sys.exit(2)
+    if arguments.log_period is not None:
+        log_period = arguments.log_period
+    if arguments.log_verbose is not None:
+        log_verbose = arguments.log_verbose
+        log_systemtime = True
+    if arguments.log_systemtime is not None and log_verbose is False:
+        log_systemtime = arguments.log_systemtime
+    if arguments.display_period is not None:
+        display_period = arguments.display_period
+    if arguments.log_directory is not None:
+        log_directory = arguments.log_directory
+
+    if not os.path.exists(os.path.dirname(rrd_file)):
+        print(
+            'rrd database directory not found {}'.format(
+                os.path.dirname(rrd_file)
+            )
+        )
+        parser.print_help()
+        sys.exit(2)
+
+    if log_period < 1:
+        print('Log period must be >= 1')
+        parser.print_help()
+        sys.exit(2)
+
+    if display_period < 1 or display_period < log_period:
+        print(('Display period must be >= 1 and could not '
+               'be faster than log period'))
+        parser.print_help()
+        sys.exit(2)
+    daemon = Daemon(
+        rrd_file, log_directory,
+        gpsd_host=gpsd_host, gpsd_port=gpsd_port,
+        n2kd_host=n2kd_host, n2kd_port=n2kd_port,
+        log_period=log_period,
+        log_systemtime=log_systemtime, log_verbose=log_verbose,
+        display_period=display_period,
+    )
+    if daemon.run():
+        sys.exit(0)
+    sys.exit(1)
Index: src/gnuboat/device/daemon/display_handler.py
===================================================================
--- src/gnuboat/device/daemon/display_handler.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/device/daemon/display_handler.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,203 @@
+# -*- coding: utf-8 -*-
+'''
+    Copyright (C) 2016 - 2020 EngSaS - 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 threading
+import time
+import sys
+
+try:
+    from EPD import EPD
+    from PIL import Image
+    from PIL import ImageDraw
+    from PIL import ImageFont
+    epd_enabled = True
+except:
+    epd_enabled = False
+
+
+class DisplayHandler(threading.Thread):
+    def __init__(
+            self, display_period, margin_horizontal, margin_vertical,
+            white, black):
+        threading.Thread.__init__(self)
+        try:
+            self._epd = EPD()
+        except:
+            epd_enabled = False
+            return
+        self._epd.clear()
+        self._update_period = display_period
+        self._margin_horizontal = margin_horizontal
+        self._margin_vertical = margin_vertical
+        self._black = black,
+        self._white = white,
+        self._running = True
+        self._speed_through_water = None
+        self._speed_over_ground = None
+        self._course_over_ground = None
+        self._water_depth = None
+        self._water_temperature = None
+        self._gps_fix = None
+
+    def set_speed_through_water(self, speed):
+        self._speed_through_water = speed
+
+    def set_speed_over_ground(self, speed):
+        self._speed_over_ground = speed
+
+    def set_course_over_ground(self, course):
+        self._course_over_ground = course
+
+    def set_water_depth(self, depth):
+        self._water_depth = depth
+
+    def set_water_temperature(self, temperature):
+        self._water_temperature = temperature
+
+    def set_gps_fix(self, fix):
+        self._gps_fix = fix
+
+    def setValues(
+        self, speed_through_water, speed_over_ground, course_over_ground,
+        water_depth, water_temperature, gps_fix
+    ):
+        self.set_speed_through_water(speed_through_water)
+        self.set_speed_over_ground(speed_over_ground)
+        self.set_course_over_ground(course_over_ground)
+        self.set_water_depth(water_depth)
+        self.set_water_temperature(water_temperature)
+        self.set_gps_fix(gps_fix)
+
+    def stop(self):
+        self._running = False
+
+    def run(self):
+        if not epd_enabled:
+            return
+        try:
+            while self._running:
+                self.display_values(
+                    self._epd, self._speed_through_water,
+                    self._speed_over_ground, self._course_over_ground,
+                    self._water_depth, self._water_temperature, self._gps_fix
+                )
+                time.sleep(self._update_period)
+        except StopIteration:
+            pass
+
+    def display_values(
+        self, epd, speed_through_water, speed_over_ground, course_over_ground,
+        water_depth, water_temperature, gps_fix
+    ):
+        if not epd_enabled:
+            return
+
+        # requires dejavu package!!!!
+        font_values = ImageFont.truetype(
+            '/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf', 34
+        )
+        font_titles = ImageFont.truetype(
+            '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', 24
+        )
+
+        # initially set all white background
+        image = Image.new('1', epd.size, WHITE)
+        width, height = image.size
+
+        row_height_titles = 25
+        row_height_values = float(
+            height - 2 * row_height_titles - 3 * self._margin_vertical
+        ) / 2.0
+        column_width_unit = 30
+        column_width_values = int(
+            float(
+                width - 3 * self._margin_horizontal - 2 * column_width_unit
+            ) / 2.0
+        )
+
+        draw = ImageDraw.Draw(image)
+        # draw.rectangle((0, 0, width, height), fill=WHITE, outline=WHITE)
+
+        x = self._margin_horizontal
+        y = self._margin_vertical
+        draw.text((x, y), "STW", fill=self._black, font=font_titles)
+        if speed_through_water is not None:
+            draw.text((x, y + row_height_titles),
+                      str(speed_through_water),
+                      fill=self._black,
+                      font=font_values)
+        draw.text((x + column_width_values, y + row_height_titles * 1.4),
+                  "kts",
+                  fill=self._black,
+                  font=font_titles)
+
+        x = x + self._margin_horizontal + column_width_values + \
+            column_width_unit
+        draw.text((x, y), "SOG", fill=self._black, font=font_titles)
+        if speed_over_ground is not None:
+            draw.text((x, y + row_height_titles),
+                      str(speed_over_ground),
+                      fill=self._black,
+                      font=font_values)
+        draw.text((x + column_width_values, y + row_height_titles * 1.4),
+                  "kts",
+                  fill=self._black,
+                  font=font_titles)
+
+        x = self._margin_horizontal
+        y = y + row_height_titles + row_height_values + self._margin_vertical
+        draw.text((x, y), "Depth", fill=self._black, font=font_titles)
+        if water_depth is not None:
+            draw.text((x, y + row_height_titles),
+                      str(water_depth),
+                      fill=self._black,
+                      font=font_values)
+        draw.text((
+            x + int(float(column_width_values) / 1.5),
+            y + row_height_titles * 1.4
+        ),
+                  "m",
+                  fill=self._black,
+                  font=font_titles)
+
+        x = x + self._margin_horizontal + column_width_values + \
+            column_width_unit
+        draw.text((x, y), "Water", fill=self._black, font=font_titles)
+        if water_temperature is not None:
+            draw.text((x, y + row_height_titles),
+                      str(water_temperature),
+                      fill=self._black,
+                      font=font_values)
+        draw.text((
+            x + int(float(column_width_values) / 1.5),
+            y + row_height_titles * 1.4
+        ),
+                  "C",
+                  fill=self._black,
+                  font=font_titles)
+
+        x = int((x + self._margin_horizontal + column_width_values) * 0.93)
+        draw.text((x, y), "Fix", fill=self._black, font=font_titles)
+        if gps_fix is not None:
+            draw.text((x, y + row_height_titles),
+                      str(gps_fix),
+                      fill=self._black,
+                      font=font_values)
+
+        epd.display(image)
+        epd.update()
Index: src/gnuboat/device/daemon/displayhandler.py
===================================================================
--- src/gnuboat/device/daemon/displayhandler.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ 	(revision )
@@ -1,203 +1,0 @@
-# -*- coding: utf-8 -*-
-'''
-    Copyright (C) 2016 - 2017 EngSaS - 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 threading
-import time
-import sys
-
-try:
-    from EPD import EPD
-    from PIL import Image
-    from PIL import ImageDraw
-    from PIL import ImageFont
-    epdEnabled = True
-except:
-    epdEnabled = False
-
-
-class DisplayHandler(threading.Thread):
-    def __init__(
-            self, display_period, margin_horizontal, margin_vertical,
-            white, black):
-        threading.Thread.__init__(self)
-        try:
-            self._epd = EPD()
-        except:
-            epd_enabled = False
-            return
-        self._epd.clear()
-        self._update_period = display_period
-        self._margin_horizontal = margin_horizontal
-        self._margin_vertical = margin_vertical
-        self._black = black,
-        self._white = white,
-        self._running = True
-        self._speed_through_water = None
-        self._speed_over_ground = None
-        self._course_over_ground = None
-        self._water_depth = None
-        self._water_temperature = None
-        self._gps_fix = None
-
-    def set_speed_through_water(self, speed):
-        self._speed_through_water = speed
-
-    def set_speed_over_ground(self, speed):
-        self._speed_over_ground = speed
-
-    def set_course_over_ground(self, course):
-        self._course_over_ground = course
-
-    def set_water_depth(self, depth):
-        self._water_depth = depth
-
-    def set_water_temperature(self, temperature):
-        self._water_temperature = temperature
-
-    def set_gps_fix(self, fix):
-        self._gps_fix = fix
-
-    def setValues(
-        self, speed_through_water, speed_over_ground, course_over_ground,
-        water_depth, water_temperature, gps_fix
-    ):
-        self.set_speed_through_water(speed_through_water)
-        self.set_speed_over_ground(speed_over_ground)
-        self.set_course_over_ground(course_over_ground)
-        self.set_water_depth(water_depth)
-        self.set_water_temperature(water_temperature)
-        self.set_gps_fix(gps_fix)
-
-    def stop(self):
-        self._running = False
-
-    def run(self):
-        if not epd_enabled:
-            return
-        try:
-            while self._running:
-                self.display_values(
-                    self._epd, self._speed_through_water,
-                    self._speed_over_ground, self._course_over_ground,
-                    self._water_depth, self._water_temperature, self._gps_fix
-                )
-                time.sleep(self._update_period)
-        except StopIteration:
-            pass
-
-    def display_values(
-        self, epd, speed_through_water, speed_over_ground, course_over_ground,
-        water_depth, water_temperature, gps_fix
-    ):
-        if not epd_enabled:
-            return
-
-        # requires dejavu package!!!!
-        font_values = ImageFont.truetype(
-            '/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf', 34
-        )
-        font_titles = ImageFont.truetype(
-            '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', 24
-        )
-
-        # initially set all white background
-        image = Image.new('1', epd.size, WHITE)
-        width, height = image.size
-
-        row_height_titles = 25
-        row_height_values = float(
-            height - 2 * row_height_titles - 3 * self._margin_vertical
-        ) / 2.0
-        column_width_unit = 30
-        column_width_values = int(
-            float(
-                width - 3 * self._margin_horizontal - 2 * column_width_unit
-            ) / 2.0
-        )
-
-        draw = ImageDraw.Draw(image)
-        # draw.rectangle((0, 0, width, height), fill=WHITE, outline=WHITE)
-
-        x = self._margin_horizontal
-        y = self._margin_vertical
-        draw.text((x, y), "STW", fill=self._black, font=font_titles)
-        if speed_through_water is not None:
-            draw.text((x, y + row_height_titles),
-                      str(speed_through_water),
-                      fill=self._black,
-                      font=font_values)
-        draw.text((x + column_width_values, y + row_height_titles * 1.4),
-                  "kts",
-                  fill=self._black,
-                  font=font_titles)
-
-        x = x + self._margin_horizontal + column_width_values + \
-            column_width_unit
-        draw.text((x, y), "SOG", fill=self._black, font=font_titles)
-        if speed_over_ground is not None:
-            draw.text((x, y + row_height_titles),
-                      str(speed_over_ground),
-                      fill=self._black,
-                      font=font_values)
-        draw.text((x + column_width_values, y + row_height_titles * 1.4),
-                  "kts",
-                  fill=self._black,
-                  font=font_titles)
-
-        x = self._margin_horizontal
-        y = y + row_height_titles + row_height_values + self._margin_vertical
-        draw.text((x, y), "Depth", fill=self._black, font=font_titles)
-        if water_depth is not None:
-            draw.text((x, y + row_height_titles),
-                      str(water_depth),
-                      fill=self._black,
-                      font=font_values)
-        draw.text((
-            x + int(float(column_width_values) / 1.5),
-            y + row_height_titles * 1.4
-        ),
-                  "m",
-                  fill=self._black,
-                  font=font_titles)
-
-        x = x + self._margin_horizontal + column_width_values + \
-            column_width_unit
-        draw.text((x, y), "Water", fill=self._black, font=font_titles)
-        if water_temperature is not None:
-            draw.text((x, y + row_height_titles),
-                      str(water_temperature),
-                      fill=self._black,
-                      font=font_values)
-        draw.text((
-            x + int(float(column_width_values) / 1.5),
-            y + row_height_titles * 1.4
-        ),
-                  "C",
-                  fill=self._black,
-                  font=font_titles)
-
-        x = int((x + self._margin_horizontal + column_width_values) * 0.93)
-        draw.text((x, y), "Fix", fill=self._black, font=font_titles)
-        if gps_fix is not None:
-            draw.text((x, y + row_height_titles),
-                      str(gps_fix),
-                      fill=self._black,
-                      font=font_values)
-
-        epd.display(image)
-        epd.update()
Index: src/gnuboat/device/daemon/gpsd_poller.py
===================================================================
--- src/gnuboat/device/daemon/gpsd_poller.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/device/daemon/gpsd_poller.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,160 @@
+# -*- coding: utf-8 -*-
+'''
+    Copyright (C) 2016 - 2020 EngSaS - 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 threading
+import dateutil.parser
+import datetime
+import socket
+import time
+import json
+
+
+class GpsdPoller(threading.Thread):
+    def __init__(self, host='127.0.0.1', port=2947, ready_event=None):
+        super().__init__()
+        self._host = host
+        self._port = port
+        self._ready_event = ready_event
+
+        self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+        self._socket.settimeout(5)
+        self._stream = None
+        self._current_value = None
+        self._running = True
+
+    def latitude(self):
+        if self._current_value is None or self.gps_fix(
+        ) < 2 or 'lat' not in self._current_value:
+            return 0
+        return self._current_value['lat']
+
+    def latitude_direction(self):
+        return 'N'
+
+    def longitude(self):
+        if self._current_value is None or self.gps_fix(
+        ) < 2 or 'lon' not in self._current_value:
+            return 0
+        return self._current_value['lon']
+
+    def longitude_direction(self):
+        return 'E'
+
+    def speed_over_ground(self):
+        if self._current_value is None or self.gps_fix(
+        ) < 2 or 'speed' not in self._current_value:
+            return 0
+        return self._current_value['speed']
+
+    def course_over_ground(self):
+        if self._current_value is None or self.gps_fix(
+        ) < 2 or 'track' not in self._current_value:
+            return 0
+        return self._current_value['track']
+
+    def error_horizontal_position(self):
+        """
+            Estimated horizontal Position (2D) Error in meters.
+            Also known as Estimated Position Error (epe)
+        """
+        if self.gps_fix() < 2 or 'eph' not in self._current_value:
+            return None
+        return self._current_value['eph']
+
+    def error_vertical_position(self):
+        """
+            Estimated vertical error in meters.
+        """
+        if self.gps_fix() < 2 or 'epv' not in self._current_value:
+            return None
+        return self._current_value['epv']
+
+    def error_spherical_position(self):
+        """
+            Estimated Spherical (3D) Position Error in meters
+        """
+        if self.gps_fix() < 2 or 'sep' not in self._current_value:
+            return None
+        return self._current_value['sep']
+
+    def gps_fix(self):
+        if self._current_value is None or 'mode' not in self._current_value:
+            return 0
+        return self._current_value['mode']
+
+    def status(self):
+        if self._current_value is None or self.gps_fix() < 2:
+            return 'V'
+        return 'A'
+
+    def time_utc(self):
+        if self._current_value is None or self.gps_fix(
+        ) < 2 or 'time' not in self._current_value:
+            return None
+        currentTime = self._current_value['time']
+        if isinstance(currentTime, float):
+            return datetime.datetime.fromtimestamp(currentTime, timezone.utc)
+        return dateutil.parser.parse(currentTime)
+
+    def close_stream(self):
+        if self._stream is not None:
+            self._stream.close()
+            self._stream = None
+        self._socket.close()
+
+    def stop(self):
+        self._running = False
+        self.close_stream()
+
+    def run(self):
+        while self._running:
+            try:
+                time.sleep(0.25)
+                # connection to the gpsd daemon
+                if self._stream is None:
+                    self._socket.connect((self._host, self._port))
+                    self._stream = self._socket.makefile(mode='rw')
+                    self._stream.write(
+                        '?WATCH={"enable": true, "json": true}\n')
+                    self._stream.flush()
+                    print('Connected to {}:{}'.format(
+                        self._host, self._port
+                    ))
+                    connectionrefused_error_printed = False
+                    if self._ready_event:
+                        self._ready_event.set()
+                # read values
+                self._stream.write('?POLL;\n')
+                self._stream.flush()
+                data = json.loads(self._stream.readline())
+                if 'active' not in data or not data['active'] or \
+                        'tpv' not in data or len(data['tpv']) < 1:
+                    self._current_value = None
+                else:
+                    self._current_value = data['tpv'][-1]
+            except json.JSONDecodeError as e:
+                pass
+            except OSError as e:
+                self._stream = None
+                pass
+            except BrokenPipeError as e:
+                self._stream = None
+                pass
+            except KeyboardInterrupt as e:
+                self.close_stream()
+                break
Index: src/gnuboat/device/daemon/gpsdpoller.py
===================================================================
--- src/gnuboat/device/daemon/gpsdpoller.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ 	(revision )
@@ -1,160 +1,0 @@
-# -*- coding: utf-8 -*-
-'''
-    Copyright (C) 2016 - 2020 EngSaS - 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 threading
-import dateutil.parser
-import datetime
-import socket
-import time
-import json
-
-
-class GpsdPoller(threading.Thread):
-    def __init__(self, host='127.0.0.1', port=2947, ready_event=None):
-        super().__init__()
-        self._host = host
-        self._port = port
-        self._ready_event = ready_event
-
-        self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-        self._socket.settimeout(5)
-        self._stream = None
-        self._current_value = None
-        self._running = True
-
-    def latitude(self):
-        if self._current_value is None or self.gps_fix(
-        ) < 2 or 'lat' not in self._current_value:
-            return 0
-        return self._current_value['lat']
-
-    def latitude_direction(self):
-        return 'N'
-
-    def longitude(self):
-        if self._current_value is None or self.gps_fix(
-        ) < 2 or 'lon' not in self._current_value:
-            return 0
-        return self._current_value['lon']
-
-    def longitude_direction(self):
-        return 'E'
-
-    def speed_over_ground(self):
-        if self._current_value is None or self.gps_fix(
-        ) < 2 or 'speed' not in self._current_value:
-            return 0
-        return self._current_value['speed']
-
-    def course_over_ground(self):
-        if self._current_value is None or self.gps_fix(
-        ) < 2 or 'track' not in self._current_value:
-            return 0
-        return self._current_value['track']
-
-    def error_horizontal_position(self):
-        """
-            Estimated horizontal Position (2D) Error in meters.
-            Also known as Estimated Position Error (epe)
-        """
-        if self.gps_fix() < 2 or 'eph' not in self._current_value:
-            return None
-        return self._current_value['eph']
-
-    def error_vertical_position(self):
-        """
-            Estimated vertical error in meters.
-        """
-        if self.gps_fix() < 2 or 'epv' not in self._current_value:
-            return None
-        return self._current_value['epv']
-
-    def error_spherical_position(self):
-        """
-            Estimated Spherical (3D) Position Error in meters
-        """
-        if self.gps_fix() < 2 or 'sep' not in self._current_value:
-            return None
-        return self._current_value['sep']
-
-    def gps_fix(self):
-        if self._current_value is None or 'mode' not in self._current_value:
-            return 0
-        return self._current_value['mode']
-
-    def status(self):
-        if self._current_value is None or self.gps_fix() < 2:
-            return 'V'
-        return 'A'
-
-    def time_utc(self):
-        if self._current_value is None or self.gps_fix(
-        ) < 2 or 'time' not in self._current_value:
-            return None
-        currentTime = self._current_value['time']
-        if isinstance(currentTime, float):
-            return datetime.datetime.fromtimestamp(currentTime, timezone.utc)
-        return dateutil.parser.parse(currentTime)
-
-    def close_stream(self):
-        if self._stream is not None:
-            self._stream.close()
-            self._stream = None
-        self._socket.close()
-
-    def stop(self):
-        self._running = False
-        self.close_stream()
-
-    def run(self):
-        while self._running:
-            try:
-                time.sleep(0.25)
-                # connection to the gpsd daemon
-                if self._stream is None:
-                    self._socket.connect((self._host, self._port))
-                    self._stream = self._socket.makefile(mode='rw')
-                    self._stream.write(
-                        '?WATCH={"enable": true, "json": true}\n')
-                    self._stream.flush()
-                    print('Connected to {}:{}'.format(
-                        self._host, self._port
-                    ))
-                    connectionrefused_error_printed = False
-                    if self._ready_event:
-                        self._ready_event.set()
-                # read values
-                self._stream.write('?POLL;\n')
-                self._stream.flush()
-                data = json.loads(self._stream.readline())
-                if 'active' not in data or not data['active'] or \
-                        'tpv' not in data or len(data['tpv']) < 1:
-                    self._current_value = None
-                else:
-                    self._current_value = data['tpv'][-1]
-            except json.JSONDecodeError as e:
-                pass
-            except OSError as e:
-                self._stream = None
-                pass
-            except BrokenPipeError as e:
-                self._stream = None
-                pass
-            except KeyboardInterrupt as e:
-                self.close_stream()
-                break
Index: src/gnuboat/device/daemon/n2kd_poller.py
===================================================================
--- src/gnuboat/device/daemon/n2kd_poller.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/device/daemon/n2kd_poller.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,160 @@
+# -*- coding: utf-8 -*-
+'''
+    Copyright (C) 2016 - 2020 EngSaS - 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 threading
+import time
+import socket
+import json
+
+
+class N2kdPoller(threading.Thread):
+    """
+        N2kdPoller
+    """
+    def __init__(self, host='127.0.0.1', port=2597, log_period=1):
+        threading.Thread.__init__(self)
+        self._server_host = host
+        self._server_port = port
+        self._log_period = log_period
+        self._timeout = 1.5
+        self._speed_through_water = 0
+        self._distance_log = 0
+        self._distance_log_trip = 0
+        self._water_depth = 0
+        self._water_depth_valid = False
+        self._water_temperature = 0
+        self._running = True
+
+    def speed_through_water(self):
+        return self._speed_through_water
+
+    def distance_log(self):
+        return self._distance_log
+
+    def distance_log_trip(self):
+        return self._distance_log_trip
+
+    def water_depth(self):
+        return self._water_depth
+
+    def water_depth_valid(self):
+        return self._water_depth_valid
+
+    def water_temperature(self):
+        return self._water_temperature
+
+    def _loadData(self):
+        n2kd_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+        n2kd_socket.settimeout(self._timeout)
+        try:
+            n2kd_socket.connect((self._server_host, self._server_port))
+        except socket.error as error:
+            print(
+                'Failed to connect to n2kd server at {}:{}: {}'.format(
+                    self._server_host, self._server_port, error
+                )
+            )
+            self._water_depth_valid = False
+            return
+        print(
+            'Connected to n2kd server at {}:{}'.format(
+                self._server_host, self._server_port
+            )
+        )
+
+        response = ""
+        while 1:
+            try:
+                data = n2kd_socket.recv(1024)
+            except Exception as e:
+                print('Failed to update n2kd data')
+                self._invalidate_data()
+                return
+            if not data:
+                break
+            if hasattr(data, 'decode'):
+                data = data.decode()
+            response += data
+        n2kd_socket.close()
+        try:
+            data = json.loads(response)
+        except ValueError as error:
+            print('Failed to decode json: {}'.format(error))
+
+        descriptions = [
+            "Water Depth", "Speed", "Environmental Parameters", "Distance Log"
+        ]
+
+        for key in data:
+            entry_keys = list(data[key].keys())
+            if len(entry_keys) != 2:
+                print('Malformed json n2kd response? {}'.format(response))
+            else:
+                if data[key]["description"] in descriptions:
+                    entry_key = entry_keys[1]
+                    line_keys = data[key][entry_key].keys()
+                    if "fields" not in line_keys:
+                        print(
+                            ('No fields entry. Malformed json n2kd response '
+                             'in {}').format(data[key][entry_key])
+                        )
+                    else:
+                        fields = data[key][entry_key]["fields"]
+                        # try water depth (NEED TO APPLY OFFSET?)
+                        if "Depth" in fields:
+                            if data[key][entry_key]["description"] == \
+                                    "Water Depth":
+                                self._water_depth = fields["Depth"]
+                                self._water_depth_valid = True
+                        # try speed
+                        if "Speed Water Referenced" in fields:
+                            self._speed_through_water = fields[
+                                "Speed Water Referenced"]
+                        # try sea temperature
+                        if ("Temperature Source" in fields and
+                                "Temperature" in fields):
+                            if fields["Temperature Source"
+                                      ] == "Sea Temperature":
+                                self._water_temperature = fields["Temperature"]
+                        # try log
+                        if "Log" in fields:
+                            self._distance_log = fields["Log"]
+                        if "Trip Log" in fields:
+                            self._distance_log_trip = fields["Trip Log"]
+
+    def _serverUrl(self):
+        return 'http://{}:{:d}/'.format(self._server_host, self._server_port)
+
+    def stop(self):
+        self._running = False
+
+    def run(self):
+        try:
+            while self._running:
+                self._loadData()
+                time.sleep(float(self._log_period) / 2.0)
+        except StopIteration:
+            pass
+
+    def _invalidate_data(self):
+        self._water_depth_valid = False
+        self._water_depth = 0
+        self._speed_through_water = 0
+        self._water_temperature = 0
+        self.__distance_log = 0
+        self.__distance_log_trip = 0
Index: src/gnuboat/device/daemon/n2kdpoller.py
===================================================================
--- src/gnuboat/device/daemon/n2kdpoller.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ 	(revision )
@@ -1,160 +1,0 @@
-# -*- coding: utf-8 -*-
-'''
-    Copyright (C) 2016 - 2020 EngSaS - 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 threading
-import time
-import socket
-import json
-
-
-class N2kdPoller(threading.Thread):
-    """
-        N2kdPoller
-    """
-    def __init__(self, host='127.0.0.1', port=2597, log_period=1):
-        threading.Thread.__init__(self)
-        self._server_host = host
-        self._server_port = port
-        self._log_period = log_period
-        self._timeout = 1.5
-        self._speed_through_water = 0
-        self._distance_log = 0
-        self._distance_log_trip = 0
-        self._water_depth = 0
-        self._water_depth_valid = False
-        self._water_temperature = 0
-        self._running = True
-
-    def speed_through_water(self):
-        return self._speed_through_water
-
-    def distance_log(self):
-        return self._distance_log
-
-    def distance_log_trip(self):
-        return self._distance_log_trip
-
-    def water_depth(self):
-        return self._water_depth
-
-    def water_depth_valid(self):
-        return self._water_depth_valid
-
-    def water_temperature(self):
-        return self._water_temperature
-
-    def _loadData(self):
-        n2kd_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-        n2kd_socket.settimeout(self._timeout)
-        try:
-            n2kd_socket.connect((self._server_host, self._server_port))
-        except socket.error as error:
-            print(
-                'Failed to connect to n2kd server at {}:{}: {}'.format(
-                    self._server_host, self._server_port, error
-                )
-            )
-            self._water_depth_valid = False
-            return
-        print(
-            'Connected to n2kd server at {}:{}'.format(
-                self._server_host, self._server_port
-            )
-        )
-
-        response = ""
-        while 1:
-            try:
-                data = n2kd_socket.recv(1024)
-            except Exception as e:
-                print('Failed to update n2kd data')
-                self._invalidate_data()
-                return
-            if not data:
-                break
-            if hasattr(data, 'decode'):
-                data = data.decode()
-            response += data
-        n2kd_socket.close()
-        try:
-            data = json.loads(response)
-        except ValueError as error:
-            print('Failed to decode json: {}'.format(error))
-
-        descriptions = [
-            "Water Depth", "Speed", "Environmental Parameters", "Distance Log"
-        ]
-
-        for key in data:
-            entry_keys = list(data[key].keys())
-            if len(entry_keys) != 2:
-                print('Malformed json n2kd response? {}'.format(response))
-            else:
-                if data[key]["description"] in descriptions:
-                    entry_key = entry_keys[1]
-                    line_keys = data[key][entry_key].keys()
-                    if "fields" not in line_keys:
-                        print(
-                            ('No fields entry. Malformed json n2kd response '
-                             'in {}').format(data[key][entry_key])
-                        )
-                    else:
-                        fields = data[key][entry_key]["fields"]
-                        # try water depth (NEED TO APPLY OFFSET?)
-                        if "Depth" in fields:
-                            if data[key][entry_key]["description"] == \
-                                    "Water Depth":
-                                self._water_depth = fields["Depth"]
-                                self._water_depth_valid = True
-                        # try speed
-                        if "Speed Water Referenced" in fields:
-                            self._speed_through_water = fields[
-                                "Speed Water Referenced"]
-                        # try sea temperature
-                        if ("Temperature Source" in fields and
-                                "Temperature" in fields):
-                            if fields["Temperature Source"
-                                      ] == "Sea Temperature":
-                                self._water_temperature = fields["Temperature"]
-                        # try log
-                        if "Log" in fields:
-                            self._distance_log = fields["Log"]
-                        if "Trip Log" in fields:
-                            self._distance_log_trip = fields["Trip Log"]
-
-    def _serverUrl(self):
-        return 'http://{}:{:d}/'.format(self._server_host, self._server_port)
-
-    def stop(self):
-        self._running = False
-
-    def run(self):
-        try:
-            while self._running:
-                self._loadData()
-                time.sleep(float(self._log_period) / 2.0)
-        except StopIteration:
-            pass
-
-    def _invalidate_data(self):
-        self._water_depth_valid = False
-        self._water_depth = 0
-        self._speed_through_water = 0
-        self._water_temperature = 0
-        self.__distance_log = 0
-        self.__distance_log_trip = 0
Index: src/gnuboat/device/tests/conftest.py
===================================================================
--- src/gnuboat/device/tests/conftest.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ src/gnuboat/device/tests/conftest.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -19,8 +19,8 @@
 import time
 
-from . import n2kdfake
+from . import n2kd_fake as n2kdfake
 
 
-@pytest.fixture(scope='module')
+@pytest.fixture(scope='function')
 def gps_fake():
     """
@@ -48,5 +48,5 @@
 
 
-@pytest.fixture(scope='module')
+@pytest.fixture(scope='function')
 def n2kd_fake():
     """
Index: src/gnuboat/device/tests/n2kd_fake.py
===================================================================
--- src/gnuboat/device/tests/n2kd_fake.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/device/tests/n2kd_fake.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,88 @@
+'''
+    Copyright (C) 2020 EngSaS - 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/>.
+'''
+
+from socketserver import StreamRequestHandler, TCPServer
+import types
+import json
+import threading
+import time
+
+
+class N2kdFakeRequestHandler(StreamRequestHandler):
+    """
+        Returns a message per request from top to bottom
+    """
+    log = None
+    finished_event = None
+
+    def handle(self):
+        if self.log is None:
+            raise ValueError('No log to serve set or log is empty')
+        if len(self.log) < 1:
+            self.finished_event.set()
+            self.log = None
+            return
+        log_entry = self.log[0]
+        self.log.pop(0)
+        self.wfile.write(json.dumps(log_entry).encode('utf-8'))
+
+
+class N2kdFakeServer(TCPServer):
+    def __init__(self):
+        self.allow_reuse_address = True
+        super().__init__()
+
+
+class N2kdFakeSession:
+    """
+        Simulates an n2kd server from canboat.
+        To get messages, add a request_handler_log()
+        and than call start(). With every request,
+        one messages (from top to bottom) is served to the
+        client, until all messages are send out
+    """
+    def __init__(self, host='127.0.0.1', port=2597):
+        self._host = host
+        self._port = port
+        self._logfile = None
+        self._server = None
+        self._server_thread = None
+        self._finished_event = threading.Event()
+
+    def request_handler_log(self, logfile):
+        with open(logfile) as f:
+            self._log = json.load(f)
+
+    def start(self):
+        N2kdFakeRequestHandler.log = self._log
+        N2kdFakeRequestHandler.finished_event = self._finished_event
+        self._server = TCPServer((self._host, self._port),
+                                 N2kdFakeRequestHandler)
+        self._server_thread = threading.Thread(
+            target=self._server.serve_forever
+        )
+        self._server_thread.start()
+        time.sleep(0.5)
+        return self._finished_event
+
+    def shutdown(self):
+        if self._server is None:
+            return
+        self._server.shutdown()
+        if self._server_thread is None:
+            return
+        self._server_thread.join(10)
Index: src/gnuboat/device/tests/n2kdfake.py
===================================================================
--- src/gnuboat/device/tests/n2kdfake.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ 	(revision )
@@ -1,88 +1,0 @@
-'''
-    Copyright (C) 2020 EngSaS - 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/>.
-'''
-
-from socketserver import StreamRequestHandler, TCPServer
-import types
-import json
-import threading
-import time
-
-
-class N2kdFakeRequestHandler(StreamRequestHandler):
-    """
-        Returns a message per request from top to bottom
-    """
-    log = None
-    finished_event = None
-
-    def handle(self):
-        if self.log is None:
-            raise ValueError('No log to serve set or log is empty')
-        if len(self.log) < 1:
-            self.finished_event.set()
-            self.log = None
-            return
-        log_entry = self.log[0]
-        self.log.pop(0)
-        self.wfile.write(json.dumps(log_entry).encode('utf-8'))
-
-
-class N2kdFakeServer(TCPServer):
-    def __init__(self):
-        self.allow_reuse_address = True
-        super().__init__()
-
-
-class N2kdFakeSession:
-    """
-        Simulates an n2kd server from canboat.
-        To get messages, add a request_handler_log()
-        and than call start(). With every request,
-        one messages (from top to bottom) is served to the
-        client, until all messages are send out
-    """
-    def __init__(self, host='127.0.0.1', port=2597):
-        self._host = host
-        self._port = port
-        self._logfile = None
-        self._server = None
-        self._server_thread = None
-        self._finished_event = threading.Event()
-
-    def request_handler_log(self, logfile):
-        with open(logfile) as f:
-            self._log = json.load(f)
-
-    def start(self):
-        N2kdFakeRequestHandler.log = self._log
-        N2kdFakeRequestHandler.finished_event = self._finished_event
-        self._server = TCPServer((self._host, self._port),
-                                 N2kdFakeRequestHandler)
-        self._server_thread = threading.Thread(
-            target=self._server.serve_forever
-        )
-        self._server_thread.start()
-        time.sleep(0.5)
-        return self._finished_event
-
-    def shutdown(self):
-        if self._server is None:
-            return
-        self._server.shutdown()
-        if self._server_thread is None:
-            return
-        self._server_thread.join(10)
Index: src/gnuboat/device/tests/test_daemon.py
===================================================================
--- src/gnuboat/device/tests/test_daemon.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ src/gnuboat/device/tests/test_daemon.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -27,5 +27,5 @@
 import threading
 
-from gnuboat.device.daemon import Daemon
+from gnuboat.device.daemon.daemon import Daemon
 
 from . import gpsd_fakehook
@@ -37,5 +37,5 @@
     rrd_file = test_dir.joinpath('rrd.db')
 
-    daemon = Daemon.Daemon(
+    daemon = Daemon(
         rrd_file, test_dir,
         gpsd_host='127.0.0.1', gpsd_port=2947,
Index: src/gnuboat/device/tests/test_gpsd_poller.py
===================================================================
--- src/gnuboat/device/tests/test_gpsd_poller.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ src/gnuboat/device/tests/test_gpsd_poller.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -24,5 +24,5 @@
 import pytz
 
-from gnuboat.device.daemon import gpsdpoller
+from gnuboat.device.daemon import gpsd_poller as gpsdpoller
 
 from . import gpsd_fakehook
Index: src/gnuboat/device/tests/test_n2kd_poller.py
===================================================================
--- src/gnuboat/device/tests/test_n2kd_poller.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ src/gnuboat/device/tests/test_n2kd_poller.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -19,5 +19,5 @@
 import os
 
-from gnuboat.device.daemon import n2kdpoller
+from gnuboat.device.daemon import n2kd_poller as n2kdpoller
 
 
Index: src/gnuboat/deviceservice_impl/Config.py
===================================================================
--- src/gnuboat/deviceservice_impl/Config.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ 	(revision )
@@ -1,51 +1,0 @@
-'''
-    Copyright (C) 2020 EngSaS - 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/>.
-'''
-
-
-class Config(object):
-    DEBUG = False
-    TESTING = False
-    MAX_CONTENT_LENGTH = 500 * 1024 * 1024
-
-
-class ProductionConfig(Config):
-    # array used for shutdown command with subprocess
-    SHUTDOWN_COMMAND = ['sudo', 'shutdown', '-h', 'now']
-    DEVICE_DATABASE = '/var/lib/gnuboat/gnuboat.rrd'
-    LOG_DIRECTORY = '/var/log/gnuboat'
-
-
-class DevelopmentConfig(Config):
-    DEBUG = True
-    MAPSERVICE = 'http://localhost:8080/mapservice/v1/'
-    MAPSERVICE_API_KEY = 'test_key_jane'
-    MAPSERVICE_DEVICE = 1
-    # Timeout to connect to mapservice in seconds
-    MAPSERVICE_TIMEOUT = 30
-    DEVICE_DATABASE = '/tmp/gnuboat-device.rrd'
-    DEMO = True
-    SHUTDOWN_COMMAND = ['echo', 'Shutdown Requested']
-    LOG_DIRECTORY = '/tmp/gnuboat-device/logs'
-    MAP_DIRECTORY = '/tmp/gnuboat-device/maps'
-
-
-class TestingConfig(DevelopmentConfig):
-    """
-        Configuration for testing purposes only (like tox/nosetests)
-    """
-    TESTING = True
-    DEBUG = False
Index: src/gnuboat/deviceservice_impl/ValidatorWorkaround.py
===================================================================
--- src/gnuboat/deviceservice_impl/ValidatorWorkaround.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ 	(revision )
@@ -1,60 +1,0 @@
-"""Hacks needed to circumvent connexion validation
-
-There is a bug on the connexion library concerning content negotiation and
-response validation. See https://github.com/zalando/connexion/issues/860 and
-https://github.com/zalando/connexion/pull/760
-
-Until this issue is fixed, we need to find a way to avoid a false validation
-error when a requests sends an 'application/geo+json' accept header
-"""
-import functools
-import logging
-
-from connexion.decorators.response import ResponseValidator
-from connexion import problem
-from connexion.exceptions import (
-    NonConformingResponseBody, NonConformingResponseHeaders
-)
-from connexion.utils import has_coroutine
-
-logger = logging.getLogger(__name__)
-
-
-class ValidatorWorkaround(ResponseValidator):
-    def validate_response_with_request(
-        self, request, data, status_code, headers, url
-    ):
-        if request.headers.get('accept', '') == 'application/zip' or \
-                headers['Content-Type'] == 'application/zip':
-            logging.debug('Circumventing validation for application/zip')
-            return True
-        return self.validate_response(data, status_code, headers, url)
-
-    def __call__(self, function):
-        """
-            :type function: types.FunctionType
-            :rtype: types.FunctionType
-        """
-        def _wrapper(request, response):
-            connexion_response = \
-             self.operation.api.get_connexion_response(response, self.mimetype)
-            self.validate_response_with_request(
-                request, connexion_response.body,
-                connexion_response.status_code, connexion_response.headers,
-                request.url
-            )
-
-            return response
-
-        if has_coroutine(function):
-            from .coroutine_wrappers import get_response_validator_wrapper
-            wrapper = get_response_validator_wrapper(function, _wrapper)
-
-        else:  # pragma: 3 no cover
-
-            @functools.wraps(function)
-            def wrapper(request):
-                response = function(request)
-                return _wrapper(request, response)
-
-        return wrapper
Index: src/gnuboat/deviceservice_impl/__init__.py
===================================================================
--- src/gnuboat/deviceservice_impl/__init__.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ src/gnuboat/deviceservice_impl/__init__.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -24,5 +24,5 @@
 from pathlib import Path
 
-from gnuboat.deviceservice_impl.ValidatorWorkaround import ValidatorWorkaround
+from gnuboat.deviceservice_impl.validator_workaround import ValidatorWorkaround
 from gnuboat.deviceservice import encoder
 
@@ -30,5 +30,5 @@
 def load_config_object(config_name):
     return import_string(
-        'gnuboat.deviceservice_impl.Config.{}Config'.format(config_name)
+        'gnuboat.deviceservice_impl.config.{}Config'.format(config_name)
     )
 
@@ -47,15 +47,9 @@
 app = connexion.App(__name__, specification_dir='../deviceservice/openapi/')
 application = app.app
-CORS(application)
 
 
-@app.route("/")
-def index():
-    return redirect("/client/index.html", code=302)
-
-
-def setup_app(app_name, config, template_folder=None):
-    application.json_encoder = encoder.JSONEncoder
-    app.add_api(
+def setup_app(app_name, config, template_folder=None, connexion_app=app):
+    connexion_app.app.json_encoder = encoder.JSONEncoder
+    connexion_app.add_api(
         'openapi.yaml',
         arguments={'title': app_name},
@@ -64,23 +58,34 @@
         validator_map={'response': ValidatorWorkaround}
     )
-    application.config.from_object(config)
+    connexion_app.app.config.from_object(config)
+    connexion_app.app.static_folder = os.path.join(
+        os.path.dirname(__file__), 'static')
 
-    application.static_url_path = '/client'
+    app = connexion_app.app
+    CORS(app)
+
+
+    @app.route("/")
+    def index():
+        return redirect("/client/index.html", code=302)
+
+    connexion_app.app.static_url_path = '/client'
     # Remove the old rule from Map._rules.
-    for rule in application.url_map.iter_rules('static'):
-        application.url_map._rules.remove(rule)  # There is probably only one.
+    for rule in connexion_app.app.url_map.iter_rules('static'):
+        # There is probably only one.
+        connexion_app.app.url_map._rules.remove(rule)
 
     # Remove the old rule from Map._rules_by_endpoint. In this case we can just
     # start fresh.
-    application.url_map._rules_by_endpoint['static'] = []
+    connexion_app.app.url_map._rules_by_endpoint['static'] = []
 
     # Add the updated rule.
-    application.add_url_rule(
-        f'{application.static_url_path}/<path:filename>',
+    connexion_app.app.add_url_rule(
+        f'{connexion_app.app.static_url_path}/<path:filename>',
         endpoint='static',
-        view_func=application.send_static_file
+        view_func=connexion_app.app.send_static_file
     )
 
-    if 'DEMO' in application.config and application.config['DEMO']:
+    if 'DEMO' in connexion_app.app.config and connexion_app.app.config['DEMO']:
         from gnuboat.deviceservice_impl.demo import create_demo
-        create_demo(application)
+        create_demo(connexion_app.app)
Index: src/gnuboat/deviceservice_impl/config.py
===================================================================
--- src/gnuboat/deviceservice_impl/config.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/deviceservice_impl/config.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,51 @@
+'''
+    Copyright (C) 2020 EngSaS - 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/>.
+'''
+
+
+class Config(object):
+    DEBUG = False
+    TESTING = False
+    MAX_CONTENT_LENGTH = 500 * 1024 * 1024
+
+
+class ProductionConfig(Config):
+    # array used for shutdown command with subprocess
+    SHUTDOWN_COMMAND = ['sudo', 'shutdown', '-h', 'now']
+    DEVICE_DATABASE = '/var/lib/gnuboat/gnuboat.rrd'
+    LOG_DIRECTORY = '/var/log/gnuboat'
+
+
+class DevelopmentConfig(Config):
+    DEBUG = True
+    MAPSERVICE = 'http://localhost:8080/mapservice/v1/'
+    MAPSERVICE_API_KEY = 'test_key_jane'
+    MAPSERVICE_DEVICE = 1
+    # Timeout to connect to mapservice in seconds
+    MAPSERVICE_TIMEOUT = 30
+    DEVICE_DATABASE = '/tmp/gnuboat-device.rrd'
+    DEMO = True
+    SHUTDOWN_COMMAND = ['echo', 'Shutdown Requested']
+    LOG_DIRECTORY = '/tmp/gnuboat-device/logs'
+    MAP_DIRECTORY = '/tmp/gnuboat-device/maps'
+
+
+class TestingConfig(DevelopmentConfig):
+    """
+        Configuration for testing purposes only (like tox/nosetests)
+    """
+    TESTING = True
+    DEBUG = False
Index: src/gnuboat/deviceservice_impl/controllers/DeviceController.py
===================================================================
--- src/gnuboat/deviceservice_impl/controllers/DeviceController.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ 	(revision )
@@ -1,133 +1,0 @@
-'''
-    Copyright (C) 2020 EngSaS - 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 connexion
-import flask
-import subprocess
-import rrdtool
-import os
-import datetime
-
-import gnuboat.common.datahandler.rrdschema as rrdschema
-from gnuboat.common.webservice.HttpErrors import (
-    GnuboatNotFound, GnuboatInternalServerError
-)
-
-
-def instrument_data_get():
-    rrdfile = _rrdfile_get()
-    try:
-        result = rrdtool.lastupdate(rrdfile)
-    except Exception as e:
-        raise GnuboatInternalServerError(
-            detail='Could not query rrd database. Error: {}'.format(repr(e)))
-    if 'ds' not in result:
-        raise GnuboatNotFound(detail='No databset found')
-    if (datetime.datetime.now() - result['date']).total_seconds() > 10:
-        raise GnuboatNotFound(detail='Last entry is older than 10s')
-    return {
-        'speedThroughWater': result['ds']['speedthroughwater'],
-        'speedOverGround': result['ds']['speedoverground'],
-        'courseOverGround': result['ds']['courseoverground'],
-        'waterDepth': result['ds']['waterdepth'],
-        'waterTemperature': result['ds']['watertemperature'],
-        'position': [result['ds']['longitude'], result['ds']['latitude']],
-        'gpsFix': gpsfix_to_enum(result['ds']['gpsfix']),
-    }
-
-
-def track_get():
-    rrdfile = _rrdfile_get()
-
-    track = {}
-    for archive in rrdschema.archives:
-        result = _rrd_fetch(rrdfile, archive.resolution,
-                            '{}s'.format(archive.duration))
-
-        start, end, interval = result[0]
-        keys = result[1]
-        latitude = keys.index('latitude')
-        longitude = keys.index('longitude')
-        speedthroughwater = keys.index('speedthroughwater')
-        speedoverground = keys.index('speedoverground')
-        courseoverground = keys.index('courseoverground')
-        waterdepth = keys.index('waterdepth')
-        watertemperature = keys.index('watertemperature')
-        gpsfix = keys.index('gpsfix')
-
-        i = 0
-        for dataset in result[2]:
-            timestamp = start + i * interval
-            if timestamp not in track and dataset[gpsfix]:
-                track[timestamp] = {
-                    'speedThroughWater': dataset[speedthroughwater],
-                    'speedOverGround': dataset[speedoverground],
-                    'courseOverGround': dataset[courseoverground],
-                    'waterDepth': dataset[waterdepth],
-                    'waterTemperature': dataset[watertemperature],
-                    'position': [dataset[longitude], dataset[latitude]],
-                    'gpsFix': gpsfix_to_enum(dataset[gpsfix]),
-                }
-            i += 1
-
-    return track
-
-
-def shutdown():
-    if 'SHUTDOWN_COMMAND' not in flask.current_app.config:
-        raise GnuboatInternalServerError(
-            detail='SHUTDOWN_COMMAND not configured'
-        )
-    command = flask.current_app.config['SHUTDOWN_COMMAND']
-    if not isinstance(command, list):
-        raise GnuboatInternalServerError(
-            detail='SHUTDOWN_COMMAND must be a list'
-        )
-    try:
-        subprocess.run(command, check=True)
-    except subprocess.CalledProcessError as e:
-        raise GnuboatInternalServerError(detail=repr(e))
-
-
-def _rrdfile_get():
-    if 'DEVICE_DATABASE' not in flask.current_app.config or not os.access(
-        flask.current_app.config['DEVICE_DATABASE'], os.R_OK
-    ):
-        raise GnuboatInternalServerError(
-            detail='DEVICE_DATABASE not configured or not accessible'
-        )
-    return flask.current_app.config['DEVICE_DATABASE']
-
-
-def _rrd_fetch(rrdfile, interval, period):
-    try:
-        return rrdtool.fetch(
-            rrdfile, 'AVERAGE', '--resolution', str(interval),
-            '--start', '-{}'.format(period), '--align-start'
-        )
-    except Exception as e:
-        raise GnuboatInternalServerError(
-            detail=('Could not fetch from rrd database. '
-                    'Error: {}').format(repr(e)))
-
-
-def gpsfix_to_enum(gpsfix):
-    if gpsfix == 2:
-        return "2D"
-    elif gpsfix == 3:
-        return "3D"
-    else:
-        return "-"
Index: src/gnuboat/deviceservice_impl/controllers/DeviceLogsController.py
===================================================================
--- src/gnuboat/deviceservice_impl/controllers/DeviceLogsController.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ 	(revision )
@@ -1,155 +1,0 @@
-'''
-    Copyright (C) 2020 EngSaS - 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 connexion
-import flask
-from werkzeug.utils import secure_filename
-from pathlib import Path
-import io
-import zipfile
-import os
-from datetime import datetime, timezone
-
-from gnuboat.common.webservice.HttpErrors import (
-    GnuboatBadRequest, GnuboatUnauthorized,
-    GnuboatNotFound, GnuboatInternalServerError
-)
-from gnuboat.common.datahandler import loghandler
-
-
-class LogEntryCallback:
-    def __init__(self):
-        self._entries = []
-        self._start = None
-        self._end = None
-
-    def valid(self):
-        if self._start is None:
-            return False
-        if self._end is None:
-            return False
-        if len(self._entries) < 1:
-            return False
-        return True
-
-    def start(self):
-        return self._start
-
-    def end(self):
-        return self._end
-
-    def entries(self):
-        return self._entries
-
-    def callback(self, dataset):
-        self._entries.append(dataset)
-
-        # check / set start and end date
-        entry_datetime = dataset.datetime_object()
-        if self.start() is None or entry_datetime < self.start():
-            self._start = entry_datetime
-        if self.end() is None or self.end() < entry_datetime:
-            self._end = entry_datetime
-
-
-def logfiles_get():
-    logdir = logdirectory_get()
-    files = sorted(logdir.glob('*.log'))
-    result = []
-    for path in files:
-        result.append(path.name)
-    return result
-
-
-def logs_get(name):
-    logdir = logdirectory_get()
-
-    logfiles = name.split(',')
-    if len(logfiles) < 1:
-        raise GnuboatNotFound(detail='Logfile {} not found'.format(name))
-    elif len(logfiles) == 1:
-        logfile = logdir.joinpath(secure_filename(name))
-        if not logfile.is_file():
-            raise GnuboatNotFound(
-                detail='Logfile {} does not exists'.format(name))
-        response = flask.send_file(
-            logfile.resolve(),
-            mimetype='text/plain',
-            as_attachment=True,
-            attachment_filename=name
-        )
-        response.direct_passthrough = False
-        return response
-    else:
-        archive_name = 'gnuboat-logs-{}'.format(
-            datetime.utcnow().strftime('%Y-%m-%d'))
-        zip_buffer = io.BytesIO()
-        with zipfile.ZipFile(
-            zip_buffer, mode='w', compression=zipfile.ZIP_DEFLATED
-        ) as zip_file:
-            for logfile in logfiles:
-                logfile = secure_filename(logfile)
-                zip_file.write(
-                    logdir.joinpath(logfile).resolve(),
-                    os.path.join(archive_name, logfile)
-                )
-        zip_buffer.seek(0)
-        response = flask.send_file(
-            zip_buffer,
-            mimetype='application/zip',
-            as_attachment=True,
-            attachment_filename='{}.zip'.format(archive_name)
-        )
-        response.direct_passthrough = False
-        return response
-
-
-def logs_track_get(name):
-    logfile = logdirectory_get().joinpath(secure_filename(name))
-    if not logfile.is_file():
-        raise GnuboatNotFound(detail='Logfile {} not found'.format(name))
-
-    log_callback = LogEntryCallback()
-    log_handler = loghandler.LogHandler()
-    result = log_handler.gnuboat_read_file(
-        logfile, log_callback.callback, False, False
-    )
-    if not result.success():
-        raise GnuboatInternalServerError(
-            detail='Could not parse logfile {}'.format(name))
-
-    result = {}
-    for entry in log_callback.entries():
-        location = entry.location()
-        result[
-            entry.datetime_object().replace(tzinfo=timezone.utc).timestamp()
-        ] = {
-            'speedOverGround': entry.speed_over_ground(),
-            'courseOverGround': entry.course_over_ground(),
-            'waterDepth': entry.water_depth(),
-            'waterTemperature': entry.water_temperature(),
-            'position': [location.longitude, location.latitude],
-            'gpsFix': '3D' if entry.gps_status() == 'A' else '-'
-        }
-    return result
-
-
-def logdirectory_get():
-    if 'LOG_DIRECTORY' not in flask.current_app.config:
-        raise GnuboatInternalServerError(
-            detail='LOG_DIRECTORY not configured or not accessible'
-        )
-    return Path(flask.current_app.config['LOG_DIRECTORY'])
Index: src/gnuboat/deviceservice_impl/controllers/DeviceMapsController.py
===================================================================
--- src/gnuboat/deviceservice_impl/controllers/DeviceMapsController.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ 	(revision )
@@ -1,219 +1,0 @@
-'''
-    Copyright (C) 2020 EngSaS - 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 connexion
-import flask
-from werkzeug.utils import secure_filename
-from pathlib import Path
-import sqlite3
-from hashlib import shake_256
-import io
-import tempfile
-import os
-import base64
-
-from gnuboat.common.webservice.HttpErrors import (
-    GnuboatNotFound, GnuboatInternalServerError,
-    GnuboatBadRequest
-)
-
-
-def map_name_to_file(name):
-    map_dir = _get_map_directory()
-    return map_dir.joinpath('{}.mbtiles'.format(_map_name_to_hash(name)))
-
-
-def maps_get():
-    result = []
-    map_dir = _get_map_directory()
-    for map_db in map_dir.glob('*.mbtiles'):
-        try:
-            metadata = {'tilejson': '2.0.0'}
-            connection = sqlite3.connect(str(map_db.resolve()))
-        except Exception as e:
-            flask.current_app.logger.error(
-                'Failed to open map {}. Error: {}'.format(
-                    map_db.resolve(), repr(e)))
-            continue
-
-        name = _get_metadata(connection, 'name', str(map_db))
-        if name is None:
-            connection.close()
-            flask.current_app.logger.error(
-                ('Name not found in map {} '
-                 'metadata --> Skipping').format(map_db.resolve()))
-            continue
-        metadata['name'] = name
-        url = flask.url_for(
-            ('/deviceservice/v1.gnuboat_deviceservice_'
-             'controllers_device_maps_controller_maps_tile_get'),
-            mapname=_map_name_to_hash(name), zoom=99, x_tile="98",
-            y_tile="97", _external=True
-        )
-        url = url.replace('/99/', '/{z}/').replace(
-            '/98/', '/{x}/').replace('/97.', '/{y}.')
-        metadata['tiles'] = [url]
-        _add_metadata(connection, 'description', str(map_db), metadata)
-        _add_metadata(connection, 'version', str(map_db), metadata)
-        _add_metadata(connection, 'attribution', str(map_db), metadata)
-        _add_metadata(connection, 'template', str(map_db), metadata)
-        _add_metadata(connection, 'legend', str(map_db), metadata)
-        _add_metadata(connection, 'schema', str(map_db), metadata)
-        _add_metadata(connection, 'minzoom', str(map_db), metadata)
-        _add_metadata(connection, 'maxzoom', str(map_db), metadata)
-        _add_metadata(connection, 'bounds', str(map_db), metadata)
-        _add_metadata(connection, 'center', str(map_db), metadata)
-        _add_metadata(connection, 'data', str(map_db), metadata)
-        _add_metadata(connection, 'grids', str(map_db), metadata)
-
-        if 'minzoom' not in metadata or 'maxzoom' not in metadata:
-            cursor = connection.cursor()
-            try:
-                cursor.execute(
-                    ('SELECT MIN(zoom_level), MAX(zoom_level) '
-                     'FROM tiles')
-                )
-                zoomlevels = cursor.fetchall()
-                if 'minzoom' not in metadata:
-                    metadata['minzoom'] = zoomlevels[0][0]
-                if 'maxzoom' not in metadata:
-                    metadata['maxzoom'] = zoomlevels[0][1]
-            except Expcetion as e:
-                flask.current_app.logger.error(
-                    ('Could not get min and max '
-                     'zoomlevel from map {}').format(str(map_db)))
-        result.append(metadata)
-
-        connection.close()
-    return result
-
-
-def maps_tile_get(mapname, zoom, x_tile, y_tile):
-    map_dir = _get_map_directory()
-    map_db = map_dir.joinpath('{}.mbtiles'.format(secure_filename(mapname)))
-    if not map_db.is_file():
-        raise GnuboatNotFound(detail='Map {} does not exist'.format(mapname))
-
-    try:
-        connection = sqlite3.connect(str(map_db.resolve()))
-    except Exception as e:
-        raise GnuboatInternalServerError(
-            detail=('Could not open map {} '
-                    'to serve tiles').format(mapname))
-    cursor = connection.cursor()
-    try:
-        cursor.execute(
-            ('SELECT tile_data FROM tiles WHERE '
-             'zoom_level=? AND tile_column=? and tile_row=?'),
-            (zoom, x_tile, y_tile))
-    except:
-        connection.close()
-        raise GnuboatInternalServerError(
-            detail=('Could not get tile '
-                    '{z}/{x}/{y} of map {} to serve tiles').format(
-                        zoom, x_tile, y_tile, mapname))
-    results = cursor.fetchall()
-    if len(results) != 1:
-        raise GnuboatNotFound(detail='Could not find tile {}/{}/{}/{}'.format(
-            mapname, zoom, x_tile, y_tile))
-    connection.close()
-
-    response = flask.send_file(
-        io.BytesIO(results[0][0]),
-        mimetype='image/png',
-        as_attachment=True,
-        attachment_filename='{}.png'.format(y_tile)
-    )
-    response.direct_passthrough = False
-    return response
-
-
-def maps_upload(body=None):
-    if body is None:
-        raise GnuboatBadRequest(detail='No map given')
-
-    database_content = base64.b64decode(body)
-    file_handle, path = tempfile.mkstemp(suffix='.mbtiles')
-    with open(file_handle, 'wb') as f:
-        f.write(database_content)
-
-    try:
-        connection = sqlite3.connect(path)
-        name = _get_metadata(connection, 'name', path)
-        connection.close()
-    except Exception as e:
-        raise GnuboatInternalServerError(
-            detail='Could not create temporary database: {}'.format(repr(e))
-        )
-    finally:
-        os.remove(path)
-
-    if name is None:
-        raise GnuboatBadRequest(
-            detail=('No name for map in mbtile-file set. '
-                    'Please add a name to the mbtiles metadata table '
-                    '(it\'s a SQLite database)'))
-
-    map_path = _get_map_directory().joinpath(
-        '{}.mbtiles'.format(_map_name_to_hash(name)))
-    if map_path.is_file():
-        raise GnuboatBadRequest(detail='Map with this name already exists')
-    with open(map_path, 'wb') as file_handle:
-        file_handle.write(database_content)
-    return maps_get()
-
-
-def _map_name_to_hash(name):
-    return shake_256(name.encode('utf-8')).hexdigest(32)
-
-
-def _add_metadata(connection, name, db, result_dict):
-    value = _get_metadata(connection, name, db)
-    if value is not None:
-        if name == 'minzoom' or name == 'maxzoom':
-            value = int(value)
-        if name == 'bounds' or name == 'center':
-            value = [float(i) for i in value.split(',')]
-        if name == 'data' or name == 'grids':
-            flask.current_app.logger.error(
-                ('Please report a bug to implement '
-                 'map metadata extraction of type {} with example value {}')
-                .format(name, value))
-        result_dict[name] = value
-
-
-def _get_metadata(connection, name, db):
-    cursor = connection.cursor()
-    try:
-        cursor.execute('SELECT value FROM metadata WHERE name=?', (name,))
-    except Exception as e:
-        flask.current_app.logger.info(
-            '{} not found in map {} metadata'.format(name, db))
-        return None
-    results = cursor.fetchall()
-    if len(results) != 1:
-        flask.current_app.logger.info(
-            '{} not found in map {} metadata'.format(name, db))
-        return None
-    return results[0][0]
-
-
-def _get_map_directory():
-    if 'MAP_DIRECTORY' not in flask.current_app.config:
-        raise GnuboatInternalServerError(
-            detail='MAP_DIRECTORY not configured or not accessible'
-        )
-    return Path(flask.current_app.config['MAP_DIRECTORY'])
Index: src/gnuboat/deviceservice_impl/controllers/MapserviceController.py
===================================================================
--- src/gnuboat/deviceservice_impl/controllers/MapserviceController.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ 	(revision )
@@ -1,305 +1,0 @@
-'''
-    Copyright (C) 2020 EngSaS - 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 connexion
-import flask
-from werkzeug.utils import secure_filename
-import socket
-from urllib.parse import urlparse
-from urllib3.exceptions import RequestError
-from enum import Enum
-import datetime
-import json
-import os
-
-from gnuboat.common.webservice.HttpErrors import (
-    GnuboatBadRequest, GnuboatUnauthorized,
-    GnuboatNotFound, GnuboatInternalServerError,
-    GnuboatPayloadToLarge, GnuboatGatewayTimeout,
-    GnuboatBadGateway
-)
-from gnuboat.deviceservice_impl.controllers.DeviceLogsController import (
-    logdirectory_get
-)
-from gnuboat.mapservice_client.configuration import (
-    Configuration as MsConfiguration
-)
-from gnuboat.mapservice_client.api_client import ApiClient as MsApiClient
-from gnuboat.mapservice_client.api.waters_api import WatersApi as MsWatersApi
-from gnuboat.mapservice_client.api.devices_api import (
-    DevicesApi as MsDevicesApi
-)
-from gnuboat.mapservice_client.api.logs_api import LogsApi as MsLogsApi
-from gnuboat.mapservice_client.models.log_creation import (
-    LogCreation as MsLogCreation
-)
-from gnuboat.mapservice_client.exceptions import ApiException as MsApiException
-
-
-class MapserviceStatus(Enum):
-    NO_API_KEY = 0
-    NO_DEVICE = 1
-    DEVICE_NOT_FOUND = 2
-    NO_CONNECTION = 4
-    OK = 7
-
-
-def mapservice_status():
-    mapservice_status = _mapservice_status()
-    flask.mapservice_status = mapservice_status
-
-    if mapservice_status == MapserviceStatus.NO_CONNECTION:
-        return mapservice_status.name, 504
-    return mapservice_status.name
-
-
-def waters_get(
-        name=None,
-        order_by=None,
-        offset=None,
-        limit=None):
-    if _mapservice_status() != MapserviceStatus.OK:
-        raise GnuboatBadRequest(
-            detail='Mapservice not available. See remote status for help')
-
-    configuration = _mapservice_configuration()
-    with MsApiClient(configuration) as api_client:
-        try:
-            waters = MsWatersApi(api_client).waters_get(
-                name=name, order_by=order_by, offset=offset, limit=limit
-            )
-        except Exception as e:
-            _handle_api_exception(e)
-
-        results = []
-        for water in waters:
-            gauges = []
-            if water.gauges is not None:
-                for gauge in water.gauges:
-                    gauges.append({
-                        'gaugeId': gauge.gauge_id,
-                        'location': gauge.location,
-                        'name': gauge.name,
-                        'referenceWaterLevelGaugeHeight':
-                            gauge.reference_water_level_gauge_height,
-                    })
-            results.append({
-                'waterId': water.water_id,
-                'name': water.name,
-                'gauges': gauges,
-            })
-        return results
-
-
-def log_create(log_creation=None):
-    if _mapservice_status() != MapserviceStatus.OK:
-        raise GnuboatBadRequest(
-            detail='Mapservice not available. See remote status for help')
-
-    log_dir = logdirectory_get()
-    logfile = secure_filename(log_creation.logfile)
-    logfile_path = log_dir.joinpath(logfile)
-    if not logfile_path.is_file():
-        raise GnuboatNotFound(detail='Logfile {} not found'.format(logfile))
-
-    # building log_creation for the mapservice
-    log_creation_mapservice = MsLogCreation(
-        water=log_creation.water,
-        device=_mapservice_device_get().device_id,
-        gauge=log_creation.gauge,
-        gauge_height=log_creation.gauge_height,
-        comment=log_creation.comment,
-    )
-
-    configuration = _mapservice_configuration()
-    with MsApiClient(configuration) as api_client:
-        # create log
-        try:
-            log_metadata = MsLogsApi(api_client).logs_log_create(
-                log_creation=log_creation_mapservice
-            )
-        except Exception as e:
-            _handle_api_exception(e)
-
-        # read log file content from local storage
-        with open(logfile_path, 'rb') as logfilehandle:
-            file_content = logfilehandle.read()
-        # upload log content to newly created log from above
-        try:
-            log_metadata = MsLogsApi(api_client).logs_log_upload(
-                log_id=log_metadata.log_id, body=file_content
-            )
-        except Exception as e:
-            _handle_api_exception(e)
-
-        if log_creation.delete:
-            os.remove(logfile_path)
-
-
-def _mapservice_url():
-    if 'MAPSERVICE' in flask.current_app.config:
-        url = flask.current_app.config['MAPSERVICE']
-        if url.endswith('/'):
-            return url[:-1]
-        return url
-    configuration = MsConfiguration()
-    if configuration.host:
-        return configuration.host
-    raise GnuboatInternalServerError(
-        detail=('No host for mapservice configured '
-                '(See MAPSERVICE config option)'))
-
-
-def _mapservice_api_key():
-    if 'MAPSERVICE_API_KEY' not in flask.current_app.config:
-        raise GnuboatInternalServerError(
-            detail='MAPSERVICE_API_KEY not configured'
-        )
-    return flask.current_app.config['MAPSERVICE_API_KEY']
-
-
-def _mapservice_device():
-    if 'MAPSERVICE_DEVICE' not in flask.current_app.config:
-        raise GnuboatInternalServerError(
-            detail='MAPSERVICE_DEVICE not configured'
-        )
-    return flask.current_app.config['MAPSERVICE_DEVICE']
-
-
-def _mapservice_device_get():
-    if hasattr(flask, 'mapservice_device') and flask.mapservice_device:
-        return flask.mapservice_device
-
-    device_id = _mapservice_device()
-    configuration = _mapservice_configuration()
-    with MsApiClient(configuration) as api_client:
-        try:
-            device = MsDevicesApi(api_client).devices_get_by_id(device_id)
-        except Exception as e:
-            flask.mapservice_device = False
-            body = json.loads(e.body)
-            if 'detail' in body:
-                flask.current_app.logger.error(
-                    'Failed to get device: {}'.format(body['detail']))
-            return False
-
-        flask.mapservice_device = device
-        return device
-
-
-def _mapservice_configuration():
-    configuration = MsConfiguration()
-    configuration.host = _mapservice_url()
-    configuration.api_key['X-API-KEY'] = _mapservice_api_key()
-    return configuration
-
-
-def _mapservice_status():
-    try:
-        mapservice_api_key = _mapservice_api_key()
-    except:
-        return MapserviceStatus.NO_API_KEY
-
-    try:
-        mapservice_device = _mapservice_device()
-    except:
-        return MapserviceStatus.NO_DEVICE
-
-    if hasattr(flask, 'mapservice_device') and not flask.mapservice_device:
-        return MapserviceStatus.DEVICE_NOT_FOUND
-
-    # prevent to many status polls
-    if hasattr(flask, 'mapservice_check') and \
-            hasattr(flask, 'mapservice_status'):
-        if (datetime.datetime.now() - flask.mapservice_check).total_seconds() \
-                < 60:
-            return flask.mapservice_status
-
-    mapservice_url = _mapservice_url()
-
-    fragments = urlparse(mapservice_url)
-    if fragments.hostname is None:
-        raise GnuboatInternalServerError(
-            detail='No hostname for mapservice set')
-    if fragments.port is None:
-        if fragments.scheme == 'http':
-            fragments.port = 80
-        elif fragments.scheme == 'https':
-            fragments.port = 443
-        else:
-            raise GnuboatInternalServerError(
-                detail='Could not determine port for mapservice')
-
-    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-    s.settimeout(5)
-    try:
-        s.connect((fragments.hostname, int(fragments.port)))
-        s.shutdown(socket.SHUT_RDWR)
-    except:
-        flask.mapservice_status = MapserviceStatus.NO_CONNECTION
-        return MapserviceStatus.NO_CONNECTION
-    finally:
-        flask.mapservice_check = datetime.datetime.now()
-        s.close()
-
-    if hasattr(flask, 'mapservice_device') and flask.mapservice_device:
-        flask.mapservice_status = MapserviceStatus.OK
-        return MapserviceStatus.OK
-
-    device = _mapservice_device_get()
-    if not device:
-        flask.mapservice_status = MapserviceStatus.DEVICE_NOT_FOUND
-        return MapserviceStatus.DEVICE_NOT_FOUND
-    flask.mapservice_status = MapserviceStatus.OK
-    return MapserviceStatus.OK
-
-
-def _handle_api_exception(exception):
-    if isinstance(exception, MsApiException):
-        if exception.body is None:
-            raise GnuboatInternalServerError(
-                detail='Unkown error occured: {}'.format(repr(exception)))
-
-        response_body = json.loads(exception.body)
-        if 'status' not in response_body:
-            raise GnuboatInternalServerError(
-                detail='Unkown error occured: {}'.format(repr(exception)))
-        status = response_body['status']
-        if 'detail' in response_body:
-            detail = response_body['detail']
-        else:
-            detail = ''
-    elif isinstance(exception, RequestError):
-        status = '502'
-        detail = 'Could not connect to server {}:{}/{}'.format(
-            exception.pool.host, exception.pool.port, exception.url
-        )
-    else:
-        status = 502
-        detail = 'An unexpected error occured: {}'.format(repr(exception))
-
-    if status == 400:
-        raise GnuboatBadRequest(detail=detail)
-    if status == 401:
-        raise GnuboatUnauthorized(detail=detail)
-    if status == 404:
-        raise GnuboatNotFound(detail=detail)
-    if status == 413:
-        raise GnuboatPayloadToLarge(detail=detail)
-    if status == 500:
-        raise GnuboatInternalServerError(detail=detail)
-    if status == 504:
-        raise GnuboatGatewayTimeout(detail=detail)
Index: src/gnuboat/deviceservice_impl/controllers/device_controller.py
===================================================================
--- src/gnuboat/deviceservice_impl/controllers/device_controller.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/deviceservice_impl/controllers/device_controller.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,133 @@
+'''
+    Copyright (C) 2020 EngSaS - 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 connexion
+import flask
+import subprocess
+import rrdtool
+import os
+import datetime
+
+import gnuboat.common.datahandler.rrd_schema as rrdschema
+from gnuboat.common.webservice.http_errors import (
+    GnuboatNotFound, GnuboatInternalServerError
+)
+
+
+def instrument_data_get():
+    rrdfile = _rrdfile_get()
+    try:
+        result = rrdtool.lastupdate(rrdfile)
+    except Exception as e:
+        raise GnuboatInternalServerError(
+            detail='Could not query rrd database. Error: {}'.format(repr(e)))
+    if 'ds' not in result:
+        raise GnuboatNotFound(detail='No databset found')
+    if (datetime.datetime.now() - result['date']).total_seconds() > 10:
+        raise GnuboatNotFound(detail='Last entry is older than 10s')
+    return {
+        'speedThroughWater': result['ds']['speedthroughwater'],
+        'speedOverGround': result['ds']['speedoverground'],
+        'courseOverGround': result['ds']['courseoverground'],
+        'waterDepth': result['ds']['waterdepth'],
+        'waterTemperature': result['ds']['watertemperature'],
+        'position': [result['ds']['longitude'], result['ds']['latitude']],
+        'gpsFix': gpsfix_to_enum(result['ds']['gpsfix']),
+    }
+
+
+def track_get():
+    rrdfile = _rrdfile_get()
+
+    track = {}
+    for archive in rrdschema.archives:
+        result = _rrd_fetch(rrdfile, archive.resolution,
+                            '{}s'.format(archive.duration))
+
+        start, end, interval = result[0]
+        keys = result[1]
+        latitude = keys.index('latitude')
+        longitude = keys.index('longitude')
+        speedthroughwater = keys.index('speedthroughwater')
+        speedoverground = keys.index('speedoverground')
+        courseoverground = keys.index('courseoverground')
+        waterdepth = keys.index('waterdepth')
+        watertemperature = keys.index('watertemperature')
+        gpsfix = keys.index('gpsfix')
+
+        i = 0
+        for dataset in result[2]:
+            timestamp = start + i * interval
+            if timestamp not in track and dataset[gpsfix]:
+                track[timestamp] = {
+                    'speedThroughWater': dataset[speedthroughwater],
+                    'speedOverGround': dataset[speedoverground],
+                    'courseOverGround': dataset[courseoverground],
+                    'waterDepth': dataset[waterdepth],
+                    'waterTemperature': dataset[watertemperature],
+                    'position': [dataset[longitude], dataset[latitude]],
+                    'gpsFix': gpsfix_to_enum(dataset[gpsfix]),
+                }
+            i += 1
+
+    return track
+
+
+def shutdown():
+    if 'SHUTDOWN_COMMAND' not in flask.current_app.config:
+        raise GnuboatInternalServerError(
+            detail='SHUTDOWN_COMMAND not configured'
+        )
+    command = flask.current_app.config['SHUTDOWN_COMMAND']
+    if not isinstance(command, list):
+        raise GnuboatInternalServerError(
+            detail='SHUTDOWN_COMMAND must be a list'
+        )
+    try:
+        subprocess.run(command, check=True)
+    except subprocess.CalledProcessError as e:
+        raise GnuboatInternalServerError(detail=repr(e))
+
+
+def _rrdfile_get():
+    if 'DEVICE_DATABASE' not in flask.current_app.config or not os.access(
+        flask.current_app.config['DEVICE_DATABASE'], os.R_OK
+    ):
+        raise GnuboatInternalServerError(
+            detail='DEVICE_DATABASE not configured or not accessible'
+        )
+    return flask.current_app.config['DEVICE_DATABASE']
+
+
+def _rrd_fetch(rrdfile, interval, period):
+    try:
+        return rrdtool.fetch(
+            rrdfile, 'AVERAGE', '--resolution', str(interval),
+            '--start', '-{}'.format(period), '--align-start'
+        )
+    except Exception as e:
+        raise GnuboatInternalServerError(
+            detail=('Could not fetch from rrd database. '
+                    'Error: {}').format(repr(e)))
+
+
+def gpsfix_to_enum(gpsfix):
+    if gpsfix == 2:
+        return "2D"
+    elif gpsfix == 3:
+        return "3D"
+    else:
+        return "-"
Index: src/gnuboat/deviceservice_impl/controllers/device_logs_controller.py
===================================================================
--- src/gnuboat/deviceservice_impl/controllers/device_logs_controller.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/deviceservice_impl/controllers/device_logs_controller.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,155 @@
+'''
+    Copyright (C) 2020 EngSaS - 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 connexion
+import flask
+from werkzeug.utils import secure_filename
+from pathlib import Path
+import io
+import zipfile
+import os
+from datetime import datetime, timezone
+
+from gnuboat.common.webservice.http_errors import (
+    GnuboatBadRequest, GnuboatUnauthorized,
+    GnuboatNotFound, GnuboatInternalServerError
+)
+from gnuboat.common.datahandler import log_handler as loghandler
+
+
+class LogEntryCallback:
+    def __init__(self):
+        self._entries = []
+        self._start = None
+        self._end = None
+
+    def valid(self):
+        if self._start is None:
+            return False
+        if self._end is None:
+            return False
+        if len(self._entries) < 1:
+            return False
+        return True
+
+    def start(self):
+        return self._start
+
+    def end(self):
+        return self._end
+
+    def entries(self):
+        return self._entries
+
+    def callback(self, dataset):
+        self._entries.append(dataset)
+
+        # check / set start and end date
+        entry_datetime = dataset.datetime_object()
+        if self.start() is None or entry_datetime < self.start():
+            self._start = entry_datetime
+        if self.end() is None or self.end() < entry_datetime:
+            self._end = entry_datetime
+
+
+def logfiles_get():
+    logdir = logdirectory_get()
+    files = sorted(logdir.glob('*.log'))
+    result = []
+    for path in files:
+        result.append(path.name)
+    return result
+
+
+def logs_get(name):
+    logdir = logdirectory_get()
+
+    logfiles = name.split(',')
+    if len(logfiles) < 1:
+        raise GnuboatNotFound(detail='Logfile {} not found'.format(name))
+    elif len(logfiles) == 1:
+        logfile = logdir.joinpath(secure_filename(name))
+        if not logfile.is_file():
+            raise GnuboatNotFound(
+                detail='Logfile {} does not exists'.format(name))
+        response = flask.send_file(
+            logfile.resolve(),
+            mimetype='text/plain',
+            as_attachment=True,
+            attachment_filename=name
+        )
+        response.direct_passthrough = False
+        return response
+    else:
+        archive_name = 'gnuboat-logs-{}'.format(
+            datetime.utcnow().strftime('%Y-%m-%d'))
+        zip_buffer = io.BytesIO()
+        with zipfile.ZipFile(
+            zip_buffer, mode='w', compression=zipfile.ZIP_DEFLATED
+        ) as zip_file:
+            for logfile in logfiles:
+                logfile = secure_filename(logfile)
+                zip_file.write(
+                    logdir.joinpath(logfile).resolve(),
+                    os.path.join(archive_name, logfile)
+                )
+        zip_buffer.seek(0)
+        response = flask.send_file(
+            zip_buffer,
+            mimetype='application/zip',
+            as_attachment=True,
+            attachment_filename='{}.zip'.format(archive_name)
+        )
+        response.direct_passthrough = False
+        return response
+
+
+def logs_track_get(name):
+    logfile = logdirectory_get().joinpath(secure_filename(name))
+    if not logfile.is_file():
+        raise GnuboatNotFound(detail='Logfile {} not found'.format(name))
+
+    log_callback = LogEntryCallback()
+    log_handler = loghandler.LogHandler()
+    result = log_handler.gnuboat_read_file(
+        logfile, log_callback.callback, False, False
+    )
+    if not result.success():
+        raise GnuboatInternalServerError(
+            detail='Could not parse logfile {}'.format(name))
+
+    result = {}
+    for entry in log_callback.entries():
+        location = entry.location()
+        result[
+            entry.datetime_object().replace(tzinfo=timezone.utc).timestamp()
+        ] = {
+            'speedOverGround': entry.speed_over_ground(),
+            'courseOverGround': entry.course_over_ground(),
+            'waterDepth': entry.water_depth(),
+            'waterTemperature': entry.water_temperature(),
+            'position': [location.longitude, location.latitude],
+            'gpsFix': '3D' if entry.gps_status() == 'A' else '-'
+        }
+    return result
+
+
+def logdirectory_get():
+    if 'LOG_DIRECTORY' not in flask.current_app.config:
+        raise GnuboatInternalServerError(
+            detail='LOG_DIRECTORY not configured or not accessible'
+        )
+    return Path(flask.current_app.config['LOG_DIRECTORY'])
Index: src/gnuboat/deviceservice_impl/controllers/device_maps_controller.py
===================================================================
--- src/gnuboat/deviceservice_impl/controllers/device_maps_controller.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/deviceservice_impl/controllers/device_maps_controller.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,219 @@
+'''
+    Copyright (C) 2020 EngSaS - 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 connexion
+import flask
+from werkzeug.utils import secure_filename
+from pathlib import Path
+import sqlite3
+from hashlib import shake_256
+import io
+import tempfile
+import os
+import base64
+
+from gnuboat.common.webservice.http_errors import (
+    GnuboatNotFound, GnuboatInternalServerError,
+    GnuboatBadRequest
+)
+
+
+def map_name_to_file(name):
+    map_dir = _get_map_directory()
+    return map_dir.joinpath('{}.mbtiles'.format(_map_name_to_hash(name)))
+
+
+def maps_get():
+    result = []
+    map_dir = _get_map_directory()
+    for map_db in map_dir.glob('*.mbtiles'):
+        try:
+            metadata = {'tilejson': '2.0.0'}
+            connection = sqlite3.connect(str(map_db.resolve()))
+        except Exception as e:
+            flask.current_app.logger.error(
+                'Failed to open map {}. Error: {}'.format(
+                    map_db.resolve(), repr(e)))
+            continue
+
+        name = _get_metadata(connection, 'name', str(map_db))
+        if name is None:
+            connection.close()
+            flask.current_app.logger.error(
+                ('Name not found in map {} '
+                 'metadata --> Skipping').format(map_db.resolve()))
+            continue
+        metadata['name'] = name
+        url = flask.url_for(
+            ('/deviceservice/v1.gnuboat_deviceservice_'
+             'controllers_device_maps_controller_maps_tile_get'),
+            mapname=_map_name_to_hash(name), zoom=99, x_tile="98",
+            y_tile="97", _external=True
+        )
+        url = url.replace('/99/', '/{z}/').replace(
+            '/98/', '/{x}/').replace('/97.', '/{y}.')
+        metadata['tiles'] = [url]
+        _add_metadata(connection, 'description', str(map_db), metadata)
+        _add_metadata(connection, 'version', str(map_db), metadata)
+        _add_metadata(connection, 'attribution', str(map_db), metadata)
+        _add_metadata(connection, 'template', str(map_db), metadata)
+        _add_metadata(connection, 'legend', str(map_db), metadata)
+        _add_metadata(connection, 'schema', str(map_db), metadata)
+        _add_metadata(connection, 'minzoom', str(map_db), metadata)
+        _add_metadata(connection, 'maxzoom', str(map_db), metadata)
+        _add_metadata(connection, 'bounds', str(map_db), metadata)
+        _add_metadata(connection, 'center', str(map_db), metadata)
+        _add_metadata(connection, 'data', str(map_db), metadata)
+        _add_metadata(connection, 'grids', str(map_db), metadata)
+
+        if 'minzoom' not in metadata or 'maxzoom' not in metadata:
+            cursor = connection.cursor()
+            try:
+                cursor.execute(
+                    ('SELECT MIN(zoom_level), MAX(zoom_level) '
+                     'FROM tiles')
+                )
+                zoomlevels = cursor.fetchall()
+                if 'minzoom' not in metadata:
+                    metadata['minzoom'] = zoomlevels[0][0]
+                if 'maxzoom' not in metadata:
+                    metadata['maxzoom'] = zoomlevels[0][1]
+            except Expcetion as e:
+                flask.current_app.logger.error(
+                    ('Could not get min and max '
+                     'zoomlevel from map {}').format(str(map_db)))
+        result.append(metadata)
+
+        connection.close()
+    return result
+
+
+def maps_tile_get(mapname, zoom, x_tile, y_tile):
+    map_dir = _get_map_directory()
+    map_db = map_dir.joinpath('{}.mbtiles'.format(secure_filename(mapname)))
+    if not map_db.is_file():
+        raise GnuboatNotFound(detail='Map {} does not exist'.format(mapname))
+
+    try:
+        connection = sqlite3.connect(str(map_db.resolve()))
+    except Exception as e:
+        raise GnuboatInternalServerError(
+            detail=('Could not open map {} '
+                    'to serve tiles').format(mapname))
+    cursor = connection.cursor()
+    try:
+        cursor.execute(
+            ('SELECT tile_data FROM tiles WHERE '
+             'zoom_level=? AND tile_column=? and tile_row=?'),
+            (zoom, x_tile, y_tile))
+    except:
+        connection.close()
+        raise GnuboatInternalServerError(
+            detail=('Could not get tile '
+                    '{z}/{x}/{y} of map {} to serve tiles').format(
+                        zoom, x_tile, y_tile, mapname))
+    results = cursor.fetchall()
+    if len(results) != 1:
+        raise GnuboatNotFound(detail='Could not find tile {}/{}/{}/{}'.format(
+            mapname, zoom, x_tile, y_tile))
+    connection.close()
+
+    response = flask.send_file(
+        io.BytesIO(results[0][0]),
+        mimetype='image/png',
+        as_attachment=True,
+        attachment_filename='{}.png'.format(y_tile)
+    )
+    response.direct_passthrough = False
+    return response
+
+
+def maps_upload(body=None):
+    if body is None:
+        raise GnuboatBadRequest(detail='No map given')
+
+    database_content = base64.b64decode(body)
+    file_handle, path = tempfile.mkstemp(suffix='.mbtiles')
+    with open(file_handle, 'wb') as f:
+        f.write(database_content)
+
+    try:
+        connection = sqlite3.connect(path)
+        name = _get_metadata(connection, 'name', path)
+        connection.close()
+    except Exception as e:
+        raise GnuboatInternalServerError(
+            detail='Could not create temporary database: {}'.format(repr(e))
+        )
+    finally:
+        os.remove(path)
+
+    if name is None:
+        raise GnuboatBadRequest(
+            detail=('No name for map in mbtile-file set. '
+                    'Please add a name to the mbtiles metadata table '
+                    '(it\'s a SQLite database)'))
+
+    map_path = _get_map_directory().joinpath(
+        '{}.mbtiles'.format(_map_name_to_hash(name)))
+    if map_path.is_file():
+        raise GnuboatBadRequest(detail='Map with this name already exists')
+    with open(map_path, 'wb') as file_handle:
+        file_handle.write(database_content)
+    return maps_get()
+
+
+def _map_name_to_hash(name):
+    return shake_256(name.encode('utf-8')).hexdigest(32)
+
+
+def _add_metadata(connection, name, db, result_dict):
+    value = _get_metadata(connection, name, db)
+    if value is not None:
+        if name == 'minzoom' or name == 'maxzoom':
+            value = int(value)
+        if name == 'bounds' or name == 'center':
+            value = [float(i) for i in value.split(',')]
+        if name == 'data' or name == 'grids':
+            flask.current_app.logger.error(
+                ('Please report a bug to implement '
+                 'map metadata extraction of type {} with example value {}')
+                .format(name, value))
+        result_dict[name] = value
+
+
+def _get_metadata(connection, name, db):
+    cursor = connection.cursor()
+    try:
+        cursor.execute('SELECT value FROM metadata WHERE name=?', (name,))
+    except Exception as e:
+        flask.current_app.logger.info(
+            '{} not found in map {} metadata'.format(name, db))
+        return None
+    results = cursor.fetchall()
+    if len(results) != 1:
+        flask.current_app.logger.info(
+            '{} not found in map {} metadata'.format(name, db))
+        return None
+    return results[0][0]
+
+
+def _get_map_directory():
+    if 'MAP_DIRECTORY' not in flask.current_app.config:
+        raise GnuboatInternalServerError(
+            detail='MAP_DIRECTORY not configured or not accessible'
+        )
+    return Path(flask.current_app.config['MAP_DIRECTORY'])
Index: src/gnuboat/deviceservice_impl/controllers/mapservice_controller.py
===================================================================
--- src/gnuboat/deviceservice_impl/controllers/mapservice_controller.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/deviceservice_impl/controllers/mapservice_controller.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,313 @@
+'''
+    Copyright (C) 2020 EngSaS - 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 connexion
+import flask
+from werkzeug.utils import secure_filename
+import socket
+from urllib.parse import urlparse
+from urllib3.exceptions import RequestError
+from enum import Enum
+import datetime
+import json
+import os
+
+from gnuboat.common.webservice.http_errors import (
+    GnuboatBadRequest, GnuboatUnauthorized,
+    GnuboatNotFound, GnuboatInternalServerError,
+    GnuboatPayloadToLarge, GnuboatGatewayTimeout,
+    GnuboatBadGateway
+)
+from gnuboat.deviceservice_impl.controllers.device_logs_controller import (
+    logdirectory_get
+)
+from gnuboat.mapservice_client.configuration import (
+    Configuration as MsConfiguration
+)
+from gnuboat.mapservice_client.api_client import ApiClient as MsApiClient
+from gnuboat.mapservice_client.api.waters_api import WatersApi as MsWatersApi
+from gnuboat.mapservice_client.api.devices_api import (
+    DevicesApi as MsDevicesApi
+)
+from gnuboat.mapservice_client.api.logs_api import LogsApi as MsLogsApi
+from gnuboat.mapservice_client.models.log_creation import (
+    LogCreation as MsLogCreation
+)
+from gnuboat.mapservice_client.exceptions import ApiException as MsApiException
+
+
+class MapserviceStatus(Enum):
+    NO_API_KEY = 0
+    NO_DEVICE = 1
+    DEVICE_NOT_FOUND = 2
+    NO_CONNECTION = 4
+    OK = 7
+
+
+def mapservice_status():
+    mapservice_status = _mapservice_status()
+    flask.mapservice_status = mapservice_status
+
+    if mapservice_status == MapserviceStatus.NO_CONNECTION:
+        return mapservice_status.name, 504
+    return mapservice_status.name
+
+
+def waters_get(
+        name=None,
+        order_by=None,
+        offset=None,
+        limit=None):
+    if _mapservice_status() != MapserviceStatus.OK:
+        raise GnuboatBadRequest(
+            detail='Mapservice not available. See remote status for help')
+
+    configuration = _mapservice_configuration()
+    with MsApiClient(configuration) as api_client:
+        try:
+            waters = MsWatersApi(api_client).waters_get(
+                name=name, order_by=order_by, offset=offset, limit=limit
+            )
+        except Exception as e:
+            _handle_api_exception(e)
+
+        results = []
+        for water in waters:
+            gauges = []
+            if water.gauges is not None:
+                for gauge in water.gauges:
+                    gauges.append({
+                        'gaugeId': gauge.gauge_id,
+                        'location': gauge.location,
+                        'name': gauge.name,
+                        'referenceWaterLevelGaugeHeight':
+                            gauge.reference_water_level_gauge_height,
+                    })
+            results.append({
+                'waterId': water.water_id,
+                'name': water.name,
+                'gauges': gauges,
+            })
+        return results
+
+
+def log_create(log_creation=None):
+    if _mapservice_status() != MapserviceStatus.OK:
+        raise GnuboatBadRequest(
+            detail='Mapservice not available. See remote status for help')
+
+    log_dir = logdirectory_get()
+    logfile = secure_filename(log_creation.logfile)
+    logfile_path = log_dir.joinpath(logfile)
+    if not logfile_path.is_file():
+        raise GnuboatNotFound(detail='Logfile {} not found'.format(logfile))
+
+    # building log_creation for the mapservice
+    log_creation_mapservice = MsLogCreation(
+        water=log_creation.water,
+        device=_mapservice_device_get().device_id,
+        gauge=log_creation.gauge,
+        gauge_height=log_creation.gauge_height,
+        comment=log_creation.comment,
+    )
+
+    configuration = _mapservice_configuration()
+    with MsApiClient(configuration) as api_client:
+        # create log
+        try:
+            log_metadata = MsLogsApi(api_client).logs_log_create(
+                log_creation=log_creation_mapservice
+            )
+        except Exception as e:
+            _handle_api_exception(e)
+
+        # read log file content from local storage
+        with open(logfile_path, 'rb') as logfilehandle:
+            file_content = logfilehandle.read()
+        # upload log content to newly created log from above
+        try:
+            log_metadata = MsLogsApi(api_client).logs_log_upload(
+                log_id=log_metadata.log_id, body=file_content
+            )
+        except Exception as e:
+            _handle_api_exception(e)
+
+        if log_creation.delete:
+            os.remove(logfile_path)
+
+
+def _mapservice_url():
+    if 'MAPSERVICE' in flask.current_app.config:
+        url = flask.current_app.config['MAPSERVICE']
+        if url.endswith('/'):
+            return url[:-1]
+        return url
+    configuration = MsConfiguration()
+    if configuration.host:
+        return configuration.host
+    raise GnuboatInternalServerError(
+        detail=('No host for mapservice configured '
+                '(See MAPSERVICE config option)'))
+
+
+def _mapservice_api_key():
+    if 'MAPSERVICE_API_KEY' not in flask.current_app.config:
+        raise GnuboatInternalServerError(
+            detail='MAPSERVICE_API_KEY not configured'
+        )
+    return flask.current_app.config['MAPSERVICE_API_KEY']
+
+
+def _mapservice_device():
+    if 'MAPSERVICE_DEVICE' not in flask.current_app.config:
+        raise GnuboatInternalServerError(
+            detail='MAPSERVICE_DEVICE not configured'
+        )
+    return flask.current_app.config['MAPSERVICE_DEVICE']
+
+
+def _mapservice_device_get():
+    if hasattr(flask, 'mapservice_device') and flask.mapservice_device:
+        return flask.mapservice_device
+
+    device_id = _mapservice_device()
+    configuration = _mapservice_configuration()
+    with MsApiClient(configuration) as api_client:
+        try:
+            device = MsDevicesApi(api_client).devices_get_by_id(device_id)
+        except Exception as e:
+            flask.mapservice_device = False
+            body = json.loads(e.body)
+            if 'detail' in body:
+                flask.current_app.logger.error(
+                    'Failed to get device: {}'.format(body['detail']))
+            return False
+
+        flask.mapservice_device = device
+        return device
+
+
+def _mapservice_configuration():
+    configuration = MsConfiguration()
+    configuration.host = _mapservice_url()
+    configuration.api_key['X-API-KEY'] = _mapservice_api_key()
+    return configuration
+
+
+def _mapservice_status():
+    try:
+        mapservice_api_key = _mapservice_api_key()
+    except:
+        return MapserviceStatus.NO_API_KEY
+
+    try:
+        mapservice_device = _mapservice_device()
+    except:
+        return MapserviceStatus.NO_DEVICE
+
+    if hasattr(flask, 'mapservice_device') and not flask.mapservice_device:
+        return MapserviceStatus.DEVICE_NOT_FOUND
+
+    # prevent to many status polls
+    if hasattr(flask, 'mapservice_check') and \
+            hasattr(flask, 'mapservice_status'):
+        if (datetime.datetime.now() - flask.mapservice_check).total_seconds() \
+                < 60:
+            return flask.mapservice_status
+
+    mapservice_url = _mapservice_url()
+
+    fragments = urlparse(mapservice_url)
+    if fragments.hostname is None:
+        raise GnuboatInternalServerError(
+            detail='No hostname for mapservice set')
+    if fragments.port is None:
+        if fragments.scheme == 'http':
+            fragments.port = 80
+        elif fragments.scheme == 'https':
+            fragments.port = 443
+        else:
+            raise GnuboatInternalServerError(
+                detail='Could not determine port for mapservice')
+
+    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+    s.settimeout(5)
+    try:
+        s.connect((fragments.hostname, int(fragments.port)))
+        s.shutdown(socket.SHUT_RDWR)
+    except:
+        flask.mapservice_status = MapserviceStatus.NO_CONNECTION
+        return MapserviceStatus.NO_CONNECTION
+    finally:
+        flask.mapservice_check = datetime.datetime.now()
+        s.close()
+
+    if hasattr(flask, 'mapservice_device') and flask.mapservice_device:
+        flask.mapservice_status = MapserviceStatus.OK
+        return MapserviceStatus.OK
+
+    device = _mapservice_device_get()
+    if not device:
+        flask.mapservice_status = MapserviceStatus.DEVICE_NOT_FOUND
+        return MapserviceStatus.DEVICE_NOT_FOUND
+    flask.mapservice_status = MapserviceStatus.OK
+    return MapserviceStatus.OK
+
+
+def _handle_api_exception(exception):
+    if isinstance(exception, MsApiException):
+        if exception.body is None:
+            raise GnuboatInternalServerError(
+                detail='Unkown error occured: {}'.format(repr(exception)))
+
+        response_body = json.loads(exception.body)
+        if 'status' not in response_body:
+            raise GnuboatInternalServerError(
+                detail='Unkown error occured: {}'.format(repr(exception)))
+        status = response_body['status']
+        if 'detail' in response_body:
+            detail = response_body['detail']
+        else:
+            detail = ''
+    elif isinstance(exception, RequestError):
+        status = '502'
+        detail = 'Could not connect to server {}:{}/{}'.format(
+            exception.pool.host, exception.pool.port, exception.url
+        )
+    else:
+        status = 502
+        detail = 'An unexpected error occured: {}'.format(repr(exception))
+
+    if status == 400:
+        raise GnuboatBadRequest(detail=detail)
+    if status == 401:
+        raise GnuboatUnauthorized(detail=detail)
+    if status == 404:
+        raise GnuboatNotFound(detail=detail)
+    if status == 413:
+        raise GnuboatPayloadToLarge(detail=detail)
+    if status == 500:
+        raise GnuboatInternalServerError(detail=detail)
+    if status == 502:
+        raise GnuboatBadGateway(detail=detail)
+    if status == 504:
+        raise GnuboatGatewayTimeout(detail=detail)
+    else:
+        raise GnuboatInternalServerError(
+            detail='Unknown error code {} with message {}'.format(
+                status, detail
+            )
+        )
Index: src/gnuboat/deviceservice_impl/demo/DemoLog.py
===================================================================
--- src/gnuboat/deviceservice_impl/demo/DemoLog.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ 	(revision )
@@ -1,78 +1,0 @@
-'''
-    Copyright (C) 2020 EngSaS - 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 datetime
-import random
-import flask
-from pathlib import Path
-import shutil
-
-import gnuboat.common.datahandler.loghandler as loghandler
-import gnuboat.common.datahandler.logdataset as logdataset
-
-logperiod = 2
-latitude_min = 47.57
-latitude_max = 47.66
-longitude_min = 10.70
-longitude_max = 10.77
-
-
-def create_logs(application):
-    if 'LOG_DIRECTORY' not in application.config:
-        print('LOG_DIRECTORY not set --> Skipping demo')
-        return
-    logdir = Path(application.config['LOG_DIRECTORY'])
-    if logdir.is_dir():
-        if len(list(logdir.glob('*.log'))) > 1:
-            return
-        shutil.rmtree(logdir)
-    logdir.mkdir(parents=True)
-
-    duration = 24 * 60 * 60
-    end_time = datetime.datetime.now()
-    start_time = end_time - datetime.timedelta(seconds=duration)
-
-    log = loghandler.LogHandler(logdir.resolve())
-    current_time = start_time
-    while (current_time <= end_time):
-        latitude = random.uniform(latitude_min, latitude_max)
-        longitude = random.uniform(longitude_min, longitude_max)
-        speedThroughWater = random.randint(0, 6)
-        speedOverGround = random.randint(-3, 8)
-        courseOverGround = random.randint(0, 360)
-        waterDepth = random.randint(0, 20)
-        waterTemperature = random.randint(2, 25)
-
-        dataset = logdataset.LogDataset(
-            datetime=current_time,
-            gps_status='A',
-            latitude=latitude,
-            latitude_direction='N',
-            longitude=longitude,
-            longitude_direction='E',
-            speed_over_ground=speedOverGround,
-            course_over_ground=courseOverGround,
-            water_depth=waterDepth,
-            water_temperature=waterTemperature
-        )
-        log.gnuboat_write(3, current_time, dataset, True, False, False)
-        current_time += datetime.timedelta(seconds=logperiod)
-
-    log.gnuboat_close()
-    for logfile in logdir.glob('*.log'):
-        shutil.copy(logfile, logdir.joinpath('demo-2.log'))
-        break
Index: src/gnuboat/deviceservice_impl/demo/DemoMaps.py
===================================================================
--- src/gnuboat/deviceservice_impl/demo/DemoMaps.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ 	(revision )
@@ -1,47 +1,0 @@
-'''
-    Copyright (C) 2020 EngSaS - 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 datetime
-import random
-import flask
-from pathlib import Path
-import shutil
-import os
-
-from gnuboat.deviceservice_impl.controllers.DeviceMapsController import (
-    _map_name_to_hash
-)
-
-
-def create_maps(application):
-    if 'MAP_DIRECTORY' not in application.config:
-        print('MAP_DIRECTORY not set --> Skipping demo')
-        return
-    mapdir = Path(application.config['MAP_DIRECTORY'])
-    if mapdir.is_dir():
-        if len(list(mapdir.glob('*.mbtiles'))) > 0:
-            return
-        shutil.rmtree(mapdir)
-    mapdir.mkdir(parents=True)
-
-    shutil.copy(
-        os.path.join(
-            os.path.dirname(__file__),
-            '../../samples/maps/000-forggensee.mbtiles'
-        ),
-        mapdir.joinpath('{}.mbtiles'.format(_map_name_to_hash('Forggensee')))
-    )
Index: src/gnuboat/deviceservice_impl/demo/DemoRrd.py
===================================================================
--- src/gnuboat/deviceservice_impl/demo/DemoRrd.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ 	(revision )
@@ -1,91 +1,0 @@
-'''
-    Copyright (C) 2020 EngSaS - 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 time
-import random
-import flask
-import os
-import datetime
-import rrdtool
-
-import gnuboat.common.datahandler.rrdhandler as rrdhandler
-
-logperiod = 2
-latitude_min = 47.57
-latitude_max = 47.66
-longitude_min = 10.70
-longitude_max = 10.77
-
-
-def rrd_create_demo(application):
-    if 'DEVICE_DATABASE' not in application.config:
-        print('DEVICE_DATABASE not set --> Skipping demo')
-        return
-
-    duration = 24 * 60 * 60
-    timestamp = int(time.time())
-    start_time = timestamp - duration - logperiod
-
-    rrdfile = application.config['DEVICE_DATABASE']
-    if os.path.isfile(rrdfile):
-        os.remove(rrdfile)
-    rrdhandler.rrd_create_database(rrdfile, logperiod, str(start_time))
-    for current_time in range(timestamp - duration, timestamp, logperiod):
-        latitude = random.uniform(latitude_min, latitude_max)
-        longitude = random.uniform(longitude_min, longitude_max)
-        speedThroughWater = random.randint(0, 6)
-        speedOverGround = random.randint(-3, 8)
-        courseOverGround = random.randint(0, 360)
-        waterDepth = random.randint(0, 20)
-        waterTemperature = random.randint(2, 25)
-        gpsFix = 3
-        # update rrd database for the webservice
-        rrdhandler.rrd_update(
-            rrdfile, '{}:{}:{}:{}:{}:{}:{}:{}:{}'.format(
-                current_time, latitude, longitude, speedThroughWater,
-                speedOverGround, courseOverGround, waterDepth,
-                waterTemperature, gpsFix
-            )
-        )
-
-    @application.before_request
-    def add_measurement():
-        if 'DEVICE_DATABASE' not in flask.current_app.config:
-            return
-        result = rrdtool.lastupdate(
-            flask.current_app.config['DEVICE_DATABASE'])
-        if ((datetime.datetime.now() - result['date']).total_seconds() <
-                logperiod):
-            # last update is not longer ago than logperiod. Skip new update
-            return
-
-        latitude = random.uniform(latitude_min, latitude_max)
-        longitude = random.uniform(longitude_min, longitude_max)
-        speedThroughWater = random.randint(0, 10)
-        speedOverGround = random.randint(-2, 15)
-        courseOverGround = random.randint(0, 360)
-        waterDepth = random.randint(0, 20)
-        waterTemperature = random.randint(2, 25)
-        gpsFix = 3
-
-        rrdhandler.rrd_update(
-            flask.current_app.config['DEVICE_DATABASE'],
-            '{}:{}:{}:{}:{}:{}:{}:{}:{}'.format(
-                int(time.time()), latitude, longitude, speedThroughWater,
-                speedOverGround, courseOverGround, waterDepth,
-                waterTemperature, gpsFix)
-        )
Index: src/gnuboat/deviceservice_impl/demo/DeviceserviceEntry.py
===================================================================
--- src/gnuboat/deviceservice_impl/demo/DeviceserviceEntry.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ 	(revision )
@@ -1,52 +1,0 @@
-# -*- coding: utf-8 -*-
-'''
-    Copyright (C) 2020 EngSaS - 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 re
-import sys
-from pkg_resources import load_entry_point
-from gunicorn.app.wsgiapp import run
-import os
-
-from gnuboat.deviceservice_impl import (
-    app, application, setup_app, config_object
-)
-
-
-def gunicorn_app():
-    template_folder = os.path.join(os.path.dirname(__file__), 'templates')
-    setup_app(
-        'GNUBoat Device API', config_object, template_folder=template_folder
-    )
-    return app
-
-
-def main():
-    # Add need configuration options
-    # sys.argv.append('--workers=2')
-    if not any('bind' in x for x in sys.argv):
-        sys.argv.append('--bind=localhost:8090')
-    sys.argv.append(
-        'gnuboat.deviceservice_impl.demo.DeviceserviceEntry:gunicorn_app()')
-
-    # Copied from /usr/bin/gunicorn
-    sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
-    sys.exit(run())
-
-
-if __name__ == '__main__':
-    main
Index: src/gnuboat/deviceservice_impl/demo/__init__.py
===================================================================
--- src/gnuboat/deviceservice_impl/demo/__init__.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ src/gnuboat/deviceservice_impl/demo/__init__.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -17,6 +17,6 @@
 
 from gnuboat.deviceservice_impl.demo import (
-    DemoLog as demolog, DemoRrd as demorrd,
-    DemoMaps as demomaps
+    demo_log as demolog, demo_rrd as demorrd,
+    demo_maps as demomaps
 )
 
Index: src/gnuboat/deviceservice_impl/demo/demo_log.py
===================================================================
--- src/gnuboat/deviceservice_impl/demo/demo_log.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/deviceservice_impl/demo/demo_log.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,78 @@
+'''
+    Copyright (C) 2020 EngSaS - 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 datetime
+import random
+import flask
+from pathlib import Path
+import shutil
+
+import gnuboat.common.datahandler.log_handler as loghandler
+import gnuboat.common.datahandler.log_dataset as logdataset
+
+logperiod = 2
+latitude_min = 47.57
+latitude_max = 47.66
+longitude_min = 10.70
+longitude_max = 10.77
+
+
+def create_logs(application):
+    if 'LOG_DIRECTORY' not in application.config:
+        print('LOG_DIRECTORY not set --> Skipping demo')
+        return
+    logdir = Path(application.config['LOG_DIRECTORY'])
+    if logdir.is_dir():
+        if len(list(logdir.glob('*.log'))) > 1:
+            return
+        shutil.rmtree(logdir)
+    logdir.mkdir(parents=True)
+
+    duration = 24 * 60 * 60
+    end_time = datetime.datetime.now()
+    start_time = end_time - datetime.timedelta(seconds=duration)
+
+    log = loghandler.LogHandler(logdir.resolve())
+    current_time = start_time
+    while (current_time <= end_time):
+        latitude = random.uniform(latitude_min, latitude_max)
+        longitude = random.uniform(longitude_min, longitude_max)
+        speedThroughWater = random.randint(0, 6)
+        speedOverGround = random.randint(-3, 8)
+        courseOverGround = random.randint(0, 360)
+        waterDepth = random.randint(0, 20)
+        waterTemperature = random.randint(2, 25)
+
+        dataset = logdataset.LogDataset(
+            datetime=current_time,
+            gps_status='A',
+            latitude=latitude,
+            latitude_direction='N',
+            longitude=longitude,
+            longitude_direction='E',
+            speed_over_ground=speedOverGround,
+            course_over_ground=courseOverGround,
+            water_depth=waterDepth,
+            water_temperature=waterTemperature
+        )
+        log.gnuboat_write(3, current_time, dataset, True, False, False)
+        current_time += datetime.timedelta(seconds=logperiod)
+
+    log.gnuboat_close()
+    for logfile in logdir.glob('*.log'):
+        shutil.copy(logfile, logdir.joinpath('demo-2.log'))
+        break
Index: src/gnuboat/deviceservice_impl/demo/demo_maps.py
===================================================================
--- src/gnuboat/deviceservice_impl/demo/demo_maps.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/deviceservice_impl/demo/demo_maps.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,47 @@
+'''
+    Copyright (C) 2020 EngSaS - 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 datetime
+import random
+import flask
+from pathlib import Path
+import shutil
+import os
+
+from gnuboat.deviceservice_impl.controllers.device_maps_controller import (
+    _map_name_to_hash
+)
+
+
+def create_maps(application):
+    if 'MAP_DIRECTORY' not in application.config:
+        print('MAP_DIRECTORY not set --> Skipping demo')
+        return
+    mapdir = Path(application.config['MAP_DIRECTORY'])
+    if mapdir.is_dir():
+        if len(list(mapdir.glob('*.mbtiles'))) > 0:
+            return
+        shutil.rmtree(mapdir)
+    mapdir.mkdir(parents=True)
+
+    shutil.copy(
+        os.path.join(
+            os.path.dirname(__file__),
+            '../../samples/maps/000-forggensee.mbtiles'
+        ),
+        mapdir.joinpath('{}.mbtiles'.format(_map_name_to_hash('Forggensee')))
+    )
Index: src/gnuboat/deviceservice_impl/demo/demo_rrd.py
===================================================================
--- src/gnuboat/deviceservice_impl/demo/demo_rrd.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/deviceservice_impl/demo/demo_rrd.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,91 @@
+'''
+    Copyright (C) 2020 EngSaS - 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 time
+import random
+import flask
+import os
+import datetime
+import rrdtool
+
+import gnuboat.common.datahandler.rrd_handler as rrdhandler
+
+logperiod = 2
+latitude_min = 47.57
+latitude_max = 47.66
+longitude_min = 10.70
+longitude_max = 10.77
+
+
+def rrd_create_demo(application):
+    if 'DEVICE_DATABASE' not in application.config:
+        print('DEVICE_DATABASE not set --> Skipping demo')
+        return
+
+    duration = 24 * 60 * 60
+    timestamp = int(time.time())
+    start_time = timestamp - duration - logperiod
+
+    rrdfile = application.config['DEVICE_DATABASE']
+    if os.path.isfile(rrdfile):
+        os.remove(rrdfile)
+    rrdhandler.rrd_create_database(rrdfile, logperiod, str(start_time))
+    for current_time in range(timestamp - duration, timestamp, logperiod):
+        latitude = random.uniform(latitude_min, latitude_max)
+        longitude = random.uniform(longitude_min, longitude_max)
+        speedThroughWater = random.randint(0, 6)
+        speedOverGround = random.randint(-3, 8)
+        courseOverGround = random.randint(0, 360)
+        waterDepth = random.randint(0, 20)
+        waterTemperature = random.randint(2, 25)
+        gpsFix = 3
+        # update rrd database for the webservice
+        rrdhandler.rrd_update(
+            rrdfile, '{}:{}:{}:{}:{}:{}:{}:{}:{}'.format(
+                current_time, latitude, longitude, speedThroughWater,
+                speedOverGround, courseOverGround, waterDepth,
+                waterTemperature, gpsFix
+            )
+        )
+
+    @application.before_request
+    def add_measurement():
+        if 'DEVICE_DATABASE' not in flask.current_app.config:
+            return
+        result = rrdtool.lastupdate(
+            flask.current_app.config['DEVICE_DATABASE'])
+        if ((datetime.datetime.now() - result['date']).total_seconds() <
+                logperiod):
+            # last update is not longer ago than logperiod. Skip new update
+            return
+
+        latitude = random.uniform(latitude_min, latitude_max)
+        longitude = random.uniform(longitude_min, longitude_max)
+        speedThroughWater = random.randint(0, 10)
+        speedOverGround = random.randint(-2, 15)
+        courseOverGround = random.randint(0, 360)
+        waterDepth = random.randint(0, 20)
+        waterTemperature = random.randint(2, 25)
+        gpsFix = 3
+
+        rrdhandler.rrd_update(
+            flask.current_app.config['DEVICE_DATABASE'],
+            '{}:{}:{}:{}:{}:{}:{}:{}:{}'.format(
+                int(time.time()), latitude, longitude, speedThroughWater,
+                speedOverGround, courseOverGround, waterDepth,
+                waterTemperature, gpsFix)
+        )
Index: src/gnuboat/deviceservice_impl/demo/service_entry.py
===================================================================
--- src/gnuboat/deviceservice_impl/demo/service_entry.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/deviceservice_impl/demo/service_entry.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,52 @@
+# -*- coding: utf-8 -*-
+'''
+    Copyright (C) 2020 EngSaS - 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 re
+import sys
+from pkg_resources import load_entry_point
+from gunicorn.app.wsgiapp import run
+import os
+
+from gnuboat.deviceservice_impl import (
+    app, application, setup_app, config_object
+)
+
+
+def gunicorn_app():
+    template_folder = os.path.join(os.path.dirname(__file__), 'templates')
+    setup_app(
+        'GNUBoat Device API', config_object, template_folder=template_folder
+    )
+    return app
+
+
+def main():
+    # Add need configuration options
+    # sys.argv.append('--workers=2')
+    if not any('bind' in x for x in sys.argv):
+        sys.argv.append('--bind=localhost:8090')
+    sys.argv.append(
+        'gnuboat.deviceservice_impl.demo.service_entry:gunicorn_app()')
+
+    # Copied from /usr/bin/gunicorn
+    sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
+    sys.exit(run())
+
+
+if __name__ == '__main__':
+    main
Index: src/gnuboat/deviceservice_impl/static/index.html
===================================================================
--- src/gnuboat/deviceservice_impl/static/index.html	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ src/gnuboat/deviceservice_impl/static/index.html	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -21,5 +21,5 @@
 		<meta name="viewport" content="width=device-width, initial-scale=1.0">
 		<link rel="icon" type="image/png" href="/client/common/icon/gnuboat-256-256-transparent.png"/>
-		<title>GNUBoat Web Application</title>
+		<title>GNUBoat Device Web Application</title>
 		
 		<link rel="stylesheet" href="/client/common/lib/css/pure/pure-min.css" type="text/css"/>
Index: src/gnuboat/deviceservice_impl/tests/__init__.py
===================================================================
--- src/gnuboat/deviceservice_impl/tests/__init__.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ src/gnuboat/deviceservice_impl/tests/__init__.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -17,8 +17,9 @@
 
 import logging
+import connexion
+from flask_cors import CORS
 import flask
 from flask import request_started, request
-import connexion
-from flask_cors import CORS
+from werkzeug.utils import import_string
 import rrdtool
 import os
@@ -29,20 +30,18 @@
 import datetime
 import shutil
-import subprocess
-import socket
-from urllib.parse import urlparse
-from werkzeug.utils import import_string
 
 from gnuboat.common.datahandler import (
-    rrdhandler, loghandler, logdataset,
+    rrd_handler as rrdhandler,
+    log_handler as loghandler,
+    log_dataset as logdataset,
 )
-from gnuboat.common.webservice.Config import (
+from gnuboat.common.webservice.config import (
     config_get
 )
 
-from gnuboat.deviceservice_impl.controllers.DeviceMapsController import (
+from gnuboat.deviceservice_impl.controllers.device_maps_controller import (
     _map_name_to_hash
 )
-from gnuboat.deviceservice.encoder import JSONEncoder
+from gnuboat.deviceservice_impl import setup_app
 
 logperiod = 2
@@ -58,19 +57,11 @@
 def create_app(testcase):
     logging.getLogger('connexion.operation').setLevel('ERROR')
-    app = connexion.App(
-        __name__,
-        specification_dir='../../deviceservice/openapi/'
-    )
+    app = connexion.App(__name__,
+                        specification_dir='../../deviceservice/openapi/')
     application = app.app
     CORS(application)
-    application.json_encoder = JSONEncoder
-    app.add_api(
-        'openapi.yaml',
-        validate_responses=True,
-        strict_validation=True,
-    )
-
-    application.config.from_object(
-        'gnuboat.deviceservice_impl.Config.TestingConfig')
+    setup_app(__name__,
+              import_string('gnuboat.deviceservice_impl.config.TestingConfig'),
+              connexion_app=app)
     application.app_context().push()
 
@@ -79,27 +70,15 @@
     _create_maps(testcase, application)
 
-    _mapservice_start(testcase, application)
-
-    return application
+    return app
 
 
-def setUp(testcase):
+def setup(app, testcase):
     pass
 
 
-def tearDown(testcase):
+def teardown(app, testcase):
     os.remove(testcase.rrdfile)
     shutil.rmtree(testcase.logdir)
     shutil.rmtree(testcase.mapdir)
-    if testcase.mapservice_process is not None:
-        testcase.mapservice_process.terminate()
-        (stdout_data, stderr_data) = \
-            testcase.mapservice_process.communicate(timeout=10)
-        if stdout_data:
-            stdout_data = stdout_data.decode('utf-8')
-            print('MAPSERVICE STDOUT: {}'.format(stdout_data))
-        if stderr_data:
-            stderr_data = stderr_data.decode('utf-8')
-            print('MAPSERVICE STDERR: {}'.format(stderr_data))
 
 
@@ -217,66 +196,2 @@
         mapdir.joinpath('{}.mbtiles'.format(_map_name_to_hash('Forggensee')))
     )
-
-
-def _mapservice_start(testcase, application):
-    if 'TestMapserviceController' not in testcase.id():
-        testcase.mapservice_process = None
-    else:
-        print('MAPSERVICE Starting')
-        mapservice_url = config_get(application.config, 'MAPSERVICE', None)
-        if mapservice_url is None:
-            raise LookupError('MAPSERVICE not configured')
-        fragments = urlparse(mapservice_url)
-        if fragments.hostname is None:
-            raise LookupError('MAPSERVICE host not found')
-        if fragments.port is None:
-            raise LookupError('MAPSERVICE port not found')
-
-        mapservice_config = 'Testing'
-        mapservice_config_object = import_string(
-            'gnuboat.mapservice_impl.Config.{}Config'.format(mapservice_config)
-        )
-        database_uri = config_get(mapservice_config_object,
-                                  'SQLALCHEMY_DATABASE_URI', None)
-        if database_uri is None:
-            raise LookupError(
-                'SQLALCHEMY_DATABASE_URI not in MAPSERVICE Testing config')
-        database_uri = database_uri.replace('sqlite:///', '')
-        if os.path.isfile(database_uri):
-            os.remove(database_uri)
-
-        mapservice_env = dict(os.environ)
-        mapservice_env['FLASK_ENV'] = mapservice_config
-        # the timeout is needed, because of the spatiallite table creation,
-        # which is pretty slow
-        testcase.mapservice_process = subprocess.Popen(
-            [
-                'gnuboat-dev-mapservice',
-                '--bind={}:{}'.format(fragments.hostname, fragments.port),
-                '--log-level=debug'
-            ],
-            env=mapservice_env, shell=True,
-            stdout=subprocess.PIPE, stderr=subprocess.PIPE
-        )
-        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-        # we need to give mapservice a chance to start before calling
-        # connect_ex
-        time.sleep(2)
-        s.settimeout(10)
-        if s.connect_ex((fragments.hostname, int(fragments.port))) == 0:
-            print('MAPSERVICE running at {}:{}'.format(
-                fragments.hostname, fragments.port))
-            s.shutdown(socket.SHUT_RDWR)
-        else:
-            print('MAPSERVICE Failed to start at {}:{}'.format(
-                fragments.hostname, fragments.port))
-            testcase.mapservice_process.terminate()
-            (stdout_data, stderr_data) = \
-                testcase.mapservice_process.communicate(timeout=10)
-            if stdout_data:
-                stdout_data = stdout_data.decode('utf-8')
-                print('MAPSERVICE STDOUT: {}'.format(stdout_data))
-            if stderr_data:
-                stderr_data = stderr_data.decode('utf-8')
-                print('MAPSERVICE STDERR: {}'.format(stderr_data))
-            testcase.mapservice_process = None
Index: src/gnuboat/deviceservice_impl/tests/conftest.py
===================================================================
--- src/gnuboat/deviceservice_impl/tests/conftest.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/deviceservice_impl/tests/conftest.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,117 @@
+'''
+    Copyright (C) 2020 EngSaS - 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 pytest
+import subprocess
+import socket
+from urllib.parse import urlparse
+from werkzeug.utils import import_string
+import os
+import time
+
+from gnuboat.deviceservice_impl.tests import create_app, setup, teardown
+from gnuboat.common.webservice.config import (
+    config_get
+)
+
+
+class TestCaseDummy:
+    pass
+
+
+@pytest.fixture(scope="module")
+def app():
+    testcase = TestCaseDummy()
+    connexion_app = create_app(testcase)
+    app = connexion_app.app
+    # LIVESERVER_PORT=8943
+    setup(app, testcase)
+    yield app
+    teardown(app, testcase)
+    del app
+    del connexion_app
+
+
+@pytest.fixture(scope="module")
+def mapservice(app):
+    print('MAPSERVICE Starting')
+    mapservice_url = config_get(app.config, 'MAPSERVICE', None)
+    if mapservice_url is None:
+        raise LookupError('MAPSERVICE not configured')
+    fragments = urlparse(mapservice_url)
+    if fragments.hostname is None:
+        raise LookupError('MAPSERVICE host not found')
+    if fragments.port is None:
+        raise LookupError('MAPSERVICE port not found')
+
+    mapservice_config = 'Testing'
+    mapservice_config_object = import_string(
+        'gnuboat.mapservice_impl.config.{}Config'.format(mapservice_config)
+    )
+    database_uri = config_get(mapservice_config_object,
+                              'SQLALCHEMY_DATABASE_URI', None)
+    if database_uri is None:
+        raise LookupError(
+            'SQLALCHEMY_DATABASE_URI not in MAPSERVICE Testing config')
+    database_uri = database_uri.replace('sqlite:///', '')
+    if os.path.isfile(database_uri):
+        os.remove(database_uri)
+
+    mapservice_env = dict(os.environ)
+    mapservice_env['FLASK_ENV'] = mapservice_config
+    # the timeout is needed, because of the spatiallite table creation,
+    # which is pretty slow
+    mapservice_process = subprocess.Popen(
+        [
+            'gnuboat-dev-mapservice',
+            '--bind={}:{}'.format(fragments.hostname, fragments.port),
+            '--log-level=debug'
+        ],
+        env=mapservice_env, shell=True,
+        stdout=subprocess.PIPE, stderr=subprocess.PIPE
+    )
+    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+    # we need to give mapservice a chance to start before calling
+    # connect_ex
+    time.sleep(2)
+    s.settimeout(10)
+    if s.connect_ex((fragments.hostname, int(fragments.port))) == 0:
+        print('MAPSERVICE running at {}:{}'.format(
+            fragments.hostname, fragments.port))
+        s.shutdown(socket.SHUT_RDWR)
+    else:
+        print('MAPSERVICE Failed to start at {}:{}'.format(
+            fragments.hostname, fragments.port))
+        mapservice_process.terminate()
+        (stdout_data, stderr_data) = \
+            mapservice_process.communicate(timeout=10)
+        if stdout_data:
+            stdout_data = stdout_data.decode('utf-8')
+            print('MAPSERVICE STDOUT: {}'.format(stdout_data))
+        if stderr_data:
+            stderr_data = stderr_data.decode('utf-8')
+            print('MAPSERVICE STDERR: {}'.format(stderr_data))
+        mapservice_process = None
+    yield True
+    mapservice_process.terminate()
+    (stdout_data, stderr_data) = \
+        mapservice_process.communicate(timeout=10)
+    if stdout_data:
+        stdout_data = stdout_data.decode('utf-8')
+        print('MAPSERVICE STDOUT: {}'.format(stdout_data))
+    if stderr_data:
+        stderr_data = stderr_data.decode('utf-8')
+        print('MAPSERVICE STDERR: {}'.format(stderr_data))
Index: src/gnuboat/deviceservice_impl/validator_workaround.py
===================================================================
--- src/gnuboat/deviceservice_impl/validator_workaround.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/deviceservice_impl/validator_workaround.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,60 @@
+"""Hacks needed to circumvent connexion validation
+
+There is a bug on the connexion library concerning content negotiation and
+response validation. See https://github.com/zalando/connexion/issues/860 and
+https://github.com/zalando/connexion/pull/760
+
+Until this issue is fixed, we need to find a way to avoid a false validation
+error when a requests sends an 'application/geo+json' accept header
+"""
+import functools
+import logging
+
+from connexion.decorators.response import ResponseValidator
+from connexion import problem
+from connexion.exceptions import (
+    NonConformingResponseBody, NonConformingResponseHeaders
+)
+from connexion.utils import has_coroutine
+
+logger = logging.getLogger(__name__)
+
+
+class ValidatorWorkaround(ResponseValidator):
+    def validate_response_with_request(
+        self, request, data, status_code, headers, url
+    ):
+        if request.headers.get('accept', '') == 'application/zip' or \
+                headers['Content-Type'] == 'application/zip':
+            logging.debug('Circumventing validation for application/zip')
+            return True
+        return self.validate_response(data, status_code, headers, url)
+
+    def __call__(self, function):
+        """
+            :type function: types.FunctionType
+            :rtype: types.FunctionType
+        """
+        def _wrapper(request, response):
+            connexion_response = \
+             self.operation.api.get_connexion_response(response, self.mimetype)
+            self.validate_response_with_request(
+                request, connexion_response.body,
+                connexion_response.status_code, connexion_response.headers,
+                request.url
+            )
+
+            return response
+
+        if has_coroutine(function):
+            from .coroutine_wrappers import get_response_validator_wrapper
+            wrapper = get_response_validator_wrapper(function, _wrapper)
+
+        else:  # pragma: 3 no cover
+
+            @functools.wraps(function)
+            def wrapper(request):
+                response = function(request)
+                return _wrapper(request, response)
+
+        return wrapper
Index: src/gnuboat/mapservice_impl/CeleryWorker.py
===================================================================
--- src/gnuboat/mapservice_impl/CeleryWorker.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ 	(revision )
@@ -1,70 +1,0 @@
-'''
-    Copyright (C) 2020 EngSaS - 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/>.
-'''
-from celery import Celery
-import flask
-from sqlalchemy import event
-
-from gnuboat.mapservice_impl import (
-    config_object, app, application, celery, setup_app
-)
-from gnuboat.mapservice_impl.database.Model import db, load_spatialite
-from gnuboat.mapservice_impl.tasks import tasks
-
-
-# see https://flask.palletsprojects.com/en/1.1.x/patterns/celery/
-def setup_celery(flask_app, celery_app):
-    celery_app.conf.update(flask_app.config)
-    TaskBase = celery_app.Task
-
-    class ContextTask(TaskBase):
-        abstract = True
-
-        def __call__(self, *args, **kwargs):
-            with flask_app.app_context():
-
-                @event.listens_for(db.engine, "connect")
-                def load_spatialite_extension(dbapi_conn, connection_record):
-                    load_spatialite(dbapi_conn, connection_record)
-
-                return TaskBase.__call__(self, *args, **kwargs)
-
-    celery_app.Task = ContextTask
-
-    with flask_app.app_context():
-        if 'TILES_LITTLE_ZOOM_SCHEDULE' not in flask.current_app.config:
-            flask.current_app.logger.error(
-                'TILES_LITTLE_ZOOM_SCHEDULE not configured'
-            )
-            raise ImportError('TILES_LITTLE_ZOOM_SCHEDULE not configured')
-        tiles_little_zoom_schedule = flask.current_app.config[
-            'TILES_LITTLE_ZOOM_SCHEDULE']
-
-        celery_app.conf.beat_schedule = {
-            'add-log_little_zoom_slice': {
-                'task':
-                    ('gnuboat.mapservice_impl.tasks.'
-                     'tasks.log_little_zoom_slice'),
-                'schedule':
-                    tiles_little_zoom_schedule
-            },
-        }
-
-    return celery_app
-
-
-setup_app('GNUBoat Celery Worker', config_object)
-setup_celery(application, celery)
Index: src/gnuboat/mapservice_impl/Config.py
===================================================================
--- src/gnuboat/mapservice_impl/Config.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ 	(revision )
@@ -1,92 +1,0 @@
-'''
-    Copyright (C) 2019 - 2020 EngSaS - 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/>.
-'''
-
-from celery.schedules import crontab
-from pathlib import Path
-import os
-
-
-class Config(object):
-    DEBUG = False
-    TESTING = False
-    CREATE_TEST_DATABASE = False
-    SQLALCHEMY_TRACK_MODIFICATIONS = False
-    MAIL_SERVER = 'localhost'
-    MAIL_PORT = 25
-    MAIL_DEFAULT_SENDER = 'GNUBoat Mapservice <gnuboat@engsas.de>'
-    MAPSERVICE_WEBCLIENT = '/'
-    CELERY_BROKER_URL = 'pyamqp://guest@localhost//'
-    CELERY_IMPORTS = ("gnuboat.mapservice_impl.tasks")
-    CELERY_RESULT_BACKEND = "cache"
-    CELERY_CACHE_BACKEND = 'memcached://127.0.0.1:11211'
-    # pixel size of tiles to be generated
-    TILES_SIZES = [256, 512]
-    # Min required data points to get no nodata value in a raster pixel
-    TILES_DENSITIES = [10, 100]
-    TILES_DENSITY_BASEE = 100
-    # How many years are data points allowed to be old,
-    # before they are excluded from calculations
-    TILES_POINT_AGE_MAX = 10
-    # log_process generates tiles for this zoom range. all lower
-    # zoomlevels (0 - x) are generated by a periodic task
-    # (s. TILES_LITTLE_ZOOM_SCHEDULE option).
-    # Those zoomlevels are not rendered by log_process(),
-    # because they contain few details, but large areas
-    TILES_ZOOM_RANGE = {'minimum': 10, 'maximum': 19}
-    # schedule, when to run the job to generate tiles for low
-    # zoomlevels (0 - TILES_ZOOM_RANGE['minimum']),
-    # As format see https://docs.celeryproject.org/en/
-    # stable/userguide/periodic-tasks.html#crontab-schedules
-    # If TILES_ZOOM_RANGE['minimum'] = 10 it might need up to
-    # 4097 slice jobs per tile_size and density
-    TILES_LITTLE_ZOOM_SCHEDULE = crontab(
-        0, 0, day_of_month='2'
-    )  # execute every second day of each month
-    TILES_SKIP_EMPTY = True
-    # Maximum size of the raster files generated during tile process in bits
-    TILES_RASTER_FILE_SIZE_MAX = 512 * 1024 * 1024 * 8
-    MAX_CONTENT_LENGTH = 128 * 1024 * 1024
-
-
-class ProductionConfig(Config):
-    SQLALCHEMY_DATABASE_URI = ('mysql+mysqldb://gnuboat:gnuboat@localhost/'
-                               'gnuboat_mapservice')
-    # TEMPLATE_FOLDER could be used to use own templates residing in
-    # TEMPLATE_FOLDER
-    TEMPLATE_FOLDER = '/usr/share/gnuboat/templates'
-
-
-class DevelopmentConfig(Config):
-    DEBUG = True
-    CREATE_TEST_DATABASE = True
-    SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/test.db'
-    MAPSERVICE_WEBCLIENT = 'http://localhost:8081'
-    # SERVER_NAME = 'gnuboat-mapservice:8080'
-    HOST = 'localhost'
-    SERVER_NAME = 'localhost:8080'
-    TILES_CACHE_PATH = os.path.join(Path.home(), '.cache/gnuboat/tiles')
-    TILES_SIZES = [256]
-
-
-class TestingConfig(DevelopmentConfig):
-    """
-        Configuration for testing purposes only
-    """
-    TESTING = True
-    DEBUG = False
-    CELERY_BROKER_URL = ''
-    SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/gnuboat-ci-tests.db'
Index: src/gnuboat/mapservice_impl/ValidatorWorkaround.py
===================================================================
--- src/gnuboat/mapservice_impl/ValidatorWorkaround.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ 	(revision )
@@ -1,59 +1,0 @@
-"""Hacks needed to circumvent connexion validation
-
-There is a bug on the connexion library concerning content negotiation and
-response validation. See https://github.com/zalando/connexion/issues/860 and
-https://github.com/zalando/connexion/pull/760
-
-Until this issue is fixed, we need to find a way to avoid a false validation
-error when a requests sends an 'application/geo+json' accept header
-"""
-import functools
-import logging
-
-from connexion.decorators.response import ResponseValidator
-from connexion import problem
-from connexion.exceptions import (
-    NonConformingResponseBody, NonConformingResponseHeaders
-)
-from connexion.utils import has_coroutine
-
-logger = logging.getLogger(__name__)
-
-
-class ValidatorWorkaround(ResponseValidator):
-    def validate_response_with_request(
-        self, request, data, status_code, headers, url
-    ):
-        if request.headers.get('accept', '') == 'application/geo+json':
-            logging.debug('Circumventing validation for application/geo+json')
-            return True
-        return self.validate_response(data, status_code, headers, url)
-
-    def __call__(self, function):
-        """
-            :type function: types.FunctionType
-            :rtype: types.FunctionType
-        """
-        def _wrapper(request, response):
-            connexion_response = \
-             self.operation.api.get_connexion_response(response, self.mimetype)
-            self.validate_response_with_request(
-                request, connexion_response.body,
-                connexion_response.status_code, connexion_response.headers,
-                request.url
-            )
-
-            return response
-
-        if has_coroutine(function):
-            from .coroutine_wrappers import get_response_validator_wrapper
-            wrapper = get_response_validator_wrapper(function, _wrapper)
-
-        else:  # pragma: 3 no cover
-
-            @functools.wraps(function)
-            def wrapper(request):
-                response = function(request)
-                return _wrapper(request, response)
-
-        return wrapper
Index: src/gnuboat/mapservice_impl/__init__.py
===================================================================
--- src/gnuboat/mapservice_impl/__init__.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ src/gnuboat/mapservice_impl/__init__.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -20,4 +20,5 @@
 from flask_cors import CORS
 from flask_mail import Mail
+from flask_migrate import Migrate
 from sqlalchemy import event
 from celery import Celery
@@ -26,14 +27,14 @@
 
 from gnuboat.mapservice import encoder
-from gnuboat.mapservice_impl.database.Model import (
+from gnuboat.mapservice_impl.database.model import (
     db, User, ApiKey,
     db_setup, load_spatialite
 )
-from gnuboat.mapservice_impl.ValidatorWorkaround import ValidatorWorkaround
+from gnuboat.mapservice_impl.validator_workaround import ValidatorWorkaround
 
 
 def load_config_object(config_name):
     return import_string(
-        'gnuboat.mapservice_impl.Config.{}Config'.format(config_name)
+        'gnuboat.mapservice_impl.config.{}Config'.format(config_name)
     )
 
@@ -54,12 +55,11 @@
 app = connexion.App(__name__, specification_dir='../mapservice/openapi/')
 application = app.app
-CORS(application)
 mail = Mail()
 celery = Celery(__name__, broker=config_object.CELERY_BROKER_URL)
 
 
-def setup_app(app_name, config, template_folder=None):
-    application.json_encoder = encoder.JSONEncoder
-    app.add_api(
+def setup_app(app_name, config, template_folder=None, connexion_app=app):
+    connexion_app.app.json_encoder = encoder.JSONEncoder
+    connexion_app.add_api(
         'openapi.yaml',
         arguments={'title': app_name},
@@ -68,15 +68,20 @@
         validator_map={'response': ValidatorWorkaround}
     )
-    application.config.from_object(config)
+    connexion_app.app.config.from_object(config)
 
-    if 'TEMPLATE_FOLDER' in application.config:
-        application.template_folder = application.config['TEMPLATE_FOLDER']
+    if 'TEMPLATE_FOLDER' in connexion_app.app.config:
+        connexion_app.app.template_folder = \
+            connexion_app.app.config['TEMPLATE_FOLDER']
     elif template_folder:
-        application.template_folder = template_folder
+        connexion_app.app.template_folder = template_folder
 
-    db.init_app(application)
-    mail.init_app(application)
+    CORS(connexion_app.app)
+    db.init_app(connexion_app.app)
+    migrate = Migrate(connexion_app.app, db,
+                      directory='migrations/mapservice_impl')
+    mail.init_app(connexion_app.app)
     celery.config_from_object(config)
-    with application.app_context():
+
+    with connexion_app.app.app_context():
         @event.listens_for(db.engine, "connect")
         def load_spatialite_extension(dbapi_conn, connection_record):
@@ -84,6 +89,6 @@
 
         if flask.current_app.config['CREATE_TEST_DATABASE'] is True:
-            from gnuboat.mapservice_impl.demo import DbSetup as demoDbSetup
-            demoDbSetup.setup()
+            from gnuboat.mapservice_impl.demo import db_setup as demodbsetup
+            demodbsetup.setup()
         else:
             db_setup()
Index: src/gnuboat/mapservice_impl/celery_worker.py
===================================================================
--- src/gnuboat/mapservice_impl/celery_worker.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/mapservice_impl/celery_worker.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,70 @@
+'''
+    Copyright (C) 2020 EngSaS - 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/>.
+'''
+from celery import Celery
+import flask
+from sqlalchemy import event
+
+from gnuboat.mapservice_impl import (
+    config_object, app, application, celery, setup_app
+)
+from gnuboat.mapservice_impl.database.model import db, load_spatialite
+from gnuboat.mapservice_impl.tasks import tasks
+
+
+# see https://flask.palletsprojects.com/en/1.1.x/patterns/celery/
+def setup_celery(flask_app, celery_app):
+    celery_app.conf.update(flask_app.config)
+    TaskBase = celery_app.Task
+
+    class ContextTask(TaskBase):
+        abstract = True
+
+        def __call__(self, *args, **kwargs):
+            with flask_app.app_context():
+
+                @event.listens_for(db.engine, "connect")
+                def load_spatialite_extension(dbapi_conn, connection_record):
+                    load_spatialite(dbapi_conn, connection_record)
+
+                return TaskBase.__call__(self, *args, **kwargs)
+
+    celery_app.Task = ContextTask
+
+    with flask_app.app_context():
+        if 'TILES_LITTLE_ZOOM_SCHEDULE' not in flask.current_app.config:
+            flask.current_app.logger.error(
+                'TILES_LITTLE_ZOOM_SCHEDULE not configured'
+            )
+            raise ImportError('TILES_LITTLE_ZOOM_SCHEDULE not configured')
+        tiles_little_zoom_schedule = flask.current_app.config[
+            'TILES_LITTLE_ZOOM_SCHEDULE']
+
+        celery_app.conf.beat_schedule = {
+            'add-log_little_zoom_slice': {
+                'task':
+                    ('gnuboat.mapservice_impl.tasks.'
+                     'tasks.log_little_zoom_slice'),
+                'schedule':
+                    tiles_little_zoom_schedule
+            },
+        }
+
+    return celery_app
+
+
+setup_app('GNUBoat Celery Worker', config_object)
+setup_celery(application, celery)
Index: src/gnuboat/mapservice_impl/config.py
===================================================================
--- src/gnuboat/mapservice_impl/config.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/mapservice_impl/config.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,93 @@
+'''
+    Copyright (C) 2019 - 2020 EngSaS - 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/>.
+'''
+
+from celery.schedules import crontab
+from pathlib import Path
+import os
+
+
+class Config(object):
+    DEBUG = False
+    TESTING = False
+    CREATE_TEST_DATABASE = False
+    SQLALCHEMY_TRACK_MODIFICATIONS = False
+    MAIL_SERVER = 'localhost'
+    MAIL_PORT = 25
+    MAIL_DEFAULT_SENDER = 'GNUBoat Mapservice <gnuboat@engsas.de>'
+    MAPSERVICE_WEBCLIENT = '/'
+    CELERY_BROKER_URL = 'pyamqp://guest@localhost//'
+    CELERY_IMPORTS = ("gnuboat.mapservice_impl.tasks")
+    CELERY_RESULT_BACKEND = "cache"
+    CELERY_CACHE_BACKEND = 'memcached://127.0.0.1:11211'
+    # pixel size of tiles to be generated
+    TILES_SIZES = [256, 512]
+    # Min required data points to get no nodata value in a raster pixel
+    TILES_DENSITIES = [10, 100]
+    TILES_DENSITY_BASEE = 100
+    # How many years are data points allowed to be old,
+    # before they are excluded from calculations
+    TILES_POINT_AGE_MAX = 10
+    # log_process generates tiles for this zoom range. all lower
+    # zoomlevels (0 - x) are generated by a periodic task
+    # (s. TILES_LITTLE_ZOOM_SCHEDULE option).
+    # Those zoomlevels are not rendered by log_process(),
+    # because they contain few details, but large areas
+    TILES_ZOOM_RANGE = {'minimum': 10, 'maximum': 19}
+    # schedule, when to run the job to generate tiles for low
+    # zoomlevels (0 - TILES_ZOOM_RANGE['minimum']),
+    # As format see https://docs.celeryproject.org/en/
+    # stable/userguide/periodic-tasks.html#crontab-schedules
+    # If TILES_ZOOM_RANGE['minimum'] = 10 it might need up to
+    # 4097 slice jobs per tile_size and density
+    TILES_LITTLE_ZOOM_SCHEDULE = crontab(
+        0, 0, day_of_month='2'
+    )  # execute every second day of each month
+    TILES_SKIP_EMPTY = True
+    # Maximum size of the raster files generated during tile process in bits
+    TILES_RASTER_FILE_SIZE_MAX = 512 * 1024 * 1024 * 8
+    MAX_CONTENT_LENGTH = 128 * 1024 * 1024
+
+
+class ProductionConfig(Config):
+    SQLALCHEMY_DATABASE_URI = ('mysql+mysqldb://gnuboat:gnuboat@localhost/'
+                               'gnuboat_mapservice')
+    # TEMPLATE_FOLDER could be used to use own templates residing in
+    # TEMPLATE_FOLDER
+    TEMPLATE_FOLDER = '/usr/share/gnuboat/templates'
+
+
+class DevelopmentConfig(Config):
+    DEBUG = True
+    CREATE_TEST_DATABASE = True
+    SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/test.db'
+    MAPSERVICE_WEBCLIENT = 'http://localhost:8081'
+    # SERVER_NAME = 'gnuboat-mapservice:8080'
+    HOST = 'localhost'
+    SERVER_NAME = 'localhost:8080'
+    TILES_CACHE_PATH = os.path.join(Path.home(), '.cache/gnuboat/tiles')
+    TILES_SIZES = [256]
+
+
+class TestingConfig(DevelopmentConfig):
+    """
+        Configuration for testing purposes only
+    """
+    TESTING = True
+    DEBUG = False
+    CELERY_BROKER_URL = None
+    SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/gnuboat-ci-tests.db'
+    CREATE_TEST_DATABASE = False
Index: src/gnuboat/mapservice_impl/controllers/DevicesController.py
===================================================================
--- src/gnuboat/mapservice_impl/controllers/DevicesController.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ 	(revision )
@@ -1,88 +1,0 @@
-'''
-    Copyright (C) 2019 - 2020 EngSaS - 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 connexion
-
-from gnuboat.mapservice_impl.database.Model import User, Device, db
-from gnuboat.common.webservice.HttpErrors import (
-    GnuboatBadRequest, GnuboatUnauthorized, GnuboatNotFound
-)
-
-
-def devices_get(name=None, order_by=None, offset=None, limit=None):
-    query = None
-
-    user = User.loggedin_user()
-    if user is None:
-        raise GnuboatUnauthorized
-
-    query = Device.query.filter_by(owner=user)
-    if name is not None:
-        query = query.filter(Device.name.like('%{}%'.format(name)))
-
-    result = []
-    for device in query.offset(offset).limit(limit):
-        result.append(device.to_dict())
-    return result
-
-
-def devices_get_by_id(id):
-    user = User.loggedin_user()
-    if user is None:
-        raise GnuboatUnauthorized
-
-    device = Device.query.filter_by(owner=user).filter_by(id=id).all()
-    if len(device) != 1:
-        raise GnuboatNotFound
-    return device[0].to_dict()
-
-
-def devices_create(device_creation):
-    user = User.loggedin_user()
-    if user is None:
-        raise GnuboatUnauthorized
-
-    comment = ""
-    if device_creation.comment:
-        comment = device_creation.comment
-
-    device = Device(
-        name=device_creation.name,
-        owner=user,
-        sensor_depth=device_creation.sensor_depth,
-        comment=comment
-    )
-    db.session.add(device)
-    db.session.commit()
-    return device.to_dict()
-
-
-def devices_device_delete(id):
-    user = User.loggedin_user()
-    if user is None:
-        raise GnuboatUnauthorized
-
-    if not Device.query.filter_by(owner=user).filter_by(id=id).delete():
-        raise GnuboatBadRequest(
-            detail="Could not delete device with id {}".format(id)
-        )
-    db.session.commit()
-
-    query = Device.query.filter_by(owner=user)
-    result = []
-    for device in query:
-        result.append(device.to_dict())
-    return result
Index: src/gnuboat/mapservice_impl/controllers/LogsController.py
===================================================================
--- src/gnuboat/mapservice_impl/controllers/LogsController.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ 	(revision )
@@ -1,178 +1,0 @@
-'''
-    Copyright (C) 2019 - 2020 EngSaS - 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 connexion
-
-from gnuboat.mapservice_impl.database.Model import (
-    User, Log, LogEntry,
-    Water, Device, Gauge, ProcessingStatus, Queue, db
-)
-from gnuboat.common.webservice.HttpErrors import (
-    GnuboatBadRequest, GnuboatUnauthorized, GnuboatNotFound
-)
-from gnuboat.mapservice_impl.tasks.tasks import log_process
-
-
-def logs_get(submitter=None, order_by=None, offset=None, limit=None):
-    query = None
-
-    if submitter is not None:
-        submitter = User.query.filter_by(username=submitter).all()
-        if len(submitter) != 1:
-            raise GnuboatNotFound(
-                detail="Could not find the submitter with id {}".
-                format(submitter)
-            )
-        submitter = submitter[0]
-
-    query = None
-    if submitter is not None:
-        query = Log.query.filter_by(submitter=submitter)
-
-    if query is None:
-        query = Log.query
-
-    result = []
-    for log in query.offset(offset).limit(limit):
-        result.append(log.meta_data())
-    return result
-
-
-def logs_log_get_by_id(id):
-    log = Log.query.filter_by(id=id).all()
-    if len(log) != 1:
-        raise GnuboatNotFound
-    if connexion.request.headers['Accept'] == "application/geo+json":
-        return log[0].to_geojson(), 200, {
-            'Content-Type': 'application/geo+json; charset=utf-8'
-        }
-    return log[0].log()
-
-
-def logs_log_create(log_creation):
-    user = User.loggedin_user()
-    if user is None:
-        raise GnuboatUnauthorized
-
-    water = Water.query.filter_by(id=log_creation.water).all()
-    if len(water) != 1:
-        raise GnuboatBadRequest(
-            detail='Water {} not found database'.format(log_creation.water)
-        )
-    water = water[0]
-
-    device = Device.query.filter_by(id=log_creation.device).all()
-    if len(device) != 1:
-        raise GnuboatBadRequest(
-            detail='Device {} not found in database'.
-            format(log_creation.device)
-        )
-    device = device[0]
-
-    gauge = Gauge.query.filter_by(id=log_creation.gauge).all()
-    if len(gauge) != 1:
-        raise GnuboatBadRequest(
-            detail='Gauge {} not found in database'.format(log_creation.gauge)
-        )
-    gauge = gauge[0]
-
-    if log_creation.gauge_height is None:
-        raise GnuboatBadRequest(detail='Gauge Height (Stage) missing')
-    else:
-        try:
-            float(log_creation.gauge_height)
-        except ValueError:
-            raise GnuboatBadRequest(
-                detail='Gauge Height (Stage) {} is no number'.
-                format(log_creation.gauge_height)
-            )
-
-    if log_creation.comment is None:
-        log_creation.comment = ""
-
-    log = Log(
-        submitter=user,
-        water=water,
-        device=device,
-        gauge=gauge,
-        gauge_height=log_creation.gauge_height,
-        start=None,
-        end=None,
-        comment=log_creation.comment
-    )
-    db.session.add(log)
-    db.session.commit()
-    return log.meta_data()
-
-
-def logs_log_upload(log_id, body=None):
-    user = User.loggedin_user()
-    if user is None:
-        raise GnuboatUnauthorized
-
-    if body is None or not body:
-        raise GnuboatBadRequest(detail='No log data')
-
-    processing_state = ProcessingStatus.query.filter_by(
-        label='Queued for Parsing'
-    ).all()
-    if len(processing_state) != 1:
-        raise GnuboatBadRequest(
-            detail='Processing status Queued for Parsing not found database'
-        )
-    processing_state = processing_state[0]
-
-    log = Log.query.filter_by(id=log_id).all()
-    if len(log) != 1:
-        raise GnuboatBadRequest(
-            detail='Log {} not found database'.format(log_id)
-        )
-    log = log[0]
-
-    # check if Log has already log entries
-    if LogEntry.query.filter_by(log=log).count() > 0:
-        raise GnuboatBadRequest(
-            detail='Log {} has already log entries. Aborting'.format(log_id)
-        )
-
-    # Add Log to Queued table and change the processing state of Log
-    queue = Queue(log=log)
-    db.session.add(queue)
-    log.processingstatus = processing_state
-    db.session.commit()
-
-    # request log parsing
-    log_process.delay(log.id, body.decode())
-
-    return log.meta_data()
-
-
-def logs_log_delete(id):
-    user = User.loggedin_user()
-    if user is None:
-        raise GnuboatUnauthorized
-
-    if not Log.query.filter_by(submitter=user).filter_by(id=id).delete():
-        raise GnuboatBadRequest(
-            detail="Could not delete log with id {}".format(id)
-        )
-    db.session.commit()
-
-    query = Log.query.filter_by(submitter=user)
-    result = []
-    for log in query:
-        result.append(log.meta_data())
-    return result
Index: src/gnuboat/mapservice_impl/controllers/TilesController.py
===================================================================
--- src/gnuboat/mapservice_impl/controllers/TilesController.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ 	(revision )
@@ -1,89 +1,0 @@
-'''
-    Copyright (C) 2020 EngSaS - 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 connexion
-import flask
-import os
-
-from gnuboat.common.webservice.HttpErrors import (
-    GnuboatInternalServerError, GnuboatBadRequest, GnuboatNotFound
-)
-
-
-def tiles_tile_get(accuracy, resolution, zoom, x_tile, y_tile):
-    if 'TILES_CACHE_PATH' not in flask.current_app.config or not os.access(
-        flask.current_app.config['TILES_CACHE_PATH'], os.R_OK
-    ):
-        raise GnuboatInternalServerError(
-            detail='TILES_CACHE_PATH not configured or not accessible'
-        )
-    tiles_cache_path = flask.current_app.config['TILES_CACHE_PATH']
-
-    if 'TILES_DENSITIES' not in flask.current_app.config:
-        raise GnuboatInternalServerError(
-            detail='TILES_DENSITIES not configured'
-        )
-    tiles_densities = flask.current_app.config['TILES_DENSITIES']
-
-    if 'TILES_DENSITY_BASEE' not in flask.current_app.config:
-        raise GnuboatInternalServerError(
-            detail='TILES_DENSITY_BASEE not configured'
-        )
-    tiles_densitiy_base = flask.current_app.config['TILES_DENSITY_BASEE']
-
-    if 'TILES_SKIP_EMPTY' not in flask.current_app.config:
-        raise GnuboatInternalServerError(
-            detail='TILES_SKIP_EMPTY not configured'
-        )
-    tiles_skip_empty = flask.current_app.config['TILES_SKIP_EMPTY']
-
-    if accuracy == 'high':
-        accuracy = '{}_{}'.format(max(tiles_densities), tiles_densitiy_base)
-    elif accuracy == 'low':
-        accuracy = '{}_{}'.format(min(tiles_densities), tiles_densitiy_base)
-    else:
-        raise GnuboatBadRequest(
-            detail=('No valid accuracy requested. '
-                    'Valid are high, low. Requested was: {}')
-            .format(accuracy)
-        )
-
-    tile__empty_path = os.path.join(
-        tiles_cache_path, '{}/{}/empty_tile.png'.format(accuracy, resolution)
-    )
-    tile_path = os.path.join(
-        tiles_cache_path, '{}/{}/{}/{}/{}.png'.format(
-            accuracy, resolution, zoom, x_tile, y_tile
-        )
-    )
-    if not os.path.isfile(tile_path):
-        if not tiles_skip_empty or not os.path.isfile(tile__empty_path):
-            raise GnuboatNotFound(
-                detail=('Tile ({}, {}) for accuracy {} with resolution {} '
-                        'at zoomlevel {} not found')
-                .format(x_tile, y_tile, accuracy, resolution, zoom)
-            )
-        tile_path = tile__empty_path
-
-    response = flask.send_file(
-        tile_path,
-        mimetype='image/png',
-        as_attachment=True,
-        attachment_filename='{}.png'.format(y_tile)
-    )
-    response.direct_passthrough = False
-    return response
Index: src/gnuboat/mapservice_impl/controllers/UsersController.py
===================================================================
--- src/gnuboat/mapservice_impl/controllers/UsersController.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ 	(revision )
@@ -1,159 +1,0 @@
-'''
-    Copyright (C) 2019 - 2020 EngSaS - 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 connexion
-
-import datetime
-import hashlib
-import re
-import flask
-from flask import request, render_template
-from flask_mail import Message
-
-from gnuboat.mapservice_impl import mail
-from gnuboat.mapservice_impl.database.Model import User, ApiKey, db
-from gnuboat.common.webservice.HttpErrors import (
-    GnuboatBadRequest, GnuboatUnauthorized, GnuboatNotFound
-)
-
-mail_regex = re.compile('[^@]+@[^@]+\\.[^@]+')
-
-
-def users_activate(activationCode):
-    user = User.query.filter_by(activation_code=activationCode).all()
-
-    webclient = flask.current_app.config['MAPSERVICE_WEBCLIENT']
-
-    if len(user) != 1:
-        return 'Bad Request', 302, {'Location': 'activation_failed.html'}
-
-    user = user[0]
-    user.activated = True
-    user.activation_code = ""
-    db.session.commit()
-    return 'Success', 302, {'Location': '{}/login'.format(webclient)}
-
-
-def users_api_key_create():
-    user = User.loggedin_user()
-    if user is None:
-        raise GnuboatUnauthorized
-
-    api_key = hashlib.md5(
-        "{}{}".format(
-            datetime.datetime.now().strftime("%Y%m%d%H%M%S"), user.salt
-        ).encode()
-    ).hexdigest()
-    user.apikeys.append(ApiKey(user=user, key=api_key))
-    db.session.commit()
-
-    result = []
-    for apiKey in user.apikeys:
-        result.append(apiKey.key)
-    return result
-
-
-def users_api_key_delete(api_key):
-    user = User.loggedin_user()
-    if user is None:
-        raise GnuboatUnauthorized
-
-    if not ApiKey.query.filter_by(key=api_key).delete():
-        raise GnuboatBadRequest(
-            detail="Could not delete api key {}".format(api_key)
-        )
-    db.session.commit()
-
-    result = []
-    for apiKey in user.apikeys:
-        result.append(apiKey.key)
-    return result
-
-
-def users_get():
-    user = User.loggedin_user()
-    if user is None:
-        raise GnuboatUnauthorized
-
-    return user_to_dict(user)
-
-
-def users_register(user_creation):
-    if user_creation is None:
-        raise GnuboatBadRequest(detail='No data specified')
-    if user_creation.username is None or not user_creation.username:
-        raise GnuboatBadRequest(detail='No username given')
-    if user_creation.password is None or not user_creation.password:
-        raise GnuboatBadRequest(detail='No password given')
-    if user_creation.first_name is None or not user_creation.first_name:
-        raise GnuboatBadRequest(detail='No first name given')
-    if user_creation.last_name is None or not user_creation.last_name:
-        raise GnuboatBadRequest(detail='No last name given')
-    if user_creation.email is None or not user_creation.email:
-        raise GnuboatBadRequest(detail='No email given')
-    if not mail_regex.match(user_creation.email):
-        raise GnuboatBadRequest(
-            detail='Email contains more than one @, no @ or no .'
-        )
-    if (user_creation.license_accepted is None or
-            not user_creation.license_accepted):
-        raise GnuboatBadRequest(
-            detail='You must accept the license to register an account'
-        )
-
-    # add user to the database
-    user = User.factory(
-        user_creation.username, user_creation.password, user_creation.email
-    )
-    user.first_name = user_creation.first_name
-    user.last_name = user_creation.last_name
-    user.license_accepted = user_creation.license_accepted
-    db.session.add(user)
-    db.session.commit()
-
-    # send activation mail
-    activation_url = '{}/activate/{}'.format(
-        request.base_url, user.activation_code
-    )
-
-    message = Message("Activate your GNUBoat account", recipients=[user.email])
-    message.body = ('Hello {},\nthank you for support the project with your '
-                    'own measurings. To activate your GNUBoat account, '
-                    'visit {}.\nKind regards,\nYour GNUBoat team').format(
-            user.first_name, activation_url
-    )
-    message.html = render_template(
-        'activation_mail.html',
-        first_name=user.first_name,
-        activation_url=activation_url
-    )
-    mail.send(message)
-
-    return user_to_dict(user)
-
-
-def user_to_dict(user):
-    # create user dict and remove not needed entries
-    result = user.to_dict()
-    del result['password']
-    del result['salt']
-    del result['activationCode']
-
-    # add api keys of the user to the result dict
-    result['apiKeys'] = []
-    for apiKey in user.apikeys:
-        result['apiKeys'].append(apiKey.key)
-    return result
Index: src/gnuboat/mapservice_impl/controllers/WatersController.py
===================================================================
--- src/gnuboat/mapservice_impl/controllers/WatersController.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ 	(revision )
@@ -1,197 +1,0 @@
-'''
-    Copyright (C) 2019 - 2020 EngSaS - 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 connexion
-
-from gnuboat.mapservice_impl.database.Model import User, Water, Gauge, Log, db
-from gnuboat.common.webservice.HttpErrors import (
-    GnuboatBadRequest,
-    GnuboatUnauthorized, GnuboatNotFound
-)
-
-
-def waters_get(
-    name=None,
-    manager=None,
-    stakeholder=None,
-    order_by=None,
-    offset=None,
-    limit=None
-):
-    query = None
-
-    if manager is not None:
-        manager = User.query.filter_by(username=manager).all()
-        if len(manager) != 1:
-            raise GnuboatNotFound(
-                detail="Could not find the manager with id {}".format(manager)
-            )
-        manager = manager[0]
-
-    query = Water.query
-    if manager is not None:
-        query = query.filter_by(manager=manager)
-    if name is not None:
-        query = query.filter(Water.name.like('%{}%'.format(name)))
-
-    waters = []
-    for water in query.offset(offset).limit(limit):
-        waters.append(water)
-
-    # handle stakeholder
-    if stakeholder is not None:
-        stakeholder = User.query.filter_by(username=stakeholder).all()
-        if len(stakeholder) != 1:
-            raise GnuboatNotFound(detail='Stakeholder not found')
-        stakeholder = stakeholder[0]
-
-        # add waters, where the stakeholder has added logs to
-        query_log = Log.query.filter_by(submitter=stakeholder).all()
-        for log in query_log:
-            already_found = False
-            for water in waters:
-                if water.id == log.water.id:
-                    already_found = True
-                    break
-            if not already_found:
-                waters.append(log.water)
-
-        # add waters, where the stakeholder has added gauges to
-        query_gauge = Gauge.query.filter_by(manager=stakeholder).all()
-        for gauge in query_gauge:
-            already_found = False
-            for water in waters:
-                if water.id == gauge.water.id:
-                    already_found = True
-                    break
-            if not already_found:
-                waters.append(gauge.water)
-
-    result = []
-    for water in waters:
-        result.append(water.to_dict())
-
-    return result
-
-
-def waters_get_by_id(id):
-    water = Water.query.filter_by(id=id).all()
-    if len(water) != 1:
-        raise GnuboatNotFound
-    return water[0].to_dict()
-
-
-def waters_create(water_creation):
-    user = User.loggedin_user()
-    if user is None:
-        raise GnuboatUnauthorized
-
-    water = Water(
-        name=water_creation.name,
-        manager=user,
-        osm_id=water_creation.osm_id,
-        osm_type=water_creation.osm_type
-    )
-    db.session.add(water)
-    db.session.commit()
-    return water.to_dict()
-
-
-def waters_gauge_get_by_id(water_id, gauge_id):
-    water = Water.query.filter_by(id=water_id).all()
-    if len(water) != 1:
-        raise GnuboatBadRequest(
-            detail="Water with id {} not found".format(water_id)
-        )
-    water = water[0]
-
-    gauge = Gauge.query.filter_by(water=water).filter_by(id=gauge_id).all()
-    if len(gauge) != 1:
-        raise GnuboatNotFound(
-            detail="Did not find gauge with id {} for water {}".
-            format(gauge_id, water.name)
-        )
-    if connexion.request.headers['Accept'] == "application/geo+json":
-        return gauge[0].to_geojson(), 200, {
-            'Content-Type': 'application/geo+json; charset=utf-8'
-        }
-    return gauge[0].to_dict()
-
-
-def waters_gauge_create(water_id, gauge_creation):
-    user = User.loggedin_user()
-    if user is None:
-        raise GnuboatUnauthorized
-
-    water = Water.query.filter_by(id=water_id).all()
-    if len(water) != 1:
-        raise GnuboatBadRequest(
-            detail="Did not find water with id {}".format(water_id)
-        )
-    water = water[0]
-
-    location = 'SRID=4326;POINT({:.6} {:.6})'.format(
-        gauge_creation.location[0], gauge_creation.location[1]
-    )
-    gauge = Gauge(
-        name=gauge_creation.name,
-        manager=user,
-        water=water,
-        location=location,
-        reference_water_level_gauge_height=gauge_creation.
-        reference_water_level_gauge_height,
-        comment=gauge_creation.comment
-    )
-    db.session.add(gauge)
-    db.session.commit()
-    return gauge.to_dict()
-
-
-def waters_gauges_get(water_id, name, manager, order_by, offset, limit):
-    water = Water.query.filter_by(id=water_id).all()
-    if len(water) != 1:
-        raise GnuboatBadRequest(
-            detail="Did not find water with id {}".format(water_id)
-        )
-
-    query = None
-
-    if manager is not None:
-        manager = User.query.filter_by(username=manager).all()
-        if len(manager) != 1:
-            raise GnuboatNotFound(
-                detail="Could not find the manager with id {}".format(manager)
-            )
-        manager = manager[0]
-
-    query = Gauge.query.filter_by(id=water_id)
-    if manager is not None:
-        if manager and name is not None:
-            query = query.filter_by(manager=manager).filter(
-                Gauge.name.like('%{}%'.format(name))
-            )
-        elif manager:
-            query = query.filter_by(manager=manager)
-    elif name is not None:
-        query = query.filter(Gauge.name.like('%{}%'.format(name)))
-
-    result = []
-    for gauge in query.offset(offset).limit(limit):
-        if connexion.request.headers['Accept'] == "application/geo+json":
-            result.append(gauge.to_geojson())
-        else:
-            result.append(gauge.to_dict())
-    return result
Index: src/gnuboat/mapservice_impl/controllers/devices_controller.py
===================================================================
--- src/gnuboat/mapservice_impl/controllers/devices_controller.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/mapservice_impl/controllers/devices_controller.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,88 @@
+'''
+    Copyright (C) 2019 - 2020 EngSaS - 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 connexion
+
+from gnuboat.mapservice_impl.database.model import User, Device, db
+from gnuboat.common.webservice.http_errors import (
+    GnuboatBadRequest, GnuboatUnauthorized, GnuboatNotFound
+)
+
+
+def devices_get(name=None, order_by=None, offset=None, limit=None):
+    query = None
+
+    user = User.loggedin_user()
+    if user is None:
+        raise GnuboatUnauthorized
+
+    query = Device.query.filter_by(owner=user)
+    if name is not None:
+        query = query.filter(Device.name.like('%{}%'.format(name)))
+
+    result = []
+    for device in query.offset(offset).limit(limit):
+        result.append(device.to_dict())
+    return result
+
+
+def devices_get_by_id(id):
+    user = User.loggedin_user()
+    if user is None:
+        raise GnuboatUnauthorized
+
+    device = Device.query.filter_by(owner=user).filter_by(id=id).all()
+    if len(device) != 1:
+        raise GnuboatNotFound
+    return device[0].to_dict()
+
+
+def devices_create(device_creation):
+    user = User.loggedin_user()
+    if user is None:
+        raise GnuboatUnauthorized
+
+    comment = ""
+    if device_creation.comment:
+        comment = device_creation.comment
+
+    device = Device(
+        name=device_creation.name,
+        owner=user,
+        sensor_depth=device_creation.sensor_depth,
+        comment=comment
+    )
+    db.session.add(device)
+    db.session.commit()
+    return device.to_dict(), 201
+
+
+def devices_device_delete(id):
+    user = User.loggedin_user()
+    if user is None:
+        raise GnuboatUnauthorized
+
+    if not Device.query.filter_by(owner=user).filter_by(id=id).delete():
+        raise GnuboatBadRequest(
+            detail="Could not delete device with id {}".format(id)
+        )
+    db.session.commit()
+
+    query = Device.query.filter_by(owner=user)
+    result = []
+    for device in query:
+        result.append(device.to_dict())
+    return result
Index: src/gnuboat/mapservice_impl/controllers/logs_controller.py
===================================================================
--- src/gnuboat/mapservice_impl/controllers/logs_controller.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/mapservice_impl/controllers/logs_controller.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,178 @@
+'''
+    Copyright (C) 2019 - 2020 EngSaS - 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 connexion
+
+from gnuboat.mapservice_impl.database.model import (
+    User, Log, LogEntry,
+    Water, Device, Gauge, ProcessingStatus, Queue, db
+)
+from gnuboat.common.webservice.http_errors import (
+    GnuboatBadRequest, GnuboatUnauthorized, GnuboatNotFound
+)
+from gnuboat.mapservice_impl.tasks.tasks import log_process
+
+
+def logs_get(submitter=None, order_by=None, offset=None, limit=None):
+    query = None
+
+    if submitter is not None:
+        submitter = User.query.filter_by(username=submitter).all()
+        if len(submitter) != 1:
+            raise GnuboatNotFound(
+                detail="Could not find the submitter with id {}".
+                format(submitter)
+            )
+        submitter = submitter[0]
+
+    query = None
+    if submitter is not None:
+        query = Log.query.filter_by(submitter=submitter)
+
+    if query is None:
+        query = Log.query
+
+    result = []
+    for log in query.offset(offset).limit(limit):
+        result.append(log.meta_data())
+    return result
+
+
+def logs_log_get_by_id(id):
+    log = Log.query.filter_by(id=id).all()
+    if len(log) != 1:
+        raise GnuboatNotFound
+    if connexion.request.headers['Accept'] == "application/geo+json":
+        return log[0].to_geojson(), 200, {
+            'Content-Type': 'application/geo+json; charset=utf-8'
+        }
+    return log[0].log()
+
+
+def logs_log_create(log_creation):
+    user = User.loggedin_user()
+    if user is None:
+        raise GnuboatUnauthorized
+
+    water = Water.query.filter_by(id=log_creation.water).all()
+    if len(water) != 1:
+        raise GnuboatBadRequest(
+            detail='Water {} not found database'.format(log_creation.water)
+        )
+    water = water[0]
+
+    device = Device.query.filter_by(id=log_creation.device).all()
+    if len(device) != 1:
+        raise GnuboatBadRequest(
+            detail='Device {} not found in database'.
+            format(log_creation.device)
+        )
+    device = device[0]
+
+    gauge = Gauge.query.filter_by(id=log_creation.gauge).all()
+    if len(gauge) != 1:
+        raise GnuboatBadRequest(
+            detail='Gauge {} not found in database'.format(log_creation.gauge)
+        )
+    gauge = gauge[0]
+
+    if log_creation.gauge_height is None:
+        raise GnuboatBadRequest(detail='Gauge Height (Stage) missing')
+    else:
+        try:
+            float(log_creation.gauge_height)
+        except ValueError:
+            raise GnuboatBadRequest(
+                detail='Gauge Height (Stage) {} is no number'.
+                format(log_creation.gauge_height)
+            )
+
+    if log_creation.comment is None:
+        log_creation.comment = ""
+
+    log = Log(
+        submitter=user,
+        water=water,
+        device=device,
+        gauge=gauge,
+        gauge_height=log_creation.gauge_height,
+        start=None,
+        end=None,
+        comment=log_creation.comment
+    )
+    db.session.add(log)
+    db.session.commit()
+    return log.meta_data(), 201
+
+
+def logs_log_upload(log_id, body=None):
+    user = User.loggedin_user()
+    if user is None:
+        raise GnuboatUnauthorized
+
+    if body is None or not body:
+        raise GnuboatBadRequest(detail='No log data')
+
+    processing_state = ProcessingStatus.query.filter_by(
+        label='Queued for Parsing'
+    ).all()
+    if len(processing_state) != 1:
+        raise GnuboatBadRequest(
+            detail='Processing status Queued for Parsing not found database'
+        )
+    processing_state = processing_state[0]
+
+    log = Log.query.filter_by(id=log_id).all()
+    if len(log) != 1:
+        raise GnuboatBadRequest(
+            detail='Log {} not found database'.format(log_id)
+        )
+    log = log[0]
+
+    # check if Log has already log entries
+    if LogEntry.query.filter_by(log=log).count() > 0:
+        raise GnuboatBadRequest(
+            detail='Log {} has already log entries. Aborting'.format(log_id)
+        )
+
+    # Add Log to Queued table and change the processing state of Log
+    queue = Queue(log=log)
+    db.session.add(queue)
+    log.processingstatus = processing_state
+    db.session.commit()
+
+    # request log parsing
+    log_process.delay(log.id, body.decode())
+
+    return log.meta_data(), 201
+
+
+def logs_log_delete(id):
+    user = User.loggedin_user()
+    if user is None:
+        raise GnuboatUnauthorized
+
+    if not Log.query.filter_by(submitter=user).filter_by(id=id).delete():
+        raise GnuboatBadRequest(
+            detail="Could not delete log with id {}".format(id)
+        )
+    db.session.commit()
+
+    query = Log.query.filter_by(submitter=user)
+    result = []
+    for log in query:
+        result.append(log.meta_data())
+    return result
Index: src/gnuboat/mapservice_impl/controllers/tiles_controller.py
===================================================================
--- src/gnuboat/mapservice_impl/controllers/tiles_controller.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/mapservice_impl/controllers/tiles_controller.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,89 @@
+'''
+    Copyright (C) 2020 EngSaS - 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 connexion
+import flask
+import os
+
+from gnuboat.common.webservice.http_errors import (
+    GnuboatInternalServerError, GnuboatBadRequest, GnuboatNotFound
+)
+
+
+def tiles_tile_get(accuracy, resolution, zoom, x_tile, y_tile):
+    if 'TILES_CACHE_PATH' not in flask.current_app.config or not os.access(
+        flask.current_app.config['TILES_CACHE_PATH'], os.R_OK
+    ):
+        raise GnuboatInternalServerError(
+            detail='TILES_CACHE_PATH not configured or not accessible'
+        )
+    tiles_cache_path = flask.current_app.config['TILES_CACHE_PATH']
+
+    if 'TILES_DENSITIES' not in flask.current_app.config:
+        raise GnuboatInternalServerError(
+            detail='TILES_DENSITIES not configured'
+        )
+    tiles_densities = flask.current_app.config['TILES_DENSITIES']
+
+    if 'TILES_DENSITY_BASEE' not in flask.current_app.config:
+        raise GnuboatInternalServerError(
+            detail='TILES_DENSITY_BASEE not configured'
+        )
+    tiles_densitiy_base = flask.current_app.config['TILES_DENSITY_BASEE']
+
+    if 'TILES_SKIP_EMPTY' not in flask.current_app.config:
+        raise GnuboatInternalServerError(
+            detail='TILES_SKIP_EMPTY not configured'
+        )
+    tiles_skip_empty = flask.current_app.config['TILES_SKIP_EMPTY']
+
+    if accuracy == 'high':
+        accuracy = '{}_{}'.format(max(tiles_densities), tiles_densitiy_base)
+    elif accuracy == 'low':
+        accuracy = '{}_{}'.format(min(tiles_densities), tiles_densitiy_base)
+    else:
+        raise GnuboatBadRequest(
+            detail=('No valid accuracy requested. '
+                    'Valid are high, low. Requested was: {}')
+            .format(accuracy)
+        )
+
+    tile__empty_path = os.path.join(
+        tiles_cache_path, '{}/{}/empty_tile.png'.format(accuracy, resolution)
+    )
+    tile_path = os.path.join(
+        tiles_cache_path, '{}/{}/{}/{}/{}.png'.format(
+            accuracy, resolution, zoom, x_tile, y_tile
+        )
+    )
+    if not os.path.isfile(tile_path):
+        if not tiles_skip_empty or not os.path.isfile(tile__empty_path):
+            raise GnuboatNotFound(
+                detail=('Tile ({}, {}) for accuracy {} with resolution {} '
+                        'at zoomlevel {} not found')
+                .format(x_tile, y_tile, accuracy, resolution, zoom)
+            )
+        tile_path = tile__empty_path
+
+    response = flask.send_file(
+        tile_path,
+        mimetype='image/png',
+        as_attachment=True,
+        attachment_filename='{}.png'.format(y_tile)
+    )
+    response.direct_passthrough = False
+    return response
Index: src/gnuboat/mapservice_impl/controllers/users_controller.py
===================================================================
--- src/gnuboat/mapservice_impl/controllers/users_controller.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/mapservice_impl/controllers/users_controller.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,159 @@
+'''
+    Copyright (C) 2019 - 2020 EngSaS - 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 connexion
+
+import datetime
+import hashlib
+import re
+import flask
+from flask import request, render_template
+from flask_mail import Message
+
+from gnuboat.mapservice_impl import mail
+from gnuboat.mapservice_impl.database.model import User, ApiKey, db
+from gnuboat.common.webservice.http_errors import (
+    GnuboatBadRequest, GnuboatUnauthorized, GnuboatNotFound
+)
+
+mail_regex = re.compile('[^@]+@[^@]+\\.[^@]+')
+
+
+def users_activate(activationCode):
+    user = User.query.filter_by(activation_code=activationCode).all()
+
+    webclient = flask.current_app.config['MAPSERVICE_WEBCLIENT']
+
+    if len(user) != 1:
+        return 'Bad Request', 302, {'Location': 'activation_failed.html'}
+
+    user = user[0]
+    user.activated = True
+    user.activation_code = ""
+    db.session.commit()
+    return 'Success', 302, {'Location': '{}/login'.format(webclient)}
+
+
+def users_api_key_create():
+    user = User.loggedin_user()
+    if user is None:
+        raise GnuboatUnauthorized
+
+    api_key = hashlib.md5(
+        "{}{}".format(
+            datetime.datetime.now().strftime("%Y%m%d%H%M%S"), user.salt
+        ).encode()
+    ).hexdigest()
+    user.apikeys.append(ApiKey(user=user, key=api_key))
+    db.session.commit()
+
+    result = []
+    for apiKey in user.apikeys:
+        result.append(apiKey.key)
+    return result
+
+
+def users_api_key_delete(api_key):
+    user = User.loggedin_user()
+    if user is None:
+        raise GnuboatUnauthorized
+
+    if not ApiKey.query.filter_by(key=api_key).delete():
+        raise GnuboatBadRequest(
+            detail="Could not delete api key {}".format(api_key)
+        )
+    db.session.commit()
+
+    result = []
+    for apiKey in user.apikeys:
+        result.append(apiKey.key)
+    return result
+
+
+def users_get():
+    user = User.loggedin_user()
+    if user is None:
+        raise GnuboatUnauthorized
+
+    return user_to_dict(user)
+
+
+def users_register(user_creation):
+    if user_creation is None:
+        raise GnuboatBadRequest(detail='No data specified')
+    if user_creation.username is None or not user_creation.username:
+        raise GnuboatBadRequest(detail='No username given')
+    if user_creation.password is None or not user_creation.password:
+        raise GnuboatBadRequest(detail='No password given')
+    if user_creation.first_name is None or not user_creation.first_name:
+        raise GnuboatBadRequest(detail='No first name given')
+    if user_creation.last_name is None or not user_creation.last_name:
+        raise GnuboatBadRequest(detail='No last name given')
+    if user_creation.email is None or not user_creation.email:
+        raise GnuboatBadRequest(detail='No email given')
+    if not mail_regex.match(user_creation.email):
+        raise GnuboatBadRequest(
+            detail='Email contains more than one @, no @ or no .'
+        )
+    if (user_creation.license_accepted is None or
+            not user_creation.license_accepted):
+        raise GnuboatBadRequest(
+            detail='You must accept the license to register an account'
+        )
+
+    # add user to the database
+    user = User.factory(
+        user_creation.username, user_creation.password, user_creation.email
+    )
+    user.first_name = user_creation.first_name
+    user.last_name = user_creation.last_name
+    user.license_accepted = user_creation.license_accepted
+    db.session.add(user)
+    db.session.commit()
+
+    # send activation mail
+    activation_url = '{}/activate/{}'.format(
+        request.base_url, user.activation_code
+    )
+
+    message = Message("Activate your GNUBoat account", recipients=[user.email])
+    message.body = ('Hello {},\nthank you for support the project with your '
+                    'own measurings. To activate your GNUBoat account, '
+                    'visit {}.\nKind regards,\nYour GNUBoat team').format(
+            user.first_name, activation_url
+    )
+    message.html = render_template(
+        'activation_mail.html',
+        first_name=user.first_name,
+        activation_url=activation_url
+    )
+    mail.send(message)
+
+    return user_to_dict(user)
+
+
+def user_to_dict(user):
+    # create user dict and remove not needed entries
+    result = user.to_dict()
+    del result['password']
+    del result['salt']
+    del result['activationCode']
+
+    # add api keys of the user to the result dict
+    result['apiKeys'] = []
+    for apiKey in user.apikeys:
+        result['apiKeys'].append(apiKey.key)
+    return result
Index: src/gnuboat/mapservice_impl/controllers/waters_controller.py
===================================================================
--- src/gnuboat/mapservice_impl/controllers/waters_controller.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/mapservice_impl/controllers/waters_controller.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,197 @@
+'''
+    Copyright (C) 2019 - 2020 EngSaS - 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 connexion
+
+from gnuboat.mapservice_impl.database.model import User, Water, Gauge, Log, db
+from gnuboat.common.webservice.http_errors import (
+    GnuboatBadRequest,
+    GnuboatUnauthorized, GnuboatNotFound
+)
+
+
+def waters_get(
+    name=None,
+    manager=None,
+    stakeholder=None,
+    order_by=None,
+    offset=None,
+    limit=None
+):
+    query = None
+
+    if manager is not None:
+        manager = User.query.filter_by(username=manager).all()
+        if len(manager) != 1:
+            raise GnuboatNotFound(
+                detail="Could not find the manager with id {}".format(manager)
+            )
+        manager = manager[0]
+
+    query = Water.query
+    if manager is not None:
+        query = query.filter_by(manager=manager)
+    if name is not None:
+        query = query.filter(Water.name.like('%{}%'.format(name)))
+
+    waters = []
+    for water in query.offset(offset).limit(limit):
+        waters.append(water)
+
+    # handle stakeholder
+    if stakeholder is not None:
+        stakeholder = User.query.filter_by(username=stakeholder).all()
+        if len(stakeholder) != 1:
+            raise GnuboatNotFound(detail='Stakeholder not found')
+        stakeholder = stakeholder[0]
+
+        # add waters, where the stakeholder has added logs to
+        query_log = Log.query.filter_by(submitter=stakeholder).all()
+        for log in query_log:
+            already_found = False
+            for water in waters:
+                if water.id == log.water.id:
+                    already_found = True
+                    break
+            if not already_found:
+                waters.append(log.water)
+
+        # add waters, where the stakeholder has added gauges to
+        query_gauge = Gauge.query.filter_by(manager=stakeholder).all()
+        for gauge in query_gauge:
+            already_found = False
+            for water in waters:
+                if water.id == gauge.water.id:
+                    already_found = True
+                    break
+            if not already_found:
+                waters.append(gauge.water)
+
+    result = []
+    for water in waters:
+        result.append(water.to_dict())
+
+    return result
+
+
+def waters_get_by_id(id):
+    water = Water.query.filter_by(id=id).all()
+    if len(water) != 1:
+        raise GnuboatNotFound
+    return water[0].to_dict()
+
+
+def waters_create(water_creation):
+    user = User.loggedin_user()
+    if user is None:
+        raise GnuboatUnauthorized
+
+    water = Water(
+        name=water_creation.name,
+        manager=user,
+        osm_id=water_creation.osm_id,
+        osm_type=water_creation.osm_type
+    )
+    db.session.add(water)
+    db.session.commit()
+    return water.to_dict(), 201
+
+
+def waters_gauge_get_by_id(water_id, gauge_id):
+    water = Water.query.filter_by(id=water_id).all()
+    if len(water) != 1:
+        raise GnuboatBadRequest(
+            detail="Water with id {} not found".format(water_id)
+        )
+    water = water[0]
+
+    gauge = Gauge.query.filter_by(water=water).filter_by(id=gauge_id).all()
+    if len(gauge) != 1:
+        raise GnuboatNotFound(
+            detail="Did not find gauge with id {} for water {}".
+            format(gauge_id, water.name)
+        )
+    if connexion.request.headers['Accept'] == "application/geo+json":
+        return gauge[0].to_geojson(), 200, {
+            'Content-Type': 'application/geo+json; charset=utf-8'
+        }
+    return gauge[0].to_dict()
+
+
+def waters_gauge_create(water_id, gauge_creation):
+    user = User.loggedin_user()
+    if user is None:
+        raise GnuboatUnauthorized
+
+    water = Water.query.filter_by(id=water_id).all()
+    if len(water) != 1:
+        raise GnuboatBadRequest(
+            detail="Did not find water with id {}".format(water_id)
+        )
+    water = water[0]
+
+    location = 'SRID=4326;POINT({:.6} {:.6})'.format(
+        gauge_creation.location[0], gauge_creation.location[1]
+    )
+    gauge = Gauge(
+        name=gauge_creation.name,
+        manager=user,
+        water=water,
+        location=location,
+        reference_water_level_gauge_height=gauge_creation.
+        reference_water_level_gauge_height,
+        comment=gauge_creation.comment
+    )
+    db.session.add(gauge)
+    db.session.commit()
+    return gauge.to_dict(), 201
+
+
+def waters_gauges_get(water_id, name, manager, order_by, offset, limit):
+    water = Water.query.filter_by(id=water_id).all()
+    if len(water) != 1:
+        raise GnuboatBadRequest(
+            detail="Did not find water with id {}".format(water_id)
+        )
+
+    query = None
+
+    if manager is not None:
+        manager = User.query.filter_by(username=manager).all()
+        if len(manager) != 1:
+            raise GnuboatNotFound(
+                detail="Could not find the manager with id {}".format(manager)
+            )
+        manager = manager[0]
+
+    query = Gauge.query.filter_by(id=water_id)
+    if manager is not None:
+        if manager and name is not None:
+            query = query.filter_by(manager=manager).filter(
+                Gauge.name.like('%{}%'.format(name))
+            )
+        elif manager:
+            query = query.filter_by(manager=manager)
+    elif name is not None:
+        query = query.filter(Gauge.name.like('%{}%'.format(name)))
+
+    result = []
+    for gauge in query.offset(offset).limit(limit):
+        if connexion.request.headers['Accept'] == "application/geo+json":
+            result.append(gauge.to_geojson())
+        else:
+            result.append(gauge.to_dict())
+    return result
Index: src/gnuboat/mapservice_impl/database/Model.py
===================================================================
--- src/gnuboat/mapservice_impl/database/Model.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ 	(revision )
@@ -1,475 +1,0 @@
-'''
-    Copyright (C) 2019 - 2020 EngSaS - 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 flask
-from flask_sqlalchemy import SQLAlchemy
-from sqlalchemy import inspect, text, Enum, event, select, func
-from sqlalchemy.orm.attributes import get_history
-from geoalchemy2 import Geometry
-from geoalchemy2.shape import to_shape
-from sqlalchemy_utils import create_view, database_exists, create_database
-import hashlib
-import datetime
-import enum
-import connexion
-from pathlib import Path
-import sys
-import os
-
-db = SQLAlchemy()
-
-
-class OsmType(enum.Enum):
-    Node = 1
-    Way = 2
-    Relation = 3
-
-
-def wkb_to_dict(wkbelement):
-    point = to_shape(wkbelement)
-    return {'longitude': point.x, 'latitude': point.y}
-
-
-class User(db.Model):
-    __tablename__ = "users"
-
-    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
-    username = db.Column(db.String(255), nullable=False, unique=True)
-    password = db.Column(db.String(50), nullable=False)
-    salt = db.Column(db.String(50), nullable=False)
-    email = db.Column(db.String(255), nullable=False)
-    first_name = db.Column(db.String(255))
-    last_name = db.Column(db.String(255))
-    activated = db.Column(db.Boolean(), default=False)
-    activation_code = db.Column(db.String(255), default='1234')
-    # activation_code = db.Column(db.String(255),
-    #     server_default=text('LEFT(MD5(NOW()), 50)'))
-    license_accepted = db.Column(db.Boolean(), default=False)
-
-    def to_dict(user):
-        result = {
-            'username': user.username,
-            'password': user.password,
-            'salt': user.salt,
-            'email': user.email,
-            'firstName': "",
-            'lastName': "",
-            'activated': user.activated,
-            'licenseAccepted': user.license_accepted
-        }
-        if user.first_name is not None:
-            result['firstName'] = user.first_name
-        if user.last_name is not None:
-            result['lastName'] = user.last_name
-        if user.activation_code is not None:
-            result['activationCode'] = user.activation_code
-
-        return result
-
-    def factory(username, password, email):
-        salt = hashlib.md5(
-            '{}{}'.format(
-                username,
-                datetime.datetime.utcnow().strftime('%Y%m%d%H%M%S')
-            ).encode()
-        ).hexdigest()
-        password = hashlib.md5('{}{}'.format(password,
-                                             salt).encode()).hexdigest()
-        activation_code = hashlib.md5(
-            '{}'.format(datetime.datetime.utcnow().strftime('%Y%m%d%H%M%S')
-                        ).encode()
-        ).hexdigest()
-        return User(
-            username=username,
-            password=password,
-            email=email,
-            salt=salt,
-            activated=False,
-            activation_code=activation_code
-        )
-
-    def password_verify(self, password):
-        return hashlib.md5("{}{}".format(password, self.salt).encode()
-                           ).hexdigest() == self.password
-
-    @staticmethod
-    def loggedin_username():
-        if 'user' not in connexion.context:
-            return None
-        return connexion.context['user']
-
-    @staticmethod
-    def loggedin_user():
-        username = User.loggedin_username()
-        if username is None:
-            return None
-        user = User.query.filter_by(username=username).all()
-        if len(user) != 1:
-            return None
-        return user[0]
-
-
-class ApiKey(db.Model):
-    __tablename__ = "apikeys"
-
-    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
-    user_id = db.Column(db.BigInteger, db.ForeignKey('users.id'))
-    key = db.Column(db.String(255), nullable=False, unique=True)
-    user = db.relationship("User", backref=db.backref("apikeys"), lazy=True)
-
-
-class Water(db.Model):
-    __tablename__ = "waters"
-
-    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
-    name = db.Column(db.String(255), nullable=False)
-    manager_id = db.Column(db.Integer, db.ForeignKey('users.id'))
-    osm_id = db.Column(db.Integer)
-    osm_type = db.Column(Enum(OsmType))
-    manager = db.relationship("User", backref=db.backref("waters"), lazy=True)
-
-    def to_dict(obj):
-        result = {'waterId': obj.id, 'name': obj.name}
-        if obj.manager:
-            result['manager'] = obj.manager.username
-        if obj.osm_id:
-            result['osmId'] = obj.osm_id
-        if obj.osm_type:
-            result['osmType'] = obj.osm_type.name
-        if obj.gauges:
-            result['gauges'] = []
-            for gauge in obj.gauges:
-                result['gauges'].append(gauge.to_dict())
-        if obj.logs:
-            logs = []
-            for log in obj.logs:
-                logs.append(log.meta_data())
-            result['logs'] = logs
-        return result
-
-
-class Gauge(db.Model):
-    __tablename__ = "gauges"
-
-    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
-    name = db.Column(db.String(255), nullable=False)
-    manager_id = db.Column(db.Integer, db.ForeignKey('users.id'))
-    water_id = db.Column(db.Integer, db.ForeignKey('waters.id'))
-    # POINT(Lon Lat)
-    location = db.Column(
-        Geometry(geometry_type='POINT', srid=4326, management=True)
-    )
-    reference_water_level_gauge_height = db.Column(db.Float, nullable=False)
-    comment = db.Column(db.String(255))
-    # osm_id = db.Column(db.Integer)
-    # osm_type = db.Column(db.String(255))
-    # osm_class = db.Column(db.String(255))
-    manager = db.relationship("User", backref=db.backref("gauges"), lazy=True)
-    water = db.relationship("Water", backref=db.backref("gauges"), lazy=True)
-
-    def to_dict(obj):
-        result = {'gaugeId': obj.id, 'name': obj.name}
-        if obj.manager:
-            result['manager'] = obj.manager.username
-        location = wkb_to_dict(obj.location)
-        result['location'] = [location['longitude'], location['latitude']]
-        result['referenceWaterLevelGaugeHeight'
-               ] = obj.reference_water_level_gauge_height
-        if obj.water:
-            result['water'] = {'label': obj.water.name, 'id': obj.water.id}
-        if obj.logs:
-            logs = []
-            for log in obj.logs:
-                logs.append(log.meta_data())
-            result['logs'] = logs
-        if obj.comment:
-            result['comment'] = obj.comment
-        return result
-
-    def to_geojson(obj):
-        location = wkb_to_dict(obj.location)
-        result = {
-            'type': 'Feature',
-            'geometry': {
-                'type': 'Point',
-                'coordinates': [location['longitude'], location['latitude']]
-            },
-            'properties': {
-                'name':
-                    obj.name,
-                'referenceWaterLevelGaugeHeight':
-                    obj.reference_water_level_gauge_height
-            }
-        }
-        if obj.manager:
-            result['properties']['manager'] = obj.manager.username
-        if obj.comment:
-            result['properties']['comment'] = obj.comment
-        return result
-
-
-class Device(db.Model):
-    __tablename__ = "devices"
-
-    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
-    name = db.Column(db.String(255), nullable=False)
-    owner_id = db.Column(db.Integer, db.ForeignKey('users.id'))
-    sensor_depth = db.Column(db.Float, nullable=False)
-    comment = db.Column(db.String(255))
-
-    owner = db.relationship("User", backref=db.backref("devices"), lazy=True)
-
-    def to_dict(obj):
-        result = {
-            'deviceId': obj.id,
-            'name': obj.name,
-            'sensorDepth': obj.sensor_depth
-        }
-        if obj.logs:
-            logs = []
-            for log in obj.logs:
-                logs.append(log.meta_data())
-            result['logs'] = logs
-        if obj.comment:
-            result['comment'] = obj.comment
-        return result
-
-
-class ProcessingStatus(db.Model):
-    __tablename__ = "processingstatus"
-
-    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
-    label = db.Column(db.String(255), nullable=False)
-
-    @staticmethod
-    def insert_states():
-        states = [
-            'Undefined', 'Queued for Parsing', 'Parsing',
-            'Queued for Processing', 'Processing', 'Deployed', 'To Old',
-            'Error'
-        ]
-        changed = False
-        for state in states:
-            query = ProcessingStatus.query.filter_by(label=state).all()
-            if len(query) != 1:
-                state = ProcessingStatus(label=state)
-                db.session.add(state)
-                changed = True
-        if changed:
-            db.session.commit()
-
-
-class Log(db.Model):
-    __tablename__ = "logs"
-
-    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
-    submitter_id = db.Column(db.Integer, db.ForeignKey('users.id'))
-    water_id = db.Column(db.Integer, db.ForeignKey('waters.id'))
-    device_id = db.Column(db.Integer, db.ForeignKey('devices.id'))
-    gauge_id = db.Column(db.Integer, db.ForeignKey('gauges.id'))
-    gauge_height = db.Column(db.Float, nullable=False)
-    start = db.Column(db.DateTime, nullable=True)
-    end = db.Column(db.DateTime, nullable=True)
-    processing_state = db.Column(
-        db.Integer, db.ForeignKey('processingstatus.id'), default=1
-    )
-    comment = db.Column(db.String(255))
-
-    submitter = db.relationship("User", backref=db.backref("logs"), lazy=True)
-    water = db.relationship("Water", backref=db.backref("logs"), lazy=True)
-    device = db.relationship("Device", backref=db.backref("logs"), lazy=True)
-    gauge = db.relationship("Gauge", backref=db.backref("logs"), lazy=True)
-    processingstatus = db.relationship(
-        "ProcessingStatus", backref=db.backref("logs"), lazy=True
-    )
-
-    def meta_data(obj):
-        result = {
-            'logId': obj.id,
-            'submitter': obj.submitter.username,
-            'water': {
-                'id': obj.water.id,
-                'label': obj.water.name,
-            },
-            'device': {
-                'id': obj.device.id,
-                'label': obj.device.name,
-            },
-            'gauge': {
-                'id': obj.gauge.id,
-                'label': obj.gauge.name,
-            },
-            'gaugeHeight': obj.gauge_height,
-            'start': None,
-            'end': None,
-            'processingState': {
-                'id': obj.processingstatus.id,
-                'label': obj.processingstatus.label
-            }
-        }
-        if obj.start is not None:
-            result['start'] = obj.start.isoformat('T')
-        if obj.end is not None:
-            result['end'] = obj.end.isoformat('T')
-
-        entries_count = 0
-        if obj.log_entries:
-            entries_count = len(obj.log_entries)
-        result['entriesCount'] = entries_count
-        if obj.comment:
-            result['comment'] = obj.comment
-        return result
-
-    def log(obj):
-        result = {'metaData': obj.meta_data()}
-        entries = []
-        if obj.log_entries:
-            for log in obj.log_entries:
-                entries.append(log.to_dict())
-        result['entries'] = entries
-        return result
-
-    def to_geojson(obj):
-        result = {'type': 'FeatureCollection', 'features': []}
-        if obj.log_entries:
-            for log in obj.log_entries:
-                location = wkb_to_dict(log.location)
-                feature = {
-                    'type': 'Feature',
-                    'geometry': {
-                        'type':
-                            'Point',
-                        'coordinates': [
-                            location['longitude'], location['latitude']
-                        ]
-                    },
-                    'properties': {
-                        'datetime': log.datetime.isoformat('T')
-                    }
-                }
-                if log.water_depth is not None:
-                    feature['properties']['waterDepth'] = log.water_depth
-                result['features'].append(feature)
-        return result
-
-
-class LogEntry(db.Model):
-    __tablename__ = "logentries"
-
-    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
-    log_id = db.Column(db.Integer, db.ForeignKey('logs.id'))
-    datetime = db.Column(db.DateTime, nullable=False)
-    # POINT(Lon Lat)
-    location = db.Column(
-        Geometry(geometry_type='POINT', srid=4326, management=True)
-    )
-    water_depth = db.Column(db.Float)
-
-    log = db.relationship("Log", backref=db.backref("log_entries"), lazy=True)
-
-    def to_dict(obj):
-        result = {'datetime': obj.datetime.isoformat('T')}
-        location = wkb_to_dict(obj.location)
-        result['location'] = [location['longitude'], location['latitude']]
-        if obj.water_depth:
-            result['waterDepth'] = obj.water_depth
-        return result
-
-
-class LogView(db.Model):
-    __table__ = create_view(
-        name='logview',
-        metadata=db.Model.metadata,
-        selectable=select([
-            Log.id, Log.submitter_id, Log.water_id, Log.device_id,
-            Log.gauge_id, Log.gauge_height, Log.start, Log.end,
-            ProcessingStatus.label,
-            func.Envelope(func.MakeLine(LogEntry.location)).label('envelope')
-        ],
-                          from_obj=(
-                              Log.__table__.join(
-                                  LogEntry, Log.id == LogEntry.log_id
-                              ).join(
-                                  ProcessingStatus,
-                                  Log.processing_state == ProcessingStatus.id
-                              )
-                          ),
-                          group_by=(Log.id)),
-        cascade_on_drop=False
-    )
-
-
-class Queue(db.Model):
-    __tablename__ = "queue"
-
-    log_id = db.Column(db.Integer, db.ForeignKey('logs.id'), primary_key=True)
-    datetime = db.Column(
-        db.DateTime,
-        nullable=False,
-        default=datetime.datetime.now(datetime.timezone.utc)
-    )
-
-    log = db.relationship("Log", backref=db.backref("queue"), lazy=True)
-
-
-def db_setup(force=False):
-    if not database_exists(db.engine.url) or force:
-        create_database(db.engine.url)
-        if 'sqlite' in flask.current_app.config['SQLALCHEMY_DATABASE_URI']:
-            result = db.engine.execute(
-                ('SELECT count(name) FROM sqlite_master '
-                 'WHERE type="table" AND name="spatial_ref_sys"')
-            )
-            if result.fetchone()[0] == 1:
-                print('Spatial lite extension already loaded')
-            else:
-                print("Initiate spatial meta data for Spatialite...")
-                db.engine.execute(select([func.InitSpatialMetaData(1)]))
-                print("...Finished")
-        db.create_all()
-        ProcessingStatus.insert_states()
-
-
-def load_spatialite(dbapi_conn, connection_record):
-    if 'sqlite' not in flask.current_app.config['SQLALCHEMY_DATABASE_URI']:
-        return
-
-    paths = [
-        os.path.join(sys.prefix, 'lib'),
-        os.path.join(sys.prefix, 'lib64'), '/usr/lib', '/usr/lib64'
-    ]
-    for path in paths:
-        if _load_spatialite_from_path(path, dbapi_conn, connection_record):
-            return True
-    raise FileNotFoundError(
-        'mod_spatialite not found in folders {}'.format(', '.join(paths))
-    )
-
-
-def _load_spatialite_from_path(search_path, dbapi_conn, connection_record):
-    for path in Path(search_path).rglob('mod_spatialite.so*'):
-        if os.path.exists(path):
-            if flask.current_app.config['DEBUG'] and (
-                'TESTING' not in flask.current_app.config or
-                not flask.current_app.config['TESTING']
-            ):
-                print('Enabling spatial lite extension. This may take a while')
-            # From https://geoalchemy-2.readthedocs.io/en/latest/
-            # spatialite_tutorial.html
-            dbapi_conn.enable_load_extension(True)
-            dbapi_conn.load_extension(str(path.resolve()))
-            return True
-    return False
Index: src/gnuboat/mapservice_impl/database/model.py
===================================================================
--- src/gnuboat/mapservice_impl/database/model.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/mapservice_impl/database/model.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,475 @@
+'''
+    Copyright (C) 2019 - 2020 EngSaS - 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 flask
+from flask_sqlalchemy import SQLAlchemy
+from sqlalchemy import inspect, text, Enum, event, select, func
+from sqlalchemy.orm.attributes import get_history
+from geoalchemy2 import Geometry
+from geoalchemy2.shape import to_shape
+from sqlalchemy_utils import create_view, database_exists, create_database
+import hashlib
+import datetime
+import enum
+import connexion
+from pathlib import Path
+import sys
+import os
+
+db = SQLAlchemy()
+
+
+class OsmType(enum.Enum):
+    Node = 1
+    Way = 2
+    Relation = 3
+
+
+def wkb_to_dict(wkbelement):
+    point = to_shape(wkbelement)
+    return {'longitude': point.x, 'latitude': point.y}
+
+
+class User(db.Model):
+    __tablename__ = "users"
+
+    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
+    username = db.Column(db.String(255), nullable=False, unique=True)
+    password = db.Column(db.String(50), nullable=False)
+    salt = db.Column(db.String(50), nullable=False)
+    email = db.Column(db.String(255), nullable=False)
+    first_name = db.Column(db.String(255))
+    last_name = db.Column(db.String(255))
+    activated = db.Column(db.Boolean(), default=False)
+    activation_code = db.Column(db.String(255), default='1234')
+    # activation_code = db.Column(db.String(255),
+    #     server_default=text('LEFT(MD5(NOW()), 50)'))
+    license_accepted = db.Column(db.Boolean(), default=False)
+
+    def to_dict(user):
+        result = {
+            'username': user.username,
+            'password': user.password,
+            'salt': user.salt,
+            'email': user.email,
+            'firstName': "",
+            'lastName': "",
+            'activated': user.activated,
+            'licenseAccepted': user.license_accepted
+        }
+        if user.first_name is not None:
+            result['firstName'] = user.first_name
+        if user.last_name is not None:
+            result['lastName'] = user.last_name
+        if user.activation_code is not None:
+            result['activationCode'] = user.activation_code
+
+        return result
+
+    def factory(username, password, email):
+        salt = hashlib.md5(
+            '{}{}'.format(
+                username,
+                datetime.datetime.utcnow().strftime('%Y%m%d%H%M%S')
+            ).encode()
+        ).hexdigest()
+        password = hashlib.md5('{}{}'.format(password,
+                                             salt).encode()).hexdigest()
+        activation_code = hashlib.md5(
+            '{}'.format(datetime.datetime.utcnow().strftime('%Y%m%d%H%M%S')
+                        ).encode()
+        ).hexdigest()
+        return User(
+            username=username,
+            password=password,
+            email=email,
+            salt=salt,
+            activated=False,
+            activation_code=activation_code
+        )
+
+    def password_verify(self, password):
+        return hashlib.md5("{}{}".format(password, self.salt).encode()
+                           ).hexdigest() == self.password
+
+    @staticmethod
+    def loggedin_username():
+        if 'user' not in connexion.context:
+            return None
+        return connexion.context['user']
+
+    @staticmethod
+    def loggedin_user():
+        username = User.loggedin_username()
+        if username is None:
+            return None
+        user = User.query.filter_by(username=username).all()
+        if len(user) != 1:
+            return None
+        return user[0]
+
+
+class ApiKey(db.Model):
+    __tablename__ = "apikeys"
+
+    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
+    user_id = db.Column(db.BigInteger, db.ForeignKey('users.id'))
+    key = db.Column(db.String(255), nullable=False, unique=True)
+    user = db.relationship("User", backref=db.backref("apikeys"), lazy=True)
+
+
+class Water(db.Model):
+    __tablename__ = "waters"
+
+    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
+    name = db.Column(db.String(255), nullable=False)
+    manager_id = db.Column(db.Integer, db.ForeignKey('users.id'))
+    osm_id = db.Column(db.Integer)
+    osm_type = db.Column(Enum(OsmType))
+    manager = db.relationship("User", backref=db.backref("waters"), lazy=True)
+
+    def to_dict(obj):
+        result = {'waterId': obj.id, 'name': obj.name}
+        if obj.manager:
+            result['manager'] = obj.manager.username
+        if obj.osm_id:
+            result['osmId'] = obj.osm_id
+        if obj.osm_type:
+            result['osmType'] = obj.osm_type.name
+        if obj.gauges:
+            result['gauges'] = []
+            for gauge in obj.gauges:
+                result['gauges'].append(gauge.to_dict())
+        if obj.logs:
+            logs = []
+            for log in obj.logs:
+                logs.append(log.meta_data())
+            result['logs'] = logs
+        return result
+
+
+class Gauge(db.Model):
+    __tablename__ = "gauges"
+
+    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
+    name = db.Column(db.String(255), nullable=False)
+    manager_id = db.Column(db.Integer, db.ForeignKey('users.id'))
+    water_id = db.Column(db.Integer, db.ForeignKey('waters.id'))
+    # POINT(Lon Lat)
+    location = db.Column(
+        Geometry(geometry_type='POINT', srid=4326, management=True)
+    )
+    reference_water_level_gauge_height = db.Column(db.Float, nullable=False)
+    comment = db.Column(db.String(255))
+    # osm_id = db.Column(db.Integer)
+    # osm_type = db.Column(db.String(255))
+    # osm_class = db.Column(db.String(255))
+    manager = db.relationship("User", backref=db.backref("gauges"), lazy=True)
+    water = db.relationship("Water", backref=db.backref("gauges"), lazy=True)
+
+    def to_dict(obj):
+        result = {'gaugeId': obj.id, 'name': obj.name}
+        if obj.manager:
+            result['manager'] = obj.manager.username
+        location = wkb_to_dict(obj.location)
+        result['location'] = [location['longitude'], location['latitude']]
+        result['referenceWaterLevelGaugeHeight'
+               ] = obj.reference_water_level_gauge_height
+        if obj.water:
+            result['water'] = {'label': obj.water.name, 'id': obj.water.id}
+        if obj.logs:
+            logs = []
+            for log in obj.logs:
+                logs.append(log.meta_data())
+            result['logs'] = logs
+        if obj.comment:
+            result['comment'] = obj.comment
+        return result
+
+    def to_geojson(obj):
+        location = wkb_to_dict(obj.location)
+        result = {
+            'type': 'Feature',
+            'geometry': {
+                'type': 'Point',
+                'coordinates': [location['longitude'], location['latitude']]
+            },
+            'properties': {
+                'name':
+                    obj.name,
+                'referenceWaterLevelGaugeHeight':
+                    obj.reference_water_level_gauge_height
+            }
+        }
+        if obj.manager:
+            result['properties']['manager'] = obj.manager.username
+        if obj.comment:
+            result['properties']['comment'] = obj.comment
+        return result
+
+
+class Device(db.Model):
+    __tablename__ = "devices"
+
+    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
+    name = db.Column(db.String(255), nullable=False)
+    owner_id = db.Column(db.Integer, db.ForeignKey('users.id'))
+    sensor_depth = db.Column(db.Float, nullable=False)
+    comment = db.Column(db.String(255))
+
+    owner = db.relationship("User", backref=db.backref("devices"), lazy=True)
+
+    def to_dict(obj):
+        result = {
+            'deviceId': obj.id,
+            'name': obj.name,
+            'sensorDepth': obj.sensor_depth
+        }
+        if obj.logs:
+            logs = []
+            for log in obj.logs:
+                logs.append(log.meta_data())
+            result['logs'] = logs
+        if obj.comment:
+            result['comment'] = obj.comment
+        return result
+
+
+class ProcessingStatus(db.Model):
+    __tablename__ = "processingstatus"
+
+    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
+    label = db.Column(db.String(255), nullable=False)
+
+    @staticmethod
+    def insert_states():
+        states = [
+            'Undefined', 'Queued for Parsing', 'Parsing',
+            'Queued for Processing', 'Processing', 'Deployed', 'To Old',
+            'Error'
+        ]
+        changed = False
+        for state in states:
+            query = ProcessingStatus.query.filter_by(label=state).all()
+            if len(query) != 1:
+                state = ProcessingStatus(label=state)
+                db.session.add(state)
+                changed = True
+        if changed:
+            db.session.commit()
+
+
+class Log(db.Model):
+    __tablename__ = "logs"
+
+    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
+    submitter_id = db.Column(db.Integer, db.ForeignKey('users.id'))
+    water_id = db.Column(db.Integer, db.ForeignKey('waters.id'))
+    device_id = db.Column(db.Integer, db.ForeignKey('devices.id'))
+    gauge_id = db.Column(db.Integer, db.ForeignKey('gauges.id'))
+    gauge_height = db.Column(db.Float, nullable=False)
+    start = db.Column(db.DateTime, nullable=True)
+    end = db.Column(db.DateTime, nullable=True)
+    processing_state = db.Column(
+        db.Integer, db.ForeignKey('processingstatus.id'), default=1
+    )
+    comment = db.Column(db.String(255))
+
+    submitter = db.relationship("User", backref=db.backref("logs"), lazy=True)
+    water = db.relationship("Water", backref=db.backref("logs"), lazy=True)
+    device = db.relationship("Device", backref=db.backref("logs"), lazy=True)
+    gauge = db.relationship("Gauge", backref=db.backref("logs"), lazy=True)
+    processingstatus = db.relationship(
+        "ProcessingStatus", backref=db.backref("logs"), lazy=True
+    )
+
+    def meta_data(obj):
+        result = {
+            'logId': obj.id,
+            'submitter': obj.submitter.username,
+            'water': {
+                'id': obj.water.id,
+                'label': obj.water.name,
+            },
+            'device': {
+                'id': obj.device.id,
+                'label': obj.device.name,
+            },
+            'gauge': {
+                'id': obj.gauge.id,
+                'label': obj.gauge.name,
+            },
+            'gaugeHeight': obj.gauge_height,
+            'start': None,
+            'end': None,
+            'processingState': {
+                'id': obj.processingstatus.id,
+                'label': obj.processingstatus.label
+            }
+        }
+        if obj.start is not None:
+            result['start'] = obj.start.isoformat('T')
+        if obj.end is not None:
+            result['end'] = obj.end.isoformat('T')
+
+        entries_count = 0
+        if obj.log_entries:
+            entries_count = len(obj.log_entries)
+        result['entriesCount'] = entries_count
+        if obj.comment:
+            result['comment'] = obj.comment
+        return result
+
+    def log(obj):
+        result = {'metaData': obj.meta_data()}
+        entries = []
+        if obj.log_entries:
+            for log in obj.log_entries:
+                entries.append(log.to_dict())
+        result['entries'] = entries
+        return result
+
+    def to_geojson(obj):
+        result = {'type': 'FeatureCollection', 'features': []}
+        if obj.log_entries:
+            for log in obj.log_entries:
+                location = wkb_to_dict(log.location)
+                feature = {
+                    'type': 'Feature',
+                    'geometry': {
+                        'type':
+                            'Point',
+                        'coordinates': [
+                            location['longitude'], location['latitude']
+                        ]
+                    },
+                    'properties': {
+                        'datetime': log.datetime.isoformat('T')
+                    }
+                }
+                if log.water_depth is not None:
+                    feature['properties']['waterDepth'] = log.water_depth
+                result['features'].append(feature)
+        return result
+
+
+class LogEntry(db.Model):
+    __tablename__ = "logentries"
+
+    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
+    log_id = db.Column(db.Integer, db.ForeignKey('logs.id'))
+    datetime = db.Column(db.DateTime, nullable=False)
+    # POINT(Lon Lat)
+    location = db.Column(
+        Geometry(geometry_type='POINT', srid=4326, management=True)
+    )
+    water_depth = db.Column(db.Float)
+
+    log = db.relationship("Log", backref=db.backref("log_entries"), lazy=True)
+
+    def to_dict(obj):
+        result = {'datetime': obj.datetime.isoformat('T')}
+        location = wkb_to_dict(obj.location)
+        result['location'] = [location['longitude'], location['latitude']]
+        if obj.water_depth:
+            result['waterDepth'] = obj.water_depth
+        return result
+
+
+class LogView(db.Model):
+    __table__ = create_view(
+        name='logview',
+        metadata=db.Model.metadata,
+        selectable=select([
+            Log.id, Log.submitter_id, Log.water_id, Log.device_id,
+            Log.gauge_id, Log.gauge_height, Log.start, Log.end,
+            ProcessingStatus.label,
+            func.Envelope(func.MakeLine(LogEntry.location)).label('envelope')
+        ],
+                          from_obj=(
+                              Log.__table__.join(
+                                  LogEntry, Log.id == LogEntry.log_id
+                              ).join(
+                                  ProcessingStatus,
+                                  Log.processing_state == ProcessingStatus.id
+                              )
+                          ),
+                          group_by=(Log.id)),
+        cascade_on_drop=False
+    )
+
+
+class Queue(db.Model):
+    __tablename__ = "queue"
+
+    log_id = db.Column(db.Integer, db.ForeignKey('logs.id'), primary_key=True)
+    datetime = db.Column(
+        db.DateTime,
+        nullable=False,
+        default=datetime.datetime.now(datetime.timezone.utc)
+    )
+
+    log = db.relationship("Log", backref=db.backref("queue"), lazy=True)
+
+
+def db_setup(force=False):
+    if not database_exists(db.engine.url) or force:
+        create_database(db.engine.url)
+        if 'sqlite' in flask.current_app.config['SQLALCHEMY_DATABASE_URI']:
+            result = db.engine.execute(
+                ('SELECT count(name) FROM sqlite_master '
+                 'WHERE type="table" AND name="spatial_ref_sys"')
+            )
+            if result.fetchone()[0] == 1:
+                print('Spatial lite extension already loaded')
+            else:
+                print("Initiate spatial meta data for Spatialite...")
+                db.engine.execute(select([func.InitSpatialMetaData(1)]))
+                print("...Finished")
+        db.create_all()
+        ProcessingStatus.insert_states()
+
+
+def load_spatialite(dbapi_conn, connection_record):
+    if 'sqlite' not in flask.current_app.config['SQLALCHEMY_DATABASE_URI']:
+        return
+
+    paths = [
+        os.path.join(sys.prefix, 'lib'),
+        os.path.join(sys.prefix, 'lib64'), '/usr/lib', '/usr/lib64'
+    ]
+    for path in paths:
+        if _load_spatialite_from_path(path, dbapi_conn, connection_record):
+            return True
+    raise FileNotFoundError(
+        'mod_spatialite not found in folders {}'.format(', '.join(paths))
+    )
+
+
+def _load_spatialite_from_path(search_path, dbapi_conn, connection_record):
+    for path in Path(search_path).rglob('mod_spatialite.so*'):
+        if os.path.exists(path):
+            if flask.current_app.config['DEBUG'] and (
+                'TESTING' not in flask.current_app.config or
+                not flask.current_app.config['TESTING']
+            ):
+                print('Enabling spatial lite extension. This may take a while')
+            # From https://geoalchemy-2.readthedocs.io/en/latest/
+            # spatialite_tutorial.html
+            dbapi_conn.enable_load_extension(True)
+            dbapi_conn.load_extension(str(path.resolve()))
+            return True
+    return False
Index: src/gnuboat/mapservice_impl/demo/CeleryEntry.py
===================================================================
--- src/gnuboat/mapservice_impl/demo/CeleryEntry.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ 	(revision )
@@ -1,41 +1,0 @@
-# -*- coding: utf-8 -*-
-'''
-    Copyright (C) 2016 - 2020 EngSaS - 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 re
-import sys
-from pkg_resources import load_entry_point
-
-
-def main():
-    # Add need configuration options
-    sys.argv.append('-A')
-    sys.argv.append('gnuboat.mapservice_impl.CeleryWorker:celery')
-    sys.argv.append('worker')
-    sys.argv.append('-l')
-    sys.argv.append('info')
-    sys.argv.append('-E')
-    sys.argv.append('-B')
-
-    # Copied from /usr/bin/celery
-    sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
-    sys.exit(
-        load_entry_point('celery', 'console_scripts', 'celery')()
-    )
-
-if __name__ == '__main__':
-    main
Index: src/gnuboat/mapservice_impl/demo/DbSetup.py
===================================================================
--- src/gnuboat/mapservice_impl/demo/DbSetup.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ 	(revision )
@@ -1,218 +1,0 @@
-'''
-    Copyright (C) 2019 - 2020 EngSaS - 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 os
-import pytz
-import flask
-
-from gnuboat.mapservice_impl.database.Model import (
-    db, User, ApiKey, Water,
-    OsmType, Gauge, Device, Log, Queue, ProcessingStatus, db_setup
-)
-from gnuboat.common.webservice.HttpErrors import (
-    GnuboatBadRequest
-)
-from gnuboat.mapservice_impl.tasks.tasks import log_process
-
-
-def setup():
-    db_setup()
-
-    print("CREATING DATABASE DEMO CONTENT...")
-    with db.session.no_autoflush:
-        test_user_john = None
-        query = User.query.filter_by(username='john').all()
-        if len(query) == 1:
-            test_user_john = query[0]
-        else:
-            test_user_john = User.factory(
-                'john', 'testpass2', 'john@example.org'
-            )
-            test_user_john.activation_code = 'dac9630aec642a428cd73f4be0a03569'
-            test_user_john.license_accepted = True
-            db.session.add(test_user_john)
-            db.session.commit()
-
-        test_user_jane = None
-        query = User.query.filter_by(username='jane').all()
-        if len(query) == 1:
-            test_user_jane = query[0]
-        else:
-            test_user_jane = User.factory(
-                'jane', 'testpass', 'jane@example.org'
-            )
-            test_user_jane.activated = True
-            test_user_jane.first_name = 'Jane'
-            test_user_jane.license_accepted = True
-            db.session.add(test_user_jane)
-            db.session.commit()
-
-        if len(ApiKey.query.filter_by(key='DelApiKey4711').all()) < 1:
-            db.session.add(ApiKey(user=test_user_jane, key='DelApiKey4711'))
-            db.session.commit()
-        if len(ApiKey.query.filter_by(key='test_key_jane').all()) < 1:
-            db.session.add(ApiKey(user=test_user_jane, key='test_key_jane'))
-            db.session.commit()
-
-        mississippi = None
-        query = Water.query.filter_by(name='Mississippi').all()
-        if len(query) == 1:
-            mississippi = query[0]
-        else:
-            mississippi = Water(
-                name='Mississippi',
-                manager=test_user_jane,
-                osm_id=1756854,
-                osm_type=OsmType.Relation
-            )
-            db.session.add(mississippi)
-            db.session.commit()
-
-        if len(Water.query.filter_by(name='Forggensee').all()) < 1:
-            forggensee = Water(
-                name='Forggensee',
-                manager=test_user_john,
-                osm_id=897899,
-                osm_type=OsmType.Relation
-            )
-            db.session.add(forggensee)
-            db.session.commit()
-
-        pfuhlersee = None
-        query = Water.query.filter_by(name='Pfuhler See').all()
-        if len(query) == 1:
-            pfuhlersee = query[0]
-        else:
-            pfuhlersee = Water(
-                name='Pfuhler See',
-                manager=test_user_jane,
-                osm_id=225888565,
-                osm_type=OsmType.Way
-            )
-            db.session.add(pfuhlersee)
-            db.session.commit()
-
-        new_orleans = None
-        query = Gauge.query.filter_by(name='New Orleans').all()
-        if len(query) == 1:
-            new_orleans = query[0]
-        else:
-            new_orleans = Gauge(
-                name='New Orleans',
-                manager=test_user_jane,
-                water=mississippi,
-                location='SRID=4326;POINT(-90.136111 29.934722)',
-                reference_water_level_gauge_height=3
-            )
-            db.session.add(new_orleans)
-            db.session.commit()
-
-        pfuhlersee_gauge = None
-        query = Gauge.query.filter_by(name='Stairs at Kiosk').all()
-        if len(query) == 1:
-            pfuhlersee_gauge = query[0]
-        else:
-            pfuhlersee_gauge = Gauge(
-                name='Stairs at Kiosk',
-                manager=test_user_jane,
-                water=pfuhlersee,
-                location='SRID=4326;POINT(10.0427 48.4275)',
-                reference_water_level_gauge_height=0.4,
-                comment=('Level zero is the level of the step '
-                         'where the handrail is fixed.')
-            )
-            db.session.add(pfuhlersee_gauge)
-            db.session.commit()
-
-        gnuboat_one = None
-        query = Device.query.filter_by(name='GnuBoat 1').all()
-        if len(query) == 1:
-            gnuboat_one = query[0]
-        else:
-            gnuboat_one = Device(
-                name='GnuBoat 1',
-                owner=test_user_jane,
-                sensor_depth=0.2,
-                comment='SUP attachment'
-            )
-            db.session.add(gnuboat_one)
-            db.session.commit()
-
-        log_file = 'sample-logs/nmea0183-2017-12-09.log'
-        sample_log = os.path.join('/usr/share/doc/gnuboat', log_file)
-        if os.path.isfile(sample_log):
-            _sample_log_add(
-                pfuhlersee, pfuhlersee_gauge, 0, gnuboat_one, test_user_jane,
-                sample_log
-            )
-        else:
-            sample_log = os.path.join(
-                os.path.dirname(__file__), '../../../../../../', log_file
-            )
-            if os.path.isfile(sample_log):
-                _sample_log_add(
-                    pfuhlersee, pfuhlersee_gauge, 0, gnuboat_one,
-                    test_user_jane, sample_log
-                )
-            else:
-                print('Demo log not found --> Skipping')
-
-        print("...Finished")
-
-
-def _sample_log_add(water, gauge, gauge_height, device, submitter, log_file):
-    if len(Log.query.filter_by(submitter=submitter).all()) > 0:
-        return None
-
-    log = Log(
-        submitter=submitter,
-        water=water,
-        device=device,
-        gauge=gauge,
-        gauge_height=0,
-        comment='Demo Log from {}'.format(log_file)
-    )
-    db.session.add(log)
-    db.session.commit()
-
-    if ('CELERY_BROKER_URL' not in flask.current_app.config or
-        not flask.current_app.config[
-           'CELERY_BROKER_URL']):
-        print('Do not add log, since their is no CELERY_BROKER_URL configured')
-        return log
-
-    with open(log_file, 'r') as logfile:
-        data = logfile.read()
-
-    processing_state = ProcessingStatus.query.filter_by(
-        label='Queued for Parsing'
-    ).all()
-    if len(processing_state) != 1:
-        raise GnuboatBadRequest(
-            detail='Processing status Queued for Parsing not found database'
-        )
-    processing_state = processing_state[0]
-
-    # Add Log to Queued table and change the processing state of Log
-    queue = Queue(log=log)
-    db.session.add(queue)
-    log.processingstatus = processing_state
-    db.session.commit()
-
-    # request log parsing
-    log_process.delay(log.id, data)
-    return log
Index: src/gnuboat/mapservice_impl/demo/MapserviceEntry.py
===================================================================
--- src/gnuboat/mapservice_impl/demo/MapserviceEntry.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ 	(revision )
@@ -1,54 +1,0 @@
-# -*- coding: utf-8 -*-
-'''
-    Copyright (C) 2020 EngSaS - 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 re
-import sys
-from pkg_resources import load_entry_point
-from gunicorn.app.wsgiapp import run
-import os
-
-from gnuboat.mapservice_impl import (
-    app, application, setup_app, config_object
-)
-
-
-def gunicorn_app():
-    template_folder = os.path.join(os.path.dirname(__file__), 'templates')
-    setup_app(
-        'GNUBoat Mapservice API',
-        config_object,
-        template_folder=template_folder
-    )
-    return app
-
-
-def main():
-    # Add need configuration options
-    # sys.argv.append('--workers=2')
-    if not any('bind' in x for x in sys.argv):
-        sys.argv.append('--bind=localhost:8080')
-    sys.argv.append(
-        'gnuboat.mapservice_impl.demo.MapserviceEntry:gunicorn_app()')
-
-    # Copied from /usr/bin/gunicorn
-    sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
-    sys.exit(run())
-
-
-if __name__ == '__main__':
-    main
Index: src/gnuboat/mapservice_impl/demo/celery_entry.py
===================================================================
--- src/gnuboat/mapservice_impl/demo/celery_entry.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/mapservice_impl/demo/celery_entry.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,41 @@
+# -*- coding: utf-8 -*-
+'''
+    Copyright (C) 2016 - 2020 EngSaS - 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 re
+import sys
+from pkg_resources import load_entry_point
+
+
+def main():
+    # Add need configuration options
+    sys.argv.append('-A')
+    sys.argv.append('gnuboat.mapservice_impl.celery_worker:celery')
+    sys.argv.append('worker')
+    sys.argv.append('-l')
+    sys.argv.append('info')
+    sys.argv.append('-E')
+    sys.argv.append('-B')
+
+    # Copied from /usr/bin/celery
+    sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
+    sys.exit(
+        load_entry_point('celery', 'console_scripts', 'celery')()
+    )
+
+if __name__ == '__main__':
+    main
Index: src/gnuboat/mapservice_impl/demo/db_setup.py
===================================================================
--- src/gnuboat/mapservice_impl/demo/db_setup.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/mapservice_impl/demo/db_setup.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,218 @@
+'''
+    Copyright (C) 2019 - 2020 EngSaS - 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 os
+import pytz
+import flask
+
+from gnuboat.mapservice_impl.database.model import (
+    db, User, ApiKey, Water,
+    OsmType, Gauge, Device, Log, Queue, ProcessingStatus, db_setup
+)
+from gnuboat.common.webservice.http_errors import (
+    GnuboatBadRequest
+)
+from gnuboat.mapservice_impl.tasks.tasks import log_process
+
+
+def setup():
+    db_setup()
+
+    print("CREATING DATABASE DEMO CONTENT...")
+    with db.session.no_autoflush:
+        test_user_john = None
+        query = User.query.filter_by(username='john').all()
+        if len(query) == 1:
+            test_user_john = query[0]
+        else:
+            test_user_john = User.factory(
+                'john', 'testpass2', 'john@example.org'
+            )
+            test_user_john.activation_code = 'dac9630aec642a428cd73f4be0a03569'
+            test_user_john.license_accepted = True
+            db.session.add(test_user_john)
+            db.session.commit()
+
+        test_user_jane = None
+        query = User.query.filter_by(username='jane').all()
+        if len(query) == 1:
+            test_user_jane = query[0]
+        else:
+            test_user_jane = User.factory(
+                'jane', 'testpass', 'jane@example.org'
+            )
+            test_user_jane.activated = True
+            test_user_jane.first_name = 'Jane'
+            test_user_jane.license_accepted = True
+            db.session.add(test_user_jane)
+            db.session.commit()
+
+        if len(ApiKey.query.filter_by(key='DelApiKey4711').all()) < 1:
+            db.session.add(ApiKey(user=test_user_jane, key='DelApiKey4711'))
+            db.session.commit()
+        if len(ApiKey.query.filter_by(key='test_key_jane').all()) < 1:
+            db.session.add(ApiKey(user=test_user_jane, key='test_key_jane'))
+            db.session.commit()
+
+        mississippi = None
+        query = Water.query.filter_by(name='Mississippi').all()
+        if len(query) == 1:
+            mississippi = query[0]
+        else:
+            mississippi = Water(
+                name='Mississippi',
+                manager=test_user_jane,
+                osm_id=1756854,
+                osm_type=OsmType.Relation
+            )
+            db.session.add(mississippi)
+            db.session.commit()
+
+        if len(Water.query.filter_by(name='Forggensee').all()) < 1:
+            forggensee = Water(
+                name='Forggensee',
+                manager=test_user_john,
+                osm_id=897899,
+                osm_type=OsmType.Relation
+            )
+            db.session.add(forggensee)
+            db.session.commit()
+
+        pfuhlersee = None
+        query = Water.query.filter_by(name='Pfuhler See').all()
+        if len(query) == 1:
+            pfuhlersee = query[0]
+        else:
+            pfuhlersee = Water(
+                name='Pfuhler See',
+                manager=test_user_jane,
+                osm_id=225888565,
+                osm_type=OsmType.Way
+            )
+            db.session.add(pfuhlersee)
+            db.session.commit()
+
+        new_orleans = None
+        query = Gauge.query.filter_by(name='New Orleans').all()
+        if len(query) == 1:
+            new_orleans = query[0]
+        else:
+            new_orleans = Gauge(
+                name='New Orleans',
+                manager=test_user_jane,
+                water=mississippi,
+                location='SRID=4326;POINT(-90.136111 29.934722)',
+                reference_water_level_gauge_height=3
+            )
+            db.session.add(new_orleans)
+            db.session.commit()
+
+        pfuhlersee_gauge = None
+        query = Gauge.query.filter_by(name='Stairs at Kiosk').all()
+        if len(query) == 1:
+            pfuhlersee_gauge = query[0]
+        else:
+            pfuhlersee_gauge = Gauge(
+                name='Stairs at Kiosk',
+                manager=test_user_jane,
+                water=pfuhlersee,
+                location='SRID=4326;POINT(10.0427 48.4275)',
+                reference_water_level_gauge_height=0.4,
+                comment=('Level zero is the level of the step '
+                         'where the handrail is fixed.')
+            )
+            db.session.add(pfuhlersee_gauge)
+            db.session.commit()
+
+        gnuboat_one = None
+        query = Device.query.filter_by(name='GnuBoat 1').all()
+        if len(query) == 1:
+            gnuboat_one = query[0]
+        else:
+            gnuboat_one = Device(
+                name='GnuBoat 1',
+                owner=test_user_jane,
+                sensor_depth=0.2,
+                comment='SUP attachment'
+            )
+            db.session.add(gnuboat_one)
+            db.session.commit()
+
+        log_file = 'sample-logs/nmea0183-2017-12-09.log'
+        sample_log = os.path.join('/usr/share/doc/gnuboat', log_file)
+        if os.path.isfile(sample_log):
+            _sample_log_add(
+                pfuhlersee, pfuhlersee_gauge, 0, gnuboat_one, test_user_jane,
+                sample_log
+            )
+        else:
+            sample_log = os.path.join(
+                os.path.dirname(__file__), '../../../../../../', log_file
+            )
+            if os.path.isfile(sample_log):
+                _sample_log_add(
+                    pfuhlersee, pfuhlersee_gauge, 0, gnuboat_one,
+                    test_user_jane, sample_log
+                )
+            else:
+                print('Demo log not found --> Skipping')
+
+        print("...Finished")
+
+
+def _sample_log_add(water, gauge, gauge_height, device, submitter, log_file):
+    if len(Log.query.filter_by(submitter=submitter).all()) > 0:
+        return None
+
+    log = Log(
+        submitter=submitter,
+        water=water,
+        device=device,
+        gauge=gauge,
+        gauge_height=0,
+        comment='Demo Log from {}'.format(log_file)
+    )
+    db.session.add(log)
+    db.session.commit()
+
+    if ('CELERY_BROKER_URL' not in flask.current_app.config or
+        not flask.current_app.config[
+           'CELERY_BROKER_URL']):
+        print('Do not add log, since their is no CELERY_BROKER_URL configured')
+        return log
+
+    with open(log_file, 'r') as logfile:
+        data = logfile.read()
+
+    processing_state = ProcessingStatus.query.filter_by(
+        label='Queued for Parsing'
+    ).all()
+    if len(processing_state) != 1:
+        raise GnuboatBadRequest(
+            detail='Processing status Queued for Parsing not found database'
+        )
+    processing_state = processing_state[0]
+
+    # Add Log to Queued table and change the processing state of Log
+    queue = Queue(log=log)
+    db.session.add(queue)
+    log.processingstatus = processing_state
+    db.session.commit()
+
+    # request log parsing
+    log_process.delay(log.id, data)
+    return log
Index: src/gnuboat/mapservice_impl/demo/service_entry.py
===================================================================
--- src/gnuboat/mapservice_impl/demo/service_entry.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/mapservice_impl/demo/service_entry.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,54 @@
+# -*- coding: utf-8 -*-
+'''
+    Copyright (C) 2020 EngSaS - 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 re
+import sys
+from pkg_resources import load_entry_point
+from gunicorn.app.wsgiapp import run
+import os
+
+from gnuboat.mapservice_impl import (
+    app, application, setup_app, config_object
+)
+
+
+def gunicorn_app():
+    template_folder = os.path.join(os.path.dirname(__file__), 'templates')
+    setup_app(
+        'GNUBoat Mapservice API',
+        config_object,
+        template_folder=template_folder
+    )
+    return app
+
+
+def main():
+    # Add need configuration options
+    # sys.argv.append('--workers=2')
+    if not any('bind' in x for x in sys.argv):
+        sys.argv.append('--bind=localhost:8080')
+    sys.argv.append(
+        'gnuboat.mapservice_impl.demo.service_entry:gunicorn_app()')
+
+    # Copied from /usr/bin/gunicorn
+    sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
+    sys.exit(run())
+
+
+if __name__ == '__main__':
+    main
Index: src/gnuboat/mapservice_impl/mapservice.py
===================================================================
--- src/gnuboat/mapservice_impl/mapservice.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/mapservice_impl/mapservice.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,30 @@
+'''
+    Copyright (C) 2020 EngSaS - 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 os
+
+from gnuboat.mapservice_impl import (
+    application as app,
+    config_object, setup_app
+)
+
+template_folder = os.path.join(os.path.dirname(__file__), 'templates')
+setup_app(
+    'GNUBoat Mapservice API',
+    config_object,
+    template_folder=template_folder
+)
Index: src/gnuboat/mapservice_impl/security/Security.py
===================================================================
--- src/gnuboat/mapservice_impl/security/Security.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ 	(revision )
@@ -1,39 +1,0 @@
-'''
-    Copyright (C) 2019 - 2020 EngSaS - 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/>.
-'''
-from ..database.Model import ApiKey, User
-
-
-def auth_basic(username, password, required_scopes=None):
-    user = User.query.filter_by(username=username).all()
-    if len(user) != 1:
-        return None
-    if user[0].password_verify(password):
-        return {'sub': user[0].username}
-    return None
-
-
-def auth_api(apikey, required_scopes=None):
-    keys = ApiKey.query.filter_by(key=apikey).all()
-    if len(keys) != 1:
-        return None
-
-    key_db = keys[0]
-    if apikey == key_db.key:
-        return {'sub': key_db.user.username}
-
-    # optional: raise exception for custom error response
-    return None
Index: src/gnuboat/mapservice_impl/security/security.py
===================================================================
--- src/gnuboat/mapservice_impl/security/security.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/mapservice_impl/security/security.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,39 @@
+'''
+    Copyright (C) 2019 - 2020 EngSaS - 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/>.
+'''
+from ..database.model import ApiKey, User
+
+
+def auth_basic(username, password, required_scopes=None):
+    user = User.query.filter_by(username=username).all()
+    if len(user) != 1:
+        return None
+    if user[0].password_verify(password):
+        return {'sub': user[0].username}
+    return None
+
+
+def auth_api(apikey, required_scopes=None):
+    keys = ApiKey.query.filter_by(key=apikey).all()
+    if len(keys) != 1:
+        return None
+
+    key_db = keys[0]
+    if apikey == key_db.key:
+        return {'sub': key_db.user.username}
+
+    # optional: raise exception for custom error response
+    return None
Index: src/gnuboat/mapservice_impl/tasks/tasks.py
===================================================================
--- src/gnuboat/mapservice_impl/tasks/tasks.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ src/gnuboat/mapservice_impl/tasks/tasks.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -34,15 +34,15 @@
 import mercantile
 
-from gnuboat.common.datahandler import loghandler
-from gnuboat.common.spatial import tilegenerator
-from gnuboat.common.spatial.tilegenerator import (
+from gnuboat.common.datahandler import log_handler as loghandler
+from gnuboat.common.spatial import tile_generator as tilegenerator
+from gnuboat.common.spatial.tile_generator import (
     RasterSlice, LngLatBbox, ZoomRange
 )
 
 from gnuboat.mapservice_impl import mail, celery as celery_app
-from gnuboat.mapservice_impl.database.Model import (
+from gnuboat.mapservice_impl.database.model import (
     User, Log, LogEntry, Water, ProcessingStatus, Queue, db
 )
-from gnuboat.mapservice_impl.tasks.tileconfig import TileConfig
+from gnuboat.mapservice_impl.tasks.tile_config import TileConfig
 
 
Index: src/gnuboat/mapservice_impl/tasks/tile_config.py
===================================================================
--- src/gnuboat/mapservice_impl/tasks/tile_config.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/mapservice_impl/tasks/tile_config.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,52 @@
+# -*- coding: utf-8 -*-
+'''
+    Copyright (C) 2020 EngSaS - 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/>.
+'''
+
+try:
+    from dataclasses import dataclass
+    from typing import List
+
+    @dataclass
+    class TileConfig:
+        cache_path: str
+        sizes: List[int]
+        densities: List[int]
+        densitiy_base: int
+        points_age_max: int
+        zoom_range: List[int]
+        raster_file_size_max: [int]
+        skip_empty: bool
+
+except ImportError:
+
+    class TileConfig:
+        """
+            Workaround for @dataclass, until python 3.7 is available
+            in main distros
+        """
+        def __init__(
+            self, cache_path, sizes, densities, densitiy_base, points_age_max,
+            zoom_range, raster_file_size_max, skip_empty
+        ):
+            self.cache_path = cache_path
+            self.sizes = sizes
+            self.densities = densities
+            self.densitiy_base = densitiy_base
+            self.points_age_max = points_age_max
+            self.zoom_range = zoom_range
+            self.raster_file_size_max = raster_file_size_max
+            self.skip_empty = skip_empty
Index: src/gnuboat/mapservice_impl/tasks/tileconfig.py
===================================================================
--- src/gnuboat/mapservice_impl/tasks/tileconfig.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ 	(revision )
@@ -1,52 +1,0 @@
-# -*- coding: utf-8 -*-
-'''
-    Copyright (C) 2020 EngSaS - 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/>.
-'''
-
-try:
-    from dataclasses import dataclass
-    from typing import List
-
-    @dataclass
-    class TileConfig:
-        cache_path: str
-        sizes: List[int]
-        densities: List[int]
-        densitiy_base: int
-        points_age_max: int
-        zoom_range: List[int]
-        raster_file_size_max: [int]
-        skip_empty: bool
-
-except ImportError:
-
-    class TileConfig:
-        """
-            Workaround for @dataclass, until python 3.7 is available
-            in main distros
-        """
-        def __init__(
-            self, cache_path, sizes, densities, densitiy_base, points_age_max,
-            zoom_range, raster_file_size_max, skip_empty
-        ):
-            self.cache_path = cache_path
-            self.sizes = sizes
-            self.densities = densities
-            self.densitiy_base = densitiy_base
-            self.points_age_max = points_age_max
-            self.zoom_range = zoom_range
-            self.raster_file_size_max = raster_file_size_max
-            self.skip_empty = skip_empty
Index: src/gnuboat/mapservice_impl/tests/__init__.py
===================================================================
--- src/gnuboat/mapservice_impl/tests/__init__.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ src/gnuboat/mapservice_impl/tests/__init__.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -17,72 +17,67 @@
 
 import logging
-
-import flask
 import connexion
 from flask_cors import CORS
 from flask_mail import Mail
+from celery import Celery
 from sqlalchemy.event import listen
-from celery import Celery
+from werkzeug.utils import import_string
 import tempfile
 import os
 from PIL import Image
-import shutil
 
-from gnuboat.mapservice.encoder import JSONEncoder
-from gnuboat.mapservice_impl.database.Model import (
+from gnuboat.mapservice_impl.database.model import (
     db, db_setup, load_spatialite
 )
 from gnuboat.mapservice_impl.tests import db_test_setup
+from gnuboat.mapservice_impl import setup_app
 
 
-def create_app(testcase):
+def check_key(key, value, data):
+    assert key in data, "{} not in data {}".format(key, data)
+    assert data[key] == value, "{} = {}".format(value, data[key])
+
+
+def create_app():
     logging.getLogger('connexion.operation').setLevel('ERROR')
-    app = connexion.App(
-        __name__,
-        specification_dir='../../mapservice/openapi/'
-    )
+    app = connexion.App(__name__,
+                        specification_dir='../../mapservice/openapi/')
     application = app.app
     CORS(application)
     mail = Mail()
-    application.json_encoder = JSONEncoder
-    app.add_api('openapi.yaml')
+    celery = Celery(__name__, broker='')
+    setup_app(__name__,
+              import_string('gnuboat.mapservice_impl.config.TestingConfig'),
+              os.path.join(os.path.dirname(__file__),
+                           '../../mapservice_impl/templates'),
+              connexion_app=app)
 
-    application.config.from_object(
-        'gnuboat.mapservice_impl.Config.TestingConfig')
-    application.template_folder = os.path.join(
-        os.path.dirname(__file__),
-        '../../mapservice_impl/templates'
-    )
-    celery = Celery(__name__, broker=application.config['CELERY_BROKER_URL'])
-    celery.config_from_object(application.config)
-    mail.init_app(application)
-    db.init_app(application)
-    application.app_context().push()
+    _create_test_tile(application)
 
-    _create_test_tile(testcase, application)
-
-    return application
+    return app
 
 
-def setUp(testcase):
-    listen(db.engine, 'connect', load_spatialite)
-    db.drop_all()
-    # create the tables whether the database already exists or not
-    db_setup(True)
-    testcase.db_content = db_test_setup.DatabaseContent()
-    testcase.db_content.setup()
+def setup(application):
+    with application.app_context():
+        listen(db.engine, 'connect', load_spatialite)
+        db.drop_all()
+        # create the tables whether the database already exists or not
+        db_setup(True)
+        application.config.db_content = db_test_setup.DatabaseContent()
+        application.config.db_content.setup()
 
 
-def tearDown(testcase):
-    db.session.remove()
-    db.drop_all()
-    shutil.rmtree(testcase.tiles_cache)
+def teardown(application):
+    with application.app_context():
+        db.session.remove()
+        db.drop_all()
 
 
-def _create_test_tile(testcase, application):
-    testcase.tiles_cache = tempfile.mkdtemp(prefix='gnuboat-tests')
-    application.config['TILES_CACHE_PATH'] = testcase.tiles_cache
+def _create_test_tile(application):
+    application.config.tiles_cache = tempfile.mkdtemp(prefix='gnuboat-tests')
+    application.config['TILES_CACHE_PATH'] = application.config.tiles_cache
 
-    tile_path = os.path.join(testcase.tiles_cache, '100_100/256/15/17298/')
+    tile_path = os.path.join(application.config.tiles_cache,
+                             '100_100/256/15/17298/')
     os.makedirs(tile_path)
     img = Image.new('RGBA', (100, 100), (255, 0, 0, 0))
Index: src/gnuboat/mapservice_impl/tests/conftest.py
===================================================================
--- src/gnuboat/mapservice_impl/tests/conftest.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/mapservice_impl/tests/conftest.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,40 @@
+'''
+    Copyright (C) 2020 EngSaS - 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 pytest
+import shutil
+
+from gnuboat.mapservice_impl.tests import create_app, setup, teardown
+from gnuboat.mapservice_impl.database.model import db
+
+
+@pytest.fixture(scope="module")
+def app():
+    connexion_app = create_app()
+    app = connexion_app.app
+
+    yield app
+
+    shutil.rmtree(app.config.tiles_cache)
+    del app
+    del connexion_app
+
+
+@pytest.fixture(scope="function", autouse=True)
+def testcase_reset(app):
+    setup(app)
+    yield True
+    teardown(app)
Index: src/gnuboat/mapservice_impl/tests/db_test_setup.py
===================================================================
--- src/gnuboat/mapservice_impl/tests/db_test_setup.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ src/gnuboat/mapservice_impl/tests/db_test_setup.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -20,9 +20,9 @@
 import flask
 
-from gnuboat.mapservice_impl.database.Model import (
+from gnuboat.mapservice_impl.database.model import (
     db, User, ApiKey, Water,
     OsmType, Gauge, Device, Log, Queue, ProcessingStatus, db_setup
 )
-from gnuboat.mapservice_impl.demo import DbSetup as demoDbSetup
+from gnuboat.mapservice_impl.demo import db_setup as demodbsetup
 from gnuboat.mapservice_impl.tasks.tasks import log_process
 
@@ -41,12 +41,13 @@
         print("CREATING DATABASE TEST CONTENT...")
         with db.session.no_autoflush:
-            self.test_user = User.factory(
+            test_user = User.factory(
                 'autotests', 'autotests', 'auto@example.org'
             )
-            self.test_user.activated = True
-            self.test_user.first_name = 'Autotests'
-            self.test_user.license_accepted = True
-            db.session.add(self.test_user)
+            test_user.activated = True
+            test_user.first_name = 'Autotests'
+            test_user.license_accepted = True
+            db.session.add(test_user)
             db.session.commit()
+            self.test_user = test_user.to_dict()
 
             user_activation = User.factory(
@@ -62,40 +63,44 @@
             db.session.commit()
 
-            db.session.add(ApiKey(user=self.test_user, key='test_key'))
-            db.session.add(ApiKey(user=self.test_user, key='test_key_delete'))
+            db.session.add(ApiKey(user=test_user, key='test_key'))
+            db.session.add(ApiKey(user=test_user, key='test_key_delete'))
             db.session.commit()
 
-            self.test_water = Water(
+            test_water = Water(
                 name='Test Water',
-                manager=self.test_user,
+                manager=test_user,
                 osm_id=1756854,
                 osm_type=OsmType.Relation
             )
-            db.session.add(self.test_water)
+            db.session.add(test_water)
             db.session.commit()
+            self.test_water = test_water.to_dict()
 
-            self.test_gauge = Gauge(
+            test_gauge = Gauge(
                 name='test_gauge',
-                manager=self.test_user,
-                water=self.test_water,
+                manager=test_user,
+                water=test_water,
                 location='SRID=4326;POINT(-90.136111 29.934722)',
                 reference_water_level_gauge_height=3
             )
-            db.session.add(self.test_gauge)
+            db.session.add(test_gauge)
             db.session.commit()
+            self.test_gauge = test_gauge.to_dict()
 
-            self.test_device = Device(
-                name='Test Device', owner=self.test_user, sensor_depth=0.2
+            test_device = Device(
+                name='Test Device', owner=test_user, sensor_depth=0.2
             )
-            db.session.add(self.test_device)
+            db.session.add(test_device)
             db.session.commit()
+            self.test_device = test_device.to_dict()
 
             log_file = os.path.join(
                 os.path.dirname(__file__), 'data/nmea0183-2017-12-09.log'
             )
-            self.test_log = demoDbSetup._sample_log_add(
-                self.test_water, self.test_gauge, 0, self.test_device,
-                self.test_user, log_file
+            test_log = demodbsetup._sample_log_add(
+                test_water, test_gauge, 0, test_device,
+                test_user, log_file
             )
+            self.test_log = test_log.meta_data()
 
             print("...Finished")
Index: src/gnuboat/mapservice_impl/tests/test_logs.py
===================================================================
--- src/gnuboat/mapservice_impl/tests/test_logs.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ src/gnuboat/mapservice_impl/tests/test_logs.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -16,158 +16,156 @@
 '''
 
-import unittest
+import pytest
 import json
-import os
 
-from gnuboat.mapservice.test import BaseTestCase
+from . import check_key
 
 
-class TestLogs(BaseTestCase):
-    @classmethod
-    def setUpClass(self):
-        self.base_url = '/mapservice/v1/logs'
-
-    def test_get(self):
-        """Test case getting log (src)
-        """
-        headers = {'Accept': 'application/json'}
-        response = self.client.open(
-            '{}/{}'.format(self.base_url, self.db_content.test_log.id),
-            method='GET',
-            headers=headers
-        )
-        assert response.status_code == 200
-        data = json.loads(response.data)
-        assert len(data) == 2
-        assert 'entries' in data
-        assert 'metaData' in data
-        metaData = data['metaData']
-        assert "submitter" in metaData
-        self.check_key(
-            "submitter", self.db_content.test_log.submitter.username, metaData
-        )
-        assert 'water' in metaData
-        self.check_key(
-            "id", self.db_content.test_log.water.id, metaData['water']
-        )
-        self.check_key(
-            "label", self.db_content.test_log.water.name, metaData['water']
-        )
-        assert 'device' in metaData
-        self.check_key(
-            "id", self.db_content.test_log.device.id, metaData['device']
-        )
-        self.check_key(
-            "label", self.db_content.test_log.device.name, metaData['device']
-        )
-        assert 'gauge' in metaData
-        self.check_key(
-            "id", self.db_content.test_log.gauge.id, metaData['gauge']
-        )
-        self.check_key(
-            "label", self.db_content.test_log.gauge.name, metaData['gauge']
-        )
-        self.check_key(
-            "gaugeHeight", self.db_content.test_log.gauge_height, metaData
-        )
-
-    def test_get_by_manager(self):
-        """Test case getting log by submitter (src)
-        """
-        headers = {'Accept': 'application/json'}
-
-        response = self.client.open(
-            '{}?submitter=not_existent'.format(self.base_url),
-            method='GET',
-            headers=headers
-        )
-        assert response.status_code == 404, '{} != {}'.format(
-            response.status_code, 404
-        )
-
-        response = self.client.open(
-            '{}?submitter={}'.format(
-                self.base_url, self.db_content.test_log.submitter.username
-            ),
-            method='GET',
-            headers=headers
-        )
-        assert response.status_code == 200
-        data = json.loads(response.data)
-        assert len(data) == 1
-        data = data[0]
-        self.check_key(
-            "submitter", self.db_content.test_log.submitter.username, data
-        )
-        assert 'water' in data
-        self.check_key("id", self.db_content.test_log.water.id, data['water'])
-        self.check_key(
-            "label", self.db_content.test_log.water.name, data['water']
-        )
-        assert 'device' in data
-        self.check_key(
-            "id", self.db_content.test_log.device.id, data['device']
-        )
-        self.check_key(
-            "label", self.db_content.test_log.device.name, data['device']
-        )
-        assert 'gauge' in data
-        self.check_key("id", self.db_content.test_log.gauge.id, data['gauge'])
-        self.check_key(
-            "label", self.db_content.test_log.gauge.name, data['gauge']
-        )
-        self.check_key(
-            "gaugeHeight", self.db_content.test_log.gauge_height, data
-        )
-
-    def test_create_log(self):
-        """Test case create log (src)
-        """
-        headers = {
-            'X-API-KEY': 'test_key',
-            'Accept': 'application/json',
-            'Content-Type': 'application/json'
-        }
-        logCreation = {
-            'water': 1,
-            'device': 1,
-            'gauge': 1,
-            'gaugeHeight': 1.0,
-            'comment': 'Log from unit test'
-        }
-
-        response = self.client.open(
-            self.base_url,
-            method='POST',
-            headers=headers,
-            data=json.dumps(logCreation),
-            content_type='application/json'
-        )
-        assert response.status_code == 200
-        data = response.get_json()
-        assert len(data) >= 7
-        self.check_key("logId", 2, data)
-        assert 'water' in data
-        self.check_key("id", logCreation['water'], data['water'])
-        assert 'device' in data
-        self.check_key("id", logCreation['device'], data['device'])
-        assert 'gauge' in data
-        self.check_key("id", logCreation['gauge'], data['gauge'])
-        self.check_key("gaugeHeight", logCreation['gaugeHeight'], data)
-        self.check_key("comment", logCreation['comment'], data)
-
-        # could not be tested without running CELERY_BROKER
-        # filename = '{}/data/nmea0183-2017-12-09.log'.format(
-        #   os.path.dirname(os.path.abspath(__file__)))
-        # fileContent = open(filename, 'rb')
-        # headers["Accept"] = "application/geo+json"
-        # response = self.client.post(
-        # "{}/{}".format(self.base_url, data["logId"]),
-        # data = fileContent,
-        # headers = headers
-        # )
-        # assert response.status_code == 200
+base_url = '/mapservice/v1/logs'
 
 
-if __name__ == '__main__':
-    unittest.main()
+def test_get(client, config):
+    """Test case getting log (src)
+    """
+    headers = {'Accept': 'application/json'}
+    response = client.open(
+        '{}/{}'.format(base_url, config.db_content.test_log['logId']),
+        method='GET',
+        headers=headers
+    )
+    assert response.status_code == 200
+    data = response.json
+    assert len(data) == 2
+    assert 'entries' in data
+    assert 'metaData' in data
+    metaData = data['metaData']
+    assert "submitter" in metaData
+    check_key(
+        "submitter", config.db_content.test_log['submitter'], metaData
+    )
+    assert 'water' in metaData
+    check_key(
+        "id", config.db_content.test_log['water']['id'], metaData['water']
+    )
+    check_key(
+        "label", config.db_content.test_log['water']['label'],
+        metaData['water']
+    )
+    assert 'device' in metaData
+    check_key(
+        "id", config.db_content.test_log['device']['id'], metaData['device']
+    )
+    check_key(
+        "label", config.db_content.test_log['device']['label'],
+        metaData['device']
+    )
+    assert 'gauge' in metaData
+    check_key(
+        "id", config.db_content.test_log['gauge']['id'], metaData['gauge']
+    )
+    check_key(
+        "label", config.db_content.test_log['gauge']['label'],
+        metaData['gauge']
+    )
+    check_key(
+        "gaugeHeight", config.db_content.test_log['gaugeHeight'], metaData
+    )
+
+
+def test_get_by_manager(client, config):
+    """Test case getting log by submitter (src)
+    """
+    headers = {'Accept': 'application/json'}
+
+    response = client.open(
+        '{}?submitter=not_existent'.format(base_url),
+        method='GET',
+        headers=headers
+    )
+    assert response.status_code == 404, '{} != {}'.format(
+        response.status_code, 404
+    )
+
+    response = client.open(
+        '{}?submitter={}'.format(
+            base_url, config.db_content.test_log['submitter']
+        ),
+        method='GET',
+        headers=headers
+    )
+    assert response.status_code == 200
+    data = response.json
+    assert len(data) == 1
+    data = data[0]
+    check_key(
+        "submitter", config.db_content.test_log['submitter'], data
+    )
+    assert 'water' in data
+    check_key("id", config.db_content.test_log['water']['id'], data['water'])
+    check_key(
+        "label", config.db_content.test_log['water']['label'], data['water']
+    )
+    assert 'device' in data
+    check_key(
+        "id", config.db_content.test_log['device']['id'], data['device']
+    )
+    check_key(
+        "label", config.db_content.test_log['device']['label'], data['device']
+    )
+    assert 'gauge' in data
+    check_key("id", config.db_content.test_log['gauge']['id'], data['gauge'])
+    check_key(
+        "label", config.db_content.test_log['gauge']['label'], data['gauge']
+    )
+    check_key(
+        "gaugeHeight", config.db_content.test_log['gaugeHeight'], data
+    )
+
+
+def test_create_log(client):
+    """Test case create log (src)
+    """
+    headers = {
+        'X-API-KEY': 'test_key',
+        'Accept': 'application/json',
+        'Content-Type': 'application/json'
+    }
+    logCreation = {
+        'water': 1,
+        'device': 1,
+        'gauge': 1,
+        'gaugeHeight': 1.0,
+        'comment': 'Log from unit test'
+    }
+
+    response = client.open(
+        base_url,
+        method='POST',
+        headers=headers,
+        data=json.dumps(logCreation),
+        content_type='application/json'
+    )
+    assert response.status_code == 201
+    data = response.json
+    assert len(data) >= 7
+    check_key("logId", 2, data)
+    assert 'water' in data
+    check_key("id", logCreation['water'], data['water'])
+    assert 'device' in data
+    check_key("id", logCreation['device'], data['device'])
+    assert 'gauge' in data
+    check_key("id", logCreation['gauge'], data['gauge'])
+    check_key("gaugeHeight", logCreation['gaugeHeight'], data)
+    check_key("comment", logCreation['comment'], data)
+
+    # could not be tested without running CELERY_BROKER
+    # filename = '{}/data/nmea0183-2017-12-09.log'.format(
+    #   os.path.dirname(os.path.abspath(__file__)))
+    # fileContent = open(filename, 'rb')
+    # headers["Accept"] = "application/geo+json"
+    # response = self.client.post(
+    # "{}/{}".format(self.base_url, data["logId"]),
+    # data = fileContent,
+    # headers = headers
+    # )
+    # assert response.status_code == 200
Index: src/gnuboat/mapservice_impl/tests/test_users.py
===================================================================
--- src/gnuboat/mapservice_impl/tests/test_users.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ src/gnuboat/mapservice_impl/tests/test_users.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -16,79 +16,73 @@
 '''
 
-import unittest
+import pytest
 import json
 
-from gnuboat.mapservice.test import BaseTestCase
+from . import check_key
+
+base_url = '/mapservice/v1/user'
 
 
-class TestUsers(BaseTestCase):
-    @classmethod
-    def setUpClass(self):
-        self.base_url = '/mapservice/v1/user'
+def test_users_get(client):
+    """Test case for getting users (src)
+    """
+    headers = {}
+    response = client.open(
+        base_url, method='GET', headers=headers
+    )
+    assert response.status_code == 401
 
-    def test_users_get(self):
-        """Test case for getting users (src)
-        """
-        headers = {}
-        response = self.client.open(
-            self.base_url, method='GET', headers=headers
-        )
-        assert response.status_code == 401
+    response = client.open(
+        base_url, method='GET', headers={'X-API-KEY': 'test_key'}
+    )
+    assert response.status_code == 200
+    data = response.json
+    check_key("username", "autotests", data)
+    check_key("firstName", "Autotests", data)
+    check_key("lastName", "", data)
+    check_key("email", "auto@example.org", data)
+    check_key("activated", True, data)
+    check_key("licenseAccepted", True, data)
 
-        response = self.client.open(
-            self.base_url, method='GET', headers={'X-API-KEY': 'test_key'}
-        )
-        assert response.status_code == 200
-        data = json.loads(response.data)
-        self.check_key("username", "autotests", data)
-        self.check_key("firstName", "Autotests", data)
-        self.check_key("lastName", "", data)
-        self.check_key("email", "auto@example.org", data)
-        self.check_key("activated", True, data)
-        self.check_key("licenseAccepted", True, data)
+    assert "apiKeys" in data
+    assert data["apiKeys"][0] == "test_key"
+    assert data["apiKeys"][1] == "test_key_delete"
 
-        assert "apiKeys" in data
-        assert data["apiKeys"][0] == "test_key"
-        assert data["apiKeys"][1] == "test_key_delete"
-
-        assert "password" not in data
-        assert "salt" not in data
-        assert "activationCode" not in data
-
-    def test_impl_users_register(self):
-        """Test case for users_register (Src)
-           Register a new user
-        """
-        user_creation = {
-            "username": "jane_doe",
-            "firstName": "Jane",
-            "lastName": "Doe",
-            "password": "1234",
-            "licenseAccepted": True,
-            "email": "jane.doe@example.org"
-        }
-        headers = {
-            'Accept': 'application/json',
-        }
-        response = self.client.open(
-            self.base_url,
-            method='POST',
-            headers=headers,
-            data=json.dumps(user_creation),
-            content_type='application/json'
-        )
-        assert response.status_code == 200
-        data = json.loads(response.data)
-        self.check_key("username", user_creation['username'], data)
-        self.check_key("firstName", user_creation['firstName'], data)
-        self.check_key("lastName", user_creation['lastName'], data)
-        self.check_key("email", user_creation['email'], data)
-        self.check_key("activated", False, data)
-        self.check_key("licenseAccepted", True, data)
-
-        assert 'apiKeys' in data
-        assert len(data['apiKeys']) == 0
+    assert "password" not in data
+    assert "salt" not in data
+    assert "activationCode" not in data
 
 
-if __name__ == '__main__':
-    unittest.main()
+def test_impl_users_register(client):
+    """Test case for users_register (Src)
+        Register a new user
+    """
+    user_creation = {
+        "username": "jane_doe",
+        "firstName": "Jane",
+        "lastName": "Doe",
+        "password": "1234",
+        "licenseAccepted": True,
+        "email": "jane.doe@example.org"
+    }
+    headers = {
+        'Accept': 'application/json',
+    }
+    response = client.open(
+        base_url,
+        method='POST',
+        headers=headers,
+        data=json.dumps(user_creation),
+        content_type='application/json'
+    )
+    assert response.status_code == 200
+    data = response.json
+    check_key("username", user_creation['username'], data)
+    check_key("firstName", user_creation['firstName'], data)
+    check_key("lastName", user_creation['lastName'], data)
+    check_key("email", user_creation['email'], data)
+    check_key("activated", False, data)
+    check_key("licenseAccepted", True, data)
+
+    assert 'apiKeys' in data
+    assert len(data['apiKeys']) == 0
Index: src/gnuboat/mapservice_impl/tests/test_waters.py
===================================================================
--- src/gnuboat/mapservice_impl/tests/test_waters.py	(revision d5199c99a93e42907020ef2d307843ef70bae033)
+++ src/gnuboat/mapservice_impl/tests/test_waters.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -16,150 +16,145 @@
 '''
 
-import unittest
-import json
+import pytest
 
-from gnuboat.mapservice.test import BaseTestCase
+from . import check_key
+
+base_url = '/mapservice/v1/waters'
 
 
-class TestWaters(BaseTestCase):
-    @classmethod
-    def setUpClass(self):
-        self.base_url = '/mapservice/v1/waters'
-
-    def test_get(self):
-        """Test case getting waters (src)
-        """
-        headers = {}
-        response = self.client.open(
-            self.base_url, method='GET', headers=headers
-        )
-        assert response.status_code == 200
-        data = json.loads(response.data)
-        assert len(data) == 1
-        data = data[0]
-        self.check_key(
-            "manager", self.db_content.test_water.manager.username, data
-        )
-        self.check_key("name", self.db_content.test_water.name, data)
-        self.check_key("waterId", self.db_content.test_water.id, data)
-        self.check_key("osmId", self.db_content.test_water.osm_id, data)
-        self.check_key(
-            "osmType", self.db_content.test_water.osm_type.name, data
-        )
-
-    def test_get_by_name(self):
-        """Test case getting waters by name (src)
-        """
-        headers = {}
-
-        response = self.client.open(
-            '{}?name=Bla'.format(self.base_url), method='GET', headers=headers
-        )
-        assert response.status_code == 200
-        data = json.loads(response.data)
-        assert len(data) == 0
-
-        response = self.client.open(
-            '{}?name={}'.format(
-                self.base_url, self.db_content.test_water.name[:3]
-            ),
-            method='GET',
-            headers=headers
-        )
-        assert response.status_code == 200
-        data = json.loads(response.data)
-        assert len(data) == 1
-        data = data[0]
-        self.check_key(
-            "manager", self.db_content.test_water.manager.username, data
-        )
-        self.check_key("name", self.db_content.test_water.name, data)
-        self.check_key("waterId", self.db_content.test_water.id, data)
-        self.check_key("osmId", self.db_content.test_water.osm_id, data)
-        self.check_key(
-            "osmType", self.db_content.test_water.osm_type.name, data
-        )
-
-    def test_get_by_manager(self):
-        """Test case getting waters by manager (src)
-        """
-        headers = {}
-
-        response = self.client.open(
-            '{}?manager=not_existent'.format(self.base_url),
-            method='GET',
-            headers=headers
-        )
-        assert response.status_code == 404, '{} != {}'.format(
-            response.status_code, 404
-        )
-
-        response = self.client.open(
-            '{}?manager={}'.format(
-                self.base_url, self.db_content.test_user.username
-            ),
-            method='GET',
-            headers=headers
-        )
-        assert response.status_code == 200
-        data = json.loads(response.data)
-        assert len(data) == 1
-        data = data[0]
-        self.check_key(
-            "manager", self.db_content.test_water.manager.username, data
-        )
-        self.check_key("name", self.db_content.test_water.name, data)
-        self.check_key("waterId", self.db_content.test_water.id, data)
-        self.check_key("osmId", self.db_content.test_water.osm_id, data)
-        self.check_key(
-            "osmType", self.db_content.test_water.osm_type.name, data
-        )
-
-    def test_get_by_name_manager(self):
-        """Test case getting waters by manager and water name (src)
-        """
-        headers = {}
-
-        response = self.client.open(
-            '{}?manager={}&name=Bla'.format(
-                self.base_url, self.db_content.test_user.username
-            ),
-            method='GET',
-            headers=headers
-        )
-        assert response.status_code == 200
-
-        response = self.client.open(
-            '{}?manager=john&name={}'.format(
-                self.base_url, self.db_content.test_water.name[:3]
-            ),
-            method='GET',
-            headers=headers
-        )
-        assert response.status_code == 404
-
-        response = self.client.open(
-            '{}?name={}&manager={}'.format(
-                self.base_url, self.db_content.test_water.name,
-                self.db_content.test_user.username
-            ),
-            method='GET',
-            headers=headers
-        )
-        assert response.status_code == 200
-        data = json.loads(response.data)
-        assert len(data) == 1
-        data = data[0]
-        self.check_key(
-            "manager", self.db_content.test_water.manager.username, data
-        )
-        self.check_key("name", self.db_content.test_water.name, data)
-        self.check_key("waterId", self.db_content.test_water.id, data)
-        self.check_key("osmId", self.db_content.test_water.osm_id, data)
-        self.check_key(
-            "osmType", self.db_content.test_water.osm_type.name, data
-        )
+def test_get(client, config):
+    """Test case getting waters (src)
+    """
+    headers = {}
+    response = client.open(
+        base_url, method='GET', headers=headers
+    )
+    assert response.status_code == 200
+    data = response.json
+    assert len(data) == 1
+    data = data[0]
+    check_key(
+        "manager", config.db_content.test_water['manager'], data
+    )
+    check_key("name", config.db_content.test_water['name'], data)
+    check_key("waterId", config.db_content.test_water['waterId'], data)
+    check_key("osmId", config.db_content.test_water['osmId'], data)
+    check_key(
+        "osmType", config.db_content.test_water['osmType'], data
+    )
 
 
-if __name__ == '__main__':
-    unittest.main()
+def test_get_by_name(client, config):
+    """Test case getting waters by name (src)
+    """
+    headers = {}
+
+    response = client.open(
+        '{}?name=Bla'.format(base_url), method='GET', headers=headers
+    )
+    assert response.status_code == 200
+    data = response.json
+    assert len(data) == 0
+
+    response = client.open(
+        '{}?name={}'.format(
+            base_url, config.db_content.test_water['name'][:3]
+        ),
+        method='GET',
+        headers=headers
+    )
+    assert response.status_code == 200
+    data = response.json
+    assert len(data) == 1
+    data = data[0]
+    check_key(
+        "manager", config.db_content.test_water['manager'], data
+    )
+    check_key("name", config.db_content.test_water['name'], data)
+    check_key("waterId", config.db_content.test_water['waterId'], data)
+    check_key("osmId", config.db_content.test_water['osmId'], data)
+    check_key(
+        "osmType", config.db_content.test_water['osmType'], data
+    )
+
+
+def test_get_by_manager(client, config):
+    """Test case getting waters by manager (src)
+    """
+    headers = {}
+
+    response = client.open(
+        '{}?manager=not_existent'.format(base_url),
+        method='GET',
+        headers=headers
+    )
+    assert response.status_code == 404, '{} != {}'.format(
+        response.status_code, 404
+    )
+
+    response = client.open(
+        '{}?manager={}'.format(
+            base_url, config.db_content.test_user['username']
+        ),
+        method='GET',
+        headers=headers
+    )
+    assert response.status_code == 200
+    data = response.json
+    assert len(data) == 1
+    data = data[0]
+    check_key(
+        "manager", config.db_content.test_water['manager'], data
+    )
+    check_key("name", config.db_content.test_water['name'], data)
+    check_key("waterId", config.db_content.test_water['waterId'], data)
+    check_key("osmId", config.db_content.test_water['osmId'], data)
+    check_key(
+        "osmType", config.db_content.test_water['osmType'], data
+    )
+
+
+def test_get_by_name_manager(client, config):
+    """Test case getting waters by manager and water name (src)
+    """
+    headers = {}
+
+    response = client.open(
+        '{}?manager={}&name=Bla'.format(
+            base_url, config.db_content.test_user['username']
+        ),
+        method='GET',
+        headers=headers
+    )
+    assert response.status_code == 200
+
+    response = client.open(
+        '{}?manager=john&name={}'.format(
+            base_url, config.db_content.test_water['name'][:3]
+        ),
+        method='GET',
+        headers=headers
+    )
+    assert response.status_code == 404
+
+    response = client.open(
+        '{}?name={}&manager={}'.format(
+            base_url, config.db_content.test_water['name'],
+            config.db_content.test_user['username']
+        ),
+        method='GET',
+        headers=headers
+    )
+    assert response.status_code == 200
+    data = response.json
+    assert len(data) == 1
+    data = data[0]
+    check_key(
+        "manager", config.db_content.test_water['manager'], data
+    )
+    check_key("name", config.db_content.test_water['name'], data)
+    check_key("waterId", config.db_content.test_water['waterId'], data)
+    check_key("osmId", config.db_content.test_water['osmId'], data)
+    check_key(
+        "osmType", config.db_content.test_water['osmType'], data
+    )
Index: src/gnuboat/mapservice_impl/validator_workaround.py
===================================================================
--- src/gnuboat/mapservice_impl/validator_workaround.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
+++ src/gnuboat/mapservice_impl/validator_workaround.py	(revision 9f0f35ed2d3b68bd7ce0e01159b997319b732748)
@@ -0,0 +1,59 @@
+"""Hacks needed to circumvent connexion validation
+
+There is a bug on the connexion library concerning content negotiation and
+response validation. See https://github.com/zalando/connexion/issues/860 and
+https://github.com/zalando/connexion/pull/760
+
+Until this issue is fixed, we need to find a way to avoid a false validation
+error when a requests sends an 'application/geo+json' accept header
+"""
+import functools
+import logging
+
+from connexion.decorators.response import ResponseValidator
+from connexion import problem
+from connexion.exceptions import (
+    NonConformingResponseBody, NonConformingResponseHeaders
+)
+from connexion.utils import has_coroutine
+
+logger = logging.getLogger(__name__)
+
+
+class ValidatorWorkaround(ResponseValidator):
+    def validate_response_with_request(
+        self, request, data, status_code, headers, url
+    ):
+        if request.headers.get('accept', '') == 'application/geo+json':
+            logging.debug('Circumventing validation for application/geo+json')
+            return True
+        return self.validate_response(data, status_code, headers, url)
+
+    def __call__(self, function):
+        """
+            :type function: types.FunctionType
+            :rtype: types.FunctionType
+        """
+        def _wrapper(request, response):
+            connexion_response = \
+             self.operation.api.get_connexion_response(response, self.mimetype)
+            self.validate_response_with_request(
+                request, connexion_response.body,
+                connexion_response.status_code, connexion_response.headers,
+                request.url
+            )
+
+            return response
+
+        if has_coroutine(function):
+            from .coroutine_wrappers import get_response_validator_wrapper
+            wrapper = get_response_validator_wrapper(function, _wrapper)
+
+        else:  # pragma: 3 no cover
+
+            @functools.wraps(function)
+            def wrapper(request):
+                response = function(request)
+                return _wrapper(request, response)
+
+        return wrapper
