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