-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.js
921 lines (832 loc) · 29.8 KB
/
main.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
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
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
/*
* Copyright 2017-2022 Joachim Bakke
*
* 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 Bacon = require("baconjs")
const util = require("util")
const utilSK = require("@signalk/nmea0183-utilities")
const express = require("express")
const _ = require("lodash")
const Database = require("better-sqlite3")
const uuidv4 = require("uuid/v4")
const parse = require("csv-parse")
const fs = require("fs")
const path = require("path")
var csvList = ["ignore"]//"Set" for unique
module.exports = function(app, options) {
"use strict"
var client
var selfContext = "vessels." + app.selfId
var userDir = app.config.configPath
var plugin = {}
plugin.id = "signalk-polar"
var unsubscribes = []
var shouldStore = function(path) {
return true
}
var allPolars = {}
var polarList = ["none"]
var polarNames = ["No active Polar"]
var activePolar
const keyPaths = [
"performance.velocityMadeGood", // if empty, populate from this plugin
"navigation.rateOfTurn", // if above threshold, vessel is turning and no data is stored
"navigation.speedThroughWater",
"environment.wind.angleApparent",
"environment.wind.speedApparent",
"navigation.courseOverGroundTrue",
"navigation.speedOverGround"
]
var currentVmg, currentRot, currentStw, currentAwa, currentTwa, currentAws, currentCog, currentSog, currentTws
var currentTwaQuadrant
var unsubscribes = []
return {
id: "signalk-polar",
name: "Polar storage and retrieval",
description:
"Signal K server plugin that stores and retrieves static and/or dynamic polar data",
uiSchema: {
entered: {
items: {
polarUuid: { "ui:widget": "hidden" },
csvTable: { "ui:widget": "textarea" }
}
},
useDynamicPolar: { "ui:widget": "hidden" },
engine: { "ui:widget": "hidden" },
additional_info: { "ui:widget": "hidden" },
sqliteFile: { "ui:widget": "hidden" },
angleResolution: { "ui:widget": "hidden" },
twsInterval: { "ui:widget": "hidden" },
maxWind: { "ui:widget": "hidden" },
rateOfTurnLimit: { "ui:widget": "hidden" }
},
schema: {
type: "object",
title:
"A Signal K (node) plugin to maintain polar diagrams",
description: "",
properties: {
activePolar: {
type: "string",
title: "Active polar table",
enum: polarList,
enumNames: polarNames,
default: "none"
},
entered: {
type: "array",
title: "Static user input polars",
items: {
title: "",
type: "object",
properties: {
mirror: {
type: "boolean",
title: "Mirror polar port and stbd?",
default: true
},
polarName: {
type: "string",
title: "Name of polar ('design', 'lastYear' etc)",
default: "Design"
},
description: {
type: "string",
title: "further description of the polar"
},
polarUuid: {
type: "string",
title: "UUID of polar"
},
angleUnit: {
type: "string",
title: "Unit for wind angle",
default: "deg",
enum: ["rad", "deg"],
enumNames: ["Radians", "Degrees"]
},
windSpeedUnit: {
type: "string",
title: "Unit for wind speed",
default: "knots",
enum: ["knots", "ms", "kph", "mph"],
enumNames: ["Knots", "m/s", "km/h", "mph"]
},
boatSpeedUnit: {
type: "string",
title: "Unit for boat speed",
default: "knots",
enum: ["knots", "ms", "kph", "mph"],
enumNames: ["Knots", "m/s", "km/h", "mph"]
},
csvPreset: {
type: "string",
title: "Preset polars from https://github.com/seandepagnier/weather_routing_pi (server restart...?)",
default: "ignore",
enum: csvList,
enumNames: csvList
},
csvTable: {
type: "string",
title:
"OR enter csv with polar in http://jieter.github.io/orc-data/site/ style"
}
}
}
},
updateTables: {
type: "boolean",
title: "Update all tables (enable after making changes)",
default: false
},
useDynamicPolar: {
type: "boolean",
title: "Use dynamic polar diagram (may slow down server). Active polar will be updated"
},
engine: {
type: "string",
title:
"How is engine status monitored - stores to polar only when engine off",
default: "doNotStore",
enum: [
"alwaysOff",
"propulsion.*.revolutions",
"propulsion.*.state",
"doNotStore"
],
enumNames: [
"assume engine always off",
"propulsion.*.revolutions > 0",
"propulsion.*.state is not 'started'",
"do not store dynamic polar"
]
},
additional_info: {
type: "string",
title:
"replace * in 'propulsion.*.revolutions' or 'propulsion.*.state' with [ ]"
},
sqliteFile: {
type: "string",
title: "File for storing sqlite3 data, ",
default: "polarDatabase.db"
},
angleResolution: {
type: "number",
title: "angle resolution in degrees",
default: 1
},
twsInterval: {
type: "number",
title: "wind speed resolution in m/s",
default: 4
},
maxWind: {
type: "number",
title: "max wind speed to record/display, in m/s",
default: 15
},
rateOfTurnLimit: {
type: "number",
title:
"Store in database if rate of turn is unavailable or less than [ ] deg/min (inertia gives false reading while turning vessel)",
default: 5
}
}
},
start: function(options) {
app.debug('started plugin')
var csvFolder = path.join(userDir, '/node_modules/', plugin.id, '/seandepagnier')
if (!fs.existsSync(csvFolder)) {
fs.mkdirSync(csvFolder)
}
fs.readdirSync(csvFolder).forEach(file => {
if (file != 'Example' && file != 'Additional'){
csvList.push(file)
}
})
if (options.activePolar){
activePolar = options.activePolar
}
if (options.updateTables){
//update tables and JSON files
if (options.entered && options.entered.length > 0) {
var counter = 0
options.entered.forEach(table => {
var tableName = table.polarName.replace(/ /gi, "_")
var tableUuid
if (table.polarUuid) {
tableUuid = table.polarUuid
//app.debug("Polar uuid exists: '" + tableUuid + "'", typeof(tableUuid))
} else {
tableUuid = uuidv4()
options.entered[counter].polarUuid = tableUuid
app.debug("Polar uuid does not exist, creating '" + tableUuid + "'")
app.savePluginOptions(options, function(err, result) {
if (err) {
app.debug(err)
}
})
}
polarList.push(table.polarUuid)
polarNames.push(tableName)
var description
if (table.description) {
description = table.description
} else {
description = ''
}
app.debug("polar name is " + tableName)
var output = []
var delimiter, lineBreak, csvTable
if(!table.csvTable && table.csvPreset && table.csvPreset != "ignore"){
//app.debug(table.csvPreset)
var extension = path.extname(table.csvPreset)
//app.debug("extension: " + extension)
var data = fs.readFileSync(path.join(userDir, '/node_modules/', plugin.id, '/seandepagnier/', table.csvPreset), 'utf8', function (err, data) {
if (err) {
app.debug(err);
process.exit(1);
}
})
var csvStrBack
if (extension == '.txt'){
csvStrBack = data.split('\n').slice(1).join('\n')
}
else if (extension == '.pol'){
csvStrBack = data
}
var csvStr = csvStrBack.replace(/\\/g, '/')
app.debug('csvStr: ' + csvStr)
if (extension == '.csv'){
var csvTab = csvStrBack.trim().replace(/\°/g, '')
csvTable = csvTab.replace(/( [\r,\n]+)|(;\D*\n)|(;\D*[\r,\n]+)/g, '\r\n')
}
else if (extension == '.pol'){
csvTable = csvStr.trim().replace(/(\t+|\t| |\t\t| )(?!\n| \n|$)/g, ";")
}
//app.debug(csvTable)
options.entered[counter].csvTable = csvTable
app.savePluginOptions(options, function(err, result) {
if (err) {
app.debug(err)
}
})
}
else {
csvTable = table.csvTable
}
delimiter = ";"
parse(csvTable, {
trim: true,
skip_empty_lines: true,
delimiter: delimiter,
record_delimiter: lineBreak
}).on("readable", function() {
let windData = []
let record
while ((record = this.read())) {
output.push(record)
}
app.debug(JSON.stringify(output))
var windSpeeds = []
var angleData = []
output[0].forEach(listSpeeds)
function listSpeeds(item, index) {
if (index > 0) {
//first is "twa/tws"
var windSpeedItem = utilSK.transform(item,table.windSpeedUnit,"ms")
windSpeeds.push(Number(windSpeedItem))
}
}
//app.debug("windspeeds: " + JSON.stringify(windSpeeds))
output.forEach(storeSpeeds)
function storeSpeeds(item, index) {
if (index > 0) {
//first row is header, and already parsed
var itemAngle = utilSK.transform(Number(item[0]),table.angleUnit,"rad")
//app.debug("itemAngle: " +itemAngle)
item.forEach(storeSpeed)
function storeSpeed(speedItem, index) {
if (!angleData[index-1]){
angleData[index-1] = [[0,null,null]]
}
var speed = utilSK.transform(speedItem,table.boatSpeedUnit, "ms" )
if (index > 0 && speed != 0) {
//first item is angle, already parsed
var vmg = getVelocityMadeGood(speed, itemAngle)
angleData[index-1].push([itemAngle, speed, vmg])
if(table.mirror){
angleData[index-1].push([-itemAngle, speed, vmg])
}
}
}
}
}
//app.debug('windSpeeds:' + util.inspect(windSpeeds))
windSpeeds.forEach(pushWindData)
function pushWindData(wind, index){
app.debug('wind: ' + wind + ' index: ' + index)
let optimalBeats =[]
let optimalGybes = []
function findOptimalBeats(arr) {
var bestVmg = 0
var bestOrigin = [];
for(var i = 0; i < arr.length; i++){
if(arr[i][2] && arr[i][2] > bestVmg){
bestVmg = arr[i][2];
bestOrigin = [arr[i][0],arr[i][1]];
}
}
if(table.mirror){
return [bestOrigin, [-bestOrigin[0], bestOrigin[1]]]
} else {
return [bestOrigin, null]//@TODO should find port beat
}
}
function findOptimalGybes(arr) {
var bestVmg = 0,
bestOrigin = [];
for(var i = 0; i < arr.length; i++){
if(arr[i][2] && arr[i][2] < bestVmg){
bestVmg = arr[i][2];
bestOrigin = [arr[i][0],arr[i][1]];
}
}
if(table.mirror){
return [bestOrigin, [-bestOrigin[0], bestOrigin[1]]]
} else {
return [bestOrigin, null]//@TODO should find port gybe
}
}
optimalBeats = findOptimalBeats(angleData[index])
optimalGybes = findOptimalGybes(angleData[index])
windData.push({
"trueWindSpeed": wind,
"optimalBeats": optimalBeats,
"optimalGybes": optimalGybes,
"angleData": angleData[index].sort((a, b) => a[0] - b[0])
})
}
var jsonFormat = {
[tableUuid]: {
"id": tableUuid,
"name": tableName,
"description": description,
"source": {
"label": "signalk-polar"
},
"windData": windData
}
}
//store polar as [uuid].json
let tableFile = path.join(userDir, 'plugin-config-data', plugin.id, tableUuid)
tableFile = tableFile.slice(0, -1) + '.json'
app.debug('tableFile: ' + tableFile)
let jsonStore = JSON.stringify(jsonFormat, null, 2)
//app.debug("jsonStore is: " + typeof(jsonStore))
//app.debug("jsonStore : " + util.inspect(jsonStore))
fs.writeFile(tableFile, jsonStore, (err) => {
app.debug('writing json file')
if (err) {
app.debug(err);
process.exit(1);
}
})
})
counter += 1
})
}
//now disable the function again
options.updateTables = false
app.savePluginOptions(options, function(err, result) {
if (err) {
app.debug(err)
}
})
}
/*
if (options.useDynamicPolar){
var mainPolarUuid
if (options.dynamic[0].polarUuid) {
mainPolarUuid = options.dynamic[0].polarUuid
app.debug("Polar uuid exists: " + mainPolarUuid, typeof mainPolarUuid)
} else {
mainPolarUuid = uuidv4()
options.dynamic[0].polarUuid = mainPolarUuid
app.debug("Polar uuid does not exist, creating " + mainPolarUuid)
app.savePluginOptions(options, function(err, result) {
if (err) {
app.debug(err)
}
})
}
//handle deltas
//use the dynamic polar as active
activePolar = options.dynamic[0].polarUuid
polarList.push(mainPolarUuid)
options.activePolar = activePolar
app.debug('active Polar: ' + options.activePolar)
app.savePluginOptions(options, function(err, result) {
if (err) {
app.debug(err)
}
})
}
*/
else if(options.entered) {
options.entered.forEach(table => {
polarList.push(table.polarUuid)
polarNames.push(table.polarName)
})
if (options.entered.length == 1){
setActivePolar(options.entered[0].polarUuid)
}
}
let obj = {}
keyPaths.forEach(element => {
obj[element] = true
})
shouldStore = function(path) {
return typeof obj[path] != "undefined"
}
app.streambundle
.getSelfStream('navigation.rateOfTurn')
.forEach(rot => {currentRot = rot; //app.debug('rot:',currentRot)
});
app.streambundle
.getSelfStream('navigation.speedThroughWater')
.forEach(stw => {currentStw = stw; //app.debug('stw:',currentStw)
});
app.streambundle
.getSelfStream('environment.wind.angleApparent')
.forEach(awa => {currentAwa = awa; //app.debug('awa:',currentAwa)
});
app.streambundle
.getSelfStream('environment.wind.angleTrueWater')
.forEach(twa => {currentTwa = twa; //app.debug('twa:',currentTwa);
currentTwaQuadrant = calculateQuadrant(currentTwa)
});
app.streambundle
.getSelfStream('environment.wind.speedApparent')
.forEach(aws => {currentAws = aws; //app.debug('aws:',currentAws)
});
app.streambundle
.getSelfStream('environment.wind.speedTrue')
.forEach(tws => {currentTws = tws; //app.debug('tws:',currentTws)
});
app.streambundle
.getSelfStream('navigation.courseOverGroundTrue')
.forEach(cog => {currentCog = cog; //app.debug('cog:',currentCog)
});
app.streambundle
.getSelfStream('navigation.speedOverGround')
.forEach(sog => {currentSog = sog; //app.debug('sog:',currentSog)
});
app.streambundle
.getSelfStream('performance.velocityMadeGood')
.forEach(vmg => {currentVmg = vmg; //app.debug('vmg:',currentVmg)
});
var fullActivePolar = {}
getPolar(activePolar, userDir, plugin).then((full) => {
fullActivePolar = full
})
if(activePolar != "none" && activePolar != undefined) {
let pushInterval = setInterval(function() {
var beatAngle, beatSpeed, gybeAngle, gybeSpeed
var activePolarWindArray = []
fullActivePolar[activePolar].windData.forEach(item => {
activePolarWindArray.push(item.trueWindSpeed)
})
var windIndex = closestTws(currentTws, activePolarWindArray)
app.debug(' currentTws: ' + currentTws + ' windIndex: ' + windIndex + ' windArray: ' + activePolarWindArray[windIndex])
//@TODO: if wind angle not more acute than beatAngle or more obtuse than gybeAngles, interpolate between angles for lower and higher windIndex, and between these
var polarSpeed, polarSpeedRatio
var windAngleIndex = closestAngle(currentTwa, fullActivePolar[activePolar].windData[windIndex].angleData)
if(windIndex == activePolarWindArray.length){
//if above highest wind speed in table, interpolate only for wind angle
polarSpeed = interpolate(
currentTwa,
fullActivePolar[activePolar].windData[windIndex].angleData[windAngleIndex][0],
fullActivePolar[activePolar].windData[windIndex].angleData[windAngleIndex+1][0],
fullActivePolar[activePolar].windData[windIndex].angleData[windAngleIndex][1],
fullActivePolar[activePolar].windData[windIndex].angleData[windAngleIndex+1][1],
)
polarSpeedRatio = currentStw/polarSpeed
pushDelta(app, "performance.polarSpeed", polarSpeed, plugin)
pushDelta(app, "performance.polarSpeedRatio", polarSpeedRatio, plugin)
}
else if (windIndex == 0){
// if below lowest wind spped in table interpolate between 0 and tws
var psLow = 0
var psHigh = interpolate(
currentTwa,
fullActivePolar[activePolar].windData[windIndex].angleData[windAngleIndex][0],
fullActivePolar[activePolar].windData[windIndex].angleData[windAngleIndex+1][0],
fullActivePolar[activePolar].windData[windIndex].angleData[windAngleIndex][1],
fullActivePolar[activePolar].windData[windIndex].angleData[windAngleIndex+1][1],
)
polarSpeed = interpolate(
currentTws,
0,
fullActivePolar[activePolar].windData[windIndex].trueWindSpeed,
psLow,
psHigh
)
polarSpeedRatio = currentStw/polarSpeed
pushDelta(app, "performance.polarSpeed", polarSpeed, plugin)
pushDelta(app, "performance.polarSpeedRatio", polarSpeedRatio, plugin)
} else {
var psLow = interpolate(
currentTwa,
fullActivePolar[activePolar].windData[windIndex-1].angleData[windAngleIndex][0],
fullActivePolar[activePolar].windData[windIndex-1].angleData[windAngleIndex+1][0],
fullActivePolar[activePolar].windData[windIndex-1].angleData[windAngleIndex][1],
fullActivePolar[activePolar].windData[windIndex-1].angleData[windAngleIndex+1][1],
)
var psHigh = interpolate(
currentTwa,
fullActivePolar[activePolar].windData[windIndex].angleData[windAngleIndex][0],
fullActivePolar[activePolar].windData[windIndex].angleData[windAngleIndex+1][0],
fullActivePolar[activePolar].windData[windIndex].angleData[windAngleIndex][1],
fullActivePolar[activePolar].windData[windIndex].angleData[windAngleIndex+1][1],
)
polarSpeed = interpolate(
currentTws,
fullActivePolar[activePolar].windData[windIndex-1].trueWindSpeed,
fullActivePolar[activePolar].windData[windIndex].trueWindSpeed,
psLow,
psHigh
)
polarSpeedRatio = currentStw/polarSpeed
pushDelta(app, "performance.polarSpeed", polarSpeed, plugin)
pushDelta(app, "performance.polarSpeedRatio", polarSpeedRatio, plugin)
}
//console.log("windAngle: " + currentTwa + " betw " + fullActivePolar[activePolar].windData[windIndex].angleData[windAngleIndex][0] + " and " + fullActivePolar[activePolar].windData[windIndex].angleData[windAngleIndex+1][0])
if(fullActivePolar[activePolar].windData[windIndex].optimalBeats[0][0]){
if(windIndex == 0 || windIndex == activePolarWindArray.length){
beatAngle = fullActivePolar[activePolar].windData[windIndex].optimalBeats[0][0]
} else {
beatAngle = interpolate(
currentTws,
fullActivePolar[activePolar].windData[windIndex].trueWindSpeed,
fullActivePolar[activePolar].windData[windIndex+1].trueWindSpeed,
fullActivePolar[activePolar].windData[windIndex].optimalBeats[0][0],
fullActivePolar[activePolar].windData[windIndex+1].optimalBeats[0][0],
)
}
pushDelta(app, "performance.beatAngle", beatAngle, plugin)
}
if(fullActivePolar[activePolar].windData[windIndex].optimalBeats[0][1]){
if(windIndex == 0 || windIndex == activePolarWindArray.length){
beatSpeed = fullActivePolar[activePolar].windData[windIndex].optimalBeats[0][1]
} else {
beatSpeed = interpolate(
currentTws,
fullActivePolar[activePolar].windData[windIndex].trueWindSpeed,
fullActivePolar[activePolar].windData[windIndex+1].trueWindSpeed,
beatSpeed = fullActivePolar[activePolar].windData[windIndex].optimalBeats[0][1],
beatSpeed = fullActivePolar[activePolar].windData[windIndex+1].optimalBeats[0][1]
)
}
pushDelta(app, "performance.beatAngleTargetSpeed", beatSpeed, plugin)
}
if(fullActivePolar[activePolar].windData[windIndex].optimalGybes[0][0]){
if(windIndex == 0 || windIndex == activePolarWindArray.length){
gybeAngle = fullActivePolar[activePolar].windData[windIndex].optimalGybes[0][0]
} else {
gybeAngle = interpolate(
currentTws,
fullActivePolar[activePolar].windData[windIndex].trueWindSpeed,
fullActivePolar[activePolar].windData[windIndex+1].trueWindSpeed,
gybeAngle = fullActivePolar[activePolar].windData[windIndex].optimalGybes[0][0],
gybeAngle = fullActivePolar[activePolar].windData[windIndex+1].optimalGybes[0][0]
)
}
pushDelta(app, "performance.gybeAngle", gybeAngle, plugin)
}
if(fullActivePolar[activePolar].windData[windIndex].optimalGybes[0][1]){
if(windIndex == 0 || windIndex == activePolarWindArray.length){
gybeSpeed = fullActivePolar[activePolar].windData[windIndex].optimalGybes[0][1]
} else {
gybeSpeed = interpolate(
currentTws,
fullActivePolar[activePolar].windData[windIndex].trueWindSpeed,
fullActivePolar[activePolar].windData[windIndex+1].trueWindSpeed,
gybeSpeed = fullActivePolar[activePolar].windData[windIndex].optimalGybes[0][1],
gybeSpeed = fullActivePolar[activePolar].windData[windIndex+1].optimalGybes[0][1]
)
}
pushDelta(app, "performance.gybeAngleTargetSpeed", gybeSpeed, plugin)
}
if(windIndex == 0 || windIndex == activePolarWindArray.length){
}
//app.debug("tws: " + tws + " abs twa: " + Math.abs(twa) + " stw: " + stw)
//getTarget(app, tws, twsInterval, twa, twaInterval, stw)
//app.debug("sent to setInterval:" + tws + " : " + twsInterval + " : " + Math.abs(twa) + " : " + twaInterval)
}, 1000)
}
function setActivePolar(uuid){
activePolar = uuid
options.activePolar = activePolar
app.debug('active Polar: ' + options.activePolar)
app.savePluginOptions(options, function(err, result) {
if (err) {
app.debug(err)
}
})
}
},
registerWithRouter: function(router) {
//@TODO: add put message to delete table
router.get("/polarTables", async(req, res) => {
res.contentType("application/json")
var polarsCombined = {}
const arr = await Promise.all(
polarList.map(item => {
return getPolar(item, userDir, plugin)
})
)
var results = arr.reduce((a, b) => Object.assign(a, b), {})
var response = { polars: results }
res.send(response)
})
router.get("/polarTable", async (req, res) => {
res.contentType("application/json")
var uuid = req.query.uuid?req.query.uuid:activePolar
var response = await getPolar(uuid, userDir, plugin)
res.send(response)
})
router.get("/listPolarTables", (req, res) => {
res.contentType("application/json")
app.debug(polarList)
res.send(polarList)
})
router.get("/deletePolarTable", (req, res) =>{
var uuid = req.query.uuid
app.debug("requested to delete " + uuid)
deletePolarTable(uuid)
res.redirect('back')
})
router.post("/setActivePolar", (req, res) =>{
var uuid = req.query.uuid
app.debug("setting active polar " + uuid)
//@TODO: Add function
res.redirect('back')
})
},
stop: function() {
unsubscribes.forEach(f => f());
polarList = polarNames = csvList = []
app.setPluginStatus('Stopped');
}
}
}
module.exports.app = "app"
module.exports.options = "options"
function getTrueWindAngle(speed, trueWindSpeed, apparentWindspeed, windAngle) {
// alpha=arccos((A*cos(beta)-V)/W)
//A is apparent wind speed,
//beta is apparent wind angle
//V is boat speed
//W is true wind speed
//alpha is true wind angle
var cosAlpha =
(apparentWindspeed * Math.cos(windAngle) - speed) / trueWindSpeed
if (windAngle === 0) {
return 0
} else if (windAngle == Math.PI) {
return Math.PI
} else if (cosAlpha > 1 || cosAlpha < -1) {
/*app.debug(
"invalid triangle aws: " +
apparentWindspeed +
" tws: " +
trueWindSpeed +
" bsp: " +
speed
)*/
return null
} else {
var calc
if (windAngle >= 0 && windAngle <= Math.PI) {
//Starboard
calc = Math.acos(cosAlpha)
} else if (windAngle < 0 && windAngle > -Math.PI) {
//Port
calc = -Math.acos(cosAlpha)
}
//app.debug("true wind angle: " + calc)
return calc
}
}
function getVelocityMadeGood(stw, twa) {
//app.debug("getVelocityMadeGood called")
return Math.cos(twa) * stw
}
function pushDelta(app, path, value, plugin) {
app.handleMessage(plugin.id, {
updates: [
{
values: [
{
path: path,
value: value
}
]
}
]
})
return
}
function closestTws(num,arr) {
//this should set the windIndex to a value if a tws falls between values in the polar tws table
// ie 0-6 kts use 6 kts column, 6.00001 to 8 kts use the 8 kts column...
var lowTws = arr[0],
index = 0;
if (num<=lowTws){
return 0;
} else if (num >=arr[arr.length]){
return arr.length;
} else {
for (var val = 0; val < arr.length -1; val++) {
if (num > arr[val] && num <= arr[val+1]) {
//console.log('tws:' + num + ' Test = ' + val +' above/below: ' + arr[val], arr[val+1])
index = val+1;
}
}
return index;
}
}
function closest(num, arr) {
var curr = arr[0],
diff = num - curr,
index = 0;
if(num<arr[0]){
return 0
} else if (num>arr[arr.length]){
return arr.length
} else {
for (var val = 0; val < arr.length-1; val++) {
//console.log(val + ' comparing ' + num + ' to ' + arr[val])
let newdiff = num - arr[val];
if (newdiff < diff && newdiff > 0) {
diff = newdiff;
curr = arr[val];
index = val;
}
}
return index;
}
}
function closestAngle(twa, angleData){
angleData.sort((a, b) => a[0] - b[0])
return closest(twa, angleData.map(x => x[0]))
}
function interpolate(x, xbottom, xtop, ybottom, ytop){
var xdist = xtop - xbottom
var ydist = ytop - ybottom;
return (ybottom + (((x-xbottom) / xdist)) * ydist)
}
function calculateQuadrant(twa){
if(twa < 0){
twa+=Math.PI*2
}
var quad = Math.floor(twa/(Math.PI/2))+1
return quad
}
const getPolar = async (uuid, userDir, plugin) => {
if(typeof(userDir) != 'undefined' && typeof(uuid) != 'undefined'){
let tableFile = path.join(userDir, 'plugin-config-data', plugin.id, uuid)
tableFile = tableFile.slice(0, -1) + '.json'
try {
if (fs.existsSync(tableFile)) {
var rawData = await fs.readFileSync(tableFile, function (err, data) {
if (err) {
app.debug(err);
process.exit(1);
}
})
var response = JSON.parse(rawData)
//app.debug(response)
return response
}
} catch(err) {
console.error(err)
}
}
else {
return
}
}