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