forked from project-chip/connectedhomeip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBLEManagerImpl.cpp
1917 lines (1631 loc) · 63.8 KB
/
BLEManagerImpl.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) 2020-2021 Project CHIP Authors
* All rights reserved.
*
* 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.
*/
/**
* @file
* Provides an implementation of the BLEManager singleton object
* for the ESP32 (NimBLE) platform.
*/
/* this file behaves like a config.h, comes first */
#include <platform/internal/CHIPDeviceLayerInternal.h>
#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE
#include "sdkconfig.h"
#if CONFIG_BT_NIMBLE_ENABLED
#if CONFIG_ENABLE_ESP32_BLE_CONTROLLER
#include <ble/BleLayer.h>
#endif
#include <ble/CHIPBleServiceData.h>
#include <lib/support/CodeUtils.h>
#include <lib/support/logging/CHIPLogging.h>
#include <platform/CommissionableDataProvider.h>
#include <platform/DeviceInstanceInfoProvider.h>
#if CONFIG_ENABLE_ESP32_BLE_CONTROLLER
#include <platform/ESP32/BLEManagerImpl.h>
#endif
#include <platform/internal/BLEManager.h>
#include <setup_payload/AdditionalDataPayloadGenerator.h>
#include <system/SystemTimer.h>
#include "esp_bt.h"
#include "esp_log.h"
#if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0)
#include "esp_nimble_hci.h"
#endif
#if CONFIG_ENABLE_ESP32_BLE_CONTROLLER
#include "blecent.h"
#endif
#include "host/ble_hs.h"
#include "host/ble_hs_pvcy.h"
#include "host/ble_uuid.h"
#include "host/util/util.h"
#include "nimble/nimble_port.h"
#include "nimble/nimble_port_freertos.h"
#include "services/gap/ble_svc_gap.h"
#include "services/gatt/ble_svc_gatt.h"
#define MAX_ADV_DATA_LEN 31
#define CHIP_ADV_DATA_TYPE_FLAGS 0x01
#define CHIP_ADV_DATA_FLAGS 0x06
#define CHIP_ADV_DATA_TYPE_SERVICE_DATA 0x16
using namespace ::chip;
using namespace ::chip::Ble;
namespace chip {
namespace DeviceLayer {
namespace Internal {
namespace {
#ifdef CONFIG_ENABLE_ESP32_BLE_CONTROLLER
static constexpr uint16_t kNewConnectionScanTimeout = 60;
static constexpr uint16_t kConnectTimeout = 20;
#endif
struct ESP32ChipServiceData
{
uint8_t ServiceUUID[2];
ChipBLEDeviceIdentificationInfo DeviceIdInfo;
};
const ble_uuid16_t ShortUUID_CHIPoBLEService = { BLE_UUID_TYPE_16, 0xFFF6 };
#if CONFIG_ENABLE_ESP32_BLE_CONTROLLER
const ble_uuid16_t ShortUUID_CHIPoBLE_CharTx_Desc = { BLE_UUID_TYPE_16, 0x2902 };
#endif
const ble_uuid128_t UUID128_CHIPoBLEChar_RX = {
BLE_UUID_TYPE_128, { 0x11, 0x9D, 0x9F, 0x42, 0x9C, 0x4F, 0x9F, 0x95, 0x59, 0x45, 0x3D, 0x26, 0xF5, 0x2E, 0xEE, 0x18 }
};
const ChipBleUUID chipUUID_CHIPoBLEChar_RX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F,
0x9D, 0x11 } };
const ChipBleUUID chipUUID_CHIPoBLEChar_TX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F,
0x9D, 0x12 } };
const ble_uuid128_t UUID_CHIPoBLEChar_TX = {
{ BLE_UUID_TYPE_128 }, { 0x12, 0x9D, 0x9F, 0x42, 0x9C, 0x4F, 0x9F, 0x95, 0x59, 0x45, 0x3D, 0x26, 0xF5, 0x2E, 0xEE, 0x18 }
};
#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING
const ble_uuid128_t UUID_CHIPoBLEChar_C3 = {
{ BLE_UUID_TYPE_128 }, { 0x04, 0x8F, 0x21, 0x83, 0x8A, 0x74, 0x7D, 0xB8, 0xF2, 0x45, 0x72, 0x87, 0x38, 0x02, 0x63, 0x64 }
};
#endif
SemaphoreHandle_t semaphoreHandle = NULL;
// LE Random Device Address
// (see Bluetooth® Core Specification 4.2 Vol 6, Part B, Section 1.3.2.1 "Static device address")
uint8_t own_addr_type = BLE_OWN_ADDR_RANDOM;
} // unnamed namespace
#if CONFIG_ENABLE_ESP32_BLE_CONTROLLER
ChipDeviceScanner & mDeviceScanner = Internal::ChipDeviceScanner::GetInstance();
#endif
BLEManagerImpl BLEManagerImpl::sInstance;
const struct ble_gatt_svc_def BLEManagerImpl::CHIPoBLEGATTAttrs[] = {
{ .type = BLE_GATT_SVC_TYPE_PRIMARY,
.uuid = (ble_uuid_t *) (&ShortUUID_CHIPoBLEService),
.characteristics =
(struct ble_gatt_chr_def[]){
{
.uuid = (ble_uuid_t *) (&UUID128_CHIPoBLEChar_RX),
.access_cb = gatt_svr_chr_access,
.flags = BLE_GATT_CHR_F_WRITE,
.val_handle = &sInstance.mRXCharAttrHandle,
},
{
.uuid = (ble_uuid_t *) (&UUID_CHIPoBLEChar_TX),
.access_cb = gatt_svr_chr_access,
.flags = BLE_GATT_CHR_F_READ | BLE_GATT_CHR_F_INDICATE,
.val_handle = &sInstance.mTXCharCCCDAttrHandle,
},
#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING
{
.uuid = (ble_uuid_t *) (&UUID_CHIPoBLEChar_C3),
.access_cb = gatt_svr_chr_access_additional_data,
.flags = BLE_GATT_CHR_F_READ,
.val_handle = &sInstance.mC3CharAttrHandle,
},
#endif
{
0, /* No more characteristics in this service */
},
} },
{
0, /* No more services. */
},
};
#if CONFIG_ENABLE_ESP32_BLE_CONTROLLER
void BLEManagerImpl::HandleConnectFailed(CHIP_ERROR error)
{
if (sInstance.mIsCentral)
{
ChipDeviceEvent event;
event.Type = DeviceEventType::kPlatformESP32BLECentralConnectFailed;
event.Platform.BLECentralConnectFailed.mError = error;
PlatformMgr().PostEventOrDie(&event);
}
}
void BLEManagerImpl::CancelConnect(void)
{
int rc = ble_gap_conn_cancel();
VerifyOrReturn(rc == 0, ChipLogError(Ble, "Failed to cancel connection rc=%d", rc));
}
void BLEManagerImpl::HandleConnectTimeout(chip::System::Layer *, void * context)
{
CancelConnect();
BLEManagerImpl::HandleConnectFailed(CHIP_ERROR_TIMEOUT);
}
void BLEManagerImpl::ConnectDevice(const ble_addr_t & addr, uint16_t timeout)
{
int rc;
uint8_t ownAddrType;
rc = ble_hs_id_infer_auto(0, &ownAddrType);
if (rc != 0)
{
ChipLogError(Ble, "Failed to infer own address type rc=%d", rc);
return;
}
rc = ble_gap_connect(ownAddrType, &addr, (timeout * 1000), NULL, ble_svr_gap_event, NULL);
if (rc != 0)
{
ChipLogError(Ble, "Failed to connect to rc=%d", rc);
}
}
void HandleIncomingBleConnection(BLEEndPoint * bleEP)
{
ChipLogProgress(DeviceLayer, "CHIPoBLE connection received");
}
#endif
CHIP_ERROR BLEManagerImpl::_Init()
{
CHIP_ERROR err;
// Initialize the Chip BleLayer.
#if CONFIG_ENABLE_ESP32_BLE_CONTROLLER
err = BleLayer::Init(this, this, this, &DeviceLayer::SystemLayer());
#else
err = BleLayer::Init(this, this, &DeviceLayer::SystemLayer());
#endif
SuccessOrExit(err);
mRXCharAttrHandle = 0;
#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING
mC3CharAttrHandle = 0;
#endif
mTXCharCCCDAttrHandle = 0;
#if CONFIG_ENABLE_ESP32_BLE_CONTROLLER
mFlags.ClearAll().Set(Flags::kAdvertisingEnabled, CHIP_DEVICE_CONFIG_CHIPOBLE_ENABLE_ADVERTISING_AUTOSTART && !mIsCentral);
mFlags.Set(Flags::kFastAdvertisingEnabled, !mIsCentral);
OnChipBleConnectReceived = HandleIncomingBleConnection;
#else
mFlags.ClearAll().Set(Flags::kAdvertisingEnabled, CHIP_DEVICE_CONFIG_CHIPOBLE_ENABLE_ADVERTISING_AUTOSTART);
mFlags.Set(Flags::kFastAdvertisingEnabled, true);
#endif
mNumGAPCons = 0;
memset(reinterpret_cast<void *>(mCons), 0, sizeof(mCons));
mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Enabled;
memset(mDeviceName, 0, sizeof(mDeviceName));
PlatformMgr().ScheduleWork(DriveBLEState, 0);
exit:
return err;
}
void BLEManagerImpl::_Shutdown()
{
CancelBleAdvTimeoutTimer();
BleLayer::Shutdown();
// selectively setting kGATTServiceStarted flag, in order to notify the state machine to stop the CHIPoBLE GATT service
mFlags.ClearAll().Set(Flags::kGATTServiceStarted);
mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Disabled;
#if CONFIG_ENABLE_ESP32_BLE_CONTROLLER
OnChipBleConnectReceived = nullptr;
#endif // CONFIG_ENABLE_ESP32_BLE_CONTROLLER
PlatformMgr().ScheduleWork(DriveBLEState, 0);
}
CHIP_ERROR BLEManagerImpl::_SetAdvertisingEnabled(bool val)
{
CHIP_ERROR err = CHIP_NO_ERROR;
VerifyOrExit(mServiceMode != ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE);
if (val)
{
StartBleAdvTimeoutTimer(CHIP_DEVICE_CONFIG_BLE_ADVERTISING_INTERVAL_CHANGE_TIME);
}
mFlags.Set(Flags::kFastAdvertisingEnabled, val);
mFlags.Set(Flags::kAdvertisingRefreshNeeded, 1);
mFlags.Set(Flags::kAdvertisingEnabled, val);
PlatformMgr().ScheduleWork(DriveBLEState, 0);
exit:
return err;
}
void BLEManagerImpl::BleAdvTimeoutHandler(System::Layer *, void *)
{
if (BLEMgrImpl().mFlags.Has(Flags::kFastAdvertisingEnabled))
{
ChipLogProgress(DeviceLayer, "bleAdv Timeout : Start slow advertisement");
BLEMgrImpl().mFlags.Set(Flags::kFastAdvertisingEnabled, 0);
BLEMgrImpl().mFlags.Set(Flags::kAdvertisingRefreshNeeded, 1);
#if CHIP_DEVICE_CONFIG_BLE_EXT_ADVERTISING
BLEMgrImpl().mFlags.Clear(Flags::kExtAdvertisingEnabled);
BLEMgrImpl().StartBleAdvTimeoutTimer(CHIP_DEVICE_CONFIG_BLE_EXT_ADVERTISING_INTERVAL_CHANGE_TIME_MS);
#endif
}
#if CHIP_DEVICE_CONFIG_BLE_EXT_ADVERTISING
else
{
ChipLogProgress(DeviceLayer, "bleAdv Timeout : Start extended advertisement");
BLEMgrImpl().mFlags.Set(Flags::kAdvertising);
BLEMgrImpl().mFlags.Set(Flags::kExtAdvertisingEnabled);
BLEMgr().SetAdvertisingMode(BLEAdvertisingMode::kSlowAdvertising);
BLEMgrImpl().mFlags.Set(Flags::kAdvertisingRefreshNeeded, 1);
}
#endif
PlatformMgr().ScheduleWork(DriveBLEState, 0);
}
CHIP_ERROR BLEManagerImpl::_SetAdvertisingMode(BLEAdvertisingMode mode)
{
switch (mode)
{
case BLEAdvertisingMode::kFastAdvertising:
mFlags.Set(Flags::kFastAdvertisingEnabled, true);
break;
case BLEAdvertisingMode::kSlowAdvertising:
mFlags.Set(Flags::kFastAdvertisingEnabled, false);
break;
default:
return CHIP_ERROR_INVALID_ARGUMENT;
}
mFlags.Set(Flags::kAdvertisingRefreshNeeded);
PlatformMgr().ScheduleWork(DriveBLEState, 0);
return CHIP_NO_ERROR;
}
CHIP_ERROR BLEManagerImpl::_GetDeviceName(char * buf, size_t bufSize)
{
if (strlen(mDeviceName) >= bufSize)
{
return CHIP_ERROR_BUFFER_TOO_SMALL;
}
strcpy(buf, mDeviceName);
return CHIP_NO_ERROR;
}
CHIP_ERROR BLEManagerImpl::_SetDeviceName(const char * deviceName)
{
CHIP_ERROR err = CHIP_NO_ERROR;
VerifyOrExit(mServiceMode != ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE);
if (deviceName != NULL && deviceName[0] != 0)
{
if (strlen(deviceName) >= kMaxDeviceNameLength)
{
return CHIP_ERROR_INVALID_ARGUMENT;
}
strcpy(mDeviceName, deviceName);
mFlags.Set(Flags::kUseCustomDeviceName);
}
else
{
mDeviceName[0] = 0;
mFlags.Clear(Flags::kUseCustomDeviceName);
}
exit:
return err;
}
void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event)
{
switch (event->Type)
{
case DeviceEventType::kCHIPoBLESubscribe:
HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX);
{
ChipDeviceEvent connectionEvent;
connectionEvent.Type = DeviceEventType::kCHIPoBLEConnectionEstablished;
PlatformMgr().PostEventOrDie(&connectionEvent);
}
break;
case DeviceEventType::kCHIPoBLEUnsubscribe:
HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX);
break;
case DeviceEventType::kCHIPoBLEWriteReceived:
HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_RX,
PacketBufferHandle::Adopt(event->CHIPoBLEWriteReceived.Data));
break;
case DeviceEventType::kCHIPoBLEIndicateConfirm:
HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX);
break;
case DeviceEventType::kCHIPoBLEConnectionError:
HandleConnectionError(event->CHIPoBLEConnectionError.ConId, event->CHIPoBLEConnectionError.Reason);
break;
case DeviceEventType::kServiceProvisioningChange:
case DeviceEventType::kWiFiConnectivityChange:
// Force the advertising configuration to be refreshed to reflect new provisioning state.
ChipLogProgress(DeviceLayer, "Updating advertising data");
mFlags.Clear(Flags::kAdvertisingConfigured);
mFlags.Set(Flags::kAdvertisingRefreshNeeded);
DriveBLEState();
break;
default:
#if CONFIG_ENABLE_ESP32_BLE_CONTROLLER
HandlePlatformSpecificBLEEvent(event);
#endif
break;
}
}
#if CONFIG_ENABLE_ESP32_BLE_CONTROLLER
void BLEManagerImpl::HandlePlatformSpecificBLEEvent(const ChipDeviceEvent * apEvent)
{
CHIP_ERROR err = CHIP_NO_ERROR;
ChipLogProgress(DeviceLayer, "HandlePlatformSpecificBLEEvent %d", apEvent->Type);
switch (apEvent->Type)
{
case DeviceEventType::kPlatformESP32BLECentralConnected:
if (BLEManagerImpl::mBLEScanConfig.mBleScanState == BleScanState::kConnecting)
{
BleConnectionDelegate::OnConnectionComplete(mBLEScanConfig.mAppState,
apEvent->Platform.BLECentralConnected.mConnection);
CleanScanConfig();
}
break;
case DeviceEventType::kPlatformESP32BLECentralConnectFailed:
if (BLEManagerImpl::mBLEScanConfig.mBleScanState == BleScanState::kConnecting)
{
BleConnectionDelegate::OnConnectionError(mBLEScanConfig.mAppState, apEvent->Platform.BLECentralConnectFailed.mError);
CleanScanConfig();
}
break;
case DeviceEventType::kPlatformESP32BLEWriteComplete:
HandleWriteConfirmation(apEvent->Platform.BLEWriteComplete.mConnection, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_RX);
break;
case DeviceEventType::kPlatformESP32BLESubscribeOpComplete:
if (apEvent->Platform.BLESubscribeOpComplete.mIsSubscribed)
HandleSubscribeComplete(apEvent->Platform.BLESubscribeOpComplete.mConnection, &CHIP_BLE_SVC_ID,
&chipUUID_CHIPoBLEChar_TX);
else
HandleUnsubscribeComplete(apEvent->Platform.BLESubscribeOpComplete.mConnection, &CHIP_BLE_SVC_ID,
&chipUUID_CHIPoBLEChar_TX);
break;
case DeviceEventType::kPlatformESP32BLEIndicationReceived:
HandleIndicationReceived(apEvent->Platform.BLEIndicationReceived.mConnection, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX,
PacketBufferHandle::Adopt(apEvent->Platform.BLEIndicationReceived.mData));
break;
default:
break;
}
if (err != CHIP_NO_ERROR)
{
ChipLogError(DeviceLayer, "Disabling CHIPoBLE service due to error: %s", ErrorStr(err));
mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Disabled;
}
}
static int OnUnsubscribeCharComplete(uint16_t conn_handle, const struct ble_gatt_error * error, struct ble_gatt_attr * attr,
void * arg)
{
ChipLogProgress(DeviceLayer, "Subscribe complete: conn_handle=%d, error=%d, attr_handle=%d", conn_handle, error->status,
attr->handle);
ChipDeviceEvent event;
event.Type = DeviceEventType::kPlatformESP32BLESubscribeOpComplete;
event.Platform.BLESubscribeOpComplete.mConnection = conn_handle;
event.Platform.BLESubscribeOpComplete.mIsSubscribed = false;
PlatformMgr().PostEventOrDie(&event);
return 0;
}
static int OnSubscribeCharComplete(uint16_t conn_handle, const struct ble_gatt_error * error, struct ble_gatt_attr * attr,
void * arg)
{
ChipLogProgress(DeviceLayer, "Subscribe complete: conn_handle=%d, error=%d, attr_handle=%d", conn_handle, error->status,
attr->handle);
ChipDeviceEvent event;
event.Type = DeviceEventType::kPlatformESP32BLESubscribeOpComplete;
event.Platform.BLESubscribeOpComplete.mConnection = conn_handle;
event.Platform.BLESubscribeOpComplete.mIsSubscribed = true;
PlatformMgr().PostEventOrDie(&event);
return 0;
}
#endif
bool BLEManagerImpl::SubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId)
{
#if CONFIG_ENABLE_ESP32_BLE_CONTROLLER
const struct peer_dsc * dsc;
uint8_t value[2];
int rc;
struct peer * peer = peer_find(conId);
if (peer == nullptr)
{
return false;
}
dsc = peer_dsc_find_uuid(peer, (ble_uuid_t *) (&ShortUUID_CHIPoBLEService), (ble_uuid_t *) (&UUID_CHIPoBLEChar_TX),
(ble_uuid_t *) (&ShortUUID_CHIPoBLE_CharTx_Desc));
if (dsc == nullptr)
{
ChipLogError(Ble, "Peer does not have CCCD");
ble_gap_terminate(peer->conn_handle, BLE_ERR_REM_USER_CONN_TERM);
return false;
}
value[0] = 0x02;
value[1] = 0x00;
rc = ble_gattc_write_flat(peer->conn_handle, dsc->dsc.handle, value, sizeof(value), OnSubscribeCharComplete, NULL);
if (rc != 0)
{
ChipLogError(Ble, "ble_gattc_write_flat failed: %d", rc);
ble_gap_terminate(peer->conn_handle, BLE_ERR_REM_USER_CONN_TERM);
return false;
}
return true;
#else
return false;
#endif
}
bool BLEManagerImpl::UnsubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId)
{
#if CONFIG_ENABLE_ESP32_BLE_CONTROLLER
const struct peer_dsc * dsc;
uint8_t value[2];
int rc;
struct peer * peer = peer_find(conId);
if (peer == nullptr)
{
return false;
}
dsc = peer_dsc_find_uuid(peer, (ble_uuid_t *) (&ShortUUID_CHIPoBLEService), (ble_uuid_t *) (&UUID_CHIPoBLEChar_TX),
(ble_uuid_t *) (&ShortUUID_CHIPoBLE_CharTx_Desc));
if (dsc == nullptr)
{
ChipLogError(Ble, "Peer does not have CCCD");
ble_gap_terminate(peer->conn_handle, BLE_ERR_REM_USER_CONN_TERM);
return false;
}
value[0] = 0x00;
value[1] = 0x00;
rc = ble_gattc_write_flat(peer->conn_handle, dsc->dsc.handle, value, sizeof(value), OnUnsubscribeCharComplete, NULL);
if (rc != 0)
{
ChipLogError(Ble, "ble_gattc_write_flat failed: %d", rc);
ble_gap_terminate(peer->conn_handle, BLE_ERR_REM_USER_CONN_TERM);
return false;
}
return true;
#else
return false;
#endif
}
bool BLEManagerImpl::CloseConnection(BLE_CONNECTION_OBJECT conId)
{
CHIP_ERROR err;
ChipLogProgress(DeviceLayer, "Closing BLE GATT connection (con %u)", conId);
// Signal the ESP BLE layer to close the conneecction.
err = MapBLEError(ble_gap_terminate(conId, BLE_ERR_REM_USER_CONN_TERM));
if (err != CHIP_NO_ERROR)
{
ChipLogError(DeviceLayer, "ble_gap_terminate() failed: %s", ErrorStr(err));
}
#if !CONFIG_ENABLE_ESP32_BLE_CONTROLLER
// Force a refresh of the advertising state.
mFlags.Set(Flags::kAdvertisingRefreshNeeded);
mFlags.Clear(Flags::kAdvertisingConfigured);
PlatformMgr().ScheduleWork(DriveBLEState, 0);
#endif
return (err == CHIP_NO_ERROR);
}
uint16_t BLEManagerImpl::GetMTU(BLE_CONNECTION_OBJECT conId) const
{
return ble_att_mtu(conId);
}
bool BLEManagerImpl::SendIndication(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId,
chip::System::PacketBufferHandle data)
{
CHIP_ERROR err = CHIP_NO_ERROR;
struct os_mbuf * om;
VerifyOrExit(IsSubscribed(conId), err = CHIP_ERROR_INVALID_ARGUMENT);
ESP_LOGD(TAG, "Sending indication for CHIPoBLE TX characteristic (con %u, len %u)", conId, data->DataLength());
om = ble_hs_mbuf_from_flat(data->Start(), data->DataLength());
if (om == NULL)
{
ChipLogError(DeviceLayer, "ble_hs_mbuf_from_flat failed:");
err = CHIP_ERROR_NO_MEMORY;
ExitNow();
}
err = MapBLEError(ble_gattc_indicate_custom(conId, mTXCharCCCDAttrHandle, om));
if (err != CHIP_NO_ERROR)
{
ChipLogError(DeviceLayer, "ble_gattc_indicate_custom() failed: %s", ErrorStr(err));
ExitNow();
}
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(DeviceLayer, "BLEManagerImpl::SendIndication() failed: %s", ErrorStr(err));
return false;
}
return true;
}
#if CONFIG_ENABLE_ESP32_BLE_CONTROLLER
static int OnWriteComplete(uint16_t conn_handle, const struct ble_gatt_error * error, struct ble_gatt_attr * attr, void * arg)
{
ChipLogDetail(Ble, "Write complete; status:%d conn_handle:%d attr_handle:%d", error->status, conn_handle, attr->handle);
ChipDeviceEvent event;
event.Type = DeviceEventType::kPlatformESP32BLEWriteComplete;
event.Platform.BLEWriteComplete.mConnection = conn_handle;
CHIP_ERROR err = PlatformMgr().PostEvent(&event);
if (err != CHIP_NO_ERROR)
{
return 1;
}
return 0;
}
#endif
bool BLEManagerImpl::SendWriteRequest(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId,
chip::System::PacketBufferHandle pBuf)
{
#if CONFIG_ENABLE_ESP32_BLE_CONTROLLER
const struct peer_chr * chr;
int rc;
const struct peer * peer = peer_find(conId);
chr = peer_chr_find_uuid(peer, (ble_uuid_t *) (&ShortUUID_CHIPoBLEService), (ble_uuid_t *) (&UUID128_CHIPoBLEChar_RX));
if (chr == nullptr)
{
ChipLogError(Ble, "Peer does not have RX characteristic");
ble_gap_terminate(peer->conn_handle, BLE_ERR_REM_USER_CONN_TERM);
return false;
}
rc = ble_gattc_write_flat(conId, chr->chr.val_handle, pBuf->Start(), pBuf->DataLength(), OnWriteComplete, this);
if (rc != 0)
{
ChipLogError(Ble, "ble_gattc_write_flat failed: %d", rc);
ble_gap_terminate(peer->conn_handle, BLE_ERR_REM_USER_CONN_TERM);
return false;
}
return true;
#else
return false;
#endif
}
bool BLEManagerImpl::SendReadRequest(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId,
chip::System::PacketBufferHandle pBuf)
{
ChipLogError(DeviceLayer, "BLEManagerImpl::SendReadRequest() not supported");
return false;
}
bool BLEManagerImpl::SendReadResponse(BLE_CONNECTION_OBJECT conId, BLE_READ_REQUEST_CONTEXT requestContext,
const ChipBleUUID * svcId, const ChipBleUUID * charId)
{
ChipLogError(DeviceLayer, "BLEManagerImpl::SendReadResponse() not supported");
return false;
}
void BLEManagerImpl::NotifyChipConnectionClosed(BLE_CONNECTION_OBJECT conId)
{
ChipLogDetail(Ble, "Received notification of closed CHIPoBLE connection (con %u)", conId);
CloseConnection(conId);
}
CHIP_ERROR BLEManagerImpl::MapBLEError(int bleErr)
{
switch (bleErr)
{
case ESP_OK:
return CHIP_NO_ERROR;
case BLE_HS_EMSGSIZE:
return CHIP_ERROR_BUFFER_TOO_SMALL;
case BLE_HS_ENOMEM:
case ESP_ERR_NO_MEM:
return CHIP_ERROR_NO_MEMORY;
case BLE_HS_ENOTCONN:
return CHIP_ERROR_NOT_CONNECTED;
case BLE_HS_ENOTSUP:
return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;
case BLE_HS_EAPP:
return CHIP_ERROR_INCORRECT_STATE;
case BLE_HS_EBADDATA:
return CHIP_ERROR_DATA_NOT_ALIGNED;
case BLE_HS_ETIMEOUT:
return CHIP_ERROR_TIMEOUT;
case BLE_HS_ENOADDR:
return CHIP_ERROR_INVALID_ADDRESS;
case ESP_ERR_INVALID_ARG:
return CHIP_ERROR_INVALID_ARGUMENT;
default:
return CHIP_ERROR(ChipError::Range::kPlatform, CHIP_DEVICE_CONFIG_ESP32_BLE_ERROR_MIN + bleErr);
}
}
void BLEManagerImpl::CancelBleAdvTimeoutTimer(void)
{
if (SystemLayer().IsTimerActive(BleAdvTimeoutHandler, nullptr))
{
SystemLayer().CancelTimer(BleAdvTimeoutHandler, nullptr);
}
}
void BLEManagerImpl::StartBleAdvTimeoutTimer(uint32_t aTimeoutInMs)
{
CancelBleAdvTimeoutTimer();
CHIP_ERROR err = SystemLayer().StartTimer(System::Clock::Milliseconds32(aTimeoutInMs), BleAdvTimeoutHandler, nullptr);
if ((err != CHIP_NO_ERROR))
{
ChipLogError(DeviceLayer, "Failed to start BledAdv timeout timer");
}
}
void BLEManagerImpl::DriveBLEState(void)
{
CHIP_ERROR err = CHIP_NO_ERROR;
// Perform any initialization actions that must occur after the Chip task is running.
if (!mFlags.Has(Flags::kAsyncInitCompleted))
{
mFlags.Set(Flags::kAsyncInitCompleted);
}
// Initializes the ESP BLE layer if needed.
if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && !mFlags.Has(Flags::kESPBLELayerInitialized))
{
err = InitESPBleLayer();
SuccessOrExit(err);
// Add delay of 500msec while NimBLE host task gets up and running
{
vTaskDelay(500 / portTICK_PERIOD_MS);
}
}
// If the application has enabled CHIPoBLE and BLE advertising...
if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled &&
mFlags.Has(Flags::kAdvertisingEnabled)
#if CHIP_DEVICE_CONFIG_CHIPOBLE_SINGLE_CONNECTION
// and no connections are active...
&& (_NumConnections() == 0)
#endif
)
{
// Start/re-start advertising if not already advertising, or if the advertising state of the
// ESP BLE layer needs to be refreshed.
if (!mFlags.Has(Flags::kAdvertising) || mFlags.Has(Flags::kAdvertisingRefreshNeeded))
{
// Configure advertising data if it hasn't been done yet. This is an asynchronous step which
// must complete before advertising can be started. When that happens, this method will
// be called again, and execution will proceed to the code below.
if (!mFlags.Has(Flags::kAdvertisingConfigured))
{
err = ConfigureAdvertisingData();
if (err != CHIP_NO_ERROR)
{
ChipLogError(DeviceLayer, "Configure Adv Data failed: %s", ErrorStr(err));
ExitNow();
}
}
// Start advertising. This is also an asynchronous step.
ESP_LOGD(TAG, "NimBLE start advertising...");
err = StartAdvertising();
if (err != CHIP_NO_ERROR)
{
ChipLogError(DeviceLayer, "Start advertising failed: %s", ErrorStr(err));
ExitNow();
}
mFlags.Clear(Flags::kAdvertisingRefreshNeeded);
// Transition to the Advertising state...
if (!mFlags.Has(Flags::kAdvertising))
{
ChipLogProgress(DeviceLayer, "CHIPoBLE advertising started");
mFlags.Set(Flags::kAdvertising);
// Post a CHIPoBLEAdvertisingChange(Started) event.
{
ChipDeviceEvent advChange;
advChange.Type = DeviceEventType::kCHIPoBLEAdvertisingChange;
advChange.CHIPoBLEAdvertisingChange.Result = kActivity_Started;
err = PlatformMgr().PostEvent(&advChange);
}
}
}
}
// Otherwise stop advertising if needed...
else
{
if (mFlags.Has(Flags::kAdvertising))
{
if (ble_gap_adv_active())
{
err = MapBLEError(ble_gap_adv_stop());
if (err != CHIP_NO_ERROR)
{
ChipLogError(DeviceLayer, "ble_gap_adv_stop() failed: %s", ErrorStr(err));
ExitNow();
}
}
// Transition to the not Advertising state...
mFlags.Clear(Flags::kAdvertising);
mFlags.Set(Flags::kFastAdvertisingEnabled, true);
ChipLogProgress(DeviceLayer, "CHIPoBLE advertising stopped");
CancelBleAdvTimeoutTimer();
// Post a CHIPoBLEAdvertisingChange(Stopped) event.
{
ChipDeviceEvent advChange;
advChange.Type = DeviceEventType::kCHIPoBLEAdvertisingChange;
advChange.CHIPoBLEAdvertisingChange.Result = kActivity_Stopped;
err = PlatformMgr().PostEvent(&advChange);
}
ExitNow();
}
}
// Stop the CHIPoBLE GATT service if needed.
if (mServiceMode != ConnectivityManager::kCHIPoBLEServiceMode_Enabled && mFlags.Has(Flags::kGATTServiceStarted))
{
DeinitESPBleLayer();
mFlags.ClearAll();
}
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(DeviceLayer, "Disabling CHIPoBLE service due to error: %s", ErrorStr(err));
mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Disabled;
}
}
void BLEManagerImpl::bleprph_on_reset(int reason)
{
ESP_LOGE(TAG, "Resetting state; reason=%d\n", reason);
}
CHIP_ERROR BLEManagerImpl::bleprph_set_random_addr(void)
{
ble_addr_t addr;
// Generates a new static random address
int rc = ble_hs_id_gen_rnd(0, &addr);
if (rc != 0)
{
ESP_LOGE(TAG, "Failed to generate random address err: %d", rc);
return CHIP_ERROR_INTERNAL;
}
// Set generated address
rc = ble_hs_id_set_rnd(addr.val);
if (rc != 0)
{
ESP_LOGE(TAG, "Failed to set random address err: %d", rc);
return CHIP_ERROR_INTERNAL;
}
// Try to configure the device with random static address
rc = ble_hs_util_ensure_addr(1);
if (rc != 0)
{
ESP_LOGE(TAG, "Failed to configure random address err: %d", rc);
return CHIP_ERROR_INTERNAL;
}
return CHIP_NO_ERROR;
}
void BLEManagerImpl::bleprph_on_sync(void)
{
ESP_LOGI(TAG, "BLE host-controller synced");
xSemaphoreGive(semaphoreHandle);
}
void BLEManagerImpl::bleprph_host_task(void * param)
{
ESP_LOGD(TAG, "BLE Host Task Started");
/* This function will return only when nimble_port_stop() is executed */
nimble_port_run();
nimble_port_freertos_deinit();
}
CHIP_ERROR BLEManagerImpl::InitESPBleLayer(void)
{
CHIP_ERROR err = CHIP_NO_ERROR;
VerifyOrExit(!mFlags.Has(Flags::kESPBLELayerInitialized), /* */);
semaphoreHandle = xSemaphoreCreateBinary();
if (semaphoreHandle == NULL)
{
err = CHIP_ERROR_NO_MEMORY;
ESP_LOGE(TAG, "Failed to create semaphore");
ExitNow();
}
for (int i = 0; i < kMaxConnections; i++)
{
mSubscribedConIds[i] = BLE_CONNECTION_UNINITIALIZED;
}
#if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0)
err = MapBLEError(esp_nimble_hci_and_controller_init());
SuccessOrExit(err);
#endif
nimble_port_init();
/* Initialize the NimBLE host configuration. */
ble_hs_cfg.reset_cb = bleprph_on_reset;
ble_hs_cfg.sync_cb = bleprph_on_sync;
ble_hs_cfg.store_status_cb = ble_store_util_status_rr;
ble_hs_cfg.sm_bonding = 1;
ble_hs_cfg.sm_our_key_dist = BLE_SM_PAIR_KEY_DIST_ENC | BLE_SM_PAIR_KEY_DIST_ID;
ble_hs_cfg.sm_their_key_dist = BLE_SM_PAIR_KEY_DIST_ENC | BLE_SM_PAIR_KEY_DIST_ID;
// Register the CHIPoBLE GATT attributes with the ESP BLE layer if needed.
if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled)
{
ble_svc_gap_init();
ble_svc_gatt_init();
err = MapBLEError(ble_gatts_count_cfg(CHIPoBLEGATTAttrs));
if (err != CHIP_NO_ERROR)
{
ChipLogError(DeviceLayer, "ble_gatts_count_cfg failed: %s", ErrorStr(err));
ExitNow();
}
err = MapBLEError(ble_gatts_add_svcs(CHIPoBLEGATTAttrs));
if (err != CHIP_NO_ERROR)
{
ChipLogError(DeviceLayer, "ble_gatts_add_svcs failed: %s", ErrorStr(err));
ExitNow();
}
}
nimble_port_freertos_init(bleprph_host_task);
xSemaphoreTake(semaphoreHandle, portMAX_DELAY);
vSemaphoreDelete(semaphoreHandle);
semaphoreHandle = NULL;
sInstance.mFlags.Set(Flags::kESPBLELayerInitialized);
sInstance.mFlags.Set(Flags::kGATTServiceStarted);
err = bleprph_set_random_addr();
exit:
return err;
}
void BLEManagerImpl::DeinitESPBleLayer()
{
VerifyOrReturn(DeinitBLE() == CHIP_NO_ERROR);
BLEManagerImpl::ClaimBLEMemory(nullptr, nullptr);
}
void BLEManagerImpl::ClaimBLEMemory(System::Layer *, void *)
{
TaskHandle_t handle = xTaskGetHandle("nimble_host");
if (handle)
{
ChipLogDetail(DeviceLayer, "Schedule ble memory reclaiming since nimble host is still running");
// Rescheduling it for later, 2 seconds is an arbitrary value, keeping it a bit more so that
// we dont have to reschedule it again