3 * Copyright (c) 2020-2021 Project CHIP Authors
4 * Copyright (c) 2014-2017 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 * 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).
30 #include <system/SystemMutex.h>
32 #include <ble/BleLayer.h>
33 #include <ble/BtpEngine.h>
34 #if CHIP_ENABLE_CHIPOBLE_TEST
35 #include <ble/BtpEngineTest.h>
41 using ::chip::System::PacketBufferHandle;
45 kBleCloseFlag_SuppressCallback = 0x01,
46 kBleCloseFlag_AbortTransmission = 0x02
49 // Forward declarations
51 class BleEndPointPool;
52 #if CHIP_ENABLE_CHIPOBLE_TEST
56 class DLL_EXPORT BLEEndPoint : public BleLayerObject
58 friend class BleLayer;
59 friend class BleEndPointPool;
60 #if CHIP_ENABLE_CHIPOBLE_TEST
61 friend class BtpEngineTest;
65 typedef uint64_t AlignT;
67 // Public data members:
71 kState_Connecting = 1,
76 } mState; // [READ-ONLY] End point connection state. Refers to state of CHIP over
77 // BLE transport protocol connection, not of underlying BLE connection.
79 // Public function pointers:
80 typedef void (*OnConnectCompleteFunct)(BLEEndPoint * endPoint, BLE_ERROR err);
81 OnConnectCompleteFunct OnConnectComplete;
83 typedef void (*OnMessageReceivedFunct)(BLEEndPoint * endPoint, PacketBufferHandle msg);
84 OnMessageReceivedFunct OnMessageReceived;
86 typedef void (*OnConnectionClosedFunct)(BLEEndPoint * endPoint, BLE_ERROR err);
87 OnConnectionClosedFunct OnConnectionClosed;
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; };
99 BLE_ERROR Send(PacketBufferHandle data);
100 BLE_ERROR Receive(PacketBufferHandle data);
101 BLE_ERROR StartConnect();
103 bool IsUnsubscribePending() const;
104 bool ConnectionObjectIs(BLE_CONNECTION_OBJECT connObj) { return connObj == mConnObj; }
109 // Private data members:
110 enum class ConnectionStateFlag : uint8_t
112 kAutoClose = 0x01, // End point should close underlying BLE conn on BTP close.
113 kCapabilitiesConfReceived = 0x02, // GATT confirmation received for sent capabilities req/resp.
114 kCapabilitiesMsgReceived = 0x04, // Capabilities request or response message received.
115 kDidBeginSubscribe = 0x08, // GATT subscribe request sent; must unsubscribe on close.
116 kStandAloneAckInFlight = 0x10, // Stand-alone ack in flight, awaiting GATT confirmation.
117 kGattOperationInFlight = 0x20 // GATT write, indication, subscribe, or unsubscribe in flight,
118 // awaiting GATT confirmation.
121 enum class TimerStateFlag : uint8_t
123 kConnectTimerRunning = 0x01, // BTP connect completion timer running.
124 kReceiveConnectionTimerRunning = 0x02, // BTP receive connection completion timer running.
125 kAckReceivedTimerRunning = 0x04, // Ack received timer running due to unacked sent fragment.
126 kSendAckTimerRunning = 0x08, // Send ack timer running; indicates pending ack to send.
127 kUnsubscribeTimerRunning = 0x10, // Unsubscribe completion timer running.
128 #if CHIP_ENABLE_CHIPOBLE_TEST
129 kUnderTestTimerRunnung = 0x80 // running throughput Tx test
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;
138 // Queue of outgoing messages to send when current BtpEngine transmission completes.
140 // Re-used during connection setup to cache capabilities request and response payloads; payloads are freed when
141 // connection is established.
142 PacketBufferHandle mSendQueue;
144 // Pending stand-alone BTP acknolwedgement. Pre-empts regular send queue or fragmented message transmission in
146 PacketBufferHandle mAckToSend;
148 BtpEngine mBtpEngine;
150 BitFlags<ConnectionStateFlag> mConnStateFlags;
151 BitFlags<TimerStateFlag> 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
159 // Private functions:
160 BLEEndPoint() = delete;
161 ~BLEEndPoint() = delete;
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);
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);
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);
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.
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);
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();
217 void FreeBtpEngine();
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(); }
224 inline void QueueTxLock() {}
225 inline void QueueTxUnlock() {}
227 void QueueTx(PacketBufferHandle && data, PacketType_t type);
230 } /* namespace Ble */
231 } /* namespace chip */