Index: src/gnuboat/common/webservice/HttpErrors.py
===================================================================
--- src/gnuboat/common/webservice/HttpErrors.py	(revision 97efbbf500cda99bad53839e7d4742fac86a4c0d)
+++ src/gnuboat/common/webservice/HttpErrors.py	(revision 9b8dd2239535af0509ca3541964a1fc741938314)
@@ -17,5 +17,6 @@
 
 from werkzeug.exceptions import (
-    BadRequest, Unauthorized, NotFound, InternalServerError
+    BadRequest, Unauthorized, NotFound, InternalServerError,
+    RequestEntityTooLarge, GatewayTimeout, BadGateway
 )
 from connexion.exceptions import ProblemException
@@ -79,4 +80,23 @@
 
 
+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__(
@@ -96,2 +116,40 @@
             **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/deviceservice_impl/Config.py
===================================================================
--- src/gnuboat/deviceservice_impl/Config.py	(revision 97efbbf500cda99bad53839e7d4742fac86a4c0d)
+++ src/gnuboat/deviceservice_impl/Config.py	(revision 9b8dd2239535af0509ca3541964a1fc741938314)
@@ -20,4 +20,5 @@
     DEBUG = False
     TESTING = False
+    MAX_CONTENT_LENGTH = 500 * 1024 * 1024
 
 
@@ -25,12 +26,21 @@
     # 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_API_KEY = 'test_key'
+    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'
-    SHUTDOWN_COMMAND = ['echo', '1']
+    DEMO = True
+    SHUTDOWN_COMMAND = ['echo', 'Shutdown Requested']
+    LOG_DIRECTORY = '/tmp/gnuboat-device/logs'
+    MAP_DIRECTORY = '/tmp/gnuboat-device/maps'
+
 
 class TestingConfig(DevelopmentConfig):
Index: src/gnuboat/deviceservice_impl/ValidatorWorkaround.py
===================================================================
--- src/gnuboat/deviceservice_impl/ValidatorWorkaround.py	(revision 9b8dd2239535af0509ca3541964a1fc741938314)
+++ src/gnuboat/deviceservice_impl/ValidatorWorkaround.py	(revision 9b8dd2239535af0509ca3541964a1fc741938314)
@@ -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/deviceservice_impl/__init__.py
===================================================================
--- src/gnuboat/deviceservice_impl/__init__.py	(revision 97efbbf500cda99bad53839e7d4742fac86a4c0d)
+++ src/gnuboat/deviceservice_impl/__init__.py	(revision 9b8dd2239535af0509ca3541964a1fc741938314)
@@ -18,11 +18,13 @@
 import connexion
 import flask
+from flask import redirect
 from flask_cors import CORS
 from werkzeug.utils import import_string
 import os
+from pathlib import Path
 
+from gnuboat.deviceservice_impl.ValidatorWorkaround import ValidatorWorkaround
 from gnuboat.deviceservice import encoder
 
-from pathlib import Path
 
 def load_config_object(config_name):
@@ -37,6 +39,7 @@
 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(''))
+    config_object = configure.config_from_file(
+        config_file, load_config_object('')
+    )
 else:
     config_object = load_config_object('Production')
@@ -46,7 +49,9 @@
 CORS(application)
 
-#@app.route("/")
-#def index():
-   #return render_template("index.html")
+
+@app.route("/")
+def index():
+    return redirect("/client/index.html", code=302)
+
 
 def setup_app(app_name, config, template_folder=None):
@@ -57,7 +62,8 @@
         validate_responses=True,
         strict_validation=True,
+        validator_map={'response': ValidatorWorkaround}
     )
     application.config.from_object(config)
-    
+
     application.static_url_path = '/client'
     # Remove the old rule from Map._rules.
@@ -65,10 +71,16 @@
         application.url_map._rules.remove(rule)  # There is probably only one.
 
-    # Remove the old rule from Map._rules_by_endpoint. In this case we can just 
+    # Remove the old rule from Map._rules_by_endpoint. In this case we can just
     # start fresh.
-    application.url_map._rules_by_endpoint['static'] = []  
+    application.url_map._rules_by_endpoint['static'] = []
 
     # Add the updated rule.
-    application.add_url_rule(f'{application.static_url_path}/<path:filename>',
-                    endpoint='static',
-                    view_func=application.send_static_file)
+    application.add_url_rule(
+        f'{application.static_url_path}/<path:filename>',
+        endpoint='static',
+        view_func=application.send_static_file
+    )
+
+    if 'DEMO' in application.config and application.config['DEMO']:
+        from gnuboat.deviceservice_impl.demo import create_demo
+        create_demo(application)
Index: src/gnuboat/deviceservice_impl/controllers/DeviceController.py
===================================================================
--- src/gnuboat/deviceservice_impl/controllers/DeviceController.py	(revision 97efbbf500cda99bad53839e7d4742fac86a4c0d)
+++ src/gnuboat/deviceservice_impl/controllers/DeviceController.py	(revision 9b8dd2239535af0509ca3541964a1fc741938314)
@@ -20,8 +20,8 @@
 import rrdtool
 import os
+import datetime
 
 import gnuboat.common.device.rrdschema as rrdschema
 from gnuboat.common.webservice.HttpErrors import (
-    GnuboatBadRequest, GnuboatUnauthorized,
     GnuboatNotFound, GnuboatInternalServerError
 )
@@ -33,7 +33,10 @@
         result = rrdtool.lastupdate(rrdfile)
     except Exception as e:
-        raise GnuboatInternalServerError(detail='Could not query rrd database. Error: {}'.format(repr(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'],
@@ -49,8 +52,9 @@
 def track_get():
     rrdfile = _rrdfile_get()
-    
+
     track = {}
     for archive in rrdschema.archives:
-        result = _rrd_fetch(rrdfile, archive.resolution, '{}s'.format(archive.duration))
+        result = _rrd_fetch(rrdfile, archive.resolution,
+                            '{}s'.format(archive.duration))
 
         start, end, interval = result[0]
@@ -64,5 +68,5 @@
         watertemperature = keys.index('watertemperature')
         gpsfix = keys.index('gpsfix')
-        
+
         i = 0
         for dataset in result[2]:
@@ -79,5 +83,5 @@
                 }
             i += 1
-   
+
     return track
 
@@ -111,14 +115,19 @@
 def _rrd_fetch(rrdfile, interval, period):
     try:
-        return rrdtool.fetch(rrdfile, 'AVERAGE', '--resolution', str(interval), '--start', '-{}'.format(period), '--align-start')
+        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)))
-    
+        raise GnuboatInternalServerError(
+            detail=('Could not fetch from rrd database. '
+                    'Error: {}').format(repr(e)))
+
 
 def gpsfix_to_enum(gpsfix):
     if gpsfix == 2:
-        return "2D";
+        return "2D"
     elif gpsfix == 3:
-        return "3D";
+        return "3D"
     else:
-        return "-";
+        return "-"
Index: src/gnuboat/deviceservice_impl/controllers/DeviceLogsController.py
===================================================================
--- src/gnuboat/deviceservice_impl/controllers/DeviceLogsController.py	(revision 97efbbf500cda99bad53839e7d4742fac86a4c0d)
+++ src/gnuboat/deviceservice_impl/controllers/DeviceLogsController.py	(revision 9b8dd2239535af0509ca3541964a1fc741938314)
@@ -16,4 +16,11 @@
 '''
 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 (
@@ -21,14 +28,128 @@
     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():
-    raise GnuboatInternalServerError
+    logdir = logdirectory_get()
+    files = sorted(logdir.glob('*.log'))
+    result = []
+    for path in files:
+        result.append(path.name)
+    return result
 
 
-def logs_get():
-    raise GnuboatInternalServerError
+def logs_get(name):
+    logdir = logdirectory_get()
 
-def logs_track_get():
-    raise GnuboatInternalServerError
+    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 97efbbf500cda99bad53839e7d4742fac86a4c0d)
+++ src/gnuboat/deviceservice_impl/controllers/DeviceMapsController.py	(revision 9b8dd2239535af0509ca3541964a1fc741938314)
@@ -16,11 +16,204 @@
 '''
 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 (
-    GnuboatBadRequest, GnuboatUnauthorized, 
-    GnuboatNotFound, GnuboatInternalServerError
+    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():
-    raise GnuboatInternalServerError
+    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 97efbbf500cda99bad53839e7d4742fac86a4c0d)
+++ src/gnuboat/deviceservice_impl/controllers/MapserviceController.py	(revision 9b8dd2239535af0509ca3541964a1fc741938314)
@@ -16,22 +16,290 @@
 '''
 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
-)
-
-
-def devices_get():
-    raise GnuboatInternalServerError
-
-
-def log_create():
-    raise GnuboatInternalServerError
+    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():
-    raise GnuboatInternalServerError
-
-def waters_get():
-    raise GnuboatInternalServerError
+    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/demo/DemoLog.py
===================================================================
--- src/gnuboat/deviceservice_impl/demo/DemoLog.py	(revision 9b8dd2239535af0509ca3541964a1fc741938314)
+++ src/gnuboat/deviceservice_impl/demo/DemoLog.py	(revision 9b8dd2239535af0509ca3541964a1fc741938314)
@@ -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.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 9b8dd2239535af0509ca3541964a1fc741938314)
+++ src/gnuboat/deviceservice_impl/demo/DemoMaps.py	(revision 9b8dd2239535af0509ca3541964a1fc741938314)
@@ -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.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 9b8dd2239535af0509ca3541964a1fc741938314)
+++ src/gnuboat/deviceservice_impl/demo/DemoRrd.py	(revision 9b8dd2239535af0509ca3541964a1fc741938314)
@@ -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.device.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 9b8dd2239535af0509ca3541964a1fc741938314)
+++ src/gnuboat/deviceservice_impl/demo/DeviceserviceEntry.py	(revision 9b8dd2239535af0509ca3541964a1fc741938314)
@@ -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.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 9b8dd2239535af0509ca3541964a1fc741938314)
+++ src/gnuboat/deviceservice_impl/demo/__init__.py	(revision 9b8dd2239535af0509ca3541964a1fc741938314)
@@ -0,0 +1,27 @@
+'''
+    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 gnuboat.deviceservice_impl.demo import (
+    DemoLog as demolog, DemoRrd as demorrd,
+    DemoMaps as demomaps
+)
+
+
+def create_demo(application):
+    demorrd.rrd_create_demo(application)
+    demolog.create_logs(application)
+    demomaps.create_maps(application)
Index: src/gnuboat/deviceservice_impl/tests/__init__.py
===================================================================
--- src/gnuboat/deviceservice_impl/tests/__init__.py	(revision 97efbbf500cda99bad53839e7d4742fac86a4c0d)
+++ src/gnuboat/deviceservice_impl/tests/__init__.py	(revision 9b8dd2239535af0509ca3541964a1fc741938314)
@@ -18,4 +18,5 @@
 import logging
 import flask
+from flask import request_started, request
 import connexion
 from flask_cors import CORS
@@ -25,18 +26,40 @@
 import time
 import random
-
-import gnuboat.common.device.rrdschema as rrdschema
-
+from pathlib import Path
+import datetime
+import shutil
+import subprocess
+import socket
+
+from gnuboat.common.device import rrdhandler as rrdhandler
+import gnuboat.common.datahandler.loghandler as loghandler
+import gnuboat.common.datahandler.logdataset as logdataset
+
+from gnuboat.deviceservice_impl.controllers.DeviceMapsController import (
+    _map_name_to_hash
+)
 from gnuboat.deviceservice.encoder import JSONEncoder
+
+logperiod = 2
+duration = 12 * 60 * 60
+timestamp = int(time.time())
+start_time = timestamp - duration - logperiod
+latitude_min = 10.0
+latitude_max = 10.9
+longitude_min = 42.0
+longitude_max = 42.9
 
 
 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',
+    app.add_api(
+        'openapi.yaml',
         validate_responses=True,
         strict_validation=True,
@@ -46,7 +69,11 @@
         'gnuboat.deviceservice_impl.Config.TestingConfig')
     application.app_context().push()
-    
+
     _create_rrdfile(testcase, application)
-    
+    _create_logs(testcase, application)
+    _create_maps(testcase, application)
+
+    _mapservice_start(testcase)
+
     return application
 
@@ -58,20 +85,30 @@
 def tearDown(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))
 
 
 def _create_rrdfile(testcase, application):
-    rrd_file_handle, testcase.rrdfile = tempfile.mkstemp(suffix='.rrd', prefix='gnuboat-tests')
+    rrd_file_handle, testcase.rrdfile = tempfile.mkstemp(
+        suffix='.rrd', prefix='gnuboat-tests'
+    )
     application.config['DEVICE_DATABASE'] = testcase.rrdfile
-    
-    logperiod = 2
-    duration = 24 * 60 * 60
-    timestamp = int(time.time())
-    start_time = timestamp - duration - logperiod
-    latitude_min = 10.0
-    latitude_max = 10.9
-    longitude_min = 42.0
-    longitude_max = 42.9
-    
-    _rrd_create_database(testcase.rrdfile, logperiod, str(start_time))
+    # we remove it here, because rrdcreate creates only databases,
+    # if the file does not exists
+    os.remove(testcase.rrdfile)
+
+    rrdhandler.rrd_create_database(
+        testcase.rrdfile, logperiod, str(start_time)
+    )
     for current_time in range(timestamp - duration, timestamp, logperiod):
         latitude = random.uniform(latitude_min, latitude_max)
@@ -84,5 +121,5 @@
         gpsFix = 3
         # update rrd database for the webservice
-        _rrd_update(
+        rrdhandler.rrd_update(
             testcase.rrdfile, '{}:{}:{}:{}:{}:{}:{}:{}:{}'.format(
                 current_time, latitude, longitude, speedThroughWater,
@@ -91,41 +128,106 @@
             )
         )
-    
-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
-    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
-                )
-            )
-        ]
-
-    rrdtool.create(
-        database_file, "--start", start_time, "--step", str(step),
-        rrd_data_sources, rrd_archives
-    )
-
-
-def _rrd_update(rrdfile, value_string):
-    rrdtool.update(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)))
+
+    @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)
+        )
+
+
+def _create_logs(testcase, application):
+    logdir = Path(tempfile.mkdtemp(prefix='gnuboat-tests-logs'))
+    testcase.logdir = logdir
+    application.config['LOG_DIRECTORY'] = str(logdir.resolve())
+
+    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('test-1.log'))
+        shutil.copy(logfile, logdir.joinpath('test-2.log'))
+        break
+
+
+def _create_maps(testcase, application):
+    mapdir = Path(tempfile.mkdtemp(prefix='gnuboat-tests-maps'))
+    testcase.mapdir = mapdir
+    application.config['MAP_DIRECTORY'] = str(mapdir.resolve())
+
+    shutil.copy(
+        os.path.join(
+            os.path.dirname(__file__),
+            '../../samples/maps/000-forggensee.mbtiles'
+        ),
+        mapdir.joinpath('{}.mbtiles'.format(_map_name_to_hash('Forggensee')))
+    )
+
+
+def _mapservice_start(testcase):
+    if 'TestMapserviceController' not in testcase.id():
+        testcase.mapservice_process = None
+    else:
+        mapservice_env = dict(os.environ)
+        mapservice_env['FLASK_ENV'] = 'Testing'
+        testcase.mapservice_process = subprocess.Popen(
+            [
+                'gnuboat-dev-mapservice', '--bind=localhost:8080',
+                '--log-level=debug'
+            ],
+            env=mapservice_env, shell=True,
+            stdout=subprocess.PIPE, stderr=subprocess.PIPE
+        )
+        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+        s.settimeout(10)
+        if s.connect_ex(('localhost', int(8090))) == 0:
+            s.shutdown(socket.SHUT_RDWR)
