-
Notifications
You must be signed in to change notification settings - Fork 518
/
Copy pathble_hal.cpp
4436 lines (4130 loc) · 197 KB
/
ble_hal.cpp
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 (c) 2019 Particle Industries, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation, either
* version 3 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, see <http://www.gnu.org/licenses/>.
*/
#include "logging.h"
LOG_SOURCE_CATEGORY("hal.ble");
#include "ble_hal.h"
#if HAL_PLATFORM_BLE
// Uncomment to enable more error logs
// #define LOG_CHECKED_ERRORS 1
/* Headers included from nRF5_SDK/components/softdevice/s140/headers */
#include "ble.h"
#include "ble_gap.h"
#include "ble_gatt.h"
#include "ble_gatts.h"
#include "ble_gattc.h"
#include "ble_types.h"
/* Headers included from nRF5_SDK/components/softdevice/common */
#include "nrf_sdh.h"
#include "nrf_sdh_ble.h"
#include "nrf_sdh_soc.h"
#include "app_util.h"
#include "concurrent_hal.h"
#include "static_recursive_mutex.h"
#include <mutex>
#include "gpio_hal.h"
#include "device_code.h"
#include "radio_common.h"
#include "nrf_system_error.h"
#include "sdk_config_system.h"
#include "spark_wiring_vector.h"
#include "simple_pool_allocator.h"
#include <string.h>
#include <memory>
#include "check_nrf.h"
#include "check.h"
#include "scope_guard.h"
#include "mbedtls/ecdh.h"
#include "mbedtls_util.h"
using namespace particle;
#include "intrusive_list.h"
static_assert(NRF_SDH_BLE_PERIPHERAL_LINK_COUNT == 1, "Multiple simultaneous peripheral connections are not supported");
static_assert(NRF_SDH_BLE_TOTAL_LINK_COUNT <= 20, "Maximum supported number of concurrent connections in the peripheral and central roles combined exceeded");
using spark::Vector;
using namespace particle::ble;
#ifdef SUB1
#undef SUB1
#endif
#define SUB1(X) (((X)>0) ? ((X)-1) : (X))
#define BLE_API_VERSION_1 1
#define BLE_API_VERSION_2 2
#define BLE_API_VERSION_3 3
//anonymous namespace
namespace {
StaticRecursiveMutex s_bleMutex;
bool bleInLockedMode = false;
constexpr auto BLE_CONN_CFG_TAG = 1;
// BLE service base start handle.
const hal_ble_attr_handle_t SERVICES_BASE_START_HANDLE = 0x0001;
// BLE service top end handle.
const hal_ble_attr_handle_t SERVICES_TOP_END_HANDLE = 0xFFFF;
// Pool for BLE event data.
constexpr size_t BLE_EVT_DATA_POOL_SIZE = 2048;
// Timeout for a BLE procedure.
constexpr uint32_t BLE_OPERATION_TIMEOUT_MS = 60000;
// Delay for GATT Client to send the ATT MTU exchanging request.
constexpr uint32_t BLE_ATT_MTU_EXCHANGE_DELAY_MS = 800;
constexpr uint8_t BLE_ENC_MIN_KEY_SIZE = 7;
constexpr uint8_t BLE_ENC_MAX_KEY_SIZE = 16;
static const uint8_t BleAdvEvtTypeMap[] = {
BLE_GAP_ADV_TYPE_CONNECTABLE_SCANNABLE_UNDIRECTED,
BLE_GAP_ADV_TYPE_EXTENDED_CONNECTABLE_NONSCANNABLE_UNDIRECTED,
BLE_GAP_ADV_TYPE_CONNECTABLE_NONSCANNABLE_DIRECTED,
BLE_GAP_ADV_TYPE_NONCONNECTABLE_NONSCANNABLE_UNDIRECTED,
BLE_GAP_ADV_TYPE_EXTENDED_NONCONNECTABLE_NONSCANNABLE_DIRECTED,
BLE_GAP_ADV_TYPE_NONCONNECTABLE_SCANNABLE_UNDIRECTED,
BLE_GAP_ADV_TYPE_EXTENDED_NONCONNECTABLE_SCANNABLE_DIRECTED
};
hal_ble_addr_t toHalAddress(const ble_gap_addr_t& address) {
hal_ble_addr_t halAddress = {};
halAddress.addr_type = (ble_sig_addr_type_t)address.addr_type;
memcpy(halAddress.addr, address.addr, BLE_SIG_ADDR_LEN);
return halAddress;
}
ble_gap_addr_t toPlatformAddress(const hal_ble_addr_t& address) {
ble_gap_addr_t platformAddress = {};
platformAddress.addr_id_peer = false;
platformAddress.addr_type = address.addr_type;
memcpy(platformAddress.addr, address.addr, BLE_SIG_ADDR_LEN);
return platformAddress;
}
uint8_t toHalCharProps(ble_gatt_char_props_t properties) {
uint8_t halProperties = 0;
if (properties.broadcast) {
halProperties |= BLE_SIG_CHAR_PROP_BROADCAST;
}
if (properties.read) {
halProperties |= BLE_SIG_CHAR_PROP_READ;
}
if (properties.write_wo_resp) {
halProperties |= BLE_SIG_CHAR_PROP_WRITE_WO_RESP;
}
if (properties.write) {
halProperties |= BLE_SIG_CHAR_PROP_WRITE;
}
if (properties.notify){
halProperties |= BLE_SIG_CHAR_PROP_NOTIFY;
}
if (properties.indicate) {
halProperties |= BLE_SIG_CHAR_PROP_INDICATE;
}
if (properties.auth_signed_wr) {
halProperties |= BLE_SIG_CHAR_PROP_AUTH_SIGN_WRITES;
}
return halProperties;
}
ble_gatt_char_props_t toPlatformCharProps(uint8_t halProperties) {
ble_gatt_char_props_t properties = {};
properties.broadcast = (halProperties & BLE_SIG_CHAR_PROP_BROADCAST) ? 1 : 0;
properties.read = (halProperties & BLE_SIG_CHAR_PROP_READ) ? 1 : 0;
properties.write_wo_resp = (halProperties & BLE_SIG_CHAR_PROP_WRITE_WO_RESP) ? 1 : 0;
properties.write = (halProperties & BLE_SIG_CHAR_PROP_WRITE) ? 1 : 0;
properties.notify = (halProperties & BLE_SIG_CHAR_PROP_NOTIFY) ? 1 : 0;
properties.indicate = (halProperties & BLE_SIG_CHAR_PROP_INDICATE) ? 1 : 0;
properties.auth_signed_wr = (halProperties & BLE_SIG_CHAR_PROP_AUTH_SIGN_WRITES) ? 1 : 0;
return properties;
}
bool addressEqual(const hal_ble_addr_t& srcAddr, const hal_ble_addr_t& destAddr) {
return (srcAddr.addr_type == destAddr.addr_type && !memcmp(srcAddr.addr, destAddr.addr, BLE_SIG_ADDR_LEN));
}
hal_ble_addr_t chipDefaultAddress() {
uint32_t addrMsb = NRF_FICR->DEVICEADDR[1];
uint32_t addrLsb = NRF_FICR->DEVICEADDR[0];
hal_ble_addr_t localAddr = {};
localAddr.addr_type = BLE_SIG_ADDR_TYPE_RANDOM_STATIC;
localAddr.addr[0] = (uint8_t)(addrLsb & 0x000000FF);
localAddr.addr[1] = (uint8_t)((addrLsb >> 8) & 0x000000FF);
localAddr.addr[2] = (uint8_t)((addrLsb >> 16) & 0x000000FF);
localAddr.addr[3] = (uint8_t)((addrLsb >> 24) & 0x000000FF);
localAddr.addr[4] = (uint8_t)(addrMsb & 0x000000FF);
localAddr.addr[5] = (uint8_t)((addrMsb >> 8) & 0x000000FF);
localAddr.addr[5] |= 0xC0; // For random static address, the two most significant bits of the address shall be equal to 1.
return localAddr;
}
} //anonymous namespace
class BleObject {
public:
class BleEventDispatcher;
class BleGap;
class Broadcaster;
class Observer;
class ConnectionsManager;
class GattServer;
class GattClient;
static BleObject& getInstance();
int init();
bool initialized() const;
int selectAntenna(hal_ble_ant_type_t antenna) const;
BleEventDispatcher* dispatcher() { return dispatcher_.get(); }
BleGap* gap() { return gap_.get(); }
Broadcaster* broadcaster() { return broadcaster_.get(); }
Observer* observer() { return observer_.get(); }
ConnectionsManager* connMgr() { return connectionsMgr_.get(); }
GattServer* gatts() { return gatts_.get(); }
GattClient* gattc() { return gattc_.get(); }
private:
BleObject() = default;
~BleObject() = default;
static int toPlatformUUID(const hal_ble_uuid_t* halUuid, ble_uuid_t* uuid);
static int toHalUUID(const ble_uuid_t* uuid, hal_ble_uuid_t* halUuid);
std::unique_ptr<BleEventDispatcher> dispatcher_; /**< BLE event dispatcher. */
std::unique_ptr<BleGap> gap_; /**< BLE GAP instance. */
std::unique_ptr<Broadcaster> broadcaster_; /**< BLE Broadcaster instance. */
std::unique_ptr<Observer> observer_; /**< BLE Observer instance. */
std::unique_ptr<ConnectionsManager> connectionsMgr_; /**< BLE connections manager instance. */
std::unique_ptr<GattServer> gatts_; /**< BLE GATT server instance. */
std::unique_ptr<GattClient> gattc_; /**< BLE GATT client instance. */
static bool initialized_;
};
class BleObject::BleEventDispatcher {
public:
BleEventDispatcher()
: evtDispatcherinitialized_(false),
evtQueue_(nullptr),
evtThread_(nullptr) {
}
~BleEventDispatcher() = default;
int init();
bool initialized() const {
return evtDispatcherinitialized_;
}
void enqueue(ble_evt_t** event);
void enqueue(const ble_evt_t* event);
void* allocEventData(size_t size) {
return pool_.alloc(size);
}
void freeEventData(void* p) {
if (p) {
pool_.free(p);
}
}
private:
static os_thread_return_t processBleEventFromThread(void* param);
bool evtDispatcherinitialized_;
os_queue_t evtQueue_; /**< BLE event queue. */
os_thread_t evtThread_; /**< BLE event thread. */
AtomicAllocedPool pool_;
};
class BleObject::BleGap {
public:
BleGap()
: gapInitialized_(false) {
}
~BleGap() = default;
int init();
bool initialized() const {
return gapInitialized_;
}
int setDeviceName(const char* deviceName, size_t len) const;
int getDeviceName(char* deviceName, size_t len) const;
int setDeviceAddress(const hal_ble_addr_t* address) const;
int getDeviceAddress(hal_ble_addr_t* address) const;
int setAppearance(ble_sig_appearance_t appearance) const;
int getAppearance(ble_sig_appearance_t* appearance) const;
int addWhitelist(const hal_ble_addr_t* addrList, size_t len) const;
int deleteWhitelist() const;
private:
static void processBleGapEvents(const ble_evt_t* event, void* context);
bool gapInitialized_;
};
class BleObject::Broadcaster {
public:
Broadcaster();
~Broadcaster() = default;
int init();
bool initialized() const {
return broadcasterInitialized_;
}
bool advertising() const;
int setAdvertisingParams(const hal_ble_adv_params_t* params);
int getAdvertisingParams(hal_ble_adv_params_t* params) const;
int setAdvertisingData(const uint8_t* buf, size_t len);
ssize_t getAdvertisingData(uint8_t* buf, size_t len) const;
int setScanResponseData(const uint8_t* buf, size_t len);
ssize_t getScanResponseData(uint8_t* buf, size_t len) const;
int setTxPower(int8_t val);
int getTxPower(int8_t* txPower) const;
int startAdvertising();
int stopAdvertising();
int setAutoAdvertiseScheme(hal_ble_auto_adv_cfg_t config);
int getAutoAdvertiseScheme(hal_ble_auto_adv_cfg_t* cfg);
int onAdvEventCallback(hal_ble_on_adv_evt_cb_t callback, void* context);
void cancelAdvEventCallback(hal_ble_on_adv_evt_cb_t callback, void* context);
int processAdvStoppedEventFromThread(const ble_evt_t* event);
private:
struct BleAdvEventHandler {
hal_ble_on_adv_evt_cb_t callback;
void* context;
};
int suspend();
int resume();
ble_gap_adv_data_t toPlatformAdvData(void);
int configure(const hal_ble_adv_params_t* params);
static int8_t roundTxPower(int8_t value);
static ble_gap_adv_params_t toPlatformAdvParams(const hal_ble_adv_params_t* halParams);
static void processBroadcasterEvents(const ble_evt_t* event, void* context);
bool broadcasterInitialized_;
volatile bool isAdvertising_; /**< If it is advertising or not. */
volatile hal_ble_auto_adv_cfg_t autoAdvCfg_; /**< Automatic advertising configuration. */
uint8_t advHandle_; /**< Advertising handle. */
hal_ble_adv_params_t advParams_; /**< Current advertising parameters. */
uint8_t advData_[BLE_MAX_ADV_DATA_LEN_EXT]; /**< Current advertising data. */
size_t advDataLen_; /**< Current advertising data length. */
uint8_t scanRespData_[BLE_MAX_SCAN_REPORT_BUF_LEN]; /**< Current scan response data. */
size_t scanRespDataLen_; /**< Current scan response data length. */
int8_t txPower_; /**< TX Power. */
bool advPending_; /**< Advertising is pending. */
bool connectedAdvParams_; /**< Whether it is using the advertising parameters being set when connected as Peripheral. */
volatile hal_ble_conn_handle_t connHandle_; /**< Connection handle. It is assigned once device is connected as Peripheral. It is used for re-start advertising. */
Vector<BleAdvEventHandler> advEventHandlers_;
static const int8_t validTxPower_[8]; /**< Valid TX power values. */
};
class BleObject::Observer {
public:
Observer()
: observerInitialized_(false),
isScanning_(false),
scanParams_{},
scanSemaphore_(nullptr),
scanResultCallback_(nullptr),
context_(nullptr),
scanGuardTimer_(nullptr) {
scanParams_.version = BLE_API_VERSION;
scanParams_.size = sizeof(hal_ble_scan_params_t);
scanParams_.active = true;
scanParams_.filter_policy = BLE_SCAN_FP_ACCEPT_ALL;
scanParams_.interval = BLE_DEFAULT_SCANNING_INTERVAL;
scanParams_.window = BLE_DEFAULT_SCANNING_WINDOW;
scanParams_.timeout = BLE_DEFAULT_SCANNING_TIMEOUT;
scanParams_.scan_phys = BLE_PHYS_AUTO;
bleScanData_.p_data = scanReportBuff_;
bleScanData_.len = sizeof(scanReportBuff_);
}
~Observer() = default;
int init();
bool initialized() const {
return observerInitialized_;
}
bool scanning();
int setScanParams(const hal_ble_scan_params_t* params);
int getScanParams(hal_ble_scan_params_t* params) const;
int startScanning(hal_ble_on_scan_result_cb_t callback, void* context);
int stopScanning();
ble_gap_scan_params_t toPlatformScanParams() const;
int processAdvReportEventFromThread(const ble_evt_t* event);
private:
hal_ble_scan_result_evt_t* getPendingResult(const hal_ble_addr_t& address);
int addPendingResult(const hal_ble_scan_result_evt_t& resultEvt);
void removePendingResult(const hal_ble_addr_t& address);
void clearPendingResult();
int continueScanning();
int constructObserverEvent(hal_ble_scan_result_evt_t& result, const ble_gap_evt_adv_report_t& advReport) const;
void notifyScanResultEvent(const hal_ble_scan_result_evt_t& result);
static void processObserverEvents(const ble_evt_t* event, void* context);
static void onScanGuardTimerExpired(os_timer_t timer);
bool observerInitialized_;
volatile bool isScanning_; /**< If it is scanning or not. */
hal_ble_scan_params_t scanParams_; /**< BLE scanning parameters. */
os_semaphore_t scanSemaphore_; /**< Semaphore to wait until the scan procedure completed. */
uint8_t scanReportBuff_[BLE_MAX_ADV_DATA_LEN_EXT]; /**< Buffer to hold the scanned report data. */
ble_data_t bleScanData_; /**< BLE scanned data. */
hal_ble_on_scan_result_cb_t scanResultCallback_; /**< Callback function on scan result. */
void* context_; /**< Context of the scan result callback function. */
os_timer_t scanGuardTimer_; /**< Timer to guard the scanning procedure is terminated successfully. */
Vector<hal_ble_scan_result_evt_t> pendingResults_;
};
class BleObject::ConnectionsManager {
public:
ConnectionsManager()
: connMgrInitialized_(false),
isConnecting_(false),
disconnectingHandle_(BLE_INVALID_CONN_HANDLE),
centralConnParamUpdateHandle_(BLE_INVALID_CONN_HANDLE),
periphConnParamUpdateHandle_(BLE_INVALID_CONN_HANDLE),
connParamsUpdateAttempts_(0),
connParamsUpdateTimer_(nullptr),
connParamsUpdateSemaphore_(nullptr),
connectSemaphore_(nullptr),
disconnectSemaphore_(nullptr),
ecdhContextInit_(false) {
connectingAddr_ = {};
pairingConfig_ = {
.version = BLE_API_VERSION,
.size = sizeof(hal_ble_pairing_config_t),
.io_caps = BLE_IO_CAPS_NONE,
.algorithm = BLE_PAIRING_ALGORITHM_AUTO,
.reserved = {}
};
}
~ConnectionsManager() = default;
int init();
bool initialized() const {
return connMgrInitialized_;
}
int onPeripheralLinkEventCallback(hal_ble_on_link_evt_cb_t cb, void* context);
int setPpcp(const hal_ble_conn_params_t* ppcp);
int getPpcp(hal_ble_conn_params_t* ppcp) const;
bool connecting(const hal_ble_addr_t* address) const;
bool connected(const hal_ble_addr_t* address = nullptr);
int connect(const hal_ble_conn_cfg_t* config, hal_ble_conn_handle_t* conn_handle);
int connectCancel(const hal_ble_addr_t* address);
int disconnect(hal_ble_conn_handle_t connHandle);
int disconnectAll();
int updateConnectionParams(hal_ble_conn_handle_t connHandle, const hal_ble_conn_params_t* params);
int getConnectionInfo(hal_ble_conn_handle_t connHandle, hal_ble_conn_info_t* info);
int setPairingConfig(const hal_ble_pairing_config_t* config);
int getPairingConfig(hal_ble_pairing_config_t* config) const;
int startPairing(hal_ble_conn_handle_t connHandle);
int rejectPairing(hal_ble_conn_handle_t connHandle);
int setPairingAuthData(hal_ble_conn_handle_t connHandle, const hal_ble_pairing_auth_data_t* auth);
bool isPairing(hal_ble_conn_handle_t connHandle);
bool isPaired(hal_ble_conn_handle_t connHandle);
bool valid(hal_ble_conn_handle_t connHandle);
ssize_t getAttMtu(hal_ble_conn_handle_t connHandle);
bool attMtuExchanged(hal_ble_conn_handle_t connHandle);
int processConnectedEventFromThread(const ble_evt_t* event);
int processDisconnectedEventFromThread(const ble_evt_t* event);
int processConnParamsUpdatedEventFromThread(const ble_evt_t* event);
int processAttMtuExchangeEventFromThread(const ble_evt_t* event);
int processSecurityEventFromThread(const ble_evt_t* event);
private:
struct BleLinkEventHandler {
hal_ble_on_link_evt_cb_t callback;
void* context;
};
enum BlePairingState {
BLE_PAIRING_STATE_NOT_INITIATED,
BLE_PAIRING_STATE_SEC_REQ_RECEIVED, // Central
BLE_PAIRING_STATE_SEC_REQ_SENT, // Peripheral
BLE_PAIRING_STATE_PAIRING_REQ_SENT, // Central
BLE_PAIRING_STATE_PAIRING_REQ_RECEIVED, // Peripheral
BLE_PAIRING_STATE_PASSKEY_DISPLAY,
BLE_PAIRING_STATE_PASSKEY_INPUT,
BLE_PAIRING_STATE_REJECTED,
BLE_PAIRING_STATE_PAIRED
};
struct BleConnection {
hal_ble_conn_info_t info;
BleLinkEventHandler handler; // It is used for central link only.
bool isMtuExchanged;
BlePairingState pairState;
std::unique_ptr<ble_gap_lesc_p256_pk_t> peerPublicKey;
};
int initSecParams(const hal_ble_pairing_config_t& config, ble_gap_sec_params_t& params);
int generateEcdhKeyPair();
int publicKeysPrepare(BleConnection* connection);
int computeDhkey(const uint8_t peerPublicKey[BLE_GAP_LESC_P256_PK_LEN], uint8_t dhKey[BLE_GAP_LESC_DHKEY_LEN]);
int configureAttMtu(hal_ble_conn_handle_t connHandle, size_t effective);
BleConnection* fetchConnection(hal_ble_conn_handle_t connHandle);
BleConnection* fetchConnection(const hal_ble_addr_t* address);
int addConnection(BleConnection&& connection);
void removeConnection(hal_ble_conn_handle_t connHandle);
void initiateConnParamsUpdateIfNeeded(const BleConnection* connection);
bool isConnParamsFeeded(const hal_ble_conn_params_t* params) const;
static ble_gap_conn_params_t toPlatformConnParams(const hal_ble_conn_params_t* halConnParams);
static hal_ble_conn_params_t toHalConnParams(const ble_gap_conn_params_t* params);
static uint8_t toPlatformIoCaps(hal_ble_pairing_io_caps_t ioCaps);
static hal_ble_pairing_io_caps_t toHalIoCaps(uint8_t ioCaps);
static void onConnParamsUpdateTimerExpired(os_timer_t timer);
void notifyLinkEvent(const hal_ble_link_evt_t& event);
static void processConnectionEvents(const ble_evt_t* event, void* context);
bool connMgrInitialized_;
volatile bool isConnecting_; /**< If it is connecting or not. */
hal_ble_addr_t connectingAddr_; /**< Address of peer the Central is connecting to. */
volatile hal_ble_conn_handle_t disconnectingHandle_; /**< Handle of connection to be disconnected. */
volatile hal_ble_conn_handle_t centralConnParamUpdateHandle_;/**< Handle of the central connection to send peripheral connection update command. */
volatile hal_ble_conn_handle_t periphConnParamUpdateHandle_;/**< Handle of the peripheral connection to send peripheral connection update request. */
volatile uint8_t connParamsUpdateAttempts_; /**< Attempts for peripheral to update connection parameters. */
os_timer_t connParamsUpdateTimer_; /**< Timer used for sending peripheral connection update request after connection established. */
os_semaphore_t connParamsUpdateSemaphore_; /**< Semaphore to wait until connection parameters updated. */
os_semaphore_t connectSemaphore_; /**< Semaphore to wait until connection established. */
os_semaphore_t disconnectSemaphore_; /**< Semaphore to wait until connection disconnected. */
Vector<BleConnection> connections_;
Vector<BleLinkEventHandler> peripheralLinkEventHandlers_; /**< It is used for peripheral link only. */
hal_ble_pairing_config_t pairingConfig_;
mbedtls_ecdh_context ecdhContext_;
volatile bool ecdhContextInit_;
std::unique_ptr<ble_gap_lesc_p256_pk_t> localPublicKey_;
};
class BleObject::GattServer {
public:
GattServer()
: gattsInitialized_(false),
isHvxing_(false),
currHvxConnHandle_(BLE_INVALID_CONN_HANDLE),
hvxSemaphore_(nullptr) {
}
~GattServer() = default;
int init();
bool initialized() const {
return gattsInitialized_;
}
int addService(uint8_t type, const hal_ble_uuid_t* uuid, hal_ble_attr_handle_t* svcHandle);
int addCharacteristic(const hal_ble_char_init_t* charInit, hal_ble_char_handles_t* charHandles);
int addDescriptor(hal_ble_attr_handle_t charHandle, const hal_ble_uuid_t* uuid, uint8_t* descriptor, size_t len, hal_ble_attr_handle_t* descHandle);
void removeSubscriberFromAllCharacteristics(hal_ble_conn_handle_t connHandle);
ssize_t setValue(hal_ble_attr_handle_t attrHandle, const uint8_t* buf, size_t len);
ssize_t notifyValue(hal_ble_attr_handle_t attrHandle, const uint8_t* buf, size_t len, bool ack);
ssize_t getValue(hal_ble_attr_handle_t attrHandle, uint8_t* buf, size_t len);
size_t getDesiredAttMtu() const;
int setDesiredAttMtu(size_t attMtu);
int processDataWrittenEventFromThread(ble_evt_t* event);
private:
struct Subscriber {
hal_ble_conn_handle_t connHandle;
ble_sig_cccd_value_t config;
};
class BleCharacteristic {
public:
BleCharacteristic() = default;
~BleCharacteristic() = default;
uint8_t properties;
hal_ble_attr_handle_t svcHandle;
hal_ble_char_handles_t charHandles;
hal_ble_on_char_evt_cb_t callback;
void* context;
Vector<Subscriber> subscribers;
};
bool findService(hal_ble_attr_handle_t svcHandle) const;
BleCharacteristic* findCharacteristic(hal_ble_attr_handle_t attrHandle);
int addSubscriber(BleCharacteristic* characteristic, hal_ble_conn_handle_t connHandle, ble_sig_cccd_value_t value);
void removeSubscriber(BleCharacteristic* characteristic, hal_ble_conn_handle_t connHandle);
static void processGattServerEvents(const ble_evt_t* event, void* context);
bool gattsInitialized_;
volatile bool isHvxing_;
hal_ble_conn_handle_t currHvxConnHandle_;
os_semaphore_t hvxSemaphore_; /**< Semaphore to wait until the HVX operation completed. */
Vector<hal_ble_attr_handle_t> services_; /**< Added services. */
Vector<BleCharacteristic> characteristics_; /**< Added characteristic. */
// GATT Server and GATT client share the same ATT_MTU.
static size_t desiredAttMtu_;
};
size_t BleObject::GattServer::desiredAttMtu_ = BLE_MAX_ATT_MTU_SIZE;
class BleObject::GattClient {
public:
GattClient()
: gattcInitialized_(false),
attMtuExchangeConnHandle_(BLE_INVALID_CONN_HANDLE),
attMtuExchangeTimer_(nullptr),
attMtuExchangeRetries_(0),
discSvcCallback_(nullptr),
discSvcContext_(nullptr),
discCharCallback_(nullptr),
discCharContext_(nullptr),
isDiscovering_(false),
currDiscConnHandle_(BLE_INVALID_CONN_HANDLE),
currDiscProcedure_(DiscoveryProcedure::BLE_DISCOVERY_PROCEDURE_IDLE),
discoverySemaphore_(nullptr),
isReading_(false),
currReadConnHandle_(BLE_INVALID_CONN_HANDLE),
readSemaphore_(nullptr),
isWriting_(false),
currWriteConnHandle_(BLE_INVALID_CONN_HANDLE),
writeSemaphore_(nullptr),
readAttrHandle_(BLE_INVALID_ATTR_HANDLE),
readBuf_(nullptr),
readLen_(0) {
resetDiscoveryState();
}
~GattClient() = default;
int init();
bool initialized() const {
return gattcInitialized_;
}
bool discovering(hal_ble_conn_handle_t connHandle) const;
int discoverServices(hal_ble_conn_handle_t connHandle, const hal_ble_uuid_t* uuid, hal_ble_on_disc_service_cb_t callback, void* context);
int discoverCharacteristics(hal_ble_conn_handle_t connHandle, const hal_ble_svc_t* service, hal_ble_on_disc_char_cb_t callback, void* context);
int removeAllPublishersOfConnection(hal_ble_conn_handle_t connHandle);
ssize_t writeAttribute(hal_ble_conn_handle_t connHandle, hal_ble_attr_handle_t attrHandle, const uint8_t* buf, size_t len, bool response);
ssize_t readAttribute(hal_ble_conn_handle_t connHandle, hal_ble_attr_handle_t attrHandle, uint8_t* buf, size_t len);
int configureRemoteCCCD(const hal_ble_cccd_config_t* config);
int exchangeAttMtu(hal_ble_conn_handle_t connHandle);
int processSvcDiscEventFromThread(const ble_evt_t* event);
int processCharDiscEventFromThread(const ble_evt_t* event);
int processDescDiscEventFromThread(const ble_evt_t* event);
int processDataReadEventFromThread(const ble_evt_t* event);
int processDataNotifiedEventFromThread(ble_evt_t* event);
private:
enum class DiscoveryProcedure {
BLE_DISCOVERY_PROCEDURE_IDLE = 0,
BLE_DISCOVERY_PROCEDURE_SERVICES = 1,
BLE_DISCOVERY_PROCEDURE_CHARACTERISTICS = 2,
BLE_DISCOVERY_PROCEDURE_DESCRIPTORS = 3,
};
struct Publisher {
hal_ble_on_char_evt_cb_t callback;
void* context;
hal_ble_conn_handle_t connHandle;
hal_ble_attr_handle_t valueHandle;
};
void resetDiscoveryState();
bool readServiceUUID128IfNeeded() const;
bool readCharacteristicUUID128IfNeeded() const;
hal_ble_svc_t* findDiscoveredService(hal_ble_attr_handle_t attrHandle);
hal_ble_char_t* findDiscoveredCharacteristic(hal_ble_attr_handle_t attrHandle);
int addPublisher(hal_ble_conn_handle_t connHandle, hal_ble_attr_handle_t valueHandle, hal_ble_on_char_evt_cb_t callback, void* context);
int removePublisher(hal_ble_conn_handle_t connHandle, hal_ble_attr_handle_t valueHandle);
static void processGattClientEvents(const ble_evt_t* event, void* context);
static void onAttMtuExchangeTimerExpired(os_timer_t timer);
bool gattcInitialized_;
volatile hal_ble_conn_handle_t attMtuExchangeConnHandle_; /**< Current handle of the connection to execute ATT_MTU exchange procedure. */
os_timer_t attMtuExchangeTimer_; /**< Timer used for sending the exchanging ATT_MTU request after connection established. */
uint8_t attMtuExchangeRetries_;
bool discoverAll_; /**< If it is going to discover all service during the service discovery procedure. */
hal_ble_on_disc_service_cb_t discSvcCallback_; /**< Callback function on services discovered. */
void* discSvcContext_; /**< Context of services discovered callback function. */
hal_ble_on_disc_char_cb_t discCharCallback_; /**< Callback function on characteristics discovered. */
void* discCharContext_; /**< Context of characteristics discovered callback function. */
volatile bool isDiscovering_; /**< If there is on-going discovery procedure. */
hal_ble_conn_handle_t currDiscConnHandle_; /**< Current connection handle under which the service and characteristics to be discovered. */
DiscoveryProcedure currDiscProcedure_; /**< Current discovery procedure. */
hal_ble_svc_t currDiscSvc_; /**< Current service to be discovered for the characteristics. */
os_semaphore_t discoverySemaphore_; /**< Semaphore to wait until the discovery procedure completed. */
volatile bool isReading_;
hal_ble_conn_handle_t currReadConnHandle_;
os_semaphore_t readSemaphore_; /**< Semaphore to wait until the read operation completed. */
volatile bool isWriting_;
hal_ble_conn_handle_t currWriteConnHandle_;
os_semaphore_t writeSemaphore_; /**< Semaphore to wait until the write operation completed. */
Vector<hal_ble_svc_t> discServices_; /**< Discover services. */
Vector<hal_ble_char_t> discCharacteristics_; /**< Discovered characteristics. */
hal_ble_attr_handle_t readAttrHandle_; /**< Current handle of which attribute to be read. */
uint8_t* readBuf_; /**< Current buffer to be filled for the read data. */
size_t readLen_; /**< Length of read data. */
Vector<Publisher> publishers_;
static constexpr uint8_t ATT_MTU_AUTO_EXCHANGE_RETRIES = 5;
};
int BleObject::BleEventDispatcher::init() {
if (os_queue_create(&evtQueue_, sizeof(ble_evt_t*), BLE_EVENT_QUEUE_ITEM_COUNT, nullptr)) {
evtQueue_ = nullptr;
LOG(ERROR, "os_queue_create() failed");
goto error;
}
if (os_thread_create(&evtThread_, "BLE Event Thread", OS_THREAD_PRIORITY_NETWORK, processBleEventFromThread, this, BLE_EVENT_THREAD_STACK_SIZE)) {
evtThread_ = nullptr;
LOG(ERROR, "os_thread_create() failed");
goto error;
}
if (pool_.init(BLE_EVT_DATA_POOL_SIZE) != SYSTEM_ERROR_NONE) {
goto error;
}
evtDispatcherinitialized_ = true;
return SYSTEM_ERROR_NONE;
error:
if (evtQueue_) {
os_queue_destroy(evtQueue_, nullptr);
evtQueue_ = nullptr;
}
if (evtThread_) {
os_thread_exit(evtThread_);
evtThread_ = nullptr;
}
return SYSTEM_ERROR_INTERNAL;
}
void BleObject::BleEventDispatcher::enqueue(ble_evt_t** event) {
if (os_queue_put(evtQueue_, event, 0, nullptr)) {
LOG(ERROR, "os_queue_put() failed.");
SPARK_ASSERT(false);
}
}
void BleObject::BleEventDispatcher::enqueue(const ble_evt_t* event) {
ble_evt_t* pBleEvent = (ble_evt_t*)allocEventData(sizeof(ble_evt_t));
if (!pBleEvent) {
LOG(ERROR, "Allocate memory for BLE event failed.");
SPARK_ASSERT(false);
}
memcpy(pBleEvent, event, sizeof(ble_evt_t));
enqueue(&pBleEvent);
}
os_thread_return_t BleObject::BleEventDispatcher::processBleEventFromThread(void* param) {
BleEventDispatcher* dispatcher = static_cast<BleEventDispatcher*>(param);
while (1) {
ble_evt_t* event;
if (!os_queue_take(dispatcher->evtQueue_, &event, CONCURRENT_WAIT_FOREVER, nullptr)) {
SCOPE_GUARD ({
dispatcher->freeEventData(event);
});
switch (event->header.evt_id) {
case BLE_GAP_EVT_ADV_SET_TERMINATED: {
BleObject::getInstance().broadcaster()->processAdvStoppedEventFromThread(event);
break;
}
case BLE_GAP_EVT_ADV_REPORT: {
BleObject::getInstance().observer()->processAdvReportEventFromThread(event);
break;
}
case BLE_GAP_EVT_CONNECTED: {
BleObject::getInstance().connMgr()->processConnectedEventFromThread(event);
break;
}
case BLE_GAP_EVT_DISCONNECTED: {
BleObject::getInstance().connMgr()->processDisconnectedEventFromThread(event);
break;
}
case BLE_GAP_EVT_CONN_PARAM_UPDATE: {
BleObject::getInstance().connMgr()->processConnParamsUpdatedEventFromThread(event);
break;
}
case BLE_GATTC_EVT_EXCHANGE_MTU_RSP:
case BLE_GATTS_EVT_EXCHANGE_MTU_REQUEST: {
BleObject::getInstance().connMgr()->processAttMtuExchangeEventFromThread(event);
break;
}
case BLE_GATTC_EVT_PRIM_SRVC_DISC_RSP: {
BleObject::getInstance().gattc()->processSvcDiscEventFromThread(event);
break;
}
case BLE_GATTC_EVT_CHAR_DISC_RSP: {
BleObject::getInstance().gattc()->processCharDiscEventFromThread(event);
break;
}
case BLE_GATTC_EVT_DESC_DISC_RSP: {
BleObject::getInstance().gattc()->processDescDiscEventFromThread(event);
break;
}
case BLE_GATTC_EVT_READ_RSP: {
BleObject::getInstance().gattc()->processDataReadEventFromThread(event);
break;
}
case BLE_GATTS_EVT_WRITE: {
BleObject::getInstance().gatts()->processDataWrittenEventFromThread(event);
break;
}
case BLE_GATTC_EVT_HVX: {
BleObject::getInstance().gattc()->processDataNotifiedEventFromThread(event);
break;
}
case BLE_GAP_EVT_SEC_INFO_REQUEST:
case BLE_GAP_EVT_LESC_DHKEY_REQUEST:
case BLE_GAP_EVT_PASSKEY_DISPLAY:
case BLE_GAP_EVT_AUTH_KEY_REQUEST:
case BLE_GAP_EVT_SEC_REQUEST:
case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
case BLE_GAP_EVT_AUTH_STATUS:
case BLE_GAP_EVT_CONN_SEC_UPDATE: {
BleObject::getInstance().connMgr()->processSecurityEventFromThread(event);
break;
}
default: {
break;
}
}
} else {
LOG(ERROR, "BLE event thread exited.");
break;
}
}
os_thread_exit(dispatcher->evtThread_);
}
struct BleGapImpl {
BleObject::BleGap* instance;
};
static BleGapImpl bleGapImpl;
int BleObject::BleGap::init() {
// Set the default device name
char devName[BLE_MAX_DEV_NAME_LEN] = {};
CHECK(get_device_name(devName, sizeof(devName)));
CHECK(setDeviceName(devName, strlen(devName)));
bleGapImpl.instance = this;
NRF_SDH_BLE_OBSERVER(bleGap, 1, processBleGapEvents, &bleGapImpl);
gapInitialized_ = true;
return SYSTEM_ERROR_NONE;
}
int BleObject::BleGap::setDeviceName(const char* deviceName, size_t len) const {
char name[BLE_MAX_DEV_NAME_LEN] = {};
if (deviceName == nullptr || len == 0) {
CHECK(get_device_name(name, sizeof(name)));
len = strlen(name);
} else {
len = std::min(len, sizeof(name));
memcpy(name, deviceName, len);
}
ble_gap_conn_sec_mode_t secMode;
BLE_GAP_CONN_SEC_MODE_SET_OPEN(&secMode);
int ret = sd_ble_gap_device_name_set(&secMode, (const uint8_t*)name, len);
return nrf_system_error(ret);
}
int BleObject::BleGap::getDeviceName(char* deviceName, size_t len) const {
CHECK_TRUE(deviceName, SYSTEM_ERROR_INVALID_ARGUMENT);
CHECK_TRUE(len, SYSTEM_ERROR_INVALID_ARGUMENT);
uint16_t nameLen = len - 1; // Reserve 1 byte for the NULL-terminated character.
int ret = sd_ble_gap_device_name_get((uint8_t*)deviceName, &nameLen);
CHECK_NRF_RETURN(ret, nrf_system_error(ret));
nameLen = std::min(len - 1, (size_t)nameLen);
deviceName[nameLen] = '\0';
return SYSTEM_ERROR_NONE;
}
int BleObject::BleGap::setDeviceAddress(const hal_ble_addr_t* address) const {
// The identity address cannot be changed while advertising, scanning or creating a connection.
CHECK_FALSE(BleObject::getInstance().broadcaster()->advertising(), SYSTEM_ERROR_INVALID_STATE);
CHECK_FALSE(BleObject::getInstance().observer()->scanning(), SYSTEM_ERROR_INVALID_STATE);
CHECK_FALSE(BleObject::getInstance().connMgr()->connecting(address), SYSTEM_ERROR_INVALID_STATE);
hal_ble_addr_t newAddr = {};
if (address == nullptr) {
newAddr = chipDefaultAddress();
} else {
newAddr = *address;
}
if (newAddr.addr_type != BLE_SIG_ADDR_TYPE_PUBLIC && newAddr.addr_type != BLE_SIG_ADDR_TYPE_RANDOM_STATIC) {
return SYSTEM_ERROR_INVALID_ARGUMENT;
}
if (newAddr.addr_type == BLE_SIG_ADDR_TYPE_RANDOM_STATIC && (newAddr.addr[5] & 0xC0) != 0xC0) {
// For random static address, the two most significant bits of the address shall be equal to 1.
return SYSTEM_ERROR_INVALID_ARGUMENT;
}
ble_gap_addr_t bleGapAddr = toPlatformAddress(newAddr);
int ret = sd_ble_gap_addr_set(&bleGapAddr);
return nrf_system_error(ret);
}
int BleObject::BleGap::getDeviceAddress(hal_ble_addr_t* address) const {
CHECK_TRUE(address, SYSTEM_ERROR_INVALID_ARGUMENT);
ble_gap_addr_t localAddr = {};
int ret = sd_ble_gap_addr_get(&localAddr);
CHECK_NRF_RETURN(ret, nrf_system_error(ret));
*address = toHalAddress(localAddr);
return SYSTEM_ERROR_NONE;
}
int BleObject::BleGap::setAppearance(ble_sig_appearance_t appearance) const {
int ret = sd_ble_gap_appearance_set((uint16_t)appearance);
return nrf_system_error(ret);
}
int BleObject::BleGap::getAppearance(ble_sig_appearance_t* appearance) const {
CHECK_TRUE(appearance, SYSTEM_ERROR_INVALID_ARGUMENT);
int ret = sd_ble_gap_appearance_get((uint16_t*)appearance);
return nrf_system_error(ret);
}
int BleObject::BleGap::addWhitelist(const hal_ble_addr_t* addrList, size_t len) const {
CHECK_TRUE(addrList, SYSTEM_ERROR_INVALID_ARGUMENT);
CHECK_TRUE(len, SYSTEM_ERROR_INVALID_ARGUMENT);
CHECK_TRUE(len <= BLE_MAX_WHITELIST_ADDR_COUNT, SYSTEM_ERROR_INVALID_ARGUMENT);
ble_gap_addr_t* whitelist = (ble_gap_addr_t*)malloc(sizeof(ble_gap_addr_t) * len);
CHECK_TRUE(whitelist, SYSTEM_ERROR_NO_MEMORY);
SCOPE_GUARD ({
free(whitelist);
});
ble_gap_addr_t const* whitelistPointer[BLE_MAX_WHITELIST_ADDR_COUNT];
for (size_t i = 0; i < len; i++) {
whitelist[i] = toPlatformAddress(addrList[i]);
whitelist[i].addr_id_peer = true;
whitelistPointer[i] = &whitelist[i];
}
int ret = sd_ble_gap_whitelist_set(whitelistPointer, len);
return nrf_system_error(ret);
}
int BleObject::BleGap::deleteWhitelist() const {
int ret = sd_ble_gap_whitelist_set(nullptr, 0);
return nrf_system_error(ret);
}
void BleObject::BleGap::processBleGapEvents(const ble_evt_t* event, void* context) {
int ret;
switch (event->header.evt_id) {
case BLE_GAP_EVT_PHY_UPDATE_REQUEST: {
LOG_DEBUG(TRACE, "BLE GAP event: physical update request.");
ble_gap_phys_t phys = {};
phys.rx_phys = BLE_GAP_PHY_AUTO;
phys.tx_phys = BLE_GAP_PHY_AUTO;
ret = sd_ble_gap_phy_update(event->evt.gap_evt.conn_handle, &phys);
if (ret != NRF_SUCCESS) {
LOG(ERROR, "sd_ble_gap_phy_update() failed: %u", (unsigned)ret);
}
break;
}
case BLE_GAP_EVT_PHY_UPDATE: {
LOG_DEBUG(TRACE, "BLE GAP event: physical updated.");
break;
}
case BLE_GAP_EVT_DATA_LENGTH_UPDATE: {
LOG_DEBUG(TRACE, "BLE GAP event: gap data length updated.");
LOG_DEBUG(TRACE, "| txo rxo txt(us) rxt(us) |.");
LOG_DEBUG(TRACE, " %d %d %d %d",
event->evt.gap_evt.params.data_length_update.effective_params.max_tx_octets, event->evt.gap_evt.params.data_length_update.effective_params.max_rx_octets,
event->evt.gap_evt.params.data_length_update.effective_params.max_tx_time_us, event->evt.gap_evt.params.data_length_update.effective_params.max_rx_time_us);
break;
}
case BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST: {
LOG_DEBUG(TRACE, "BLE GAP event: gap data length update request.");
ble_gap_data_length_params_t gapDataLenParams;
gapDataLenParams.max_tx_octets = BLE_GAP_DATA_LENGTH_AUTO;
gapDataLenParams.max_rx_octets = BLE_GAP_DATA_LENGTH_AUTO;
gapDataLenParams.max_tx_time_us = BLE_GAP_DATA_LENGTH_AUTO;
gapDataLenParams.max_rx_time_us = BLE_GAP_DATA_LENGTH_AUTO;
ret = sd_ble_gap_data_length_update(event->evt.gap_evt.conn_handle, &gapDataLenParams, nullptr);
if (ret != NRF_SUCCESS) {
LOG(ERROR, "sd_ble_gap_data_length_update() failed: %u", (unsigned)ret);
}
break;
}
case BLE_GAP_EVT_TIMEOUT: {
if (event->evt.gap_evt.params.timeout.src == BLE_GAP_TIMEOUT_SRC_AUTH_PAYLOAD) {
LOG_DEBUG(ERROR, "BLE GAP event: Authenticated payload timeout");
}
break;
}
default: {
break;
}
}
}
/* FIXME: It causes a section type conflict if using NRF_SDH_BLE_OBSERVER() in c++ class.*/
struct BroadcasterImpl {
BleObject::Broadcaster* instance;
};
static BroadcasterImpl broadcasterImpl;
BleObject::Broadcaster::Broadcaster()
: broadcasterInitialized_(false),
isAdvertising_(false),
autoAdvCfg_(BLE_AUTO_ADV_ALWAYS),
advHandle_(BLE_GAP_ADV_SET_HANDLE_NOT_SET),
advParams_{},
txPower_(0),
advPending_(false),
connectedAdvParams_(false),
connHandle_(BLE_INVALID_CONN_HANDLE) {
/* Default advertising parameters. */
advParams_.version = BLE_API_VERSION;
advParams_.size = sizeof(hal_ble_adv_params_t);
advParams_.type = BLE_ADV_CONNECTABLE_SCANNABLE_UNDIRECRED_EVT;
advParams_.filter_policy = BLE_ADV_FP_ANY;
advParams_.interval = BLE_DEFAULT_ADVERTISING_INTERVAL;
advParams_.timeout = BLE_DEFAULT_ADVERTISING_TIMEOUT;
advParams_.inc_tx_power = false;
advParams_.primary_phy = BLE_PHYS_AUTO;
memset(advData_, 0x00, sizeof(advData_));
memset(scanRespData_, 0x00, sizeof(scanRespData_));
advDataLen_ = scanRespDataLen_ = 0;
/* Default advertising data. */
// FLags
advData_[advDataLen_++] = 0x02; // Length field of an AD structure, it is the length of the rest AD structure data.
advData_[advDataLen_++] = BLE_SIG_AD_TYPE_FLAGS; // Type field of an AD structure.
advData_[advDataLen_++] = BLE_SIG_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE; // Payload field of an AD structure.
}
int BleObject::Broadcaster::init() {