1 /*
2 * Copyright (c) 2021-2024 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 "miscdevice_service.h"
17
18 #include <algorithm>
19 #include <map>
20 #include <string_ex.h>
21
22 #include "death_recipient_template.h"
23 #ifdef MEMMGR_ENABLE
24 #include "iservice_registry.h"
25 #include "mem_mgr_client.h"
26 #endif // MEMMGR_ENABLE
27 #include "system_ability_definition.h"
28
29 #include "sensors_errors.h"
30 #include "vibration_priority_manager.h"
31
32 #ifdef HDF_DRIVERS_INTERFACE_LIGHT
33 #include "v1_0/light_interface_proxy.h"
34 #endif // HDF_DRIVERS_INTERFACE_LIGHT
35
36 #ifdef OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM
37 #include "parameters.h"
38 #include "default_vibrator_decoder.h"
39 #include "default_vibrator_decoder_factory.h"
40 #include "vibrator_decoder_creator.h"
41 #endif // OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM
42
43 #undef LOG_TAG
44 #define LOG_TAG "MiscdeviceService"
45
46 namespace OHOS {
47 namespace Sensors {
48 namespace {
49 auto g_miscdeviceService = MiscdeviceDelayedSpSingleton<MiscdeviceService>::GetInstance();
50 const bool G_REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(g_miscdeviceService.GetRefPtr());
51 constexpr int32_t MIN_VIBRATOR_TIME = 0;
52 constexpr int32_t MAX_VIBRATOR_TIME = 1800000;
53 constexpr int32_t MIN_VIBRATOR_COUNT = 1;
54 constexpr int32_t MAX_VIBRATOR_COUNT = 1000;
55 constexpr int32_t INTENSITY_MIN = 0;
56 constexpr int32_t INTENSITY_MAX = 100;
57 constexpr int32_t FREQUENCY_MIN = 0;
58 constexpr int32_t FREQUENCY_MAX = 100;
59 constexpr int32_t INTENSITY_ADJUST_MIN = 0;
60 constexpr int32_t INTENSITY_ADJUST_MAX = 100;
61 constexpr int32_t FREQUENCY_ADJUST_MIN = -100;
62 constexpr int32_t FREQUENCY_ADJUST_MAX = 100;
63 constexpr int32_t INVALID_PID = -1;
64 constexpr int32_t VIBRATOR_ID = 0;
65 constexpr int32_t BASE_YEAR = 1900;
66 constexpr int32_t BASE_MON = 1;
67 constexpr int32_t CONVERSION_RATE = 1000;
68 VibratorCapacity g_capacity;
69 #ifdef OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM
70 const std::string PHONE_TYPE = "phone";
71 #endif // OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM
72 } // namespace
73
74 bool MiscdeviceService::isVibrationPriorityReady_ = false;
75
MiscdeviceService()76 MiscdeviceService::MiscdeviceService()
77 : SystemAbility(MISCDEVICE_SERVICE_ABILITY_ID, true),
78 lightExist_(false),
79 vibratorExist_(false),
80 state_(MiscdeviceServiceState::STATE_STOPPED),
81 vibratorThread_(nullptr)
82 {
83 MISC_HILOGD("Add SystemAbility");
84 }
85
~MiscdeviceService()86 MiscdeviceService::~MiscdeviceService()
87 {
88 StopVibrateThread();
89 }
90
OnDump()91 void MiscdeviceService::OnDump()
92 {
93 MISC_HILOGI("Ondump is invoked");
94 }
95
SubscribeCommonEvent(const std::string & eventName,EventReceiver receiver)96 int32_t MiscdeviceService::SubscribeCommonEvent(const std::string &eventName,
97 EventReceiver receiver) __attribute__((no_sanitize("cfi")))
98 {
99 if (receiver == nullptr) {
100 MISC_HILOGE("receiver is nullptr");
101 return ERROR;
102 }
103 EventFwk::MatchingSkills matchingSkills;
104 matchingSkills.AddEvent(eventName);
105 EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
106 auto subscribePtr = std::make_shared<MiscdeviceCommonEventSubscriber>(subscribeInfo, receiver);
107 if (!EventFwk::CommonEventManager::SubscribeCommonEvent(subscribePtr)) {
108 MISC_HILOGE("Subscribe common event fail");
109 return ERROR;
110 }
111 return ERR_OK;
112 }
113
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)114 void MiscdeviceService::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
115 {
116 MISC_HILOGI("OnAddSystemAbility systemAbilityId:%{public}d", systemAbilityId);
117 switch (systemAbilityId) {
118 case MEMORY_MANAGER_SA_ID: {
119 MISC_HILOGI("Memory manager service start");
120 #ifdef MEMMGR_ENABLE
121 Memory::MemMgrClient::GetInstance().NotifyProcessStatus(getpid(),
122 PROCESS_TYPE_SA, PROCESS_STATUS_STARTED, MISCDEVICE_SERVICE_ABILITY_ID);
123 #endif // MEMMGR_ENABLE
124 break;
125 }
126 case COMMON_EVENT_SERVICE_ID: {
127 MISC_HILOGI("Common event service start");
128 int32_t ret = SubscribeCommonEvent("usual.event.DATA_SHARE_READY",
129 std::bind(&MiscdeviceService::OnReceiveEvent, this, std::placeholders::_1));
130 if (ret != ERR_OK) {
131 MISC_HILOGE("Subscribe usual.event.DATA_SHARE_READY fail");
132 }
133 AddSystemAbilityListener(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID);
134 break;
135 }
136 case DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID: {
137 MISC_HILOGI("Distributed kv data service start");
138 std::lock_guard<std::mutex> lock(isVibrationPriorityReadyMutex_);
139 if (PriorityManager->Init()) {
140 MISC_HILOGI("PriorityManager init");
141 isVibrationPriorityReady_ = true;
142 } else {
143 MISC_HILOGE("PriorityManager init fail");
144 }
145 break;
146 }
147 default: {
148 MISC_HILOGI("Unknown service, systemAbilityId:%{public}d", systemAbilityId);
149 break;
150 }
151 }
152 }
153
OnReceiveEvent(const EventFwk::CommonEventData & data)154 void MiscdeviceService::OnReceiveEvent(const EventFwk::CommonEventData &data)
155 {
156 const auto &want = data.GetWant();
157 std::string action = want.GetAction();
158 if (action == "usual.event.DATA_SHARE_READY") {
159 MISC_HILOGI("On receive usual.event.DATA_SHARE_READY");
160 std::lock_guard<std::mutex> lock(isVibrationPriorityReadyMutex_);
161 if (isVibrationPriorityReady_) {
162 MISC_HILOGI("PriorityManager already init");
163 return;
164 }
165 if (PriorityManager->Init()) {
166 MISC_HILOGI("PriorityManager init");
167 isVibrationPriorityReady_ = true;
168 } else {
169 MISC_HILOGE("PriorityManager init fail");
170 }
171 }
172 }
173
OnStart()174 void MiscdeviceService::OnStart()
175 {
176 CALL_LOG_ENTER;
177 if (state_ == MiscdeviceServiceState::STATE_RUNNING) {
178 MISC_HILOGW("state_ already started");
179 return;
180 }
181 if (!InitInterface()) {
182 MISC_HILOGE("Init interface error");
183 }
184 if (!InitLightInterface()) {
185 MISC_HILOGE("InitLightInterface failed");
186 }
187 if (!SystemAbility::Publish(MiscdeviceDelayedSpSingleton<MiscdeviceService>::GetInstance())) {
188 MISC_HILOGE("Publish MiscdeviceService failed");
189 return;
190 }
191 std::lock_guard<std::mutex> lock(miscDeviceIdMapMutex_);
192 auto ret = miscDeviceIdMap_.insert(std::make_pair(MiscdeviceDeviceId::LED, lightExist_));
193 if (!ret.second) {
194 MISC_HILOGI("Light exist in miscDeviceIdMap_");
195 ret.first->second = lightExist_;
196 }
197 ret = miscDeviceIdMap_.insert(std::make_pair(MiscdeviceDeviceId::VIBRATOR, vibratorExist_));
198 if (!ret.second) {
199 MISC_HILOGI("Vibrator exist in miscDeviceIdMap_");
200 ret.first->second = vibratorExist_;
201 }
202 state_ = MiscdeviceServiceState::STATE_RUNNING;
203 #ifdef MEMMGR_ENABLE
204 AddSystemAbilityListener(MEMORY_MANAGER_SA_ID);
205 #endif // MEMMGR_ENABLE
206 AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID);
207 }
208
OnStartFuzz()209 void MiscdeviceService::OnStartFuzz()
210 {
211 CALL_LOG_ENTER;
212 if (state_ == MiscdeviceServiceState::STATE_RUNNING) {
213 MISC_HILOGW("state_ already started");
214 return;
215 }
216 if (!InitInterface()) {
217 MISC_HILOGE("Init interface error");
218 }
219 if (!InitLightInterface()) {
220 MISC_HILOGE("InitLightInterface failed");
221 }
222 std::lock_guard<std::mutex> lock(miscDeviceIdMapMutex_);
223 auto ret = miscDeviceIdMap_.insert(std::make_pair(MiscdeviceDeviceId::LED, lightExist_));
224 if (!ret.second) {
225 MISC_HILOGI("Light exist in miscDeviceIdMap_");
226 ret.first->second = lightExist_;
227 }
228 ret = miscDeviceIdMap_.insert(std::make_pair(MiscdeviceDeviceId::VIBRATOR, vibratorExist_));
229 if (!ret.second) {
230 MISC_HILOGI("Vibrator exist in miscDeviceIdMap_");
231 ret.first->second = vibratorExist_;
232 }
233 state_ = MiscdeviceServiceState::STATE_RUNNING;
234 }
235
InitInterface()236 bool MiscdeviceService::InitInterface()
237 {
238 auto ret = vibratorHdiConnection_.ConnectHdi();
239 if (ret != ERR_OK) {
240 MISC_HILOGE("InitVibratorServiceImpl failed");
241 return false;
242 }
243 if (vibratorHdiConnection_.GetVibratorCapacity(g_capacity) != ERR_OK) {
244 MISC_HILOGE("GetVibratorCapacity failed");
245 }
246 return true;
247 }
248
InitLightInterface()249 bool MiscdeviceService::InitLightInterface()
250 {
251 auto ret = lightHdiConnection_.ConnectHdi();
252 if (ret != ERR_OK) {
253 MISC_HILOGE("ConnectHdi failed");
254 return false;
255 }
256 return true;
257 }
258
IsValid(int32_t lightId)259 bool MiscdeviceService::IsValid(int32_t lightId)
260 {
261 CALL_LOG_ENTER;
262 std::lock_guard<std::mutex> lightInfosLock(lightInfosMutex_);
263 for (const auto &item : lightInfos_) {
264 if (lightId == item.GetLightId()) {
265 return true;
266 }
267 }
268 return false;
269 }
270
IsLightAnimationValid(const LightAnimationIPC & animation)271 bool MiscdeviceService::IsLightAnimationValid(const LightAnimationIPC &animation)
272 {
273 CALL_LOG_ENTER;
274 int32_t mode = animation.GetMode();
275 int32_t onTime = animation.GetOnTime();
276 int32_t offTime = animation.GetOffTime();
277 if ((mode < 0) || (mode >= LIGHT_MODE_BUTT)) {
278 MISC_HILOGE("animation mode is invalid, mode:%{public}d", mode);
279 return false;
280 }
281 if ((onTime < 0) || (offTime < 0)) {
282 MISC_HILOGE("animation onTime or offTime is invalid, onTime:%{public}d, offTime:%{public}d",
283 onTime, offTime);
284 return false;
285 }
286 return true;
287 }
288
OnStop()289 void MiscdeviceService::OnStop()
290 {
291 CALL_LOG_ENTER;
292 if (state_ == MiscdeviceServiceState::STATE_STOPPED) {
293 MISC_HILOGW("MiscdeviceService stopped already");
294 return;
295 }
296 state_ = MiscdeviceServiceState::STATE_STOPPED;
297 int32_t ret = vibratorHdiConnection_.DestroyHdiConnection();
298 if (ret != ERR_OK) {
299 MISC_HILOGE("Destroy hdi connection fail");
300 }
301 #ifdef MEMMGR_ENABLE
302 Memory::MemMgrClient::GetInstance().NotifyProcessStatus(getpid(), PROCESS_TYPE_SA, PROCESS_STATUS_DIED,
303 MISCDEVICE_SERVICE_ABILITY_ID);
304 #endif // MEMMGR_ENABLE
305 }
306
ShouldIgnoreVibrate(const VibrateInfo & info)307 bool MiscdeviceService::ShouldIgnoreVibrate(const VibrateInfo &info)
308 {
309 std::lock_guard<std::mutex> lock(isVibrationPriorityReadyMutex_);
310 if (!isVibrationPriorityReady_) {
311 MISC_HILOGE("Vibraion priority manager not ready");
312 return VIBRATION;
313 }
314 return (PriorityManager->ShouldIgnoreVibrate(info, vibratorThread_) != VIBRATION);
315 }
316
Vibrate(int32_t vibratorId,int32_t timeOut,int32_t usage,bool systemUsage)317 int32_t MiscdeviceService::Vibrate(int32_t vibratorId, int32_t timeOut, int32_t usage, bool systemUsage)
318 {
319 if ((timeOut <= MIN_VIBRATOR_TIME) || (timeOut > MAX_VIBRATOR_TIME)
320 || (usage >= USAGE_MAX) || (usage < 0)) {
321 MISC_HILOGE("Invalid parameter");
322 return PARAMETER_ERROR;
323 }
324 VibrateInfo info = {
325 .mode = VIBRATE_TIME,
326 .packageName = GetPackageName(GetCallingTokenID()),
327 .pid = GetCallingPid(),
328 .uid = GetCallingUid(),
329 .usage = usage,
330 .systemUsage = systemUsage,
331 .duration = timeOut
332 };
333 std::lock_guard<std::mutex> lock(vibratorThreadMutex_);
334 std::string curVibrateTime = GetCurrentTime();
335 if (ShouldIgnoreVibrate(info)) {
336 MISC_HILOGE("%{public}s:vibration is ignored and high priority is vibrating", curVibrateTime.c_str());
337 return ERROR;
338 }
339 StartVibrateThread(info);
340 MISC_HILOGI("Start vibrator, currentTime:%{public}s, package:%{public}s, pid:%{public}d, usage:%{public}d,"
341 "vibratorId:%{public}d, duration:%{public}d", curVibrateTime.c_str(), info.packageName.c_str(), info.pid,
342 info.usage, vibratorId, info.duration);
343 return NO_ERROR;
344 }
345
StopVibrator(int32_t vibratorId)346 int32_t MiscdeviceService::StopVibrator(int32_t vibratorId)
347 {
348 std::lock_guard<std::mutex> lock(vibratorThreadMutex_);
349 #ifdef OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM
350 if ((vibratorThread_ == nullptr) || (!vibratorThread_->IsRunning() &&
351 !vibratorHdiConnection_.IsVibratorRunning())) {
352 MISC_HILOGD("No vibration, no need to stop");
353 return ERROR;
354 }
355 if (vibratorHdiConnection_.IsVibratorRunning()) {
356 vibratorHdiConnection_.Stop(HDF_VIBRATOR_MODE_PRESET);
357 vibratorHdiConnection_.Stop(HDF_VIBRATOR_MODE_HDHAPTIC);
358 }
359 #else
360 if ((vibratorThread_ == nullptr) || (!vibratorThread_->IsRunning())) {
361 MISC_HILOGD("No vibration, no need to stop");
362 return ERROR;
363 }
364 #endif // OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM
365 StopVibrateThread();
366 std::string packageName = GetPackageName(GetCallingTokenID());
367 std::string curVibrateTime = GetCurrentTime();
368 MISC_HILOGI("Stop vibrator, currentTime:%{public}s, package:%{public}s, pid:%{public}d, vibratorId:%{public}d",
369 curVibrateTime.c_str(), packageName.c_str(), GetCallingPid(), vibratorId);
370 return NO_ERROR;
371 }
372
PlayVibratorEffect(int32_t vibratorId,const std::string & effect,int32_t count,int32_t usage,bool systemUsage)373 int32_t MiscdeviceService::PlayVibratorEffect(int32_t vibratorId, const std::string &effect,
374 int32_t count, int32_t usage, bool systemUsage)
375 {
376 if ((count < MIN_VIBRATOR_COUNT) || (count > MAX_VIBRATOR_COUNT) || (usage >= USAGE_MAX) || (usage < 0)) {
377 MISC_HILOGE("Invalid parameter");
378 return PARAMETER_ERROR;
379 }
380 std::optional<HdfEffectInfo> effectInfo = vibratorHdiConnection_.GetEffectInfo(effect);
381 if (!effectInfo) {
382 MISC_HILOGE("GetEffectInfo fail");
383 return ERROR;
384 }
385 if (!(effectInfo->isSupportEffect)) {
386 MISC_HILOGE("Effect not supported");
387 return PARAMETER_ERROR;
388 }
389 VibrateInfo info = {
390 .mode = VIBRATE_PRESET,
391 .packageName = GetPackageName(GetCallingTokenID()),
392 .pid = GetCallingPid(),
393 .uid = GetCallingUid(),
394 .usage = usage,
395 .systemUsage = systemUsage,
396 .duration = effectInfo->duration,
397 .effect = effect,
398 .count = count,
399 .intensity = INTENSITY_ADJUST_MAX
400 };
401 std::lock_guard<std::mutex> lock(vibratorThreadMutex_);
402 std::string curVibrateTime = GetCurrentTime();
403 if (ShouldIgnoreVibrate(info)) {
404 MISC_HILOGE("%{public}s:vibration is ignored and high priority is vibrating", curVibrateTime.c_str());
405 return ERROR;
406 }
407 StartVibrateThread(info);
408 MISC_HILOGI("Start vibrator, currentTime:%{public}s, package:%{public}s, pid:%{public}d, usage:%{public}d,"
409 "vibratorId:%{public}d, duration:%{public}d, effect:%{public}s, count:%{public}d", curVibrateTime.c_str(),
410 info.packageName.c_str(), info.pid, info.usage, vibratorId, info.duration, info.effect.c_str(), info.count);
411 return NO_ERROR;
412 }
413
StartVibrateThread(VibrateInfo info)414 void MiscdeviceService::StartVibrateThread(VibrateInfo info)
415 {
416 if (vibratorThread_ == nullptr) {
417 vibratorThread_ = std::make_shared<VibratorThread>();
418 }
419 StopVibrateThread();
420 #ifdef OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM
421 if (vibratorHdiConnection_.IsVibratorRunning()) {
422 vibratorHdiConnection_.Stop(HDF_VIBRATOR_MODE_PRESET);
423 vibratorHdiConnection_.Stop(HDF_VIBRATOR_MODE_HDHAPTIC);
424 }
425 #endif // OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM
426 vibratorThread_->UpdateVibratorEffect(info);
427 vibratorThread_->Start("VibratorThread");
428 DumpHelper->SaveVibrateRecord(info);
429 }
430
StopVibrateThread()431 void MiscdeviceService::StopVibrateThread()
432 {
433 if ((vibratorThread_ != nullptr) && (vibratorThread_->IsRunning())) {
434 vibratorThread_->SetExitStatus(true);
435 vibratorThread_->WakeUp();
436 vibratorThread_->NotifyExitSync();
437 vibratorThread_->SetExitStatus(false);
438 }
439 }
440
StopVibrator(int32_t vibratorId,const std::string & mode)441 int32_t MiscdeviceService::StopVibrator(int32_t vibratorId, const std::string &mode)
442 {
443 std::lock_guard<std::mutex> lock(vibratorThreadMutex_);
444 if ((vibratorThread_ == nullptr) || (!vibratorThread_->IsRunning())) {
445 MISC_HILOGD("No vibration, no need to stop");
446 return ERROR;
447 }
448 const VibrateInfo info = vibratorThread_->GetCurrentVibrateInfo();
449 if (info.mode != mode) {
450 MISC_HILOGD("Stop vibration information mismatch");
451 return ERROR;
452 }
453 StopVibrateThread();
454 std::string packageName = GetPackageName(GetCallingTokenID());
455 std::string curVibrateTime = GetCurrentTime();
456 MISC_HILOGI("Stop vibrator, currentTime:%{public}s, package:%{public}s, pid:%{public}d, vibratorId:%{public}d,"
457 "mode:%{public}s", curVibrateTime.c_str(), packageName.c_str(), GetCallingPid(), vibratorId, mode.c_str());
458 return NO_ERROR;
459 }
460
IsSupportEffect(const std::string & effect,bool & state)461 int32_t MiscdeviceService::IsSupportEffect(const std::string &effect, bool &state)
462 {
463 std::optional<HdfEffectInfo> effectInfo = vibratorHdiConnection_.GetEffectInfo(effect);
464 if (!effectInfo) {
465 MISC_HILOGE("GetEffectInfo fail");
466 return ERROR;
467 }
468 state = effectInfo->isSupportEffect;
469 return NO_ERROR;
470 }
471
GetCurrentTime()472 std::string MiscdeviceService::GetCurrentTime()
473 {
474 timespec curTime;
475 clock_gettime(CLOCK_REALTIME, &curTime);
476 struct tm *timeinfo = localtime(&(curTime.tv_sec));
477 std::string currentTime;
478 if (timeinfo == nullptr) {
479 MISC_HILOGE("timeinfo is null");
480 return currentTime;
481 }
482 currentTime.append(std::to_string(timeinfo->tm_year + BASE_YEAR)).append("-")
483 .append(std::to_string(timeinfo->tm_mon + BASE_MON)).append("-").append(std::to_string(timeinfo->tm_mday))
484 .append(" ").append(std::to_string(timeinfo->tm_hour)).append(":").append(std::to_string(timeinfo->tm_min))
485 .append(":").append(std::to_string(timeinfo->tm_sec)).append(".")
486 .append(std::to_string(curTime.tv_nsec / (CONVERSION_RATE * CONVERSION_RATE)));
487 return currentTime;
488 }
489
490 #ifdef OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM
PlayVibratorCustom(int32_t vibratorId,const RawFileDescriptor & rawFd,int32_t usage,bool systemUsage,const VibrateParameter & parameter)491 int32_t MiscdeviceService::PlayVibratorCustom(int32_t vibratorId, const RawFileDescriptor &rawFd, int32_t usage,
492 bool systemUsage, const VibrateParameter ¶meter)
493 {
494 if (!(g_capacity.isSupportHdHaptic || g_capacity.isSupportPresetMapping || g_capacity.isSupportTimeDelay)) {
495 MISC_HILOGE("The device does not support this operation");
496 return IS_NOT_SUPPORTED;
497 }
498 if ((usage >= USAGE_MAX) || (usage < 0) || (!CheckVibratorParmeters(parameter))) {
499 MISC_HILOGE("Invalid parameter, usage:%{public}d", usage);
500 return PARAMETER_ERROR;
501 }
502 JsonParser parser(rawFd);
503 VibratorDecoderCreator creator;
504 std::unique_ptr<IVibratorDecoder> decoder(creator.CreateDecoder(parser));
505 CHKPR(decoder, ERROR);
506 VibratePackage package;
507 int32_t ret = decoder->DecodeEffect(rawFd, parser, package);
508 if (ret != SUCCESS || package.patterns.empty()) {
509 MISC_HILOGE("Decode effect error");
510 return ERROR;
511 }
512 MergeVibratorParmeters(parameter, package);
513 package.Dump();
514 VibrateInfo info = {
515 .packageName = GetPackageName(GetCallingTokenID()),
516 .pid = GetCallingPid(),
517 .uid = GetCallingUid(),
518 .usage = usage,
519 .systemUsage = systemUsage,
520 .package = package,
521 };
522 if (g_capacity.isSupportHdHaptic) {
523 info.mode = VIBRATE_CUSTOM_HD;
524 } else if (g_capacity.isSupportPresetMapping) {
525 info.mode = VIBRATE_CUSTOM_COMPOSITE_EFFECT;
526 } else if (g_capacity.isSupportTimeDelay) {
527 info.mode = VIBRATE_CUSTOM_COMPOSITE_TIME;
528 }
529 std::lock_guard<std::mutex> lock(vibratorThreadMutex_);
530 std::string curVibrateTime = GetCurrentTime();
531 if (ShouldIgnoreVibrate(info)) {
532 MISC_HILOGE("%{public}s:vibration is ignored and high priority is vibrating", curVibrateTime.c_str());
533 return ERROR;
534 }
535 StartVibrateThread(info);
536 MISC_HILOGI("Start vibrator, currentTime:%{public}s, package:%{public}s, pid:%{public}d, usage:%{public}d,"
537 "vibratorId:%{public}d, duration:%{public}d", curVibrateTime.c_str(), info.packageName.c_str(), info.pid,
538 info.usage, vibratorId, package.packageDuration);
539 return NO_ERROR;
540 }
541 #endif // OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM
542
GetPackageName(AccessTokenID tokenId)543 std::string MiscdeviceService::GetPackageName(AccessTokenID tokenId)
544 {
545 std::string packageName;
546 int32_t tokenType = AccessTokenKit::GetTokenTypeFlag(tokenId);
547 switch (tokenType) {
548 case ATokenTypeEnum::TOKEN_HAP: {
549 HapTokenInfo hapInfo;
550 if (AccessTokenKit::GetHapTokenInfo(tokenId, hapInfo) != 0) {
551 MISC_HILOGE("Get hap token info fail");
552 return {};
553 }
554 packageName = hapInfo.bundleName;
555 break;
556 }
557 case ATokenTypeEnum::TOKEN_NATIVE:
558 case ATokenTypeEnum::TOKEN_SHELL: {
559 NativeTokenInfo tokenInfo;
560 if (AccessTokenKit::GetNativeTokenInfo(tokenId, tokenInfo) != 0) {
561 MISC_HILOGE("Get native token info fail");
562 return {};
563 }
564 packageName = tokenInfo.processName;
565 break;
566 }
567 default: {
568 MISC_HILOGW("Token type not match");
569 break;
570 }
571 }
572 return packageName;
573 }
574
GetLightList()575 std::vector<LightInfoIPC> MiscdeviceService::GetLightList()
576 {
577 std::lock_guard<std::mutex> lightInfosLock(lightInfosMutex_);
578 std::string packageName = GetPackageName(GetCallingTokenID());
579 MISC_HILOGI("GetLightList, package:%{public}s", packageName.c_str());
580 int32_t ret = lightHdiConnection_.GetLightList(lightInfos_);
581 if (ret != ERR_OK) {
582 MISC_HILOGE("GetLightList failed, ret:%{public}d", ret);
583 }
584 return lightInfos_;
585 }
586
TurnOn(int32_t lightId,const LightColor & color,const LightAnimationIPC & animation)587 int32_t MiscdeviceService::TurnOn(int32_t lightId, const LightColor &color, const LightAnimationIPC &animation)
588 {
589 std::string packageName = GetPackageName(GetCallingTokenID());
590 MISC_HILOGI("TurnOn, package:%{public}s", packageName.c_str());
591 if (!IsValid(lightId)) {
592 MISC_HILOGE("lightId is invalid, lightId:%{public}d", lightId);
593 return MISCDEVICE_NATIVE_SAM_ERR;
594 }
595 if (!IsLightAnimationValid(animation)) {
596 MISC_HILOGE("animation is invalid");
597 return MISCDEVICE_NATIVE_SAM_ERR;
598 }
599 int32_t ret = lightHdiConnection_.TurnOn(lightId, color, animation);
600 if (ret != ERR_OK) {
601 MISC_HILOGE("TurnOn failed, error:%{public}d", ret);
602 return ERROR;
603 }
604 return ret;
605 }
606
TurnOff(int32_t lightId)607 int32_t MiscdeviceService::TurnOff(int32_t lightId)
608 {
609 std::string packageName = GetPackageName(GetCallingTokenID());
610 MISC_HILOGI("TurnOff, package:%{public}s", packageName.c_str());
611 if (!IsValid(lightId)) {
612 MISC_HILOGE("lightId is invalid, lightId:%{public}d", lightId);
613 return MISCDEVICE_NATIVE_SAM_ERR;
614 }
615 int32_t ret = lightHdiConnection_.TurnOff(lightId);
616 if (ret != ERR_OK) {
617 MISC_HILOGE("TurnOff failed, error:%{public}d", ret);
618 return ERROR;
619 }
620 return ret;
621 }
622
Dump(int32_t fd,const std::vector<std::u16string> & args)623 int32_t MiscdeviceService::Dump(int32_t fd, const std::vector<std::u16string> &args)
624 {
625 CALL_LOG_ENTER;
626 if (fd < 0) {
627 MISC_HILOGE("Invalid fd");
628 return DUMP_PARAM_ERR;
629 }
630 if (args.empty()) {
631 MISC_HILOGE("args cannot be empty");
632 dprintf(fd, "args cannot be empty\n");
633 DumpHelper->DumpHelp(fd);
634 return DUMP_PARAM_ERR;
635 }
636 std::vector<std::string> argList = { "" };
637 std::transform(args.begin(), args.end(), std::back_inserter(argList),
638 [](const std::u16string &arg) {
639 return Str16ToStr8(arg);
640 });
641 DumpHelper->ParseCommand(fd, argList);
642 return ERR_OK;
643 }
644
PlayPattern(const VibratePattern & pattern,int32_t usage,bool systemUsage,const VibrateParameter & parameter)645 int32_t MiscdeviceService::PlayPattern(const VibratePattern &pattern, int32_t usage,
646 bool systemUsage, const VibrateParameter ¶meter)
647 {
648 if ((usage >= USAGE_MAX) || (usage < 0) || (!CheckVibratorParmeters(parameter))) {
649 MISC_HILOGE("Invalid parameter, usage:%{public}d", usage);
650 return PARAMETER_ERROR;
651 }
652 VibratePattern vibratePattern = {
653 .startTime = 0,
654 .events = pattern.events
655 };
656 std::vector<VibratePattern> patterns = {vibratePattern};
657 VibratePackage package = {
658 .patterns = patterns
659 };
660 MergeVibratorParmeters(parameter, package);
661 package.Dump();
662 VibrateInfo info = {
663 .mode = VIBRATE_BUTT,
664 .packageName = GetPackageName(GetCallingTokenID()),
665 .pid = GetCallingPid(),
666 .uid = GetCallingUid(),
667 .usage = usage,
668 .systemUsage = systemUsage
669 };
670 if (g_capacity.isSupportHdHaptic) {
671 std::lock_guard<std::mutex> lock(vibratorThreadMutex_);
672 std::string curVibrateTime = GetCurrentTime();
673 if (ShouldIgnoreVibrate(info)) {
674 MISC_HILOGE("%{public}s:vibration is ignored and high priority is vibrating", curVibrateTime.c_str());
675 return ERROR;
676 }
677 StartVibrateThread(info);
678 return vibratorHdiConnection_.PlayPattern(package.patterns.front());
679 } else if (g_capacity.isSupportPresetMapping) {
680 info.mode = VIBRATE_CUSTOM_COMPOSITE_EFFECT;
681 } else if (g_capacity.isSupportTimeDelay) {
682 info.mode = VIBRATE_CUSTOM_COMPOSITE_TIME;
683 }
684 info.package = package;
685 std::lock_guard<std::mutex> lock(vibratorThreadMutex_);
686 std::string curVibrateTime = GetCurrentTime();
687 if (ShouldIgnoreVibrate(info)) {
688 MISC_HILOGE("%{public}s:vibration is ignored and high priority is vibrating", curVibrateTime.c_str());
689 return ERROR;
690 }
691 StartVibrateThread(info);
692 MISC_HILOGI("Start vibrator, currentTime:%{public}s, package:%{public}s, pid:%{public}d, usage:%{public}d,"
693 "duration:%{public}d", curVibrateTime.c_str(), info.packageName.c_str(), info.pid, info.usage,
694 pattern.patternDuration);
695 return ERR_OK;
696 }
697
GetDelayTime(int32_t & delayTime)698 int32_t MiscdeviceService::GetDelayTime(int32_t &delayTime)
699 {
700 std::string packageName = GetPackageName(GetCallingTokenID());
701 MISC_HILOGD("GetDelayTime, package:%{public}s", packageName.c_str());
702 return vibratorHdiConnection_.GetDelayTime(g_capacity.GetVibrateMode(), delayTime);
703 }
704
CheckVibratorParmeters(const VibrateParameter & parameter)705 bool MiscdeviceService::CheckVibratorParmeters(const VibrateParameter ¶meter)
706 {
707 if ((parameter.intensity < INTENSITY_ADJUST_MIN) || (parameter.intensity > INTENSITY_ADJUST_MAX) ||
708 (parameter.frequency < FREQUENCY_ADJUST_MIN) || (parameter.frequency > FREQUENCY_ADJUST_MAX)) {
709 MISC_HILOGE("Input invalid, intensity parameter is %{public}d, frequency parameter is %{public}d",
710 parameter.intensity, parameter.frequency);
711 return false;
712 }
713 return true;
714 }
715
MergeVibratorParmeters(const VibrateParameter & parameter,VibratePackage & package)716 void MiscdeviceService::MergeVibratorParmeters(const VibrateParameter ¶meter, VibratePackage &package)
717 {
718 if ((parameter.intensity == INTENSITY_ADJUST_MAX) && (parameter.frequency == 0)) {
719 MISC_HILOGD("The adjust parameter is not need to merge");
720 return;
721 }
722 parameter.Dump();
723 for (VibratePattern &pattern : package.patterns) {
724 for (VibrateEvent &event : pattern.events) {
725 float intensityScale = static_cast<float>(parameter.intensity) / INTENSITY_ADJUST_MAX;
726 if ((event.tag == EVENT_TAG_TRANSIENT) || (event.points.empty())) {
727 event.intensity = static_cast<int32_t>(event.intensity * intensityScale);
728 event.intensity = std::max(std::min(event.intensity, INTENSITY_MAX), INTENSITY_MIN);
729 event.frequency = event.frequency + parameter.frequency;
730 event.frequency = std::max(std::min(event.frequency, FREQUENCY_MAX), FREQUENCY_MIN);
731 } else {
732 for (VibrateCurvePoint &point : event.points) {
733 point.intensity = static_cast<int32_t>(point.intensity * intensityScale);
734 point.intensity = std::max(std::min(point.intensity, INTENSITY_ADJUST_MAX), INTENSITY_ADJUST_MIN);
735 point.frequency = point.frequency + parameter.frequency;
736 point.frequency = std::max(std::min(point.frequency, FREQUENCY_ADJUST_MAX), FREQUENCY_ADJUST_MIN);
737 }
738 }
739 }
740 }
741 }
742
TransferClientRemoteObject(const sptr<IRemoteObject> & vibratorServiceClient)743 int32_t MiscdeviceService::TransferClientRemoteObject(const sptr<IRemoteObject> &vibratorServiceClient)
744 {
745 auto clientPid = GetCallingPid();
746 if (clientPid < 0) {
747 MISC_HILOGE("ClientPid is invalid, clientPid:%{public}d", clientPid);
748 return ERROR;
749 }
750 RegisterClientDeathRecipient(vibratorServiceClient, clientPid);
751 return ERR_OK;
752 }
753
ProcessDeathObserver(const wptr<IRemoteObject> & object)754 void MiscdeviceService::ProcessDeathObserver(const wptr<IRemoteObject> &object)
755 {
756 CALL_LOG_ENTER;
757 sptr<IRemoteObject> client = object.promote();
758 int32_t clientPid = FindClientPid(client);
759 VibrateInfo info;
760 {
761 std::lock_guard<std::mutex> lock(vibratorThreadMutex_);
762 if (vibratorThread_ == nullptr) {
763 vibratorThread_ = std::make_shared<VibratorThread>();
764 }
765 info = vibratorThread_->GetCurrentVibrateInfo();
766 }
767 int32_t vibratePid = info.pid;
768 MISC_HILOGI("ClientPid:%{public}d, VibratePid:%{public}d", clientPid, vibratePid);
769 if ((clientPid != INVALID_PID) && (clientPid == vibratePid)) {
770 StopVibrator(VIBRATOR_ID);
771 }
772 UnregisterClientDeathRecipient(client);
773 }
774
RegisterClientDeathRecipient(sptr<IRemoteObject> vibratorServiceClient,int32_t pid)775 void MiscdeviceService::RegisterClientDeathRecipient(sptr<IRemoteObject> vibratorServiceClient, int32_t pid)
776 {
777 if (vibratorServiceClient == nullptr) {
778 MISC_HILOGE("VibratorServiceClient is nullptr");
779 return;
780 }
781 std::lock_guard<std::mutex> lock(clientDeathObserverMutex_);
782 if (clientDeathObserver_ == nullptr) {
783 clientDeathObserver_ = new (std::nothrow) DeathRecipientTemplate(*const_cast<MiscdeviceService *>(this));
784 if (clientDeathObserver_ == nullptr) {
785 MISC_HILOGE("ClientDeathObserver_ is nullptr");
786 return;
787 }
788 }
789 vibratorServiceClient->AddDeathRecipient(clientDeathObserver_);
790 SaveClientPid(vibratorServiceClient, pid);
791 }
792
UnregisterClientDeathRecipient(sptr<IRemoteObject> vibratorServiceClient)793 void MiscdeviceService::UnregisterClientDeathRecipient(sptr<IRemoteObject> vibratorServiceClient)
794 {
795 if (vibratorServiceClient == nullptr) {
796 MISC_HILOGE("vibratorServiceClient is nullptr");
797 return;
798 }
799 int32_t clientPid = FindClientPid(vibratorServiceClient);
800 if (clientPid == INVALID_PID) {
801 MISC_HILOGE("Pid is invalid");
802 return;
803 }
804 std::lock_guard<std::mutex> lock(clientDeathObserverMutex_);
805 vibratorServiceClient->RemoveDeathRecipient(clientDeathObserver_);
806 DestroyClientPid(vibratorServiceClient);
807 }
808
SaveClientPid(const sptr<IRemoteObject> & vibratorServiceClient,int32_t pid)809 void MiscdeviceService::SaveClientPid(const sptr<IRemoteObject> &vibratorServiceClient, int32_t pid)
810 {
811 if (vibratorServiceClient == nullptr) {
812 MISC_HILOGE("VibratorServiceClient is nullptr");
813 return;
814 }
815 std::lock_guard<std::mutex> lock(clientPidMapMutex_);
816 clientPidMap_.insert(std::make_pair(vibratorServiceClient, pid));
817 }
818
FindClientPid(const sptr<IRemoteObject> & vibratorServiceClient)819 int32_t MiscdeviceService::FindClientPid(const sptr<IRemoteObject> &vibratorServiceClient)
820 {
821 if (vibratorServiceClient == nullptr) {
822 MISC_HILOGE("VibratorServiceClient is nullptr");
823 return INVALID_PID;
824 }
825 std::lock_guard<std::mutex> lock(clientPidMapMutex_);
826 auto it = clientPidMap_.find(vibratorServiceClient);
827 if (it == clientPidMap_.end()) {
828 MISC_HILOGE("Cannot find client pid");
829 return INVALID_PID;
830 }
831 return it->second;
832 }
833
DestroyClientPid(const sptr<IRemoteObject> & vibratorServiceClient)834 void MiscdeviceService::DestroyClientPid(const sptr<IRemoteObject> &vibratorServiceClient)
835 {
836 if (vibratorServiceClient == nullptr) {
837 MISC_HILOGD("VibratorServiceClient is nullptr");
838 return;
839 }
840 std::lock_guard<std::mutex> lock(clientPidMapMutex_);
841 auto it = clientPidMap_.find(vibratorServiceClient);
842 if (it == clientPidMap_.end()) {
843 MISC_HILOGE("Cannot find client pid");
844 return;
845 }
846 clientPidMap_.erase(it);
847 }
848
PlayPrimitiveEffect(int32_t vibratorId,const std::string & effect,int32_t intensity,int32_t usage,bool systemUsage,int32_t count)849 int32_t MiscdeviceService::PlayPrimitiveEffect(int32_t vibratorId, const std::string &effect,
850 int32_t intensity, int32_t usage, bool systemUsage, int32_t count)
851 {
852 if ((intensity <= INTENSITY_MIN) || (intensity > INTENSITY_MAX) || (usage >= USAGE_MAX) || (usage < 0)) {
853 MISC_HILOGE("Invalid parameter");
854 return PARAMETER_ERROR;
855 }
856 std::optional<HdfEffectInfo> effectInfo = vibratorHdiConnection_.GetEffectInfo(effect);
857 if (!effectInfo) {
858 MISC_HILOGE("GetEffectInfo fail");
859 return ERROR;
860 }
861 if (!(effectInfo->isSupportEffect)) {
862 MISC_HILOGE("Effect not supported");
863 return PARAMETER_ERROR;
864 }
865 VibrateInfo info = {
866 .mode = VIBRATE_PRESET,
867 .packageName = GetPackageName(GetCallingTokenID()),
868 .pid = GetCallingPid(),
869 .uid = GetCallingUid(),
870 .usage = usage,
871 .systemUsage = systemUsage,
872 .duration = effectInfo->duration,
873 .effect = effect,
874 .count = count,
875 .intensity = intensity
876 };
877 std::lock_guard<std::mutex> lock(vibratorThreadMutex_);
878 std::string curVibrateTime = GetCurrentTime();
879 if (ShouldIgnoreVibrate(info)) {
880 MISC_HILOGE("%{public}s:vibration is ignored and high priority is vibrating", curVibrateTime.c_str());
881 return ERROR;
882 }
883 StartVibrateThread(info);
884 MISC_HILOGI("Start vibrator, currentTime:%{public}s, package:%{public}s, pid:%{public}d, usage:%{public}d,"
885 "vibratorId:%{public}d, duration:%{public}d, effect:%{public}s", curVibrateTime.c_str(),
886 info.packageName.c_str(), info.pid, info.usage, vibratorId, info.duration, info.effect.c_str());
887 return NO_ERROR;
888 }
889
GetVibratorCapacity(VibratorCapacity & capacity)890 int32_t MiscdeviceService::GetVibratorCapacity(VibratorCapacity &capacity)
891 {
892 capacity = g_capacity;
893 return ERR_OK;
894 }
895 } // namespace Sensors
896 } // namespace OHOS
897