-
Notifications
You must be signed in to change notification settings - Fork 7
/
uiIndex.js
1725 lines (1014 loc) · 50.4 KB
/
uiIndex.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
/****************************************************************************
* uiIndex.js
* openacousticdevices.info
* November 2019
*****************************************************************************/
'use strict';
/* global document */
const {ipcRenderer} = require('electron');
const audiomoth = require('audiomoth-hid');
const packetReader = require('./packetReader.js');
const util = require('util');
const electron = require('electron');
const {dialog, Menu, clipboard, BrowserWindow} = require('@electron/remote');
const ui = require('./ui.js');
const schedule = require('./schedule/schedule.js');
const scheduleBar = require('./scheduleBar.js');
const saveLoad = require('./saveLoad.js');
const timeHandler = require('./timeHandler.js');
const lifeDisplay = require('./lifeDisplay.js');
const constants = require('./constants.js');
const uiSchedule = require('./schedule/uiSchedule.js');
const uiSettings = require('./settings/uiSettings.js');
const uiSun = require('./schedule/uiSun.js');
const versionChecker = require('./versionChecker.js');
const THRESHOLD_SCALE_PERCENTAGE = 0;
const THRESHOLD_SCALE_16BIT = 1;
const THRESHOLD_SCALE_DECIBEL = 2;
/* UI components */
const applicationMenu = Menu.getApplicationMenu();
const idDisplay = document.getElementById('id-display');
const idLabel = document.getElementById('id-label');
const firmwareVersionDisplay = document.getElementById('firmware-version-display');
const firmwareVersionLabel = document.getElementById('firmware-version-label');
const firmwareDescriptionDisplay = document.getElementById('firmware-description-display');
const firmwareDescriptionLabel = document.getElementById('firmware-description-label');
const batteryDisplay = document.getElementById('battery-display');
const batteryLabel = document.getElementById('battery-label');
const ledCheckbox = document.getElementById('led-checkbox');
const batteryLevelCheckbox = document.getElementById('battery-level-checkbox');
const firstRecordingDateCheckbox = document.getElementById('first-date-checkbox');
const configureButton = document.getElementById('configure-button');
/* Store version number for packet size checks and description for compatibility check */
let firmwareVersion = '0.0.0';
let firmwareDescription = '-';
/* If the ID of the current device differs from the previous one, then warning messages can be reset */
let previousID = '';
/* Indicate whether the firmware should be updated */
let updateRecommended = false;
/* Whether or not a warning about the version number has been displayed for this device */
let versionWarningShown = false;
/* Whether or not a warning about the firmware has been displayed for this device */
let firmwareWarningShown = false;
/* Whether or not communication with device is currently happening */
let communicating = false;
/* Communication constants */
const MAXIMUM_RETRIES = 10;
const DEFAULT_RETRY_INTERVAL = 100;
/* Used for checking clock speed */
const MAXIMUM_SECONDS_DRIFT_IN_ONE_DAY = 600;
const MINIMUM_ALLOWABLE_AUDIOMOTH_TIME_ERROR = 4;
let displayedClockError = false;
let connectionComputerTime = null;
let connectionAudioMothTime = null;
let sendingConfigurationPacket = false;
/* Utility functions */
async function callWithRetry (funcSync, argument, milliseconds, repeats) {
let result;
let attempt = 0;
while (attempt < repeats) {
try {
if (argument) {
result = await funcSync(argument);
} else {
result = await funcSync();
}
break;
} catch (e) {
const interval = milliseconds / 2 + milliseconds / 2 * Math.random();
await delay(interval);
attempt += 1;
}
}
if (result === undefined) throw ('Error: Repeated attempts to access the device failed.');
if (result === null) throw ('No device detected');
return result;
}
async function delay (milliseconds) {
return new Promise(resolve => setTimeout(resolve, milliseconds));
}
/* Promisified versions of AudioMoth-HID calls */
const getFirmwareDescription = util.promisify(audiomoth.getFirmwareDescription);
const getFirmwareVersion = util.promisify(audiomoth.getFirmwareVersion);
const getBatteryState = util.promisify(audiomoth.getBatteryState);
const getID = util.promisify(audiomoth.getID);
const getTime = util.promisify(audiomoth.getTime);
const setPacket = util.promisify(audiomoth.setPacket);
/* Device interaction functions */
async function getAudioMothPacket () {
try {
/* Read from AudioMoth */
const date = await callWithRetry(getTime, null, DEFAULT_RETRY_INTERVAL, MAXIMUM_RETRIES);
const nowComputerTime = new Date();
const nowAudioMothTime = date;
if ((connectionComputerTime === null || connectionAudioMothTime === null) && sendingConfigurationPacket === false) {
connectionComputerTime = nowComputerTime;
connectionAudioMothTime = date;
}
const id = await callWithRetry(getID, null, DEFAULT_RETRY_INTERVAL, MAXIMUM_RETRIES);
const description = await callWithRetry(getFirmwareDescription, null, DEFAULT_RETRY_INTERVAL, MAXIMUM_RETRIES);
const versionArr = await callWithRetry(getFirmwareVersion, null, DEFAULT_RETRY_INTERVAL, MAXIMUM_RETRIES);
const batteryState = await callWithRetry(getBatteryState, null, DEFAULT_RETRY_INTERVAL, MAXIMUM_RETRIES);
/* Compare current date/time object with previous time to make sure clock isn't running too slow/fast */
if (connectionComputerTime !== null && connectionAudioMothTime !== null && communicating === false && displayedClockError === false) {
const computerTimeDiff = nowComputerTime - connectionComputerTime;
const audioMothTimeDiff = nowAudioMothTime - connectionAudioMothTime;
const maximumAllowableDrift = Math.floor(MAXIMUM_SECONDS_DRIFT_IN_ONE_DAY * computerTimeDiff / constants.MILLISECONDS_IN_SECOND / constants.SECONDS_IN_DAY);
const measuredAudioMothDrift = Math.round((computerTimeDiff - audioMothTimeDiff) / constants.MILLISECONDS_IN_SECOND);
if (Math.abs(measuredAudioMothDrift) > MINIMUM_ALLOWABLE_AUDIOMOTH_TIME_ERROR && Math.abs(measuredAudioMothDrift) > maximumAllowableDrift) {
const direction = measuredAudioMothDrift < 0 ? 'fast' : 'slow';
dialog.showMessageBoxSync(BrowserWindow.getFocusedWindow(), {
type: 'warning',
title: 'Device clock too ' + direction,
message: 'The clock on the connected AudioMoth seems to be running ' + direction + '. Compare the time displayed in the Configuration App to your computer clock to check that your AudioMoth is keeping correct time.'
});
displayedClockError = true;
}
}
/* No exceptions have occurred so update display */
if (id !== previousID) {
firmwareWarningShown = false;
versionWarningShown = false;
previousID = id;
}
firmwareVersion = versionArr[0] + '.' + versionArr[1] + '.' + versionArr[2];
firmwareDescription = description;
const supported = checkVersionCompatibility();
if (communicating === false) {
ui.updateDate(date);
ui.showTime();
enableDisplay();
}
if (supported === false) configureButton.disabled = true;
updateIdDisplay(id);
updateFirmwareDisplay(firmwareVersion, firmwareDescription);
updateBatteryDisplay(batteryState);
} catch (e) {
/* Problem reading from AudioMoth or no AudioMoth */
disableDisplay();
displayedClockError = false;
connectionComputerTime = null;
connectionAudioMothTime = null;
}
/* Schedule the next call */
const milliseconds = Date.now() % constants.MILLISECONDS_IN_SECOND;
let delay = constants.MILLISECONDS_IN_SECOND / 2 - milliseconds;
if (delay < 0) delay += constants.MILLISECONDS_IN_SECOND;
setTimeout(getAudioMothPacket, delay);
}
function getEquivalentVersion (desc) {
const foundEquivalence = desc.match(constants.EQUIVALENCE_REGEX)[0];
const regex1 = /[0-9]+/g;
const equivalentVersionStrArray = foundEquivalence.match(regex1);
const equivalentVersionArray = [parseInt(equivalentVersionStrArray[0]), parseInt(equivalentVersionStrArray[1]), parseInt(equivalentVersionStrArray[2])];
return equivalentVersionArray;
}
/* Check the version and description to see if the firmware is compatible or equivalent to an equivalent version of firmware */
function checkVersionCompatibility () {
/* This version array may be replaced if the firmware is custom with an equivalent official version */
let trueVersionArr = firmwareVersion.split('.');
const classification = constants.getFirmwareClassification(firmwareDescription);
let versionWarningText, versionWarningTitle;
switch (classification) {
case constants.FIRMWARE_OFFICIAL_RELEASE:
case constants.FIRMWARE_OFFICIAL_RELEASE_CANDIDATE:
versionWarningTitle = 'Firmware update recommended';
versionWarningText = 'Update to at least version ' + constants.LATEST_FIRMWARE_VERSION_STRING + ' of AudioMoth-Firmware-Basic firmware to use all the features of this version of the AudioMoth Configuration App.';
break;
case constants.FIRMWARE_CUSTOM_EQUIVALENT:
trueVersionArr = getEquivalentVersion(firmwareDescription);
versionWarningTitle = 'Unsupported features';
versionWarningText = 'The firmware installed on your AudioMoth does not allow you to use all the features of this version of the AudioMoth Configuration App.';
break;
case constants.FIRMWARE_UNSUPPORTED:
updateRecommended = false;
if (firmwareWarningShown === false) {
firmwareWarningShown = true;
setTimeout(() => {
dialog.showMessageBoxSync(BrowserWindow.getFocusedWindow(), {
type: 'warning',
title: 'Unsupported firmware',
message: 'The firmware installed on your AudioMoth is not supported by the AudioMoth Configuration App.'
});
}, 100);
}
return false;
}
/* If OFFICIAL_RELEASE, OFFICIAL_RELEASE_CANDIDATE or CUSTOM_EQUIVALENT */
if (constants.isOlderSemanticVersion(trueVersionArr, constants.LATEST_FIRMWARE_VERSION_MAJOR, constants.LATEST_FIRMWARE_VERSION_MINOR, constants.LATEST_FIRMWARE_VERSION_PATCH)) {
if (classification === constants.FIRMWARE_OFFICIAL_RELEASE || classification === constants.FIRMWARE_OFFICIAL_RELEASE_CANDIDATE) updateRecommended = true;
if (versionWarningShown === false) {
versionWarningShown = true;
setTimeout(() => {
dialog.showMessageBoxSync(BrowserWindow.getFocusedWindow(), {
type: 'warning',
title: versionWarningTitle,
message: versionWarningText
});
}, 100);
}
} else {
updateRecommended = false;
}
return true;
}
/* Write bytes into a buffer for transmission */
function writeLittleEndianBytes (buffer, start, byteCount, value) {
for (let i = 0; i < byteCount; i++) {
buffer[start + i] = (value >> (i * 8)) & 255;
}
}
function getTrueFirmwareVersion () {
let trueFirmwareVersion = firmwareVersion.split('.');
/* Check for equivalent if using custom firmware */
const classification = constants.getFirmwareClassification(firmwareDescription);
if (classification === constants.FIRMWARE_CUSTOM_EQUIVALENT) {
trueFirmwareVersion = getEquivalentVersion(firmwareDescription);
console.log('Treating firmware as equivalent version: ' + trueFirmwareVersion[0] + '.' + trueFirmwareVersion[1] + '.' + trueFirmwareVersion[2]);
}
/* Use latest version if custom */
if (classification === constants.FIRMWARE_UNSUPPORTED) {
trueFirmwareVersion = constants.LATEST_FIRMWARE_VERSION_ARRAY;
console.log('Unsupported firmware, treating firmware as latest version');
}
return trueFirmwareVersion;
}
/* Send configuration packet to AudioMoth */
async function sendAudioMothPacket (packet) {
const showError = () => {
dialog.showMessageBox(BrowserWindow.getFocusedWindow(), {
type: 'error',
title: 'Configuration failed',
message: 'The connected AudioMoth did not respond correctly and the configuration may not have been applied. Please try again.'
});
configureButton.classList.remove('grey');
};
try {
const data = await callWithRetry(setPacket, packet, DEFAULT_RETRY_INTERVAL, MAXIMUM_RETRIES);
/* Check if the firmware version of the device being configured has a known packet length */
/* If not, the length of the packet sent/received is used */
let packetLength = Math.min(packet.length, data.length - 1);
const trueFirmwareVersion = getTrueFirmwareVersion();
for (let k = 0; k < constants.PACKET_LENGTH_VERSIONS.length; k++) {
const possibleFirmwareVersion = constants.PACKET_LENGTH_VERSIONS[k].firmwareVersion;
if (constants.isOlderSemanticVersion(trueFirmwareVersion, possibleFirmwareVersion[0], possibleFirmwareVersion[1], possibleFirmwareVersion[2])) {
break;
}
packetLength = constants.PACKET_LENGTH_VERSIONS[k].packetLength;
}
console.log('Using packet length', packetLength);
/* Verify the packet sent was read correctly by the device by comparing it to the returned packet */
let matches = true;
for (let j = 0; j < packetLength; j++) {
if (packet[j] !== data[j + 1]) {
console.log('(' + j + ') ' + packet[j] + ' - ' + data[j + 1]);
matches = false;
break;
}
}
if (matches === false) throw ('Packet does not match');
} catch (e) {
showError();
}
}
/**
* Fit 4 ten bit values into a 5 byte area of a bvffer
* @param {buffer} buffer Buffer data is to be written to
* @param {integer} start Where in the buffer to start writing
* @param {integer} value1 First value
* @param {integer} value2 Second value
* @param {integer} value3 Third value
* @param {integer} value4 Fourth value
*/
function writeFourTenBitValuesAsFiveBytes (buffer, start, value1, value2, value3, value4) {
buffer[start] = value1 & 0b0011111111;
buffer[start + 1] = ((value1 & 0b1100000000) >> 8) | ((value2 & 0b0000111111) << 2);
buffer[start + 2] = ((value2 & 0b1111000000) >> 6) | ((value3 & 0b0000001111) << 4);
buffer[start + 3] = ((value3 & 0b1111110000) >> 4) | ((value4 & 0b0000000011) << 6);
buffer[start + 4] = (value4 & 0b1111111100) >> 2;
}
function configureDevice () {
const USB_LAG = 20;
const MINIMUM_DELAY = 100;
console.log('Configuring device');
const settings = getCurrentConfiguration();
/* Build configuration packet */
let index = 0;
/* Packet length is only increased with updates, so take the size of the latest firmware version packet */
const maxPacketLength = constants.PACKET_LENGTH_VERSIONS.slice(-1)[0].packetLength;
const packet = new Uint8Array(maxPacketLength);
/* Increment to next second transition */
const sendTime = new Date();
let delay = constants.MILLISECONDS_IN_SECOND - sendTime.getMilliseconds() - USB_LAG;
if (delay < MINIMUM_DELAY) delay += constants.MILLISECONDS_IN_SECOND;
sendTime.setMilliseconds(sendTime.getMilliseconds() + delay);
/* Make the data packet */
writeLittleEndianBytes(packet, index, 4, Math.round(sendTime.valueOf() / 1000));
index += 4;
packet[index++] = settings.gain;
/* If equivalent firmware or unsupported firmware is present, use correct firmware version */
const trueFirmwareVersion = getTrueFirmwareVersion();
const configurations = (constants.isOlderSemanticVersion(trueFirmwareVersion, 1, 4, 4) && settings.sampleRateIndex < 3) ? constants.OLD_CONFIGURATIONS : constants.CONFIGURATIONS;
const sampleRateConfiguration = configurations[settings.sampleRateIndex];
packet[index++] = sampleRateConfiguration.clockDivider;
packet[index++] = sampleRateConfiguration.acquisitionCycles;
packet[index++] = sampleRateConfiguration.oversampleRate;
writeLittleEndianBytes(packet, index, 4, sampleRateConfiguration.sampleRate);
index += 4;
packet[index++] = sampleRateConfiguration.sampleRateDivider;
writeLittleEndianBytes(packet, index, 2, settings.sleepDuration);
index += 2;
writeLittleEndianBytes(packet, index, 2, settings.recordDuration);
index += 2;
packet[index++] = ledCheckbox.checked ? 1 : 0;
if (settings.sunScheduleEnabled) {
let packedValue3 = settings.sunMode & 0b111;
packedValue3 |= (settings.sunDefinition & 0b11) << 3;
packet[index++] = packedValue3;
let latitude = settings.latitude.degrees * 100 + settings.latitude.hundredths;
latitude *= settings.latitude.positiveDirection ? 1 : -1;
writeLittleEndianBytes(packet, index, 2, latitude);
index += 2;
let longitude = settings.longitude.degrees * 100 + settings.longitude.hundredths;
longitude *= settings.longitude.positiveDirection ? 1 : -1;
writeLittleEndianBytes(packet, index, 2, longitude);
index += 2;
packet[index++] = settings.sunRounding;
const sunPeriods = settings.sunPeriods;
writeFourTenBitValuesAsFiveBytes(packet, index, sunPeriods.sunriseBefore, sunPeriods.sunriseAfter, sunPeriods.sunsetBefore, sunPeriods.sunsetAfter);
index += 5;
/* Pad rest of block as normal schedule is 10 bytes longer than sunrise/sunset settings */
index += 10;
} else {
let timePeriods;
if (constants.isOlderSemanticVersion(trueFirmwareVersion, 1, 9, 0)) {
/* If AudioMoth is using a firmware version older than 1.9.0, split any periods which wrap around */
timePeriods = JSON.parse(JSON.stringify(schedule.getTimePeriodsNoWrap()));
} else {
timePeriods = JSON.parse(JSON.stringify(schedule.getTimePeriods()));
}
timePeriods = timeHandler.sortPeriods(timePeriods);
packet[index++] = timePeriods.length;
for (let i = 0; i < timePeriods.length; i++) {
writeLittleEndianBytes(packet, index, 2, timePeriods[i].startMins);
index += 2;
const endMins = timePeriods[i].endMins === 0 ? constants.MINUTES_IN_DAY : timePeriods[i].endMins;
writeLittleEndianBytes(packet, index, 2, endMins);
index += 2;
}
for (let i = 0; i < (constants.MAX_PERIODS + 1) - timePeriods.length; i++) {
writeLittleEndianBytes(packet, index, 2, 0);
index += 2;
writeLittleEndianBytes(packet, index, 2, 0);
index += 2;
}
}
const timeZoneOffset = timeHandler.getTimeZoneOffset();
const offsetHours = timeZoneOffset < 0 ? Math.ceil(timeZoneOffset / constants.MINUTES_IN_HOUR) : Math.floor(timeZoneOffset / constants.MINUTES_IN_HOUR);
const offsetMins = timeZoneOffset % constants.MINUTES_IN_HOUR;
packet[index++] = offsetHours;
/* Low voltage cutoff is always enabled */
packet[index++] = 1;
packet[index++] = batteryLevelCheckbox.checked ? 0 : 1;
/* For non-integer timeZones */
packet[index++] = offsetMins;
/* Duty cycle disabled (default value = 0) and filename with device ID */
/* Duty cycle setting is inverted because setting on device is "duty cycle disabled" but having a negative checkbox would make the UI confusing */
let packedValue4 = !settings.dutyEnabled ? 1 : 0;
if (constants.isNewerOrEqualSemanticVersion(trueFirmwareVersion, 1, 11, 0)) {
packedValue4 |= settings.filenameWithDeviceIDEnabled ? (1 << 1) : 0;
if (settings.timeSettingFromGPSEnabled) {
packedValue4 |= settings.acquireGpsFixBeforeAfter === 'individual' ? (1 << 2) : 0;
packedValue4 |= (settings.gpsFixTime & 0b1111) << 3;
}
}
packet[index++] = packedValue4;
/* Start/stop dates */
const firstRecordingDateEnabled = uiSchedule.isFirstRecordingDateEnabled();
let earliestRecordingTime = 0;
if (firstRecordingDateEnabled) {
const dateComponents = ui.extractDateComponents(uiSchedule.getFirstRecordingDate());
const firstRecordingTimestamp = Date.UTC(dateComponents.year, dateComponents.month - 1, dateComponents.day, 0, 0, 0, 0).valueOf() / 1000;
const firstRecordingOffsetTimestamp = firstRecordingTimestamp - timeZoneOffset * constants.SECONDS_IN_MINUTE;
earliestRecordingTime = firstRecordingOffsetTimestamp;
}
const lastRecordingDateEnabled = uiSchedule.isLastRecordingDateEnabled();
let latestRecordingTime = 0;
if (lastRecordingDateEnabled) {
const dateComponents = ui.extractDateComponents(uiSchedule.getLastRecordingDate());
const lastRecordingTimestamp = Date.UTC(dateComponents.year, dateComponents.month - 1, dateComponents.day, 0, 0, 0, 0).valueOf() / 1000;
const lastRecordingOffsetTimestamp = lastRecordingTimestamp + constants.SECONDS_IN_DAY - timeZoneOffset * constants.SECONDS_IN_MINUTE;
latestRecordingTime = lastRecordingOffsetTimestamp;
}
/* Check ranges of values before sending */
earliestRecordingTime = Math.min(constants.UINT32_MAX, earliestRecordingTime);
latestRecordingTime = Math.min(constants.UINT32_MAX, latestRecordingTime);
writeLittleEndianBytes(packet, index, 4, earliestRecordingTime);
index += 4;
writeLittleEndianBytes(packet, index, 4, latestRecordingTime);
index += 4;
let lowerFilter, higherFilter;
/* Filter settings */
if (settings.passFiltersEnabled && !settings.frequencyTriggerEnabled) {
switch (settings.filterType) {
case 'low':
/* Low-pass */
lowerFilter = constants.UINT16_MAX;
higherFilter = settings.higherFilter / 100;
break;
case 'band':
/* Band-pass */
lowerFilter = settings.lowerFilter / 100;
higherFilter = settings.higherFilter / 100;
break;
case 'high':
/* High-pass */
lowerFilter = settings.lowerFilter / 100;
higherFilter = constants.UINT16_MAX;
break;
case 'none':
lowerFilter = 0;
higherFilter = 0;
}
} else {
lowerFilter = 0;
higherFilter = 0;
}
writeLittleEndianBytes(packet, index, 2, lowerFilter);
index += 2;
writeLittleEndianBytes(packet, index, 2, higherFilter);
index += 2;
/* Amplitude threshold or Goertzel filter frequency can be in this packet index */
let thresholdUnionValue;
const amplitudeThresholdScaleIndex = settings.amplitudeThresholdScaleIndex;
if (settings.amplitudeThresholdingEnabled) {
let amplitudeThreshold, percentageAmplitudeThreshold;
/* Amplitude threshold value is based on the value displayed to the user, rather than the raw position on the slider */
/* E.g. 10% selected, threshold = 10% of the max amplitude */
switch (amplitudeThresholdScaleIndex) {
case THRESHOLD_SCALE_16BIT:
amplitudeThreshold = uiSettings.get16BitAmplitudeThreshold();
break;
case THRESHOLD_SCALE_PERCENTAGE:
percentageAmplitudeThreshold = uiSettings.getPercentageAmplitudeThresholdExponentMantissa();
amplitudeThreshold = Math.round(32768 * percentageAmplitudeThreshold.mantissa * Math.pow(10, percentageAmplitudeThreshold.exponent) / 100);
break;
case THRESHOLD_SCALE_DECIBEL:
amplitudeThreshold = Math.round(32768 * Math.pow(10, uiSettings.getDecibelAmplitudeThreshold() / 20));
break;
}
thresholdUnionValue = amplitudeThreshold;
} else if (settings.frequencyTriggerEnabled && constants.isNewerOrEqualSemanticVersion(trueFirmwareVersion, 1, 8, 0)) {
thresholdUnionValue = settings.frequencyTriggerCentreFrequency / 100;
} else {
/* If firmware is older than 1.8.0, then frequency thresholding isn't supported, so just send zero */
thresholdUnionValue = 0;
}
writeLittleEndianBytes(packet, index, 2, thresholdUnionValue);
index += 2;
/* Minimum threshold duration, voltage range and whether acoustic configuration is required before deployment */
let minimumThresholdDuration;
const minimumThresholdDurations = [0, 1, 2, 5, 10, 15, 30, 60];
if (settings.amplitudeThresholdingEnabled) {
minimumThresholdDuration = minimumThresholdDurations[settings.minimumAmplitudeThresholdDuration];
} else if (settings.frequencyTriggerEnabled && constants.isNewerOrEqualSemanticVersion(trueFirmwareVersion, 1, 8, 0)) {
minimumThresholdDuration = minimumThresholdDurations[settings.minimumFrequencyTriggerDuration];
} else {
minimumThresholdDuration = 0;
}
let packedValue0 = settings.requireAcousticConfig ? 1 : 0;
packedValue0 |= settings.displayVoltageRange ? (1 << 1) : 0;
packedValue0 |= (minimumThresholdDuration & 0b111111) << 2;
packet[index++] = packedValue0;
if (settings.amplitudeThresholdingEnabled) {
let enableAmplitudeThresholdDecibelScale = 0;
let enableAmplitudeThresholdPercentageScale = 0;
switch (amplitudeThresholdScaleIndex) {
case THRESHOLD_SCALE_16BIT:
enableAmplitudeThresholdDecibelScale = 1;
enableAmplitudeThresholdPercentageScale = 1;
break;
case THRESHOLD_SCALE_PERCENTAGE:
enableAmplitudeThresholdDecibelScale = 0;
enableAmplitudeThresholdPercentageScale = 1;
break;
case THRESHOLD_SCALE_DECIBEL:
enableAmplitudeThresholdDecibelScale = 1;
enableAmplitudeThresholdPercentageScale = 0;
break;
}
/* Decibel-scale amplitude threshold */
const amplitudeThresholdDecibels = (amplitudeThresholdScaleIndex === THRESHOLD_SCALE_DECIBEL) ? Math.abs(uiSettings.getDecibelAmplitudeThreshold()) : 0;
let packedValue1 = enableAmplitudeThresholdDecibelScale & 0b1;
packedValue1 |= (amplitudeThresholdDecibels & 0b1111111) << 1;
packet[index++] = packedValue1;
/* Percentage-scale amplitude threshold */
let amplitudeThresholdPercentageExponent, amplitudeThresholdPercentageMantissa;
if (amplitudeThresholdScaleIndex === THRESHOLD_SCALE_PERCENTAGE) {
const percentageAmplitudeThreshold = uiSettings.getPercentageAmplitudeThresholdExponentMantissa();
amplitudeThresholdPercentageExponent = percentageAmplitudeThreshold.exponent;
amplitudeThresholdPercentageMantissa = percentageAmplitudeThreshold.mantissa;
} else {
amplitudeThresholdPercentageExponent = 0;
amplitudeThresholdPercentageMantissa = 0;
}
let packedValue2 = enableAmplitudeThresholdPercentageScale & 0b1;
packedValue2 |= (amplitudeThresholdPercentageMantissa & 0b1111) << 1;
packedValue2 |= (amplitudeThresholdPercentageExponent & 0b111) << 5;
packet[index++] = packedValue2;
} else if (settings.frequencyTriggerEnabled && constants.isNewerOrEqualSemanticVersion(trueFirmwareVersion, 1, 8, 0)) {
const frequencyTriggerWindowLength = Math.log2(settings.frequencyTriggerWindowLength);
const frequencyTriggerThreshold = uiSettings.getFrequencyFilterThresholdExponentMantissa();
let packedValue1 = frequencyTriggerWindowLength & 0b1111;
packedValue1 |= (frequencyTriggerThreshold.mantissa & 0b1111) << 4;
packet[index++] = packedValue1;
const packedValue2 = frequencyTriggerThreshold.exponent & 0b111;
packet[index++] = packedValue2;
} else {
/* If firmware is older than 1.8.0, then frequency thresholding isn't supported, so just send zeroes */
packet[index++] = 0;
packet[index++] = 0;
}
/* Whether to use NiMH/LiPo voltage range for battery level indication */
let packedByte3 = settings.energySaverModeEnabled ? 1 : 0;
/* Whether to turn off the 48Hz DC blocking filter which is on by default */
packedByte3 |= settings.disable48DCFilter ? (1 << 1) : 0;
/* Whether to allow the time to be updated via GPS */
packedByte3 |= settings.timeSettingFromGPSEnabled ? (1 << 2) : 0;
/* Whether to check the magnetic switch to start a delayed schedule */
packedByte3 |= settings.magneticSwitchEnabled ? (1 << 3) : 0;
/* Whether to enable the low gain range */
packedByte3 |= settings.lowGainRangeEnabled ? (1 << 4) : 0;
/* Whether to enable the Goertzel frequency filter */
packedByte3 |= settings.enableFrequencyFilter ? (1 << 5) : 0;
/* Whether to create a new folder each day to store files */
packedByte3 |= settings.dailyFolders ? (1 << 6) : 0;
/* Whether to enable sunrise/sunset scheduling */
packedByte3 |= settings.sunScheduleEnabled ? (1 << 7) : 0;
packet[index++] = packedByte3;
console.log('Packet length: ', index);
/* Send packet to device */
console.log('Sending packet:');
console.log(packet);
packetReader.read(packet);
const now = new Date();
const sendTimeDiff = sendTime.getTime() - now.getTime();
/* Calculate when to re-enable time display */
communicating = true;
ui.disableTimeDisplay();
sendingConfigurationPacket = true;
configureButton.disabled = true;
connectionAudioMothTime = null;
connectionComputerTime = null;
displayedClockError = false;
const updateDelay = sendTimeDiff <= 0 ? constants.MILLISECONDS_IN_SECOND : sendTimeDiff;
setTimeout(() => {
communicating = false;
}, updateDelay);