xref: /aosp_15_r20/system/chre/chpp/test/fake_link.h (revision 84e339476a462649f82315436d70fd732297a399)
1 /*
2  * Copyright (C) 2022 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <chrono>
18 #include <condition_variable>
19 #include <cstdint>
20 #include <deque>
21 #include <mutex>
22 #include <vector>
23 
24 #include <android-base/thread_annotations.h>
25 
26 #include "chpp/transport.h"
27 
28 using ::std::literals::chrono_literals::operator""ms;
29 
30 namespace chpp::test {
31 
32 /**
33  * Wrapper for a fake CHPP link layer which puts outgoing packets on a queue
34  * where they can be extracted and inspected.
35  */
36 class FakeLink {
37  public:
38   //! How long CHPP is expected to wait on an ACK for a transmitted packet
39   static constexpr auto kTransportTimeout =
40       std::chrono::duration_cast<std::chrono::milliseconds>(
41           std::chrono::nanoseconds(CHPP_TRANSPORT_TX_TIMEOUT_NS));
42 
43   // Our default timeout covers the retry timeout, plus some extra buffer to
44   // account for processing delays
45   static constexpr auto kDefaultTimeout = 10 * (kTransportTimeout + 5ms);
46 
47   /**
48    * Call from link send. Makes a copy of the provided buffer and
49    * appends it to the TX packet queue.
50    */
51   void appendTxPacket(uint8_t *data, size_t len);
52 
53   //! Returns the number of TX packets waiting to be popped
54   int getTxPacketCount();  // int to make EXPECT_EQ against a literal simpler
55                            // with -Wsign-compare enabled
56 
57   /**
58    * Wait up to the provided timeout for a packet to hit the TX queue, or return
59    * immediately if a packet is already waiting to be popped.
60    *
61    * @return true if a packet is waiting, false on timeout
62    */
63   bool waitForTxPacket(std::chrono::milliseconds timeout = kDefaultTimeout);
64 
65   //! Pop and return the oldest packet on the TX queue, or assert if queue is
66   //! empty
67   std::vector<uint8_t> popTxPacket();
68 
69   //! Empties the TX packet queue
70   void reset();
71 
72  private:
73   std::mutex mMutex;
74   std::condition_variable mCondVar;
75   std::deque<std::vector<uint8_t>> mTxPackets GUARDED_BY(mMutex);
76 };
77 
78 }  // namespace chpp::test