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 "power_vibrator.h"
42 #include "v2_0/ibattery_callback.h"
43
44 using namespace OHOS::HDI::Battery;
45 using namespace OHOS::AAFwk;
46
47 namespace OHOS {
48 namespace PowerMgr {
49 namespace {
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 const std::string BATTERY_VIBRATOR_CONFIG_FILE = "etc/battery/battery_vibrator.json";
55 const std::string VENDOR_BATTERY_VIBRATOR_CONFIG_FILE = "/vendor/etc/battery/battery_vibrator.json";
56 const std::string SYSTEM_BATTERY_VIBRATOR_CONFIG_FILE = "/system/etc/battery/battery_vibrator.json";
57 const std::string COMMON_EVENT_BATTERY_CHANGED = "usual.event.BATTERY_CHANGED";
58 sptr<BatteryService> g_service = DelayedSpSingleton<BatteryService>::GetInstance();
59 FFRTQueue g_queue("battery_service");
60 FFRTHandle g_lowCapacityShutdownHandle = nullptr;
61 BatteryPluggedType g_lastPluggedType = BatteryPluggedType::PLUGGED_TYPE_NONE;
62 SysParam::BootCompletedCallback g_bootCompletedCallback;
63 }
64 std::atomic_bool BatteryService::isBootCompleted_ = false;
65
66 const bool G_REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(
67 DelayedSpSingleton<BatteryService>::GetInstance().GetRefPtr());
68
BatteryService()69 BatteryService::BatteryService()
70 : SystemAbility(POWER_MANAGER_BATT_SERVICE_ID, true)
71 {
72 }
73
~BatteryService()74 BatteryService::~BatteryService() {}
75
GetCurrentTime()76 static int64_t GetCurrentTime()
77 {
78 constexpr int32_t SEC_TO_MSEC = 1000;
79 constexpr int32_t NSEC_TO_MSEC = 1000000;
80 timespec tm {};
81 clock_gettime(CLOCK_MONOTONIC, &tm);
82
83 return tm.tv_sec * SEC_TO_MSEC + (tm.tv_nsec / NSEC_TO_MSEC);
84 }
85
OnStart()86 void BatteryService::OnStart()
87 {
88 if (ready_) {
89 BATTERY_HILOGD(COMP_SVC, "Service is ready, nothing to do");
90 return;
91 }
92 if (!(Init())) {
93 BATTERY_HILOGE(COMP_SVC, "Call init failed");
94 return;
95 }
96 RegisterHdiStatusListener();
97 if (!Publish(this)) {
98 BATTERY_HILOGE(COMP_SVC, "Register to system ability manager failed");
99 return;
100 }
101 AddSystemAbilityListener(MISCDEVICE_SERVICE_ABILITY_ID);
102 ready_ = true;
103 }
104
Init()105 bool BatteryService::Init()
106 {
107 InitConfig();
108 if (!batteryNotify_) {
109 batteryNotify_ = std::make_unique<BatteryNotify>();
110 }
111 VibratorInit();
112 RegisterBootCompletedCallback();
113 return true;
114 }
115
RegisterBootCompletedCallback()116 void BatteryService::RegisterBootCompletedCallback()
117 {
118 g_bootCompletedCallback = []() {
119 isBootCompleted_ = true;
120 };
121 SysParam::RegisterBootCompletedCallback(g_bootCompletedCallback);
122 }
123
OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)124 void BatteryService::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
125 {
126 BATTERY_HILOGI(COMP_SVC, "systemAbilityId=%{public}d, deviceId=%{private}s", systemAbilityId, deviceId.c_str());
127 if (systemAbilityId == MISCDEVICE_SERVICE_ABILITY_ID) {
128 batteryLight_.InitLight();
129 }
130 }
131
RegisterBatteryHdiCallback()132 bool BatteryService::RegisterBatteryHdiCallback()
133 {
134 std::lock_guard<std::shared_mutex> lock(mutex_);
135 if (iBatteryInterface_ == nullptr) {
136 iBatteryInterface_ = V2_0::IBatteryInterface::Get();
137 BATTERY_HILOGE(COMP_SVC, "failed to get battery hdi interface");
138 RETURN_IF_WITH_RET(iBatteryInterface_ == nullptr, false);
139 }
140 sptr<V2_0::IBatteryCallback> callback = new BatteryCallback();
141 ErrCode ret = iBatteryInterface_->Register(callback);
142 if (ret < 0) {
143 BATTERY_HILOGE(COMP_SVC, "register callback failed");
144 return false;
145 }
146
147 BatteryCallback::BatteryEventCallback eventCb =
148 [this](const V2_0::BatteryInfo& event) -> int32_t { return this->HandleBatteryCallbackEvent(event); };
149 BatteryCallback::RegisterBatteryEvent(eventCb);
150 return true;
151 }
152
InitConfig()153 void BatteryService::InitConfig()
154 {
155 auto& batteryConfig = BatteryConfig::GetInstance();
156 #ifdef HAS_BATTERY_CONFIG_POLICY_PART
157 batteryConfig.ParseConfig();
158 #endif
159
160 warnCapacity_ = batteryConfig.GetInt("soc.warning", warnCapacity_);
161 highTemperature_ = batteryConfig.GetInt("temperature.high", highTemperature_);
162 lowTemperature_ = batteryConfig.GetInt("temperature.low", lowTemperature_);
163 shutdownCapacityThreshold_ = batteryConfig.GetInt("soc.shutdown", shutdownCapacityThreshold_);
164 criticalCapacityThreshold_ = batteryConfig.GetInt("soc.critical", criticalCapacityThreshold_);
165 warningCapacityThreshold_ = batteryConfig.GetInt("soc.warning", warningCapacityThreshold_);
166 lowCapacityThreshold_ = batteryConfig.GetInt("soc.low", lowCapacityThreshold_);
167 normalCapacityThreshold_ = batteryConfig.GetInt("soc.normal", normalCapacityThreshold_);
168 highCapacityThreshold_ = batteryConfig.GetInt("soc.high", highCapacityThreshold_);
169 fullCapacityThreshold_ = batteryConfig.GetInt("soc.full", fullCapacityThreshold_);
170 BATTERY_HILOGI(COMP_SVC, "warnCapacity_=%{public}d, highTemperature_=%{public}d,\
171 lowTemperature_=%{public}d, shutdownCapacityThreshold_=%{public}d,\
172 criticalCapacityThreshold_=%{public}d, warningCapacityThreshold_=%{public}d, lowCapacityThreshold_=%{public}d,\
173 normalCapacityThreshold_=%{public}d, highCapacityThreshold_=%{public}d, fullCapacityThreshold_=%{public}d",
174 warnCapacity_, highTemperature_, lowTemperature_, shutdownCapacityThreshold_, criticalCapacityThreshold_,
175 warningCapacityThreshold_, lowCapacityThreshold_, normalCapacityThreshold_, highCapacityThreshold_,
176 fullCapacityThreshold_);
177 }
178
HandleBatteryCallbackEvent(const V2_0::BatteryInfo& event)179 int32_t BatteryService::HandleBatteryCallbackEvent(const V2_0::BatteryInfo& event)
180 {
181 if (isMockUnplugged_ || isMockCapacity_ || isMockUevent_) {
182 return ERR_OK;
183 }
184
185 ConvertingEvent(event);
186 RETURN_IF_WITH_RET(lastBatteryInfo_ == batteryInfo_, ERR_OK);
187 HandleBatteryInfo();
188 return ERR_OK;
189 }
190
ConvertingEvent(const V2_0::BatteryInfo& event)191 void BatteryService::ConvertingEvent(const V2_0::BatteryInfo& event)
192 {
193 if (!isMockCapacity_) {
194 batteryInfo_.SetCapacity(event.capacity);
195 }
196 if (!isMockUnplugged_) {
197 batteryInfo_.SetPluggedType(BatteryPluggedType(event.pluggedType));
198 batteryInfo_.SetPluggedMaxCurrent(event.pluggedMaxCurrent);
199 batteryInfo_.SetPluggedMaxVoltage(event.pluggedMaxVoltage);
200 batteryInfo_.SetChargeState(BatteryChargeState(event.chargeState));
201 }
202 batteryInfo_.SetVoltage(event.voltage);
203 batteryInfo_.SetTemperature(event.temperature);
204 batteryInfo_.SetHealthState(BatteryHealthState(event.healthState));
205 batteryInfo_.SetChargeCounter(event.chargeCounter);
206 batteryInfo_.SetTotalEnergy(event.totalEnergy);
207 batteryInfo_.SetCurAverage(event.curAverage);
208 batteryInfo_.SetRemainEnergy(event.remainEnergy);
209 batteryInfo_.SetPresent(event.present);
210 batteryInfo_.SetTechnology(event.technology);
211 batteryInfo_.SetNowCurrent(event.curNow);
212 batteryInfo_.SetChargeType(GetChargeType());
213 if (!isMockUevent_) {
214 batteryInfo_.SetUevent(event.uevent);
215 }
216 }
217
InitBatteryInfo()218 void BatteryService::InitBatteryInfo()
219 {
220 batteryInfo_.SetCapacity(GetCapacity());
221 batteryInfo_.SetPluggedType(GetPluggedType());
222 batteryInfo_.SetChargeState(GetChargingStatus());
223 batteryInfo_.SetVoltage(GetVoltage());
224 batteryInfo_.SetTemperature(GetBatteryTemperature());
225 batteryInfo_.SetHealthState(GetHealthStatus());
226 batteryInfo_.SetTotalEnergy(GetTotalEnergy());
227 batteryInfo_.SetCurAverage(GetCurrentAverage());
228 batteryInfo_.SetRemainEnergy(GetRemainEnergy());
229 batteryInfo_.SetPresent(GetPresent());
230 batteryInfo_.SetTechnology(GetTechnology());
231 batteryInfo_.SetNowCurrent(GetNowCurrent());
232 batteryInfo_.SetChargeType(GetChargeType());
233 AddBootCommonEvents();
234 HandleBatteryInfo();
235 }
236
AddBootCommonEvents()237 void BatteryService::AddBootCommonEvents()
238 {
239 std::string ueventName;
240 std::string commonEventName = COMMON_EVENT_BATTERY_CHANGED;
241 if (FillCommonEvent(ueventName, commonEventName)) {
242 BATTERY_HILOGI(COMP_SVC, "need boot broadcast %{public}s", commonEventName.c_str());
243 // Splicing strings for parsing uevent
244 batteryInfo_.SetUevent(ueventName + "$sendcommonevent");
245 }
246
247 if (commonEventName != COMMON_EVENT_BATTERY_CHANGED) {
248 batteryInfo_.SetUevent(ueventName);
249 batteryNotify_->PublishCustomEvent(batteryInfo_, commonEventName);
250 batteryInfo_.SetUevent("");
251 }
252 }
253
FillCommonEvent(std::string& ueventName, std::string& commonEventName)254 bool BatteryService::FillCommonEvent(std::string& ueventName, std::string& commonEventName)
255 {
256 const auto& commonEventConf = BatteryConfig::GetInstance().GetCommonEventConf();
257 if (commonEventConf.empty()) {
258 BATTERY_HILOGI(COMP_SVC, "don't need send common event, config is empty!");
259 return false;
260 }
261 for (const auto& iter : commonEventConf) {
262 commonEventName = iter.eventName;
263 ueventName = iter.uevent;
264 std::string result;
265 BatteryError error = GetBatteryConfig(iter.sceneConfigName, result);
266 if (error != BatteryError::ERR_OK) {
267 continue;
268 }
269 bool isEqual = iter.sceneConfigEqual;
270 std::string configValue = iter.sceneConfigValue;
271 ueventName += result;
272 if ((isEqual && result == configValue) || (!isEqual && result != configValue)) {
273 return true;
274 }
275 }
276 BATTERY_HILOGI(COMP_SVC, "don't need send common event");
277 return false;
278 }
279
HandleBatteryInfo()280 void BatteryService::HandleBatteryInfo()
281 {
282 BATTERY_HILOGI(FEATURE_BATT_INFO, "capacity=%{public}d, voltage=%{public}d, temperature=%{public}d, "
283 "healthState=%{public}d, pluggedType=%{public}d, pluggedMaxCurrent=%{public}d, "
284 "pluggedMaxVoltage=%{public}d, chargeState=%{public}d, chargeCounter=%{public}d, present=%{public}d, "
285 "technology=%{public}s, currNow=%{public}d, totalEnergy=%{public}d, curAverage=%{public}d, "
286 "remainEnergy=%{public}d, chargeType=%{public}d, event=%{public}s", batteryInfo_.GetCapacity(),
287 batteryInfo_.GetVoltage(), batteryInfo_.GetTemperature(), batteryInfo_.GetHealthState(),
288 batteryInfo_.GetPluggedType(), batteryInfo_.GetPluggedMaxCurrent(), batteryInfo_.GetPluggedMaxVoltage(),
289 batteryInfo_.GetChargeState(), batteryInfo_.GetChargeCounter(), batteryInfo_.IsPresent(),
290 batteryInfo_.GetTechnology().c_str(), batteryInfo_.GetNowCurrent(), batteryInfo_.GetTotalEnergy(),
291 batteryInfo_.GetCurAverage(), batteryInfo_.GetRemainEnergy(), batteryInfo_.GetChargeType(),
292 batteryInfo_.GetUevent().c_str());
293
294 batteryLight_.UpdateColor(batteryInfo_.GetChargeState(), batteryInfo_.GetCapacity());
295 WakeupDevice(batteryInfo_.GetPluggedType());
296 CalculateRemainingChargeTime(batteryInfo_.GetCapacity(), batteryInfo_.GetChargeState());
297
298 batteryNotify_->PublishEvents(batteryInfo_);
299 HandleTemperature(batteryInfo_.GetTemperature());
300 HandleCapacity(batteryInfo_.GetCapacity(), batteryInfo_.GetChargeState(), batteryInfo_.IsPresent());
301 lastBatteryInfo_ = batteryInfo_;
302 }
303
RegisterHdiStatusListener()304 bool BatteryService::RegisterHdiStatusListener()
305 {
306 hdiServiceMgr_ = OHOS::HDI::ServiceManager::V1_0::IServiceManager::Get();
307 if (hdiServiceMgr_ == nullptr) {
308 BATTERY_HILOGW(COMP_SVC, "hdi service manager is nullptr, Try again after %{public}u second", RETRY_TIME);
309 FFRTTask retryTask = [this] {
310 return RegisterHdiStatusListener();
311 };
312 FFRTUtils::SubmitDelayTask(retryTask, RETRY_TIME, g_queue);
313 return false;
314 }
315
316 hdiServStatListener_ = new HdiServiceStatusListener(HdiServiceStatusListener::StatusCallback(
317 [this](const OHOS::HDI::ServiceManager::V1_0::ServiceStatus &status) {
318 RETURN_IF(status.serviceName != BATTERY_HDI_NAME || status.deviceClass != DEVICE_CLASS_DEFAULT);
319
320 std::lock_guard<std::shared_mutex> lock(mutex_);
321 if (status.status == SERVIE_STATUS_START) {
322 FFRTTask task = [this] {
323 (void)RegisterBatteryHdiCallback();
324 #ifdef BATTERY_MANAGER_SET_LOW_CAPACITY_THRESHOLD
325 SetLowCapacityThreshold();
326 #endif
327 InitBatteryInfo();
328 return;
329 };
330 FFRTUtils::SubmitTask(task);
331 BATTERY_HILOGD(COMP_SVC, "battery interface service start");
332 } else if (status.status == SERVIE_STATUS_STOP && iBatteryInterface_) {
333 iBatteryInterface_->UnRegister();
334 iBatteryInterface_ = nullptr;
335 BATTERY_HILOGW(COMP_SVC, "battery interface service stop, unregister interface");
336 }
337 }
338 ));
339
340 int32_t status = hdiServiceMgr_->RegisterServiceStatusListener(hdiServStatListener_, DEVICE_CLASS_DEFAULT);
341 if (status != ERR_OK) {
342 BATTERY_HILOGW(COMP_SVC, "Register hdi failed, Try again after %{public}u second", RETRY_TIME);
343 FFRTTask retryTask = [this] {
344 return RegisterHdiStatusListener();
345 };
346 FFRTUtils::SubmitDelayTask(retryTask, RETRY_TIME, g_queue);
347 return false;
348 }
349 return true;
350 }
351
OnStop()352 void BatteryService::OnStop()
353 {
354 if (!ready_) {
355 return;
356 }
357 ready_ = false;
358 isBootCompleted_ = false;
359
360 std::lock_guard<std::shared_mutex> lock(mutex_);
361 if (iBatteryInterface_ != nullptr) {
362 iBatteryInterface_->UnRegister();
363 iBatteryInterface_ = nullptr;
364 }
365 if (hdiServiceMgr_ != nullptr) {
366 hdiServiceMgr_->UnregisterServiceStatusListener(hdiServStatListener_);
367 hdiServiceMgr_ = nullptr;
368 }
369 }
370
IsLastPlugged()371 bool BatteryService::IsLastPlugged()
372 {
373 if (g_lastPluggedType != BatteryPluggedType::PLUGGED_TYPE_NONE &&
374 g_lastPluggedType != BatteryPluggedType::PLUGGED_TYPE_BUTT) {
375 return true;
376 }
377 return false;
378 }
379
IsNowPlugged(BatteryPluggedType pluggedType)380 bool BatteryService::IsNowPlugged(BatteryPluggedType pluggedType)
381 {
382 if (pluggedType != BatteryPluggedType::PLUGGED_TYPE_NONE &&
383 pluggedType != BatteryPluggedType::PLUGGED_TYPE_BUTT) {
384 return true;
385 }
386 return false;
387 }
388
IsPlugged(BatteryPluggedType pluggedType)389 bool BatteryService::IsPlugged(BatteryPluggedType pluggedType)
390 {
391 if (!IsLastPlugged() && IsNowPlugged(pluggedType)) {
392 return true;
393 }
394 return false;
395 }
396
IsUnplugged(BatteryPluggedType pluggedType)397 bool BatteryService::IsUnplugged(BatteryPluggedType pluggedType)
398 {
399 if (IsLastPlugged() && !IsNowPlugged(pluggedType)) {
400 return true;
401 }
402 return false;
403 }
404
IsCharging(BatteryChargeState chargeState)405 bool BatteryService::IsCharging(BatteryChargeState chargeState)
406 {
407 return chargeState == BatteryChargeState::CHARGE_STATE_ENABLE;
408 }
409
IsInExtremePowerSaveMode()410 bool BatteryService::IsInExtremePowerSaveMode()
411 {
412 PowerMode mode = PowerMgrClient::GetInstance().GetDeviceMode();
413 return mode == PowerMode::EXTREME_POWER_SAVE_MODE;
414 }
415
WakeupDevice(BatteryPluggedType pluggedType)416 void BatteryService::WakeupDevice(BatteryPluggedType pluggedType)
417 {
418 if (IsPlugged(pluggedType) || IsUnplugged(pluggedType)) {
419 PowerMgrClient::GetInstance().WakeupDevice();
420 }
421 g_lastPluggedType = pluggedType;
422 }
423
HandleTemperature(int32_t temperature)424 void BatteryService::HandleTemperature(int32_t temperature)
425 {
426 if (((temperature <= lowTemperature_) || (temperature >= highTemperature_)) &&
427 (highTemperature_ != lowTemperature_)) {
428 PowerMgrClient::GetInstance().ShutDownDevice("TemperatureOutOfRange");
429 }
430 }
431
HandleCapacity(int32_t capacity, BatteryChargeState chargeState, bool isBatteryPresent)432 void BatteryService::HandleCapacity(int32_t capacity, BatteryChargeState chargeState, bool isBatteryPresent)
433 {
434 if ((capacity <= shutdownCapacityThreshold_) &&
435 (g_lowCapacityShutdownHandle == nullptr) &&
436 #ifndef BATTERY_MANAGER_SET_LOW_CAPACITY_THRESHOLD
437 isBatteryPresent &&
438 #endif
439 (!IsCharging(chargeState))) {
440 BATTERY_HILOGI(COMP_SVC, "HandleCapacity begin to submit task, "
441 "capacity=%{public}d, chargeState=%{public}u, isBatteryPresent=%{public}d",
442 capacity, static_cast<uint32_t>(chargeState), isBatteryPresent);
443 FFRTTask task = [&] {
444 if (!IsInExtremePowerSaveMode()) {
445 BATTERY_HILOGI(COMP_SVC, "HandleCapacity begin to shutdown");
446 PowerMgrClient::GetInstance().ShutDownDevice("LowCapacity");
447 }
448 };
449 g_lowCapacityShutdownHandle = FFRTUtils::SubmitDelayTask(task, SHUTDOWN_DELAY_TIME_MS, g_queue);
450 }
451
452 if (g_lowCapacityShutdownHandle != nullptr && IsCharging(chargeState)) {
453 BATTERY_HILOGI(COMP_SVC, "HandleCapacity cancel shutdown task, "
454 "capacity=%{public}d, chargeState=%{public}u, isBatteryPresent=%{public}d",
455 capacity, static_cast<uint32_t>(chargeState), isBatteryPresent);
456 FFRTUtils::CancelTask(g_lowCapacityShutdownHandle, g_queue);
457 g_lowCapacityShutdownHandle = nullptr;
458 }
459 }
460
GetCapacity()461 int32_t BatteryService::GetCapacity()
462 {
463 if (isMockCapacity_) {
464 BATTERY_HILOGD(FEATURE_BATT_INFO, "Return mock battery capacity");
465 return batteryInfo_.GetCapacity();
466 }
467 std::shared_lock<std::shared_mutex> lock(mutex_);
468 int32_t capacity = BATTERY_FULL_CAPACITY;
469 if (iBatteryInterface_ == nullptr) {
470 BATTERY_HILOGE(FEATURE_BATT_INFO, "iBatteryInterface_ is nullptr");
471 return capacity;
472 }
473 iBatteryInterface_->GetCapacity(capacity);
474 return capacity;
475 }
476
ChangePath(const std::string path)477 bool BatteryService::ChangePath(const std::string path)
478 {
479 BATTERY_HILOGD(FEATURE_BATT_INFO, "Enter");
480 std::shared_lock<std::shared_mutex> lock(mutex_);
481 if (iBatteryInterface_ == nullptr) {
482 BATTERY_HILOGE(FEATURE_BATT_INFO, "iBatteryInterface_ is nullptr");
483 return false;
484 }
485 iBatteryInterface_->ChangePath(path);
486 return true;
487 }
488
489 #ifdef BATTERY_MANAGER_SET_LOW_CAPACITY_THRESHOLD
SetLowCapacityThreshold()490 void BatteryService::SetLowCapacityThreshold()
491 {
492 const std::string thers = "low_battery_thers";
493 if (iBatteryInterface_ == nullptr) {
494 BATTERY_HILOGE(FEATURE_BATT_INFO, "iBatteryInterface_ is nullptr");
495 return;
496 }
497 BATTERY_HILOGI(FEATURE_BATT_INFO, "set low capacity thres: criticalCapacityThreshold_ = %{public}d",
498 criticalCapacityThreshold_);
499 iBatteryInterface_->SetBatteryConfig(thers, std::to_string(criticalCapacityThreshold_));
500 }
501 #endif
502
SetBatteryConfig(const std::string& sceneName, const std::string& value)503 BatteryError BatteryService::SetBatteryConfig(const std::string& sceneName, const std::string& value)
504 {
505 if (!Permission::IsSystem() || !Permission::IsNativePermissionGranted("ohos.permission.POWER_OPTIMIZATION")) {
506 BATTERY_HILOGI(FEATURE_BATT_INFO, "SetBatteryConfig failed, System permission intercept");
507 return BatteryError::ERR_SYSTEM_API_DENIED;
508 }
509
510 BATTERY_HILOGD(FEATURE_BATT_INFO, "Enter SetBatteryConfig");
511 std::shared_lock<std::shared_mutex> lock(mutex_);
512 if (iBatteryInterface_ == nullptr) {
513 BATTERY_HILOGE(FEATURE_BATT_INFO, "iBatteryInterface_ is nullptr");
514 return BatteryError::ERR_FAILURE;
515 }
516 return iBatteryInterface_->SetBatteryConfig(sceneName, value) == ERR_OK ?
517 BatteryError::ERR_OK : BatteryError::ERR_FAILURE;
518 }
519
GetBatteryConfig(const std::string& sceneName, std::string& result)520 BatteryError BatteryService::GetBatteryConfig(const std::string& sceneName, std::string& result)
521 {
522 if (!Permission::IsSystem()) {
523 BATTERY_HILOGI(FEATURE_BATT_INFO, "GetBatteryConfig failed, System permission intercept");
524 return BatteryError::ERR_SYSTEM_API_DENIED;
525 }
526
527 BATTERY_HILOGD(FEATURE_BATT_INFO, "Enter GetBatteryConfig");
528 std::shared_lock<std::shared_mutex> lock(mutex_);
529 if (iBatteryInterface_ == nullptr) {
530 BATTERY_HILOGE(FEATURE_BATT_INFO, "iBatteryInterface_ is nullptr");
531 return BatteryError::ERR_FAILURE;
532 }
533
534 int32_t ret = iBatteryInterface_->GetBatteryConfig(sceneName, result);
535 if (ret != ERR_OK) {
536 BATTERY_HILOGE(FEATURE_BATT_INFO, "get charge config failed, key:%{public}s", sceneName.c_str());
537 return BatteryError::ERR_FAILURE;
538 }
539
540 return BatteryError::ERR_OK;
541 }
542
IsBatteryConfigSupported(const std::string& sceneName, bool& result)543 BatteryError BatteryService::IsBatteryConfigSupported(const std::string& sceneName, bool& result)
544 {
545 if (!Permission::IsSystem()) {
546 BATTERY_HILOGI(FEATURE_BATT_INFO, "IsBatteryConfigSupported failed, System permission intercept");
547 return BatteryError::ERR_SYSTEM_API_DENIED;
548 }
549
550 BATTERY_HILOGD(FEATURE_BATT_INFO, "Enter IsBatteryConfigSupported");
551 std::shared_lock<std::shared_mutex> lock(mutex_);
552 if (iBatteryInterface_ == nullptr) {
553 BATTERY_HILOGE(FEATURE_BATT_INFO, "iBatteryInterface_ is nullptr");
554 return BatteryError::ERR_FAILURE;
555 }
556
557 int32_t ret = iBatteryInterface_->IsBatteryConfigSupported(sceneName, result);
558 if (ret != ERR_OK) {
559 BATTERY_HILOGE(FEATURE_BATT_INFO, "get support charge config failed, key:%{public}s", sceneName.c_str());
560 return BatteryError::ERR_FAILURE;
561 }
562 return BatteryError::ERR_OK;
563 }
564
GetChargingStatus()565 BatteryChargeState BatteryService::GetChargingStatus()
566 {
567 if (isMockUnplugged_) {
568 BATTERY_HILOGD(FEATURE_BATT_INFO, "Return mock charge status");
569 return batteryInfo_.GetChargeState();
570 }
571 std::shared_lock<std::shared_mutex> lock(mutex_);
572 V2_0::BatteryChargeState chargeState = V2_0::BatteryChargeState(0);
573 if (iBatteryInterface_ == nullptr) {
574 BATTERY_HILOGE(FEATURE_BATT_INFO, "iBatteryInterface_ is nullptr");
575 return BatteryChargeState(chargeState);
576 }
577 iBatteryInterface_->GetChargeState(chargeState);
578 return BatteryChargeState(chargeState);
579 }
580
GetHealthStatus()581 BatteryHealthState BatteryService::GetHealthStatus()
582 {
583 BATTERY_HILOGD(FEATURE_BATT_INFO, "Enter");
584 std::shared_lock<std::shared_mutex> lock(mutex_);
585 V2_0::BatteryHealthState healthState = V2_0::BatteryHealthState(0);
586 if (iBatteryInterface_ == nullptr) {
587 BATTERY_HILOGE(FEATURE_BATT_INFO, "iBatteryInterface_ is nullptr");
588 return BatteryHealthState(healthState);
589 }
590
591 iBatteryInterface_->GetHealthState(healthState);
592 return BatteryHealthState(healthState);
593 }
594
GetPluggedType()595 BatteryPluggedType BatteryService::GetPluggedType()
596 {
597 if (isMockUnplugged_) {
598 BATTERY_HILOGD(FEATURE_BATT_INFO, "Return mock plugged type");
599 return batteryInfo_.GetPluggedType();
600 }
601 std::shared_lock<std::shared_mutex> lock(mutex_);
602 V2_0::BatteryPluggedType pluggedType = V2_0::BatteryPluggedType(0);
603 if (iBatteryInterface_ == nullptr) {
604 BATTERY_HILOGE(FEATURE_BATT_INFO, "iBatteryInterface_ is nullptr");
605 return BatteryPluggedType(pluggedType);
606 }
607 iBatteryInterface_->GetPluggedType(pluggedType);
608 return BatteryPluggedType(pluggedType);
609 }
610
GetVoltage()611 int32_t BatteryService::GetVoltage()
612 {
613 std::shared_lock<std::shared_mutex> lock(mutex_);
614 if (iBatteryInterface_ == nullptr) {
615 BATTERY_HILOGE(FEATURE_BATT_INFO, "iBatteryInterface_ is nullptr");
616 return ERR_NO_INIT;
617 }
618 int32_t voltage = INVALID_BATT_INT_VALUE;
619 iBatteryInterface_->GetVoltage(voltage);
620 return voltage;
621 }
622
GetPresent()623 bool BatteryService::GetPresent()
624 {
625 std::shared_lock<std::shared_mutex> lock(mutex_);
626 bool present = false;
627 if (iBatteryInterface_ == nullptr) {
628 BATTERY_HILOGE(FEATURE_BATT_INFO, "iBatteryInterface_ is nullptr");
629 return present;
630 }
631
632 iBatteryInterface_->GetPresent(present);
633 return present;
634 }
635
GetTechnology()636 std::string BatteryService::GetTechnology()
637 {
638 std::shared_lock<std::shared_mutex> lock(mutex_);
639 if (iBatteryInterface_ == nullptr) {
640 BATTERY_HILOGE(FEATURE_BATT_INFO, "iBatteryInterface_ is nullptr");
641 return "";
642 }
643
644 std::string technology;
645 iBatteryInterface_->GetTechnology(technology);
646 return technology;
647 }
648
GetBatteryTemperature()649 int32_t BatteryService::GetBatteryTemperature()
650 {
651 std::shared_lock<std::shared_mutex> lock(mutex_);
652 if (iBatteryInterface_ == nullptr) {
653 BATTERY_HILOGE(FEATURE_BATT_INFO, "iBatteryInterface_ is nullptr");
654 return batteryInfo_.GetTemperature();
655 }
656 int32_t temperature = INVALID_BATT_INT_VALUE;
657 iBatteryInterface_->GetTemperature(temperature);
658 return temperature;
659 }
660
GetTotalEnergy()661 int32_t BatteryService::GetTotalEnergy()
662 {
663 int32_t totalEnergy = INVALID_BATT_INT_VALUE;
664 if (!Permission::IsSystem()) {
665 BATTERY_HILOGD(FEATURE_BATT_INFO, "GetTotalEnergy totalEnergy: %{public}d", totalEnergy);
666 return totalEnergy;
667 }
668 std::shared_lock<std::shared_mutex> lock(mutex_);
669 if (iBatteryInterface_ == nullptr) {
670 BATTERY_HILOGE(FEATURE_BATT_INFO, "iBatteryInterface_ is nullptr");
671 return batteryInfo_.GetTotalEnergy();
672 }
673 iBatteryInterface_->GetTotalEnergy(totalEnergy);
674 return totalEnergy;
675 }
676
GetCurrentAverage()677 int32_t BatteryService::GetCurrentAverage()
678 {
679 std::shared_lock<std::shared_mutex> lock(mutex_);
680 if (iBatteryInterface_ == nullptr) {
681 BATTERY_HILOGE(FEATURE_BATT_INFO, "iBatteryInterface_ is nullptr");
682 return batteryInfo_.GetCurAverage();
683 }
684 int32_t curAverage = INVALID_BATT_INT_VALUE;
685 iBatteryInterface_->GetCurrentAverage(curAverage);
686 return curAverage;
687 }
688
GetNowCurrent()689 int32_t BatteryService::GetNowCurrent()
690 {
691 int32_t nowCurr = INVALID_BATT_INT_VALUE;
692 std::shared_lock<std::shared_mutex> lock(mutex_);
693 if (iBatteryInterface_ == nullptr) {
694 BATTERY_HILOGE(FEATURE_BATT_INFO, "iBatteryInterface_ is nullptr");
695 return batteryInfo_.GetNowCurrent();
696 }
697 iBatteryInterface_->GetCurrentNow(nowCurr);
698 return nowCurr;
699 }
700
GetRemainEnergy()701 int32_t BatteryService::GetRemainEnergy()
702 {
703 int32_t remainEnergy = INVALID_BATT_INT_VALUE;
704 if (!Permission::IsSystem()) {
705 BATTERY_HILOGD(FEATURE_BATT_INFO, "GetRemainEnergy remainEnergy: %{public}d", remainEnergy);
706 return remainEnergy;
707 }
708 std::shared_lock<std::shared_mutex> lock(mutex_);
709 if (iBatteryInterface_ == nullptr) {
710 BATTERY_HILOGE(FEATURE_BATT_INFO, "iBatteryInterface_ is nullptr");
711 return batteryInfo_.GetRemainEnergy();
712 }
713 iBatteryInterface_->GetRemainEnergy(remainEnergy);
714 return remainEnergy;
715 }
716
GetChargeType()717 ChargeType BatteryService::GetChargeType()
718 {
719 std::shared_lock<std::shared_mutex> lock(mutex_);
720 V2_0::ChargeType chargeType = V2_0::ChargeType::CHARGE_TYPE_NONE;
721 if (iBatteryInterface_ == nullptr) {
722 BATTERY_HILOGE(FEATURE_BATT_INFO, "iBatteryInterface_ is nullptr");
723 return ChargeType(chargeType);
724 }
725
726 iBatteryInterface_->GetChargeType(chargeType);
727 return ChargeType(chargeType);
728 }
729
CalculateRemainingChargeTime(int32_t capacity, BatteryChargeState chargeState)730 void BatteryService::CalculateRemainingChargeTime(int32_t capacity, BatteryChargeState chargeState)
731 {
732 if (capacity > BATTERY_FULL_CAPACITY) {
733 BATTERY_HILOGE(FEATURE_BATT_INFO, "capacity error");
734 return;
735 }
736
737 if (chargeState != BatteryChargeState::CHARGE_STATE_ENABLE) {
738 remainTime_ = 0;
739 chargeFlag_ = false;
740 return;
741 }
742
743 if (!chargeFlag_) {
744 lastCapacity_ = capacity;
745 lastTime_ = GetCurrentTime();
746 chargeFlag_ = true;
747 }
748
749 if (capacity < lastCapacity_) {
750 lastCapacity_ = capacity;
751 }
752
753 if (((capacity - lastCapacity_) >= 1) && (lastCapacity_ >= 0) && chargeFlag_) {
754 int64_t onceTime = (GetCurrentTime() - lastTime_) / (capacity - lastCapacity_);
755 remainTime_ = (BATTERY_FULL_CAPACITY - capacity) * onceTime;
756 lastCapacity_ = capacity;
757 lastTime_ = GetCurrentTime();
758 }
759 }
760
GetRemainingChargeTime()761 int64_t BatteryService::GetRemainingChargeTime()
762 {
763 if (!Permission::IsSystem()) {
764 BATTERY_HILOGW(FEATURE_BATT_INFO, "system permission denied.");
765 return INVALID_REMAINING_CHARGE_TIME_VALUE;
766 }
767 return remainTime_;
768 }
769
IsCapacityLevelDefined(int32_t capacityThreshold)770 bool IsCapacityLevelDefined(int32_t capacityThreshold)
771 {
772 return capacityThreshold != INVALID_BATT_INT_VALUE;
773 }
774
GetCapacityLevel()775 BatteryCapacityLevel BatteryService::GetCapacityLevel()
776 {
777 BatteryCapacityLevel batteryCapacityLevel = BatteryCapacityLevel::LEVEL_NONE;
778 int32_t capacity = GetCapacity();
779 if (IsCapacityLevelDefined(shutdownCapacityThreshold_) && capacity > 0 && capacity <= shutdownCapacityThreshold_) {
780 batteryCapacityLevel = BatteryCapacityLevel::LEVEL_SHUTDOWN;
781 } else if (IsCapacityLevelDefined(criticalCapacityThreshold_) && capacity > shutdownCapacityThreshold_ &&
782 capacity <= criticalCapacityThreshold_) {
783 batteryCapacityLevel = BatteryCapacityLevel::LEVEL_CRITICAL;
784 } else if (IsCapacityLevelDefined(warningCapacityThreshold_) && capacity > criticalCapacityThreshold_ &&
785 capacity <= warningCapacityThreshold_) {
786 batteryCapacityLevel = BatteryCapacityLevel::LEVEL_WARNING;
787 } else if (IsCapacityLevelDefined(lowCapacityThreshold_) && capacity > warningCapacityThreshold_ &&
788 capacity <= lowCapacityThreshold_) {
789 batteryCapacityLevel = BatteryCapacityLevel::LEVEL_LOW;
790 } else if (IsCapacityLevelDefined(normalCapacityThreshold_) && capacity > lowCapacityThreshold_ &&
791 capacity <= normalCapacityThreshold_) {
792 batteryCapacityLevel = BatteryCapacityLevel::LEVEL_NORMAL;
793 } else if (IsCapacityLevelDefined(highCapacityThreshold_) && capacity > normalCapacityThreshold_ &&
794 capacity <= highCapacityThreshold_) {
795 batteryCapacityLevel = BatteryCapacityLevel::LEVEL_HIGH;
796 } else if (IsCapacityLevelDefined(fullCapacityThreshold_) && capacity > highCapacityThreshold_ &&
797 capacity <= fullCapacityThreshold_) {
798 batteryCapacityLevel = BatteryCapacityLevel::LEVEL_FULL;
799 }
800 return batteryCapacityLevel;
801 }
802
Dump(int32_t fd, const std::vector<std::u16string> &args)803 int32_t BatteryService::Dump(int32_t fd, const std::vector<std::u16string> &args)
804 {
805 if (!isBootCompleted_) {
806 return ERR_NO_INIT;
807 }
808 if (!Permission::IsSystem()) {
809 return ERR_PERMISSION_DENIED;
810 }
811
812 BatteryDump& batteryDump = BatteryDump::GetInstance();
813 if ((args.empty()) || (args[0].compare(u"-h") == 0)) {
814 batteryDump.DumpBatteryHelp(fd);
815 return ERR_OK;
816 }
817 bool getBatteryInfo = batteryDump.GetBatteryInfo(fd, g_service, args);
818 bool unplugged = batteryDump.MockUnplugged(fd, g_service, args);
819 bool mockedCapacity = batteryDump.MockCapacity(fd, g_service, args);
820 bool mockedUevent = batteryDump.MockUevent(fd, g_service, args);
821 bool reset = batteryDump.Reset(fd, g_service, args);
822 bool total = getBatteryInfo + unplugged + mockedCapacity + mockedUevent + reset;
823 if (!total) {
824 dprintf(fd, "cmd param is invalid\n");
825 batteryDump.DumpBatteryHelp(fd);
826 return ERR_NO_INIT;
827 }
828
829 return ERR_OK;
830 }
831
MockUnplugged()832 void BatteryService::MockUnplugged()
833 {
834 std::shared_lock<std::shared_mutex> lock(mutex_);
835 if (!iBatteryInterface_) {
836 BATTERY_HILOGE(FEATURE_BATT_INFO, "iBatteryInterface_ is nullptr");
837 return;
838 }
839 isMockUnplugged_ = true;
840 V2_0::BatteryInfo event;
841 iBatteryInterface_->GetBatteryInfo(event);
842 ConvertingEvent(event);
843 batteryInfo_.SetPluggedType(BatteryPluggedType::PLUGGED_TYPE_NONE);
844 batteryInfo_.SetPluggedMaxCurrent(0);
845 batteryInfo_.SetPluggedMaxVoltage(0);
846 batteryInfo_.SetChargeState(BatteryChargeState::CHARGE_STATE_NONE);
847 HandleBatteryInfo();
848 }
849
IsMockUnplugged()850 bool BatteryService::IsMockUnplugged()
851 {
852 return isMockUnplugged_;
853 }
854
MockCapacity(int32_t capacity)855 void BatteryService::MockCapacity(int32_t capacity)
856 {
857 std::shared_lock<std::shared_mutex> lock(mutex_);
858 if (!iBatteryInterface_) {
859 BATTERY_HILOGE(FEATURE_BATT_INFO, "iBatteryInterface_ is nullptr");
860 return;
861 }
862 isMockCapacity_ = true;
863 V2_0::BatteryInfo event;
864 iBatteryInterface_->GetBatteryInfo(event);
865 ConvertingEvent(event);
866 batteryInfo_.SetCapacity(capacity);
867 HandleBatteryInfo();
868 }
869
IsMockCapacity()870 bool BatteryService::IsMockCapacity()
871 {
872 return isMockCapacity_;
873 }
874
MockUevent(const std::string& uevent)875 void BatteryService::MockUevent(const std::string& uevent)
876 {
877 std::shared_lock<std::shared_mutex> lock(mutex_);
878 if (!iBatteryInterface_) {
879 BATTERY_HILOGE(FEATURE_BATT_INFO, "iBatteryInterface_ is nullptr");
880 return;
881 }
882 isMockUevent_ = true;
883 V2_0::BatteryInfo event;
884 iBatteryInterface_->GetBatteryInfo(event);
885 ConvertingEvent(event);
886 batteryInfo_.SetUevent(uevent);
887 HandleBatteryInfo();
888 }
889
Reset()890 void BatteryService::Reset()
891 {
892 std::shared_lock<std::shared_mutex> lock(mutex_);
893 if (!iBatteryInterface_) {
894 BATTERY_HILOGE(FEATURE_BATT_INFO, "iBatteryInterface_ is nullptr");
895 return;
896 }
897 isMockUnplugged_ = false;
898 isMockCapacity_ = false;
899 isMockUevent_ = false;
900 V2_0::BatteryInfo event;
901 iBatteryInterface_->GetBatteryInfo(event);
902 ConvertingEvent(event);
903 HandleBatteryInfo();
904 }
905
VibratorInit()906 void BatteryService::VibratorInit()
907 {
908 std::shared_ptr<PowerVibrator> vibrator = PowerVibrator::GetInstance();
909 vibrator->LoadConfig(BATTERY_VIBRATOR_CONFIG_FILE,
910 VENDOR_BATTERY_VIBRATOR_CONFIG_FILE, SYSTEM_BATTERY_VIBRATOR_CONFIG_FILE);
911 }
912 } // namespace PowerMgr
913 } // namespace OHOS
914