36daf0de7af5ff7286fa74124fe52b9e55ee6ef1
[platform/upstream/connectedhomeip.git] / src / ble / BLEEndPoint.h
1 /*
2  *
3  *    Copyright (c) 2020 Project CHIP Authors
4  *    Copyright (c) 2014-2017 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  *      This file defines a Bluetooth Low Energy (BLE) connection
22  *      endpoint abstraction for the byte-streaming,
23  *      connection-oriented CHIP over Bluetooth Low Energy (CHIPoBLE)
24  *      Bluetooth Transport Protocol (BTP).
25  *
26  */
27
28 #pragma once
29
30 #include <system/SystemMutex.h>
31
32 #include <ble/BleLayer.h>
33 #include <ble/BtpEngine.h>
34 #if CHIP_ENABLE_CHIPOBLE_TEST
35 #include <ble/BtpEngineTest.h>
36 #endif
37
38 namespace chip {
39 namespace Ble {
40
41 using ::chip::System::PacketBufferHandle;
42
43 enum
44 {
45     kBleCloseFlag_SuppressCallback  = 0x01,
46     kBleCloseFlag_AbortTransmission = 0x02
47 };
48
49 // Forward declarations
50 class BleLayer;
51 class BleEndPointPool;
52 #if CHIP_ENABLE_CHIPOBLE_TEST
53 class BtpEngineTest;
54 #endif
55
56 class DLL_EXPORT BLEEndPoint : public BleLayerObject
57 {
58     friend class BleLayer;
59     friend class BleEndPointPool;
60 #if CHIP_ENABLE_CHIPOBLE_TEST
61     friend class BtpEngineTest;
62 #endif
63
64 public:
65     typedef uint64_t AlignT;
66
67     // Public data members:
68     enum
69     {
70         kState_Ready      = 0,
71         kState_Connecting = 1,
72         kState_Aborting   = 2,
73         kState_Connected  = 3,
74         kState_Closing    = 4,
75         kState_Closed     = 5
76     } mState; // [READ-ONLY] End point connection state. Refers to state of CHIP over
77               // BLE transport protocol connection, not of underlying BLE connection.
78
79     // Public function pointers:
80     typedef void (*OnConnectCompleteFunct)(BLEEndPoint * endPoint, BLE_ERROR err);
81     OnConnectCompleteFunct OnConnectComplete;
82
83     typedef void (*OnMessageReceivedFunct)(BLEEndPoint * endPoint, PacketBufferHandle msg);
84     OnMessageReceivedFunct OnMessageReceived;
85
86     typedef void (*OnConnectionClosedFunct)(BLEEndPoint * endPoint, BLE_ERROR err);
87     OnConnectionClosedFunct OnConnectionClosed;
88
89 #if CHIP_ENABLE_CHIPOBLE_TEST
90     typedef void (*OnCommandReceivedFunct)(BLEEndPoint * endPoint, PacketBufferHandle msg);
91     OnCommandReceivedFunct OnCommandReceived;
92     inline void SetOnCommandReceivedCB(OnCommandReceivedFunct cb) { OnCommandReceived = cb; };
93     BtpEngineTest mBtpEngineTest;
94     inline void SetTxWindowSize(uint8_t size) { mRemoteReceiveWindowSize = size; };
95     inline void SetRxWindowSize(uint8_t size) { mReceiveWindowMaxSize = size; };
96 #endif
97
98     // Public functions:
99     BLE_ERROR Send(PacketBufferHandle data);
100     BLE_ERROR Receive(PacketBufferHandle data);
101     BLE_ERROR StartConnect();
102
103     bool IsUnsubscribePending() const;
104     bool ConnectionObjectIs(BLE_CONNECTION_OBJECT connObj) { return connObj == mConnObj; }
105     void Close();
106     void Abort();
107
108 private:
109     // Private data members:
110     enum ConnectionStateFlags
111     {
112         kConnState_AutoClose                = 0x01, // End point should close underlying BLE conn on BTP close.
113         kConnState_CapabilitiesConfReceived = 0x02, // GATT confirmation received for sent capabilities req/resp.
114         kConnState_CapabilitiesMsgReceived  = 0x04, // Capabilities request or response message received.
115         kConnState_DidBeginSubscribe        = 0x08, // GATT subscribe request sent; must unsubscribe on close.
116         kConnState_StandAloneAckInFlight    = 0x10, // Stand-alone ack in flight, awaiting GATT confirmation.
117         kConnState_GattOperationInFlight    = 0x20  // GATT write, indication, subscribe, or unsubscribe in flight,
118                                                     // awaiting GATT confirmation.
119     };
120
121     enum TimerStateFlags
122     {
123         kTimerState_ConnectTimerRunning           = 0x01, // BTP connect completion timer running.
124         kTimerState_ReceiveConnectionTimerRunning = 0x02, // BTP receive connection completion timer running.
125         kTimerState_AckReceivedTimerRunning       = 0x04, // Ack received timer running due to unacked sent fragment.
126         kTimerState_SendAckTimerRunning           = 0x08, // Send ack timer running; indicates pending ack to send.
127         kTimerState_UnsubscribeTimerRunning       = 0x10, // Unsubscribe completion timer running.
128 #if CHIP_ENABLE_CHIPOBLE_TEST
129         kTimerState_UnderTestTimerRunnung = 0x80 // running throughput Tx test
130 #endif
131     };
132
133     // BLE connection to which an end point is uniquely bound. Type BLE_CONNECTION_OBJECT is defined by the platform or
134     // void* by default. This object is passed back to the platform delegate with each call to send traffic over or
135     // modify the state of the underlying BLE connection.
136     BLE_CONNECTION_OBJECT mConnObj;
137
138     // Queue of outgoing messages to send when current BtpEngine transmission completes.
139     //
140     // Re-used during connection setup to cache capabilities request and response payloads; payloads are freed when
141     // connection is established.
142     PacketBufferHandle mSendQueue;
143
144     // Pending stand-alone BTP acknolwedgement. Pre-empts regular send queue or fragmented message transmission in
145     // progress.
146     PacketBufferHandle mAckToSend;
147
148     BtpEngine mBtpEngine;
149     BleRole mRole;
150     uint8_t mConnStateFlags;
151     uint8_t mTimerStateFlags;
152     SequenceNumber_t mLocalReceiveWindowSize;
153     SequenceNumber_t mRemoteReceiveWindowSize;
154     SequenceNumber_t mReceiveWindowMaxSize;
155 #if CHIP_ENABLE_CHIPOBLE_TEST
156     chip::System::Mutex mTxQueueMutex; // For MT-safe Tx queuing
157 #endif
158
159     // Private functions:
160     BLEEndPoint()  = delete;
161     ~BLEEndPoint() = delete;
162
163     BLE_ERROR Init(BleLayer * bleLayer, BLE_CONNECTION_OBJECT connObj, BleRole role, bool autoClose);
164     bool IsConnected(uint8_t state) const;
165     void DoClose(uint8_t flags, BLE_ERROR err);
166
167     // Transmit path:
168     BLE_ERROR DriveSending();
169     BLE_ERROR DriveStandAloneAck();
170     bool PrepareNextFragment(PacketBufferHandle && data, bool & sentAck);
171     BLE_ERROR SendNextMessage();
172     BLE_ERROR ContinueMessageSend();
173     BLE_ERROR DoSendStandAloneAck();
174     BLE_ERROR SendCharacteristic(PacketBufferHandle && buf);
175     bool SendIndication(PacketBufferHandle && buf);
176     bool SendWrite(PacketBufferHandle && buf);
177
178     // Receive path:
179     BLE_ERROR HandleConnectComplete();
180     BLE_ERROR HandleReceiveConnectionComplete();
181     void HandleSubscribeReceived();
182     void HandleSubscribeComplete();
183     void HandleUnsubscribeComplete();
184     BLE_ERROR HandleGattSendConfirmationReceived();
185     BLE_ERROR HandleHandshakeConfirmationReceived();
186     BLE_ERROR HandleFragmentConfirmationReceived();
187     BLE_ERROR HandleCapabilitiesRequestReceived(PacketBufferHandle data);
188     BLE_ERROR HandleCapabilitiesResponseReceived(PacketBufferHandle data);
189     SequenceNumber_t AdjustRemoteReceiveWindow(SequenceNumber_t lastReceivedAck, SequenceNumber_t maxRemoteWindowSize,
190                                                SequenceNumber_t newestUnackedSentSeqNum);
191
192     // Timer control functions:
193     BLE_ERROR StartConnectTimer();           // Start connect timer.
194     BLE_ERROR StartReceiveConnectionTimer(); // Start receive connection timer.
195     BLE_ERROR StartAckReceivedTimer();       // Start ack-received timer if it's not already running.
196     BLE_ERROR RestartAckReceivedTimer();     // Restart ack-received timer.
197     BLE_ERROR StartSendAckTimer();           // Start send-ack timer if it's not already running.
198     BLE_ERROR StartUnsubscribeTimer();
199     void StopConnectTimer();           // Stop connect timer.
200     void StopReceiveConnectionTimer(); // Stop receive connection timer.
201     void StopAckReceivedTimer();       // Stop ack-received timer.
202     void StopSendAckTimer();           // Stop send-ack timer.
203     void StopUnsubscribeTimer();       // Stop unsubscribe timer.
204
205     // Timer expired callbacks:
206     static void HandleConnectTimeout(chip::System::Layer * systemLayer, void * appState, chip::System::Error err);
207     static void HandleReceiveConnectionTimeout(chip::System::Layer * systemLayer, void * appState, chip::System::Error err);
208     static void HandleAckReceivedTimeout(chip::System::Layer * systemLayer, void * appState, chip::System::Error err);
209     static void HandleSendAckTimeout(chip::System::Layer * systemLayer, void * appState, chip::System::Error err);
210     static void HandleUnsubscribeTimeout(chip::System::Layer * systemLayer, void * appState, chip::System::Error err);
211
212     // Close functions:
213     void DoCloseCallback(uint8_t state, uint8_t flags, BLE_ERROR err);
214     void FinalizeClose(uint8_t state, uint8_t flags, BLE_ERROR err);
215     void ReleaseBleConnection();
216     void Free();
217     void FreeBtpEngine();
218
219     // Mutex lock on Tx queue. Used only in BtpEngine test build for now.
220 #if CHIP_ENABLE_CHIPOBLE_TEST
221     inline void QueueTxLock() { mTxQueueMutex.Lock(); }
222     inline void QueueTxUnlock() { mTxQueueMutex.Unlock(); }
223 #else
224     inline void QueueTxLock() {}
225     inline void QueueTxUnlock() {}
226 #endif
227     void QueueTx(PacketBufferHandle && data, PacketType_t type);
228 };
229
230 } /* namespace Ble */
231 } /* namespace chip */