/
ble_hal.cpp
4022 lines (3670 loc) · 164 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) 2022 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/>.
*/
#define LOG_COMPILE_TIME_LEVEL LOG_LEVEL_TRACE
#include "logging.h"
LOG_SOURCE_CATEGORY("hal.ble");
#include "ble_hal.h"
#if HAL_PLATFORM_BLE
extern "C" {
#include "rtl8721d.h"
#include "rtl8721d_efuse.h"
#include "rtk_coex.h"
}
#include <platform_opts_bt.h>
#include <os_sched.h>
#include <string.h>
#include <trace_app.h>
#include <gap.h>
#include <gap_adv.h>
#include <gap_scan.h>
#include <gap_bond_le.h>
#include <gap_le.h>
#include <gap_conn_le.h>
#include <profile_server.h>
#include <profile_client.h>
#include <gatt_builtin_services.h>
#include <gap_msg.h>
#include <simple_ble_service.h>
#include <bas.h>
#include <bte.h>
#include <gap_config.h>
#include <bt_flags.h>
#include <stdio.h>
#include "wifi_constants.h"
#include <wifi/wifi_conf.h>
#include "rtk_coex.h"
#include "ftl_int.h"
#include "bt_intf.h"
//FIXME
#include "app_msg.h"
#include "os_msg.h"
#include "os_task.h"
#include "delay_hal.h"
#include "device_code.h"
#include "concurrent_hal.h"
#include "static_recursive_mutex.h"
#include <mutex>
#include "spark_wiring_vector.h"
#include <string.h>
#include <memory>
#include "check.h"
#include "scope_guard.h"
#include "rtl_system_error.h"
#include "radio_common.h"
#include "timer_hal.h"
#include "mbedtls/ecdh.h"
#include "mbedtls_util.h"
#include "spark_wiring_thread.h"
// FIXME
#undef OFF
#undef ON
#include "network/ncp/wifi/ncp.h"
#include "network/ncp/wifi/wifi_network_manager.h"
#include "network/ncp/wifi/wifi_ncp_client.h"
#include "rtl_sdk_support.h"
using spark::Vector;
using namespace particle;
using namespace particle::ble;
extern "C" void __real_bt_coex_handle_specific_evt(uint8_t* p, uint8_t len);
extern "C" void __wrap_bt_coex_handle_specific_evt(uint8_t* p, uint8_t len);
extern "C" int rltk_coex_set_wifi_slot(u8 wifi_slot);
void __wrap_bt_coex_handle_specific_evt(uint8_t* p, uint8_t len) {
__real_bt_coex_handle_specific_evt(p, len);
}
namespace {
// FIXME: should probably move under some class here
StaticRecursiveMutex sBleEventMutex;
#define WRAP_BLE_EVT_LOCK(_expr) \
({ \
std::lock_guard<StaticRecursiveMutex> _lk(sBleEventMutex); \
_expr; \
})
#define CHECK_RTL(_expr) \
({ \
const auto _ret = _expr; \
if (_ret != GAP_CAUSE_SUCCESS) { \
_LOG_CHECKED_ERROR(_expr, rtl_ble_error_to_system(_ret)); \
return rtl_ble_error_to_system(_ret); \
} \
_ret; \
})
#define WAIT_TIMED(timeout_ms, what) ({ \
system_tick_t _micros = HAL_Timer_Get_Micro_Seconds(); \
bool res = true; \
while ((what)) { \
system_tick_t dt = (HAL_Timer_Get_Micro_Seconds() - _micros); \
bool nok = (((timeout_ms * 1000) < dt) && (what)); \
if (nok) { \
res = false; \
break; \
} \
} \
res; \
})
#if 0
#define LOCAL_DEBUG(_fmt, ...) \
do { \
LOG(TRACE, _fmt "\r\n", ##__VA_ARGS__); \
} while (false)
#else
#define LOCAL_DEBUG(_fmt, ...)
#endif
constexpr uint32_t BLE_OPERATION_TIMEOUT_MS = 60000;
constexpr system_tick_t BLE_ENQUEUE_TIMEOUT_MS = 5000;
StaticRecursiveMutex s_bleMutex;
bool isUuidEqual(const hal_ble_uuid_t* uuid1, const hal_ble_uuid_t* uuid2) {
if (uuid1->type != uuid2->type) {
return false;
}
if (uuid1->type == BLE_UUID_TYPE_128BIT) {
return memcmp(uuid1->uuid128, uuid2->uuid128, BLE_SIG_UUID_128BIT_LEN) == 0;
} else {
return uuid1->uuid16 == uuid2->uuid16;
}
}
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 chipDefaultPublicAddress() {
hal_ble_addr_t localAddr = {};
uint8_t mac[BLE_SIG_ADDR_LEN] = {};
if (hal_get_mac_address(HAL_DEVICE_MAC_BLE, mac, BLE_SIG_ADDR_LEN, nullptr) == BLE_SIG_ADDR_LEN) {
// As per BLE spec, we store BLE data in little-endian
for (uint8_t i = 0, j = BLE_SIG_ADDR_LEN - 1; i < BLE_SIG_ADDR_LEN; i++, j--) {
localAddr.addr[i] = mac[j];
}
localAddr.addr_type = BLE_SIG_ADDR_TYPE_PUBLIC;
}
return localAddr;
}
T_GAP_IO_CAP toPlatformIoCaps(hal_ble_pairing_io_caps_t index) {
constexpr T_GAP_IO_CAP iocaps[] = {
GAP_IO_CAP_NO_INPUT_NO_OUTPUT,
GAP_IO_CAP_DISPLAY_ONLY,
GAP_IO_CAP_DISPLAY_YES_NO,
GAP_IO_CAP_KEYBOARD_ONLY,
GAP_IO_CAP_KEYBOARD_DISPLAY
};
return iocaps[index];
}
} //anonymous namespace
class BleEventDispatcher {
public:
int start();
int stop();
static BleEventDispatcher& getInstance() {
static BleEventDispatcher instance;
return instance;
}
bool isThreadCurrent() const {
if (!thread_) {
return false;
}
return os_thread_current(nullptr) == thread_;
}
private:
BleEventDispatcher()
: thread_(nullptr),
allEvtQueue_(nullptr),
ioEvtQueue_(nullptr),
started_(false) {
}
~BleEventDispatcher() = default;
void handleIoMessage(T_IO_MSG message) const;
static void bleEventDispatchThread(void *context);
void cleanup();
void* thread_;
void* allEvtQueue_;
void* ioEvtQueue_;
bool started_;
static constexpr uint8_t BLE_EVENT_THREAD_PRIORITY = OS_THREAD_PRIORITY_NETWORK - 1; // IMPORTANT: below network for coexistence to work!
static constexpr uint8_t MAX_NUMBER_OF_GAP_MESSAGE = 0x20;
static constexpr uint8_t MAX_NUMBER_OF_IO_MESSAGE = 0x20;
static constexpr uint8_t MAX_NUMBER_OF_EVENT_MESSAGE = (MAX_NUMBER_OF_GAP_MESSAGE + MAX_NUMBER_OF_IO_MESSAGE);
static constexpr uint8_t BLE_EVENT_STOP = 0xff;
};
union RtlGapDevState {
T_GAP_DEV_STATE state;
uint8_t raw;
static_assert(sizeof(state) == sizeof(raw), "Size of T_GAP_DEV_STATE does not match uint8_t");
};
class BleGapDevState {
public:
BleGapDevState()
: state_{},
initSet_{false},
advSet_{false},
advSubSet_{false},
scanSet_{false},
connSet_{false} {
}
explicit BleGapDevState(RtlGapDevState s)
: state_(s),
initSet_{true},
advSet_{true},
advSubSet_{true},
scanSet_{true},
connSet_{true} {
}
BleGapDevState(BleGapDevState&& other) = default;
BleGapDevState(const BleGapDevState& other) = default;
BleGapDevState& init(uint8_t state) {
state_.state.gap_init_state = state;
initSet_ = true;
return *this;
}
BleGapDevState& adv(uint8_t state) {
state_.state.gap_adv_state = state;
advSet_ = true;
return *this;
}
BleGapDevState& advSub(uint8_t state) {
state_.state.gap_adv_sub_state = state;
advSubSet_ = true;
return *this;
}
BleGapDevState& scan(uint8_t state) {
state_.state.gap_scan_state = state;
scanSet_ = true;
return *this;
}
BleGapDevState& conn(uint8_t state) {
state_.state.gap_conn_state = state;
connSet_ = true;
return *this;
}
bool operator==(const BleGapDevState& other) {
auto a = sanitizedState();
auto b = other.sanitizedState();
return !memcmp(&a, &b, sizeof(a));
}
BleGapDevState& copySetParamsFrom(const BleGapDevState& other) {
initSet_ = other.initSet_;
advSet_ = other.advSet_;
advSubSet_ = other.advSubSet_;
scanSet_ = other.scanSet_;
connSet_ = other.connSet_;
return *this;
}
bool isNotInitialized() const {
T_GAP_DEV_STATE state = {};
return initSet_ && advSet_ && advSubSet_ && scanSet_ && connSet_ && !memcmp(&state, &state_, sizeof(state));
}
RtlGapDevState state() const {
return state_;
}
private:
RtlGapDevState sanitizedState() const {
auto state = state_;
if (!initSet_) {
state.state.gap_init_state = 0;
}
if (!advSet_) {
state.state.gap_adv_state = 0;
}
if (!advSubSet_) {
state.state.gap_adv_sub_state = 0;
}
if (!scanSet_) {
state.state.gap_scan_state = 0;
}
if (!connSet_) {
state.state.gap_conn_state = 0;
}
return state;
}
RtlGapDevState state_;
bool initSet_;
bool advSet_;
bool advSubSet_;
bool scanSet_;
bool connSet_;
};
class BleGap {
public:
int start();
int stop(bool restore = true);
int init();
bool initialized() const {
return initialized_;
}
int setAppearance(uint16_t appearance) const;
int setDeviceName(const char* deviceName, size_t len);
int getDeviceName(char* deviceName, size_t len) const;
int setDeviceAddress(const hal_ble_addr_t* address);
int getDeviceAddress(hal_ble_addr_t* address) const;
int setAdvertisingParameters(const hal_ble_adv_params_t* params);
int getAdvertisingParameters(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 startAdvertising(bool wait = true); // TODO: always wait, now we have command thread to execute asynchronously
int stopAdvertising(bool wait = true); // TODO: always wait, now we have command thread to execute asynchronously
int notifyAdvStop();
bool isAdvertising() const {
return isAdvertising_;
}
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();
int setPpcp(const hal_ble_conn_params_t* ppcp);
int getPpcp(hal_ble_conn_params_t* ppcp) const;
int connect(const hal_ble_conn_cfg_t* config, hal_ble_conn_handle_t* conn_handle);
int connectCancel(const hal_ble_addr_t* address);
ssize_t getAttMtu(hal_ble_conn_handle_t connHandle);
int getConnectionInfo(hal_ble_conn_handle_t connHandle, hal_ble_conn_info_t* info);
int disconnect(hal_ble_conn_handle_t connHandle);
int disconnectAll();
bool valid(hal_ble_conn_handle_t connHandle);
bool connected(const hal_ble_addr_t* address) {
std::lock_guard<RecursiveMutex> lk(connectionsMutex_);
if (address == nullptr) {
return connections_.size() > 0;
}
if (fetchConnection(address)) {
return true;
}
return false;
}
bool connecting() const {
return connecting_;
}
int setPairingConfig(const hal_ble_pairing_config_t* config);
int getPairingConfig(hal_ble_pairing_config_t* config) const;
int setPairingAuthData(hal_ble_conn_handle_t connHandle, const hal_ble_pairing_auth_data_t* auth);
int startPairing(hal_ble_conn_handle_t connHandle);
int rejectPairing(hal_ble_conn_handle_t connHandle);
bool isPairing(hal_ble_conn_handle_t connHandle);
bool isPaired(hal_ble_conn_handle_t connHandle);
int waitState(BleGapDevState state, system_tick_t timeout = BLE_STATE_DEFAULT_TIMEOUT, bool forcePoll = false);
void handleDevStateChanged(T_GAP_DEV_STATE state, uint16_t cause);
void handleConnectionStateChanged(uint8_t connHandle, T_GAP_CONN_STATE newState, uint16_t discCause);
void handleMtuUpdated(uint8_t connHandle, uint16_t mtuSize);
void handleConnParamsUpdated(uint8_t connHandle, uint8_t status, uint16_t cause);
int handleAuthenStateChanged(uint8_t connHandle, uint8_t state, uint16_t cause);
int handlePairJustWork(uint8_t connHandle);
int handlePairPasskeyDisplay(uint8_t connHandle, bool displayOnly = true);
int handlePairPasskeyInput(uint8_t connHandle);
int onPeripheralLinkEventCallback(hal_ble_on_link_evt_cb_t cb, void* context) {
std::pair<hal_ble_on_link_evt_cb_t, void*> callback(cb, context);
CHECK_TRUE(periphEvtCallbacks_.append(callback), SYSTEM_ERROR_NO_MEMORY);
return SYSTEM_ERROR_NONE;
}
int enqueue(uint8_t cmd) {
CHECK_TRUE(cmdQueue_, SYSTEM_ERROR_INVALID_STATE);
if (os_queue_put(cmdQueue_, &cmd, BLE_ENQUEUE_TIMEOUT_MS, nullptr)) {
LOG(ERROR, "os_queue_put() failed.");
SPARK_ASSERT(false);
}
return SYSTEM_ERROR_NONE;
}
bool isQueueAvailable() const {
uint8_t command;
if (!os_queue_peek(cmdQueue_, &command, 0, nullptr)) {
return true;
}
return false;
}
void lockMode(bool lock) {
bleInLockedMode_ = lock;
}
bool lockMode() {
return bleInLockedMode_;
}
static BleGap& getInstance() {
static BleGap instance;
return instance;
}
int onAdvEventCallback(hal_ble_on_adv_evt_cb_t callback, void* context);
void cancelAdvEventCallback(hal_ble_on_adv_evt_cb_t callback, void* context);
private:
enum BlePairingState {
BLE_PAIRING_STATE_NOT_INITIATED,
BLE_PAIRING_STATE_INITIATED, // Central role only
BLE_PAIRING_STATE_STARTED,
BLE_PAIRING_STATE_USER_REQ_REJECT,
BLE_PAIRING_STATE_SET_AUTH_DATA,
BLE_PAIRING_STATE_REJECTED,
BLE_PAIRING_STATE_PAIRED
};
enum BleGapCommand {
BLE_CMD_EXIT_THREAD,
BLE_CMD_STOP_ADV,
BLE_CMD_STOP_ADV_NOTIFY,
BLE_CMD_START_ADV
};
struct BleGapCache {
bool isAdv;
bool isScan;
bool isConn;
};
struct BleConnection {
hal_ble_conn_info_t info;
std::pair<hal_ble_on_link_evt_cb_t, void*> handler; // It is used for central link only.
BlePairingState pairState;
};
BleGap()
: cmdThread_(nullptr),
cmdQueue_(nullptr),
initialized_(false),
btStackStarted_(false),
state_{},
addr_{},
advParams_{},
advTimeoutTimer_(nullptr),
isScanning_(false),
scanParams_{},
scanSemaphore_(nullptr),
scanResultCallback_(nullptr),
context_(nullptr),
periphEvtCallbacks_{},
connectingAddr_{},
connectSemaphore_(nullptr),
disconnectSemaphore_(nullptr),
disconnectingHandle_(BLE_INVALID_CONN_HANDLE),
connecting_(false),
ppcp_{},
pairingConfig_{},
devNameLen_(0),
isAdvertising_(false),
stateSemaphore_(nullptr),
pairingLesc_(false),
bleInLockedMode_(false),
cache_{} {
advParams_.version = BLE_API_VERSION;
advParams_.size = sizeof(hal_ble_adv_params_t);
advParams_.interval = BLE_DEFAULT_ADVERTISING_INTERVAL;
advParams_.timeout = BLE_DEFAULT_ADVERTISING_TIMEOUT;
advParams_.type = BLE_ADV_CONNECTABLE_SCANNABLE_UNDIRECRED_EVT;
advParams_.filter_policy = BLE_ADV_FP_ANY;
advParams_.inc_tx_power = false;
advParams_.primary_phy = 0; // Not used
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;
ppcp_.version = BLE_API_VERSION;
ppcp_.size = sizeof(hal_ble_conn_params_t);
ppcp_.min_conn_interval = BLE_DEFAULT_MIN_CONN_INTERVAL;
ppcp_.max_conn_interval = BLE_DEFAULT_MAX_CONN_INTERVAL;
ppcp_.slave_latency = BLE_DEFAULT_SLAVE_LATENCY;
ppcp_.conn_sup_timeout = BLE_DEFAULT_CONN_SUP_TIMEOUT;
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.
pairingConfig_ = {
.version = BLE_API_VERSION,
.size = sizeof(hal_ble_pairing_config_t),
.io_caps = BLE_IO_CAPS_NONE,
.algorithm = BLE_PAIRING_ALGORITHM_AUTO,
.reserved = {}
};
}
~BleGap() = default;
T_GAP_ADTYPE toPlatformAdvEvtType(hal_ble_adv_evt_type_t type) const {
switch (type) {
case BLE_ADV_CONNECTABLE_SCANNABLE_UNDIRECRED_EVT:
case BLE_ADV_CONNECTABLE_UNDIRECTED_EVT: {
return GAP_ADTYPE_ADV_IND;
}
case BLE_ADV_CONNECTABLE_DIRECTED_EVT: {
return GAP_ADTYPE_ADV_HDC_DIRECT_IND;
}
case BLE_ADV_NON_CONNECTABLE_NON_SCANABLE_UNDIRECTED_EVT:
case BLE_ADV_NON_CONNECTABLE_NON_SCANABLE_DIRECTED_EVT: {
return GAP_ADTYPE_ADV_NONCONN_IND;
}
case BLE_ADV_SCANABLE_UNDIRECTED_EVT:
case BLE_ADV_SCANABLE_DIRECTED_EVT: {
return GAP_ADTYPE_ADV_SCAN_IND;
}
default:{
return GAP_ADTYPE_ADV_IND;
}
}
}
RtlGapDevState getState() const {
RtlGapDevState s;
s.raw = state_.raw;
return s;
}
void notifyScanResult(T_LE_SCAN_INFO* advReport);
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();
bool connectedAsBlePeripheral() const {
for (auto& connection : connections_) {
if (connection.info.role == BLE_ROLE_PERIPHERAL) {
return true;
}
}
return false;
}
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 notifyLinkEvent(const hal_ble_link_evt_t& event);
static T_APP_RESULT gapEventCallback(uint8_t type, void *data);
static void onAdvTimeoutTimerExpired(os_timer_t timer);
static void bleCommandThread(void *context);
struct BleAdvEventHandler {
hal_ble_on_adv_evt_cb_t callback;
void* context;
};
void* cmdThread_;
void* cmdQueue_;
bool initialized_;
bool btStackStarted_;
volatile RtlGapDevState state_; /**< This should be atomically r/w as the struct is <= uint32_t */
hal_ble_addr_t addr_;
hal_ble_adv_params_t advParams_;
os_timer_t advTimeoutTimer_; /**< Timer for advertising timeout. */
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. */
hal_ble_on_scan_result_cb_t scanResultCallback_; /**< Callback function on scan result. */
void* context_; /**< Context of the scan result callback function. */
Vector<hal_ble_scan_result_evt_t> pendingResults_;
Vector<std::pair<hal_ble_on_link_evt_cb_t, void*>> periphEvtCallbacks_;
hal_ble_addr_t connectingAddr_; /**< Address of peer the Central is connecting to. */
os_semaphore_t connectSemaphore_; /**< Semaphore to wait until connection established. */
std::pair<hal_ble_on_link_evt_cb_t, void*> centralLinkCbCache_; // It is used for central link only.
os_semaphore_t disconnectSemaphore_; /**< Semaphore to wait until connection disconnected. */
volatile hal_ble_conn_handle_t disconnectingHandle_; /**< Handle of connection to be disconnected. */
Vector<BleConnection> connections_;
volatile bool connecting_;
hal_ble_conn_params_t ppcp_;
hal_ble_pairing_config_t pairingConfig_;
uint8_t advData_[BLE_MAX_ADV_DATA_LEN]; /**< Current advertising data. */
size_t advDataLen_; /**< Current advertising data length. */
uint8_t scanRespData_[BLE_MAX_ADV_DATA_LEN]; /**< Current scan response data. */
size_t scanRespDataLen_; /**< Current scan response data length. */
char devName_[BLE_MAX_DEV_NAME_LEN + 1]; // null-terminated
size_t devNameLen_;
static constexpr uint16_t BLE_ADV_TIMEOUT_EXT_MS = 50;
volatile bool isAdvertising_;
os_semaphore_t stateSemaphore_;
uint8_t pairingLesc_;
bool bleInLockedMode_;
BleGapCache cache_;
Vector<BleAdvEventHandler> advEventHandlers_;
Mutex advEventMutex_;
RecursiveMutex connectionsMutex_;
static constexpr system_tick_t BLE_WAIT_STATE_POLL_PERIOD_MS = 10;
// IMPORTANT: large enough, some of the state changes are dependent
// on callback execution etc.
static constexpr system_tick_t BLE_STATE_DEFAULT_TIMEOUT = 10000;
static constexpr uint8_t BLE_CMD_THREAD_PRIORITY = OS_THREAD_PRIORITY_NETWORK - 1; // IMPORTANT: below network for coexistence to work!
static constexpr uint16_t BLE_CMD_THREAD_STACK_SIZE = 2048;
static constexpr uint8_t BLE_CMD_QUEUE_SIZE = 0x20;
};
class BleGatt {
public:
struct Subscriber {
hal_ble_conn_handle_t connHandle;
ble_sig_cccd_value_t config;
};
struct CccdConfig {
uint16_t index;
Subscriber subscriber; // FIXME: now we assume that only one client is connected
};
struct BleCharacteristic {
hal_ble_attr_handle_t handle;
uint16_t index;
hal_ble_on_char_evt_cb_t callback;
void* context;
};
struct BleService {
T_SERVER_ID id;
Vector<T_ATTRIB_APPL> attrTable;
hal_ble_uuid_t uuid;
hal_ble_attr_handle_t startHandle;
hal_ble_attr_handle_t endHandle;
Vector<BleCharacteristic> characteristics;
Vector<CccdConfig> cccdConfigs;
};
int init();
int deinit();
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 registerAttributeTable();
ssize_t setValue(hal_ble_attr_handle_t attrHandle, const uint8_t* buf, size_t len);
ssize_t getValue(hal_ble_attr_handle_t attrHandle, uint8_t* buf, size_t len);
ssize_t notifyValue(hal_ble_attr_handle_t attrHandle, const uint8_t* buf, size_t len, bool ack);
int removeSubscriber(hal_ble_conn_handle_t connHandle);
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, const hal_ble_uuid_t* uuid, hal_ble_on_disc_char_cb_t callback, void* context);
int configureRemoteCCCD(const hal_ble_cccd_config_t* config);
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 setDesiredAttMtu(size_t attMtu);
bool registered() const {
return serviceRegistered_;
}
Vector<BleService>& services() {
return services_;
}
static BleGatt& getInstance() {
static BleGatt instance;
return instance;
}
private:
BleGatt()
: serviceRegistered_(false),
attrConfigured_(false),
isNotifying_(false),
notifySemaphore_(nullptr),
isDiscovering_(false),
currDiscConnHandle_(BLE_INVALID_CONN_HANDLE),
currDiscService_(nullptr),
discoverySemaphore_(nullptr),
discSvcUuid_(nullptr),
discSvcCallback_(nullptr),
discSvcContext_(nullptr),
discCharCallback_(nullptr),
discCharContext_(nullptr),
clientId_(CLIENT_PROFILE_GENERAL_ID),
clientCallbacks_{},
serverCallbacks_(),
currReadConnHandle_(BLE_INVALID_CONN_HANDLE),
readAttrHandle_(BLE_INVALID_ATTR_HANDLE),
readBuf_(nullptr),
readLen_(0),
readSemaphore_(nullptr),
currWriteConnHandle_(BLE_INVALID_CONN_HANDLE),
writeAttrHandle_(BLE_INVALID_ATTR_HANDLE),
writeSemaphore_(nullptr),
desiredAttMtu_(BLE_MAX_ATT_MTU_SIZE) {
clientCallbacks_.discover_state_cb = onDiscoverStateCallback;
clientCallbacks_.discover_result_cb = onDiscoverResultCallback;
clientCallbacks_.read_result_cb = onReadResultCallback;
clientCallbacks_.write_result_cb = onWriteResultCallback;
clientCallbacks_.notify_ind_result_cb = onNotifyIndResultCallback;
clientCallbacks_.disconnect_cb = onGattClientDisconnectCallback;
serverCallbacks_.read_attr_cb = gattReadAttrCallback;
serverCallbacks_.write_attr_cb = gattWriteAttrCallback;
serverCallbacks_.cccd_update_cb = gattCccdUpdatedCallback;
resetDiscoveryState();
}
~BleGatt() = default;
struct Publisher {
hal_ble_on_char_evt_cb_t callback;
void* context;
hal_ble_conn_handle_t connHandle;
hal_ble_attr_handle_t valueHandle;
};
T_ATTRIB_APPL* findAttribute(hal_ble_attr_handle_t attrHandle) {
for (auto& svc : services_) {
if (attrHandle < svc.startHandle && attrHandle > svc.endHandle) {
continue;
}
for (const auto& charact : svc.characteristics) {
if (charact.handle != attrHandle) {
continue;
}
LOG_DEBUG(TRACE, "Found attr, id:%d, index:%d", svc.id, charact.index);
return &svc.attrTable[charact.index];
}
}
return nullptr;
}
void resetDiscoveryState();
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);
int removeAllPublishersOfConnection(hal_ble_conn_handle_t connHandle);
static T_APP_RESULT gattServerEventCallback(T_SERVER_ID serviceId, void *pData);
static T_APP_RESULT gattReadAttrCallback(uint8_t connHandle, T_SERVER_ID serviceId, uint16_t index, uint16_t offset, uint16_t *length, uint8_t **value);
static T_APP_RESULT gattWriteAttrCallback(uint8_t connHandle, T_SERVER_ID serviceId, uint16_t index, T_WRITE_TYPE type, uint16_t length, uint8_t *value, P_FUN_WRITE_IND_POST_PROC *postProc);
static void gattCccdUpdatedCallback(uint8_t connHandle, T_SERVER_ID serviceId, uint16_t index, uint16_t bits);
static void onDiscoverStateCallback(uint8_t connHandle, T_DISCOVERY_STATE discoveryState);
static void onDiscoverResultCallback(uint8_t connHandle, T_DISCOVERY_RESULT_TYPE type, T_DISCOVERY_RESULT_DATA data);
static void onReadResultCallback(uint8_t connHandle, uint16_t cause, uint16_t handle, uint16_t size, uint8_t *value);
static void onWriteResultCallback(uint8_t connHandle, T_GATT_WRITE_TYPE type, uint16_t handle, uint16_t cause, uint8_t credits);
static T_APP_RESULT onNotifyIndResultCallback(uint8_t connHandle, bool notify, uint16_t handle, uint16_t size, uint8_t *value);
static void onGattClientDisconnectCallback(uint8_t connHandle);
bool serviceRegistered_;
bool attrConfigured_;
volatile bool isNotifying_;
os_semaphore_t notifySemaphore_; /**< Semaphore to sync notify/indicate operation. */
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. */
const hal_ble_svc_t* currDiscService_; /**< Used for discovering descriptors */
os_semaphore_t discoverySemaphore_; /**< Semaphore to wait until the discovery procedure completed. */
const hal_ble_uuid_t* discSvcUuid_; /**< Used only when discover service by UUID. */
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. */
Vector<hal_ble_svc_t> discServices_; /**< Discover services. */
Vector<hal_ble_char_t> discCharacteristics_; /**< Discovered characteristics. */
T_CLIENT_ID clientId_;
T_FUN_CLIENT_CBS clientCallbacks_;
T_FUN_GATT_SERVICE_CBS serverCallbacks_;
hal_ble_conn_handle_t currReadConnHandle_;
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. */
os_semaphore_t readSemaphore_; /**< Semaphore to wait until the read operation completed. */
hal_ble_conn_handle_t currWriteConnHandle_;
hal_ble_attr_handle_t writeAttrHandle_; /**< Current handle of which attribute to be read. */
os_semaphore_t writeSemaphore_; /**< Semaphore to wait until the write operation completed. */
size_t desiredAttMtu_;
Vector<BleService> services_;
Vector<Publisher> publishers_;
static constexpr uint8_t MAX_ALLOWED_BLE_SERVICES = 5;
static constexpr uint16_t CUSTOMER_SERVICE_START_HANDLE = 30;
static constexpr uint8_t SERVICE_HANDLE_RANGE_RESERVED = 20;
};
int BleEventDispatcher::start() {
if (started_) {
// Already running
return SYSTEM_ERROR_NONE;
}
SCOPE_GUARD({
if (!started_) {
cleanup();
}
});
if (!ioEvtQueue_) {
CHECK_TRUE(os_msg_queue_create(&ioEvtQueue_, MAX_NUMBER_OF_IO_MESSAGE, sizeof(T_IO_MSG)), SYSTEM_ERROR_INTERNAL);
}
if (!allEvtQueue_) {
CHECK_TRUE(os_msg_queue_create(&allEvtQueue_, MAX_NUMBER_OF_EVENT_MESSAGE, sizeof(uint8_t)), SYSTEM_ERROR_INTERNAL);
}
if (!thread_) {
CHECK_TRUE(os_thread_create(&thread_, "bleEvtThread", BLE_EVENT_THREAD_PRIORITY, bleEventDispatchThread, this, BLE_EVENT_THREAD_STACK_SIZE) == 0, SYSTEM_ERROR_INTERNAL);
}
CHECK_TRUE(gap_start_bt_stack(allEvtQueue_, ioEvtQueue_, MAX_NUMBER_OF_GAP_MESSAGE), SYSTEM_ERROR_INTERNAL);
started_ = true;
return SYSTEM_ERROR_NONE;
}
int BleEventDispatcher::stop() {
cleanup();
started_ = false;
return SYSTEM_ERROR_NONE;
}
void BleEventDispatcher::cleanup() {
if (thread_ && allEvtQueue_ && !isThreadCurrent()) {
uint8_t ev = BLE_EVENT_STOP;
SPARK_ASSERT(os_msg_send(allEvtQueue_, &ev, BLE_ENQUEUE_TIMEOUT_MS));
os_thread_join(thread_);
thread_ = nullptr;
}
if (allEvtQueue_) {
if (!thread_) {
os_msg_queue_delete(allEvtQueue_);
allEvtQueue_ = nullptr;
} else {
uint8_t event;
while (os_msg_recv(allEvtQueue_, &event, 0) == true) {}
}
}
if (ioEvtQueue_) {
if (!thread_) {
os_msg_queue_delete(ioEvtQueue_);
ioEvtQueue_ = nullptr;
} else {
T_IO_MSG message;
while (os_msg_recv(ioEvtQueue_, &message, 0) == true) {}
}
}
}
void BleEventDispatcher::handleIoMessage(T_IO_MSG message) const {
switch (message.type) {
case IO_MSG_TYPE_BT_STATUS: {
T_LE_GAP_MSG gap_msg;
memcpy(&gap_msg, &message.u.param, sizeof(message.u.param));
switch (message.subtype) {
case GAP_MSG_LE_DEV_STATE_CHANGE: {
LOG_DEBUG(TRACE, "handleIoMessage, GAP_MSG_LE_DEV_STATE_CHANGE");
const auto& devStateChange = gap_msg.msg_data.gap_dev_state_change;
BleGap::getInstance().handleDevStateChanged(devStateChange.new_state, devStateChange.cause);
break;
}
case GAP_MSG_LE_CONN_STATE_CHANGE: {
LOG_DEBUG(TRACE, "handleIoMessage, GAP_MSG_LE_CONN_STATE_CHANGE");
const auto& connStateChange = gap_msg.msg_data.gap_conn_state_change;
BleGap::getInstance().handleConnectionStateChanged(connStateChange.conn_id, (T_GAP_CONN_STATE)connStateChange.new_state, connStateChange.disc_cause);
break;
}
case GAP_MSG_LE_CONN_MTU_INFO: {
LOG_DEBUG(TRACE, "handleIoMessage, GAP_MSG_LE_CONN_MTU_INFO");
const auto& mtuUpdated = gap_msg.msg_data.gap_conn_mtu_info;
BleGap::getInstance().handleMtuUpdated(mtuUpdated.conn_id, mtuUpdated.mtu_size);
break;
}
case GAP_MSG_LE_CONN_PARAM_UPDATE: {
LOG_DEBUG(TRACE, "handleIoMessage, GAP_MSG_LE_CONN_PARAM_UPDATE");
const auto& connParamsUpdated = gap_msg.msg_data.gap_conn_param_update;
BleGap::getInstance().handleConnParamsUpdated(connParamsUpdated.conn_id, connParamsUpdated.status, connParamsUpdated.cause);
break;
}
case GAP_MSG_LE_AUTHEN_STATE_CHANGE: {
LOG_DEBUG(TRACE, "handleIoMessage, GAP_MSG_LE_AUTHEN_STATE_CHANGE");
const auto& authenStateChanged = gap_msg.msg_data.gap_authen_state;
BleGap::getInstance().handleAuthenStateChanged(authenStateChanged.conn_id, authenStateChanged.new_state, authenStateChanged.status);
break;
}
case GAP_MSG_LE_BOND_JUST_WORK: {
LOG_DEBUG(TRACE, "handleIoMessage, GAP_MSG_LE_BOND_JUST_WORK");
const auto& pairJustWork = gap_msg.msg_data.gap_bond_just_work_conf;
BleGap::getInstance().handlePairJustWork(pairJustWork.conn_id);
break;
}
case GAP_MSG_LE_BOND_PASSKEY_DISPLAY: {
LOG_DEBUG(TRACE, "handleIoMessage, GAP_MSG_LE_BOND_PASSKEY_DISPLAY");
auto& passkeyDisplay = gap_msg.msg_data.gap_bond_passkey_display;
BleGap::getInstance().handlePairPasskeyDisplay(passkeyDisplay.conn_id);
break;
}
case GAP_MSG_LE_BOND_USER_CONFIRMATION: {
// Numeric comparison
LOG_DEBUG(TRACE, "handleIoMessage, GAP_MSG_LE_BOND_USER_CONFIRMATION");
auto& numericComparison = gap_msg.msg_data.gap_bond_user_conf;
BleGap::getInstance().handlePairPasskeyDisplay(numericComparison.conn_id, false);
break;
}
case GAP_MSG_LE_BOND_PASSKEY_INPUT: {
LOG_DEBUG(TRACE, "handleIoMessage: GAP_MSG_LE_BOND_PASSKEY_INPUT");
auto& passkeyInput = gap_msg.msg_data.gap_bond_passkey_input;
BleGap::getInstance().handlePairPasskeyInput(passkeyInput.conn_id);
break;
}
default: {
LOG_DEBUG(TRACE, "handleIoMessage: unknown subtype %d", message.subtype);
break;
}
}
break;
}
case IO_MSG_TYPE_AT_CMD: {
LOG_DEBUG(TRACE, "handleIoMessage: IO_MSG_TYPE_AT_CMD");
break;
}
case IO_MSG_TYPE_QDECODE: {
LOG_DEBUG(TRACE, "handleIoMessage: IO_MSG_TYPE_QDECODE");
break;
}
default: break;
}
}
void BleEventDispatcher::bleEventDispatchThread(void *context) {
BleEventDispatcher* dispatcher = (BleEventDispatcher*)context;
while (true) {
uint8_t event;
if (os_msg_recv(dispatcher->allEvtQueue_, &event, 0xFFFFFFFF) == true) {
std::lock_guard<StaticRecursiveMutex> lk(sBleEventMutex);
if (event == EVENT_IO_TO_APP) {
T_IO_MSG message;
if (os_msg_recv(dispatcher->ioEvtQueue_, &message, 0) == true) {
// Handled by application directly
dispatcher->handleIoMessage(message);