-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.c
2324 lines (1861 loc) · 73.2 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
/**
*/
/** @file
*
* @defgroup main.c
* @{
* @}
* @ingroup
* @brief
*
* This file contains the source code for a sample application.
*/
#include <stdint.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>
#include "boards.h"
#include "nordic_common.h"
#ifdef FREERTOS
#include "FreeRTOS.h"
#include "task.h"
#include "timers.h"
#include "nrf_sdh_freertos.h"
#endif
#include "bsp.h"
#include "nrf_drv_clock.h"
#include "nrf.h"
#include "sdk_errors.h"
#include "app_error.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 "ble.h"
#include "ble_advdata.h"
#include "ble_advertising.h"
#include "ble_conn_params.h"
#include "ble_db_discovery.h"
#include "ble_conn_state.h"
//#include "nrf_fstorage.h"
//#include "fds.h"
#include "nrf_ble_gatt.h"
#include "nrf_ble_qwr.h"
#include "app_timer.h"
#include "app_util_platform.h"
#include "bsp_btn_ble.h"
#include "nrf_pwr_mgmt.h"
#include "nrf_drv_timer.h"
#include "nrf_ble_scan.h"
#include "nrf_delay.h"
#include "nrf_timer.h"
#include "nrf_drv_gpiote.h"
#include "nrf_gpiote.h"
#include "time_sync.h"
#include "nrf_ppi.h"
#include "ServiceConfig.h"
#include "ServiceDebug.h"
#include "TimedCircBuffer.h"
#include "ScanList.h"
#include "BroadcastAdvertising.h"
#include "Config.h"
#include "amt.h"
#include "HwTimers.h"
#include "HwSensor.h"
//#define NRF_LOG_MODULE_NAME main
//#define NRF_LOG_LEVEL 4
#include "nrf_log.h"
#include "nrf_log_ctrl.h"
#include "nrf_log_default_backends.h"
// Relay application related LEDs
#define PERIPHERAL_ADVERTISING_LED -1
#define PERIPHERAL_CONNECTED_LED -1
#define CENTRAL_SCANNING_LED -1
#define CENTRAL_CONNECTED_LED -1
// AMT related LEDs
#define READY_LED -1
#define PROGRESS_LED -1
#define DONE_LED -1
#define CENTRAL_DEVICE_NAME "nRF Relay\0" /**< Name of device used for advertising. */
#define PERIPHERAL_DEVICE_NAME "nRF_Node"
#define AMTS_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 MSEC_TO_UNITS(500, UNIT_1_25_MS) /**< The advertising interval (in units of 0.625 ms). This value corresponds to 500 ms. */
#define APP_ADV_DURATION_FIRST 400 /**< The advertising duration (180 seconds) in units of 10 milliseconds of the first advertising period. */
#define APP_ADV_DURATION 18000 /**< The advertising duration (180 seconds) in units of 10 milliseconds of all subsequent periods. */
#define APP_BLE_CONN_CFG_TAG 1 /**< Tag that identifies the SoftDevice BLE configuration. */
#define MIN_CONN_INTERVAL MSEC_TO_UNITS(20, UNIT_1_25_MS) /**< Minimum acceptable connection interval (20 ms), Connection interval uses 1.25 ms units. */
#define MAX_CONN_INTERVAL MSEC_TO_UNITS(75, 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. */
#define SEC_PARAM_BOND 0 /**< 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. */
/**@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 1 /**< Number of DB Discovery instances. */
NRF_BLE_GQ_DEF(m_ble_gatt_queue, /**< BLE GATT Queue instance. */
NRF_SDH_BLE_CENTRAL_LINK_COUNT,
NRF_BLE_GQ_QUEUE_SIZE);
NRF_BLE_GATT_DEF(m_gatt); /**< GATT module instance. */
NRF_BLE_SCAN_DEF(m_scan); /**< Scanning Module instance. */
NRF_BLE_QWRS_DEF(m_qwr, /**< Context for the Queued Write module.*/
NRF_SDH_BLE_TOTAL_LINK_COUNT);
BLE_ADVERTISING_DEF(m_advertising); /**< Advertising module instance. */
BLE_DB_DISCOVERY_ARRAY_DEF(m_db_discovery, /**< Database discovery module instances. */
DB_DISCOVERY_INSTANCE_CNT);
//BLE_DBG_DEF(m_dbg);
static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; /**< Handle of the current peripheral-role connection. */
/**@brief Definition of the application timers used.
*/
APP_TIMER_DEF(m_sync_timer);
APP_TIMER_DEF(m_sleep_timer);
APP_TIMER_DEF(m_scan_timer);
APP_TIMER_DEF(notif_timeout);
APP_TIMER_DEF(m_reading_timer);
APP_TIMER_DEF(led_flash_timer);
#define SLEEP_TIMEOUT_PERIPHERAL APP_TIMER_TICKS(5*60*1000) /**< Timeout for peripheral to wait before sleeping -- 0 to indicate no timeout. */
#define SLEEP_TIMEOUT_CENTRAL APP_TIMER_TICKS(10*60*1000) /**< Timeout for peripheral to wait before sleeping -- 0 to indicate no timeout. */
#define SCAN_TIMEOUT APP_TIMER_TICKS(120000) /**< Time between doing scans */
static void notif_timeout_handler(void * p_context);
static void scan_timer_timeout_handler(void * p_context);
static void do_time_sync(void);
static void sync_timer_init(void);
static void sync_timer_stop(void);
//NRF_BLE_GQ_DEF(m_ble_gatt_queue, /**< BLE GATT Queue instance. */
// NRF_SDH_BLE_CENTRAL_LINK_COUNT,
// NRF_BLE_GQ_QUEUE_SIZE);
//static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
// ^---------------- never used ???
/**@brief AMT Service UUID. */
static ble_uuid_t const m_scan_uuid =
{
.uuid = AMT_SERVICE_UUID,
.type = AMTS_SERVICE_UUID_TYPE
};
/**@brief UUIDs to advertise. */
static ble_uuid_t m_adv_uuids[] =
{
{AMT_SERVICE_UUID, AMTS_SERVICE_UUID_TYPE}
};
/**@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[] = "";
static ble_gap_scan_params_t m_scan_param_central = /**< 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_gap_scan_params_t m_scan_param_peripheral = /**< Scan parameters requested for scanning only. */
{
.active = 0x00,
.extended = 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,
};
/* Define the configs */
config_service_t cfgs;
static void scan_start (void);
static void scan_stop (void);
#define DEVICE_ID_BYTE_0_ADDR 0x10000060
#define DEVICE_ID_BYTE_0 (*((uint8_t const * const)DEVICE_ID_BYTE_0_ADDR))
static bool privateIsCentral = false;
static inline void SetAsCentral(bool new_value)
{
privateIsCentral = new_value;
}
static const bool isCentral(void) {return privateIsCentral;}
static const bool isPeripheral(void) {return !isCentral();}
bool publicIsCentral(void){ return isCentral(); }
static void amts_evt_handler(nrf_ble_amts_evt_t);
static nrf_ble_amts_t m_amts;
NRF_SDH_BLE_OBSERVER(m_amts_ble_obs, BLE_AMTS_BLE_OBSERVER_PRIO, nrf_ble_amts_on_ble_evt, &m_amts);
static void amtc_evt_handler(nrf_ble_amtc_t *, nrf_ble_amtc_evt_t *);
static nrf_ble_amtc_t m_amtc;
NRF_SDH_BLE_OBSERVER(m_amtc_ble_obs, BLE_AMTC_BLE_OBSERVER_PRIO, nrf_ble_amtc_on_ble_evt, &m_amtc);
static ret_code_t BroadcastAdvertising_SetUp(ble_advertising_t * const p_advertising, bool isBroadcast);
/**@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 bool isAwake = false;
static void do_sleep(void)
{
if (isAwake)
{
isAwake = false;
scan_stop();
hw_timers_stop();
led_flash_seq_stop();
sensor_off();
if (isUseSyncTimer())
{
sync_timer_stop();
}
gpio_off();
}
}
static void do_wake(void)
{
if (!isAwake)
{
isAwake = true;
led_flash_seq_start();
TimedCircBuffer_Clear();
if (isPeripheral()) // << for testing only, don't want central scanning
{
scan_start();
}
if (isUseSyncTimer())
{
sync_timer_init();
}
sensor_on();
gpio_on();
}
}
bool IsAwake(void) {return isAwake;}
static void on_sleep_timer_timeout(void * p_context)
{
(void) p_context;
// The timer has timed out. Can sleep at this point (continuing advertising).
do_sleep();
}
static void flash_led(void)
{
ret_code_t err_code;
bsp_board_led_on(BSP_BOARD_LED_0);
err_code = app_timer_start(led_flash_timer, APP_TIMER_TICKS(200), (void *) 0);
APP_ERROR_CHECK(err_code);
}
static void led_flash_timeout_handler(void * p_context)
{
bsp_board_led_off(BSP_BOARD_LED_0);
}
static void reading_timeout_handler(void * p_context);
static void BroadcastAdvertising_SetData(uint32_t, enum BroadcastTypes);
/** Supported by Central only. Trigger a reading in all leaf devices. */
void doTrigger(enum BroadcastTypes ty)
{
if (!isCentral())
{
APP_ERROR_CHECK(NRF_ERROR_FORBIDDEN);
}
if (m_conn_handle != BLE_CONN_HANDLE_INVALID) // Only do broadcast if we're connected as peripheral -- otherwise are busy advertising
{
ret_code_t err_code;
//(void) sd_ble_gap_adv_stop(m_advertising.adv_handle);
if (isUseSyncTimer())
{
BroadcastAdvertising_SetData( (uint32_t) (ts_timestamp_get_ticks_u64(6) / 32000ULL) , ty );
}
err_code = BroadcastAdvertising_SetUp(&m_advertising, true);
APP_ERROR_CHECK(err_code);
// Now do a simplified version of ble_advertising_Start() with a non-default version of properties.type
m_advertising.adv_mode_current = BLE_ADV_MODE_FAST;
if (true)
m_advertising.adv_params.properties.type = BLE_GAP_ADV_TYPE_NONCONNECTABLE_SCANNABLE_UNDIRECTED;
else
m_advertising.adv_params.properties.type = BLE_GAP_ADV_TYPE_CONNECTABLE_SCANNABLE_UNDIRECTED;
err_code = sd_ble_gap_adv_set_configure(&m_advertising.adv_handle, m_advertising.p_adv_data, &m_advertising.adv_params);
APP_ERROR_CHECK(err_code);
err_code = sd_ble_gap_adv_start(m_advertising.adv_handle, m_advertising.conn_cfg_tag);
APP_ERROR_CHECK(err_code);
NRF_LOG_INFO("Started scannable adv.");
}
}
/**@brief Function for initializing the timer module.
*/
static void timers_init(void)
{
ret_code_t err_code = app_timer_init();
APP_ERROR_CHECK(err_code);
err_code = app_timer_create(&m_sleep_timer, APP_TIMER_MODE_SINGLE_SHOT, on_sleep_timer_timeout);
APP_ERROR_CHECK(err_code);
isAwake = true;
if (isPeripheral())
{
if (SLEEP_TIMEOUT_PERIPHERAL != 0)
{
err_code = app_timer_start(m_sleep_timer, SLEEP_TIMEOUT_PERIPHERAL, (void *) 0);
APP_ERROR_CHECK(err_code);
}
}
else
{
if (SLEEP_TIMEOUT_CENTRAL != 0)
{
err_code = app_timer_start(m_sleep_timer, SLEEP_TIMEOUT_CENTRAL, (void *) 0);
APP_ERROR_CHECK(err_code);
}
err_code = app_timer_create(&m_scan_timer, APP_TIMER_MODE_REPEATED, scan_timer_timeout_handler);
APP_ERROR_CHECK(err_code);
err_code = app_timer_start(m_scan_timer, SCAN_TIMEOUT, (void *) 0);
APP_ERROR_CHECK(err_code);
err_code = app_timer_create(¬if_timeout, APP_TIMER_MODE_REPEATED, notif_timeout_handler);
APP_ERROR_CHECK(err_code);
err_code = app_timer_create(&m_reading_timer, APP_TIMER_MODE_SINGLE_SHOT, reading_timeout_handler);
APP_ERROR_CHECK(err_code);
}
err_code = app_timer_create(&led_flash_timer, APP_TIMER_MODE_SINGLE_SHOT, led_flash_timeout_handler);
APP_ERROR_CHECK(err_code);
}
/**@brief Function for the GAP initialization.
*
* @details This function will set up all the necessary GAP (Generic Access Profile) parameters of
* the device. It also sets the permissions and appearance.
*/
static void gap_params_init(const bool central)
{
ret_code_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);
err_code = sd_ble_gap_device_name_set(&sec_mode,
central ? (const uint8_t *)CENTRAL_DEVICE_NAME : (const uint8_t *)PERIPHERAL_DEVICE_NAME,
central ? strlen(CENTRAL_DEVICE_NAME) : strlen(PERIPHERAL_DEVICE_NAME));
APP_ERROR_CHECK(err_code);
memset(&gap_conn_params, 0, sizeof(gap_conn_params));
#if 1 // def PERIPHERAL
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;
#else
gap_conn_params.min_conn_interval = m_scan.conn_params.min_conn_interval;
gap_conn_params.max_conn_interval = m_scan.conn_params.max_conn_interval;
gap_conn_params.slave_latency = m_scan.conn_params.slave_latency;
gap_conn_params.conn_sup_timeout = m_scan.conn_params.conn_sup_timeout;
#endif
err_code = sd_ble_gap_ppcp_set(&gap_conn_params);
APP_ERROR_CHECK(err_code);
}
/**@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);
}
/**@brief Function for handling events from the Config module.
*/
uint16_t cfgs_handler(ble_evt_t const * p_evt)
{
return service_cfg_on_ble_evt(&cfgs, p_evt);
}
/**@snippet [Handling the data received over BLE] */
/**@brief Function for initializing services that will be used by the application.
*/
static void services_init(void)
{
uint32_t err_code;
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[0], &qwr_init);
APP_ERROR_CHECK(err_code);
// Add the base UUID. Don't do anything with it for now, the individual services
// will be using it.
ble_uuid128_t sync_app_base_uuid = {SYNC_APP_UUID_BASE};
uint8_t uuid_type;
err_code = sd_ble_uuid_vs_add(&sync_app_base_uuid, &uuid_type);
APP_ERROR_CHECK(err_code);
(void) uuid_type;
//err_code = ble_debug_service_init(&m_dbg);
//APP_ERROR_CHECK(err_code);
// Initialise AMTS service
// A Central device needs a big TX FIFO in order to relay large data sets.
// The Peripheral does not, as it just uses data directly from its own
// buffer spaces.
nrf_ble_amts_init(&m_amts, amts_evt_handler, (isCentral() ? 16384 : 1024), 256);
if (isCentral())
{
// Initialise the ATMC service.
nrf_ble_amtc_init_t amtc_init;
memset(&amtc_init, 0, sizeof(amtc_init));
amtc_init.evt_handler = amtc_evt_handler;
amtc_init.p_gatt_queue = &m_ble_gatt_queue;
err_code = nrf_ble_amtc_init(&m_amtc, &amtc_init);
APP_ERROR_CHECK(err_code);
}
// Initialise the Config service
service_config_init_t cfgs_init;
cfgs_init.evt_handler = NULL;
cfgs_init.error_handler = NULL;
cfgs_init.p_cfgs_ctx = NULL;
(void) service_config_init(&cfgs_init, &cfgs);
}
/**@brief Function for handling an event from the Connection Parameters Module.
*
* @details This function will be called for all events in the Connection Parameters Module
* which are passed to the application.
*
* @note All this function does is to disconnect. This could have been done by simply setting
* the disconnect_on_fail config parameter, but instead we use the event handler
* mechanism to demonstrate its use.
*
* @param[in] p_evt Event received from the Connection Parameters Module.
*/
static void on_conn_params_evt(ble_conn_params_evt_t * p_evt)
{
uint32_t err_code;
if (p_evt->evt_type == BLE_CONN_PARAMS_EVT_FAILED)
{
err_code = sd_ble_gap_disconnect(p_evt->conn_handle, BLE_HCI_CONN_INTERVAL_UNACCEPTABLE);
APP_ERROR_CHECK(err_code);
}
}
/**@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);
}
/**@brief Function for initializing the Connection Parameters module.
*/
static void conn_params_init(void)
{
ret_code_t err_code;
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_CONN_HANDLE_INVALID; // Start upon connection.
cp_init.disconnect_on_fail = false;
cp_init.evt_handler = on_conn_params_evt;
cp_init.error_handler = conn_params_error_handler;
err_code = ble_conn_params_init(&cp_init);
APP_ERROR_CHECK(err_code);
}
#ifdef PERIPHERAL
/**@brief Function for putting the chip into sleep mode.
*
* @note This function will not return.
*/
__attribute__ (( unused ))
static void sleep_mode_enter(void)
{
uint32_t err_code = bsp_indication_set(BSP_INDICATE_IDLE);
APP_ERROR_CHECK(err_code);
// Prepare wakeup buttons.
// err_code = bsp_btn_ble_sleep_mode_prepare();
// APP_ERROR_CHECK(err_code);
// Go to system-off mode (this function will not return; wakeup will cause a reset).
err_code = sd_power_system_off();
APP_ERROR_CHECK(err_code);
}
#endif
/**@brief Function for handling the Heart Rate Service Client
* Running Speed and Cadence Service Client.
*
* @param[in] nrf_error Error code containing information about what went wrong.
*/
__attribute__ (( unused ))
static void service_error_handler(uint32_t nrf_error)
{
APP_ERROR_HANDLER(nrf_error);
}
static void check_manu_data(unsigned char const * x, int len)
{
// Check if manufacturer data meets the expected format.
if (len >= 2 + /*sizeof(BroadcastData_T)*/ 5)
{
ble_advdata_manuf_data_t const * manu = (ble_advdata_manuf_data_t const *) x;
if (manu->company_identifier == MY_MANUFACTURER_ID)
{
if (isPeripheral())
{
const BroadcastData_T * receivedData = (BroadcastData_T const *) &x[2];
NRF_LOG_DEBUG("MANU DATA: 0x%x", receivedData->type);
if (receivedData->type == BroadcastType_RequestLock)
{
// Pretend like we've received a lock instruction INSTRUCTION_CODE__LOCK
const uint32_t INSTRUCTION_CODE__LOCK = 0x0A;
(void) TimedCircBuffer_RxOperation_NoResponse(INSTRUCTION_CODE__LOCK, *((uint32_t const *)receivedData->data));
}
}
}
}
}
/** Returns true if trigger magnitude is to be uploaded. If true, then all other operation will not
* proceed. If false, it will still be uploaded but after the trigger broadcast has completed. Should
* normally be false. */
static inline bool uploadSimpleTrigger(void)
{
if (!isUploadTriggerSize())
{
return false;
}
return ((cfgs.value_3 & CONFIG_3_SIMPLE_TRIGGER_MASK) == CONFIG_3_SIMPLE_TRIGGER_MASK);
}
static uint32_t last_trigger_size = 0UL;
static void doTriggerUpload(void)
{
NRF_LOG_DEBUG("UPLOAD Trigger 0x%x", last_trigger_size);
uint32_t root_size = (uint32_t) sqrtf((float) last_trigger_size);
last_trigger_size = 0UL; // Clear the static value.
uint32_t data [3] = {0x80000022, root_size, (uint32_t) (ts_timestamp_get_ticks_u64(6) / 32000ULL) };
amts_queue_tx_data((uint8_t const *) &data, 3*sizeof(uint32_t));
}
/** Called to indicate a trigger event, and to kick-start the response to it. This only
* happens in a Central device.
*
* "size" indicates the square magnitude of the trigger event. If the trigger is an
* acceleration event (normally that will be the case), this will be in units of m^2 s^-4. */
void trigger(uint32_t size)
{
last_trigger_size = size;
if (m_conn_handle != BLE_CONN_HANDLE_INVALID)
{
/* If simple trigger upload is selected, upload the magnitude and take no other action. */
if (LeafListCount() == 0 || uploadSimpleTrigger())
{
doTriggerUpload();
}
/* Otherwise, send to leaf nodes if there are any. */
else if (!isLedOnBroadcast() && LeafListCount() > 0)
{
doTrigger(BroadcastType_RequestLock);
}
}
}
/** Returns true if triggered. */
static bool trigger_from_scan_timer_timeout(void)
{
if (isSendOccasionalDebugTriggers() && m_conn_handle != BLE_CONN_HANDLE_INVALID && LeafListCount() > 0)
{
bool debugCase = false;
const int countdownTop = 10;
static int countdown = 5; // Start half-way, so we don't have to wait so long.
countdown ++;
if (countdown >= countdownTop)
{
countdown = 0;
debugCase = true;
}
if (debugCase)
{
// Need to have advertising available to us.
if (m_advertising.adv_mode_current != BLE_ADV_MODE_IDLE)
{
return false;
}
doTrigger(BroadcastType_Debug);
return true;
}
}
return false;
}
/** Returns true if scan started. */
static bool scan_from_scan_timer_timeout(void)
{
if (isCentral() && m_conn_handle != BLE_CONN_HANDLE_INVALID)
{
// If not connected, time syncs are aligned with advertising timeouts. When
// connected there is not that route, so we must do here.
do_time_sync();
}
else if (IsAwake())
{
scan_start();
return true;
}
return false;
}
static bool doingDownload = false;
static unsigned int downloadPtr = 0;
#define READING_TIMEOUT_FIRST APP_TIMER_TICKS(5000) // Need a long initial timeout to let the readings complete
#define READING_TIMEOUT APP_TIMER_TICKS(200)
static bool do_a_connection(void)
{
// Connect to next unit
if (ConnectLeaf(downloadPtr, &m_scan))
{
downloadPtr ++;
return true;
}
else
{
// The readout is finished.
doingDownload = false;
return false;
}
}
static bool doNextConnection(void)
{
if (doingDownload)
{
app_timer_start(m_reading_timer, READING_TIMEOUT, (void *) 0);
return true;
}
return false;
}
__attribute__ (( unused ))
static bool doConnectionAndDownload(void)
{
// If any found, then connect to them
if (LeafListCount() > 0)
{
doingDownload = true;
downloadPtr = 0;
app_timer_start(m_reading_timer, READING_TIMEOUT_FIRST, (void *) 0);
return true;
}
return false;
}
static void reading_timeout_handler(void * p_context)
{
do_a_connection();
}
/** Returns true if should upload the leaf list to the host after completing each scan. As currently implemented,
* the central relaying functionality is not used so this will always be true. */
static inline bool mustUploadLeafList(void)
{
return ((cfgs.value_3 & CONFIG_3_UPLOAD_LEAF_LIST_MASK) == CONFIG_3_UPLOAD_LEAF_LIST_MASK);
}
static void upload_leaf_list(void)
{
ScanListClearReading();
StartSending(&ScanList_FifoFill, 0);
}
/**@brief Function for handling Scanning Module events.
*/
static void scan_evt_handler(scan_evt_t const * p_scan_evt)
{
ret_code_t err_code;
switch(p_scan_evt->scan_evt_id)
{
case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
{
NRF_LOG_WARNING("Scan connecting error");
err_code = p_scan_evt->params.connecting_err.err_code;
APP_ERROR_CHECK(err_code);
} break;
case NRF_BLE_SCAN_EVT_CONNECTED:
{
ble_gap_evt_connected_t const * p_connected =
p_scan_evt->params.connected.p_connected;
// Scan is automatically stopped by the connection.
NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
p_connected->peer_addr.addr[0],
p_connected->peer_addr.addr[1],
p_connected->peer_addr.addr[2],
p_connected->peer_addr.addr[3],
p_connected->peer_addr.addr[4],
p_connected->peer_addr.addr[5]
);
} break;
case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
{
NRF_LOG_INFO("Scan timed out.");
if (isCentral() && m_conn_handle != BLE_CONN_HANDLE_INVALID && mustUploadLeafList())
{
upload_leaf_list();
}
else if (isPeripheral())
{
// Peripheral should keep continually scanning.
scan_start();
}
// Scan completed. Now start beaconing.
// (void)doConnectionAndDownload();
} break;
case NRF_BLE_SCAN_EVT_FILTER_MATCH:
{
NRF_LOG_INFO("Scan filter match");
on_scan_list_scan_evt(p_scan_evt);
// Initiate connection - don't need to do this, since using "connect_if_match".
//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;
case NRF_BLE_SCAN_EVT_NOT_FOUND:
{
if (isCentral())
{
NRF_LOG_INFO("Scan not found");
// It's not clear why this will be called in the central case. Best to ignore it.
}
else
{
// This is called if a device is seen without filters enabled, i.e. the peripheral case.
ble_gap_evt_adv_report_t const * adv = p_scan_evt->params.p_not_found;
// Only recognise non-connectable, non-scannable and non-directed advertisements.
if (!adv->type.connectable && !!adv->type.scannable && !adv->type.directed)
{
NRF_LOG_INFO("Scan not found");
uint16_t offs = 0;
uint16_t len = ble_advdata_search(adv->data.p_data, adv->data.len, &offs, BLE_GAP_AD_TYPE_MANUFACTURER_SPECIFIC_DATA);
if (len > 0)
{
check_manu_data(&adv->data.p_data[offs], len);
}
}
}
} break;
default:
NRF_LOG_INFO("Scan evt: 0x%x", p_scan_evt->scan_evt_id);
break;
}
}
/**@brief Function for initializing the scanning and setting the filters.
*/
static void scan_init(void)
{
if (isPeripheral())
{
ret_code_t err_code;
nrf_ble_scan_init_t init_scan;
memset(&init_scan, 0, sizeof(init_scan));
init_scan.connect_if_match = false;
init_scan.conn_cfg_tag = APP_BLE_CONN_CFG_TAG;
init_scan.p_scan_param = &m_scan_param_peripheral;
err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
APP_ERROR_CHECK(err_code);
}
else if (isCentral())
{
ret_code_t err_code;
nrf_ble_scan_init_t init_scan;
memset(&init_scan, 0, sizeof(init_scan));
init_scan.connect_if_match = false;
init_scan.conn_cfg_tag = APP_BLE_CONN_CFG_TAG;
init_scan.p_scan_param = &m_scan_param_central;
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_uuid);
APP_ERROR_CHECK(err_code);
err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
APP_ERROR_CHECK(err_code);
}
}
/**@brief Function to start scanning. */
static void scan_start(void)
{
ret_code_t err_code;
ClearLeafList();
err_code = nrf_ble_scan_start(&m_scan);
APP_ERROR_CHECK(err_code);
}
static void scan_stop(void)
{
nrf_ble_scan_stop();
}
static unsigned int debug_pkt_count = 0;
static bool DebugPacketFillFifo(app_fifo_t * const p_fifo)
{
if (debug_pkt_count >= (10000/4))
{
return false;
}
uint32_t len;
app_fifo_write(p_fifo, NULL, &len);
while(len >= 4)
{
uint32_t len_2;
len_2 = 4;