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_subscriber.h"
17
18 #include "common_event_data.h"
19 #include "common_event_manager.h"
20 #include "common_event_subscriber.h"
21 #include "common_event_subscribe_info.h"
22 #include "common_event_support.h"
23
24 #include "battery_info.h"
25 #include "battery_stats_service.h"
26 #include "stats_helper.h"
27 #include "stats_log.h"
28
29 namespace OHOS {
30 namespace PowerMgr {
31 namespace {
32 const int32_t BATTERY_LEVEL_FULL = 100;
33 }
OnReceiveEvent(const OHOS::EventFwk::CommonEventData & data)34 void BatteryStatsSubscriber::OnReceiveEvent(const OHOS::EventFwk::CommonEventData &data)
35 {
36 std::string action = data.GetWant().GetAction();
37 auto statsService = DelayedStatsSpSingleton<BatteryStatsService>::GetInstance();
38 if (statsService == nullptr) {
39 STATS_HILOGE(COMP_SVC, "Battery stats service is null");
40 return;
41 }
42 if (action == OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_SHUTDOWN) {
43 statsService->GetBatteryStatsCore()->SaveBatteryStatsData();
44 STATS_HILOGI(COMP_SVC, "Received COMMON_EVENT_SHUTDOWN event");
45 } else if (action == OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_BATTERY_CHANGED) {
46 int capacity = data.GetWant().GetIntParam(BatteryInfo::COMMON_EVENT_KEY_CAPACITY, StatsUtils::INVALID_VALUE);
47 int pluggedType = data.GetWant().GetIntParam(
48 BatteryInfo::COMMON_EVENT_KEY_PLUGGED_TYPE, StatsUtils::INVALID_VALUE);
49
50 STATS_HILOGI(COMP_SVC,
51 "Received COMMON_EVENT_BATTERY_CHANGED event, capacity=%{public}d, pluggedType=%{public}d",
52 capacity, pluggedType);
53 if (capacity == BATTERY_LEVEL_FULL) {
54 statsService->GetBatteryStatsCore()->Reset();
55 }
56 if (pluggedType == static_cast<int32_t>(BatteryPluggedType::PLUGGED_TYPE_NONE) ||
57 pluggedType == static_cast<int32_t>(BatteryPluggedType::PLUGGED_TYPE_BUTT)) {
58 StatsHelper::SetOnBattery(true);
59 } else {
60 StatsHelper::SetOnBattery(false);
61 }
62 }
63 }
64 } // namespace PowerMgr
65 } // namespace OHOS
66