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 "fake_link.h"
18
19 #include <cstring>
20
21 #include "chpp/log.h"
22 #include "packet_util.h"
23
24 namespace chpp::test {
25
appendTxPacket(uint8_t * data,size_t len)26 void FakeLink::appendTxPacket(uint8_t *data, size_t len) {
27 std::vector<uint8_t> pkt;
28 pkt.resize(len);
29 memcpy(pkt.data(), data, len);
30 checkPacketValidity(pkt);
31 {
32 std::lock_guard<std::mutex> lock(mMutex);
33 mTxPackets.emplace_back(std::move(pkt));
34 mTxCondVar.notify_all();
35 }
36 }
37
getTxPacketCount()38 int FakeLink::getTxPacketCount() {
39 std::lock_guard<std::mutex> lock(mMutex);
40 return static_cast<int>(mTxPackets.size());
41 }
42
waitForTxPacket(std::chrono::milliseconds timeout)43 bool FakeLink::waitForTxPacket(std::chrono::milliseconds timeout) {
44 std::unique_lock<std::mutex> lock(mMutex);
45 auto now = std::chrono::system_clock::now();
46 CHPP_LOGD("FakeLink::waitForTxPacket waiting...");
47 return mTxCondVar.wait_until(lock, now + timeout,
48 [this] { return !mTxPackets.empty(); });
49 }
50
waitForEmpty(std::chrono::milliseconds timeout)51 bool FakeLink::waitForEmpty(std::chrono::milliseconds timeout) {
52 std::unique_lock<std::mutex> lock(mMutex);
53 auto now = std::chrono::system_clock::now();
54 CHPP_LOGD("FakeLink::waitForEmpty waiting...");
55 return mRxCondVar.wait_until(lock, now + timeout,
56 [this] { return mTxPackets.empty(); });
57 }
58
popTxPacket()59 std::vector<uint8_t> FakeLink::popTxPacket() {
60 std::lock_guard<std::mutex> lock(mMutex);
61 assert(!mTxPackets.empty());
62 std::vector<uint8_t> vec = std::move(mTxPackets.front());
63 mTxPackets.pop_front();
64 mRxCondVar.notify_all();
65 return vec;
66 }
67
reset()68 void FakeLink::reset() {
69 std::lock_guard<std::mutex> lock(mMutex);
70 mTxPackets.clear();
71 }
72
73 } // namespace chpp::test