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