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