1 /*
2 * Copyright (C) 2018 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 #define LOG_TAG "CommConn"
18
19 #include <thread>
20
21 #include <log/log.h>
22
23 #include "CommConn.h"
24
25 namespace android {
26 namespace hardware {
27 namespace automotive {
28 namespace vehicle {
29 namespace V2_0 {
30
31 namespace impl {
32
start()33 void CommConn::start() {
34 mReadThread = std::make_unique<std::thread>(std::bind(&CommConn::readThread, this));
35 }
36
stop()37 void CommConn::stop() {
38 if (mReadThread->joinable()) {
39 mReadThread->join();
40 }
41 }
42
sendMessage(vhal_proto::EmulatorMessage const & msg)43 void CommConn::sendMessage(vhal_proto::EmulatorMessage const& msg) {
44 int numBytes = msg.ByteSize();
45 std::vector<uint8_t> buffer(static_cast<size_t>(numBytes));
46 if (!msg.SerializeToArray(buffer.data(), numBytes)) {
47 ALOGE("%s: SerializeToString failed!", __func__);
48 return;
49 }
50
51 std::lock_guard<std::mutex> lock(mSendMessageLock);
52
53 write(buffer);
54 }
55
readThread()56 void CommConn::readThread() {
57 std::vector<uint8_t> buffer;
58 while (isOpen()) {
59 buffer = read();
60 if (buffer.size() == 0) {
61 ALOGI("%s: Read returned empty message, exiting read loop.", __func__);
62 break;
63 }
64
65 vhal_proto::EmulatorMessage rxMsg;
66 if (rxMsg.ParseFromArray(buffer.data(), static_cast<int32_t>(buffer.size()))) {
67 vhal_proto::EmulatorMessage respMsg;
68 mMessageProcessor->processMessage(rxMsg, &respMsg);
69
70 sendMessage(respMsg);
71 }
72 }
73 }
74
75 } // namespace impl
76
77 } // namespace V2_0
78 } // namespace vehicle
79 } // namespace automotive
80 } // namespace hardware
81 } // namespace android
82