-
Notifications
You must be signed in to change notification settings - Fork 2
/
communication.js
1650 lines (1028 loc) · 42.5 KB
/
communication.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
/****************************************************************************
* communication.js
* openacousticdevices.info
* October 2019
*****************************************************************************/
'use strict';
const electron = require('electron');
const {dialog} = require('@electron/remote');
const audiomoth = require('audiomoth-hid');
const {SerialPort, ByteLengthParser} = require('serialport');
const fs = require('fs');
const path = require('path');
const util = require('util');
const electronLog = require('electron-log');
/* Flash constants */
const MAXIMUM_RETRIES = 10;
const DEFAULT_RETRY_INTERVAL = 100;
const DEFAULT_DELAY_BETWEEN_PACKETS = 10;
const DEFAULT_DELAY_BETWEEN_CRC_REQUESTS = 500;
const MAXIMUM_FIRMWARE_PACKET_SIZE = 56;
const NUMBER_OF_BUFFER_TO_SEND = process.platform === 'win32' ? 30 : 60;
/* USB HID flashing constants */
/* eslint-disable no-multi-spaces,no-unused-vars */
const AM_BOOTLOADER_GET_VERSION = 0x01;
const AM_BOOTLOADER_INITIALISE_SRAM = 0x02;
const AM_BOOTLOADER_CLEAR_USER_DATA = 0x03;
const AM_BOOTLOADER_SET_SRAM_FIRMWARE_PACKET = 0x04;
const AM_BOOTLOADER_CALC_SRAM_FIRMWARE_CRC = 0x05;
const AM_BOOTLOADER_CALC_FLASH_FIRMWARE_CRC = 0x06;
const AM_BOOTLOADER_GET_FIRMWARE_CRC = 0x07;
const AM_BOOTLOADER_FLASH_FIRMWARE = 0x08;
/* eslint-enable no-multi-spaces,no-unused-vars */
/* Timeout to close port if message is sent and no response is received */
const PORT_TIMEOUT_LENGTH = 1500;
/* Counter for ready checks */
const MAX_READY_CHECK_COUNT = 7;
let readyCheckCount;
const READY_CHECK_DELAY_LENGTH = 100;
/* Timeout to wait for a switch to bootloader mode after the message is sent */
const BOOTLOADER_CHECK_MAX_TIMEOUT_LENGTH = 10000;
const BOOTLOADER_CHECK_TIMEOUT_LENGTH = 100;
let bootloaderCheckTimeout;
let bootloaderCheckTimedOut = false;
/* Timeout to wait for a reset after flash */
const RESET_TIMEOUT_LENGTH = 7500;
const RESET_CHECK_TIMEOUT_LENGTH = 100;
/* Time spent resetting */
let resetTime;
/* Whether or not the app is in the process of communicating with a device (used to prevent spamming requests) */
let communicating = false;
/* Serial port through which AudioMoth communication is taking place */
let port;
/* Buffer object which extends as more bytes are received */
let queue;
/* Regex to be applied to the queue buffer when it's full */
let responseRegex;
/* Number of bytes expected as a response to a given message */
let responseExpectedLength;
/* Function which is run when correct response is received */
let completionFunction;
/* Callback called by openPort if failure occurs */
let portErrorCallback;
/* ID of timeout waiting for correct response */
let responseTimeout;
/* Whether or not a message request has already timed out */
let timedOut;
/* Number of times checking the user data checksum has been attempted */
let userDataCheckCount;
const MAX_USER_DATA_CHECK_COUNT = 5;
const USER_DATA_CHECK_DELAY_LENGTH = 100;
/* Timeout for attempting another ready check */
let readyTimeout;
let receiveComplete;
/* ID of timeout waiting for reset response */
let flashResetTimeout;
/* xmodem values: */
const SOH = 0x01;
const EOF = 0x04;
const ACK = 0x06;
const FILLER = 0xFF;
const BLOCK_SIZE = 128;
exports.BLOCK_SIZE = BLOCK_SIZE;
const MAX_REPEATS = 10;
/* Variables used to keep track of flash process */
let numberOfRepeats;
let blockNumber;
let lower = 0;
let upper = 0;
/* Array of buffers of length BLOCK_SIZE */
let splitBuffers;
/* Blank buffer for clearing the user data */
const blankBuffer = Buffer.alloc(128);
/* Device statuses */
exports.STATUS_SERIAL_BOOTLOADER = 1;
exports.STATUS_NO_AUDIOMOTH = 2;
exports.STATUS_AUDIOMOTH_AUTO = 3;
exports.STATUS_AUDIOMOTH_MANUAL = 4;
exports.STATUS_AUDIOMOTH_USB = 5;
/* Flag indicating the overall process has failed and shouldn't continue */
let flashFailed = false;
/**
* Call a synchronous function, repeating a fixed number of times with a delay between each attempt
* @param {function} funcSync Synchronous function being called
* @param {*} argument Argument(s) sent to function
* @param {int} milliseconds Delay between attempts
* @param {int} repeats Number of attempts before giving up
* @returns Result of function
*/
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 AudioMoth failed.');
}
if (result === null) {
throw ('Error: No AudioMoth detected.');
}
return result;
}
/**
* Wait a given number of milliseconds
* @param {int} milliseconds Pause length
*/
async function delay (milliseconds) {
return new Promise(resolve => setTimeout(resolve, milliseconds));
}
/* Promisified versions of AudioMoth-HID calls */
const queryUSBHIDBootloader = util.promisify(audiomoth.queryUSBHIDBootloader);
const sendPacketToUSBHIDBootloader = util.promisify(audiomoth.sendPacketToUSBHIDBootloader);
const sendMultiplePacketsToUSBHIDBootloader = util.promisify(audiomoth.sendMultiplePacketsToUSBHIDBootloader);
const switchToBootloader = util.promisify(audiomoth.switchToBootloader);
const queryBootloader = util.promisify(audiomoth.queryBootloader);
const getFirmwareVersion = util.promisify(audiomoth.getFirmwareVersion);
const getFirmwareDescription = util.promisify(audiomoth.getFirmwareDescription);
async function getStatus () {
try {
const supportsUSBHIDFlash = await callWithRetry(queryUSBHIDBootloader, null, DEFAULT_RETRY_INTERVAL, MAXIMUM_RETRIES);
const supportsBootloaderSwitch = await callWithRetry(queryBootloader, null, DEFAULT_RETRY_INTERVAL, MAXIMUM_RETRIES);
const firmwareVersion = await callWithRetry(getFirmwareVersion, null, DEFAULT_RETRY_INTERVAL, MAXIMUM_RETRIES);
const firmwareDescription = await callWithRetry(getFirmwareDescription, null, DEFAULT_RETRY_INTERVAL, MAXIMUM_RETRIES);
return {
supportsUSBHIDFlash,
supportsBootloaderSwitch,
firmwareVersion,
firmwareDescription
};
} catch (err) {
return null;
}
}
exports.getStatus = getStatus;
/**
* Close serial port if it's open
*/
function closePort () {
if (port !== undefined) {
if (port.isOpen) {
port.close();
}
}
}
exports.closePort = closePort;
/**
* @param {buffer} buffer Buffer of data being checked
* @returns Cyclical Redundancy Check code (CRC)
*/
function crc16 (buffer) {
let crc = 0x0;
for (let i = 0; i < buffer.length; i++) {
const byte = buffer[i];
let code = (crc >>> 8) & 0xFF;
code ^= byte & 0xFF;
code ^= code >>> 4;
crc = (crc << 8) & 0xFFFF;
crc ^= code;
code = (code << 5) & 0xFFFF;
crc ^= code;
code = (code << 7) & 0xFFFF;
crc ^= code;
}
return crc;
}
/**
* Create error message window which blocks interaction with the main window
* @param {string} title Text in title bar
* @param {string} message Text in error message body
*/
function displayError (title, message) {
electron.ipcRenderer.send('set-bar-aborted');
dialog.showMessageBox({
type: 'error',
icon: path.join(__dirname, '/icon-64.png'),
title,
buttons: ['OK'],
message
});
}
exports.displayError = displayError;
/**
* Check all serial ports and return port name if AudioMoth is found
* @returns Name of the port where an AudioMoth can be found
*/
async function getAudioMothPortName () {
const ports = await SerialPort.list();
for (let i = 0; i < ports.length; i += 1) {
const p = ports[i];
let vid = p.vendorId;
const pid = p.productId;
const portPath = p.path;
if (vid !== undefined && pid !== undefined && portPath !== undefined) {
vid = vid.toUpperCase();
/* Vendor ID varies based on when the AudioMoth was manufactured */
if ((vid === '10C4' || vid === '2544') && pid === '0003') {
return portPath;
}
}
}
return false;
}
exports.getAudioMothPortName = getAudioMothPortName;
/**
* Verify the device is now in the bootloader
* @param {function} callback Called when verification is complete
*/
async function checkBootloaderSwitch (callback) {
/* Check for serial bootloader */
const deviceFound = await isInBootloader();
if (deviceFound) {
clearTimeout(bootloaderCheckTimeout);
callback();
} else {
if (!bootloaderCheckTimedOut) {
setTimeout(() => {
checkBootloaderSwitch(callback);
}, BOOTLOADER_CHECK_TIMEOUT_LENGTH);
}
}
}
/**
* Send message to AudioMoth in USB mode to switch to bootloader
* @param {function} callback Called when request has a response. Called with an error argument if one occurred
*/
async function requestBootloader (callback) {
/* Send bootloader request packet and await confirmation message */
try {
const switchedToBootloader = await callWithRetry(switchToBootloader, null, DEFAULT_RETRY_INTERVAL, MAXIMUM_RETRIES);
/* Check for expected confirmation response */
if (switchedToBootloader) {
electronLog.log('Attached AudioMoth switching to serial flash mode');
/* Device will load bootloader, repeatedly check for the appearance of a serial bootloader until timeout */
bootloaderCheckTimedOut = false;
checkBootloaderSwitch(callback);
bootloaderCheckTimeout = setTimeout(() => {
bootloaderCheckTimedOut = true;
callback('Error: Failed to switch AudioMoth to serial flash mode. Detach and reattach your AudioMoth, and try again.');
}, BOOTLOADER_CHECK_MAX_TIMEOUT_LENGTH);
} else {
callback('Error: AudioMoth refused to switch to serial flash mode. Detach and reattach your AudioMoth, and try again.');
}
} catch (err) {
callback('Error: Failed to switch AudioMoth to serial flash mode. Detach and reattach your AudioMoth, and try again.');
}
}
exports.requestBootloader = requestBootloader;
/**
* Function called whenever 1 byte of data is received
* @param {buffer} data Buffer containing 1 byte of data
*/
function receive (data) {
if (port === undefined) {
return;
}
if (receiveComplete || timedOut || !port.isOpen) {
return;
}
/* Add 1 byte of data to the queue */
queue = Buffer.concat([queue, data]);
/* When a given number of bytes have been added to the queue, check contents */
if (queue.length >= responseExpectedLength) {
clearTimeout(responseTimeout);
timedOut = false;
receiveComplete = true;
/* Apply provided regex */
const regexResult = responseRegex.exec(queue.toString('utf8'));
/* Only return response if it matches the expected regex */
if (regexResult) {
switch (responseRegex.source) {
case String.fromCharCode(ACK):
electronLog.log('Received expected response: ACK');
break;
case String.fromCharCode(EOF):
electronLog.log('Received expected response: EOF');
break;
default:
electronLog.log('Received expected response: "' + regexResult[0] + '"');
break;
}
completionFunction(null, regexResult[0]);
} else {
electronLog.error('Unexpected response: "' + queue.toString('hex') + '"');
completionFunction('Error: Unexpected response: "' + queue.toString('hex') + '"');
}
}
}
/**
* Send buffer to AudioMoth on given port
* @param {buffer} buffer Data to be sent
* @param {int} expectedLength Expected length of response
* @param {regex} regex Regex to be applied to response
* @param {function} callback Called when completed sending
*/
async function send (buffer, expectedLength, regex, callback) {
if (flashFailed || port === undefined) {
return;
}
if (!port.isOpen) {
electronLog.error('Sending buffer failed. Port is closed');
clearTimeout(responseTimeout);
if (completionFunction) {
completionFunction('Error: Sending buffer failed. Port is closed');
}
return;
}
receiveComplete = false;
/* Set response expectations */
responseExpectedLength = expectedLength;
/* Set REGEX */
responseRegex = regex;
/* Set function which will be run after the right number of bytes have been received and the response matches responseRegex */
completionFunction = callback;
/* Clear buffer */
queue = Buffer.alloc(0);
if (buffer.length === 1) {
if (buffer[0] === EOF) {
electronLog.log('Writing data to port: EOF');
} else {
electronLog.log('Writing data to port: \'' + String.fromCharCode(buffer[0]) + '\'');
}
} else {
electronLog.log('Writing data to port:', buffer.toString('hex'));
}
/* Send command */
port.write(buffer, (err) => {
electronLog.log('Write complete');
if (err) {
clearTimeout(responseTimeout);
}
});
responseTimeout = setTimeout(() => {
electronLog.error('Timed out waiting for response');
timedOut = true;
completionFunction('Error: Timed out waiting for response');
}, PORT_TIMEOUT_LENGTH);
timedOut = false;
}
exports.setPortErrorCallback = (callback) => {
portErrorCallback = callback;
};
exports.failFlash = () => {
displayError('Communication failure', 'Could not connect to AudioMoth. Reconnect AudioMoth and try again.');
flashFailed = true;
};
/**
* Open a port with given name, calling each of the given callbacks when the port opens/closes
* @param {string} name Name of port to be opened
* @param {function} openCallback Called when port has been opened
* @param {function} closeCallback Called when port closes
* @param {function} errorCallback Called when an error occurs
*/
function openPort (name, openCallback, closeCallback, errorCallback) {
/* Clear buffer */
queue = Buffer.alloc(0);
/* Open a connection to the port at the given path */
port = new SerialPort({
path: name,
baudRate: 9600
});
port.on('open', () => {
openCallback();
});
/* Add functions to event listeners if they're provided */
if (closeCallback) {
port.on('close', closeCallback);
}
if (errorCallback) {
portErrorCallback = errorCallback;
}
port.on('error', (err) => {
electronLog.error(err);
if (portErrorCallback) {
portErrorCallback();
}
});
/* Every time 1 byte is received, call receive(data) */
const parser = port.pipe(new ByteLengthParser({length: 1}));
parser.on('data', receive);
}
exports.openPort = openPort;
/**
* Query AudioMoth as to whether it supports switching from USB mode to the bootloader in response to a packet
* @param {function} callback Called when response is received
*/
async function queryBootloaderSwitching (callback) {
try {
const supportsBootloaderSwitch = await callWithRetry(queryBootloader, null, DEFAULT_RETRY_INTERVAL, MAXIMUM_RETRIES);
callback(null, supportsBootloaderSwitch);
} catch (err) {
callback('Error: Could not connect to AudioMoth to query whether it supports serial flash mode switching. Verify connection and try again.');
}
}
exports.queryBootloaderSwitching = queryBootloaderSwitching;
/**
* Request current firmware version. When response is received, run callback with string containing version number as the only argument
* @param {function} callback Called when response is received
*/
async function requestFirmwareVersion (callback) {
try {
const versionArr = await callWithRetry(getFirmwareVersion, null, DEFAULT_RETRY_INTERVAL, MAXIMUM_RETRIES);
callback(null, versionArr[0] + '.' + versionArr[1] + '.' + versionArr[2]);
} catch (err) {
callback('Error: Could not connect to AudioMoth to obtain firmware version. Verify connection and try again.');
}
}
exports.requestFirmwareVersion = requestFirmwareVersion;
/**
* Request current firmware description. When response is received, run callback with string containing description assigned in firmware source
* @param {function} callback Called when response is received
*/
async function requestFirmwareDescription (callback) {
try {
const description = await callWithRetry(getFirmwareDescription, null, DEFAULT_RETRY_INTERVAL, MAXIMUM_RETRIES);
callback(null, description);
} catch (err) {
callback('Error: Could not connect to AudioMoth to obtain firmware description. Verify connection and try again.');
}
}
exports.requestFirmwareDescription = requestFirmwareDescription;
/**
* Attempt to retrieve the port name of a connected ID, if one is found return true, else return false
*/
async function isInBootloader () {
/* Asynchronously obtain the port of the AudioMoth */
const audioMothPortName = await getAudioMothPortName();
return audioMothPortName !== false;
}
exports.isInBootloader = isInBootloader;
/**
* Return variable representing communication between the app and a device which prevents overlapping communication
*/
function isCommunicating () {
return communicating;
}
exports.isCommunicating = isCommunicating;
function startCommunicating () {
communicating = true;
}
exports.startCommunicating = startCommunicating;
/**
* Set communication flag to false and then close the port if it's currently open
*/
function stopCommunicating () {
communicating = false;
closePort();
}
exports.stopCommunicating = stopCommunicating;
/**
* Request the CRC of the firmware currently on the AudioMoth
* @param {boolean} isDestructive If the flash is destructive, then the CRC should take into account the bootloader as well as the firmware itself
* @param {function} callback Called when send action is complete
*/
function requestCRC (isDestructive, callback) {
/* If the flash is destructive, then the CRC should take into account the bootloader as well as the firmware itself */
const readType = isDestructive ? 'v' : 'c';
const sendBuffer = Buffer.from(readType);
const responseLength = 18;
const regex = /CRC: 0000[A-Z0-9]{4}/;
send(sendBuffer, responseLength, regex, callback);
}
/**
* Request the version of the bootloader currently installed on the AudioMoth
* @param {function} callback Called when response is received
*/
function requestBootloaderVersion (callback) {
const sendBuffer = Buffer.from('i');
const responseLength = 54;
const regex = /BOOTLOADER version [0-9]\.[0-9]{2}, Chip ID [0-9A-Z]{16}/;
send(sendBuffer, responseLength, regex, (err, response) => {
if (err) {
callback('Error: Unable to establish communication with bootloader.');
} else {
const bootloaderVersion = parseFloat(response.substr(19, 23));
callback(null, bootloaderVersion);
}
});
}
exports.requestBootloaderVersion = requestBootloaderVersion;
/**
* Animate progress as app waits for flashed device to reset
* @param {string} message Message displayed on serial flash progress window
* @param {function} successCallback Called when restart has been successfully completed
*/
async function restartTimer (message, successCallback) {
if (resetTime < RESET_TIMEOUT_LENGTH) {
electron.ipcRenderer.send('set-bar-restart-progress', resetTime);
setTimeout(() => {
resetTime += RESET_CHECK_TIMEOUT_LENGTH;
restartTimer(message, successCallback);
}, RESET_CHECK_TIMEOUT_LENGTH);
} else {
electron.ipcRenderer.send('set-bar-restarted');
successCallback(message);
}
}
/**
* Display message window explaining that resetting failed
* @param {string} message Text appended to window body text (usually an explanation for the reset failure)
*/
function resetFailure (message) {
electronLog.error('Reset failed');
dialog.showMessageBox({
type: 'warning',
icon: path.join(__dirname, '/icon-64.png'),
title: 'Flashing complete',
buttons: ['OK'],
message: message + ' Switch to USB/OFF, detach and reattach your AudioMoth to verify new firmware version.'
});
electron.ipcRenderer.send('set-bar-aborted');
stopCommunicating();
}
/**
* Send reset message to device then wait for the bootloader to disappear from serial port list
* @param {string} message Text in window body
* @param {function} successCallback Called when restart is completed successfully
*/
function resetDevice (message, successCallback) {
/* Send full reset message */
const sendBuffer = Buffer.from('r');
const responseLength = 1;
const regex = /r/;
send(sendBuffer, responseLength, regex, (err, response) => {
clearTimeout(flashResetTimeout);
clearTimeout(responseTimeout);
closePort();
if (err) {
resetFailure(message);
return;
}
electronLog.log('Reset message sent, response: "' + response + '"');
electronLog.log('Waiting for AudioMoth to restart');
/* Check device has reset */
electron.ipcRenderer.send('set-bar-restarting', RESET_TIMEOUT_LENGTH);
resetTime = 0;
restartTimer(message, successCallback);
});
/* If there's no response to the reset message */
flashResetTimeout = setTimeout(() => {
resetFailure(message);
}, 5000);
}
/**
* Verify flash was successful by comparing new firmware CRC with previously calculated CRC
* @param {string} expectedCRC Previously calculated CRC
* @param {boolean} isDestructive Is the flash a destructive flash
* @param {function} successCallback Called when CRC is successful and they match
*/
function crcCheck (expectedCRC, isDestructive, successCallback) {
requestCRC(isDestructive, (err, response) => {
if (err) {
displayError('Communication failure', 'Flash completed but success could not be verified. Detach and reattach your AudioMoth, and try again.');
electron.ipcRenderer.send('set-bar-aborted');
stopCommunicating();
} else {
/* CRC message sent by bootloader is prepended with 'CRC:', so only the last 4 characters which actually contain the CRC are needed */
const receivedCRC = response.substr(response.length - 4, 4);
if (expectedCRC) {
electronLog.log('Comparing CRCs');
electronLog.log('Expected: ' + expectedCRC + ', Received: ' + receivedCRC);
if (receivedCRC === expectedCRC) {
electronLog.log('Flash CRC was correct, resetting AudioMoth');
resetDevice('Firmware has been successfully updated.', successCallback);
} else {
electronLog.error('Flash CRC was incorrect, ending communication');
let errorString = 'Flash failed, CRC did not match. ';
errorString += 'Expected ' + expectedCRC + ' but received ' + receivedCRC + '. ';
errorString += 'Reconnect AudioMoth and try again.';
displayError('Verification failure', errorString);
electron.ipcRenderer.send('set-bar-aborted');
stopCommunicating();
}
} else {
resetDevice('Firmware has been successfully updated.\nFlash CRC: ' + receivedCRC, successCallback);
}
}
});
}
/**
* Send EOF message to device and wait for confirmation
* @param {string} expectedCRC Previously calculated CRC
* @param {boolean} isDestructive Is the flash destructive
* @param {function} successCallback Called when flash is successful
*/
function confirmEOF (expectedCRC, isDestructive, successCallback) {
const sendBuffer = Buffer.from([EOF]);
const responseLength = 1;
const regex = new RegExp(String.fromCharCode(ACK));
send(sendBuffer, responseLength, regex, (err, response) => {
if (err) {
electronLog.error('Did not receive ACK from AudioMoth after sending end of file');
displayError('Communication failure', 'End of file acknowledgement was not received from AudioMoth. Detach and reattach your AudioMoth, and try again.');
stopCommunicating();
} else {
electronLog.log('Successfully sent all blocks and received EOF message');
clearTimeout(responseTimeout);
crcCheck(expectedCRC, isDestructive, successCallback);
}
});
}
/**
* Create the nth buffer to send to the device
* @param {int} n Buffer index
* @returns Generated send buffer
*/
function generateSendBuffer (n) {
let crcString = crc16(splitBuffers[n]).toString(16);
/* If the CRC is an odd length, pad it with a zero */
if (crcString.length % 2 === 1) {
crcString = '0'.concat(crcString);
}
/* CRC must be 2 bytes of length, pad with zeroes to achieve this */
if (crcString.length === 2) {
crcString = '00'.concat(crcString);