-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathrenderer.js
2110 lines (1817 loc) · 89.4 KB
/
renderer.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
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict'
const { ipcRenderer } = require ('electron');
const { app, BrowserWindow } = require ( '@electron/remote' )
const ConfigStore = require ( 'configstore' );
const { SerialPort } = require ( 'serialport' );
const Chart = require ( 'chart.js' );
const Swal = require ( 'sweetalert2' );
const FREQ_VENDOR_PRESETS = require ( 'require-all' )(__dirname +'/frequency_data/presets' );
const Pkg = require ('./package.json');
const fs = require ('fs');
var { Subject, firstValueFrom } = require('rxjs');
const { timeout } = require ('rxjs/operators');
const configStore = new ConfigStore ( Pkg.name )
require ( './logger.js' );
const moment = require('moment-timezone');
// Supported devices
const RFExplorer = require('./scan_devices/rf_explorer.js');
const TinySA = require('./scan_devices/tiny_sa.js');
const SAVED_DATA_VERSION = 1
const CONGESTION_LEVEL_DBM = -85
const SERIAL_RESPONSE_TIMEOUT = 1500
const LINE_LIVE = 0
const LINE_RECOMMENDED = 1
const LINE_FORBIDDEN = 2
const LINE_CONGESTED = 3
const LINE_CONGEST_TRESH = 4
const LINE_GRIDS = 5
const LINE_FORBIDDEN_MARKERS = 6
global.MAX_DBM = -20
global.MIN_DBM = -110
global.MIN_FREQ = undefined
global.MAX_FREQ = undefined
global.MIN_SPAN = undefined
global.MAX_SPAN = undefined
global.SWEEP_POINTS = 100 // default value
var COM_PORT = undefined
var VENDOR_ID = 'NON'
const SENNHEISER_CHANNEL_WIDTH = 96000 // +/-48kHz Spitzenhub
let isExecuting = false
var port = null
let globalPorts = []
let baudRate = ''
var scanDevice = null
let saved_data_version = configStore.get('saved_data_version')
let portDetectionIndex = 0
var data$ = new Subject();
let dataSubscription = null
let popupCategory = ''
let responseCheckTimer = null
let formValid = false
let ctx = null;
let curKeyInputTarget = '';
let keyInputTargets = {
MANUAL_BAND_SETTINGS: 'MANUAL_BAND_SETTINGS',
SWEEP_POINT_SETTINGS: 'SWEEP_POINT_SETTINGS'
}
// Saved data version handling
if ( !saved_data_version ) {
configStore.set ( 'saved_data_version', SAVED_DATA_VERSION )
saved_data_version = SAVED_DATA_VERSION
} else {
switch ( saved_data_version ) {
case 1: // Nothing to do
break;
default:
log.info ( "Unknown version of saved data!" )
}
}
let chPreset_Vendor = configStore.get('chPreset.vendor');
let chPreset_Band = configStore.get('chPreset.band' );
let chPreset_Series = configStore.get('chPreset.series');
let chPreset_Preset = configStore.get('chPreset.preset');
let COUNTRY_CODE = configStore.get('country_code' );
var COUNTRY_NAME = configStore.get('country_name' );
global.START_FREQ = configStore.get('start_freq');
var LAST_START_FREQ = configStore.get('last_start_freq');
global.STOP_FREQ = configStore.get('stop_freq');
var LAST_STOP_FREQ = configStore.get('last_stop_freq' );
var FREQ_STEP = configStore.get('freq_step');
var BAND_LABEL = configStore.get('band_label' );
var BAND_DETAILS = configStore.get('band_details' );
var VIS_MANUF_CHAN = configStore.get('graphVisibility.recommended');
var VIS_FORBIDDEN = configStore.get('graphVisibility.forbidden' );
var VIS_CONGEST = configStore.get('graphVisibility.congested' );
var VIS_TV_CHAN = configStore.get('graphVisibility.grids' );
global.MX_LINUX_WORKAROUND = configStore.get('mx_linux_workaround_enabled' );
global.SCAN_DEVICE = configStore.get('scan_device' );
var COM_PORT = configStore.get('com_port');
var SWEEP_POINTS = configStore.get('sweep_points');
let DARK_MODE = configStore.get('dark_mode');
const chartColors = {
RED : 'rgb(255, 99 ,132 )',
AMBER : 'rgb(255, 159, 64 )',
GREEN : 'rgb(75 , 222, 192)',
PURPLE : 'rgb(153, 102, 255)',
GREY : 'rgb(201, 203, 207)'
}
const RECOMMENDED_CHANNELS_COLOR = chartColors.GREEN
const FORBIDDEN_COLOR = chartColors.RED
const SCAN_COLOR = chartColors.PURPLE
const CONGESTED_COLOR = chartColors.AMBER
const CHAN_GRID_COLOR = chartColors.GREY
if ( !global.MX_LINUX_WORKAROUND ) {
configStore.set('mx_linux_workaround_enabled', false )
global.MX_LINUX_WORKAROUND = false
}
log.info ( "=========== Starting application ===========")
log.info ( `Running on platform: '${process.platform}'`)
log.info ( "MX Linux workaround is " + (global.MX_LINUX_WORKAROUND ? "enabled" : "disabled"))
ipcRenderer.send ('MX_LINUX_WORKAROUND', { checked : global.MX_LINUX_WORKAROUND });
if ( !DARK_MODE) {
configStore.set('dark_mode', false )
DARK_MODE = false
}
log.info ( "Dark mode is " + (DARK_MODE ? "enabled" : "disabled"))
ipcRenderer.send ('DARK_MODE', { checked : DARK_MODE });
if ( VIS_MANUF_CHAN === undefined ) VIS_MANUF_CHAN = true;
if ( VIS_FORBIDDEN === undefined ) VIS_FORBIDDEN = true;
if ( VIS_CONGEST === undefined ) VIS_CONGEST = true;
if ( VIS_TV_CHAN === undefined ) VIS_TV_CHAN = true;
if ( !COUNTRY_CODE || !fs.existsSync ( __dirname + '/frequency_data/forbidden/FORBIDDEN_' + COUNTRY_CODE + '.json' ) ) {
COUNTRY_CODE = 'DE';
log.info ( "No country set or file with forbidden ranges for that country does not exist! Falling back to 'DE'");
}
if ( !COM_PORT ) {
COM_PORT = 'AUTO'
configStore.set ( 'com_port', COM_PORT )
} else {
ipcRenderer.send ('SET_PORT', { portPath : COM_PORT });
}
if ( !SWEEP_POINTS ) {
configStore.set ( 'sweep_points', global.SWEEP_POINTS )
} else {
global.SWEEP_POINTS = SWEEP_POINTS
}
var FREQ_FORBIDDEN = require ( __dirname + '/frequency_data/forbidden/FORBIDDEN_' + COUNTRY_CODE + '.json');
if ( fs.existsSync ( __dirname + '/frequency_data/grids/GRIDS_' + COUNTRY_CODE + '.json' ) )
var FREQ_GRIDS = require ( __dirname + '/frequency_data/grids/GRIDS_' + COUNTRY_CODE + '.json');
else
var FREQ_GRIDS = null;
var chDispValShadowArr = [];
var myChart = null
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('donate-button').addEventListener ('click', () => openDonateWindow() )
if (DARK_MODE) {
document.getElementsByTagName('body')[0].setAttribute('class', 'dark-mode')
}
ctx = document.getElementById("graph2d").getContext('2d');
if ( global.SCAN_DEVICE ) {
ipcRenderer.send ('SET_SCAN_DEVICE', { scanDevice : global.SCAN_DEVICE });
log.info ( `Scan device is '${global.SCAN_DEVICE}'`)
initChart()
connectDevice ( COM_PORT?COM_PORT:'AUTO', true )
} else {
log.info ( `No scan device selected. Waiting for user to select via popup ...`)
Swal.fire({
title: "Device selection",
html: `Please choose your scan device. You can change it later via the 'Device' menu.`,
input: 'select',
inputOptions: {
'RF_EXPLORER': RFExplorer.NAME,
'TINY_SA': TinySA.NAME
},
inputPlaceholder: 'Choose a scan device',
icon: "question",
showCancelButton: false,
confirmButtonColor: "#0099ff",
customClass: {
title: 'sweetalert2-title',
container: 'sweetalert2-container'
},
willOpen: function () {
Swal.getConfirmButton().setAttribute('disabled', 'true');
},
didOpen: () => {
document.getElementById('swal2-select').addEventListener("change", () => {
Swal.getConfirmButton().removeAttribute('disabled');
})
}
}).then ( result => {
initChart()
switch (result.value) {
case RFExplorer.HW_TYPE:
ipcRenderer.send ('SET_SCAN_DEVICE', { scanDevice : RFExplorer.HW_TYPE });
configStore.set ('scan_device', 'RF_EXPLORER')
global.SCAN_DEVICE = RFExplorer.HW_TYPE;
connectDevice ( COM_PORT?COM_PORT:'AUTO', true )
break
case TinySA.HW_TYPE:
ipcRenderer.send ('SET_SCAN_DEVICE', { scanDevice : TinySA.HW_TYPE });
configStore.set ('scan_device', 'TINY_SA')
global.SCAN_DEVICE = TinySA.HW_TYPE;
connectDevice(COM_PORT?COM_PORT:'AUTO', true )
break
}
})
}
})
async function showPopup ( type, category, title, html, buttonsArr = [] ) {
popupCategory = category
let swalConfig = {
title,
html,
icon: type,
showCancelButton: buttonsArr.length > 1 ? true : false,
confirmButtonColor: "#0099ff",
customClass: {
title: 'sweetalert2-title',
container: 'sweetalert2-container'
}
}
if ( buttonsArr.length ) {
swalConfig.confirmButtonText = buttonsArr[0]
}
if ( buttonsArr.length > 1 ) {
swalConfig.cancelButtonText = buttonsArr[buttonsArr.length-1]
}
return Swal.fire ( swalConfig )
}
async function initChart () {
myChart = new Chart(ctx, {
type: 'bar',
data: {
datasets: [
{
type: "line",
label: 'Live Scan (Peak Hold)',
backgroundColor: Chart.helpers.color(SCAN_COLOR).alpha(0.5).rgbString(),
borderColor: SCAN_COLOR,
pointBackgroundColor: SCAN_COLOR,
borderWidth: 2,
pointRadius: 1.5,
fill: 'start',
lineTension: 0.4
},{
type: "line",
label: 'Recommended Manuf. Channels',
backgroundColor: Chart.helpers.color(RECOMMENDED_CHANNELS_COLOR).alpha(0.5).rgbString(),
borderColor: RECOMMENDED_CHANNELS_COLOR,
borderWidth: 0.01, // 0 is not working!
pointRadius: 0,
fill: 'start',
lineTension: 0,
spanGaps: false,
hidden: !VIS_MANUF_CHAN
},{
type: "line",
label: 'Forbidden Ranges',
backgroundColor: Chart.helpers.color(FORBIDDEN_COLOR).alpha(0.5).rgbString(),
borderColor: FORBIDDEN_COLOR,
borderWidth: 0.01, // 0 is not working!
pointRadius: 0,
fill: 'start',
lineTension: 0,
spanGaps: false,
hidden: !VIS_FORBIDDEN
},{
type: "line",
label: 'Congested / Forbidden Channels',
backgroundColor: Chart.helpers.color(CONGESTED_COLOR).alpha(0.7).rgbString(),
borderColor: CONGESTED_COLOR,
borderWidth: 0.01, // 0 is not working!
pointRadius: 0,
fill: 'start',
lineTension: 0,
spanGaps: false,
hidden: !VIS_CONGEST
},{
type: "line",
label: 'Congest_Thresh',
backgroundColor: Chart.helpers.color(FORBIDDEN_COLOR).alpha(0.5).rgbString(),
borderColor: FORBIDDEN_COLOR,
borderWidth: 2,
pointRadius: 0,
fill: 'none',
lineTension: 0,
spanGaps: true
},{
type: "line",
label: 'TV Chan. Grid',
backgroundColor: Chart.helpers.color(CHAN_GRID_COLOR).alpha(0.3).rgbString(),
borderColor: CHAN_GRID_COLOR,
borderWidth: 0.01, // 0 is not working!
pointRadius: 0,
fill: 'start',
lineTension: 0,
spanGaps: false,
hidden: !VIS_TV_CHAN
},{
type: "bar",
label: 'Forbidden Start Marker',
backgroundColor: Chart.helpers.color(FORBIDDEN_COLOR).alpha(1).rgbString(),
borderColor: FORBIDDEN_COLOR,
borderWidth: 0.01,
pointRadius: 0,
lineTension: 0,
spanGaps: false,
barThickness: 2,
hidden: !VIS_FORBIDDEN
}
]
},
options: {
// animation: false,
responsive: true,
legend: {
labels : {
filter: (legendItem, chartData) => {
if ( legendItem.datasetIndex === 0 ||
legendItem.datasetIndex === 4 ||
legendItem.datasetIndex === 6)
return false;
else
return true;
}
},
onClick: legendClick
},
scales: {
xAxes: [{
scaleLabel: {
display: true,
labelString: BAND_LABEL?BAND_LABEL:'Hz'
},
barPercentage: 0.2,
gridLines : {
offsetGridLines: false
},
offset: false
},{
position: "top",
weight: 2,
labels: [],
offset: true,
gridLines: { display: false },
ticks: {
autoSkip: false,
fontColor: '#FF6384'
}
},{
position: "top",
weight: 1,
labels: [],
offset: true,
gridLines: { display: false },
ticks: {
autoSkip: false,
fontColor: '#4BDEC0'
}
},{
position: "top",
weight: 0,
labels: [],
gridLines: { display: false },
ticks: {
autoSkip: false,
fontColor: '#BBBBBB',
maxRotation: 0
}
}],
yAxes: [{
ticks: {
min : global.MIN_DBM,
suggestedMax : global.MAX_DBM
},
scaleLabel: {
display: true,
labelString: 'dBm'
}
}]
}
}
});
}
function openDonateWindow () {
let win = new BrowserWindow ({
webPreferences: {
nodeIntegration: true,
contextIsolation: false
},
width: 650,
height: 650
})
win.setMenuBarVisibility ( false )
win.loadURL("file://" + __dirname + "/donate.html")
//win.webContents.openDevTools()
}
function connectDevice (portIdentifier, shouldScan ) {
if ( shouldScan ) {
portDetectionIndex = 0 // when a port scan is requested, it can be considered that all ports should be checked
scanPorts()
.then ( () => connectPort(portIdentifier) )
.then ( () => scanDevice.getConfiguration() )
.catch( (error) => {
log.error ( "scanPorts(): " + error )
})
} else {
connectPort(portIdentifier)
.then ( () => scanDevice.getConfiguration() )
}
}
function legendClick ( e, legendItem ) {
var index = legendItem.datasetIndex;
var ci = this.chart;
var meta = ci.getDatasetMeta(index);
switch ( index ) {
case LINE_RECOMMENDED: configStore.set('graphVisibility.recommended', legendItem.hidden?true:false ); break;
case LINE_FORBIDDEN : configStore.set('graphVisibility.forbidden' , legendItem.hidden?true:false ); break;
case LINE_CONGESTED : configStore.set('graphVisibility.congested' , legendItem.hidden?true:false ); break;
case LINE_GRIDS : configStore.set('graphVisibility.grids' , legendItem.hidden?true:false ); break;
default:
}
meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null;
if ( index === LINE_FORBIDDEN ) {
let meta_2 = ci.getDatasetMeta ( LINE_FORBIDDEN_MARKERS )
meta_2.hidden = meta_2.hidden === null ? !ci.data.datasets[LINE_FORBIDDEN_MARKERS].hidden : null;
}
ci.update();
}
function setForbidden () {
for ( var f of FREQ_FORBIDDEN ) {
let range_res = isInRange ( f.start*1000, f.stop*1000);
let left_data_point = undefined;
let right_data_point = undefined;
if ( !range_res )
continue;
if ( range_res === "FULL_COVERAGE" ) {
left_data_point = 0;
right_data_point = global.SWEEP_POINTS - 1;
} else {
left_data_point = alignToBoundary ( Math.round ( (f.start * 1000 - global.START_FREQ) / FREQ_STEP ) );
right_data_point = alignToBoundary ( Math.round ( (f.stop * 1000 - global.START_FREQ) / FREQ_STEP ) );
}
let data_point = left_data_point;
myChart.config.options.scales.xAxes[1].labels[left_data_point] = f.info;
if ( f.start * 1000 >= global.START_FREQ ) {
myChart.data.datasets[LINE_FORBIDDEN_MARKERS].data[left_data_point] = global.MIN_DBM;
}
while ( data_point <= right_data_point ) {
myChart.data.datasets[LINE_FORBIDDEN].data[data_point] = global.MAX_DBM;
data_point++;
}
if ( f.stop * 1000 <= global.STOP_FREQ ) {
myChart.data.datasets[LINE_FORBIDDEN_MARKERS].data[right_data_point] = global.MIN_DBM;
}
}
}
function setChannelGrids () {
if ( !FREQ_GRIDS )
return;
let even = true;
let last_data_point = undefined; //avoid overwriting edge values
for ( var f of FREQ_GRIDS ) {
let range_res = isInRange ( f.start*1000, f.stop*1000);
let left_data_point = undefined;
let right_data_point = undefined;
let data_point = undefined;
if ( !range_res )
continue;
if ( range_res === "FULL_COVERAGE" ) {
left_data_point = 0;
right_data_point = global.SWEEP_POINTS - 1;
} else {
left_data_point = alignToBoundary ( Math.round ( (f.start * 1000 - global.START_FREQ) / FREQ_STEP ) );
right_data_point = alignToBoundary ( Math.round ( (f.stop * 1000 - global.START_FREQ) / FREQ_STEP ) );
}
data_point = left_data_point;
if ( f.start * 1000 >= global.START_FREQ )
myChart.config.options.scales.xAxes[3].labels[left_data_point] = '|';
myChart.config.options.scales.xAxes[3].labels[Math.round((left_data_point+right_data_point)/2)] = f.label;
if ( !even ) { // Only draw even (gray) fields. Otherwise overlapping occours. For odd (white fields we simply do nothing)
even = !even;
last_data_point = right_data_point;
continue;
}
while ( data_point <= right_data_point ) {
myChart.data.datasets[LINE_GRIDS].data[data_point] = even?global.MAX_DBM:undefined;
last_data_point = data_point;
data_point++;
}
even = !even;
}
if ( last_data_point < global.SWEEP_POINTS - 1) // Draw last marker
myChart.config.options.scales.xAxes[3].labels[last_data_point] = '|';
}
function setVendorChannels ( presets, bank ) {
if ( !presets )
return;
for ( let i = 0 ; i < global.SWEEP_POINTS ; i++ ) {
myChart.data.datasets[LINE_RECOMMENDED].data[i] = undefined;
myChart.data.datasets[LINE_CONGESTED].data[i] = undefined;
myChart.config.options.scales.xAxes[2].labels[i] = '';
chDispValShadowArr = [];
}
for ( let i = 0 ; i < presets.length ; i++ ) {
let left_freq_edge = presets[i]*1000 - SENNHEISER_CHANNEL_WIDTH/2;
let right_freq_edge = presets[i]*1000 + SENNHEISER_CHANNEL_WIDTH/2;
if ( !isInRange ( left_freq_edge, right_freq_edge) )
continue;
let left_data_point = alignToBoundary ( Math.round ( (left_freq_edge - global.START_FREQ) / FREQ_STEP ) );
let right_data_point = alignToBoundary ( Math.round ( (right_freq_edge - global.START_FREQ) / FREQ_STEP ) );
if ( right_data_point === left_data_point && right_data_point < global.SWEEP_POINTS - 1)
right_data_point++;
chDispValShadowArr.push ([left_data_point, right_data_point, false]); // Last param shows if congested or not
let data_point = left_data_point;
let f = presets[i].toString().split('');
f.splice ( 3, 0, "." );
f = f.join ( '' );
let label_pos = left_data_point + Math.floor((right_data_point - left_data_point )/2);
myChart.config.options.scales.xAxes[2].labels[label_pos] = 'B'+(bank.length===1?'0':'')+bank+'.C'+(i.toString().length===1?'0':'')+(i+1)+' ('+f+')';
while ( data_point <= right_data_point ) {
if ( isForbidden ( left_freq_edge, right_freq_edge ) )
myChart.data.datasets[LINE_CONGESTED ].data[data_point] = global.MAX_DBM;
else
myChart.data.datasets[LINE_RECOMMENDED].data[data_point] = global.MAX_DBM;
data_point++;
}
}
myChart.config.options.scales.xAxes[2].labels[0] = ' ';
myChart.config.options.scales.xAxes[2].labels[global.SWEEP_POINTS-1] = ' ';
}
function isInRange ( start, stop ) {
if ( (start >= global.START_FREQ && start <= global.STOP_FREQ) || (stop >= global.START_FREQ && stop <= global.STOP_FREQ) )
return true;
else if ( (start <= global.START_FREQ && stop >= global.STOP_FREQ) )
return "FULL_COVERAGE";
else
return false;
}
function isForbidden ( start, stop ) {
for ( var f of FREQ_FORBIDDEN ) {
if ( (start >= f.start*1000 && start <= f.stop*1000) || (stop >= f.start*1000 && stop <= f.stop*1000) )
return true;
}
return false;
}
function alignToBoundary ( point ) {
if ( point < 0 )
return 0;
else if ( point > global.SWEEP_POINTS - 1 )
return global.SWEEP_POINTS - 1;
else
return point;
}
function formatFrequencyString ( freq ) { // as Hz
let arr = freq.toString().split ( /(?=(?:...)*$)/ )
return arr.join('.')
}
function updateChart () {
myChart.data.labels = [];
for ( var freq = global.START_FREQ; freq <= global.STOP_FREQ ; freq += FREQ_STEP ) {
myChart.data.labels.push ( formatFrequencyString ( freq ) );
}
// Initialize all values of all graphs (except the scan graph) with lowest dBm value
myChart.data.datasets[LINE_LIVE].data = []; // Live scan
myChart.data.datasets[LINE_RECOMMENDED].data = []; // Recommended
myChart.data.datasets[LINE_FORBIDDEN].data = []; // Forbidden
myChart.data.datasets[LINE_CONGESTED].data = []; // Congested
myChart.data.datasets[LINE_GRIDS].data = []; // Grids
myChart.data.datasets[LINE_FORBIDDEN_MARKERS].data = []; // Forbidden start markers
myChart.data.datasets[LINE_CONGEST_TRESH].data[0] = CONGESTION_LEVEL_DBM;
myChart.data.datasets[LINE_CONGEST_TRESH].data[global.SWEEP_POINTS-1] = CONGESTION_LEVEL_DBM;
for ( let i = 0 ; i < global.SWEEP_POINTS ; i++ ) {
myChart.config.options.scales.xAxes[1].labels[i] = '';
myChart.config.options.scales.xAxes[2].labels[i] = '';
myChart.config.options.scales.xAxes[3].labels[i] = '';
}
setForbidden ();
setChannelGrids ();
if ( FREQ_VENDOR_PRESETS [chPreset_Vendor+'_'+chPreset_Band+'_'+chPreset_Series] && chPreset_Vendor && chPreset_Band && chPreset_Series && chPreset_Preset)
setVendorChannels ( FREQ_VENDOR_PRESETS[chPreset_Vendor+'_'+chPreset_Band+'_'+chPreset_Series][parseInt(chPreset_Preset)-1], chPreset_Preset );
myChart.update();
}
let tryPort = (index) => {
return new Promise ( (resolve, reject) => {
if ( index > globalPorts.length -1 ) {
reject ( 'ERR_PORT_INVALID_INDEX' )
return
}
log.info ( "=========================================================" )
log.info ( `Trying port ${globalPorts[index].path} with baud rate ${baudRate} ...` );
port = new SerialPort ({ path: globalPorts[index].path, baudRate : baudRate }, err => {
if ( err ) {
if ( err.toString().indexOf('Access denied') !== -1 ) { // If access denied error
showPopup (
'error',
'POPUP_CAT_CONNECTION_ISSUE',
"Access denied!",
`Got 'Access denied' on serial port! The application must be restarted!`,
['Restart']
).then ( result => {
popupCategory = ''
if ( result.isConfirmed ) {
restartApp()
}
})
// TODO: Show popup to restart the app in case of: "Error: Opening COM4: File not found"
log.error ( err )
reject ( 'ERR_PORT_ACCESS_DENIED' )
return
}
log.error ( err )
reject ( err )
return
}
log.info( `Successfully connected to ${globalPorts[index].path}!` )
resolve ( 'SUCCESS' )
})
// Create a promise of write() function
port.writePromise = async (data, type ) => {
if ( port.isOpen ) {
port.write (data, type, (err) => {
if (err) {
return Promise.reject(err);
}
return Promise.resolve();
});
} else {
log.error ( `Tried to write the following data to port '${port.settings.path}', but the port is closed: '${data}'`)
showPopup(
'error',
'POPUP_CAT_CONNECTION_ISSUE',
`Port '${port.settings.path}' is closed!`,
`Tried to write data to port '${port.settings.path}', but the port is closed! Please reset the scan device first and then restart th application.`,
['Restart']
).then ( result => {
popupCategory = ''
if ( result.isConfirmed ) {
restartApp()
}
})
}
}
})
}
const portOpenCb = () => {
switch ( global.SCAN_DEVICE ) {
case 'RF_EXPLORER':
scanDevice = new RFExplorer(port);
if ( scanDevice ) {
scanDevice.setHandler(data$)
if ( dataSubscription ) {
dataSubscription.unsubscribe()
}
dataSubscription = data$.subscribe ( data => {
switch ( data[0].type ) {
case 'NAME':
if ( data[0].values.NAME === RFExplorer.NAME ) {
log.info ( `Stoping response check timer #${responseCheckTimer} ...` )
clearTimeout ( responseCheckTimer )
responseCheckTimer = null
log.info ( `Successfully detected '${data[0].values.NAME}' hardware!` )
if ( popupCategory === 'POPUP_CAT_CONNECTION_ISSUE' ) {
popupCategory = ''
Swal.close()
}
ipcRenderer.send('SET_MAIN_WINDOW_TITLE', `${RFExplorer.NAME} on ${globalPorts[portDetectionIndex].path}`)
return
}
break
case 'CONFIG_DATA':
global.START_FREQ = data[0].values.START_FREQ
global.STOP_FREQ = data[0].values.STOP_FREQ
FREQ_STEP = data[0].values.FREQ_STEP
global.SWEEP_POINTS = data[0].values.SWEEP_POINTS
global.MIN_FREQ = data[0].values.MIN_FREQ
global.MAX_FREQ = data[0].values.MAX_FREQ
global.MIN_SPAN = data[0].values.MIN_SPAN
global.MAX_SPAN = data[0].values.MAX_SPAN
configStore.set ( 'start_freq', global.START_FREQ )
configStore.set ( 'stop_freq' , global.STOP_FREQ )
configStore.set ( 'freq_step' , FREQ_STEP )
if ( !RFExplorer.isValidFreqConfig ( data[0].values.START_FREQ, data[0].values.STOP_FREQ ) ) {
log.error ( `Invalid frequency range: ${data[0].values.START_FREQ} - ${data[0].values.STOP_FREQ} Hz!` )
showPopup(
'warning',
'POPUP_CAT_INVALID_FREQUENCY',
"Invalid frequency range!",
`The currently selected frequency range is not valid for device <b>${RFExplorer.NAME}</b>!` +
`<br><br>Allowed range is: ${global.MIN_FREQ} - ${global.MAX_FREQ} Hz` +
`<br><br>Current range is: ${data[0].values.START_FREQ} - ${data[0].values.STOP_FREQ} Hz`,
['Ok']
)
return
}
let band_details = ""
if ( !BAND_DETAILS )
band_details = " | Band: <NO BAND SELECTED>"
else
band_details = " | Band: " + BAND_DETAILS + ""
let country_information = ""
if ( !COUNTRY_CODE || !COUNTRY_NAME)
country_information = " | Country: Germany (DE)"
else
country_information = " | Country: " + COUNTRY_NAME + " (" + COUNTRY_CODE + ")"
const sweep_points = " | Sweep points: " + global.SWEEP_POINTS
let label = "Range: " + formatFrequencyString(global.START_FREQ) + " - " + formatFrequencyString(global.STOP_FREQ) + " Hz | Span: " + formatFrequencyString(global.STOP_FREQ - global.START_FREQ) + " Hz" + country_information + band_details + sweep_points
myChart.options.scales.xAxes[0].scaleLabel.labelString = label
configStore.set ( 'band_label' , label )
BAND_LABEL = label
updateChart ()
break
case 'SCAN_DATA': {
hideWaitIndicator()
let val_changed = false
for ( let i = 0 ; i < data[0].values.length ; i++ ) {
let value = -( data[0].values[i].charCodeAt(0) / 2 )
if ( value < global.MIN_DBM)
value = global.MIN_DBM
if ( value > myChart.data.datasets[LINE_LIVE].data[i] || myChart.data.datasets[LINE_LIVE].data[i] === undefined ) {
myChart.data.datasets[LINE_LIVE].data[i] = value
val_changed = true
let congestedChannel = checkCongestion ( i, value )
if ( congestedChannel ) {
for ( let i = congestedChannel[0] ; i <= congestedChannel[1] ; i++ ) {
myChart.data.datasets[LINE_RECOMMENDED].data[i] = undefined
myChart.data.datasets[LINE_CONGESTED ].data[i] = global.MAX_DBM
}
}
}
}
if ( val_changed ) {
myChart.update()
}
} break
}
})
// In case another timer is running stop it!
if ( responseCheckTimer ) {
log.info ( `Stoping response check timer #${responseCheckTimer} ...` )
clearTimeout ( responseCheckTimer )
responseCheckTimer = null
}
responseCheckTimer = setTimeout ( () => {
log.info ( `Response check timer ${responseCheckTimer} expired!`)
responseCheckTimer = null
log.error ( `No or invalid response from '${RFExplorer.NAME}' on '${globalPorts[portDetectionIndex].path}'!`)
log.error ( `Make sure that no other serial USB device is connected to '${globalPorts[portDetectionIndex].path}!'`)
// If serial port was connected successfully but to a different device type
disconnectPort().then ( async err => {
if (err) {
log.error(err)
return
}
if ( COM_PORT === 'AUTO' ) {
portDetectionIndex++
if ( portDetectionIndex < globalPorts.length ) {
log.info ( `Now trying port with index ${portDetectionIndex}`)
connectDevice ( 'AUTO', false )
} else {
log.info ( `No more ports available!` )
}
if ( portDetectionIndex === globalPorts.length || COM_PORT !== 'AUTO' ) {
// No more ports available
showPopup (
"error",
'POPUP_CAT_CONNECTION_ISSUE',
"No or invalid response from scan device!",
`<b>${RFExplorer.NAME}</b> could not be found or identified properly on any of the available ports!` +
`<br><br>Please choose the correct device type from the menu or connect the chosen device. If the correct` +
` device is already connected, please restart it and then click 'Reconnect'.`,
['Reconnect', 'Cancel']
).then ( result => {
if ( result.isConfirmed ) {
popupCategory = ''
connectDevice ( COM_PORT?COM_PORT:'AUTO', true )
}
})
}
}
})
}, SERIAL_RESPONSE_TIMEOUT)
log.info ( `Started response check timer ${responseCheckTimer}` )
} else {
log.error ("Unable to instantiate class RFExplorer!")
}
break;
case 'TINY_SA':
scanDevice = new TinySA(port, data$);
if ( scanDevice ) {
scanDevice.setHandler()
if ( dataSubscription ) {
dataSubscription.unsubscribe()
}
dataSubscription = data$.subscribe ( data => {
switch ( data[0].type ) {
case 'NAME':
if ( data[0].values.NAME === TinySA.NAME ) {
log.info ( `Stoping response check timer #${responseCheckTimer} ...` )
clearTimeout ( responseCheckTimer )
responseCheckTimer = null
log.info ( `Successfully detected '${data[0].values.NAME}${TinySA.MODEL==="ULTRA"?" Ultra":""}' hardware!` )
if ( popupCategory === 'POPUP_CAT_CONNECTION_ISSUE' ) {
popupCategory = ''
Swal.close()
}
ipcRenderer.send('SET_MAIN_WINDOW_TITLE', `${TinySA.NAME} on ${globalPorts[portDetectionIndex].path}`)
return
}
break
case 'CONFIG_DATA':
global.START_FREQ = data[0].values.START_FREQ
global.STOP_FREQ = data[0].values.STOP_FREQ
FREQ_STEP = data[0].values.FREQ_STEP
global.MIN_FREQ = data[0].values.MIN_FREQ
global.MAX_FREQ = data[0].values.MAX_FREQ
global.MIN_SPAN = data[0].values.MIN_SPAN
global.MAX_SPAN = data[0].values.MAX_SPAN
configStore.set ( 'start_freq', global.START_FREQ )
configStore.set ( 'stop_freq' , global.STOP_FREQ )
configStore.set ( 'freq_step' , FREQ_STEP )
if ( !TinySA.isValidFreqConfig ( data[0].values.START_FREQ, data[0].values.STOP_FREQ ) ) {
log.error ( `Invalid frequency range: ${data[0].values.START_FREQ} - ${data[0].values.STOP_FREQ} Hz!` )
showPopup(
'warning',
'POPUP_CAT_INVALID_FREQUENCY',
"Invalid frequency range!",
`The currently selected frequency range is not valid for device <b>${TinySA.NAME}${TinySA.MODEL==="ULTRA"?" Ultra":""}</b>!` +
`<br><br>Allowed range is: ${global.MIN_FREQ} - ${global.MAX_FREQ} Hz` +
`<br><br>Current range is: ${data[0].values.START_FREQ} - ${data[0].values.STOP_FREQ} Hz`,
['Ok']
)
return
}
const range = "Range: " + formatFrequencyString(global.START_FREQ) + " - " + formatFrequencyString(global.STOP_FREQ) + " Hz"
const span = " | Span: " + formatFrequencyString(global.STOP_FREQ - global.START_FREQ) + " Hz"
let country = ''
if ( !COUNTRY_CODE || !COUNTRY_NAME) {
country = " | Country: Germany (DE)"
} else {
country = " | Country: " + COUNTRY_NAME + " (" + COUNTRY_CODE + ")"
}
let band = ''
if ( !BAND_DETAILS ) {
band = " | Band: <NO BAND SELECTED>"
} else {
band = " | Band: " + BAND_DETAILS + ""
}
const sweep_points = " | Sweep points: " + global.SWEEP_POINTS
const label = range + span + country + band + sweep_points
myChart.options.scales.xAxes[0].scaleLabel.labelString = label
configStore.set ( 'band_label' , label )
BAND_LABEL = label
updateChart ()
break
case 'SCAN_DATA': {
hideWaitIndicator()
let val_changed = false
for ( let i = 0 ; i < data[0].values.length ; i++ ) {
let value = -data[0].values[i]
if ( value < global.MIN_DBM)
value = global.MIN_DBM
if ( value > myChart.data.datasets[LINE_LIVE].data[i] || myChart.data.datasets[LINE_LIVE].data[i] === undefined ) {
myChart.data.datasets[LINE_LIVE].data[i] = value
val_changed = true
let congestedChannel = checkCongestion ( i, value )