@noforeignland/signalk-to-noforeignland 1.0.1-beta.1 → 1.0.1-beta.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.github/workflows/publish.yml +40 -35
- package/CHANGELOG.md +112 -109
- package/README.md +45 -45
- package/cleanup-old-plugin.js +80 -0
- package/doc/beta_install_cerbo.md +106 -0
- package/doc/beta_install_rpi.md +64 -0
- package/doc/dev +17 -0
- package/index.js +979 -902
- package/package.json +35 -35
- package/doc/beta_install.md +0 -60
- package/migrate-config.js +0 -56
package/index.js
CHANGED
|
@@ -1,903 +1,980 @@
|
|
|
1
|
-
const { EOL } = require('os');
|
|
2
|
-
const fs = require('fs-extra');
|
|
3
|
-
const path = require('path');
|
|
4
|
-
const CronJob = require('cron').CronJob;
|
|
5
|
-
const readline = require('readline');
|
|
6
|
-
const fetch = require('node-fetch');
|
|
7
|
-
|
|
8
|
-
const apiUrl = 'https://www.noforeignland.com/home/api/v1/boat/tracking/track';
|
|
9
|
-
const pluginApiKey = '0ede6cb6-5213-45f5-8ab4-b4836b236f97';
|
|
10
|
-
const defaultTracksDir = 'nfl-track';
|
|
11
|
-
const routeSaveName = 'pending.jsonl';
|
|
12
|
-
const routeSentName = 'sent.jsonl';
|
|
13
|
-
|
|
14
|
-
class SignalkToNoforeignland {
|
|
15
|
-
constructor(app) {
|
|
16
|
-
this.app = app;
|
|
17
|
-
this.pluginId = 'signalk-to-noforeignland';
|
|
18
|
-
this.pluginName = 'Signal K to Noforeignland';
|
|
19
|
-
this.creator = 'signalk-track-logger';
|
|
20
|
-
|
|
21
|
-
// runtime state
|
|
22
|
-
this.unsubscribes = [];
|
|
23
|
-
this.unsubscribesControl = [];
|
|
24
|
-
this.lastPosition = null;
|
|
25
|
-
this.upSince = null;
|
|
26
|
-
this.cron = null;
|
|
27
|
-
this.options = {};
|
|
28
|
-
this.lastSuccessfulTransfer = null;
|
|
29
|
-
|
|
30
|
-
// Track status for data path updates
|
|
31
|
-
this.currentStatus = '';
|
|
32
|
-
this.currentError = null;
|
|
33
|
-
|
|
34
|
-
// Track auto-selected source
|
|
35
|
-
this.autoSelectedSource = null;
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
// Emit SignalK deltas for data paths
|
|
39
|
-
emitDelta(path, value) {
|
|
40
|
-
try {
|
|
41
|
-
const delta = {
|
|
42
|
-
context: 'vessels.self',
|
|
43
|
-
updates: [{
|
|
44
|
-
timestamp: new Date().toISOString(),
|
|
45
|
-
values: [{
|
|
46
|
-
path: path,
|
|
47
|
-
value: value
|
|
48
|
-
}]
|
|
49
|
-
}]
|
|
50
|
-
};
|
|
51
|
-
this.app.handleMessage(this.pluginId, delta);
|
|
52
|
-
} catch (err) {
|
|
53
|
-
this.app.debug(`Failed to emit delta for ${path}:`, err.message);
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
updateStatusPaths() {
|
|
58
|
-
const hasError = this.currentError !== null;
|
|
59
|
-
|
|
60
|
-
// SHORT format for data path
|
|
61
|
-
if (!hasError) {
|
|
62
|
-
const activeSource = this.options.filterSource || this.autoSelectedSource || '';
|
|
63
|
-
const saveTime = this.lastPosition ? new Date(this.lastPosition.currentTime).toLocaleTimeString() : 'None since start';
|
|
64
|
-
const transferTime = this.lastSuccessfulTransfer ? this.lastSuccessfulTransfer.toLocaleTimeString() : 'None since start';
|
|
65
|
-
const shortStatus = `Save: ${saveTime} | Transfer: ${transferTime}`;
|
|
66
|
-
this.emitDelta('noforeignland.status', shortStatus);
|
|
67
|
-
this.emitDelta('noforeignland.source', activeSource);
|
|
68
|
-
} else {
|
|
69
|
-
this.emitDelta('noforeignland.status', `ERROR: ${this.currentError}`);
|
|
70
|
-
}
|
|
71
|
-
this.emitDelta('noforeignland.status_boolean', hasError ? 1 : 0);
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
// Override setPluginStatus to also emit data path
|
|
75
|
-
setPluginStatus(status) {
|
|
76
|
-
this.currentStatus = status;
|
|
77
|
-
this.currentError = null;
|
|
78
|
-
this.app.setPluginStatus(status);
|
|
79
|
-
this.updateStatusPaths();
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
// Override setPluginError to also emit data path
|
|
83
|
-
setPluginError(error) {
|
|
84
|
-
this.currentError = error;
|
|
85
|
-
this.app.setPluginError(error);
|
|
86
|
-
this.updateStatusPaths();
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
getSchema() {
|
|
90
|
-
return {
|
|
91
|
-
title: this.pluginName,
|
|
92
|
-
description: 'Some parameters need for use',
|
|
93
|
-
type: 'object',
|
|
94
|
-
properties: {
|
|
95
|
-
// Mandatory Settings Group
|
|
96
|
-
mandatory: {
|
|
97
|
-
type: 'object',
|
|
98
|
-
title: 'Mandatory Settings',
|
|
99
|
-
properties: {
|
|
100
|
-
boatApiKey: {
|
|
101
|
-
type: 'string',
|
|
102
|
-
title: 'Boat API Key',
|
|
103
|
-
description: 'Boat API Key from noforeignland.com. Can be found in Account > Settings > Boat tracking > API Key.'
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
},
|
|
107
|
-
|
|
108
|
-
// Advanced Settings Group
|
|
109
|
-
advanced: {
|
|
110
|
-
type: 'object',
|
|
111
|
-
title: 'Advanced Settings',
|
|
112
|
-
properties: {
|
|
113
|
-
minMove: {
|
|
114
|
-
type: 'number',
|
|
115
|
-
title: 'Minimum boat move to log in meters',
|
|
116
|
-
description: 'To keep file sizes small we only log positions if a move larger than this size (if set to 0 will log every move)',
|
|
117
|
-
default: 80
|
|
118
|
-
},
|
|
119
|
-
minSpeed: {
|
|
120
|
-
type: 'number',
|
|
121
|
-
title: 'Minimum boat speed to log in knots',
|
|
122
|
-
description: 'To keep file sizes small we only log positions if boat speed goes above this value to minimize recording position on anchor or mooring (if set to 0 will log every move)',
|
|
123
|
-
default: 1.5
|
|
124
|
-
},
|
|
125
|
-
sendWhileMoving: {
|
|
126
|
-
type: 'boolean',
|
|
127
|
-
title: 'Attempt sending location while moving',
|
|
128
|
-
description: 'Should the plugin attempt to send tracking data to NFL while detecting the vessel is moving or only when stopped?',
|
|
129
|
-
default: true
|
|
130
|
-
},
|
|
131
|
-
ping_api_every_24h: {
|
|
132
|
-
type: 'boolean',
|
|
133
|
-
title: 'Force a send every 24 hours',
|
|
134
|
-
description: 'Keeps your boat active on NFL in your current location even if you do not move',
|
|
135
|
-
default: true
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
},
|
|
139
|
-
|
|
140
|
-
// Expert Settings Group
|
|
141
|
-
expert: {
|
|
142
|
-
type: 'object',
|
|
143
|
-
title: 'Expert Settings',
|
|
144
|
-
properties: {
|
|
145
|
-
filterSource: {
|
|
146
|
-
type: 'string',
|
|
147
|
-
title: 'Position source device',
|
|
148
|
-
description: 'EMPTY DEFAULT IS FINE - Set this value to the name of a source if you want to only use the position given by that source.'
|
|
149
|
-
},
|
|
150
|
-
trackDir: {
|
|
151
|
-
type: 'string',
|
|
152
|
-
title: 'Directory to cache tracks',
|
|
153
|
-
description: 'EMPTY DEFAULT IS FINE - Path to store track data. Relative paths are stored in plugin data directory. Absolute paths can point anywhere.\nDefault: nfl-track'
|
|
154
|
-
},
|
|
155
|
-
keepFiles: {
|
|
156
|
-
type: 'boolean',
|
|
157
|
-
title: 'Keep track files on disk',
|
|
158
|
-
description: 'If you have a lot of hard drive space you can keep the track files for logging purposes.',
|
|
159
|
-
default: false
|
|
160
|
-
},
|
|
161
|
-
trackFrequency: {
|
|
162
|
-
type: 'integer',
|
|
163
|
-
title: 'Position tracking frequency in seconds',
|
|
164
|
-
description: 'To keep file sizes small we only log positions once in a while (unless you set this value to 0)',
|
|
165
|
-
default: 60
|
|
166
|
-
},
|
|
167
|
-
apiCron: {
|
|
168
|
-
type: 'string',
|
|
169
|
-
title: 'Send attempt CRON',
|
|
170
|
-
description: 'We send the tracking data to NFL once in a while, you can set the schedule with this setting.\nCRON format: https://crontab.guru/',
|
|
171
|
-
default: '*/10 * * * *'
|
|
172
|
-
},
|
|
173
|
-
internetTestTimeout: {
|
|
174
|
-
type: 'number',
|
|
175
|
-
title: 'Timeout for testing internet connection in ms',
|
|
176
|
-
description: 'Set this number higher for slower computers and internet connections',
|
|
177
|
-
default: 2000
|
|
178
|
-
},
|
|
179
|
-
apiTimeout: {
|
|
180
|
-
type: 'integer',
|
|
181
|
-
title: 'API request timeout in seconds',
|
|
182
|
-
description: 'Timeout for sending data to NFL API. Increase for slow connections.',
|
|
183
|
-
default: 30,
|
|
184
|
-
minimum: 10,
|
|
185
|
-
maximum: 180
|
|
186
|
-
}
|
|
187
|
-
}
|
|
188
|
-
}
|
|
189
|
-
}
|
|
190
|
-
};
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
getPluginObject() {
|
|
194
|
-
return {
|
|
195
|
-
id: this.pluginId,
|
|
196
|
-
name: this.pluginName,
|
|
197
|
-
description: 'SignalK track logger to noforeignland.com',
|
|
198
|
-
schema: this.getSchema(),
|
|
199
|
-
start: this.start.bind(this),
|
|
200
|
-
stop: this.stop.bind(this)
|
|
201
|
-
};
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
async start(options = {}, restartPlugin) {
|
|
205
|
-
// Position data health check
|
|
206
|
-
this.positionCheckInterval = null;
|
|
207
|
-
this.lastPositionReceived = null;
|
|
208
|
-
|
|
209
|
-
// Backward compatibility: migrate old flat structure to new nested structure
|
|
210
|
-
let needsSave = false;
|
|
211
|
-
if (options.boatApiKey && !options.mandatory) {
|
|
212
|
-
this.app.debug('Migrating old configuration to new grouped structure');
|
|
213
|
-
needsSave = true;
|
|
214
|
-
|
|
215
|
-
options = {
|
|
216
|
-
mandatory: {
|
|
217
|
-
boatApiKey: options.boatApiKey
|
|
218
|
-
},
|
|
219
|
-
advanced: {
|
|
220
|
-
minMove: options.minMove !== undefined ? options.minMove : 50,
|
|
221
|
-
minSpeed: options.minSpeed !== undefined ? options.minSpeed : 1.5,
|
|
222
|
-
sendWhileMoving: options.sendWhileMoving !== undefined ? options.sendWhileMoving : true,
|
|
223
|
-
ping_api_every_24h: options.ping_api_every_24h !== undefined ? options.ping_api_every_24h : true
|
|
224
|
-
},
|
|
225
|
-
expert: {
|
|
226
|
-
filterSource: options.filterSource,
|
|
227
|
-
trackDir: options.trackDir,
|
|
228
|
-
keepFiles: options.keepFiles !== undefined ? options.keepFiles : false,
|
|
229
|
-
trackFrequency: options.trackFrequency !== undefined ? options.trackFrequency : 60,
|
|
230
|
-
internetTestTimeout: options.internetTestTimeout !== undefined ? options.internetTestTimeout : 2000,
|
|
231
|
-
apiCron: options.apiCron || '*/10 * * * *',
|
|
232
|
-
apiTimeout: options.apiTimeout !== undefined ? options.apiTimeout : 30
|
|
233
|
-
}
|
|
234
|
-
};
|
|
235
|
-
|
|
236
|
-
try {
|
|
237
|
-
this.app.debug('Saving migrated configuration...');
|
|
238
|
-
await this.app.savePluginOptions(options, () => {
|
|
239
|
-
this.app.debug('Configuration successfully migrated and saved');
|
|
240
|
-
});
|
|
241
|
-
} catch (err) {
|
|
242
|
-
this.app.debug('Failed to save migrated configuration:', err.message);
|
|
243
|
-
}
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
// Flatten the nested structure for easier access and apply defaults
|
|
247
|
-
this.options = {
|
|
248
|
-
boatApiKey: options.mandatory?.boatApiKey,
|
|
249
|
-
minMove: options.advanced?.minMove !== undefined ? options.advanced.minMove : 80,
|
|
250
|
-
minSpeed: options.advanced?.minSpeed !== undefined ? options.advanced.minSpeed : 1.5,
|
|
251
|
-
sendWhileMoving: options.advanced?.sendWhileMoving !== undefined ? options.advanced.sendWhileMoving : true,
|
|
252
|
-
ping_api_every_24h: options.advanced?.ping_api_every_24h !== undefined ? options.advanced.ping_api_every_24h : true,
|
|
253
|
-
filterSource: options.expert?.filterSource,
|
|
254
|
-
trackDir: options.expert?.trackDir || defaultTracksDir,
|
|
255
|
-
keepFiles: options.expert?.keepFiles !== undefined ? options.expert.keepFiles : false,
|
|
256
|
-
trackFrequency: options.expert?.trackFrequency !== undefined ? options.expert.trackFrequency : 60,
|
|
257
|
-
internetTestTimeout: options.expert?.internetTestTimeout !== undefined ? options.expert.internetTestTimeout : 2000,
|
|
258
|
-
apiCron: options.expert?.apiCron || '*/10 * * * *',
|
|
259
|
-
apiTimeout: options.expert?.apiTimeout !== undefined ? options.expert.apiTimeout : 30
|
|
260
|
-
};
|
|
261
|
-
|
|
262
|
-
// Validate that boatApiKey is set
|
|
263
|
-
if (!this.options.boatApiKey || this.options.boatApiKey.trim() === '') {
|
|
264
|
-
const errorMsg = 'No boat API key configured. Please set your API key in plugin settings (Mandatory Settings > Boat API key). You can find your API key at noforeignland.com under Account > Settings > Boat tracking > API Key.';
|
|
265
|
-
this.app.debug(errorMsg);
|
|
266
|
-
this.setPluginError(errorMsg);
|
|
267
|
-
this.stop();
|
|
268
|
-
return;
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
// Resolve track directory path
|
|
272
|
-
if (!path.isAbsolute(this.options.trackDir)) {
|
|
273
|
-
const dataDirPath = this.app.getDataDirPath();
|
|
274
|
-
this.options.trackDir = path.join(dataDirPath, this.options.trackDir);
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
if (!this.createDir(this.options.trackDir)) {
|
|
278
|
-
this.stop();
|
|
279
|
-
return;
|
|
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
|
-
if (
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
}
|
|
380
|
-
}
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
this.
|
|
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
|
-
this.
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
this.
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
const
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
const
|
|
883
|
-
if (
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
1
|
+
const { EOL } = require('os');
|
|
2
|
+
const fs = require('fs-extra');
|
|
3
|
+
const path = require('path');
|
|
4
|
+
const CronJob = require('cron').CronJob;
|
|
5
|
+
const readline = require('readline');
|
|
6
|
+
const fetch = require('node-fetch');
|
|
7
|
+
|
|
8
|
+
const apiUrl = 'https://www.noforeignland.com/home/api/v1/boat/tracking/track';
|
|
9
|
+
const pluginApiKey = '0ede6cb6-5213-45f5-8ab4-b4836b236f97';
|
|
10
|
+
const defaultTracksDir = 'nfl-track';
|
|
11
|
+
const routeSaveName = 'pending.jsonl';
|
|
12
|
+
const routeSentName = 'sent.jsonl';
|
|
13
|
+
|
|
14
|
+
class SignalkToNoforeignland {
|
|
15
|
+
constructor(app) {
|
|
16
|
+
this.app = app;
|
|
17
|
+
this.pluginId = 'signalk-to-noforeignland';
|
|
18
|
+
this.pluginName = 'Signal K to Noforeignland';
|
|
19
|
+
this.creator = 'signalk-track-logger';
|
|
20
|
+
|
|
21
|
+
// runtime state
|
|
22
|
+
this.unsubscribes = [];
|
|
23
|
+
this.unsubscribesControl = [];
|
|
24
|
+
this.lastPosition = null;
|
|
25
|
+
this.upSince = null;
|
|
26
|
+
this.cron = null;
|
|
27
|
+
this.options = {};
|
|
28
|
+
this.lastSuccessfulTransfer = null;
|
|
29
|
+
|
|
30
|
+
// Track status for data path updates
|
|
31
|
+
this.currentStatus = '';
|
|
32
|
+
this.currentError = null;
|
|
33
|
+
|
|
34
|
+
// Track auto-selected source
|
|
35
|
+
this.autoSelectedSource = null;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Emit SignalK deltas for data paths
|
|
39
|
+
emitDelta(path, value) {
|
|
40
|
+
try {
|
|
41
|
+
const delta = {
|
|
42
|
+
context: 'vessels.self',
|
|
43
|
+
updates: [{
|
|
44
|
+
timestamp: new Date().toISOString(),
|
|
45
|
+
values: [{
|
|
46
|
+
path: path,
|
|
47
|
+
value: value
|
|
48
|
+
}]
|
|
49
|
+
}]
|
|
50
|
+
};
|
|
51
|
+
this.app.handleMessage(this.pluginId, delta);
|
|
52
|
+
} catch (err) {
|
|
53
|
+
this.app.debug(`Failed to emit delta for ${path}:`, err.message);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
updateStatusPaths() {
|
|
58
|
+
const hasError = this.currentError !== null;
|
|
59
|
+
|
|
60
|
+
// SHORT format for data path
|
|
61
|
+
if (!hasError) {
|
|
62
|
+
const activeSource = this.options.filterSource || this.autoSelectedSource || '';
|
|
63
|
+
const saveTime = this.lastPosition ? new Date(this.lastPosition.currentTime).toLocaleTimeString() : 'None since start';
|
|
64
|
+
const transferTime = this.lastSuccessfulTransfer ? this.lastSuccessfulTransfer.toLocaleTimeString() : 'None since start';
|
|
65
|
+
const shortStatus = `Save: ${saveTime} | Transfer: ${transferTime}`;
|
|
66
|
+
this.emitDelta('noforeignland.status', shortStatus);
|
|
67
|
+
this.emitDelta('noforeignland.source', activeSource);
|
|
68
|
+
} else {
|
|
69
|
+
this.emitDelta('noforeignland.status', `ERROR: ${this.currentError}`);
|
|
70
|
+
}
|
|
71
|
+
this.emitDelta('noforeignland.status_boolean', hasError ? 1 : 0);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// Override setPluginStatus to also emit data path
|
|
75
|
+
setPluginStatus(status) {
|
|
76
|
+
this.currentStatus = status;
|
|
77
|
+
this.currentError = null;
|
|
78
|
+
this.app.setPluginStatus(status);
|
|
79
|
+
this.updateStatusPaths();
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Override setPluginError to also emit data path
|
|
83
|
+
setPluginError(error) {
|
|
84
|
+
this.currentError = error;
|
|
85
|
+
this.app.setPluginError(error);
|
|
86
|
+
this.updateStatusPaths();
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
getSchema() {
|
|
90
|
+
return {
|
|
91
|
+
title: this.pluginName,
|
|
92
|
+
description: 'Some parameters need for use',
|
|
93
|
+
type: 'object',
|
|
94
|
+
properties: {
|
|
95
|
+
// Mandatory Settings Group
|
|
96
|
+
mandatory: {
|
|
97
|
+
type: 'object',
|
|
98
|
+
title: 'Mandatory Settings',
|
|
99
|
+
properties: {
|
|
100
|
+
boatApiKey: {
|
|
101
|
+
type: 'string',
|
|
102
|
+
title: 'Boat API Key',
|
|
103
|
+
description: 'Boat API Key from noforeignland.com. Can be found in Account > Settings > Boat tracking > API Key.'
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
},
|
|
107
|
+
|
|
108
|
+
// Advanced Settings Group
|
|
109
|
+
advanced: {
|
|
110
|
+
type: 'object',
|
|
111
|
+
title: 'Advanced Settings',
|
|
112
|
+
properties: {
|
|
113
|
+
minMove: {
|
|
114
|
+
type: 'number',
|
|
115
|
+
title: 'Minimum boat move to log in meters',
|
|
116
|
+
description: 'To keep file sizes small we only log positions if a move larger than this size (if set to 0 will log every move)',
|
|
117
|
+
default: 80
|
|
118
|
+
},
|
|
119
|
+
minSpeed: {
|
|
120
|
+
type: 'number',
|
|
121
|
+
title: 'Minimum boat speed to log in knots',
|
|
122
|
+
description: 'To keep file sizes small we only log positions if boat speed goes above this value to minimize recording position on anchor or mooring (if set to 0 will log every move)',
|
|
123
|
+
default: 1.5
|
|
124
|
+
},
|
|
125
|
+
sendWhileMoving: {
|
|
126
|
+
type: 'boolean',
|
|
127
|
+
title: 'Attempt sending location while moving',
|
|
128
|
+
description: 'Should the plugin attempt to send tracking data to NFL while detecting the vessel is moving or only when stopped?',
|
|
129
|
+
default: true
|
|
130
|
+
},
|
|
131
|
+
ping_api_every_24h: {
|
|
132
|
+
type: 'boolean',
|
|
133
|
+
title: 'Force a send every 24 hours',
|
|
134
|
+
description: 'Keeps your boat active on NFL in your current location even if you do not move',
|
|
135
|
+
default: true
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
},
|
|
139
|
+
|
|
140
|
+
// Expert Settings Group
|
|
141
|
+
expert: {
|
|
142
|
+
type: 'object',
|
|
143
|
+
title: 'Expert Settings',
|
|
144
|
+
properties: {
|
|
145
|
+
filterSource: {
|
|
146
|
+
type: 'string',
|
|
147
|
+
title: 'Position source device',
|
|
148
|
+
description: 'EMPTY DEFAULT IS FINE - Set this value to the name of a source if you want to only use the position given by that source.'
|
|
149
|
+
},
|
|
150
|
+
trackDir: {
|
|
151
|
+
type: 'string',
|
|
152
|
+
title: 'Directory to cache tracks',
|
|
153
|
+
description: 'EMPTY DEFAULT IS FINE - Path to store track data. Relative paths are stored in plugin data directory. Absolute paths can point anywhere.\nDefault: nfl-track'
|
|
154
|
+
},
|
|
155
|
+
keepFiles: {
|
|
156
|
+
type: 'boolean',
|
|
157
|
+
title: 'Keep track files on disk',
|
|
158
|
+
description: 'If you have a lot of hard drive space you can keep the track files for logging purposes.',
|
|
159
|
+
default: false
|
|
160
|
+
},
|
|
161
|
+
trackFrequency: {
|
|
162
|
+
type: 'integer',
|
|
163
|
+
title: 'Position tracking frequency in seconds',
|
|
164
|
+
description: 'To keep file sizes small we only log positions once in a while (unless you set this value to 0)',
|
|
165
|
+
default: 60
|
|
166
|
+
},
|
|
167
|
+
apiCron: {
|
|
168
|
+
type: 'string',
|
|
169
|
+
title: 'Send attempt CRON',
|
|
170
|
+
description: 'We send the tracking data to NFL once in a while, you can set the schedule with this setting.\nCRON format: https://crontab.guru/',
|
|
171
|
+
default: '*/10 * * * *'
|
|
172
|
+
},
|
|
173
|
+
internetTestTimeout: {
|
|
174
|
+
type: 'number',
|
|
175
|
+
title: 'Timeout for testing internet connection in ms',
|
|
176
|
+
description: 'Set this number higher for slower computers and internet connections',
|
|
177
|
+
default: 2000
|
|
178
|
+
},
|
|
179
|
+
apiTimeout: {
|
|
180
|
+
type: 'integer',
|
|
181
|
+
title: 'API request timeout in seconds',
|
|
182
|
+
description: 'Timeout for sending data to NFL API. Increase for slow connections.',
|
|
183
|
+
default: 30,
|
|
184
|
+
minimum: 10,
|
|
185
|
+
maximum: 180
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
getPluginObject() {
|
|
194
|
+
return {
|
|
195
|
+
id: this.pluginId,
|
|
196
|
+
name: this.pluginName,
|
|
197
|
+
description: 'SignalK track logger to noforeignland.com',
|
|
198
|
+
schema: this.getSchema(),
|
|
199
|
+
start: this.start.bind(this),
|
|
200
|
+
stop: this.stop.bind(this)
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
async start(options = {}, restartPlugin) {
|
|
205
|
+
// Position data health check
|
|
206
|
+
this.positionCheckInterval = null;
|
|
207
|
+
this.lastPositionReceived = null;
|
|
208
|
+
|
|
209
|
+
// Backward compatibility: migrate old flat structure to new nested structure
|
|
210
|
+
let needsSave = false;
|
|
211
|
+
if (options.boatApiKey && !options.mandatory) {
|
|
212
|
+
this.app.debug('Migrating old configuration to new grouped structure');
|
|
213
|
+
needsSave = true;
|
|
214
|
+
|
|
215
|
+
options = {
|
|
216
|
+
mandatory: {
|
|
217
|
+
boatApiKey: options.boatApiKey
|
|
218
|
+
},
|
|
219
|
+
advanced: {
|
|
220
|
+
minMove: options.minMove !== undefined ? options.minMove : 50,
|
|
221
|
+
minSpeed: options.minSpeed !== undefined ? options.minSpeed : 1.5,
|
|
222
|
+
sendWhileMoving: options.sendWhileMoving !== undefined ? options.sendWhileMoving : true,
|
|
223
|
+
ping_api_every_24h: options.ping_api_every_24h !== undefined ? options.ping_api_every_24h : true
|
|
224
|
+
},
|
|
225
|
+
expert: {
|
|
226
|
+
filterSource: options.filterSource,
|
|
227
|
+
trackDir: options.trackDir,
|
|
228
|
+
keepFiles: options.keepFiles !== undefined ? options.keepFiles : false,
|
|
229
|
+
trackFrequency: options.trackFrequency !== undefined ? options.trackFrequency : 60,
|
|
230
|
+
internetTestTimeout: options.internetTestTimeout !== undefined ? options.internetTestTimeout : 2000,
|
|
231
|
+
apiCron: options.apiCron || '*/10 * * * *',
|
|
232
|
+
apiTimeout: options.apiTimeout !== undefined ? options.apiTimeout : 30
|
|
233
|
+
}
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
try {
|
|
237
|
+
this.app.debug('Saving migrated configuration...');
|
|
238
|
+
await this.app.savePluginOptions(options, () => {
|
|
239
|
+
this.app.debug('Configuration successfully migrated and saved');
|
|
240
|
+
});
|
|
241
|
+
} catch (err) {
|
|
242
|
+
this.app.debug('Failed to save migrated configuration:', err.message);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// Flatten the nested structure for easier access and apply defaults
|
|
247
|
+
this.options = {
|
|
248
|
+
boatApiKey: options.mandatory?.boatApiKey,
|
|
249
|
+
minMove: options.advanced?.minMove !== undefined ? options.advanced.minMove : 80,
|
|
250
|
+
minSpeed: options.advanced?.minSpeed !== undefined ? options.advanced.minSpeed : 1.5,
|
|
251
|
+
sendWhileMoving: options.advanced?.sendWhileMoving !== undefined ? options.advanced.sendWhileMoving : true,
|
|
252
|
+
ping_api_every_24h: options.advanced?.ping_api_every_24h !== undefined ? options.advanced.ping_api_every_24h : true,
|
|
253
|
+
filterSource: options.expert?.filterSource,
|
|
254
|
+
trackDir: options.expert?.trackDir || defaultTracksDir,
|
|
255
|
+
keepFiles: options.expert?.keepFiles !== undefined ? options.expert.keepFiles : false,
|
|
256
|
+
trackFrequency: options.expert?.trackFrequency !== undefined ? options.expert.trackFrequency : 60,
|
|
257
|
+
internetTestTimeout: options.expert?.internetTestTimeout !== undefined ? options.expert.internetTestTimeout : 2000,
|
|
258
|
+
apiCron: options.expert?.apiCron || '*/10 * * * *',
|
|
259
|
+
apiTimeout: options.expert?.apiTimeout !== undefined ? options.expert.apiTimeout : 30
|
|
260
|
+
};
|
|
261
|
+
|
|
262
|
+
// Validate that boatApiKey is set
|
|
263
|
+
if (!this.options.boatApiKey || this.options.boatApiKey.trim() === '') {
|
|
264
|
+
const errorMsg = 'No boat API key configured. Please set your API key in plugin settings (Mandatory Settings > Boat API key). You can find your API key at noforeignland.com under Account > Settings > Boat tracking > API Key.';
|
|
265
|
+
this.app.debug(errorMsg);
|
|
266
|
+
this.setPluginError(errorMsg);
|
|
267
|
+
this.stop();
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// Resolve track directory path
|
|
272
|
+
if (!path.isAbsolute(this.options.trackDir)) {
|
|
273
|
+
const dataDirPath = this.app.getDataDirPath();
|
|
274
|
+
this.options.trackDir = path.join(dataDirPath, this.options.trackDir);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
if (!this.createDir(this.options.trackDir)) {
|
|
278
|
+
this.stop();
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// Cleanup old plugin (fire and forget, non-blocking)
|
|
283
|
+
this.cleanupOldPlugin().catch(err => {
|
|
284
|
+
this.app.debug('Error in cleanupOldPlugin:', err.message);
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
// Migrate old track files
|
|
288
|
+
await this.migrateOldTrackFile();
|
|
289
|
+
|
|
290
|
+
this.app.debug('track logger started, now logging to', this.options.trackDir);
|
|
291
|
+
this.setPluginStatus(`Started${needsSave ? ' (config migrated)' : ''}`);
|
|
292
|
+
this.upSince = new Date().getTime();
|
|
293
|
+
|
|
294
|
+
// Adjust default CRON if unchanged
|
|
295
|
+
if (!this.options.apiCron || this.options.apiCron === '*/10 * * * *') {
|
|
296
|
+
const startMinute = Math.floor(Math.random() * 10);
|
|
297
|
+
const startSecond = Math.floor(Math.random() * 60);
|
|
298
|
+
this.options.apiCron = `${startSecond} ${startMinute}/10 * * * *`;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
this.app.debug('Setting CRON to', this.options.apiCron);
|
|
302
|
+
this.app.debug('trackFrequency is set to', this.options.trackFrequency, 'seconds');
|
|
303
|
+
|
|
304
|
+
// Subscribe and start logging
|
|
305
|
+
this.doLogging();
|
|
306
|
+
|
|
307
|
+
// Start cron job
|
|
308
|
+
this.cron = new CronJob(this.options.apiCron, this.interval.bind(this));
|
|
309
|
+
this.cron.start();
|
|
310
|
+
|
|
311
|
+
// Start position health check
|
|
312
|
+
this.startPositionHealthCheck();
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
async cleanupOldPlugin() {
|
|
316
|
+
try {
|
|
317
|
+
// Detect SignalK directory (standard or Victron Cerbo)
|
|
318
|
+
const victronPath = '/data/conf/signalk';
|
|
319
|
+
const standardPath = process.env.SIGNALK_NODE_CONFIG_DIR ||
|
|
320
|
+
path.join(process.env.HOME || process.env.USERPROFILE, '.signalk');
|
|
321
|
+
|
|
322
|
+
const configDir = fs.existsSync(victronPath) ? victronPath : standardPath;
|
|
323
|
+
this.app.debug(`Using SignalK directory: ${configDir}`);
|
|
324
|
+
|
|
325
|
+
const configPath = path.join(configDir, 'plugin-config-data');
|
|
326
|
+
|
|
327
|
+
// 1. Config Migration - only from signalk-to-noforeignland
|
|
328
|
+
const oldConfigFile = path.join(configPath, 'signalk-to-noforeignland.json');
|
|
329
|
+
const newConfigFile = path.join(configPath, '@noforeignland-signalk-to-noforeignland.json');
|
|
330
|
+
|
|
331
|
+
if (fs.existsSync(oldConfigFile) && !fs.existsSync(newConfigFile)) {
|
|
332
|
+
this.app.debug('Migrating configuration from old plugin "signalk-to-noforeignland"...');
|
|
333
|
+
fs.copyFileSync(oldConfigFile, newConfigFile);
|
|
334
|
+
fs.copyFileSync(oldConfigFile, `${oldConfigFile}.backup`);
|
|
335
|
+
this.app.debug('✓ Configuration migrated successfully');
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
// 2. Check if old plugins still exist (including very old signalk-to-nfl)
|
|
339
|
+
const oldPlugins = [
|
|
340
|
+
{ dir: path.join(configDir, 'node_modules', 'signalk-to-noforeignland'), name: 'signalk-to-noforeignland' },
|
|
341
|
+
{ dir: path.join(configDir, 'node_modules', 'signalk-to-nfl'), name: 'signalk-to-nfl' }
|
|
342
|
+
];
|
|
343
|
+
|
|
344
|
+
const foundOldPlugins = oldPlugins.filter(plugin => fs.existsSync(plugin.dir));
|
|
345
|
+
|
|
346
|
+
if (foundOldPlugins.length > 0) {
|
|
347
|
+
const pluginNames = foundOldPlugins.map(p => `"${p.name}"`).join(' and ');
|
|
348
|
+
const uninstallCmd = foundOldPlugins.map(p => p.name).join(' ');
|
|
349
|
+
|
|
350
|
+
this.app.debug(`Old plugin(s) detected: ${pluginNames}`);
|
|
351
|
+
this.app.setPluginError(
|
|
352
|
+
`Old plugin(s) ${pluginNames} still installed. ` +
|
|
353
|
+
`Please uninstall manually: cd ${configDir} && npm uninstall ${uninstallCmd}`
|
|
354
|
+
);
|
|
355
|
+
|
|
356
|
+
// Try to remove them after a delay (non-blocking)
|
|
357
|
+
setTimeout(async () => {
|
|
358
|
+
let anyRemoved = false;
|
|
359
|
+
let anyFailed = false;
|
|
360
|
+
|
|
361
|
+
for (const plugin of foundOldPlugins) {
|
|
362
|
+
try {
|
|
363
|
+
this.app.debug(`Attempting to remove old plugin directory: ${plugin.name}...`);
|
|
364
|
+
await fs.remove(plugin.dir);
|
|
365
|
+
this.app.debug(`✓ Old plugin "${plugin.name}" directory removed`);
|
|
366
|
+
anyRemoved = true;
|
|
367
|
+
} catch (err) {
|
|
368
|
+
this.app.debug(`Could not automatically remove old plugin "${plugin.name}":`, err.message);
|
|
369
|
+
anyFailed = true;
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
if (anyRemoved && !anyFailed) {
|
|
374
|
+
this.setPluginStatus('Started (old plugins cleaned up)');
|
|
375
|
+
} else if (anyFailed) {
|
|
376
|
+
const remainingPlugins = foundOldPlugins.map(p => p.name).join(' ');
|
|
377
|
+
this.app.debug(`Please manually run: cd ${configDir} && npm uninstall ${remainingPlugins}`);
|
|
378
|
+
}
|
|
379
|
+
}, 5000); // 5 seconds wait for SignalK to fully start
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
} catch (err) {
|
|
383
|
+
this.app.debug('Error during old plugin cleanup:', err.message);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
async migrateOldTrackFile() {
|
|
388
|
+
const oldTrackFile = path.join(this.options.trackDir, 'nfl-track.jsonl');
|
|
389
|
+
const oldPendingFile = path.join(this.options.trackDir, 'nfl-track-pending.jsonl');
|
|
390
|
+
const oldSentFile = path.join(this.options.trackDir, 'nfl-track-sent.jsonl');
|
|
391
|
+
const newPendingFile = path.join(this.options.trackDir, routeSaveName);
|
|
392
|
+
const newSentFile = path.join(this.options.trackDir, routeSentName);
|
|
393
|
+
|
|
394
|
+
try {
|
|
395
|
+
// Migrate old track file
|
|
396
|
+
if (await fs.pathExists(oldTrackFile) && !(await fs.pathExists(newPendingFile))) {
|
|
397
|
+
this.app.debug('Migrating old track file to new naming scheme...');
|
|
398
|
+
await fs.move(oldTrackFile, newPendingFile);
|
|
399
|
+
this.app.debug('Successfully migrated old track file to:', routeSaveName);
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
// Migrate old pending file
|
|
403
|
+
if (await fs.pathExists(oldPendingFile) && !(await fs.pathExists(newPendingFile))) {
|
|
404
|
+
this.app.debug('Migrating old pending file to new naming scheme...');
|
|
405
|
+
await fs.move(oldPendingFile, newPendingFile);
|
|
406
|
+
this.app.debug('Successfully migrated old pending file to:', routeSaveName);
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
// Migrate old sent file
|
|
410
|
+
if (await fs.pathExists(oldSentFile) && !(await fs.pathExists(newSentFile))) {
|
|
411
|
+
this.app.debug('Migrating old sent file to new naming scheme...');
|
|
412
|
+
await fs.move(oldSentFile, newSentFile);
|
|
413
|
+
this.app.debug('Successfully migrated old sent file to:', routeSentName);
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
// Check old plugin directory location
|
|
417
|
+
const oldPluginTrackDir = path.join(__dirname, 'track');
|
|
418
|
+
if (await fs.pathExists(oldPluginTrackDir)) {
|
|
419
|
+
this.app.debug('Found old track directory in plugin folder, migrating to new location...');
|
|
420
|
+
|
|
421
|
+
const oldFiles = [
|
|
422
|
+
'nfl-track.jsonl',
|
|
423
|
+
'nfl-track-pending.jsonl',
|
|
424
|
+
routeSaveName
|
|
425
|
+
];
|
|
426
|
+
|
|
427
|
+
for (const oldFile of oldFiles) {
|
|
428
|
+
const oldPath = path.join(oldPluginTrackDir, oldFile);
|
|
429
|
+
if (await fs.pathExists(oldPath) && !(await fs.pathExists(newPendingFile))) {
|
|
430
|
+
await fs.move(oldPath, newPendingFile);
|
|
431
|
+
this.app.debug('Migrated pending track file from old plugin location');
|
|
432
|
+
break;
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
// Migrate sent archive
|
|
437
|
+
const oldSentFiles = [routeSentName, 'nfl-track-sent.jsonl'];
|
|
438
|
+
for (const oldFile of oldSentFiles) {
|
|
439
|
+
const oldPath = path.join(oldPluginTrackDir, oldFile);
|
|
440
|
+
if (await fs.pathExists(oldPath) && !(await fs.pathExists(newSentFile))) {
|
|
441
|
+
await fs.move(oldPath, newSentFile);
|
|
442
|
+
this.app.debug('Migrated sent track archive from old plugin location');
|
|
443
|
+
break;
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
// Try to remove old directory if empty
|
|
448
|
+
try {
|
|
449
|
+
const remainingFiles = await fs.readdir(oldPluginTrackDir);
|
|
450
|
+
if (remainingFiles.length === 0) {
|
|
451
|
+
await fs.rmdir(oldPluginTrackDir);
|
|
452
|
+
this.app.debug('Removed empty old track directory');
|
|
453
|
+
}
|
|
454
|
+
} catch (err) {
|
|
455
|
+
this.app.debug('Could not remove old track directory:', err.message);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
} catch (err) {
|
|
459
|
+
this.app.debug('Error during track file migration:', err.message);
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
stop() {
|
|
464
|
+
this.app.debug('plugin stopped');
|
|
465
|
+
|
|
466
|
+
this.autoSelectedSource = null;
|
|
467
|
+
|
|
468
|
+
if (this.positionCheckInterval) {
|
|
469
|
+
clearInterval(this.positionCheckInterval);
|
|
470
|
+
this.positionCheckInterval = null;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
if (this.cron) {
|
|
474
|
+
this.cron.stop();
|
|
475
|
+
this.cron = undefined;
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
this.unsubscribesControl.forEach(f => f());
|
|
479
|
+
this.unsubscribesControl = [];
|
|
480
|
+
this.unsubscribes.forEach(f => f());
|
|
481
|
+
this.unsubscribes = [];
|
|
482
|
+
this.app.setPluginStatus('Plugin stopped');
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
doLogging() {
|
|
486
|
+
let shouldDoLog = true;
|
|
487
|
+
|
|
488
|
+
this.app.subscriptionmanager.subscribe({
|
|
489
|
+
context: 'vessels.self',
|
|
490
|
+
subscribe: [{
|
|
491
|
+
path: 'navigation.position',
|
|
492
|
+
format: 'delta',
|
|
493
|
+
policy: 'instant',
|
|
494
|
+
minPeriod: this.options.trackFrequency ? this.options.trackFrequency * 1000 : 0
|
|
495
|
+
}]
|
|
496
|
+
}, this.unsubscribes, (subscriptionError) => {
|
|
497
|
+
this.app.debug('Error subscription to data:' + subscriptionError);
|
|
498
|
+
this.setPluginError('Error subscription to data:' + subscriptionError.message);
|
|
499
|
+
}, this.doOnValue.bind(this, () => shouldDoLog, newShould => { shouldDoLog = newShould; }));
|
|
500
|
+
|
|
501
|
+
// Subscribe for speed
|
|
502
|
+
if (this.options.minSpeed) {
|
|
503
|
+
this.app.subscriptionmanager.subscribe({
|
|
504
|
+
context: 'vessels.self',
|
|
505
|
+
subscribe: [{
|
|
506
|
+
path: 'navigation.speedOverGround',
|
|
507
|
+
format: 'delta',
|
|
508
|
+
policy: 'instant'
|
|
509
|
+
}]
|
|
510
|
+
}, this.unsubscribes, (subscriptionError) => {
|
|
511
|
+
this.app.debug('Error subscription to data:' + subscriptionError);
|
|
512
|
+
this.setPluginError('Error subscription to data:' + subscriptionError.message);
|
|
513
|
+
}, (delta) => {
|
|
514
|
+
delta.updates.forEach(update => {
|
|
515
|
+
if (this.options.filterSource && update.$source !== this.options.filterSource) {
|
|
516
|
+
return;
|
|
517
|
+
}
|
|
518
|
+
update.values.forEach(value => {
|
|
519
|
+
const speedInKnots = value.value * 1.94384;
|
|
520
|
+
if (!shouldDoLog && this.options.minSpeed < speedInKnots) {
|
|
521
|
+
this.app.debug('setting shouldDoLog to true, speed:', speedInKnots.toFixed(2), 'knots');
|
|
522
|
+
shouldDoLog = true;
|
|
523
|
+
}
|
|
524
|
+
});
|
|
525
|
+
});
|
|
526
|
+
});
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
// FIXED: Use continue instead of return to handle multiple updates properly
|
|
531
|
+
async doOnValue(getShouldDoLog, setShouldDoLog, delta) {
|
|
532
|
+
for (const update of delta.updates) {
|
|
533
|
+
// Auto-select source logic
|
|
534
|
+
if (!this.options.filterSource) {
|
|
535
|
+
const timeSinceLastPosition = this.lastPositionReceived
|
|
536
|
+
? (new Date().getTime() - this.lastPositionReceived) / 1000
|
|
537
|
+
: null;
|
|
538
|
+
|
|
539
|
+
if (!this.autoSelectedSource) {
|
|
540
|
+
this.autoSelectedSource = update.$source;
|
|
541
|
+
this.lastPositionReceived = new Date().getTime();
|
|
542
|
+
this.app.debug(`Auto-selected GPS source: '${this.autoSelectedSource}'`);
|
|
543
|
+
} else if (update.$source !== this.autoSelectedSource) {
|
|
544
|
+
if (timeSinceLastPosition && timeSinceLastPosition > 300) {
|
|
545
|
+
this.app.debug(`Switching from stale source '${this.autoSelectedSource}' to '${update.$source}' (no data for ${timeSinceLastPosition.toFixed(0)}s)`);
|
|
546
|
+
this.autoSelectedSource = update.$source;
|
|
547
|
+
this.lastPositionReceived = new Date().getTime();
|
|
548
|
+
} else {
|
|
549
|
+
this.app.debug(`Ignoring position from '${update.$source}', using auto-selected source '${this.autoSelectedSource}'`);
|
|
550
|
+
continue;
|
|
551
|
+
}
|
|
552
|
+
} else {
|
|
553
|
+
this.lastPositionReceived = new Date().getTime();
|
|
554
|
+
}
|
|
555
|
+
} else if (update.$source !== this.options.filterSource) {
|
|
556
|
+
this.app.debug(`Ignoring position from '${update.$source}', filterSource is set to '${this.options.filterSource}'`);
|
|
557
|
+
continue;
|
|
558
|
+
} else {
|
|
559
|
+
this.lastPositionReceived = new Date().getTime();
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
const timestamp = update.timestamp;
|
|
563
|
+
for (const value of update.values) {
|
|
564
|
+
// Validation: GPS near (0,0)
|
|
565
|
+
if (Math.abs(value.value.latitude) <= 0.01 && Math.abs(value.value.longitude) <= 0.01) {
|
|
566
|
+
this.app.debug('GPS coordinates near (0,0), ignoring point to avoid invalid data logging.');
|
|
567
|
+
continue;
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
// Validate lat/lon
|
|
571
|
+
if (!this.isValidLatitude(value.value.latitude) || !this.isValidLongitude(value.value.longitude)) {
|
|
572
|
+
this.app.debug('got invalid position, ignoring...', value.value);
|
|
573
|
+
continue;
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
// 24h ping check
|
|
577
|
+
let force24hSave = false;
|
|
578
|
+
if (this.options.ping_api_every_24h && this.lastPosition) {
|
|
579
|
+
const timeSinceLastPoint = (new Date().getTime() - this.lastPosition.currentTime);
|
|
580
|
+
if (timeSinceLastPoint >= 24 * 60 * 60 * 1000) {
|
|
581
|
+
this.app.debug('24h since last point, forcing save of point to keep boat active on NFL');
|
|
582
|
+
force24hSave = true;
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
// Check if we should log
|
|
587
|
+
if (!force24hSave && !getShouldDoLog()) {
|
|
588
|
+
this.app.debug('shouldDoLog is false, not logging position');
|
|
589
|
+
continue;
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
// Check timestamp and distance
|
|
593
|
+
if (this.lastPosition && !force24hSave) {
|
|
594
|
+
if (new Date(this.lastPosition.timestamp).getTime() > new Date(timestamp).getTime()) {
|
|
595
|
+
this.app.debug('got error in timestamp:', timestamp, 'is earlier than previous:', this.lastPosition.timestamp);
|
|
596
|
+
continue;
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
const distance = this.equirectangularDistance(this.lastPosition.pos, value.value);
|
|
600
|
+
if (this.options.minMove && distance < this.options.minMove) {
|
|
601
|
+
this.app.debug('Distance', distance.toFixed(2), 'm is less than minMove', this.options.minMove, 'm - skipping');
|
|
602
|
+
continue;
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
this.app.debug('Distance', distance.toFixed(2), 'm is greater than minMove', this.options.minMove, 'm - logging');
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
// Save point
|
|
609
|
+
this.app.debug('Saving position from source:', update.$source, 'lat:', value.value.latitude, 'lon:', value.value.longitude);
|
|
610
|
+
this.lastPosition = { pos: value.value, timestamp, currentTime: new Date().getTime() };
|
|
611
|
+
await this.savePoint(this.lastPosition);
|
|
612
|
+
|
|
613
|
+
// Reset shouldDoLog if minSpeed is active
|
|
614
|
+
if (this.options.minSpeed) {
|
|
615
|
+
this.app.debug('options.minSpeed - setting shouldDoLog to false');
|
|
616
|
+
setShouldDoLog(false);
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
async savePoint(point) {
|
|
623
|
+
const obj = {
|
|
624
|
+
lat: point.pos.latitude,
|
|
625
|
+
lon: point.pos.longitude,
|
|
626
|
+
t: point.timestamp
|
|
627
|
+
};
|
|
628
|
+
this.app.debug(`save data point:`, obj);
|
|
629
|
+
await fs.appendFile(path.join(this.options.trackDir, routeSaveName), JSON.stringify(obj) + EOL);
|
|
630
|
+
|
|
631
|
+
const now = new Date();
|
|
632
|
+
this.emitDelta('noforeignland.savepoint', now.toISOString());
|
|
633
|
+
this.emitDelta('noforeignland.savepoint_local', now.toLocaleString());
|
|
634
|
+
|
|
635
|
+
// ISO8601 format for Dashboard
|
|
636
|
+
const activeSource = this.options.filterSource || this.autoSelectedSource || '';
|
|
637
|
+
const sourcePrefix = activeSource ? `${activeSource} | ` : '';
|
|
638
|
+
const saveTime = now.toISOString();
|
|
639
|
+
const transferTime = this.lastSuccessfulTransfer ? this.lastSuccessfulTransfer.toISOString() : 'None since start';
|
|
640
|
+
|
|
641
|
+
this.setPluginStatus(`Save: ${saveTime} | Transfer: ${transferTime} | ${sourcePrefix}`);
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
isValidLatitude(obj) {
|
|
645
|
+
return this.isDefinedNumber(obj) && obj > -90 && obj < 90;
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
isValidLongitude(obj) {
|
|
649
|
+
return this.isDefinedNumber(obj) && obj > -180 && obj < 180;
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
isDefinedNumber(obj) {
|
|
653
|
+
return (obj !== undefined && obj !== null && typeof obj === 'number');
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
equirectangularDistance(from, to) {
|
|
657
|
+
const rad = Math.PI / 180;
|
|
658
|
+
const φ1 = from.latitude * rad;
|
|
659
|
+
const φ2 = to.latitude * rad;
|
|
660
|
+
const Δλ = (to.longitude - from.longitude) * rad;
|
|
661
|
+
const R = 6371e3;
|
|
662
|
+
const x = Δλ * Math.cos((φ1 + φ2) / 2);
|
|
663
|
+
const y = (φ2 - φ1);
|
|
664
|
+
const d = Math.sqrt(x * x + y * y) * R;
|
|
665
|
+
return d;
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
createDir(dir) {
|
|
669
|
+
let res = true;
|
|
670
|
+
if (fs.existsSync(dir)) {
|
|
671
|
+
try {
|
|
672
|
+
fs.accessSync(dir, fs.constants.R_OK | fs.constants.W_OK);
|
|
673
|
+
} catch (error) {
|
|
674
|
+
this.app.debug('[createDir]', error.message);
|
|
675
|
+
this.setPluginError(`No rights to directory ${dir}`);
|
|
676
|
+
res = false;
|
|
677
|
+
}
|
|
678
|
+
} else {
|
|
679
|
+
try {
|
|
680
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
681
|
+
} catch (error) {
|
|
682
|
+
switch (error.code) {
|
|
683
|
+
case 'EACCES':
|
|
684
|
+
case 'EPERM':
|
|
685
|
+
this.app.debug(`Failed to create ${dir} by Permission denied`);
|
|
686
|
+
this.setPluginError(`Failed to create ${dir} by Permission denied`);
|
|
687
|
+
res = false;
|
|
688
|
+
break;
|
|
689
|
+
case 'ETIMEDOUT':
|
|
690
|
+
this.app.debug(`Failed to create ${dir} by Operation timed out`);
|
|
691
|
+
this.setPluginError(`Failed to create ${dir} by Operation timed out`);
|
|
692
|
+
res = false;
|
|
693
|
+
break;
|
|
694
|
+
default:
|
|
695
|
+
this.app.debug(`Error creating directory ${dir}: ${error.message}`);
|
|
696
|
+
this.setPluginError(`Error creating directory ${dir}: ${error.message}`);
|
|
697
|
+
res = false;
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
return res;
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
startPositionHealthCheck() {
|
|
705
|
+
this.positionCheckInterval = setInterval(() => {
|
|
706
|
+
const now = new Date().getTime();
|
|
707
|
+
const timeSinceLastPosition = this.lastPositionReceived
|
|
708
|
+
? (now - this.lastPositionReceived) / 1000
|
|
709
|
+
: null;
|
|
710
|
+
|
|
711
|
+
const activeSource = this.options.filterSource || this.autoSelectedSource || 'any';
|
|
712
|
+
const filterMsg = activeSource !== 'any' ? ` from source '${activeSource}'` : '';
|
|
713
|
+
|
|
714
|
+
if (!this.lastPositionReceived) {
|
|
715
|
+
const errorMsg = this.options.filterSource
|
|
716
|
+
? `No GPS position data received from filtered source '${this.options.filterSource}'. Check Expert Settings > Position source device, or leave empty to use any GPS source.`
|
|
717
|
+
: 'No GPS position data received. Check that your GPS is connected and SignalK is receiving navigation.position data.';
|
|
718
|
+
this.setPluginError(errorMsg);
|
|
719
|
+
this.app.debug('Position health check: No position data ever received' + filterMsg);
|
|
720
|
+
} else if (timeSinceLastPosition > 300) {
|
|
721
|
+
const errorMsg = this.options.filterSource
|
|
722
|
+
? `No GPS position data${filterMsg} for ${Math.floor(timeSinceLastPosition / 60)} minutes. Check that source '${this.options.filterSource}' is active, or change/clear Position source device in Expert Settings.`
|
|
723
|
+
: `No GPS position data${filterMsg} for ${Math.floor(timeSinceLastPosition / 60)} minutes. Check your GPS connection.`;
|
|
724
|
+
this.setPluginError(errorMsg);
|
|
725
|
+
this.app.debug(`Position health check: No position for ${timeSinceLastPosition.toFixed(0)} seconds` + filterMsg);
|
|
726
|
+
} else {
|
|
727
|
+
this.app.debug(`Position health check: OK (last position ${timeSinceLastPosition.toFixed(0)} seconds ago${filterMsg})`);
|
|
728
|
+
|
|
729
|
+
// Clear any previous errors when position health is OK
|
|
730
|
+
if (this.currentError) {
|
|
731
|
+
const activeSource = this.options.filterSource || this.autoSelectedSource || '';
|
|
732
|
+
const sourcePrefix = activeSource ? `${activeSource} | ` : '';
|
|
733
|
+
const saveTime = this.lastPosition ? new Date(this.lastPosition.currentTime).toISOString() : 'None since start';
|
|
734
|
+
const transferTime = this.lastSuccessfulTransfer ? this.lastSuccessfulTransfer.toISOString() : 'None since start';
|
|
735
|
+
this.setPluginStatus(`Save: ${saveTime} | Transfer: ${transferTime} | ${sourcePrefix}`);
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
}, 5 * 60 * 1000);
|
|
739
|
+
|
|
740
|
+
// Initial check after 2 minutes of startup
|
|
741
|
+
setTimeout(() => {
|
|
742
|
+
if (!this.lastPositionReceived) {
|
|
743
|
+
const activeSource = this.options.filterSource || this.autoSelectedSource || 'any';
|
|
744
|
+
const errorMsg = this.options.filterSource
|
|
745
|
+
? `No GPS position data received after 2 minutes from filtered source '${this.options.filterSource}'. Check Expert Settings > Position source device. You may need to leave it empty to use any available GPS source.`
|
|
746
|
+
: 'No GPS position data received after 2 minutes. Check that your GPS is connected and SignalK is receiving navigation.position data.';
|
|
747
|
+
this.setPluginError(errorMsg);
|
|
748
|
+
this.app.debug('Initial position check: No position data received' + (activeSource !== 'any' ? ` from source '${activeSource}'` : ''));
|
|
749
|
+
}
|
|
750
|
+
}, 2 * 60 * 1000);
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
async interval() {
|
|
754
|
+
const boatMoving = this.checkBoatMoving();
|
|
755
|
+
if (!boatMoving) {
|
|
756
|
+
return;
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
const hasTrack = await this.checkTrack();
|
|
760
|
+
if (!hasTrack) {
|
|
761
|
+
return;
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
const hasInternet = await this.testInternet();
|
|
765
|
+
if (!hasInternet) {
|
|
766
|
+
const errorMsg = 'No internet connection detected. Unable to send tracking data to NFL. DNS lookups failed - check your internet connection.';
|
|
767
|
+
this.app.debug(errorMsg);
|
|
768
|
+
this.setPluginError(errorMsg);
|
|
769
|
+
return;
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
await this.sendData();
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
checkBoatMoving() {
|
|
776
|
+
if (!this.options.trackFrequency) {
|
|
777
|
+
return true;
|
|
778
|
+
}
|
|
779
|
+
const time = this.lastPosition ? this.lastPosition.currentTime : this.upSince;
|
|
780
|
+
const secsSinceLastPoint = (new Date().getTime() - time) / 1000;
|
|
781
|
+
const isMoving = secsSinceLastPoint <= (this.options.trackFrequency * 2);
|
|
782
|
+
if (isMoving) {
|
|
783
|
+
this.app.debug('Boat is still moving, last move', secsSinceLastPoint, 'seconds ago');
|
|
784
|
+
return this.options.sendWhileMoving;
|
|
785
|
+
} else {
|
|
786
|
+
this.app.debug('Boat stopped moving, last move at least', secsSinceLastPoint, 'seconds ago');
|
|
787
|
+
return true;
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
async testInternet() {
|
|
792
|
+
const dns = require('dns').promises;
|
|
793
|
+
|
|
794
|
+
this.app.debug('testing internet connection');
|
|
795
|
+
|
|
796
|
+
const timeoutMs = this.options.internetTestTimeout || 2000;
|
|
797
|
+
this.app.debug(`Using internet test timeout: ${timeoutMs}ms`);
|
|
798
|
+
|
|
799
|
+
const dnsServers = [
|
|
800
|
+
{ name: 'Google DNS', ip: '8.8.8.8' },
|
|
801
|
+
{ name: 'Cloudflare DNS', ip: '1.1.1.1' }
|
|
802
|
+
];
|
|
803
|
+
|
|
804
|
+
for (const server of dnsServers) {
|
|
805
|
+
try {
|
|
806
|
+
const startTime = Date.now();
|
|
807
|
+
const result = await Promise.race([
|
|
808
|
+
dns.reverse(server.ip),
|
|
809
|
+
new Promise((_, reject) =>
|
|
810
|
+
setTimeout(() => reject(new Error('DNS timeout')), timeoutMs)
|
|
811
|
+
)
|
|
812
|
+
]);
|
|
813
|
+
const elapsed = Date.now() - startTime;
|
|
814
|
+
|
|
815
|
+
this.app.debug(`internet connection = true, ${server.name} (${server.ip}) is reachable (took ${elapsed}ms)`);
|
|
816
|
+
return true;
|
|
817
|
+
} catch (err) {
|
|
818
|
+
this.app.debug(`${server.name} (${server.ip}) not reachable:`, err.message);
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
this.app.debug(`internet connection = false, no public DNS servers reachable (timeout was ${timeoutMs}ms)`);
|
|
823
|
+
return false;
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
async checkTrack() {
|
|
827
|
+
const trackFile = path.join(this.options.trackDir, routeSaveName);
|
|
828
|
+
this.app.debug('checking the track', trackFile, 'if should send');
|
|
829
|
+
const exists = await fs.pathExists(trackFile);
|
|
830
|
+
const size = exists ? (await fs.lstat(trackFile)).size : 0;
|
|
831
|
+
this.app.debug(`'${trackFile}'.size=${size} ${trackFile}'.exists=${exists}`);
|
|
832
|
+
return size > 0;
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
async sendData() {
|
|
836
|
+
if (this.options.boatApiKey) {
|
|
837
|
+
await this.sendApiData();
|
|
838
|
+
} else {
|
|
839
|
+
this.app.debug('Failed to send track - no boat API key set in plugin settings.');
|
|
840
|
+
this.setPluginError(`Failed to send track - no boat API key set in plugin settings.`);
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
async sendApiData() {
|
|
845
|
+
this.app.debug('sending the data');
|
|
846
|
+
const pendingFile = path.join(this.options.trackDir, routeSaveName);
|
|
847
|
+
const trackData = await this.createTrack(pendingFile);
|
|
848
|
+
if (!trackData) {
|
|
849
|
+
this.app.debug('Recorded track did not contain any valid track points, aborting sending.');
|
|
850
|
+
this.setPluginError(`Failed to send track - Recorded track did not contain any valid track points, aborting sending.`);
|
|
851
|
+
return;
|
|
852
|
+
}
|
|
853
|
+
this.app.debug('created track data with timestamp:', new Date(trackData.timestamp));
|
|
854
|
+
const params = new URLSearchParams();
|
|
855
|
+
params.append('timestamp', trackData.timestamp);
|
|
856
|
+
params.append('track', JSON.stringify(trackData.track));
|
|
857
|
+
params.append('boatApiKey', this.options.boatApiKey);
|
|
858
|
+
const headers = { 'X-NFL-API-Key': pluginApiKey };
|
|
859
|
+
this.app.debug('sending track to API');
|
|
860
|
+
|
|
861
|
+
const maxRetries = 3;
|
|
862
|
+
const baseTimeout = (this.options.apiTimeout || 30) * 1000;
|
|
863
|
+
|
|
864
|
+
for (let attempt = 1; attempt <= maxRetries; attempt++) {
|
|
865
|
+
try {
|
|
866
|
+
const currentTimeout = baseTimeout * attempt;
|
|
867
|
+
this.app.debug(`Attempt ${attempt}/${maxRetries} with ${currentTimeout}ms timeout`);
|
|
868
|
+
|
|
869
|
+
const controller = new AbortController();
|
|
870
|
+
const timeoutId = setTimeout(() => controller.abort(), currentTimeout);
|
|
871
|
+
|
|
872
|
+
const response = await fetch(apiUrl, {
|
|
873
|
+
method: 'POST',
|
|
874
|
+
body: params,
|
|
875
|
+
headers: new fetch.Headers(headers),
|
|
876
|
+
signal: controller.signal
|
|
877
|
+
});
|
|
878
|
+
|
|
879
|
+
clearTimeout(timeoutId);
|
|
880
|
+
|
|
881
|
+
if (response.ok) {
|
|
882
|
+
const responseBody = await response.json();
|
|
883
|
+
if (responseBody.status === 'ok') {
|
|
884
|
+
this.lastSuccessfulTransfer = new Date();
|
|
885
|
+
|
|
886
|
+
this.emitDelta('noforeignland.sent_to_api', this.lastSuccessfulTransfer.toISOString());
|
|
887
|
+
this.emitDelta('noforeignland.sent_to_api_local', this.lastSuccessfulTransfer.toLocaleString());
|
|
888
|
+
|
|
889
|
+
this.app.debug('Track successfully sent to API');
|
|
890
|
+
|
|
891
|
+
// ISO8601 format for Dashboard
|
|
892
|
+
const activeSource = this.options.filterSource || this.autoSelectedSource || '';
|
|
893
|
+
const sourcePrefix = activeSource ? `${activeSource} | ` : '';
|
|
894
|
+
const saveTime = this.lastPosition ? new Date(this.lastPosition.currentTime).toISOString() : 'None since start';
|
|
895
|
+
const transferTime = this.lastSuccessfulTransfer.toISOString();
|
|
896
|
+
this.setPluginStatus(`Save: ${saveTime} | Transfer: ${transferTime} | ${sourcePrefix}`);
|
|
897
|
+
|
|
898
|
+
await this.handleSuccessfulSend(pendingFile);
|
|
899
|
+
return;
|
|
900
|
+
} else {
|
|
901
|
+
this.app.debug('Could not send track to API, returned response json:', responseBody);
|
|
902
|
+
this.setPluginError(`Failed to send track - API returned error.`);
|
|
903
|
+
return;
|
|
904
|
+
}
|
|
905
|
+
} else {
|
|
906
|
+
this.app.debug('Could not send track to API, returned response code:', response.status, response.statusText);
|
|
907
|
+
if (response.status >= 400 && response.status < 500) {
|
|
908
|
+
this.setPluginError(`Failed to send track - HTTP ${response.status}.`);
|
|
909
|
+
return;
|
|
910
|
+
}
|
|
911
|
+
throw new Error(`HTTP ${response.status}`);
|
|
912
|
+
}
|
|
913
|
+
} catch (err) {
|
|
914
|
+
this.app.debug(`Attempt ${attempt} failed:`, err.message);
|
|
915
|
+
|
|
916
|
+
if (attempt === maxRetries) {
|
|
917
|
+
this.app.debug('Could not send track to API after', maxRetries, 'attempts:', err);
|
|
918
|
+
this.setPluginError(`Failed to send track after ${maxRetries} attempts - check logs for details.`);
|
|
919
|
+
} else {
|
|
920
|
+
const waitTime = 2000 * attempt;
|
|
921
|
+
this.app.debug(`Waiting ${waitTime}ms before retry...`);
|
|
922
|
+
await new Promise(resolve => setTimeout(resolve, waitTime));
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
async handleSuccessfulSend(pendingFile) {
|
|
929
|
+
const sentFile = path.join(this.options.trackDir, routeSentName);
|
|
930
|
+
|
|
931
|
+
try {
|
|
932
|
+
if (this.options.keepFiles) {
|
|
933
|
+
this.app.debug('Appending sent data to archive file:', routeSentName);
|
|
934
|
+
const pendingContent = await fs.readFile(pendingFile, 'utf8');
|
|
935
|
+
await fs.appendFile(sentFile, pendingContent);
|
|
936
|
+
this.app.debug('Successfully archived sent track data');
|
|
937
|
+
} else {
|
|
938
|
+
this.app.debug('keepFiles disabled, will delete pending file');
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
this.app.debug('Deleting pending track file');
|
|
942
|
+
await fs.remove(pendingFile);
|
|
943
|
+
this.app.debug('Successfully processed track files after send');
|
|
944
|
+
|
|
945
|
+
} catch (err) {
|
|
946
|
+
this.app.debug('Error handling files after successful send:', err.message);
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
async createTrack(inputPath) {
|
|
951
|
+
const fileStream = fs.createReadStream(inputPath);
|
|
952
|
+
const rl = readline.createInterface({ input: fileStream, crlfDelay: Infinity });
|
|
953
|
+
const track = [];
|
|
954
|
+
let lastTimestamp;
|
|
955
|
+
for await (const line of rl) {
|
|
956
|
+
if (line) {
|
|
957
|
+
try {
|
|
958
|
+
const point = JSON.parse(line);
|
|
959
|
+
const timestamp = new Date(point.t).getTime();
|
|
960
|
+
if (!isNaN(timestamp) && this.isValidLatitude(point.lat) && this.isValidLongitude(point.lon)) {
|
|
961
|
+
track.push([timestamp, point.lat, point.lon]);
|
|
962
|
+
lastTimestamp = timestamp;
|
|
963
|
+
}
|
|
964
|
+
} catch (error) {
|
|
965
|
+
this.app.debug('could not parse line from track file:', line);
|
|
966
|
+
this.setPluginError(`Failed could not parse line from track file - check logs for details.`);
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
if (track.length > 0) {
|
|
971
|
+
return { timestamp: new Date(lastTimestamp).getTime(), track };
|
|
972
|
+
}
|
|
973
|
+
return null;
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
module.exports = function (app) {
|
|
978
|
+
const instance = new SignalkToNoforeignland(app);
|
|
979
|
+
return instance.getPluginObject();
|
|
903
980
|
};
|