3 * Copyright (c) 2020-2021 Project CHIP Authors
4 * Copyright (c) 2019 Nest Labs, Inc.
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
21 * Provides an implementation of the BLEManager singleton object
22 * for the Silicon Labs EFR32 platforms.
25 /* this file behaves like a config.h, comes first */
26 #include <platform/internal/CHIPDeviceLayerInternal.h>
27 #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE
29 #include <platform/internal/BLEManager.h>
31 #include "sl_bt_api.h"
32 #include "sl_bt_stack_config.h"
33 #include "sl_bt_stack_init.h"
34 #include <ble/CHIPBleServiceData.h>
35 #include <platform/EFR32/freertos_bluetooth.h>
36 #include <support/CodeUtils.h>
37 #include <support/logging/CHIPLogging.h>
39 using namespace ::chip;
40 using namespace ::chip::Ble;
43 namespace DeviceLayer {
48 #define CHIP_ADV_DATA_TYPE_FLAGS 0x01
49 #define CHIP_ADV_DATA_TYPE_UUID 0x03
50 #define CHIP_ADV_DATA_TYPE_NAME 0x09
51 #define CHIP_ADV_DATA_TYPE_SERVICE_DATA 0x16
53 #define CHIP_ADV_DATA_FLAGS 0x06
55 #define CHIP_ADV_DATA 0
56 #define CHIP_ADV_SCAN_RESPONSE_DATA 1
57 #define CHIP_ADV_SHORT_UUID_LEN 2
59 #define MAX_RESPONSE_DATA_LEN 31
60 #define MAX_ADV_DATA_LEN 31
62 // Timer Frequency used.
63 #define TIMER_CLK_FREQ ((uint32_t) 32768)
64 // Convert msec to timer ticks.
65 #define TIMER_MS_2_TIMERTICK(ms) ((TIMER_CLK_FREQ * ms) / 1000)
66 #define TIMER_S_2_TIMERTICK(s) (TIMER_CLK_FREQ * s)
68 #define BLE_MAX_BUFFER_SIZE (3150)
69 #define BLE_MAX_ADVERTISERS (1)
70 #define BLE_CONFIG_MAX_PERIODIC_ADVERTISING_SYNC (0)
71 #define BLE_CONFIG_MAX_SOFTWARE_TIMERS (4)
72 #define BLE_CONFIG_MIN_TX_POWER (-30)
73 #define BLE_CONFIG_MAX_TX_POWER (80)
74 #define BLE_CONFIG_RF_PATH_GAIN_TX (0)
75 #define BLE_CONFIG_RF_PATH_GAIN_RX (0)
77 /* Bluetooth stack configuration parameters (see "UG136: Silicon Labs Bluetooth C Application Developer's Guide" for
78 * details on each parameter) */
79 static sl_bt_configuration_t config;
81 const uint8_t UUID_CHIPoBLEService[] = { 0xFB, 0x34, 0x9B, 0x5F, 0x80, 0x00, 0x00, 0x80,
82 0x00, 0x10, 0x00, 0x00, 0xAF, 0xFE, 0x00, 0x00 };
83 const uint8_t ShortUUID_CHIPoBLEService[] = { 0xAF, 0xFE };
84 const ChipBleUUID ChipUUID_CHIPoBLEChar_RX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F,
86 const ChipBleUUID ChipUUID_CHIPoBLEChar_TX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F,
91 BLEManagerImpl BLEManagerImpl::sInstance;
93 /***************************************************************************/
95 * Setup the bluetooth init function.
99 * All bluetooth specific initialization
100 * code should be here like sl_bt_init_stack(),
101 * sl_bt_init_multiprotocol() and so on.
102 ******************************************************************************/
103 extern "C" sl_status_t initialize_bluetooth()
105 sl_status_t ret = sl_bt_init_stack(&config);
106 sl_bt_class_system_init();
107 sl_bt_class_advertiser_init();
108 sl_bt_class_gap_init();
109 sl_bt_class_scanner_init();
110 sl_bt_class_connection_init();
111 sl_bt_class_gatt_init();
112 sl_bt_class_gatt_server_init();
113 sl_bt_class_nvm_init();
114 sl_bt_class_sm_init();
115 sl_bt_init_multiprotocol();
119 static void initBleConfig(void)
121 memset(&config, 0, sizeof(sl_bt_configuration_t));
122 config.config_flags = SL_BT_CONFIG_FLAG_RTOS; /* Check flag options from UG136 */
123 config.bluetooth.max_connections = BLE_LAYER_NUM_BLE_ENDPOINTS; /* Maximum number of simultaneous connections */
124 config.bluetooth.max_advertisers = BLE_MAX_ADVERTISERS;
125 config.bluetooth.max_periodic_sync = BLE_CONFIG_MAX_PERIODIC_ADVERTISING_SYNC;
126 config.bluetooth.max_buffer_memory = BLE_MAX_BUFFER_SIZE;
127 config.gattdb = &bg_gattdb_data; /* Pointer to GATT database */
128 config.scheduler_callback = BluetoothLLCallback;
129 config.stack_schedule_callback = BluetoothUpdate;
130 config.max_timers = BLE_CONFIG_MAX_SOFTWARE_TIMERS;
131 config.rf.tx_gain = BLE_CONFIG_RF_PATH_GAIN_TX;
132 config.rf.rx_gain = BLE_CONFIG_RF_PATH_GAIN_RX;
133 config.rf.tx_min_power = BLE_CONFIG_MIN_TX_POWER;
134 config.rf.tx_max_power = BLE_CONFIG_MAX_TX_POWER;
136 config.pa.config_enable = 1; /* Set this to be a valid PA config */
137 #if defined(FEATURE_PA_INPUT_FROM_VBAT)
138 config.pa.input = SL_BT_RADIO_PA_INPUT_VBAT; /* Configure PA input to VBAT */
140 config.pa.input = SL_BT_RADIO_PA_INPUT_DCDC; /* Configure PA input to DCDC */
141 #endif // defined(FEATURE_PA_INPUT_FROM_VBAT)
142 #endif // (HAL_PA_ENABLE)
145 CHIP_ERROR BLEManagerImpl::_Init()
150 // Initialize the CHIP BleLayer.
151 err = BleLayer::Init(this, this, &SystemLayer);
154 memset(mBleConnections, 0, sizeof(mBleConnections));
155 memset(mIndConfId, kUnusedIndex, sizeof(mIndConfId));
156 mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Enabled;
160 // Start Bluetooth Link Layer and stack tasks
162 bluetooth_start(CHIP_DEVICE_CONFIG_BLE_LL_TASK_PRIORITY, CHIP_DEVICE_CONFIG_BLE_STACK_TASK_PRIORITY, initialize_bluetooth);
164 VerifyOrExit(ret == bg_err_success, err = MapBLEError(ret));
166 // Create the Bluetooth Application task
167 xTaskCreate(bluetoothStackEventHandler, /* Function that implements the task. */
168 CHIP_DEVICE_CONFIG_BLE_APP_TASK_NAME, /* Text name for the task. */
169 CHIP_DEVICE_CONFIG_BLE_APP_TASK_STACK_SIZE / sizeof(StackType_t), /* Number of indexes in the xStack array. */
170 this, /* Parameter passed into the task. */
171 CHIP_DEVICE_CONFIG_BLE_APP_TASK_PRIORITY, /* Priority at which the task is created. */
172 NULL); /* Variable to hold the task's data structure. */
174 mFlags.ClearAll().Set(Flags::kAdvertisingEnabled, CHIP_DEVICE_CONFIG_CHIPOBLE_ENABLE_ADVERTISING_AUTOSTART);
175 PlatformMgr().ScheduleWork(DriveBLEState, 0);
181 uint16_t BLEManagerImpl::_NumConnections(void)
183 uint16_t numCons = 0;
184 for (uint16_t i = 0; i < kMaxConnections; i++)
186 if (mBleConnections[i].allocated)
195 void BLEManagerImpl::bluetoothStackEventHandler(void * p_arg)
197 EventBits_t flags = 0;
201 // wait for Bluetooth stack events, do not consume set flag
202 flags = xEventGroupWaitBits(bluetooth_event_flags, /* The event group being tested. */
203 BLUETOOTH_EVENT_FLAG_EVT_WAITING, /* The bits within the event group to wait for. */
204 pdFALSE, /* Dont clear flags before returning */
205 pdFALSE, /* Any flag will do, dont wait for all flags to be set */
206 portMAX_DELAY); /* Wait for maximum duration for bit to be set */
208 if (flags & BLUETOOTH_EVENT_FLAG_EVT_WAITING)
210 flags &= ~BLUETOOTH_EVENT_FLAG_EVT_WAITING;
211 xEventGroupClearBits(bluetooth_event_flags, BLUETOOTH_EVENT_FLAG_EVT_WAITING);
213 // As this is running in a separate thread, we need to block CHIP from operating,
214 // until the events are handled.
215 PlatformMgr().LockChipStack();
217 // handle bluetooth events
218 switch (SL_BT_MSG_ID(bluetooth_evt->header))
220 case sl_bt_evt_system_boot_id: {
221 ChipLogProgress(DeviceLayer, "Bluetooth stack booted: v%d.%d.%d-b%d\n", bluetooth_evt->data.evt_system_boot.major,
222 bluetooth_evt->data.evt_system_boot.minor, bluetooth_evt->data.evt_system_boot.patch,
223 bluetooth_evt->data.evt_system_boot.build);
224 sInstance.HandleBootEvent();
228 case sl_bt_evt_connection_opened_id: {
229 sInstance.HandleConnectEvent(bluetooth_evt);
232 case sl_bt_evt_connection_parameters_id: {
233 // ChipLogProgress(DeviceLayer, "Connection parameter ID received. Nothing to do");
236 case sl_bt_evt_connection_phy_status_id: {
237 // ChipLogProgress(DeviceLayer, "PHY update procedure is completed");
240 case sl_bt_evt_connection_closed_id: {
241 sInstance.HandleConnectionCloseEvent(bluetooth_evt);
245 /* This event indicates that a remote GATT client is attempting to write a value of an
246 * attribute in to the local GATT database, where the attribute was defined in the GATT
247 * XML firmware configuration file to have type="user". */
248 case sl_bt_evt_gatt_server_attribute_value_id: {
249 sInstance.HandleWriteEvent(bluetooth_evt);
253 case sl_bt_evt_gatt_mtu_exchanged_id: {
254 sInstance.UpdateMtu(bluetooth_evt);
258 // confirmation of indication received from remote GATT client
259 case sl_bt_evt_gatt_server_characteristic_status_id: {
260 sl_bt_gatt_server_characteristic_status_flag_t StatusFlags;
262 StatusFlags = (sl_bt_gatt_server_characteristic_status_flag_t)
263 bluetooth_evt->data.evt_gatt_server_characteristic_status.status_flags;
265 if (sl_bt_gatt_server_confirmation == StatusFlags)
267 sInstance.HandleTxConfirmationEvent(bluetooth_evt);
269 else if ((bluetooth_evt->data.evt_gatt_server_characteristic_status.characteristic == gattdb_CHIPoBLEChar_Tx) &&
270 (bluetooth_evt->data.evt_gatt_server_characteristic_status.status_flags == gatt_server_client_config))
272 sInstance.HandleTXCharCCCDWrite(bluetooth_evt);
277 /* Software Timer event */
278 case sl_bt_evt_system_soft_timer_id: {
279 sInstance.HandleSoftTimerEvent(bluetooth_evt);
284 ChipLogProgress(DeviceLayer, "evt_UNKNOWN id = %08x", SL_BT_MSG_ID(bluetooth_evt->header));
289 PlatformMgr().UnlockChipStack();
291 vRaiseEventFlagBasedOnContext(bluetooth_event_flags, BLUETOOTH_EVENT_FLAG_EVT_HANDLED);
295 CHIP_ERROR BLEManagerImpl::_SetCHIPoBLEServiceMode(CHIPoBLEServiceMode val)
297 CHIP_ERROR err = CHIP_NO_ERROR;
299 VerifyOrExit(val != ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, err = CHIP_ERROR_INVALID_ARGUMENT);
300 VerifyOrExit(mServiceMode != ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE);
302 if (val != mServiceMode)
305 PlatformMgr().ScheduleWork(DriveBLEState, 0);
312 CHIP_ERROR BLEManagerImpl::_SetAdvertisingEnabled(bool val)
314 CHIP_ERROR err = CHIP_NO_ERROR;
316 VerifyOrExit(mServiceMode != ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE);
318 if (mFlags.Has(Flags::kAdvertisingEnabled) != val)
320 mFlags.Set(Flags::kAdvertisingEnabled, val);
321 PlatformMgr().ScheduleWork(DriveBLEState, 0);
328 CHIP_ERROR BLEManagerImpl::_SetFastAdvertisingEnabled(bool val)
330 CHIP_ERROR err = CHIP_NO_ERROR;
332 VerifyOrExit(mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE);
334 if (mFlags.Has(Flags::kFastAdvertisingEnabled) != val)
336 mFlags.Set(Flags::kFastAdvertisingEnabled, val);
337 PlatformMgr().ScheduleWork(DriveBLEState, 0);
344 CHIP_ERROR BLEManagerImpl::_GetDeviceName(char * buf, size_t bufSize)
346 if (strlen(mDeviceName) >= bufSize)
348 return CHIP_ERROR_BUFFER_TOO_SMALL;
350 strcpy(buf, mDeviceName);
351 return CHIP_NO_ERROR;
354 CHIP_ERROR BLEManagerImpl::_SetDeviceName(const char * deviceName)
357 CHIP_ERROR err = CHIP_NO_ERROR;
358 if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_NotSupported)
360 return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;
362 if (deviceName != NULL && deviceName[0] != 0)
364 if (strlen(deviceName) >= kMaxDeviceNameLength)
366 return CHIP_ERROR_INVALID_ARGUMENT;
368 strcpy(mDeviceName, deviceName);
369 mFlags.Set(Flags::kDeviceNameSet);
370 ChipLogProgress(DeviceLayer, "Setting device name to : \"%s\"", deviceName);
371 static_assert(kMaxDeviceNameLength <= UINT16_MAX, "deviceName length might not fit in a uint8_t");
372 ret = sl_bt_gatt_server_write_attribute_value(gattdb_device_name, 0, strlen(deviceName), (uint8_t *) deviceName);
373 if (ret != SL_STATUS_OK)
375 err = MapBLEError(ret);
376 ChipLogError(DeviceLayer, "sl_bt_gatt_server_write_attribute_value() failed: %s", ErrorStr(err));
384 return CHIP_NO_ERROR;
387 void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event)
391 case DeviceEventType::kCHIPoBLESubscribe: {
392 ChipDeviceEvent connEstEvent;
394 ChipLogProgress(DeviceLayer, "_OnPlatformEvent kCHIPoBLESubscribe");
395 HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX);
396 connEstEvent.Type = DeviceEventType::kCHIPoBLEConnectionEstablished;
397 PlatformMgr().PostEvent(&connEstEvent);
401 case DeviceEventType::kCHIPoBLEUnsubscribe: {
402 ChipLogProgress(DeviceLayer, "_OnPlatformEvent kCHIPoBLEUnsubscribe");
403 HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX);
407 case DeviceEventType::kCHIPoBLEWriteReceived: {
408 ChipLogProgress(DeviceLayer, "_OnPlatformEvent kCHIPoBLEWriteReceived");
409 HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_RX,
410 PacketBufferHandle::Adopt(event->CHIPoBLEWriteReceived.Data));
414 case DeviceEventType::kCHIPoBLEConnectionError: {
415 ChipLogProgress(DeviceLayer, "_OnPlatformEvent kCHIPoBLEConnectionError");
416 HandleConnectionError(event->CHIPoBLEConnectionError.ConId, event->CHIPoBLEConnectionError.Reason);
420 case DeviceEventType::kCHIPoBLEIndicateConfirm: {
421 ChipLogProgress(DeviceLayer, "_OnPlatformEvent kCHIPoBLEIndicateConfirm");
422 HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX);
427 ChipLogProgress(DeviceLayer, "_OnPlatformEvent default: event->Type = %d", event->Type);
432 bool BLEManagerImpl::SubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId)
434 ChipLogProgress(DeviceLayer, "BLEManagerImpl::SubscribeCharacteristic() not supported");
438 bool BLEManagerImpl::UnsubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId)
440 ChipLogProgress(DeviceLayer, "BLEManagerImpl::UnsubscribeCharacteristic() not supported");
444 bool BLEManagerImpl::CloseConnection(BLE_CONNECTION_OBJECT conId)
446 CHIP_ERROR err = CHIP_NO_ERROR;
449 ChipLogProgress(DeviceLayer, "Closing BLE GATT connection (con %u)", conId);
451 ret = sl_bt_connection_close(conId);
452 err = MapBLEError(ret);
454 if (err != CHIP_NO_ERROR)
456 ChipLogError(DeviceLayer, "sl_bt_connection_close() failed: %s", ErrorStr(err));
459 return (err == CHIP_NO_ERROR);
462 uint16_t BLEManagerImpl::GetMTU(BLE_CONNECTION_OBJECT conId) const
464 CHIPoBLEConState * conState = const_cast<BLEManagerImpl *>(this)->GetConnectionState(conId);
465 return (conState != NULL) ? conState->mtu : 0;
468 bool BLEManagerImpl::SendIndication(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId,
469 PacketBufferHandle data)
471 CHIP_ERROR err = CHIP_NO_ERROR;
472 CHIPoBLEConState * conState = GetConnectionState(conId);
474 uint16_t cId = (UUIDsMatch(&ChipUUID_CHIPoBLEChar_RX, charId) ? gattdb_CHIPoBLEChar_Rx : gattdb_CHIPoBLEChar_Tx);
475 uint8_t timerHandle = GetTimerHandle(conId, true);
477 VerifyOrExit(((conState != NULL) && (conState->subscribed != 0)), err = CHIP_ERROR_INVALID_ARGUMENT);
478 VerifyOrExit(timerHandle != kMaxConnections, err = CHIP_ERROR_NO_MEMORY);
480 // start timer for light indication confirmation. Long delay for spake2 indication
481 sl_bt_system_set_soft_timer(TIMER_S_2_TIMERTICK(6), timerHandle, true);
483 ret = sl_bt_gatt_server_send_indication(conId, cId, (data->DataLength()), data->Start());
485 err = MapBLEError(ret);
488 if (err != CHIP_NO_ERROR)
490 ChipLogError(DeviceLayer, "BLEManagerImpl::SendIndication() failed: %s", ErrorStr(err));
496 bool BLEManagerImpl::SendWriteRequest(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId,
497 PacketBufferHandle pBuf)
499 ChipLogProgress(DeviceLayer, "BLEManagerImpl::SendWriteRequest() not supported");
503 bool BLEManagerImpl::SendReadRequest(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId,
504 PacketBufferHandle pBuf)
506 ChipLogProgress(DeviceLayer, "BLEManagerImpl::SendReadRequest() not supported");
510 bool BLEManagerImpl::SendReadResponse(BLE_CONNECTION_OBJECT conId, BLE_READ_REQUEST_CONTEXT requestContext,
511 const ChipBleUUID * svcId, const ChipBleUUID * charId)
513 ChipLogProgress(DeviceLayer, "BLEManagerImpl::SendReadResponse() not supported");
517 void BLEManagerImpl::NotifyChipConnectionClosed(BLE_CONNECTION_OBJECT conId)
522 CHIP_ERROR BLEManagerImpl::MapBLEError(int bleErr)
527 return CHIP_NO_ERROR;
528 case SL_STATUS_BT_ATT_INVALID_ATT_LENGTH:
529 return CHIP_ERROR_INVALID_STRING_LENGTH;
530 case SL_STATUS_INVALID_PARAMETER:
531 return CHIP_ERROR_INVALID_ARGUMENT;
533 return (CHIP_ERROR) bleErr + CHIP_DEVICE_CONFIG_EFR32_BLE_ERROR_MIN;
537 void BLEManagerImpl::DriveBLEState(void)
539 CHIP_ERROR err = CHIP_NO_ERROR;
541 // Check if BLE stack is initialized
542 VerifyOrExit(mFlags.Has(Flags::kEFRBLEStackInitialized), /* */);
544 // Start advertising if needed...
545 if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && mFlags.Has(Flags::kAdvertisingEnabled))
547 // Start/re-start advertising if not already started, or if there is a pending change
548 // to the advertising configuration.
549 if (!mFlags.Has(Flags::kAdvertising) || mFlags.Has(Flags::kRestartAdvertising))
551 err = StartAdvertising();
556 // Otherwise, stop advertising if it is enabled.
557 else if (mFlags.Has(Flags::kAdvertising))
559 err = StopAdvertising();
564 if (err != CHIP_NO_ERROR)
566 ChipLogError(DeviceLayer, "Disabling CHIPoBLE service due to error: %s", ErrorStr(err));
567 mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Disabled;
571 CHIP_ERROR BLEManagerImpl::ConfigureAdvertisingData(void)
574 ChipBLEDeviceIdentificationInfo mDeviceIdInfo;
576 uint8_t responseData[MAX_RESPONSE_DATA_LEN];
577 uint8_t advData[MAX_ADV_DATA_LEN];
579 uint32_t mDeviceNameLength = 0;
580 uint8_t mDeviceIdInfoLength = 0;
582 VerifyOrExit((kMaxDeviceNameLength + 1) < UINT8_MAX, err = CHIP_ERROR_INVALID_ARGUMENT);
584 memset(responseData, 0, MAX_RESPONSE_DATA_LEN);
585 memset(advData, 0, MAX_ADV_DATA_LEN);
587 err = ConfigurationMgr().GetBLEDeviceIdentificationInfo(mDeviceIdInfo);
590 if (!mFlags.Has(Flags::kDeviceNameSet))
592 snprintf(mDeviceName, sizeof(mDeviceName), "%s%04" PRIX32, CHIP_DEVICE_CONFIG_BLE_DEVICE_NAME_PREFIX, (uint32_t) 0);
594 mDeviceName[kMaxDeviceNameLength] = 0;
595 mDeviceNameLength = strlen(mDeviceName);
597 VerifyOrExit(mDeviceNameLength < kMaxDeviceNameLength, err = CHIP_ERROR_INVALID_ARGUMENT);
599 ret = sl_bt_gatt_server_write_attribute_value(gattdb_device_name, 0, mDeviceNameLength, (uint8_t *) mDeviceName);
600 if (ret != SL_STATUS_OK)
602 err = MapBLEError(ret);
603 ChipLogError(DeviceLayer, "sl_bt_gatt_server_write_attribute_value() failed: %s", ErrorStr(err));
608 mDeviceNameLength = strlen(mDeviceName); // Device Name length + length field
609 VerifyOrExit(mDeviceNameLength < kMaxDeviceNameLength, err = CHIP_ERROR_INVALID_ARGUMENT);
611 mDeviceIdInfoLength = sizeof(mDeviceIdInfo); // Servicedatalen + length+ UUID (Short)
612 static_assert(sizeof(mDeviceIdInfo) + CHIP_ADV_SHORT_UUID_LEN + 1 <= UINT8_MAX, "Our length won't fit in a uint8_t");
613 static_assert(2 + CHIP_ADV_SHORT_UUID_LEN + sizeof(mDeviceIdInfo) + 1 <= MAX_ADV_DATA_LEN, "Our buffer is not big enough");
616 advData[index++] = 0x02; // length
617 advData[index++] = CHIP_ADV_DATA_TYPE_FLAGS; // AD type : flags
618 advData[index++] = CHIP_ADV_DATA_FLAGS; // AD value
619 advData[index++] = static_cast<uint8_t>(mDeviceIdInfoLength + CHIP_ADV_SHORT_UUID_LEN + 1); // AD length
620 advData[index++] = CHIP_ADV_DATA_TYPE_SERVICE_DATA; // AD type : Service Data
621 advData[index++] = ShortUUID_CHIPoBLEService[0]; // AD value
622 advData[index++] = ShortUUID_CHIPoBLEService[1];
623 memcpy(&advData[index], (void *) &mDeviceIdInfo, mDeviceIdInfoLength); // AD value
624 index += mDeviceIdInfoLength;
626 advData[index++] = static_cast<uint8_t>(mDeviceNameLength + 1); // length
627 advData[index++] = CHIP_ADV_DATA_TYPE_NAME; // AD type : name
628 memcpy(&advData[index], mDeviceName, mDeviceNameLength); // AD value
629 index += mDeviceNameLength;
631 if (0xff != advertising_set_handle)
633 sl_bt_advertiser_delete_set(advertising_set_handle);
634 advertising_set_handle = 0xff;
637 ret = sl_bt_advertiser_create_set(&advertising_set_handle);
638 if (ret != SL_STATUS_OK)
640 err = MapBLEError(ret);
641 ChipLogError(DeviceLayer, "sl_bt_advertiser_create_set() failed: %s", ErrorStr(err));
644 ret = sl_bt_advertiser_set_data(advertising_set_handle, CHIP_ADV_DATA, index, (uint8_t *) advData);
646 if (ret != SL_STATUS_OK)
648 err = MapBLEError(ret);
649 ChipLogError(DeviceLayer, "sl_bt_advertiser_set_data() failed: %s", ErrorStr(err));
655 responseData[index++] = CHIP_ADV_SHORT_UUID_LEN + 1; // AD length
656 responseData[index++] = CHIP_ADV_DATA_TYPE_UUID; // AD type : uuid
657 responseData[index++] = ShortUUID_CHIPoBLEService[0]; // AD value
658 responseData[index++] = ShortUUID_CHIPoBLEService[1];
660 ret = sl_bt_advertiser_set_data(advertising_set_handle, CHIP_ADV_SCAN_RESPONSE_DATA, index, (uint8_t *) responseData);
662 if (ret != SL_STATUS_OK)
664 err = MapBLEError(ret);
665 ChipLogError(DeviceLayer, "sl_bt_advertiser_set_data() failed: %s", ErrorStr(err));
669 err = MapBLEError(ret);
675 CHIP_ERROR BLEManagerImpl::StartAdvertising(void)
679 uint32_t interval_min;
680 uint32_t interval_max;
681 uint16_t numConnectionss = NumConnections();
682 uint8_t connectableAdv =
683 (numConnectionss < kMaxConnections) ? sl_bt_advertiser_connectable_scannable : sl_bt_advertiser_scannable_non_connectable;
685 err = ConfigureAdvertisingData();
688 mFlags.Clear(Flags::kRestartAdvertising);
690 interval_min = interval_max =
691 ((numConnectionss == 0 && !ConfigurationMgr().IsPairedToAccount()) || mFlags.Has(Flags::kFastAdvertisingEnabled))
692 ? CHIP_DEVICE_CONFIG_BLE_FAST_ADVERTISING_INTERVAL
693 : CHIP_DEVICE_CONFIG_BLE_SLOW_ADVERTISING_INTERVAL;
695 ret = sl_bt_advertiser_set_timing(advertising_set_handle, interval_min, interval_max, 0, 0);
696 err = MapBLEError(ret);
699 ret = sl_bt_advertiser_start(advertising_set_handle, sl_bt_advertiser_user_data, connectableAdv);
701 if (SL_STATUS_OK == ret)
703 mFlags.Set(Flags::kAdvertising);
706 err = MapBLEError(ret);
712 CHIP_ERROR BLEManagerImpl::StopAdvertising(void)
714 CHIP_ERROR err = CHIP_NO_ERROR;
717 if (mFlags.Has(Flags::kAdvertising))
719 mFlags.Clear(Flags::kAdvertising).Clear(Flags::kRestartAdvertising);
721 ret = sl_bt_advertiser_stop(advertising_set_handle);
722 sl_bt_advertiser_delete_set(advertising_set_handle);
723 advertising_set_handle = 0xff;
724 err = MapBLEError(ret);
732 void BLEManagerImpl::UpdateMtu(volatile sl_bt_msg_t * evt)
734 CHIPoBLEConState * bleConnState = GetConnectionState(evt->data.evt_gatt_mtu_exchanged.connection);
735 if (bleConnState != NULL)
737 // bleConnState->MTU is a 10-bit field inside a uint16_t. We're
738 // assigning to it from a uint16_t, and compilers warn about
739 // possibly not fitting. There's no way to suppress that warning
740 // via explicit cast; we have to disable the warning around the
743 // TODO: https://github.com/project-chip/connectedhomeip/issues/2569
744 // tracks making this safe with a check or explaining why no check
746 #pragma GCC diagnostic push
747 #pragma GCC diagnostic ignored "-Wconversion"
748 bleConnState->mtu = evt->data.evt_gatt_mtu_exchanged.mtu;
749 #pragma GCC diagnostic pop
754 void BLEManagerImpl::HandleBootEvent(void)
756 mFlags.Set(Flags::kEFRBLEStackInitialized);
757 PlatformMgr().ScheduleWork(DriveBLEState, 0);
760 void BLEManagerImpl::HandleConnectEvent(volatile sl_bt_msg_t * evt)
762 sl_bt_evt_connection_opened_t * conn_evt = (sl_bt_evt_connection_opened_t *) &(evt->data);
763 uint8_t connHandle = conn_evt->connection;
764 uint8_t bondingHandle = conn_evt->bonding;
766 ChipLogProgress(DeviceLayer, "Connect Event for handle : %d", connHandle);
768 AddConnection(connHandle, bondingHandle);
770 // mFlags.Set(Flags::kRestartAdvertising);
771 PlatformMgr().ScheduleWork(DriveBLEState, 0);
774 void BLEManagerImpl::HandleConnectionCloseEvent(volatile sl_bt_msg_t * evt)
776 sl_bt_evt_connection_closed_t * conn_evt = (sl_bt_evt_connection_closed_t *) &(evt->data);
777 uint8_t connHandle = conn_evt->connection;
779 ChipLogProgress(DeviceLayer, "Disconnect Event for handle : %d", connHandle);
781 if (RemoveConnection(connHandle))
783 ChipDeviceEvent event;
784 event.Type = DeviceEventType::kCHIPoBLEConnectionError;
785 event.CHIPoBLEConnectionError.ConId = connHandle;
787 switch (conn_evt->reason)
789 case bg_err_bt_remote_user_terminated:
790 case bg_err_bt_remote_device_terminated_connection_due_to_low_resources:
791 case bg_err_bt_remote_powering_off:
792 event.CHIPoBLEConnectionError.Reason = BLE_ERROR_REMOTE_DEVICE_DISCONNECTED;
795 case bg_err_bt_connection_terminated_by_local_host:
796 event.CHIPoBLEConnectionError.Reason = BLE_ERROR_APP_CLOSED_CONNECTION;
800 event.CHIPoBLEConnectionError.Reason = BLE_ERROR_CHIPOBLE_PROTOCOL_ABORT;
804 ChipLogProgress(DeviceLayer, "BLE GATT connection closed (con %u, reason %u)", connHandle, conn_evt->reason);
806 PlatformMgr().PostEvent(&event);
808 // Arrange to re-enable connectable advertising in case it was disabled due to the
809 // maximum connection limit being reached.
810 mFlags.Set(Flags::kRestartAdvertising);
811 PlatformMgr().ScheduleWork(DriveBLEState, 0);
815 void BLEManagerImpl::HandleWriteEvent(volatile sl_bt_msg_t * evt)
817 uint16_t attribute = evt->data.evt_gatt_server_user_write_request.characteristic;
819 ChipLogProgress(DeviceLayer, "Char Write Req, char : %d", attribute);
821 if (gattdb_CHIPoBLEChar_Rx == attribute)
823 HandleRXCharWrite(evt);
827 void BLEManagerImpl::HandleTXCharCCCDWrite(volatile sl_bt_msg_t * evt)
829 CHIP_ERROR err = CHIP_NO_ERROR;
830 CHIPoBLEConState * bleConnState;
831 bool indicationsEnabled;
832 ChipDeviceEvent event;
834 bleConnState = GetConnectionState(evt->data.evt_gatt_server_user_write_request.connection);
836 VerifyOrExit(bleConnState != NULL, err = CHIP_ERROR_NO_MEMORY);
838 // Determine if the client is enabling or disabling indications.
839 indicationsEnabled = (evt->data.evt_gatt_server_characteristic_status.client_config_flags == gatt_indication);
841 ChipLogProgress(DeviceLayer, "CHIPoBLE %s received", indicationsEnabled ? "subscribe" : "unsubscribe");
843 if (indicationsEnabled)
845 // If indications are not already enabled for the connection...
846 if (!bleConnState->subscribed)
848 bleConnState->subscribed = 1;
849 // Post an event to the CHIP queue to process either a CHIPoBLE Subscribe or Unsubscribe based on
850 // whether the client is enabling or disabling indications.
852 event.Type = DeviceEventType::kCHIPoBLESubscribe;
853 event.CHIPoBLESubscribe.ConId = evt->data.evt_gatt_server_user_write_request.connection;
854 PlatformMgr().PostEvent(&event);
860 bleConnState->subscribed = 0;
861 event.Type = DeviceEventType::kCHIPoBLEUnsubscribe;
862 event.CHIPoBLESubscribe.ConId = evt->data.evt_gatt_server_user_write_request.connection;
863 PlatformMgr().PostEvent(&event);
867 if (err != CHIP_NO_ERROR)
869 ChipLogError(DeviceLayer, "HandleTXCharCCCDWrite() failed: %s", ErrorStr(err));
873 void BLEManagerImpl::HandleRXCharWrite(volatile sl_bt_msg_t * evt)
875 CHIP_ERROR err = CHIP_NO_ERROR;
876 System::PacketBufferHandle buf;
877 uint16_t writeLen = evt->data.evt_gatt_server_user_write_request.value.len;
878 uint8_t * data = (uint8_t *) evt->data.evt_gatt_server_user_write_request.value.data;
880 // Copy the data to a packet buffer.
881 buf = System::PacketBufferHandle::NewWithData(data, writeLen, 0, 0);
882 VerifyOrExit(!buf.IsNull(), err = CHIP_ERROR_NO_MEMORY);
884 ChipLogDetail(DeviceLayer, "Write request/command received for CHIPoBLE RX characteristic (con %" PRIu16 ", len %" PRIu16 ")",
885 evt->data.evt_gatt_server_user_write_request.connection, buf->DataLength());
887 // Post an event to the CHIP queue to deliver the data into the CHIP stack.
889 ChipDeviceEvent event;
890 event.Type = DeviceEventType::kCHIPoBLEWriteReceived;
891 event.CHIPoBLEWriteReceived.ConId = evt->data.evt_gatt_server_user_write_request.connection;
892 event.CHIPoBLEWriteReceived.Data = std::move(buf).UnsafeRelease();
893 PlatformMgr().PostEvent(&event);
897 if (err != CHIP_NO_ERROR)
899 ChipLogError(DeviceLayer, "HandleRXCharWrite() failed: %s", ErrorStr(err));
903 void BLEManagerImpl::HandleTxConfirmationEvent(volatile sl_bt_msg_t * evt)
905 ChipDeviceEvent event;
906 uint8_t timerHandle = sInstance.GetTimerHandle(evt->data.evt_gatt_server_characteristic_status.connection);
908 ChipLogProgress(DeviceLayer, "Tx Confirmation received");
910 // stop indication confirmation timer
911 if (timerHandle < kMaxConnections)
913 ChipLogProgress(DeviceLayer, " stop soft timer");
914 sl_bt_system_set_soft_timer(0, timerHandle, false);
917 event.Type = DeviceEventType::kCHIPoBLEIndicateConfirm;
918 event.CHIPoBLEIndicateConfirm.ConId = evt->data.evt_gatt_server_characteristic_status.connection;
919 PlatformMgr().PostEvent(&event);
922 void BLEManagerImpl::HandleSoftTimerEvent(volatile sl_bt_msg_t * evt)
924 // BLE Manager starts soft timers with timer handles less than kMaxConnections
925 // If we receive a callback for unknown timer handle ignore this.
926 if (evt->data.evt_system_soft_timer.handle < kMaxConnections)
928 ChipLogProgress(DeviceLayer, "BLEManagerImpl::HandleSoftTimerEvent CHIPOBLE_PROTOCOL_ABORT");
929 ChipDeviceEvent event;
930 event.Type = DeviceEventType::kCHIPoBLEConnectionError;
931 event.CHIPoBLEConnectionError.ConId = mIndConfId[evt->data.evt_system_soft_timer.handle];
932 sInstance.mIndConfId[evt->data.evt_system_soft_timer.handle] = kUnusedIndex;
933 event.CHIPoBLEConnectionError.Reason = BLE_ERROR_CHIPOBLE_PROTOCOL_ABORT;
934 PlatformMgr().PostEvent(&event);
938 bool BLEManagerImpl::RemoveConnection(uint8_t connectionHandle)
940 CHIPoBLEConState * bleConnState = GetConnectionState(connectionHandle, true);
943 if (bleConnState != NULL)
945 memset(bleConnState, 0, sizeof(CHIPoBLEConState));
952 void BLEManagerImpl::AddConnection(uint8_t connectionHandle, uint8_t bondingHandle)
954 CHIPoBLEConState * bleConnState = GetConnectionState(connectionHandle, true);
956 if (bleConnState != NULL)
958 memset(bleConnState, 0, sizeof(CHIPoBLEConState));
959 bleConnState->allocated = 1;
960 bleConnState->connectionHandle = connectionHandle;
961 bleConnState->bondingHandle = bondingHandle;
965 BLEManagerImpl::CHIPoBLEConState * BLEManagerImpl::GetConnectionState(uint8_t connectionHandle, bool allocate)
967 uint8_t freeIndex = kMaxConnections;
969 for (uint8_t i = 0; i < kMaxConnections; i++)
971 if (mBleConnections[i].allocated == 1)
973 if (mBleConnections[i].connectionHandle == connectionHandle)
975 return &mBleConnections[i];
979 else if (i < freeIndex)
987 if (freeIndex < kMaxConnections)
989 return &mBleConnections[freeIndex];
992 ChipLogError(DeviceLayer, "Failed to allocate CHIPoBLEConState");
998 uint8_t BLEManagerImpl::GetTimerHandle(uint8_t connectionHandle, bool allocate)
1000 uint8_t freeIndex = kMaxConnections;
1002 for (uint8_t i = 0; i < kMaxConnections; i++)
1004 if (mIndConfId[i] == connectionHandle)
1017 if (freeIndex < kMaxConnections)
1019 mIndConfId[freeIndex] = connectionHandle;
1023 ChipLogError(DeviceLayer, "Failed to Save Conn Handle for indication");
1029 void BLEManagerImpl::DriveBLEState(intptr_t arg)
1031 sInstance.DriveBLEState();
1034 } // namespace Internal
1035 } // namespace DeviceLayer
1037 #endif // CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE