Changes in / [944372e:949f66d]


Ignore:
Files:
25 deleted
22 edited

Legend:

Unmodified
Added
Removed
  • debian/changelog

    r944372e r949f66d  
    1 gnuboat (0.4.15) jessie; urgency=low
    2 
    3   * Fixed wrong format of latitude and longitude in NMEA log
    4   * Improved gnuboat-log-converter (NMEA, CSV, GPX formats)
    5   * Removed timeout from gpsd poller (which caused falling behind in reading
    6     gpsd messages)
    7   * Fixed webservice to handle timestamps in front of the nmea sentence
    8 
    9  -- EngSaS - Maintainer <info@engsas.de>  Thu, 21 Sep 2017 14:00:00 +0200
    101gnuboat (0.4.14) jessie; urgency=low
    112
  • debian/control

    r944372e r949f66d  
    2727Package: python-gnuboat
    2828Section: python
    29 Architecture: all
    30 Depends: ${misc:Depends}, ${python:Depends}, python-pil, python-dateutil, python-tz, python-rrdtool, python-pynmea2, gpsd, gpsbabel, n2kd-scripts, n2kd-bin, gnuboat-daemon-config
     29Architecture: any
     30Depends: ${misc:Depends}, ${python:Depends}, python-pil, python-dateutil, python-tz, python-rrdtool, python-pynmea2, gpsd, n2kd-scripts, n2kd-bin, gnuboat-daemon-config
    3131Recommends: python-epd
    3232Description: GNUBoat logging daemon
    … …  
    3636#Package: python3-gnuboat
    3737#Section: python
    38 #Architecture: all
    39 #Depends: ${misc:Depends}, ${python3:Depends}, python3-pil, python3-dateutil, python3-tz, python3-rrdtool, python3-pynmea2, gpsd, gpsbabel, n2kd-scripts, n2kd-bin, gnuboat-daemon-config
     38#Architecture: any
     39#Depends: ${misc:Depends}, ${python3:Depends}, python3-pil, python3-dateutil, python3-tz, python3-rrdtool, python3-pynmea2, gpsd, n2kd-scripts, n2kd-bin, gnuboat-daemon-config
    4040#Recommends: python-epd
    4141#Description: GNUBoat logging daemon
  • setup.py

    r944372e r949f66d  
    2626setup(
    2727  name="gnuboat",
    28   version="0.4.7",
     28  version="0.4.6",
    2929  maintainer="EngSaS - Langenbach",
    3030  maintainer_email="info@engsas.de",
  • src/python/bin/gnuboat

    r944372e r949f66d  
    2727from pytz import timezone
    2828import pytz
    29 import argparse
     29import getopt
    3030import sys
    3131import pynmea2
    32 import traceback
    3332
    3433from gnuboat import daemon
    … …  
    4443logdir = "/var/log/gnuboat"
    4544logperiod = 2
    46 logverbose = False
    47 logsystemtime = False
    4845displayperiod = 5
    4946
    … …  
    7370    print "  gnuboat -r PATH_TO_RRD_DATABAE_FILE -s PATH_TO_SHUTDOWN_REQUEST_FILE [-l [LOG_UPDATE_PERIOD] [-d DISPLAY_UPDATE_PERIOD] [-o PATH_TO_NMEA1983_LOG]"
    7471    print ""
    75     print "  -h  --help              Display this help"
    76     print "  -r  --rrdfile           Path to the rrd database used by the webservice to serve the clients"
    77     print "  -s  --shutdownfile      Path to the shutdown request file, used by the webservice to request a shutdown of the system running gnuboat"
    78     print "  -l  --logperiod         Time in seconds to update the logs"
    79     print "  -lv --log-verbose       Log verbose information to nmea log file (Enables -ls and adds RMC sentences, with invalid GPS state, on non fixes"
    80     print "  -ls --log-system-time   Add to enable prefixing every logline with the system time (Default off)"
    81     print "  -d  --displayperiod     Timein seconds to update the display"
    82     print "  -o  --output            Directory where the log files are stored (e.g. the NMEA0183 log files)"
     72    print "  -h --help              Display this help"
     73    print "  -r --rrdfile           Path to the rrd database used by the webservice to serve the clients"
     74    print "  -s --shutdownfile      Path to the shutdown request file, used by the webservice to request a shutdown of the system running gnuboat"
     75    print "  -l --logperiod         Time in seconds to update the logs"
     76    print "  -d --displayperiod     Timein seconds to update the display"
     77    print "  -o --output            Directory where the log files are stored (e.g. the NMEA0183 log files)"
    8378
    8479def log(gpsFix, gpsTime, gpsStatus, latitude, latitudeDirection, longitude,
    85         longitudeDirection, courseOverGround, speedOverGround, waterDepth, waterTemperature, transducerValid, logVerbose, logSystemTime):
     80        longitudeDirection, courseOverGround, speedOverGround, waterDepth, waterTemperature, transducerValid):
    8681    global logdir
    8782    global nmeafile
    8883    global nmeaFileDate
    89 
     84   
    9085    # Only log, if we have a gps fix
    9186    if gpsFix < 2:
    92         if not logVerbose:
    93             return
    94         gpsStatus = 'V'
    95         mode = 'N'
    96         if gpsTime is None:
    97             gpsTime = datetime.datetime.utcnow()
     87        return
    9888   
    9989    nmeaFileDateShould = datetime.datetime.utcnow().strftime("%Y-%m-%d")
    … …  
    10999            print "Could not open the logfile: %s" % error
    110100            sys.exit(2)
    111 
    112     latitude = degreesDecimalToNmea(latitude)
    113     longitude = degreesDecimalToNmea(longitude)
    114 
    115     logsystemtime = ""
    116     if logsystemtime:
    117         logsystemtime = "%s:" datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
    118        
    119     try:
    120         nmeafile.write("%s%s\r\n" % (logsystemtime, str(pynmea2.RMC('GN', 'RMC',
    121                                                      (gpsTime.strftime("%H%M%S"), gpsStatus,
    122                                                      '%02d%s' % (latitude['degrees'], latitude['minutes'])
    123                                                      latitudeDirection,
    124                                                      '%03d%s' % (longitude['degrees'], longitude['minutes']),
    125                                                      longitudeDirection,
    126                                                      '%04.1f' % speedOverGround, '%04.1f' % courseOverGround,
    127                                                      gpsTime.strftime("%d%m%y"), '', '', mode)))))
    128         if transducerValid:
    129             nmeafile.write("%s%s\r\n" % (logsystemtime, str(pynmea2.DPT('SD', 'DPT', ('%05.2f' % waterDepth, '00.00')))))
    130             nmeafile.write("%s%s\r\n" % (logsystemtime, str(pynmea2.MTW('YX', 'MTW', ('%04.1f' % waterTemperature, 'C')))))
    131     except:
    132         print "Failed writing to logfile %s" % nmeaLogFile
    133         print(traceback.format_exc())
    134 
    135 def degreesDecimalToNmea(decimalDegrees):
    136     degrees = math.floor(decimalDegrees)
    137     minutes = 60.0 * (decimalDegrees - degrees)
    138     return { 'degrees': degrees, 'minutes': minutes}
     101               
     102    nmeafile.write("%s\r\n" % str(pynmea2.RMC('GN', 'RMC',
     103                                              (gpsTime.strftime("%H%M%S"), gpsStatus, '%08.3f' % latitude,
     104                                               latitudeDirection, '%09.3f' % longitude, longitudeDirection,
     105                                               '%04.1f' % speedOverGround, '%04.1f' % courseOverGround,
     106                                               gpsTime.strftime("%d%m%y"), '', '', mode))))
     107    if transducerValid:
     108        nmeafile.write("%s\r\n" % str(pynmea2.DPT('SD', 'DPT', ('%05.2f' % waterDepth, '00.00'))))
     109        nmeafile.write("%s\r\n" % str(pynmea2.MTW('YX', 'MTW', ('%04.1f' % waterTemperature, 'C'))))
    139110
    140111def main(argv):
    … …  
    142113    global shutdownfile
    143114    global logperiod
    144     global logverbose
    145     global logsystemtime
    146115    global displayperiod
    147116    global logdir
    148117    global nmeafile
    149118
    150     parser = argparse.ArgumentParser(description="Collects the data from canboat and gpsd and writes them to the rrd database and the nmea log file")
    151     parser.add_argument('-r', '--rrdfile', dest='rrd_file', metavar='rrd_file', type=str,
    152                         help='Path to the rrd database used by the webservice to serve the clients', default=rrdfile)
    153     parser.add_argument('-s', '--shutdownfile', dest='shutdown_file', metavar='shutdown_file', type=str,
    154                         help='Path to the shutdown request file, used by the webservice to request a shutdown of the system running gnuboat', default=shutdownfile)
    155     parser.add_argument('-lp', '--logperiod', dest='log_period', metavar='log_period', type=int,
    156                         help='Time in seconds to update the logs', default=logperiod)
    157     parser.add_argument('-lv', '--log-verbose', action='store_true', dest='log_verbose',
    158                         help='Log verbose information to nmea log file (Enables -ls and adds RMC sentences, with invalid GPS state, on non fixes (Default off)')
    159     parser.add_argument('-ls', '--log-system-time', action='store_true', dest='log_system_time',
    160                         help='Add to enable prefixing every logline with the system time (Default off)')
    161     parser.add_argument('-d', '--displayperiod', dest='display_period', metavar='display_period', type=int,
    162                         help='Time in seconds to update the display', default=displayperiod)
    163     parser.add_argument('-o', '--output', dest='output', metavar='output', type=str,
    164                         help='Directory where the log files are stored (e.g. the NMEA0183 log files)', default=logdir)
    165     arguments = parser.parse_args(argv)
    166    
    167     if arguments.rrd_file is not None:
    168         rrdfile = arguments.rrd_file
    169     if arguments.shutdown_file is not None:
    170         shutdownfile = arguments.shutdown_file
    171     if arguments.log_period is not None:
    172         logperiod = arguments.log_period   
    173     if arguments.log_verbose is not None:
    174         logverbose = arguments.log_verbose
    175         logsystemtime = True
    176     if arguments.log_system_time is not None and arguments.log_verbose is None:
    177         logsystemtime = arguments.log_system_time
    178     if arguments.display_period is not None:
    179         displayperiod = arguments.display_period
    180     if arguments.output is not None:
    181         logdir = arguments.output
     119    try:
     120        opts, args = getopt.getopt(argv, "hr:s:l:d:o:", [
     121                                   "help", "rrdfile=", "shutdownfile=", "logperiod=", "displayperiod=", "output="])
     122    except getopt.GetoptError:
     123        usage()
     124        sys.exit(2)
     125
     126    for option, argument in opts:
     127        if option == ("-h", "--help"):
     128            usage()
     129            sys.exit()
     130        elif option in ("-r", "--rrdfile"):
     131            rrdfile = argument
     132        elif option in ("-s", "--shutdownfile"):
     133            shutdownfile = argument
     134        elif option in ("-l", "--logperiod"):
     135            logperiod = argument
     136        elif option in ("-d", "--displayperiod"):
     137            displayperiod = argument
     138        elif option in ("-o", "--output"):
     139            logdir = argument
     140        else:
     141            assert False, "unhandled option"
    182142
    183143    if not os.path.exists(os.path.dirname(rrdfile)):
    … …  
    237197            log(gpsFix, gpsp.timeUtc(), gpsp.status(), latitude, gpsp.latitudeDirection(),
    238198                longitude, gpsp.longitudeDirection(), courseOverGround, speedOverGround,
    239                 waterDepth, waterTemperature, n2kd.waterDepthValid(), logverbose, logsystemtime)
     199                waterDepth, waterTemperature, n2kd.waterDepthValid())
    240200           
    241201            # display data
  • src/python/bin/gnuboat-log-converter

    r944372e r949f66d  
    2424from enum import Enum
    2525import csv
    26 import re
    27 import tempfile
    28 import subprocess
    2926
    3027class Format(Enum):
    3128    CSV = 1
    32     NMEA0183 = 2
    33     GPX = 3
    3429
    35 regex_nmea_sentence = re.compile(r"^([^\$!]{0,})([\$!]{1}[\w]{2}[\w]{3}[^\*]+\*[\da-zA-Z]+)$")
    36 regex_nmea_position = re.compile(r"^([0-9]+)([0-9]{2}\.[0-9]+)$")
     30input_file_path = None
     31output_file_path = None
     32output_format_option = None
     33output_format = Format.CSV
     34errors_ignore = False
    3735
    3836def toFloat(string, current_row):
    … …  
    4644           return 0
    4745
    48 def nmeaToDecimalDegrees(nmea_value, current_row):
    49     global regex_nmea_position
    50 
    51     if toFloat(nmea_value, current_row) == 0:
    52         return 0
    53 
    54     matches = regex_nmea_position.match(nmea_value)
    55     if matches is None:
    56         print 'INFO: Failed to convert position value from line %s into decimal degrees: %s' % (current_row, nmea_value)
    57         return
    58     decimalDegrees = toFloat(matches.group(1), current_row)
    59     decimalMinutes = toFloat(matches.group(2), current_row)
    60     return decimalDegrees + (decimalMinutes / 60.0)
    61 
    62 def convertToCsv(input_file_path, output_file_path, errors_ignore, strip_time):
    63     global regex_nmea_sentence
    64 
    65     try:
    66         output_file = open(output_file_path, 'w', 0)
    67     except IOError as error:
    68         print "ERROR: Could not open the output file: %s" % error
    69         sys.exit(3)
    70 
    71     output_file_csv = None
    72     fields = ['datetime', 'gps_status', 'latitude', 'latitude_direction', 'longitude',
    73               'longitude_direction', 'speed_over_ground', 'course_over_ground' ,
    74               'water_depth', 'water_temperature']
    75     output_file_csv = csv.DictWriter(output_file, delimiter=' ', quotechar='"',
    76                                      quoting=csv.QUOTE_NONNUMERIC, fieldnames=fields)
    77     output_file_csv.writeheader()
    78 
    79     # reading input file
    80     try:
    81         input_file = open(input_file_path, 'r')
    82     except IOError as error:
    83         print "ERROR: Could not open the input file: %s" % error
    84         sys.exit(3)
    85     current_row = 1
    86     last_row = None
    87     for line in input_file:
    88         line = line.strip()
    89         matches = regex_nmea_sentence.match(line)
    90         if matches is None:
    91             print 'INFO: Failed to parse nmea sentence (%s) at line %s\n' % (line, current_row)
    92             if not errors_ignore:
    93                 input_file.close()
    94                 output_file.close()
    95                 sys.exit(4)
    96         else:
    97             nmea_sentence = pynmea2.parse(matches.group(2))
    98             if nmea_sentence.sentence_type == 'RMC':
    99                 if last_row is not None:
    100                     output_file_csv.writerow(last_row)
    101                 last_row = {'datetime': '%s %s' % (nmea_sentence.datestamp, nmea_sentence.timestamp),
    102                             'gps_status': nmea_sentence.status,
    103                             'latitude': nmeaToDecimalDegrees(nmea_sentence.lat, current_row),
    104                             'latitude_direction': nmea_sentence.lat_dir,
    105                             'longitude': nmeaToDecimalDegrees(nmea_sentence.lon, current_row),
    106                             'longitude_direction': nmea_sentence.lon_dir,
    107                             'speed_over_ground': toFloat(nmea_sentence.spd_over_grnd, current_row),
    108                             'course_over_ground': toFloat(nmea_sentence.true_course, current_row),
    109                             'water_depth': None,
    110                             'water_temperature': None}
    111             elif nmea_sentence.sentence_type == 'DBT' and last_row is not None:
    112                 last_row['water_depth'] = toFloat(nmea_sentence.depth_meters, current_row)
    113             elif nmea_sentence.sentence_type == 'MTW' and last_row is not None:
    114                 last_row['water_temperature'] = toFloat(nmea_sentence.temperature, current_row)
    115             current_row += 1
    116     if last_row is not None:
    117         output_file_csv.writerow(last_row)
    118     output_file.close()
    119     input_file.close()
    120 
    121 def convertToNmea0183(input_file_path, output_file_path, errors_ignore, strip_time):
    122     global regex_nmea_sentence
    123 
    124     try:
    125         output_file = open(output_file_path, 'w', 0)
    126     except IOError as error:
    127         print "ERROR: Could not open the output file: %s" % error
    128         sys.exit(3)
    129 
    130     # reading input file
    131     try:
    132         input_file = open(input_file_path, 'r')
    133     except IOError as error:
    134         print "ERROR: Could not open the input file: %s" % error
    135         sys.exit(3)
    136     current_row = 1
    137     last_row = None
    138     for line in input_file:
    139         line = line.strip()
    140         matches = regex_nmea_sentence.match(line)
    141         if matches is None:
    142             print 'INFO: Failed to parse nmea sentence (%s) at line %s\n' % (line, current_row)
    143             if not errors_ignore:
    144                 input_file.close()
    145                 output_file.close()
    146                 sys.exit(4)
    147         else:
    148             nmea_sentence = pynmea2.parse(matches.group(2))
    149             output_string = str(nmea_sentence)
    150             if not strip_time and matches.group(1):
    151                 output_string = '%s%s' % (matches.group(1), output_string)
    152             output_file.write("%s\r\n" % str(output_string))
    153     output_file.close()
    154     input_file.close()
    155    
    156 def convertToGpx(input_file_path, output_file_path, errors_ignore, strip_time):
    157     global regex_nmea_sentence
    158    
    159     # make sure, nmea input file, does not have timestamps in front of the nmea
    160     # sentences
    161     [nmea_without_timestamps_handle, nmea_without_timestamp_file_path] = tempfile.mkstemp(text=True)
    162     convertToNmea0183(input_file_path, nmea_without_timestamp_file_path, errors_ignore, True)
    163    
    164     subprocess.call(['gpsbabel', '-i', 'nmea', '-f', nmea_without_timestamp_file_path, '-o', 'gpx', '-F', output_file_path])
    165     os.remove(nmea_without_timestamp_file_path)
    166 
    16746def main(argv):
    168     input_file_path = None
    169     output_file_path = None
    170     output_format_option = None
    171     output_format = Format.CSV
    172     errors_ignore = False
    173     strip_time = False
    174        
    17547    formats = []
    17648    for file_format in Format:
    … …  
    18658    parser.add_argument('output_file', metavar='output_file_path', type=str,
    18759                        help='Write the converted content to file (output)')
    188     parser.add_argument('--strip-time', dest='strip_time', action='store_true',
    189                         help='Removes timestamp in front of the nmea sentence, if it is there')
    19060    arguments = parser.parse_args(argv)
    19161   
    … …  
    19767               format_found = True
    19868        if not format_found:
    199             print 'ERROR: Invalid input format specified: %s' % arguments.output_format
     69            print 'Invalid input format specified: %s' % arguments.output_format
    20070            sys.exit(1)
    20171
    20272    if arguments.errors_ignore is not None:
    20373        errors_ignore = arguments.errors_ignore
    204        
    205     if arguments.strip_time is not None:
    206         strip_time = arguments.strip_time
    20774           
    20875    if arguments.input_file is None:
    209         print 'ERROR: No input file specified'
     76        print 'No input file specified'
    21077        sys.exit(2)
    21178    elif not os.path.exists(arguments.input_file):
    212         print 'ERROR: Specified input file does not exists: %s' % arguments.input_file
     79        print 'Specified input file does not exists: %s' % arguments.input_file
    21380        sys.exit(3)
    21481    else:
    … …  
    21683       
    21784    if arguments.output_file is None:
    218         print 'ERROR: No output file specified'
     85        print 'No output file specified'
    21986        sys.exit(2)
    22087    elif not os.path.exists(os.path.dirname(arguments.output_file)):
    221         print 'ERROR: Specified directory of output file does not exists: %s' % arguments.output_file
     88        print 'Specified directory of output file does not exists: %s' % arguments.output_file
    22289        sys.exit(3)
    22390    else:
    22491        output_file_path = arguments.output_file
    22592
    226     if output_format == Format.CSV.value:
    227         convertToCsv(input_file_path, output_file_path, errors_ignore, strip_time)
    228     elif output_format == Format.NMEA0183.value:
    229         convertToNmea0183(input_file_path, output_file_path, errors_ignore, strip_time)
    230     elif output_format == Format.GPX.value:
    231         convertToGpx(input_file_path, output_file_path, errors_ignore, strip_time)
    232     else:
    233         print "ERROR: Undefined output format!\n";
    234         sys.exit(1)
     93    try:
     94        output_file = open(output_file_path, 'w', 0)
     95    except IOError as error:
     96        print "Could not open the output file: %s" % error
     97        sys.exit(3)
     98       
     99    output_file_csv = None
     100    if output_format == Format.CSV.value:
     101        fields = ['datetime', 'gps_status', 'latitude', 'latitude_direction', 'longitude',
     102                  'longitude_direction', 'speed_over_ground', 'course_over_ground' ,
     103                  'water_depth', 'water_temperature']
     104        output_file_csv = csv.DictWriter(output_file, delimiter=' ', quotechar='"',
     105                                         quoting=csv.QUOTE_NONNUMERIC, fieldnames=fields)
     106        output_file_csv.writeheader()
    235107
     108    # reading input file
     109    nmea_errors='raise'
     110    if errors_ignore:
     111        nmea_errors='ignore'
     112    nmea_file = pynmea2.NMEAFile(input_file_path)
     113    current_row = 1
     114    last_row = None
     115    for nmea_sentence in nmea_file:
     116        if output_format == Format.CSV.value:
     117            if nmea_sentence.sentence_type == 'RMC':
     118                if last_row is not None:
     119                    output_file_csv.writerow(last_row)
     120                last_row = {'datetime': '%s %s' % (nmea_sentence.datestamp, nmea_sentence.timestamp),
     121                            'gps_status': nmea_sentence.status,
     122                            'latitude': toFloat(nmea_sentence.lat, current_row),
     123                            'latitude_direction': nmea_sentence.lat_dir,
     124                            'longitude': toFloat(nmea_sentence.lon, current_row),
     125                            'longitude_direction': nmea_sentence.lon_dir,
     126                            'speed_over_ground': toFloat(nmea_sentence.spd_over_grnd, current_row),
     127                            'course_over_ground': toFloat(nmea_sentence.true_course, current_row),
     128                            'water_depth': None,
     129                            'water_temperature': None}
     130            elif nmea_sentence.sentence_type == 'DBT' and last_row is not None:
     131                last_row['water_depth'] = toFloat(nmea_sentence.depth_meters, current_row)
     132            elif nmea_sentence.sentence_type == 'MTW' and last_row is not None:
     133                last_row['water_temperature'] = toFloat(nmea_sentence.temperature, current_row)
     134        current_row += 1
     135    if last_row is not None:
     136        output_file_csv.writerow(last_row) 
     137       
     138    output_file.close()
    236139    sys.exit(0)
    237140
  • src/python/gnuboat/daemon/gpsdpoller.py

    r944372e r949f66d  
    2222import datetime
    2323import gps
    24 import traceback
    2524
    2625# Copied from https://gist.github.com/wolfg1969/4653340
    … …  
    4241
    4342    def latitude(self):
    44         if self._currentValue == None or self.gpsFix() < 2:
     43        if self._session == None or self.gpsFix() < 2:
    4544            return 0
    46         return self._currentValue.fix.latitude
     45        return self._session.fix.latitude
    4746
    4847    def latitudeDirection(self):
    … …  
    5049
    5150    def longitude(self):
    52         if self._currentValue == None or self.gpsFix() < 2:
     51        if self._session == None or self.gpsFix() < 2:
    5352            return 0
    54         return self._currentValue.fix.longitude
     53        return self._session.fix.longitude
    5554
    5655    def longitudeDirection(self):
    … …  
    5857
    5958    def speedOverGround(self):
    60         if self._currentValue == None or self.gpsFix() < 2:
     59        if self._session == None or self.gpsFix() < 2:
    6160            return 0
    62         return self._currentValue.fix.speed
     61        return self._session.fix.speed
    6362
    6463    def courseOverGround(self):
    65         if self._currentValue == None or self.gpsFix() < 2:
     64        if self._session == None or self.gpsFix() < 2:
    6665            return 0
    67         return self._currentValue.fix.track
     66        return self._session.fix.track
    6867
    6968    def gpsFix(self):
    70         if self._currentValue == None:
     69        if self._session == None:
    7170            return 0
    72         return self._currentValue.fix.mode
     71        return self._session.fix.mode
    7372
    7473    def status(self):
    75         if self._currentValue == None or self.gpsFix() < 2:
     74        if self._session == None or self.gpsFix() < 2:
    7675            return "V"
    7776        return "A"
    7877
    7978    def timeUtc(self):
    80         if self._currentValue == None or self.gpsFix() < 2:
     79        if self._session == None or self.gpsFix() < 2:
    8180            return None
    82         currentTime = self._currentValue.fix.time
     81        currentTime = self._session.fix.time
    8382        if isinstance(currentTime, float):
    8483            return datetime.datetime.fromtimestamp(currentTime)
    85         return dateutil.parser.parse(currentTime)
     84        return dateutil.parser.parse(self._session.fix.time)
    8685
    8786    def stop(self):
    … …  
    9190        try:
    9291            while self._running:
    93                 try:
    94                     self._currentValue = self._session.next()
    95                 except StopIteration:
    96                     break;
    97                 except:
    98                     print "Failed to read gpsd data"
    99                     print(traceback.format_exc())
    100                     self._currentValue = None
     92                self._currentValue = self._session.next()
     93                time.sleep(float(self._logperiod) / 2.0)
    10194        except StopIteration:
    10295            pass
  • src/python/gnuboat/daemon/n2kdpoller.py

    r944372e r949f66d  
    2121import socket
    2222import json
    23 import traceback
    2423
    2524"""@class N2kdPoller
    … …  
    7978        response = ""
    8079        while 1:
    81             try:
    82                 data = n2kdSocket.recv(1024)
    83             except:
    84                 print "Failed to update n2kd data"
    85                 print(traceback.format_exc())
    86                 self._waterDepthValid = False
     80            data = n2kdSocket.recv(1024)
    8781            if not data:
    8882                break
  • src/python/gnuboat/daemon/rrdhandler.py

    r944372e r949f66d  
    1919import rrdtool
    2020import os
    21 import traceback
    2221
    2322def rrd_create_database(database_file, logperiod, start_time = 'N'):
    … …  
    5352
    5453def rrd_update(rrdfile, value_string):
    55     try:
    56         rrdtool.update(rrdfile, value_string)
    57     except:
    58         print "Failed to update rrd database %s with values\n  %s" % (rrdfile, value_string)
    59         print(traceback.format_exc())
     54    rrdtool.update(rrdfile, value_string)
    6055
    6156def _rows(duration, resolution, step):
  • src/webapp/build.xml

    r944372e r949f66d  
    2828                        <exclude name="mbtiles/**"/>
    2929                        <exclude name="tests/**"/>
    30                         <exclude name="config/**"/>
    3130                </fileset>
    3231                <fileset dir="./webservice/mbtiles" id="filesWebserviceMaps">
    … …  
    4544
    4645
    47         <target name="dist" depends="buildwebservice,buildwebclient,test">
     46        <target name="dist" depends="buildwebservice,buildwebclient">
    4847                <echo msg="Creating archive"/>
    49                 <tar destfile="${builddir}/..//gnuboat-webapp.tar.gz" compression="gzip">
     48        <!--    <tar destfile="${builddir}/..//gnuboat-webapp.tar.gz" compression="gzip">
    5049                        <fileset refid="filesWebApp"/>
    51                 </tar>
     50                </tar>-->
    5251                <echo msg="Files copied and compressed in build directory weblcient.tar.gz OK!" />
    5352        </target>
    54 
    55         <target name="testdist" depends="buildwebservice,buildwebclient,test">
     53        <target name="testdist" depends="buildwebservice,buildwebclient">
    5654                <echo msg="Install project into ${user.home}/public_html/gnuboat"/>
    57                 <fileset id="filesConfig" dir="./webservice/config">
    58                         <include name="config.php"/>
    59                 </fileset>
    60                 <fileset id="filesLogs" dir="./webservice/tests/logs">
    61                         <include name="*.log"/>
    62                 </fileset>
    63        
    6455                <copy todir="${user.home}/public_html/gnuboat">
    6556                        <fileset refid="filesWebApp"/>
    6657                </copy>
    67                 <copy todir="${user.home}/public_html/gnuboat/webservice/tests/logs">
    68                         <fileset refid="filesLogs"/>
    69                 </copy>
    70                 <copy todir="${user.home}/public_html/gnuboat/webservice/config">
    71                         <fileset refid="filesConfig"/>
    72                 </copy>
    7358        </target>
    7459
    75         <target name="test">
    76                 <exec command="php phpunit-4.8.9.phar" passthru="true" checkreturn="true"/>
    77                 <!--<phpunit pharlocation="phpunit-4.8.9.phar" configuration="phpunit.xml" haltonfailure="true" haltonerror="true" printsummary="true" codecoverage="false">
    78                         <formatter type="plain" usefile="false"/> -->
    79                         <!--<formatter type="JUnit" usefile="true"/>-->
    80 <!--                    <batchtest>
    81                                 <fileset dir="webservice">
    82                                         <include name="tests/*Test.php"/>
    83                                 </fileset>
    84                         </batchtest>
    85                 </phpunit>-->
    86         </target>
     60        <!-- <phpunit bootstrap="webservice/inc/autoloader.php" pharlocation="phpunit-4.8.9.phar" haltonfailure="true" haltonerror="true" printsummary="true">
     61                <formatter type="plain" usefile="false"/>
     62                <batchtest>
     63                        <fileset dir="webservice">
     64                                <include name="tests/ServiceTest.php"/>
     65                        </fileset>
     66                </batchtest>
     67        </phpunit> -->
    8768</project>
  • src/webapp/webclient/css/GnuBoat.css

    r944372e r949f66d  
    9797
    9898.viewportGeometry {
    99 /*      width: 100%; */
     99        width: 100%;
    100100        height: 24em;
    101101}
    … …  
    129129        background:url('../resources/view-refresh.svg') no-repeat left center;
    130130}
    131 
    132 .hidden {
    133         display: none;
    134 }
    135 
    136 #mapLgend table {
    137         margin-top: 0.25em;
    138         margin-left: 1em;
    139 }
    140 
    141 #mapLegend table tr td.level {
    142         text-align: right;
    143 }
  • src/webapp/webclient/index.html

    r944372e r949f66d  
    139139                                        <div id="map">
    140140                                                <a name="map"></a>
    141                                                 <form id="mapSelectForm" class="pure-form pure-form-aligned">
    142                                                         <div class="pure-control-group">
    143                                                                 <label for="mapModusSelect">Map Modus:</label>
    144                                                                 <select id="mapModusSelect" size="1" class="pure-input-1-2"></select>
    145                                                         </div>
    146                                                         <div class="pure-control-group">
    147                                                                 <label for="mapSelect">Map Selection:</label>
    148                                                                 <select id="mapSelect" size="1" class="pure-input-1-2"></select>
    149                                                         </div>
    150                                                 </form>
    151                                                 <div class="pure-g">
    152                                                         <div class="pure-u-1 pure-u-md-4-5 pure-u-lg-4-5">
    153                                                                 <div id="mapViewport" class="viewportGeometry"></div>
    154                                                         </div>
    155                                                         <div class="pure-u-1 pure-u-md-1-5 pure-u-lg-1-5">
    156                                                                 <div id="mapLegend"></div>
    157                                                         </div>
    158                                                 </div>
     141                                                <form id="mapSelectForm" class="pure-form"><select id="mapSelect" class="pure-input-1" size="1"></select></form>
     142                                                <div id="mapViewport" class="viewportGeometry"></div>
    159143                                        </div>
    160144                                        <form id="mapTileUpload" class="pure-form pure-form-aligned" enctype="multipart/form-data">
    … …  
    173157                                        </form>
    174158
    175                                         <h2 class="content-subhead">3D Rendering of Water Depth</h2>
     159                                        <h2 class="content-subhead">3D Rendering</h2>
    176160                                        <div>
    177161                                                <a name="rendering"></a>
  • src/webapp/webclient/js/GnuBoat.js

    r944372e r949f66d  
    5454{
    5555        if(GnuBoat.private.serverBaseUrl == null){
    56                 GnuBoat.displayMessage('<span class="error">No server set/found</span>');
     56                GnuBoat.displayMessage("No server set/found");
    5757                return;
    5858        }
    … …  
    6767{
    6868        if(GnuBoat.private.serverBaseUrl == null){
    69                 GnuBoat.displayMessage('<span class="error">No server set/found</span>');
     69                GnuBoat.displayMessage("No server set/found");
    7070                return;
    7171        }
    … …  
    7979{
    8080        if(GnuBoat.private.serverBaseUrl == null){
    81                 GnuBoat.displayMessage('<span class="error">No server set/found</span>');
     81                GnuBoat.displayMessage("No server set/found");
    8282                return;
    8383        }
    8484        $("#logfilesForm").empty();
    8585        $.getJSON(GnuBoat.private.serverBaseUrl +"?request=logfiles", function(data){
    86                 GnuBoat.private.updateMapModus(data);
    8786                if(!Array.isArray(data) || data.length < 1){
    8887                        $("<p>No Logfiles found!</p>").appendTo("#logfilesForm");
    … …  
    9190                }
    9291                if(("error" in data) && data["error"] == 1){
    93                         GnuBoat.displayMessage('<span class="error">Failed to get log files: '+ data["errormessage"] +'</span>');
    94                         $("<p>No Logfiles found!</p>").appendTo("#logfilesForm");
    95                         console.log(data);
     92                        alert("Failed to upload map: "+ data["errormessage"]);
     93                        $("#mapTileUploadProgress").hide();
     94                        $("#mapFileInput").show();
    9695                        return;
    9796                }
    … …  
    109108{
    110109        if(GnuBoat.private.serverBaseUrl == null){
    111                 GnuBoat.displayMessage('<span class="error">No server set/found</span>');
     110                GnuBoat.displayMessage("No server set/found");
    112111                return;
    113112        }
    … …  
    130129{
    131130        if(GnuBoat.private.serverBaseUrl == null){
    132                 displayMessage('<span class="error">No server set/found</span>');
     131                displayMessage("No server set/found");
    133132                return;
    134133        }
    … …  
    143142                success: function(data){
    144143                        if(("error" in data) && data["error"] == 1){
    145                                 GnuBoat.displayMessage('<span class="error">Failed to upload map: '+ data["errormessage"] +'</span>');
     144                                alert("Failed to upload map: "+ data["errormessage"]);
    146145                                $("#mapTileUploadProgress").hide();
    147146                                $("#mapFileInput").show();
    148147                                return;
    149148                        }
    150                         GnuBoat.displayMessage('<span class="error">Map upload successfully</span>');
     149                        alert("Map upload successfully");
    151150                        $("#mapTileUploadProgress").hide();
    152151                        $("#mapFileInput").show();
    … …  
    154153                },
    155154                error: function(jqXHR, exception, errorThrown){
    156                         GnuBoat.displayMessage('<span class="error">Failed to upload map (XHR): '+ exception +'</span>');
     155                        alert("Failed to upload map (XHR): "+ exception);
    157156                        $("#mapTileUploadProgress").hide();
    158157                        $("#mapFileInput").show();
    … …  
    168167GnuBoat.initialize = function()
    169168{
    170         $("#mapModusSelect").change(function(){ GnuBoat.private.mapModusChanged(); });
    171169        $("#mapTileUploadProgress").hide();
    172170        $("#logfilesReload").click(GnuBoat.logfilesLoad);
    … …  
    216214        GnuBoat.private.renderControls = new THREE.OrbitControls( GnuBoat.private.renderCamera, GnuBoat.private.renderRenderer.domElement );
    217215        GnuBoat.private.renderControls.zoomSpeed = 2;
     216       
     217       
     218       
     219        var deep = new THREE.Color(0x347C7C);
     220        var shallow = new THREE.Color(0xBCD9D9);
     221        var size = 5;
     222        GnuBoat.private.renderDepthSteps = 50;
     223
     224        var deltaR = (Math.max(deep.r, shallow.r) - Math.min(deep.r, shallow.r))/GnuBoat.private.renderDepthSteps;
     225        var deltaG = (Math.max(deep.g, shallow.g) - Math.min(deep.g, shallow.g))/GnuBoat.private.renderDepthSteps;
     226        var deltaB = (Math.max(deep.b, shallow.b) - Math.min(deep.b, shallow.b))/GnuBoat.private.renderDepthSteps;
     227        for(var i = 0; i < GnuBoat.private.renderDepthSteps; i++){
     228                var stepColor = new THREE.Color(Math.max(deep.r, shallow.r) - i * deltaR,
     229                                                                                Math.max(deep.g, shallow.g) - i * deltaG,
     230                                                                                Math.max(deep.b, shallow.b) - i * deltaB);
     231                GnuBoat.private.renderDepthMaterials.push(stepColor);
     232        }
     233        GnuBoat.private.renderDepthMaterials.push(shallow);
    218234}
    219235
    … …  
    226242{
    227243        if(GnuBoat.private.serverBaseUrl == null){
    228                 GnuBoat.displayMessage('<span class="error">No server set/found</span>');
     244                GnuBoat.displayMessage("No server set/found");
    229245                return;
    230246        }
    … …  
    234250        if(GnuBoat.private.timerDisplay == null)
    235251                GnuBoat.private.timerDisplay = setInterval(GnuBoat.displayDataGet, 10000);
    236         GnuBoat.logfilesLoad();
     252        GnuBoat.logfilesLoad(); 
    237253       
    238254        GnuBoat.private.animate();
    … …  
    260276        mapsMetadata: null,
    261277        mapBounds: null,
    262         mapModusLive: true,
    263         mapHotlineGradientDefault: { absolute: false, palette: { 0.0: 'green', 0.5: 'yellow', 1.0: 'red' } },
    264278        dataMappings: {
    265279                speedthroughwater: {display: true, map: true, mapActive: false, titleLong: "Speed Through Water", titleShort: "STW", unit: "kts"},
    266280                speedoverground:  {display: true, map: true, mapActive: false, titleLong: "Speed Over Ground", titleShort: "SOG", unit: "kts"},
    267                 waterdepth: {
    268                         display: true, map: true, mapActive: true, titleLong: "Waterdepth", titleShort: "Depth", unit: "m",
    269                         gradient: {
    270                                 absolute: true,
    271                                 palette: { 0: 'DarkBlue', 2: 'DodgerBlue', 6: 'LightBlue', 10: 'AliceBlue'},
    272                         }
    273                 },
     281                waterdepth: {display: true, map: true, mapActive: true, titleLong: "Waterdepth", titleShort: "Depth", unit: "m"},
    274282                watertemperature: {display: true, map: true, mapActive: false, titleLong: "Watertemperature", titleShort: "Water", unit: "°C"},
    275283                gpsfix: {display: true, map: false, mapActive: false, titleLong: "GPS Fix", titleShort: "Fix", unit: ""},
    … …  
    284292        renderControls: null,
    285293        renderCloud: null,
     294        renderDepthMaterials: [],
     295        renderDepthSteps: null,
    286296       
    287297        openLink: function(target)
    … …  
    292302        displayDataSet: function(data)
    293303        {
    294 //              if(!Array.isArray(data) || data.length < 1){
    295 //                      console.log("No data array returned!");
    296 //                      console.log(data);
    297 //                      return;
    298 //              }
    299                 if(("error" in data) && data["error"] == 1){
    300                         GnuBoat.displayMessage('<span class="error">Failed to get display data and tracks: '+ data["errormessage"] +'</span>');
    301                         return;
    302                 }
    303 
    304304                var keysDisplay = [];
    305305                for(var key in GnuBoat.private.dataMappings){
    … …  
    307307                                keysDisplay.push(key);
    308308                }
    309 
     309                if(!Array.isArray(data) && !(data instanceof Object)){
     310                        console.log("No data array returned!");
     311                        console.log(data);
     312                        return;
     313                }
    310314                if(!("lastvalid" in data)){
    311315                                console.log("No last valid values given!");
    … …  
    329333                }
    330334               
    331                 // map displays logged data
    332                 if(!GnuBoat.private.mapModusLive)
    333                         return;
    334                 else if(!("track" in data)){
    335                         console.log("No track given!");
    336                         return;
    337                 }
    338                 GnuBoat.private.mapAddTracks(data["track"]);
     335                if(!("track" in data)){
     336                                console.log("No track given!");
     337                }
     338                else{
     339                        if(GnuBoat.private.map == null){
     340                                console.log("No map in use");
     341                        }
     342                        else{
     343                                var track = data["track"];
     344                                var maximas = [];
     345                                var minimas = [];
     346                                var points = [];
     347                                var densityPoints = [];
     348                               
     349                                var keysMap = [];
     350                                for(var key in GnuBoat.private.dataMappings){
     351                                        if(GnuBoat.private.dataMappings[key]["map"] === true)
     352                                                keysMap.push(key);
     353                                }
     354                                for(var i = 0; i < keysMap.length; i++){
     355                                        if(keysMap[i] == "gpsfix")
     356                                                continue;
     357                                        points[keysMap[i]] = [];
     358                                }
     359                               
     360                                // getting maximas, minimums for normalization and the tracks themselves
     361                                for(var time in track){
     362                                        for(var i = 0; i < keysMap.length; i++){
     363                                                var key = keysMap[i];
     364                                                if(key == "gpsfix")
     365                                                        continue;
     366                                                if(!(key in maximas))
     367                                                        maximas[key] = track[time][key]
     368                                                else if(maximas[key] < track[time][key])
     369                                                        maximas[key] = track[time][key];
     370                                                if(!(key in minimas))
     371                                                        minimas[key] = track[time][key]
     372                                                else if(minimas[key] > track[time][key])
     373                                                        minimas[key] = track[time][key];
     374                                                points[key].push(new L.latLng(track[time]["latitude"], track[time]["longitude"], track[time][key]));
     375                                                densityPoints.push({latitude: track[time]["latitude"], longitude: track[time]["longitude"], depth: track[time]["waterdepth"]});
     376                                        }
     377                                }
     378                                for(var i = 0; i < keysMap.length; i++){
     379                                        var key = keysMap[i];
     380                                        if(key == "gpsfix")
     381                                                continue;
     382                                        if(points[key].length > 0){
     383                                                if(key in GnuBoat.private.mapPolylines)
     384                                                        GnuBoat.private.mapPolylines[key].setLatLngs(points[key]);
     385                                                else{
     386                                                        GnuBoat.private.mapPolylines[key] = L.hotline(points[key], {weight: 3, outlineWidth: 0, min: minimas[key], max: maximas[key]});
     387                                                        if(GnuBoat.private.mapControl){
     388                                                                var name = GnuBoat.private.dataMappings[key]["titleLong"] +" in "+ GnuBoat.private.dataMappings[key]["unit"] +" ("+ GnuBoat.private.dataMappings[key]["titleShort"] +")";
     389                                                                GnuBoat.private.mapControl.addOverlay(GnuBoat.private.mapPolylines[key], name);
     390                                                        }
     391                                                        if(GnuBoat.private.dataMappings[key]["mapActive"] === true)
     392                                                                GnuBoat.private.mapPolylines[key].addTo(GnuBoat.private.map);
     393                                                }
     394                                        }
     395                                }
     396                                GnuBoat.private.drawDensityEstimation(densityPoints, maximas["waterdepth"], minimas["waterdepth"]);
     397                        }
     398                }
    339399        },
    340400       
    … …  
    372432                        // only initialize the map (viewport) once
    373433                        GnuBoat.private.map = L.map('mapViewport');
    374                         GnuBoat.private.map.on('overlayadd', function(layerObject){ GnuBoat.private.mapOverlayLegendSwitch(layerObject.layer); });
    375                         GnuBoat.private.map.on('overlayremove', function(layerObject){ GnuBoat.private.mapOverlayLegendSwitch(layerObject.layer); });
    376434                }
    377435                GnuBoat.private.map.setView([latitudeCenter, longitudeCenter], mapZoomStart);
    … …  
    469527        },
    470528       
    471         drawDensityEstimation: function(densityPoints, gradient, maximum, minimum)
    472         {
    473                 var colors = GnuBoat.private.gradientToRenderColors(gradient, maximum, minimum);
    474                 // converting all indizes into numbers to sort them correctly
    475                 // in descending order e.g. 10, 2, 1, 0 and not 2, 10, 1, 0
    476                 var colorsIndizes = Object.getOwnPropertyNames(colors);
    477                 colorsIndizes.sort(function(a, b){
    478                         a = +a;
    479                         b = +b;
    480                         return a-b;
    481                 });
    482                 var colorsCount = colorsIndizes.length;
    483                
     529        drawDensityEstimation: function(densityPoints, maximum, minimum)
     530        {
    484531                var material = new THREE.PointsMaterial({vertexColors: THREE.VertexColors, size: 5});
    485532                var geometry = new THREE.Geometry();
    … …  
    491538                        var mercator = GnuBoat.private.mercator(densityPoints[i].latitude, densityPoints[i].longitude);
    492539                        var vertex = new THREE.Vector3(mercator.x - mercatorSouthWest.x, mercator.y - mercatorSouthWest.y, (densityPoints[i].depth * -1) + maximum);
    493                         var step = (densityPoints[i].depth - minimum)/(maximum-minimum);
    494540                        var color = new THREE.Color(0x000000);
    495                         for(var j = 0; j < colorsCount; j++){
    496                                 if(j < colorsCount - 1)
    497                                         color = colors[colorsIndizes[j]];
    498                                 if(step <= colorsIndizes[j+1]){
    499                                         color = colors[colorsIndizes[j]];
    500                                         break;
    501                                 }
     541                        if(GnuBoat.private.renderDepthSteps != null){
     542                                var step = Math.floor((densityPoints[i].depth - minimum)/((maximum-minimum)/GnuBoat.private.renderDepthSteps));
     543                                if(step >= 0 && step < GnuBoat.private.renderDepthMaterials.length)
     544                                        color = GnuBoat.private.renderDepthMaterials[step];
    502545                        }
    503546                        geometry.vertices.push(vertex);
    … …  
    535578                return result;
    536579        },
    537        
    538         updateMapModus: function(data)
    539         {
    540                 var selected = $("#mapModusSelect").val();
    541                 $("#mapModusSelect").empty();
    542                 var selectedFound = false;
    543                 if(selected != null && Array.isArray(data)){
    544                         data.forEach(function(value, index){
    545                                 if(value == selected)
    546                                         selectedFound = true;
    547                         });
    548                 }
    549                 var selectedString = "";
    550                 if(!selectedFound)
    551                         selectedString = " selected";
    552                 $('<option value="live"'+ selectedString +'>Live View</option>').appendTo("#mapModusSelect");
    553                 if(!Array.isArray(data) || data.length < 1){
    554                         console.log(data);
    555                         return;
    556                 }
    557                 if(("error" in data) && data["error"] == 1){
    558                         GnuBoat.displayMessage('<span class="error">Failed to upload map: '+ data["errormessage"] +'</span>');
    559                         return;
    560                 }
    561                 data.forEach(function(value, index){
    562                         var selectedString = "";
    563                         if(value == selected)
    564                                 selectedString = " selected";
    565                         $("<option value=\""+ value +"\""+ selected +">"+ value +"</option>").appendTo("#mapModusSelect");
    566                 });
    567         },
    568        
    569         mapModusChanged: function()
    570         {
    571                 var modus = $("#mapModusSelect").val();
    572                 // live modus is automatically activated on displayDataSet
    573                 if(modus == "live"){
    574                         GnuBoat.private.mapModusLive = true;
    575                         return;
    576                 }
    577                 // remove overlays
    578                 if(GnuBoat.private.mapControl != null){
    579                         for(var key in GnuBoat.private.dataMappings){
    580                                 if(GnuBoat.private.dataMappings[key]["map"] === true)
    581                                         if(key in GnuBoat.private.mapPolylines){
    582                                                 GnuBoat.private.mapControl.removeLayer(GnuBoat.private.mapPolylines[key]);
    583                                                 GnuBoat.private.mapPolylines[key].remove();
    584                                                 delete GnuBoat.private.mapPolylines[key];
    585                                         }
    586                         }
    587                 }
    588                 GnuBoat.private.mapModusLive = false;
    589                 $.post({
    590                         url: GnuBoat.private.serverBaseUrl +'?request=replay',
    591                         data: { logfile: modus },
    592                         success: function(data){
    593 //                              if(!Array.isArray(data) || data.length < 1){
    594 //                                      console.log("No data array returned!");
    595 //                                      console.log(data);
    596 //                                      return;
    597 //                              }
    598                                 if(("error" in data) && data["error"] == 1){
    599                                         GnuBoat.displayMessage('<span class="error">Failed to get logged tracks: '+ data["errormessage"] +'</span>');
    600                                         return;
    601                                 }
    602                                 if(!("track" in data)){
    603                                         console.log("No track given!");
    604                                         return;
    605                                 }
    606                                 GnuBoat.private.mapAddTracks(data["track"]);
    607                         }
    608                 });
    609         },
    610        
    611         mapAddTracks: function(track)
    612         {
    613                 if(GnuBoat.private.map == null){
    614                         console.log("No map in use");
    615                         return;
    616                 }
    617                
    618                 $("#mapLegend").empty();
    619                 var maximas = [];
    620                 var minimas = [];
    621                 var points = [];
    622                 var densityPoints = [];
    623                
    624                 var keysMap = [];
    625                 for(var key in GnuBoat.private.dataMappings){
    626                         if(GnuBoat.private.dataMappings[key]["map"] === true)
    627                                 keysMap.push(key);
    628                 }
    629                 for(var i = 0; i < keysMap.length; i++){
    630                         points[keysMap[i]] = [];
    631                 }
    632                
    633                 // getting maximas, minimums for normalization and the tracks themselves
    634                 for(var time in track){
    635                         for(var i = 0; i < keysMap.length; i++){
    636                                 var key = keysMap[i];
    637                                 var value = track[time][key];
    638                                 if(!$.isNumeric(value))
    639                                         continue;
    640                                 if(!(key in maximas))
    641                                         maximas[key] = value
    642                                 else if(maximas[key] < value)
    643                                         maximas[key] = value;
    644                                 if(!(key in minimas))
    645                                         minimas[key] = value
    646                                 else if(minimas[key] > value)
    647                                         minimas[key] = value;
    648                                 points[key].push(new L.latLng(track[time]["latitude"], track[time]["longitude"], value));
    649                                 if(key == "waterdepth")
    650                                         densityPoints.push({latitude: track[time]["latitude"], longitude: track[time]["longitude"], depth: value});
    651                         }
    652                 }
    653                 for(var i = 0; i < keysMap.length; i++){
    654                         var key = keysMap[i];
    655                         if(points[key].length > 0){
    656                                 var palette = GnuBoat.private.mapHotlineGradientDefault.palette;
    657                                 var paletteLegend = GnuBoat.private.mapHotlineGradientDefault.palette;
    658                                 if("gradient" in GnuBoat.private.dataMappings[key]){
    659                                         palette = GnuBoat.private.gradientToPalette(GnuBoat.private.dataMappings[key]["gradient"], maximas[key], minimas[key]);
    660                                         // use original palette, to use absolute values, if possible
    661                                         paletteLegend = GnuBoat.private.dataMappings[key]["gradient"]["palette"];
    662                                 }
    663                                
    664                                 var legendTable = $('<table id="'+ key +'" class="hidden"></table>');
    665                                 $("<tr><th colspan=2>"+ GnuBoat.private.dataMappings[key]["titleShort"] +" in "+ GnuBoat.private.dataMappings[key]["unit"] +"</th></tr>").appendTo(legendTable);
    666                                 $("<tr><th>Level</th><th>Color</th></tr>").appendTo(legendTable);
    667                                 // converting all indizes into numbers to sort them correctly
    668                                 // e.g. 0, 1, 2, 10 and not 0, 1, 10, 2
    669                                 var indizes = Object.getOwnPropertyNames(paletteLegend);
    670                                 indizes.sort(function(a, b){
    671                                         a = +a;
    672                                         b = +b;
    673                                         return a-b;
    674                                 });
    675                                 for(var j=0; j < indizes.length; j++){
    676                                         var index = indizes[j];
    677                                         $('<tr><td class="level">'+ index.toString() +'</td><td style="background-color: '+ paletteLegend[index] +'"></td></tr>').appendTo(legendTable);
    678                                 }
    679                                 $('<tr><td colspan="2">Extrema: '+ maximas[key].toString() +' / '+ minimas[key].toString() +'</td></tr>').appendTo(legendTable);
    680                                
    681                                 var hotlineOptions = {
    682                                         weight: 3,
    683                                         outlineWidth: 0,
    684                                         min: minimas[key],
    685                                         max: maximas[key],
    686                                         palette: palette,
    687                                 };
    688                                
    689                                 legendTable.appendTo("#mapLegend");
    690                        
    691                                 if(key in GnuBoat.private.mapPolylines){
    692                                         GnuBoat.private.mapPolylines[key].setStyle(hotlineOptions);
    693                                         GnuBoat.private.mapPolylines[key].setLatLngs(points[key]);
    694                                         if(GnuBoat.private.map.hasLayer(GnuBoat.private.mapPolylines[key]))
    695                                                 GnuBoat.private.mapOverlayLegendSwitch(GnuBoat.private.mapPolylines[key]);
    696                                         GnuBoat.private.mapPolylines[key].unbindPopup();
    697                                 }
    698                                 else{
    699                                         GnuBoat.private.mapPolylines[key] = L.hotline(points[key], hotlineOptions);
    700                                         if(GnuBoat.private.mapControl){
    701                                                 var name = GnuBoat.private.dataMappings[key]["titleLong"] +" in "+ GnuBoat.private.dataMappings[key]["unit"] +" ("+ GnuBoat.private.dataMappings[key]["titleShort"] +")";
    702                                                 GnuBoat.private.mapControl.addOverlay(GnuBoat.private.mapPolylines[key], name);
    703                                         }
    704                                         if(GnuBoat.private.dataMappings[key]["mapActive"] === true)
    705                                                 GnuBoat.private.mapPolylines[key].addTo(GnuBoat.private.map);
    706                                 }
    707                                 GnuBoat.private.mapPolylines[key].bindPopup(legendTable[0].outerHTML);
    708                         }
    709                 }
    710                 var gradient = GnuBoat.private.mapHotlineGradientDefault.palette;
    711                 if("gradient" in GnuBoat.private.dataMappings["waterdepth"])
    712                         gradient = GnuBoat.private.dataMappings["waterdepth"]["gradient"];
    713                 GnuBoat.private.drawDensityEstimation(densityPoints, gradient, maximas["waterdepth"], minimas["waterdepth"]);
    714         },
    715        
    716         gradientToPalette: function(gradient, maximum, minimum)
    717         {
    718                 if(!("palette" in gradient)){
    719                         return GnuBoat.private.mapHotlineGradientDefault.palette;
    720                 }
    721                 if(!("absolute" in gradient) || !gradient.absolute){
    722                         // palette is already relative
    723                         return gradient.palette;
    724                 }
    725                 var range = maximum - minimum;
    726                 if(range == 0){
    727                         console.log("Range is zero --> Could not make gradient relative");
    728                         return  GnuBoat.private.mapHotlineGradientDefault.palette;
    729                 }
    730                 var palette = {};
    731                 var addedStop = false;
    732                 for(var indexAbs in gradient.palette){
    733                         var indexRel = (indexAbs - minimum)/range;
    734                         if(indexRel < 0){
    735                                 // add the nearest minimum value (which might be configured smaller than minimum)
    736                                 indexRel = 0;
    737                                 palette[indexRel] = gradient.palette[indexAbs];
    738                                 addedStop = true;
    739                         }
    740                         else if(indexRel < 1){
    741                                 palette[indexRel] = gradient.palette[indexAbs];
    742                                 addedStop = true;
    743                         }
    744                         else{
    745                                 // add first index > 1 as the maximum value at 1
    746                                 indexRel = 1;
    747                                 palette[indexRel] = gradient.palette[indexAbs];
    748                                 addedStop = true;
    749                                 break;
    750                         }
    751                 }
    752                 if(!addedStop)
    753                         return GnuBoat.private.mapHotlineGradientDefault.palette;
    754                 return palette;
    755         },
    756        
    757         gradientToRenderColors: function(gradient, maximum, minimum)
    758         {
    759                 var paletteRelative = GnuBoat.private.gradientToPalette(gradient, maximum, minimum);
    760 
    761                 var colors = {};
    762                 for(var index in paletteRelative)
    763                         colors[index] = new THREE.Color(paletteRelative[index].toLowerCase());
    764 
    765                 return colors;
    766         },
    767 
    768         mapOverlayLegendSwitch: function(layer)
    769         {
    770                 var overlayKey = null;
    771                 for(var key in GnuBoat.private.mapPolylines){
    772                         if(GnuBoat.private.mapPolylines.hasOwnProperty(key)){
    773                                 if(GnuBoat.private.mapPolylines[key] === layer){
    774                                         overlayKey = key;
    775                                         break;
    776                                 }
    777                         }
    778                 }
    779                 // ECMAScript 6
    780 //              var overlayKey = Object.keys(GnuBoat.private.mapPolylines).find(key => GnuBoat.private.mapPolylines[key] === overlay);
    781                 if(overlayKey == null)
    782                         return;
    783                 if(overlayKey){
    784                         $("#mapLegend #"+ overlayKey).toggleClass("hidden");
    785                 }
    786         },
    787580};
  • src/webapp/webservice/inc/GnuBoat/Config.php

    r944372e r949f66d  
    2626        public function __construct()
    2727        {
    28                 $configFile = __DIR__ ."/../../config/config.php";
     28                $configFile = __DIR__ ."/../config/config.php";
    2929                if(file_exists($configFile)){
    3030                        include($configFile);
    … …  
    5151        {
    5252                if(array_key_exists("datadirectory", $this->_config))
    53                         return $this->addTrailingSlash($this->_config["datadirectory"]);
     53                        return addTrailingSlash($this->_config["datadirectory"]);
    5454                return "/var/lib/gnuboat/";
    5555        }
    … …  
    5858        {
    5959                if(array_key_exists("logdirectory", $this->_config))
    60                         return $this->addTrailingSlash($this->_config["logdirectory"]);
     60                        return addTrailingSlash($this->_config["logdirectory"]);
    6161                return "/var/log/gnuboat/";
    6262        }
  • src/webapp/webservice/inc/GnuBoat/Service.php

    r944372e r949f66d  
    4444                $this->process();
    4545        }
    46        
    47         public static function errorStatic($message, $additionalContent = array(), $debug)
    48         {
    49                 error_log($message);
    50                 if($debug > 0)
    51                         print $message ."\n";
    52                 $result = ["error" => 1, "errormessage" => $message];
    53                 Service::outputStatic(array_merge($result, $additionalContent), $debug);
    54         }
    55        
    56         public static function outputStatic($content, $debug)
    57         {
    58                 header('Content-Type: application/json');
    59                 if($debug > 0){
    60                         echo json_encode($content,  JSON_PRETTY_PRINT) ."\n";
    61                 }
    62                 else{
    63                         echo json_encode($content) ."\n";
    64                 }
    65         }
    66        
    67         protected function error($message, $additionalContent = array())
    68         {
    69                 Service::errorStatic($message, $additionalContent, $this->debug());
    70         }
    71        
    72         protected function output($content)
    73         {
    74                 Service::outputStatic($content, $this->debug());
    75         }
    7646
    7747        /**
  • src/webapp/webservice/inc/GnuBoat/ServiceData.php

    r944372e r949f66d  
    2929                $this->_configRound = array
    3030                (
    31                         "latitude" => 4,
    32                         "longitude" => 4,
     31                        "latitude" => 5,
     32                        "longitude" => 5,
    3333                        "speedthroughwater" => 1,
    3434                        "speedoverground" => 1,
    35                         "courseoverground" => 1,
    3635                        "waterdepth" => 1,
    3736                        "watertemperature" => 1,
    … …  
    4948                $result["track"] = array();
    5049
    51                 if(!file_exists($dbFile))
    52                         return $this->error("Database file ". $dbFile ." does not exist");
    53 
     50                if(!file_exists($dbFile)){
     51                        echo json_encode("");
     52                        if($debug > 0)
     53                                echo "Database file ". $dbFile ." does not exist!";
     54                        error_log("Database file ". $dbFile ." does not exist");
     55                        exit;
     56                }
    5457                // Fetch entries of the last 30s with maximum (available) resolution of 2s
    5558                $this->addRrdData($dbFile, "2", "240", $result, $lastValid);
    56                 if($lastValid !== false){
    57                         $result["lastvalid"] = $lastValid->toArray();
     59                if($lastValid){
     60                        $result["lastvalid"] = $lastValid;
    5861                }
    5962                // Fetch entries of the last 1h with maximum (available) resolution of 10s
    … …  
    6265                $this->addRrdData($dbFile, "60", "86400", $result, $lastTime);
    6366
    64                 return $this->output($result);
     67                if($debug > 0){
     68                        echo json_encode($result,  JSON_PRETTY_PRINT) ."\n";
     69                }
     70                else{
     71                        header('Content-Type: application/json');
     72                        echo json_encode($result) ."\n";
     73                }
    6574        }
    6675
    … …  
    7382                $data = rrd_fetch($dbFile, array("AVERAGE", "--resolution", $interval, "--start", $startTime, "--end", $endTime));
    7483                // $data = rrd_fetch($dbFile, array("AVERAGE", "--resolution", $interval, "--start", "-". $period, "--end", "start+". $period, "--align-start"));
    75                 if($data === false)
    76                         return $this->error("Failure reading rrd database ". $dbFile .": ". rrd_error(), $result);
     84                if($data === false){
     85                        echo json_encode($result);
     86                        $message = "Failure reading rrd database ". $dbFile .": ". rrd_error();
     87                        if($debug > 0)
     88                                echo $message;
     89                        else
     90                                error_log($message);
     91                        return;
     92                }
    7793
    7894                if($debug > 2){
     95                        echo "<pre>";
    7996                        var_dump($data);
     97                        echo "</pre>";
    8098                }
    8199
    … …  
    84102                // transform them into json format
    85103                $i = 0;
    86                 $lastValid = false;
     104                $lastValid = -1;
    87105                $keys = array_keys($data);
    88106                $keyTimeframes = $keys[0];
    89107                $itemCount = count($keys);
    90                 if($itemCount < 0 )
    91                         return $this->error("No keys in fetched rrd data from ". $dbFile);
    92 
     108                if($itemCount < 0 ){
     109                        error_log("No keys in fetched rrd data from ". $dbFile);
     110                        echo json_encode("");
     111                        exit;
     112                }
    93113                $timeframesCount = count($data[$keyTimeframes]);
    94                 if($debug > 1){
    95                         error_log("Variables: ". $itemCount ."; Timeframes: ". $timeframesCount);
     114                if($debug > 0){
     115                        echo "<p>Variables: ". $itemCount ."; Timeframes: ". $timeframesCount ."</p>\n";
    96116                }
    97117                foreach($data[$keys[0]] as $timeframe => $value){
    98                         $tmp = new TrackItem($timeframe);
     118                        $allValid = true;
     119                        $gpsFix = false;
     120                        $tmp = array();
    99121                        foreach($keys as $key){
    100                                 $value = $data[$key][$timeframe];
    101                                 if(array_key_exists($key, $this->_configRound) && is_integer($this->_configRound[$key]))
    102                                         $value = round($value, $this->_configRound[$key]);
    103                                 if(!$tmp->setProperty($key, $value) && $debug > 1)
    104                                         error_log("Coult not set property ". $key ." to value ". $value ." at ". $timeframe);
     122                                if($key == "gpsfix"){
     123                                        switch($data[$key][$timeframe]){
     124                                                case 2:
     125                                                        $tmp[$key] = "2D";
     126                                                        $gpsFix = true;
     127                                                        break;
     128                                                case 3:
     129                                                        $tmp[$key] = "3D";
     130                                                        $gpsFix = true;
     131                                                        break;
     132                                                default:
     133                                                        $tmp[$key] = "-";
     134                                        }
     135                                }
     136                                else{
     137                                        $tmp[$key] = $data[$key][$timeframe];
     138                                        if(!is_numeric($tmp[$key]) || is_nan($tmp[$key])){
     139                                                $allValid = false;
     140                                                if($debug > 1){
     141                                                        echo "Invalid value ". $key ." (". $tmp[$key] .") at time ". $timeframe ."<br/>";
     142                                                }
     143                                        }
     144                                        elseif(array_key_exists($key, $this->_configRound) && is_integer($this->_configRound[$key]))
     145                                                $tmp[$key] = round($tmp[$key], $this->_configRound[$key]);
     146                                }
    105147                        }
    106148                        // only add the timeframe to the track, if the values are valid and we had a gps fix at that time
    107                         if($tmp->isValid()){
     149                        if($allValid){
    108150                                $lastValid = $tmp;
    109                                 if($tmp->gpsFixed()){
     151                                if($gpsFix){
    110152                                        if(!array_key_exists($timeframe, $result["track"])){
    111                                                 $result["track"][$timeframe] = $tmp->toArray();
     153                                                $result["track"][$timeframe] = $tmp;
    112154                                        }
    113155                                }
  • src/webapp/webservice/inc/GnuBoat/ServiceLogFiles.php

    r944372e r949f66d  
    3232                $debug = $this->debug();
    3333                $config = new Config();
    34                 if($debug > 1)
    35                         print "Log directory: ". $config->logDirectory() ."\n";
    3634
    3735                if(!array_key_exists("logfilesSelected", $_POST)){
    … …  
    3937                        $files = glob($config->logDirectory() ."*.log");
    4038                        array_walk($files, 'GnuBoat\ServiceLogFiles::stripLogDirectory');
    41                         return $this->output($files);
    42                 }
    4339
    44                 // prepare a download of available log files
    45                 $files = $_POST["logfilesSelected"];
    46                 if(count($files) < 1)
    47                         return $this->error("No logfile selected");
    48                 elseif(count($files) == 1){
    49                         $content = file_get_contents($config->logDirectory() . $files[0]);
    50                         if($content === false){
    51                                 echo "<html><head></head><body>Failed to read logfile ". $files[0] ."</body></html>";
     40                        header('Content-Type: application/json');
     41                        if($debug > 0){
     42                                echo json_encode($files,  JSON_PRETTY_PRINT) ."\n";
    5243                        }
    53                
    54                         header('Content-Type: text/plain');
    55                         header('Content-disposition: attachment; filename="'. $files[0] .'"');
    56                         header('Content-Length: ' . filesize($config->logDirectory() . $files[0]));
    57                         echo $content;
     44                        else{
     45                                echo json_encode($files) ."\n";
     46                        }
    5847                }
    5948                else{
    60                         $date = new \DateTime('NOW');
    61                         $archiveName = "gnuboat-logs-". $date->format("Y-m-d");
    62                
    63                         // provide files as zip file
    64                         $tmpArchive = tempnam(sys_get_temp_dir(), $archiveName);
    65                         $zip = new \ZipArchive();
    66                         if($zip->open($tmpArchive, \ZipArchive::CREATE) !== TRUE){
    67                                 echo "<html><head></head><body>Failed to create zip file</body></html>";
     49                        // prepare a download of available log files
     50                        $files = $_POST["logfilesSelected"];
     51                        if(count($files) < 1){
    6852                                return;
    6953                        }
    70                         foreach($files as $file){
    71                                 if($zip->addFile($config->logDirectory() . $file, $archiveName ."/". $file) !== true){
    72                                         $zip->close();
    73                                         echo "<html><head></head><body>Failed to add logfile ". $file ." to the zip file</body></html>";
     54                        elseif(count($files) == 1){
     55                                $content = file_get_contents($config->logDirectory() . $files[0]);
     56                                if($content === false){
     57                                        echo "<html><head></head><body>Failed to read logfile ". $files[0] ."</body></html>";
     58                                }
     59                       
     60                                header('Content-Type: text/plain');
     61                                header('Content-disposition: attachment; filename="'. $files[0] .'"');
     62                                header('Content-Length: ' . filesize($config->logDirectory() . $files[0]));
     63                                echo $content;
     64                        }
     65                        else{
     66                                $date = new \DateTime('NOW');
     67                                $archiveName = "gnuboat-logs-". $date->format("Y-m-d");
     68                       
     69                                // provide files as zip file
     70                                $tmpArchive = tempnam(sys_get_temp_dir(), $archiveName);
     71                                $zip = new \ZipArchive();
     72                                if($zip->open($tmpArchive, \ZipArchive::CREATE) !== TRUE){
     73                                        echo "<html><head></head><body>Failed to create zip file</body></html>";
    7474                                        return;
    7575                                }
     76                                foreach($files as $file){
     77                                        if($zip->addFile($config->logDirectory() . $file, $archiveName ."/". $file) !== true){
     78                                                $zip->close();
     79                                                echo "<html><head></head><body>Failed to add logfile ". $file ." to the zip file</body></html>";
     80                                                return;
     81                                        }
     82                                }
     83                                if($zip->close() !== true){
     84                                                echo "<html><head></head><body>Failed to save zip file</body></html>";
     85                                                return;
     86                                }
     87                               
     88                                echo "<html><head></head><body>Failed to add logfile ". $file ." to the zip file</body></html>";
     89                               
     90                                //Send zip folder
     91                                while (ob_get_level()) {
     92                                        ob_end_clean();
     93                                }
     94                                ob_start();
     95                                header('Content-Type: application/zip');
     96                                header('Content-Transfer-Encoding: Binary');
     97                                header('Content-disposition: attachment; filename=' . $archiveName . '.zip');
     98                                header('Content-Length: ' . filesize($tmpArchive));
     99                                ob_flush();
     100                                ob_clean();
     101                                readfile($tmpArchive);
     102                                unlink($tmpArchive);
     103                                return;
    76104                        }
    77                         if($zip->close() !== true){
    78                                         echo "<html><head></head><body>Failed to save zip file</body></html>";
    79                                         return;
    80                         }
    81                        
    82                         echo "<html><head></head><body>Failed to add logfile ". $file ." to the zip file</body></html>";
    83                        
    84                         //Send zip folder
    85                         while (ob_get_level()) {
    86                                 ob_end_clean();
    87                         }
    88                         ob_start();
    89                         header('Content-Type: application/zip');
    90                         header('Content-Transfer-Encoding: Binary');
    91                         header('Content-disposition: attachment; filename=' . $archiveName . '.zip');
    92                         header('Content-Length: ' . filesize($tmpArchive));
    93                         ob_flush();
    94                         ob_clean();
    95                         readfile($tmpArchive);
    96                         unlink($tmpArchive);
    97                         return;
    98105                }
    99106        }
  • src/webapp/webservice/inc/GnuBoat/ServiceMap.php

    r944372e r949f66d  
    3030        protected function process()
    3131        {
    32                 if(!array_key_exists("mapName", $_POST))
    33                         return $this->error("Please specify map name (no value)");
     32                header('Content-type: application/json');
    3433
     34                $result["error"] = 1;
     35                $result["errormessage"] = "Unknown Error";
     36
     37                if(!array_key_exists("mapName", $_POST)){
     38                        $result["error"] = 1;
     39                        $result["errormessage"] = "Please specify map name (no value)";
     40                        echo json_encode($result);
     41                        return;
     42                }
    3543                $mapName = $_POST["mapName"];
    36                 if(empty($mapName) || $mapName == "")
    37                         return $this->error("Please specifiy map name (empty value)");
     44                if(empty($mapName) || $mapName == ""){
     45                        $result["error"] = 1;
     46                        $result["errormessage"] = "Please specifiy map name (empty value)";
     47                        echo json_encode($result);
     48                        return;
     49                }
    3850
    3951                $mapDirectory = __DIR__ ."/../../maps";
    40                 if(!array_key_exists("mapFile", $_FILES))
    41                         return $this->error("No map file recieved");
    42 
    43                 if (!isset($_FILES['mapFile']['error']) || is_array($_FILES['mapFile']['error']))
    44                         return $this->error("Invalid parameters");
    45 
     52                if(!array_key_exists("mapFile", $_FILES)){
     53                        $result["error"] = 1;
     54                        $result["errormessage"] = "No map file recieved";
     55                        echo json_encode($result);
     56                        return;
     57                }
     58                if (!isset($_FILES['mapFile']['error']) || is_array($_FILES['mapFile']['error'])){
     59                        $result["error"] = 1;
     60                        $result["errormessage"] = "Invalid parameters";
     61                        echo json_encode($result);
     62                        return;
     63                }
    4664                switch ($_FILES['mapFile']['error']) {
    4765                        case UPLOAD_ERR_OK:
    4866                                break;
    4967                        case UPLOAD_ERR_NO_FILE:
    50                                 return $this->error("No file sent");
     68                                $result["error"] = 1;
     69                                $result["errormessage"] = "No file sent";
     70                                echo json_encode($result);
     71                                return;
    5172                        case UPLOAD_ERR_INI_SIZE:
    5273                        case UPLOAD_ERR_FORM_SIZE:
    53                                 return $this->error("Exceeded filesize limit.");
     74                                $result["error"] = 1;
     75                                $result["errormessage"] = "Exceeded filesize limit.";
     76                                echo json_encode($result);
     77                                return;
    5478                        default:
    55                                 return $this->error("Unknown PHP Error");
     79                                $result["error"] = 1;
     80                                $result["errormessage"] = "Unknown PHP Error";
     81                                echo json_encode($result);
     82                                return;
    5683                }
    5784                $mapFileName = $mapDirectory ."/". sha1_file($_FILES['mapFile']['tmp_name']) .".mbtiles";
    5885                if(move_uploaded_file($_FILES['mapFile']['tmp_name'], $mapFileName)){
    59                         if(!chmod($mapFileName, 0755))
    60                                 return $this->error("Could not change permissions of the map file");
    61                         // correct map metadata
    62                         $resultRename = $this->setMapName($mapFileName, $mapName);
    63                         if($resultRename[0] === true)
    64                                 return $this->output(["error" => 0, "errormessage" => ""]);
    65                        
    66                         return $this->error($resultRename[1]);
     86                        if(!chmod($mapFileName, 0755)){
     87                                $result["error"] = 1;
     88                                $result["errormessage"] = "Could not change permissions of the map file";
     89                        }
     90                        else{
     91                                // correct map metadata
     92                                $resultRename = $this->setMapName($mapFileName, $mapName);
     93                                if($resultRename[0] === true){
     94                                        $result["error"] = 0;
     95                                        $result["errormessage"] = "";
     96                                }
     97                                else{
     98                                        $result["error"] = 1;
     99                                        $result["errormessage"] = $resultRename[1];
     100                                }
     101                        }
    67102                }
    68                 else
    69                         return $this->error("Could not move map in place");
     103                else {
     104                        $result["error"] = 1;
     105                        $result["errormessage"] = "Could not move map in place";
     106                }
     107                echo json_encode($result);
    70108        }
    71109       
  • src/webapp/webservice/inc/GnuBoat/ServiceShutdown.php

    r944372e r949f66d  
    3636                if($handle === false){
    3737                        $message = "Could not create file (". $config->shutdownRequestFile() .") to indicate shutdown to the daemon.";
    38                         return $this->error($message, ["shutdownstart" => -1]);
     38                        error_log($message);
     39                        $result["shutdownstart"] = -1;
     40                        $result["errormessage"] = $message;
     41                }
     42                else{
     43                        $shutdownTime = new \DateTime('NOW');
     44                        $shutdownTime->modify("+15 seconds");
     45                        fwrite($handle, $shutdownTime->format(\DateTime::ATOM));
     46                        $result["shutdownstart"] = $shutdownTime->format(\DateTime::ATOM);
    3947                }
    4048
    41                 $shutdownTime = new \DateTime('NOW');
    42                 $shutdownTime->modify("+15 seconds");
    43                 fwrite($handle, $shutdownTime->format(\DateTime::ATOM));
    44                 fclose($handle);
    45                 $result["shutdownstart"] = $shutdownTime->format(\DateTime::ATOM);
    46                 $this->output($result);
     49                header('Content-Type: application/json');
     50                if($debug > 0){
     51                        echo json_encode($result,  JSON_PRETTY_PRINT) ."\n";
     52                }
     53                else{
     54                        echo json_encode($result) ."\n";
     55                }
    4756        }
    4857}
  • src/webapp/webservice/inc/GnuBoat/Webservice.php

    r944372e r949f66d  
    2323class WebService
    2424{
    25         function __construct($debug)
     25        function __construct()
    2626        {
    2727                $this->_requests = array();
    … …  
    3030                $this->_requests["logfiles"] = "GnuBoat\ServiceLogFiles";
    3131                $this->_requests["map"] = "GnuBoat\ServiceMap";
    32                 $this->_requests["replay"] = "GnuBoat\ServiceReplay";
    33                
    34                 $this->_debug = $debug;
    3532        }
    3633
    3734        public function process()
    3835        {
     36                $debug = 0;
     37                if(is_array($_GET) && array_key_exists("debug", $_GET))
     38                        $debug = $_GET["debug"];
     39
    3940                $request = array_keys($this->_requests)[0];
    4041                if(is_array($_GET) && array_key_exists("request", $_GET)){
    … …  
    4344
    4445                if(!array_key_exists($request, $this->_requests)){
    45                         return Service::errorStatic("Request ". $request ." not implemented", $this->_debug);
     46                        $result["error"] = 1;
     47                        $result["errormessage"] = "Request ". $request ." not implemented";
     48                       
     49                        header('Content-Type: application/json');
     50                        echo json_encode($result) ."\n";
     51                        return;
    4652                }
    47                
    48                 call_user_func(array(new $this->_requests[$request], "processRequest"), $this->_debug);
     53
     54                call_user_func(array(new $this->_requests[$request], "processRequest"), $debug);
    4955        }
    5056
    5157        private $_requests;
    52         private $_debug;
    5358}
    5459
  • src/webapp/webservice/inc/autoloader.php

    r944372e r949f66d  
    2525}
    2626
    27 function canClassBeLoaded($class) {
    28         $parts = explode('\\', $class);
    29         $fileName = __DIR__ ."/". join("/", $parts) .".php";
    30         return file_exists($fileName);
    31 }
    32 
    3327spl_autoload_register("gnuboatAutoloader");
    3428
  • src/webapp/webservice/index.php

    r944372e r949f66d  
    1919require_once(__DIR__ ."/inc/autoloader.php");
    2020
    21 $debug = 0;
    22 if(array_key_exists("debug", $_GET))
    23         $debug = $_GET["debug"];
    24 
    25 $webservice = new GnuBoat\Webservice($debug);
     21$webservice = new GnuBoat\Webservice();
    2622$webservice->process();
    2723
  • src/webapp/webservice/tests/ServiceTest.php

    r944372e r949f66d  
    2020// declare(Strict_types=1);
    2121
    22 namespace GnuBoat;
    23 
    2422/**
    25   * @brief Covers Service.php tests
     23  * @brief Covers index.php tests
    2624  */
    27 final class ServiceTest extends \PHPUnit_Framework_TestCase
     25final class ServiceTest extends PHPUnit_Framework_TestCase
    2826{
     27        /**
     28          * @runInSeparateProcess
     29          */
    2930        public function testData()
    3031        {
    31                 $webservice = new Webservice(0);
    32                 $this->assertInstanceOf(Webservice::class, $webservice);
    33                 $_GET["request"] = "data";
     32                $webservice = new GnuBoat\Webservice();
     33                $this->assertInstanceOf(GnuBoat\Webservice::class, $webservice);
     34                $_POST["request"] = "data";
    3435                $webservice->process();
    3536        }
    3637
     38        /**
     39          * @runInSeparateProcess
     40          */
    3741        public function testLogFiles()
    3842        {
    39                 $webservice = new Webservice(0);
    40                 $this->assertInstanceOf(Webservice::class, $webservice);
    41                 $_GET["request"] = "logfiles";
     43                $webservice = new GnuBoat\Webservice();
     44                $this->assertInstanceOf(GnuBoat\Webservice::class, $webservice);
     45                $_POST["request"] = "logfiles";
    4246                $webservice->process();
    4347        }
    4448       
     49        /**
     50          * @runInSeparateProcess
     51          */
    4552        public function testShutdown()
    4653        {
    47                 $webservice = new Webservice(0);
    48                 $this->assertInstanceOf(Webservice::class, $webservice);
    49                 $_GET["request"] = "shutdown";
     54                $webservice = new GnuBoat\Webservice();
     55                $this->assertInstanceOf(GnuBoat\Webservice::class, $webservice);
     56                $_POST["request"] = "shutdown";
    5057                $webservice->process();
    5158        }
    52 
     59       
     60        /**
     61          * @runInSeparateProcess
     62          */
    5363        public function testMap()
    5464        {
    55                 $webservice = new Webservice(0);
    56                 $this->assertInstanceOf(Webservice::class, $webservice);
    57                 $_GET["request"] = "map";
     65                $webservice = new GnuBoat\Webservice();
     66                $this->assertInstanceOf(GnuBoat\Webservice::class, $webservice);
     67                $_POST["request"] = "map";
    5868                $webservice->process();
    59         }
    60 
    61         public function testReplay()
    62         {
    63                 $webservice = new Webservice(0);
    64                 $_GET["request"] = "replay";
    65                 $_POST["logfile"] = "replay-test.log";
    66                 $webservice->process();
    67                 $output = $this->getActualOutput();
    68                 $this->assertJsonStringEqualsJsonString('{"track":{"1503767412":{"latitude":10.001,"longitude":1.001,"speedthroughwater":"-","speedoverground":11,"courseoverground":21,"waterdepth":"-","watertemperature":"-","gpsfix":"-"},"1503767413":{"latitude":20.002,"longitude":2.002,"speedthroughwater":"-","speedoverground":12,"courseoverground":22,"waterdepth":"-","watertemperature":"-","gpsfix":"-"},"1503767414":{"latitude":30.003,"longitude":3.003,"speedthroughwater":"-","speedoverground":13,"courseoverground":23,"waterdepth":1,"watertemperature":21,"gpsfix":"-"},"1503767415":{"latitude":40.004,"longitude":4.004,"speedthroughwater":"-","speedoverground":14,"courseoverground":24,"waterdepth":2,"watertemperature":22,"gpsfix":"-"},"1503767416":{"latitude":50.005,"longitude":5.005,"speedthroughwater":"-","speedoverground":15,"courseoverground":25,"waterdepth":3,"watertemperature":23,"gpsfix":"-"}}}', $output);
    6969        }
    7070}
    7171
    72 function error_log($msg)
    73 {
    74         echo "ERR GnuBoat: ". $msg ."\n";
    75 }
    76 
    7772?>
Note: See TracChangeset for help on using the changeset viewer.