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