-
-
Notifications
You must be signed in to change notification settings - Fork 170
/
Copy pathNimBLEDevice.cpp
1279 lines (1116 loc) · 42.8 KB
/
NimBLEDevice.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 2020-2025 Ryan Powell <[email protected]> and
* esp-nimble-cpp, NimBLE-Arduino contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "nimconfig.h"
#if defined(CONFIG_BT_ENABLED)
# include "NimBLEDevice.h"
# include "NimBLEUtils.h"
# ifdef ESP_PLATFORM
# include "esp_err.h"
# ifndef CONFIG_IDF_TARGET_ESP32P4
# include "esp_bt.h"
# endif
# include "nvs_flash.h"
# if defined(CONFIG_NIMBLE_CPP_IDF)
# if (ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0) || CONFIG_BT_NIMBLE_LEGACY_VHCI_ENABLE)
# include "esp_nimble_hci.h"
# endif
# include "nimble/nimble_port.h"
# include "nimble/nimble_port_freertos.h"
# include "host/ble_hs.h"
# include "host/ble_hs_pvcy.h"
# include "host/util/util.h"
# include "services/gap/ble_svc_gap.h"
# include "services/gatt/ble_svc_gatt.h"
# else
# include "nimble/esp_port/esp-hci/include/esp_nimble_hci.h"
# endif
# else
# include "nimble/nimble/controller/include/controller/ble_phy.h"
# endif
# ifndef CONFIG_NIMBLE_CPP_IDF
# include "nimble/porting/nimble/include/nimble/nimble_port.h"
# include "nimble/porting/npl/freertos/include/nimble/nimble_port_freertos.h"
# include "nimble/nimble/host/include/host/ble_hs.h"
# include "nimble/nimble/host/include/host/ble_hs_pvcy.h"
# include "nimble/nimble/host/util/include/host/util/util.h"
# include "nimble/nimble/host/services/gap/include/services/gap/ble_svc_gap.h"
# include "nimble/nimble/host/services/gatt/include/services/gatt/ble_svc_gatt.h"
# endif
# if defined(ESP_PLATFORM) && defined(CONFIG_ENABLE_ARDUINO_DEPENDS)
# include "esp32-hal-bt.h"
# endif
# if defined(CONFIG_BT_NIMBLE_ROLE_CENTRAL)
# include "NimBLEClient.h"
# endif
# if defined(CONFIG_BT_NIMBLE_ROLE_PERIPHERAL)
# include "NimBLEServer.h"
# endif
# include "NimBLELog.h"
static const char* LOG_TAG = "NimBLEDevice";
extern "C" void ble_store_config_init(void);
/**
* Singletons for the NimBLEDevice.
*/
NimBLEDeviceCallbacks NimBLEDevice::defaultDeviceCallbacks{};
NimBLEDeviceCallbacks* NimBLEDevice::m_pDeviceCallbacks = &defaultDeviceCallbacks;
# if defined(CONFIG_BT_NIMBLE_ROLE_OBSERVER)
NimBLEScan* NimBLEDevice::m_pScan = nullptr;
# endif
# if defined(CONFIG_BT_NIMBLE_ROLE_PERIPHERAL)
NimBLEServer* NimBLEDevice::m_pServer = nullptr;
# endif
# if defined(CONFIG_BT_NIMBLE_ROLE_BROADCASTER)
# if CONFIG_BT_NIMBLE_EXT_ADV
NimBLEExtAdvertising* NimBLEDevice::m_bleAdvertising = nullptr;
# else
NimBLEAdvertising* NimBLEDevice::m_bleAdvertising = nullptr;
# endif
# endif
# if defined(CONFIG_BT_NIMBLE_ROLE_CENTRAL)
std::array<NimBLEClient*, NIMBLE_MAX_CONNECTIONS> NimBLEDevice::m_pClients{nullptr};
# endif
bool NimBLEDevice::m_initialized{false};
uint32_t NimBLEDevice::m_passkey{123456};
bool NimBLEDevice::m_synced{false};
ble_gap_event_listener NimBLEDevice::m_listener{};
std::vector<NimBLEAddress> NimBLEDevice::m_whiteList{};
uint8_t NimBLEDevice::m_ownAddrType{BLE_OWN_ADDR_PUBLIC};
# ifdef ESP_PLATFORM
# ifdef CONFIG_BTDM_BLE_SCAN_DUPL
uint16_t NimBLEDevice::m_scanDuplicateSize{CONFIG_BTDM_SCAN_DUPL_CACHE_SIZE};
uint8_t NimBLEDevice::m_scanFilterMode{CONFIG_BTDM_SCAN_DUPL_TYPE};
# endif
# endif
/* -------------------------------------------------------------------------- */
/* SERVER FUNCTIONS */
/* -------------------------------------------------------------------------- */
# if defined(CONFIG_BT_NIMBLE_ROLE_PERIPHERAL)
/**
* @brief Create an instance of a server.
* @return A pointer to the instance of the server.
*/
NimBLEServer* NimBLEDevice::createServer() {
if (NimBLEDevice::m_pServer == nullptr) {
NimBLEDevice::m_pServer = new NimBLEServer();
ble_gatts_reset();
ble_svc_gap_init();
ble_svc_gatt_init();
}
return m_pServer;
} // createServer
/**
* @brief Get the instance of the server.
* @return A pointer to the server instance or nullptr if none have been created.
*/
NimBLEServer* NimBLEDevice::getServer() {
return m_pServer;
} // getServer
# endif // #if defined(CONFIG_BT_NIMBLE_ROLE_PERIPHERAL)
/* -------------------------------------------------------------------------- */
/* ADVERTISING FUNCTIONS */
/* -------------------------------------------------------------------------- */
# if defined(CONFIG_BT_NIMBLE_ROLE_BROADCASTER)
# if CONFIG_BT_NIMBLE_EXT_ADV
/**
* @brief Get the instance of the extended advertising object.
* @return A pointer to the extended advertising object.
*/
NimBLEExtAdvertising* NimBLEDevice::getAdvertising() {
if (m_bleAdvertising == nullptr) {
m_bleAdvertising = new NimBLEExtAdvertising();
}
return m_bleAdvertising;
}
/**
* @brief Convenience function to begin advertising.
* @param [in] instId The extended advertisement instance ID to start.
* @param [in] duration How long to advertise for in milliseconds, 0 = forever (default).
* @param [in] maxEvents Maximum number of advertisement events to send, 0 = no limit (default).
* @return True if advertising started successfully.
*/
bool NimBLEDevice::startAdvertising(uint8_t instId, int duration, int maxEvents) {
return getAdvertising()->start(instId, duration, maxEvents);
} // startAdvertising
/**
* @brief Convenience function to stop advertising a data set.
* @param [in] instId The extended advertisement instance ID to stop advertising.
* @return True if advertising stopped successfully.
*/
bool NimBLEDevice::stopAdvertising(uint8_t instId) {
return getAdvertising()->stop(instId);
} // stopAdvertising
# endif
# if !CONFIG_BT_NIMBLE_EXT_ADV || defined(_DOXYGEN_)
/**
* @brief Get the instance of the advertising object.
* @return A pointer to the advertising object.
*/
NimBLEAdvertising* NimBLEDevice::getAdvertising() {
if (m_bleAdvertising == nullptr) {
m_bleAdvertising = new NimBLEAdvertising();
}
return m_bleAdvertising;
}
/**
* @brief Convenience function to begin advertising.
* @param [in] duration The duration in milliseconds to advertise for, default = forever.
* @return True if advertising started successfully.
*/
bool NimBLEDevice::startAdvertising(uint32_t duration) {
return getAdvertising()->start(duration);
} // startAdvertising
# endif
/**
* @brief Convenience function to stop all advertising.
* @return True if advertising stopped successfully.
*/
bool NimBLEDevice::stopAdvertising() {
return getAdvertising()->stop();
} // stopAdvertising
# endif // #if defined(CONFIG_BT_NIMBLE_ROLE_BROADCASTER)
/* -------------------------------------------------------------------------- */
/* SCAN FUNCTIONS */
/* -------------------------------------------------------------------------- */
/**
* @brief Retrieve the Scan object that we use for scanning.
* @return The scanning object reference. This is a singleton object. The caller should not
* try and release/delete it.
*/
# if defined(CONFIG_BT_NIMBLE_ROLE_OBSERVER)
NimBLEScan* NimBLEDevice::getScan() {
if (m_pScan == nullptr) {
m_pScan = new NimBLEScan();
}
return m_pScan;
} // getScan
# ifdef ESP_PLATFORM
# ifdef CONFIG_BTDM_BLE_SCAN_DUPL
/**
* @brief Set the duplicate filter cache size for filtering scanned devices.
* @param [in] size The number of advertisements filtered before the cache is reset.\n
* Range is 10-1000, a larger value will reduce how often the same devices are reported.
* @details Must only be called before calling NimBLEDevice::init.
*/
void NimBLEDevice::setScanDuplicateCacheSize(uint16_t size) {
if (m_initialized) {
NIMBLE_LOGE(LOG_TAG, "Cannot change scan cache size while initialized");
return;
} else {
if (size > 1000) {
size = 1000;
} else if (size < 10) {
size = 10;
}
}
NIMBLE_LOGD(LOG_TAG, "Set duplicate cache size to: %u", size);
m_scanDuplicateSize = size;
}
/**
* @brief Set the duplicate filter mode for filtering scanned devices.
* @param [in] mode One of three possible options:
* * CONFIG_BTDM_SCAN_DUPL_TYPE_DEVICE (0) (default)\n
Filter by device address only, advertisements from the same address will be reported only once.
* * CONFIG_BTDM_SCAN_DUPL_TYPE_DATA (1)\n
Filter by data only, advertisements with the same data will only be reported once,\n
even from different addresses.
* * CONFIG_BTDM_SCAN_DUPL_TYPE_DATA_DEVICE (2)\n
Filter by address and data, advertisements from the same address will be reported only once,\n
except if the data in the advertisement has changed, then it will be reported again.
* @details Must only be called before calling NimBLEDevice::init.
*/
void NimBLEDevice::setScanFilterMode(uint8_t mode) {
if (m_initialized) {
NIMBLE_LOGE(LOG_TAG, "Cannot change scan duplicate type while initialized");
return;
} else if (mode > 2) {
NIMBLE_LOGE(LOG_TAG, "Invalid scan duplicate type");
return;
}
m_scanFilterMode = mode;
}
# endif // CONFIG_BTDM_BLE_SCAN_DUPL
# endif // ESP_PLATFORM
# endif // #if defined(CONFIG_BT_NIMBLE_ROLE_OBSERVER)
/* -------------------------------------------------------------------------- */
/* CLIENT FUNCTIONS */
/* -------------------------------------------------------------------------- */
# if defined(CONFIG_BT_NIMBLE_ROLE_CENTRAL)
/**
* @brief Creates a new client object, each client can connect to 1 peripheral device.
* @return A pointer to the new client object, or nullptr on error.
*/
NimBLEClient* NimBLEDevice::createClient() {
return createClient(NimBLEAddress{});
} // createClient
/**
* @brief Creates a new client object, each client can connect to 1 peripheral device.
* @param [in] peerAddress A peer address reference that is copied to the new client
* object, allows for calling NimBLEClient::connect(bool) without a device or address parameter.
* @return A pointer to the new client object, or nullptr on error.
*/
NimBLEClient* NimBLEDevice::createClient(const NimBLEAddress& peerAddress) {
for (auto& clt : m_pClients) {
if (clt == nullptr) {
clt = new NimBLEClient(peerAddress);
return clt;
}
}
NIMBLE_LOGE(LOG_TAG, "Unable to create client; already at max: %d", NIMBLE_MAX_CONNECTIONS);
return nullptr;
} // createClient
/**
* @brief Delete the client object and remove it from the list.\n
* Checks if it is connected or trying to connect and disconnects/stops it first.
* @param [in] pClient A pointer to the client object.
*/
bool NimBLEDevice::deleteClient(NimBLEClient* pClient) {
if (pClient == nullptr) {
return false;
}
for (auto& clt : m_pClients) {
if (clt == pClient) {
if (clt->isConnected()) {
clt->m_config.deleteOnDisconnect = true;
if (!clt->disconnect()) {
break;
}
} else if (pClient->m_pTaskData != nullptr) {
clt->m_config.deleteOnConnectFail = true;
if (!clt->cancelConnect()) {
break;
}
} else {
delete clt;
clt = nullptr;
}
return true;
}
}
return false;
} // deleteClient
/**
* @brief Get the number of created client objects.
* @return Number of client objects created.
*/
size_t NimBLEDevice::getCreatedClientCount() {
size_t count = 0;
for (const auto clt : m_pClients) {
if (clt != nullptr) {
count++;
}
}
return count;
} // getCreatedClientCount
/**
* @brief Get a reference to a client by connection handle.
* @param [in] connHandle The client connection handle to search for.
* @return A pointer to the client object with the specified connection handle or nullptr.
*/
NimBLEClient* NimBLEDevice::getClientByHandle(uint16_t connHandle) {
for (const auto clt : m_pClients) {
if (clt != nullptr && clt->getConnHandle() == connHandle) {
return clt;
}
}
return nullptr;
} // getClientByHandle
/**
* @brief Get a reference to a client by peer address.
* @param [in] addr The address of the peer to search for.
* @return A pointer to the client object with the peer address or nullptr.
*/
NimBLEClient* NimBLEDevice::getClientByPeerAddress(const NimBLEAddress& addr) {
for (const auto clt : m_pClients) {
if (clt != nullptr && clt->getPeerAddress() == addr) {
return clt;
}
}
return nullptr;
} // getClientPeerAddress
/**
* @brief Finds the first disconnected client available.
* @return A pointer to the first client object that is not connected to a peer or nullptr.
*/
NimBLEClient* NimBLEDevice::getDisconnectedClient() {
for (const auto clt : m_pClients) {
if (clt != nullptr && !clt->isConnected()) {
return clt;
}
}
return nullptr;
} // getDisconnectedClient
/**
* @brief Get a list of connected clients.
* @return A vector of connected client objects.
*/
std::vector<NimBLEClient*> NimBLEDevice::getConnectedClients() {
std::vector<NimBLEClient*> clients;
for (const auto clt : m_pClients) {
if (clt != nullptr && clt->isConnected()) {
clients.push_back(clt);
}
}
return clients;
} // getConnectedClients
# endif // #if defined(CONFIG_BT_NIMBLE_ROLE_CENTRAL)
/* -------------------------------------------------------------------------- */
/* TRANSMIT POWER */
/* -------------------------------------------------------------------------- */
# ifdef ESP_PLATFORM
# ifndef CONFIG_IDF_TARGET_ESP32P4
/**
* @brief Get the transmission power.
* @return The power level currently used in esp_power_level_t or a negative value on error.
*/
esp_power_level_t NimBLEDevice::getPowerLevel(esp_ble_power_type_t powerType) {
esp_power_level_t pwr = esp_ble_tx_power_get(powerType);
# if defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32S3)
// workaround for bug when "enhanced tx power" was added
if (pwr == 0xFF) {
pwr = esp_ble_tx_power_get(ESP_BLE_PWR_TYPE_CONN_HDL3);
}
# endif
return pwr;
} // getPowerLevel
/**
* @brief Set the transmission power.
* @param [in] powerLevel The power level to set in esp_power_level_t.
* @return True if the power level was set successfully.
*/
bool NimBLEDevice::setPowerLevel(esp_power_level_t powerLevel, esp_ble_power_type_t powerType) {
esp_err_t errRc = esp_ble_tx_power_set(powerType, powerLevel);
if (errRc != ESP_OK) {
NIMBLE_LOGE(LOG_TAG, "esp_ble_tx_power_set: rc=%d", errRc);
}
return errRc == ESP_OK;
} // setPowerLevel
# endif // !CONFIG_IDF_TARGET_ESP32P4
# endif // ESP_PLATFORM
/**
* @brief Set the transmission power.
* @param [in] dbm The power level to set in dBm.
* @return True if the power level was set successfully.
*/
bool NimBLEDevice::setPower(int8_t dbm, NimBLETxPowerType type) {
# ifdef ESP_PLATFORM
# ifdef CONFIG_IDF_TARGET_ESP32P4
return false; // CONFIG_IDF_TARGET_ESP32P4 does not support esp_ble_tx_power_set
# else
if (dbm % 3 == 2) {
dbm++; // round up to the next multiple of 3 to be able to target 20dbm
}
bool success = false;
esp_power_level_t espPwr = static_cast<esp_power_level_t>(dbm / 3 + ESP_PWR_LVL_N0);
if (type == NimBLETxPowerType::All) {
success = setPowerLevel(espPwr, ESP_BLE_PWR_TYPE_ADV);
success &= setPowerLevel(espPwr, ESP_BLE_PWR_TYPE_SCAN);
success &= setPowerLevel(espPwr, ESP_BLE_PWR_TYPE_DEFAULT);
} else if (type == NimBLETxPowerType::Advertise) {
success = setPowerLevel(espPwr, ESP_BLE_PWR_TYPE_ADV);
} else if (type == NimBLETxPowerType::Scan) {
success = setPowerLevel(espPwr, ESP_BLE_PWR_TYPE_SCAN);
} else if (type == NimBLETxPowerType::Connection) {
success = setPowerLevel(espPwr, ESP_BLE_PWR_TYPE_DEFAULT);
}
return success;
# endif
# else
(void)type; // unused
NIMBLE_LOGD(LOG_TAG, ">> setPower: %d", dbm);
ble_hci_vs_set_tx_pwr_cp cmd{dbm};
ble_hci_vs_set_tx_pwr_rp rsp{0};
int rc = ble_hs_hci_send_vs_cmd(BLE_HCI_OCF_VS_SET_TX_PWR, &cmd, sizeof(cmd), &rsp, sizeof(rsp));
if (rc) {
NIMBLE_LOGE(LOG_TAG, "failed to set TX power, rc: %04x\n", rc);
return false;
}
NIMBLE_LOGD(LOG_TAG, "TX power set to %d dBm\n", rsp.tx_power);
return true;
# endif
} // setPower
/**
* @brief Get the transmission power.
* @return The power level currently used in dbm or 0xFF on error.
*/
int NimBLEDevice::getPower(NimBLETxPowerType type) {
# ifdef ESP_PLATFORM
# ifdef CONFIG_IDF_TARGET_ESP32P4
return 0xFF; // CONFIG_IDF_TARGET_ESP32P4 does not support esp_ble_tx_power_get
# else
esp_ble_power_type_t espPwr = type == NimBLETxPowerType::Advertise ? ESP_BLE_PWR_TYPE_ADV
: type == NimBLETxPowerType::Scan ? ESP_BLE_PWR_TYPE_SCAN
: ESP_BLE_PWR_TYPE_DEFAULT;
int pwr = getPowerLevel(espPwr);
if (pwr < 0) {
NIMBLE_LOGE(LOG_TAG, "esp_ble_tx_power_get failed rc=%d", pwr);
return 0xFF;
}
if (pwr < ESP_PWR_LVL_N0) {
return -3 * (ESP_PWR_LVL_N0 - pwr);
}
if (pwr > ESP_PWR_LVL_N0) {
return std::min<int>((pwr - ESP_PWR_LVL_N0) * 3, 20);
}
return 0;
# endif
# else
(void)type; // unused
return ble_phy_txpwr_get();
# endif
} // getPower
/* -------------------------------------------------------------------------- */
/* MTU FUNCTIONS */
/* -------------------------------------------------------------------------- */
/**
* @brief Setup local mtu that will be used to negotiate mtu during request from client peer.
* @param [in] mtu Value to set local mtu:
* * This should be larger than 23 and lower or equal to BLE_ATT_MTU_MAX = 527.
* @return True if the mtu was set successfully.
*/
bool NimBLEDevice::setMTU(uint16_t mtu) {
int rc = ble_att_set_preferred_mtu(mtu);
if (rc != 0) {
NIMBLE_LOGE(LOG_TAG, "Could not set local mtu value to: %d, rc: %d", mtu, rc);
}
return rc == 0;
} // setMTU
/**
* @brief Get local MTU value set.
* @return The current preferred MTU setting.
*/
uint16_t NimBLEDevice::getMTU() {
return ble_att_preferred_mtu();
}
/* -------------------------------------------------------------------------- */
/* BOND MANAGEMENT */
/* -------------------------------------------------------------------------- */
# if defined(CONFIG_BT_NIMBLE_ROLE_CENTRAL) || defined(CONFIG_BT_NIMBLE_ROLE_PERIPHERAL)
/**
* @brief Gets the number of bonded peers stored
*/
int NimBLEDevice::getNumBonds() {
ble_addr_t peer_id_addrs[MYNEWT_VAL(BLE_STORE_MAX_BONDS)];
int num_peers, rc;
rc = ble_store_util_bonded_peers(&peer_id_addrs[0], &num_peers, MYNEWT_VAL(BLE_STORE_MAX_BONDS));
if (rc != 0) {
return 0;
}
return num_peers;
}
/**
* @brief Deletes all bonding information.
* @returns True on success.
*/
bool NimBLEDevice::deleteAllBonds() {
int rc = ble_store_clear();
if (rc != 0) {
NIMBLE_LOGE(LOG_TAG, "Failed to delete all bonds; rc=%d", rc);
return false;
}
return true;
}
/**
* @brief Deletes a peer bond.
* @param [in] address The address of the peer with which to delete bond info.
* @returns True on success.
*/
bool NimBLEDevice::deleteBond(const NimBLEAddress& address) {
return ble_gap_unpair(address.getBase()) == 0;
}
/**
* @brief Checks if a peer device is bonded.
* @param [in] address The address to check for bonding.
* @returns True if bonded.
*/
bool NimBLEDevice::isBonded(const NimBLEAddress& address) {
ble_addr_t peer_id_addrs[MYNEWT_VAL(BLE_STORE_MAX_BONDS)];
int num_peers, rc;
rc = ble_store_util_bonded_peers(&peer_id_addrs[0], &num_peers, MYNEWT_VAL(BLE_STORE_MAX_BONDS));
if (rc != 0) {
return false;
}
for (int i = 0; i < num_peers; i++) {
NimBLEAddress storedAddr(peer_id_addrs[i]);
if (storedAddr == address) {
return true;
}
}
return false;
}
/**
* @brief Get the address of a bonded peer device by index.
* @param [in] index The index to retrieve the peer address of.
* @returns NimBLEAddress of the found bonded peer or null address if not found.
*/
NimBLEAddress NimBLEDevice::getBondedAddress(int index) {
ble_addr_t peer_id_addrs[MYNEWT_VAL(BLE_STORE_MAX_BONDS)];
int num_peers, rc;
rc = ble_store_util_bonded_peers(&peer_id_addrs[0], &num_peers, MYNEWT_VAL(BLE_STORE_MAX_BONDS));
if (rc != 0 || index > num_peers || index < 0) {
return NimBLEAddress{};
}
return NimBLEAddress(peer_id_addrs[index]);
}
# endif
/* -------------------------------------------------------------------------- */
/* WHITELIST */
/* -------------------------------------------------------------------------- */
/**
* @brief Checks if a peer device is whitelisted.
* @param [in] address The address to check for in the whitelist.
* @returns True if the address is in the whitelist.
*/
bool NimBLEDevice::onWhiteList(const NimBLEAddress& address) {
for (const auto& addr : m_whiteList) {
if (addr == address) {
return true;
}
}
return false;
}
/**
* @brief Add a peer address to the whitelist.
* @param [in] address The address to add to the whitelist.
* @returns True if successful.
*/
bool NimBLEDevice::whiteListAdd(const NimBLEAddress& address) {
if (!NimBLEDevice::onWhiteList(address)) {
m_whiteList.push_back(address);
int rc = ble_gap_wl_set(reinterpret_cast<ble_addr_t*>(&m_whiteList[0]), m_whiteList.size());
if (rc != 0) {
NIMBLE_LOGE(LOG_TAG, "Failed adding to whitelist rc=%d", rc);
m_whiteList.pop_back();
return false;
}
}
return true;
}
/**
* @brief Remove a peer address from the whitelist.
* @param [in] address The address to remove from the whitelist.
* @returns True if successful.
*/
bool NimBLEDevice::whiteListRemove(const NimBLEAddress& address) {
for (auto it = m_whiteList.begin(); it < m_whiteList.end(); ++it) {
if (*it == address) {
m_whiteList.erase(it);
int rc = ble_gap_wl_set(reinterpret_cast<ble_addr_t*>(&m_whiteList[0]), m_whiteList.size());
if (rc != 0) {
m_whiteList.push_back(address);
NIMBLE_LOGE(LOG_TAG, "Failed removing from whitelist rc=%d", rc);
return false;
}
std::vector<NimBLEAddress>(m_whiteList).swap(m_whiteList);
}
}
return true;
}
/**
* @brief Gets the count of addresses in the whitelist.
* @returns The number of addresses in the whitelist.
*/
size_t NimBLEDevice::getWhiteListCount() {
return m_whiteList.size();
}
/**
* @brief Gets the address at the vector index.
* @param [in] index The vector index to retrieve the address from.
* @returns The NimBLEAddress at the whitelist index or null address if not found.
*/
NimBLEAddress NimBLEDevice::getWhiteListAddress(size_t index) {
if (index > m_whiteList.size()) {
NIMBLE_LOGE(LOG_TAG, "Invalid index; %u", index);
return NimBLEAddress{};
}
return m_whiteList[index];
}
/* -------------------------------------------------------------------------- */
/* STACK FUNCTIONS */
/* -------------------------------------------------------------------------- */
# if CONFIG_BT_NIMBLE_EXT_ADV || defined(_DOXYGEN_)
/**
* @brief Set the preferred default phy to use for connections.
* @param [in] txPhyMask TX PHY. Can be mask of following:
* - BLE_GAP_LE_PHY_1M_MASK
* - BLE_GAP_LE_PHY_2M_MASK
* - BLE_GAP_LE_PHY_CODED_MASK
* - BLE_GAP_LE_PHY_ANY_MASK
* @param [in] rxPhyMask RX PHY. Can be mask of following:
* - BLE_GAP_LE_PHY_1M_MASK
* - BLE_GAP_LE_PHY_2M_MASK
* - BLE_GAP_LE_PHY_CODED_MASK
* - BLE_GAP_LE_PHY_ANY_MASK
* @return True if successful.
*/
bool NimBLEDevice::setDefaultPhy(uint8_t txPhyMask, uint8_t rxPhyMask) {
int rc = ble_gap_set_prefered_default_le_phy(txPhyMask, rxPhyMask);
if (rc != 0) {
NIMBLE_LOGE(LOG_TAG, "Failed to set default phy; rc=%d %s", rc, NimBLEUtils::returnCodeToString(rc));
}
return rc == 0;
}
# endif
/**
* @brief Host reset, we pass the message so we don't make calls until re-synced.
* @param [in] reason The reason code for the reset.
*/
void NimBLEDevice::onReset(int reason) {
if (!m_synced) {
return;
}
m_synced = false;
NIMBLE_LOGE(LOG_TAG, "Host reset; reason=%d, %s", reason, NimBLEUtils::returnCodeToString(reason));
} // onReset
/**
* @brief Host synced with controller, all clear to make calls to the stack.
*/
void NimBLEDevice::onSync(void) {
NIMBLE_LOGI(LOG_TAG, "NimBle host synced.");
// This check is needed due to potentially being called multiple times in succession
// If this happens, the call to scan start may get stuck or cause an advertising fault.
if (m_synced) {
return;
}
// Get the public and random address for the device.
int rc = ble_hs_util_ensure_addr(0);
if (rc == 0) {
rc = ble_hs_util_ensure_addr(1);
}
if (rc != 0) {
NIMBLE_LOGE(LOG_TAG, "error ensuring address; rc=%d", rc);
return;
}
// start with using the public address if available, if not then use random.
rc = ble_hs_id_copy_addr(BLE_OWN_ADDR_PUBLIC, NULL, NULL);
if (rc != 0) {
m_ownAddrType = BLE_OWN_ADDR_RANDOM;
}
// Yield for housekeeping tasks before returning to operations.
// Occasionally triggers exception without.
ble_npl_time_delay(1);
m_synced = true;
if (m_initialized) {
# if defined(CONFIG_BT_NIMBLE_ROLE_OBSERVER)
if (m_pScan != nullptr) {
m_pScan->onHostSync();
}
# endif
# if defined(CONFIG_BT_NIMBLE_ROLE_BROADCASTER)
if (m_bleAdvertising != nullptr) {
m_bleAdvertising->onHostSync();
}
# endif
}
} // onSync
/**
* @brief The main host task.
*/
void NimBLEDevice::host_task(void* param) {
NIMBLE_LOGI(LOG_TAG, "BLE Host Task Started");
nimble_port_run(); // This function will return only when nimble_port_stop() is executed
nimble_port_freertos_deinit();
} // host_task
/**
* @brief Initialize the BLE environment.
* @param [in] deviceName The device name of the device.
*/
bool NimBLEDevice::init(const std::string& deviceName) {
if (!m_initialized) {
# ifdef ESP_PLATFORM
# ifdef CONFIG_ENABLE_ARDUINO_DEPENDS
// make sure the linker includes esp32-hal-bt.c so Arduino init doesn't release BLE memory.
btStarted();
# endif
esp_err_t err = nvs_flash_init();
if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
err = nvs_flash_erase();
if (err == ESP_OK) {
err = nvs_flash_init();
}
}
if (err != ESP_OK) {
NIMBLE_LOGE(LOG_TAG, "nvs_flash_init() failed; err=%d", err);
return false;
}
# if CONFIG_IDF_TARGET_ESP32
esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT);
# endif
# if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0) | !defined(CONFIG_NIMBLE_CPP_IDF)
esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT();
# if defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32S3)
bt_cfg.bluetooth_mode = ESP_BT_MODE_BLE;
# else
bt_cfg.mode = ESP_BT_MODE_BLE;
bt_cfg.ble_max_conn = CONFIG_BT_NIMBLE_MAX_CONNECTIONS;
# endif
# ifdef CONFIG_BTDM_BLE_SCAN_DUPL
bt_cfg.normal_adv_size = m_scanDuplicateSize;
bt_cfg.scan_duplicate_type = m_scanFilterMode;
# endif
err = esp_bt_controller_init(&bt_cfg);
if (err != ESP_OK) {
NIMBLE_LOGE(LOG_TAG, "esp_bt_controller_init() failed; err=%d", err);
return false;
}
err = esp_bt_controller_enable(ESP_BT_MODE_BLE);
if (err != ESP_OK) {
NIMBLE_LOGE(LOG_TAG, "esp_bt_controller_enable() failed; err=%d", err);
return false;
}
err = esp_nimble_hci_init();
if (err != ESP_OK) {
NIMBLE_LOGE(LOG_TAG, "esp_nimble_hci_init() failed; err=%d", err);
return false;
}
# endif
# endif
nimble_port_init();
// Setup callbacks for host events
ble_hs_cfg.reset_cb = NimBLEDevice::onReset;
ble_hs_cfg.sync_cb = NimBLEDevice::onSync;
ble_hs_cfg.store_status_cb = [](struct ble_store_status_event* event, void* arg) {
return m_pDeviceCallbacks->onStoreStatus(event, arg);
};
// Set initial security capabilities
ble_hs_cfg.sm_io_cap = BLE_HS_IO_NO_INPUT_OUTPUT;
ble_hs_cfg.sm_bonding = 0;
ble_hs_cfg.sm_mitm = 0;
ble_hs_cfg.sm_sc = 1;
ble_hs_cfg.sm_our_key_dist = BLE_SM_PAIR_KEY_DIST_ENC;
ble_hs_cfg.sm_their_key_dist = BLE_SM_PAIR_KEY_DIST_ENC;
# if MYNEWT_VAL(BLE_LL_CFG_FEAT_LL_PRIVACY)
ble_hs_cfg.sm_our_key_dist |= BLE_SM_PAIR_KEY_DIST_ID;
ble_hs_cfg.sm_their_key_dist |= BLE_SM_PAIR_KEY_DIST_ID;
# endif
setDeviceName(deviceName);
ble_store_config_init();
nimble_port_freertos_init(NimBLEDevice::host_task);
}
// Wait for host and controller to sync before returning and accepting new tasks
while (!m_synced) {
ble_npl_time_delay(1);
}
m_initialized = true; // Set the initialization flag to ensure we are only initialized once.
return true;
} // init
/**
* @brief Shutdown the NimBLE stack/controller.
* @param [in] clearAll If true, deletes all server/advertising/scan/client objects after de-initializing.
* @note If clearAll is true when called all objects created will be deleted and any references to the created objects become invalid.
* If clearAll is false, the objects will remain and can be used again after re-initializing the stack.
* If the stack was not already initialized, the objects created can be deleted when clearAll is true with no effect on the stack.
*/
bool NimBLEDevice::deinit(bool clearAll) {
int rc = 0;
if (m_initialized) {
rc = nimble_port_stop();
if (rc == 0) {
nimble_port_deinit();
# ifdef CONFIG_NIMBLE_CPP_IDF
# if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0)
rc = esp_nimble_hci_and_controller_deinit();
if (rc != ESP_OK) {
NIMBLE_LOGE(LOG_TAG, "esp_nimble_hci_and_controller_deinit() failed with error: %d", rc);
}
# endif
# endif
m_initialized = false;
m_synced = false;
}
}
if (clearAll) {
# if defined(CONFIG_BT_NIMBLE_ROLE_PERIPHERAL)
if (NimBLEDevice::m_pServer != nullptr) {
delete NimBLEDevice::m_pServer;
NimBLEDevice::m_pServer = nullptr;
}
# endif
# if defined(CONFIG_BT_NIMBLE_ROLE_BROADCASTER)
if (NimBLEDevice::m_bleAdvertising != nullptr) {
delete NimBLEDevice::m_bleAdvertising;
NimBLEDevice::m_bleAdvertising = nullptr;
}
# endif
# if defined(CONFIG_BT_NIMBLE_ROLE_OBSERVER)
if (NimBLEDevice::m_pScan != nullptr) {
delete NimBLEDevice::m_pScan;
NimBLEDevice::m_pScan = nullptr;
}
# endif
# if defined(CONFIG_BT_NIMBLE_ROLE_CENTRAL)
for (auto clt : m_pClients) {
deleteClient(clt);
}
# endif
}
return rc == 0;
} // deinit
/**
* @brief Check if the initialization is complete.
* @return true if initialized.
*/
bool NimBLEDevice::isInitialized() {
return m_initialized;
} // getInitialized