1 /**
2  * Copyright (c) 2021, 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 CPP_LIBSYSFSMONITOR_SRC_SYSFSMONITOR_H_
18 #define CPP_LIBSYSFSMONITOR_SRC_SYSFSMONITOR_H_
19 
20 #include <android-base/result.h>
21 #include <android-base/unique_fd.h>
22 #include <utils/RefBase.h>
23 
24 #include <functional>
25 #include <string>
26 #include <thread>  // NOLINT(build/c++11)
27 #include <unordered_set>
28 
29 namespace android {
30 namespace automotive {
31 
32 using CallbackFunc = ::std::function<void(const std::vector<int32_t>&)>;
33 
34 /**
35  * SysfsMonitor monitors sysfs file changes and invokes the registered callback when there is a
36  * change at the sysfs files to monitor.
37  */
38 class SysfsMonitor final : public RefBase {
39 public:
40     // Initializes SysfsMonitor instance.
41     android::base::Result<void> init(CallbackFunc callback);
42     // Releases resources used for monitoring.
43     android::base::Result<void> release();
44     // Registers a sysfs file to monitor.
45     android::base::Result<void> registerFd(int32_t fd);
46     // Unregisters a sysfs file to monitor.
47     // Some events may be in process, so events may
48     // continue to be reported even after this method completes.
49     android::base::Result<void> unregisterFd(int32_t fd);
50     // Starts observing sysfs file changes.
51     android::base::Result<void> observe();
52 
53 private:
54     android::base::unique_fd mEpollFd;
55     std::unordered_set<int32_t> mMonitoringFds;
56     CallbackFunc mCallback;
57     std::thread mMonitoringThread;
58     int mPipefd[2];
59 };
60 
61 }  // namespace automotive
62 }  // namespace android
63 
64 #endif  // CPP_LIBSYSFSMONITOR_SRC_SYSFSMONITOR_H_
65