/* Copyright (C) 2016 - 2017 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ /** @namespace GnuBoat JavaScript namespace */ var GnuBoat = GnuBoat || {}; /** * @brief Sets the webservice base url, used by any other functions */ GnuBoat.setServer = function(baseUrl) { if(baseUrl.slice(-1) != "/") baseUrl += "/"; GnuBoat.private.serverBaseUrl = baseUrl; var link = document.createElement("a"); link.setAttribute("href", baseUrl); $("#opencpnHint").empty(); $("
To connect OpenCPN with the GPSD running on this webservice, use "+ link.hostname +":2947 and "+ link.hostname +":2597 for the messages recieved on NMEA2000 bus.
").appendTo("#opencpnHint"); } /** * @brief Used to display user messages */ GnuBoat.displayMessage = function(text) { $("#message").clear(); $(shutdownHint).appendTo("#message"); location.hash = "#messages"; } /** * @brief Fetches the data shown in the display area from the webservice */ GnuBoat.displayDataGet = function() { if(GnuBoat.private.serverBaseUrl == null){ GnuBoat.displayMessage("No server set/found"); return; } var gnuboatApi = GnuBoat.private.serverBaseUrl; $.getJSON(gnuboatApi, GnuBoat.private.displayDataSet); }; /** * @brief Gets the metadata of all maps, provided by the tileserver */ GnuBoat.getMapInfos = function() { if(GnuBoat.private.serverBaseUrl == null){ GnuBoat.displayMessage("No server set/found"); return; } $.getJSON(GnuBoat.private.serverBaseUrl +"tileserver.php?/index.json", GnuBoat.private.mapInfos); }; /** * @brief Fetches the list of available logfiles and adds them to the log file download form */ GnuBoat.logfilesLoad = function() { if(GnuBoat.private.serverBaseUrl == null){ GnuBoat.displayMessage("No server set/found"); return; } $("#logfilesForm").empty(); $.getJSON(GnuBoat.private.serverBaseUrl +"?request=logfiles", function(data){ if(!Array.isArray(data) || data.length < 1){ $("No Logfiles found!
").appendTo("#logfilesForm"); console.log(data); return; } if(("error" in data) && data["error"] == 1){ alert("Failed to upload map: "+ data["errormessage"]); $("#mapTileUploadProgress").hide(); $("#mapFileInput").show(); return; } $("").appendTo("#logfilesForm"); $("").appendTo("#logfilesForm"); data.forEach(function(value, index){ $("").appendTo("#logfilesSelect"); }); }); }; /** * @brief Sends a shutdown request to the webservice */ GnuBoat.shutdown = function() { if(GnuBoat.private.serverBaseUrl == null){ GnuBoat.displayMessage("No server set/found"); return; } $.getJSON(GnuBoat.private.serverBaseUrl +"?request=shutdown", function(data){ var shutdownTime = data["shutdownstart"]; var shutdownDate = Date.parse(shutdownTime); var currentDate = new Date(); var shutdownHint = "Shutting down in "+ Math.floor((shutdownDate - currentDate)/1000) +"s at "+ shutdownTime.toLocaleString(); if(shutdownTime == -1){ shutdownHint = "Failed to initiate shutdown: "+ data["errormessage"]; } GnuBoat.displayMessage(shutdownHint); }); }; /** * @brief Uploads a map and refreshes the maps metadata on success */ GnuBoat.uploadMap = function(form) { if(GnuBoat.private.serverBaseUrl == null){ displayMessage("No server set/found"); return; } $("#mapFileInput").hide(); $("#mapTileUploadProgress").show(); $.ajax({ type: 'POST', url: GnuBoat.private.serverBaseUrl +'?request=map', data: new FormData($("#mapTileUpload")[0]), contentType: false, processData: false, success: function(data){ if(("error" in data) && data["error"] == 1){ alert("Failed to upload map: "+ data["errormessage"]); $("#mapTileUploadProgress").hide(); $("#mapFileInput").show(); return; } alert("Map upload successfully"); $("#mapTileUploadProgress").hide(); $("#mapFileInput").show(); GnuBoat.getMapInfos(); }, error: function(jqXHR, exception, errorThrown){ alert("Failed to upload map (XHR): "+ exception); $("#mapTileUploadProgress").hide(); $("#mapFileInput").show(); } }).progress(function(e){ $("#mapTileUploadProgress").attr({value: e.oloaded, max: e.total}); }); }; /** * @brief Setups up GnuBoat to be able to start() after configured a server with setServer(). */ GnuBoat.initialize = function() { $("#mapTileUploadProgress").hide(); $("#logfilesReload").click(GnuBoat.logfilesLoad); $("#shutdownButton").click(GnuBoat.shutdown); $("#mapTileUpload").validate({ rules: { mapFile: { required: true }, mapName: { required: true } }, submitHandler: function(form){ GnuBoat.uploadMap(form); } }); $("#logfilesForm").validate({ rules: { logfilesSelect: { required: true }, } }); } /** * @brief Starts querying the webservice * * Call initialize() and setServer() before start() */ GnuBoat.start = function() { if(GnuBoat.private.serverBaseUrl == null){ GnuBoat.displayMessage("No server set/found"); return; } GnuBoat.getMapInfos(); GnuBoat.displayDataGet(); if(GnuBoat.private.timerDisplay == null) GnuBoat.private.timerDisplay = setInterval(GnuBoat.displayDataGet, 10000); GnuBoat.logfilesLoad(); } /** * @brief Stops querying the webservice */ GnuBoat.stop = function() { if(GnuBoat.private.timerDisplay != null){ clearInterval(GnuBoat.private.timerDisplay); GnuBoat.private.timerDisplay = null; } } /** * @brief Private methods and properties of GnuBoat */ GnuBoat.private = { map: null, mapLayerCurrent: null, mapPolylines: [], mapControl: null, mapsMetadata: null, dataMappings: { speedthroughwater: {display: true, map: true, mapActive: false, titleLong: "Speed Through Water", titleShort: "STW", unit: "kts"}, speedoverground: {display: true, map: true, mapActive: false, titleLong: "Speed Over Ground", titleShort: "SOG", unit: "kts"}, waterdepth: {display: true, map: true, mapActive: true, titleLong: "Waterdepth", titleShort: "Depth", unit: "m"}, watertemperature: {display: true, map: true, mapActive: false, titleLong: "Watertemperature", titleShort: "Water", unit: "°C"}, gpsfix: {display: true, map: false, mapActive: false, titleLong: "GPS Fix", titleShort: "Fix", unit: ""}, }, serverBaseUrl: null, timerDisplay: null, openLink: function(target) { window.location=target; }, displayDataSet: function(data) { var keysDisplay = []; for(var key in GnuBoat.private.dataMappings){ if(GnuBoat.private.dataMappings[key]["display"] === true) keysDisplay.push(key); } if(!Array.isArray(data) && !(data instanceof Object)){ console.log("No data array returned!"); console.log(data); return; } if(!("lastvalid" in data)){ console.log("No last valid values given!"); } else{ var lastValid = data["lastvalid"]; for(var i = 0; i < keysDisplay.length; i++){ var key = keysDisplay[i]; var value = lastValid[key]; if($.isNumeric(value)){ var text = value.toFixed(1); if(key == "watertemperature"){ text = value.toFixed(0); } $("#display #"+ key +" #value").text(text); } else if(key == "gpsfix"){ $("#display #"+ key +" #value").text(value); } } } if(!("track" in data)){ console.log("No track given!"); } else{ if(GnuBoat.private.map == null){ console.log("No map in use"); } else{ var track = data["track"]; var maximas = []; var minimas = []; var points = []; var keysMap = []; for(var key in GnuBoat.private.dataMappings){ if(GnuBoat.private.dataMappings[key]["map"] === true) keysMap.push(key); } for(var i = 0; i < keysMap.length; i++){ if(keysMap[i] == "gpsfix") continue; points[keysMap[i]] = []; } // getting maximas, minimums for normalization and the tracks themselves for(var time in track){ for(var i = 0; i < keysMap.length; i++){ var key = keysMap[i]; if(key == "gpsfix") continue; if(!(key in maximas)) maximas[key] = track[time][key] else if(maximas[key] < track[time][key]) maximas[key] = track[time][key]; if(!(key in minimas)) minimas[key] = track[time][key] else if(minimas[key] > track[time][key]) minimas[key] = track[time][key]; points[key].push(new L.latLng(track[time]["latitude"], track[time]["longitude"], track[time][key])); } } for(var i = 0; i < keysMap.length; i++){ var key = keysMap[i]; if(key == "gpsfix") continue; if(points[key].length > 0){ if(key in GnuBoat.private.mapPolylines){ GnuBoat.private.mapPolylines[key].setLatLngs(points[key]); } else{ GnuBoat.private.mapPolylines[key] = L.hotline(points[key], {weight: 3, outlineWidth: 0, min: minimas[key], max: maximas[key]}); if(GnuBoat.private.mapControl){ var name = GnuBoat.private.dataMappings[key]["titleLong"] +" in "+ GnuBoat.private.dataMappings[key]["unit"] +" ("+ GnuBoat.private.dataMappings[key]["titleShort"] +")"; GnuBoat.private.mapControl.addOverlay(GnuBoat.private.mapPolylines[key], name); } if(GnuBoat.private.dataMappings[key]["mapActive"] === true) GnuBoat.private.mapPolylines[key].addTo(GnuBoat.private.map); } } } } } }, mapSetup: function () { var mapMetadataIndex = $("#mapSelect").val(); if(GnuBoat.private.mapsMetadata == null){ console.log("No mapsMetadata set"); return; } if(mapMetadataIndex < 0 || mapMetadataIndex >= GnuBoat.private.mapsMetadata.length){ console.log("Map metadata is outside of range :"+ mapMetadataIndex.toString()); console.log(mapsMetadata); return; } var mapMetadata = GnuBoat.private.mapsMetadata[mapMetadataIndex]; var latitudeTop = mapMetadata["bounds"][3]; var latitudeBottom = mapMetadata["bounds"][1]; var longitudeLeft = mapMetadata["bounds"][0]; var longitudeRight = mapMetadata["bounds"][2]; var mapZoomMin = mapMetadata["minzoom"]; var mapZoomMax = mapMetadata["maxzoom"]; var latitudeCenter = (latitudeTop - latitudeBottom)/2 + latitudeBottom; var longitudeCenter = (longitudeLeft - longitudeRight)/2 + longitudeRight; var mapZoomStart = (mapZoomMax - mapZoomMin)/2 + mapZoomMin; var mapBounds = new L.LatLngBounds( new L.LatLng(latitudeBottom, longitudeLeft), new L.LatLng(latitudeTop, longitudeRight)); if(GnuBoat.private.map == null){ // only initialize the map (viewport) once GnuBoat.private.map = L.map('mapViewport'); } GnuBoat.private.map.setView([latitudeCenter, longitudeCenter], mapZoomStart); if(GnuBoat.private.mapLayerCurrent != null){ GnuBoat.private.map.removeLayer(GnuBoat.private.mapLayerCurrent); if(GnuBoat.private.mapControl) GnuBoat.private.mapControl.removeLayer(GnuBoat.private.mapLayerCurrent); GnuBoat.private.mapLayerCurrent = null; } GnuBoat.private.mapLayerCurrent = L.tileLayer(mapMetadata["tiles"][0], { minZoom: mapZoomMin, maxZoom: mapZoomMax, bounds: mapBounds, attribution: mapMetadata["name"], opacity: 0.85 }).addTo(GnuBoat.private.map); if(GnuBoat.private.mapControl) GnuBoat.private.mapControl.addBaseLayer(GnuBoat.private.mapLayerCurrent, "Map"); else{ GnuBoat.private.mapControl = L.control.layers({"Map": GnuBoat.private.mapLayerCurrent}, GnuBoat.private.mapOverlaysToList(), {hideSingleBase: true, sortLayers: true, }).addTo(GnuBoat.private.map); } }, mapInfos: function(data) { GnuBoat.private.mapsMetadata = data; $("#mapSelect").empty(); var selected = "selected"; data.forEach(function(value, index){ $("").appendTo("#mapSelect"); selected = ""; }); GnuBoat.private.mapSetup(); $("#mapSelect").change(function(){ mapSetup(); }); }, mapOverlaysToList: function() { var overlays = {}; for(var key in GnuBoat.private.mapPolylines){ overlays[key] = GnuBoat.private.mapPolylines[key]; } return overlays; }, };