• 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_service.h"
17 
18 #include <ctime>
19 #include <cstdio>
20 #include <functional>
21 #include <ipc_skeleton.h>
22 #include "ability_manager_client.h"
23 #include "errors.h"
24 #include "new"
25 #include "permission.h"
26 #include "system_ability_definition.h"
27 #include "iremote_object.h"
28 #include "v1_1/ibattery_callback.h"
29 #include "hdf_io_service_if.h"
30 #include "hdf_service_status.h"
31 #include "battery_callback.h"
32 #include "battery_config.h"
33 #include "battery_dump.h"
34 #include "battery_log.h"
35 #include "power_mgr_client.h"
36 #include "power_common.h"
37 #include "watchdog.h"
38 
39 using namespace OHOS::HDI::Battery;
40 using namespace OHOS::AAFwk;
41 
42 namespace OHOS {
43 namespace PowerMgr {
44 namespace {
45 constexpr const char* BATTERY_SERVICE_NAME = "BatteryService";
46 constexpr const char* BATTERY_HDI_NAME = "battery_interface_service";
47 constexpr int32_t HELP_DUMP_PARAM = 2;
48 constexpr int32_t BATTERY_FULL_CAPACITY = 100;
49 constexpr uint32_t RETRY_TIME = 1000;
50 sptr<BatteryService> g_service;
51 BatteryPluggedType g_lastPluggedType = BatteryPluggedType::PLUGGED_TYPE_NONE;
52 static PowerMgrClient& g_powerMgrClient = PowerMgrClient::GetInstance();
53 }
54 
55 const bool G_REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(
56     DelayedSpSingleton<BatteryService>::GetInstance().GetRefPtr());
57 
BatteryService()58 BatteryService::BatteryService()
59     : SystemAbility(POWER_MANAGER_BATT_SERVICE_ID, true)
60 {
61 }
62 
~BatteryService()63 BatteryService::~BatteryService() {}
64 
GetCurrentTime()65 static int64_t GetCurrentTime()
66 {
67     constexpr int32_t SEC_TO_MSEC = 1000;
68     constexpr int32_t NSEC_TO_MSEC = 1000000;
69     timespec tm {};
70     clock_gettime(CLOCK_MONOTONIC, &tm);
71 
72     return tm.tv_sec * SEC_TO_MSEC + (tm.tv_nsec / NSEC_TO_MSEC);
73 }
74 
OnStart()75 void BatteryService::OnStart()
76 {
77     if (ready_) {
78         BATTERY_HILOGD(COMP_SVC, "Service is ready, nothing to do");
79         return;
80     }
81     if (!(Init())) {
82         BATTERY_HILOGE(COMP_SVC, "Call init failed");
83         return;
84     }
85     RegisterHdiStatusListener();
86     if (!Publish(this)) {
87         BATTERY_HILOGE(COMP_SVC, "Register to system ability manager failed");
88         return;
89     }
90     AddSystemAbilityListener(MISCDEVICE_SERVICE_ABILITY_ID);
91     ready_ = true;
92 }
93 
Init()94 bool BatteryService::Init()
95 {
96     if (!eventRunner_) {
97         eventRunner_ = AppExecFwk::EventRunner::Create(BATTERY_SERVICE_NAME);
98         if (eventRunner_ == nullptr) {
99             BATTERY_HILOGE(COMP_SVC, "Init failed due to create EventRunner");
100             return false;
101         }
102     }
103     if (!handler_) {
104         handler_ = std::make_shared<BatteryServiceEventHandler>(eventRunner_,
105             DelayedSpSingleton<BatteryService>::GetInstance());
106         if (handler_ == nullptr) {
107             BATTERY_HILOGE(COMP_SVC, "Init failed due to create handler error");
108             return false;
109         }
110         HiviewDFX::Watchdog::GetInstance().AddThread("BatteryServiceEventHandler", handler_);
111     }
112 
113     InitConfig();
114     if (!batteryNotify_) {
115         batteryNotify_ = std::make_unique<BatteryNotify>();
116     }
117     return true;
118 }
119 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)120 void BatteryService::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
121 {
122     BATTERY_HILOGI(COMP_SVC, "systemAbilityId=%{public}d, deviceId=%{private}s", systemAbilityId, deviceId.c_str());
123     if (systemAbilityId == MISCDEVICE_SERVICE_ABILITY_ID) {
124         batteryLight_.InitLight();
125     }
126 }
127 
RegisterBatteryHdiCallback()128 bool BatteryService::RegisterBatteryHdiCallback()
129 {
130     if (iBatteryInterface_ == nullptr) {
131         iBatteryInterface_ = V1_1::IBatteryInterface::Get();
132         BATTERY_HILOGE(COMP_SVC, "failed to get battery hdi interface");
133         RETURN_IF_WITH_RET(iBatteryInterface_ == nullptr, false);
134     }
135     sptr<V1_1::IBatteryCallback> callback = new BatteryCallback();
136     ErrCode ret = iBatteryInterface_->Register(callback);
137     if (ret < 0) {
138         BATTERY_HILOGE(COMP_SVC, "register callback failed");
139         return false;
140     }
141 
142     BatteryCallback::BatteryEventCallback eventCb =
143         std::bind(&BatteryService::HandleBatteryCallbackEvent, this, std::placeholders::_1);
144     BatteryCallback::RegisterBatteryEvent(eventCb);
145     return true;
146 }
147 
InitConfig()148 void BatteryService::InitConfig()
149 {
150     auto& batteryConfig = BatteryConfig::GetInstance();
151     batteryConfig.ParseConfig();
152 
153     warnCapacity_ = batteryConfig.GetInt("soc.warning", warnCapacity_);
154     highTemperature_ = batteryConfig.GetInt("temperature.high", highTemperature_);
155     lowTemperature_ = batteryConfig.GetInt("temperature.low", lowTemperature_);
156     shutdownCapacityThreshold_ = batteryConfig.GetInt("soc.shutdown", shutdownCapacityThreshold_);
157     criticalCapacityThreshold_ = batteryConfig.GetInt("soc.critical", criticalCapacityThreshold_);
158     warningCapacityThreshold_ = batteryConfig.GetInt("soc.warning", warningCapacityThreshold_);
159     lowCapacityThreshold_ = batteryConfig.GetInt("soc.low", lowCapacityThreshold_);
160     normalCapacityThreshold_ = batteryConfig.GetInt("soc.normal", normalCapacityThreshold_);
161     highCapacityThreshold_ = batteryConfig.GetInt("soc.high", highCapacityThreshold_);
162     fullCapacityThreshold_ = batteryConfig.GetInt("soc.full", fullCapacityThreshold_);
163     BATTERY_HILOGI(COMP_SVC, "warnCapacity_=%{public}d, highTemperature_=%{public}d,\
164         lowTemperature_=%{public}d, shutdownCapacityThreshold_=%{public}d,\
165         criticalCapacityThreshold_=%{public}d, warningCapacityThreshold_=%{public}d, lowCapacityThreshold_=%{public}d,\
166         normalCapacityThreshold_=%{public}d, highCapacityThreshold_=%{public}d, fullCapacityThreshold_=%{public}d",
167         warnCapacity_, highTemperature_, lowTemperature_, shutdownCapacityThreshold_, criticalCapacityThreshold_,
168         warningCapacityThreshold_, lowCapacityThreshold_, normalCapacityThreshold_, highCapacityThreshold_,
169         fullCapacityThreshold_);
170 }
171 
HandleBatteryCallbackEvent(const V1_1::BatteryInfo & event)172 int32_t BatteryService::HandleBatteryCallbackEvent(const V1_1::BatteryInfo& event)
173 {
174     if (isMockUnplugged_) {
175         return ERR_OK;
176     }
177 
178     ConvertingEvent(event);
179     RETURN_IF_WITH_RET(lastBatteryInfo_ == batteryInfo_, ERR_OK);
180     HandleBatteryInfo();
181     return ERR_OK;
182 }
183 
ConvertingEvent(const V1_1::BatteryInfo & event)184 void BatteryService::ConvertingEvent(const V1_1::BatteryInfo& event)
185 {
186     batteryInfo_.SetCapacity(event.capacity);
187     batteryInfo_.SetVoltage(event.voltage);
188     batteryInfo_.SetTemperature(event.temperature);
189     batteryInfo_.SetHealthState(BatteryHealthState(event.healthState));
190     batteryInfo_.SetPluggedType(BatteryPluggedType(event.pluggedType));
191     batteryInfo_.SetPluggedMaxCurrent(event.pluggedMaxCurrent);
192     batteryInfo_.SetPluggedMaxVoltage(event.pluggedMaxVoltage);
193     batteryInfo_.SetChargeState(BatteryChargeState(event.chargeState));
194     batteryInfo_.SetChargeCounter(event.chargeCounter);
195     batteryInfo_.SetTotalEnergy(event.totalEnergy);
196     batteryInfo_.SetCurAverage(event.curAverage);
197     batteryInfo_.SetRemainEnergy(event.remainEnergy);
198     batteryInfo_.SetPresent(event.present);
199     batteryInfo_.SetTechnology(event.technology);
200     batteryInfo_.SetNowCurrent(event.curNow);
201 }
202 
HandleBatteryInfo()203 void BatteryService::HandleBatteryInfo()
204 {
205     BATTERY_HILOGD(FEATURE_BATT_INFO, "capacity=%{public}d, voltage=%{public}d, temperature=%{public}d, "
206         "healthState=%{public}d, pluggedType=%{public}d, pluggedMaxCurrent=%{public}d, "
207         "pluggedMaxVoltage=%{public}d, chargeState=%{public}d, chargeCounter=%{public}d, present=%{public}d, "
208         "technology=%{public}s, currNow=%{public}d, totalEnergy=%{public}d, curAverage=%{public}d, "
209         "remainEnergy=%{public}d", batteryInfo_.GetCapacity(), batteryInfo_.GetVoltage(), batteryInfo_.GetTemperature(),
210         batteryInfo_.GetHealthState(), batteryInfo_.GetPluggedType(), batteryInfo_.GetPluggedMaxCurrent(),
211         batteryInfo_.GetPluggedMaxVoltage(), batteryInfo_.GetChargeState(), batteryInfo_.GetChargeCounter(),
212         batteryInfo_.IsPresent(), batteryInfo_.GetTechnology().c_str(), batteryInfo_.GetNowCurrent(),
213         batteryInfo_.GetTotalEnergy(), batteryInfo_.GetCurAverage(), batteryInfo_.GetRemainEnergy());
214 
215     batteryLight_.UpdateColor(batteryInfo_.GetChargeState(), batteryInfo_.GetCapacity());
216     WakeupDevice(batteryInfo_.GetPluggedType());
217     HandlePopupEvent(batteryInfo_.GetCapacity());
218     CalculateRemainingChargeTime(batteryInfo_.GetCapacity(), batteryInfo_.GetChargeState());
219 
220     batteryNotify_->PublishEvents(batteryInfo_);
221     HandleTemperature(batteryInfo_.GetTemperature());
222     HandleCapacity(batteryInfo_.GetCapacity(), batteryInfo_.GetChargeState());
223     lastBatteryInfo_ = batteryInfo_;
224 }
225 
RegisterHdiStatusListener()226 bool BatteryService::RegisterHdiStatusListener()
227 {
228     hdiServiceMgr_ = OHOS::HDI::ServiceManager::V1_0::IServiceManager::Get();
229     if (hdiServiceMgr_ == nullptr) {
230         BATTERY_HILOGW(COMP_SVC, "hdi service manager is nullptr, Try again after %{public}u second", RETRY_TIME);
231         SendEvent(BatteryServiceEventHandler::EVENT_RETRY_REGISTER_HDI_STATUS_LISTENER, RETRY_TIME);
232         return false;
233     }
234 
235     hdiServStatListener_ = new HdiServiceStatusListener(HdiServiceStatusListener::StatusCallback(
236         [&](const OHOS::HDI::ServiceManager::V1_0::ServiceStatus &status) {
237             RETURN_IF(status.serviceName != BATTERY_HDI_NAME || status.deviceClass != DEVICE_CLASS_DEFAULT);
238 
239             if (status.status == SERVIE_STATUS_START) {
240                 SendEvent(BatteryServiceEventHandler::EVENT_REGISTER_BATTERY_HDI_CALLBACK, 0);
241                 BATTERY_HILOGD(COMP_SVC, "battery interface service start");
242             } else if (status.status == SERVIE_STATUS_STOP && iBatteryInterface_) {
243                 iBatteryInterface_->UnRegister();
244                 iBatteryInterface_ = nullptr;
245                 BATTERY_HILOGW(COMP_SVC, "battery interface service stop, unregister interface");
246             }
247         }
248     ));
249 
250     int32_t status = hdiServiceMgr_->RegisterServiceStatusListener(hdiServStatListener_, DEVICE_CLASS_DEFAULT);
251     if (status != ERR_OK) {
252         BATTERY_HILOGW(COMP_SVC, "Register hdi failed, Try again after %{public}u second", RETRY_TIME);
253         SendEvent(BatteryServiceEventHandler::EVENT_RETRY_REGISTER_HDI_STATUS_LISTENER, RETRY_TIME);
254         return false;
255     }
256     return true;
257 }
258 
SendEvent(int32_t event,int64_t delayTime)259 void BatteryService::SendEvent(int32_t event, int64_t delayTime)
260 {
261     RETURN_IF_WITH_LOG(handler_ == nullptr, "handler is nullptr");
262     handler_->RemoveEvent(event);
263     handler_->SendEvent(event, 0, delayTime);
264 }
265 
OnStop()266 void BatteryService::OnStop()
267 {
268     if (!ready_) {
269         return;
270     }
271     eventRunner_.reset();
272     handler_.reset();
273     ready_ = false;
274 
275     if (iBatteryInterface_ != nullptr) {
276         iBatteryInterface_->UnRegister();
277         iBatteryInterface_ = nullptr;
278     }
279     if (hdiServiceMgr_ != nullptr) {
280         hdiServiceMgr_->UnregisterServiceStatusListener(hdiServStatListener_);
281         hdiServiceMgr_ = nullptr;
282     }
283 }
284 
IsLastPlugged()285 bool BatteryService::IsLastPlugged()
286 {
287     if (g_lastPluggedType != BatteryPluggedType::PLUGGED_TYPE_NONE &&
288         g_lastPluggedType != BatteryPluggedType::PLUGGED_TYPE_BUTT) {
289         return true;
290     }
291     return false;
292 }
293 
IsNowPlugged(BatteryPluggedType pluggedType)294 bool BatteryService::IsNowPlugged(BatteryPluggedType pluggedType)
295 {
296     if (pluggedType != BatteryPluggedType::PLUGGED_TYPE_NONE &&
297         pluggedType != BatteryPluggedType::PLUGGED_TYPE_BUTT) {
298         return true;
299     }
300     return false;
301 }
302 
IsPlugged(BatteryPluggedType pluggedType)303 bool BatteryService::IsPlugged(BatteryPluggedType pluggedType)
304 {
305     if (!IsLastPlugged() && IsNowPlugged(pluggedType)) {
306         return true;
307     }
308     return false;
309 }
310 
IsUnplugged(BatteryPluggedType pluggedType)311 bool BatteryService::IsUnplugged(BatteryPluggedType pluggedType)
312 {
313     if (IsLastPlugged() && !IsNowPlugged(pluggedType)) {
314         return true;
315     }
316     return false;
317 }
318 
WakeupDevice(BatteryPluggedType pluggedType)319 void BatteryService::WakeupDevice(BatteryPluggedType pluggedType)
320 {
321     if (IsPlugged(pluggedType) || IsUnplugged(pluggedType)) {
322         PowerMgrClient::GetInstance().WakeupDevice();
323     }
324     g_lastPluggedType = pluggedType;
325 }
326 
HandlePopupEvent(int32_t capacity)327 void BatteryService::HandlePopupEvent(int32_t capacity)
328 {
329     if ((capacity < warnCapacity_) && !isLowPower_) {
330         ShowBatteryDialog();
331         g_powerMgrClient.RefreshActivity(UserActivityType::USER_ACTIVITY_TYPE_ATTENTION);
332         isLowPower_ = true;
333         return;
334         }
335     if (capacity >= warnCapacity_ && isLowPower_) {
336         DestoryBatteryDialog();
337         isLowPower_ = false;
338         return;
339     }
340 }
341 
ShowBatteryDialog()342 bool BatteryService::ShowBatteryDialog()
343 {
344     BATTERY_HILOGD(COMP_SVC, "ShowBatteryDialog start.");
345     auto client = AbilityManagerClient::GetInstance();
346     if (client == nullptr) {
347         return false;
348     }
349     AAFwk::Want want;
350     want.SetElementName("com.ohos.powerdialog", "BatteryServiceExtAbility");
351     int32_t result = client->StartAbility(want);
352     if (result != 0) {
353         BATTERY_HILOGE(COMP_SVC, "ShowBatteryDialog failed, result = %{public}d", result);
354         return false;
355     }
356     BATTERY_HILOGD(COMP_SVC, "ShowBatteryDialog success.");
357     return true;
358 }
359 
DestoryBatteryDialog()360 bool BatteryService::DestoryBatteryDialog()
361 {
362     BATTERY_HILOGD(COMP_SVC, "DestoryBatteryDialog start.");
363     auto client = AbilityManagerClient::GetInstance();
364     if (client == nullptr) {
365         return false;
366     }
367     AAFwk::Want want;
368     want.SetElementName("com.ohos.powerdialog", "BatteryServiceExtAbility");
369     int32_t result = client->StopServiceAbility(want);
370     if (result != 0) {
371         BATTERY_HILOGE(COMP_SVC, "DestoryBatteryDialog failed, result = %{public}d", result);
372         return false;
373     }
374     BATTERY_HILOGD(COMP_SVC, "DestoryBatteryDialog success.");
375     return true;
376 }
377 
HandleTemperature(int32_t temperature)378 void BatteryService::HandleTemperature(int32_t temperature)
379 {
380     auto& powerMgrClient = PowerMgrClient::GetInstance();
381     if (((temperature <= lowTemperature_) || (temperature >= highTemperature_)) &&
382         (highTemperature_ != lowTemperature_)) {
383         std::string reason = "TemperatureOutOfRange";
384         powerMgrClient.ShutDownDevice(reason);
385     }
386 }
387 
HandleCapacity(int32_t capacity,BatteryChargeState chargeState)388 void BatteryService::HandleCapacity(int32_t capacity, BatteryChargeState chargeState)
389 {
390     auto& powerMgrClient = PowerMgrClient::GetInstance();
391     if ((capacity <= shutdownCapacityThreshold_) &&
392         ((chargeState == BatteryChargeState::CHARGE_STATE_NONE) ||
393          (chargeState == BatteryChargeState::CHARGE_STATE_BUTT))) {
394         std::string reason = "LowCapacity";
395         powerMgrClient.ShutDownDevice(reason);
396     }
397 }
398 
GetCapacity()399 int32_t BatteryService::GetCapacity()
400 {
401     int capacity = BATTERY_FULL_CAPACITY;
402     BATTERY_HILOGD(FEATURE_BATT_INFO, "Enter");
403     if (iBatteryInterface_ == nullptr) {
404         BATTERY_HILOGE(FEATURE_BATT_INFO, "iBatteryInterface_ is nullptr");
405         return ERR_NO_INIT;
406     }
407     iBatteryInterface_->GetCapacity(capacity);
408     return capacity;
409 }
410 
ChangePath(const std::string path)411 void BatteryService::ChangePath(const std::string path)
412 {
413     BATTERY_HILOGD(FEATURE_BATT_INFO, "Enter");
414     if (iBatteryInterface_ == nullptr) {
415         BATTERY_HILOGE(FEATURE_BATT_INFO, "iBatteryInterface_ is nullptr");
416         return;
417     }
418     iBatteryInterface_->ChangePath(path);
419     return;
420 }
421 
GetChargingStatus()422 BatteryChargeState BatteryService::GetChargingStatus()
423 {
424     BATTERY_HILOGD(FEATURE_BATT_INFO, "Enter");
425     V1_1::BatteryChargeState chargeState = V1_1::BatteryChargeState(0);
426 
427     if (iBatteryInterface_ == nullptr) {
428         BATTERY_HILOGE(FEATURE_BATT_INFO, "iBatteryInterface_ is nullptr");
429         return BatteryChargeState(chargeState);
430     }
431 
432     iBatteryInterface_->GetChargeState(chargeState);
433     return BatteryChargeState(chargeState);
434 }
435 
GetHealthStatus()436 BatteryHealthState BatteryService::GetHealthStatus()
437 {
438     BATTERY_HILOGD(FEATURE_BATT_INFO, "Enter");
439     V1_1::BatteryHealthState healthState = V1_1::BatteryHealthState(0);
440 
441     if (iBatteryInterface_ == nullptr) {
442         BATTERY_HILOGE(FEATURE_BATT_INFO, "iBatteryInterface_ is nullptr");
443         return BatteryHealthState(healthState);
444     }
445 
446     iBatteryInterface_->GetHealthState(healthState);
447     return BatteryHealthState(healthState);
448 }
449 
GetPluggedType()450 BatteryPluggedType BatteryService::GetPluggedType()
451 {
452     V1_1::BatteryPluggedType pluggedType = V1_1::BatteryPluggedType(0);
453 
454     if (iBatteryInterface_ == nullptr) {
455         BATTERY_HILOGE(FEATURE_BATT_INFO, "iBatteryInterface_ is nullptr");
456         return BatteryPluggedType(pluggedType);
457     }
458 
459     iBatteryInterface_->GetPluggedType(pluggedType);
460     return BatteryPluggedType(pluggedType);
461 }
462 
GetVoltage()463 int32_t BatteryService::GetVoltage()
464 {
465     int voltage;
466     if (iBatteryInterface_ == nullptr) {
467         BATTERY_HILOGE(FEATURE_BATT_INFO, "iBatteryInterface_ is nullptr");
468         return ERR_NO_INIT;
469     }
470 
471     iBatteryInterface_->GetVoltage(voltage);
472     return voltage;
473 }
474 
GetPresent()475 bool BatteryService::GetPresent()
476 {
477     bool present = false;
478 
479     if (iBatteryInterface_ == nullptr) {
480         BATTERY_HILOGE(FEATURE_BATT_INFO, "iBatteryInterface_ is nullptr");
481         return present;
482     }
483 
484     iBatteryInterface_->GetPresent(present);
485     return present;
486 }
487 
GetTechnology()488 std::string BatteryService::GetTechnology()
489 {
490     if (iBatteryInterface_ == nullptr) {
491         BATTERY_HILOGE(FEATURE_BATT_INFO, "iBatteryInterface_ is nullptr");
492         return "";
493     }
494 
495     std::string technology;
496     iBatteryInterface_->GetTechnology(technology);
497     return technology;
498 }
499 
GetBatteryTemperature()500 int32_t BatteryService::GetBatteryTemperature()
501 {
502     int temperature;
503     if (iBatteryInterface_ == nullptr) {
504         BATTERY_HILOGE(FEATURE_BATT_INFO, "iBatteryInterface_ is nullptr");
505         return ERR_NO_INIT;
506     }
507     iBatteryInterface_->GetTemperature(temperature);
508     return temperature;
509 }
510 
GetTotalEnergy()511 int32_t BatteryService::GetTotalEnergy()
512 {
513     int32_t totalEnergy = -1;
514     if (iBatteryInterface_ == nullptr) {
515         BATTERY_HILOGE(FEATURE_BATT_INFO, "iBatteryInterface_ is nullptr");
516         return ERR_NO_INIT;
517     }
518 
519     if (!Permission::IsSystem()) {
520         BATTERY_HILOGD(FEATURE_BATT_INFO, "GetTotalEnergy totalEnergy: %{public}d", totalEnergy);
521         return totalEnergy;
522     }
523     iBatteryInterface_->GetTotalEnergy(totalEnergy);
524     return totalEnergy;
525 }
526 
GetCurrentAverage()527 int32_t BatteryService::GetCurrentAverage()
528 {
529     int curAverage;
530     if (iBatteryInterface_ == nullptr) {
531         BATTERY_HILOGE(FEATURE_BATT_INFO, "iBatteryInterface_ is nullptr");
532         return ERR_NO_INIT;
533     }
534     iBatteryInterface_->GetCurrentAverage(curAverage);
535     return curAverage;
536 }
537 
GetNowCurrent()538 int32_t BatteryService::GetNowCurrent()
539 {
540     int32_t nowCurr = -1;
541     if (iBatteryInterface_ == nullptr) {
542         BATTERY_HILOGE(FEATURE_BATT_INFO, "iBatteryInterface_ is nullptr");
543         return ERR_NO_INIT;
544     }
545 
546     if (!Permission::IsSystem()) {
547         BATTERY_HILOGD(FEATURE_BATT_INFO, "GetNowCurrent nowCurr: %{public}d", nowCurr);
548         return nowCurr;
549     }
550     iBatteryInterface_->GetCurrentNow(nowCurr);
551     return nowCurr;
552 }
553 
GetRemainEnergy()554 int32_t BatteryService::GetRemainEnergy()
555 {
556     int32_t remainEnergy = -1;
557     if (iBatteryInterface_ == nullptr) {
558         BATTERY_HILOGE(FEATURE_BATT_INFO, "iBatteryInterface_ is nullptr");
559         return ERR_NO_INIT;
560     }
561 
562     if (!Permission::IsSystem()) {
563         BATTERY_HILOGD(FEATURE_BATT_INFO, "GetRemainEnergy remainEnergy: %{public}d", remainEnergy);
564         return remainEnergy;
565     }
566     iBatteryInterface_->GetRemainEnergy(remainEnergy);
567     return remainEnergy;
568 }
569 
CalculateRemainingChargeTime(int32_t capacity,BatteryChargeState chargeState)570 void BatteryService::CalculateRemainingChargeTime(int32_t capacity, BatteryChargeState chargeState)
571 {
572     if (capacity > BATTERY_FULL_CAPACITY) {
573         BATTERY_HILOGE(FEATURE_BATT_INFO, "capacity error");
574         return;
575     }
576 
577     if (chargeState != BatteryChargeState::CHARGE_STATE_ENABLE) {
578         remainTime_ = 0;
579         chargeFlag_ = false;
580         return;
581     }
582 
583     if (!chargeFlag_) {
584         lastCapacity_ = capacity;
585         lastTime_ = GetCurrentTime();
586         chargeFlag_ = true;
587     }
588 
589     if (capacity < lastCapacity_) {
590         lastCapacity_ = capacity;
591     }
592 
593     if (((capacity - lastCapacity_) >= 1) && (lastCapacity_ >= 0) && chargeFlag_) {
594         int64_t onceTime = (GetCurrentTime() - lastTime_) / (capacity - lastCapacity_);
595         remainTime_ = (BATTERY_FULL_CAPACITY - capacity) * onceTime;
596         lastCapacity_ = capacity;
597         lastTime_ = GetCurrentTime();
598     }
599 }
600 
GetRemainingChargeTime()601 int64_t BatteryService::GetRemainingChargeTime()
602 {
603     if (!Permission::IsSystem()) {
604         BATTERY_HILOGW(FEATURE_BATT_INFO, "system permission denied.");
605         return INVALID_REMAINING_CHARGE_TIME_VALUE;
606     }
607     return remainTime_;
608 }
609 
IsCapacityLevelDefined(int32_t capacityThreshold)610 bool IsCapacityLevelDefined(int32_t capacityThreshold)
611 {
612     return capacityThreshold != INVALID_BATT_INT_VALUE;
613 }
614 
GetCapacityLevel()615 BatteryCapacityLevel BatteryService::GetCapacityLevel()
616 {
617     BatteryCapacityLevel batteryCapacityLevel = BatteryCapacityLevel::LEVEL_NONE;
618     int32_t capacity = GetCapacity();
619     if (IsCapacityLevelDefined(shutdownCapacityThreshold_) && capacity > 0 && capacity <= shutdownCapacityThreshold_) {
620         batteryCapacityLevel = BatteryCapacityLevel::LEVEL_SHUTDOWN;
621     } else if (IsCapacityLevelDefined(criticalCapacityThreshold_) && capacity > shutdownCapacityThreshold_ &&
622         capacity <= criticalCapacityThreshold_) {
623         batteryCapacityLevel = BatteryCapacityLevel::LEVEL_CRITICAL;
624     } else if (IsCapacityLevelDefined(warningCapacityThreshold_) && capacity > criticalCapacityThreshold_ &&
625         capacity <= warningCapacityThreshold_) {
626         batteryCapacityLevel = BatteryCapacityLevel::LEVEL_WARNING;
627     } else if (IsCapacityLevelDefined(lowCapacityThreshold_) && capacity > warningCapacityThreshold_ &&
628         capacity <= lowCapacityThreshold_) {
629         batteryCapacityLevel = BatteryCapacityLevel::LEVEL_LOW;
630     } else if (IsCapacityLevelDefined(normalCapacityThreshold_) && capacity > lowCapacityThreshold_ &&
631         capacity <= normalCapacityThreshold_) {
632         batteryCapacityLevel = BatteryCapacityLevel::LEVEL_NORMAL;
633     } else if (IsCapacityLevelDefined(highCapacityThreshold_) && capacity > normalCapacityThreshold_ &&
634         capacity <= highCapacityThreshold_) {
635         batteryCapacityLevel = BatteryCapacityLevel::LEVEL_HIGH;
636     } else if (IsCapacityLevelDefined(fullCapacityThreshold_) && capacity > highCapacityThreshold_ &&
637         capacity <= fullCapacityThreshold_) {
638         batteryCapacityLevel = BatteryCapacityLevel::LEVEL_FULL;
639     }
640     return batteryCapacityLevel;
641 }
642 
Dump(int32_t fd,const std::vector<std::u16string> & args)643 int32_t BatteryService::Dump(int32_t fd, const std::vector<std::u16string> &args)
644 {
645     if (!Permission::IsSystem()) {
646         return ERR_PERMISSION_DENIED;
647     }
648     g_service = DelayedSpSingleton<BatteryService>::GetInstance();
649     BatteryDump& batteryDump = BatteryDump::GetInstance();
650     if ((args.empty()) || (args[0].size() != HELP_DUMP_PARAM)) {
651         BATTERY_HILOGD(FEATURE_BATT_INFO, "param cannot be empty or the length is not 2");
652         dprintf(fd, "cmd param number is not equal to 2\n");
653         batteryDump.DumpHelp(fd);
654         return ERR_NO_INIT;
655     }
656     if (args[0].compare(u"-d") == 0) {
657         ShowBatteryDialog();
658         dprintf(fd, "show low power dialog \n");
659         return ERR_OK;
660     }
661 
662     bool helpRet = batteryDump.DumpBatteryHelp(fd, args);
663     bool getBatteryInfo = batteryDump.GetBatteryInfo(fd, g_service, args);
664     bool unplugged = batteryDump.MockUnplugged(fd, g_service, args);
665     bool reset = batteryDump.ResetPlugged(fd, g_service, args);
666     bool total = helpRet + getBatteryInfo + unplugged + reset;
667     if (!total) {
668         dprintf(fd, "cmd param is error\n");
669         batteryDump.DumpHelp(fd);
670         return ERR_NO_INIT;
671     }
672 
673     return ERR_OK;
674 }
675 
MockUnplugged(bool isUnplugged)676 void BatteryService::MockUnplugged(bool isUnplugged)
677 {
678     V1_1::BatteryInfo event;
679     if (!iBatteryInterface_) {
680         BATTERY_HILOGE(FEATURE_BATT_INFO, "iBatteryInterface_ is nullptr");
681         return;
682     }
683 
684     iBatteryInterface_->GetBatteryInfo(event);
685     ConvertingEvent(event);
686     if (isUnplugged) {
687         batteryInfo_.SetPluggedType(BatteryPluggedType::PLUGGED_TYPE_NONE);
688         batteryInfo_.SetPluggedMaxCurrent(0);
689         batteryInfo_.SetPluggedMaxVoltage(0);
690         batteryInfo_.SetChargeState(BatteryChargeState::CHARGE_STATE_NONE);
691         HandleBatteryInfo();
692         isMockUnplugged_ = true;
693     } else {
694         isMockUnplugged_ = false;
695         HandleBatteryInfo();
696     }
697 }
698 
IsMockUnplugged()699 bool BatteryService::IsMockUnplugged()
700 {
701     return isMockUnplugged_;
702 }
703 } // namespace PowerMgr
704 } // namespace OHOS
705