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_SENSORHAL_EXT_CONNECTION_DETECTOR_H 18 #define ANDROID_SENSORHAL_EXT_CONNECTION_DETECTOR_H 19 20 #include "BaseDynamicSensorDaemon.h" 21 #include <utils/Thread.h> 22 #include <utils/Looper.h> 23 24 #include <regex> 25 26 #include <poll.h> 27 28 namespace android { 29 namespace SensorHalExt { 30 31 // Abstraction of connection detector: an entity that calls 32 // BaseDynamicSensorDaemon::onConnectionChange() when necessary. 33 class ConnectionDetector : virtual public RefBase { 34 public: ConnectionDetector(BaseDynamicSensorDaemon * d)35 ConnectionDetector(BaseDynamicSensorDaemon *d) : mDaemon(d) { } 36 virtual ~ConnectionDetector() = default; 37 protected: 38 BaseDynamicSensorDaemon* mDaemon; 39 }; 40 41 // Open a socket that listen to localhost:port and notify sensor daemon of connection and 42 // disconnection event when socket is connected or disconnected, respectively. Only one concurrent 43 // client is accepted. 44 class SocketConnectionDetector : public ConnectionDetector, public Thread { 45 public: 46 SocketConnectionDetector(BaseDynamicSensorDaemon *d, int port); 47 virtual ~SocketConnectionDetector(); 48 private: 49 // implement virtual of Thread 50 virtual bool threadLoop(); 51 int waitForConnection(); 52 static void waitForDisconnection(int connFd); 53 54 int mListenFd; 55 std::string mDevice; 56 }; 57 58 // Detect file change under path and notify sensor daemon of connection and disconnection event when 59 // file is created in or removed from the directory, respectively. 60 class FileConnectionDetector : public ConnectionDetector, public Thread { 61 public: 62 FileConnectionDetector( 63 BaseDynamicSensorDaemon *d, const std::string &path, const std::string ®ex); 64 virtual ~FileConnectionDetector(); 65 private: 66 static constexpr int POLL_IDENT = 1; 67 // implement virtual of Thread 68 virtual bool threadLoop(); 69 70 bool matches(const std::string &name) const; 71 void processExistingFiles() const; 72 void handleInotifyData(ssize_t len, const char *data); 73 bool readInotifyData(); 74 std::string getFullName(const std::string name) const; 75 76 std::string mPath; 77 std::regex mRegex; 78 sp<Looper> mLooper; 79 int mInotifyFd; 80 }; 81 82 } // namespace SensorHalExt 83 } // namespace android 84 85 #endif // ANDROID_SENSORHAL_EXT_DYNAMIC_SENSOR_DAEMON_H 86