-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.c
2629 lines (2278 loc) · 80.7 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
/*
Copyright 2019 Benjamin Vedder [email protected]
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdint.h>
#include <string.h>
#include <math.h>
#include <stdarg.h>
#include <stdio.h>
#include "nrf_fstorage.h"
#include "nrf_drv_qspi.h"
#include "nrf_drv_spi.h"
#include "nordic_common.h"
#include "nrf.h"
#include "ble_hci.h"
#include "ble_advdata.h"
#include "ble_advertising.h"
#include "ble_conn_params.h"
#include "nrf_sdh.h"
#include "nrf_sdh_soc.h"
#include "nrf_sdh_ble.h"
#include "nrf_ble_gatt.h"
#include "nrf_ble_qwr.h"
#include "app_timer.h"
#include "ble_fus.h"
#include "app_uart.h"
#include "gps_uart.h"
#include "app_util_platform.h"
#include "nrf_pwr_mgmt.h"
#include "bsp_btn_ble.h"
#include "nrf_delay.h"
#include "bsp.h"
#include "security_manager.h"
#if defined (UART_PRESENT)
#include "nrf_uart.h"
#endif
#if defined (UARTE_PRESENT)
#include "nrf_uarte.h"
#endif
#define BIT(x) 1<<x
#ifdef ENABLE_USBD
#include "app_usbd_core.h"
#include "app_usbd.h"
#include "app_usbd_string_desc.h"
#include "app_usbd_cdc_acm.h"
#include "app_usbd_serial_num.h"
#include "nrf_drv_power.h"
#include "nrf_drv_usbd.h"
#include "nrf_drv_clock.h"
#endif
#include "packet.h"
#include "buffer.h"
#include "datatypes.h"
#include "crc.h"
#include "nrf_log.h"
#include "nrf_log_ctrl.h"
#include "nrf_log_default_backends.h"
#include "command_interface.h"
#include <time.h>
#include "nrf_drv_twi.h"
const nrf_drv_twi_t m_twi_master = NRF_DRV_TWI_INSTANCE(0);
#include "lwgps/lwgps.h"
#include "minigame.h"
////////////////////////////////////////
// GPS handle
////////////////////////////////////////
lwgps_t hgps;
static LOG_GPS log_message_gps;
static LOG_GPS_DELTA log_message_gps_delta;
static LOG_FREESK8 log_message_freesk8;
////////////////////////////////////////
// Button input
////////////////////////////////////////
#include "button_input.h"
////////////////////////////////////////
// ESC data
////////////////////////////////////////
static TELEMETRY_DATA esc_telemetry;
static volatile int esc_rx_cnt = 0;
static LOG_ESC log_message_esc;
static LOG_ESC_DELTA log_message_esc_delta;
static LOG_HEADER log_message_header;
////////////////////////////////////////
// Display
////////////////////////////////////////
#if HAS_DISPLAY
static volatile bool update_display = false; // Set to true to trigger I2C communication with OLED
static char display_text_buffer[32] = {0};
#include "SSD1306.h"
#include "Adafruit_GFX.h"
void i2c_oled_comm_handle(uint8_t hdl_address, uint8_t *hdl_buffer, size_t hdl_buffer_size)
{
nrf_drv_twi_tx(&m_twi_master, hdl_address, hdl_buffer, hdl_buffer_size, false);
}
#endif
////////////////////////////////////////
// Time/Event tracking
////////////////////////////////////////
#include "rtc.h"
volatile bool update_rtc = false; // Set to true to trigger I2C communication with RTC module
volatile bool rtc_time_has_sync = false; // Set to true when the RTC has been set by GPS or Mobile app
static struct tm * tmTime;
struct tm gpsTime; // Time received from GPS
static time_t currentTime; // Current time of the Robogotchi
static time_t timeSyncTime; // New time from GPS to be set during timeSync event
static time_t fileSystemSyncTime; // The last time the filesystem performed a sync to QSPI
static char datetimestring[ 64 ] = { 0 };
volatile bool log_file_active = false;
static volatile bool write_logdata_now = false;
static volatile bool gps_signal_locked = false;
static time_t time_esc_last_responded; // For triggering TX and RX pin swapping
static time_t time_gps_last_responded; // For detecting stale data
volatile bool write_gps_now = false;
volatile bool write_gps_delta_now = false;
volatile bool write_time_sync_now = false;
void update_time(int syear, int smonth, int sday, int shour, int sminute, int ssecond)
{
tmTime->tm_year = syear - 1900;
tmTime->tm_mon = smonth - 1;
tmTime->tm_mday = sday;
tmTime->tm_hour = shour;
tmTime->tm_min = sminute;
tmTime->tm_sec = ssecond;
currentTime = mktime(tmTime);
time_esc_last_responded = currentTime;
time_gps_last_responded = currentTime;
}
////////////////////////////////////////
// Fault tracking
////////////////////////////////////////
struct esc_fault {
uint8_t fault_code;
uint16_t fault_count;
uint16_t esc_id;
time_t dt_first_seen;
time_t dt_last_seen;
};
static uint16_t fault_count = 0; // Count of messages containing fault codes
#define RECENT_FAULT_LIMIT 12 // Limit the fault code historical array
static uint8_t recent_fault_index = 0; // Track current index of historical array
static struct esc_fault recent_faults[RECENT_FAULT_LIMIT] = {0}; // Historical array of faults
////////////////////////////////////////
// Piezo
////////////////////////////////////////
#include "buzzer/nrf_pwm.h"
#include "buzzer/melody_notes.h"
#define PIN_PIEZO 8
int melody_notes=0;
int melody_wholenote = 0;
int melody_divider = 0;
int melody_note_duration = 0;
int melody_this_note = 0;
bool is_melody_playing = false;
bool is_melody_playing_pause = false;
uint32_t melody_next_note = 0;
int *melody;
int melody_last_alert_index = MELODY_NONE;
uint16_t melody_snooze_seconds = 0;
uint32_t app_timer_ms(uint32_t ticks)
{
// eg. (7 + 1) * 1000 / 32768
// = 8000 / 32768
// = 0.24414062
float numerator = ((float)0/*TODO: APP_TIMER_PRESCALER*/ + 1.0f) * 1000.0f;
float denominator = (float)APP_TIMER_CLOCK_FREQ;
float ms_per_tick = numerator / denominator;
uint32_t ms = ms_per_tick * ticks;
return ms;
}
uint32_t millis(void)
{
return app_timer_ms(app_timer_cnt_get());
}
void melody_play(int index, bool interrupt_melody)
{
if ((is_melody_playing && !interrupt_melody) || melody_snooze_seconds > 0)
{
return;
}
switch (index)
{
case MELODY_GOTCHI_FAULT:
melody = (int*)&melody_gotchi_fault;
// sizeof gives the number of bytes, each int value is composed of two bytes (16 bits)
// there are two values per note (pitch and duration), so for each note there are four bytes
melody_notes=sizeof(melody_gotchi_fault)/sizeof(melody_gotchi_fault[0])/2;
// this calculates the duration of a whole note in ms (60s/tempo)*4 beats
melody_wholenote = (60000 * 4) / tempo_gotchi_fault;
melody_last_alert_index = MELODY_GOTCHI_FAULT;
break;
case MELODY_ESC_FAULT:
melody = (int*)&melody_esc_fault;
melody_notes=sizeof(melody_esc_fault)/sizeof(melody_esc_fault[0])/2;
melody_wholenote = (60000 * 4) / tempo_esc_fault;
melody_last_alert_index = MELODY_ESC_FAULT;
break;
case MELODY_BLE_FAIL:
melody = (int*)&melody_ble_fail;
melody_notes=sizeof(melody_ble_fail)/sizeof(melody_ble_fail[0])/2;
melody_wholenote = (60000 * 4) / tempo_ble_fail;
break;
case MELODY_BLE_SUCCESS:
melody = (int*)&melody_ble_success;
melody_notes=sizeof(melody_ble_success)/sizeof(melody_ble_success[0])/2;
melody_wholenote = (60000 * 4) / tempo_ble_success;
break;
case MELODY_STORAGE_LIMIT:
melody = (int*)&melody_storage_limit;
melody_notes=sizeof(melody_storage_limit)/sizeof(melody_storage_limit[0])/2;
melody_wholenote = (60000 * 4) / tempo_storage_limit;
melody_last_alert_index = MELODY_STORAGE_LIMIT;
break;
case MELODY_ESC_TEMP:
melody = (int*)&melody_esc_temp;
melody_notes=sizeof(melody_esc_temp)/sizeof(melody_esc_temp[0])/2;
melody_wholenote = (60000 * 4) / tempo_esc_temp;
melody_last_alert_index = MELODY_ESC_TEMP;
break;
case MELODY_MOTOR_TEMP:
melody = (int*)&melody_motor_temp;
melody_notes=sizeof(melody_motor_temp)/sizeof(melody_motor_temp[0])/2;
melody_wholenote = (60000 * 4) / tempo_motor_temp;
melody_last_alert_index = MELODY_MOTOR_TEMP;
break;
case MELODY_VOLTAGE_LOW:
melody = (int*)&melody_voltage_low;
melody_notes=sizeof(melody_voltage_low)/sizeof(melody_voltage_low[0])/2;
melody_wholenote = (60000 * 4) / tempo_voltage_low;
melody_last_alert_index = MELODY_VOLTAGE_LOW;
break;
case MELODY_LOG_START:
melody = (int*)&melody_ascending;
melody_notes=sizeof(melody_ascending)/sizeof(melody_ascending[0])/2;
melody_wholenote = (60000 * 4) / tempo_ascending;
break;
case MELODY_LOG_STOP:
melody = (int*)&melody_descending;
melody_notes=sizeof(melody_descending)/sizeof(melody_descending[0])/2;
melody_wholenote = (60000 * 4) / tempo_descending;
break;
case MELODY_STARTUP:
melody = (int*)&melody_startup;
melody_notes=sizeof(melody_startup)/sizeof(melody_startup[0])/2;
melody_wholenote = (60000 * 4) / tempo_startup;
break;
case MELODY_GPS_LOCK:
melody = (int*)&melody_gps_locked;
melody_notes=sizeof(melody_gps_locked)/sizeof(melody_gps_locked[0])/2;
melody_wholenote = (60000 * 4) / tempo_gps_locked;
break;
case MELODY_GPS_LOST:
melody = (int*)&melody_gps_lost;
melody_notes=sizeof(melody_gps_lost)/sizeof(melody_gps_lost[0])/2;
melody_wholenote = (60000 * 4) / tempo_gps_lost;
break;
default:
//TODO: add default melody
break;
}
melody_divider = 0;
melody_note_duration = 0;
melody_this_note = 0; // Play from the beginning
is_melody_playing = true;
is_melody_playing_pause = false;
melody_next_note = millis();
nrf_pwm_set_enabled(true);
}
void melody_step(void)
{
if (is_melody_playing)
{
// Check if we've reached the end or the user pressed button 2
// to stop the melody
if ((melody_this_note >= melody_notes *2) || isButton2Pressed)
{
melody_this_note = 0;
is_melody_playing = false;
nrf_pwm_set_enabled(false);
NRF_LOG_INFO("end of melody");
NRF_LOG_FLUSH();
return;
}
// Check if it's time to play the next note
uint32_t now = millis();
if (now >= melody_next_note)
{
// calculates the duration of each note
melody_divider = melody[melody_this_note + 1];
if (melody_divider > 0) {
// regular note, just proceed
melody_note_duration = (melody_wholenote) / melody_divider;
} else if (melody_divider < 0) {
// dotted notes are represented with negative durations!!
melody_note_duration = (melody_wholenote) / abs(melody_divider);
melody_note_duration *= 1.5; // increases the duration in half for dotted notes
}
if (is_melody_playing_pause)
{
// stop the waveform generation before the next note.
set_frequency_and_duty_cycle((uint32_t)(melody[melody_this_note]), 0);
melody_next_note = now + (melody_note_duration * 0.1);
is_melody_playing_pause = false; // Set to false so we play a note on the next step
melody_this_note += 2; // Increment current note by 1 (note + duration)
}
else
{
// we only play the note for 90% of the duration, leaving 10% as a pause
set_frequency_and_duty_cycle((uint32_t)(melody[melody_this_note]), 45);
melody_next_note = now + (melody_note_duration * 0.9);
is_melody_playing_pause = true; // Set to true so we pause on the next step
}
}
}
else
{
//TODO: This should not be necessary but a steady tone
// seems to happen in some situations.
//TODO: This is not a patch and not the best solution
nrf_pwm_set_enabled(false);
}
}
void buzzer_init(void)
{
nrf_pwm_config_t pwm_config =
{.num_channels = 1,
.gpio_num = {PIN_PIEZO},
.ppi_channel = {0,1,2,3,4,5},
.gpiote_channel = {0,1},
.mode = PWM_MODE_BUZZER_255};
nrf_pwm_init(&pwm_config);
}
////////////////////////////////////////
//LITTLEFS
////////////////////////////////////////
volatile bool sync_in_progress = false;
time_t lastTimeBoardMoved = 0;
int log_file_stop();
void log_file_start();
uint32_t boot_count = 0;
#include "lfs.h"
int qspi_read(const struct lfs_config *c, lfs_block_t block,
lfs_off_t off, void *buffer, lfs_size_t size)
{
uint32_t addr = c->block_size * block + off;
uint32_t err_code = nrf_drv_qspi_read((uint8_t*)buffer, size, addr);
return err_code;
}
int qspi_prog(const struct lfs_config *c, lfs_block_t block,
lfs_off_t off, const void *buffer, lfs_size_t size)
{
uint32_t addr = c->block_size * block + off;
uint32_t err_code = nrf_drv_qspi_write((uint8_t*)buffer, size, addr);
APP_ERROR_CHECK(err_code);
return err_code;
}
int qspi_erase(const struct lfs_config *c, lfs_block_t block)
{
uint32_t addr = c->block_size * block;
uint32_t err_code = nrf_drv_qspi_erase(NRF_QSPI_ERASE_LEN_4KB, addr);
APP_ERROR_CHECK(err_code);
return err_code;
}
int qspi_sync(const struct lfs_config *c)
{
return LFS_ERR_OK;
}
// variables used by the filesystem
uint16_t lfs_file_count = 0;
static lfs_t lfs;
static lfs_file_t file;
static uint8_t lfs_read_buf[4096]; // Must be cache_size
static uint8_t lfs_prog_buf[4096]; // Must be cache_size
static uint8_t lfs_lookahead_buf[4096]; // 128/8=16
static uint8_t lfs_file_buf[4096]; // Must be cache size
static struct lfs_file_config lfs_file_config;
// configuration of the filesystem is provided by this struct
const struct lfs_config cfg = {
// block device operations
.read = &qspi_read,
.prog = &qspi_prog,
.erase = &qspi_erase,
.sync = &qspi_sync,
// block device configuration
.read_size = 4,
.prog_size = 4,
.block_size = 4096,
.block_count = 8192, //4096 bytes/block @ 256Mbit (33554432 bytes) = 8192 blocks
.cache_size = 4096,
.lookahead_size = 4096,
.block_cycles = 500,
.read_buffer = lfs_read_buf,
.prog_buffer = lfs_prog_buf,
.lookahead_buffer = lfs_lookahead_buf,
};
////////////////////////////////////////
// User configuration
////////////////////////////////////////
void user_cfg_set(bool restart_telemetry_timer);
void user_cfg_get(void);
#include "user_cfg.h"
static int multiESCIndex = 0;
const struct gotchi_configuration gotchi_cfg_default = {
.log_auto_stop_idle_time = 300,
.log_auto_stop_low_voltage = 20.0,
.log_auto_start_erpm = 2000,
.log_interval_hz = 1,
.log_auto_erase_when_full = 0,
.multi_esc_mode = 0,
.multi_esc_ids = {0,0,0,0},
.gps_baud_rate = NRF_UARTE_BAUDRATE_9600,
.alert_low_voltage = 0.0,
.alert_esc_temp = 0.0,
.alert_motor_temp = 0.0,
.alert_storage_at_capacity = 0,
.timezone_hour_offset = 0,
.timezone_minute_offset = 0,
.cfg_version = 4 // Expected configuration version, increment with changes to struct
};
struct gotchi_configuration gotchi_cfg_user = {
.log_auto_stop_idle_time = 300,
.log_auto_stop_low_voltage = 20.0,
.log_auto_start_erpm = 2000,
.log_interval_hz = 1,
.log_auto_erase_when_full = 0,
.multi_esc_mode = 0,
.multi_esc_ids = {0,0,0,0},
.gps_baud_rate = NRF_UARTE_BAUDRATE_9600,
.alert_low_voltage = 0.0,
.alert_esc_temp = 0.0,
.alert_motor_temp = 0.0,
.alert_storage_at_capacity = 0,
.timezone_hour_offset = 0,
.timezone_minute_offset = 0,
.cfg_version = 0
};
////////////////////////////////////////
// Tracking free space
////////////////////////////////////////
static volatile int lfs_percent_free = 0;
uint8_t lfs_free_space_check(void)
{
//TODO: when shit goes wrong this returns -84
//<info> app: FS Blocks Allocated: -84
int lfs_blocks_allocated = lfs_fs_size(&lfs);
if (lfs_blocks_allocated == LFS_ERR_CORRUPT) {
melody_play(MELODY_GOTCHI_FAULT, true); // Play robogotchi fault, interrupt
}
lfs_percent_free = 100 - (int)((double)lfs_blocks_allocated / (double)cfg.block_count * 100);
NRF_LOG_INFO("FS Blocks Allocated: %ld", lfs_blocks_allocated);
NRF_LOG_INFO("FS BlockCount: %d Percentage Free: %d", cfg.block_count, lfs_percent_free);
NRF_LOG_FLUSH();
#if HAS_DISPLAY
snprintf(display_text_buffer,4,"%02d%%", lfs_percent_free);
Adafruit_GFX_print(display_text_buffer, 88, 16);
update_display = true;
#endif
if (gotchi_cfg_user.alert_storage_at_capacity != 0 && 100 - lfs_percent_free >= gotchi_cfg_user.alert_storage_at_capacity)
{
melody_play(MELODY_STORAGE_LIMIT, false); // Play storage at capacity alert, do not interrupt
}
return lfs_percent_free;
}
////////////////////////////////////////////////////////////
// Everything that once was but has been heavily modified
////////////////////////////////////////////////////////////
#ifndef MODULE_BUILTIN
#define MODULE_BUILTIN 0
#endif
#ifndef MODULE_FREESK8
#define MODULE_FREESK8 1
#endif
#define APP_BLE_CONN_CFG_TAG 1 /**< A tag identifying the SoftDevice BLE configuration. */
#ifdef NRF52840_XXAA
#if MODULE_BUILTIN
#define DEVICE_NAME "FreeSK8 Receiver"
#elif defined(MODULE_FREESK8)
#define DEVICE_NAME "FreeSK8 Robogotchi"
#else
#define DEVICE_NAME "VESC 52840 UART"
#endif
#else
#if MODULE_BUILTIN
#define DEVICE_NAME "VESC 52832 BUILTIN"
#else
#define DEVICE_NAME "VESC 52832 UART"
#endif
#endif
#define FUS_SERVICE_UUID_TYPE BLE_UUID_TYPE_VENDOR_BEGIN /**< UUID type for the FreeSK8 UART Service (vendor specific). */
#define APP_BLE_OBSERVER_PRIO 3 /**< Application's BLE observer priority. You shouldn't need to modify this value. */
#define APP_ADV_INTERVAL 64 /**< The advertising interval (in units of 0.625 ms. This value corresponds to 40 ms). */
#define APP_ADV_DURATION 18000 /**< The advertising duration (180 seconds) in units of 10 milliseconds. */
#define MIN_CONN_INTERVAL MSEC_TO_UNITS(7.5, UNIT_1_25_MS) /**< Minimum acceptable connection interval (20 ms), Connection interval uses 1.25 ms units. */
#define MAX_CONN_INTERVAL MSEC_TO_UNITS(35, UNIT_1_25_MS) /**< Maximum acceptable connection interval (75 ms), Connection interval uses 1.25 ms units. */
#define SLAVE_LATENCY 0 /**< Slave latency. */
#define CONN_SUP_TIMEOUT MSEC_TO_UNITS(4000, UNIT_10_MS) /**< Connection supervisory timeout (4 seconds), Supervision Timeout uses 10 ms units. */
#define FIRST_CONN_PARAMS_UPDATE_DELAY APP_TIMER_TICKS(5000) /**< Time from initiating event (connect or start of notification) to first time sd_ble_gap_conn_param_update is called (5 seconds). */
#define NEXT_CONN_PARAMS_UPDATE_DELAY APP_TIMER_TICKS(30000) /**< Time between each call to sd_ble_gap_conn_param_update after the first call (30 seconds). */
#define MAX_CONN_PARAMS_UPDATE_COUNT 3 /**< Number of attempts before giving up the connection parameter negotiation. */
#define DEAD_BEEF 0xDEADBEEF /**< Value used as error code on stack dump, can be used to identify stack location on stack unwind. */
#ifdef NRF52840_XXAA
#define UART_TX_BUF_SIZE 1024
#define UART_RX_BUF_SIZE 1024
#else
#error Gurl, whatchu doing?
#endif
#define PACKET_VESC 0
#define PACKET_BLE 1
#ifdef NRF52840_XXAA
#if MODULE_BUILTIN
#define UART_RX 26
#define UART_TX 25
#define LED_PIN 27
#elif defined(MODULE_FREESK8)
#define UART_RX 6
#define UART_TX 7
#define LED_PIN 5
#else
#error Define MODULE_FREESK8 or MODULE_BUILTIN
#endif
#else
#error Firmware is deisnged for 52840_XXAA
#endif
// Private variables
APP_TIMER_DEF(m_packet_timer);
APP_TIMER_DEF(m_logging_timer);
APP_TIMER_DEF(m_telemetry_timer);
BLE_FUS_DEF(m_fus, NRF_SDH_BLE_TOTAL_LINK_COUNT); /**< BLE FUS service instance. */
NRF_BLE_GATT_DEF(m_gatt); /**< GATT module instance. */
NRF_BLE_QWR_DEF(m_qwr); /**< Context for the Queued Write module.*/
BLE_ADVERTISING_DEF(m_advertising); /**< Advertising module instance. */
static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; /**< Handle of the current connection. */
uint16_t m_ble_fus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - 3; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
static ble_uuid_t m_adv_uuids[] = /**< Universally unique service identifier. */
{
{BLE_UUID_FUS_SERVICE, FUS_SERVICE_UUID_TYPE}
};
static volatile bool m_is_enabled = true;
static volatile bool m_uart_error = false;
static volatile int m_other_comm_disable_time = 0;
app_uart_comm_params_t m_uart_comm_params =
{
.rx_pin_no = UART_RX,
.tx_pin_no = UART_TX,
.rts_pin_no = 0,
.cts_pin_no = 0,
.flow_control = APP_UART_FLOW_CONTROL_DISABLED,
.use_parity = false,
.baud_rate = NRF_UARTE_BAUDRATE_115200
};
gps_uart_comm_params_t m_gpsuart_comm_params =
{
.rx_pin_no = 2,
.tx_pin_no = 3,
.rts_pin_no = 0,
.cts_pin_no = 0,
.flow_control = GPS_UART_FLOW_CONTROL_DISABLED,
.use_parity = false,
.baud_rate = NRF_UARTE_BAUDRATE_4800
};
// Functions
void ble_printf(const char* format, ...);
#ifdef ENABLE_USBD
static void cdc_acm_user_ev_handler(app_usbd_class_inst_t const * p_inst,
app_usbd_cdc_acm_user_event_t event);
#define CDC_ACM_COMM_INTERFACE 0
#define CDC_ACM_COMM_EPIN NRF_DRV_USBD_EPIN2
#define CDC_ACM_DATA_INTERFACE 1
#define CDC_ACM_DATA_EPIN NRF_DRV_USBD_EPIN1
#define CDC_ACM_DATA_EPOUT NRF_DRV_USBD_EPOUT1
/**
* @brief CDC_ACM class instance
* */
APP_USBD_CDC_ACM_GLOBAL_DEF(m_app_cdc_acm,
cdc_acm_user_ev_handler,
CDC_ACM_COMM_INTERFACE,
CDC_ACM_DATA_INTERFACE,
CDC_ACM_COMM_EPIN,
CDC_ACM_DATA_EPIN,
CDC_ACM_DATA_EPOUT,
APP_USBD_CDC_COMM_PROTOCOL_NONE
);
static void cdc_acm_user_ev_handler(app_usbd_class_inst_t const * p_inst, app_usbd_cdc_acm_user_event_t event) {
switch (event) {
case APP_USBD_CDC_ACM_USER_EVT_PORT_OPEN: {
// nrf_gpio_pin_set(LED_PIN);
// Setup first transfer
char rx;
app_usbd_cdc_acm_read(&m_app_cdc_acm, &rx, 1);
break;
}
case APP_USBD_CDC_ACM_USER_EVT_PORT_CLOSE:
// nrf_gpio_pin_clear(LED_PIN);
break;
case APP_USBD_CDC_ACM_USER_EVT_TX_DONE:
break;
case APP_USBD_CDC_ACM_USER_EVT_RX_DONE: {
ret_code_t ret;
char rx;
do {
ret = app_usbd_cdc_acm_read(&m_app_cdc_acm, &rx, 1);
} while (ret == NRF_SUCCESS);
break;
}
default:
break;
}
}
static void usbd_user_ev_handler(app_usbd_event_type_t event) {
switch (event) {
case APP_USBD_EVT_DRV_SUSPEND:
break;
case APP_USBD_EVT_DRV_RESUME:
break;
case APP_USBD_EVT_STARTED:
break;
case APP_USBD_EVT_STOPPED:
app_usbd_disable();
break;
case APP_USBD_EVT_POWER_DETECTED:
if (!nrf_drv_usbd_is_enabled()) {
app_usbd_enable();
}
break;
case APP_USBD_EVT_POWER_REMOVED:
app_usbd_stop();
break;
case APP_USBD_EVT_POWER_READY:
app_usbd_start();
break;
default:
break;
}
}
#endif
/**@brief Function for assert macro callback.
*
* @details This function will be called in case of an assert in the SoftDevice.
*
* @warning This handler is an example only and does not fit a final product. You need to analyse
* how your product is supposed to react in case of Assert.
* @warning On assert from the SoftDevice, the system can only recover on reset.
*
* @param[in] line_num Line number of the failing ASSERT call.
* @param[in] p_file_name File name of the failing ASSERT call.
*/
void assert_nrf_callback(uint16_t line_num, const uint8_t * p_file_name)
{
app_error_handler(DEAD_BEEF, line_num, p_file_name);
}
#include "peer_manager.h"
#include "peer_manager_handler.h"
static void advertising_start(bool erase_bonds);
static pm_peer_id_t m_peer_to_be_deleted = PM_PEER_ID_INVALID;
#define SEC_PARAM_BOND 1 /**< Perform bonding. */
#define SEC_PARAM_MITM 1 /**< Man In The Middle protection not required. */
#define SEC_PARAM_LESC 0 /**< LE Secure Connections enabled. */
#define SEC_PARAM_KEYPRESS 0 /**< Keypress notifications not enabled. */
#define SEC_PARAM_IO_CAPABILITIES BLE_GAP_IO_CAPS_DISPLAY_ONLY /**< No I/O capabilities. */
#define SEC_PARAM_OOB 0 /**< Out Of Band data not available. */
#define SEC_PARAM_MIN_KEY_SIZE 7 /**< Minimum encryption key size in octets. */
#define SEC_PARAM_MAX_KEY_SIZE 16 /**< Maximum encryption key size in octets. */
#define PASSKEY_LENGTH 6 /**< Length of pass-key received by the stack for display. */
static void passkey_init(uint32_t ble_pin)
{
char passkey[6];
itoa(ble_pin, passkey, 10);
ble_opt_t ble_opt;
ble_opt.gap_opt.passkey.p_passkey = (uint8_t*)&passkey[0];
(void)sd_ble_opt_set(BLE_GAP_OPT_PASSKEY, &ble_opt);
}
/**@brief Clear bond information from persistent storage.
*/
static void delete_bonds(void)
{
ret_code_t err_code;
NRF_LOG_INFO("Erase bonds!");
err_code = pm_peers_delete();
APP_ERROR_CHECK(err_code);
}
/**@brief Function for handling Peer Manager events.
*
* @param[in] p_evt Peer Manager event.
*/
static volatile bool is_connection_secure = false;
static void pm_evt_handler(pm_evt_t const * p_evt)
{
ret_code_t err_code;
pm_handler_on_pm_evt(p_evt);
pm_handler_disconnect_on_sec_failure(p_evt);
pm_handler_flash_clean(p_evt);
switch (p_evt->evt_id)
{
case PM_EVT_CONN_SEC_SUCCEEDED:
{
pm_conn_sec_status_t conn_sec_status;
// Check if the link is authenticated (meaning at least MITM).
err_code = pm_conn_sec_status_get(p_evt->conn_handle, &conn_sec_status);
APP_ERROR_CHECK(err_code);
if (conn_sec_status.mitm_protected)
{
NRF_LOG_INFO("Link secured. Role: %d. conn_handle: %d, Procedure: %d",
ble_conn_state_role(p_evt->conn_handle),
p_evt->conn_handle,
p_evt->params.conn_sec_succeeded.procedure);
is_connection_secure = true;
melody_play(MELODY_BLE_SUCCESS, true); // Play BLE Success sound
#if HAS_DISPLAY
// Notify user connection successful
Adafruit_GFX_print("BLE OK", 64, 0);
update_display = true;
#endif
}
else
{
// The peer did not use MITM, disconnect.
NRF_LOG_INFO("Collector did not use MITM, disconnecting");
err_code = pm_peer_id_get(m_conn_handle, &m_peer_to_be_deleted);
APP_ERROR_CHECK(err_code);
err_code = sd_ble_gap_disconnect(m_conn_handle,
BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
APP_ERROR_CHECK(err_code);
}
} break;
case PM_EVT_CONN_SEC_FAILED:
m_conn_handle = BLE_CONN_HANDLE_INVALID;
// Notify user connection failed
Adafruit_GFX_print("BLEPIN", 64, 0);
update_display = true;
melody_play(MELODY_BLE_FAIL, false); // Play BLE Failed sound. Do not interrupt (may happen repeatedly)
break;
case PM_EVT_CONN_SEC_CONFIG_REQ:
{
// Allow pairing request from an already bonded peer.
pm_conn_sec_config_t conn_sec_config = {.allow_repairing = true};
pm_conn_sec_config_reply(p_evt->conn_handle, &conn_sec_config);
} break;
case PM_EVT_PEERS_DELETE_SUCCEEDED:
advertising_start(false);
break;
default:
break;
}
}
/**@brief Function for the Peer Manager initialization.
*/
static void peer_manager_init(void)
{
ble_gap_sec_params_t sec_param;
ret_code_t err_code;
err_code = pm_init();
APP_ERROR_CHECK(err_code);
memset(&sec_param, 0, sizeof(ble_gap_sec_params_t));
// Security parameters to be used for all security procedures.
sec_param.bond = SEC_PARAM_BOND;
sec_param.mitm = SEC_PARAM_MITM;
sec_param.lesc = SEC_PARAM_LESC;
sec_param.keypress = SEC_PARAM_KEYPRESS;
sec_param.io_caps = SEC_PARAM_IO_CAPABILITIES;
sec_param.oob = SEC_PARAM_OOB;
sec_param.min_key_size = SEC_PARAM_MIN_KEY_SIZE;
sec_param.max_key_size = SEC_PARAM_MAX_KEY_SIZE;
sec_param.kdist_own.enc = 1;
sec_param.kdist_own.id = 1;
sec_param.kdist_peer.enc = 1;
sec_param.kdist_peer.id = 1;
err_code = pm_sec_params_set(&sec_param);
APP_ERROR_CHECK(err_code);
err_code = pm_register(pm_evt_handler);
APP_ERROR_CHECK(err_code);
}
static void gap_params_init(void)
{
uint32_t err_code;
ble_gap_conn_params_t gap_conn_params;
ble_gap_conn_sec_mode_t sec_mode;
//BLE_GAP_CONN_SEC_MODE_SET_OPEN(&sec_mode);
BLE_GAP_CONN_SEC_MODE_SET_ENC_WITH_MITM(&sec_mode);
err_code = sd_ble_gap_device_name_set(&sec_mode,
(const uint8_t *) DEVICE_NAME,
strlen(DEVICE_NAME));
APP_ERROR_CHECK(err_code);
memset(&gap_conn_params, 0, sizeof(gap_conn_params));
gap_conn_params.min_conn_interval = MIN_CONN_INTERVAL;
gap_conn_params.max_conn_interval = MAX_CONN_INTERVAL;
gap_conn_params.slave_latency = SLAVE_LATENCY;
gap_conn_params.conn_sup_timeout = CONN_SUP_TIMEOUT;
err_code = sd_ble_gap_ppcp_set(&gap_conn_params);
APP_ERROR_CHECK(err_code);
}
/**@brief Function for starting advertising.
*/
static void advertising_start(bool erase_bonds)
{
if (erase_bonds == true)
{
delete_bonds();
// Advertising is started by PM_EVT_PEERS_DELETE_SUCCEEDED event.
}
else
{
ret_code_t err_code = ble_advertising_start(&m_advertising, BLE_ADV_MODE_FAST);
APP_ERROR_CHECK(err_code);
sd_ble_gap_tx_power_set(BLE_GAP_TX_POWER_ROLE_ADV, m_advertising.adv_handle, 8);
}
}
/**@brief Function for handling Queued Write Module errors.
*
* @details A pointer to this function will be passed to each service which may need to inform the
* application about an error.
*
* @param[in] nrf_error Error code containing information about what went wrong.
*/
static void nrf_qwr_error_handler(uint32_t nrf_error)
{
APP_ERROR_HANDLER(nrf_error);
}
void ble_send_logbuffer(unsigned char *data, unsigned int len) {
if (m_conn_handle != BLE_CONN_HANDLE_INVALID) {
uint32_t err_code = NRF_SUCCESS;
int ind = 0;
while (len > 0) {
if (m_conn_handle == BLE_CONN_HANDLE_INVALID ||
(err_code != NRF_ERROR_BUSY && err_code != NRF_SUCCESS && err_code != NRF_ERROR_RESOURCES)) {
break;
}
uint16_t max_len = m_ble_fus_max_data_len;
uint16_t tmp_len = len > max_len ? max_len : len;
err_code = ble_fus_logdata_send(&m_fus, data + ind, &tmp_len, m_conn_handle);
if (err_code != NRF_ERROR_RESOURCES && err_code != NRF_ERROR_BUSY) {
len -= tmp_len;
ind += tmp_len;
}
}
}
}
static void fus_data_handler(ble_fus_evt_t * p_evt) {
if (p_evt->type == BLE_FUS_EVT_RX_DATA) {
for (uint32_t i = 0; i < p_evt->params.rx_data.length; i++) {
//NRF_LOG_INFO("tx_data[%03d] = 0x%02x", i, p_evt->params.rx_data.p_data[i]);
//NRF_LOG_FLUSH();
packet_process_byte(p_evt->params.rx_data.p_data[i], PACKET_BLE);
}
}
else if (p_evt->type == BLE_FUS_EVT_RXLOG_DATA) {
for (uint32_t i = 0; i < p_evt->params.rx_data.length; i++) {
//NRF_LOG_INFO("rx_data[%d] = %c", i, p_evt->params.rx_data.p_data[i]);
//NRF_LOG_FLUSH();
command_interface_process_byte(p_evt->params.rx_data.p_data[i]);
}
}
}
static void services_init(void) {
uint32_t err_code;
ble_fus_init_t fus_init;
nrf_ble_qwr_init_t qwr_init = {0};
// Initialize Queued Write Module.
qwr_init.error_handler = nrf_qwr_error_handler;
err_code = nrf_ble_qwr_init(&m_qwr, &qwr_init);
APP_ERROR_CHECK(err_code);