-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
782 lines (716 loc) · 24.1 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
/*
* Copyright 2019-2023 Ilker Temir <[email protected]>
* Copyright 2023-2024 Saillogger LLC <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const POLL_INTERVAL = 5 // Poll every N seconds
const SUBMIT_INTERVAL = 1 // Submit to server every N minutes
const AIS_SUBMISSION_INTERVAL = 5 // Submit AIS data every N minutes
const SEND_METADATA_INTERVAL = 1 // Submit to API every N hours
const CONFIGURATION_PORT = 1977 // Port number for configuration
const API_BASE = 'https://saillogger.com/api/v1/collector'
const fs = require('fs')
const filePath = require('path')
const request = require('request')
const sqlite3 = require('sqlite3')
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const { machineId, machineIdSync } = require('node-machine-id');
const package = require('./package.json');
const userAgent = `Saillogger plugin v${package.version}`;
module.exports = function(app) {
var plugin = {};
var unsubscribes = [];
var submitProcess;
var aisSubmissionProcess;
var sendMetadataProcess;
var metdataSubmitted = false;
var db;
var uuid;
var gpsSource;
var configuration;
var monitoringConfiguration;
var updateLastCalled = Date.now();
var lastSuccessfulUpdate;
var position;
var speedOverGround;
var maxSpeedOverGround;
var courseOverGroundTrue;
var windSpeedApparent = 0;
var angleSpeedApparent;
var previousSpeeds = [];
var previousCOGs = [];
var deviceSerialNumber;
var aisTarget = {};
const selfMmsi = app.getSelfPath('mmsi');
plugin.id = "signalk-saillogger";
plugin.name = "Saillogger";
plugin.description = "Saillogger plugin for Signal K";
plugin.start = function(options) {
configuration = options;
startPlugin(options);
}
plugin.stop = function() {
app.debug(`Stopping the plugin`);
clearInterval(sendMetadataProcess);
clearInterval(submitProcess);
clearInterval(aisSubmissionProcess);
if (db) {
db.close();
}
};
plugin.schema = {
type: 'object',
required: ['uuid'],
properties: {
uuid: {
type: "string",
title: "Collector ID (obtain free from https://saillogger.com/boats/)"
},
source: {
type: "string",
title: "GPS source (leave empty if unsure; details at https://saillogger.com/support/)"
}
}
}
function startPlugin(options) {
let platform = findPlatform();
app.debug(`Running on ${platform}`);
if (!options.uuid) {
if ( isVenusOS() ) {
// We spin up the automatic configuration interface for Venus OS only
app.debug('Collector ID is required, going into configuration mode');
setupWebServerForConfiguration();
}
return
} else {
app.debug(`Starting the plugin with collector ID ${options.uuid}`);
}
uuid = options.uuid;
gpsSource = options.source;
deviceSerialNumber = machineIdSync();
app.setPluginStatus('Saillogger started. Please wait for a status update.');
let dbFile= filePath.join(app.getDataDirPath(), 'saillogger_v2.sqlite3');
db = new sqlite3.Database(dbFile);
db.run('CREATE TABLE IF NOT EXISTS buffer(ts REAL,' +
' latitude REAL,' +
' longitude REAL,' +
' speedOverGround REAL,' +
' courseOverGroundTrue REAL,' +
' windSpeedApparent REAL,' +
' angleSpeedApparent REAL,' +
' additionalData TEXT)');
db.run('CREATE TABLE IF NOT EXISTS configuration(id INTEGER PRIMARY KEY,' +
' config TEXT)');
getConfiguration();
sendMetadata();
let subscription = {
context: 'vessels.self',
subscribe: [{
path: 'navigation.position',
period: POLL_INTERVAL * 1000
}, {
path: 'navigation.speedOverGround',
period: POLL_INTERVAL * 1000
}, {
path: 'navigation.courseOverGroundTrue',
period: POLL_INTERVAL * 1000
}, {
path: 'environment.wind.speedApparent',
period: POLL_INTERVAL * 1000
}, {
path: 'environment.wind.angleApparent',
period: POLL_INTERVAL * 1000
}]
};
app.subscriptionmanager.subscribe(subscription, unsubscribes, function() {
app.error('Subscription error');
}, data => processDelta(data));
submitDataToServer();
updatePluginStatus();
// Send metadata and AIS targets after a warm-up period
setTimeout( function() {
sendMetadata();
sendAisTargets();
}, 60 * 1000);
sendMetadataProcess = setInterval( function() {
sendMetadata();
}, SEND_METADATA_INTERVAL * 60 * 60 * 1000);
submitProcess = setInterval( function() {
submitDataToServer();
updatePluginStatus();
}, SUBMIT_INTERVAL * 60 * 1000);
aisSubmissionProcess = setInterval( function() {
sendAisTargets();
}, AIS_SUBMISSION_INTERVAL * 60 * 1000);
}
function updatePluginStatus() {
db.get('SELECT COUNT(*) AS count FROM buffer', function(err, row) {
if (err) {
app.debug('Error querying buffer count:', err);
} else {
let message;
if (row.count == 1) {
message = `${row.count} entry in the queue,`;
} else {
message = `${row.count} entries in the queue,`;
}
if (lastSuccessfulUpdate) {
let since = timeSince(lastSuccessfulUpdate);
message += ` last connection to the server was ${since} ago.`;
} else {
message += ` no successful connection to the server since restart.`;
}
app.setPluginStatus(message);
}
});
}
function isVenusOS() {
return (fs.existsSync('/etc/venus'));
}
function getVictronDeviceModel() {
if (!isVenusOS()) {
return (null);
}
var name;
try {
name = require('child_process').execSync('/usr/bin/product-name', {stdio : 'pipe' }).toLocaleString()
} catch {
name = null;
}
return name;
}
function setupWebServerForConfiguration() {
var expressApp = express();
var corsOptions = {
origin: 'http://cdn.saillogger.com',
optionsSuccessStatus: 200
}
expressApp.use(cors(corsOptions));
expressApp.use(bodyParser.urlencoded({
extended: true,
}));
expressApp.post('/registerCollector', function (req, res, next) {
const model = getVictronDeviceModel();
if (configuration.uuid) {
app.debug(`Received a configuration request but collector id already set, ignoring`);
return res.json({
success: false,
reason: 'CollectorID already set',
model: model
});
}
let collectorId = req.body.collectorId;
app.debug(`Received request to configure collector with ${collectorId}`);
if (!collectorId) {
res.json({
success: false,
reason: 'No CollectorID',
model: model
});
} else {
configuration.uuid = collectorId;
app.savePluginOptions(configuration, () => {
app.debug(`Collector ID saved (${collectorId}), restarting the plugin`);
// Start the plugin with proper collectorId now
startPlugin(configuration);
res.json({
success: true,
reason: null,
model: model
});
});
}
})
expressApp.listen(CONFIGURATION_PORT, function () {
app.debug(`Configuration web server listening on port ${CONFIGURATION_PORT}`);
})
}
// Find the platform we are running on
function findPlatform() {
if ( isVenusOS() ) {
let platform = `Victron ${getVictronDeviceModel()}`;
return platform;
}
let platform = '';
try {
const cpuInfo = fs.readFileSync('/proc/cpuinfo', { encoding: 'utf8', flag: 'r' });
let re = /Model\s*:\s*([^\n]+)/i;
let found = cpuInfo.match(re);
if (found) {
platform += found[1];
}
re = /Model Name\s*:\s*([^\n]+)/i;
found = cpuInfo.match(re);
if (found) {
platform += ' ' + found[1];
}
} catch (err) {
app.debug('Cannot find /proc/cpuinfo');
}
return platform;
}
function saveConfiguration() {
config = JSON.stringify(monitoringConfiguration);
db.run('INSERT OR REPLACE INTO configuration(id, config) VALUES(1, ?)', [config], function(err) {
if (err) {
app.debug(`Failed to store configuration locally ${err}`);
} else {
app.debug('Configuration stored locally');
}
});
}
function loadConfiguration() {
db.get('SELECT * FROM configuration WHERE id=1', function(err, row) {
if (err) {
app.debug('Failed to load configuration');
} else {
if (row) {
app.debug('Configuration loaded from local storage');
monitoringConfiguration = JSON.parse(row.config);
} else {
app.debug('No locally stored configuration found');
}
}
});
}
function getConfiguration() {
app.debug('Retrieving monitoring configuration');
let options = {
uri: API_BASE + '/monitoring/' + uuid + '/configuration',
method: 'GET',
headers: {
'User-Agent': userAgent,
}
};
request.get(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
monitoringConfiguration = JSON.parse(body);
app.debug(`Monitoring configuration: ${JSON.stringify(monitoringConfiguration)}`);
saveConfiguration();
} else {
app.debug('Failed to get monitoring configuration, trying to load from local storage');
loadConfiguration();
}
});
}
function sendMetadata() {
function getAllKeys(obj, parentKey = '', result = []) {
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
const newKey = parentKey ? `${parentKey}.${key}` : key;
if (obj[key] !== null && typeof obj[key] === 'object') {
if (obj[key]['$source']) {
if (obj[key].value !== null && typeof(obj[key].value)=== 'number') {
result.push({
key: newKey,
unit: obj[key]?.meta?.units ?? null
});
}
} else {
getAllKeys(obj[key], newKey, result);
}
}
}
}
return result;
}
let self = app.getPath('self');
let dataModel = app.getPath(self);
let availableKeys=getAllKeys(dataModel);
let data = {
name: app.getSelfPath('name'),
mmsi: selfMmsi,
length: app.getSelfPath('design.length.value.overall'),
beam: app.getSelfPath('design.beam.value'),
height: app.getSelfPath('design.airHeight.value'),
ship_type: app.getSelfPath('design.aisShipType.value.id'),
version: package.version,
signalk_version: app.config.version,
platform: findPlatform(),
serial_number: deviceSerialNumber,
configuration: configuration,
available_keys: availableKeys
}
let postData = {
uri: API_BASE + '/' + uuid + '/update',
method: 'POST',
json: JSON.stringify(data),
headers: {
'User-Agent': userAgent,
}
};
app.debug (`Metadata: ${JSON.stringify(data)}`);
request(postData, function (error, response, body) {
if (!error && response.statusCode == 200) {
app.debug('Successfully submitted metadata');
lastSuccessfulUpdate = Date.now();
metdataSubmitted = true;
} else {
app.debug('Metadata submission failed');
}
});
}
function refreshAisData() {
function getVesselDetails(vessel) {
return {
beam: vessel.design?.beam?.value,
length: vessel.design?.length?.value,
shipType: vessel.design?.aisShipType?.value.id,
ais: {
class: vessel.sensors?.ais?.class?.value,
fromBow: vessel.sensors?.ais?.fromBow?.value,
fromCenter: vessel.sensors?.ais?.fromCenter?.value,
},
navigation: {
state: vessel.navigation?.specialManeuver?.value,
rateOfTurn: vessel.navigation?.rateOfTurn?.value,
specialManeuver: vessel.navigation?.specialManeuver?.value,
destination: vessel.navigation?.destination?.commonName?.value,
},
registrations: vessel.registrations?.value
}
}
let vessels = app.getPath('vessels');
let detectedTargets = [];
for (let key in vessels) {
let vessel=vessels[key];
if ((!vessel.mmsi) || (vessel.mmsi == selfMmsi)) {
continue;
}
if (!("navigation" in vessel) || !("position" in vessel.navigation)) {
continue;
}
detectedTargets.push(vessel.mmsi);
let position = vessel.navigation.position.value;
let date = new Date(vessel.navigation.position.timestamp);
let timeStamp = Math.round(date.getTime()/1000);
let heading= vessel.navigation.courseOverGroundTrue?.value;
if (heading) {
heading = Math.round(heading * 57.295779513); // Convert to degrees
} else {
heading = vessel.navigation.headingTrue?.value;
if (heading) {
heading = Math.round(heading * 57.295779513); // Convert to degrees
} else {
heading = 0;
}
}
let speed=vessel.navigation.speedOverGround?.value;
if (speed) {
speed = speed*1.94384;
if (speed < 10) {
speed = Math.round(speed*10)/10;
} else {
speed = Math.round(speed);
}
} else {
speed = 0;
}
let shipType = vessel.design?.aisShipType?.value.name;
if (!shipType) {
shipType = 'Unknown';
}
let name;
if (!vessel.name) {
name = "Unknown";
} else {
name = vessel.name;
}
if (!(vessel.mmsi in aisTarget)) {
app.debug(`Inserting AIS vessel ${vessel.mmsi} details`);
aisTarget[vessel.mmsi] = {
counter: 0,
updated: timeStamp,
name: name,
position: position,
speed: speed,
heading: heading,
type: shipType,
vessel: getVesselDetails(vessel)
}
} else if (aisTarget[vessel.mmsi].updated != timeStamp) {
app.debug(`Updating AIS vessel ${vessel.mmsi} details`);
aisTarget[vessel.mmsi].updated = timeStamp;
aisTarget[vessel.mmsi].name = name;
aisTarget[vessel.mmsi].position = position;
aisTarget[vessel.mmsi].speed = speed;
aisTarget[vessel.mmsi].heading = heading;
aisTarget[vessel.mmsi].type = shipType;
if (aisTarget[vessel.mmsi].counter++ == 30) {
app.debug(`Sending full vessel details for ${vessel.mmsi}`);
aisTarget[vessel.mmsi].counter = 0;
aisTarget[vessel.mmsi].vessel = getVesselDetails(vessel);
} else {
delete aisTarget[vessel.mmsi].vessel;
}
} else {
app.debug(`AIS vessel ${vessel.mmsi} details not changed`);
}
}
// Remove vessels that moved out of range
for (let mmsi in aisTarget) {
if (!detectedTargets.includes(mmsi)) {
delete aisTarget[mmsi];
}
}
}
function updateDatabase() {
let ts = Date.now();
updateLastCalled = ts;
if ((!position) || (!position.changedOn)) {
return
}
let monitoringDataInJson = null;
if (monitoringConfiguration) {
let monitoringData = getMonitoringData(monitoringConfiguration);
monitoringDataInJson = JSON.stringify(monitoringData);
} else {
getConfiguration();
monitoringDataInJson = null;
}
let values = [position.changedOn, position.latitude, position.longitude,
maxSpeedOverGround, courseOverGroundTrue, windSpeedApparent,
angleSpeedApparent, monitoringDataInJson];
db.run('INSERT INTO buffer VALUES(?, ?, ?, ?, ?, ?, ?, ?)', values, function(err) {
windSpeedApparent = 0;
maxSpeedOverGround = 0;
});
position.changedOn = null;
}
function submitDataToServer() {
db.all('SELECT * FROM buffer ORDER BY ts LIMIT 60', function(err, data) {
if (data.length == 0) {
app.debug('Local cache is empty, sending an empty ping');
}
let httpOptions = {
uri: API_BASE + '/' + uuid + '/push',
method: 'POST',
json: JSON.stringify(data),
headers: {
'User-Agent': userAgent,
}
};
request(httpOptions, function (error, response, body) {
if (!error && response.statusCode == 200) {
let lastTs = body.processedUntil;
app.debug(`Successfully submitted ${data.length} data record(s)`);
if (body.refreshMetadata) {
app.debug('Server requested metadata refresh');
sendMetadata();
}
if (monitoringConfiguration && (body.configurationVersion > monitoringConfiguration.version)) {
app.debug(`New monitoring configuration available (v${body.configurationVersion})`);
getConfiguration();
}
db.run('DELETE FROM buffer where ts <= ' + lastTs, function(err) {
lastSuccessfulUpdate = Date.now();
db.get('SELECT COUNT(*) AS count FROM buffer', function(err, row) {
if (err) {
app.debug('Error querying buffer count:', err);
} else if (row.count > 1) {
app.debug(`Cache not fully flushed, ${row.count} record(s) left. Continuing...`);
submitDataToServer();
}
});
});
} else if (!error && response.statusCode == 204) {
app.debug('Server responded with HTTP-204');
} else {
app.debug(`Connection to the server failed, retry in ${SUBMIT_INTERVAL} min`);
}
});
});
}
function getKeyValue(key, maxAge) {
let data = app.getSelfPath(key);
if (!data) {
return null;
}
let now = new Date();
let ts = new Date(data.timestamp);
let age = (now - ts) / 1000;
if (age <= maxAge) {
return data.value
} else {
return null;
}
}
function sendAisTargets() {
if (!monitoringConfiguration) {
app.debug('Monitoring configuration not available yet');
return
}
if (!monitoringConfiguration.sendAisTargets) {
app.debug('AIS target submission is disabled');
return
}
refreshAisData();
let data = {
aisTargets: aisTarget,
}
let httpOptions = {
uri: API_BASE + '/ais/' + uuid + '/push',
method: 'POST',
json: JSON.stringify(data),
headers: {
'User-Agent': userAgent,
}
};
app.debug(`Sending AIS data for ${Object.keys(data).length} vessels`);
request(httpOptions, function (error, response, responseData) {
if (!error && response.statusCode == 200) {
app.debug(`AIS data successfully submitted`);
} else {
app.debug('Submission of AIS data failed');
}
});
}
function getMonitoringData(configuration) {
let data = {
sog: metersPerSecondToKnots(getKeyValue('navigation.speedOverGround', 60)),
cog: radiantToDegrees(getKeyValue('navigation.courseOverGroundTrue', 60)),
heading: radiantToDegrees(getKeyValue('navigation.headingTrue', 60)),
anchor: {
position: getKeyValue('navigation.anchor.position', 60),
radius: getKeyValue('navigation.anchor.maxRadius', 60)
},
water: {
depth: getKeyValue(configuration.depthKey, 10),
temperature: kelvinToCelsius(getKeyValue(configuration.waterTemperatureKey, 90))
},
wind: {
speed: metersPerSecondToKnots(getKeyValue(configuration.windSpeedKey, 90)),
direction: radiantToDegrees(getKeyValue(configuration.windDirectionKey, 90))
},
pressure: pascalToHectoPascal(getKeyValue(configuration.pressureKey, 90)),
temperature: {
inside: kelvinToCelsius(getKeyValue(configuration.insideTemperatureKey, 90)),
outside: kelvinToCelsius(getKeyValue(configuration.outsideTemperatureKey, 90))
},
humidity: {
inside: floatToPercentage(getKeyValue(configuration.insideHumidityKey, 90)),
outside: floatToPercentage(getKeyValue(configuration.outsideHumidityKey, 90))
},
battery: {
voltage: getKeyValue(configuration.batteryVoltageKey, 60),
charge: floatToPercentage(getKeyValue(configuration.batteryChargeKey, 60))
}
};
for (let i = 0; i < configuration.additionalDataKeys.length; i++) {
let key = configuration.additionalDataKeys[i];
let value = getKeyValue(key, 60);
if (value) {
data[key] = value;
}
}
return data;
}
function timeSince(date) {
var seconds = Math.floor((new Date() - date) / 1000);
var interval = seconds / 31536000;
if (interval > 1) {
return Math.floor(interval) + " years";
}
interval = seconds / 2592000;
if (interval > 1) {
return Math.floor(interval) + " months";
}
interval = seconds / 86400;
if (interval > 1) {
return Math.floor(interval) + " days";
}
interval = seconds / 3600;
if (interval > 1) {
return Math.floor(interval) + " hours";
}
interval = seconds / 60;
if (interval > 1) {
return Math.floor(interval) + " minutes";
}
return Math.floor(seconds) + " seconds";
}
function radiantToDegrees(rad) {
if (rad == null) {
return null;
}
return Math.round(rad * 57.2958 * 10) / 10;
}
function metersPerSecondToKnots(ms) {
if (ms == null) {
return null;
}
return Math.round(ms * 1.94384 * 10) / 10;
}
function kelvinToCelsius(deg) {
if (deg == null) {
return null;
}
return Math.round((deg - 273.15) * 10) / 10;
}
function floatToPercentage(val) {
if (val == null) {
return null;
}
return val * 100;
}
function pascalToHectoPascal(pa) {
if (pa == null) {
return null;
}
return Math.round(pa/100*10)/10;
}
function processDelta(data) {
let dict = data.updates[0].values[0];
let path = dict.path;
let value = dict.value;
let timePassed = Date.now() - updateLastCalled;
switch (path) {
case 'navigation.position':
let source = data.updates[0]['$source'];
if ((gpsSource) && (source != gpsSource)) {
app.debug(`Skipping position from GPS resource ${source}`);
break;
}
if (timePassed >= SUBMIT_INTERVAL * 60 * 1000) {
position = value;
position.changedOn = Date.now();
updateDatabase();
}
break;
case 'navigation.speedOverGround':
// Keep the previous 3 values
speedOverGround = metersPerSecondToKnots(value);
maxSpeedOverGround = Math.max(maxSpeedOverGround, speedOverGround)
previousSpeeds.unshift(speedOverGround);
previousSpeeds = previousSpeeds.slice(0, 3);
break;
case 'navigation.courseOverGroundTrue':
// Keep the previous 3 values
courseOverGroundTrue = radiantToDegrees(value);
previousCOGs.unshift(courseOverGroundTrue);
previousCOGs = previousCOGs.slice(0, 6);
break;
case 'environment.wind.speedApparent':
windSpeedApparent = Math.max(windSpeedApparent, metersPerSecondToKnots(value));
break;
case 'environment.wind.angleApparent':
angleSpeedApparent = radiantToDegrees(value);
break;
default:
app.error('Unknown path: ' + path);
}
}
return plugin;
}