forked from OpenAcousticDevices/AudioMoth-Firmware-Basic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
1453 lines (797 loc) · 45.3 KB
/
main.c
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
/****************************************************************************
* main.c
* openacousticdevices.info
* June 2017
*****************************************************************************/
#include <time.h>
#include <math.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include "audioMoth.h"
#include "digitalFilter.h"
/* Useful time constants */
#define SECONDS_IN_MINUTE 60
#define SECONDS_IN_HOUR (60 * SECONDS_IN_MINUTE)
#define SECONDS_IN_DAY (24 * SECONDS_IN_HOUR)
/* Useful type constants */
#define BITS_PER_BYTE 8
#define UINT32_SIZE_IN_BITS 32
#define UINT32_SIZE_IN_BYTES 4
/* Sleep and LED constants */
#define DEFAULT_WAIT_INTERVAL 1
#define WAITING_LED_FLASH_INTERVAL 2
#define WAITING_LED_FLASH_DURATION 10
#define LOW_BATTERY_LED_FLASHES 10
#define SHORT_LED_FLASH_DURATION 100
#define LONG_LED_FLASH_DURATION 500
/* SRAM buffer constants */
#define NUMBER_OF_BUFFERS 8
#define NUMBER_OF_BYTES_IN_SAMPLE 2
#define EXTERNAL_SRAM_SIZE_IN_SAMPLES (AM_EXTERNAL_SRAM_SIZE_IN_BYTES / NUMBER_OF_BYTES_IN_SAMPLE)
#define NUMBER_OF_SAMPLES_IN_BUFFER (EXTERNAL_SRAM_SIZE_IN_SAMPLES / NUMBER_OF_BUFFERS)
/* DMA transfer constant */
#define MAXIMUM_SAMPLES_IN_DMA_TRANSFER 1024
/* Microphone warm-up constant */
#define FRACTION_OF_SECOND_FOR_WARMUP 2
/* Compression constants */
#define COMPRESSION_BUFFER_SIZE_IN_BYTES 512
/* File size constants */
#define MAXIMUM_WAV_FILE_SIZE (UINT32_MAX - 1)
/* WAV header constant */
#define PCM_FORMAT 1
#define RIFF_ID_LENGTH 4
#define LENGTH_OF_ARTIST 32
#define LENGTH_OF_COMMENT 384
/* USB configuration constant */
#define MAX_START_STOP_PERIODS 5
/* Digital filter constant */
#define FILTER_FREQ_MULTIPLIER 100
/* DC filter constant */
#define DC_BLOCKING_FREQ 48
/* Supply monitor constant */
#define MINIMUM_SUPPLY_VOLTAGE 2800
/* Useful macros */
#define FLASH_LED(led, duration) { \
AudioMoth_set ## led ## LED(true); \
AudioMoth_delay(duration); \
AudioMoth_set ## led ## LED(false); \
}
#define FLASH_LED_AND_RETURN_ON_ERROR(fn) { \
bool success = (fn); \
if (success != true) { \
FLASH_LED(Both, LONG_LED_FLASH_DURATION) \
return SDCARD_WRITE_ERROR; \
} \
}
#define RETURN_BOOL_ON_ERROR(fn) { \
bool success = (fn); \
if (success != true) { \
return success; \
} \
}
#define SAVE_SWITCH_POSITION_AND_POWER_DOWN(duration) { \
*previousSwitchPosition = switchPosition; \
AudioMoth_powerDownAndWake(duration, true); \
}
#define ABS(a) ((a) < (0) ? (-a) : (a))
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define ROUNDED_DIV(a, b) (((a) + (b/2)) / (b))
/* Recording state enumeration */
typedef enum {RECORDING_OKAY, FILE_SIZE_LIMITED, SUPPLY_VOLTAGE_LOW, SWITCH_CHANGED, SDCARD_WRITE_ERROR} AM_recordingState_t;
/* Filter type enumeration */
typedef enum {NO_FILTER, LOW_PASS_FILTER, BAND_PASS_FILTER, HIGH_PASS_FILTER} AM_filterType_t;
/* WAV header */
#pragma pack(push, 1)
typedef struct {
char id[RIFF_ID_LENGTH];
uint32_t size;
} chunk_t;
typedef struct {
chunk_t icmt;
char comment[LENGTH_OF_COMMENT];
} icmt_t;
typedef struct {
chunk_t iart;
char artist[LENGTH_OF_ARTIST];
} iart_t;
typedef struct {
uint16_t format;
uint16_t numberOfChannels;
uint32_t samplesPerSecond;
uint32_t bytesPerSecond;
uint16_t bytesPerCapture;
uint16_t bitsPerSample;
} wavFormat_t;
typedef struct {
chunk_t riff;
char format[RIFF_ID_LENGTH];
chunk_t fmt;
wavFormat_t wavFormat;
chunk_t list;
char info[RIFF_ID_LENGTH];
icmt_t icmt;
iart_t iart;
chunk_t data;
} wavHeader_t;
#pragma pack(pop)
static wavHeader_t wavHeader = {
.riff = {.id = "RIFF", .size = 0},
.format = "WAVE",
.fmt = {.id = "fmt ", .size = sizeof(wavFormat_t)},
.wavFormat = {.format = PCM_FORMAT, .numberOfChannels = 1, .samplesPerSecond = 0, .bytesPerSecond = 0, .bytesPerCapture = 2, .bitsPerSample = 16},
.list = {.id = "LIST", .size = RIFF_ID_LENGTH + sizeof(icmt_t) + sizeof(iart_t)},
.info = "INFO",
.icmt = {.icmt.id = "ICMT", .icmt.size = LENGTH_OF_COMMENT, .comment = ""},
.iart = {.iart.id = "IART", .iart.size = LENGTH_OF_ARTIST, .artist = ""},
.data = {.id = "data", .size = 0}
};
/* Functions to set WAV header details and comment */
static void setHeaderDetails(wavHeader_t *wavHeader, uint32_t sampleRate, uint32_t numberOfSamples) {
wavHeader->wavFormat.samplesPerSecond = sampleRate;
wavHeader->wavFormat.bytesPerSecond = NUMBER_OF_BYTES_IN_SAMPLE * sampleRate;
wavHeader->data.size = NUMBER_OF_BYTES_IN_SAMPLE * numberOfSamples;
wavHeader->riff.size = NUMBER_OF_BYTES_IN_SAMPLE * numberOfSamples + sizeof(wavHeader_t) - sizeof(chunk_t);
}
static void setHeaderComment(wavHeader_t *wavHeader, uint32_t currentTime, int8_t timezoneHours, int8_t timezoneMinutes, uint8_t *serialNumber, uint32_t gain, AM_extendedBatteryState_t extendedBatteryState, int32_t temperature, bool switchPositionChanged, bool supplyVoltageLow, bool fileSizeLimited, uint32_t amplitudeThreshold, AM_filterType_t filterType, uint32_t lowerFilterFreq, uint32_t higherFilterFreq) {
time_t rawtime = currentTime + timezoneHours * SECONDS_IN_HOUR + timezoneMinutes * SECONDS_IN_MINUTE;
struct tm *time = gmtime(&rawtime);
/* Format artist field */
char *artist = wavHeader->iart.artist;
sprintf(artist, "AudioMoth %08X%08X", (unsigned int)*((uint32_t*)serialNumber + 1), (unsigned int)*((uint32_t*)serialNumber));
/* Format comment field */
char *comment = wavHeader->icmt.comment;
comment += sprintf(comment, "Recorded at %02d:%02d:%02d %02d/%02d/%04d (UTC", time->tm_hour, time->tm_min, time->tm_sec, time->tm_mday, 1 + time->tm_mon, 1900 + time->tm_year);
if (timezoneHours < 0) {
comment += sprintf(comment, "%d", timezoneHours);
} else if (timezoneHours > 0) {
comment += sprintf(comment, "+%d", timezoneHours);
} else {
if (timezoneMinutes < 0) comment += sprintf(comment, "-%d", timezoneHours);
if (timezoneMinutes > 0) comment += sprintf(comment, "+%d", timezoneHours);
}
if (timezoneMinutes < 0) comment += sprintf(comment, ":%02d", -timezoneMinutes);
if (timezoneMinutes > 0) comment += sprintf(comment, ":%02d", timezoneMinutes);
static char *gainSettings[5] = {"low", "low-medium", "medium", "medium-high", "high"};
comment += sprintf(comment, ") by %s at %s gain setting while battery state was ", artist, gainSettings[gain]);
if (extendedBatteryState == AM_EXT_BAT_LOW) {
comment += sprintf(comment, "less than 2.5V");
} else if (extendedBatteryState >= AM_EXT_BAT_FULL) {
comment += sprintf(comment, "greater than 4.9V");
} else {
uint32_t batteryVoltage = extendedBatteryState + AM_EXT_BAT_STATE_OFFSET / AM_BATTERY_STATE_INCREMENT;
comment += sprintf(comment, "%01d.%01dV", (unsigned int)batteryVoltage / 10, (unsigned int)batteryVoltage % 10);
}
char *sign = temperature < 0 ? "-" : "";
uint32_t temperatureInDecidegrees = ROUNDED_DIV(ABS(temperature), 100);
comment += sprintf(comment, " and temperature was %s%d.%dC.", sign, (unsigned int)temperatureInDecidegrees / 10, (unsigned int)temperatureInDecidegrees % 10);
if (amplitudeThreshold > 0) {
comment += sprintf(comment, " Amplitude threshold was %d.", (unsigned int)amplitudeThreshold);
}
if (filterType == LOW_PASS_FILTER) {
comment += sprintf(comment, " Low-pass filter applied with cut-off frequency of %01d.%01dkHz.", (unsigned int)higherFilterFreq / 10, (unsigned int)higherFilterFreq % 10);
} else if (filterType == BAND_PASS_FILTER) {
comment += sprintf(comment, " Band-pass filter applied with cut-off frequencies of %01d.%01dkHz and %01d.%01dkHz.", (unsigned int)lowerFilterFreq / 10, (unsigned int)lowerFilterFreq % 10, (unsigned int)higherFilterFreq / 10, (unsigned int)higherFilterFreq % 10);
} else if (filterType == HIGH_PASS_FILTER) {
comment += sprintf(comment, " High-pass filter applied with cut-off frequency of %01d.%01dkHz.", (unsigned int)lowerFilterFreq / 10, (unsigned int)lowerFilterFreq % 10);
}
if (supplyVoltageLow || switchPositionChanged || fileSizeLimited) {
comment += sprintf(comment, " Recording cancelled before completion due to ");
if (switchPositionChanged) {
comment += sprintf(comment, "change of switch position.");
} else if (supplyVoltageLow) {
comment += sprintf(comment, "low voltage.");
} else if (fileSizeLimited) {
comment += sprintf(comment, "file size limit.");
}
}
}
/* USB configuration data structure */
#pragma pack(push, 1)
typedef struct {
uint16_t startMinutes;
uint16_t stopMinutes;
} startStopPeriod_t;
typedef struct {
uint32_t time;
uint8_t gain;
uint8_t clockDivider;
uint8_t acquisitionCycles;
uint8_t oversampleRate;
uint32_t sampleRate;
uint8_t sampleRateDivider;
uint16_t sleepDuration;
uint16_t recordDuration;
uint8_t enableLED;
uint8_t activeStartStopPeriods;
startStopPeriod_t startStopPeriods[MAX_START_STOP_PERIODS];
int8_t timezoneHours;
uint8_t enableLowVoltageCutoff;
uint8_t disableBatteryLevelDisplay;
int8_t timezoneMinutes;
uint8_t disableSleepRecordCycle;
uint32_t earliestRecordingTime;
uint32_t latestRecordingTime;
uint16_t lowerFilterFreq;
uint16_t higherFilterFreq;
uint16_t amplitudeThreshold;
} configSettings_t;
#pragma pack(pop)
static const configSettings_t defaultConfigSettings = {
.time = 0,
.gain = 2,
.clockDivider = 4,
.acquisitionCycles = 16,
.oversampleRate = 1,
.sampleRate = 384000,
.sampleRateDivider = 8,
.sleepDuration = 5,
.recordDuration = 55,
.enableLED = 1,
.activeStartStopPeriods = 0,
.startStopPeriods = {
{.startMinutes = 000, .stopMinutes = 060},
{.startMinutes = 120, .stopMinutes = 180},
{.startMinutes = 240, .stopMinutes = 300},
{.startMinutes = 360, .stopMinutes = 420},
{.startMinutes = 480, .stopMinutes = 540}
},
.timezoneHours = 0,
.enableLowVoltageCutoff = 0,
.disableBatteryLevelDisplay = 0,
.timezoneMinutes = 0,
.disableSleepRecordCycle = 0,
.earliestRecordingTime = 0,
.latestRecordingTime = 0,
.lowerFilterFreq = 0,
.higherFilterFreq = 0,
.amplitudeThreshold = 0
};
/* Function to write configuration to file */
static bool writeConfigurationToFile(configSettings_t *configSettings, uint8_t *firmwareDescription, uint8_t *firmwareVersion, uint8_t *serialNumber) {
uint16_t length;
static char configBuffer[512];
RETURN_BOOL_ON_ERROR(AudioMoth_openFile("CONFIG.TXT"));
length = sprintf(configBuffer, "\nDevice ID : %08X%08X\n", (unsigned int)*((uint32_t*)serialNumber + 1), (unsigned int)*((uint32_t*)serialNumber));
length += sprintf(configBuffer + length, "Firmware : %s (%d.%d.%d)\n\n", firmwareDescription, firmwareVersion[0], firmwareVersion[1], firmwareVersion[2]);
length += sprintf(configBuffer + length, "Time zone : UTC");
if (configSettings->timezoneHours < 0) {
length += sprintf(configBuffer + length, "%d", configSettings->timezoneHours);
} else if (configSettings->timezoneHours > 0) {
length += sprintf(configBuffer + length, "+%d", configSettings->timezoneHours);
} else {
if (configSettings->timezoneMinutes < 0) length += sprintf(configBuffer + length, "-%d", configSettings->timezoneHours);
if (configSettings->timezoneMinutes > 0) length += sprintf(configBuffer + length, "+%d", configSettings->timezoneHours);
}
if (configSettings->timezoneMinutes < 0) length += sprintf(configBuffer + length, ":%02d", -configSettings->timezoneMinutes);
if (configSettings->timezoneMinutes > 0) length += sprintf(configBuffer + length, ":%02d", configSettings->timezoneMinutes);
RETURN_BOOL_ON_ERROR(AudioMoth_writeToFile(configBuffer, length));
length = sprintf(configBuffer, "\n\nSample rate (Hz) : %d\n", (unsigned int)configSettings->sampleRate / (unsigned int)configSettings->sampleRateDivider);
static char *gainSettings[5] = {"Low", "Low-Medium", "Medium", "Medium-High", "High"};
length += sprintf(configBuffer + length, "Gain : %s\n\n", gainSettings[configSettings->gain]);
length += sprintf(configBuffer + length, "Sleep duration (s) : ");
if (configSettings->disableSleepRecordCycle) {
length += sprintf(configBuffer + length, "-");
} else {
length += sprintf(configBuffer + length, "%d", (unsigned int)configSettings->sleepDuration);
}
length += sprintf(configBuffer + length, "\nRecording duration (s) : ");
if (configSettings->disableSleepRecordCycle) {
length += sprintf(configBuffer + length, "-");
} else {
length += sprintf(configBuffer + length, "%d", (unsigned int)configSettings->recordDuration);
}
RETURN_BOOL_ON_ERROR(AudioMoth_writeToFile(configBuffer, length));
length = sprintf(configBuffer, "\n\nActive recording periods : %d\n", (unsigned int)configSettings->activeStartStopPeriods);
for (uint32_t i = 0; i < configSettings->activeStartStopPeriods; i += 1) {
uint32_t startMinutes = configSettings->startStopPeriods[i].startMinutes;
uint32_t stopMinutes = configSettings->startStopPeriods[i].stopMinutes;
if (i == 0) length += sprintf(configBuffer + length, "\n");
length += sprintf(configBuffer + length, "Recording period %d : %02d:%02d - %02d:%02d (UTC)\n", (unsigned int)i + 1, (unsigned int)startMinutes / 60, (unsigned int)startMinutes % 60, (unsigned int)stopMinutes / 60, (unsigned int)stopMinutes % 60);
}
length += sprintf(configBuffer + length, "\nEarliest recording time : ");
if (configSettings->earliestRecordingTime == 0) {
length += sprintf(configBuffer + length, "---------- --:--:--");
} else {
struct tm *time = gmtime((time_t*)&configSettings->earliestRecordingTime);
length += sprintf(configBuffer + length, "%04d-%02d-%02d %02d:%02d:%02d (UTC)", 1900 + time->tm_year, time->tm_mon + 1, time->tm_mday, time->tm_hour, time->tm_min, time->tm_sec);
}
length += sprintf(configBuffer + length, "\nLatest recording time : ");
if (configSettings->latestRecordingTime == 0) {
length += sprintf(configBuffer + length, "---------- --:--:--");
} else {
struct tm *time = gmtime((time_t*)&configSettings->latestRecordingTime);
length += sprintf(configBuffer + length, "%04d-%02d-%02d %02d:%02d:%02d (UTC)", 1900 + time->tm_year, time->tm_mon + 1, time->tm_mday, time->tm_hour, time->tm_min, time->tm_sec);
}
RETURN_BOOL_ON_ERROR(AudioMoth_writeToFile(configBuffer, length));
length = sprintf(configBuffer, "\n\nFilter : ");
if (configSettings->lowerFilterFreq == 0 && configSettings->higherFilterFreq == 0) {
length += sprintf(configBuffer + length, "-");
} else if (configSettings->lowerFilterFreq == UINT16_MAX) {
length += sprintf(configBuffer + length, "Low-pass (%d.%dkHz)", (unsigned int)configSettings->higherFilterFreq / 10, (unsigned int)configSettings->higherFilterFreq % 10);
} else if (configSettings->higherFilterFreq == UINT16_MAX) {
length += sprintf(configBuffer + length, "High-pass (%d.%dkHz)", (unsigned int)configSettings->lowerFilterFreq / 10, (unsigned int)configSettings->lowerFilterFreq % 10);
} else {
length += sprintf(configBuffer + length, "Band-pass (%d.%dkHz - %d.%dkHz)", (unsigned int)configSettings->lowerFilterFreq / 10, (unsigned int)configSettings->lowerFilterFreq % 10, (unsigned int)configSettings->higherFilterFreq / 10, (unsigned int)configSettings->higherFilterFreq % 10);
}
length += sprintf(configBuffer + length, "\nAmplitude threshold : ");
if (configSettings->amplitudeThreshold == 0) {
length += sprintf(configBuffer + length, "-");
} else {
length += sprintf(configBuffer + length, "%d", (unsigned int)configSettings->amplitudeThreshold);
}
RETURN_BOOL_ON_ERROR(AudioMoth_writeToFile(configBuffer, length));
length = sprintf(configBuffer, "\n\nEnable LED : %s\n", configSettings->enableLED ? "true" : "false");
length += sprintf(configBuffer + length, "Enable low-voltage cutoff : %s\n", configSettings->enableLowVoltageCutoff ? "true" : "false");
length += sprintf(configBuffer + length, "Enable battery level indication : %s\n", configSettings->disableBatteryLevelDisplay ? "false" : "true");
RETURN_BOOL_ON_ERROR(AudioMoth_writeToFile(configBuffer, length));
RETURN_BOOL_ON_ERROR(AudioMoth_closeFile());
return true;
}
/* Backup domain variables */
static uint32_t *previousSwitchPosition = (uint32_t*)AM_BACKUP_DOMAIN_START_ADDRESS;
static uint32_t *timeOfNextRecording = (uint32_t*)(AM_BACKUP_DOMAIN_START_ADDRESS + 4);
static uint32_t *durationOfNextRecording = (uint32_t*)(AM_BACKUP_DOMAIN_START_ADDRESS + 8);
static uint32_t *writtenConfigurationToFile = (uint32_t*)(AM_BACKUP_DOMAIN_START_ADDRESS + 12);
static configSettings_t *configSettings = (configSettings_t*)(AM_BACKUP_DOMAIN_START_ADDRESS + 16);
/* Filter variables */
static AM_filterType_t requestedFilterType;
/* DMA transfer variable */
static uint32_t numberOfSamplesInDMATransfer;
/* SRAM buffer variables */
static volatile uint32_t writeBuffer;
static volatile uint32_t writeBufferIndex;
static int16_t* buffers[NUMBER_OF_BUFFERS];
/* Initial microphone warm-up period settings */
static uint32_t dmaTransfersToSkip;
static volatile uint32_t dmaTransfersProcessed;
/* Compression buffers */
static bool writeIndicator[NUMBER_OF_BUFFERS];
static int16_t compressionBuffer[COMPRESSION_BUFFER_SIZE_IN_BYTES / NUMBER_OF_BYTES_IN_SAMPLE];
/* Recording state */
static volatile bool switchPositionChanged;
/* DMA buffers */
static int16_t primaryBuffer[MAXIMUM_SAMPLES_IN_DMA_TRANSFER];
static int16_t secondaryBuffer[MAXIMUM_SAMPLES_IN_DMA_TRANSFER];
/* Current recording file name */
static char fileName[32];
/* Firmware version and description */
static uint8_t firmwareVersion[AM_FIRMWARE_VERSION_LENGTH] = {1, 4, 4};
static uint8_t firmwareDescription[AM_FIRMWARE_DESCRIPTION_LENGTH] = "AudioMoth-Firmware-Basic";
/* Function prototypes */
static void flashLedToIndicateBatteryLife(void);
static void scheduleRecording(uint32_t currentTime, uint32_t *timeOfNextRecording, uint32_t *durationOfNextRecording);
static AM_recordingState_t makeRecording(uint32_t currentTime, uint32_t recordDuration, bool enableLED, AM_extendedBatteryState_t extendedBatteryState, int32_t temperature);
/* Functions of copy to and from the backup domain */
static void copyFromBackupDomain(uint8_t *dst, uint32_t *src, uint32_t length) {
for (uint32_t i = 0; i < length; i += 1) {
*(dst + i) = *((uint8_t*)src + i);
}
}
static void copyToBackupDomain(uint32_t *dst, uint8_t *src, uint32_t length) {
uint32_t value = 0;
for (uint32_t i = 0; i < length / UINT32_SIZE_IN_BYTES; i += 1) {
*(dst + i) = *((uint32_t*)src + i);
}
for (uint32_t i = 0; i < length % UINT32_SIZE_IN_BYTES; i += 1) {
value = (value << BITS_PER_BYTE) + *(src + length - 1 - i);
}
*(dst + length / UINT32_SIZE_IN_BYTES) = value;
}
/* Main function */
int main(void) {
/* Initialise device */
AudioMoth_initialise();
AM_switchPosition_t switchPosition = AudioMoth_getSwitchPosition();
if (AudioMoth_isInitialPowerUp()) {
*timeOfNextRecording = 0;
*durationOfNextRecording = 0;
*writtenConfigurationToFile = false;
*previousSwitchPosition = AM_SWITCH_NONE;
copyToBackupDomain((uint32_t*)configSettings, (uint8_t*)&defaultConfigSettings, sizeof(configSettings_t));
} else {
/* Indicate battery state is not initial power up and switch has been moved into USB if enabled */
if (switchPosition != *previousSwitchPosition && switchPosition == AM_SWITCH_USB && !configSettings->disableBatteryLevelDisplay) {
flashLedToIndicateBatteryLife();
}
}
/* Handle the case that the switch is in USB position */
if (switchPosition == AM_SWITCH_USB) {
AudioMoth_handleUSB();
SAVE_SWITCH_POSITION_AND_POWER_DOWN(DEFAULT_WAIT_INTERVAL);
}
/* Handle the case that the switch is in CUSTOM position but the time has not been set or their are no active recording periods */
if (switchPosition == AM_SWITCH_CUSTOM && (AudioMoth_hasTimeBeenSet() == false || configSettings->activeStartStopPeriods == 0)) {
FLASH_LED(Both, SHORT_LED_FLASH_DURATION)
SAVE_SWITCH_POSITION_AND_POWER_DOWN(DEFAULT_WAIT_INTERVAL);
}
/* Calculate time of next recording if switch has changed position */
uint32_t currentTime;
bool fileSystemEnabled = false;
bool writtenConfigurationToFileInThisSession = false;
AudioMoth_getTime(¤tTime, NULL);
if (switchPosition != *previousSwitchPosition) {
/* Reset persistent configuration write flag */
*writtenConfigurationToFile = false;
/* Try to write configuration to file */
if (!fileSystemEnabled) fileSystemEnabled = AudioMoth_enableFileSystem();
if (fileSystemEnabled) writtenConfigurationToFileInThisSession = writeConfigurationToFile(configSettings, firmwareDescription, firmwareVersion, (uint8_t*)AM_UNIQUE_ID_START_ADDRESS);
/* Schedule the next recording */
if (switchPosition == AM_SWITCH_CUSTOM) {
scheduleRecording(currentTime, timeOfNextRecording, durationOfNextRecording);
}
/* Set parameters to start recording now */
if (switchPosition == AM_SWITCH_DEFAULT) {
*timeOfNextRecording = currentTime;
*durationOfNextRecording = UINT32_MAX;
}
}
/* Make recording if appropriate */
bool enableLED = (switchPosition == AM_SWITCH_DEFAULT) || configSettings->enableLED;
if (currentTime >= *timeOfNextRecording) {
/* Write configuration if not already done so */
if (!writtenConfigurationToFileInThisSession && *writtenConfigurationToFile == false) {
if (!fileSystemEnabled) fileSystemEnabled = AudioMoth_enableFileSystem();
if (fileSystemEnabled) *writtenConfigurationToFile = writeConfigurationToFile(configSettings, firmwareDescription, firmwareVersion, (uint8_t*)AM_UNIQUE_ID_START_ADDRESS);
}
/* Reduce the recording duration if necessary */
if (switchPosition == AM_SWITCH_CUSTOM) {
uint32_t missedSeconds = MIN(currentTime - *timeOfNextRecording, *durationOfNextRecording);
*durationOfNextRecording -= missedSeconds;
}
/* Make the recording */
AM_recordingState_t recordingState = RECORDING_OKAY;
if (*durationOfNextRecording > 0) {
/* Measure battery voltage */
uint32_t supplyVoltage = AudioMoth_getSupplyVoltage();
AM_extendedBatteryState_t extendedBatteryState = AudioMoth_getExtendedBatteryState(supplyVoltage);
/* Check if low voltage check is enabled and that the voltage is okay */
bool okayToMakeRecording = true;
if (configSettings->enableLowVoltageCutoff) {
AudioMoth_enableSupplyMonitor();
AudioMoth_setSupplyMonitorThreshold(MINIMUM_SUPPLY_VOLTAGE);
okayToMakeRecording = AudioMoth_isSupplyAboveThreshold();
}
/* Make recording if okay */
if (okayToMakeRecording) {
AudioMoth_enableTemperature();
int32_t temperature = AudioMoth_getTemperature();
AudioMoth_disableTemperature();
if (!fileSystemEnabled) fileSystemEnabled = AudioMoth_enableFileSystem();
if (fileSystemEnabled) {
recordingState = makeRecording(currentTime, *durationOfNextRecording, enableLED, extendedBatteryState, temperature);
} else {
FLASH_LED(Both, LONG_LED_FLASH_DURATION);
recordingState = SDCARD_WRITE_ERROR;
}
} else {
if (enableLED) FLASH_LED(Both, LONG_LED_FLASH_DURATION);
recordingState = SUPPLY_VOLTAGE_LOW;
}
/* Disable low voltage monitor if it was used */
if (configSettings->enableLowVoltageCutoff) AudioMoth_disableSupplyMonitor();
}
/* Schedule next recording if recording did not end early due to the file size limit (otherwise restart immediately) */
if (switchPosition == AM_SWITCH_CUSTOM && recordingState != FILE_SIZE_LIMITED) {
scheduleRecording(currentTime + *durationOfNextRecording, timeOfNextRecording, durationOfNextRecording);
}
/* Use longer power-down period if recording did not end normally or early due to the file size limit (otherwise restart immediately) */
if (switchPosition == AM_SWITCH_DEFAULT && (recordingState == SUPPLY_VOLTAGE_LOW || recordingState == SWITCH_CHANGED || recordingState == SDCARD_WRITE_ERROR)) {
SAVE_SWITCH_POSITION_AND_POWER_DOWN(DEFAULT_WAIT_INTERVAL);
}
} else if (enableLED) {
/* Flash LED to indicate waiting */
FLASH_LED(Green, WAITING_LED_FLASH_DURATION);
}
/* Determine how long to power down */
uint32_t secondsToSleep = 0;
if (*timeOfNextRecording > currentTime) {
secondsToSleep = MIN(*timeOfNextRecording - currentTime, WAITING_LED_FLASH_INTERVAL);
}
/* Power down */
SAVE_SWITCH_POSITION_AND_POWER_DOWN(secondsToSleep);
}
/* Time zone handler */
inline void AudioMoth_timezoneRequested(int8_t *timezoneHours, int8_t *timezoneMinutes) {
*timezoneHours = configSettings->timezoneHours;
*timezoneMinutes = configSettings->timezoneMinutes;
}
/* AudioMoth interrupt handlers */
inline void AudioMoth_handleSwitchInterrupt() {
switchPositionChanged = true;
}
inline void AudioMoth_handleMicrophoneInterrupt(int16_t sample) { }
inline void AudioMoth_handleDirectMemoryAccessInterrupt(bool isPrimaryBuffer, int16_t **nextBuffer) {
int16_t *source = secondaryBuffer;
if (isPrimaryBuffer) source = primaryBuffer;
/* Update the current buffer index and write buffer */
bool thresholdExceeded = DigitalFilter_filter(source, buffers[writeBuffer] + writeBufferIndex, configSettings->sampleRateDivider, numberOfSamplesInDMATransfer, configSettings->amplitudeThreshold);
if (dmaTransfersProcessed > dmaTransfersToSkip) {
writeIndicator[writeBuffer] |= thresholdExceeded;
writeBufferIndex += numberOfSamplesInDMATransfer / configSettings->sampleRateDivider;
if (writeBufferIndex == NUMBER_OF_SAMPLES_IN_BUFFER) {
writeBufferIndex = 0;
writeBuffer = (writeBuffer + 1) & (NUMBER_OF_BUFFERS - 1);
writeIndicator[writeBuffer] = false;
}
}
dmaTransfersProcessed += 1;
}
/* AudioMoth USB message handlers */
inline void AudioMoth_usbFirmwareVersionRequested(uint8_t **firmwareVersionPtr) {
*firmwareVersionPtr = firmwareVersion;
}
inline void AudioMoth_usbFirmwareDescriptionRequested(uint8_t **firmwareDescriptionPtr) {
*firmwareDescriptionPtr = firmwareDescription;
}
inline void AudioMoth_usbApplicationPacketRequested(uint32_t messageType, uint8_t *transmitBuffer, uint32_t size) {
/* Copy the current time to the USB packet */
uint32_t currentTime;
AudioMoth_getTime(¤tTime, NULL);
memcpy(transmitBuffer + 1, ¤tTime, UINT32_SIZE_IN_BYTES);
/* Copy the unique ID to the USB packet */
memcpy(transmitBuffer + 5, (uint8_t*)AM_UNIQUE_ID_START_ADDRESS, AM_UNIQUE_ID_SIZE_IN_BYTES);
/* Copy the battery state to the USB packet */
uint32_t supplyVoltage = AudioMoth_getSupplyVoltage();
AM_batteryState_t batteryState = AudioMoth_getBatteryState(supplyVoltage);
memcpy(transmitBuffer + 5 + AM_UNIQUE_ID_SIZE_IN_BYTES, &batteryState, 1);
/* Copy the firmware version to the USB packet */
memcpy(transmitBuffer + 6 + AM_UNIQUE_ID_SIZE_IN_BYTES, firmwareVersion, AM_FIRMWARE_VERSION_LENGTH);
/* Copy the firmware description to the USB packet */
memcpy(transmitBuffer + 6 + AM_UNIQUE_ID_SIZE_IN_BYTES + AM_FIRMWARE_VERSION_LENGTH, firmwareDescription, AM_FIRMWARE_DESCRIPTION_LENGTH);
}
inline void AudioMoth_usbApplicationPacketReceived(uint32_t messageType, uint8_t* receiveBuffer, uint8_t *transmitBuffer, uint32_t size) {
/* Copy the USB packet contents to the back-up register data structure location */
copyToBackupDomain((uint32_t*)configSettings, receiveBuffer + 1, sizeof(configSettings_t));
/* Copy the back-up register data structure to the USB packet */
copyFromBackupDomain(transmitBuffer + 1, (uint32_t*)configSettings, sizeof(configSettings_t));
/* Set the time */
AudioMoth_setTime(configSettings->time, 0);
}
/* Encode the compression buffer */
static void encodeCompressionBuffer(uint32_t numberOfCompressedBuffers) {
for (uint32_t i = 0; i < UINT32_SIZE_IN_BITS; i += 1) {
compressionBuffer[i] = numberOfCompressedBuffers & 0x01 ? 1 : -1;
numberOfCompressedBuffers >>= 1;
}
for (uint32_t i = UINT32_SIZE_IN_BITS; i < COMPRESSION_BUFFER_SIZE_IN_BYTES / NUMBER_OF_BYTES_IN_SAMPLE; i += 1) {
compressionBuffer[i] = 0;
}
}
/* Save recording to SD card */
static AM_recordingState_t makeRecording(uint32_t currentTime, uint32_t recordDuration, bool enableLED, AM_extendedBatteryState_t extendedBatteryState, int32_t temperature) {
/* Initialise buffers */
writeBuffer = 0;
writeBufferIndex = 0;
buffers[0] = (int16_t*)AM_EXTERNAL_SRAM_START_ADDRESS;
for (uint32_t i = 1; i < NUMBER_OF_BUFFERS; i += 1) {
buffers[i] = buffers[i - 1] + NUMBER_OF_SAMPLES_IN_BUFFER;
}