1 /*
2  * Copyright (C) 2020 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 #pragma once
18 
19 #include <PowerStatsAidl.h>
20 
21 #include <utils/Looper.h>
22 #include <utils/Thread.h>
23 
24 #include <cstdio>
25 #include <cstring>
26 #include <mutex>
27 #include <thread>
28 #include <unordered_map>
29 
30 namespace aidl {
31 namespace android {
32 namespace hardware {
33 namespace power {
34 namespace stats {
35 
36 class DisplayStateResidencyDataProvider : public PowerStats::IStateResidencyDataProvider {
37   public:
38     // name = powerEntityName to be associated with this data provider
39     // path = path to the display state file descriptor
40     // state = list of states to be tracked
41     DisplayStateResidencyDataProvider(std::string name, std::string path,
42                                       std::vector<std::string> states);
43     ~DisplayStateResidencyDataProvider();
44 
45     // Methods from PowerStats::IStateResidencyDataProvider
46     bool getStateResidencies(
47             std::unordered_map<std::string, std::vector<StateResidency>> *residencies) override;
48     std::unordered_map<std::string, std::vector<State>> getInfo() override;
49 
50   private:
51     // Poll for display state changes
52     void pollLoop();
53     // Main function to update the stats when display state change is detected
54     void updateStats();
55 
56     // File descriptor of display state
57     int mFd;
58     // Path to display state file descriptor
59     const std::string mPath;
60     // Power Entity name associated with this data provider
61     const std::string mName;
62     // List of states to track indexed by mCurState
63     std::vector<std::string> mStates;
64     // Lock to protect concurrent read/write to mResidencies and mCurState
65     std::mutex mLock;
66     // Accumulated display state stats indexed by mCurState
67     std::vector<StateResidency> mResidencies;
68     // Index of current state
69     int mCurState;
70     // Looper to facilitate polling of display state file desciptor
71     ::android::sp<::android::Looper> mLooper;
72 
73     std::thread mThread;
74 };
75 
76 }  // namespace stats
77 }  // namespace power
78 }  // namespace hardware
79 }  // namespace android
80 }  // namespace aidl
81