-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
1029 lines (865 loc) · 29.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 - 2022 Benjamin Vedder benjamin@vedder.se
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 "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_nus.h"
#include "app_uart.h"
#include "app_util_platform.h"
#include "nrf_pwr_mgmt.h"
#include "bsp_btn_ble.h"
#include "nrf_delay.h"
#include "storage.h"
#include "nrf_ble_lesc.h"
#include "peer_manager.h"
#include "peer_manager_handler.h"
#if defined (UART_PRESENT)
#include "nrf_uart.h"
#endif
#if defined (UARTE_PRESENT)
#include "nrf_uarte.h"
#endif
#ifdef NRF52840_XXAA
#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 "esb_timeslot.h"
#include "crc.h"
#ifndef MODULE_BUILTIN
#define MODULE_BUILTIN 1
#endif
#ifndef MODULE_RD2
#define MODULE_RD2 0
#endif
#ifndef MODULE_RD_BMS
#define MODULE_RD_BMS 0
#endif
#define USE_SLEEP 0
#define USE_USB 0
#ifdef NRF52840_XXAA
#if MODULE_BUILTIN
#define DEVICE_NAME "VESC 52840 BUILTIN"
#elif MODULE_RD2
#define DEVICE_NAME "VESC RAD2"
#elif MODULE_STORMCORE
#define DEVICE_NAME "STORMCORE"
#elif MODULE_RD_BMS
#define DEVICE_NAME "VESC RBAT BMS"
#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 SEC_PARAM_BOND 1 /**< Perform bonding. */
#define SEC_PARAM_MITM 1 /**< Man In The Middle protection required (applicable when display module is detected). */
#define SEC_PARAM_LESC 1 /**< LE Secure Connections enabled. */
#define SEC_PARAM_KEYPRESS 0 /**< Keypress notifications not enabled. */
#define SEC_PARAM_IO_CAPABILITIES BLE_GAP_IO_CAPS_DISPLAY_ONLY /**< Display 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. */
#define SEC_PARAM_MAX_KEY_SIZE 16 /**< Maximum encryption key size. */
static pm_peer_id_t m_peer_to_be_deleted = PM_PEER_ID_INVALID;
#define APP_BLE_CONN_CFG_TAG 1 /**< A tag identifying the SoftDevice BLE configuration. */
#define NUS_SERVICE_UUID_TYPE BLE_UUID_TYPE_VENDOR_BEGIN /**< UUID type for the Nordic 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 100 /**< The advertising duration (180 seconds) in units of 10 milliseconds. */
#define MIN_CONN_INTERVAL MSEC_TO_UNITS(15, UNIT_1_25_MS) /**< Minimum acceptable connection interval (20 ms), Connection interval uses 1.25 ms units. */
#define MAX_CONN_INTERVAL MSEC_TO_UNITS(30, 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 16384
#define UART_RX_BUF_SIZE 16384
#else
#define UART_TX_BUF_SIZE 2048
#define UART_RX_BUF_SIZE 8192
#endif
#define PACKET_VESC 0
#define PACKET_BLE 1
#define LED_ON() nrf_gpio_pin_set(LED_PIN)
#define LED_OFF() nrf_gpio_pin_clear(LED_PIN)
#ifdef NRF52840_XXAA
#if MODULE_BUILTIN
#define UART_RX 26
#define UART_TX 25
#define UART_TX_DISABLED 28
#define LED_PIN 27
#elif MODULE_RD2
#define UART_RX 11
#define UART_TX 12
#define UART_TX_DISABLED 18
#define LED_PIN 15
#elif MODULE_STORMCORE
#define UART_RX 31
#define UART_TX 30
#define UART_TX_DISABLED 29
#define LED_PIN 5
#elif MODULE_RD_BMS
#define UART_RX 4
#define UART_TX 5
#define UART_TX_DISABLED 2
#define LED_PIN NRF_GPIO_PIN_MAP(1, 5)
#undef LED_ON
#undef LED_OFF
#define LED_ON() nrf_gpio_pin_set(NRF_GPIO_PIN_MAP(1, 1)); nrf_gpio_pin_clear(LED_PIN)
#define LED_OFF() nrf_gpio_pin_set(LED_PIN)
#else
#define UART_RX 11
#define UART_TX 8
#define UART_TX_DISABLED 25
#define LED_PIN 7
#endif
#else
#if MODULE_BUILTIN
#define UART_RX 6
#define UART_TX 7
#define UART_TX_DISABLED 25
#define EN_DEFAULT 1
#define LED_PIN 8
#define LED_PIN2_INV 5
#else
#define UART_RX 7
#define UART_TX 6
#define UART_TX_DISABLED 25
#define EN_DEFAULT 1
#define LED_PIN 8
#endif
#endif
// Alternative inverted LED pin
#ifdef LED_PIN2_INV
#undef LED_ON
#undef LED_OFF
#define LED_ON() nrf_gpio_pin_set(LED_PIN); nrf_gpio_pin_clear(LED_PIN2_INV)
#define LED_OFF() nrf_gpio_pin_clear(LED_PIN); nrf_gpio_pin_set(LED_PIN2_INV)
#endif
// Private variables
APP_TIMER_DEF(m_packet_timer);
APP_TIMER_DEF(m_nrf_timer);
BLE_NUS_DEF(m_nus, NRF_SDH_BLE_TOTAL_LINK_COUNT); /**< BLE NUS 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. */
static uint16_t m_ble_nus_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_NUS_SERVICE, NUS_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;
static volatile int m_no_sleep_cnt = 0;
static volatile int m_disconnect_cnt = 0;
static volatile int m_reset_timer = 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,
#if defined (UART_PRESENT)
.baud_rate = NRF_UART_BAUDRATE_115200
#else
.baud_rate = NRF_UARTE_BAUDRATE_115200
#endif
};
// Functions
void ble_printf(const char* format, ...);
static void set_enabled(bool en);
static void start_advertising(void);
#if USE_SLEEP
static void go_to_sleep(void);
#endif
#if defined(NRF52840_XXAA) && USE_USB
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
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
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) {
} else {
// The peer did not use MITM, disconnect.
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;
break;
case PM_EVT_PEERS_DELETE_SUCCEEDED:
start_advertising();
break;
case PM_EVT_CONN_SEC_CONFIG_REQ: {
// Allow re-pairing
pm_conn_sec_config_t config = {.allow_repairing = true};
pm_conn_sec_config_reply(p_evt->conn_handle, &config);
break;
}
default:
break;
}
}
/**@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);
}
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);
char *dev_name = DEVICE_NAME;
if (m_config.name_set) {
dev_name = m_config.name;
}
sd_ble_gap_device_name_set(&sec_mode, (const uint8_t *)dev_name, strlen(dev_name));
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);
if (m_config.pin_set) {
ble_gap_opt_t gap_opt;
gap_opt.passkey.p_passkey = (uint8_t*)m_config.pin;
sd_ble_opt_set(BLE_GAP_OPT_PASSKEY,(const ble_opt_t *)&gap_opt);
}
}
static void start_advertising(void) {
ble_advertising_start(&m_advertising, BLE_ADV_MODE_FAST);
sd_ble_gap_tx_power_set(BLE_GAP_TX_POWER_ROLE_ADV, m_advertising.adv_handle, 8);
}
static void nrf_qwr_error_handler(uint32_t nrf_error) {
APP_ERROR_HANDLER(nrf_error);
}
static void nus_data_handler(ble_nus_evt_t * p_evt) {
if (p_evt->type == BLE_NUS_EVT_RX_DATA) {
for (uint32_t i = 0; i < p_evt->params.rx_data.length; i++) {
packet_process_byte(p_evt->params.rx_data.p_data[i], PACKET_BLE);
}
}
}
static void services_init(void) {
ble_nus_init_t nus_init;
nrf_ble_qwr_init_t qwr_init = {0};
// Initialize Queued Write Module.
qwr_init.error_handler = nrf_qwr_error_handler;
nrf_ble_qwr_init(&m_qwr, &qwr_init);
// Initialize NUS.
memset(&nus_init, 0, sizeof(nus_init));
nus_init.data_handler = nus_data_handler;
ble_nus_init(&m_nus, &nus_init, m_config.pin_set);
}
static void conn_params_error_handler(uint32_t nrf_error) {
APP_ERROR_HANDLER(nrf_error);
}
static void conn_params_init(void) {
ble_conn_params_init_t cp_init;
memset(&cp_init, 0, sizeof(cp_init));
cp_init.p_conn_params = NULL;
cp_init.first_conn_params_update_delay = FIRST_CONN_PARAMS_UPDATE_DELAY;
cp_init.next_conn_params_update_delay = NEXT_CONN_PARAMS_UPDATE_DELAY;
cp_init.max_conn_params_update_count = MAX_CONN_PARAMS_UPDATE_COUNT;
cp_init.start_on_notify_cccd_handle = BLE_GATT_HANDLE_INVALID;
cp_init.disconnect_on_fail = true;
cp_init.evt_handler = NULL;
cp_init.error_handler = conn_params_error_handler;
ble_conn_params_init(&cp_init);
}
static void on_adv_evt(ble_adv_evt_t ble_adv_evt) {
switch (ble_adv_evt) {
case BLE_ADV_EVT_FAST:
// bsp_indication_set(BSP_INDICATE_ADVERTISING);
break;
case BLE_ADV_EVT_IDLE:
#if USE_SLEEP
if (m_no_sleep_cnt) {
m_no_sleep_cnt--;
start_advertising();
} else {
go_to_sleep();
}
#else
start_advertising();
#endif
break;
default:
break;
}
}
static void ble_evt_handler(ble_evt_t const * p_ble_evt, void * p_context) {
if (m_config.pin_set) {
pm_handler_secure_on_connection(p_ble_evt);
}
switch (p_ble_evt->header.evt_id) {
case BLE_GAP_EVT_CONNECTED:
LED_ON();
m_peer_to_be_deleted = PM_PEER_ID_INVALID;
m_conn_handle = p_ble_evt->evt.gap_evt.conn_handle;
nrf_ble_qwr_conn_handle_assign(&m_qwr, m_conn_handle);
sd_ble_gap_tx_power_set(BLE_GAP_TX_POWER_ROLE_CONN, m_conn_handle, 8);
break;
case BLE_GAP_EVT_DISCONNECTED:
LED_OFF();
m_conn_handle = BLE_CONN_HANDLE_INVALID;
m_disconnect_cnt = 100;
if (m_peer_to_be_deleted != PM_PEER_ID_INVALID) {
pm_peer_delete(m_peer_to_be_deleted);
m_peer_to_be_deleted = PM_PEER_ID_INVALID;
}
break;
case BLE_GAP_EVT_PHY_UPDATE_REQUEST: {
ble_gap_phys_t const phys =
{
.rx_phys = BLE_GAP_PHY_AUTO,
.tx_phys = BLE_GAP_PHY_AUTO,
};
sd_ble_gap_phy_update(p_ble_evt->evt.gap_evt.conn_handle, &phys);
} break;
case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
// Pairing not supported
if (!m_config.pin_set) {
sd_ble_gap_sec_params_reply(m_conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
}
break;
case BLE_GATTS_EVT_SYS_ATTR_MISSING:
// No system attributes have been stored.
sd_ble_gatts_sys_attr_set(m_conn_handle, NULL, 0, 0);
break;
case BLE_GATTC_EVT_TIMEOUT:
// Disconnect on GATT Client timeout event.
sd_ble_gap_disconnect(p_ble_evt->evt.gattc_evt.conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
break;
case BLE_GATTS_EVT_TIMEOUT:
// Disconnect on GATT Server timeout event.
sd_ble_gap_disconnect(p_ble_evt->evt.gatts_evt.conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
break;
default:
// No implementation needed.
break;
}
}
static void ble_stack_init(void) {
nrf_sdh_enable_request();
// Configure the BLE stack using the default settings.
// Fetch the start address of the application RAM.
uint32_t ram_start = 0;
nrf_sdh_ble_default_cfg_set(APP_BLE_CONN_CFG_TAG, &ram_start);
// Enable BLE stack.
nrf_sdh_ble_enable(&ram_start);
// Register a handler for BLE events.
NRF_SDH_BLE_OBSERVER(m_ble_observer, APP_BLE_OBSERVER_PRIO, ble_evt_handler, NULL);
}
void gatt_evt_handler(nrf_ble_gatt_t * p_gatt, nrf_ble_gatt_evt_t const * p_evt) {
if ((m_conn_handle == p_evt->conn_handle) && (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)) {
m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
// ble_printf("Data len is set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
}
}
void gatt_init(void) {
nrf_ble_gatt_init(&m_gatt, gatt_evt_handler);
nrf_ble_gatt_att_mtu_periph_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
}
void uart_event_handle(app_uart_evt_t * p_event) {
switch (p_event->evt_type) {
case APP_UART_DATA_READY: {
// uint8_t byte;
// while (app_uart_get(&byte) == NRF_SUCCESS) {
// packet_process_byte(byte, PACKET_VESC);
// }
} break;
case APP_UART_COMMUNICATION_ERROR:
// m_uart_error = true;
break;
case APP_UART_FIFO_ERROR:
// m_uart_error = true;
break;
default:
break;
}
}
static void peer_manager_init(void) {
pm_init();
ble_gap_sec_params_t sec_param;
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;
pm_sec_params_set(&sec_param);
pm_register(pm_evt_handler);
}
static void uart_init(void) {
uint32_t err_code;
APP_UART_FIFO_INIT(&m_uart_comm_params,
UART_RX_BUF_SIZE,
UART_TX_BUF_SIZE,
uart_event_handle,
APP_IRQ_PRIORITY_LOW,
err_code);
APP_ERROR_CHECK(err_code);
}
static void advertising_init(void) {
uint32_t err_code;
ble_advertising_init_t init;
memset(&init, 0, sizeof(init));
init.advdata.name_type = BLE_ADVDATA_FULL_NAME;
init.advdata.include_appearance = false;
init.advdata.flags = BLE_GAP_ADV_FLAGS_LE_ONLY_LIMITED_DISC_MODE;
init.srdata.uuids_complete.uuid_cnt = sizeof(m_adv_uuids) / sizeof(m_adv_uuids[0]);
init.srdata.uuids_complete.p_uuids = m_adv_uuids;
init.config.ble_adv_fast_enabled = true;
init.config.ble_adv_fast_interval = APP_ADV_INTERVAL;
init.config.ble_adv_fast_timeout = APP_ADV_DURATION;
init.evt_handler = on_adv_evt;
err_code = ble_advertising_init(&m_advertising, &init);
APP_ERROR_CHECK(err_code);
ble_advertising_conn_cfg_tag_set(&m_advertising, APP_BLE_CONN_CFG_TAG);
}
static void set_enabled(bool en) {
m_is_enabled = en;
if (m_is_enabled) {
app_uart_close();
m_uart_comm_params.tx_pin_no = UART_TX;
uart_init();
nrf_gpio_cfg_default(UART_TX_DISABLED);
} else {
app_uart_close();
m_uart_comm_params.tx_pin_no = UART_TX_DISABLED;
uart_init();
nrf_gpio_cfg_default(UART_TX);
}
}
static void uart_send_buffer(unsigned char *data, unsigned int len) {
for (int i = 0;i < len;i++) {
app_uart_put(data[i]);
}
}
void rfhelp_send_data_crc(uint8_t *data, unsigned int len) {
uint8_t buffer[len + 2];
unsigned short crc = crc16((unsigned char*)data, len);
memcpy(buffer, data, len);
buffer[len] = (char)(crc >> 8);
buffer[len + 1] = (char)(crc & 0xFF);
esb_timeslot_set_next_packet(buffer, len + 2);
}
static void ble_send_buffer(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_nus_max_data_len;
uint16_t tmp_len = len > max_len ? max_len : len;
err_code = ble_nus_data_send(&m_nus, 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 process_packet_ble(unsigned char *data, unsigned int len) {
if (data[0] == COMM_ERASE_NEW_APP ||
data[0] == COMM_WRITE_NEW_APP_DATA ||
data[0] == COMM_ERASE_NEW_APP_ALL_CAN ||
data[0] == COMM_WRITE_NEW_APP_DATA_ALL_CAN) {
m_other_comm_disable_time = 5000;
}
m_no_sleep_cnt = 20;
CRITICAL_REGION_ENTER();
packet_send_packet(data, len, PACKET_VESC);
CRITICAL_REGION_EXIT();
}
static void process_packet_vesc(unsigned char *data, unsigned int len) {
if (data[0] == COMM_EXT_NRF_ESB_SET_CH_ADDR) {
esb_timeslot_set_ch_addr(data[1], data[2], data[3], data[4]);
} else if (data[0] == COMM_EXT_NRF_ESB_SEND_DATA) {
rfhelp_send_data_crc(data + 1, len - 1);
} else if (data[0] == COMM_EXT_NRF_SET_ENABLED) {
set_enabled(data[1]);
} else if (data[0] == COMM_SET_BLE_NAME) {
if (len > 3 && len <= 30) {
memcpy(m_config.name, data + 1, len - 1);
m_config.name[len] = '\0';
m_config.name_set = 1;
m_reset_timer = 3000;
} else {
if (m_config.name_set) {
m_reset_timer = 3000;
}
m_config.name_set = 0;
}
storage_save_config();
} else if (data[0] == COMM_SET_BLE_PIN) {
if (len >= 7 &&
data[1] >= '0' && data[1] <= '9' &&
data[2] >= '0' && data[2] <= '9' &&
data[3] >= '0' && data[3] <= '9' &&
data[4] >= '0' && data[4] <= '9' &&
data[5] >= '0' && data[5] <= '9' &&
data[6] >= '0' && data[6] <= '9') {
memcpy(m_config.pin, data + 1, 6);
m_config.pin[7] = '\0';
m_config.pin_set = 1;
m_reset_timer = 3000;
} else {
if (m_config.pin_set) {
pm_peers_delete();
m_reset_timer = 3000;
}
m_config.pin_set = 0;
}
storage_save_config();
} else {
if (m_is_enabled) {
packet_send_packet(data, len, PACKET_BLE);
}
}
}
void ble_printf(const char* format, ...) {
va_list arg;
va_start (arg, format);
int len;
static char print_buffer[255];
print_buffer[0] = COMM_PRINT;
len = vsnprintf(print_buffer + 1, 254, format, arg);
va_end (arg);
if(len > 0) {
packet_send_packet((unsigned char*)print_buffer, (len < 254) ? len + 1 : 255, PACKET_BLE);
}
}
void cdc_printf(const char* format, ...) {
#if defined(NRF52840_XXAA) && USE_USB
va_list arg;
va_start (arg, format);
int len;
static char print_buffer[255];
len = vsnprintf(print_buffer, sizeof(print_buffer), format, arg);
va_end (arg);
if(len > 0) {
app_usbd_cdc_acm_write(&m_app_cdc_acm, print_buffer,
len < sizeof(print_buffer) ? len : sizeof(print_buffer));
}
#else
(void)format;
#endif
}
static void esb_timeslot_data_handler(void *p_data, uint16_t length) {
if (m_other_comm_disable_time == 0) {
uint8_t buffer[length + 1];
buffer[0] = COMM_EXT_NRF_ESB_RX_DATA;
memcpy(buffer + 1, p_data, length);
CRITICAL_REGION_ENTER();
packet_send_packet(buffer, length + 1, PACKET_VESC);
CRITICAL_REGION_EXIT();
}
m_no_sleep_cnt = 20;
}
static void packet_timer_handler(void *p_context) {
(void)p_context;
packet_timerfunc();
if (m_reset_timer > 0) {
m_reset_timer--;
if (m_reset_timer == 0) {
NVIC_SystemReset();
}
}
CRITICAL_REGION_ENTER();
if (m_other_comm_disable_time > 0) {
m_other_comm_disable_time--;
}
CRITICAL_REGION_EXIT();
}
static void nrf_timer_handler(void *p_context) {
(void)p_context;
#if USE_SLEEP
// If BLE just disconnected this packet is sent at a higher rate for 10 seconds. The reason
// is that the disconnect might have happened because the connected VESC or VESC BMS was
// sleeping and didn't respond. This higher rate gives it a change to wake up on UART events
// so that the next connect works.
// TODO: Maybe this should be handled from VESC Tool by trying for longer?
if (m_disconnect_cnt) {
m_disconnect_cnt--;
app_timer_start(m_nrf_timer, APP_TIMER_TICKS(100), NULL);
} else {
app_timer_start(m_nrf_timer, APP_TIMER_TICKS(1000), NULL);
}
#else
app_timer_start(m_nrf_timer, APP_TIMER_TICKS(1000), NULL);
#endif
if (m_other_comm_disable_time == 0) {
uint8_t buffer[2];
buffer[0] = COMM_EXT_NRF_PRESENT;
buffer[1] = 3; // Indicate name and pin code update is supported
CRITICAL_REGION_ENTER();
packet_send_packet(buffer, 2, PACKET_VESC);
CRITICAL_REGION_EXIT();
}
cdc_printf("Test\r\n");
// Reload watchdog
NRF_WDT->RR[0] = WDT_RR_RR_Reload;
}
#if USE_SLEEP
static void go_to_sleep(void) {
app_uart_close();
app_timer_stop_all();
esb_timeslot_sd_stop();
nrf_gpio_cfg_default(LED_PIN);
nrf_gpio_cfg_default(UART_RX);
nrf_gpio_cfg_default(UART_TX);
#ifdef LED_PIN2_INV
nrf_gpio_cfg_default(LED_PIN2_INV);
#endif
// Workaround current consumption issue by power cycling the UART peripherals
// https://devzone.nordicsemi.com/f/nordic-q-a/42883/current-consumption-when-using-timer-and-scheduler-alongwith-nrf_pwr_mgmt_run/167545#167545
*(volatile uint32_t *)0x40002FFC = 0; // Power down UARTE0
*(volatile uint32_t *)0x40002FFC; //
*(volatile uint32_t *)0x40002FFC = 1; // Power on UARTE0 so it is ready for next time
*(volatile uint32_t *)0x40028FFC = 0; // Power down UARTE1
*(volatile uint32_t *)0x40028FFC; //
*(volatile uint32_t *)0x40028FFC = 1; // Power on UARTE1 so it is ready for next time
#ifdef MODULE_RD_BMS
nrf_gpio_pin_clear(NRF_GPIO_PIN_MAP(1, 1));
#endif
if (nrf_sdh_is_enabled()) {
nrf_sdh_disable_request();
while (nrf_sdh_is_enabled()) {}
}
// The watchdog will wake up the CPU. Then we reset and start
// advertising ble again.
__set_FPSCR(__get_FPSCR() & ~(0x0000009F));
(void)__get_FPSCR();
NVIC_ClearPendingIRQ(FPU_IRQn);
__SEV();
__WFE();
__WFE();
NVIC_SystemReset();
}
#endif
int main(void) {
nrf_gpio_cfg_output(LED_PIN);
#ifdef LED_PIN2_INV
nrf_gpio_cfg_output(LED_PIN2_INV);
#endif
#if MODULE_RD_BMS
nrf_gpio_cfg_output(NRF_GPIO_PIN_MAP(1, 1));
LED_ON();
nrf_delay_ms(5);
nrf_gpio_pin_clear(NRF_GPIO_PIN_MAP(1, 1));
LED_OFF();
#endif
#if defined(NRF52840_XXAA) && USE_USB
nrf_drv_clock_init();
static const app_usbd_config_t usbd_config = {
.ev_state_proc = usbd_user_ev_handler
};
app_usbd_serial_num_generate();
app_usbd_init(&usbd_config);
app_usbd_class_inst_t const * class_cdc_acm = app_usbd_cdc_acm_class_inst_get(&m_app_cdc_acm);
app_usbd_class_append(class_cdc_acm);
#endif
// Watchdog
NRF_WDT->CONFIG = (WDT_CONFIG_HALT_Pause << WDT_CONFIG_HALT_Pos) | ( WDT_CONFIG_SLEEP_Run << WDT_CONFIG_SLEEP_Pos);
NRF_WDT->CRV = 5 * 32768; // 5s timout
NRF_WDT->RREN |= WDT_RREN_RR0_Msk;
NRF_WDT->TASKS_START = 1;
storage_init();
uart_init();
app_timer_init();
nrf_pwr_mgmt_init();
ble_stack_init();
gap_params_init();
gatt_init();
services_init();
advertising_init();
conn_params_init();
if (m_config.pin_set) {
peer_manager_init();
}
(void)set_enabled;
packet_init(uart_send_buffer, process_packet_vesc, PACKET_VESC);
packet_init(ble_send_buffer, process_packet_ble, PACKET_BLE);
app_timer_create(&m_packet_timer, APP_TIMER_MODE_REPEATED, packet_timer_handler);
app_timer_start(m_packet_timer, APP_TIMER_TICKS(1), NULL);
app_timer_create(&m_nrf_timer, APP_TIMER_MODE_SINGLE_SHOT, nrf_timer_handler);
app_timer_start(m_nrf_timer, APP_TIMER_TICKS(1200), NULL);
esb_timeslot_init(esb_timeslot_data_handler);
esb_timeslot_sd_start();
#if defined(NRF52840_XXAA) && USE_USB
app_usbd_power_events_enable();
#endif
start_advertising();
for (;;) {
#if defined(NRF52840_XXAA) && USE_USB
while (app_usbd_event_queue_process()){}