• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "battery_stats_service.h"
17 
18 #include <file_ex.h>
19 #include <cmath>
20 #include <ipc_skeleton.h>
21 
22 #include "common_event_data.h"
23 #include "common_event_manager.h"
24 #include "common_event_subscribe_info.h"
25 #include "common_event_support.h"
26 #include "hisysevent.h"
27 #include "hisysevent_manager.h"
28 #include "iservice_registry.h"
29 #include "if_system_ability_manager.h"
30 #include "permission.h"
31 #include "system_ability_definition.h"
32 #include "watchdog.h"
33 
34 #include "battery_stats_dumper.h"
35 #include "battery_stats_listener.h"
36 #include "battery_stats_subscriber.h"
37 #include "stats_common.h"
38 
39 namespace OHOS {
40 namespace PowerMgr {
41 namespace {
42 auto g_statsService = DelayedStatsSpSingleton<BatteryStatsService>::GetInstance();
43 const bool G_REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(g_statsService.GetRefPtr());
44 }
45 
BatteryStatsService()46 BatteryStatsService::BatteryStatsService() : SystemAbility(POWER_MANAGER_BATT_STATS_SERVICE_ID, true) {}
47 
~BatteryStatsService()48 BatteryStatsService::~BatteryStatsService() {}
49 
OnStart()50 void BatteryStatsService::OnStart()
51 {
52     if (ready_) {
53         STATS_HILOGI(COMP_SVC, "OnStart is ready, nothing to do");
54         return;
55     }
56     if (!(Init())) {
57         STATS_HILOGE(COMP_SVC, "Call init failed");
58         return;
59     }
60     AddSystemAbilityListener(DFX_SYS_EVENT_SERVICE_ABILITY_ID);
61     AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID);
62     if (!Publish(DelayedStatsSpSingleton<BatteryStatsService>::GetInstance())) {
63         STATS_HILOGE(COMP_SVC, "OnStart register to system ability manager failed");
64         return;
65     }
66 
67     ready_ = true;
68 }
69 
OnStop()70 void BatteryStatsService::OnStop()
71 {
72     if (!ready_) {
73         STATS_HILOGI(COMP_SVC, "OnStop is not ready, nothing to do");
74         return;
75     }
76     ready_ = false;
77     RemoveSystemAbilityListener(DFX_SYS_EVENT_SERVICE_ABILITY_ID);
78     RemoveSystemAbilityListener(COMMON_EVENT_SERVICE_ID);
79     HiviewDFX::HiSysEventManager::RemoveListener(listenerPtr_);
80     if (!OHOS::EventFwk::CommonEventManager::UnSubscribeCommonEvent(subscriberPtr_)) {
81         STATS_HILOGE(COMP_SVC, "OnStart unregister to commonevent manager failed");
82     }
83 }
84 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)85 void BatteryStatsService::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
86 {
87     STATS_HILOGI(COMP_SVC, "systemAbilityId=%{public}d, deviceId=%{private}s", systemAbilityId,
88                  deviceId.c_str());
89     if (systemAbilityId == DFX_SYS_EVENT_SERVICE_ABILITY_ID) {
90         AddHiSysEventListener();
91     }
92     if (systemAbilityId == COMMON_EVENT_SERVICE_ID) {
93         SubscribeCommonEvent();
94     }
95 }
96 
Init()97 bool BatteryStatsService::Init()
98 {
99     if (parser_ == nullptr) {
100         parser_ = std::make_shared<BatteryStatsParser>();
101         if (!parser_->Init()) {
102             STATS_HILOGE(COMP_SVC, "Battery stats parser initialization failed");
103             return false;
104         }
105     }
106 
107     if (core_ == nullptr) {
108         core_ = std::make_shared<BatteryStatsCore>();
109         if (!core_->Init()) {
110             STATS_HILOGE(COMP_SVC, "Battery stats core initialization failed");
111             return false;
112         }
113     }
114 
115     if (detector_ == nullptr) {
116         detector_ = std::make_shared<BatteryStatsDetector>();
117     }
118 
119     if (!runner_) {
120         runner_ = AppExecFwk::EventRunner::Create("BatteryStatsEventRunner");
121         if (runner_ == nullptr) {
122             STATS_HILOGE(COMP_SVC, "Create EventRunner failed");
123             return false;
124         }
125     }
126 
127     if (!handler_) {
128         handler_ = std::make_shared<OHOS::AppExecFwk::EventHandler>(runner_);
129         if (handler_ == nullptr) {
130             STATS_HILOGE(COMP_SVC, "Create EventHandler failed");
131             return false;
132         }
133         HiviewDFX::Watchdog::GetInstance().AddThread("BatteryStatsEventHandler", handler_);
134     }
135 
136     return true;
137 }
138 
SubscribeCommonEvent()139 bool BatteryStatsService::SubscribeCommonEvent()
140 {
141     bool result = false;
142     OHOS::EventFwk::MatchingSkills matchingSkills;
143     matchingSkills.AddEvent(OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_SHUTDOWN);
144     matchingSkills.AddEvent(OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_BOOT_COMPLETED);
145     matchingSkills.AddEvent(OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_BATTERY_CHANGED);
146     OHOS::EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
147     if (!subscriberPtr_) {
148         subscriberPtr_ = std::make_shared<BatteryStatsSubscriber>(subscribeInfo);
149     }
150     result = OHOS::EventFwk::CommonEventManager::SubscribeCommonEvent(subscriberPtr_);
151     if (!result) {
152         STATS_HILOGE(COMP_SVC, "Subscribe CommonEvent failed");
153     }
154     return result;
155 }
156 
AddHiSysEventListener()157 bool BatteryStatsService::AddHiSysEventListener()
158 {
159     if (!listenerPtr_) {
160         OHOS::EventFwk::CommonEventSubscribeInfo info;
161         listenerPtr_ = std::make_shared<BatteryStatsListener>();
162     }
163     OHOS::HiviewDFX::ListenerRule statsRule("PowerStats");
164     OHOS::HiviewDFX::ListenerRule distSchedRule("DISTSCHEDULE", "START_REMOTE_ABILITY");
165     std::vector<OHOS::HiviewDFX::ListenerRule> sysRules;
166     sysRules.push_back(statsRule);
167     sysRules.push_back(distSchedRule);
168     auto res = HiviewDFX::HiSysEventManager::AddListener(listenerPtr_, sysRules);
169     if (res != 0) {
170         STATS_HILOGE(COMP_SVC, "Listener added failed");
171     }
172     return res;
173 }
174 
IsServiceReady() const175 bool BatteryStatsService::IsServiceReady() const
176 {
177     return ready_;
178 }
179 
GetBatteryStats()180 BatteryStatsInfoList BatteryStatsService::GetBatteryStats()
181 {
182     BatteryStatsInfoList statsInfoList = {};
183     if (!Permission::IsSystem()) {
184         return statsInfoList;
185     }
186     core_->ComputePower();
187     statsInfoList = core_->GetBatteryStats();
188     return statsInfoList;
189 }
190 
Dump(int32_t fd,const std::vector<std::u16string> & args)191 int32_t BatteryStatsService::Dump(int32_t fd, const std::vector<std::u16string>& args)
192 {
193     std::lock_guard lock(mutex_);
194     std::vector<std::string> argsInStr;
195     std::transform(args.begin(), args.end(), std::back_inserter(argsInStr),
196         [](const std::u16string &arg) {
197         std::string ret = Str16ToStr8(arg);
198         STATS_HILOGD(COMP_SVC, "arg: %{public}s", ret.c_str());
199         return ret;
200     });
201     std::string result;
202     BatteryStatsDumper::Dump(argsInStr, result);
203     if (!SaveStringToFd(fd, result)) {
204         STATS_HILOGE(COMP_SVC, "Dump save to fd failed, %{public}s", result.c_str());
205         return ERR_OK;
206     }
207     return ERR_OK;
208 }
209 
GetAppStatsMah(const int32_t & uid)210 double BatteryStatsService::GetAppStatsMah(const int32_t& uid)
211 {
212     if (!Permission::IsSystem()) {
213         return StatsUtils::DEFAULT_VALUE;
214     }
215     core_->ComputePower();
216     return core_->GetAppStatsMah(uid);
217 }
218 
GetAppStatsPercent(const int32_t & uid)219 double BatteryStatsService::GetAppStatsPercent(const int32_t& uid)
220 {
221     if (!Permission::IsSystem()) {
222         return StatsUtils::DEFAULT_VALUE;
223     }
224     core_->ComputePower();
225     return core_->GetAppStatsPercent(uid);
226 }
227 
GetPartStatsMah(const BatteryStatsInfo::ConsumptionType & type)228 double BatteryStatsService::GetPartStatsMah(const BatteryStatsInfo::ConsumptionType& type)
229 {
230     if (!Permission::IsSystem()) {
231         return StatsUtils::DEFAULT_VALUE;
232     }
233     core_->ComputePower();
234     return core_->GetPartStatsMah(type);
235 }
236 
GetPartStatsPercent(const BatteryStatsInfo::ConsumptionType & type)237 double BatteryStatsService::GetPartStatsPercent(const BatteryStatsInfo::ConsumptionType& type)
238 {
239     if (!Permission::IsSystem()) {
240         return StatsUtils::DEFAULT_VALUE;
241     }
242     core_->ComputePower();
243     return core_->GetPartStatsPercent(type);
244 }
245 
GetTotalTimeSecond(const StatsUtils::StatsType & statsType,const int32_t & uid)246 uint64_t BatteryStatsService::GetTotalTimeSecond(const StatsUtils::StatsType& statsType, const int32_t& uid)
247 {
248     STATS_HILOGD(COMP_SVC, "statsType: %{public}d, uid: %{public}d", statsType, uid);
249     uint64_t timeSecond;
250     if (uid > StatsUtils::INVALID_VALUE) {
251         double timeMs = static_cast<double>(core_->GetTotalTimeMs(uid, statsType));
252         timeSecond = round(timeMs / StatsUtils::MS_IN_SECOND);
253     } else {
254         double timeMs = static_cast<double>(core_->GetTotalTimeMs(statsType));
255         timeSecond = round(timeMs / StatsUtils::MS_IN_SECOND);
256     }
257     return timeSecond;
258 }
259 
GetTotalDataBytes(const StatsUtils::StatsType & statsType,const int32_t & uid)260 uint64_t BatteryStatsService::GetTotalDataBytes(const StatsUtils::StatsType& statsType, const int32_t& uid)
261 {
262     return core_->GetTotalDataCount(statsType, uid);
263 }
264 
Reset()265 void BatteryStatsService::Reset()
266 {
267     if (!Permission::IsSystem()) {
268         return;
269     }
270     core_->Reset();
271 }
272 
GetBatteryStatsCore() const273 std::shared_ptr<BatteryStatsCore> BatteryStatsService::GetBatteryStatsCore() const
274 {
275     return core_;
276 }
277 
GetBatteryStatsParser() const278 std::shared_ptr<BatteryStatsParser> BatteryStatsService::GetBatteryStatsParser() const
279 {
280     return parser_;
281 }
282 
GetBatteryStatsDetector() const283 std::shared_ptr<BatteryStatsDetector> BatteryStatsService::GetBatteryStatsDetector() const
284 {
285     return detector_;
286 }
287 
SetOnBattery(bool isOnBattery)288 void BatteryStatsService::SetOnBattery(bool isOnBattery)
289 {
290     if (!Permission::IsSystem()) {
291         return;
292     }
293     StatsHelper::SetOnBattery(isOnBattery);
294 }
295 
ShellDump(const std::vector<std::string> & args,uint32_t argc)296 std::string BatteryStatsService::ShellDump(const std::vector<std::string>& args, uint32_t argc)
297 {
298     if (!Permission::IsSystem()) {
299         return "";
300     }
301     std::lock_guard lock(mutex_);
302     pid_t pid = IPCSkeleton::GetCallingPid();
303     std::string result;
304     bool ret = BatteryStatsDumper::Dump(args, result);
305     STATS_HILOGI(COMP_SVC, "PID: %{public}d, Dump result :%{public}d", pid, ret);
306     return result;
307 }
308 } // namespace PowerMgr
309 } // namespace OHOS
310