-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
3471 lines (2881 loc) · 125 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
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "nordic_common.h"
#include "nrf_sdh.h"
#include "nrf_sdh_soc.h"
#include "nrf_sdh_ble.h"
#include "peer_manager.h"
#include "peer_manager_handler.h"
#include "app_timer.h"
#include "bsp_btn_ble.h"
#include "ble.h"
#include "ble_advdata.h"
#include "ble_advertising.h"
#include "ble_conn_params.h"
#include "ble_db_discovery.h"
// Provided services
#include "ble_hrs.h"
#include "ble_cps.h"
#include "ble_dis.h"
#include "ble_cscs.h"
#include "ble_bas.h"
#include "ble_ftms.h"
#include "ble_fec.h"
// #include "ble_boot_custom.h" // Not needed for Tacx!
#include "ble_atom.h"
#include "ble_uds.h"
// Backend services
#include "ble_hrs_c.h"
#include "ble_cscs_c.h"
#include "ble_bas_c.h"
#include "ble_dis_c.h"
#include "ble_conn_state.h"
#include "nrf_fstorage.h"
#include "fds.h"
#include "nrf_ble_gatt.h"
#include "nrf_ble_qwr.h"
#include "nrf_pwr_mgmt.h"
#include "nrf_ble_scan.h"
#include "nrf_log.h"
#include "nrf_log_ctrl.h"
#include "nrf_log_default_backends.h"
#include "calculations.h"
#include "counter.h"
#include "math.h"
#include "oled_controller.h"
#include "nrf_drv_gpiote.h"
#include "app_button.h"
#include "app_error.h"
#include "app_scheduler.h"
#include <ble_gap.h>
#include "helper.h"
#include "assert.h"
#include "gear_buttons.h"
#include "shimano.h"
#include "cryptoutil.h"
// S-DFU related
#include "nrf_dfu_ble_svci_bond_sharing.h"
#include "ble_dfu.h"
#include "nrf_bootloader_info.h"
#include "nrf_svci_async_function.h"
#include "nrf_svci_async_handler.h"
#include "nrf_power.h"
#include "bond_mgr.h"
#include "nrf_strerror.h"
#define PERIPHERAL_ADVERTISING_LED BSP_BOARD_LED_2
#define PERIPHERAL_CONNECTED_LED BSP_BOARD_LED_3
#define CENTRAL_SCANNING_LED BSP_BOARD_LED_0
#define CENTRAL_CONNECTED_LED BSP_BOARD_LED_1
#define SIM_MODE_ENABLED 0
// check sdk_config.h's define for NRF_LOG_ENABLED to enable/disable logging in DEBUG mode.
#define EMULATE_TACX 1
// Setting it to 1 will include the DIS values and adv. values from TACX
// and will establish the FE-C handling
#define BENCHMARK 0
#if EMULATE_TACX
#define DEVICE_NAME "Tacx Neo" /**< Name of device used for advertising. */
#define MANUFACTURER_NAME "Tacx" /**< Manufacturer. Passed to Device Information Service. */
#define MODEL_NUMBER "2875"
#define SERIAL_NUMBER "000001"
#define HW_REVISION "2.0"
#else
#define DEVICE_NAME "nRF CPS" /**< Name of device used for advertising. */
#define MANUFACTURER_NAME "Daubsi" /**< Manufacturer. Passed to Device Information Service. */
#define MODEL_NUMBER "1"
#endif
#define BUILD "8.9"
#define VERSION "Version: " BUILD
#define APP_ADV_INTERVAL 300 /**< The advertising interval (in units of 0.625 ms). This value corresponds to 187.5 ms. */
#define APP_ADV_DURATION 18000 /**< The advertising duration (180 seconds) in units of 10 milliseconds. */
#define APP_BLE_CONN_CFG_TAG 1 /**< Tag that identifies the SoftDevice BLE configuration. */
#define FIRST_CONN_PARAMS_UPDATE_DELAY APP_TIMER_TICKS(5000) /**< Time from initiating event (connect or start of notification) to the 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 RESISTANCE_REEVALUTATION_MS 300
#define SEC_PARAM_BOND 1 /**< Perform bonding. */
#define SEC_PARAM_MITM 0 /**< Man In The Middle protection not required. */
#define SEC_PARAM_LESC 0 /**< LE Secure Connections not enabled. */
#define SEC_PARAM_KEYPRESS 0 /**< Keypress notifications not enabled. */
#define SEC_PARAM_IO_CAPABILITIES BLE_GAP_IO_CAPS_NONE /**< 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 NUS_SERVICE_UUID_TYPE BLE_UUID_TYPE_VENDOR_BEGIN
#define TRAINER_INITIAL_RESISTANCE_LEVEL 10
#define APP_TIMER_PRESCALER 0
#define APP_TIMER_OP_QUEUE_SIZE 2
/**@brief Priority of the application BLE event handler.
* @note You shouldn't need to modify this value.
*/
#define APP_BLE_OBSERVER_PRIO 3
#define DB_DISCOVERY_INSTANCE_CNT 3 /**< Number of DB Discovery instances. */
// Controls which services we want to offer
typedef enum {
RESISTANCE_CHANGE_NEEDED_RESULT_BUSY,
RESISTANCE_CHANGE_NEEDED_RESULT_NO_CHANGE_NEEDED,
RESISTANCE_CHANGE_NEEDED_RESULT_PLUS_NEEDED,
RESISTANCE_CHANGE_NEEDED_RESULT_MINUS_NEEDED
} resistance_change_needed_t;
/* Normal mode */
bool ble_ftms_active = false;
bool ble_cps_active = true;
bool ble_cscs_active = true;
volatile bool ble_fec_active = true;
bool ble_hrs_active = true;
bool ble_dis_active = true;
bool ble_bas_active = true;
bool ble_atom_active = true;
bool ble_uds_active = false;
/* Debug mode */
/*
bool ble_ftms_active = false;
bool ble_cps_active = true;
bool ble_cscs_active = false;
bool ble_fec_active = true;
bool ble_hrs_active = false;
bool ble_dis_active = true;
bool ble_bas_active = false;
bool ble_atom_active = false;
*/
static ble_hrs_t m_hrs; /**< Heart Rate Service instance. */
static ble_cps_t m_cps; /**< Cycling Power Service instance. */
static ble_cscs_t m_cscs; /**< Cycling Speed and Cadence Service instance. */
static ble_bas_t m_bas; /**< Cycling Speed and Cadence Service instance. */
static ble_ftms_t m_ftms; /**< Fitness Machine Service instance. */
static ble_atom_t m_atom;
static ble_uds_t m_uds;
// static ble_dis_t m_dis;
static ble_hrs_c_t m_hrs_c; /**< Heart Rate Service client instance. */
static ble_cscs_c_t m_cscs_c; /**< Cycling Speed and Cadence Service client instance. */
static ble_bas_c_t m_bas_c[2]; /**< Battery Service client instances. */
static ble_dis_c_t m_dis_c[2]; /**< Device Information client instances. */
static bool need_peer_delete = false;
NRF_BLE_GQ_DEF(m_ble_gatt_queue, /**< BLE GATT Queue instance. */
6, // Increased from
// NRF_SDH_BLE_CENTRAL_LINK_COUNT and,
8 // NRF_BLE_GQ_QUEUE_SIZE - because my additional services might need a larger queue/size
);
NRF_BLE_GATT_DEF(m_gatt); /**< GATT module instance. */
NRF_BLE_QWRS_DEF(m_qwr, NRF_SDH_BLE_TOTAL_LINK_COUNT); /**< Context for the Queued Write module.*/
BLE_ADVERTISING_DEF(m_advertising); /**< Advertising module instance. */
BLE_DB_DISCOVERY_ARRAY_DEF(m_db_discovery, 4); /**< Database discovery module instances. */
NRF_BLE_SCAN_DEF(m_scan); /**< Scanning module instance. */
// DO NOT DO THIS!! It will cause all kind of event havoc
#if EMULATE_TACX
/******************************************************************
* Our BLE_FEC_DEF does not include the BLE_SDH_OBSERVER_MACRO! *
* Therefore it's safe to use it like that! (see ble_fec.h) *
******************************************************************/
BLE_FEC_DEF(m_fec, NRF_SDH_BLE_TOTAL_LINK_COUNT);
// Not needed for Tacx! BLE_BOOT_DEF(m_boot, NRF_SDH_BLE_TOTAL_LINK_COUNT);
#endif
APP_TIMER_DEF(m_setup_hometrainer_timer_id);
static uint16_t m_conn_handle_hrs_c = BLE_CONN_HANDLE_INVALID; /**< Connection handle for the HRS central application */
static uint16_t m_conn_handle_cscs_c = BLE_CONN_HANDLE_INVALID; /**< Connection handle for the CSCP central application */
static uint16_t m_conn_handle_bas_c[2] = { BLE_CONN_HANDLE_INVALID, BLE_CONN_HANDLE_INVALID}; /**< Connection handle for the BAS central application */
static uint16_t m_conn_handle_dis_c[2] = { BLE_CONN_HANDLE_INVALID, BLE_CONN_HANDLE_INVALID}; /**< Connection handle for the DIS central application */
static uint16_t m_central_conn_handle = BLE_CONN_HANDLE_INVALID;
void setupHomeTrainerTimer();
void delete_bonds(void);
static void ble_dis_c_pnp_id_log(uint16_t conn_handle, ble_dis_pnp_id_t const * const p_pnp_id);
static void ble_dis_c_cert_list_log(uint16_t conn_handle, ble_dis_reg_cert_data_list_t const * const p_cert_list);
static void ble_dis_c_system_id_log(uint16_t conn_handle, ble_dis_sys_id_t const * const p_sys_id);
static void ble_dis_c_string_char_log(uint16_t conn_handle, ble_dis_c_char_type_t char_type,
ble_dis_c_string_t const * const p_string);
static uint32_t ble_dis_c_all_chars_read(uint8_t instance);
static void advertising_init(void);
/**@brief Names that the central application scans for, and that are advertised by the peripherals.
* If these are set to empty strings, the UUIDs defined below are used.
*/
static char const m_target_periph_name[] = "";
/**@brief UUIDs that the central application scans for if the name above is set to an empty string,
* and that are to be advertised by the peripherals.
*/
#if EMULATE_TACX
// It's the same as in the "custom_nus" service -> Refactor. Note: UUID is in reverse order! ("6E40FEC1-B5A3-F393-E0A9-E50E24DCCA9E")
#define BLE_UUID_FEC_BRAKE_SERVICE {{0x9E, 0xCA, 0xDC, 0x24, 0x0E, 0xE5, 0xA9, 0xE0, 0x93, 0xF3, 0xA3, 0xB5, 0xC1, 0xFE, 0x40, 0x6E}} // Tacx Neo 2 specific brake service
ble_uuid128_t brake_uuid = BLE_UUID_FEC_BRAKE_SERVICE;
static ble_uuid_t m_adv_uuids[] =
{
{BLE_UUID_CYCLING_SPEED_AND_CADENCE, BLE_UUID_TYPE_BLE},
//{BLE_UUID_HEART_RATE_SERVICE, BLE_UUID_TYPE_BLE},
//{BLE_UUID_CYCLING_POWER, BLE_UUID_TYPE_BLE},
{BLE_UUID_DEVICE_INFORMATION_SERVICE, BLE_UUID_TYPE_BLE}, // Tacx Detection absolutely needs this!
//{BLE_UUID_BATTERY_SERVICE, BLE_UUID_TYPE_BLE},
//{BLE_UUID_FITNESS_MACHINE, BLE_UUID_TYPE_BLE}
};
static ble_uuid_t m_adv_sr_uuids[] =
{
{ BLE_UUID_TACX_SERVICE, BLE_UUID_TYPE_VENDOR_BEGIN},
// // Tacx Detection absolutely needs this!
};
// Tacx also needs the Secure DFU from Nordic names "TXN2_DFU"
#else
static ble_uuid_t m_adv_uuids[] =
{
{BLE_UUID_HEART_RATE_SERVICE, BLE_UUID_TYPE_BLE},
{BLE_UUID_CYCLING_POWER, BLE_UUID_TYPE_BLE},
//{BLE_UUID_BATTERY_SERVICE, BLE_UUID_TYPE_BLE},
{BLE_UUID_FITNESS_MACHINE, BLE_UUID_TYPE_BLE}
};
#endif
//#define CPS_SERVICE_UUID_ADV_IDX 0 /**< CPS service UUID index in array. */
//#define CSCS_SERVICE_UUID_ADV_IDX 1 /**< CSCS service UUID index in array. */
//#define HART_RATE_SERVICE_UUID_ADV_IDX 1 /**< Hart Rate service UUID index in array. */
//#define BATTERY_SERVICE_UUID_ADV_IDX 3 /**< Battery Service UUID index in array. */
//#define FTMS_SERVICE_UUID_ADV_IDX 4 /**< Fitness Machine Service UUID index in array. */
//#define FTMS_SERVICE_UUID_ADV_IDX 2 /**< Fitness Machine Service UUID index in array. */
static ble_uuid_t m_scan_uuids[] =
{
{BLE_UUID_CYCLING_SPEED_AND_CADENCE, BLE_UUID_TYPE_BLE},
{BLE_UUID_HEART_RATE_SERVICE, BLE_UUID_TYPE_BLE},
{BLE_UUID_BATTERY_SERVICE, BLE_UUID_TYPE_BLE},
{BLE_UUID_DEVICE_INFORMATION_SERVICE,BLE_UUID_TYPE_BLE}
};
#define CSCS_SERVICE_UUID_SCAN_IDX 0 /**< CSCS service UUID index in array. */
#define HART_RATE_SERVICE_UUID_SCAN_IDX 1 /**< Hart Rate service UUID index in array. */
#define BATTERY_SERVICE_UUID_SCAN_IDX 2 // Do we need this? /**< Battery Service UUID index in arrya. */
#define DEVICE_INFORMATION_SERVICE_UUID_SCAN_IDX 3 // Do we need this?
static ble_gap_scan_params_t m_scan_param = /**< Scan parameters requested for scanning and connection. */
{
.active = 0x01,
.interval = NRF_BLE_SCAN_SCAN_INTERVAL,
.window = NRF_BLE_SCAN_SCAN_WINDOW,
.filter_policy = BLE_GAP_SCAN_FP_ACCEPT_ALL,
.timeout = NRF_BLE_SCAN_SCAN_DURATION,
.scan_phys = BLE_GAP_PHY_1MBPS,
.extended = true,
};
static ble_sensor_location_t supported_locations[] = /**< Supported location for the sensor location. */
{
BLE_SENSOR_LOCATION_FRONT_WHEEL,
BLE_SENSOR_LOCATION_LEFT_CRANK,
BLE_SENSOR_LOCATION_RIGHT_CRANK,
BLE_SENSOR_LOCATION_LEFT_PEDAL,
BLE_SENSOR_LOCATION_RIGHT_PEDAL,
BLE_SENSOR_LOCATION_FRONT_HUB,
BLE_SENSOR_LOCATION_REAR_DROPOUT,
BLE_SENSOR_LOCATION_CHAINSTAY,
BLE_SENSOR_LOCATION_REAR_WHEEL,
BLE_SENSOR_LOCATION_REAR_HUB
};
/**@brief Strings to display data retrieved by Device Information Service client module. */
static char const * const m_dis_char_names[] =
{
"Manufacturer Name String",
"Model Number String ",
"Serial Number String ",
"Hardware Revision String",
"Firmware Revision String",
"Software Revision String",
"System ID",
"IEEE 11073-20601 Regulatory Certification Data List",
"PnP ID"
};
volatile uint8_t resistance_level = 1;
volatile uint8_t target_resistance_level = 1;
volatile int8_t gear_offset = 0;
volatile bool requireResistanceMinus;
volatile bool requireResistancePlus;
volatile bool doCalcResistance;
volatile bool is_advertising = false;
extern oled_data_t oled_data;
extern volatile bool doUpdateOLED;
extern volatile bool doInjectSimEvent;
extern volatile bool doTriggerFECEvent;
extern volatile bool doCalcModel;
extern volatile bool doSteer;
extern volatile bool gpio_busy;
extern volatile bool gpio_finished;
extern volatile gear_button_state_t gear_button_state;
/*
void in_pin_handler(nrf_drv_gpiote_pin_t pin, nrf_gpiote_polarity_t action)
{
switch (pin)
{
case TRAINER_BUTTON_INCLINE_UP:
NRF_LOG_INFO("Set incline up!");
break;
case TRAINER_BUTTON_INCLINE_DOWN:
NRF_LOG_INFO("Set incline down!");
break;
default:
break;
}
// NRF_LOG_FLUSH();
}
*/
/**@brief Function for handling asserts in the SoftDevice.
*
* @details This function is called in case of an assert in the SoftDevice.
*
* @warning This handler is an example only and is not meant for the final product. You need to analyze
* 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(0xDEADBEEF, line_num, p_file_name);
}
/**@brief Function for handling the Heart Rate Service Client
* Cycling Speed and Cadence Service Client.
*
* @param[in] nrf_error Error code containing information about what went wrong.
*/
static void service_error_handler(uint32_t nrf_error)
{
APP_ERROR_HANDLER(nrf_error);
}
/**@brief Function for handling errors from the Connection Parameters module.
*
* @param[in] nrf_error Error code containing information about what went wrong.
*/
static void conn_params_error_handler(uint32_t nrf_error)
{
APP_ERROR_HANDLER(nrf_error);
}
static void scan_evt_handler(scan_evt_t const * p_scan_evt)
{
ret_code_t err_code;
ble_gap_evt_adv_report_t const * p_adv =
p_scan_evt->params.filter_match.p_adv_report;
ble_gap_scan_params_t const * p_scan_param =
p_scan_evt->p_scan_params;
p_scan_evt->p_scan_params;
switch(p_scan_evt->scan_evt_id)
{
case NRF_BLE_SCAN_EVT_FILTER_MATCH:
{
// Initiate connection.
err_code = sd_ble_gap_connect(&p_adv->peer_addr,
p_scan_param,
&m_scan.conn_params,
APP_BLE_CONN_CFG_TAG);
APP_ERROR_CHECK(err_code);
} break;
default:
break;
}
}
static bool app_shutdown_handler(nrf_pwr_mgmt_evt_t event)
{
switch (event)
{
case NRF_PWR_MGMT_EVT_PREPARE_DFU:
NRF_LOG_INFO("Power management wants to reset to DFU mode.");
// YOUR_JOB: Get ready to reset into DFU mode
//
// If you aren't finished with any ongoing tasks, return "false" to
// signal to the system that reset is impossible at this stage.
//
// Here is an example using a variable to delay resetting the device.
//
// if (!m_ready_for_reset)
// {
// return false;
// }
// else
//{
//
// // Device ready to enter
// uint32_t err_code;
// err_code = sd_softdevice_disable();
// APP_ERROR_CHECK(err_code);
// err_code = app_timer_stop_all();
// APP_ERROR_CHECK(err_code);
//}
break;
default:
// YOUR_JOB: Implement any of the other events available from the power management module:
// -NRF_PWR_MGMT_EVT_PREPARE_SYSOFF
// -NRF_PWR_MGMT_EVT_PREPARE_WAKEUP
// -NRF_PWR_MGMT_EVT_PREPARE_RESET
return true;
}
NRF_LOG_INFO("Power management allowed to reset to DFU mode.");
return true;
}
static void disconnect(uint16_t conn_handle, void * p_context)
{
UNUSED_PARAMETER(p_context);
ret_code_t err_code = sd_ble_gap_disconnect(conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
if (err_code != NRF_SUCCESS)
{
NRF_LOG_WARNING("Failed to disconnect connection. Connection handle: %d Error: %d", conn_handle, err_code);
}
else
{
NRF_LOG_DEBUG("Disconnected connection handle %d", conn_handle);
}
}
//lint -esym(528, m_app_shutdown_handler)
/**@brief Register application shutdown handler with priority 0.
*/
NRF_PWR_MGMT_HANDLER_REGISTER(app_shutdown_handler, 0);
static void advertising_config_get(ble_adv_modes_config_t * p_config)
{
memset(p_config, 0, sizeof(ble_adv_modes_config_t));
p_config->ble_adv_fast_enabled = true;
p_config->ble_adv_fast_interval = APP_ADV_INTERVAL;
p_config->ble_adv_fast_timeout = APP_ADV_DURATION;
}
static void buttonless_dfu_sdh_state_observer(nrf_sdh_state_evt_t state, void * p_context)
{
if (state == NRF_SDH_EVT_STATE_DISABLED)
{
// Softdevice was disabled before going into reset. Inform bootloader to skip CRC on next boot.
nrf_power_gpregret2_set(BOOTLOADER_DFU_SKIP_CRC);
//Go to system off.
nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
}
}
/* nrf_sdh state observer. */
NRF_SDH_STATE_OBSERVER(m_buttonless_dfu_state_obs, 0) =
{
.handler = buttonless_dfu_sdh_state_observer,
};
// YOUR_JOB: Update this code if you want to do anything given a DFU event (optional).
/**@brief Function for handling dfu events from the Buttonless Secure DFU service
*
* @param[in] event Event from the Buttonless Secure DFU service.
*/
static void ble_dfu_evt_handler(ble_dfu_buttonless_evt_type_t event)
{
switch (event)
{
case BLE_DFU_EVT_BOOTLOADER_ENTER_PREPARE:
{
NRF_LOG_INFO("Device is preparing to enter bootloader mode.");
// Prevent device from advertising on disconnect.
ble_adv_modes_config_t config;
advertising_config_get(&config);
config.ble_adv_on_disconnect_disabled = true;
ble_advertising_modes_config_set(&m_advertising, &config);
// Disconnect all other bonded devices that currently are connected.
// This is required to receive a service changed indication
// on bootup after a successful (or aborted) Device Firmware Update.
uint32_t conn_count = ble_conn_state_for_each_connected(disconnect, NULL);
NRF_LOG_INFO("Disconnected %d links.", conn_count);
break;
}
case BLE_DFU_EVT_BOOTLOADER_ENTER:
// YOUR_JOB: Write app-specific unwritten data to FLASH, control finalization of this
// by delaying reset by reporting false in app_shutdown_handler
NRF_LOG_INFO("Device will enter bootloader mode.");
break;
case BLE_DFU_EVT_BOOTLOADER_ENTER_FAILED:
NRF_LOG_ERROR("Request to enter bootloader mode failed asynchroneously.");
// YOUR_JOB: Take corrective measures to resolve the issue
// like calling APP_ERROR_CHECK to reset the device.
break;
case BLE_DFU_EVT_RESPONSE_SEND_ERROR:
NRF_LOG_ERROR("Request to send a response to client failed.");
// YOUR_JOB: Take corrective measures to resolve the issue
// like calling APP_ERROR_CHECK to reset the device.
APP_ERROR_CHECK(false);
break;
default:
NRF_LOG_ERROR("Unknown event from ble_dfu_buttonless.");
break;
}
}
/**@brief Function for initialization the scanning and setting the filters.
*/
static void scan_init(void)
{
ret_code_t err_code;
nrf_ble_scan_init_t init_scan;
memset(&init_scan, 0, sizeof(init_scan));
init_scan.p_scan_param = &m_scan_param;
err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
APP_ERROR_CHECK(err_code);
if (strlen(m_target_periph_name) != 0)
{
err_code = nrf_ble_scan_filter_set(&m_scan,
SCAN_NAME_FILTER,
m_target_periph_name);
APP_ERROR_CHECK(err_code);
}
err_code = nrf_ble_scan_filter_set(&m_scan,
SCAN_UUID_FILTER,
&m_scan_uuids[CSCS_SERVICE_UUID_SCAN_IDX]);
APP_ERROR_CHECK(err_code);
err_code = nrf_ble_scan_filter_set(&m_scan,
SCAN_UUID_FILTER,
&m_scan_uuids[HART_RATE_SERVICE_UUID_SCAN_IDX]);
APP_ERROR_CHECK(err_code);
/*
// Would need to increase NRF_BLE_SCAN_UUID_CNT in sdk_config.h here!
err_code = nrf_ble_scan_filter_set(&m_scan,
SCAN_UUID_FILTER,
&m_scan_uuids[BATTERY_SERVICE_UUID_IDX]);
APP_ERROR_CHECK(err_code);
*/
err_code = nrf_ble_scan_filters_enable(&m_scan,
NRF_BLE_SCAN_ALL_FILTER,
false);
APP_ERROR_CHECK(err_code);
}
/**@brief Function for initializing the scanning.
*/
static void scan_start(void)
{
ret_code_t err_code;
err_code = nrf_ble_scan_start(&m_scan);
APP_ERROR_CHECK(err_code);
}
/**@brief Function for initializing the advertising and the scanning.
*/
static void adv_scan_start(void)
{
ret_code_t err_code;
//check if there are no flash operations in progress
if (!nrf_fstorage_is_busy(NULL))
{
// Start scanning for peripherals and initiate connection to devices which
// advertise Heart Rate or Cycling speed and cadence UUIDs.
scan_start();
// Turn on the LED to signal scanning.
bsp_board_led_on(CENTRAL_SCANNING_LED);
// Start advertising.
err_code = ble_advertising_start(&m_advertising, BLE_ADV_MODE_FAST);
APP_ERROR_CHECK(err_code);
}
}
/**@brief Function for handling Peer Manager events.
*
* @param[in] p_evt Peer Manager event.
*/
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_PEERS_DELETE_SUCCEEDED:
{
need_peer_delete = false;
//adv_scan_start();
// Deletion succeeded! Remove it from the deletion table.
//remove_peer_from_deletion_table(p_evt->peer_id);
NRF_LOG_INFO("PM_EVT_PEERS_DELETE_SUCCEEDED received");
break;
}
case PM_EVT_PEER_DELETE_SUCCEEDED:
{
need_peer_delete = false;
//adv_scan_start();
// Deletion succeeded! Remove it from the deletion table.
//remove_peer_from_deletion_table(p_evt->peer_id);
NRF_LOG_INFO("PM_EVT_PEER_DELETE_SUCCEEDED received: Peer-ID: %u", p_evt->peer_id);
// Try to re-eanble adv and scan
scan_init();
advertising_init();
break;
}
case PM_EVT_PEER_DELETE_FAILED:
{
// Again, for this design, if we fail to delete the peer,
// were giving up and removing it from the deletion table,
// but your application may need to handle it differently.
//remove_peer_from_deletion_table(p_evt->peer_id);
NRF_LOG_INFO("PM_EVT_PEER_DELETE_FAILED received: Peer-ID: %u", p_evt->peer_id);
}
case PM_EVT_PEERS_DELETE_FAILED:
{
// Again, for this design, if we fail to delete the peer,
// were giving up and removing it from the deletion table,
// but your application may need to handle it differently.
//remove_peer_from_deletion_table(p_evt->peer_id);
NRF_LOG_INFO("PM_EVT_PEERS_DELETE_FAILED received");
}
break;
case PM_EVT_CONN_SEC_FAILED:
{
//NRF_LOG_INFO("Establishing a secure link by Peer Manager failed! Please press Button 2 + RESET on the DK to delete bonding data");
pm_conn_secure_failed_evt_t e = p_evt->params.conn_sec_failed;
pm_sec_error_code_t error = e.error;
uint8_t error_src = e.error_src;
pm_conn_sec_procedure_t procedure = e.procedure;
switch (procedure)
{
case PM_CONN_SEC_PROCEDURE_ENCRYPTION:
NRF_LOG_INFO("PM_CONN_SEC_PROCEDURE_ENCRYPTION procedure failed");
break;
case PM_CONN_SEC_PROCEDURE_BONDING:
NRF_LOG_INFO("PM_CONN_SEC_PROCEDURE_BONDING procedure failed");
break;
case PM_CONN_SEC_PROCEDURE_PAIRING:
NRF_LOG_INFO("PM_CONN_SEC_PROCEDURE_PAIRING procedure failed");
break;
default:
NRF_LOG_INFO("Unknown peer manager procedure failed");
break;
}
switch (error)
{
case PM_CONN_SEC_ERROR_PIN_OR_KEY_MISSING:
NRF_LOG_INFO("Error PM_CONN_SEC_ERROR_PIN_OR_KEY_MISSING");
break;
case PM_CONN_SEC_ERROR_MIC_FAILURE:
NRF_LOG_INFO("Error PM_CONN_SEC_ERROR_MIC_FAILURE");
break;
case PM_CONN_SEC_ERROR_DISCONNECT:
NRF_LOG_INFO("Error PM_CONN_SEC_ERROR_DISCONNECT");
break;
case PM_CONN_SEC_ERROR_SMP_TIMEOUT :
NRF_LOG_INFO("Error PM_CONN_SEC_ERROR_SMP_TIMEOUT");
break;
default:
NRF_LOG_INFO("Unknown error");
break;
}
NRF_LOG_INFO("Establishing a secure link by Peer Manager failed! Trying to remove bonds and rescan");
err_code = bond_mgr_queue_peer_for_deletion(p_evt->peer_id);
APP_ERROR_CHECK(err_code);
need_peer_delete = true;
//delete_bonds();
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;
default:
break;
}
}
/**@brief Function for changing filter settings after establishing the connection.
*/
static void filter_settings_change(void)
{
ret_code_t err_code;
err_code = nrf_ble_scan_all_filter_remove(&m_scan);
APP_ERROR_CHECK(err_code);
if (strlen(m_target_periph_name) != 0)
{
err_code = nrf_ble_scan_filter_set(&m_scan,
SCAN_NAME_FILTER,
m_target_periph_name);
APP_ERROR_CHECK(err_code);
}
if (m_conn_handle_cscs_c == BLE_CONN_HANDLE_INVALID)
{
err_code = nrf_ble_scan_filter_set(&m_scan,
SCAN_UUID_FILTER,
&m_scan_uuids[CSCS_SERVICE_UUID_SCAN_IDX]);
}
/*else if ((m_conn_handle_cscs_c != BLE_CONN_HANDLE_INVALID) &&
(m_conn_handle_bas_c == BLE_CONN_HANDLE_INVALID))
{
err_code = nrf_ble_scan_filter_set(&m_scan,
SCAN_UUID_FILTER,
&m_scan_uuids[BATTERY_SERVICE_UUID_IDX]);
}*/
else if ((m_conn_handle_cscs_c != BLE_CONN_HANDLE_INVALID) &&
// (m_conn_handle_bas_c != BLE_CONN_HANDLE_INVALID) &&
(m_conn_handle_hrs_c == BLE_CONN_HANDLE_INVALID))
{
err_code = nrf_ble_scan_filter_set(&m_scan,
SCAN_UUID_FILTER,
&m_scan_uuids[HART_RATE_SERVICE_UUID_SCAN_IDX]);
}
APP_ERROR_CHECK(err_code);
}
/**@brief Handles events coming from the Heart Rate central module.
*/
static void hrs_c_evt_handler(ble_hrs_c_t * p_hrs_c, ble_hrs_c_evt_t * p_hrs_c_evt)
{
switch (p_hrs_c_evt->evt_type)
{
case BLE_HRS_C_EVT_DISCOVERY_COMPLETE:
{
if (m_conn_handle_hrs_c == BLE_CONN_HANDLE_INVALID)
{
ret_code_t err_code;
m_conn_handle_hrs_c = p_hrs_c_evt->conn_handle;
NRF_LOG_INFO("HRS discovered on conn_handle 0x%x", m_conn_handle_hrs_c);
filter_settings_change();
err_code = ble_hrs_c_handles_assign(p_hrs_c,
m_conn_handle_hrs_c,
&p_hrs_c_evt->params.peer_db);
APP_ERROR_CHECK(err_code);
// Initiate bonding.
err_code = pm_conn_secure(m_conn_handle_hrs_c, false);
if (err_code != NRF_ERROR_BUSY)
{
APP_ERROR_CHECK(err_code);
}
// Heart rate service discovered. Enable notification of Heart Rate Measurement.
err_code = ble_hrs_c_hrm_notif_enable(p_hrs_c);
APP_ERROR_CHECK(err_code);
}
} break; // BLE_HRS_C_EVT_DISCOVERY_COMPLETE
case BLE_HRS_C_EVT_HRM_NOTIFICATION:
{
ret_code_t err_code;
// NRF_LOG_INFO("Heart Rate = %d", p_hrs_c_evt->params.hrm.hr_value);
err_code = ble_hrs_heart_rate_measurement_send(&m_hrs, p_hrs_c_evt->params.hrm.hr_value);
if ((err_code != NRF_SUCCESS) &&
(err_code != NRF_ERROR_INVALID_STATE) &&
(err_code != NRF_ERROR_RESOURCES) &&
(err_code != NRF_ERROR_BUSY) &&
(err_code != BLE_ERROR_GATTS_SYS_ATTR_MISSING)
)
{
APP_ERROR_HANDLER(err_code);
}
} break; // BLE_HRS_C_EVT_HRM_NOTIFICATION
default:
// No implementation needed.
break;
}
}
/**@brief Handles events coming from the Battery central module.
*/
static void bas_c_evt_handler(ble_bas_c_t * p_bas_c, ble_bas_c_evt_t * p_bas_c_evt)
{
switch (p_bas_c_evt->evt_type)
{
case BLE_BAS_C_EVT_DISCOVERY_COMPLETE:
{
if (m_conn_handle_bas_c[0] == BLE_CONN_HANDLE_INVALID)
{
ret_code_t err_code;
m_conn_handle_bas_c[0] = p_bas_c_evt->conn_handle;
NRF_LOG_INFO("BAS 1 discovered on conn_handle 0x%x", m_conn_handle_bas_c[0]);
filter_settings_change();
err_code = ble_bas_c_handles_assign(&p_bas_c[0],
m_conn_handle_bas_c[0],
&p_bas_c_evt->params.bas_db);
APP_ERROR_CHECK(err_code);
NRF_LOG_INFO("Battery Service 1 discovered. Reading battery level.");
err_code = ble_bas_c_bl_read(&p_bas_c[0]);
APP_ERROR_CHECK(err_code);
// Battery service discovered. Enable notification of Battery Measurement.
//NRF_LOG_INFO("Enabling Battery Level Notification.");
//err_code = ble_bas_c_bl_notif_enable(p_bas_c);
//APP_ERROR_CHECK(err_code);
}
else if (m_conn_handle_bas_c[1] == BLE_CONN_HANDLE_INVALID)
{
ret_code_t err_code;
m_conn_handle_bas_c[1] = p_bas_c_evt->conn_handle;
NRF_LOG_INFO("BAS 2 discovered on conn_handle 0x%x", m_conn_handle_bas_c[1]);
filter_settings_change();
err_code = ble_bas_c_handles_assign(&p_bas_c[1],
m_conn_handle_bas_c[1],
&p_bas_c_evt->params.bas_db);
APP_ERROR_CHECK(err_code);
NRF_LOG_INFO("Battery Service 2 discovered. Reading battery level.");
err_code = ble_bas_c_bl_read(&p_bas_c[1]);
APP_ERROR_CHECK(err_code);
// Battery service discovered. Enable notification of Battery Measurement.
//NRF_LOG_INFO("Enabling Battery Level Notification.");
//err_code = ble_bas_c_bl_notif_enable(p_bas_c);
//APP_ERROR_CHECK(err_code);
}
} break; // BLE_BAS_C_EVT_DISCOVERY_COMPLETE
case BLE_BAS_C_EVT_BATT_NOTIFICATION:
{
ret_code_t err_code;
// We can only report one battery!
NRF_LOG_INFO("Battery = %d", p_bas_c_evt->params.battery_level);
err_code = ble_bas_battery_level_update(&m_bas, p_bas_c_evt->params.battery_level,BLE_CONN_HANDLE_ALL);
if ((err_code != NRF_SUCCESS) &&
(err_code != NRF_ERROR_INVALID_STATE) &&
(err_code != NRF_ERROR_RESOURCES) &&
(err_code != NRF_ERROR_BUSY) &&
(err_code != BLE_ERROR_GATTS_SYS_ATTR_MISSING)
)
{
APP_ERROR_HANDLER(err_code);
}
} break; // BLE_BAS_C_EVT_BAM_NOTIFICATION
case BLE_BAS_C_EVT_BATT_READ_RESP:
NRF_LOG_INFO("Battery Level Read as %d %%.", p_bas_c_evt->params.battery_level);
break;
default:
// No implementation needed.
break;
}
}
/**@brief Function for reading all characteristics that can be present in DIS.
*
* @return The number of discovered characteristics.
*/
static uint32_t ble_dis_c_all_chars_read(uint8_t instance)
{
ret_code_t err_code;
uint32_t disc_char_num = 0;
for (ble_dis_c_char_type_t char_type = (ble_dis_c_char_type_t) 0;
char_type < BLE_DIS_C_CHAR_TYPES_NUM;
char_type++)
{
err_code = ble_dis_c_read(&m_dis_c[instance], char_type);
// The NRF_ERROR_INVALID_STATE error code means that the characteristic is not present in DIS.
if (err_code != NRF_ERROR_INVALID_STATE)
{
APP_ERROR_CHECK(err_code);
disc_char_num++;
}