-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathuiIndex.js
821 lines (447 loc) · 19.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
/****************************************************************************
* uiIndex.js
* openacousticdevices.info
* August 2021
*****************************************************************************/
'use strict';
/* global document */
const audiomoth = require('audiomoth-hid');
const packetReader = require('./packetReader.js');
const util = require('util');
const electron = require('electron');
const { dialog, Menu, BrowserWindow, clipboard } = require('@electron/remote');
const ui = require('./ui.js');
const constants = require('./constants.js');
const uiSettings = require('./settings/uiSettings.js');
const versionChecker = require('./versionChecker.js');
const UINT16_MAX = 0xFFFF;
const MILLISECONDS_IN_SECOND = 1000;
/* 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 samplerateDisplay = document.getElementById('samplerate-display');
const samplerateLabel = document.getElementById('samplerate-label');
const gainDisplay = document.getElementById('gain-display');
const gainLabel = document.getElementById('gain-label');
const filterSettingDisplay = document.getElementById('filter-setting-display');
const filterSettingLabel = document.getElementById('filter-setting-label');
const additionalDisplay = document.getElementById('additional-display');
const additionalLabel = document.getElementById('additional-label');
const configureButton = document.getElementById('configure-button');
const packetLabels = [samplerateLabel, gainLabel, filterSettingLabel, additionalLabel];
const packetDisplays = [samplerateDisplay, gainDisplay, filterSettingDisplay, additionalDisplay];
const firmwareLabels = [firmwareVersionLabel, firmwareDescriptionLabel, idLabel];
const firmwareDisplays = [firmwareVersionDisplay, firmwareDescriptionDisplay, idDisplay];
/* Store version number for packet size checks and description for compatibility check */
var firmwareVersion = '0.0.0';
var 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;
/* Compare two semantic versions and return true if older */
function isOlderSemanticVersion (aVersion, bVersion) {
for (let i = 0; i < aVersion.length; i++) {
const aVersionNum = parseInt(aVersion[i]);
const bVersionNum = parseInt(bVersion[i]);
if (aVersionNum > bVersionNum) {
return false;
} else if (aVersionNum < bVersionNum) {
return true;
}
}
return 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 getPacket = util.promisify(audiomoth.getPacket);
const setPacket = util.promisify(audiomoth.setPacket);
const getID = util.promisify(audiomoth.getID);
/* Device interaction functions */
async function getAudioMothPacket () {
try {
/* Read from AudioMoth */
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 packet = await callWithRetry(getPacket, null, DEFAULT_RETRY_INTERVAL, MAXIMUM_RETRIES);
/* No exceptions have occurred so update display */
if (id !== previousID) {
firmwareWarningShown = false;
versionWarningShown = false;
previousID = id;
}
firmwareDescription = description;
firmwareVersion = versionArr[0] + '.' + versionArr[1] + '.' + versionArr[2];
const supported = checkVersionCompatibility();
updateIdDisplay(id);
updateFirmwareDisplay(firmwareVersion, firmwareDescription);
enableFirmwareDisplay();
if (supported) {
if (communicating === false) usePacketValues(packet);
} else {
disablePacketDisplay();
clearPacketDisplay();
disableButton();
}
} catch (e) {
/* Problem reading from AudioMoth or no AudioMoth */
disableFirmwareDisplay();
disablePacketDisplay();
disableButton();
}
const milliseconds = Date.now() % MILLISECONDS_IN_SECOND;
let delay = MILLISECONDS_IN_SECOND / 2 - milliseconds;
if (delay < 0) delay += MILLISECONDS_IN_SECOND;
setTimeout(getAudioMothPacket, delay);
}
/* 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.latestFirmwareVersionString + ' of AudioMoth-USB-Microphone firmware to use all the features of this version of the AudioMoth USB Microphone App.';
break;
case constants.FIRMWARE_UNSUPPORTED:
updateRecommended = false;
if (firmwareWarningShown === false) {
firmwareWarningShown = true;
setTimeout(function () {
dialog.showMessageBoxSync(BrowserWindow.getFocusedWindow(), {
type: 'warning',
title: 'Unsupported firmware',
message: 'The firmware installed on your AudioMoth is not supported by the AudioMoth USB Microphone App.'
});
}, 100);
}
return false;
}
/* If OFFICIAL_RELEASE, OFFICIAL_RELEASE_CANDIDATE or CUSTOM_EQUIVALENT */
if (isOlderSemanticVersion(trueVersionArr, constants.latestFirmwareVersionArray)) {
updateRecommended = true;
if (versionWarningShown === false) {
versionWarningShown = true;
setTimeout(function () {
dialog.showMessageBoxSync(BrowserWindow.getFocusedWindow(), {
type: 'warning',
title: versionWarningTitle,
message: versionWarningText
});
}, 100);
}
} else {
updateRecommended = false;
}
return true;
}
/* Fill in time/date, ID, battery state, firmware version */
function usePacketValues (packet) {
const config = packetReader.read(packet.splice(1));
samplerateDisplay.textContent = (config.sampleRate / config.sampleRateDivider / 1000) + 'kHz';
const gains = ['Low', 'Low-Medium', 'Medium', 'Medium-High', 'High'];
gainDisplay.textContent = gains[config.gain];
if (config.lowerFilterFreq === 0 && config.higherFilterFreq === 0) {
filterSettingDisplay.textContent = 'None';
} else if (config.lowerFilterFreq === UINT16_MAX) {
filterSettingDisplay.textContent = 'Low-pass (' + Math.floor(config.higherFilterFreq / 10) + '.' + (config.higherFilterFreq % 10) + 'kHz)';
} else if (config.higherFilterFreq === UINT16_MAX) {
filterSettingDisplay.textContent = 'High-pass (' + Math.floor(config.lowerFilterFreq / 10) + '.' + (config.lowerFilterFreq % 10) + 'kHz)';
} else {
filterSettingDisplay.textContent = 'Band-pass (' + Math.floor(config.lowerFilterFreq / 10) + '.' + (config.lowerFilterFreq % 10) + ' - ' + Math.floor(config.higherFilterFreq / 10) + '.' + (config.higherFilterFreq % 10) + 'kHz)';
}
var count = 0;
var textContent = '';
if (config.disable48DCFilter === 1) {
textContent += 'Disable 48Hz DC filter';
count += 1;
}
if (config.energySaverModeEnabled === 1) {
if (count > 0) textContent += ' / ';
textContent += 'Energy saver mode';
count += 1;
}
if (config.lowGainRangeEnabled === 1) {
if (count > 0) textContent += ' / ';
textContent += 'Low gain range';
count += 1;
}
if (count === 0) textContent = 'None';
additionalDisplay.textContent = textContent;
enablePacketDisplay();
enableButton();
}
/* 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.style.color = '';
};
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 firmwareVersionArr = firmwareVersion.split('.');
for (let k = 0; k < constants.packetLengthVersions.length; k++) {
const possibleFirmwareVersion = constants.packetLengthVersions[k].firmwareVersion;
if (isOlderSemanticVersion(firmwareVersionArr, possibleFirmwareVersion.split('.'))) {
break;
}
packetLength = constants.packetLengthVersions[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();
}
}
/* 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;
}
}
/* Build configuration packet */
function configureDevice () {
const USB_LAG = 20;
const MINIMUM_DELAY = 100;
disablePacketDisplay();
console.log('Configuring device');
const settings = uiSettings.getSettings();
/* 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.packetLengthVersions.slice(-1)[0].packetLength;
const packet = new Uint8Array(maxPacketLength);
/* Increment to next second transition */
const sendTime = new Date();
let delay = MILLISECONDS_IN_SECOND - sendTime.getMilliseconds() - USB_LAG;
if (delay < MINIMUM_DELAY) delay += 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;
const sampleRateConfiguration = constants.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;
let lowerFilter, higherFilter;
if (settings.passFiltersEnabled) {
switch (settings.filterTypeIndex) {
case 0:
/* Low-pass */
lowerFilter = UINT16_MAX;
higherFilter = settings.higherFilter / 100;
break;
case 1:
/* Band-pass */
lowerFilter = settings.lowerFilter / 100;
higherFilter = settings.higherFilter / 100;
break;
case 2:
/* High-pass */
lowerFilter = settings.lowerFilter / 100;
higherFilter = UINT16_MAX;
break;
}
} else {
lowerFilter = 0;
higherFilter = 0;
}
writeLittleEndianBytes(packet, index, 2, lowerFilter);
index += 2;
writeLittleEndianBytes(packet, index, 2, higherFilter);
index += 2;
const disableLED = settings.enableLED ? 0 : 1;
const energySaverModeEnabled = settings.energySaverModeEnabled ? 1 : 0;
const disable48DCFilter = settings.disable48DCFilter ? 1 : 0;
const enableLowGainRange = settings.lowGainRangeEnabled ? 1 : 0;
packet[index++] = energySaverModeEnabled | (disable48DCFilter << 1) | (enableLowGainRange << 2) | (disableLED << 3);
console.log('Packet length: ', index);
/* Send packet to device */
console.log('Sending packet:');
console.log(packet);
let config = packetReader.read(packet);
packetReader.print(config);
const now = new Date();
const sendTimeDiff = sendTime.getTime() - now.getTime();
/* Calculate when to re-enable time display */
disableButton();
communicating = true;
const updateDelay = sendTimeDiff <= 0 ? MILLISECONDS_IN_SECOND : sendTimeDiff;
setTimeout(function () {
communicating = false;
}, updateDelay);
/* Either send immediately or wait until the transition */
if (sendTimeDiff <= 0) {
console.log('Sending...');
sendAudioMothPacket(packet);
} else {
console.log('Sending in', sendTimeDiff);
setTimeout(function () {
sendAudioMothPacket(packet);
}, sendTimeDiff);
}
}
/* Initialise device information displays */
function initialiseDisplay () {
idDisplay.textContent = '-';
firmwareVersionDisplay.textContent = '-';
firmwareDescriptionDisplay.textContent = '-';
}
/* Disable/enable device information display */
function disableFirmwareDisplay () {
firmwareLabels.forEach(label => label.classList.add('grey'));
firmwareDisplays.forEach(display => display.classList.add('grey'));
};
function clearPacketDisplay() {
packetDisplays.forEach(display => display.textContent = '-');
}
function disablePacketDisplay () {
packetLabels.forEach(label => label.classList.add('grey'));
packetDisplays.forEach(display => display.classList.add('grey'));
};
function disableButton () {
configureButton.disabled = true;
}
function enableFirmwareDisplay () {
firmwareLabels.forEach(label => label.classList.remove('grey'));
firmwareDisplays.forEach(display => display.classList.remove('grey'));
};
function enablePacketDisplay () {
packetLabels.forEach(label => label.classList.remove('grey'));
packetDisplays.forEach(display => display.classList.remove('grey'));
}
function enableButton () {
configureButton.disabled = false;
}
/* Insert retrieved values into device information display */
function updateIdDisplay (deviceId) {
applicationMenu.getMenuItemById('copyid').enabled = true;
idDisplay.textContent = deviceId;
}
function updateFirmwareDisplay (version, description) {
firmwareVersionDisplay.textContent = version;
if (updateRecommended) {
firmwareVersionDisplay.textContent += ' (Update recommended)';
}
firmwareDescriptionDisplay.textContent = description;
}
function copyDeviceID () {
const id = idDisplay.textContent;
clipboard.writeText(id);
idDisplay.style.color = 'green';
setTimeout(() => {
idDisplay.style.color = '';
}, 2000);
}
electron.ipcRenderer.on('copy-id', copyDeviceID);
function toggleNightMode () {
ui.toggleNightMode();
}
/* Add listeners to update menu options */
electron.ipcRenderer.on('update-check', function () {
versionChecker.checkLatestRelease(function (response) {
if (response.error) {
console.error(response.error);
dialog.showMessageBox(BrowserWindow.getFocusedWindow(), {
type: 'error',
title: 'Failed to check for updates',
message: response.error
});
return;
}
if (response.updateNeeded === false) {
dialog.showMessageBox(BrowserWindow.getFocusedWindow(), {
type: 'info',
buttons: ['OK'],
title: 'Update not needed',
message: 'Your app is on the latest version (' + response.latestVersion + ').'
});
return;
}
const buttonIndex = dialog.showMessageBoxSync({
type: 'warning',
buttons: ['Yes', 'No'],
title: 'Download newer version',
message: 'A newer version of this app is available (' + response.latestVersion + '), would you like to download it?'
});
if (buttonIndex === 0) {
electron.shell.openExternal('https://www.openacousticdevices.info/applications');
}
});
});
/* Prepare UI */
idDisplay.addEventListener('click', copyDeviceID);
disableFirmwareDisplay();
disablePacketDisplay();
disableButton();
initialiseDisplay();
getAudioMothPacket();
electron.ipcRenderer.on('night-mode', toggleNightMode);
configureButton.addEventListener('click', () => {
configureDevice();
});
uiSettings.prepareUI();