-
Notifications
You must be signed in to change notification settings - Fork 7.8k
Expand file tree
/
Copy pathBLEAdvertising.cpp
More file actions
1784 lines (1574 loc) · 57.2 KB
/
BLEAdvertising.cpp
File metadata and controls
1784 lines (1574 loc) · 57.2 KB
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 2017-2026 Espressif Systems (Shanghai) PTE LTD
* Copyright 2020-2025 Ryan Powell <ryan@nable-embedded.io> and
* esp-nimble-cpp, NimBLE-Arduino contributors.
* Copyright 2017 Neil Kolban
*
* 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.
*/
/*
* BLEAdvertising.cpp
*
* This class encapsulates advertising a BLE Server.
* Created on: Jun 21, 2017
* Author: kolban
*
* Modified on: Feb 18, 2025
* Author: lucasssvaz (based on kolban's and h2zero's work)
* Description: Added support for NimBLE
*
* The ESP-IDF provides a framework for BLE advertising. It has determined that there are a common set
* of properties that are advertised and has built a data structure that can be populated by the programmer.
* This means that the programmer doesn't have to "mess with" the low level construction of a low level
* BLE advertising frame. Many of the fields are determined for us while others we can set before starting
* to advertise.
*
* Should we wish to construct our own payload, we can use the BLEAdvertisementData class and call the setters
* upon it. Once it is populated, we can then associate it with the advertising and what ever the programmer
* set in the data will be advertised.
*
*/
#include "soc/soc_caps.h"
#include "sdkconfig.h"
#if defined(SOC_BLE_SUPPORTED) || defined(CONFIG_ESP_HOSTED_ENABLE_BT_NIMBLE)
#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
/***************************************************************************
* Common includes *
***************************************************************************/
#include "BLEAdvertising.h"
#include <esp_err.h>
#include "BLEUtils.h"
#include "BLEDevice.h"
#include "GeneralUtils.h"
#include "esp32-hal-log.h"
/***************************************************************************
* Common functions *
***************************************************************************/
/**
* @brief Construct a default advertising object.
*/
BLEAdvertising::BLEAdvertising() {
reset();
} // BLEAdvertising
/**
* @brief Add a service uuid to exposed list of services.
* @param [in] serviceUUID The UUID of the service to expose.
*/
void BLEAdvertising::addServiceUUID(BLEUUID serviceUUID) {
m_serviceUUIDs.push_back(serviceUUID);
m_advDataSet = false;
} // addServiceUUID
/**
* @brief Add a service uuid to exposed list of services.
* @param [in] serviceUUID The string representation of the service to expose.
*/
void BLEAdvertising::addServiceUUID(const char *serviceUUID) {
addServiceUUID(BLEUUID(serviceUUID));
} // addServiceUUID
/**
* @brief Remove a service uuid to exposed list of services.
* @param [in] index The index of the service to stop exposing.
*/
bool BLEAdvertising::removeServiceUUID(int index) {
// If index is larger than the size of the
// advertised services, return false
if (index > m_serviceUUIDs.size()) {
return false;
}
m_serviceUUIDs.erase(m_serviceUUIDs.begin() + index);
m_advDataSet = false;
return true;
}
/**
* @brief Remove a service uuid to exposed list of services.
* @param [in] serviceUUID The BLEUUID of the service to stop exposing.
*/
bool BLEAdvertising::removeServiceUUID(BLEUUID serviceUUID) {
for (int i = 0; i < m_serviceUUIDs.size(); i++) {
if (m_serviceUUIDs.at(i).equals(serviceUUID)) {
return removeServiceUUID(i);
}
}
return false;
}
/**
* @brief Remove a service uuid to exposed list of services.
* @param [in] serviceUUID The string of the service to stop exposing.
*/
bool BLEAdvertising::removeServiceUUID(const char *serviceUUID) {
return removeServiceUUID(BLEUUID(serviceUUID));
}
/**
* @brief Set the device appearance in the advertising data.
* The appearance attribute is of type 0x19. The codes for distinct appearances can be found here:
* https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.gap.appearance.xml.
* @param [in] appearance The appearance of the device in the advertising data.
* @return N/A.
*/
void BLEAdvertising::setAppearance(uint16_t appearance) {
m_advData.appearance = appearance;
#ifdef CONFIG_NIMBLE_ENABLED
m_advData.appearance_is_present = 1;
#endif
m_advDataSet = false;
} // setAppearance
void BLEAdvertising::setAdvertisementType(uint8_t adv_type) {
#ifdef CONFIG_BLUEDROID_ENABLED
m_advParams.adv_type = (esp_ble_adv_type_t)adv_type;
#endif
#if defined(CONFIG_NIMBLE_ENABLED)
m_advParams.conn_mode = adv_type;
#endif
} // setAdvertisementType
void BLEAdvertising::setMinInterval(uint16_t mininterval) {
#ifdef CONFIG_BLUEDROID_ENABLED
m_advParams.adv_int_min = mininterval;
#endif
#if defined(CONFIG_NIMBLE_ENABLED)
m_advParams.itvl_min = mininterval;
#endif
} // setMinInterval
void BLEAdvertising::setMaxInterval(uint16_t maxinterval) {
#ifdef CONFIG_BLUEDROID_ENABLED
m_advParams.adv_int_max = maxinterval;
#endif
#if defined(CONFIG_NIMBLE_ENABLED)
m_advParams.itvl_max = maxinterval;
#endif
} // setMaxInterval
void BLEAdvertising::setMinPreferred(uint16_t mininterval) {
#ifdef CONFIG_BLUEDROID_ENABLED
m_advData.min_interval = mininterval;
m_advDataSet = false;
#endif
#if defined(CONFIG_NIMBLE_ENABLED)
// invalid parameters, set the slave interval to null
if (mininterval < 0x0006 || mininterval > 0x0C80) {
m_advData.slave_itvl_range = nullptr;
return;
}
if (m_advData.slave_itvl_range == nullptr) {
m_advData.slave_itvl_range = m_slaveItvl;
}
m_slaveItvl[0] = mininterval;
m_slaveItvl[1] = mininterval >> 8;
uint16_t maxinterval = *(uint16_t *)(m_advData.slave_itvl_range + 2);
// If mininterval is higher than the maxinterval make them the same
if (mininterval > maxinterval) {
m_slaveItvl[2] = m_slaveItvl[0];
m_slaveItvl[3] = m_slaveItvl[1];
}
m_advDataSet = false;
#endif
} //
void BLEAdvertising::setMaxPreferred(uint16_t maxinterval) {
#ifdef CONFIG_BLUEDROID_ENABLED
m_advData.max_interval = maxinterval;
m_advDataSet = false;
#endif
#if defined(CONFIG_NIMBLE_ENABLED)
// invalid parameters, set the slave interval to null
if (maxinterval < 0x0006 || maxinterval > 0x0C80) {
m_advData.slave_itvl_range = nullptr;
return;
}
if (m_advData.slave_itvl_range == nullptr) {
m_advData.slave_itvl_range = m_slaveItvl;
}
m_slaveItvl[2] = maxinterval;
m_slaveItvl[3] = maxinterval >> 8;
uint16_t mininterval = *(uint16_t *)(m_advData.slave_itvl_range);
// If mininterval is higher than the maxinterval make them the same
if (mininterval > maxinterval) {
m_slaveItvl[0] = m_slaveItvl[2];
m_slaveItvl[1] = m_slaveItvl[3];
}
m_advDataSet = false;
#endif
} //
void BLEAdvertising::setScanResponse(bool set) {
m_scanResp = set;
m_advDataSet = false;
}
/**
* @brief Set the filtering for the scan filter.
* @param [in] scanRequestWhitelistOnly If true, only allow scan requests from those on the white list.
* @param [in] connectWhitelistOnly If true, only allow connections from those on the white list.
*/
void BLEAdvertising::setScanFilter(bool scanRequestWhitelistOnly, bool connectWhitelistOnly) {
log_v(">> setScanFilter: scanRequestWhitelistOnly: %d, connectWhitelistOnly: %d", scanRequestWhitelistOnly, connectWhitelistOnly);
if (!scanRequestWhitelistOnly && !connectWhitelistOnly) {
#ifdef CONFIG_BLUEDROID_ENABLED
m_advParams.adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY;
#endif
#if defined(CONFIG_NIMBLE_ENABLED)
m_advParams.filter_policy = BLE_HCI_ADV_FILT_NONE;
#endif
log_v("<< setScanFilter");
return;
}
if (scanRequestWhitelistOnly && !connectWhitelistOnly) {
#ifdef CONFIG_BLUEDROID_ENABLED
m_advParams.adv_filter_policy = ADV_FILTER_ALLOW_SCAN_WLST_CON_ANY;
#endif
#if defined(CONFIG_NIMBLE_ENABLED)
m_advParams.filter_policy = BLE_HCI_ADV_FILT_SCAN;
#endif
log_v("<< setScanFilter");
return;
}
if (!scanRequestWhitelistOnly && connectWhitelistOnly) {
#ifdef CONFIG_BLUEDROID_ENABLED
m_advParams.adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_WLST;
#endif
#if defined(CONFIG_NIMBLE_ENABLED)
m_advParams.filter_policy = BLE_HCI_ADV_FILT_CONN;
#endif
log_v("<< setScanFilter");
return;
}
if (scanRequestWhitelistOnly && connectWhitelistOnly) {
#ifdef CONFIG_BLUEDROID_ENABLED
m_advParams.adv_filter_policy = ADV_FILTER_ALLOW_SCAN_WLST_CON_WLST;
#endif
#if defined(CONFIG_NIMBLE_ENABLED)
m_advParams.filter_policy = BLE_HCI_ADV_FILT_BOTH;
#endif
log_v("<< setScanFilter");
return;
}
} // setScanFilter
/**
* @brief Set the advertisement data that is to be published in a regular advertisement.
* @param [in] advertisementData The data to be advertised.
*/
bool BLEAdvertising::setAdvertisementData(BLEAdvertisementData &advertisementData) {
log_v(">> setAdvertisementData");
#ifdef CONFIG_BLUEDROID_ENABLED
esp_err_t errRc = ::esp_ble_gap_config_adv_data_raw((uint8_t *)advertisementData.getPayload().c_str(), advertisementData.getPayload().length());
if (errRc != ESP_OK) {
log_e("esp_ble_gap_config_adv_data_raw: %d %s", errRc, GeneralUtils::errorToString(errRc));
}
#endif
#if defined(CONFIG_NIMBLE_ENABLED)
esp_err_t errRc = ble_gap_adv_set_data((uint8_t *)advertisementData.getPayload().c_str(), advertisementData.getPayload().length());
if (errRc != ESP_OK) {
log_e("ble_gap_adv_set_data: %d %s", errRc, BLEUtils::returnCodeToString(errRc));
}
#endif
m_customAdvData = true; // Set the flag that indicates we are using custom advertising data.
log_v("<< setAdvertisementData");
return ESP_OK == errRc;
} // setAdvertisementData
/**
* @brief Set the advertisement data that is to be published in a scan response.
* @param [in] advertisementData The data to be advertised.
*/
bool BLEAdvertising::setScanResponseData(BLEAdvertisementData &advertisementData) {
log_v(">> setScanResponseData");
#ifdef CONFIG_BLUEDROID_ENABLED
esp_err_t errRc = ::esp_ble_gap_config_scan_rsp_data_raw((uint8_t *)advertisementData.getPayload().c_str(), advertisementData.getPayload().length());
if (errRc != ESP_OK) {
log_e("esp_ble_gap_config_scan_rsp_data_raw: %d %s", errRc, GeneralUtils::errorToString(errRc));
}
#endif
#if defined(CONFIG_NIMBLE_ENABLED)
esp_err_t errRc = ble_gap_adv_rsp_set_data((uint8_t *)advertisementData.getPayload().c_str(), advertisementData.getPayload().length());
if (errRc != ESP_OK) {
log_e("ble_gap_adv_rsp_set_data: %d %s", errRc, BLEUtils::returnCodeToString(errRc));
}
#endif
m_customScanResponseData = true; // Set the flag that indicates we are using custom scan response data.
log_v("<< setScanResponseData");
return ESP_OK == errRc;
} // setScanResponseData
/**
* @brief Add data to the payload to be advertised.
* @param [in] data The data to be added to the payload.
*/
void BLEAdvertisementData::addData(String data) {
if ((m_payload.length() + data.length()) > ESP_BLE_ADV_DATA_LEN_MAX) {
return;
}
m_payload.concat(data);
} // addData
void BLEAdvertisementData::addData(char *data, size_t length) {
if ((m_payload.length() + length) > ESP_BLE_ADV_DATA_LEN_MAX) {
return;
}
m_payload.concat(String(data, length));
} // addData
/**
* @brief Set the appearance.
* @param [in] appearance The appearance code value.
*
* See also:
* https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.gap.appearance.xml
*/
void BLEAdvertisementData::setAppearance(uint16_t appearance) {
char cdata[2];
cdata[0] = 3;
cdata[1] = ESP_BLE_AD_TYPE_APPEARANCE; // 0x19
addData(String(cdata, 2) + String((char *)&appearance, 2));
} // setAppearance
/**
* @brief Set the complete services.
* @param [in] uuid The single service to advertise.
*/
void BLEAdvertisementData::setCompleteServices(BLEUUID uuid) {
char cdata[2];
switch (uuid.bitSize()) {
case 16:
{
// [Len] [0x03] [LL] [HH]
cdata[0] = 3;
cdata[1] = ESP_BLE_AD_TYPE_16SRV_CMPL; // 0x03
#if defined(CONFIG_BLUEDROID_ENABLED)
addData(String(cdata, 2) + String((char *)&uuid.getNative()->uuid.uuid16, 2));
#endif
#if defined(CONFIG_NIMBLE_ENABLED)
addData(String(cdata, 2) + String((char *)&uuid.getNative()->u16.value, 2));
#endif
break;
}
case 32:
{
// [Len] [0x05] [LL] [LL] [HH] [HH]
cdata[0] = 5;
cdata[1] = ESP_BLE_AD_TYPE_32SRV_CMPL; // 0x05
#if defined(CONFIG_BLUEDROID_ENABLED)
addData(String(cdata, 2) + String((char *)&uuid.getNative()->uuid.uuid32, 4));
#endif
#if defined(CONFIG_NIMBLE_ENABLED)
addData(String(cdata, 2) + String((char *)&uuid.getNative()->u32.value, 4));
#endif
break;
}
case 128:
{
// [Len] [0x07] [0] [1] ... [15]
cdata[0] = 17;
cdata[1] = ESP_BLE_AD_TYPE_128SRV_CMPL; // 0x07
#if defined(CONFIG_BLUEDROID_ENABLED)
addData(String(cdata, 2) + String((char *)uuid.getNative()->uuid.uuid128, 16));
#endif
#if defined(CONFIG_NIMBLE_ENABLED)
addData(String(cdata, 2) + String((char *)uuid.getNative()->u128.value, 16));
#endif
break;
}
default: return;
}
} // setCompleteServices
/**
* @brief Set the advertisement flags.
* @param [in] The flags to be set in the advertisement.
*
* * ESP_BLE_ADV_FLAG_LIMIT_DISC
* * ESP_BLE_ADV_FLAG_GEN_DISC
* * ESP_BLE_ADV_FLAG_BREDR_NOT_SPT
* * ESP_BLE_ADV_FLAG_DMT_CONTROLLER_SPT
* * ESP_BLE_ADV_FLAG_DMT_HOST_SPT
* * ESP_BLE_ADV_FLAG_NON_LIMIT_DISC
*/
void BLEAdvertisementData::setFlags(uint8_t flag) {
char cdata[3];
cdata[0] = 2;
cdata[1] = ESP_BLE_AD_TYPE_FLAG; // 0x01
cdata[2] = flag;
addData(String(cdata, 3));
} // setFlag
/**
* @brief Set manufacturer specific data.
* @param [in] data Manufacturer data.
*/
void BLEAdvertisementData::setManufacturerData(String data) {
log_d("BLEAdvertisementData", ">> setManufacturerData");
char cdata[2];
cdata[0] = data.length() + 1;
cdata[1] = ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE; // 0xff
addData(String(cdata, 2) + data);
log_d("BLEAdvertisementData", "<< setManufacturerData");
} // setManufacturerData
/**
* @brief Set the name.
* @param [in] The complete name of the device.
*/
void BLEAdvertisementData::setName(String name) {
log_d("BLEAdvertisementData", ">> setName: %s", name.c_str());
char cdata[2];
cdata[0] = name.length() + 1;
cdata[1] = ESP_BLE_AD_TYPE_NAME_CMPL; // 0x09
addData(String(cdata, 2) + name);
log_d("BLEAdvertisementData", "<< setName");
} // setName
/**
* @brief Set the partial services.
* @param [in] uuid The single service to advertise.
*/
void BLEAdvertisementData::setPartialServices(BLEUUID uuid) {
char cdata[2];
switch (uuid.bitSize()) {
case 16:
{
// [Len] [0x02] [LL] [HH]
cdata[0] = 3;
cdata[1] = ESP_BLE_AD_TYPE_16SRV_PART; // 0x02
#if defined(CONFIG_BLUEDROID_ENABLED)
addData(String(cdata, 2) + String((char *)&uuid.getNative()->uuid.uuid16, 2));
#endif
#if defined(CONFIG_NIMBLE_ENABLED)
addData(String(cdata, 2) + String((char *)&uuid.getNative()->u16.value, 2));
#endif
break;
}
case 32:
{
// [Len] [0x04] [LL] [LL] [HH] [HH]
cdata[0] = 5;
cdata[1] = ESP_BLE_AD_TYPE_32SRV_PART; // 0x04
#if defined(CONFIG_BLUEDROID_ENABLED)
addData(String(cdata, 2) + String((char *)&uuid.getNative()->uuid.uuid32, 4));
#endif
#if defined(CONFIG_NIMBLE_ENABLED)
addData(String(cdata, 2) + String((char *)&uuid.getNative()->u32.value, 4));
#endif
break;
}
case 128:
{
// [Len] [0x06] [0] [1] ... [15]
cdata[0] = 17;
cdata[1] = ESP_BLE_AD_TYPE_128SRV_PART; // 0x06
#if defined(CONFIG_BLUEDROID_ENABLED)
addData(String(cdata, 2) + String((char *)&uuid.getNative()->uuid.uuid128, 16));
#endif
#if defined(CONFIG_NIMBLE_ENABLED)
addData(String(cdata, 2) + String((char *)&uuid.getNative()->u128.value, 16));
#endif
break;
}
default: return;
}
} // setPartialServices
/**
* @brief Set the service data (UUID + data)
* @param [in] uuid The UUID to set with the service data. Size of UUID will be used.
* @param [in] data The data to be associated with the service data advert.
*/
void BLEAdvertisementData::setServiceData(BLEUUID uuid, String data) {
char cdata[2];
switch (uuid.bitSize()) {
case 16:
{
// [Len] [0x16] [UUID16] data
cdata[0] = data.length() + 3;
cdata[1] = ESP_BLE_AD_TYPE_SERVICE_DATA; // 0x16
#if defined(CONFIG_BLUEDROID_ENABLED)
addData(String(cdata, 2) + String((char *)&uuid.getNative()->uuid.uuid16, 2) + data);
#endif
#if defined(CONFIG_NIMBLE_ENABLED)
addData(String(cdata, 2) + String((char *)&uuid.getNative()->u16.value, 2) + data);
#endif
break;
}
case 32:
{
// [Len] [0x20] [UUID32] data
cdata[0] = data.length() + 5;
cdata[1] = ESP_BLE_AD_TYPE_32SERVICE_DATA; // 0x20
#if defined(CONFIG_BLUEDROID_ENABLED)
addData(String(cdata, 2) + String((char *)&uuid.getNative()->uuid.uuid32, 4) + data);
#endif
#if defined(CONFIG_NIMBLE_ENABLED)
addData(String(cdata, 2) + String((char *)&uuid.getNative()->u32.value, 4) + data);
#endif
break;
}
case 128:
{
// [Len] [0x21] [UUID128] data
cdata[0] = data.length() + 17;
cdata[1] = ESP_BLE_AD_TYPE_128SERVICE_DATA; // 0x21
#if defined(CONFIG_BLUEDROID_ENABLED)
addData(String(cdata, 2) + String((char *)&uuid.getNative()->uuid.uuid128, 16) + data);
#endif
#if defined(CONFIG_NIMBLE_ENABLED)
addData(String(cdata, 2) + String((char *)&uuid.getNative()->u128.value, 16) + data);
#endif
break;
}
default: return;
}
} // setServiceData
/**
* @brief Set the short name.
* @param [in] The short name of the device.
*/
void BLEAdvertisementData::setShortName(String name) {
log_d("BLEAdvertisementData", ">> setShortName: %s", name.c_str());
char cdata[2];
cdata[0] = name.length() + 1;
cdata[1] = ESP_BLE_AD_TYPE_NAME_SHORT; // 0x08
addData(String(cdata, 2) + name);
log_d("BLEAdvertisementData", "<< setShortName");
} // setShortName
/**
* @brief Adds Tx power level to the advertisement data.
*/
void BLEAdvertisementData::addTxPower() {
char cdata[3];
cdata[0] = 2; // length
cdata[1] = ESP_BLE_AD_TYPE_TX_PWR;
cdata[2] = BLEDevice::getPower();
addData(cdata, 3);
} // addTxPower
/**
* @brief Set the preferred connection interval parameters.
* @param [in] min The minimum interval desired.
* @param [in] max The maximum interval desired.
*/
void BLEAdvertisementData::setPreferredParams(uint16_t min, uint16_t max) {
char cdata[6];
cdata[0] = 5; // length
cdata[1] = ESP_BLE_AD_TYPE_INT_RANGE;
cdata[2] = min;
cdata[3] = min >> 8;
cdata[4] = max;
cdata[5] = max >> 8;
addData(cdata, 6);
} // setPreferredParams
/**
* @brief Retrieve the payload that is to be advertised.
* @return The payload that is to be advertised.
*/
String BLEAdvertisementData::getPayload() {
return m_payload;
} // getPayload
/***************************************************************************
* Bluedroid functions *
***************************************************************************/
#if defined(CONFIG_BLUEDROID_ENABLED)
void BLEAdvertising::reset() {
if (BLEDevice::getInitialized()) {
stop();
}
memset(&m_scanRespData, 0, sizeof(esp_ble_adv_data_t));
memset(&m_advData, 0, sizeof(esp_ble_adv_data_t));
memset(&m_advParams, 0, sizeof(esp_ble_adv_params_t));
m_advData.set_scan_rsp = false;
m_advData.include_name = true;
m_advData.include_txpower = true;
m_advData.min_interval = 0x20;
m_advData.max_interval = 0x40;
m_advData.appearance = 0x00;
m_advData.manufacturer_len = 0;
m_advData.p_manufacturer_data = nullptr;
m_advData.service_data_len = 0;
m_advData.p_service_data = nullptr;
m_advData.service_uuid_len = 0;
m_advData.p_service_uuid = nullptr;
m_advData.flag = (ESP_BLE_ADV_FLAG_GEN_DISC | ESP_BLE_ADV_FLAG_BREDR_NOT_SPT);
m_advParams.adv_int_min = 0x20;
m_advParams.adv_int_max = 0x40;
m_advParams.adv_type = ADV_TYPE_IND;
m_advParams.own_addr_type = BLE_ADDR_TYPE_PUBLIC;
m_advParams.channel_map = ADV_CHNL_ALL;
m_advParams.adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY;
m_advParams.peer_addr_type = BLE_ADDR_TYPE_PUBLIC;
m_customAdvData = false; // No custom advertising data
m_customScanResponseData = false; // No custom scan response data
m_advDataSet = false; // Force advertising data reconfiguration
m_advConfiguring = false; // Not currently configuring
m_nameInScanResp = false; // Name placement decided fresh on each start()
} // BLEAdvertising
void BLEAdvertising::freeServiceUUIDs() {
free(m_advData.p_service_uuid);
m_advData.p_service_uuid = nullptr;
m_advData.service_uuid_len = 0;
}
/**
* @brief Build raw scan response data bytes containing TX power and, when the
* device name overflowed the advertising packet, the device name.
*
* TX power is encoded first (always 3 bytes). The device name is appended only
* when @ref m_nameInScanResp is true (i.e. the name did not fit in the
* advertising packet). This mirrors NimBLE's behavior: the name stays in the
* advertising packet when there is room for it there, and is moved to the scan
* response only when the advertising payload is already full.
*
* @param [out] buf Destination buffer; at most ESP_BLE_ADV_DATA_LEN_MAX bytes
* will be written.
* @param [in] bufLen Size of buf; clamped to ESP_BLE_ADV_DATA_LEN_MAX.
* @return Number of bytes written.
*/
uint16_t BLEAdvertising::buildRawScanRespData(uint8_t *buf, uint16_t bufLen) {
uint8_t *p = buf;
uint16_t remaining = (bufLen < ESP_BLE_ADV_DATA_LEN_MAX) ? bufLen : ESP_BLE_ADV_DATA_LEN_MAX;
// --- TX power level ---
if (remaining >= 3) {
*p++ = 2;
*p++ = ESP_BLE_AD_TYPE_TX_PWR;
*p++ = (uint8_t)BLEDevice::getPower();
remaining -= 3;
}
// --- Device name (only when it overflowed the advertising packet) ---
// Mirrors NimBLE: name stays in the adv packet when it fits there; only
// moved here when the adv payload was already full.
if (m_nameInScanResp) {
String deviceName = BLEDevice::getDeviceName();
uint16_t nameLen = deviceName.length();
if (nameLen > 0 && remaining >= 3) {
uint16_t maxChars = remaining - 2;
bool complete = (nameLen <= maxChars);
uint16_t actualLen = complete ? nameLen : maxChars;
*p++ = actualLen + 1;
*p++ = complete ? ESP_BLE_AD_TYPE_NAME_CMPL : ESP_BLE_AD_TYPE_NAME_SHORT;
memcpy(p, deviceName.c_str(), actualLen);
p += actualLen;
remaining -= 2 + actualLen;
}
}
return (uint16_t)(p - buf);
}
bool BLEAdvertising::configureScanResponseData() {
// Build a compact raw scan response carrying TX power and, when the device
// name overflowed the advertising packet (m_nameInScanResp == true), the
// device name. Service UUIDs are never duplicated here — they are already
// encoded in the advertising packet.
// This mirrors NimBLE's behavior: the name only moves to the scan response
// when the advertising payload was too full to accommodate it.
uint8_t rawBuf[ESP_BLE_ADV_DATA_LEN_MAX];
uint16_t rawLen = buildRawScanRespData(rawBuf, sizeof(rawBuf));
esp_err_t errRc = ::esp_ble_gap_config_scan_rsp_data_raw(rawBuf, rawLen);
if (errRc != ESP_OK) {
log_e("esp_ble_gap_config_scan_rsp_data_raw: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
return false;
}
return true;
}
/**
* @brief Build raw advertising data bytes with fields encoded in their native sizes.
*
* Used for all advertising (both with and without scan response). Fields are
* written in priority order: flags, service UUIDs (16/32/128-bit in native
* sizes), appearance, manufacturer data, service data, and optionally the
* device name. TX power and connection interval are intentionally omitted from
* the advertising packet to maximize space; TX power is placed in the scan
* response when scan response is enabled. If the full name does not fit, it is
* truncated and the AD type is set to Shortened Local Name (0x08).
*
* Encoding UUIDs in their native sizes (rather than expanding all to 128-bit as
* the Bluedroid structured API does) maximizes the available advertising payload.
*
* @param [out] buf Destination buffer; at most ESP_BLE_ADV_DATA_LEN_MAX
* bytes will be written.
* @param [in] bufLen Size of buf; clamped to ESP_BLE_ADV_DATA_LEN_MAX.
* @param [in] includeName Whether to append the device name. Pass false when
* the name will be carried in the scan response.
* @return Number of bytes written.
*/
uint16_t BLEAdvertising::buildRawAdvData(uint8_t *buf, uint16_t bufLen, bool includeName) {
uint8_t *p = buf;
uint16_t remaining = (bufLen < ESP_BLE_ADV_DATA_LEN_MAX) ? bufLen : ESP_BLE_ADV_DATA_LEN_MAX;
// --- Flags ---
if (m_advData.flag != 0 && remaining >= 3) {
*p++ = 2;
*p++ = ESP_BLE_AD_TYPE_FLAG;
*p++ = m_advData.flag;
remaining -= 3;
}
// --- Service UUIDs (grouped by size) ---
// 16-bit
{
uint8_t *hdr = nullptr;
bool hasMore16 = false;
for (auto &uuid : m_serviceUUIDs) {
if (uuid.getNative()->len == ESP_UUID_LEN_16) {
if (remaining >= (hdr ? 2u : 4u)) {
if (!hdr) {
hdr = p;
*p++ = 1;
*p++ = ESP_BLE_AD_TYPE_16SRV_CMPL;
remaining -= 2;
}
uint16_t val = uuid.getNative()->uuid.uuid16;
*p++ = val & 0xFF;
*p++ = (val >> 8) & 0xFF;
remaining -= 2;
*hdr += 2;
} else {
hasMore16 = true;
}
}
}
if (hdr != nullptr && hasMore16) {
*(hdr + 1) = ESP_BLE_AD_TYPE_16SRV_PART;
}
}
// 32-bit
{
uint16_t num32 = 0;
for (auto &uuid : m_serviceUUIDs) {
if (uuid.getNative()->len == ESP_UUID_LEN_32) {
++num32;
}
}
bool allFit32 = (num32 == 0) || (remaining >= 2u + 4u * num32);
uint8_t *hdr = nullptr;
for (auto &uuid : m_serviceUUIDs) {
if (uuid.getNative()->len == ESP_UUID_LEN_32 && remaining >= (hdr ? 4u : 6u)) {
if (!hdr) {
hdr = p;
*p++ = 1;
*p++ = allFit32 ? ESP_BLE_AD_TYPE_32SRV_CMPL : ESP_BLE_AD_TYPE_32SRV_PART;
remaining -= 2;
}
uint32_t val = uuid.getNative()->uuid.uuid32;
*p++ = val & 0xFF;
*p++ = (val >> 8) & 0xFF;
*p++ = (val >> 16) & 0xFF;
*p++ = (val >> 24) & 0xFF;
remaining -= 4;
*hdr += 4;
}
}
}
// 128-bit (at most one in a legacy advertising PDU)
{
size_t num128 = 0;
for (auto &uuid : m_serviceUUIDs) {
if (uuid.getNative()->len == ESP_UUID_LEN_128) {
++num128;
}
}
for (auto &uuid : m_serviceUUIDs) {
if (uuid.getNative()->len == ESP_UUID_LEN_128 && remaining >= 18) {
*p++ = 17;
*p++ = (num128 == 1) ? ESP_BLE_AD_TYPE_128SRV_CMPL : ESP_BLE_AD_TYPE_128SRV_PART;
memcpy(p, uuid.getNative()->uuid.uuid128, 16);
p += 16;
remaining -= 18;
break;
}
}
}
// --- Appearance ---
if (m_advData.appearance != 0 && remaining >= 4) {
*p++ = 3;
*p++ = ESP_BLE_AD_TYPE_APPEARANCE;
*p++ = m_advData.appearance & 0xFF;
*p++ = (m_advData.appearance >> 8) & 0xFF;
remaining -= 4;
}
// --- Manufacturer data ---
if (m_advData.manufacturer_len > 0 && m_advData.p_manufacturer_data && remaining >= (uint16_t)(2 + m_advData.manufacturer_len)) {
*p++ = m_advData.manufacturer_len + 1;
*p++ = ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE;
memcpy(p, m_advData.p_manufacturer_data, m_advData.manufacturer_len);
p += m_advData.manufacturer_len;
remaining -= 2 + m_advData.manufacturer_len;
}
// --- Service data ---
if (m_advData.service_data_len > 0 && m_advData.p_service_data && remaining >= (uint16_t)(2 + m_advData.service_data_len)) {
*p++ = m_advData.service_data_len + 1;
*p++ = ESP_BLE_AD_TYPE_SERVICE_DATA;
memcpy(p, m_advData.p_service_data, m_advData.service_data_len);
p += m_advData.service_data_len;
remaining -= 2 + m_advData.service_data_len;
}
// --- Device name (truncated to fit, omitted when name goes in the scan response) ---
if (includeName) {
String deviceName = BLEDevice::getDeviceName();
uint16_t nameLen = deviceName.length();
if (nameLen > 0 && remaining >= 3) {
uint16_t maxChars = remaining - 2;
bool complete = (nameLen <= maxChars);
uint16_t actualLen = complete ? nameLen : maxChars;
*p++ = actualLen + 1;
*p++ = complete ? ESP_BLE_AD_TYPE_NAME_CMPL : ESP_BLE_AD_TYPE_NAME_SHORT;
memcpy(p, deviceName.c_str(), actualLen);
p += actualLen;
remaining -= 2 + actualLen;
}
}
return (uint16_t)(p - buf);
}
void BLEAdvertising::setAdvertisementChannelMap(esp_ble_adv_channel_t channel_map) {
m_advParams.channel_map = channel_map;
} // setAdvertisementChannelMap
/**
* @brief Start advertising.
* Start advertising.
* @return N/A.
*/
bool BLEAdvertising::start() {
log_v(">> start: customAdvData: %d, customScanResponseData: %d, advDataSet: %d", m_customAdvData, m_customScanResponseData, m_advDataSet);
// If async configuration is already in progress, don't re-enter.
// The GAP event handler will start advertising when the config completes.
if (m_advConfiguring) {
log_w("Advertising configuration already in progress");
return true;
}
// If advertising data needs to be (re)configured, kick off the async configuration.
// Bluedroid's esp_ble_gap_config_adv_data() is asynchronous and fires a GAP completion
// event when done. We must NOT block here with semaphores because start() can be called
// from BT callbacks (e.g., the disconnect handler), and both GATT and GAP callbacks are
// dispatched on the same BTC task - blocking would deadlock.
// Instead, we use the same non-blocking approach as NimBLE: kick off the config and let
// the GAP event handler (handleGAPEvent) chain the remaining steps.
if (!m_advDataSet) {
freeServiceUUIDs();
if (!m_customAdvData) {
// Always use the raw advertising API to encode service UUIDs in their
// native compact sizes (16/32/128-bit).
//
// Match NimBLE behavior for name placement: try to fit the device name
// in the advertising packet first; only move it to the scan response when
// the advertising payload is already full (consistent with NimBLE's
// name-overflow check at lines 1609-1633 of the NimBLE start() path).
uint8_t rawBuf[ESP_BLE_ADV_DATA_LEN_MAX];
// First pass: build the adv packet without the name to measure remaining space.
uint16_t baseLen = buildRawAdvData(rawBuf, sizeof(rawBuf), false);
String deviceName = BLEDevice::getDeviceName();
// +2 accounts for the 2-byte AD field header (length byte + type byte).
uint16_t nameBytes = (deviceName.length() > 0) ? (uint16_t)(deviceName.length() + 2) : 0;
bool nameFitsInAdv = (nameBytes == 0) || (nameBytes <= (ESP_BLE_ADV_DATA_LEN_MAX - baseLen));
uint16_t rawLen;
if (nameFitsInAdv || !m_scanResp) {
// Name fits in the adv packet, or there is no scan response fallback.
// buildRawAdvData will truncate the name if it does not fully fit and
// scan response is disabled (matching NimBLE's truncation path).
rawLen = buildRawAdvData(rawBuf, sizeof(rawBuf), true);
m_nameInScanResp = false;
} else {
// Name overflows the adv packet and scan response is available:
// keep the adv packet without the name, let configureScanResponseData()
// include it in the scan response (matching NimBLE's overflow path).
rawLen = baseLen;
m_nameInScanResp = true;
}
esp_err_t errRc = ::esp_ble_gap_config_adv_data_raw(rawBuf, rawLen);
if (errRc != ESP_OK) {
log_e("esp_ble_gap_config_adv_data_raw: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
return false;
}
m_advConfiguring = true;
return true;
}
if (!m_customScanResponseData && m_scanResp) {
// Custom adv data but auto scan response - configure scan response asynchronously.
// Since the adv data is user-supplied we do not know whether it contains
// the name; always include the name in the scan response to be safe.
m_nameInScanResp = true;
// The GAP event handler will start advertising when config completes.
if (!configureScanResponseData()) {
freeServiceUUIDs();
return false;
}
m_advConfiguring = true;
log_d("Scan response data configuration started (async)");
return true;
}
// Both adv data and scan response are custom (or no scan response needed).
// No async operations, mark as configured and proceed to start.
m_advDataSet = true;
freeServiceUUIDs();
}
// Advertising data is already configured, just start advertising.
esp_err_t errRc = ::esp_ble_gap_start_advertising(&m_advParams);
if (errRc != ESP_OK) {
log_e("<< esp_ble_gap_start_advertising: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
} else {