• 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 "display_power_mgr_service.h"
17 
18 #include <hisysevent.h>
19 #include <file_ex.h>
20 #include <securec.h>
21 #include <system_ability_definition.h>
22 #include "errors.h"
23 #include "new"
24 #include "screen_action.h"
25 #ifdef ENABLE_SENSOR_PART
26 #include "sensor_agent.h"
27 #endif
28 #include "xcollie/watchdog.h"
29 #include "display_log.h"
30 #include "display_auto_brightness.h"
31 #include "display_setting_helper.h"
32 #include "display_param_helper.h"
33 #include "permission.h"
34 #include "setting_provider.h"
35 #include "ffrt_utils.h"
36 
37 namespace OHOS {
38 namespace DisplayPowerMgr {
39 using namespace OHOS::PowerMgr;
40 namespace {
41 DisplayParamHelper::BootCompletedCallback g_bootCompletedCallback;
42 FFRTHandle g_screenOffDelayTaskHandle;
43 const uint32_t GET_DISPLAY_ID_DELAY_MS = 50;
44 const uint32_t US_PER_MS = 1000;
45 const uint32_t GET_DISPLAY_ID_RETRY_COUNT = 3;
46 const uint32_t DEFALUT_DISPLAY_ID = 0;
47 const uint32_t TEST_MODE = 1;
48 const uint32_t NORMAL_MODE = 2;
49 const uint32_t DEFAULT_DIMMING_TIME = 500;
50 const uint32_t BOOTED_COMPLETE_DELAY_TIME = 2000;
51 }
52 
53 const uint32_t DisplayPowerMgrService::BRIGHTNESS_MIN = DisplayParamHelper::GetMinBrightness();
54 const uint32_t DisplayPowerMgrService::BRIGHTNESS_DEFAULT = DisplayParamHelper::GetDefaultBrightness();
55 const uint32_t DisplayPowerMgrService::BRIGHTNESS_MAX = DisplayParamHelper::GetMaxBrightness();
56 std::atomic_bool DisplayPowerMgrService::isBootCompleted_ = false;
57 DisplayPowerMgrService::DisplayPowerMgrService() = default;
58 
Init()59 void DisplayPowerMgrService::Init()
60 {
61     queue_ = std::make_shared<FFRTQueue> ("display_power_mgr_service");
62     DISPLAY_HILOGI(COMP_SVC, "DisplayPowerMgrService Create");
63     std::vector<uint32_t> displayIds;
64     for (uint32_t tryCount = 0; tryCount <= GET_DISPLAY_ID_RETRY_COUNT; tryCount++) {
65         displayIds = ScreenAction::GetAllDisplayId();
66         if (!displayIds.empty()) {
67             break;
68         }
69         if (tryCount < GET_DISPLAY_ID_RETRY_COUNT) {
70             usleep(GET_DISPLAY_ID_DELAY_MS * US_PER_MS);
71             DISPLAY_HILOGI(COMP_SVC, "cannot find any display id, retry! count: %{public}u", tryCount + 1);
72         } else {
73             displayIds.emplace_back(DEFALUT_DISPLAY_ID);
74             DISPLAY_HILOGE(COMP_SVC, "cannot find any display id after max retry, fill with 0");
75         }
76     }
77     BrightnessManager::Get().Init(BRIGHTNESS_MAX, BRIGHTNESS_MIN);
78     for (const auto& id: displayIds) {
79         DISPLAY_HILOGI(COMP_SVC, "find display, id=%{public}u", id);
80         controllerMap_.emplace(id, std::make_shared<ScreenController>(id));
81         BrightnessManager::Get().SetDisplayId(id);
82     }
83 
84     callback_ = nullptr;
85     cbDeathRecipient_ = nullptr;
86 #ifdef ENABLE_SENSOR_PART
87     InitSensors();
88 #endif
89     FFRTTask task = [this]() {
90         DISPLAY_HILOGI(COMP_SVC, "Boot completed delayed");
91         SetBootCompletedBrightness();
92         SetBootCompletedAutoBrightness();
93         RegisterSettingObservers();
94     };
95     g_screenOffDelayTaskHandle = FFRTUtils::SubmitDelayTask(task, BOOTED_COMPLETE_DELAY_TIME, queue_);
96     RegisterBootCompletedCallback();
97 }
RegisterBootCompletedCallback()98 void DisplayPowerMgrService::RegisterBootCompletedCallback()
99 {
100     g_bootCompletedCallback = []() {
101         isBootCompleted_ = true;
102     };
103     DisplayParamHelper::RegisterBootCompletedCallback(g_bootCompletedCallback);
104 }
105 
Deinit()106 void DisplayPowerMgrService::Deinit()
107 {
108     UnregisterSettingObservers();
109     BrightnessManager::Get().DeInit();
110     isBootCompleted_ = false;
111 }
112 
Reset()113 void DisplayPowerMgrService::Reset()
114 {
115     DISPLAY_HILOGI(FEAT_BRIGHTNESS, "reset begin");
116     if (queue_) {
117         queue_.reset();
118         g_screenOffDelayTaskHandle = nullptr;
119         DISPLAY_HILOGI(FEAT_BRIGHTNESS, "destruct display_power_queue");
120     }
121     DISPLAY_HILOGI(FEAT_BRIGHTNESS, "reset end");
122 }
123 
SetBootCompletedBrightness()124 void DisplayPowerMgrService::SetBootCompletedBrightness()
125 {
126     uint32_t mainDisplayId = DelayedSpSingleton<DisplayPowerMgrService>::GetInstance()->GetMainDisplayId();
127     uint32_t brightness = DelayedSpSingleton<DisplayPowerMgrService>::GetInstance()->GetBrightness(mainDisplayId);
128     uint32_t currentDisplayId = BrightnessManager::Get().GetCurrentDisplayId(mainDisplayId);
129     DisplayState state = DelayedSpSingleton<DisplayPowerMgrService>::GetInstance()->GetDisplayState(mainDisplayId);
130     BrightnessManager::Get().SetDisplayId(currentDisplayId);
131     BrightnessManager::Get().SetDisplayState(currentDisplayId, state);
132     DelayedSpSingleton<DisplayPowerMgrService>::GetInstance()->SetBrightness(brightness, mainDisplayId);
133     DISPLAY_HILOGI(FEAT_BRIGHTNESS, "SetBootCompletedBrightness currentDisplayId=%{public}d", currentDisplayId);
134 }
135 
SetBootCompletedAutoBrightness()136 void DisplayPowerMgrService::SetBootCompletedAutoBrightness()
137 {
138     bool enable = GetSettingAutoBrightness();
139     DISPLAY_HILOGI(FEAT_BRIGHTNESS, "SetBootCompletedAutoBrightness enable=%{public}d", enable);
140     DelayedSpSingleton<DisplayPowerMgrService>::GetInstance()->AutoAdjustBrightness(enable);
141     BrightnessManager::Get().AutoAdjustBrightness(enable);
142 }
143 
RegisterSettingObservers()144 void DisplayPowerMgrService::RegisterSettingObservers()
145 {
146     uint32_t mainDisplayId = DelayedSpSingleton<DisplayPowerMgrService>::GetInstance()->GetMainDisplayId();
147     auto controllerMap = DelayedSpSingleton<DisplayPowerMgrService>::GetInstance()->controllerMap_;
148     auto iter = controllerMap.find(mainDisplayId);
149     if (iter != controllerMap.end()) {
150         iter->second->RegisterSettingBrightnessObserver();
151     }
152     RegisterSettingAutoBrightnessObserver();
153 }
154 
UnregisterSettingObservers()155 void DisplayPowerMgrService::UnregisterSettingObservers()
156 {
157     uint32_t mainDisplayId = DelayedSpSingleton<DisplayPowerMgrService>::GetInstance()->GetMainDisplayId();
158     auto controllerMap = DelayedSpSingleton<DisplayPowerMgrService>::GetInstance()->controllerMap_;
159     auto iter = controllerMap.find(mainDisplayId);
160     if (iter != controllerMap.end()) {
161         iter->second->UnregisterSettingBrightnessObserver();
162     }
163     UnregisterSettingAutoBrightnessObserver();
164 }
165 
RegisterSettingAutoBrightnessObserver()166 void DisplayPowerMgrService::RegisterSettingAutoBrightnessObserver()
167 {
168     SettingObserver::UpdateFunc updateFunc = [&](const std::string& key) { AutoBrightnessSettingUpdateFunc(key); };
169     DisplaySettingHelper::RegisterSettingAutoBrightnessObserver(updateFunc);
170 }
171 
AutoBrightnessSettingUpdateFunc(const std::string & key)172 void DisplayPowerMgrService::AutoBrightnessSettingUpdateFunc(const std::string& key)
173 {
174     bool isSettingEnable = GetSettingAutoBrightness(key);
175     bool isSystemEnable = DelayedSpSingleton<DisplayPowerMgrService>::GetInstance()->IsAutoAdjustBrightness();
176     if (isSettingEnable == isSystemEnable) {
177         DISPLAY_HILOGI(FEAT_BRIGHTNESS, "no need change autoAdjustSwitch");
178         return;
179     }
180     DISPLAY_HILOGI(FEAT_BRIGHTNESS, "AutoBrightnessSettingUpdateFunc isSettingEnable=%{public}d", isSettingEnable);
181     BrightnessManager::Get().AutoAdjustBrightness(isSettingEnable);
182     DelayedSpSingleton<DisplayPowerMgrService>::GetInstance()->AutoAdjustBrightness(isSettingEnable);
183     if (!isSettingEnable) {
184         DelayedSpSingleton<DisplayPowerMgrService>::GetInstance()->ClearOffset();
185     }
186 }
187 
SetScreenOnBrightness()188 void DisplayPowerMgrService::SetScreenOnBrightness()
189 {
190     BrightnessManager::Get().SetScreenOnBrightness();
191 }
192 
ClearOffset()193 void DisplayPowerMgrService::ClearOffset()
194 {
195     BrightnessManager::Get().ClearOffset();
196 }
197 
SetSettingAutoBrightness(bool enable)198 void DisplayPowerMgrService::SetSettingAutoBrightness(bool enable)
199 {
200     DisplaySettingHelper::SetSettingAutoBrightness(enable);
201 }
202 
GetSettingAutoBrightness(const std::string & key)203 bool DisplayPowerMgrService::GetSettingAutoBrightness(const std::string& key)
204 {
205     return DisplaySettingHelper::GetSettingAutoBrightness(key);
206 }
ScreenOffDelay(uint32_t id,DisplayState state,uint32_t reason)207 void DisplayPowerMgrService::ScreenOffDelay(uint32_t id, DisplayState state, uint32_t reason)
208 {
209     isDisplayDelayOff_ = false;
210     DISPLAY_HILOGI(COMP_SVC, "ScreenOffDelay %{public}d, %{public}d,  %{public}d", id, state, reason);
211     auto iterator = controllerMap_.find(id);
212     if (iterator == controllerMap_.end()) {
213         return;
214     }
215     setDisplayStateRet_ = iterator->second->UpdateState(state, reason);
216 }
217 
UnregisterSettingAutoBrightnessObserver()218 void DisplayPowerMgrService::UnregisterSettingAutoBrightnessObserver()
219 {
220     DisplaySettingHelper::UnregisterSettingAutoBrightnessObserver();
221 }
222 
SetDisplayState(uint32_t id,DisplayState state,uint32_t reason)223 bool DisplayPowerMgrService::SetDisplayState(uint32_t id, DisplayState state, uint32_t reason)
224 {
225     if (!Permission::IsSystem()) {
226         return false;
227     }
228     DISPLAY_HILOGI(COMP_SVC, "[UL_POWER] SetDisplayState %{public}d, %{public}d, %{public}u", id, state, reason);
229     auto iterator = controllerMap_.find(id);
230     if (iterator == controllerMap_.end()) {
231         if (id != DEFALUT_DISPLAY_ID) {
232             return false;
233         }
234         id = GetMainDisplayId();
235         iterator = controllerMap_.find(id);
236         if (iterator == controllerMap_.end()) {
237             return false;
238         }
239     }
240 
241     BrightnessManager::Get().SetDisplayState(id, state);
242 
243     if (state == DisplayState::DISPLAY_OFF) {
244         if (!isDisplayDelayOff_) {
245             DISPLAY_HILOGI(COMP_SVC, "screen off immediately");
246             bool ret = iterator->second->UpdateState(state, reason);
247             if (!ret) {
248                 DISPLAY_HILOGI(COMP_SVC, "[UL_POWER]undo brightness SetDisplayState");
249                 BrightnessManager::Get().SetDisplayState(id, iterator->second->GetState());
250             }
251             return ret;
252         }
253         displayId_ = id;
254         displayState_ = state;
255         displayReason_ = reason;
256         FFRTTask task = [this]() { ScreenOffDelay(displayId_, displayState_, displayReason_); };
257         g_screenOffDelayTaskHandle = FFRTUtils::SubmitDelayTask(task, displayOffDelayMs_, queue_);
258         tempState_ = iterator->second->SetDelayOffState();
259         return true;
260     } else if (state == DisplayState::DISPLAY_ON) {
261         if (isDisplayDelayOff_) {
262             DISPLAY_HILOGI(COMP_SVC, "need remove delay task");
263             FFRTUtils::CancelTask(g_screenOffDelayTaskHandle, queue_);
264             isDisplayDelayOff_ = false;
265             tempState_ = iterator->second->SetOnState();
266             return true;
267         }
268     }
269     return iterator->second->UpdateState(state, reason);
270 }
271 
GetDisplayState(uint32_t id)272 DisplayState DisplayPowerMgrService::GetDisplayState(uint32_t id)
273 {
274     DISPLAY_HILOGD(COMP_SVC, "GetDisplayState %{public}d", id);
275     auto iterator = controllerMap_.find(id);
276     if (iterator == controllerMap_.end()) {
277         if (id != DEFALUT_DISPLAY_ID) {
278             return DisplayState::DISPLAY_UNKNOWN;
279         }
280         id = GetMainDisplayId();
281         iterator = controllerMap_.find(id);
282         if (iterator == controllerMap_.end()) {
283             return DisplayState::DISPLAY_UNKNOWN;
284         }
285     }
286     return iterator->second->GetState();
287 }
288 
GetDisplayIds()289 std::vector<uint32_t> DisplayPowerMgrService::GetDisplayIds()
290 {
291     std::vector<uint32_t> ids;
292     for (auto& iter: controllerMap_) {
293         ids.push_back(iter.first);
294     }
295     return ids;
296 }
297 
GetMainDisplayId()298 uint32_t DisplayPowerMgrService::GetMainDisplayId()
299 {
300     uint32_t id = ScreenAction::GetDefaultDisplayId();
301     DISPLAY_HILOGD(COMP_SVC, "GetMainDisplayId %{public}d", id);
302     return id;
303 }
304 
SetBrightness(uint32_t value,uint32_t displayId,bool continuous)305 bool DisplayPowerMgrService::SetBrightness(uint32_t value, uint32_t displayId, bool continuous)
306 {
307     if (!Permission::IsSystem()) {
308         lastError_ = DisplayErrors::ERR_SYSTEM_API_DENIED;
309         return false;
310     }
311 
312     auto brightness = GetSafeBrightness(value);
313     DISPLAY_HILOGI(FEAT_BRIGHTNESS, "SetBrightness displayId=%{public}u, value=%{public}u, continuous=%{public}d",
314         displayId, brightness, continuous);
315     return BrightnessManager::Get().SetBrightness(brightness, 0, continuous);
316 }
317 
DiscountBrightness(double discount,uint32_t displayId)318 bool DisplayPowerMgrService::DiscountBrightness(double discount, uint32_t displayId)
319 {
320     if (!Permission::IsSystem()) {
321         return false;
322     }
323     auto iter = controllerMap_.find(displayId);
324     if (iter == controllerMap_.end()) {
325         return false;
326     }
327     bool ret = BrightnessManager::Get().DiscountBrightness(discount);
328     if (ret) {
329         return true;
330     }
331     auto brightness = iter->second->GetBrightness();
332     auto safeDiscount = GetSafeDiscount(discount, brightness);
333     DISPLAY_HILOGI(FEAT_BRIGHTNESS, "DiscountBrightness displayId=%{public}u, discount-%{public}lf",
334                    displayId, safeDiscount);
335     HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::DISPLAY, "BACKLIGHT_DISCOUNT",
336         HiviewDFX::HiSysEvent::EventType::STATISTIC, "RATIO", safeDiscount);
337     return iter->second->DiscountBrightness(safeDiscount);
338 }
339 
OverrideBrightness(uint32_t value,uint32_t displayId)340 bool DisplayPowerMgrService::OverrideBrightness(uint32_t value, uint32_t displayId)
341 {
342     if (!Permission::IsSystem()) {
343         return false;
344     }
345     auto brightness = GetSafeBrightness(value);
346     DISPLAY_HILOGI(COMP_SVC, "OverrideBrightness displayId=%{public}u, value=%{public}u, duration=%{public}d",
347         displayId, brightness, DEFAULT_DIMMING_TIME);
348     auto iter = controllerMap_.find(displayId);
349     if (iter == controllerMap_.end()) {
350         return false;
351     }
352     return BrightnessManager::Get().OverrideBrightness(brightness, DEFAULT_DIMMING_TIME);
353 }
354 
OverrideDisplayOffDelay(uint32_t delayMs)355 bool DisplayPowerMgrService::OverrideDisplayOffDelay(uint32_t delayMs)
356 {
357     if (!Permission::IsSystem()) {
358         return false;
359     }
360     if (GetDisplayState(GetMainDisplayId()) != DisplayState::DISPLAY_ON || delayMs == DELAY_TIME_UNSET) {
361         isDisplayDelayOff_ = false;
362         return isDisplayDelayOff_;
363     }
364     DISPLAY_HILOGI(COMP_SVC, "OverrideDisplayOffDelay delayMs=%{public}u", delayMs);
365     isDisplayDelayOff_ = true;
366     displayOffDelayMs_ = delayMs;
367 
368     return isDisplayDelayOff_;
369 }
370 
RestoreBrightness(uint32_t displayId)371 bool DisplayPowerMgrService::RestoreBrightness(uint32_t displayId)
372 {
373     if (!Permission::IsSystem()) {
374         return false;
375     }
376     DISPLAY_HILOGI(COMP_SVC, "RestoreBrightness displayId=%{public}u, duration=%{public}d",
377         displayId, DEFAULT_DIMMING_TIME);
378     auto iter = controllerMap_.find(displayId);
379     if (iter == controllerMap_.end()) {
380         return false;
381     }
382     bool ret = BrightnessManager::Get().RestoreBrightness(DEFAULT_DIMMING_TIME);
383     if (ret) {
384         return true;
385     }
386     return iter->second->RestoreBrightness();
387 }
388 
GetBrightness(uint32_t displayId)389 uint32_t DisplayPowerMgrService::GetBrightness(uint32_t displayId)
390 {
391     DISPLAY_HILOGD(FEAT_BRIGHTNESS, "GetBrightness displayId=%{public}u", displayId);
392     auto iter = controllerMap_.find(displayId);
393     if (iter == controllerMap_.end()) {
394         return BRIGHTNESS_OFF;
395     }
396     return BrightnessManager::Get().GetBrightness();
397 }
398 
GetDefaultBrightness()399 uint32_t DisplayPowerMgrService::GetDefaultBrightness()
400 {
401     return BRIGHTNESS_DEFAULT;
402 }
403 
GetMaxBrightness()404 uint32_t DisplayPowerMgrService::GetMaxBrightness()
405 {
406     return BRIGHTNESS_MAX;
407 }
408 
GetMinBrightness()409 uint32_t DisplayPowerMgrService::GetMinBrightness()
410 {
411     return BRIGHTNESS_MIN;
412 }
413 
AdjustBrightness(uint32_t id,int32_t value,uint32_t duration)414 bool DisplayPowerMgrService::AdjustBrightness(uint32_t id, int32_t value, uint32_t duration)
415 {
416     if (!Permission::IsSystem()) {
417         return false;
418     }
419     DISPLAY_HILOGI(FEAT_BRIGHTNESS, "AdjustBrightness %{public}d, %{public}d, %{public}d",
420                    id, value, duration);
421     auto iterator = controllerMap_.find(id);
422     if (iterator == controllerMap_.end()) {
423         return false;
424     }
425     bool ret = BrightnessManager::Get().SetBrightness(value, duration);
426     if (ret) {
427         return true;
428     }
429     return iterator->second->SetBrightness(value, duration);
430 }
431 
AutoAdjustBrightness(bool enable)432 bool DisplayPowerMgrService::AutoAdjustBrightness(bool enable)
433 {
434     if (!Permission::IsSystem()) {
435         return false;
436     }
437     DISPLAY_HILOGD(FEAT_BRIGHTNESS, "AutoAdjustBrightness start");
438     if (!supportLightSensor_) {
439         DISPLAY_HILOGD(FEAT_BRIGHTNESS, "AutoAdjustBrightness not support");
440         SetSettingAutoBrightness(false);
441         return false;
442     }
443     if (enable) {
444         DISPLAY_HILOGD(FEAT_BRIGHTNESS, "AutoAdjustBrightness enable");
445         if (autoBrightness_) {
446             DISPLAY_HILOGD(FEAT_BRIGHTNESS, "AutoAdjustBrightness is already enabled");
447             return true;
448         }
449         autoBrightness_ = true;
450         BrightnessManager::Get().AutoAdjustBrightness(true);
451     } else {
452         DISPLAY_HILOGD(FEAT_BRIGHTNESS, "AutoAdjustBrightness disable");
453         if (!autoBrightness_) {
454             DISPLAY_HILOGD(FEAT_BRIGHTNESS, "AutoAdjustBrightness is already disabled");
455             return true;
456         }
457         autoBrightness_ = false;
458         BrightnessManager::Get().AutoAdjustBrightness(false);
459     }
460     SetSettingAutoBrightness(enable);
461     return true;
462 }
463 
464 #ifdef ENABLE_SENSOR_PART
ActivateAmbientSensor()465 void DisplayPowerMgrService::ActivateAmbientSensor()
466 {
467     if (!autoBrightness_) {
468         DISPLAY_HILOGD(FEAT_BRIGHTNESS, "auto brightness is not enabled");
469         return;
470     }
471     if (ambientSensorEnabled_) {
472         DISPLAY_HILOGD(FEAT_BRIGHTNESS, "Ambient Sensor is already on");
473         return;
474     }
475     (void) strcpy_s(sensorUser_.name, sizeof(sensorUser_.name), "DisplayPowerMgrService");
476     sensorUser_.userData = nullptr;
477     sensorUser_.callback = &AmbientLightCallback;
478     SubscribeSensor(SENSOR_TYPE_ID_AMBIENT_LIGHT, &sensorUser_);
479     SetBatch(SENSOR_TYPE_ID_AMBIENT_LIGHT, &sensorUser_, SAMPLING_RATE, SAMPLING_RATE);
480     ActivateSensor(SENSOR_TYPE_ID_AMBIENT_LIGHT, &sensorUser_);
481     SetMode(SENSOR_TYPE_ID_AMBIENT_LIGHT, &sensorUser_, SENSOR_ON_CHANGE);
482     ambientSensorEnabled_ = true;
483 }
484 
DeactivateAmbientSensor()485 void DisplayPowerMgrService::DeactivateAmbientSensor()
486 {
487     if (!autoBrightness_) {
488         DISPLAY_HILOGD(FEAT_BRIGHTNESS, "auto brightness is not enabled");
489         return;
490     }
491     if (!ambientSensorEnabled_) {
492         DISPLAY_HILOGD(FEAT_BRIGHTNESS, "Ambient Sensor is already off");
493         return;
494     }
495     DeactivateSensor(SENSOR_TYPE_ID_AMBIENT_LIGHT, &sensorUser_);
496     UnsubscribeSensor(SENSOR_TYPE_ID_AMBIENT_LIGHT, &sensorUser_);
497     ambientSensorEnabled_ = false;
498 }
499 #endif
500 
IsAutoAdjustBrightness()501 bool DisplayPowerMgrService::IsAutoAdjustBrightness()
502 {
503     return autoBrightness_;
504 }
505 
RegisterCallback(sptr<IDisplayPowerCallback> callback)506 bool DisplayPowerMgrService::RegisterCallback(sptr<IDisplayPowerCallback> callback)
507 {
508     if (!Permission::IsSystem()) {
509         return false;
510     }
511     std::lock_guard lock(mutex_);
512     DISPLAY_HILOGI(COMP_SVC, "RegisterCallback");
513     if (callback_ != nullptr) {
514         DISPLAY_HILOGI(COMP_SVC, "Callback function exist");
515         return false;
516     }
517     callback_ = callback;
518     sptr<IRemoteObject> remote = callback_->AsObject();
519     if (!remote->IsProxyObject()) {
520         DISPLAY_HILOGE(COMP_FWK, "Callback is not proxy");
521         return false;
522     }
523     if (cbDeathRecipient_ == nullptr) {
524         cbDeathRecipient_ = new CallbackDeathRecipient();
525     }
526     remote->AddDeathRecipient(cbDeathRecipient_);
527     return true;
528 }
529 
BoostBrightness(int32_t timeoutMs,uint32_t displayId)530 bool DisplayPowerMgrService::BoostBrightness(int32_t timeoutMs, uint32_t displayId)
531 {
532     if (!Permission::IsSystem()) {
533         return false;
534     }
535     DISPLAY_HILOGD(FEAT_BRIGHTNESS, "Timing boost brightness: %{public}d, id: %{public}d", timeoutMs, displayId);
536     RETURN_IF_WITH_RET(timeoutMs <= 0, false);
537     auto iter = controllerMap_.find(displayId);
538     RETURN_IF_WITH_RET(iter == controllerMap_.end(), false);
539     return BrightnessManager::Get().BoostBrightness(timeoutMs);
540 }
541 
CancelBoostBrightness(uint32_t displayId)542 bool DisplayPowerMgrService::CancelBoostBrightness(uint32_t displayId)
543 {
544     if (!Permission::IsSystem()) {
545         return false;
546     }
547     DISPLAY_HILOGD(FEAT_BRIGHTNESS, "Cancel boost brightness, id: %{public}d", displayId);
548     auto iter = controllerMap_.find(displayId);
549     RETURN_IF_WITH_RET(iter == controllerMap_.end(), false);
550     bool ret = BrightnessManager::Get().CancelBoostBrightness();
551     if (ret) {
552         return true;
553     }
554     return iter->second->CancelBoostBrightness();
555 }
556 
GetDeviceBrightness(uint32_t displayId)557 uint32_t DisplayPowerMgrService::GetDeviceBrightness(uint32_t displayId)
558 {
559     DISPLAY_HILOGD(FEAT_BRIGHTNESS, "GetDeviceBrightness displayId=%{public}u", displayId);
560     auto iter = controllerMap_.find(displayId);
561     if (iter == controllerMap_.end()) {
562         return BRIGHTNESS_OFF;
563     }
564     return BrightnessManager::Get().GetDeviceBrightness();
565 }
566 
SetCoordinated(bool coordinated,uint32_t displayId)567 bool DisplayPowerMgrService::SetCoordinated(bool coordinated, uint32_t displayId)
568 {
569     if (!Permission::IsSystem()) {
570         return false;
571     }
572     DISPLAY_HILOGD(FEAT_STATE, "Set coordinated=%{public}d, displayId=%{public}u", coordinated, displayId);
573     auto iter = controllerMap_.find(displayId);
574     RETURN_IF_WITH_RET(iter == controllerMap_.end(), false);
575     iter->second->SetCoordinated(coordinated);
576     return true;
577 }
578 
SetLightBrightnessThreshold(std::vector<int32_t> threshold,sptr<IDisplayBrightnessCallback> callback)579 uint32_t DisplayPowerMgrService::SetLightBrightnessThreshold(
580     std::vector<int32_t> threshold, sptr<IDisplayBrightnessCallback> callback)
581 {
582     if (!Permission::IsSystem()) {
583         return static_cast<uint32_t>(ERR_PERMISSION_DENIED);
584     }
585     return BrightnessManager::Get().SetLightBrightnessThreshold(threshold, callback);
586 }
587 
NotifyStateChangeCallback(uint32_t displayId,DisplayState state,uint32_t reason)588 void DisplayPowerMgrService::NotifyStateChangeCallback(uint32_t displayId, DisplayState state, uint32_t reason)
589 {
590     std::lock_guard lock(mutex_);
591     if (callback_ != nullptr) {
592         callback_->OnDisplayStateChanged(displayId, state, reason);
593     }
594 }
595 
DumpDisplayInfo(std::string & result)596 void DisplayPowerMgrService::DumpDisplayInfo(std::string& result)
597 {
598     for (auto& iter: controllerMap_) {
599         auto control = iter.second;
600         result.append("Display Id=").append(std::to_string(iter.first));
601         result.append(" State=").append(std::to_string(static_cast<uint32_t>(BrightnessManager::Get().GetState())));
602         result.append(" Discount=").append(std::to_string(BrightnessManager::Get().GetDiscount()));
603         result.append(" Brightness=").append(std::to_string(BrightnessManager::Get().GetBrightness()));
604         if (BrightnessManager::Get().IsBrightnessOverridden()) {
605             result.append(" OverrideBrightness=")
606                 .append(std::to_string(BrightnessManager::Get().GetScreenOnBrightness()));
607         }
608         if (BrightnessManager::Get().IsBrightnessBoosted()) {
609             result.append(" BoostBrightness=")
610                 .append(std::to_string(BrightnessManager::Get().GetScreenOnBrightness()));
611         }
612         result.append("\n");
613         result.append("DeviceBrightness=");
614         result.append(std::to_string(BrightnessManager::Get().GetDeviceBrightness())).append("\n");
615     }
616 }
617 
Dump(int32_t fd,const std::vector<std::u16string> & args)618 int32_t DisplayPowerMgrService::Dump(int32_t fd, const std::vector<std::u16string>& args)
619 {
620     if (!isBootCompleted_) {
621         return ERR_NO_INIT;
622     }
623     if (!Permission::IsSystem()) {
624         return ERR_PERMISSION_DENIED;
625     }
626     std::string result("DISPLAY POWER MANAGER DUMP:\n");
627     DumpDisplayInfo(result);
628 #ifdef ENABLE_SENSOR_PART
629     result.append("Support Ambient Light: ");
630     if (supportLightSensor_) {
631         result.append("TRUE");
632     } else {
633         result.append("FALSE");
634     }
635     result.append("\n");
636 
637     result.append("Auto Adjust Brightness: ");
638     if (autoBrightness_) {
639         result.append("ON");
640     } else {
641         result.append("OFF");
642     }
643     result.append("\n");
644 #endif
645 
646     result.append("Brightness Limits: ").append("Max=" + std::to_string(GetMaxBrightness()) + " ");
647     result.append("Min=" + std::to_string(GetMinBrightness()) + " ");
648     result.append("Default=" + std::to_string(GetDefaultBrightness())).append("\n");
649 
650     if (!SaveStringToFd(fd, result)) {
651         DISPLAY_HILOGE(COMP_SVC, "Failed to save dump info to fd");
652     }
653     return ERR_OK;
654 }
655 
656 #ifdef ENABLE_SENSOR_PART
InitSensors()657 void DisplayPowerMgrService::InitSensors()
658 {
659     DISPLAY_HILOGI(FEAT_BRIGHTNESS, "InitSensors start");
660     SensorInfo* sensorInfo = nullptr;
661     int32_t count;
662     int ret = GetAllSensors(&sensorInfo, &count);
663     if (ret != 0 || sensorInfo == nullptr) {
664         DISPLAY_HILOGI(FEAT_BRIGHTNESS, "Can't get sensors");
665         return;
666     }
667     supportLightSensor_ = false;
668     for (int i = 0; i < count; i++) {
669         if (sensorInfo[i].sensorId == SENSOR_TYPE_ID_AMBIENT_LIGHT) {
670             DISPLAY_HILOGI(FEAT_BRIGHTNESS, "AMBIENT_LIGHT Support");
671             supportLightSensor_ = true;
672             break;
673         }
674     }
675 
676     if (!supportLightSensor_) {
677         DISPLAY_HILOGI(FEAT_BRIGHTNESS, "AMBIENT_LIGHT not support");
678     }
679 }
680 
AmbientLightCallback(SensorEvent * event)681 void DisplayPowerMgrService::AmbientLightCallback(SensorEvent* event)
682 {
683     if (event->sensorTypeId != SENSOR_TYPE_ID_AMBIENT_LIGHT) {
684         DISPLAY_HILOGI(FEAT_BRIGHTNESS, "Sensor Callback is not AMBIENT_LIGHT");
685         return;
686     }
687     auto pms = DelayedSpSingleton<DisplayPowerMgrService>::GetInstance();
688     if (pms == nullptr) {
689         DISPLAY_HILOGI(FEAT_BRIGHTNESS, "Sensor Callback no service");
690         return;
691     }
692     uint32_t mainDispId = pms->GetMainDisplayId();
693     auto mainDisp = pms->controllerMap_.find(mainDispId);
694     if (mainDisp == pms->controllerMap_.end()) {
695         return;
696     }
697     if (mainDisp->second->IsBrightnessOverridden() || mainDisp->second->IsBrightnessBoosted()) {
698         DISPLAY_HILOGD(FEAT_BRIGHTNESS, "Overwrite or boost brightness scene, auto brightness is invalid");
699         return;
700     }
701     AmbientLightData* data = (AmbientLightData*) event->data;
702     int32_t brightness = static_cast<int32_t>(mainDisp->second->GetCachedSettingBrightness());
703     uint32_t animationUpdateTime = mainDisp->second->GetAnimationUpdateTime();
704     int32_t changeBrightness = 0;
705     if (pms->CalculateBrightness(data->intensity, brightness, changeBrightness)) {
706         double discountStride = static_cast<double>(AUTO_ADJUST_BRIGHTNESS_STRIDE / mainDisp->second->GetDiscount());
707         uint32_t gradualDuration = floor(changeBrightness / discountStride) * animationUpdateTime;
708         pms->AdjustBrightness(mainDispId, brightness, gradualDuration);
709     }
710 }
711 
IsChangedLux(float scalar)712 bool DisplayPowerMgrService::IsChangedLux(float scalar)
713 {
714     DISPLAY_HILOGD(FEAT_BRIGHTNESS, "changed: %{public}d, %{public}f vs %{public}f",
715                    luxChanged_, lastLux_, scalar);
716     if (lastLuxTime_ <= 0) {
717         DISPLAY_HILOGD(FEAT_BRIGHTNESS, "receive lux at first time");
718         lastLuxTime_ = time(0);
719         lastLux_ = scalar;
720         luxChanged_ = true;
721         return false;
722     }
723 
724     if (!luxChanged_) {
725         float luxChangeMin = (lastLux_ / LUX_CHANGE_RATE_THRESHOLD) + 1;
726         if (abs(scalar - lastLux_) < luxChangeMin) {
727             DISPLAY_HILOGD(FEAT_BRIGHTNESS, "Too little change");
728             return false;
729         } else {
730             DISPLAY_HILOGI(FEAT_BRIGHTNESS, "First time to change, wait for stable");
731             luxChanged_ = true;
732             return false;
733         }
734     } else {
735         float luxChangeMin = (lastLux_ / LUX_CHANGE_RATE_THRESHOLD) + 1;
736         if (luxChangeMin < LUX_CHANGE_STABLE_MIN) {
737             luxChangeMin = LUX_CHANGE_STABLE_MIN;
738         }
739         if (abs(scalar - lastLux_) >= luxChangeMin) {
740             time_t currentTime = time(0);
741             time_t sub = currentTime - lastLuxTime_;
742             DISPLAY_HILOGD(FEAT_BRIGHTNESS, "stable lux");
743             if (sub >= LUX_STABLE_TIME) {
744                 DISPLAY_HILOGI(FEAT_BRIGHTNESS, "stable enought to change");
745                 lastLuxTime_ = time(0);
746                 lastLux_ = scalar;
747                 luxChanged_ = false;
748                 return true;
749             }
750         } else {
751             DISPLAY_HILOGD(FEAT_BRIGHTNESS, "unstable lux, wait for stable");
752             luxChanged_ = true;
753             return false;
754         }
755     }
756     return false;
757 }
758 #endif
759 
GetSafeBrightness(uint32_t value)760 uint32_t DisplayPowerMgrService::GetSafeBrightness(uint32_t value)
761 {
762     auto brightnessValue = value;
763     if (brightnessValue > BRIGHTNESS_MAX) {
764         DISPLAY_HILOGD(FEAT_BRIGHTNESS, "brightness value is greater than max, value=%{public}u", value);
765         brightnessValue = BRIGHTNESS_MAX;
766     }
767     if (brightnessValue < BRIGHTNESS_MIN) {
768         DISPLAY_HILOGD(FEAT_BRIGHTNESS, "brightness value is less than min, value=%{public}u", value);
769         brightnessValue = BRIGHTNESS_MIN;
770     }
771     return brightnessValue;
772 }
773 
GetSafeDiscount(double discount,uint32_t brightness)774 double DisplayPowerMgrService::GetSafeDiscount(double discount, uint32_t brightness)
775 {
776     auto safeDiscount = discount;
777     if (safeDiscount > DISCOUNT_MAX) {
778         DISPLAY_HILOGD(COMP_SVC, "discount value is greater than max, discount=%{public}lf", discount);
779         safeDiscount = DISCOUNT_MAX;
780     }
781     if (safeDiscount < DISCOUNT_MIN) {
782         DISPLAY_HILOGD(COMP_SVC, "discount value is less than min, discount=%{public}lf", discount);
783         safeDiscount = DISCOUNT_MIN;
784     }
785     if (static_cast<uint32_t>(BRIGHTNESS_MIN / safeDiscount) > BRIGHTNESS_MAX) {
786         DISPLAY_HILOGD(COMP_SVC, "brightness than max, brightness=%{public}u, discount=%{public}lf",
787                        static_cast<uint32_t>(BRIGHTNESS_MIN / safeDiscount), discount);
788         safeDiscount = static_cast<double>(BRIGHTNESS_MIN / static_cast<double>(brightness));
789     }
790 
791     return safeDiscount;
792 }
793 
CalculateBrightness(float scalar,int32_t & brightness,int32_t & change)794 bool DisplayPowerMgrService::CalculateBrightness(float scalar, int32_t& brightness, int32_t& change)
795 {
796     const float lastLux = lastLux_;
797 #ifdef ENABLE_SENSOR_PART
798     if (!IsChangedLux(scalar)) {
799         return false;
800     }
801 #endif
802     int32_t calcBrightness = GetBrightnessFromLightScalar(scalar);
803     int32_t difference = abs(calcBrightness - brightness);
804     DISPLAY_HILOGD(FEAT_BRIGHTNESS, "lux: %{public}f -> %{public}f, screen: %{public}d -> %{public}d",
805                    lastLux, scalar, brightness, calcBrightness);
806     if (difference < BRIGHTNESS_CHANGE_MIN
807         || (scalar > lastLux && calcBrightness < brightness)
808         || (scalar < lastLux && calcBrightness > brightness)) {
809         DISPLAY_HILOGI(FEAT_BRIGHTNESS, "screen is too light/dark when calculated change");
810         return false;
811     }
812     brightness = calcBrightness;
813     change = difference;
814     return true;
815 }
816 
GetBrightnessFromLightScalar(float scalar)817 int32_t DisplayPowerMgrService::GetBrightnessFromLightScalar(float scalar)
818 {
819     uint32_t brightness = DisplayAutoBrightness::CalculateAutoBrightness(scalar);
820     DISPLAY_HILOGD(FEAT_BRIGHTNESS, "scalar: %{public}f, brightness: %{public}d", scalar, brightness);
821     if (brightness > BRIGHTNESS_MAX) {
822         brightness = BRIGHTNESS_MAX;
823     } else if (brightness < BRIGHTNESS_MIN) {
824         brightness = BRIGHTNESS_MIN;
825     }
826     return static_cast<int32_t>(brightness);
827 }
828 
GetError()829 DisplayErrors DisplayPowerMgrService::GetError()
830 {
831     DisplayErrors tmpError = lastError_;
832     lastError_ = DisplayErrors::ERR_OK;
833     return tmpError;
834 }
835 
OnRemoteDied(const wptr<IRemoteObject> & remote)836 void DisplayPowerMgrService::CallbackDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& remote)
837 {
838     DISPLAY_HILOGI(COMP_SVC, "CallbackDeathRecipient OnRemoteDied");
839     auto pms = DelayedSpSingleton<DisplayPowerMgrService>::GetInstance();
840     if (pms == nullptr) {
841         DISPLAY_HILOGI(COMP_SVC, "OnRemoteDied no service");
842         return;
843     }
844 
845     std::lock_guard lock(callbackMutex_);
846     pms->callback_ = nullptr;
847 }
848 
849 /**
850 * @brief Function to limit maximum screen brightness
851 * @param value  The max brightness level that needs to be restricted
852 * @param mode  0 = default mode, set param value as maxBrightness;
853 *               1 = enter testMode, when running unittest set maxBrightness to default value;
854 *               2 = exit testMode
855 * @return false = set failed; true = set Sucess
856 */
SetMaxBrightness(double value,uint32_t mode)857 bool DisplayPowerMgrService::SetMaxBrightness(double value, uint32_t mode)
858 {
859     if (!Permission::IsSystem()) {
860         lastError_ = DisplayErrors::ERR_SYSTEM_API_DENIED;
861         DISPLAY_HILOGE(COMP_SVC, "SetMaxBrightness Permission Error!");
862         return false;
863     }
864     if (mode == TEST_MODE) {
865         isInTestMode_ = true;
866         DISPLAY_HILOGI(COMP_SVC, "SetMaxBrightness enter TestMode");
867     }
868     if (mode == NORMAL_MODE) {
869         isInTestMode_ = false;
870         DISPLAY_HILOGI(COMP_SVC, "SetMaxBrightness cancel TestMode");
871     }
872     if (isInTestMode_) {
873         DISPLAY_HILOGI(COMP_SVC, "in the TestMode SetMaxBrightness to Default Value!");
874         double maxBrightness = 1.0;
875         return BrightnessManager::Get().SetMaxBrightness(maxBrightness);
876     }
877     return BrightnessManager::Get().SetMaxBrightness(value);
878 }
879 
880 /**
881 * @brief Function to limit maximum screen brightness
882 * @param maxNit  The max brightness Nit that needs to be restricted
883 * @param mode  0 = default mode, set param value as maxBrightness;
884 *               1 = enter testMode, when running unittest set maxBrightness to default value;
885 *               2 = exit testMode
886 * @return false = set failed; true = set Sucess
887 */
SetMaxBrightnessNit(uint32_t maxNit,uint32_t mode)888 bool DisplayPowerMgrService::SetMaxBrightnessNit(uint32_t maxNit, uint32_t mode)
889 {
890     if (!Permission::IsSystem()) {
891         lastError_ = DisplayErrors::ERR_SYSTEM_API_DENIED;
892         DISPLAY_HILOGE(COMP_SVC, "SetMaxBrightness Permission Error!");
893         return false;
894     }
895     if (mode == TEST_MODE) {
896         isInTestMode_ = true;
897         DISPLAY_HILOGI(COMP_SVC, "SetMaxBrightness enter TestMode");
898     }
899     if (mode == NORMAL_MODE) {
900         isInTestMode_ = false;
901         DISPLAY_HILOGI(COMP_SVC, "SetMaxBrightness cancel TestMode");
902     }
903     if (isInTestMode_) {
904         DISPLAY_HILOGI(COMP_SVC, "in the TestMode SetMaxBrightness to Default Value!");
905         uint32_t default_max_nit = 600;
906         return BrightnessManager::Get().SetMaxBrightnessNit(default_max_nit);
907     }
908     return BrightnessManager::Get().SetMaxBrightnessNit(maxNit);
909 }
910 } // namespace DisplayPowerMgr
911 } // namespace OHOS
912