source: src/webapp/webclient/js/GnuBoat.js@ 60de003a

0.5 debian/bullseye debian/jessie
Last change on this file since 60de003a was 79a1004, checked in by Joachim Langenbach <joachim.langenbach@…>, 9 years ago

Added hints to connect OpenCPN to the used webservice (Closes #3)

  • Property mode set to 100644
File size: 10.0 KB
RevLine 
[4ce069e]1/*
2
3 Copyright (C) 2016 - 2017 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
18 MA 02110-1301 USA.
19
20*/
21
22/** @namespace GnuBoat JavaScript namespace */
23var GnuBoat = GnuBoat || {};
24
25/**
26 * @brief Sets the webservice base url, used by any other functions
27 */
28GnuBoat.setServer = function(baseUrl)
29{
30 if(baseUrl.slice(-1) != "/")
31 baseUrl += "/";
32 GnuBoat.private.serverBaseUrl = baseUrl;
33
[79a1004]34 var link = document.createElement("a");
35 link.setAttribute("href", baseUrl);
36 $("#opencpnHint").empty();
37 $("<p>To connect OpenCPN with the GPSD running on this webservice, use <b>"+ link.hostname +":2947</b> and <b>"+ link.hostname +":2597</b> for the messages recieved on NMEA2000 bus.</p>").appendTo("#opencpnHint");
[4ce069e]38}
39
40/**
41 * @brief Used to display user messages
42 */
43GnuBoat.displayMessage = function(text)
44{
45 $("#message").clear();
46 $(shutdownHint).appendTo("#message");
47 location.hash = "#messages";
48}
49
50/**
51 * @brief Fetches the data shown in the display area from the webservice
52 */
53GnuBoat.displayDataGet = function()
54{
55 if(GnuBoat.private.serverBaseUrl == null){
56 GnuBoat.displayMessage("No server set/found");
57 return;
58 }
59 var gnuboatApi = GnuBoat.private.serverBaseUrl;
60 $.getJSON(gnuboatApi, GnuBoat.private.displayDataSet);
61};
62
63/**
64 * @brief Gets the metadata of all maps, provided by the tileserver
65 */
66GnuBoat.getMapInfos = function()
67{
68 if(GnuBoat.private.serverBaseUrl == null){
69 GnuBoat.displayMessage("No server set/found");
70 return;
71 }
72 $.getJSON(GnuBoat.private.serverBaseUrl +"tileserver.php?/index.json", GnuBoat.private.mapInfos);
73};
74
75/**
76 * @brief Fetches the list of available logfiles and adds them to the log file download form
77 */
78GnuBoat.logfilesLoad = function()
79{
80 if(GnuBoat.private.serverBaseUrl == null){
81 GnuBoat.displayMessage("No server set/found");
82 return;
83 }
84 $("#logfilesForm").empty();
85 $.getJSON(GnuBoat.private.serverBaseUrl +"?request=logfiles", function(data){
86 if(!Array.isArray(data) || data.length < 1){
87 $("<p>No Logfiles found!</p>").appendTo("#logfilesForm");
88 console.log(data);
89 return;
90 }
91 if(("error" in data) && data["error"] == 1){
92 alert("Failed to upload map: "+ data["errormessage"]);
93 $("#mapTileUploadProgress").hide();
94 $("#mapFileInput").show();
95 return;
96 }
97 $("<select id=\"logfilesSelect\" name=\"logfilesSelected[]\" class=\"pure-input-1\" multiple></select>").appendTo("#logfilesForm");
98 $("<input type=\"submit\" class=\"pure-button pure-button-primary\" name=\"logfilesDownload\" value=\"Download\"/>").appendTo("#logfilesForm");
99 data.forEach(function(value, index){
100 $("<option value=\""+ value +"\">"+ value +"</option>").appendTo("#logfilesSelect");
101 });
102 });
103};
104/**
105 * @brief Sends a shutdown request to the webservice
106 */
107GnuBoat.shutdown = function()
108{
109 if(GnuBoat.private.serverBaseUrl == null){
110 GnuBoat.displayMessage("No server set/found");
111 return;
112 }
113 $.getJSON(GnuBoat.private.serverBaseUrl +"?request=shutdown", function(data){
114 var shutdownTime = data["shutdownstart"];
115 var shutdownDate = Date.parse(shutdownTime);
116 var currentDate = new Date();
117 var shutdownHint = "Shutting down in "+ Math.floor((shutdownDate - currentDate)/1000) +"s at "+ shutdownTime.toLocaleString();
118 if(shutdownTime == -1){
119 shutdownHint = "Failed to initiate shutdown: "+ data["errormessage"];
120 }
121 GnuBoat.displayMessage(shutdownHint);
122 });
123};
124
125/**
126 * @brief Uploads a map and refreshes the maps metadata on success
127 */
128GnuBoat.uploadMap = function(form)
129{
130 if(GnuBoat.private.serverBaseUrl == null){
131 displayMessage("No server set/found");
132 return;
133 }
134 $("#mapFileInput").hide();
135 $("#mapTileUploadProgress").show();
136 $.ajax({
137 type: 'POST',
138 url: GnuBoat.private.serverBaseUrl +'?request=map',
139 data: new FormData($("#mapTileUpload")[0]),
140 contentType: false,
141 processData: false,
142 success: function(data){
143 if(("error" in data) && data["error"] == 1){
144 alert("Failed to upload map: "+ data["errormessage"]);
145 $("#mapTileUploadProgress").hide();
146 $("#mapFileInput").show();
147 return;
148 }
149 alert("Map upload successfully");
150 $("#mapTileUploadProgress").hide();
151 $("#mapFileInput").show();
152 GnuBoat.getMapInfos();
153 },
154 error: function(jqXHR, exception, errorThrown){
155 alert("Failed to upload map (XHR): "+ exception);
156 $("#mapTileUploadProgress").hide();
157 $("#mapFileInput").show();
158 }
159 }).progress(function(e){
160 $("#mapTileUploadProgress").attr({value: e.oloaded, max: e.total});
161 });
162};
163
164/**
165 * @brief Setups up GnuBoat to be able to start() after configured a server with setServer().
166 */
167GnuBoat.initialize = function()
168{
169 $("#mapTileUploadProgress").hide();
170 $("#logfilesReload").click(GnuBoat.logfilesLoad);
171 $("#shutdownButton").click(GnuBoat.shutdown);
172
173 $("#mapTileUpload").validate({
174 rules: {
175 mapFile: {
176 required: true
177 },
178 mapName: {
179 required: true
180 }
181 },
182 submitHandler: function(form){
183 GnuBoat.uploadMap(form);
184 }
185 });
186
187 $("#logfilesForm").validate({
188 rules: {
189 logfilesSelect: {
190 required: true
191 },
192 }
193 });
194}
195
196/**
197 * @brief Starts querying the webservice
198 *
199 * Call initialize() and setServer() before start()
200 */
201GnuBoat.start = function()
202{
203 if(GnuBoat.private.serverBaseUrl == null){
204 GnuBoat.displayMessage("No server set/found");
205 return;
206 }
207
208 GnuBoat.getMapInfos();
209 GnuBoat.displayDataGet();
210 if(GnuBoat.private.timerDisplay == null)
211 GnuBoat.private.timerDisplay = setInterval(GnuBoat.displayDataGet, 10000);
212 GnuBoat.logfilesLoad();
213}
214
215/**
216 * @brief Stops querying the webservice
217 */
218GnuBoat.stop = function()
219{
220 if(GnuBoat.private.timerDisplay != null){
221 clearInterval(GnuBoat.private.timerDisplay);
222 GnuBoat.private.timerDisplay = null;
223 }
224}
225
226/**
227 * @brief Private methods and properties of GnuBoat
228 */
229GnuBoat.private = {
230 map: null,
231 mapLayerCurrent: null,
232 // var mapControl = null;
233 mapsMetadata: null,
234 polyline: null,
235 serverBaseUrl: null,
236 timerDisplay: null,
237
238 openLink: function(target)
239 {
240 window.location=target;
241 },
242
243 displayDataSet: function(data)
244 {
245 if(!Array.isArray(data) && !(data instanceof Object)){
246 console.log("No data array returned!");
247 console.log(data);
248 return;
249 }
250 if(!("lastvalid" in data)){
251 console.log("No last valid values given!");
252 }
253 else{
254 var lastValid = data["lastvalid"];
255 var keys = ["speedthroughwater", "speedoverground", "waterdepth", "watertemperature", "gpsfix"];
256 for(var i = 0; i < keys.length; i++){
257 var key = keys[i];
258 var value = lastValid[key];
259 if($.isNumeric(value)){
260 var text = value.toFixed(1);
261 if(key == "watertemperature"){
262 text = value.toFixed(0);
263 }
264 $("#display #"+ keys[i] +" #value").text(text);
265 }
266 else if(key == "gpsfix"){
267 $("#display #"+ keys[i] +" #value").text(value);
268 }
269 }
270 }
271
272 if(!("track" in data)){
273 console.log("No track given!");
274 }
275 else{
276 if(GnuBoat.private.map == null){
277 console.log("No map in use");
278 }
279 else{
280 var track = data["track"];
281 var points = [];
282 for(var time in track){
283 points.push(new L.latLng(track[time]["latitude"], track[time]["longitude"]));
284 }
285 if(points.length > 0){
286 if(!GnuBoat.private.polyline){
287 GnuBoat.private.polyline = L.polyline(points, {color: 'red'}).addTo(GnuBoat.private.map);
288 }
289 else{
290 GnuBoat.private.polyline.setLatLngs(points);
291 }
292 GnuBoat.private.map.fitBounds(GnuBoat.private.polyline.getBounds());
293 }
294 }
295 }
296 },
297
298 mapSetup: function ()
299 {
300 var mapMetadataIndex = $("#mapSelect").val();
301 if(GnuBoat.private.mapsMetadata == null){
302 console.log("No mapsMetadata set");
303 return;
304 }
305 if(mapMetadataIndex < 0 || mapMetadataIndex >= GnuBoat.private.mapsMetadata.length){
306 console.log("Map metadata is outside of range :"+ mapMetadataIndex.toString());
307 console.log(mapsMetadata);
308 return;
309 }
310 var mapMetadata = GnuBoat.private.mapsMetadata[mapMetadataIndex];
311
312 var latitudeTop = mapMetadata["bounds"][3];
313 var latitudeBottom = mapMetadata["bounds"][1];
314 var longitudeLeft = mapMetadata["bounds"][0];
315 var longitudeRight = mapMetadata["bounds"][2];
316
317 var mapZoomMin = mapMetadata["minzoom"];
318 var mapZoomMax = mapMetadata["maxzoom"];
319
320 var latitudeCenter = (latitudeTop - latitudeBottom)/2 + latitudeBottom;
321 var longitudeCenter = (longitudeLeft - longitudeRight)/2 + longitudeRight;
322 var mapZoomStart = (mapZoomMax - mapZoomMin)/2 + mapZoomMin;
323
324 var mapBounds = new L.LatLngBounds(
325 new L.LatLng(latitudeBottom, longitudeLeft),
326 new L.LatLng(latitudeTop, longitudeRight));
327
328 if(GnuBoat.private.map == null){
329 // only initialize the map (viewport) once
330 GnuBoat.private.map = L.map('mapViewport');
331 }
332 GnuBoat.private.map.setView([latitudeCenter, longitudeCenter], mapZoomStart);
333
334 if(GnuBoat.private.mapLayerCurrent != null){
335 GnuBoat.private.map.removeLayer(GnuBoat.private.mapLayerCurrent);
336 GnuBoat.private.mapLayerCurrent = null;
337 }
338 GnuBoat.private.mapLayerCurrent = L.tileLayer(mapMetadata["tiles"][0], {
339 minZoom: mapZoomMin, maxZoom: mapZoomMax,
340 bounds: mapBounds,
341 attribution: mapMetadata["name"],
342 opacity: 0.85
343 }).addTo(GnuBoat.private.map);
344 },
345
346 mapInfos: function(data)
347 {
348 GnuBoat.private.mapsMetadata = data;
349
350 $("#mapSelect").empty();
351 var selected = "selected";
352 data.forEach(function(value, index){
353 $("<option value=\""+ index.toString() +"\" "+ selected +">"+ value["name"] +"</option>").appendTo("#mapSelect");
354 selected = "";
355 });
356
357 GnuBoat.private.mapSetup();
358 $("#mapSelect").change(function(){ mapSetup(); });
359 },
360};
Note: See TracBrowser for help on using the repository browser.