Apply Upstream code (2021-03-15)
[platform/upstream/connectedhomeip.git] / src / platform / EFR32 / BLEManagerImpl.cpp
1 /*
2  *
3  *    Copyright (c) 2020-2021 Project CHIP Authors
4  *    Copyright (c) 2019 Nest Labs, Inc.
5  *
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
9  *
10  *        http://www.apache.org/licenses/LICENSE-2.0
11  *
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.
17  */
18
19 /**
20  *    @file
21  *          Provides an implementation of the BLEManager singleton object
22  *          for the Silicon Labs EFR32 platforms.
23  */
24
25 /* this file behaves like a config.h, comes first */
26 #include <platform/internal/CHIPDeviceLayerInternal.h>
27 #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE
28
29 #include <platform/internal/BLEManager.h>
30
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>
38
39 using namespace ::chip;
40 using namespace ::chip::Ble;
41
42 namespace chip {
43 namespace DeviceLayer {
44 namespace Internal {
45
46 namespace {
47
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
52
53 #define CHIP_ADV_DATA_FLAGS 0x06
54
55 #define CHIP_ADV_DATA 0
56 #define CHIP_ADV_SCAN_RESPONSE_DATA 1
57 #define CHIP_ADV_SHORT_UUID_LEN 2
58
59 #define MAX_RESPONSE_DATA_LEN 31
60 #define MAX_ADV_DATA_LEN 31
61
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)
67
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)
76
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;
80
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,
85                                                  0x9D, 0x11 } };
86 const ChipBleUUID ChipUUID_CHIPoBLEChar_TX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F,
87                                                  0x9D, 0x12 } };
88
89 } // namespace
90
91 BLEManagerImpl BLEManagerImpl::sInstance;
92
93 /***************************************************************************/
94 /**
95  * Setup the bluetooth init function.
96  *
97  * @return none
98  *
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()
104 {
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();
116     return ret;
117 }
118
119 static void initBleConfig(void)
120 {
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;
135 #if (HAL_PA_ENABLE)
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 */
139 #else
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)
143 }
144
145 CHIP_ERROR BLEManagerImpl::_Init()
146 {
147     CHIP_ERROR err;
148     sl_status_t ret;
149
150     // Initialize the CHIP BleLayer.
151     err = BleLayer::Init(this, this, &SystemLayer);
152     SuccessOrExit(err);
153
154     memset(mBleConnections, 0, sizeof(mBleConnections));
155     memset(mIndConfId, kUnusedIndex, sizeof(mIndConfId));
156     mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Enabled;
157
158     initBleConfig();
159
160     // Start Bluetooth Link Layer and stack tasks
161     ret =
162         bluetooth_start(CHIP_DEVICE_CONFIG_BLE_LL_TASK_PRIORITY, CHIP_DEVICE_CONFIG_BLE_STACK_TASK_PRIORITY, initialize_bluetooth);
163
164     VerifyOrExit(ret == bg_err_success, err = MapBLEError(ret));
165
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. */
173
174     mFlags.ClearAll().Set(Flags::kAdvertisingEnabled, CHIP_DEVICE_CONFIG_CHIPOBLE_ENABLE_ADVERTISING_AUTOSTART);
175     PlatformMgr().ScheduleWork(DriveBLEState, 0);
176
177 exit:
178     return err;
179 }
180
181 uint16_t BLEManagerImpl::_NumConnections(void)
182 {
183     uint16_t numCons = 0;
184     for (uint16_t i = 0; i < kMaxConnections; i++)
185     {
186         if (mBleConnections[i].allocated)
187         {
188             numCons++;
189         }
190     }
191
192     return numCons;
193 }
194
195 void BLEManagerImpl::bluetoothStackEventHandler(void * p_arg)
196 {
197     EventBits_t flags = 0;
198
199     while (1)
200     {
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 */
207
208         if (flags & BLUETOOTH_EVENT_FLAG_EVT_WAITING)
209         {
210             flags &= ~BLUETOOTH_EVENT_FLAG_EVT_WAITING;
211             xEventGroupClearBits(bluetooth_event_flags, BLUETOOTH_EVENT_FLAG_EVT_WAITING);
212
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();
216
217             // handle bluetooth events
218             switch (SL_BT_MSG_ID(bluetooth_evt->header))
219             {
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();
225             }
226             break;
227
228             case sl_bt_evt_connection_opened_id: {
229                 sInstance.HandleConnectEvent(bluetooth_evt);
230             }
231             break;
232             case sl_bt_evt_connection_parameters_id: {
233                 // ChipLogProgress(DeviceLayer, "Connection parameter ID received. Nothing to do");
234             }
235             break;
236             case sl_bt_evt_connection_phy_status_id: {
237                 // ChipLogProgress(DeviceLayer, "PHY update procedure is completed");
238             }
239             break;
240             case sl_bt_evt_connection_closed_id: {
241                 sInstance.HandleConnectionCloseEvent(bluetooth_evt);
242             }
243             break;
244
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);
250             }
251             break;
252
253             case sl_bt_evt_gatt_mtu_exchanged_id: {
254                 sInstance.UpdateMtu(bluetooth_evt);
255             }
256             break;
257
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;
261
262                 StatusFlags = (sl_bt_gatt_server_characteristic_status_flag_t)
263                                   bluetooth_evt->data.evt_gatt_server_characteristic_status.status_flags;
264
265                 if (sl_bt_gatt_server_confirmation == StatusFlags)
266                 {
267                     sInstance.HandleTxConfirmationEvent(bluetooth_evt);
268                 }
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))
271                 {
272                     sInstance.HandleTXCharCCCDWrite(bluetooth_evt);
273                 }
274             }
275             break;
276
277             /* Software Timer event */
278             case sl_bt_evt_system_soft_timer_id: {
279                 sInstance.HandleSoftTimerEvent(bluetooth_evt);
280             }
281             break;
282
283             default:
284                 ChipLogProgress(DeviceLayer, "evt_UNKNOWN id = %08x", SL_BT_MSG_ID(bluetooth_evt->header));
285                 break;
286             }
287         }
288
289         PlatformMgr().UnlockChipStack();
290
291         vRaiseEventFlagBasedOnContext(bluetooth_event_flags, BLUETOOTH_EVENT_FLAG_EVT_HANDLED);
292     }
293 }
294
295 CHIP_ERROR BLEManagerImpl::_SetCHIPoBLEServiceMode(CHIPoBLEServiceMode val)
296 {
297     CHIP_ERROR err = CHIP_NO_ERROR;
298
299     VerifyOrExit(val != ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, err = CHIP_ERROR_INVALID_ARGUMENT);
300     VerifyOrExit(mServiceMode != ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE);
301
302     if (val != mServiceMode)
303     {
304         mServiceMode = val;
305         PlatformMgr().ScheduleWork(DriveBLEState, 0);
306     }
307
308 exit:
309     return err;
310 }
311
312 CHIP_ERROR BLEManagerImpl::_SetAdvertisingEnabled(bool val)
313 {
314     CHIP_ERROR err = CHIP_NO_ERROR;
315
316     VerifyOrExit(mServiceMode != ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE);
317
318     if (mFlags.Has(Flags::kAdvertisingEnabled) != val)
319     {
320         mFlags.Set(Flags::kAdvertisingEnabled, val);
321         PlatformMgr().ScheduleWork(DriveBLEState, 0);
322     }
323
324 exit:
325     return err;
326 }
327
328 CHIP_ERROR BLEManagerImpl::_SetFastAdvertisingEnabled(bool val)
329 {
330     CHIP_ERROR err = CHIP_NO_ERROR;
331
332     VerifyOrExit(mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE);
333
334     if (mFlags.Has(Flags::kFastAdvertisingEnabled) != val)
335     {
336         mFlags.Set(Flags::kFastAdvertisingEnabled, val);
337         PlatformMgr().ScheduleWork(DriveBLEState, 0);
338     }
339
340 exit:
341     return err;
342 }
343
344 CHIP_ERROR BLEManagerImpl::_GetDeviceName(char * buf, size_t bufSize)
345 {
346     if (strlen(mDeviceName) >= bufSize)
347     {
348         return CHIP_ERROR_BUFFER_TOO_SMALL;
349     }
350     strcpy(buf, mDeviceName);
351     return CHIP_NO_ERROR;
352 }
353
354 CHIP_ERROR BLEManagerImpl::_SetDeviceName(const char * deviceName)
355 {
356     sl_status_t ret;
357     CHIP_ERROR err = CHIP_NO_ERROR;
358     if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_NotSupported)
359     {
360         return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;
361     }
362     if (deviceName != NULL && deviceName[0] != 0)
363     {
364         if (strlen(deviceName) >= kMaxDeviceNameLength)
365         {
366             return CHIP_ERROR_INVALID_ARGUMENT;
367         }
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)
374         {
375             err = MapBLEError(ret);
376             ChipLogError(DeviceLayer, "sl_bt_gatt_server_write_attribute_value() failed: %s", ErrorStr(err));
377             return err;
378         }
379     }
380     else
381     {
382         mDeviceName[0] = 0;
383     }
384     return CHIP_NO_ERROR;
385 }
386
387 void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event)
388 {
389     switch (event->Type)
390     {
391     case DeviceEventType::kCHIPoBLESubscribe: {
392         ChipDeviceEvent connEstEvent;
393
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);
398     }
399     break;
400
401     case DeviceEventType::kCHIPoBLEUnsubscribe: {
402         ChipLogProgress(DeviceLayer, "_OnPlatformEvent kCHIPoBLEUnsubscribe");
403         HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX);
404     }
405     break;
406
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));
411     }
412     break;
413
414     case DeviceEventType::kCHIPoBLEConnectionError: {
415         ChipLogProgress(DeviceLayer, "_OnPlatformEvent kCHIPoBLEConnectionError");
416         HandleConnectionError(event->CHIPoBLEConnectionError.ConId, event->CHIPoBLEConnectionError.Reason);
417     }
418     break;
419
420     case DeviceEventType::kCHIPoBLEIndicateConfirm: {
421         ChipLogProgress(DeviceLayer, "_OnPlatformEvent kCHIPoBLEIndicateConfirm");
422         HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX);
423     }
424     break;
425
426     default:
427         ChipLogProgress(DeviceLayer, "_OnPlatformEvent default:  event->Type = %d", event->Type);
428         break;
429     }
430 }
431
432 bool BLEManagerImpl::SubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId)
433 {
434     ChipLogProgress(DeviceLayer, "BLEManagerImpl::SubscribeCharacteristic() not supported");
435     return false;
436 }
437
438 bool BLEManagerImpl::UnsubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId)
439 {
440     ChipLogProgress(DeviceLayer, "BLEManagerImpl::UnsubscribeCharacteristic() not supported");
441     return false;
442 }
443
444 bool BLEManagerImpl::CloseConnection(BLE_CONNECTION_OBJECT conId)
445 {
446     CHIP_ERROR err = CHIP_NO_ERROR;
447     sl_status_t ret;
448
449     ChipLogProgress(DeviceLayer, "Closing BLE GATT connection (con %u)", conId);
450
451     ret = sl_bt_connection_close(conId);
452     err = MapBLEError(ret);
453
454     if (err != CHIP_NO_ERROR)
455     {
456         ChipLogError(DeviceLayer, "sl_bt_connection_close() failed: %s", ErrorStr(err));
457     }
458
459     return (err == CHIP_NO_ERROR);
460 }
461
462 uint16_t BLEManagerImpl::GetMTU(BLE_CONNECTION_OBJECT conId) const
463 {
464     CHIPoBLEConState * conState = const_cast<BLEManagerImpl *>(this)->GetConnectionState(conId);
465     return (conState != NULL) ? conState->mtu : 0;
466 }
467
468 bool BLEManagerImpl::SendIndication(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId,
469                                     PacketBufferHandle data)
470 {
471     CHIP_ERROR err              = CHIP_NO_ERROR;
472     CHIPoBLEConState * conState = GetConnectionState(conId);
473     sl_status_t ret;
474     uint16_t cId        = (UUIDsMatch(&ChipUUID_CHIPoBLEChar_RX, charId) ? gattdb_CHIPoBLEChar_Rx : gattdb_CHIPoBLEChar_Tx);
475     uint8_t timerHandle = GetTimerHandle(conId, true);
476
477     VerifyOrExit(((conState != NULL) && (conState->subscribed != 0)), err = CHIP_ERROR_INVALID_ARGUMENT);
478     VerifyOrExit(timerHandle != kMaxConnections, err = CHIP_ERROR_NO_MEMORY);
479
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);
482
483     ret = sl_bt_gatt_server_send_indication(conId, cId, (data->DataLength()), data->Start());
484
485     err = MapBLEError(ret);
486
487 exit:
488     if (err != CHIP_NO_ERROR)
489     {
490         ChipLogError(DeviceLayer, "BLEManagerImpl::SendIndication() failed: %s", ErrorStr(err));
491         return false;
492     }
493     return true;
494 }
495
496 bool BLEManagerImpl::SendWriteRequest(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId,
497                                       PacketBufferHandle pBuf)
498 {
499     ChipLogProgress(DeviceLayer, "BLEManagerImpl::SendWriteRequest() not supported");
500     return false;
501 }
502
503 bool BLEManagerImpl::SendReadRequest(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId,
504                                      PacketBufferHandle pBuf)
505 {
506     ChipLogProgress(DeviceLayer, "BLEManagerImpl::SendReadRequest() not supported");
507     return false;
508 }
509
510 bool BLEManagerImpl::SendReadResponse(BLE_CONNECTION_OBJECT conId, BLE_READ_REQUEST_CONTEXT requestContext,
511                                       const ChipBleUUID * svcId, const ChipBleUUID * charId)
512 {
513     ChipLogProgress(DeviceLayer, "BLEManagerImpl::SendReadResponse() not supported");
514     return false;
515 }
516
517 void BLEManagerImpl::NotifyChipConnectionClosed(BLE_CONNECTION_OBJECT conId)
518 {
519     // Nothing to do
520 }
521
522 CHIP_ERROR BLEManagerImpl::MapBLEError(int bleErr)
523 {
524     switch (bleErr)
525     {
526     case SL_STATUS_OK:
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;
532     default:
533         return (CHIP_ERROR) bleErr + CHIP_DEVICE_CONFIG_EFR32_BLE_ERROR_MIN;
534     }
535 }
536
537 void BLEManagerImpl::DriveBLEState(void)
538 {
539     CHIP_ERROR err = CHIP_NO_ERROR;
540
541     // Check if BLE stack is initialized
542     VerifyOrExit(mFlags.Has(Flags::kEFRBLEStackInitialized), /* */);
543
544     // Start advertising if needed...
545     if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && mFlags.Has(Flags::kAdvertisingEnabled))
546     {
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))
550         {
551             err = StartAdvertising();
552             SuccessOrExit(err);
553         }
554     }
555
556     // Otherwise, stop advertising if it is enabled.
557     else if (mFlags.Has(Flags::kAdvertising))
558     {
559         err = StopAdvertising();
560         SuccessOrExit(err);
561     }
562
563 exit:
564     if (err != CHIP_NO_ERROR)
565     {
566         ChipLogError(DeviceLayer, "Disabling CHIPoBLE service due to error: %s", ErrorStr(err));
567         mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Disabled;
568     }
569 }
570
571 CHIP_ERROR BLEManagerImpl::ConfigureAdvertisingData(void)
572 {
573     sl_status_t ret;
574     ChipBLEDeviceIdentificationInfo mDeviceIdInfo;
575     CHIP_ERROR err;
576     uint8_t responseData[MAX_RESPONSE_DATA_LEN];
577     uint8_t advData[MAX_ADV_DATA_LEN];
578     uint32_t index              = 0;
579     uint32_t mDeviceNameLength  = 0;
580     uint8_t mDeviceIdInfoLength = 0;
581
582     VerifyOrExit((kMaxDeviceNameLength + 1) < UINT8_MAX, err = CHIP_ERROR_INVALID_ARGUMENT);
583
584     memset(responseData, 0, MAX_RESPONSE_DATA_LEN);
585     memset(advData, 0, MAX_ADV_DATA_LEN);
586
587     err = ConfigurationMgr().GetBLEDeviceIdentificationInfo(mDeviceIdInfo);
588     SuccessOrExit(err);
589
590     if (!mFlags.Has(Flags::kDeviceNameSet))
591     {
592         snprintf(mDeviceName, sizeof(mDeviceName), "%s%04" PRIX32, CHIP_DEVICE_CONFIG_BLE_DEVICE_NAME_PREFIX, (uint32_t) 0);
593
594         mDeviceName[kMaxDeviceNameLength] = 0;
595         mDeviceNameLength                 = strlen(mDeviceName);
596
597         VerifyOrExit(mDeviceNameLength < kMaxDeviceNameLength, err = CHIP_ERROR_INVALID_ARGUMENT);
598
599         ret = sl_bt_gatt_server_write_attribute_value(gattdb_device_name, 0, mDeviceNameLength, (uint8_t *) mDeviceName);
600         if (ret != SL_STATUS_OK)
601         {
602             err = MapBLEError(ret);
603             ChipLogError(DeviceLayer, "sl_bt_gatt_server_write_attribute_value() failed: %s", ErrorStr(err));
604             return err;
605         }
606     }
607
608     mDeviceNameLength = strlen(mDeviceName); // Device Name length + length field
609     VerifyOrExit(mDeviceNameLength < kMaxDeviceNameLength, err = CHIP_ERROR_INVALID_ARGUMENT);
610
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");
614
615     index            = 0;
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;
625
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;
630
631     if (0xff != advertising_set_handle)
632     {
633         sl_bt_advertiser_delete_set(advertising_set_handle);
634         advertising_set_handle = 0xff;
635     }
636
637     ret = sl_bt_advertiser_create_set(&advertising_set_handle);
638     if (ret != SL_STATUS_OK)
639     {
640         err = MapBLEError(ret);
641         ChipLogError(DeviceLayer, "sl_bt_advertiser_create_set() failed: %s", ErrorStr(err));
642         ExitNow();
643     }
644     ret = sl_bt_advertiser_set_data(advertising_set_handle, CHIP_ADV_DATA, index, (uint8_t *) advData);
645
646     if (ret != SL_STATUS_OK)
647     {
648         err = MapBLEError(ret);
649         ChipLogError(DeviceLayer, "sl_bt_advertiser_set_data() failed: %s", ErrorStr(err));
650         ExitNow();
651     }
652
653     index = 0;
654
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];
659
660     ret = sl_bt_advertiser_set_data(advertising_set_handle, CHIP_ADV_SCAN_RESPONSE_DATA, index, (uint8_t *) responseData);
661
662     if (ret != SL_STATUS_OK)
663     {
664         err = MapBLEError(ret);
665         ChipLogError(DeviceLayer, "sl_bt_advertiser_set_data() failed: %s", ErrorStr(err));
666         ExitNow();
667     }
668
669     err = MapBLEError(ret);
670
671 exit:
672     return err;
673 }
674
675 CHIP_ERROR BLEManagerImpl::StartAdvertising(void)
676 {
677     CHIP_ERROR err;
678     sl_status_t ret;
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;
684
685     err = ConfigureAdvertisingData();
686     SuccessOrExit(err);
687
688     mFlags.Clear(Flags::kRestartAdvertising);
689
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;
694
695     ret = sl_bt_advertiser_set_timing(advertising_set_handle, interval_min, interval_max, 0, 0);
696     err = MapBLEError(ret);
697     SuccessOrExit(err);
698
699     ret = sl_bt_advertiser_start(advertising_set_handle, sl_bt_advertiser_user_data, connectableAdv);
700
701     if (SL_STATUS_OK == ret)
702     {
703         mFlags.Set(Flags::kAdvertising);
704     }
705
706     err = MapBLEError(ret);
707
708 exit:
709     return err;
710 }
711
712 CHIP_ERROR BLEManagerImpl::StopAdvertising(void)
713 {
714     CHIP_ERROR err = CHIP_NO_ERROR;
715     sl_status_t ret;
716
717     if (mFlags.Has(Flags::kAdvertising))
718     {
719         mFlags.Clear(Flags::kAdvertising).Clear(Flags::kRestartAdvertising);
720
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);
725         SuccessOrExit(err);
726     }
727
728 exit:
729     return err;
730 }
731
732 void BLEManagerImpl::UpdateMtu(volatile sl_bt_msg_t * evt)
733 {
734     CHIPoBLEConState * bleConnState = GetConnectionState(evt->data.evt_gatt_mtu_exchanged.connection);
735     if (bleConnState != NULL)
736     {
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
741         // assignment.
742         //
743         // TODO: https://github.com/project-chip/connectedhomeip/issues/2569
744         // tracks making this safe with a check or explaining why no check
745         // is needed.
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
750         ;
751     }
752 }
753
754 void BLEManagerImpl::HandleBootEvent(void)
755 {
756     mFlags.Set(Flags::kEFRBLEStackInitialized);
757     PlatformMgr().ScheduleWork(DriveBLEState, 0);
758 }
759
760 void BLEManagerImpl::HandleConnectEvent(volatile sl_bt_msg_t * evt)
761 {
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;
765
766     ChipLogProgress(DeviceLayer, "Connect Event for handle : %d", connHandle);
767
768     AddConnection(connHandle, bondingHandle);
769
770     // mFlags.Set(Flags::kRestartAdvertising);
771     PlatformMgr().ScheduleWork(DriveBLEState, 0);
772 }
773
774 void BLEManagerImpl::HandleConnectionCloseEvent(volatile sl_bt_msg_t * evt)
775 {
776     sl_bt_evt_connection_closed_t * conn_evt = (sl_bt_evt_connection_closed_t *) &(evt->data);
777     uint8_t connHandle                       = conn_evt->connection;
778
779     ChipLogProgress(DeviceLayer, "Disconnect Event for handle : %d", connHandle);
780
781     if (RemoveConnection(connHandle))
782     {
783         ChipDeviceEvent event;
784         event.Type                          = DeviceEventType::kCHIPoBLEConnectionError;
785         event.CHIPoBLEConnectionError.ConId = connHandle;
786
787         switch (conn_evt->reason)
788         {
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;
793             break;
794
795         case bg_err_bt_connection_terminated_by_local_host:
796             event.CHIPoBLEConnectionError.Reason = BLE_ERROR_APP_CLOSED_CONNECTION;
797             break;
798
799         default:
800             event.CHIPoBLEConnectionError.Reason = BLE_ERROR_CHIPOBLE_PROTOCOL_ABORT;
801             break;
802         }
803
804         ChipLogProgress(DeviceLayer, "BLE GATT connection closed (con %u, reason %u)", connHandle, conn_evt->reason);
805
806         PlatformMgr().PostEvent(&event);
807
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);
812     }
813 }
814
815 void BLEManagerImpl::HandleWriteEvent(volatile sl_bt_msg_t * evt)
816 {
817     uint16_t attribute = evt->data.evt_gatt_server_user_write_request.characteristic;
818
819     ChipLogProgress(DeviceLayer, "Char Write Req, char : %d", attribute);
820
821     if (gattdb_CHIPoBLEChar_Rx == attribute)
822     {
823         HandleRXCharWrite(evt);
824     }
825 }
826
827 void BLEManagerImpl::HandleTXCharCCCDWrite(volatile sl_bt_msg_t * evt)
828 {
829     CHIP_ERROR err = CHIP_NO_ERROR;
830     CHIPoBLEConState * bleConnState;
831     bool indicationsEnabled;
832     ChipDeviceEvent event;
833
834     bleConnState = GetConnectionState(evt->data.evt_gatt_server_user_write_request.connection);
835
836     VerifyOrExit(bleConnState != NULL, err = CHIP_ERROR_NO_MEMORY);
837
838     // Determine if the client is enabling or disabling indications.
839     indicationsEnabled = (evt->data.evt_gatt_server_characteristic_status.client_config_flags == gatt_indication);
840
841     ChipLogProgress(DeviceLayer, "CHIPoBLE %s received", indicationsEnabled ? "subscribe" : "unsubscribe");
842
843     if (indicationsEnabled)
844     {
845         // If indications are not already enabled for the connection...
846         if (!bleConnState->subscribed)
847         {
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.
851             {
852                 event.Type                    = DeviceEventType::kCHIPoBLESubscribe;
853                 event.CHIPoBLESubscribe.ConId = evt->data.evt_gatt_server_user_write_request.connection;
854                 PlatformMgr().PostEvent(&event);
855             }
856         }
857     }
858     else
859     {
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);
864     }
865
866 exit:
867     if (err != CHIP_NO_ERROR)
868     {
869         ChipLogError(DeviceLayer, "HandleTXCharCCCDWrite() failed: %s", ErrorStr(err));
870     }
871 }
872
873 void BLEManagerImpl::HandleRXCharWrite(volatile sl_bt_msg_t * evt)
874 {
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;
879
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);
883
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());
886
887     // Post an event to the CHIP queue to deliver the data into the CHIP stack.
888     {
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);
894     }
895
896 exit:
897     if (err != CHIP_NO_ERROR)
898     {
899         ChipLogError(DeviceLayer, "HandleRXCharWrite() failed: %s", ErrorStr(err));
900     }
901 }
902
903 void BLEManagerImpl::HandleTxConfirmationEvent(volatile sl_bt_msg_t * evt)
904 {
905     ChipDeviceEvent event;
906     uint8_t timerHandle = sInstance.GetTimerHandle(evt->data.evt_gatt_server_characteristic_status.connection);
907
908     ChipLogProgress(DeviceLayer, "Tx Confirmation received");
909
910     // stop indication confirmation timer
911     if (timerHandle < kMaxConnections)
912     {
913         ChipLogProgress(DeviceLayer, " stop soft timer");
914         sl_bt_system_set_soft_timer(0, timerHandle, false);
915     }
916
917     event.Type                          = DeviceEventType::kCHIPoBLEIndicateConfirm;
918     event.CHIPoBLEIndicateConfirm.ConId = evt->data.evt_gatt_server_characteristic_status.connection;
919     PlatformMgr().PostEvent(&event);
920 }
921
922 void BLEManagerImpl::HandleSoftTimerEvent(volatile sl_bt_msg_t * evt)
923 {
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)
927     {
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);
935     }
936 }
937
938 bool BLEManagerImpl::RemoveConnection(uint8_t connectionHandle)
939 {
940     CHIPoBLEConState * bleConnState = GetConnectionState(connectionHandle, true);
941     bool status                     = false;
942
943     if (bleConnState != NULL)
944     {
945         memset(bleConnState, 0, sizeof(CHIPoBLEConState));
946         status = true;
947     }
948
949     return status;
950 }
951
952 void BLEManagerImpl::AddConnection(uint8_t connectionHandle, uint8_t bondingHandle)
953 {
954     CHIPoBLEConState * bleConnState = GetConnectionState(connectionHandle, true);
955
956     if (bleConnState != NULL)
957     {
958         memset(bleConnState, 0, sizeof(CHIPoBLEConState));
959         bleConnState->allocated        = 1;
960         bleConnState->connectionHandle = connectionHandle;
961         bleConnState->bondingHandle    = bondingHandle;
962     }
963 }
964
965 BLEManagerImpl::CHIPoBLEConState * BLEManagerImpl::GetConnectionState(uint8_t connectionHandle, bool allocate)
966 {
967     uint8_t freeIndex = kMaxConnections;
968
969     for (uint8_t i = 0; i < kMaxConnections; i++)
970     {
971         if (mBleConnections[i].allocated == 1)
972         {
973             if (mBleConnections[i].connectionHandle == connectionHandle)
974             {
975                 return &mBleConnections[i];
976             }
977         }
978
979         else if (i < freeIndex)
980         {
981             freeIndex = i;
982         }
983     }
984
985     if (allocate)
986     {
987         if (freeIndex < kMaxConnections)
988         {
989             return &mBleConnections[freeIndex];
990         }
991
992         ChipLogError(DeviceLayer, "Failed to allocate CHIPoBLEConState");
993     }
994
995     return NULL;
996 }
997
998 uint8_t BLEManagerImpl::GetTimerHandle(uint8_t connectionHandle, bool allocate)
999 {
1000     uint8_t freeIndex = kMaxConnections;
1001
1002     for (uint8_t i = 0; i < kMaxConnections; i++)
1003     {
1004         if (mIndConfId[i] == connectionHandle)
1005         {
1006             return i;
1007         }
1008         else if (allocate)
1009         {
1010             if (i < freeIndex)
1011             {
1012                 freeIndex = i;
1013             }
1014         }
1015     }
1016
1017     if (freeIndex < kMaxConnections)
1018     {
1019         mIndConfId[freeIndex] = connectionHandle;
1020     }
1021     else
1022     {
1023         ChipLogError(DeviceLayer, "Failed to Save Conn Handle for indication");
1024     }
1025
1026     return freeIndex;
1027 }
1028
1029 void BLEManagerImpl::DriveBLEState(intptr_t arg)
1030 {
1031     sInstance.DriveBLEState();
1032 }
1033
1034 } // namespace Internal
1035 } // namespace DeviceLayer
1036 } // namespace chip
1037 #endif // CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE