forked from project-chip/connectedhomeip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBLEManagerImpl.cpp
1904 lines (1585 loc) · 61.9 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-2022 Project CHIP Authors
* Copyright (c) 2019 Nest Labs, Inc.
*
* 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 object for cc13xx_cc26xx
* platform using the Texas Instruments SDK and the OpenThread stack.
*/
#include <string.h>
/* this file behaves like a config.h, comes first */
#include <platform/internal/CHIPDeviceLayerInternal.h>
#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE
#include <ble/Ble.h>
#include <platform/internal/BLEManager.h>
#include "FreeRTOS.h"
#include <queue.h>
#include <task.h>
/* Include DMM module */
#include "chipOBleProfile.h"
#include "hal_types.h"
#include "ti_dmm_application_policy.h"
#include <bcomdef.h>
#include <devinfoservice.h>
#include <dmm/apps/common/freertos/util.h>
#include <dmm/dmm_policy.h>
#include <dmm/dmm_priority_ble_thread.h>
#include <dmm/dmm_scheduler.h>
#include <icall.h>
#include <icall_ble_api.h>
#include <util.h>
extern "C" {
#include "ti_ble_config.h"
#include "ti_drivers_config.h"
#ifndef ICALL_FEATURE_SEPARATE_IMGINFO
#include <icall_addrs.h>
#endif /* ICALL_FEATURE_SEPARATE_IMGINFO */
}
// BLE Manager Debug Logs
extern "C" {
#ifdef BLEMGR_DBG_LOGGING
extern void cc13xx_26xxLog(const char * aFormat, ...);
#define BLEMGR_LOG(...) cc13xx_26xxLog(__VA_ARGS__);
#else
#define BLEMGR_LOG(...)
#endif
}
#ifndef USE_DEFAULT_USER_CFG
#include "ble_user_config.h"
// BLE user defined configuration. Required to be globally accesible for BLE initialization
icall_userCfg_t user0Cfg = BLE_USER_CFG;
#endif // USE_DEFAULT_USER_CFG
using namespace ::chip;
using namespace ::chip::Ble;
namespace chip {
namespace DeviceLayer {
namespace Internal {
/* Static class member initialization */
BLEManagerImpl BLEManagerImpl::sInstance;
TaskHandle_t BLEManagerImpl::sBleTaskHndl;
ICall_EntityID BLEManagerImpl::sSelfEntity;
ICall_SyncHandle BLEManagerImpl::sSyncEvent;
QueueHandle_t BLEManagerImpl::sEventHandlerMsgQueueID;
chipOBleProfileCBs_t BLEManagerImpl::CHIPoBLEProfile_CBs = {
// Provisioning GATT Characteristic value change callback
CHIPoBLEProfile_charValueChangeCB
};
// GAP Bond Manager Callbacks
gapBondCBs_t BLEManagerImpl::BLEMgr_BondMgrCBs = {
PasscodeCb, // Passcode callback
PairStateCb // Pairing/Bonding state Callback
};
// ===== Members that implement the BLEManager internal interface.
CHIP_ERROR BLEManagerImpl::_Init(void)
{
CHIP_ERROR err = CHIP_NO_ERROR;
BLEMGR_LOG("BLEMGR: BLE Initialization Start");
// Initialize the CHIP BleLayer.
err = BleLayer::Init(this, this, &DeviceLayer::SystemLayer());
if (err != CHIP_NO_ERROR)
{
return err;
}
/* Register BLE Stack assert handler */
RegisterAssertCback(AssertHandler);
mFlags.ClearAll().Set(Flags::kAdvertisingEnabled, CHIP_DEVICE_CONFIG_CHIPOBLE_ENABLE_ADVERTISING_AUTOSTART);
mFlags.Set(Flags::kFastAdvertisingEnabled, true);
mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Enabled;
err = CreateEventHandler();
return err;
}
bool BLEManagerImpl::_IsAdvertisingEnabled(void)
{
return mFlags.Has(Flags::kAdvertisingEnabled);
}
/* Post event to app processing loop to begin CHIP advertising */
CHIP_ERROR BLEManagerImpl::_SetAdvertisingEnabled(bool val)
{
mFlags.Set(Flags::kAdvertisingEnabled, val);
/* Send event to process state change request */
return DriveBLEState();
}
CHIP_ERROR BLEManagerImpl::_SetAdvertisingMode(BLEAdvertisingMode mode)
{
CHIP_ERROR ret = CHIP_NO_ERROR;
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);
ret = DriveBLEState();
return ret;
}
bool BLEManagerImpl::_IsAdvertising(void)
{
return mFlags.Has(Flags::kAdvertising);
}
CHIP_ERROR BLEManagerImpl::_GetDeviceName(char * buf, size_t bufSize)
{
CHIP_ERROR ret = CHIP_NO_ERROR;
if (bufSize <= GAP_DEVICE_NAME_LEN)
{
Platform::CopyString(buf, bufSize, mDeviceName);
}
else
{
ret = CHIP_ERROR_BUFFER_TOO_SMALL;
}
return ret;
}
CHIP_ERROR BLEManagerImpl::_SetDeviceName(const char * deviceName)
{
CHIP_ERROR ret = CHIP_NO_ERROR;
if (strlen(deviceName) <= GAP_DEVICE_NAME_LEN)
{
Platform::CopyString(mDeviceName, deviceName);
mFlags.Set(Flags::kBLEStackGATTNameUpdate);
mFlags.Set(Flags::kAdvertisingRefreshNeeded);
ret = DriveBLEState();
}
else
{
ret = CHIP_ERROR_BUFFER_TOO_SMALL;
}
return ret;
}
uint16_t BLEManagerImpl::_NumConnections(void)
{
uint8_t i, numConns = 0;
// Try to find an available entry
for (i = 0; i < MAX_NUM_BLE_CONNS; i++)
{
if (connList[i].connHandle != LL_CONNHANDLE_INVALID)
{
numConns++;
}
}
return numConns;
}
void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event)
{
switch (event->Type)
{
case DeviceEventType::kCHIPoBLESubscribe: {
ChipDeviceEvent connEstEvent;
BLEMGR_LOG("BLEMGR: OnPlatformEvent, kCHIPoBLESubscribe");
HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID);
connEstEvent.Type = DeviceEventType::kCHIPoBLEConnectionEstablished;
PlatformMgr().PostEventOrDie(&connEstEvent);
}
break;
case DeviceEventType::kCHIPoBLEUnsubscribe: {
BLEMGR_LOG("BLEMGR: OnPlatformEvent, kCHIPoBLEUnsubscribe");
HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID);
}
break;
case DeviceEventType::kCHIPoBLEWriteReceived: {
BLEMGR_LOG("BLEMGR: OnPlatformEvent, kCHIPoBLEWriteReceived");
HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_1_UUID,
PacketBufferHandle::Adopt(event->CHIPoBLEWriteReceived.Data));
}
break;
case DeviceEventType::kCHIPoBLEIndicateConfirm:
HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &Ble::CHIP_BLE_CHAR_2_UUID);
break;
case DeviceEventType::kCHIPoBLEConnectionError: {
BLEMGR_LOG("BLEMGR: OnPlatformEvent, kCHIPoBLEConnectionError");
HandleConnectionError(event->CHIPoBLEConnectionError.ConId, event->CHIPoBLEConnectionError.Reason);
}
break;
default:
break;
}
}
// ===== Members that implement virtual methods on BlePlatformDelegate.
CHIP_ERROR BLEManagerImpl::CloseConnection(BLE_CONNECTION_OBJECT conId)
{
void * pMsg = (void *) ICall_malloc(sizeof(void *));
pMsg = (void *) conId;
EnqueueEvtHdrMsg(BLEManagerIMPL_CHIPOBLE_CLOSE_CONN_EVT, (void *) pMsg);
return CHIP_NO_ERROR;
}
uint16_t BLEManagerImpl::GetMTU(BLE_CONNECTION_OBJECT conId) const
{
uint8_t index;
uint16_t mtu = 0;
index = GetBLEConnIndex(*((uint32_t *) conId));
if (index != MAX_NUM_BLE_CONNS)
{
mtu = sInstance.connList[index].mtu;
/* Prior to MTU update event, MTU is determined by the below formula */
if (mtu == 0)
{
mtu = MAX_PDU_SIZE - 4;
}
}
return mtu;
}
// ===== Members that implement virtual methods on BleApplicationDelegate.
void BLEManagerImpl::NotifyChipConnectionClosed(BLE_CONNECTION_OBJECT conId)
{
// Unused
}
CHIP_ERROR BLEManagerImpl::SendIndication(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId,
PacketBufferHandle data)
{
BLEMGR_LOG("BLEMGR: BLE SendIndication ");
// Allocate buffers to send to BLE app task
uint8_t dataLen = static_cast<uint8_t>(data->DataLength());
CHIPoBLEIndEvt_t * pMsg;
uint8_t * pBuf;
pMsg = (CHIPoBLEIndEvt_t *) ICall_malloc(sizeof(CHIPoBLEIndEvt_t));
if (NULL == pMsg)
{
return CHIP_ERROR_NO_MEMORY;
}
pBuf = (uint8_t *) ICall_malloc(dataLen);
if (NULL == pBuf)
{
ICall_free((void *) pMsg);
return CHIP_ERROR_NO_MEMORY;
}
memset(pBuf, 0x00, dataLen);
memcpy(pBuf, data->Start(), dataLen);
pMsg->pData = pBuf;
pMsg->len = dataLen;
EnqueueEvtHdrMsg(BLEManagerIMPL_CHIPOBLE_TX_IND_EVT, (void *) pMsg);
BLEMGR_LOG("BLEMGR: BLE SendIndication RETURN, Length: %d ", dataLen);
return CHIP_NO_ERROR;
}
CHIP_ERROR BLEManagerImpl::SubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId,
const Ble::ChipBleUUID * charId)
{
/* Unsupported on TI peripheral device implementation */
return CHIP_ERROR_NOT_IMPLEMENTED;
}
CHIP_ERROR BLEManagerImpl::UnsubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId,
const Ble::ChipBleUUID * charId)
{
/* Unsupported on TI peripheral device implementation */
return CHIP_ERROR_NOT_IMPLEMENTED;
}
CHIP_ERROR BLEManagerImpl::SendWriteRequest(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId,
PacketBufferHandle pBuf)
{
/* Unsupported on TI peripheral device implementation */
return CHIP_ERROR_NOT_IMPLEMENTED;
}
// ===== Helper Members that implement the Low level BLE Stack behavior.
/*********************************************************************
* @fn ConfigureAdvertisements
*
* @brief Initialize CHIPoBLE Advertisements.
*/
void BLEManagerImpl::ConfigureAdvertisements(void)
{
bStatus_t status = FAILURE;
uint16_t deviceDiscriminator;
uint8_t localDeviceNameLen;
uint8_t scanIndex = 0;
uint8_t advIndex = 0;
uint8_t scanResLength;
uint8_t advLength;
GapAdv_params_t advParams = { .eventProps = GAP_ADV_PROP_CONNECTABLE | GAP_ADV_PROP_LEGACY | GAP_ADV_PROP_SCANNABLE,
.primIntMin = CHIP_DEVICE_CONFIG_BLE_FAST_ADVERTISING_INTERVAL_MIN,
.primIntMax = CHIP_DEVICE_CONFIG_BLE_FAST_ADVERTISING_INTERVAL_MIN,
.primChanMap = GAP_ADV_CHAN_ALL,
.peerAddrType = PEER_ADDRTYPE_PUBLIC_OR_PUBLIC_ID,
.peerAddr = { 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa },
.filterPolicy = GAP_ADV_AL_POLICY_ANY_REQ,
.txPower = GAP_ADV_TX_POWER_NO_PREFERENCE,
.primPhy = GAP_ADV_PRIM_PHY_1_MBPS,
.secPhy = GAP_ADV_SEC_PHY_1_MBPS,
.sid = 0 };
BLEMGR_LOG("BLEMGR: ConfigureAdvertisements");
ChipBLEDeviceIdentificationInfo mDeviceIdInfo;
ConfigurationMgr().GetBLEDeviceIdentificationInfo(mDeviceIdInfo);
memset(sInstance.mScanResDatachipOBle, 0, CHIPOBLE_ADV_DATA_MAX_SIZE);
memset(sInstance.mAdvDatachipOBle, 0, CHIPOBLE_ADV_DATA_MAX_SIZE);
// Verify device name was not already set
if (!sInstance.mFlags.Has(Flags::kBLEStackGATTNameSet))
{
/* Default device name is CHIP-<DISCRIMINATOR> */
deviceDiscriminator = mDeviceIdInfo.GetDeviceDiscriminator();
localDeviceNameLen = strlen(CHIP_DEVICE_CONFIG_BLE_DEVICE_NAME_PREFIX) + CHIPOBLE_DEVICE_DESC_LENGTH;
memset(sInstance.mDeviceName, 0, GAP_DEVICE_NAME_LEN);
snprintf(sInstance.mDeviceName, GAP_DEVICE_NAME_LEN, "%s%04u", CHIP_DEVICE_CONFIG_BLE_DEVICE_NAME_PREFIX,
deviceDiscriminator);
// Set the Device Name characteristic in the GAP GATT Service
// For more information, see the section in the User's Guide:
// http://software-dl.ti.com/lprf/ble5stack-latest/
GGS_SetParameter(GGS_DEVICE_NAME_ATT, GAP_DEVICE_NAME_LEN, sInstance.mDeviceName);
BLEMGR_LOG("BLEMGR: AdvInit New device name set: %s", sInstance.mDeviceName);
}
else
{
sInstance.mFlags.Clear(Flags::kBLEStackGATTNameUpdate);
localDeviceNameLen = strlen(sInstance.mDeviceName);
}
scanResLength = localDeviceNameLen + CHIPOBLE_SCANRES_SIZE_NO_NAME;
/* Verify scan response data length */
assert(scanResLength < CHIPOBLE_ADV_DATA_MAX_SIZE);
sInstance.mScanResDatachipOBle[scanIndex++] = localDeviceNameLen + 1;
sInstance.mScanResDatachipOBle[scanIndex++] = GAP_ADTYPE_LOCAL_NAME_COMPLETE;
memcpy(&sInstance.mScanResDatachipOBle[scanIndex], sInstance.mDeviceName, localDeviceNameLen);
scanIndex += localDeviceNameLen;
sInstance.mScanResDatachipOBle[scanIndex++] = 0x03;
sInstance.mScanResDatachipOBle[scanIndex++] = GAP_ADTYPE_16BIT_COMPLETE;
sInstance.mScanResDatachipOBle[scanIndex++] = static_cast<uint8_t>(LO_UINT16(CHIPOBLE_SERV_UUID));
sInstance.mScanResDatachipOBle[scanIndex++] = static_cast<uint8_t>(HI_UINT16(CHIPOBLE_SERV_UUID));
for (uint8_t temp = 0; temp < scanIndex; temp++)
{
BLEMGR_LOG("BLEMGR: AdvInit Scan Response Data: %x", sInstance.mScanResDatachipOBle[temp]);
}
advLength = sizeof(static_cast<uint16_t>(CHIPOBLE_SERV_UUID)) + static_cast<uint8_t>(sizeof(mDeviceIdInfo)) + 1;
/* Verify advertising data length */
assert((CHIPOBLE_ADV_SIZE_NO_DEVICE_ID_INFO + advLength) < CHIPOBLE_ADV_DATA_MAX_SIZE);
BLEMGR_LOG("BLEMGR: AdvInit: MDeviceIDInfo Size: %d", sizeof(mDeviceIdInfo));
BLEMGR_LOG("BLEMGR: AdvInit: advlength: %d", advLength);
BLEMGR_LOG("BLEMGR: AdvInit:Desc : %d", mDeviceIdInfo.GetDeviceDiscriminator());
sInstance.mAdvDatachipOBle[advIndex++] = 0x02;
sInstance.mAdvDatachipOBle[advIndex++] = GAP_ADTYPE_FLAGS;
sInstance.mAdvDatachipOBle[advIndex++] = GAP_ADTYPE_FLAGS_BREDR_NOT_SUPPORTED | GAP_ADTYPE_FLAGS_GENERAL;
sInstance.mAdvDatachipOBle[advIndex++] = advLength;
sInstance.mAdvDatachipOBle[advIndex++] = GAP_ADTYPE_SERVICE_DATA;
sInstance.mAdvDatachipOBle[advIndex++] = static_cast<uint8_t>(LO_UINT16(CHIPOBLE_SERV_UUID));
sInstance.mAdvDatachipOBle[advIndex++] = static_cast<uint8_t>(HI_UINT16(CHIPOBLE_SERV_UUID));
memcpy(&sInstance.mAdvDatachipOBle[advIndex], (void *) &mDeviceIdInfo, static_cast<uint8_t>(sizeof(mDeviceIdInfo)));
// Setup and start Advertising
// For more information, see the GAP section in the User's Guide:
// http://software-dl.ti.com/lprf/ble5stack-latest/
if (!sInstance.mFlags.Has(Flags::kBLEStackAdvInitialized))
{
// Create Advertisement set #1 and assign handle
status = (bStatus_t) GapAdv_create(&advCallback, &advParams, &sInstance.advHandleLegacy);
assert(status == SUCCESS);
// Set event mask for set #1
status = (bStatus_t) GapAdv_setEventMask(sInstance.advHandleLegacy,
GAP_ADV_EVT_MASK_START_AFTER_ENABLE | GAP_ADV_EVT_MASK_END_AFTER_DISABLE |
GAP_ADV_EVT_MASK_SET_TERMINATED);
Util_constructClock(&sInstance.clkAdvTimeout, AdvTimeoutHandler, ADV_TIMEOUT, 0, false, (uintptr_t) NULL);
}
if (sInstance.mFlags.Has(Flags::kBLEStackAdvInitialized))
{
// Don't free anything since we're going to use the same buffer to re-load
GapAdv_prepareLoadByHandle(sInstance.advHandleLegacy, GAP_ADV_FREE_OPTION_DONT_FREE);
}
// Load advertising data for set #1 that is statically allocated by the app
status = (bStatus_t) GapAdv_loadByHandle(sInstance.advHandleLegacy, GAP_ADV_DATA_TYPE_ADV,
CHIPOBLE_ADV_SIZE_NO_DEVICE_ID_INFO + advLength, sInstance.mAdvDatachipOBle);
assert(status == SUCCESS);
if (sInstance.mFlags.Has(Flags::kBLEStackAdvInitialized))
{
// Don't free anything since we're going to use the same buffer to re-load
GapAdv_prepareLoadByHandle(sInstance.advHandleLegacy, GAP_ADV_FREE_OPTION_DONT_FREE);
}
// Load scan response data for set #1 that is statically allocated by the app
status = (bStatus_t) GapAdv_loadByHandle(sInstance.advHandleLegacy, GAP_ADV_DATA_TYPE_SCAN_RSP, scanResLength,
sInstance.mScanResDatachipOBle);
assert(status == SUCCESS);
}
/*********************************************************************
* @fn EventHandler_init
*
* @brief Called during initialization and contains application
* specific initialization (ie. hardware initialization/setup,
* table initialization, power up notification, etc), and
* profile initialization/setup.
*/
void BLEManagerImpl::EventHandler_init(void)
{
BLEMGR_LOG("BLEMGR: EventHandler_init");
/* Update User Configuration of the stack */
user0Cfg.appServiceInfo->timerTickPeriod = ICall_getTickPeriod();
user0Cfg.appServiceInfo->timerMaxMillisecond = ICall_getMaxMSecs();
/* Initialize ICall module */
ICall_init();
/* Start tasks of external images */
ICall_createRemoteTasks();
BLEManagerImpl::sBleTaskHndl = (TaskHandle_t) (*((TaskHandle_t *) ICall_getRemoteTaskHandle(0)));
DMMSch_registerClient((TaskHandle_t) BLEManagerImpl::sBleTaskHndl, DMMPolicy_StackRole_BlePeripheral);
/* set the stacks in default states */
DMMPolicy_updateStackState(DMMPolicy_StackRole_BlePeripheral, DMMPOLICY_BLE_IDLE);
vTaskPrioritySet(xTaskGetCurrentTaskHandle(), BLE_MANAGER_TASK_PRIORITY);
// ******************************************************************
// N0 STACK API CALLS CAN OCCUR BEFORE THIS CALL TO ICall_registerApp
// ******************************************************************
// Register the current thread as an ICall dispatcher application
// so that the application can send and receive messages.
ICall_registerApp(&BLEManagerImpl::sSelfEntity, &BLEManagerImpl::sSyncEvent);
#ifdef USE_RCOSC
RCOSC_enableCalibration();
#endif // USE_RCOSC
// Create an RTOS queue for message from profile to be sent to app.
Util_constructQueue(&BLEManagerImpl::sEventHandlerMsgQueueID);
// Configure GAP
{
uint16_t paramUpdateDecision = DEFAULT_PARAM_UPDATE_REQ_DECISION;
// Pass all parameter update requests to the app for it to decide
GAP_SetParamValue(GAP_PARAM_LINK_UPDATE_DECISION, paramUpdateDecision);
}
// Setup the GAP Bond Manager. For more information see the GAP Bond Manager
// section in the User's Guide:
// http://software-dl.ti.com/lprf/ble5stack-latest/
setBondManagerParameters();
// Initialize GATT attributes
GGS_AddService(GATT_ALL_SERVICES); // GAP GATT Service
GATTServApp_AddService(GATT_ALL_SERVICES); // GATT Service
DevInfo_AddService(); // Device Information Service
CHIPoBLEProfile_AddService(GATT_ALL_SERVICES);
// Start Bond Manager and register callback
VOID GAPBondMgr_Register(&BLEMgr_BondMgrCBs);
// Register with GAP for HCI/Host messages. This is needed to receive HCI
// events. For more information, see the HCI section in the User's Guide:
// http://software-dl.ti.com/lprf/ble5stack-latest/
GAP_RegisterForMsgs(BLEManagerImpl::sSelfEntity);
// Register for GATT local events and ATT Responses pending for transmission
GATT_RegisterForMsgs(BLEManagerImpl::sSelfEntity);
CHIPoBLEProfile_RegisterAppCBs(&CHIPoBLEProfile_CBs);
// Set default values for Data Length Extension
// Extended Data Length Feature is already enabled by default
{
// This API is documented in hci.h
// See the LE Data Length Extension section in the BLE5-Stack User's Guide for information on using this command:
// http://software-dl.ti.com/lprf/ble5stack-latest/
HCI_LE_WriteSuggestedDefaultDataLenCmd(BLEMANAGER_SUGGESTED_PDU_SIZE, BLEMANAGER_SUGGESTED_TX_TIME);
}
// Initialize GATT Client
GATT_InitClient("");
// Initialize Connection List
ClearBLEConnListEntry(LL_CONNHANDLE_ALL);
// Initialize GAP layer for Peripheral role and register to receive GAP events
GAP_DeviceInit(GAP_PROFILE_PERIPHERAL, BLEManagerImpl::sSelfEntity, sInstance.addrMode, &pRandomAddress);
// Initialize array to store connection handle and RSSI values
InitPHYRSSIArray();
BLEMGR_LOG("BLEMGR: EventHandler_init Done");
}
/*********************************************************************
* @fn InitPHYRSSIArray
*
* @brief Initializes the array of structure/s to store data related
* RSSI based auto PHy change
*
* @param connHandle - the connection handle
*
* @param addr - pointer to device address
*
* @return index of connection handle
*/
void BLEManagerImpl::InitPHYRSSIArray(void)
{
BLEMGR_LOG("BLEMGR: InitPHYRSSIArray");
// Initialize array to store connection handle and RSSI values
memset(sInstance.connList, 0, sizeof(sInstance.connList));
for (uint8_t index = 0; index < MAX_NUM_BLE_CONNS; index++)
{
sInstance.connList[index].connHandle = INVALID_HANDLE;
}
}
/*********************************************************************
* @fn CreateEventHandler
*
* @brief Create FreeRTOS Task for BLE Event handling
*
*/
CHIP_ERROR BLEManagerImpl::CreateEventHandler(void)
{
BLEMGR_LOG("BLEMGR: CreateEventHandler");
BaseType_t xReturned;
/* Create the task, storing the handle. */
xReturned = xTaskCreate(EventHandler, /* Function that implements the task. */
"ble_hndlr", /* Text name for the task. */
BLEMANAGER_EVENT_HANDLER_STACK_SIZE, /* Stack size in words, not bytes. */
this, /* Parameter passed into the task. */
BLE_STACK_TASK_PRIORITY, /* Keep priority the same as ICALL until init is complete */
NULL); /* Used to pass out the created task's handle. */
if (xReturned == errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY)
{
return CHIP_ERROR_NO_MEMORY;
}
else
{
return CHIP_NO_ERROR;
}
}
/*********************************************************************
* @fn RemoteDisplay_processStackMsg
*
* @brief Process an incoming stack message.
*
* @param pMsg - message to process
*
* @return TRUE if safe to deallocate incoming message, FALSE otherwise.
*/
uint8_t BLEManagerImpl::ProcessStackEvent(ICall_Hdr * pMsg)
{
// Always dealloc pMsg unless set otherwise
uint8_t safeToDealloc = TRUE;
switch (pMsg->event)
{
case GAP_MSG_EVENT:
ProcessGapMessage((gapEventHdr_t *) pMsg);
break;
case GATT_MSG_EVENT:
// Process GATT message
safeToDealloc = ProcessGATTMsg((gattMsgEvent_t *) pMsg);
break;
case HCI_GAP_EVENT_EVENT: {
// Process HCI message
switch (pMsg->status)
{
case HCI_COMMAND_COMPLETE_EVENT_CODE:
// Process HCI Command Complete Events here
{
// RemoteDisplay_processCmdCompleteEvt((hciEvt_CmdComplete_t *) pMsg);
break;
}
case HCI_BLE_HARDWARE_ERROR_EVENT_CODE:
assert(false);
break;
// HCI Commands Events
case HCI_COMMAND_STATUS_EVENT_CODE: {
hciEvt_CommandStatus_t * pMyMsg = (hciEvt_CommandStatus_t *) pMsg;
switch (pMyMsg->cmdOpcode)
{
case HCI_LE_SET_PHY: {
if (pMyMsg->cmdStatus == HCI_ERROR_CODE_UNSUPPORTED_REMOTE_FEATURE)
{
/* PHY Change failure, peer does not support this */
}
break;
}
default:
break;
}
break;
}
case HCI_LE_EVENT_CODE: {
hciEvt_BLEPhyUpdateComplete_t * pPUC = (hciEvt_BLEPhyUpdateComplete_t *) pMsg;
// A Phy Update Has Completed or Failed
if (pPUC->BLEEventCode == HCI_BLE_PHY_UPDATE_COMPLETE_EVENT)
{
if (pPUC->status != SUCCESS)
{
/* PHY Change failure */
}
else
{
/* PHY Update successful */
}
}
break;
}
default:
break;
}
break;
}
default:
// do nothing
break;
}
return safeToDealloc;
}
/*********************************************************************
* @fn ProcessEvtHdrMsg
*
* @brief Process an incoming callback from a profile.
*
* @param pMsg - message to process
*
* @return None.
*/
void BLEManagerImpl::ProcessEvtHdrMsg(QueuedEvt_t * pMsg)
{
bool dealloc = TRUE;
switch (pMsg->event)
{
/* External CHIPoBLE Event trigger */
case BLEManagerIMPL_STATE_UPDATE_EVT: {
bStatus_t status;
/* Verify BLE service mode is enabled */
if ((sInstance.mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled) &&
sInstance.mFlags.Has(Flags::kBLEStackInitialized))
{
if (sInstance.mFlags.Has(Flags::kAdvertisingEnabled))
{
BLEMGR_LOG("BLEMGR: BLE Process Application Message: kAdvertisingEnabled");
if (sInstance.mFlags.Has(Flags::kAdvertisingRefreshNeeded))
{
BLEMGR_LOG("BLEMGR: BLE Process Application Message: kAdvertisingRefreshNeeded");
// Disable advertisements and proceed with updates
sInstance.mFlags.Clear(Flags::kAdvertisingRefreshNeeded);
GapAdv_disable(sInstance.advHandleLegacy);
sInstance.mFlags.Clear(Flags::kAdvertising);
uint32_t newParamMax = 0, newParamMin = 0;
if (sInstance.mFlags.Has(Flags::kFastAdvertisingEnabled))
{
// Update advertising interval
BLEMGR_LOG("BLEMGR: ConfigureAdvertisements: Fast Advertising Enabled");
newParamMax = CHIP_DEVICE_CONFIG_BLE_FAST_ADVERTISING_INTERVAL_MAX;
newParamMin = CHIP_DEVICE_CONFIG_BLE_FAST_ADVERTISING_INTERVAL_MIN;
}
else
{
// Decrease advertising interval
BLEMGR_LOG("BLEMGR: ConfigureAdvertisements: Slow Advertising Enabled");
newParamMax = CHIP_DEVICE_CONFIG_BLE_SLOW_ADVERTISING_INTERVAL_MAX;
newParamMin = CHIP_DEVICE_CONFIG_BLE_SLOW_ADVERTISING_INTERVAL_MIN;
}
// Set a parameter
GapAdv_setParam(sInstance.advHandleLegacy, GAP_ADV_PARAM_PRIMARY_INTERVAL_MAX, &newParamMax);
GapAdv_setParam(sInstance.advHandleLegacy, GAP_ADV_PARAM_PRIMARY_INTERVAL_MIN, &newParamMin);
// Update advertisement parameters
ConfigureAdvertisements();
}
}
// Turn on advertisements
if (sInstance.mFlags.Has(Flags::kAdvertisingEnabled) && !sInstance.mFlags.Has(Flags::kAdvertising))
{
// Send notification to thread manager that CHIPoBLE advertising is starting
// Enable legacy advertising for set #1
status = (bStatus_t) GapAdv_enable(sInstance.advHandleLegacy, GAP_ADV_ENABLE_OPTIONS_USE_MAX, 0);
// If adverisement fails, keep flags set
if (status == SUCCESS)
{
// Start advertisement timeout timer
if (sInstance.mFlags.Has(Flags::kFastAdvertisingEnabled))
{
Util_rescheduleClock(&sInstance.clkAdvTimeout, CHIP_DEVICE_CONFIG_BLE_ADVERTISING_INTERVAL_CHANGE_TIME);
}
else
{
Util_rescheduleClock(&sInstance.clkAdvTimeout,
ADV_TIMEOUT - CHIP_DEVICE_CONFIG_BLE_ADVERTISING_INTERVAL_CHANGE_TIME);
}
Util_startClock(&sInstance.clkAdvTimeout);
sInstance.mFlags.Set(Flags::kAdvertising);
}
}
// Advertising should be disabled
if ((!sInstance.mFlags.Has(Flags::kAdvertisingEnabled)) && sInstance.mFlags.Has(Flags::kAdvertising))
{
BLEMGR_LOG("BLEMGR: BLE Process Application Message: ADvertisements disabled");
// Stop advertising
GapAdv_disable(sInstance.advHandleLegacy);
sInstance.mFlags.Clear(Flags::kAdvertising);
Util_stopClock(&sInstance.clkAdvTimeout);
// reset fast advertising
sInstance.mFlags.Set(Flags::kFastAdvertisingEnabled);
}
}
}
break;
case BLEManagerIMPL_CHIPOBLE_CLOSE_CONN_EVT: {
uint16_t connHandle = *((uint16_t *) (pMsg->pData));
// Close active connection
GAP_TerminateLinkReq(connHandle, HCI_DISCONNECT_REMOTE_USER_TERM);
}
break;
case BLEManagerIMPL_CHIPOBLE_TX_IND_EVT: {
uint8_t dataLen = ((CHIPoBLEIndEvt_t *) (pMsg->pData))->len;
CHIPoBLEProfile_SetParameter(CHIPOBLEPROFILE_TX_CHAR, dataLen, (void *) (((CHIPoBLEIndEvt_t *) (pMsg->pData))->pData),
BLEManagerImpl::sSelfEntity);
BLEMGR_LOG("BLEMGR: BLE Process Application Message: BLEManagerIMPL_CHIPOBLE_TX_IND_EVT: Length: %d", dataLen);
ICall_free((void *) (((CHIPoBLEIndEvt_t *) (pMsg->pData))->pData));
dealloc = TRUE;
}
break;
case CHIPOBLE_CHAR_CHANGE_EVT: {
uint16_t writeLen = ((CHIPoBLEProfChgEvt_t *) (pMsg->pData))->len;
uint8_t paramId = ((CHIPoBLEProfChgEvt_t *) (pMsg->pData))->paramId;
uint16_t connHandleId = ((CHIPoBLEProfChgEvt_t *) (pMsg->pData))->connHandle;
void * connHandle;
ChipDeviceEvent event;
uint8_t i;
ConnRec_t * activeConnObj = NULL;
// Find active connection
for (i = 0; i < MAX_NUM_BLE_CONNS; i++)
{
if (sInstance.connList[i].connHandle == connHandleId)
{
activeConnObj = &sInstance.connList[i];
}
}
connHandle = (void *) &activeConnObj->connHandle;
if (paramId == CHIPOBLEPROFILE_RX_CHAR)
{
BLEMGR_LOG("BLEMGR: BLE Process Application Message: CHIPOBLE_CHAR_CHANGE_EVT, CHIPOBLEPROFILE_RX_CHAR");
// Pull written data from CHIPOBLE Profile based on extern server write
uint8_t * rxBuf = (uint8_t *) ICall_malloc(writeLen);
if (rxBuf == NULL)
{
// alloc error
return;
}
memset(rxBuf, 0x00, writeLen);
BLEMGR_LOG("BLEMGR: BLE Process Application Message: CHIPOBLE_CHAR_CHANGE_EVT, length: %d", writeLen);
CHIPoBLEProfile_GetParameter(CHIPOBLEPROFILE_RX_CHAR, rxBuf, writeLen);
System::PacketBufferHandle packetBuf = System::PacketBufferHandle::NewWithData(rxBuf, writeLen, 0, 0);
ICall_free(rxBuf);
if (packetBuf.IsNull())
{
// alloc error
return;
}
// Arrange to post a CHIPoBLERXWriteEvent event to the CHIP queue.
event.Type = DeviceEventType::kCHIPoBLEWriteReceived;
event.CHIPoBLEWriteReceived.ConId = (void *) connHandle;
event.CHIPoBLEWriteReceived.Data = std::move(packetBuf).UnsafeRelease();
}
else if (paramId == CHIPOBLEPROFILE_CCCWrite)
{
BLEMGR_LOG("BLEMGR: BLE Process Application Message: CHIPOBLE_CHAR_CHANGE_EVT, CHIPOBLEPROFILE_CCCWrite");
// TODO: Add check to see if subscribing OR unsubscribing from char indications
uint8_t cccValue;
CHIPoBLEProfile_GetParameter(CHIPOBLEPROFILE_CCCWrite, &cccValue, 1);
// Check whether it is a sub/unsub event. 0x1 = Notifications enabled, 0x2 = Indications enabled
if (cccValue & 0x2)
{
// Post event to CHIP
BLEMGR_LOG("BLEMGR: BLE Process Application Message: CHIPOBLE_CHAR_CHANGE_EVT, Subscrbe");
event.Type = DeviceEventType::kCHIPoBLESubscribe;
}
else
{
BLEMGR_LOG("BLEMGR: BLE Process Application Message: CHIPOBLE_CHAR_CHANGE_EVT, unsubscrbe");
event.Type = DeviceEventType::kCHIPoBLEUnsubscribe;
}
// Post event to CHIP
event.CHIPoBLESubscribe.ConId = (void *) connHandle;
}
PlatformMgr().PostEventOrDie(&event);
}
break;
case ADV_EVT:
ProcessAdvEvent((GapAdvEventData_t *) (pMsg->pData));
break;
case PAIR_STATE_EVT: {
BLEMGR_LOG("BLEMGR: PAIR_STATE_EVT");
}
break;
case PASSCODE_EVT: {
BLEMGR_LOG("BLEMGR: PASSCODE_EVT");
}
break;
case READ_RPA_EVT:
UpdateBLERPA();
break;
case SEND_PARAM_UPDATE_EVT: {
// Extract connection handle from data
uint16_t connHandle = *(uint16_t *) (((ClockEventData_t *) pMsg->pData)->data);
if (CHIP_NO_ERROR != ProcessParamUpdate(connHandle))
{
// error
return;
}
// This data is not dynamically allocated
dealloc = FALSE;
/* If we are sending a param update request then the service discovery
* should have ended. Changed state to connected */
DMMPolicy_updateStackState(DMMPolicy_StackRole_BlePeripheral, DMMPOLICY_BLE_CONNECTED);
break;
}
case CONN_EVT:
break;
default:
// Do nothing.
break;
}
// Free message data if it exists and we are to dealloc
if ((dealloc == TRUE) && (pMsg->pData != NULL))
{
ICall_free(pMsg->pData);
}
}