forked from project-chip/connectedhomeip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBLEEndPoint.cpp
1507 lines (1246 loc) · 55.2 KB
/
BLEEndPoint.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
*
* Copyright (c) 2020-2021 Project CHIP Authors
* Copyright (c) 2014-2017 Nest Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file
* This file implements a Bluetooth Low Energy (BLE) connection
* endpoint abstraction for the byte-streaming,
* connection-oriented CHIP over Bluetooth Low Energy (CHIPoBLE)
* Bluetooth Transport Protocol (BTP).
*
*/
#define _CHIP_BLE_BLE_H
#include "BLEEndPoint.h"
#include <cstdint>
#include <cstring>
#include <utility>
#include <lib/support/BitFlags.h>
#include <lib/support/CodeUtils.h>
#include <lib/support/logging/CHIPLogging.h>
#include <system/SystemClock.h>
#include <system/SystemLayer.h>
#include <system/SystemPacketBuffer.h>
#include "BleApplicationDelegate.h"
#include "BleConfig.h"
#include "BleError.h"
#include "BleLayer.h"
#include "BleLayerDelegate.h"
#include "BlePlatformDelegate.h"
#include "BleRole.h"
#include "BleUUID.h"
#include "BtpEngine.h"
// Define below to enable extremely verbose, BLE end point-specific debug logging.
#undef CHIP_BLE_END_POINT_DEBUG_LOGGING_ENABLED
#ifdef CHIP_BLE_END_POINT_DEBUG_LOGGING_ENABLED
#define ChipLogDebugBleEndPoint(MOD, MSG, ...) ChipLogDetail(MOD, MSG, ##__VA_ARGS__)
#else
#define ChipLogDebugBleEndPoint(MOD, MSG, ...)
#endif
/**
* @def BLE_CONFIG_IMMEDIATE_ACK_WINDOW_THRESHOLD
*
* @brief
* If an end point's receive window drops equal to or below this value, it will send an immediate acknowledgement
* packet to re-open its window instead of waiting for the send-ack timer to expire.
*
*/
#define BLE_CONFIG_IMMEDIATE_ACK_WINDOW_THRESHOLD 1
/**
* @def BLE_UNSUBSCRIBE_TIMEOUT_MS
*
* @brief
* This is amount of time, in milliseconds, which a BLE end point will wait for an unsubscribe operation to complete
* before it automatically releases its BLE connection and frees itself. The default value of 5 seconds is arbitrary.
*
*/
#define BLE_UNSUBSCRIBE_TIMEOUT_MS 5000
#define BTP_ACK_SEND_TIMEOUT_MS 2500
/**
* @def BTP_WINDOW_NO_ACK_SEND_THRESHOLD
*
* @brief
* Data fragments may only be sent without piggybacked acks if receiver's window size is above this threshold.
*
*/
#define BTP_WINDOW_NO_ACK_SEND_THRESHOLD 1
namespace chip {
namespace Ble {
CHIP_ERROR BLEEndPoint::StartConnect()
{
CHIP_ERROR err = CHIP_NO_ERROR;
BleTransportCapabilitiesRequestMessage req;
PacketBufferHandle buf;
constexpr uint8_t numVersions =
CHIP_BLE_TRANSPORT_PROTOCOL_MAX_SUPPORTED_VERSION - CHIP_BLE_TRANSPORT_PROTOCOL_MIN_SUPPORTED_VERSION + 1;
static_assert(numVersions <= NUM_SUPPORTED_PROTOCOL_VERSIONS, "Incompatibly protocol versions");
// Ensure we're in the correct state.
VerifyOrExit(mState == kState_Ready, err = CHIP_ERROR_INCORRECT_STATE);
mState = kState_Connecting;
// Build BLE transport protocol capabilities request.
buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize);
VerifyOrExit(!buf.IsNull(), err = CHIP_ERROR_NO_MEMORY);
// Zero-initialize BLE transport capabilities request.
memset(&req, 0, sizeof(req));
req.mMtu = mBle->mPlatformDelegate->GetMTU(mConnObj);
req.mWindowSize = BLE_MAX_RECEIVE_WINDOW_SIZE;
// Populate request with highest supported protocol versions
for (uint8_t i = 0; i < numVersions; i++)
{
req.SetSupportedProtocolVersion(i, static_cast<uint8_t>(CHIP_BLE_TRANSPORT_PROTOCOL_MAX_SUPPORTED_VERSION - i));
}
err = req.Encode(buf);
SuccessOrExit(err);
// Start connect timer. Canceled when end point freed or connection established.
err = StartConnectTimer();
SuccessOrExit(err);
// Send BLE transport capabilities request to peripheral via GATT write.
// Add reference to message fragment for duration of platform's GATT write attempt. CHIP retains partial
// ownership of message fragment's packet buffer, since this is the same buffer as that of the whole message, just
// with a fragmenter-modified payload offset and data length, by a Retain() on the handle when calling this function.
if (!SendWrite(buf.Retain()))
{
err = BLE_ERROR_GATT_WRITE_FAILED;
ExitNow();
}
// Free request buffer on write confirmation. Stash a reference to it in mSendQueue, which we don't use anyway
// until the connection has been set up.
QueueTx(std::move(buf), kType_Data);
exit:
// If we failed to initiate the connection, close the end point.
if (err != CHIP_NO_ERROR)
{
StopConnectTimer();
DoClose(kBleCloseFlag_AbortTransmission, err);
}
return err;
}
CHIP_ERROR BLEEndPoint::HandleConnectComplete()
{
CHIP_ERROR err = CHIP_NO_ERROR;
mState = kState_Connected;
// Cancel the connect timer.
StopConnectTimer();
// We've successfully completed the BLE transport protocol handshake, so let the application know we're open for business.
if (mBleTransport != nullptr)
{
// Indicate connect complete to next-higher layer.
mBleTransport->OnEndPointConnectComplete(this, CHIP_NO_ERROR);
}
else
{
// If no connect complete callback has been set up, close the end point.
err = BLE_ERROR_NO_CONNECT_COMPLETE_CALLBACK;
}
return err;
}
CHIP_ERROR BLEEndPoint::HandleReceiveConnectionComplete()
{
CHIP_ERROR err = CHIP_NO_ERROR;
ChipLogDebugBleEndPoint(Ble, "entered HandleReceiveConnectionComplete");
mState = kState_Connected;
// Cancel receive connection timer.
StopReceiveConnectionTimer();
// We've successfully completed the BLE transport protocol handshake, so let the transport know we're open for business.
if (mBleTransport != nullptr)
{
// Indicate BLE transport protocol connection received to next-higher layer.
err = mBleTransport->SetEndPoint(this);
}
else
{
err = BLE_ERROR_NO_CONNECTION_RECEIVED_CALLBACK;
}
return err;
}
void BLEEndPoint::HandleSubscribeReceived()
{
CHIP_ERROR err = CHIP_NO_ERROR;
VerifyOrExit(mState == kState_Connecting || mState == kState_Aborting, err = CHIP_ERROR_INCORRECT_STATE);
VerifyOrExit(!mSendQueue.IsNull(), err = CHIP_ERROR_INCORRECT_STATE);
// Send BTP capabilities response to peripheral via GATT indication.
// Add reference to message fragment for duration of platform's GATT indication attempt. CHIP retains partial
// ownership of message fragment's packet buffer, since this is the same buffer as that of the whole message, just
// with a fragmenter-modified payload offset and data length.
if (!SendIndication(mSendQueue.Retain()))
{
// Ensure transmit queue is empty and set to NULL.
mSendQueue = nullptr;
ChipLogError(Ble, "cap resp ind failed");
err = BLE_ERROR_GATT_INDICATE_FAILED;
ExitNow();
}
// Shrink remote receive window counter by 1, since we've sent an indication which requires acknowledgement.
mRemoteReceiveWindowSize = static_cast<SequenceNumber_t>(mRemoteReceiveWindowSize - 1);
ChipLogDebugBleEndPoint(Ble, "decremented remote rx window, new size = %u", mRemoteReceiveWindowSize);
// Start ack recvd timer for handshake indication.
err = StartAckReceivedTimer();
SuccessOrExit(err);
ChipLogDebugBleEndPoint(Ble, "got subscribe, sent indication w/ capabilities response");
// If SendIndication returns true, mSendQueue is freed on indication confirmation, or on close in case of
// connection error.
if (mState != kState_Aborting)
{
// If peripheral accepted the BTP connection, its end point must enter the connected state here, i.e. before it
// receives a GATT confirmation for the capabilities response indication. This behavior is required to handle the
// case where a peripheral's BLE controller passes up the central's first message fragment write before the
// capabilities response indication confirmation. If the end point waited for this indication confirmation before
// it entered the connected state, it'd be in the wrong state to receive the central's first data write, and drop
// the corresponding message fragment.
err = HandleReceiveConnectionComplete();
SuccessOrExit(err);
} // Else State == kState_Aborting, so we'll close end point when indication confirmation received.
exit:
if (err != CHIP_NO_ERROR)
{
DoClose(kBleCloseFlag_SuppressCallback | kBleCloseFlag_AbortTransmission, err);
}
}
void BLEEndPoint::HandleSubscribeComplete()
{
ChipLogProgress(Ble, "subscribe complete, ep = %p", this);
mConnStateFlags.Clear(ConnectionStateFlag::kGattOperationInFlight);
CHIP_ERROR err = DriveSending();
if (err != CHIP_NO_ERROR)
{
DoClose(kBleCloseFlag_AbortTransmission, CHIP_NO_ERROR);
}
}
void BLEEndPoint::HandleUnsubscribeComplete()
{
// Don't bother to clear GattOperationInFlight, we're about to free the end point anyway.
Free();
}
bool BLEEndPoint::IsConnected(uint8_t state) const
{
return (state == kState_Connected || state == kState_Closing);
}
bool BLEEndPoint::IsUnsubscribePending() const
{
return mTimerStateFlags.Has(TimerStateFlag::kUnsubscribeTimerRunning);
}
void BLEEndPoint::Abort()
{
// No more callbacks after this point, since application explicitly called Abort().
OnConnectComplete = nullptr;
OnConnectionClosed = nullptr;
OnMessageReceived = nullptr;
DoClose(kBleCloseFlag_SuppressCallback | kBleCloseFlag_AbortTransmission, CHIP_NO_ERROR);
}
void BLEEndPoint::Close()
{
// No more callbacks after this point, since application explicitly called Close().
OnConnectComplete = nullptr;
OnConnectionClosed = nullptr;
OnMessageReceived = nullptr;
DoClose(kBleCloseFlag_SuppressCallback, CHIP_NO_ERROR);
}
void BLEEndPoint::DoClose(uint8_t flags, CHIP_ERROR err)
{
uint8_t oldState = mState;
// If end point is not closed or closing, OR end point was closing gracefully, but tx abort has been specified...
if ((mState != kState_Closed && mState != kState_Closing) ||
(mState == kState_Closing && (flags & kBleCloseFlag_AbortTransmission)))
{
// Cancel Connect and ReceiveConnect timers if they are running.
// Check role first to avoid needless iteration over timer pool.
if (mRole == kBleRole_Central)
{
StopConnectTimer();
}
else // (mRole == kBleRole_Peripheral), verified on Init
{
StopReceiveConnectionTimer();
}
// If transmit buffer is empty or a transmission abort was specified...
if (mBtpEngine.TxState() == BtpEngine::kState_Idle || (flags & kBleCloseFlag_AbortTransmission))
{
FinalizeClose(oldState, flags, err);
}
else
{
// Wait for send queue and fragmenter's tx buffer to become empty, to ensure all pending messages have been
// sent. Only free end point and tell platform it can throw away the underlying BLE connection once all
// pending messages have been sent and acknowledged by the remote CHIPoBLE stack, or once the remote stack
// closes the CHIPoBLE connection.
//
// In so doing, BLEEndPoint attempts to emulate the level of reliability afforded by TCPEndPoint and TCP
// sockets in general with a typical default SO_LINGER option. That said, there is no hard guarantee that
// pending messages will be sent once (Do)Close() is called, so developers should use application-level
// messages to confirm the receipt of all data sent prior to a Close() call.
mState = kState_Closing;
if ((flags & kBleCloseFlag_SuppressCallback) == 0)
{
DoCloseCallback(oldState, flags, err);
}
if (mBleTransport != nullptr && (flags & kBleCloseFlag_SuppressCallback) != 0)
{
mBleTransport->OnEndPointConnectionClosed(this, err);
}
}
}
}
void BLEEndPoint::FinalizeClose(uint8_t oldState, uint8_t flags, CHIP_ERROR err)
{
mState = kState_Closed;
// Ensure transmit queue is empty and set to NULL.
mSendQueue = nullptr;
// Fire application's close callback if we haven't already, and it's not suppressed.
if (oldState != kState_Closing && (flags & kBleCloseFlag_SuppressCallback) == 0)
{
DoCloseCallback(oldState, flags, err);
}
if (mBleTransport != nullptr && (flags & kBleCloseFlag_SuppressCallback) != 0)
{
mBleTransport->OnEndPointConnectionClosed(this, err);
}
// If underlying BLE connection has closed, connection object is invalid, so just free the end point and return.
if (err == BLE_ERROR_REMOTE_DEVICE_DISCONNECTED || err == BLE_ERROR_APP_CLOSED_CONNECTION)
{
mConnObj = BLE_CONNECTION_UNINITIALIZED; // Clear handle to BLE connection, so we don't double-close it.
Free();
}
else // Otherwise, try to signal close to remote device before end point releases BLE connection and frees itself.
{
if (mRole == kBleRole_Central && mConnStateFlags.Has(ConnectionStateFlag::kDidBeginSubscribe))
{
// Cancel send and receive-ack timers, if running.
StopAckReceivedTimer();
StopSendAckTimer();
// Indicate close of chipConnection to peripheral via GATT unsubscribe. Keep end point allocated until
// unsubscribe completes or times out, so platform doesn't close underlying BLE connection before
// we're really sure the unsubscribe request has been sent.
if (!mBle->mPlatformDelegate->UnsubscribeCharacteristic(mConnObj, &CHIP_BLE_SVC_ID, &CHIP_BLE_CHAR_2_UUID))
{
ChipLogError(Ble, "BtpEngine unsub failed");
// If unsubscribe fails, release BLE connection and free end point immediately.
Free();
}
else if (mConnObj != BLE_CONNECTION_UNINITIALIZED)
{
// Unsubscribe request was sent successfully, and a confirmation wasn't spontaneously generated or
// received in the downcall to UnsubscribeCharacteristic, so set timer for the unsubscribe to complete.
err = StartUnsubscribeTimer();
if (err != CHIP_NO_ERROR)
{
Free();
}
// Mark unsubscribe GATT operation in progress.
mConnStateFlags.Set(ConnectionStateFlag::kGattOperationInFlight);
}
}
else // mRole == kBleRole_Peripheral, OR mTimerStateFlags.Has(ConnectionStateFlag::kDidBeginSubscribe) == false...
{
Free();
}
}
}
void BLEEndPoint::DoCloseCallback(uint8_t state, uint8_t flags, CHIP_ERROR err)
{
if (state == kState_Connecting)
{
if (mBleTransport != nullptr)
{
mBleTransport->OnEndPointConnectComplete(this, err);
}
}
else
{
if (mBleTransport != nullptr)
{
mBleTransport->OnEndPointConnectionClosed(this, err);
}
}
// Callback fires once per end point lifetime.
OnConnectComplete = nullptr;
OnConnectionClosed = nullptr;
}
void BLEEndPoint::ReleaseBleConnection()
{
if (mConnObj != BLE_CONNECTION_UNINITIALIZED)
{
if (mConnStateFlags.Has(ConnectionStateFlag::kAutoClose))
{
ChipLogProgress(Ble, "Auto-closing end point's BLE connection.");
mBle->mPlatformDelegate->CloseConnection(mConnObj);
}
else
{
ChipLogProgress(Ble, "Releasing end point's BLE connection back to application.");
mBle->mApplicationDelegate->NotifyChipConnectionClosed(mConnObj);
}
// Never release the same BLE connection twice.
mConnObj = BLE_CONNECTION_UNINITIALIZED;
}
}
void BLEEndPoint::Free()
{
// Release BLE connection. Will close connection if AutoClose enabled for this end point. Otherwise, informs
// application that CHIP is done with this BLE connection, and application makes decision about whether to close
// and clean up or retain connection.
ReleaseBleConnection();
// Clear fragmentation and reassembly engine's Tx and Rx buffers. Counters will be reset by next engine init.
FreeBtpEngine();
// Clear pending ack buffer, if any.
mAckToSend = nullptr;
// Cancel all timers.
StopConnectTimer();
StopReceiveConnectionTimer();
StopAckReceivedTimer();
StopSendAckTimer();
StopUnsubscribeTimer();
// Clear callbacks.
OnConnectComplete = nullptr;
OnMessageReceived = nullptr;
OnConnectionClosed = nullptr;
// Clear handle to underlying BLE connection.
mConnObj = BLE_CONNECTION_UNINITIALIZED;
// Release the AddRef() that happened when the end point was allocated.
Release();
}
void BLEEndPoint::FreeBtpEngine()
{
// Free transmit disassembly buffer
mBtpEngine.ClearTxPacket();
// Free receive reassembly buffer
mBtpEngine.ClearRxPacket();
}
CHIP_ERROR BLEEndPoint::Init(BleLayer * bleLayer, BLE_CONNECTION_OBJECT connObj, BleRole role, bool autoClose)
{
// Fail if already initialized.
VerifyOrReturnError(mBle == nullptr, CHIP_ERROR_INCORRECT_STATE);
// Validate args.
VerifyOrReturnError(bleLayer != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrReturnError(connObj != BLE_CONNECTION_UNINITIALIZED, CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrReturnError((role == kBleRole_Central || role == kBleRole_Peripheral), CHIP_ERROR_INVALID_ARGUMENT);
// If end point plays peripheral role, expect ack for indication sent as last step of BTP handshake.
// If central, peripheral's handshake indication 'ack's write sent by central to kick off the BTP handshake.
bool expectInitialAck = (role == kBleRole_Peripheral);
CHIP_ERROR err = mBtpEngine.Init(this, expectInitialAck);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Ble, "BtpEngine init failed");
return err;
}
mBle = bleLayer;
mRefCount = 1;
// BLEEndPoint data members:
mConnObj = connObj;
mRole = role;
mTimerStateFlags.ClearAll();
mConnStateFlags.ClearAll().Set(ConnectionStateFlag::kAutoClose, autoClose);
mLocalReceiveWindowSize = 0;
mRemoteReceiveWindowSize = 0;
mReceiveWindowMaxSize = 0;
mSendQueue = nullptr;
mAckToSend = nullptr;
ChipLogDebugBleEndPoint(Ble, "initialized local rx window, size = %u", mLocalReceiveWindowSize);
// End point is ready to connect or receive a connection.
mState = kState_Ready;
return CHIP_NO_ERROR;
}
void BLEEndPoint::AddRef()
{
VerifyOrDie(mRefCount < UINT32_MAX);
mRefCount++;
}
void BLEEndPoint::Release()
{
VerifyOrDie(mRefCount > 0u);
// Decrement the ref count. When it reaches zero, NULL out the pointer to the chip::System::Layer
// object. This effectively declared the object free and ready for re-allocation.
mRefCount--;
if (mRefCount == 0)
{
mBle = nullptr;
}
}
CHIP_ERROR BLEEndPoint::SendCharacteristic(PacketBufferHandle && buf)
{
CHIP_ERROR err = CHIP_NO_ERROR;
if (mRole == kBleRole_Central)
{
if (!SendWrite(std::move(buf)))
{
err = BLE_ERROR_GATT_WRITE_FAILED;
}
else
{
// Write succeeded, so shrink remote receive window counter by 1.
mRemoteReceiveWindowSize = static_cast<SequenceNumber_t>(mRemoteReceiveWindowSize - 1);
ChipLogDebugBleEndPoint(Ble, "decremented remote rx window, new size = %u", mRemoteReceiveWindowSize);
}
}
else // (mRole == kBleRole_Peripheral), verified on Init
{
if (!SendIndication(std::move(buf)))
{
err = BLE_ERROR_GATT_INDICATE_FAILED;
}
else
{
// Indication succeeded, so shrink remote receive window counter by 1.
mRemoteReceiveWindowSize = static_cast<SequenceNumber_t>(mRemoteReceiveWindowSize - 1);
ChipLogDebugBleEndPoint(Ble, "decremented remote rx window, new size = %u", mRemoteReceiveWindowSize);
}
}
return err;
}
/*
* Routine to queue the Tx packet with a packet type
* kType_Data(0) - data packet
* kType_Control(1) - control packet
*/
void BLEEndPoint::QueueTx(PacketBufferHandle && data, PacketType_t type)
{
if (mSendQueue.IsNull())
{
mSendQueue = std::move(data);
ChipLogDebugBleEndPoint(Ble, "%s: Set data as new mSendQueue %p, type %d", __FUNCTION__, mSendQueue->Start(), type);
}
else
{
mSendQueue->AddToEnd(std::move(data));
ChipLogDebugBleEndPoint(Ble, "%s: Append data to mSendQueue %p, type %d", __FUNCTION__, mSendQueue->Start(), type);
}
}
CHIP_ERROR BLEEndPoint::Send(PacketBufferHandle && data)
{
ChipLogDebugBleEndPoint(Ble, "entered Send");
CHIP_ERROR err = CHIP_NO_ERROR;
VerifyOrExit(!data.IsNull(), err = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(IsConnected(mState), err = CHIP_ERROR_INCORRECT_STATE);
// Ensure outgoing message fits in a single contiguous packet buffer, as currently required by the
// message fragmentation and reassembly engine.
if (data->HasChainedBuffer())
{
data->CompactHead();
if (data->HasChainedBuffer())
{
err = CHIP_ERROR_OUTBOUND_MESSAGE_TOO_BIG;
ExitNow();
}
}
// Add new message to send queue.
QueueTx(std::move(data), kType_Data);
// Send first fragment of new message, if we can.
err = DriveSending();
SuccessOrExit(err);
exit:
ChipLogDebugBleEndPoint(Ble, "exiting Send");
if (err != CHIP_NO_ERROR)
{
DoClose(kBleCloseFlag_AbortTransmission, err);
}
return err;
}
bool BLEEndPoint::PrepareNextFragment(PacketBufferHandle && data, bool & sentAck)
{
// If we have a pending fragment acknowledgement to send, piggyback it on the fragment we're about to transmit.
if (mTimerStateFlags.Has(TimerStateFlag::kSendAckTimerRunning))
{
// Reset local receive window counter.
mLocalReceiveWindowSize = mReceiveWindowMaxSize;
ChipLogDebugBleEndPoint(Ble, "reset local rx window on piggyback ack tx, size = %u", mLocalReceiveWindowSize);
// Tell caller AND fragmenter we have an ack to piggyback.
sentAck = true;
}
else
{
// No ack to piggyback.
sentAck = false;
}
return mBtpEngine.HandleCharacteristicSend(std::move(data), sentAck);
}
CHIP_ERROR BLEEndPoint::SendNextMessage()
{
// Get the first queued packet to send
PacketBufferHandle data = mSendQueue.PopHead();
// Hand whole message payload to the fragmenter.
bool sentAck;
VerifyOrReturnError(PrepareNextFragment(std::move(data), sentAck), BLE_ERROR_CHIPOBLE_PROTOCOL_ABORT);
/*
// Todo: reenabled it after integrating fault injection
// Send first message fragment over the air.
CHIP_FAULT_INJECT(chip::FaultInjection::kFault_CHIPOBLESend, {
if (mRole == kBleRole_Central)
{
err = BLE_ERROR_GATT_WRITE_FAILED;
}
else
{
err = BLE_ERROR_GATT_INDICATE_FAILED;
}
ExitNow();
});
*/
ReturnErrorOnFailure(SendCharacteristic(mBtpEngine.BorrowTxPacket()));
if (sentAck)
{
// If sent piggybacked ack, stop send-ack timer.
StopSendAckTimer();
}
// Start ack received timer, if it's not already running.
return StartAckReceivedTimer();
}
CHIP_ERROR BLEEndPoint::ContinueMessageSend()
{
bool sentAck;
if (!PrepareNextFragment(nullptr, sentAck))
{
// Log BTP error
ChipLogError(Ble, "btp fragmenter error on send!");
mBtpEngine.LogState();
return BLE_ERROR_CHIPOBLE_PROTOCOL_ABORT;
}
ReturnErrorOnFailure(SendCharacteristic(mBtpEngine.BorrowTxPacket()));
if (sentAck)
{
// If sent piggybacked ack, stop send-ack timer.
StopSendAckTimer();
}
// Start ack received timer, if it's not already running.
return StartAckReceivedTimer();
}
CHIP_ERROR BLEEndPoint::HandleHandshakeConfirmationReceived()
{
ChipLogDebugBleEndPoint(Ble, "entered HandleHandshakeConfirmationReceived");
CHIP_ERROR err = CHIP_NO_ERROR;
uint8_t closeFlags = kBleCloseFlag_AbortTransmission;
// Free capabilities request/response payload.
mSendQueue.FreeHead();
if (mRole == kBleRole_Central)
{
// Subscribe to characteristic which peripheral will use to send indications. Prompts peripheral to send
// BLE transport capabilities indication.
VerifyOrExit(mBle->mPlatformDelegate->SubscribeCharacteristic(mConnObj, &CHIP_BLE_SVC_ID, &CHIP_BLE_CHAR_2_UUID),
err = BLE_ERROR_GATT_SUBSCRIBE_FAILED);
// We just sent a GATT subscribe request, so make sure to attempt unsubscribe on close.
mConnStateFlags.Set(ConnectionStateFlag::kDidBeginSubscribe);
// Mark GATT operation in progress for subscribe request.
mConnStateFlags.Set(ConnectionStateFlag::kGattOperationInFlight);
}
else // (mRole == kBleRole_Peripheral), verified on Init
{
ChipLogDebugBleEndPoint(Ble, "got peripheral handshake indication confirmation");
if (mState == kState_Connected) // If we accepted BTP connection...
{
// If local receive window size has shrunk to or below immediate ack threshold, AND a message fragment is not
// pending on which to piggyback an ack, send immediate stand-alone ack.
if (mLocalReceiveWindowSize <= BLE_CONFIG_IMMEDIATE_ACK_WINDOW_THRESHOLD && mSendQueue.IsNull())
{
err = DriveStandAloneAck(); // Encode stand-alone ack and drive sending.
SuccessOrExit(err);
}
else
{
// Drive sending in case application called Send() after we sent the handshake indication, but
// before the GATT confirmation for this indication was received.
err = DriveSending();
SuccessOrExit(err);
}
}
else if (mState == kState_Aborting) // Else, if we rejected BTP connection...
{
closeFlags |= kBleCloseFlag_SuppressCallback;
err = BLE_ERROR_INCOMPATIBLE_PROTOCOL_VERSIONS;
ExitNow();
}
}
exit:
ChipLogDebugBleEndPoint(Ble, "exiting HandleHandshakeConfirmationReceived");
if (err != CHIP_NO_ERROR)
{
DoClose(closeFlags, err);
}
return err;
}
CHIP_ERROR BLEEndPoint::HandleFragmentConfirmationReceived()
{
CHIP_ERROR err = CHIP_NO_ERROR;
ChipLogDebugBleEndPoint(Ble, "entered HandleFragmentConfirmationReceived");
// Suppress error logging if GATT confirmation overlaps with unsubscribe on final close.
if (IsUnsubscribePending())
{
ChipLogDebugBleEndPoint(Ble, "send conf rx'd while unsubscribe in flight");
ExitNow();
}
// Ensure we're in correct state to receive confirmation of non-handshake GATT send.
VerifyOrExit(IsConnected(mState), err = CHIP_ERROR_INCORRECT_STATE);
if (mConnStateFlags.Has(ConnectionStateFlag::kStandAloneAckInFlight))
{
// If confirmation was received for stand-alone ack, free its tx buffer.
mAckToSend = nullptr;
mConnStateFlags.Clear(ConnectionStateFlag::kStandAloneAckInFlight);
}
// If local receive window size has shrunk to or below immediate ack threshold, AND a message fragment is not
// pending on which to piggyback an ack, send immediate stand-alone ack.
//
// This check covers the case where the local receive window has shrunk between transmission and confirmation of
// the stand-alone ack, and also the case where a window size < the immediate ack threshold was detected in
// Receive(), but the stand-alone ack was deferred due to a pending outbound message fragment.
if (mLocalReceiveWindowSize <= BLE_CONFIG_IMMEDIATE_ACK_WINDOW_THRESHOLD && mSendQueue.IsNull() &&
mBtpEngine.TxState() != BtpEngine::kState_InProgress)
{
err = DriveStandAloneAck(); // Encode stand-alone ack and drive sending.
SuccessOrExit(err);
}
else
{
err = DriveSending();
SuccessOrExit(err);
}
exit:
if (err != CHIP_NO_ERROR)
{
DoClose(kBleCloseFlag_AbortTransmission, err);
}
return err;
}
CHIP_ERROR BLEEndPoint::HandleGattSendConfirmationReceived()
{
ChipLogDebugBleEndPoint(Ble, "entered HandleGattSendConfirmationReceived");
// Mark outstanding GATT operation as finished.
mConnStateFlags.Clear(ConnectionStateFlag::kGattOperationInFlight);
// If confirmation was for outbound portion of BTP connect handshake...
if (!mConnStateFlags.Has(ConnectionStateFlag::kCapabilitiesConfReceived))
{
mConnStateFlags.Set(ConnectionStateFlag::kCapabilitiesConfReceived);
return HandleHandshakeConfirmationReceived();
}
return HandleFragmentConfirmationReceived();
}
CHIP_ERROR BLEEndPoint::DriveStandAloneAck()
{
// Stop send-ack timer if running.
StopSendAckTimer();
// If stand-alone ack not already pending, allocate new payload buffer here.
if (mAckToSend.IsNull())
{
mAckToSend = System::PacketBufferHandle::New(kTransferProtocolStandaloneAckHeaderSize);
VerifyOrReturnError(!mAckToSend.IsNull(), CHIP_ERROR_NO_MEMORY);
}
// Attempt to send stand-alone ack.
return DriveSending();
}
CHIP_ERROR BLEEndPoint::DoSendStandAloneAck()
{
ChipLogDebugBleEndPoint(Ble, "entered DoSendStandAloneAck; sending stand-alone ack");
// Encode and transmit stand-alone ack.
mBtpEngine.EncodeStandAloneAck(mAckToSend);
ReturnErrorOnFailure(SendCharacteristic(mAckToSend.Retain()));
// Reset local receive window counter.
mLocalReceiveWindowSize = mReceiveWindowMaxSize;
ChipLogDebugBleEndPoint(Ble, "reset local rx window on stand-alone ack tx, size = %u", mLocalReceiveWindowSize);
mConnStateFlags.Set(ConnectionStateFlag::kStandAloneAckInFlight);
// Start ack received timer, if it's not already running.
return StartAckReceivedTimer();
}
CHIP_ERROR BLEEndPoint::DriveSending()
{
ChipLogDebugBleEndPoint(Ble, "entered DriveSending");
// If receiver's window is almost closed and we don't have an ack to send, OR we do have an ack to send but
// receiver's window is completely empty, OR another GATT operation is in flight, awaiting confirmation...
if ((mRemoteReceiveWindowSize <= BTP_WINDOW_NO_ACK_SEND_THRESHOLD &&
!mTimerStateFlags.Has(TimerStateFlag::kSendAckTimerRunning) && mAckToSend.IsNull()) ||
(mRemoteReceiveWindowSize == 0) || (mConnStateFlags.Has(ConnectionStateFlag::kGattOperationInFlight)))
{
#ifdef CHIP_BLE_END_POINT_DEBUG_LOGGING_ENABLED
if (mRemoteReceiveWindowSize <= BTP_WINDOW_NO_ACK_SEND_THRESHOLD &&
!mTimerStateFlags.Has(TimerStateFlag::kSendAckTimerRunning) && mAckToSend.IsNull())
{
ChipLogDebugBleEndPoint(Ble, "NO SEND: receive window almost closed, and no ack to send");
}
if (mRemoteReceiveWindowSize == 0)
{
ChipLogDebugBleEndPoint(Ble, "NO SEND: remote receive window closed");
}
if (mConnStateFlags.Has(ConnectionStateFlag::kGattOperationInFlight))
{
ChipLogDebugBleEndPoint(Ble, "NO SEND: Gatt op in flight");
}
#endif
// Can't send anything.
return CHIP_NO_ERROR;
}
// Otherwise, let's see what we can send.
if (!mAckToSend.IsNull()) // If immediate, stand-alone ack is pending, send it.
{
ReturnErrorOnFailure(DoSendStandAloneAck());
}
else if (mBtpEngine.TxState() == BtpEngine::kState_Idle) // Else send next message fragment, if any.
{
// Fragmenter's idle, let's see what's in the send queue...
if (!mSendQueue.IsNull())
{
// Transmit first fragment of next whole message in send queue.
ReturnErrorOnFailure(SendNextMessage());
}
else
{
// Nothing to send!
}
}
else if (mBtpEngine.TxState() == BtpEngine::kState_InProgress)
{
// Send next fragment of message currently held by fragmenter.
ReturnErrorOnFailure(ContinueMessageSend());
}
else if (mBtpEngine.TxState() == BtpEngine::kState_Complete)
{
// Clear fragmenter's pointer to sent message buffer and reset its Tx state.
// Buffer will be freed at scope exit.
PacketBufferHandle sentBuf = mBtpEngine.TakeTxPacket();
if (!mSendQueue.IsNull())
{
// Transmit first fragment of next whole message in send queue.
ReturnErrorOnFailure(SendNextMessage());
}
else if (mState == kState_Closing && !mBtpEngine.ExpectingAck()) // and mSendQueue is NULL, per above...
{
// If end point closing, got last ack, and got out-of-order confirmation for last send, finalize close.
FinalizeClose(mState, kBleCloseFlag_SuppressCallback, CHIP_NO_ERROR);
}
else
{
// Nothing to send!
mBle->mApplicationDelegate->CheckNonConcurrentBleClosing();
}
}
return CHIP_NO_ERROR;
}
CHIP_ERROR BLEEndPoint::HandleCapabilitiesRequestReceived(PacketBufferHandle && data)
{
BleTransportCapabilitiesRequestMessage req;
BleTransportCapabilitiesResponseMessage resp;
uint16_t mtu;
VerifyOrReturnError(!data.IsNull(), CHIP_ERROR_INVALID_ARGUMENT);
mState = kState_Connecting;
// Decode BTP capabilities request.
ReturnErrorOnFailure(BleTransportCapabilitiesRequestMessage::Decode(data, req));
PacketBufferHandle responseBuf = System::PacketBufferHandle::New(kCapabilitiesResponseLength);