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