1 /* 2 * Copyright (C) 2017 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 #ifndef ANDROID_EMULATORSOCKETCOMM_SOCKETCOMM_H 18 #define ANDROID_EMULATORSOCKETCOMM_SOCKETCOMM_H 19 20 #include <mutex> 21 #include <thread> 22 #include <vector> 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 33 class SocketConn; 34 35 /** 36 * SocketComm opens a socket, and listens for connections from clients. Typically the client will be 37 * adb's TCP port-forwarding to enable a host PC to connect to the VehicleHAL. 38 */ 39 class SocketComm : public MessageSender { 40 public: 41 SocketComm(MessageProcessor* messageProcessor); 42 virtual ~SocketComm(); 43 44 void start() override; 45 void stop() override ; 46 47 /** 48 * Serialized and send the given message to all connected clients. 49 */ 50 void sendMessage(vhal_proto::EmulatorMessage const& msg) override; 51 52 private: 53 int mListenFd; 54 std::unique_ptr<std::thread> mListenThread; 55 std::vector<std::unique_ptr<SocketConn>> mOpenConnections; 56 MessageProcessor* mMessageProcessor; 57 std::mutex mMutex; 58 59 /** 60 * Opens the socket and begins listening. 61 * 62 * @return bool Returns true on success. 63 */ 64 bool listen(); 65 66 /** 67 * Blocks and waits for a connection from a client, returns a new SocketConn with the connection 68 * or null, if the connection has been closed. 69 * 70 * @return int Returns fd or socket number if connection is successful. 71 * Otherwise, returns -1 if no connection is available. 72 */ 73 SocketConn* accept(); 74 75 void listenThread(); 76 77 void removeClosedConnections(); 78 }; 79 80 /** 81 * SocketConn represents a single connection to a client. 82 */ 83 class SocketConn : public CommConn { 84 public: 85 SocketConn(MessageProcessor* messageProcessor, int sfd); 86 virtual ~SocketConn() = default; 87 88 void stop() override; 89 isOpen()90 inline bool isOpen() override { return mSockFd > 0; } 91 92 private: 93 int mSockFd; 94 95 std::vector<uint8_t> read() override; 96 int write(const std::vector<uint8_t>& data) override; 97 }; 98 99 } // impl 100 101 } // namespace V2_0 102 } // namespace vehicle 103 } // namespace automotive 104 } // namespace hardware 105 } // namespace android 106 107 #endif // ANDROID_EMULATORSOCKETCOMM_SOCKETCOMM_H 108