Apply Upstream code (2021-03-15)
[platform/upstream/connectedhomeip.git] / src / platform / K32W / BLEManagerImpl.h
1 /*
2  *
3  *    Copyright (c) 2020-2021 Project CHIP Authors
4  *    Copyright (c) 2020 Nest Labs, Inc.
5  *    All rights reserved.
6  *
7  *    Licensed under the Apache License, Version 2.0 (the "License");
8  *    you may not use this file except in compliance with the License.
9  *    You may obtain a copy of the License at
10  *
11  *        http://www.apache.org/licenses/LICENSE-2.0
12  *
13  *    Unless required by applicable law or agreed to in writing, software
14  *    distributed under the License is distributed on an "AS IS" BASIS,
15  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *    See the License for the specific language governing permissions and
17  *    limitations under the License.
18  */
19
20 /**
21  *    @file
22  *          Provides an implementation of the BLEManager singleton object
23  *          for the K32W platforms.
24  */
25
26 #pragma once
27
28 #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE
29
30 #include "Messaging.h"
31
32 #include "fsl_os_abstraction.h"
33
34 #include "ble_conn_manager.h"
35 #include "ble_controller_task_config.h"
36 #include "ble_general.h"
37 #include "ble_host_task_config.h"
38 #include "ble_host_tasks.h"
39 #include "controller_interface.h"
40 #include "gap_interface.h"
41 #include "gatt_db_dynamic.h"
42 #include "gatt_server_interface.h"
43
44 #include "FreeRTOS.h"
45 #include "event_groups.h"
46 #include "timers.h"
47
48 namespace chip {
49 namespace DeviceLayer {
50 namespace Internal {
51
52 using namespace chip::Ble;
53
54 /**
55  * Concrete implementation of the NetworkProvisioningServer singleton object for the K32W platforms.
56  */
57 class BLEManagerImpl final : public BLEManager, private BleLayer, private BlePlatformDelegate, private BleApplicationDelegate
58 {
59     // Allow the BLEManager interface class to delegate method calls to
60     // the implementation methods provided by this class.
61     friend BLEManager;
62
63 private:
64     // ===== Members that implement the BLEManager internal interface.
65
66     CHIP_ERROR _Init(void);
67     CHIPoBLEServiceMode _GetCHIPoBLEServiceMode(void);
68     CHIP_ERROR _SetCHIPoBLEServiceMode(CHIPoBLEServiceMode val);
69     bool _IsAdvertisingEnabled(void);
70     CHIP_ERROR _SetAdvertisingEnabled(bool val);
71     bool _IsFastAdvertisingEnabled(void);
72     CHIP_ERROR _SetFastAdvertisingEnabled(bool val);
73     bool _IsAdvertising(void);
74     CHIP_ERROR _GetDeviceName(char * buf, size_t bufSize);
75     CHIP_ERROR _SetDeviceName(const char * deviceName);
76     uint16_t _NumConnections(void);
77     void _OnPlatformEvent(const ChipDeviceEvent * event);
78     BleLayer * _GetBleLayer(void);
79
80     // ===== Members that implement virtual methods on BlePlatformDelegate.
81
82     bool SubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId,
83                                  const Ble::ChipBleUUID * charId) override;
84     bool UnsubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId,
85                                    const Ble::ChipBleUUID * charId) override;
86     bool CloseConnection(BLE_CONNECTION_OBJECT conId) override;
87     uint16_t GetMTU(BLE_CONNECTION_OBJECT conId) const override;
88     bool SendIndication(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId, const Ble::ChipBleUUID * charId,
89                         System::PacketBufferHandle pBuf) override;
90     bool SendWriteRequest(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId, const Ble::ChipBleUUID * charId,
91                           System::PacketBufferHandle pBuf) override;
92     bool SendReadRequest(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId, const Ble::ChipBleUUID * charId,
93                          System::PacketBufferHandle pBuf) override;
94     bool SendReadResponse(BLE_CONNECTION_OBJECT conId, BLE_READ_REQUEST_CONTEXT requestContext, const Ble::ChipBleUUID * svcId,
95                           const Ble::ChipBleUUID * charId) override;
96
97     // ===== Members that implement virtual methods on BleApplicationDelegate.
98
99     void NotifyChipConnectionClosed(BLE_CONNECTION_OBJECT conId) override;
100
101     // ===== Members for internal use by the following friends.
102
103     friend BLEManager & BLEMgr(void);
104     friend BLEManagerImpl & BLEMgrImpl(void);
105
106     static BLEManagerImpl sInstance;
107
108     // ===== Private members reserved for use by this class only.
109
110     enum class Flags : uint8_t
111     {
112         kAdvertisingEnabled      = 0x0001,
113         kFastAdvertisingEnabled  = 0x0002,
114         kAdvertising             = 0x0004,
115         kRestartAdvertising      = 0x0008,
116         kK32WBLEStackInitialized = 0x0010,
117         kDeviceNameSet           = 0x0020,
118     };
119     BitFlags<BLEManagerImpl::Flags> mFlags;
120
121     enum
122     {
123         kMaxConnections      = BLE_LAYER_NUM_BLE_ENDPOINTS,
124         kMaxDeviceNameLength = 16,
125         kUnusedIndex         = 0xFF,
126     };
127
128     typedef enum
129     {
130         BLE_KW_MSG_ERROR = 0x01,
131         BLE_KW_MSG_CONNECTED,
132         BLE_KW_MSG_DISCONNECTED,
133         BLE_KW_MSG_MTU_CHANGED,
134         BLE_KW_MSG_ATT_WRITTEN,
135         BLE_KW_MSG_ATT_LONG_WRITTEN,
136         BLE_KW_MSG_ATT_READ,
137         BLE_KW_MSG_ATT_CCCD_WRITTEN,
138         BLE_KW_MSG_FORCE_DISCONNECT,
139     } blekw_msg_type_t;
140
141     typedef struct hk_ble_kw_msg_s
142     {
143         blekw_msg_type_t type;
144         uint16_t length;
145         union
146         {
147             uint8_t u8;
148             uint16_t u16;
149             uint32_t u32;
150             uint8_t data[1];
151             char * str;
152         } data;
153     } blekw_msg_t;
154
155     typedef enum ble_err_t
156     {
157         BLE_OK = 0,
158         BLE_INTERNAL_GATT_ERROR,
159         BLE_E_SET_ADV_PARAMS,
160         BLE_E_ADV_PARAMS_FAILED,
161         BLE_E_SET_ADV_DATA,
162         BLE_E_ADV_CHANGED,
163         BLE_E_ADV_FAILED,
164         BLE_E_ADV_SETUP_FAILED,
165         BLE_E_START_ADV,
166         BLE_E_STOP,
167         BLE_E_FAIL,
168         BLE_E_START_ADV_FAILED,
169         BLE_INTERNAL_ERROR,
170     } ble_err_t;
171
172     typedef struct ble_att_written_data_s
173     {
174         uint8_t device_id;
175         uint16_t handle;
176         uint16_t length;
177         uint8_t data[1];
178     } blekw_att_written_data_t;
179
180     typedef struct hk_ble_att_read_data_s
181     {
182         uint8_t device_id;
183         uint16_t handle;
184     } blekw_att_read_data_t;
185
186     struct CHIPoBLEConState
187     {
188         uint16_t mtu : 10;
189         uint16_t allocated : 1;
190         uint16_t subscribed : 1;
191         uint16_t unused : 4;
192         uint8_t connectionHandle;
193         uint8_t bondingHandle;
194     };
195     CHIPoBLEConState mBleConnections[kMaxConnections];
196
197     CHIPoBLEServiceMode mServiceMode;
198     uint16_t mNumGAPCons;
199     uint8_t mAdvHandle;
200     char mDeviceName[kMaxDeviceNameLength + 1];
201
202     void DriveBLEState(void);
203     CHIP_ERROR ConfigureAdvertising(void);
204     CHIP_ERROR StartAdvertising(void);
205     CHIP_ERROR StopAdvertising(void);
206     void HandleSoftDeviceBLEEvent(const ChipDeviceEvent * event);
207     void HandleConnectEvent(blekw_msg_t * msg);
208     void HandleConnectionCloseEvent(blekw_msg_t * msg);
209     void HandleWriteEvent(blekw_msg_t * msg);
210     void HandleRXCharWrite(blekw_msg_t * msg);
211     void HandleTXCharCCCDWrite(blekw_msg_t * msg);
212     CHIP_ERROR HandleGAPConnect(const ChipDeviceEvent * event);
213     CHIP_ERROR HandleGAPDisconnect(const ChipDeviceEvent * event);
214     CHIP_ERROR HandleRXCharWrite(const ChipDeviceEvent * event);
215     CHIP_ERROR HandleTXCharCCCDWrite(const ChipDeviceEvent * event);
216     CHIP_ERROR HandleTXComplete(const ChipDeviceEvent * event);
217     CHIP_ERROR SetSubscribed(uint16_t conId);
218     bool UnsetSubscribed(uint16_t conId);
219     bool IsSubscribed(uint16_t conId);
220     CHIP_ERROR ConfigureAdvertisingData(void);
221     BLEManagerImpl::ble_err_t blekw_send_event(int8_t connection_handle, uint16_t handle, uint8_t * data, uint32_t len);
222     bool RemoveConnection(uint8_t connectionHandle);
223     void AddConnection(uint8_t connectionHandle);
224     BLEManagerImpl::CHIPoBLEConState * GetConnectionState(uint8_t connectionHandle, bool allocate);
225
226     static void DriveBLEState(intptr_t arg);
227
228     static void BLE_SignalFromISRCallback(void);
229     static void blekw_connection_timeout_cb(TimerHandle_t timer);
230     static CHIP_ERROR blekw_msg_add_u8(blekw_msg_type_t type, uint8_t data);
231     static void blekw_new_data_received_notification(uint32_t mask);
232     static CHIP_ERROR blekw_controller_init(void);
233     static CHIP_ERROR blekw_host_init(void);
234     static void Host_Task(osaTaskParam_t argument);
235     static void blekw_generic_cb(gapGenericEvent_t * pGenericEvent);
236     static void blekw_gatt_server_cb(deviceId_t deviceId, gattServerEvent_t * pServerEvent);
237     static CHIP_ERROR blekw_msg_add_u16(blekw_msg_type_t type, uint16_t data);
238     static CHIP_ERROR blekw_msg_add_att_written(blekw_msg_type_t type, uint8_t device_id, uint16_t handle, uint8_t * data,
239                                                 uint16_t length);
240     static CHIP_ERROR blekw_msg_add_att_read(blekw_msg_type_t type, uint8_t device_id, uint16_t handle);
241     static BLEManagerImpl::ble_err_t blekw_start_advertising(gapAdvertisingParameters_t * adv_params, gapAdvertisingData_t * adv,
242                                                              gapScanResponseData_t * scnrsp);
243     static BLEManagerImpl::ble_err_t blekw_stop_advertising(void);
244     static void blekw_gap_advertising_cb(gapAdvertisingEvent_t * pAdvertisingEvent);
245     static void blekw_gap_connection_cb(deviceId_t deviceId, gapConnectionEvent_t * pConnectionEvent);
246     static void blekw_start_connection_timeout(void);
247     static void blekw_stop_connection_timeout(void);
248
249     static void bleAppTask(void * p_arg);
250 };
251
252 /**
253  * Returns a reference to the public interface of the BLEManager singleton object.
254  *
255  * Internal components should use this to access features of the BLEManager object
256  * that are common to all platforms.
257  */
258 inline BLEManager & BLEMgr(void)
259 {
260     return BLEManagerImpl::sInstance;
261 }
262
263 /**
264  * Returns the platform-specific implementation of the BLEManager singleton object.
265  *
266  * Internal components can use this to gain access to features of the BLEManager
267  * that are specific to the K32W platforms.
268  */
269 inline BLEManagerImpl & BLEMgrImpl(void)
270 {
271     return BLEManagerImpl::sInstance;
272 }
273
274 inline BleLayer * BLEManagerImpl::_GetBleLayer()
275 {
276     return this;
277 }
278
279 inline BLEManager::CHIPoBLEServiceMode BLEManagerImpl::_GetCHIPoBLEServiceMode(void)
280 {
281     return mServiceMode;
282 }
283
284 } // namespace Internal
285 } // namespace DeviceLayer
286 } // namespace chip
287
288 #endif // CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE