Fix for x86_64 build fail
[platform/upstream/connectedhomeip.git] / src / platform / cc13x2_26x2 / BLEManagerImpl.h
1 /*
2  *
3  *    Copyright (c) 2020 Project CHIP Authors
4  *    Copyright (c) 2020 Texas Instruments Incorporated
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 object for the Texas
22  * Instruments cc13xx_cc26xx platform.
23  */
24
25 #ifndef BLEManager_IMPL_H
26 #define BLEManager_IMPL_H
27
28 #pragma once
29
30 #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE
31
32 #ifdef __cplusplus
33 extern "C" {
34 #endif
35
36 #include "FreeRTOS.h"
37 #include <queue.h>
38 #include <task.h>
39
40 #include <icall.h>
41 #include <icall_ble_api.h>
42
43 #include "hal_types.h"
44
45 #include "chipOBleProfile.h"
46 #include "ti_ble_config.h"
47 #include "ti_drivers_config.h"
48
49 #ifdef __cplusplus
50 }
51 #endif
52
53 namespace chip {
54 namespace DeviceLayer {
55 namespace Internal {
56
57 using namespace chip::Ble;
58
59 // Internal Events for RTOS application
60 #define ICALL_EVT ICALL_MSG_EVENT_ID  // Event_Id_31
61 #define QUEUE_EVT UTIL_QUEUE_EVENT_ID // Event_Id_30
62
63 // Application events
64 #define BLEManagerIMPL_STATE_UPDATE_EVT (0)
65
66 // 500ms interval
67 #define BLEMANAGERIMPL_ADV_INT_SLOW (800)
68 // 100ms interval (Default)
69 #define BLEMANAGERIMPL_ADV_INT_FAST (160)
70
71 #define CHIPOBLE_ADV_SIZE_NO_DEVICE_ID_INFO (4)
72
73 #define CHIPOBLE_SCANRES_SIZE_NO_NAME (6)
74
75 // How often to read current current RPA (in ms)
76 #define READ_RPA_EVT_PERIOD 3000
77
78 // 15 Minute Advertisement CHIP Timeout period
79 #define ADV_TIMEOUT (900000)
80
81 #define STATE_CHANGE_EVT 0
82 #define CHAR_CHANGE_EVT 1
83 #define CHIPOBLE_CHAR_CHANGE_EVT 2
84 #define BLEManagerIMPL_CHIPOBLE_TX_IND_EVT 3
85 #define ADV_EVT 4
86 #define PAIR_STATE_EVT 5
87 #define PASSCODE_EVT 6
88 #define READ_RPA_EVT 7
89 #define SEND_PARAM_UPDATE_EVT 8
90 #define BLEManagerIMPL_CHIPOBLE_CLOSE_CONN_EVT 9
91 #define CONN_EVT 10
92
93 // For storing the active connections
94 #define RSSI_TRACK_CHNLS 1 // Max possible channels can be GAP_BONDINGS_MAX
95 #define MAX_RSSI_STORE_DEPTH 5
96 #define INVALID_HANDLE 0xFFFF
97 #define RSSI_2M_THRSHLD -30
98 #define RSSI_1M_THRSHLD -40
99 #define RSSI_S2_THRSHLD -50
100 #define RSSI_S8_THRSHLD -60
101 #define PHY_NONE LL_PHY_NONE // No PHY set
102 #define AUTO_PHY_UPDATE 0xFF
103 // Set initial values to maximum, RX is set to max. by default(251 octets, 2120us)
104 // Some brand smartphone is essentially needing 251/2120, so we set them here.
105 #define BLEMANAGER_SUGGESTED_PDU_SIZE 251 // default is 27 octets(TX)
106 #define BLEMANAGER_SUGGESTED_TX_TIME 2120 // default is 328us(TX)
107
108 typedef struct
109 {
110     uint8_t len;  // data length
111     void * pData; // pointer to message
112 } CHIPoBLEIndEvt_t;
113
114 typedef struct
115 {
116     uint8_t paramId;     // Parameter written
117     uint16_t len;        //  data length
118     uint16_t connHandle; // Active connection which received the write
119 } CHIPoBLEProfChgEvt_t;
120
121 // App event passed from stack modules. This type is defined by the application
122 // since it can queue events to itself however it wants.
123 typedef struct
124 {
125     uint8_t event; // event type
126     void * pData;  // pointer to message
127 } QueuedEvt_t;
128
129 // Container to store advertising event data when passing from advertising
130 // callback to app event. See the respective event in GapAdvScan_Event_IDs
131 // in gap_advertiser.h for the type that pBuf should be cast to.
132 typedef struct
133 {
134     uint32_t event;
135     void * pBuf;
136 } GapAdvEventData_t;
137
138 // Container to store information from clock expiration using a flexible array
139 // since data is not always needed
140 typedef struct
141 {
142     uint8_t event;
143     uint8_t data[];
144 } ClockEventData_t;
145
146 // List element for parameter update and PHY command status lists
147 typedef struct
148 {
149     List_Elem elem;
150     uint16_t connHandle;
151 } ConnHandleEntry_t;
152
153 // Connected device information
154 typedef struct
155 {
156     uint16_t connHandle;          // Connection Handle
157     ClockP_Struct * pUpdateClock; // pointer to clock struct
158     int8_t rssiArr[MAX_RSSI_STORE_DEPTH];
159     uint8_t rssiCntr;
160     int8_t rssiAvg;
161     bool phyCngRq; // Set to true if PHY change request is in progress
162     uint8_t currPhy;
163     uint8_t rqPhy;
164     uint8_t phyRqFailCnt; // PHY change request count
165     bool isAutoPHYEnable; // Flag to indicate auto phy change
166     uint16_t mtu;
167     ClockEventData_t * pParamUpdateEventData;
168 } ConnRec_t;
169
170 // Container to store passcode data when passing from gapbondmgr callback
171 // to app event. See the pfnPairStateCB_t documentation from the gapbondmgr.h
172 // header file for more information on each parameter.
173 typedef struct
174 {
175     uint8_t state;
176     uint16_t connHandle;
177     uint8_t status;
178 } PairStateData_t;
179
180 // Container to store passcode data when passing from gapbondmgr callback
181 // to app event. See the pfnPasscodeCB_t documentation from the gapbondmgr.h
182 // header file for more information on each parameter.
183 typedef struct
184 {
185     uint8_t deviceAddr[B_ADDR_LEN];
186     uint16_t connHandle;
187     uint8_t uiInputs;
188     uint8_t uiOutputs;
189     uint32_t numComparison;
190 } PasscodeData_t;
191
192 /**
193  * Concrete implementation of the BLEManager singleton object for cc13x2_cc26x2.
194  */
195 class BLEManagerImpl final : public BLEManager, private BleLayer, private BlePlatformDelegate, private BleApplicationDelegate
196
197 {
198     // Allow the BLEManager interface class to delegate method calls to
199     // the implementation methods provided by this class.
200     friend BLEManager;
201
202 public:
203     // ===== Platform-specific members that may be accessed directly by the application.
204
205 private:
206     // ===== Members that implement the BLEManager internal interface.
207
208     CHIP_ERROR _Init(void);
209     CHIPoBLEServiceMode _GetCHIPoBLEServiceMode(void);
210     CHIP_ERROR _SetCHIPoBLEServiceMode(CHIPoBLEServiceMode val);
211     bool _IsAdvertisingEnabled(void);
212     CHIP_ERROR _SetAdvertisingEnabled(bool val);
213     bool _IsAdvertising(void);
214     CHIP_ERROR _SetAdvertisingMode(BLEAdvertisingMode mode);
215     CHIP_ERROR _GetDeviceName(char * buf, size_t bufSize);
216     CHIP_ERROR _SetDeviceName(const char * deviceName);
217     uint16_t _NumConnections(void);
218     void _OnPlatformEvent(const ChipDeviceEvent * event);
219     BleLayer * _GetBleLayer(void);
220
221     // ===== Members that implement virtual methods on BlePlatformDelegate.
222
223     bool SubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId,
224                                  const Ble::ChipBleUUID * charId) override;
225     bool UnsubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId,
226                                    const Ble::ChipBleUUID * charId) override;
227     bool CloseConnection(BLE_CONNECTION_OBJECT conId) override;
228     uint16_t GetMTU(BLE_CONNECTION_OBJECT conId) const override;
229
230     bool SendIndication(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId, const Ble::ChipBleUUID * charId,
231                         System::PacketBufferHandle pBuf) override;
232     bool SendWriteRequest(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId, const Ble::ChipBleUUID * charId,
233                           System::PacketBufferHandle pBuf) override;
234     bool SendReadRequest(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId, const Ble::ChipBleUUID * charId,
235                          System::PacketBufferHandle pBuf) override;
236     bool SendReadResponse(BLE_CONNECTION_OBJECT conId, BLE_READ_REQUEST_CONTEXT requestContext, const Ble::ChipBleUUID * svcId,
237                           const Ble::ChipBleUUID * charId) override;
238
239     // ===== Members that implement virtual methods on BleApplicationDelegate.
240
241     void NotifyChipConnectionClosed(BLE_CONNECTION_OBJECT conId) override;
242
243     const ChipBleUUID chipUUID_CHIPoBLEChar_RX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42,
244                                                      0x9F, 0x9D, 0x11 } };
245     const ChipBleUUID chipUUID_CHIPoBLEChar_TX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42,
246                                                      0x9F, 0x9D, 0x12 } };
247
248     friend BLEManager & BLEMgr(void);
249     friend BLEManagerImpl & BLEMgrImpl(void);
250
251     static BLEManagerImpl sInstance;
252
253     /* BLE stack task handle */
254     static TaskHandle_t sBleTaskHndl;
255     // Entity ID globally used to check for source and/or destination of messages
256     static ICall_EntityID sSelfEntity;
257
258     // Event globally used to post local events and pend on system and
259     // local events.
260     static ICall_SyncHandle sSyncEvent;
261     static QueueHandle_t sEventHandlerMsgQueueID;
262     static chipOBleProfileCBs_t CHIPoBLEProfile_CBs;
263     static gapBondCBs_t BLEMgr_BondMgrCBs;
264
265     enum class Flags : uint16_t
266     {
267         kAdvertisingEnabled       = 0x0001, /* App enabled CHIPoBLE advertising */
268         kFastAdvertisingEnabled   = 0x0002, /* App enabled Fash CHIPoBLE advertising */
269         kAdvertising              = 0x0004, /* TI BLE stack actively advertising */
270         kBLEStackInitialized      = 0x0008, /* TI BLE Stack GAP Intilization complete */
271         kBLEStackGATTNameUpdate   = 0x0010, /* Trigger TI BLE Stack name update, must be performed prior to adv start */
272         kBLEStackGATTNameSet      = 0x0020, /* Device name has been set externally*/
273         kAdvertisingRefreshNeeded = 0x0040, /* Advertising settings changed and it should be restarted */
274
275     };
276
277     BitFlags<Flags> mFlags;
278     CHIPoBLEServiceMode mServiceMode;
279     char mDeviceName[GAP_DEVICE_NAME_LEN];
280
281     ConnRec_t connList[MAX_NUM_BLE_CONNS];
282     // List to store connection handles for queued param updates
283     List_List paramUpdateList;
284
285     // Advertising handles
286     uint8_t advHandleLegacy;
287     // Address mode
288     GAP_Addr_Modes_t addrMode = DEFAULT_ADDRESS_MODE;
289     // Current Random Private Address
290     uint8_t rpa[B_ADDR_LEN] = { 0 };
291
292     ClockP_Struct clkRpaRead;
293     ClockP_Struct clkAdvTimeout;
294     // Memory to pass RPA read event ID to clock handler
295     ClockEventData_t argRpaRead = { .event = READ_RPA_EVT };
296
297     // ===== Private BLE Stack Helper functions.
298     void AdvInit(void);
299     void EventHandler_init(void);
300     void InitPHYRSSIArray(void);
301     CHIP_ERROR CreateEventHandler(void);
302     uint8_t ProcessStackEvent(ICall_Hdr * pMsg);
303     void ProcessEvtHdrMsg(QueuedEvt_t * pMsg);
304     void ProcessGapMessage(gapEventHdr_t * pMsg);
305     uint8_t ProcessGATTMsg(gattMsgEvent_t * pMsg);
306     void ProcessAdvEvent(GapAdvEventData_t * pEventData);
307     CHIP_ERROR ProcessParamUpdate(uint16_t connHandle);
308     status_t EnqueueEvtHdrMsg(uint8_t event, void * pData);
309     uint8_t AddBLEConn(uint16_t connHandle);
310     uint8_t RemoveBLEConn(uint16_t connHandle);
311     uint8_t GetBLEConnIndex(uint16_t connHandle) const;
312     uint8_t ClearBLEConnListEntry(uint16_t connHandle);
313     void ClearPendingBLEParamUpdate(uint16_t connHandle);
314     void UpdateBLERPA(void);
315
316     static void HandleIncomingBleConnection(Ble::BLEEndPoint * bleEP);
317
318     /* Static helper function */
319     static void EventHandler(void * arg);
320     static CHIP_ERROR DriveBLEState(void);
321
322     /* Declared static to acquire function ptr */
323     static void advCallback(uint32_t event, void * pBuf, uintptr_t arg);
324     static void ClockHandler(uintptr_t arg);
325     static void AdvTimeoutHandler(uintptr_t arg);
326     static void CHIPoBLEProfile_charValueChangeCB(uint8_t paramId, uint16_t len, uint16_t connHandle);
327     static void PasscodeCb(uint8_t * pDeviceAddr, uint16_t connHandle, uint8_t uiInputs, uint8_t uiOutputs, uint32_t numComparison);
328     static void PairStateCb(uint16_t connHandle, uint8_t state, uint8_t status);
329     static void AssertHandler(uint8 assertCause, uint8 assertSubcause);
330 };
331
332 /**
333  * Returns a reference to the public interface of the BLEManager singleton object.
334  *
335  * Internal components should use this to access features of the BLEManager object
336  * that are common to all platforms.
337  */
338 inline BLEManager & BLEMgr(void)
339 {
340     return BLEManagerImpl::sInstance;
341 }
342
343 /**
344  * Returns the platform-specific implementation of the BLEManager singleton object.
345  *
346  * Internal components can use this to gain access to features of the BLEManager
347  * that are specific to the cc13x2_cc26x2 platforms.
348  */
349 inline BLEManagerImpl & BLEMgrImpl(void)
350 {
351     return BLEManagerImpl::sInstance;
352 }
353
354 inline BleLayer * BLEManagerImpl::_GetBleLayer()
355 {
356     return this;
357 }
358
359 } // namespace Internal
360 } // namespace DeviceLayer
361 } // namespace chip
362
363 #endif // CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE
364
365 #endif // BLEManager_IMPL_H