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