• 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 "thermal_service.h"
17 
18 #include "file_ex.h"
19 #include "if_system_ability_manager.h"
20 #include "iservice_registry.h"
21 #include "securec.h"
22 #include "system_ability_definition.h"
23 #include <algorithm>
24 #include <fcntl.h>
25 #include <ipc_skeleton.h>
26 #include <thread>
27 #include <unistd.h>
28 
29 #include "config_policy_utils.h"
30 #include "constants.h"
31 #include "ffrt_utils.h"
32 #include "permission.h"
33 #include "sysparam.h"
34 #include "soc_action_base.h"
35 #include "thermal_common.h"
36 #include "thermal_mgr_dumper.h"
37 #include "xcollie/watchdog.h"
38 
39 namespace OHOS {
40 namespace PowerMgr {
41 sptr<ThermalService> ThermalService::instance_ = nullptr;
42 std::mutex ThermalService::singletonMutex_;
43 namespace {
44 const std::string THERMAL_SERVICE_CONFIG_PATH = "etc/thermal_config/thermal_service_config.xml";
45 const std::string VENDOR_THERMAL_SERVICE_CONFIG_PATH = "/vendor/etc/thermal_config/thermal_service_config.xml";
46 const std::string SYSTEM_THERMAL_SERVICE_CONFIG_PATH = "/system/etc/thermal_config/thermal_service_config.xml";
47 constexpr const char* THMERMAL_SERVICE_NAME = "ThermalService";
48 constexpr const char* HDI_SERVICE_NAME = "thermal_interface_service";
49 FFRTQueue g_queue("thermal_service");
50 constexpr uint32_t RETRY_TIME = 1000;
51 auto g_service = ThermalService::GetInstance();
52 const bool G_REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(g_service.GetRefPtr());
53 SysParam::BootCompletedCallback g_bootCompletedCallback;
54 } // namespace
55 std::atomic_bool ThermalService::isBootCompleted_ = false;
56 std::string ThermalService::scene_;
57 #ifdef HAS_THERMAL_AIRPLANE_MANAGER_PART
58 bool ThermalService::userAirplaneState_ = false;
59 bool ThermalService::isThermalAirplane_ = false;
60 #endif
ThermalService()61 ThermalService::ThermalService() : SystemAbility(POWER_MANAGER_THERMAL_SERVICE_ID, true) {}
62 
~ThermalService()63 ThermalService::~ThermalService() {}
64 
GetInstance()65 sptr<ThermalService> ThermalService::GetInstance()
66 {
67     if (instance_ == nullptr) {
68         std::lock_guard<std::mutex> lock(singletonMutex_);
69         if (instance_ == nullptr) {
70             instance_ = new ThermalService();
71         }
72     }
73     return instance_;
74 }
75 
OnStart()76 void ThermalService::OnStart()
77 {
78     THERMAL_HILOGD(COMP_SVC, "Enter");
79     if (ready_) {
80         THERMAL_HILOGE(COMP_SVC, "OnStart is ready, nothing to do");
81         return;
82     }
83 
84     if (!(Init())) {
85         THERMAL_HILOGE(COMP_SVC, "OnStart call init fail");
86         return;
87     }
88 
89     AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID);
90     AddSystemAbilityListener(SOC_PERF_SERVICE_SA_ID);
91     AddSystemAbilityListener(POWER_MANAGER_BATT_SERVICE_ID);
92     if (!Publish(ThermalService::GetInstance())) {
93         THERMAL_HILOGE(COMP_SVC, "OnStart register to system ability manager failed.");
94         return;
95     }
96     RegisterBootCompletedCallback();
97     ready_ = true;
98     THERMAL_HILOGD(COMP_SVC, "OnStart and add system ability success");
99 }
100 
RegisterBootCompletedCallback()101 void ThermalService::RegisterBootCompletedCallback()
102 {
103     g_bootCompletedCallback = []() {
104         isBootCompleted_ = true;
105     };
106     SysParam::RegisterBootCompletedCallback(g_bootCompletedCallback);
107 }
108 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)109 void ThermalService::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
110 {
111     THERMAL_HILOGI(COMP_SVC, "systemAbilityId=%{public}d, deviceId=%{private}s", systemAbilityId, deviceId.c_str());
112     if (systemAbilityId == COMMON_EVENT_SERVICE_ID) {
113         InitStateMachine();
114 #ifdef HAS_THERMAL_AIRPLANE_MANAGER_PART
115         SubscribeCommonEvent();
116 #endif
117     } else if (systemAbilityId == SOC_PERF_SERVICE_SA_ID) {
118         ThermalActionManager::ThermalActionMap actionMap = GetActionManagerObj()->GetActionMap();
119         std::lock_guard<std::mutex> lock(mutex_);
120         for (auto& iter : SocActionBase::SocSet) {
121             auto actionIter = actionMap.find(iter);
122             if (actionIter == actionMap.end() || actionIter->second == nullptr) {
123                 THERMAL_HILOGE(COMP_SVC, "can't find action [%{public}s] ability", iter.c_str());
124                 continue;
125             }
126             actionIter->second->ResetActionValue();
127         }
128     } else if (systemAbilityId == POWER_MANAGER_BATT_SERVICE_ID) {
129 #ifdef BATTERY_MANAGER_ENABLE
130         auto csc = ChargerStateCollection::GetInstance();
131         if (csc == nullptr) {
132             THERMAL_HILOGE(COMP_SVC, "ChargerStateCollection GetInstance failed");
133             return;
134         }
135         csc->InitChargeState();
136 #endif
137     }
138 }
139 
140 #ifdef HAS_THERMAL_AIRPLANE_MANAGER_PART
SubscribeCommonEvent()141 bool ThermalService::SubscribeCommonEvent()
142 {
143     using namespace OHOS::EventFwk;
144     bool result = false;
145     MatchingSkills matchingSkills;
146     matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_AIRPLANE_MODE_CHANGED);
147     CommonEventSubscribeInfo subscribeInfo(matchingSkills);
148     subscribeInfo.SetThreadMode(CommonEventSubscribeInfo::ThreadMode::COMMON);
149     if (!subscriberPtr_) {
150         subscriberPtr_ = std::make_shared<AirplaneCommonEventSubscriber>(subscribeInfo);
151     }
152     result = CommonEventManager::SubscribeCommonEvent(subscriberPtr_);
153     if (!result) {
154         THERMAL_HILOGE(COMP_SVC, "Subscribe CommonEvent failed");
155     } else {
156         THERMAL_HILOGD(COMP_SVC, "Subscribe CommonEvent success");
157     }
158     return result;
159 }
160 
OnReceiveEvent(const OHOS::EventFwk::CommonEventData & data)161 void AirplaneCommonEventSubscriber::OnReceiveEvent(const OHOS::EventFwk::CommonEventData &data)
162 {
163     if (!ThermalService::isThermalAirplane_) {
164         int32_t code = data.GetCode();
165         ThermalService::userAirplaneState_ = static_cast<bool>(code);
166         THERMAL_HILOGD(COMP_SVC, "user %{public}s Airplane mode",
167             ThermalService::userAirplaneState_ ? "open" : "close");
168     } else {
169         ThermalService::isThermalAirplane_ = false;
170         THERMAL_HILOGD(COMP_SVC, "thermal change Airplane mode");
171     }
172 }
173 #endif
174 
Init()175 bool ThermalService::Init()
176 {
177     THERMAL_HILOGD(COMP_SVC, "Enter");
178     if (!CreateConfigModule()) {
179         return false;
180     }
181     if (!InitModules()) {
182         return false;
183     }
184     RegisterHdiStatusListener();
185     THERMAL_HILOGD(COMP_SVC, "Init success");
186     return true;
187 }
188 
CreateConfigModule()189 bool ThermalService::CreateConfigModule()
190 {
191     if (!baseInfo_) {
192         baseInfo_ = std::make_shared<ThermalConfigBaseInfo>();
193         if (baseInfo_ == nullptr) {
194             THERMAL_HILOGE(COMP_SVC, "failed to create base info");
195             return false;
196         }
197     }
198 
199     if (!state_) {
200         state_ = std::make_shared<StateMachine>();
201         if (state_ == nullptr) {
202             THERMAL_HILOGE(COMP_SVC, "failed to create state machine");
203             return false;
204         }
205     }
206 
207     if (!actionMgr_) {
208         actionMgr_ = std::make_shared<ThermalActionManager>();
209         if (actionMgr_ == nullptr) {
210             THERMAL_HILOGE(COMP_SVC, "failed to create action manager");
211             return false;
212         }
213     }
214 
215     if (!policy_) {
216         policy_ = std::make_shared<ThermalPolicy>();
217         if (policy_ == nullptr) {
218             THERMAL_HILOGE(COMP_SVC, "failed to create thermal policy");
219             return false;
220         }
221     }
222 
223     if (!fanFaultDetect_) {
224         fanFaultDetect_ = std::make_shared<FanFaultDetect>();
225         if (fanFaultDetect_ == nullptr) {
226             THERMAL_HILOGE(COMP_SVC, "failed to create fan fault detect");
227             return false;
228         }
229     }
230 
231     return true;
232 }
233 
InitConfigFile()234 bool ThermalService::InitConfigFile()
235 {
236     if (serviceConfigParsed) {
237         THERMAL_HILOGI(COMP_SVC, "system config file has parsed.");
238         return true;
239     }
240     char buf[MAX_PATH_LEN];
241     char* path = GetOneCfgFile(THERMAL_SERVICE_CONFIG_PATH.c_str(), buf, MAX_PATH_LEN);
242     if (path != nullptr && *path != '\0') {
243         if (configParser_.ThermalSrvConfigInit(path)) {
244             THERMAL_HILOGD(COMP_SVC, "match pliocy config file");
245             return true;
246         }
247         THERMAL_HILOGE(COMP_SVC, "policy config file config init err");
248         return false;
249     }
250 
251     if (configParser_.ThermalSrvConfigInit(VENDOR_THERMAL_SERVICE_CONFIG_PATH)) {
252         THERMAL_HILOGD(COMP_SVC, "thermal service config init suc:VENDOR_CONFIG");
253         return true;
254     }
255 
256     if (configParser_.ThermalSrvConfigInit(SYSTEM_THERMAL_SERVICE_CONFIG_PATH)) {
257         THERMAL_HILOGD(COMP_SVC, "thermal service config init suc:SYSTEM_CONFIG");
258         return true;
259     }
260     THERMAL_HILOGE(COMP_SVC, "policy config file config init fail");
261 
262     return false;
263 }
264 
265 
InitConfigModule()266 bool ThermalService::InitConfigModule()
267 {
268     THERMAL_HILOGD(COMP_SVC, "InitVendor Enter");
269     if (!CreateConfigModule()) {
270         THERMAL_HILOGD(COMP_SVC, "CreateConfigModule fail");
271     }
272 
273     if (!configParser_.ThermalSrvConfigInit(SYSTEM_THERMAL_SERVICE_CONFIG_PATH)) {
274         THERMAL_HILOGE(COMP_SVC, "system thermal service config init failed.");
275         return false;
276     }
277     serviceConfigParsed = true;
278 
279     THERMAL_HILOGE(COMP_SVC, "system thermal service config init suc.");
280     return true;
281 }
282 
InitModules()283 bool ThermalService::InitModules()
284 {
285     if (!InitConfigFile()) {
286         return false;
287     }
288 
289     if (popup_ == nullptr) {
290         popup_ = std::make_shared<ActionPopup>(POPUP_ACTION_NAME);
291     }
292 
293     if (!InitThermalObserver()) {
294         THERMAL_HILOGE(COMP_SVC, "thermal observer start fail");
295         return false;
296     }
297 
298     if (!InitActionManager()) {
299         THERMAL_HILOGE(COMP_SVC, "action manager init fail");
300         return false;
301     }
302 
303     if (!InitThermalPolicy()) {
304         THERMAL_HILOGE(COMP_SVC, "thermal policy start fail");
305         return false;
306     }
307 
308     if (!InitThermalSubscriber()) {
309         THERMAL_HILOGE(COMP_SVC, "thermal subscriber init fail");
310         return false;
311     }
312     return true;
313 }
314 
InitThermalObserver()315 bool ThermalService::InitThermalObserver()
316 {
317     if (!InitBaseInfo()) {
318         return false;
319     }
320 
321     THERMAL_HILOGD(COMP_SVC, "Enter");
322     if (observer_ == nullptr) {
323         observer_ = std::make_shared<ThermalObserver>();
324         if (!(observer_->Init())) {
325             THERMAL_HILOGE(COMP_SVC, "InitThermalObserver: thermal observer start fail");
326             return false;
327         }
328     }
329     if (info_ == nullptr) {
330         info_ = std::make_shared<ThermalSensorInfo>();
331     }
332     THERMAL_HILOGI(COMP_SVC, "InitThermalObserver: Init Success");
333     return true;
334 }
335 
InitBaseInfo()336 bool ThermalService::InitBaseInfo()
337 {
338     THERMAL_HILOGD(COMP_SVC, "Enter");
339     if (!baseInfo_->Init()) {
340         THERMAL_HILOGE(COMP_SVC, "InitBaseInfo: base info init failed");
341         return false;
342     }
343     return true;
344 }
345 
InitStateMachine()346 bool ThermalService::InitStateMachine()
347 {
348     THERMAL_HILOGD(COMP_SVC, "Enter");
349     if (!state_->Init()) {
350         THERMAL_HILOGE(COMP_SVC, "InitStateMachine: state machine init failed");
351         return false;
352     }
353     return true;
354 }
355 
InitActionManager()356 bool ThermalService::InitActionManager()
357 {
358     THERMAL_HILOGD(COMP_SVC, "Enter");
359     if (!actionMgr_->Init()) {
360         THERMAL_HILOGE(COMP_SVC, "InitActionManager: action manager init failed");
361         return false;
362     }
363     return true;
364 }
365 
InitThermalPolicy()366 bool ThermalService::InitThermalPolicy()
367 {
368     THERMAL_HILOGD(COMP_SVC, "Enter");
369     if (!policy_->Init()) {
370         THERMAL_HILOGE(COMP_SVC, "InitThermalPolicy: policy init failed");
371         return false;
372     }
373     return true;
374 }
375 
InitThermalSubscriber()376 bool ThermalService::InitThermalSubscriber()
377 {
378     if (serviceSubscriber_ == nullptr) {
379         serviceSubscriber_ = std::make_shared<ThermalServiceSubscriber>();
380         if (!(serviceSubscriber_->Init())) {
381             THERMAL_HILOGE(COMP_SVC, "InitThermalSubscriber: thermal subscriber init failed");
382             return false;
383         }
384     }
385     return true;
386 }
387 
OnStop()388 void ThermalService::OnStop()
389 {
390     THERMAL_HILOGD(COMP_SVC, "Enter");
391     if (!ready_) {
392         return;
393     }
394     ready_ = false;
395     isBootCompleted_ = false;
396     RemoveSystemAbilityListener(COMMON_EVENT_SERVICE_ID);
397     if (thermalInterface_) {
398         thermalInterface_->Unregister();
399         thermalInterface_->UnregisterFanCallback();
400         thermalInterface_ = nullptr;
401     }
402     if (hdiServiceMgr_) {
403         hdiServiceMgr_->UnregisterServiceStatusListener(hdiServStatListener_);
404         hdiServiceMgr_ = nullptr;
405     }
406 #ifdef HAS_THERMAL_AIRPLANE_MANAGER_PART
407     if (!OHOS::EventFwk::CommonEventManager::UnSubscribeCommonEvent(subscriberPtr_)) {
408         THERMAL_HILOGE(COMP_SVC, "Thermal Onstop unregister to commonevent manager failed!");
409     } else {
410         THERMAL_HILOGD(COMP_SVC, "Thermal Onstop unregister to commonevent manager success!");
411     }
412 #endif
413 }
414 
SubscribeThermalTempCallback(const std::vector<std::string> & typeList,const sptr<IThermalTempCallback> & callback)415 bool ThermalService::SubscribeThermalTempCallback(
416     const std::vector<std::string>& typeList, const sptr<IThermalTempCallback>& callback)
417 {
418     if (!Permission::IsSystem()) {
419         return false;
420     }
421     auto uid = IPCSkeleton::GetCallingUid();
422     THERMAL_HILOGI(COMP_SVC, "%{public}s is called by uid=%{public}d", __func__, uid);
423     observer_->SubscribeThermalTempCallback(typeList, callback);
424     return true;
425 }
426 
UnSubscribeThermalTempCallback(const sptr<IThermalTempCallback> & callback)427 bool ThermalService::UnSubscribeThermalTempCallback(const sptr<IThermalTempCallback>& callback)
428 {
429     if (!Permission::IsSystem()) {
430         return false;
431     }
432     auto uid = IPCSkeleton::GetCallingUid();
433     THERMAL_HILOGI(COMP_SVC, "%{public}s is called by uid=%{public}d", __func__, uid);
434     observer_->UnSubscribeThermalTempCallback(callback);
435     return true;
436 }
437 
GetThermalSrvSensorInfo(const SensorType & type,ThermalSrvSensorInfo & sensorInfo)438 bool ThermalService::GetThermalSrvSensorInfo(const SensorType& type, ThermalSrvSensorInfo& sensorInfo)
439 {
440     THERMAL_HILOGD(COMP_SVC, "Enter");
441     if (!(observer_->GetThermalSrvSensorInfo(type, sensorInfo))) {
442         THERMAL_HILOGW(COMP_SVC, "failed to get sensor temp, type enum: %{public}u", static_cast<uint32_t>(type));
443         return false;
444     }
445     return true;
446 }
447 
SubscribeThermalLevelCallback(const sptr<IThermalLevelCallback> & callback)448 bool ThermalService::SubscribeThermalLevelCallback(const sptr<IThermalLevelCallback>& callback)
449 {
450     auto uid = IPCSkeleton::GetCallingUid();
451     THERMAL_HILOGI(COMP_SVC, "%{public}s is called by uid=%{public}d", __func__, uid);
452     actionMgr_->SubscribeThermalLevelCallback(callback);
453     return true;
454 }
455 
UnSubscribeThermalLevelCallback(const sptr<IThermalLevelCallback> & callback)456 bool ThermalService::UnSubscribeThermalLevelCallback(const sptr<IThermalLevelCallback>& callback)
457 {
458     auto uid = IPCSkeleton::GetCallingUid();
459     THERMAL_HILOGI(COMP_SVC, "%{public}s is called by uid=%{public}d", __func__, uid);
460     actionMgr_->UnSubscribeThermalLevelCallback(callback);
461     return true;
462 }
463 
SubscribeThermalActionCallback(const std::vector<std::string> & actionList,const std::string & desc,const sptr<IThermalActionCallback> & callback)464 bool ThermalService::SubscribeThermalActionCallback(
465     const std::vector<std::string>& actionList, const std::string& desc, const sptr<IThermalActionCallback>& callback)
466 {
467     if (!Permission::IsSystem()) {
468         return false;
469     }
470     auto pid = IPCSkeleton::GetCallingPid();
471     auto uid = IPCSkeleton::GetCallingUid();
472     THERMAL_HILOGI(COMP_SVC, "%{public}s is called by pid=%{public}d, uid=%{public}d", __func__, pid, uid);
473     observer_->SubscribeThermalActionCallback(actionList, desc, callback);
474     return true;
475 }
476 
UnSubscribeThermalActionCallback(const sptr<IThermalActionCallback> & callback)477 bool ThermalService::UnSubscribeThermalActionCallback(const sptr<IThermalActionCallback>& callback)
478 {
479     if (!Permission::IsSystem()) {
480         return false;
481     }
482     auto pid = IPCSkeleton::GetCallingPid();
483     auto uid = IPCSkeleton::GetCallingUid();
484     THERMAL_HILOGI(COMP_SVC, "%{public}s is called by pid=%{public}d, uid=%{public}d", __func__, pid, uid);
485     observer_->UnSubscribeThermalActionCallback(callback);
486     return true;
487 }
488 
GetThermalLevel(ThermalLevel & level)489 bool ThermalService::GetThermalLevel(ThermalLevel& level)
490 {
491     uint32_t levelValue = actionMgr_->GetThermalLevel();
492     level = static_cast<ThermalLevel>(levelValue);
493     return true;
494 }
495 
GetThermalInfo()496 bool ThermalService::GetThermalInfo()
497 {
498     THERMAL_HILOGD(COMP_SVC, "Enter");
499     HdfThermalCallbackInfo thermalInfo;
500     bool ret = false;
501     if (thermalInterface_ == nullptr) {
502         thermalInterface_ = IThermalInterface::Get();
503         if (thermalInterface_ == nullptr) {
504             THERMAL_HILOGD(COMP_SVC, "thermalInterface_ is nullptr");
505             return ret;
506         }
507     }
508 
509     if (thermalInterface_ != nullptr) {
510         int32_t res = thermalInterface_->GetThermalZoneInfo(thermalInfo);
511         HandleThermalCallbackEvent(thermalInfo);
512         if (!res) {
513             ret = true;
514         }
515     }
516     return ret;
517 }
518 
SetScene(const std::string & scene)519 bool ThermalService::SetScene(const std::string& scene)
520 {
521     if (!Permission::IsSystem()) {
522         return false;
523     }
524     scene_ = scene;
525     return true;
526 }
527 
UpdateThermalState(const std::string & tag,const std::string & val,bool isImmed)528 bool ThermalService::UpdateThermalState(const std::string& tag, const std::string& val, bool isImmed)
529 {
530     if (!Permission::IsSystem()) {
531         return false;
532     }
533     THERMAL_HILOGI(COMP_SVC, "tag %{public}s, val %{public}s, isImmed %{public}d",
534         tag.c_str(), val.c_str(), isImmed);
535     std::lock_guard<std::mutex> lock(mutex_);
536     state_->UpdateState(tag, val);
537     if (isImmed) {
538         policy_->ExecutePolicy();
539     }
540     return true;
541 }
542 
RegisterHdiStatusListener()543 void ThermalService::RegisterHdiStatusListener()
544 {
545     THERMAL_HILOGD(COMP_SVC, "Enter");
546     hdiServiceMgr_ = IServiceManager::Get();
547     if (hdiServiceMgr_ == nullptr) {
548         FFRTTask retryTask = [this] {
549             return RegisterHdiStatusListener();
550         };
551         FFRTUtils::SubmitDelayTask(retryTask, RETRY_TIME, g_queue);
552         THERMAL_HILOGW(COMP_SVC, "hdi service manager is nullptr, try again after %{public}u ms", RETRY_TIME);
553         return;
554     }
555 
556     hdiServStatListener_ = new HdiServiceStatusListener(
557         HdiServiceStatusListener::StatusCallback([&](const OHOS::HDI::ServiceManager::V1_0::ServiceStatus& status) {
558             THERMAL_RETURN_IF(status.serviceName != HDI_SERVICE_NAME || status.deviceClass != DEVICE_CLASS_DEFAULT)
559 
560             if (status.status == SERVIE_STATUS_START) {
561                 FFRTTask task = [this] {
562                     RegisterThermalHdiCallback();
563                     RegisterFanHdiCallback();
564                 };
565                 FFRTUtils::SubmitTask(task);
566                 THERMAL_HILOGD(COMP_SVC, "thermal interface service start");
567             } else if (status.status == SERVIE_STATUS_STOP && thermalInterface_) {
568                 thermalInterface_->Unregister();
569                 thermalInterface_->UnregisterFanCallback();
570                 thermalInterface_ = nullptr;
571                 THERMAL_HILOGW(COMP_SVC, "thermal interface service, unregister interface");
572             }
573         }));
574 
575     int32_t status = hdiServiceMgr_->RegisterServiceStatusListener(hdiServStatListener_, DEVICE_CLASS_DEFAULT);
576     if (status != ERR_OK) {
577         THERMAL_HILOGW(COMP_SVC, "Register hdi failed, try again after %{public}u ms", RETRY_TIME);
578         FFRTTask retryTask = [this] {
579             return RegisterHdiStatusListener();
580         };
581         FFRTUtils::SubmitDelayTask(retryTask, RETRY_TIME, g_queue);
582     }
583 }
584 
RegisterThermalHdiCallback()585 void ThermalService::RegisterThermalHdiCallback()
586 {
587     THERMAL_HILOGD(COMP_SVC, "register thermal hdi callback");
588     if (thermalInterface_ == nullptr) {
589         thermalInterface_ = IThermalInterface::Get();
590         THERMAL_RETURN_IF_WITH_LOG(thermalInterface_ == nullptr, "failed to get thermal hdi interface");
591     }
592 
593     sptr<IThermalCallback> callback = new ThermalCallback();
594     ThermalCallback::ThermalEventCallback eventCb =
595         [this](const HdfThermalCallbackInfo& event) -> int32_t { return this->HandleThermalCallbackEvent(event); };
596     ThermalCallback::RegisterThermalEvent(eventCb);
597     int32_t ret = thermalInterface_->Register(callback);
598     THERMAL_HILOGI(COMP_SVC, "register thermal hdi callback end, ret: %{public}d", ret);
599 }
600 
UnRegisterThermalHdiCallback()601 void ThermalService::UnRegisterThermalHdiCallback()
602 {
603     if (thermalInterface_ == nullptr) {
604         FFRTTask retryTask = [this] {
605             return UnRegisterThermalHdiCallback();
606         };
607         FFRTUtils::SubmitDelayTask(retryTask, RETRY_TIME, g_queue);
608         THERMAL_HILOGW(COMP_SVC, "thermalInterface_ is nullptr, try again after %{public}u ms", RETRY_TIME);
609         return;
610     }
611     int32_t ret = thermalInterface_->Unregister();
612     THERMAL_HILOGI(COMP_SVC, "unregister thermal hdi callback end, ret: %{public}d", ret);
613 }
614 
HandleThermalCallbackEvent(const HdfThermalCallbackInfo & event)615 int32_t ThermalService::HandleThermalCallbackEvent(const HdfThermalCallbackInfo& event)
616 {
617 #ifndef THERMAL_USER_VERSION
618     if (!isTempReport_) {
619         return ERR_OK;
620     }
621 #endif
622     TypeTempMap typeTempMap;
623     if (!event.info.empty()) {
624         for (auto iter = event.info.begin(); iter != event.info.end(); iter++) {
625             typeTempMap.insert(std::make_pair(iter->type, iter->temp));
626         }
627     }
628     std::lock_guard<std::mutex> lock(mutex_);
629     serviceSubscriber_->OnTemperatureChanged(typeTempMap);
630     return ERR_OK;
631 }
632 
HandleTempEmulation(const TypeTempMap & typeTempMap)633 bool ThermalService::HandleTempEmulation(const TypeTempMap& typeTempMap)
634 {
635     if (isTempReport_) {
636         return false;
637     }
638     std::lock_guard<std::mutex> lock(mutex_);
639     serviceSubscriber_->OnTemperatureChanged(typeTempMap);
640     return true;
641 }
642 
RegisterFanHdiCallback()643 void ThermalService::RegisterFanHdiCallback()
644 {
645     if (!fanFaultDetect_->HasFanConfig()) {
646         return;
647     }
648 
649     if (thermalInterface_ == nullptr) {
650         thermalInterface_ = IThermalInterface::Get();
651         THERMAL_RETURN_IF_WITH_LOG(thermalInterface_ == nullptr, "failed to get thermal hdi interface");
652     }
653 
654     sptr<IFanCallback> callback = new FanCallback();
655     FanCallback::FanEventCallback eventCb =
656         [this](const HdfThermalCallbackInfo& event) -> int32_t { return this->HandleFanCallbackEvent(event); };
657     FanCallback::RegisterFanEvent(eventCb);
658     int32_t ret = thermalInterface_->RegisterFanCallback(callback);
659     THERMAL_HILOGI(COMP_SVC, "register fan hdi callback end, ret: %{public}d", ret);
660 
661     return;
662 }
663 
HandleFanCallbackEvent(const HdfThermalCallbackInfo & event)664 int32_t ThermalService::HandleFanCallbackEvent(const HdfThermalCallbackInfo& event)
665 {
666     FanSensorInfo report;
667     if (!event.info.empty()) {
668         for (auto iter = event.info.begin(); iter != event.info.end(); iter++) {
669             report.insert(std::make_pair(iter->type, iter->temp));
670         }
671     }
672 
673     fanFaultDetect_->OnFanSensorInfoChanged(report);
674     return ERR_OK;
675 }
676 
ShellDump(const std::vector<std::string> & args,uint32_t argc)677 std::string ThermalService::ShellDump(const std::vector<std::string>& args, uint32_t argc)
678 {
679     if (!Permission::IsSystem() || !isBootCompleted_) {
680         return "";
681     }
682     std::lock_guard<std::mutex> lock(mutex_);
683     pid_t pid = IPCSkeleton::GetCallingPid();
684     THERMAL_HILOGI(COMP_SVC, "PID: %{public}d", pid);
685     std::string result;
686     bool ret = ThermalMgrDumper::Dump(args, result);
687     THERMAL_HILOGI(COMP_SVC, "ThermalMgrDumper :%{public}d", ret);
688     return result;
689 }
690 
Dump(int fd,const std::vector<std::u16string> & args)691 int32_t ThermalService::Dump(int fd, const std::vector<std::u16string>& args)
692 {
693     if (!isBootCompleted_) {
694         return ERR_NO_INIT;
695     }
696     if (!Permission::IsSystem()) {
697         return ERR_PERMISSION_DENIED;
698     }
699     std::vector<std::string> argsInStr;
700     std::transform(args.begin(), args.end(), std::back_inserter(argsInStr), [](const std::u16string& arg) {
701         std::string ret = Str16ToStr8(arg);
702         THERMAL_HILOGI(COMP_SVC, "arg: %{public}s", ret.c_str());
703         return ret;
704     });
705     std::string result;
706     ThermalMgrDumper::Dump(argsInStr, result);
707     if (!SaveStringToFd(fd, result)) {
708         THERMAL_HILOGE(COMP_SVC, "ThermalService::Dump failed, save to fd failed.");
709         THERMAL_HILOGE(COMP_SVC, "Dump Info:\n");
710         THERMAL_HILOGE(COMP_SVC, "%{public}s", result.c_str());
711         return ERR_OK;
712     }
713     return ERR_OK;
714 }
715 
EnableMock(const std::string & actionName,void * mockObject)716 void ThermalService::EnableMock(const std::string& actionName, void* mockObject)
717 {
718     std::lock_guard<std::mutex> lock(mutex_);
719     actionMgr_->EnableMock(actionName, mockObject);
720 }
721 
DestroyInstance()722 void ThermalService::DestroyInstance()
723 {
724     std::lock_guard<std::mutex> lock(singletonMutex_);
725     if (instance_) {
726         instance_.clear();
727         instance_ = nullptr;
728     }
729 }
730 } // namespace PowerMgr
731 } // namespace OHOS
732