-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
413 lines (391 loc) · 12.8 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
/*
* Copyright 2022-2024 Ilker Temir <[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_STARLINK_INTERVAL = 15 // Poll every N seconds
const STARLINK = 'network.providers.starlink'
const path = require('path');
const protoLoader = require('@grpc/proto-loader');
const grpc = require('@grpc/grpc-js');
const gRpcOptions = {
keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true,
includeDirs: [path.join(__dirname, '/protos')]
}
const packageDefinition = protoLoader.loadSync('spacex/api/device/service.proto', gRpcOptions);
const Device = grpc.loadPackageDefinition(packageDefinition).SpaceX.API.Device.Device;
var client = new Device(
"192.168.100.1:9200",
grpc.credentials.createInsecure()
);
var dishyStatus;
var stowRequested;
var positions = [];
var gpsSource;
var errorCount = 0;
var previousLatitude;
var previousLongitude;
module.exports = function(app) {
var plugin = {};
var unsubscribes = [];
var pollProcess;
plugin.id = "signalk-starlink";
plugin.name = "Starlink";
plugin.description = "Starlink plugin for Signal K";
plugin.schema = {
type: 'object',
required: [],
properties: {
retrieveGps: {
type: "boolean",
title: "Use Starlink as a GPS source (requires enabling access on local network)",
default: true
},
stowWhileMoving: {
type: "boolean",
title: "Stow Dishy while moving",
default: false
},
gpsSource: {
type: "string",
title: "GPS source (Optional - only if you have multiple GPS sources and you want to use an explicit source)"
},
}
}
plugin.start = function(options) {
gpsSource = options.gpsSource;
let subscription = {
context: 'vessels.self',
subscribe: [{
path: 'navigation.position',
period: 60 * 1000 // Every minute
}]
};
app.subscriptionmanager.subscribe(subscription, unsubscribes, function() {
app.debug('Subscription error');
}, data => processDelta(options, data));
pollProcess = setInterval( function() {
if (options.retrieveGps) {
client.Handle({
'get_location': {}
}, (error, response) => {
if (error) {
app.debug('Cannot retrieve position from Starlink');
return;
}
let latitude = response.get_location.lla.lat;
let longitude = response.get_location.lla.lon;
let values;
if ((previousLatitude) && (previousLongitude)) {
courseAndSpeedOverGround = calculateCourseAndSpeed(
previousLatitude,
previousLongitude,
latitude,
longitude
);
values = [
{
path: 'navigation.position',
value: {
'longitude': longitude,
'latitude': latitude
},
}, {
path: 'navigation.courseOverGroundTrue',
value: courseAndSpeedOverGround.course
}, {
path: 'navigation.speedOverGround',
value: courseAndSpeedOverGround.speed
}
]
} else {
values = [
{
path: 'navigation.position',
value: {
'longitude': longitude,
'latitude': latitude
}
}
]
}
app.handleMessage('signalk-starlink', {
updates: [{
values: values
}]
});
previousLatitude = latitude;
previousLongitude = longitude;
app.debug(`Position received from Starlink (${latitude}, ${longitude})`);
});
}
client.Handle({
'get_status': {}
}, (error, response) => {
if (error) {
app.debug(`Error reading from Dishy.`);
if (errorCount++ >= 5) {
client.close();
client = new Device(
"192.168.100.1:9200",
grpc.credentials.createInsecure()
);
errorCount = 0;
app.debug(`Retrying connection`);
}
return;
}
let values;
if (response.dish_get_status.outage) {
let duration = response.dish_get_status.outage.duration_ns / 1000 / 1000 /1000;
duration = timeSince(duration);
app.setPluginStatus(`Starlink has been offline (${response.dish_get_status.outage.cause}) for ${duration}`);
dishyStatus = response.dish_get_status.outage.cause;
values = [
{
path: `${STARLINK}.status`,
value: 'offline'
},
{
path: `${STARLINK}.outage.cause`,
value: response.dish_get_status.outage.cause
},
{
path: `${STARLINK}.outage.start`,
value: new Date(response.dish_get_status.outage.start_timestamp_ns/1000/1000)
},
{
path: `${STARLINK}.outage.duration`,
value: response.dish_get_status.outage.duration_ns/1000/1000/1000
},
{
path: `${STARLINK}.uptime`,
value: response.dish_get_status.device_state.uptime_s
},
{
path: `${STARLINK}.hardware`,
value: response.dish_get_status.device_info.hardware_version
},
{
path: `${STARLINK}.software`,
value: response.dish_get_status.device_info.software_version
},
{
path: `${STARLINK}.alerts`,
value: response.dish_get_status.alerts
}
];
} else {
if (dishyStatus != "online") {
app.setPluginStatus('Starlink is online');
dishyStatus = "online";
}
values = [
{
path: `${STARLINK}.status`,
value: 'online'
},
{
path: `${STARLINK}.uptime`,
value: response.dish_get_status.device_state.uptime_s
},
{
path: `${STARLINK}.hardware`,
value: response.dish_get_status.device_info.hardware_version
},
{
path: `${STARLINK}.software`,
value: response.dish_get_status.device_info.software_version
},
{
path: `${STARLINK}.downlink_throughput`,
value: response.dish_get_status.downlink_throughput_bps || 0
},
{
path: `${STARLINK}.uplink_throughput`,
value: response.dish_get_status.uplink_throughput_bps || 0
},
{
path: `${STARLINK}.latency`,
value: response.dish_get_status.pop_ping_latency_ms
},
{
path: `${STARLINK}.alerts`,
value: response.dish_get_status.alerts
}
];
}
app.handleMessage('signalk-starlink', {
updates: [{
values: values
}]
});
});
}, POLL_STARLINK_INTERVAL * 1000);
}
plugin.stop = function() {
clearInterval(pollProcess);
app.setPluginStatus('Pluggin stopped');
};
function stowDishy() {
client.Handle({
'dish_stow': {}
}, (error, response) => {
if (!error) {
stowRequested = true;
}
});
}
function unstowDishy() {
client.Handle({
'dish_stow': {
unstow: true
}
}, (error, response) => {
if (!error) {
stowRequested = false;
}
});
}
function calculateDistance(lat1, lon1, lat2, lon2) {
if ((lat1 == lat2) && (lon1 == lon2)) {
return 0;
}
else {
var radlat1 = Math.PI * lat1/180;
var radlat2 = Math.PI * lat2/180;
var theta = lon1-lon2;
var radtheta = Math.PI * theta/180;
var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
if (dist > 1) {
dist = 1;
}
dist = Math.acos(dist);
dist = dist * 180/Math.PI;
dist = dist * 60 * 1.1515;
dist = dist * 0.8684; // Convert to Nautical miles
return dist;
}
}
function processDelta(options, data) {
let source = data.updates[0]['$source'];
let dict = data.updates[0].values[0];
let path = dict.path;
let value = dict.value;
switch (path) {
case 'navigation.position':
if (!gpsSource) {
gpsSource = source;
app.debug(`Setting GPS source to ${source}.`);
} else if (gpsSource != source) {
app.debug(`Ignoring position from ${source}.`);
break;
}
positions.unshift({
latitude: value.latitude,
longitude: value.longitude
});
positions = positions.slice(0, 10); // Keep 10 minutes of positions
if (positions.length < 10) {
app.debug(`Not enough position reports yet (${positions.length}) to calculate distance.`);
break;
}
let distance = 0;
for (let i=1;i < positions.length;i++) {
let previousPosition = positions[i-1];
let position = positions[i];
distance = distance + calculateDistance(position.latitude,
position.longitude,
previousPosition.latitude,
previousPosition.longitude);
}
app.debug (`Distance covered in the last 10 minutes is ${distance} miles.`);
if (options.stowWhileMoving && (distance >= 0.15)) {
if (dishyStatus == "online") {
app.debug (`Vessel is moving, stowing Dishy.`);
stowDishy();
} else {
app.debug(`Vessel is moving but Dishy is not online.`);
}
} else {
if (dishyStatus == "online") {
app.debug (`Vessel is stationary, and dishy is not stowed.`);
} else if (dishyStatus == "STOWED") {
if (stowRequested) {
app.debug (`Vessel is stationary, and we previously stowed Dishy. Unstowing.`);
unstowDishy();
} else {
app.debug (`Vessel is stationary, and Dishy is stowed, but not by us. Ignoring.`);
}
}
}
break;
case 'environment.wind.speedApparent':
break;
default:
app.error('Unknown path: ' + path);
}
}
function timeSince(seconds) {
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 haversine(lat1, lon1, lat2, lon2) {
const earthRadius = 6371e3; // Radius of the Earth in meters
// Convert latitude and longitude from degrees to radians
const lat1Rad = lat1 * Math.PI / 180;
const lon1Rad = lon1 * Math.PI / 180;
const lat2Rad = lat2 * Math.PI / 180;
const lon2Rad = lon2 * Math.PI / 180;
// Haversine formula
const dLat = lat2Rad - lat1Rad;
const dLon = lon2Rad - lon1Rad;
const a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.sin(dLon/2) * Math.sin(dLon/2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
const distance = earthRadius * c; // Distance in meters
return distance;
}
function calculateCourseAndSpeed(lat1, lon1, lat2, lon2) {
// Calculate distance between the two points
const distance = haversine(lat1, lon1, lat2, lon2);
// Calculate speed over ground (SOG) in meters per second
const speed = distance / POLL_STARLINK_INTERVAL;
// Calculate course over ground (COG) in radians
const angle = Math.atan2(lon2 - lon1, lat2 - lat1);
const course = angle < 0 ? angle + 2 * Math.PI : angle;
return { course, speed };
}
return plugin;
}