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 write(buffer);
52 }
53
readThread()54 void CommConn::readThread() {
55 std::vector<uint8_t> buffer;
56 while (isOpen()) {
57 buffer = read();
58 if (buffer.size() == 0) {
59 ALOGI("%s: Read returned empty message, exiting read loop.", __func__);
60 break;
61 }
62
63 vhal_proto::EmulatorMessage rxMsg;
64 if (rxMsg.ParseFromArray(buffer.data(), static_cast<int32_t>(buffer.size()))) {
65 vhal_proto::EmulatorMessage respMsg;
66 mMessageProcessor->processMessage(rxMsg, &respMsg);
67
68 sendMessage(respMsg);
69 }
70 }
71 }
72
73 } // namespace impl
74
75 } // namespace V2_0
76 } // namespace vehicle
77 } // namespace automotive
78 } // namespace hardware
79 } // namespace android
80