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 #include "sensor_agent.h"
26 #include "xcollie/watchdog.h"
27 #include "display_log.h"
28 #include "display_auto_brightness.h"
29 #include "display_setting_helper.h"
30 #include "display_param_helper.h"
31 #include "permission.h"
32 #include "setting_provider.h"
33 #include "ffrt_utils.h"
34
35 namespace OHOS {
36 namespace DisplayPowerMgr {
37 using namespace OHOS::PowerMgr;
38 namespace {
39 DisplayParamHelper::BootCompletedCallback g_bootCompletedCallback;
40 FFRTQueue g_queue("display_power_mgr_service");
41 FFRTHandle g_screenOffDelayTaskHandle;
42 }
43
44 const uint32_t DisplayPowerMgrService::BRIGHTNESS_MIN = DisplayParamHelper::GetMinBrightness();
45 const uint32_t DisplayPowerMgrService::BRIGHTNESS_DEFAULT = DisplayParamHelper::GetDefaultBrightness();
46 const uint32_t DisplayPowerMgrService::BRIGHTNESS_MAX = DisplayParamHelper::GetMaxBrightness();
47 std::atomic_bool DisplayPowerMgrService::isBootCompleted_ = false;
48 DisplayPowerMgrService::DisplayPowerMgrService() = default;
49
Init()50 void DisplayPowerMgrService::Init()
51 {
52 DISPLAY_HILOGI(COMP_SVC, "DisplayPowerMgrService Create");
53 std::vector<uint32_t> displayIds = ScreenAction::GetAllDisplayId();
54 for (const auto& id: displayIds) {
55 DISPLAY_HILOGI(COMP_SVC, "find display, id=%{public}u", id);
56 controllerMap_.emplace(id, std::make_shared<ScreenController>(id));
57 }
58
59 callback_ = nullptr;
60 cbDeathRecipient_ = nullptr;
61
62 InitSensors();
63 RegisterBootCompletedCallback();
64 }
RegisterBootCompletedCallback()65 void DisplayPowerMgrService::RegisterBootCompletedCallback()
66 {
67 g_bootCompletedCallback = []() {
68 SetBootCompletedBrightness();
69 SetBootCompletedAutoBrightness();
70 RegisterSettingObservers();
71 isBootCompleted_ = true;
72 };
73 DisplayParamHelper::RegisterBootCompletedCallback(g_bootCompletedCallback);
74 }
75
Deinit()76 void DisplayPowerMgrService::Deinit()
77 {
78 UnregisterSettingObservers();
79 isBootCompleted_ = false;
80 }
81
SetBootCompletedBrightness()82 void DisplayPowerMgrService::SetBootCompletedBrightness()
83 {
84 uint32_t mainDisplayId = DelayedSpSingleton<DisplayPowerMgrService>::GetInstance()->GetMainDisplayId();
85 uint32_t brightness = DelayedSpSingleton<DisplayPowerMgrService>::GetInstance()->GetBrightness(mainDisplayId);
86 DelayedSpSingleton<DisplayPowerMgrService>::GetInstance()->SetBrightness(brightness, mainDisplayId);
87 }
88
SetBootCompletedAutoBrightness()89 void DisplayPowerMgrService::SetBootCompletedAutoBrightness()
90 {
91 bool enable = GetSettingAutoBrightness();
92 DelayedSpSingleton<DisplayPowerMgrService>::GetInstance()->AutoAdjustBrightness(enable);
93 }
94
RegisterSettingObservers()95 void DisplayPowerMgrService::RegisterSettingObservers()
96 {
97 uint32_t mainDisplayId = DelayedSpSingleton<DisplayPowerMgrService>::GetInstance()->GetMainDisplayId();
98 auto controllerMap = DelayedSpSingleton<DisplayPowerMgrService>::GetInstance()->controllerMap_;
99 auto iter = controllerMap.find(mainDisplayId);
100 if (iter != controllerMap.end()) {
101 iter->second->RegisterSettingBrightnessObserver();
102 }
103 RegisterSettingAutoBrightnessObserver();
104 }
105
UnregisterSettingObservers()106 void DisplayPowerMgrService::UnregisterSettingObservers()
107 {
108 uint32_t mainDisplayId = DelayedSpSingleton<DisplayPowerMgrService>::GetInstance()->GetMainDisplayId();
109 auto controllerMap = DelayedSpSingleton<DisplayPowerMgrService>::GetInstance()->controllerMap_;
110 auto iter = controllerMap.find(mainDisplayId);
111 if (iter != controllerMap.end()) {
112 iter->second->UnregisterSettingBrightnessObserver();
113 }
114 UnregisterSettingAutoBrightnessObserver();
115 }
116
RegisterSettingAutoBrightnessObserver()117 void DisplayPowerMgrService::RegisterSettingAutoBrightnessObserver()
118 {
119 SettingObserver::UpdateFunc updateFunc = [&](const std::string& key) { AutoBrightnessSettingUpdateFunc(key); };
120 DisplaySettingHelper::RegisterSettingAutoBrightnessObserver(updateFunc);
121 }
122
AutoBrightnessSettingUpdateFunc(const std::string & key)123 void DisplayPowerMgrService::AutoBrightnessSettingUpdateFunc(const std::string& key)
124 {
125 bool isSettingEnable = GetSettingAutoBrightness(key);
126 bool isSystemEnable = DelayedSpSingleton<DisplayPowerMgrService>::GetInstance()->IsAutoAdjustBrightness();
127 if (isSettingEnable == isSystemEnable) {
128 return;
129 }
130 DelayedSpSingleton<DisplayPowerMgrService>::GetInstance()->AutoAdjustBrightness(isSettingEnable);
131 }
132
SetSettingAutoBrightness(bool enable)133 void DisplayPowerMgrService::SetSettingAutoBrightness(bool enable)
134 {
135 DisplaySettingHelper::SetSettingAutoBrightness(enable);
136 }
137
GetSettingAutoBrightness(const std::string & key)138 bool DisplayPowerMgrService::GetSettingAutoBrightness(const std::string& key)
139 {
140 return DisplaySettingHelper::GetSettingAutoBrightness(key);
141 }
ScreenOffDelay(uint32_t id,DisplayState state,uint32_t reason)142 void DisplayPowerMgrService::ScreenOffDelay(uint32_t id, DisplayState state, uint32_t reason)
143 {
144 isDisplayDelayOff_ = false;
145 DISPLAY_HILOGI(COMP_SVC, "ScreenOffDelay %{public}d, %{public}d, %{public}d", id, state, reason);
146 auto iterator = controllerMap_.find(id);
147 if (iterator == controllerMap_.end()) {
148 return;
149 }
150 setDisplayStateRet_ = iterator->second->UpdateState(state, reason);
151 }
152
UnregisterSettingAutoBrightnessObserver()153 void DisplayPowerMgrService::UnregisterSettingAutoBrightnessObserver()
154 {
155 DisplaySettingHelper::UnregisterSettingAutoBrightnessObserver();
156 }
157
SetDisplayState(uint32_t id,DisplayState state,uint32_t reason)158 bool DisplayPowerMgrService::SetDisplayState(uint32_t id, DisplayState state, uint32_t reason)
159 {
160 if (!Permission::IsSystem()) {
161 return false;
162 }
163 DISPLAY_HILOGI(COMP_SVC, "SetDisplayState %{public}d, %{public}d", id, state);
164 auto iterator = controllerMap_.find(id);
165 if (iterator == controllerMap_.end()) {
166 return false;
167 }
168 if (id == GetMainDisplayId()) {
169 DISPLAY_HILOGI(COMP_SVC, "change ambient sensor status");
170 if (state == DisplayState::DISPLAY_ON) {
171 ActivateAmbientSensor();
172 } else if (state == DisplayState::DISPLAY_OFF) {
173 DeactivateAmbientSensor();
174 }
175 }
176
177 if (state == DisplayState::DISPLAY_OFF) {
178 if (!isDisplayDelayOff_) {
179 DISPLAY_HILOGI(COMP_SVC, "screen off immediately");
180 return iterator->second->UpdateState(state, reason);
181 }
182 displayId_ = id;
183 displayState_ = state;
184 displayReason_ = reason;
185 FFRTTask task = [this]() { ScreenOffDelay(displayId_, displayState_, displayReason_); };
186 g_screenOffDelayTaskHandle = FFRTUtils::SubmitDelayTask(task, displayOffDelayMs_, g_queue);
187 tempState_ = iterator->second->SetDelayOffState();
188 return true;
189 } else if (state == DisplayState::DISPLAY_ON) {
190 if (isDisplayDelayOff_) {
191 DISPLAY_HILOGI(COMP_SVC, "need remove delay task");
192 FFRTUtils::CancelTask(g_screenOffDelayTaskHandle, g_queue);
193 isDisplayDelayOff_ = false;
194 tempState_ = iterator->second->SetOnState();
195 return true;
196 }
197 }
198 return iterator->second->UpdateState(state, reason);
199 }
200
GetDisplayState(uint32_t id)201 DisplayState DisplayPowerMgrService::GetDisplayState(uint32_t id)
202 {
203 DISPLAY_HILOGD(COMP_SVC, "GetDisplayState %{public}d", id);
204 auto iterator = controllerMap_.find(id);
205 if (iterator == controllerMap_.end()) {
206 return DisplayState::DISPLAY_UNKNOWN;
207 }
208 return iterator->second->GetState();
209 }
210
GetDisplayIds()211 std::vector<uint32_t> DisplayPowerMgrService::GetDisplayIds()
212 {
213 std::vector<uint32_t> ids;
214 for (auto& iter: controllerMap_) {
215 ids.push_back(iter.first);
216 }
217 return ids;
218 }
219
GetMainDisplayId()220 uint32_t DisplayPowerMgrService::GetMainDisplayId()
221 {
222 uint32_t id = ScreenAction::GetDefaultDisplayId();
223 DISPLAY_HILOGD(COMP_SVC, "GetMainDisplayId %{public}d", id);
224 return id;
225 }
226
SetBrightness(uint32_t value,uint32_t displayId)227 bool DisplayPowerMgrService::SetBrightness(uint32_t value, uint32_t displayId)
228 {
229 if (!Permission::IsSystem()) {
230 lastError_ = DisplayErrors::ERR_SYSTEM_API_DENIED;
231 return false;
232 }
233
234 auto brightness = GetSafeBrightness(value);
235 DISPLAY_HILOGI(FEAT_BRIGHTNESS, "SetBrightness displayId=%{public}u, value=%{public}u", displayId, brightness);
236 auto iter = controllerMap_.find(displayId);
237 if (iter == controllerMap_.end()) {
238 return false;
239 }
240 return iter->second->SetBrightness(brightness);
241 }
242
DiscountBrightness(double discount,uint32_t displayId)243 bool DisplayPowerMgrService::DiscountBrightness(double discount, uint32_t displayId)
244 {
245 if (!Permission::IsSystem()) {
246 return false;
247 }
248 auto iter = controllerMap_.find(displayId);
249 if (iter == controllerMap_.end()) {
250 return false;
251 }
252 auto brightness = iter->second->GetBrightness();
253 auto safeDiscount = GetSafeDiscount(discount, brightness);
254 DISPLAY_HILOGI(FEAT_BRIGHTNESS, "DiscountBrightness displayId=%{public}u, discount-%{public}lf",
255 displayId, safeDiscount);
256 HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::DISPLAY, "BACKLIGHT_DISCOUNT",
257 HiviewDFX::HiSysEvent::EventType::STATISTIC, "RATIO", safeDiscount);
258 return iter->second->DiscountBrightness(safeDiscount);
259 }
260
OverrideBrightness(uint32_t value,uint32_t displayId)261 bool DisplayPowerMgrService::OverrideBrightness(uint32_t value, uint32_t displayId)
262 {
263 if (!Permission::IsSystem()) {
264 return false;
265 }
266 auto brightness = GetSafeBrightness(value);
267 DISPLAY_HILOGI(COMP_SVC, "OverrideBrightness displayId=%{public}u, value=%{public}u", displayId, brightness);
268 auto iter = controllerMap_.find(displayId);
269 if (iter == controllerMap_.end()) {
270 return false;
271 }
272 return iter->second->OverrideBrightness(brightness);
273 }
274
OverrideDisplayOffDelay(uint32_t delayMs)275 bool DisplayPowerMgrService::OverrideDisplayOffDelay(uint32_t delayMs)
276 {
277 if (GetDisplayState(GetMainDisplayId()) != DisplayState::DISPLAY_ON || delayMs == DELAY_TIME_UNSET) {
278 isDisplayDelayOff_ = false;
279 return isDisplayDelayOff_;
280 }
281 DISPLAY_HILOGI(COMP_SVC, "OverrideDisplayOffDelay delayMs=%{public}u", delayMs);
282 isDisplayDelayOff_ = true;
283 displayOffDelayMs_ = delayMs;
284
285 return isDisplayDelayOff_;
286 }
287
RestoreBrightness(uint32_t displayId)288 bool DisplayPowerMgrService::RestoreBrightness(uint32_t displayId)
289 {
290 if (!Permission::IsSystem()) {
291 return false;
292 }
293 DISPLAY_HILOGI(COMP_SVC, "RestoreBrightness displayId=%{public}u", displayId);
294 auto iter = controllerMap_.find(displayId);
295 if (iter == controllerMap_.end()) {
296 return false;
297 }
298 return iter->second->RestoreBrightness();
299 }
300
GetBrightness(uint32_t displayId)301 uint32_t DisplayPowerMgrService::GetBrightness(uint32_t displayId)
302 {
303 DISPLAY_HILOGD(FEAT_BRIGHTNESS, "GetBrightness displayId=%{public}u", displayId);
304 auto iter = controllerMap_.find(displayId);
305 if (iter == controllerMap_.end()) {
306 return BRIGHTNESS_OFF;
307 }
308 return iter->second->GetBrightness();
309 }
310
GetDefaultBrightness()311 uint32_t DisplayPowerMgrService::GetDefaultBrightness()
312 {
313 return BRIGHTNESS_DEFAULT;
314 }
315
GetMaxBrightness()316 uint32_t DisplayPowerMgrService::GetMaxBrightness()
317 {
318 return BRIGHTNESS_MAX;
319 }
320
GetMinBrightness()321 uint32_t DisplayPowerMgrService::GetMinBrightness()
322 {
323 return BRIGHTNESS_MIN;
324 }
325
AdjustBrightness(uint32_t id,int32_t value,uint32_t duration)326 bool DisplayPowerMgrService::AdjustBrightness(uint32_t id, int32_t value, uint32_t duration)
327 {
328 if (!Permission::IsSystem()) {
329 return false;
330 }
331 DISPLAY_HILOGD(FEAT_BRIGHTNESS, "SetDisplayState %{public}d, %{public}d, %{public}d",
332 id, value, duration);
333 auto iterator = controllerMap_.find(id);
334 if (iterator == controllerMap_.end()) {
335 return false;
336 }
337 return iterator->second->SetBrightness(value, duration);
338 }
339
AutoAdjustBrightness(bool enable)340 bool DisplayPowerMgrService::AutoAdjustBrightness(bool enable)
341 {
342 DISPLAY_HILOGD(FEAT_BRIGHTNESS, "AutoAdjustBrightness start");
343 if (!supportLightSensor_) {
344 DISPLAY_HILOGD(FEAT_BRIGHTNESS, "AutoAdjustBrightness not support");
345 SetSettingAutoBrightness(false);
346 return false;
347 }
348 if (enable) {
349 DISPLAY_HILOGD(FEAT_BRIGHTNESS, "AutoAdjustBrightness enable");
350 if (autoBrightness_) {
351 DISPLAY_HILOGD(FEAT_BRIGHTNESS, "AutoAdjustBrightness is already enabled");
352 return true;
353 }
354 autoBrightness_ = true;
355 if (GetDisplayState(GetMainDisplayId()) == DisplayState::DISPLAY_ON) {
356 ActivateAmbientSensor();
357 }
358 } else {
359 DISPLAY_HILOGD(FEAT_BRIGHTNESS, "AutoAdjustBrightness disable");
360 if (!autoBrightness_) {
361 DISPLAY_HILOGD(FEAT_BRIGHTNESS, "AutoAdjustBrightness is already disabled");
362 return true;
363 }
364 DeactivateAmbientSensor();
365 autoBrightness_ = false;
366 }
367 SetSettingAutoBrightness(enable);
368 return true;
369 }
370
IsAutoAdjustBrightness()371 bool DisplayPowerMgrService::IsAutoAdjustBrightness()
372 {
373 return autoBrightness_;
374 }
375
ActivateAmbientSensor()376 void DisplayPowerMgrService::ActivateAmbientSensor()
377 {
378 if (!autoBrightness_) {
379 DISPLAY_HILOGD(FEAT_BRIGHTNESS, "auto brightness is not enabled");
380 return;
381 }
382 if (ambientSensorEnabled_) {
383 DISPLAY_HILOGD(FEAT_BRIGHTNESS, "Ambient Sensor is already on");
384 return;
385 }
386 (void) strcpy_s(sensorUser_.name, sizeof(sensorUser_.name), "DisplayPowerMgrService");
387 sensorUser_.userData = nullptr;
388 sensorUser_.callback = &AmbientLightCallback;
389 SubscribeSensor(SENSOR_TYPE_ID_AMBIENT_LIGHT, &sensorUser_);
390 SetBatch(SENSOR_TYPE_ID_AMBIENT_LIGHT, &sensorUser_, SAMPLING_RATE, SAMPLING_RATE);
391 ActivateSensor(SENSOR_TYPE_ID_AMBIENT_LIGHT, &sensorUser_);
392 SetMode(SENSOR_TYPE_ID_AMBIENT_LIGHT, &sensorUser_, SENSOR_ON_CHANGE);
393 ambientSensorEnabled_ = true;
394 }
395
DeactivateAmbientSensor()396 void DisplayPowerMgrService::DeactivateAmbientSensor()
397 {
398 if (!autoBrightness_) {
399 DISPLAY_HILOGD(FEAT_BRIGHTNESS, "auto brightness is not enabled");
400 return;
401 }
402 if (!ambientSensorEnabled_) {
403 DISPLAY_HILOGD(FEAT_BRIGHTNESS, "Ambient Sensor is already off");
404 return;
405 }
406 DeactivateSensor(SENSOR_TYPE_ID_AMBIENT_LIGHT, &sensorUser_);
407 UnsubscribeSensor(SENSOR_TYPE_ID_AMBIENT_LIGHT, &sensorUser_);
408 ambientSensorEnabled_ = false;
409 }
410
RegisterCallback(sptr<IDisplayPowerCallback> callback)411 bool DisplayPowerMgrService::RegisterCallback(sptr<IDisplayPowerCallback> callback)
412 {
413 if (!Permission::IsSystem()) {
414 return false;
415 }
416 std::lock_guard lock(mutex_);
417 DISPLAY_HILOGI(COMP_SVC, "RegisterCallback");
418 if (callback_ != nullptr) {
419 DISPLAY_HILOGI(COMP_SVC, "Callback function exist");
420 return false;
421 }
422 callback_ = callback;
423 sptr<IRemoteObject> remote = callback_->AsObject();
424 if (!remote->IsProxyObject()) {
425 DISPLAY_HILOGE(COMP_FWK, "Callback is not proxy");
426 return false;
427 }
428 if (cbDeathRecipient_ == nullptr) {
429 cbDeathRecipient_ = new CallbackDeathRecipient();
430 }
431 remote->AddDeathRecipient(cbDeathRecipient_);
432 return true;
433 }
434
BoostBrightness(int32_t timeoutMs,uint32_t displayId)435 bool DisplayPowerMgrService::BoostBrightness(int32_t timeoutMs, uint32_t displayId)
436 {
437 if (!Permission::IsSystem()) {
438 return false;
439 }
440 DISPLAY_HILOGD(FEAT_BRIGHTNESS, "Timing boost brightness: %{public}d, id: %{public}d", timeoutMs, displayId);
441 RETURN_IF_WITH_RET(timeoutMs <= 0, false);
442 auto iter = controllerMap_.find(displayId);
443 RETURN_IF_WITH_RET(iter == controllerMap_.end(), false);
444 return iter->second->BoostBrightness(timeoutMs);
445 }
446
CancelBoostBrightness(uint32_t displayId)447 bool DisplayPowerMgrService::CancelBoostBrightness(uint32_t displayId)
448 {
449 if (!Permission::IsSystem()) {
450 return false;
451 }
452 DISPLAY_HILOGD(FEAT_BRIGHTNESS, "Cancel boost brightness, id: %{public}d", displayId);
453 auto iter = controllerMap_.find(displayId);
454 RETURN_IF_WITH_RET(iter == controllerMap_.end(), false);
455 return iter->second->CancelBoostBrightness();
456 }
457
GetDeviceBrightness(uint32_t displayId)458 uint32_t DisplayPowerMgrService::GetDeviceBrightness(uint32_t displayId)
459 {
460 DISPLAY_HILOGD(FEAT_BRIGHTNESS, "GetDeviceBrightness displayId=%{public}u", displayId);
461 auto iter = controllerMap_.find(displayId);
462 if (iter == controllerMap_.end()) {
463 return BRIGHTNESS_OFF;
464 }
465 return iter->second->GetDeviceBrightness();
466 }
467
NotifyStateChangeCallback(uint32_t displayId,DisplayState state,uint32_t reason)468 void DisplayPowerMgrService::NotifyStateChangeCallback(uint32_t displayId, DisplayState state, uint32_t reason)
469 {
470 std::lock_guard lock(mutex_);
471 if (callback_ != nullptr) {
472 callback_->OnDisplayStateChanged(displayId, state, reason);
473 }
474 }
475
Dump(int32_t fd,const std::vector<std::u16string> & args)476 int32_t DisplayPowerMgrService::Dump(int32_t fd, const std::vector<std::u16string>& args)
477 {
478 if (!isBootCompleted_) {
479 return ERR_NO_INIT;
480 }
481 if (!Permission::IsSystem()) {
482 return ERR_PERMISSION_DENIED;
483 }
484 std::string result("DISPLAY POWER MANAGER DUMP:\n");
485 for (auto& iter: controllerMap_) {
486 auto control = iter.second;
487 result.append("Display Id=");
488 result.append(std::to_string(iter.first));
489 result.append(" State=");
490 result.append(std::to_string(static_cast<uint32_t>(control->GetState())));
491 result.append(" Discount=");
492 result.append(std::to_string(control->GetDiscount()));
493 result.append(" Brightness=");
494 result.append(std::to_string(control->GetBrightness()));
495 if (control->IsBrightnessOverridden()) {
496 result.append(" OverrideBrightness=");
497 result.append(std::to_string(control->GetScreenOnBrightness()));
498 }
499 if (control->IsBrightnessBoosted()) {
500 result.append(" BoostBrightness=");
501 result.append(std::to_string(control->GetScreenOnBrightness()));
502 }
503 result.append("\n");
504 result.append("DeviceBrightness=");
505 result.append(std::to_string(control->GetDeviceBrightness()));
506 result.append("\n");
507 }
508
509 result.append("Support Ambient Light: ");
510 if (supportLightSensor_) {
511 result.append("TRUE");
512 } else {
513 result.append("FALSE");
514 }
515 result.append("\n");
516
517 result.append("Auto Adjust Brightness: ");
518 if (autoBrightness_) {
519 result.append("ON");
520 } else {
521 result.append("OFF");
522 }
523 result.append("\n");
524
525 result.append("Brightness Limits: ");
526 result.append("Max=" + std::to_string(GetMaxBrightness()) + " ");
527 result.append("Min=" + std::to_string(GetMinBrightness()) + " ");
528 result.append("Default=" + std::to_string(GetDefaultBrightness()));
529 result.append("\n");
530
531 if (!SaveStringToFd(fd, result)) {
532 DISPLAY_HILOGE(COMP_SVC, "Failed to save dump info to fd");
533 }
534 return ERR_OK;
535 }
536
InitSensors()537 void DisplayPowerMgrService::InitSensors()
538 {
539 DISPLAY_HILOGI(FEAT_BRIGHTNESS, "InitSensors start");
540 SensorInfo* sensorInfo = nullptr;
541 int32_t count;
542 int ret = GetAllSensors(&sensorInfo, &count);
543 if (ret != 0 || sensorInfo == nullptr) {
544 DISPLAY_HILOGI(FEAT_BRIGHTNESS, "Can't get sensors");
545 return;
546 }
547 supportLightSensor_ = false;
548 for (int i = 0; i < count; i++) {
549 if (sensorInfo[i].sensorId == SENSOR_TYPE_ID_AMBIENT_LIGHT) {
550 DISPLAY_HILOGI(FEAT_BRIGHTNESS, "AMBIENT_LIGHT Support");
551 supportLightSensor_ = true;
552 break;
553 }
554 }
555
556 if (!supportLightSensor_) {
557 DISPLAY_HILOGI(FEAT_BRIGHTNESS, "AMBIENT_LIGHT not support");
558 }
559 }
560
AmbientLightCallback(SensorEvent * event)561 void DisplayPowerMgrService::AmbientLightCallback(SensorEvent* event)
562 {
563 if (event->sensorTypeId != SENSOR_TYPE_ID_AMBIENT_LIGHT) {
564 DISPLAY_HILOGI(FEAT_BRIGHTNESS, "Sensor Callback is not AMBIENT_LIGHT");
565 return;
566 }
567 auto pms = DelayedSpSingleton<DisplayPowerMgrService>::GetInstance();
568 if (pms == nullptr) {
569 DISPLAY_HILOGI(FEAT_BRIGHTNESS, "Sensor Callback no service");
570 return;
571 }
572 uint32_t mainDispId = pms->GetMainDisplayId();
573 auto mainDisp = pms->controllerMap_.find(mainDispId);
574 if (mainDisp == pms->controllerMap_.end()) {
575 return;
576 }
577 if (mainDisp->second->IsBrightnessOverridden() || mainDisp->second->IsBrightnessBoosted()) {
578 DISPLAY_HILOGD(FEAT_BRIGHTNESS, "Overwrite or boost brightness scene, auto brightness is invalid");
579 return;
580 }
581 AmbientLightData* data = (AmbientLightData*) event->data;
582 int32_t brightness = static_cast<int32_t>(mainDisp->second->GetCachedSettingBrightness());
583 uint32_t animationUpdateTime = mainDisp->second->GetAnimationUpdateTime();
584 int32_t changeBrightness = 0;
585 if (pms->CalculateBrightness(data->intensity, brightness, changeBrightness)) {
586 double discountStride = static_cast<double>(AUTO_ADJUST_BRIGHTNESS_STRIDE / mainDisp->second->GetDiscount());
587 uint32_t gradualDuration = floor(changeBrightness / discountStride) * animationUpdateTime;
588 pms->AdjustBrightness(mainDispId, brightness, gradualDuration);
589 }
590 // Notify ambient brightness change event to battery statistics
591 HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::DISPLAY, "AMBIENT_LIGHT",
592 HiviewDFX::HiSysEvent::EventType::STATISTIC, "LEVEL", brightness);
593 }
594
IsChangedLux(float scalar)595 bool DisplayPowerMgrService::IsChangedLux(float scalar)
596 {
597 DISPLAY_HILOGD(FEAT_BRIGHTNESS, "changed: %{public}d, %{public}f vs %{public}f",
598 luxChanged_, lastLux_, scalar);
599 if (lastLuxTime_ <= 0) {
600 DISPLAY_HILOGD(FEAT_BRIGHTNESS, "receive lux at first time");
601 lastLuxTime_ = time(0);
602 lastLux_ = scalar;
603 luxChanged_ = true;
604 return false;
605 }
606
607 if (!luxChanged_) {
608 float luxChangeMin = (lastLux_ / LUX_CHANGE_RATE_THRESHOLD) + 1;
609 if (abs(scalar - lastLux_) < luxChangeMin) {
610 DISPLAY_HILOGD(FEAT_BRIGHTNESS, "Too little change");
611 return false;
612 } else {
613 DISPLAY_HILOGI(FEAT_BRIGHTNESS, "First time to change, wait for stable");
614 luxChanged_ = true;
615 return false;
616 }
617 } else {
618 float luxChangeMin = (lastLux_ / LUX_CHANGE_RATE_THRESHOLD) + 1;
619 if (luxChangeMin < LUX_CHANGE_STABLE_MIN) {
620 luxChangeMin = LUX_CHANGE_STABLE_MIN;
621 }
622 if (abs(scalar - lastLux_) >= luxChangeMin) {
623 time_t currentTime = time(0);
624 time_t sub = currentTime - lastLuxTime_;
625 DISPLAY_HILOGD(FEAT_BRIGHTNESS, "stable lux");
626 if (sub >= LUX_STABLE_TIME) {
627 DISPLAY_HILOGI(FEAT_BRIGHTNESS, "stable enought to change");
628 lastLuxTime_ = time(0);
629 lastLux_ = scalar;
630 luxChanged_ = false;
631 return true;
632 }
633 } else {
634 DISPLAY_HILOGD(FEAT_BRIGHTNESS, "unstable lux, wait for stable");
635 luxChanged_ = true;
636 return false;
637 }
638 }
639 return false;
640 }
641
GetSafeBrightness(uint32_t value)642 uint32_t DisplayPowerMgrService::GetSafeBrightness(uint32_t value)
643 {
644 auto brightnessValue = value;
645 if (brightnessValue > BRIGHTNESS_MAX) {
646 DISPLAY_HILOGD(FEAT_BRIGHTNESS, "brightness value is greater than max, value=%{public}u", value);
647 brightnessValue = BRIGHTNESS_MAX;
648 }
649 if (brightnessValue < BRIGHTNESS_MIN) {
650 DISPLAY_HILOGD(FEAT_BRIGHTNESS, "brightness value is less than min, value=%{public}u", value);
651 brightnessValue = BRIGHTNESS_MIN;
652 }
653 return brightnessValue;
654 }
655
GetSafeDiscount(double discount,uint32_t brightness)656 double DisplayPowerMgrService::GetSafeDiscount(double discount, uint32_t brightness)
657 {
658 auto safeDiscount = discount;
659 if (safeDiscount > DISCOUNT_MAX) {
660 DISPLAY_HILOGD(COMP_SVC, "discount value is greater than max, discount=%{public}lf", discount);
661 safeDiscount = DISCOUNT_MAX;
662 }
663 if (safeDiscount < DISCOUNT_MIN) {
664 DISPLAY_HILOGD(COMP_SVC, "discount value is less than min, discount=%{public}lf", discount);
665 safeDiscount = DISCOUNT_MIN;
666 }
667 if (static_cast<uint32_t>(BRIGHTNESS_MIN / safeDiscount) > BRIGHTNESS_MAX) {
668 DISPLAY_HILOGD(COMP_SVC, "brightness than max, brightness=%{public}u, discount=%{public}lf",
669 static_cast<uint32_t>(BRIGHTNESS_MIN / safeDiscount), discount);
670 safeDiscount = static_cast<double>(BRIGHTNESS_MIN / static_cast<double>(brightness));
671 }
672
673 return safeDiscount;
674 }
675
CalculateBrightness(float scalar,int32_t & brightness,int32_t & change)676 bool DisplayPowerMgrService::CalculateBrightness(float scalar, int32_t& brightness, int32_t& change)
677 {
678 const float lastLux = lastLux_;
679 if (!IsChangedLux(scalar)) {
680 return false;
681 }
682 int32_t calcBrightness = GetBrightnessFromLightScalar(scalar);
683 int32_t difference = abs(calcBrightness - brightness);
684 DISPLAY_HILOGD(FEAT_BRIGHTNESS, "lux: %{public}f -> %{public}f, screen: %{public}d -> %{public}d",
685 lastLux, scalar, brightness, calcBrightness);
686 if (difference < BRIGHTNESS_CHANGE_MIN
687 || (scalar > lastLux && calcBrightness < brightness)
688 || (scalar < lastLux && calcBrightness > brightness)) {
689 DISPLAY_HILOGI(FEAT_BRIGHTNESS, "screen is too light/dark when calculated change");
690 return false;
691 }
692 brightness = calcBrightness;
693 change = difference;
694 return true;
695 }
696
GetBrightnessFromLightScalar(float scalar)697 int32_t DisplayPowerMgrService::GetBrightnessFromLightScalar(float scalar)
698 {
699 uint32_t brightness = DisplayAutoBrightness::CalculateAutoBrightness(scalar);
700 DISPLAY_HILOGD(FEAT_BRIGHTNESS, "scalar: %{public}f, brightness: %{public}d", scalar, brightness);
701 if (brightness > BRIGHTNESS_MAX) {
702 brightness = BRIGHTNESS_MAX;
703 } else if (brightness < BRIGHTNESS_MIN) {
704 brightness = BRIGHTNESS_MIN;
705 }
706 return static_cast<int32_t>(brightness);
707 }
708
GetError()709 DisplayErrors DisplayPowerMgrService::GetError()
710 {
711 DisplayErrors tmpError = lastError_;
712 lastError_ = DisplayErrors::ERR_OK;
713 return tmpError;
714 }
715
OnRemoteDied(const wptr<IRemoteObject> & remote)716 void DisplayPowerMgrService::CallbackDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& remote)
717 {
718 DISPLAY_HILOGI(COMP_SVC, "CallbackDeathRecipient OnRemoteDied");
719 auto pms = DelayedSpSingleton<DisplayPowerMgrService>::GetInstance();
720 if (pms == nullptr) {
721 DISPLAY_HILOGI(COMP_SVC, "OnRemoteDied no service");
722 return;
723 }
724
725 std::lock_guard lock(callbackMutex_);
726 pms->callback_ = nullptr;
727 }
728 } // namespace DisplayPowerMgr
729 } // namespace OHOS
730