diff --git a/frameworks/js/napi/vibrator/include/vibrator_napi_utils.h b/frameworks/js/napi/vibrator/include/vibrator_napi_utils.h index 3cb87e75766449e1e0ca122745f6bc852a2bd64f..6302cd280b206689ea98cba617a0e54d91d9ad90 100644 --- a/frameworks/js/napi/vibrator/include/vibrator_napi_utils.h +++ b/frameworks/js/napi/vibrator/include/vibrator_napi_utils.h @@ -34,10 +34,21 @@ using std::string; constexpr int32_t CALLBACK_NUM = 3; constexpr uint32_t STRING_LENGTH_MAX = 64; +#define CHKNRF(env, state, message) \ + do { \ + if ((state) != napi_ok) { \ + MISC_HILOGE("(%{public}s) fail", #message); \ + return false; \ + } \ + } while (0) + enum CallbackType { SYSTEM_VIBRATE_CALLBACK = 1, COMMON_CALLBACK, IS_SUPPORT_EFFECT_CALLBACK, + GET_VIBRATOR_INFO_LIST, + GET_EFFECT_INFO, + VIBRATOR_STATE_CHANGE, }; struct VibrateInfo { @@ -71,6 +82,10 @@ public: AsyncCallbackError error; CallbackType callbackType = COMMON_CALLBACK; bool isSupportEffect {false}; + std::vector vibratorInfos; + int32_t arrayLength; + EffectInfo effectInfo; + VibratorDeviceInfo deviceInfo; std::string flag; AsyncCallbackInfo(napi_env env) : env(env) {} ~AsyncCallbackInfo(); @@ -80,6 +95,9 @@ using ConstructResultFunc = bool(*)(const napi_env &env, sptr napi_value result[], int32_t length); bool CreateInt32Property(napi_env env, napi_value &eventObj, const char* name, int32_t value); +bool CreateStringProperty(napi_env env, napi_value &eventObj, const char* name, + const char* value, int32_t valueLength); +bool CreateBooleanProperty(napi_env env, napi_value &eventObj, const char* name, bool value); bool IsMatchArrayType(const napi_env &env, const napi_value &value); bool IsMatchType(const napi_env &env, const napi_value &value, const napi_valuetype &type); bool GetNapiInt32(const napi_env &env, const int32_t value, napi_value &result); @@ -94,10 +112,18 @@ bool GetPropertyInt32(const napi_env &env, const napi_value &value, const std::s bool GetPropertyInt64(const napi_env &env, const napi_value &value, const std::string &type, int64_t &result); bool GetNapiParam(const napi_env &env, const napi_callback_info &info, size_t &argc, napi_value &argv); bool ConvertErrorToResult(const napi_env &env, sptr asyncCallbackInfo, napi_value &result); +napi_value ConvertToJsVibratorInfo(const napi_env& env, const VibratorInfos& vibratorInfo); +napi_value ConvertToJsEffectInfo(const napi_env& env, const EffectInfo& effectInfo); bool ConstructCommonResult(const napi_env &env, sptr asyncCallbackInfo, napi_value result[], int32_t length); bool ConstructIsSupportEffectResult(const napi_env &env, sptr asyncCallbackInfo, napi_value result[], int32_t length); +bool ConstructGetVibratorInfoListResult(const napi_env &env, sptr asyncCallbackInfo, + napi_value result[], int32_t length); +bool ConstructIsSupportEffectInfoResult(const napi_env &env, sptr asyncCallbackInfo, + napi_value result[], int32_t length); +bool ConstructVibratorPlugInfoResult(const napi_env &env, sptr asyncCallbackInfo, + napi_value result[], int32_t length); void EmitAsyncCallbackWork(sptr async_callback_info); void EmitPromiseWork(sptr asyncCallbackInfo); bool ClearVibratorPattern(VibratorPattern &vibratorPattern); diff --git a/frameworks/js/napi/vibrator/src/vibrator_js.cpp b/frameworks/js/napi/vibrator/src/vibrator_js.cpp index 0273505f2d449cba8ca11e660250c682cd2b6ff7..ac3cdc0e897e29a684cbdea5294fad122275275e 100644 --- a/frameworks/js/napi/vibrator/src/vibrator_js.cpp +++ b/frameworks/js/napi/vibrator/src/vibrator_js.cpp @@ -68,6 +68,9 @@ static std::map g_usageType = { }; static std::set g_allowedTypes = {"time", "preset", "file", "pattern"}; +static std::map>> g_onCallbackInfos; +static std::mutex g_Mutex; +static std::mutex g_plugCallbackMutex; static napi_value EmitAsyncWork(napi_value param, sptr info) { @@ -84,6 +87,7 @@ static napi_value EmitAsyncWork(napi_value param, sptr info) } napi_deferred deferred = nullptr; napi_value promise = nullptr; + MISC_HILOGD("this is promise task"); status = napi_create_promise(info->env, &deferred, &promise); if (status != napi_ok) { MISC_HILOGE("napi_create_promise fail"); @@ -383,9 +387,21 @@ static bool CheckVibratorPatternParameter(VibratorPattern &vibratorPattern) return true; } -bool ParseParameter(napi_env env, napi_value args[], size_t argc, VibrateInfo &info) +bool ParseVibratorIdentifier(napi_env env, napi_value value, VibratorIdentifier &identifier) { - CHKCF((argc >= PARAMETER_TWO), "Wrong argument number"); + CALL_LOG_ENTER; + bool deviceIdResult = GetPropertyInt32(env, value, "deviceId", identifier.deviceId); + bool vibratorIdResult = GetPropertyInt32(env, value, "vibratorId", identifier.vibratorId); + if(deviceIdResult || vibratorIdResult) { + MISC_HILOGI("Get vibrate identifier success"); + return true; + } + return false; +} + +bool ParseParameter(napi_env env, napi_value args[], size_t argc, VibrateInfo &info, VibratorIdentifier &identifier) +{ + CHKCF((argc >= PARAMETER_THREE), "Wrong argument number"); CHKCF(GetPropertyString(env, args[0], "type", info.type), "Get vibrate type fail"); if (info.type == "time") { CHKCF(GetPropertyInt32(env, args[0], "duration", info.duration), "Get vibrate duration fail"); @@ -416,22 +432,28 @@ bool ParseParameter(napi_env env, napi_value args[], size_t argc, VibrateInfo &i if (!GetPropertyBool(env, args[1], "systemUsage", info.systemUsage)) { info.systemUsage = false; } + if (!GetPropertyInt32(env, args[1], "deviceId", identifier.deviceId)) { + identifier.deviceId = -1; + } + if (!GetPropertyInt32(env, args[1], "id", identifier.vibratorId)) { + identifier.vibratorId = -1; + } return true; } -bool SetUsage(const std::string &usage, bool systemUsage) +bool SetUsage(const VibratorIdentifier &identifier, const std::string &usage, bool systemUsage) { if (auto iter = g_usageType.find(usage); iter == g_usageType.end()) { MISC_HILOGE("Wrong usage type"); return false; } - return SetUsage(g_usageType[usage], systemUsage); + return SetUsageEnhanced(identifier, g_usageType[usage], systemUsage); } -int32_t CheckParameters(const VibrateInfo &info) +int32_t CheckParameters(const VibrateInfo &info, const VibratorIdentifier &identifier) { CALL_LOG_ENTER; - if (!SetUsage(info.usage, info.systemUsage)) { + if (!SetUsage(identifier, info.usage, info.systemUsage)) { MISC_HILOGE("SetUsage fail"); return PARAMETER_ERROR; } @@ -442,32 +464,34 @@ int32_t CheckParameters(const VibrateInfo &info) return ERR_OK; } -int32_t StartVibrate(const VibrateInfo &info) +int32_t StartVibrate(const VibrateInfo &info, const VibratorIdentifier &identifier) { CALL_LOG_ENTER; - if (CheckParameters(info) != ERR_OK) { + if (CheckParameters(info, identifier) != ERR_OK) { MISC_HILOGE("CheckParameters fail"); return PARAMETER_ERROR; } if (info.type == "file") { - return PlayVibratorCustom(info.fd, info.offset, info.length); + return PlayVibratorCustomEnhanced(identifier, info.fd, info.offset, info.length); } else if (info.type == "pattern") { - return PlayPattern(info.vibratorPattern); + return PlayPatternEnhanced(identifier, info.vibratorPattern); } - return StartVibratorOnce(info.duration); + return StartVibratorOnceEnhanced(identifier, info.duration); } static napi_value VibrateEffect(napi_env env, napi_value args[], size_t argc) { sptr asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo(env); CHKPP(asyncCallbackInfo); - if (!ParseParameter(env, args, argc, asyncCallbackInfo->info)) { + VibratorIdentifier identifier; + if (!ParseParameter(env, args, argc, asyncCallbackInfo->info, identifier)) { MISC_HILOGE("ParseParameter fail"); ThrowErr(env, PARAMETER_ERROR, "ParseParameter fail"); return nullptr; } if (asyncCallbackInfo->info.type == "preset") { - if (!SetLoopCount(asyncCallbackInfo->info.count) || CheckParameters(asyncCallbackInfo->info) != ERR_OK || + if (!SetLoopCountEnhanced(identifier, asyncCallbackInfo->info.count) || + CheckParameters(asyncCallbackInfo->info, identifier) != ERR_OK || asyncCallbackInfo->info.effectId.empty()) { MISC_HILOGE("SetLoopCount fail or parameter invalid"); ThrowErr(env, PARAMETER_ERROR, "SetLoopCount fail or parameter invalid"); @@ -475,7 +499,7 @@ static napi_value VibrateEffect(napi_env env, napi_value args[], size_t argc) } asyncCallbackInfo->flag = "preset"; } else { - asyncCallbackInfo->error.code = StartVibrate(asyncCallbackInfo->info); + asyncCallbackInfo->error.code = StartVibrate(asyncCallbackInfo->info, identifier); if (asyncCallbackInfo->info.vibratorPattern.events != nullptr) { CHKCP(ClearVibratorPattern(asyncCallbackInfo->info.vibratorPattern), "ClearVibratorPattern fail"); } @@ -533,33 +557,46 @@ static napi_value Vibrate(napi_env env, napi_callback_info info) static napi_value Cancel(napi_env env, napi_callback_info info) { - size_t argc = 1; - napi_value args[1] = {}; + size_t argc = 2; + napi_value args[2] = {}; napi_value thisArg = nullptr; napi_status status = napi_get_cb_info(env, info, &argc, args, &thisArg, nullptr); if (status != napi_ok) { ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail"); return nullptr; } + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1 + }; sptr asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo(env); CHKPP(asyncCallbackInfo); - asyncCallbackInfo->error.code = Cancel(); if ((argc > 0) && (IsMatchType(env, args[0], napi_function))) { + asyncCallbackInfo->error.code = CancelEnhanced(identifier); return EmitAsyncWork(args[0], asyncCallbackInfo); + }else if((argc > 0) && IsMatchType(env, args[0], napi_object) && ParseVibratorIdentifier(env, args[0], identifier)) { + asyncCallbackInfo->error.code = CancelEnhanced(identifier); + return EmitAsyncWork(nullptr, asyncCallbackInfo); + }else { + asyncCallbackInfo->error.code = CancelEnhanced(identifier); + return EmitAsyncWork(nullptr, asyncCallbackInfo); } - return EmitAsyncWork(nullptr, asyncCallbackInfo); } static napi_value Stop(napi_env env, napi_callback_info info) { - size_t argc = 2; - napi_value args[2] = {}; + size_t argc = 3; + napi_value args[3] = {}; napi_value thisArg = nullptr; napi_status status = napi_get_cb_info(env, info, &argc, args, &thisArg, nullptr); if (status != napi_ok) { ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail"); return nullptr; } + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1 + }; if (argc >= 1 && IsMatchType(env, args[0], napi_string)) { string mode; if (!GetStringValue(env, args[0], mode)) { @@ -568,7 +605,7 @@ static napi_value Stop(napi_env env, napi_callback_info info) } sptr asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo(env); CHKPP(asyncCallbackInfo); - asyncCallbackInfo->error.code = StopVibrator(mode.c_str()); + asyncCallbackInfo->error.code = StopVibratorEnhanced(identifier, mode.c_str()); if ((asyncCallbackInfo->error.code != SUCCESS) && (asyncCallbackInfo->error.code == PARAMETER_ERROR)) { ThrowErr(env, PARAMETER_ERROR, "Parameters invalid"); return nullptr; @@ -748,6 +785,325 @@ static napi_value CreateEnumEffectId(const napi_env env, const napi_value export return exports; } +static napi_value GetVibratorListSync(napi_env env, napi_callback_info info) +{ + CALL_LOG_ENTER; + size_t argc = 1; + napi_value args[1] = {0}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr)); + + VibratorIdentifier identifier; + if (argc > 0) { + if (!ParseVibratorIdentifier(env, args[0], identifier)) { + MISC_HILOGW("deviceId and vibratorId is undefined, set default value deviceId = -1 and vibratorId = -1"); + } + MISC_HILOGD("identifier=[deviceId=%{public}d, vibratorId=%{pubilc}d]", + identifier.deviceId, identifier.vibratorId); + } + napi_value jsArray = nullptr; + NAPI_CALL(env, napi_create_array(env, &jsArray)); + std::vector vibratorInfo; + int32_t ret = GetVibratorIdList(identifier, vibratorInfo); + if (ret == SUCCESS) { + int32_t length = 0; + for (auto& info : vibratorInfo) { + napi_value jsInfo = ConvertToJsVibratorInfo(env, info); + NAPI_CALL(env, napi_set_element(env, jsArray, length++, jsInfo)); + } + } else { + ThrowErr(env, ret, "Failed to get vibrator list"); + return nullptr; + } + return jsArray; +} + +// static napi_value GetVibratorList(napi_env env, napi_callback_info info) +// { +// CALL_LOG_ENTER; +// size_t argc = 1; +// napi_value args[2] = {0}; +// NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr)); + +// VibratorIdentifier identifier; +// if (argc > 0) { +// if (!ParseVibratorIdentifier(env, args[0], identifier)) { +// MISC_HILOGW("deviceId and vibratorId is undefined, set default value deviceId = -1 and vibratorId = -1"); +// } +// MISC_HILOGD("identifier=[deviceId=%{public}d, vibratorId=%{pubilc}d]", identifier.deviceId, identifier.vibratorId); +// } + +// sptr asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo(env); +// CHKPP(asyncCallbackInfo); +// asyncCallbackInfo->callbackType = GET_VIBRATOR_INFO_LIST; +// asyncCallbackInfo->error.code = GetVibratorIdList(identifier, asyncCallbackInfo->vibratorInfos); +// if ((argc > 0) && IsMatchType(env, args[1], napi_function)) { +// return EmitAsyncWork(args[1], asyncCallbackInfo); +// } +// return EmitAsyncWork(nullptr, asyncCallbackInfo); +// } + +static napi_value GetSupportEffectInfoSync(napi_env env, napi_callback_info info) +{ + CALL_LOG_ENTER; + size_t argc = 2; + napi_value args[2] = {0}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr)); + if ((argc == 0) || !IsMatchType(env, args[0], napi_string)) { + MISC_HILOGW("Parameter error, expect string"); + return nullptr; + } + std::vector buffer(STRING_LENGTH_MAX); + NAPI_CALL(env, napi_get_value_string_utf8(env, args[0], buffer.data(), STRING_LENGTH_MAX, nullptr)); + std::string effectType(buffer.data()); + MISC_HILOGD("effectType = %{public}s", effectType.c_str()); + + VibratorIdentifier identifier; + if (argc > 1) { + if (!ParseVibratorIdentifier(env, args[1], identifier)) { + MISC_HILOGW("deviceId and vibratorId is undefined, set default value deviceId = -1 and vibratorId = -1"); + } + MISC_HILOGD("identifier=[deviceId=%{public}d, vibratorId=%{pubilc}d]", identifier.deviceId, identifier.vibratorId); + } + + EffectInfo effectInfo; + int32_t ret = GetEffectInfo(identifier, effectType, effectInfo); + MISC_HILOGD("effectInfo=[%{public}s]", (effectInfo.isSupportEffect? "true" : "false")); + + napi_value jsEffectInfo = nullptr; + if (ret == SUCCESS) { + jsEffectInfo = ConvertToJsEffectInfo(env, effectInfo); + } + return jsEffectInfo; +} + +// static napi_value IsSupportEffectInfo(napi_env env, napi_callback_info info) +// { +// CALL_LOG_ENTER; +// size_t argc = 3; +// napi_value args[3]; +// NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr)); + +// std::vector buffer(64); +// NAPI_CALL(env, napi_get_value_string_utf8(env, args[0], buffer.data(), 64, nullptr)); +// std::string effectType(buffer.data()); +// MISC_HILOGD("effectType = %{public}s", effectType.c_str()); + +// VibratorIdentifier identifier; +// if (argc > 1) { +// if (!ParseVibratorIdentifier(env, args[1], identifier)) { +// MISC_HILOGW("deviceId and vibratorId is undefined, set default value deviceId = -1 and vibratorId = -1"); +// } +// MISC_HILOGD("identifier=[deviceId=%{public}d, vibratorId=%{pubilc}d]", identifier.deviceId, identifier.vibratorId); +// } + +// sptr asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo(env); +// CHKPP(asyncCallbackInfo); +// asyncCallbackInfo->callbackType = GET_EFFECT_INFO; +// asyncCallbackInfo->error.code = GetEffectInfo(identifier, effectType, asyncCallbackInfo->effectInfo); +// if ((argc > 1) && (IsMatchType(env, args[2], napi_function))) { +// return EmitAsyncWork(args[2], asyncCallbackInfo); +// } +// return EmitAsyncWork(nullptr, asyncCallbackInfo); +// } + +bool IsSameValue(const napi_env &env, const napi_value &lhs, const napi_value &rhs) +{ + CALL_LOG_ENTER; + bool result = false; + CHKNRF(env, napi_strict_equals(env, lhs, rhs, &result), "napi_strict_equals"); + return result; +} + +static bool IsSubscribed(const napi_env& env, std::string vibratorEvent, napi_value callback) +{ + CALL_LOG_ENTER; + MISC_HILOGD("g_onCallbackInfos.size() = %{public}d", g_onCallbackInfos.size()); + if (g_onCallbackInfos.empty()){ + return true; + } + if (auto iter = g_onCallbackInfos.find(vibratorEvent); iter == g_onCallbackInfos.end()) { + MISC_HILOGW("No client subscribe, vibratorEvent:%{public}s", vibratorEvent.c_str()); + return false; + } + std::vector> callbackInfos = g_onCallbackInfos[vibratorEvent]; + for (auto callbackInfo : callbackInfos) { + CHKPC(callbackInfo); + if (callbackInfo->env != env) { + continue; + } + napi_value vibratorCallback = nullptr; + CHKNRF(env, napi_get_reference_value(env, callbackInfo->callback[0], &vibratorCallback), + "napi_get_reference_value"); + if (IsSameValue(env, callback, vibratorCallback)) { + return true; + } + } + return false; +} + +static void UpdateCallbackInfos(const napi_env& env, std::string& vibratorEvent, napi_value callback) +{ + CALL_LOG_ENTER; + std::lock_guard onSubcribeLock(g_Mutex); + CHKCV(IsSubscribed(env, vibratorEvent, callback), "The callback has been subscribed"); + sptr asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo(env); + CHKPV(asyncCallbackInfo); + + if (vibratorEvent == "VibratorDeviceStateChange") { + asyncCallbackInfo->callbackType = VIBRATOR_STATE_CHANGE; + } + napi_status status = napi_create_reference(env, callback, 1, &asyncCallbackInfo->callback[0]); + if (status != napi_ok) { + ThrowErr(env, PARAMETER_ERROR, "napi_create_reference fail"); + return; + } + + std::vector> callbackInfos = g_onCallbackInfos[vibratorEvent]; + callbackInfos.push_back(asyncCallbackInfo); + g_onCallbackInfos[vibratorEvent] = callbackInfos; +} + +static int32_t UpdatePlugInfo(VibratorDeviceInfo *deviceInfo, sptr &asyncCallbackInfo) +{ + CALL_LOG_ENTER; + MISC_HILOGD("deviceInfo : [ type = %{public}d, deviceId = %{public}d]", deviceInfo->type, deviceInfo->deviceId); + CHKPR(deviceInfo, PARAMETER_ERROR); + if (deviceInfo->type == PLUG_STATE_EVENT_UNKNOWN || + deviceInfo->deviceId == -1) { + MISC_HILOGE("UpdatePlugInfo failed"); + return PARAMETER_ERROR; + } + asyncCallbackInfo->deviceInfo.type = deviceInfo->type; + asyncCallbackInfo->deviceInfo.deviceId = deviceInfo->deviceId; + MISC_HILOGD("asyncCallbackInfo->deviceInfo : [ VibratorPlugState = %{public}d, deviceId = %{public}d]", + asyncCallbackInfo->deviceInfo.type, asyncCallbackInfo->deviceInfo.deviceId); + return 0; +} + +void DataCallbackImpl(VibratorDeviceInfo *deviceInfo) +{ + CALL_LOG_ENTER; + CHKPV(deviceInfo); + std::lock_guard CallbackLock(g_plugCallbackMutex); + std::vector> callBackArry; + for (auto& allCallBack : g_onCallbackInfos) { + callBackArry = allCallBack.second; + for (auto& callback : callBackArry) { + if (callback->callbackType == VIBRATOR_STATE_CHANGE) { + MISC_HILOGD("VIBRATOR_STATE_CHANGE"); + callback->error.code = UpdatePlugInfo(deviceInfo, callback); + EmitAsyncCallbackWork(callback); + } + } + } +} + +const VibratorUser user = { + .callback = DataCallbackImpl +}; + +int32_t SubscribeVibrator(RecordVibratorPlugCallback callback) +{ + CALL_LOG_ENTER; + int32_t ret = SubscribeVibrator(user); + if (ret != ERR_OK) { + MISC_HILOGE("SubscribeVibrator failed"); + return ret; + } + return ret; +} + +static napi_value On(napi_env env, napi_callback_info info) { + CALL_LOG_ENTER; + size_t argc = 2; + napi_value args[2]; + napi_status status = napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); + if (status != napi_ok || argc < 2) { + ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail or number of parameter invalid"); + return nullptr; + } + if ((!IsMatchType(env, args[0], napi_string)) || (!IsMatchType(env, args[1], napi_function))) { + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type"); + return nullptr; + } + std::string eventType; + if(!GetStringValue(env, args[0], eventType)) { + ThrowErr(env, PARAMETER_ERROR, "napi_get_value_int32 fail, the number of parameter invalid"); + return nullptr; + } + MISC_HILOGD("eventType = %{public}s", eventType.c_str()); + + int32_t ret = SubscribeVibrator(DataCallbackImpl); + if (ret != ERR_OK) { + ThrowErr(env, ret, "SubscribeVibrator fail"); + return nullptr; + } + UpdateCallbackInfos(env, eventType, args[1]); + return nullptr; +} + +static int32_t RemoveAllCallback(const napi_env& env, std::string& eventType) +{ + CALL_LOG_ENTER; + std::lock_guard onCancelLock(g_Mutex); + std::vector> callbackInfos = g_onCallbackInfos[eventType]; + for (auto iter = callbackInfos.begin(); iter != callbackInfos.end();) { + CHKPC(*iter); + if ((*iter)->env != env) { + ++iter; + continue; + } + iter = callbackInfos.erase(iter); + } + if (callbackInfos.empty()) { + MISC_HILOGD("No subscription to change"); + g_onCallbackInfos.erase(eventType); + return 0; + } + g_onCallbackInfos[eventType] = callbackInfos; + return callbackInfos.size(); +} + +static napi_value Off(napi_env env, napi_callback_info info) { + size_t argc = 2; + napi_value args[2]; + napi_status status = napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); + if (status != napi_ok || argc < 2) { + ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail or number of parameter invalid"); + return nullptr; + } + if ((!IsMatchType(env, args[0], napi_string)) || (!IsMatchType(env, args[1], napi_function))) { + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type"); + return nullptr; + } + std::string eventType; + if(!GetStringValue(env, args[0], eventType)) { + ThrowErr(env, PARAMETER_ERROR, "GetStringValue fail, the number of parameter invalid"); + return nullptr; + } + int32_t subscribeSize = -1; + if (IsMatchType(env, args[1], napi_function)) { + subscribeSize = RemoveAllCallback(env, eventType); + } else { + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, args[1] should is napi_function"); + return nullptr; + } + if (subscribeSize > 0) { + MISC_HILOGW("There are other client subscribe system js api as well, not need unsubscribe"); + return nullptr; + } + + int32_t ret = UnSubscribeVibrator(user); + if (ret != ERR_OK && ret != CALLBACK_UNSUBSCRIBED) { + ThrowErr(env, ret, "User callback unsubscribe fail"); + return nullptr; + } else if (ret == CALLBACK_UNSUBSCRIBED) { + ThrowErr(env, ret, "User callback deregistered repeatedly"); + return nullptr; + } + return nullptr; +} + static napi_value CreateEnumHapticFeedback(const napi_env env, napi_value exports) { napi_value effectSoft = nullptr; @@ -789,6 +1145,10 @@ static napi_value Init(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("isHdHapticSupported", IsHdHapticSupported), DECLARE_NAPI_FUNCTION("isSupportEffect", IsSupportEffect), DECLARE_NAPI_FUNCTION("isSupportEffectSync", IsSupportEffectSync), + DECLARE_NAPI_FUNCTION("getVibratorListSync", GetVibratorListSync), + DECLARE_NAPI_FUNCTION("getEffectSupportInfoSync", GetSupportEffectInfoSync), + DECLARE_NAPI_FUNCTION("on", On), + DECLARE_NAPI_FUNCTION("off", Off), }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(napi_property_descriptor), desc)); NAPI_ASSERT_BASE(env, CreateEnumStopMode(env, exports) != nullptr, "Create enum stop mode fail", exports); diff --git a/frameworks/js/napi/vibrator/src/vibrator_napi_utils.cpp b/frameworks/js/napi/vibrator/src/vibrator_napi_utils.cpp index bebac3db8f5283fbc0ab7372971e5c51a224f5c9..9f68bc113b8487c046130c5f98e626ab33d29b06 100644 --- a/frameworks/js/napi/vibrator/src/vibrator_napi_utils.cpp +++ b/frameworks/js/napi/vibrator/src/vibrator_napi_utils.cpp @@ -78,6 +78,33 @@ bool CreateInt32Property(napi_env env, napi_value &eventObj, const char* name, i return true; } +bool CreateStringProperty(napi_env env, napi_value &eventObj, const char* name, + const char* value, int32_t valueLength) +{ + CALL_LOG_ENTER; + napi_value propValue = nullptr; + napi_status status = napi_create_string_utf8(env, value, valueLength, &propValue); + if (status != napi_ok) { + MISC_HILOGE("napi_create_string_utf8 fail"); + return false; + } + CHKCF((napi_set_named_property(env, eventObj, name, propValue) == napi_ok), "napi_set_named_property fail"); + return true; +} + +bool CreateBooleanProperty(napi_env env, napi_value &eventObj, const char* name, bool value) +{ + CALL_LOG_ENTER; + napi_value propValue = nullptr; + napi_status status = napi_get_boolean(env, value, &propValue); + if (status != napi_ok) { + MISC_HILOGE("napi_get_boolean fail"); + return false; + } + CHKCF((napi_set_named_property(env, eventObj, name, propValue) == napi_ok), "napi_set_named_property fail"); + return true; +} + bool IsMatchArrayType(const napi_env &env, const napi_value &value) { bool result = false; @@ -258,6 +285,9 @@ bool GetPropertyBool(const napi_env &env, const napi_value &value, const std::st std::map g_convertFuncList = { {COMMON_CALLBACK, ConstructCommonResult}, {IS_SUPPORT_EFFECT_CALLBACK, ConstructIsSupportEffectResult}, + // {GET_VIBRATOR_INFO_LIST, ConstructGetVibratorInfoListResult}, + // {GET_EFFECT_INFO, ConstructIsSupportEffectInfoResult}, + // {VIBRATOR_STATE_CHANGE, ConstructVibratorPlugInfoResult}, }; bool ConvertErrorToResult(const napi_env &env, sptr asyncCallbackInfo, napi_value &result) @@ -304,6 +334,145 @@ bool ConstructIsSupportEffectResult(const napi_env &env, sptr return true; } +napi_value ConvertToJsVibratorInfo(const napi_env& env, const VibratorInfos& vibratorInfo) +{ + CALL_LOG_ENTER; + napi_value jsObject = nullptr; + napi_status status = napi_create_object(env, &jsObject); + if (status != napi_ok) { + return jsObject; + } + MISC_HILOGD("VibratorInfos: [deviceId = %{public}d, vibratorId = %{public}d, deviceName = %{public}s,\ + isSupportHdHaptic = %{public}s, isLocalVibrator = %{public}s]", vibratorInfo.deviceId, + vibratorInfo.vibratorId, vibratorInfo.deviceName.c_str(), (vibratorInfo.isSupportHdHaptic ? "true":"false"), + (vibratorInfo.isLocalVibrator ? "true":"false")); + if (!CreateInt32Property(env, jsObject, "deviceId", vibratorInfo.deviceId)) { + MISC_HILOGE("Create vibratorInfo.deviceId failed"); + return jsObject; + } + if (!CreateInt32Property(env, jsObject, "vibratorId", vibratorInfo.vibratorId)) { + MISC_HILOGE("Create vibratorInfo.vibratorId failed"); + return jsObject; + } + if (!CreateStringProperty(env, jsObject, "deviceName", vibratorInfo.deviceName.c_str(), + vibratorInfo.deviceName.length())) { + MISC_HILOGE("Create vibratorInfo.deviceName failed"); + return jsObject; + } + if (!CreateBooleanProperty(env, jsObject, "isSupportHdHaptic", vibratorInfo.isSupportHdHaptic)) { + MISC_HILOGE("Create vibratorInfo.isSupportHdHaptic failed"); + return jsObject; + } + if (!CreateBooleanProperty(env, jsObject, "isLocalVibrator", vibratorInfo.isLocalVibrator)) { + MISC_HILOGE("Create vibratorInfo.isLocalVibrator failed"); + return jsObject; + } + return jsObject; +} + +napi_value ConvertToJsEffectInfo(const napi_env& env, const EffectInfo& effectInfo) { + CALL_LOG_ENTER; + napi_value jsObject = nullptr; + napi_status status = napi_create_object(env, &jsObject); + if (status != napi_ok) { + return jsObject; + } + if (!CreateBooleanProperty(env, jsObject, "isSupportEffect", effectInfo.isSupportEffect)) { + MISC_HILOGE("Create effectInfo.isSupportEffect failed"); + return jsObject; + } + return jsObject; +} + +napi_value ConvertToJsVibratorPlungInfo(const napi_env& env, const VibratorDeviceInfo& deviceInfo) { + CALL_LOG_ENTER; + MISC_HILOGD("deviceInfo: [type = %{public}d, deviceId = %{public}d]", deviceInfo.type, deviceInfo.deviceId); + bool plugFlag = false; + napi_value jsObject = nullptr; + napi_status status = napi_create_object(env, &jsObject); + if (status != napi_ok) { + napi_throw_error(env, nullptr, "Failed to create JS object"); + return jsObject; + } + if (deviceInfo.type == PLUG_STATE_EVENT_PLUG_IN) { + plugFlag = true; + } else if (deviceInfo.type == PLUG_STATE_EVENT_PLUG_OUT) { + plugFlag = false; + } + MISC_HILOGD("plugFlag = %{public}s", plugFlag? "true":"false"); + if (!CreateBooleanProperty(env, jsObject, "VibratorPlugState", plugFlag)) { + MISC_HILOGE("Create plugFlag failed"); + return jsObject; + } + if (!CreateInt32Property(env, jsObject, "deviceId", deviceInfo.deviceId)) { + MISC_HILOGE("Create deviceInfo.deviceId failed"); + return jsObject; + } + + return jsObject; +} + +// bool ConstructGetVibratorInfoListResult(const napi_env &env, sptr asyncCallbackInfo, +// napi_value result[], int32_t length) +// { +// CALL_LOG_ENTER; +// CHKPF(asyncCallbackInfo); +// CHKCF(length == RESULT_LENGTH, "Array length is different"); +// if (asyncCallbackInfo->error.code != SUCCESS) { +// CHKCF(ConvertErrorToResult(env, asyncCallbackInfo, result[0]), "Create napi err fail in async work"); +// CHKCF((napi_get_undefined(env, &result[1]) == napi_ok), "napi_get_undefined fail"); +// } else { +// CHKCF((napi_get_undefined(env, &result[0]) == napi_ok), "napi_get_undefined fail"); +// napi_value jsArray; +// CHKCF((napi_create_array(env, &jsArray) == napi_ok), "napi_set_element fail"); +// for (size_t i = 0; i < asyncCallbackInfo->vibratorInfos.size(); ++i) { +// napi_value jsInfo = ConvertToJsVibratorInfo(env, asyncCallbackInfo->vibratorInfos[i]); +// CHKPF(jsInfo); +// CHKCF((napi_set_element(env, jsArray, i, jsInfo) == napi_ok), "napi_set_element fail"); +// } +// result[1] = jsArray; +// } +// return true; +// } + +// bool ConstructIsSupportEffectInfoResult(const napi_env &env, sptr asyncCallbackInfo, +// napi_value result[], int32_t length) +// { +// CALL_LOG_ENTER; +// CHKPF(asyncCallbackInfo); +// CHKCF(length == RESULT_LENGTH, "Array length is different"); +// if (asyncCallbackInfo->error.code != SUCCESS) { +// CHKCF(ConvertErrorToResult(env, asyncCallbackInfo, result[0]), "Create napi err fail in async work"); +// CHKCF((napi_get_undefined(env, &result[1]) == napi_ok), "napi_get_undefined fail"); +// } else { +// CHKCF((napi_get_undefined(env, &result[0]) == napi_ok), "napi_get_undefined fail"); +// napi_value jsEffectInfo; +// jsEffectInfo = ConvertToJsEffectInfo(env, asyncCallbackInfo->effectInfo); +// CHKPF(jsEffectInfo); +// result[1] = jsEffectInfo; +// } +// return true; +// } + +// bool ConstructVibratorPlugInfoResult(const napi_env &env, sptr asyncCallbackInfo, +// napi_value result[], int32_t length) +// { +// CALL_LOG_ENTER; +// CHKPF(asyncCallbackInfo); +// CHKCF(length == RESULT_LENGTH, "Array length is different"); +// if (asyncCallbackInfo->error.code != SUCCESS) { +// CHKCF(ConvertErrorToResult(env, asyncCallbackInfo, result[0]), "Create napi err fail in async work"); +// CHKCF((napi_get_undefined(env, &result[1]) == napi_ok), "napi_get_undefined fail"); +// } else { +// napi_value jsDevicePlugInfo; +// jsDevicePlugInfo = ConvertToJsVibratorPlungInfo(env, asyncCallbackInfo->deviceInfo); +// CHKPF(jsDevicePlugInfo); +// result[0] = jsDevicePlugInfo; +// CHKCF((napi_get_undefined(env, &result[1]) == napi_ok), "napi_get_undefined fail"); +// } +// return true; +// } + void EmitSystemCallback(const napi_env &env, sptr asyncCallbackInfo) { CHKPV(asyncCallbackInfo); diff --git a/frameworks/native/vibrator/all/IMiscdeviceService.idl b/frameworks/native/vibrator/all/IMiscdeviceService.idl index 2e2ceea0301a8cec7df6bde9a9da75e8645ce3fd..c2b64ec87e1795c46e23decb2abcebe4fbe5a264 100644 --- a/frameworks/native/vibrator/all/IMiscdeviceService.idl +++ b/frameworks/native/vibrator/all/IMiscdeviceService.idl @@ -18,23 +18,30 @@ sequenceable light_animation_ipc..OHOS.Sensors.LightAnimationIPC; sequenceable light_info_ipc..OHOS.Sensors.LightInfoIPC; sequenceable OHOS.IRemoteObject; sequenceable raw_file_descriptor..OHOS.Sensors.RawFileDescriptor; -sequenceable vibrator_infos..OHOS.Sensors.VibrateParameter; sequenceable vibrator_infos..OHOS.Sensors.VibratePattern; sequenceable vibrator_infos..OHOS.Sensors.VibratorCapacity; +sequenceable vibrator_infos..OHOS.Sensors.VibratorIdentifierIPC; +sequenceable vibrator_infos..OHOS.Sensors.VibratorInfoIPC; +sequenceable vibrator_infos..OHOS.Sensors.EffectInfoIPC; +sequenceable vibrator_infos..OHOS.Sensors.CustomHapticInfoIPC; +sequenceable vibrator_infos..OHOS.Sensors.PrimitiveEffectIPC; interface OHOS.Sensors.IMiscdeviceService { - void Vibrate([in] int vibratorId, [in] int timeOut, [in] int usage, [in] boolean systemUsage); - void PlayVibratorEffect([in] int vibratorId, [in] String effect, [in] int loopCount, [in] int usage, [in] boolean systemUsage); - void PlayVibratorCustom([in] int vibratorId, [in] FileDescriptor fd, [in] long offset, [in] long length, [in] int usage, [in] boolean systemUsage, [in] VibrateParameter parameter); - void StopVibrator([in] int vibratorId); - void StopVibratorByMode([in] int vibratorId, [in] String mode); - void IsSupportEffect([in] String effect, [out] boolean state); + void Vibrate([in] VibratorIdentifierIPC identifier, [in] int timeOut, [in] int usage, [in] boolean systemUsage); + void PlayVibratorEffect([in] VibratorIdentifierIPC identifier, [in] String effect, [in] int loopCount, [in] int usage, [in] boolean systemUsage); + void PlayVibratorCustom([in] VibratorIdentifierIPC identifier, [in] FileDescriptor fd, [in] long offset, [in] long length, [in] CustomHapticInfoIPC customHapticInfoIPC); + void StopVibrator([in] VibratorIdentifierIPC identifier); + void StopVibratorByMode([in] VibratorIdentifierIPC identifier, [in] String mode); + void IsSupportEffect([in] VibratorIdentifierIPC identifier, [in] String effect, [out] boolean state); void GetLightList([out] LightInfoIPC[] lightInfoIpcList); void TurnOn([in] int lightId, [in] int singleColor, [in] LightAnimationIPC animation); void TurnOff([in] int lightId); - void GetDelayTime([out] int delayTime); - void PlayPattern([in] VibratePattern pattern, [in] int usage, [in] boolean systemUsage, [in] VibrateParameter parameter); + void GetDelayTime([in] VibratorIdentifierIPC identifier, [out] int delayTime); + void PlayPattern([in] VibratorIdentifierIPC identifier, [in] VibratePattern pattern, [in] CustomHapticInfoIPC customHapticInfoIPC); void TransferClientRemoteObject([in] IRemoteObject vibratorClient); - void PlayPrimitiveEffect([in] int vibratorId, [in] String effect, [in] int intensity, [in] int usage, [in] boolean systemUsage, [in] int count); - void GetVibratorCapacity([out] VibratorCapacity capacity); + void PlayPrimitiveEffect([in] VibratorIdentifierIPC identifier, [in] String effect, [in] PrimitiveEffectIPC primitiveEffectIPC); + void GetVibratorCapacity([in] VibratorIdentifierIPC identifier, [out] VibratorCapacity capacity); + void GetVibratorIdList([in] VibratorIdentifierIPC identifier, [out] VibratorInfoIPC[] vibratorInfoIPC); + void GetEffectInfo([in] VibratorIdentifierIPC identifier, [in] String effectType, [out] EffectInfoIPC effectInfoIPC); + void SubscribeVibratorPlugInfo([in] IRemoteObject vibratorClient); } \ No newline at end of file diff --git a/frameworks/native/vibrator/include/i_vibrator_client.h b/frameworks/native/vibrator/include/i_vibrator_client.h index 8c83ed06649453e16196c38be3e9b273f083644d..7278d632e28258c52dbc259301de75feec6a4678 100644 --- a/frameworks/native/vibrator/include/i_vibrator_client.h +++ b/frameworks/native/vibrator/include/i_vibrator_client.h @@ -22,8 +22,12 @@ namespace OHOS { namespace Sensors { class IVibratorClient : public IRemoteBroker { public: + enum VibratorClientInterfaceId { + TRANS_ID_PLUG_ABILITY = 5, + }; IVibratorClient() = default; virtual ~IVibratorClient() = default; + virtual int ProcessPlugEvent(int32_t eventCode, int32_t deviceId) = 0; DECLARE_INTERFACE_DESCRIPTOR(u"IVibratorClient"); }; } // namespace Sensors diff --git a/frameworks/native/vibrator/include/vibrator_client_proxy.h b/frameworks/native/vibrator/include/vibrator_client_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..0ef859db592b6252ebd109ade42a2f044f383535 --- /dev/null +++ b/frameworks/native/vibrator/include/vibrator_client_proxy.h @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef VIBRATOR_CLIENT_STUB_H +#define VIBRATOR_CLIENT_STUB_H + +#include "message_parcel.h" +#include "miscdevice_log.h" +#include "iremote_proxy.h" +#include "i_vibrator_client.h" + +#undef LOG_TAG +#define LOG_TAG "VibratorClientProxy" + +namespace OHOS { +namespace Sensors { +class VibratorClientProxy : public IRemoteProxy { +public: + explicit VibratorClientProxy(const sptr &impl) : IRemoteProxy(impl){} + virtual ~VibratorClientProxy() = default; + int ProcessPlugEvent(int32_t eventCode, int32_t deviceId) override + { + MessageOption option; + MessageParcel dataParcel; + MessageParcel replyParcel; + + if (!dataParcel.WriteInterfaceToken(GetDescriptor())) { + MISC_HILOGE("Failed to write descriptor to parcelable"); + return PARAMETER_ERROR; + } + if (!dataParcel.WriteInt32(eventCode)) { + MISC_HILOGE("Failed to write eventCode to parcelable"); + return PARAMETER_ERROR; + } + if (!dataParcel.WriteInt32(deviceId)) { + MISC_HILOGE("Failed to write deviceId to parcelable"); + return PARAMETER_ERROR; + } + int error = Remote()->SendRequest(TRANS_ID_PLUG_ABILITY, dataParcel, replyParcel, option); + if (error != ERR_NONE) { + MISC_HILOGE("failed, error code is: %{public}d", error); + return PARAMETER_ERROR; + } + int result = (error == ERR_NONE) ? replyParcel.ReadInt32() : -1; + return result; + } + +private: + DISALLOW_COPY_AND_MOVE(VibratorClientProxy); + static inline BrokerDelegator delegator_; +}; +} // namespace Sensors +} // namespace OHOS +#endif // VIBRATOR_CLIENT_STUB_H diff --git a/frameworks/native/vibrator/include/vibrator_client_stub.h b/frameworks/native/vibrator/include/vibrator_client_stub.h index 1f55bbda33dea66478822418eaea5534090dfff3..dab55ed953bc95e9916712cd815125ccd31f276e 100644 --- a/frameworks/native/vibrator/include/vibrator_client_stub.h +++ b/frameworks/native/vibrator/include/vibrator_client_stub.h @@ -28,6 +28,7 @@ public: virtual ~VibratorClientStub() = default; virtual int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + int ProcessPlugEvent(int32_t eventCode, int32_t deviceId) override; }; } // namespace Sensors } // namespace OHOS diff --git a/frameworks/native/vibrator/include/vibrator_service_client.h b/frameworks/native/vibrator/include/vibrator_service_client.h index 9b5d1c56b52c40ce908b205f99d3eb574106d85c..5b60d5f6ae8001e835626726d3ec3770a992c109 100644 --- a/frameworks/native/vibrator/include/vibrator_service_client.h +++ b/frameworks/native/vibrator/include/vibrator_service_client.h @@ -18,6 +18,9 @@ #include #include +#include +#include +#include #include "iremote_object.h" #include "singleton.h" @@ -54,35 +57,46 @@ struct VibratorDecodeHandle { class VibratorServiceClient : public Singleton { public: ~VibratorServiceClient() override; - int32_t Vibrate(int32_t vibratorId, int32_t timeOut, int32_t usage, bool systemUsage); - int32_t Vibrate(int32_t vibratorId, const std::string &effect, int32_t loopCount, int32_t usage, bool systemUsage); + int32_t Vibrate(const VibratorIdentifier &identifier, int32_t timeOut, int32_t usage, bool systemUsage); + int32_t Vibrate(const VibratorIdentifier &identifier, const std::string &effect, + int32_t loopCount, int32_t usage, bool systemUsage); #ifdef OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM - int32_t PlayVibratorCustom(int32_t vibratorId, const RawFileDescriptor &rawFd, int32_t usage, - bool systemUsage, const VibratorParameter ¶meter); + int32_t PlayVibratorCustom(const VibratorIdentifier &identifier, const RawFileDescriptor &rawFd, + int32_t usage, bool systemUsage, const VibratorParameter ¶meter); #endif // OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM - int32_t StopVibrator(int32_t vibratorId, const std::string &mode); - int32_t StopVibrator(int32_t vibratorId); - bool IsHdHapticSupported(); - int32_t IsSupportEffect(const std::string &effect, bool &state); + int32_t StopVibrator(const VibratorIdentifier &identifier, const std::string &mode); + int32_t StopVibrator(const VibratorIdentifier &identifier); + bool IsHdHapticSupported(const VibratorIdentifier &identifier); + int32_t IsSupportEffect(const VibratorIdentifier &identifier, const std::string &effect, bool &state); void ProcessDeathObserver(const wptr &object); int32_t PreProcess(const VibratorFileDescription &fd, VibratorPackage &package); - int32_t GetDelayTime(int32_t &delayTime); - int32_t InitPlayPattern(const VibratorPattern &pattern, int32_t usage, bool systemUsage, - const VibratorParameter ¶meter); - int32_t PlayPattern(const VibratorPattern &pattern, int32_t usage, bool systemUsage, - const VibratorParameter ¶meter); + int32_t GetDelayTime(const VibratorIdentifier &identifier, int32_t &delayTime); + int32_t InitPlayPattern(const VibratorIdentifier &identifier, const VibratorPattern &pattern, int32_t usage, + bool systemUsage, const VibratorParameter ¶meter); + int32_t PlayPattern(const VibratorIdentifier &identifier, const VibratorPattern &pattern, int32_t usage, + bool systemUsage, const VibratorParameter ¶meter); int32_t FreeVibratorPackage(VibratorPackage &package); - int32_t PlayPrimitiveEffect(int32_t vibratorId, const std::string &effect, int32_t intensity, int32_t usage, - bool systemUsage, int32_t count); - bool IsSupportVibratorCustom(); + int32_t PlayPrimitiveEffect(const VibratorIdentifier &identifier, const std::string &effect, + const PrimitiveEffect &primitiveEffect); + bool IsSupportVibratorCustom(const VibratorIdentifier &identifier); int32_t SeekTimeOnPackage(int32_t seekTime, const VibratorPackage &completePackage, VibratorPackage &seekPackage); + int32_t SubscribeVibratorPlugInfo(const VibratorUser *user); + int32_t UnsubscribeVibratorPlugInfo(const VibratorUser *user); + std::set GetSubscribeUserCallback(int32_t deviceId); + bool HandleVibratorData(VibratorDeviceInfo info); + void SetUsage(const VibratorIdentifier &identifier, int32_t usage, bool systemUsage); + void SetLoopCount(const VibratorIdentifier &identifier, int32_t count); + void SetParameters(const VibratorIdentifier &identifier, const VibratorParameter ¶meter); + VibratorEffectParameter GetVibratorEffectParameter(const VibratorIdentifier &identifier); + int32_t GetVibratorIdList(const VibratorIdentifier& identifier, std::vector& vibratorInfo); + int32_t GetEffectInfo(const VibratorIdentifier& identifier,const std::string& effectType, EffectInfo& effectInfo); private: int32_t InitServiceClient(); int32_t LoadDecoderLibrary(const std::string& path); int32_t ConvertVibratorPackage(const VibratePackage& inPkg, VibratorPackage &outPkg); int32_t TransferClientRemoteObject(); - int32_t GetVibratorCapacity(); + int32_t GetVibratorCapacity(const VibratorIdentifier &identifier, VibratorCapacity &capacity); void ConvertSeekVibratorPackage(const VibratorPackage &completePackage, VibratePackage &convertPackage, int32_t seekTime); void ConvertVibratorPattern(const VibratorPattern &vibratorPattern, VibratePattern &vibratePattern); @@ -94,9 +108,14 @@ private: sptr miscdeviceProxy_ = nullptr; sptr vibratorClient_ = nullptr; VibratorDecodeHandle decodeHandle_; - VibratorCapacity capacity_; std::mutex clientMutex_; std::mutex decodeMutex_; + + std::recursive_mutex subscribeMutex_; + std::set subscribeSet_; + + std::mutex vibratorEffectMutex_; + std::map vibratorEffectMap_; }; } // namespace Sensors } // namespace OHOS diff --git a/frameworks/native/vibrator/part/IMiscdeviceService.idl b/frameworks/native/vibrator/part/IMiscdeviceService.idl index 2415e99d700bf8818c7a9d89f0d7cc000d0843ab..1f086fd873c648280017052abf027f0d063ee66d 100644 --- a/frameworks/native/vibrator/part/IMiscdeviceService.idl +++ b/frameworks/native/vibrator/part/IMiscdeviceService.idl @@ -18,22 +18,29 @@ sequenceable light_animation_ipc..OHOS.Sensors.LightAnimationIPC; sequenceable light_info_ipc..OHOS.Sensors.LightInfoIPC; sequenceable OHOS.IRemoteObject; sequenceable raw_file_descriptor..OHOS.Sensors.RawFileDescriptor; -sequenceable vibrator_infos..OHOS.Sensors.VibrateParameter; sequenceable vibrator_infos..OHOS.Sensors.VibratePattern; sequenceable vibrator_infos..OHOS.Sensors.VibratorCapacity; +sequenceable vibrator_infos..OHOS.Sensors.VibratorIdentifierIPC; +sequenceable vibrator_infos..OHOS.Sensors.VibratorInfoIPC; +sequenceable vibrator_infos..OHOS.Sensors.EffectInfoIPC; +sequenceable vibrator_infos..OHOS.Sensors.CustomHapticInfoIPC; +sequenceable vibrator_infos..OHOS.Sensors.PrimitiveEffectIPC; interface OHOS.Sensors.IMiscdeviceService { - void Vibrate([in] int vibratorId, [in] int timeOut, [in] int usage, [in] boolean systemUsage); - void PlayVibratorEffect([in] int vibratorId, [in] String effect, [in] int loopCount, [in] int usage, [in] boolean systemUsage); - void StopVibrator([in] int vibratorId); - void StopVibratorByMode([in] int vibratorId, [in] String mode); - void IsSupportEffect([in] String effect, [out] boolean state); + void Vibrate([in] VibratorIdentifierIPC identifier, [in] int timeOut, [in] int usage, [in] boolean systemUsage); + void PlayVibratorEffect([in] VibratorIdentifierIPC identifier, [in] String effect, [in] int loopCount, [in] int usage, [in] boolean systemUsage); + void StopVibrator([in] VibratorIdentifierIPC identifier); + void StopVibratorByMode([in] VibratorIdentifierIPC identifier, [in] String mode); + void IsSupportEffect([in] VibratorIdentifierIPC identifier, [in] String effect, [out] boolean state); void GetLightList([out] LightInfoIPC[] lightInfoIpcList); void TurnOn([in] int lightId, [in] int singleColor, [in] LightAnimationIPC animation); void TurnOff([in] int lightId); - void GetDelayTime([out] int delayTime); - void PlayPattern([in] VibratePattern pattern, [in] int usage, [in] boolean systemUsage, [in] VibrateParameter parameter); + void GetDelayTime([in] VibratorIdentifierIPC identifier, [out] int delayTime); + void PlayPattern([in] VibratorIdentifierIPC identifier, [in] VibratePattern pattern, [in] CustomHapticInfoIPC customHapticInfoIPC); void TransferClientRemoteObject([in] IRemoteObject vibratorClient); - void PlayPrimitiveEffect([in] int vibratorId, [in] String effect, [in] int intensity, [in] int usage, [in] boolean systemUsage, [in] int count); - void GetVibratorCapacity([out] VibratorCapacity capacity); + void PlayPrimitiveEffect([in] VibratorIdentifierIPC identifier, [in] String effect, [in] PrimitiveEffectIPC primitiveEffectIPC); + void GetVibratorCapacity([in] VibratorIdentifierIPC identifier, [out] VibratorCapacity capacity); + void GetVibratorIdList([in] VibratorIdentifierIPC identifier, [out] VibratorInfoIPC[] vibratorInfoIPC); + void GetEffectInfo([in] VibratorIdentifierIPC identifier, [in] String effectType, [out] EffectInfoIPC effectInfoIPC); + void SubscribeVibratorPlugInfo(); } \ No newline at end of file diff --git a/frameworks/native/vibrator/src/vibrator_client_stub.cpp b/frameworks/native/vibrator/src/vibrator_client_stub.cpp index f6dc8c4180641ee049c392dbbd9df5834ce2694f..d2763630d017c2c9553a5a2e8e721573c81426c7 100644 --- a/frameworks/native/vibrator/src/vibrator_client_stub.cpp +++ b/frameworks/native/vibrator/src/vibrator_client_stub.cpp @@ -18,11 +18,13 @@ #include "message_parcel.h" #include "miscdevice_log.h" +#include "vibrator_service_client.h" #undef LOG_TAG #define LOG_TAG "VibratorClientStub" namespace OHOS { namespace Sensors { +using OHOS::Sensors::VibratorServiceClient; int32_t VibratorClientStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) @@ -33,7 +35,41 @@ int32_t VibratorClientStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MISC_HILOGE("Client and service descriptors are inconsistent"); return OBJECT_NULL; } - MISC_HILOGD("Begin, cmd:%{public}u", code); + MISC_HILOGD("Begin, cmd:%{public}u", code); + switch (code) { + case TRANS_ID_PLUG_ABILITY: { + int32_t eventCode = 0; + int32_t deviceId = -1; + if (!data.ReadInt32(eventCode)) { + MISC_HILOGE("Read eventCode failed."); + return PARAMETER_ERROR; + } + if (!data.ReadInt32(deviceId)) { + MISC_HILOGE("Read eventCode failed."); + return PARAMETER_ERROR; + } + int result = ProcessPlugEvent(eventCode, deviceId); + reply.WriteInt32(result); + return NO_ERROR; + } + } + return NO_ERROR; +} + +int VibratorClientStub::ProcessPlugEvent(int32_t eventCode, int32_t deviceId) +{ + MISC_HILOGD("Begin, eventCode=%{public}d, deviceId:%{public}d", eventCode, deviceId); + VibratorDeviceInfo info = { + .type = static_cast(eventCode), + .deviceId = deviceId + }; + auto &client = VibratorServiceClient::GetInstance(); + bool ret = client.HandleVibratorData(info); + if (!ret) { + MISC_HILOGE("Handle bibrator data failed, ret:%{public}d", ret); + return PARAMETER_ERROR; + } + MISC_HILOGD("Success to process plug event"); return NO_ERROR; } } // namespace Sensors diff --git a/frameworks/native/vibrator/src/vibrator_service_client.cpp b/frameworks/native/vibrator/src/vibrator_service_client.cpp index 92528086c3505aba0590c0beaa09f8e3ed480852..71273ad451be01170a026ace55fdf23d681aeb6c 100644 --- a/frameworks/native/vibrator/src/vibrator_service_client.cpp +++ b/frameworks/native/vibrator/src/vibrator_service_client.cpp @@ -92,11 +92,6 @@ int32_t VibratorServiceClient::InitServiceClient() MISC_HILOGE("TransferClientRemoteObject failed, ret:%{public}d", ret); return ERROR; } - ret = GetVibratorCapacity(); - if (ret != ERR_OK) { - MISC_HILOGE("GetVibratorCapacity failed, ret:%{public}d", ret); - return ERROR; - } return ERR_OK; } #ifdef HIVIEWDFX_HISYSEVENT_ENABLE @@ -123,9 +118,11 @@ int32_t VibratorServiceClient::TransferClientRemoteObject() return ret; } -int32_t VibratorServiceClient::Vibrate(int32_t vibratorId, int32_t timeOut, int32_t usage, bool systemUsage) +int32_t VibratorServiceClient::Vibrate(const VibratorIdentifier &identifier, int32_t timeOut, int32_t usage, + bool systemUsage) { - MISC_HILOGD("Vibrate begin, time:%{public}d, usage:%{public}d", timeOut, usage); + MISC_HILOGD("Vibrate begin, time:%{public}d, usage:%{public}d, deviceId:%{public}d, vibratorId:%{public}d", + timeOut, usage, identifier.deviceId, identifier.vibratorId); int32_t ret = InitServiceClient(); if (ret != ERR_OK) { MISC_HILOGE("InitServiceClient failed, ret:%{public}d", ret); @@ -136,7 +133,10 @@ int32_t VibratorServiceClient::Vibrate(int32_t vibratorId, int32_t timeOut, int3 #ifdef HIVIEWDFX_HITRACE_ENABLE StartTrace(HITRACE_TAG_SENSORS, "VibrateTime"); #endif // HIVIEWDFX_HITRACE_ENABLE - ret = miscdeviceProxy_->Vibrate(vibratorId, timeOut, usage, systemUsage); + VibratorIdentifierIPC vibrateIdentifier; + vibrateIdentifier.deviceId = identifier.deviceId; + vibrateIdentifier.vibratorId = identifier.vibratorId; + ret = miscdeviceProxy_->Vibrate(vibrateIdentifier, timeOut, usage, systemUsage); WriteVibratorHiSysIPCEvent(IMiscdeviceServiceIpcCode::COMMAND_VIBRATE, ret); #ifdef HIVIEWDFX_HITRACE_ENABLE FinishTrace(HITRACE_TAG_SENSORS); @@ -147,7 +147,7 @@ int32_t VibratorServiceClient::Vibrate(int32_t vibratorId, int32_t timeOut, int3 return ret; } -int32_t VibratorServiceClient::Vibrate(int32_t vibratorId, const std::string &effect, +int32_t VibratorServiceClient::Vibrate(const VibratorIdentifier &identifier, const std::string &effect, int32_t loopCount, int32_t usage, bool systemUsage) { MISC_HILOGD("Vibrate begin, effect:%{public}s, loopCount:%{public}d, usage:%{public}d", @@ -162,7 +162,10 @@ int32_t VibratorServiceClient::Vibrate(int32_t vibratorId, const std::string &ef #ifdef HIVIEWDFX_HITRACE_ENABLE StartTrace(HITRACE_TAG_SENSORS, "VibrateEffect"); #endif // HIVIEWDFX_HITRACE_ENABLE - ret = miscdeviceProxy_->PlayVibratorEffect(vibratorId, effect, loopCount, usage, systemUsage); + VibratorIdentifierIPC vibrateIdentifier; + vibrateIdentifier.deviceId = identifier.deviceId; + vibrateIdentifier.vibratorId = identifier.vibratorId; + ret = miscdeviceProxy_->PlayVibratorEffect(vibrateIdentifier, effect, loopCount, usage, systemUsage); WriteVibratorHiSysIPCEvent(IMiscdeviceServiceIpcCode::COMMAND_PLAY_VIBRATOR_EFFECT, ret); #ifdef HIVIEWDFX_HITRACE_ENABLE FinishTrace(HITRACE_TAG_SENSORS); @@ -175,8 +178,8 @@ int32_t VibratorServiceClient::Vibrate(int32_t vibratorId, const std::string &ef } #ifdef OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM -int32_t VibratorServiceClient::PlayVibratorCustom(int32_t vibratorId, const RawFileDescriptor &rawFd, int32_t usage, - bool systemUsage, const VibratorParameter ¶meter) +int32_t VibratorServiceClient::PlayVibratorCustom(const VibratorIdentifier &identifier, const RawFileDescriptor &rawFd, + int32_t usage, bool systemUsage, const VibratorParameter ¶meter) { MISC_HILOGD("Vibrate begin, fd:%{public}d, offset:%{public}lld, length:%{public}lld, usage:%{public}d", rawFd.fd, static_cast(rawFd.offset), static_cast(rawFd.length), usage); @@ -190,11 +193,16 @@ int32_t VibratorServiceClient::PlayVibratorCustom(int32_t vibratorId, const RawF #ifdef HIVIEWDFX_HITRACE_ENABLE StartTrace(HITRACE_TAG_SENSORS, "PlayVibratorCustom"); #endif // HIVIEWDFX_HITRACE_ENABLE - VibrateParameter vibateParameter; - vibateParameter.intensity = parameter.intensity; - vibateParameter.frequency = parameter.frequency; - ret = miscdeviceProxy_->PlayVibratorCustom(vibratorId, rawFd.fd, rawFd.offset, rawFd.length, usage, systemUsage, - vibateParameter); + CustomHapticInfoIPC customHapticInfoIPC; + customHapticInfoIPC.usage = usage; + customHapticInfoIPC.systemUsage = systemUsage; + customHapticInfoIPC.parameter.intensity = parameter.intensity; + customHapticInfoIPC.parameter.frequency = parameter.frequency; + VibratorIdentifierIPC vibrateIdentifier; + vibrateIdentifier.deviceId = identifier.deviceId; + vibrateIdentifier.vibratorId = identifier.vibratorId; + ret = miscdeviceProxy_->PlayVibratorCustom(vibrateIdentifier, rawFd.fd, rawFd.offset, + rawFd.length, customHapticInfoIPC); WriteVibratorHiSysIPCEvent(IMiscdeviceServiceIpcCode::COMMAND_PLAY_VIBRATOR_CUSTOM, ret); #ifdef HIVIEWDFX_HITRACE_ENABLE FinishTrace(HITRACE_TAG_SENSORS); @@ -206,9 +214,10 @@ int32_t VibratorServiceClient::PlayVibratorCustom(int32_t vibratorId, const RawF } #endif // OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM -int32_t VibratorServiceClient::StopVibrator(int32_t vibratorId, const std::string &mode) +int32_t VibratorServiceClient::StopVibrator(const VibratorIdentifier &identifier, const std::string &mode) { - MISC_HILOGD("StopVibrator begin, vibratorId:%{public}d, mode:%{public}s", vibratorId, mode.c_str()); + MISC_HILOGD("StopVibrator begin, deviceId:%{public}d, vibratorId:%{public}d, mode:%{public}s", identifier.deviceId, + identifier.vibratorId, mode.c_str()); int32_t ret = InitServiceClient(); if (ret != ERR_OK) { MISC_HILOGE("InitServiceClient failed, ret:%{public}d", ret); @@ -219,7 +228,10 @@ int32_t VibratorServiceClient::StopVibrator(int32_t vibratorId, const std::strin #ifdef HIVIEWDFX_HITRACE_ENABLE StartTrace(HITRACE_TAG_SENSORS, "StopVibratorByMode"); #endif // HIVIEWDFX_HITRACE_ENABLE - ret = miscdeviceProxy_->StopVibratorByMode(vibratorId, mode); + VibratorIdentifierIPC vibrateIdentifier; + vibrateIdentifier.deviceId = identifier.deviceId; + vibrateIdentifier.vibratorId = identifier.vibratorId; + ret = miscdeviceProxy_->StopVibratorByMode(vibrateIdentifier, mode); WriteVibratorHiSysIPCEvent(IMiscdeviceServiceIpcCode::COMMAND_STOP_VIBRATOR_BY_MODE, ret); #ifdef HIVIEWDFX_HITRACE_ENABLE FinishTrace(HITRACE_TAG_SENSORS); @@ -230,9 +242,10 @@ int32_t VibratorServiceClient::StopVibrator(int32_t vibratorId, const std::strin return ret; } -int32_t VibratorServiceClient::StopVibrator(int32_t vibratorId) +int32_t VibratorServiceClient::StopVibrator(const VibratorIdentifier &identifier) { - MISC_HILOGD("StopVibrator begin, vibratorId:%{public}d", vibratorId); + MISC_HILOGD("StopVibrator begin, deviceId:%{public}d, vibratorId:%{public}d", identifier.deviceId, + identifier.vibratorId); int32_t ret = InitServiceClient(); if (ret != ERR_OK) { MISC_HILOGE("InitServiceClient failed, ret:%{public}d", ret); @@ -243,7 +256,10 @@ int32_t VibratorServiceClient::StopVibrator(int32_t vibratorId) #ifdef HIVIEWDFX_HITRACE_ENABLE StartTrace(HITRACE_TAG_SENSORS, "StopVibratorAll"); #endif // HIVIEWDFX_HITRACE_ENABLE - ret = miscdeviceProxy_->StopVibrator(vibratorId); + VibratorIdentifierIPC vibrateIdentifier; + vibrateIdentifier.deviceId = identifier.deviceId; + vibrateIdentifier.vibratorId = identifier.vibratorId; + ret = miscdeviceProxy_->StopVibrator(vibrateIdentifier); WriteVibratorHiSysIPCEvent(IMiscdeviceServiceIpcCode::COMMAND_STOP_VIBRATOR, ret); #ifdef HIVIEWDFX_HITRACE_ENABLE FinishTrace(HITRACE_TAG_SENSORS); @@ -254,7 +270,7 @@ int32_t VibratorServiceClient::StopVibrator(int32_t vibratorId) return ret; } -bool VibratorServiceClient::IsHdHapticSupported() +bool VibratorServiceClient::IsHdHapticSupported(const VibratorIdentifier &identifier) { CALL_LOG_ENTER; int32_t ret = InitServiceClient(); @@ -262,10 +278,24 @@ bool VibratorServiceClient::IsHdHapticSupported() MISC_HILOGE("InitServiceClient failed, ret:%{public}d", ret); return MISC_NATIVE_GET_SERVICE_ERR; } + VibratorCapacity capacity_; + std::lock_guard clientLock(clientMutex_); + CHKPR(miscdeviceProxy_, ERROR); +#ifdef HIVIEWDFX_HITRACE_ENABLE + StartTrace(HITRACE_TAG_SENSORS, "IsHdHapticSupported"); +#endif // HIVIEWDFX_HITRACE_ENABLE + ret = GetVibratorCapacity(identifier, capacity_); +#ifdef HIVIEWDFX_HITRACE_ENABLE + FinishTrace(HITRACE_TAG_SENSORS); +#endif // HIVIEWDFX_HITRACE_ENABLE + if (ret != ERR_OK) { + MISC_HILOGE("IsHdHapticSupported failed, ret:%{public}d", ret); + } return capacity_.isSupportHdHaptic; } -int32_t VibratorServiceClient::IsSupportEffect(const std::string &effect, bool &state) +int32_t VibratorServiceClient::IsSupportEffect(const VibratorIdentifier &identifier, const std::string &effect, + bool &state) { MISC_HILOGD("IsSupportEffect begin, effect:%{public}s", effect.c_str()); int32_t ret = InitServiceClient(); @@ -278,7 +308,10 @@ int32_t VibratorServiceClient::IsSupportEffect(const std::string &effect, bool & #ifdef HIVIEWDFX_HITRACE_ENABLE StartTrace(HITRACE_TAG_SENSORS, "VibrateEffect"); #endif // HIVIEWDFX_HITRACE_ENABLE - ret = miscdeviceProxy_->IsSupportEffect(effect, state); + VibratorIdentifierIPC vibrateIdentifier; + vibrateIdentifier.deviceId = identifier.deviceId; + vibrateIdentifier.vibratorId = identifier.vibratorId; + ret = miscdeviceProxy_->IsSupportEffect(vibrateIdentifier, effect, state); WriteOtherHiSysIPCEvent(IMiscdeviceServiceIpcCode::COMMAND_IS_SUPPORT_EFFECT, ret); #ifdef HIVIEWDFX_HITRACE_ENABLE FinishTrace(HITRACE_TAG_SENSORS); @@ -364,7 +397,7 @@ int32_t VibratorServiceClient::PreProcess(const VibratorFileDescription &fd, Vib return ConvertVibratorPackage(pkg, package); } -int32_t VibratorServiceClient::GetDelayTime(int32_t &delayTime) +int32_t VibratorServiceClient::GetDelayTime(const VibratorIdentifier &identifier, int32_t &delayTime) { int32_t ret = InitServiceClient(); if (ret != ERR_OK) { @@ -376,7 +409,10 @@ int32_t VibratorServiceClient::GetDelayTime(int32_t &delayTime) #ifdef HIVIEWDFX_HITRACE_ENABLE StartTrace(HITRACE_TAG_SENSORS, "GetDelayTime"); #endif // HIVIEWDFX_HITRACE_ENABLE - ret = miscdeviceProxy_->GetDelayTime(delayTime); + VibratorIdentifierIPC vibrateIdentifier; + vibrateIdentifier.deviceId = identifier.deviceId; + vibrateIdentifier.vibratorId = identifier.vibratorId; + ret = miscdeviceProxy_->GetDelayTime(vibrateIdentifier, delayTime); WriteOtherHiSysIPCEvent(IMiscdeviceServiceIpcCode::COMMAND_GET_DELAY_TIME, ret); #ifdef HIVIEWDFX_HITRACE_ENABLE FinishTrace(HITRACE_TAG_SENSORS); @@ -387,8 +423,8 @@ int32_t VibratorServiceClient::GetDelayTime(int32_t &delayTime) return ret; } -int32_t VibratorServiceClient::InitPlayPattern(const VibratorPattern &pattern, int32_t usage, - bool systemUsage, const VibratorParameter ¶meter) +int32_t VibratorServiceClient::InitPlayPattern(const VibratorIdentifier &identifier, const VibratorPattern &pattern, + int32_t usage, bool systemUsage, const VibratorParameter ¶meter) { VibratePattern vibratePattern = {}; vibratePattern.startTime = pattern.time; @@ -418,18 +454,23 @@ int32_t VibratorServiceClient::InitPlayPattern(const VibratorPattern &pattern, i vibratePattern.events.emplace_back(event); vibratePattern.patternDuration = pattern.patternDuration; } - VibrateParameter vibateParameter; - vibateParameter.intensity = parameter.intensity; - vibateParameter.frequency = parameter.frequency; + CustomHapticInfoIPC customHapticInfoIPC; + customHapticInfoIPC.usage = usage; + customHapticInfoIPC.systemUsage = systemUsage; + customHapticInfoIPC.parameter.intensity = parameter.intensity; + customHapticInfoIPC.parameter.frequency = parameter.frequency; + VibratorIdentifierIPC vibrateIdentifier; + vibrateIdentifier.deviceId = identifier.deviceId; + vibrateIdentifier.vibratorId = identifier.vibratorId; std::lock_guard clientLock(clientMutex_); CHKPR(miscdeviceProxy_, ERROR); - int32_t ret = miscdeviceProxy_->PlayPattern(vibratePattern, usage, systemUsage, vibateParameter); + int32_t ret = miscdeviceProxy_->PlayPattern(vibrateIdentifier, vibratePattern, customHapticInfoIPC); WriteOtherHiSysIPCEvent(IMiscdeviceServiceIpcCode::COMMAND_PLAY_PATTERN, ret); return ret; } -int32_t VibratorServiceClient::PlayPattern(const VibratorPattern &pattern, int32_t usage, - bool systemUsage, const VibratorParameter ¶meter) +int32_t VibratorServiceClient::PlayPattern(const VibratorIdentifier &identifier, const VibratorPattern &pattern, + int32_t usage, bool systemUsage, const VibratorParameter ¶meter) { MISC_HILOGD("Vibrate begin, usage:%{public}d", usage); int32_t ret = InitServiceClient(); @@ -440,7 +481,7 @@ int32_t VibratorServiceClient::PlayPattern(const VibratorPattern &pattern, int32 #ifdef HIVIEWDFX_HITRACE_ENABLE StartTrace(HITRACE_TAG_SENSORS, "PlayPattern"); #endif // HIVIEWDFX_HITRACE_ENABLE - ret = InitPlayPattern(pattern, usage, systemUsage, parameter); + ret = InitPlayPattern(identifier, pattern, usage, systemUsage, parameter); #ifdef HIVIEWDFX_HITRACE_ENABLE FinishTrace(HITRACE_TAG_SENSORS); #endif // HIVIEWDFX_HITRACE_ENABLE @@ -532,11 +573,11 @@ int32_t VibratorServiceClient::FreeVibratorPackage(VibratorPackage &package) return ERR_OK; } -int32_t VibratorServiceClient::PlayPrimitiveEffect(int32_t vibratorId, const std::string &effect, int32_t intensity, - int32_t usage, bool systemUsage, int32_t count) +int32_t VibratorServiceClient::PlayPrimitiveEffect(const VibratorIdentifier &identifier, const std::string &effect, + const PrimitiveEffect &primitiveEffect) { MISC_HILOGD("Vibrate begin, effect:%{public}s, intensity:%{public}d, usage:%{public}d, count:%{public}d", - effect.c_str(), intensity, usage, count); + effect.c_str(), primitiveEffect.intensity, primitiveEffect.usage, primitiveEffect.count); int32_t ret = InitServiceClient(); if (ret != ERR_OK) { MISC_HILOGE("InitServiceClient failed, ret:%{public}d", ret); @@ -547,39 +588,65 @@ int32_t VibratorServiceClient::PlayPrimitiveEffect(int32_t vibratorId, const std #ifdef HIVIEWDFX_HITRACE_ENABLE StartTrace(HITRACE_TAG_SENSORS, "PlayPrimitiveEffect"); #endif // HIVIEWDFX_HITRACE_ENABLE - ret = miscdeviceProxy_->PlayPrimitiveEffect(vibratorId, effect, intensity, usage, systemUsage, count); + PrimitiveEffectIPC primitiveEffectIPC; + primitiveEffectIPC.intensity = primitiveEffect.intensity; + primitiveEffectIPC.usage = primitiveEffect.usage; + primitiveEffectIPC.systemUsage = primitiveEffect.systemUsage; + primitiveEffectIPC.count = primitiveEffect.count; + VibratorIdentifierIPC vibrateIdentifier; + vibrateIdentifier.deviceId = identifier.deviceId; + vibrateIdentifier.vibratorId = identifier.vibratorId; + ret = miscdeviceProxy_->PlayPrimitiveEffect(vibrateIdentifier, effect, primitiveEffectIPC); WriteOtherHiSysIPCEvent(IMiscdeviceServiceIpcCode::COMMAND_PLAY_PRIMITIVE_EFFECT, ret); #ifdef HIVIEWDFX_HITRACE_ENABLE FinishTrace(HITRACE_TAG_SENSORS); #endif // HIVIEWDFX_HITRACE_ENABLE if (ret != ERR_OK) { MISC_HILOGE("Play primitive effect failed, ret:%{public}d, effect:%{public}s, intensity:%{public}d," - "usage:%{public}d, count:%{public}d", ret, effect.c_str(), intensity, usage, count); + "usage:%{public}d, count:%{public}d", ret, effect.c_str(), primitiveEffect.intensity, + primitiveEffect.usage, primitiveEffect.count); } return ret; } -int32_t VibratorServiceClient::GetVibratorCapacity() +int32_t VibratorServiceClient::GetVibratorCapacity(const VibratorIdentifier &identifier, VibratorCapacity &capacity) { CHKPR(miscdeviceProxy_, ERROR); #ifdef HIVIEWDFX_HITRACE_ENABLE StartTrace(HITRACE_TAG_SENSORS, "GetVibratorCapacity"); #endif // HIVIEWDFX_HITRACE_ENABLE - int32_t ret = miscdeviceProxy_->GetVibratorCapacity(capacity_); + VibratorIdentifierIPC vibrateIdentifier; + vibrateIdentifier.deviceId = identifier.deviceId; + vibrateIdentifier.vibratorId = identifier.vibratorId; + int32_t ret = miscdeviceProxy_->GetVibratorCapacity(vibrateIdentifier, capacity); WriteVibratorHiSysIPCEvent(IMiscdeviceServiceIpcCode::COMMAND_GET_VIBRATOR_CAPACITY, ret); #ifdef HIVIEWDFX_HITRACE_ENABLE FinishTrace(HITRACE_TAG_SENSORS); #endif // HIVIEWDFX_HITRACE_ENABLE - capacity_.Dump(); + capacity.Dump(); return ret; } -bool VibratorServiceClient::IsSupportVibratorCustom() +bool VibratorServiceClient::IsSupportVibratorCustom(const VibratorIdentifier &identifier) { + MISC_HILOGD("Vibrate begin"); int32_t ret = InitServiceClient(); if (ret != ERR_OK) { MISC_HILOGE("InitServiceClient failed, ret:%{public}d", ret); } + VibratorCapacity capacity_; + std::lock_guard clientLock(clientMutex_); + CHKPR(miscdeviceProxy_, ERROR); +#ifdef HIVIEWDFX_HITRACE_ENABLE + StartTrace(HITRACE_TAG_SENSORS, "IsSupportVibratorCustom"); +#endif // HIVIEWDFX_HITRACE_ENABLE + ret = GetVibratorCapacity(identifier, capacity_); +#ifdef HIVIEWDFX_HITRACE_ENABLE + FinishTrace(HITRACE_TAG_SENSORS); +#endif // HIVIEWDFX_HITRACE_ENABLE + if (ret != ERR_OK) { + MISC_HILOGE("Is support vibrator custom, ret:%{public}d", ret); + } return (capacity_.isSupportHdHaptic || capacity_.isSupportPresetMapping || capacity_.isSupportTimeDelay); } @@ -591,6 +658,151 @@ int32_t VibratorServiceClient::SeekTimeOnPackage(int32_t seekTime, const Vibrato return ConvertVibratorPackage(convertPackage, seekPackage); } +int32_t VibratorServiceClient::SubscribeVibratorPlugInfo(const VibratorUser *user) +{ + MISC_HILOGD("In, SubscribeVibratorPlugInfo"); + CHKPR(user, OHOS::Sensors::ERROR); + CHKPR(user->callback, OHOS::Sensors::ERROR); + + int32_t ret = InitServiceClient(); + if (ret != ERR_OK) { + MISC_HILOGE("InitServiceClient failed, ret:%{public}d", ret); + return MISC_NATIVE_GET_SERVICE_ERR; + } + + std::lock_guard subscribeLock(subscribeMutex_); + auto status = subscribeSet_.insert(user); + if (!status.second) { + MISC_HILOGD("User has been subscribed"); + }else { + std::lock_guard clientLock(clientMutex_); + auto remoteObject = vibratorClient_->AsObject(); + CHKPR(remoteObject, MISC_NATIVE_GET_SERVICE_ERR); + CHKPR(miscdeviceProxy_, ERROR); +#ifdef HIVIEWDFX_HITRACE_ENABLE + StartTrace(HITRACE_TAG_SENSORS, "SubscribeVibratorPlugInfo"); +#endif // HIVIEWDFX_HITRACE_ENABLE + ret = miscdeviceProxy_->SubscribeVibratorPlugInfo(remoteObject); + WriteOtherHiSysIPCEvent(IMiscdeviceServiceIpcCode::COMMAND_SUBSCRIBE_VIBRATOR_PLUG_INFO, ret); +#ifdef HIVIEWDFX_HITRACE_ENABLE + FinishTrace(HITRACE_TAG_SENSORS); +#endif // HIVIEWDFX_HITRACE_ENABLE + if (ret != ERR_OK) { + MISC_HILOGE("Subscribe vibrator plug info failed"); + return ret; + } + } + return OHOS::Sensors::SUCCESS; +} + +int32_t VibratorServiceClient::UnsubscribeVibratorPlugInfo(const VibratorUser *user) +{ + MISC_HILOGD("In, UnsubscribeVibratorPlugInfo"); + CHKPR(user, OHOS::Sensors::ERROR); + CHKPR(user->callback, OHOS::Sensors::ERROR); + + std::lock_guard subscribeLock(subscribeMutex_); + if (subscribeSet_.find(user) == subscribeSet_.end()) { + MISC_HILOGD("Deactivate user first"); + return OHOS::Sensors::CALLBACK_UNSUBSCRIBED; + } + subscribeSet_.erase(user); + return OHOS::Sensors::SUCCESS; +} + +std::set VibratorServiceClient::GetSubscribeUserCallback(int32_t deviceId) +{ + CALL_LOG_ENTER; + std::lock_guard subscribeLock(subscribeMutex_); + std::set callback; + for (const auto &it : subscribeSet_) { + auto ret = callback.insert(it->callback); + if (!ret.second) { + MISC_HILOGD("callback insert fail"); + } + } + return callback; +} + +bool VibratorServiceClient::HandleVibratorData(VibratorDeviceInfo info) __attribute__((no_sanitize("cfi"))) +{ + CALL_LOG_ENTER; + if(info.type == PLUG_STATE_EVENT_PLUG_OUT) { + std::lock_guard VibratorEffectLock(vibratorEffectMutex_); + for (auto it = vibratorEffectMap_.begin(); it != vibratorEffectMap_.end(); ) { + if (it->first.deviceId == info.deviceId) { + it = vibratorEffectMap_.erase(it); + } else { + ++it; + } + } + } + std::lock_guard subscribeLock(subscribeMutex_); + auto callbacks = GetSubscribeUserCallback(info.deviceId); + MISC_HILOGD("callbacks.size() = %{public}d", callbacks.size()); + MISC_HILOGD("VibratorDeviceInfo = [type = %{public}d, deviceId = %{public}d]", info.type, info.deviceId); + for (const auto &callback : callbacks) { + MISC_HILOGD("callback is run"); + if(callback != nullptr) + callback(&info); + } + return true; +} + +void VibratorServiceClient::SetUsage(const VibratorIdentifier &identifier, int32_t usage, bool systemUsage) +{ + std::lock_guard VibratorEffectLock(vibratorEffectMutex_); + auto it = vibratorEffectMap_.find(identifier); + if (it != vibratorEffectMap_.end()) { + it->second.usage = usage; + it->second.systemUsage = systemUsage; + } else { + VibratorEffectParameter param = { + .usage = usage, + .systemUsage = systemUsage, + }; + vibratorEffectMap_[identifier] = param; + } +} + +void VibratorServiceClient::SetLoopCount(const VibratorIdentifier &identifier, int32_t count) +{ + std::lock_guard VibratorEffectLock(vibratorEffectMutex_); + auto it = vibratorEffectMap_.find(identifier); + if (it != vibratorEffectMap_.end()) { + it->second.loopCount = count; + } else { + VibratorEffectParameter param = { + .loopCount = count, + }; + vibratorEffectMap_[identifier] = param; + } +} + +void VibratorServiceClient::SetParameters(const VibratorIdentifier &identifier, const VibratorParameter ¶meter) +{ + std::lock_guard VibratorEffectLock(vibratorEffectMutex_); + auto it = vibratorEffectMap_.find(identifier); + if (it != vibratorEffectMap_.end()) { + it->second.vibratorParameter = parameter; + } else { + VibratorEffectParameter param = { + .vibratorParameter = parameter, + }; + vibratorEffectMap_[identifier] = param; + } +} + +VibratorEffectParameter VibratorServiceClient::GetVibratorEffectParameter(const VibratorIdentifier &identifier) +{ + std::lock_guard VibratorEffectLock(vibratorEffectMutex_); + auto it = vibratorEffectMap_.find(identifier); + if (it != vibratorEffectMap_.end()) { + return it->second; + } + return VibratorEffectParameter(); +} + void VibratorServiceClient::ConvertSeekVibratorPackage(const VibratorPackage &completePackage, VibratePackage &convertPackage, int32_t seekTime) { @@ -681,6 +893,81 @@ bool VibratorServiceClient::SkipEventAndConvertVibratorEvent(const VibratorEvent return false; } +int32_t VibratorServiceClient::GetVibratorIdList(const VibratorIdentifier& identifier, + std::vector& vibratorInfo) +{ + CALL_LOG_ENTER; + MISC_HILOGD("VibratorIdentifier = [deviceId = %{public}d, vibratorId = %{public}d]", identifier.deviceId, + identifier.vibratorId); + int32_t ret = InitServiceClient(); + if (ret != ERR_OK) { + MISC_HILOGE("InitServiceClient failed, ret:%{public}d", ret); + return MISC_NATIVE_GET_SERVICE_ERR; + } + CHKPR(miscdeviceProxy_, OHOS::Sensors::ERROR); + + VibratorIdentifierIPC param; + param.deviceId = identifier.deviceId; + param.vibratorId = identifier.vibratorId; + std::vector vibratorInfoList; +#ifdef HIVIEWDFX_HITRACE_ENABLE + StartTrace(HITRACE_TAG_SENSORS, "GetVibratorIdList"); +#endif // HIVIEWDFX_HITRACE_ENABLE + ret = miscdeviceProxy_->GetVibratorIdList(param, vibratorInfoList); + WriteOtherHiSysIPCEvent(IMiscdeviceServiceIpcCode::COMMAND_GET_VIBRATOR_ID_LIST, ret); +#ifdef HIVIEWDFX_HITRACE_ENABLE + FinishTrace(HITRACE_TAG_SENSORS); +#endif // HIVIEWDFX_HITRACE_ENABLE + if (ret != ERR_OK) { + MISC_HILOGE("Get vibrator info list failed, [ret = %{public}d, deviceId = %{public}d,\ + vibratorId = %{public}d]", ret, identifier.deviceId, identifier.vibratorId); + return ret; + } + VibratorInfos resInfo; + for (auto &info : vibratorInfoList) { + resInfo.deviceId = info.deviceId; + resInfo.vibratorId = info.vibratorId; + resInfo.deviceName = info.deviceName; + resInfo.isSupportHdHaptic = info.isSupportHdHaptic; + resInfo.isLocalVibrator = info.isLocalVibrator; + vibratorInfo.push_back(resInfo); + } + return OHOS::Sensors::SUCCESS; +} + +int32_t VibratorServiceClient::GetEffectInfo(const VibratorIdentifier& identifier, + const std::string& effectType, EffectInfo& effectInfo) +{ + CALL_LOG_ENTER; + MISC_HILOGD("VibratorIdentifier = [deviceId = %{public}d, vibratorId = %{public}d, effectType = %{public}s]", + identifier.deviceId, identifier.vibratorId, effectType.c_str()); + int32_t ret = InitServiceClient(); + if (ret != OHOS::Sensors::SUCCESS) { + MISC_HILOGE("InitServiceClient failed, ret:%{public}d", ret); + return MISC_NATIVE_GET_SERVICE_ERR; + } + CHKPR(miscdeviceProxy_, OHOS::Sensors::ERROR); + VibratorIdentifierIPC param; + param.deviceId = identifier.deviceId; + param.vibratorId = identifier.vibratorId; + EffectInfoIPC resInfo; +#ifdef HIVIEWDFX_HITRACE_ENABLE + StartTrace(HITRACE_TAG_SENSORS, "GetEffectInfo"); +#endif // HIVIEWDFX_HITRACE_ENABLE + ret = miscdeviceProxy_->GetEffectInfo(param, effectType, resInfo); + WriteOtherHiSysIPCEvent(IMiscdeviceServiceIpcCode::COMMAND_GET_EFFECT_INFO, ret); +#ifdef HIVIEWDFX_HITRACE_ENABLE + FinishTrace(HITRACE_TAG_SENSORS); +#endif // HIVIEWDFX_HITRACE_ENABLE + if (ret != ERR_OK) { + MISC_HILOGE("Get effect info failed, [ret = %{public}d, deviceId = %{public}d, vibratorId = %{public}d,\ + effectType = %{public}s]", ret, identifier.deviceId, identifier.vibratorId, effectType.c_str()); + return ret; + } + effectInfo.isSupportEffect = resInfo.isSupportEffect; + return OHOS::Sensors::SUCCESS; +} + void VibratorServiceClient::WriteVibratorHiSysIPCEvent(IMiscdeviceServiceIpcCode code, int32_t ret) { #ifdef HIVIEWDFX_HISYSEVENT_ENABLE @@ -710,6 +997,14 @@ void VibratorServiceClient::WriteVibratorHiSysIPCEvent(IMiscdeviceServiceIpcCode HiSysEventWrite(HiSysEvent::Domain::MISCDEVICE, "MISC_SERVICE_IPC_EXCEPTION", HiSysEvent::EventType::FAULT, "PKG_NAME", "GetVibratorCapacity", "ERROR_CODE", ret); break; + case IMiscdeviceServiceIpcCode::COMMAND_GET_VIBRATOR_ID_LIST: + HiSysEventWrite(HiSysEvent::Domain::MISCDEVICE, "MISC_SERVICE_IPC_EXCEPTION", + HiSysEvent::EventType::FAULT, "PKG_NAME", "GetVibratorIdList", "ERROR_CODE", ret); + break; + case IMiscdeviceServiceIpcCode::COMMAND_GET_EFFECT_INFO: + HiSysEventWrite(HiSysEvent::Domain::MISCDEVICE, "MISC_SERVICE_IPC_EXCEPTION", + HiSysEvent::EventType::FAULT, "PKG_NAME", "GetEffectInfo", "ERROR_CODE", ret); + break; default: MISC_HILOGW("Code does not exist, code:%{public}d", static_cast(code)); break; diff --git a/frameworks/native/vibrator/vibrator_agent.cpp b/frameworks/native/vibrator/vibrator_agent.cpp index af47f7b8d3ad8fb89632673c365287c913b7fb87..177de3b44b38db43de461a7a63b6df4d6199fe12 100644 --- a/frameworks/native/vibrator/vibrator_agent.cpp +++ b/frameworks/native/vibrator/vibrator_agent.cpp @@ -27,11 +27,6 @@ namespace Sensors { using OHOS::Sensors::VibratorServiceClient; namespace { -constexpr int32_t DEFAULT_VIBRATOR_ID = 123; -int32_t g_loopCount = 1; -int32_t g_usage = USAGE_UNKNOWN; -bool g_systemUsage = false; -VibratorParameter g_vibratorParameter; const std::string PHONE_TYPE = "phone"; const int32_t INTENSITY_ADJUST_MIN = 0; const int32_t INTENSITY_ADJUST_MAX = 100; @@ -51,6 +46,9 @@ static int32_t NormalizeErrCode(int32_t code) case IS_NOT_SUPPORTED: { return IS_NOT_SUPPORTED; } + case CALLBACK_UNSUBSCRIBED : { + return CALLBACK_UNSUBSCRIBED; + } default: { return DEVICE_OPERATION_FAILED; } @@ -58,24 +56,44 @@ static int32_t NormalizeErrCode(int32_t code) } bool SetLoopCount(int32_t count) +{ + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1 + }; + return SetLoopCountEnhanced(identifier, count); +} + +bool SetLoopCountEnhanced(const VibratorIdentifier identifier, int32_t count) { if (count <= 0) { MISC_HILOGE("Input invalid, count is %{public}d", count); return false; } - g_loopCount = count; + auto &client = VibratorServiceClient::GetInstance(); + client.SetLoopCount(identifier, count); return true; } int32_t StartVibrator(const char *effectId) +{ + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1 + }; + return StartVibratorEnhanced(identifier, effectId); +} + +int32_t StartVibratorEnhanced(const VibratorIdentifier identifier, const char *effectId) { MISC_HILOGD("Time delay measurement:start time"); CHKPR(effectId, PARAMETER_ERROR); auto &client = VibratorServiceClient::GetInstance(); - int32_t ret = client.Vibrate(DEFAULT_VIBRATOR_ID, effectId, g_loopCount, g_usage, g_systemUsage); - g_loopCount = 1; - g_usage = USAGE_UNKNOWN; - g_systemUsage = false; + VibratorEffectParameter vibratorEffectParameter = client.GetVibratorEffectParameter(identifier); + int32_t ret = client.Vibrate(identifier, effectId, vibratorEffectParameter.loopCount, + vibratorEffectParameter.usage, vibratorEffectParameter.systemUsage); + client.SetUsage(identifier, USAGE_UNKNOWN, false); + client.SetLoopCount(identifier, 1); if (ret != ERR_OK) { MISC_HILOGD("Vibrate effectId failed, ret:%{public}d", ret); return NormalizeErrCode(ret); @@ -84,15 +102,24 @@ int32_t StartVibrator(const char *effectId) } int32_t StartVibratorOnce(int32_t duration) +{ + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1 + }; + return StartVibratorOnceEnhanced(identifier, duration); +} + +int32_t StartVibratorOnceEnhanced(const VibratorIdentifier identifier, int32_t duration) { if (duration <= 0) { MISC_HILOGE("duration is invalid"); return PARAMETER_ERROR; } auto &client = VibratorServiceClient::GetInstance(); - int32_t ret = client.Vibrate(DEFAULT_VIBRATOR_ID, duration, g_usage, g_systemUsage); - g_usage = USAGE_UNKNOWN; - g_systemUsage = false; + VibratorEffectParameter vibratorEffectParameter = client.GetVibratorEffectParameter(identifier); + int32_t ret = client.Vibrate(identifier, duration, vibratorEffectParameter.usage, vibratorEffectParameter.systemUsage); + client.SetUsage(identifier, USAGE_UNKNOWN, false); if (ret != ERR_OK) { MISC_HILOGD("Vibrate duration failed, ret:%{public}d", ret); return NormalizeErrCode(ret); @@ -101,12 +128,30 @@ int32_t StartVibratorOnce(int32_t duration) } bool IsSupportVibratorCustom() +{ + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1 + }; + return IsSupportVibratorCustomEnhanced(identifier); +} + +bool IsSupportVibratorCustomEnhanced(const VibratorIdentifier identifier) { auto &client = VibratorServiceClient::GetInstance(); - return client.IsSupportVibratorCustom(); + return client.IsSupportVibratorCustom(identifier); } int32_t PlayVibratorCustom(int32_t fd, int64_t offset, int64_t length) +{ + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1 + }; + return PlayVibratorCustomEnhanced(identifier, fd, offset, length); +} + +int32_t PlayVibratorCustomEnhanced(const VibratorIdentifier identifier, int32_t fd, int64_t offset, int64_t length) { #ifdef OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM MISC_HILOGD("Time delay measurement:start time"); @@ -121,11 +166,13 @@ int32_t PlayVibratorCustom(int32_t fd, int64_t offset, int64_t length) .offset = offset, .length = length }; - int32_t ret = client.PlayVibratorCustom(DEFAULT_VIBRATOR_ID, rawFd, g_usage, g_systemUsage, g_vibratorParameter); - g_usage = USAGE_UNKNOWN; - g_systemUsage = false; - g_vibratorParameter.intensity = INTENSITY_ADJUST_MAX; - g_vibratorParameter.frequency = 0; + VibratorEffectParameter vibratorEffectParameter = client.GetVibratorEffectParameter(identifier); + int32_t ret = client.PlayVibratorCustom(identifier, rawFd, vibratorEffectParameter.usage, + vibratorEffectParameter.systemUsage, vibratorEffectParameter.vibratorParameter); + vibratorEffectParameter.vibratorParameter.intensity = INTENSITY_ADJUST_MAX; + vibratorEffectParameter.vibratorParameter.frequency = 0; + client.SetUsage(identifier, USAGE_UNKNOWN, false); + client.SetParameters(identifier, vibratorEffectParameter.vibratorParameter); if (ret != ERR_OK) { MISC_HILOGD("PlayVibratorCustom failed, ret:%{public}d", ret); return NormalizeErrCode(ret); @@ -138,6 +185,15 @@ int32_t PlayVibratorCustom(int32_t fd, int64_t offset, int64_t length) } int32_t StopVibrator(const char *mode) +{ + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1 + }; + return StopVibratorEnhanced(identifier, mode); +} + +int32_t StopVibratorEnhanced(const VibratorIdentifier identifier, const char *mode) { CHKPR(mode, PARAMETER_ERROR); if (strcmp(mode, "time") != 0 && strcmp(mode, "preset") != 0) { @@ -145,7 +201,7 @@ int32_t StopVibrator(const char *mode) return PARAMETER_ERROR; } auto &client = VibratorServiceClient::GetInstance(); - int32_t ret = client.StopVibrator(DEFAULT_VIBRATOR_ID, mode); + int32_t ret = client.StopVibrator(identifier, mode); if (ret != ERR_OK) { MISC_HILOGD("StopVibrator by mode failed, ret:%{public}d, mode:%{public}s", ret, mode); return NormalizeErrCode(ret); @@ -154,9 +210,18 @@ int32_t StopVibrator(const char *mode) } int32_t Cancel() +{ + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1 + }; + return CancelEnhanced(identifier); +} + +int32_t CancelEnhanced(const VibratorIdentifier identifier) { auto &client = VibratorServiceClient::GetInstance(); - int32_t ret = client.StopVibrator(DEFAULT_VIBRATOR_ID); + int32_t ret = client.StopVibrator(identifier); if (ret != ERR_OK) { MISC_HILOGD("StopVibrator failed, ret:%{public}d", ret); return NormalizeErrCode(ret); @@ -165,27 +230,54 @@ int32_t Cancel() } bool SetUsage(int32_t usage, bool systemUsage) +{ + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1 + }; + return SetUsageEnhanced(identifier, usage, systemUsage); +} + +bool SetUsageEnhanced(const VibratorIdentifier identifier, int32_t usage, bool systemUsage) { if ((usage < 0) || (usage >= USAGE_MAX)) { MISC_HILOGE("Input invalid, usage is %{public}d", usage); return false; } - g_usage = usage; - g_systemUsage = systemUsage; + auto &client = VibratorServiceClient::GetInstance(); + client.SetUsage(identifier, usage, systemUsage); return true; } bool IsHdHapticSupported() +{ + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1 + }; + return IsHdHapticSupportedEnhanced(identifier); +} + +bool IsHdHapticSupportedEnhanced(const VibratorIdentifier identifier) { auto &client = VibratorServiceClient::GetInstance(); - return client.IsHdHapticSupported(); + return client.IsHdHapticSupported(identifier); } int32_t IsSupportEffect(const char *effectId, bool *state) +{ + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1 + }; + return IsSupportEffectEnhanced(identifier, effectId, state); +} + +int32_t IsSupportEffectEnhanced(const VibratorIdentifier identifier, const char *effectId, bool *state) { CHKPR(effectId, PARAMETER_ERROR); auto &client = VibratorServiceClient::GetInstance(); - int32_t ret = client.IsSupportEffect(effectId, *state); + int32_t ret = client.IsSupportEffect(identifier, effectId, *state); if (ret != ERR_OK) { MISC_HILOGD("Query effect support failed, ret:%{public}d, effectId:%{public}s", ret, effectId); return NormalizeErrCode(ret); @@ -205,9 +297,18 @@ int32_t PreProcess(const VibratorFileDescription &fd, VibratorPackage &package) } int32_t GetDelayTime(int32_t &delayTime) +{ + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1 + }; + return GetDelayTimeEnhanced(identifier, delayTime); +} + +int32_t GetDelayTimeEnhanced(const VibratorIdentifier identifier, int32_t &delayTime) { auto &client = VibratorServiceClient::GetInstance(); - int32_t ret = client.GetDelayTime(delayTime); + int32_t ret = client.GetDelayTime(identifier, delayTime); if (ret != ERR_OK) { MISC_HILOGD("GetDelayTime failed, ret:%{public}d", ret); return NormalizeErrCode(ret); @@ -216,13 +317,24 @@ int32_t GetDelayTime(int32_t &delayTime) } int32_t PlayPattern(const VibratorPattern &pattern) +{ + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1 + }; + return PlayPatternEnhanced(identifier, pattern); +} + +int32_t PlayPatternEnhanced(const VibratorIdentifier identifier, const VibratorPattern &pattern) { auto &client = VibratorServiceClient::GetInstance(); - int32_t ret = client.PlayPattern(pattern, g_usage, g_systemUsage, g_vibratorParameter); - g_usage = USAGE_UNKNOWN; - g_systemUsage = false; - g_vibratorParameter.intensity = INTENSITY_ADJUST_MAX; - g_vibratorParameter.frequency = 0; + VibratorEffectParameter vibratorEffectParameter = client.GetVibratorEffectParameter(identifier); + int32_t ret = client.PlayPattern(identifier, pattern, vibratorEffectParameter.usage, vibratorEffectParameter.systemUsage, + vibratorEffectParameter.vibratorParameter); + vibratorEffectParameter.vibratorParameter.intensity = INTENSITY_ADJUST_MAX; + vibratorEffectParameter.vibratorParameter.frequency = 0; + client.SetUsage(identifier, USAGE_UNKNOWN, false); + client.SetParameters(identifier, vibratorEffectParameter.vibratorParameter); if (ret != ERR_OK) { MISC_HILOGD("PlayPattern failed, ret:%{public}d", ret); return NormalizeErrCode(ret); @@ -253,6 +365,15 @@ int32_t FreeVibratorPackage(VibratorPackage &package) } bool SetParameters(const VibratorParameter ¶meter) +{ + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1 + }; + return SetParametersEnhanced(identifier, parameter); +} + +bool SetParametersEnhanced(const VibratorIdentifier identifier, const VibratorParameter ¶meter) { if ((parameter.intensity < INTENSITY_ADJUST_MIN) || (parameter.intensity > INTENSITY_ADJUST_MAX) || (parameter.frequency < FREQUENCY_ADJUST_MIN) || (parameter.frequency > FREQUENCY_ADJUST_MAX)) { @@ -260,25 +381,95 @@ bool SetParameters(const VibratorParameter ¶meter) parameter.intensity, parameter.frequency); return false; } - g_vibratorParameter = parameter; + auto &client = VibratorServiceClient::GetInstance(); + client.SetParameters(identifier, parameter); return true; } int32_t PlayPrimitiveEffect(const char *effectId, int32_t intensity) +{ + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1 + }; + return PlayPrimitiveEffectEnhanced(identifier, effectId, intensity); +} + +int32_t PlayPrimitiveEffectEnhanced(const VibratorIdentifier identifier, const char *effectId, int32_t intensity) { MISC_HILOGD("Time delay measurement:start time"); CHKPR(effectId, PARAMETER_ERROR); auto &client = VibratorServiceClient::GetInstance(); - int32_t ret = client.PlayPrimitiveEffect(DEFAULT_VIBRATOR_ID, effectId, intensity, - g_usage, g_systemUsage, g_loopCount); - g_loopCount = 1; - g_usage = USAGE_UNKNOWN; - g_systemUsage = false; + VibratorEffectParameter vibratorEffectParameter = client.GetVibratorEffectParameter(identifier); + PrimitiveEffect primitiveEffect; + primitiveEffect.intensity = intensity; + primitiveEffect.usage = vibratorEffectParameter.usage; + primitiveEffect.systemUsage = vibratorEffectParameter.systemUsage; + primitiveEffect.count = vibratorEffectParameter.loopCount; + int32_t ret = client.PlayPrimitiveEffect(identifier, effectId, primitiveEffect); + client.SetUsage(identifier, USAGE_UNKNOWN, false); + client.SetLoopCount(identifier, 1); if (ret != ERR_OK) { MISC_HILOGD("Play primitive effect failed, ret:%{public}d", ret); return NormalizeErrCode(ret); } return SUCCESS; } + +int32_t GetVibratorIdList(const VibratorIdentifier& identifier, std::vector& vibratorInfo) +{ + CALL_LOG_ENTER; + CHKCR(&identifier, PARAMETER_ERROR, "Invalid parameters"); + MISC_HILOGD("VibratorIdentifier = [deviceId = %{public}d, vibratorId = %{public}d]", identifier.deviceId, + identifier.vibratorId); + auto &client = VibratorServiceClient::GetInstance(); + int32_t ret = client.GetVibratorIdList(identifier, vibratorInfo); + if (ret != ERR_OK) { + MISC_HILOGE("Get vibrator list failed, ret:%{public}d", ret); + return NormalizeErrCode(ret); + } + return SUCCESS; +} + +int32_t GetEffectInfo(const VibratorIdentifier& identifier, const std::string& effectType, EffectInfo& effectInfo) +{ + CALL_LOG_ENTER; + CHKCR(&identifier, PARAMETER_ERROR, "Invalid parameters"); + MISC_HILOGD("VibratorIdentifier = [deviceId = %{public}d, vibratorId = %{public}d]", identifier.deviceId, + identifier.vibratorId); + auto &client = VibratorServiceClient::GetInstance(); + int32_t ret = client.GetEffectInfo(identifier, effectType, effectInfo); + if (ret != ERR_OK) { + effectInfo.isSupportEffect = false; + MISC_HILOGW("Get effect info failed, ret:%{public}d", ret); + } + return SUCCESS; +} + +int32_t SubscribeVibrator(const VibratorUser& user) +{ + CALL_LOG_ENTER; + CHKCR(user.callback, PARAMETER_ERROR, "Invalid parameters"); + auto &client = VibratorServiceClient::GetInstance(); + int32_t ret = client.SubscribeVibratorPlugInfo(&user); + if (ret != ERR_OK) { + MISC_HILOGE("SubscribeVibrator failed, ret:%{public}d", ret); + return NormalizeErrCode(ret); + } + return SUCCESS; +} + +int32_t UnSubscribeVibrator(const VibratorUser& user) +{ + CALL_LOG_ENTER; + CHKCR(user.callback, PARAMETER_ERROR, "Invalid parameters"); + auto &client = VibratorServiceClient::GetInstance(); + int32_t ret = client.UnsubscribeVibratorPlugInfo(&user); + if (ret != ERR_OK) { + MISC_HILOGE("UnsubscribeVibratorPlugInfo failed, ret:%{public}d", ret); + return NormalizeErrCode(ret); + } + return SUCCESS; +} } // namespace Sensors } // namespace OHOS \ No newline at end of file diff --git a/interfaces/inner_api/vibrator/vibrator_agent.h b/interfaces/inner_api/vibrator/vibrator_agent.h index 859d7eac4ae9c6c25681f729b0fe28e6e1bdbdf2..e10328f8b9208ed322583faea6e7156b82a47d62 100644 --- a/interfaces/inner_api/vibrator/vibrator_agent.h +++ b/interfaces/inner_api/vibrator/vibrator_agent.h @@ -29,6 +29,7 @@ */ #ifndef VIBRATOR_AGENT_H #include +#include #include "vibrator_agent_type.h" #define VIBRATOR_AGENT_H @@ -218,6 +219,227 @@ bool SetParameters(const VibratorParameter ¶meter); * @since 12 */ int32_t PlayPrimitiveEffect(const char *effectId, int32_t intensity); + +/** + * @brief Controls this vibrator to perform a vibration with a preset vibration effect. + * + * @param effectId Indicates the preset vibration effect, which is described in {@link vibrator_agent_type.h}, for + * example:{@link VIBRATOR_TYPE_CLOCK_TIMER}: Describes the vibration effect of the vibrator when a user adjusts the + * timer. + * @param param Indicate the device and vibrator information that needs to be controlled, which is described in + * {@link vibrator_agent_type.h}. + * @return Returns 0 if the vibrator vibrates as expected; returns -1 otherwise, for example, the preset + * vibration effect is not supported. + * + * @since 18 + */ +int32_t StartVibratorEnhanced(const VibratorIdentifier identifier, const char *effectId); + +/** + * @brief Controls this vibrator to perform a one-shot vibration at a given duration. + * + * @param duration Indicates the duration that the one-shot vibration lasts, in milliseconds. + * @param identifier Indicate the device and vibrator information that needs to be controlled, which is described in + * {@link vibrator_agent_type.h}. + * @return Returns 0 if the vibrator vibrates as expected; returns -1 otherwise, for example, the given + * duration for the one-shot vibration is invalid. + * + * @since 18 + */ +int32_t StartVibratorOnceEnhanced(const VibratorIdentifier identifier, int32_t duration); + +/** + * @brief Query whether the device supports custom vibration. + * @param identifier Indicate the device and vibrator information that needs to be controlled, which is described in + * {@link vibrator_agent_type.h}. + * @return Returning true indicates support; otherwise, it indicates no support. + * + * @since 18 + */ +bool IsSupportVibratorCustomEnhanced(const VibratorIdentifier identifier); + +/** + * @brief Play a custom vibration sequence. + * + * @param identifier Indicate the device and vibrator information that needs to be controlled, which is described in + * {@link vibrator_agent_type.h}. + * @param fd Indicates the file handle for custom vibration sequence. + * @param offset Indicates the starting address (in bytes) of the custom vibration sequence. + * @param length Indicates the total length (in bytes) of the custom vibration sequence. + * @return Returning 0 indicates success; otherwise, it indicates failure. + * + * @since 18 + */ +int32_t PlayVibratorCustomEnhanced(const VibratorIdentifier identifier, int32_t fd, int64_t offset, int64_t length); + +/** + * @brief Sets the number of cycles for vibration. + * @param identifier Indicate the device and vibrator information that needs to be controlled, which is described in + * {@link vibrator_agent_type.h}. + * @param count Indicates the number of cycles for vibration. + * @since 18 + */ +bool SetLoopCountEnhanced(const VibratorIdentifier identifier, int32_t count); + +/** + * @brief Stop the motor vibration according to the input mode. + * + * @param identifier Indicate the device and vibrator information that needs to be controlled, which is described in + * {@link vibrator_agent_type.h}. + * @param mode Indicates the mode of the vibration to stop. The values can be time and preset, + * respectively representing a one-shot vibration mode and a preset vibration mode. + * @return Returns 0 if the vibration is stopped as expected; returns -1 otherwise. + * @since 18 + */ +int32_t StopVibratorEnhanced(const VibratorIdentifier identifier, const char *mode); + +/** + * @brief Cancel the current motor vibration. + * @param identifier Indicate the device and vibrator information that needs to be controlled, which is described in + * {@link vibrator_agent_type.h}. + * @return Returning 0 indicates success; otherwise, it indicates failure. + * @since 18 + */ +int32_t CancelEnhanced(const VibratorIdentifier identifier); + +/** + * @brief Set the usage of vibration. + * + * @param identifier Indicate the device and vibrator information that needs to be controlled, which is described in + * {@link vibrator_agent_type.h}. + * @param usage Indicates the vibration usage, which is described in {@link vibrator_agent_type.h},for + * example:{@link USAGE_ALARM}: Describes the vibration is used for alarm. + * @since 18 + */ +bool SetUsageEnhanced(const VibratorIdentifier identifier, int32_t usage, bool systemUsage = false); + +/** + * @brief Query whether the HdHaptic is supported. + * @param identifier Indicate the device and vibrator information that needs to be controlled, which is described in + * {@link vibrator_agent_type.h}. + * @return Returning true indicates support; otherwise, it indicates no support. + * + * @since 18 + */ +bool IsHdHapticSupportedEnhanced(const VibratorIdentifier identifier); + +/** + * @brief Query whether a vibration effect is supported. + * + * @param identifier Indicate the device and vibrator information that needs to be controlled, which is described in + * {@link vibrator_agent_type.h}. + * @param effectId Indicates the preset vibration effect, which is described in {@link vibrator_agent_type.h}, for + * example:{@link VIBRATOR_TYPE_CLOCK_TIMER}: Describes the vibration effect of the vibrator when a user adjusts the + * timer. + * @param state Indicates a pointer to the query result. + * @return Returning 0 indicates success; otherwise, it indicates failure. + * + * @since 18 + */ +int32_t IsSupportEffectEnhanced(const VibratorIdentifier identifier, const char *effectId, bool *state); + +/** + * @brief Obtain the vibration delay, the time interval from the time the vibration is issued + * to the time when the vibration is started, which can be used in the scene of sound + * and vibration coordination. + * @param identifier Indicate the device and vibrator information that needs to be controlled, which is described in + * {@link vibrator_agent_type.h}. + * @param delayTime: Out of the parameter, return the vibration time delay, the time interval + * from the time the vibration is issued to the start of the vibration, in milliseconds. + * @return 0 indicates success, otherwise indicates failure. + * @since 18 + */ +int32_t GetDelayTimeEnhanced(const VibratorIdentifier identifier, int32_t &delayTime); + +/** + * @brief Play the vibration sequence. + * @param identifier Indicate the device and vibrator information that needs to be controlled, which is described in + * {@link vibrator_agent_type.h}. + * @param pattern: Vibration sequences, such as {@link VibratorPattern}. + * @return 0 indicates success, otherwise indicates failure. + * @since 18 + */ +int32_t PlayPatternEnhanced(const VibratorIdentifier identifier, const VibratorPattern &pattern); + +/** + * @brief Set the vibration effect adjustment parameters. + * @param identifier Indicate the device and vibrator information that needs to be controlled, which is described in + * {@link vibrator_agent_type.h}. + * @param parameter: Vibration adjustment parameter, such as {@link VibratorParameter}. + * @return true indicates success, otherwise indicates failure. + * @since 18 + */ +bool SetParametersEnhanced(const VibratorIdentifier identifier, const VibratorParameter ¶meter); + +/** + * @brief Control the vibrator to perform vibration with a preset vibration effect at a certain intensity. + * + * @param identifier Indicate the device and vibrator information that needs to be controlled, which is described in + * {@link vibrator_agent_type.h}. + * @param effectId Indicates the preset vibration effect, which is described in {@link vibrator_agent_type.h}, for + * example:{@link VIBRATOR_TYPE_HARD}: Describes the hard vibration effect of the vibrator. + * @param intensity Indicates the intensity of vibration, ranging from 1 to 100. + * @return Returns 0 if the vibrator vibrates as expected; otherwise indicates failure. + * + * @since 18 + */ +int32_t PlayPrimitiveEffectEnhanced(const VibratorIdentifier identifier, const char *effectId, int32_t intensity); + +/** + * @brief Retrieve a list of vibrator IDs available for the specified parameters. + * + * This function fetches the identifiers of all vibrators that match the given parameters. + * + * @param identifier Indicate the device and vibrator information that needs to be controlled, which is described in + * {@link vibrator_agent_type.h}. + * @param vibratorInfo A reference to a vector that will be populated with available vibrator information, + * each represented as a `VibratorInfos` structure. + * @return Returns 0 if the operation is successful; otherwise, indicates failure with an error code. + * + * @since 18 + */ +int32_t GetVibratorIdList(const VibratorIdentifier& identifier, std::vector& vibratorInfo); + +/** + * @brief Retrieve information about a specific vibration effect type. + * + * This function obtains detailed information regarding the specified vibration effect, such as its support status + * and duration. + * + * @param identifier Indicate the device and vibrator information that needs to be controlled, which is described in + * {@link vibrator_agent_type.h}. + * @param effectType A string representing the type of vibration effect to query, as defined in + * {@link vibrator_agent_type.h}. + * @param effectInfo A reference to an `EffectInfo` structure that will be populated with the effect's details. + * @return Returns 0 if the operation is successful; otherwise, indicates failure with an error code. + * + * @since 18 + */ +int32_t GetEffectInfo(const VibratorIdentifier& identifier, const std::string& effectType, EffectInfo& effectInfo); + +/** + * @brief Subscribe a user to receive updates from the vibrator. + * + * This function registers a specified user to receive notifications about vibrator state changes or events. + * + * @param user The user information that needs to be subscribed to the vibrator notifications, defined as `VibratorUser`. + * @return Returns 0 if the subscription is successful; otherwise, indicates failure with an error code. + * + * @since 18 + */ +int32_t SubscribeVibrator(const VibratorUser& user); + +/** + * @brief Unsubscribe a user from receiving updates from the vibrator. + * + * This function removes a specified user from receiving notifications about vibrator state changes or events. + * + * @param user The user information that needs to be unsubscribed from the vibrator notifications, defined as `VibratorUser`. + * @return Returns 0 if the unsubscription is successful; otherwise, indicates failure with an error code. + * + * @since 18 + */ +int32_t UnSubscribeVibrator(const VibratorUser& user); } // namespace Sensors } // namespace OHOS #ifdef __cplusplus diff --git a/interfaces/inner_api/vibrator/vibrator_agent_type.h b/interfaces/inner_api/vibrator/vibrator_agent_type.h index 9c336720cb03112e7bda11fd801e92466d24c4fd..e8db40b8f2cd78a028e3df274cbbf9dc461d9ed1 100644 --- a/interfaces/inner_api/vibrator/vibrator_agent_type.h +++ b/interfaces/inner_api/vibrator/vibrator_agent_type.h @@ -15,11 +15,20 @@ #ifndef VIBRATOR_AGENT_TYPE_H #define VIBRATOR_AGENT_TYPE_H +#include +#include #ifdef __cplusplus extern "C" { #endif +#ifndef NAME_MAX_LEN +#define NAME_MAX_LEN 128 +#endif /* NAME_MAX_LEN */ +#ifndef VIBRATOR_USER_DATA_SIZE +#define VIBRATOR_USER_DATA_SIZE 104 +#endif /* VIBRATOR_USER_DATA_SIZE */ + /** * @brief Describes the vibration effect of the vibrator when a user adjusts the timer. * @@ -225,6 +234,124 @@ typedef struct VibratorParameter { int32_t frequency = 0; // from -100 to 100 int32_t reserved = 0; } VibratorParameter; + +/** + * @brief Represents the information about a vibrator device in the system. + * + * @since 18 + */ +typedef struct VibratorInfos { + int32_t deviceId; + int32_t vibratorId; + std::string deviceName; + bool isSupportHdHaptic; + bool isLocalVibrator; +} VibratorInfos; + +/** + * @brief Represents the parameters for querying vibrator information. + * + * @since 18 + */ +typedef struct VibratorIdentifier { + int32_t deviceId = -1; + int32_t vibratorId = -1; + bool operator<(const VibratorIdentifier& other) const { + if (deviceId != other.deviceId) { + return deviceId < other.deviceId; + } + return vibratorId < other.vibratorId; + } +} VibratorIdentifier; + +/** + * @brief Represents the parameters for playing primitive effect. + * + * @since 18 + */ +typedef struct PrimitiveEffect { + int32_t intensity = 0; + int32_t usage = 0; + bool systemUsage; + int32_t count = 0; +} PrimitiveEffect; + +/** + * @brief Defines the vibration effect information. + * + * The information include the capability to set the effect and the vibration duration of the effect. + * + * @since 18 + */ +typedef struct EffectInfo { + bool isSupportEffect; +} EffectInfo; + +/** + * @brief Defines the plug state events for the vibrator device. + * + * This enumeration represents the various plug and unplug state events + * that can occur with the vibrator device, including its connection status. + * + * @since 18 + */ +typedef enum VibratorPlugState { + PLUG_STATE_EVENT_UNKNOWN = -1, /* Unknown plug and unplug state event */ + PLUG_STATE_EVENT_PLUG_OUT = 0, /* Event indicating that the vibrator is unplugged */ + PLUG_STATE_EVENT_PLUG_IN = 1, /* Event indicating that the vibrator is plugged in */ +} VibratorPlugState; + +/** + * @brief Contains information about a vibrator device's status. + * + * This structure holds the current plug state of the vibrator device and its + * unique identifier. It is used to monitor and manage the vibrator's connectivity + * and operational mode. + * + * @since 18 + */ +typedef struct VibratorDeviceInfo { + VibratorPlugState type = PLUG_STATE_EVENT_UNKNOWN; + int32_t deviceId = 0; +} VibratorDeviceInfo; + +/** + * @brief Defines the callback for data reporting by the sensor agent. + * + * @since 18 + */ +typedef void (*RecordVibratorPlugCallback)(VibratorDeviceInfo *deviceInfo); + +/** + * @brief Defines a reserved field for the sensor data subscriber. + * + * @since 18 + */ +typedef struct UserData { + char userData[VIBRATOR_USER_DATA_SIZE]; /* Reserved for the sensor data subscriber */ +} UserData; + +/** + * @brief Defines information about the sensor data subscriber. + * + * @since 18 + */ +typedef struct VibratorUser { + RecordVibratorPlugCallback callback; /* Callback for reporting sensor data */ + UserData *userData = nullptr; /* Reserved field for the sensor data subscriber */ +} VibratorUser; + +/** + * @brief Defines information about vibrator effects + * + * @since 18 + */ +typedef struct VibratorEffectParameter { + int32_t loopCount = 1; + int32_t usage = USAGE_UNKNOWN; + bool systemUsage = false; + VibratorParameter vibratorParameter; +}VibratorEffectParameter; /** @} */ #ifdef __cplusplus }; diff --git a/miscdevice.gni b/miscdevice.gni index 40c1f0a5f9f770f510005a80648caa3fa508267c..412d76c4fe23a679b5ad726699412ab1678683a0 100644 --- a/miscdevice.gni +++ b/miscdevice.gni @@ -36,6 +36,8 @@ if (miscdevice_feature_vibrator_custom) { if (miscdevice_feature_vibrator_input_method_enable) { miscdevice_default_defines += [ "OHOS_BUILD_ENABLE_VIBRATOR_INPUT_METHOD" ] +} else { + miscdevice_default_defines += [ "OHOS_BUILD_ENABLE_VIBRATOR_PRESET_INFO" ] } if (miscdevice_feature_crown_vibrator_enable) { diff --git a/services/miscdevice_service/BUILD.gn b/services/miscdevice_service/BUILD.gn index 418469dd9c0466bd08abdacd3d71b229e0a754c4..0c37eef7df890a874ad9cd206a8cc0011a532c78 100644 --- a/services/miscdevice_service/BUILD.gn +++ b/services/miscdevice_service/BUILD.gn @@ -20,6 +20,7 @@ ohos_shared_library("libmiscdevice_service") { "hdi_connection/adapter/src/compatible_light_connection.cpp", "hdi_connection/interface/src/light_hdi_connection.cpp", "hdi_connection/interface/src/vibrator_hdi_connection.cpp", + "hdi_connection/adapter/src/vibrator_plug_callback.cpp", "src/miscdevice_common_event_subscriber.cpp", "src/miscdevice_dump.cpp", "src/miscdevice_observer.cpp", @@ -105,6 +106,7 @@ ohos_shared_library("libmiscdevice_service") { "drivers_interface_vibrator:libvibrator_proxy_1.1", "drivers_interface_vibrator:libvibrator_proxy_1.2", "drivers_interface_vibrator:libvibrator_proxy_1.3", + "drivers_interface_vibrator:libvibrator_proxy_2.0", ] } @@ -219,6 +221,7 @@ ohos_static_library("libmiscdevice_service_static") { "drivers_interface_vibrator:libvibrator_proxy_1.1", "drivers_interface_vibrator:libvibrator_proxy_1.2", "drivers_interface_vibrator:libvibrator_proxy_1.3", + "drivers_interface_vibrator:libvibrator_proxy_2.0", ] } diff --git a/services/miscdevice_service/haptic_matcher/include/custom_vibration_matcher.h b/services/miscdevice_service/haptic_matcher/include/custom_vibration_matcher.h index 1df08ede061e439a92c1aa62fdaf11569dff1a3b..206d558dfcef15aa1cd15d781acf6f0adeb21849 100644 --- a/services/miscdevice_service/haptic_matcher/include/custom_vibration_matcher.h +++ b/services/miscdevice_service/haptic_matcher/include/custom_vibration_matcher.h @@ -26,6 +26,7 @@ class CustomVibrationMatcher { public: ~CustomVibrationMatcher() = default; static CustomVibrationMatcher &GetInstance(); + CustomVibrationMatcher(const VibratorIdentifierIPC& identifier, std::vector wareInfo); #ifdef HDF_DRIVERS_INTERFACE_VIBRATOR int32_t TransformTime(const VibratePackage &package, std::vector &compositeEffects); int32_t TransformEffect(const VibratePackage &package, std::vector &compositeEffects); diff --git a/services/miscdevice_service/haptic_matcher/src/custom_vibration_matcher.cpp b/services/miscdevice_service/haptic_matcher/src/custom_vibration_matcher.cpp index 27967db2fea1c5802bed7a7f4ff11c99ba9a01da..9de12ef83f79f19ff691607d819ac3b8fcbbb732 100644 --- a/services/miscdevice_service/haptic_matcher/src/custom_vibration_matcher.cpp +++ b/services/miscdevice_service/haptic_matcher/src/custom_vibration_matcher.cpp @@ -54,7 +54,10 @@ CustomVibrationMatcher::CustomVibrationMatcher() { #ifdef HDF_DRIVERS_INTERFACE_VIBRATOR auto &VibratorDevice = VibratorHdiConnection::GetInstance(); - int32_t ret = VibratorDevice.GetAllWaveInfo(hdfWaveInfos_); + VibratorIdentifierIPC identifier; + identifier.deviceId = -1; + identifier.vibratorId = -1; + int32_t ret = VibratorDevice.GetAllWaveInfo(identifier, hdfWaveInfos_); if (ret != ERR_OK) { MISC_HILOGE("GetAllWaveInfo failed infoSize:%{public}zu", hdfWaveInfos_.size()); return; @@ -68,6 +71,19 @@ CustomVibrationMatcher::CustomVibrationMatcher() } } +CustomVibrationMatcher::CustomVibrationMatcher(const VibratorIdentifierIPC& identifier, + std::vector waveInfo) +{ + hdfWaveInfos_ = waveInfo; + if (!hdfWaveInfos_.empty()) { + for (auto it = hdfWaveInfos_.begin(); it != hdfWaveInfos_.end(); ++it) { + MISC_HILOGI("waveId:%{public}d, intensity:%{public}f, frequency:%{public}f, duration:%{public}d", + it->waveId, it->intensity, it->frequency, it->duration); + } + NormalizedWaveInfo(); + } +} + void CustomVibrationMatcher::NormalizedWaveInfo() { CALL_LOG_ENTER; diff --git a/services/miscdevice_service/hdi_connection/adapter/include/compatible_connection.h b/services/miscdevice_service/hdi_connection/adapter/include/compatible_connection.h index 954c274c95999ea5a11d64167734e0f60fdb3bd6..7550ee24b9786f81b4e0a9ccfac7520c06efb557 100644 --- a/services/miscdevice_service/hdi_connection/adapter/include/compatible_connection.h +++ b/services/miscdevice_service/hdi_connection/adapter/include/compatible_connection.h @@ -27,25 +27,36 @@ public: CompatibleConnection() = default; virtual ~CompatibleConnection() {}; int32_t ConnectHdi() override; - int32_t StartOnce(uint32_t duration) override; - int32_t Start(const std::string &effectType) override; + int32_t StartOnce(const VibratorIdentifierIPC &identifier, uint32_t duration) override; + int32_t Start(const VibratorIdentifierIPC &identifier, const std::string &effectType) override; #ifdef HDF_DRIVERS_INTERFACE_VIBRATOR #ifdef OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM - int32_t EnableCompositeEffect(const HdfCompositeEffect &hdfCompositeEffect) override; - bool IsVibratorRunning() override; + int32_t EnableCompositeEffect(const VibratorIdentifierIPC &identifier, + const HdfCompositeEffect &hdfCompositeEffect) override; + bool IsVibratorRunning(const VibratorIdentifierIPC &identifier) override; #endif // OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM - std::optional GetEffectInfo(const std::string &effect) override; - int32_t Stop(HdfVibratorModeV1_2 mode) override; + std::optional GetEffectInfo(const VibratorIdentifierIPC &identifier, + const std::string &effect) override; + int32_t Stop(const VibratorIdentifierIPC &identifier, HdfVibratorMode mode) override; #endif // HDF_DRIVERS_INTERFACE_VIBRATOR - int32_t GetDelayTime(int32_t mode, int32_t &delayTime) override; - int32_t GetVibratorCapacity(VibratorCapacity &capacity) override; - int32_t PlayPattern(const VibratePattern &pattern) override; + int32_t GetDelayTime(const VibratorIdentifierIPC &identifier, int32_t mode, int32_t &delayTime) override; + int32_t GetVibratorCapacity(const VibratorIdentifierIPC &identifier, VibratorCapacity &capacity) override; + int32_t PlayPattern(const VibratorIdentifierIPC &identifier, const VibratePattern &pattern) override; int32_t DestroyHdiConnection() override; - int32_t StartByIntensity(const std::string &effect, int32_t intensity) override; + int32_t StartByIntensity(const VibratorIdentifierIPC &identifier, const std::string &effect, + int32_t intensity) override; #ifdef HDF_DRIVERS_INTERFACE_VIBRATOR - int32_t GetAllWaveInfo(std::vector &waveInfos) override; + int32_t GetVibratorInfo(std::vector &hdfVibratorInfo) override; + int32_t GetAllWaveInfo(const VibratorIdentifierIPC &identifier, + std::vector &waveInfos) override; + int32_t GetVibratorIdList(const VibratorIdentifierIPC &identifier, + std::vector &vibratorInfoIpc) override; + int32_t GetEffectInfo(const VibratorIdentifierIPC &identifier, const std::string &effectType, + HdfEffectInfo &effectInfo) override; #endif // HDF_DRIVERS_INTERFACE_VIBRATOR - + int32_t RegisterVibratorPlugCallback(DevicePlugCallback cb) override; + DevicePlugCallback GetVibratorPlugCb() override; + private: DISALLOW_COPY_AND_MOVE(CompatibleConnection); std::thread vibrateThread_; diff --git a/services/miscdevice_service/hdi_connection/adapter/include/hdi_connection.h b/services/miscdevice_service/hdi_connection/adapter/include/hdi_connection.h index 0c4426f3bc44d18960982da4142338a75814a550..7941d2cfde86a01456525189fa9e546fa757d717 100644 --- a/services/miscdevice_service/hdi_connection/adapter/include/hdi_connection.h +++ b/services/miscdevice_service/hdi_connection/adapter/include/hdi_connection.h @@ -17,14 +17,14 @@ #define HDI_CONNECTION_H #ifdef HDF_DRIVERS_INTERFACE_VIBRATOR -#include "v1_3/vibrator_interface_proxy.h" +#include "v2_0/vibrator_interface_proxy.h" #endif // HDF_DRIVERS_INTERFACE_VIBRATOR #include "death_recipient_template.h" #include "i_vibrator_hdi_connection.h" #ifdef HDF_DRIVERS_INTERFACE_VIBRATOR -using OHOS::HDI::Vibrator::V1_3::IVibratorInterface; +using OHOS::HDI::Vibrator::V2_0::IVibratorInterface; #endif // HDF_DRIVERS_INTERFACE_VIBRATOR namespace OHOS { namespace Sensors { @@ -33,25 +33,36 @@ public: HdiConnection() = default; virtual ~HdiConnection() {}; int32_t ConnectHdi() override; - int32_t StartOnce(uint32_t duration) override; - int32_t Start(const std::string &effectType) override; + int32_t StartOnce(const VibratorIdentifierIPC &identifier, uint32_t duration) override; + int32_t Start(const VibratorIdentifierIPC &identifier, const std::string &effectType) override; #ifdef HDF_DRIVERS_INTERFACE_VIBRATOR #ifdef OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM - int32_t EnableCompositeEffect(const HdfCompositeEffect &hdfCompositeEffect) override; - bool IsVibratorRunning() override; + int32_t EnableCompositeEffect(const VibratorIdentifierIPC &identifier, + const HdfCompositeEffect &hdfCompositeEffect) override; + bool IsVibratorRunning(const VibratorIdentifierIPC &identifier) override; #endif // OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM - std::optional GetEffectInfo(const std::string &effect) override; - int32_t Stop(HdfVibratorModeV1_2 mode) override; + std::optional GetEffectInfo(const VibratorIdentifierIPC &identifier, + const std::string &effect) override; + int32_t Stop(const VibratorIdentifierIPC &identifier, HdfVibratorMode mode) override; #endif // HDF_DRIVERS_INTERFACE_VIBRATOR - int32_t GetDelayTime(int32_t mode, int32_t &delayTime) override; - int32_t GetVibratorCapacity(VibratorCapacity &capacity) override; - int32_t PlayPattern(const VibratePattern &pattern) override; + int32_t GetDelayTime(const VibratorIdentifierIPC &identifier, int32_t mode, int32_t &delayTime) override; + int32_t GetVibratorCapacity(const VibratorIdentifierIPC &identifier, VibratorCapacity &capacity) override; + int32_t PlayPattern(const VibratorIdentifierIPC &identifier, const VibratePattern &pattern) override; int32_t DestroyHdiConnection() override; void ProcessDeathObserver(const wptr &object); - int32_t StartByIntensity(const std::string &effect, int32_t intensity) override; + int32_t StartByIntensity(const VibratorIdentifierIPC &identifier, const std::string &effect, + int32_t intensity) override; #ifdef HDF_DRIVERS_INTERFACE_VIBRATOR - int32_t GetAllWaveInfo(std::vector &waveInfos) override; + int32_t GetVibratorInfo(std::vector &hdfVibratorInfo) override; + int32_t GetAllWaveInfo(const VibratorIdentifierIPC &identifier, + std::vector &waveInfos) override; + int32_t GetVibratorIdList(const VibratorIdentifierIPC &identifier, + std::vector &vibratorInfoIpc) override; + int32_t GetEffectInfo(const VibratorIdentifierIPC &identifier, const std::string &effectType, + HdfEffectInfo &effectInfo) override; #endif // HDF_DRIVERS_INTERFACE_VIBRATOR + int32_t RegisterVibratorPlugCallback(DevicePlugCallback cb) override; + DevicePlugCallback GetVibratorPlugCb() override; private: DISALLOW_COPY_AND_MOVE(HdiConnection); @@ -59,6 +70,7 @@ private: sptr vibratorInterface_ = nullptr; #endif // HDF_DRIVERS_INTERFACE_VIBRATOR sptr hdiDeathObserver_ = nullptr; + static DevicePlugCallback devicePlugCb_; void RegisterHdiDeathRecipient(); void UnregisterHdiDeathRecipient(); void Reconnect(); diff --git a/services/miscdevice_service/hdi_connection/adapter/include/vibrator_plug_callback.h b/services/miscdevice_service/hdi_connection/adapter/include/vibrator_plug_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..463f4a31553816a95bd16701a99d634fb39c3ad0 --- /dev/null +++ b/services/miscdevice_service/hdi_connection/adapter/include/vibrator_plug_callback.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + #ifndef VIBRATOR_PLUG_CALLBACK_H + #define VIBRATOR_PLUG_CALLBACK_H + + #include + #ifdef HDF_DRIVERS_INTERFACE_VIBRATOR + #include "v2_0/ivibrator_interface.h" + #include "v2_0/ivibrator_plug_callback.h" + #include "v2_0/vibrator_types.h" + #endif // HDF_DRIVERS_INTERFACE_VIBRATOR + + #ifdef HDF_DRIVERS_INTERFACE_VIBRATOR + using OHOS::HDI::Vibrator::V2_0::IVibratorPlugCallback; + #endif // HDF_DRIVERS_INTERFACE_VIBRATOR + + namespace OHOS { + namespace Sensors { + class VibratorPlugCallback : public IVibratorPlugCallback { + public: + virtual ~VibratorPlugCallback() {} + int32_t OnVibratorPlugEvent(const HdfVibratorPlugInfo &vibratorPlugInfo) override; + }; + } // namespace Sensors + } // namespace OHOS + #endif // VIBRATOR_PLUG_CALLBACK_H + \ No newline at end of file diff --git a/services/miscdevice_service/hdi_connection/adapter/src/compatible_connection.cpp b/services/miscdevice_service/hdi_connection/adapter/src/compatible_connection.cpp index ebecb241396ba09cc051336abddda5729e5a9ced..1de663105a625ce72b70cd2a72a832a05814ec87 100644 --- a/services/miscdevice_service/hdi_connection/adapter/src/compatible_connection.cpp +++ b/services/miscdevice_service/hdi_connection/adapter/src/compatible_connection.cpp @@ -43,7 +43,7 @@ std::unordered_map g_vibratorEffect = { {"haptic.notice.warning", 2200} }; #ifdef HDF_DRIVERS_INTERFACE_VIBRATOR -HdfVibratorModeV1_2 g_vibrateMode; +HdfVibratorMode g_vibrateMode; #endif // HDF_DRIVERS_INTERFACE_VIBRATOR constexpr int32_t VIBRATE_DELAY_TIME = 10; } // namespace @@ -56,7 +56,7 @@ int32_t CompatibleConnection::ConnectHdi() return ERR_OK; } -int32_t CompatibleConnection::StartOnce(uint32_t duration) +int32_t CompatibleConnection::StartOnce(const VibratorIdentifierIPC &identifier, uint32_t duration) { CALL_LOG_ENTER; duration_ = static_cast(duration); @@ -71,7 +71,7 @@ int32_t CompatibleConnection::StartOnce(uint32_t duration) return ERR_OK; } -int32_t CompatibleConnection::Start(const std::string &effectType) +int32_t CompatibleConnection::Start(const VibratorIdentifierIPC &identifier, const std::string &effectType) { CALL_LOG_ENTER; if (g_vibratorEffect.find(effectType) == g_vibratorEffect.end()) { @@ -93,7 +93,8 @@ int32_t CompatibleConnection::Start(const std::string &effectType) #ifdef HDF_DRIVERS_INTERFACE_VIBRATOR #ifdef OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM -int32_t CompatibleConnection::EnableCompositeEffect(const HdfCompositeEffect &hdfCompositeEffect) +int32_t CompatibleConnection::EnableCompositeEffect(const VibratorIdentifierIPC &identifier, + const HdfCompositeEffect &hdfCompositeEffect) { CALL_LOG_ENTER; if (hdfCompositeEffect.compositeEffects.empty()) { @@ -118,14 +119,15 @@ int32_t CompatibleConnection::EnableCompositeEffect(const HdfCompositeEffect &hd return ERR_OK; } -bool CompatibleConnection::IsVibratorRunning() +bool CompatibleConnection::IsVibratorRunning(const VibratorIdentifierIPC &identifier) { CALL_LOG_ENTER; return (!isStop_); } #endif // OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM -std::optional CompatibleConnection::GetEffectInfo(const std::string &effect) +std::optional CompatibleConnection::GetEffectInfo(const VibratorIdentifierIPC &identifier, + const std::string &effect) { CALL_LOG_ENTER; HdfEffectInfo effectInfo; @@ -140,7 +142,7 @@ std::optional CompatibleConnection::GetEffectInfo(const std::stri return effectInfo; } -int32_t CompatibleConnection::Stop(HdfVibratorModeV1_2 mode) +int32_t CompatibleConnection::Stop(const VibratorIdentifierIPC &identifier, HdfVibratorMode mode) { CALL_LOG_ENTER; if (mode < 0 || mode >= HDF_VIBRATOR_MODE_BUTT) { @@ -160,19 +162,19 @@ int32_t CompatibleConnection::Stop(HdfVibratorModeV1_2 mode) } #endif // HDF_DRIVERS_INTERFACE_VIBRATOR -int32_t CompatibleConnection::GetDelayTime(int32_t mode, int32_t &delayTime) +int32_t CompatibleConnection::GetDelayTime(const VibratorIdentifierIPC &identifier, int32_t mode, int32_t &delayTime) { CALL_LOG_ENTER; delayTime = VIBRATE_DELAY_TIME; return ERR_OK; } -int32_t CompatibleConnection::GetVibratorCapacity(VibratorCapacity &capacity) +int32_t CompatibleConnection::GetVibratorCapacity(const VibratorIdentifierIPC &identifier, VibratorCapacity &capacity) { return ERR_OK; } -int32_t CompatibleConnection::PlayPattern(const VibratePattern &pattern) +int32_t CompatibleConnection::PlayPattern(const VibratorIdentifierIPC &identifier, const VibratePattern &pattern) { return ERR_OK; } @@ -198,7 +200,8 @@ void CompatibleConnection::VibrateProcess() return; } -int32_t CompatibleConnection::StartByIntensity(const std::string &effect, int32_t intensity) +int32_t CompatibleConnection::StartByIntensity(const VibratorIdentifierIPC &identifier, const std::string &effect, + int32_t intensity) { CALL_LOG_ENTER; if (g_vibratorEffect.find(effect) == g_vibratorEffect.end()) { @@ -218,11 +221,40 @@ int32_t CompatibleConnection::StartByIntensity(const std::string &effect, int32_ } #ifdef HDF_DRIVERS_INTERFACE_VIBRATOR -int32_t CompatibleConnection::GetAllWaveInfo(std::vector &waveInfos) +int32_t CompatibleConnection::GetVibratorInfo(std::vector &hdfVibratorInfo) { return ERR_OK; } +int32_t CompatibleConnection::GetAllWaveInfo(const VibratorIdentifierIPC &identifier, + std::vector &waveInfos) +{ + return ERR_OK; +} + +int32_t CompatibleConnection::GetVibratorIdList(const VibratorIdentifierIPC &identifier, + std::vector &vibratorInfoIpc) +{ + CALL_LOG_ENTER; + return ERR_OK; +} + +int32_t CompatibleConnection::GetEffectInfo(const VibratorIdentifierIPC &identifier, const std::string &effectType, + HdfEffectInfo &effectInfo) +{ + CALL_LOG_ENTER; + return ERR_OK; +} #endif // HDF_DRIVERS_INTERFACE_VIBRATOR +int32_t CompatibleConnection::RegisterVibratorPlugCallback(DevicePlugCallback cb) +{ + return ERR_OK; +} + +DevicePlugCallback CompatibleConnection::GetVibratorPlugCb() +{ + return NULL; +} + } // namespace Sensors -} // namespace OHOS +} // namespace OHOS \ No newline at end of file diff --git a/services/miscdevice_service/hdi_connection/adapter/src/hdi_connection.cpp b/services/miscdevice_service/hdi_connection/adapter/src/hdi_connection.cpp index 6d22d8046f0914ef2f260d2d2ab2a6f615c2051c..a99b88d160c9d9c0a9ca4dc8ad73ef3226067ee2 100644 --- a/services/miscdevice_service/hdi_connection/adapter/src/hdi_connection.cpp +++ b/services/miscdevice_service/hdi_connection/adapter/src/hdi_connection.cpp @@ -21,6 +21,7 @@ #endif // HIVIEWDFX_HISYSEVENT_ENABLE #include "sensors_errors.h" +#include "vibrator_plug_callback.h" #undef LOG_TAG #define LOG_TAG "HdiConnection" @@ -29,17 +30,23 @@ namespace OHOS { namespace Sensors { using namespace OHOS::HiviewDFX; namespace { +sptr g_eventCallback = nullptr; constexpr int32_t GET_HDI_SERVICE_COUNT = 10; constexpr uint32_t WAIT_MS = 100; } // namespace +DevicePlugCallback HdiConnection::devicePlugCb_ = nullptr; int32_t HdiConnection::ConnectHdi() { + return ERR_OK; CALL_LOG_ENTER; int32_t retry = 0; while (retry < GET_HDI_SERVICE_COUNT) { vibratorInterface_ = IVibratorInterface::Get(); if (vibratorInterface_ != nullptr) { + MISC_HILOGW("Connect v2_0 hdi success"); + g_eventCallback = new (std::nothrow) VibratorPlugCallback(); + CHKPR(g_eventCallback, ERR_NO_INIT); RegisterHdiDeathRecipient(); return ERR_OK; } @@ -55,10 +62,11 @@ int32_t HdiConnection::ConnectHdi() return ERR_INVALID_VALUE; } -int32_t HdiConnection::StartOnce(uint32_t duration) +int32_t HdiConnection::StartOnce(const VibratorIdentifierIPC ¶ms, uint32_t duration) { - CHKPR(vibratorInterface_, ERR_INVALID_VALUE); - int32_t ret = vibratorInterface_->StartOnce(duration); + // CHKPR(vibratorInterface_, ERR_INVALID_VALUE); + // int32_t ret = vibratorInterface_->StartOnce(params.deviceId, params.vibratorId, duration); + int32_t ret = 0; if (ret < 0) { #ifdef HIVIEWDFX_HISYSEVENT_ENABLE HiSysEventWrite(HiSysEvent::Domain::MISCDEVICE, "VIBRATOR_HDF_SERVICE_EXCEPTION", @@ -70,15 +78,17 @@ int32_t HdiConnection::StartOnce(uint32_t duration) return ERR_OK; } -int32_t HdiConnection::Start(const std::string &effectType) +int32_t HdiConnection::Start(const VibratorIdentifierIPC ¶ms, const std::string &effectType) { MISC_HILOGD("Time delay measurement:end time"); if (effectType.empty()) { MISC_HILOGE("effectType is null"); return VIBRATOR_ON_ERR; } - CHKPR(vibratorInterface_, ERR_INVALID_VALUE); - int32_t ret = vibratorInterface_->Start(effectType); + // CHKPR(vibratorInterface_, ERR_INVALID_VALUE); + // int32_t ret = vibratorInterface_->Start(params.deviceId, params.vibratorId, effectType); + int32_t ret = 0; + if (ret < 0) { #ifdef HIVIEWDFX_HISYSEVENT_ENABLE HiSysEventWrite(HiSysEvent::Domain::MISCDEVICE, "VIBRATOR_HDF_SERVICE_EXCEPTION", @@ -91,15 +101,17 @@ int32_t HdiConnection::Start(const std::string &effectType) } #ifdef OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM -int32_t HdiConnection::EnableCompositeEffect(const HdfCompositeEffect &hdfCompositeEffect) +int32_t HdiConnection::EnableCompositeEffect(const VibratorIdentifierIPC ¶ms, const HdfCompositeEffect &hdfCompositeEffect) { MISC_HILOGD("Time delay measurement:end time"); if (hdfCompositeEffect.compositeEffects.empty()) { MISC_HILOGE("compositeEffects is empty"); return VIBRATOR_ON_ERR; } - CHKPR(vibratorInterface_, ERR_INVALID_VALUE); - int32_t ret = vibratorInterface_->EnableCompositeEffect(hdfCompositeEffect); + // CHKPR(vibratorInterface_, ERR_INVALID_VALUE); + // int32_t ret = vibratorInterface_->EnableCompositeEffect(params.deviceId, params.vibratorId, hdfCompositeEffect); + int32_t ret = 0; + if (ret < 0) { #ifdef HIVIEWDFX_HISYSEVENT_ENABLE HiSysEventWrite(HiSysEvent::Domain::MISCDEVICE, "VIBRATOR_HDF_SERVICE_EXCEPTION", @@ -111,23 +123,29 @@ int32_t HdiConnection::EnableCompositeEffect(const HdfCompositeEffect &hdfCompos return ERR_OK; } -bool HdiConnection::IsVibratorRunning() +bool HdiConnection::IsVibratorRunning(const VibratorIdentifierIPC ¶ms) { bool state = false; - CHKPR(vibratorInterface_, false); - vibratorInterface_->IsVibratorRunning(state); + // CHKPR(vibratorInterface_, false); + // vibratorInterface_->IsVibratorRunning(params.deviceId, params.vibratorId, state); + state = true; + return state; } #endif // OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM -std::optional HdiConnection::GetEffectInfo(const std::string &effect) +std::optional HdiConnection::GetEffectInfo(const VibratorIdentifierIPC ¶ms, const std::string &effect) { - if (vibratorInterface_ == nullptr) { - MISC_HILOGE("Connect v1_1 hdi failed"); - return std::nullopt; - } + // if (vibratorInterface_ == nullptr) { + // MISC_HILOGE("Connect v1_1 hdi failed"); + // return std::nullopt; + // } HdfEffectInfo effectInfo; - int32_t ret = vibratorInterface_->GetEffectInfo(effect, effectInfo); + // int32_t ret = vibratorInterface_->GetEffectInfo(params.deviceId, params.vibratorId, effect, effectInfo); + effectInfo.duration = 2000; + effectInfo.isSupportEffect = true; + int32_t ret = 0; + if (ret < 0) { #ifdef HIVIEWDFX_HISYSEVENT_ENABLE HiSysEventWrite(HiSysEvent::Domain::MISCDEVICE, "VIBRATOR_HDF_SERVICE_EXCEPTION", @@ -139,10 +157,12 @@ std::optional HdiConnection::GetEffectInfo(const std::string &eff return effectInfo; } -int32_t HdiConnection::Stop(HdfVibratorModeV1_2 mode) +int32_t HdiConnection::Stop(const VibratorIdentifierIPC ¶ms, HdfVibratorMode mode) { - CHKPR(vibratorInterface_, ERR_INVALID_VALUE); - int32_t ret = vibratorInterface_->StopV1_2(mode); + // CHKPR(vibratorInterface_, ERR_INVALID_VALUE); + // int32_t ret = vibratorInterface_->Stop(params.deviceId, params.vibratorId, mode); + int32_t ret = 0; + if (ret < 0) { #ifdef HIVIEWDFX_HISYSEVENT_ENABLE HiSysEventWrite(HiSysEvent::Domain::MISCDEVICE, "VIBRATOR_HDF_SERVICE_EXCEPTION", @@ -154,10 +174,13 @@ int32_t HdiConnection::Stop(HdfVibratorModeV1_2 mode) return ERR_OK; } -int32_t HdiConnection::GetDelayTime(int32_t mode, int32_t &delayTime) +int32_t HdiConnection::GetDelayTime(const VibratorIdentifierIPC ¶ms, int32_t mode, int32_t &delayTime) { - CHKPR(vibratorInterface_, ERR_INVALID_VALUE); - int32_t ret = vibratorInterface_->GetHapticStartUpTime(mode, delayTime); + // CHKPR(vibratorInterface_, ERR_INVALID_VALUE); + // int32_t ret = vibratorInterface_->GetHapticStartUpTime(params.deviceId, params.vibratorId, mode, delayTime); + int32_t ret = 0; + delayTime = 2000; + if (ret < 0) { #ifdef HIVIEWDFX_HISYSEVENT_ENABLE HiSysEventWrite(HiSysEvent::Domain::MISCDEVICE, "VIBRATOR_HDF_SERVICE_EXCEPTION", @@ -169,11 +192,17 @@ int32_t HdiConnection::GetDelayTime(int32_t mode, int32_t &delayTime) return ERR_OK; } -int32_t HdiConnection::GetVibratorCapacity(VibratorCapacity &capacity) +int32_t HdiConnection::GetVibratorCapacity(const VibratorIdentifierIPC ¶ms, VibratorCapacity &capacity) { - CHKPR(vibratorInterface_, ERR_INVALID_VALUE); + // CHKPR(vibratorInterface_, ERR_INVALID_VALUE); HapticCapacity hapticCapacity; - int32_t ret = vibratorInterface_->GetHapticCapacity(hapticCapacity); + // int32_t ret = vibratorInterface_->GetHapticCapacity(params.deviceId, hapticCapacity); + int32_t ret = 0; + capacity.isSupportHdHaptic = true; + capacity.isSupportPresetMapping = true; + capacity.isSupportTimeDelay = true; + return ERR_OK; + if (ret < 0) { #ifdef HIVIEWDFX_HISYSEVENT_ENABLE HiSysEventWrite(HiSysEvent::Domain::MISCDEVICE, "VIBRATOR_HDF_SERVICE_EXCEPTION", @@ -189,9 +218,9 @@ int32_t HdiConnection::GetVibratorCapacity(VibratorCapacity &capacity) return ERR_OK; } -int32_t HdiConnection::PlayPattern(const VibratePattern &pattern) +int32_t HdiConnection::PlayPattern(const VibratorIdentifierIPC ¶ms, const VibratePattern &pattern) { - CHKPR(vibratorInterface_, ERR_INVALID_VALUE); + // CHKPR(vibratorInterface_, ERR_INVALID_VALUE); HapticPaket packet = {}; packet.time = pattern.startTime; int32_t eventNum = static_cast(pattern.events.size()); @@ -215,7 +244,9 @@ int32_t HdiConnection::PlayPattern(const VibratePattern &pattern) } packet.events.emplace_back(hapticEvent); } - int32_t ret = vibratorInterface_->PlayHapticPattern(packet); + // int32_t ret = vibratorInterface_->PlayHapticPattern(params.deviceId, packet); + int32_t ret = 0; + if (ret < 0) { #ifdef HIVIEWDFX_HISYSEVENT_ENABLE HiSysEventWrite(HiSysEvent::Domain::MISCDEVICE, "VIBRATOR_HDF_SERVICE_EXCEPTION", @@ -229,12 +260,26 @@ int32_t HdiConnection::PlayPattern(const VibratePattern &pattern) int32_t HdiConnection::DestroyHdiConnection() { + CALL_LOG_ENTER; + CHKPR(vibratorInterface_, ERR_NO_INIT); + int32_t ret = vibratorInterface_->UnRegVibratorPlugCallback(g_eventCallback); + if (ret != 0) { +#ifdef HIVIEWDFX_HISYSEVENT_ENABLE + HiSysEventWrite(HiSysEvent::Domain::MISCDEVICE, "VIBRATOR_HDF_SERVICE_EXCEPTION", + HiSysEvent::EventType::FAULT, "PKG_NAME", "DestroyHdiConnection", "ERROR_CODE", ret); +#endif // HIVIEWDFX_HISYSEVENT_ENABLE + MISC_HILOGE("UnRegVibratorPlugCallback is failed"); + return ret; + } + g_eventCallback = nullptr; UnregisterHdiDeathRecipient(); return ERR_OK; } void HdiConnection::RegisterHdiDeathRecipient() { + return; + CALL_LOG_ENTER; if (vibratorInterface_ == nullptr) { MISC_HILOGE("Connect v1_1 hdi failed"); @@ -281,15 +326,17 @@ void HdiConnection::Reconnect() } } -int32_t HdiConnection::StartByIntensity(const std::string &effect, int32_t intensity) +int32_t HdiConnection::StartByIntensity(const VibratorIdentifierIPC ¶ms, const std::string &effect, int32_t intensity) { MISC_HILOGD("Time delay measurement:end time, effect:%{public}s, intensity:%{public}d", effect.c_str(), intensity); if (effect.empty()) { MISC_HILOGE("effect is null"); return VIBRATOR_ON_ERR; } - CHKPR(vibratorInterface_, ERR_INVALID_VALUE); - int32_t ret = vibratorInterface_->StartByIntensity(effect, intensity); + // CHKPR(vibratorInterface_, ERR_INVALID_VALUE); + // int32_t ret = vibratorInterface_->StartByIntensity(params.deviceId, params.vibratorId, effect, intensity); + int32_t ret = 0; + if (ret < 0) { #ifdef HIVIEWDFX_HISYSEVENT_ENABLE HiSysEventWrite(HiSysEvent::Domain::MISCDEVICE, "VIBRATOR_HDF_SERVICE_EXCEPTION", @@ -301,16 +348,177 @@ int32_t HdiConnection::StartByIntensity(const std::string &effect, int32_t inten return ERR_OK; } -int32_t HdiConnection::GetAllWaveInfo(std::vector &waveInfos) +int32_t HdiConnection::GetVibratorInfo(std::vector &hdfVibratorInfo) +{ + // CHKPR(vibratorInterface_, ERR_INVALID_VALUE); + // int32_t ret = vibratorInterface_->GetVibratorInfo(hdfVibratorInfo); + int32_t ret = 0; + HdfVibratorInfo info; + info.isSupportIntensity = true; + info.isSupportFrequency = false; + info.intensityMaxValue = 255; + info.intensityMinValue = 0; + info.frequencyMaxValue = 200; + info.frequencyMinValue = 50; + info.deviceId = 2; + info.vibratorId = 99; + info.isLocal = 1; + info.position = 1; + hdfVibratorInfo.push_back(info); + + HdfVibratorInfo info1; + info1.isSupportIntensity = true; + info1.isSupportFrequency = false; + info1.intensityMaxValue = 255; + info1.intensityMinValue = 0; + info1.frequencyMaxValue = 200; + info1.frequencyMinValue = 50; + info1.deviceId = 2; + info1.vibratorId = 100; + info1.isLocal = 1; + info1.position = 2; + hdfVibratorInfo.push_back(info1); + + if (ret != ERR_OK) { + MISC_HILOGE("GetVibratorInfo failed"); + } + return ret; + +} + +int32_t HdiConnection::GetAllWaveInfo(const VibratorIdentifierIPC ¶ms, std::vector &waveInfos) { - CHKPR(vibratorInterface_, ERR_INVALID_VALUE); - int32_t vibratorId = 1; - int32_t ret = vibratorInterface_->GetAllWaveInfo(vibratorId, waveInfos); + // CHKPR(vibratorInterface_, ERR_INVALID_VALUE); + // int32_t ret = vibratorInterface_->GetAllWaveInfo(params.deviceId, params.vibratorId, waveInfos); + int32_t ret = 0; + HdfWaveInformation info1; + info1.vibratorId = 1; + info1.waveId = 101; + info1.intensity = 0.8f; + info1.frequency = 50.0f; + info1.duration = 200; + info1.reserved = 0; + waveInfos.push_back(info1); + + HdfWaveInformation info2; + info2.vibratorId = 2; + info2.waveId = 102; + info2.intensity = 0.6f; + info2.frequency = 60.0f; + info2.duration = 300; + info2.reserved = 0; + waveInfos.push_back(info2); + if (ret != ERR_OK) { MISC_HILOGE("GetAllWaveInfo failed"); } return ret; } +int32_t HdiConnection::GetVibratorIdList(const VibratorIdentifierIPC ¶ms, + std::vector &vibratorInfo) +{ + // CHKPR(vibratorInterface_, ERR_INVALID_VALUE); + // int32_t ret = vibratorInterface_->GetVibratorIdSingle(params.deviceId, vibratorInfo); + int32_t ret = 0; + HdfVibratorInfo info; + info.isSupportIntensity = true; + info.isSupportFrequency = false; + info.intensityMaxValue = 255; + info.intensityMinValue = 0; + info.frequencyMaxValue = 200; + info.frequencyMinValue = 50; + info.deviceId = 3; + info.vibratorId = 101; + info.isLocal = 0; + vibratorInfo.push_back(info); + + HdfVibratorInfo info1; + info1.isSupportIntensity = true; + info1.isSupportFrequency = false; + info1.intensityMaxValue = 255; + info1.intensityMinValue = 0; + info1.frequencyMaxValue = 200; + info1.frequencyMinValue = 50; + info1.deviceId = 3; + info1.vibratorId = 102; + info1.isLocal = 0; + vibratorInfo.push_back(info1); + + + if (ret != ERR_OK) { + MISC_HILOGE("GetVibratorIdList failed"); + } + return ret; +} + +int32_t HdiConnection::GetEffectInfo(const VibratorIdentifierIPC ¶ms, const std::string &effectType, + HdfEffectInfo &effectInfo) +{ + // CHKPR(vibratorInterface_, ERR_INVALID_VALUE); + // int32_t ret = vibratorInterface_->GetEffectInfo(params.deviceId, params.vibratorId, effectType, effectInfo); + int32_t ret = 0; + effectInfo.duration = 2000; + effectInfo.isSupportEffect = true; + + if (ret != ERR_OK) { + MISC_HILOGE("GetVibratorIdList failed"); + } + return ret; +} + +int32_t HdiConnection::RegisterVibratorPlugCallback(DevicePlugCallback cb) +{ + CALL_LOG_ENTER; + CHKPR(cb, ERR_NO_INIT); + // CHKPR(vibratorInterface_, ERR_NO_INIT); + devicePlugCb_ = cb; + // int32_t ret = vibratorInterface_->RegVibratorPlugCallback(g_eventCallback); + int32_t ret = 0; + + if (ret != 0) { +#ifdef HIVIEWDFX_HISYSEVENT_ENABLE + HiSysEventWrite(HiSysEvent::Domain::MISCDEVICE, "VIBRATOR_HDF_SERVICE_EXCEPTION", + HiSysEvent::EventType::FAULT, "PKG_NAME", "RegisterVibratorCallback", "ERROR_CODE", ret); +#endif // HIVIEWDFX_HISYSEVENT_ENABLE + MISC_HILOGE("RegVibratorPlugCallback is failed"); + return ret; + } + + + // std::thread thread([this]() mutable { + // while (1) + // { + // sleep(30); + // HdfVibratorPlugInfo info; + // info.status = 1; + // info.deviceId = 2; + // if (devicePlugCb_) { + // devicePlugCb_(info); + // } + // sleep(30); + // { + // HdfVibratorPlugInfo info; + // info.status = 0; + // info.deviceId = 2; + // if (devicePlugCb_) { + // devicePlugCb_(info); + // } + // } + // } + // }); + // thread.detach(); + + + return ERR_OK; +} + +DevicePlugCallback HdiConnection::GetVibratorPlugCb() +{ + if (devicePlugCb_ == nullptr) { + MISC_HILOGE("GetVibratorPlugCb cannot be null"); + } + return devicePlugCb_; +} } // namespace Sensors -} // namespace OHOS +} // namespace OHOS \ No newline at end of file diff --git a/services/miscdevice_service/hdi_connection/adapter/src/vibrator_plug_callback.cpp b/services/miscdevice_service/hdi_connection/adapter/src/vibrator_plug_callback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..52c9c208eb7b1a19fedf5cbd1da5a01bc95bba6d --- /dev/null +++ b/services/miscdevice_service/hdi_connection/adapter/src/vibrator_plug_callback.cpp @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include "hdi_connection.h" +#include "vibrator_plug_callback.h" +#include "sensors_errors.h" + +#undef LOG_TAG +#define LOG_TAG "VibratorPlugCallback" + +namespace OHOS { +namespace Sensors { +using namespace OHOS::HiviewDFX; +namespace { +std::unique_ptr HdiConnection_ = std::make_unique(); +} // namespace + +int32_t VibratorPlugCallback::OnVibratorPlugEvent(const HdfVibratorPlugInfo &vibratorPlugInfo) +{ + DevicePlugCallback devicePlugCb_ = HdiConnection_->GetVibratorPlugCb(); + CHKPR(devicePlugCb_, ERR_NO_INIT); + devicePlugCb_(vibratorPlugInfo); + return ERR_OK; +} +} // namespace Sensors +} // namespace OHOS \ No newline at end of file diff --git a/services/miscdevice_service/hdi_connection/interface/include/i_vibrator_hdi_connection.h b/services/miscdevice_service/hdi_connection/interface/include/i_vibrator_hdi_connection.h index 008b3dbc116653b03daf86675a4f3c5ef107edd1..50fc46d11ad73cb8104a6ce0ab8b8c3ca31c4b24 100644 --- a/services/miscdevice_service/hdi_connection/interface/include/i_vibrator_hdi_connection.h +++ b/services/miscdevice_service/hdi_connection/interface/include/i_vibrator_hdi_connection.h @@ -17,59 +17,72 @@ #define I_VIBRATOR_HDI_CONNECTION_H #ifdef HDF_DRIVERS_INTERFACE_VIBRATOR -#include "v1_3/ivibrator_interface.h" +#include "v2_0/ivibrator_interface.h" #endif // HDF_DRIVERS_INTERFACE_VIBRATOR #include "vibrator_infos.h" namespace OHOS { namespace Sensors { #ifdef HDF_DRIVERS_INTERFACE_VIBRATOR -using OHOS::HDI::Vibrator::V1_2::HdfVibratorModeV1_2; -using OHOS::HDI::Vibrator::V1_2::HDF_VIBRATOR_MODE_ONCE; -using OHOS::HDI::Vibrator::V1_2::HDF_VIBRATOR_MODE_PRESET; -using OHOS::HDI::Vibrator::V1_2::HDF_VIBRATOR_MODE_HDHAPTIC; -using OHOS::HDI::Vibrator::V1_2::HDF_VIBRATOR_MODE_BUTT; -using OHOS::HDI::Vibrator::V1_2::CurvePoint; -using OHOS::HDI::Vibrator::V1_2::EVENT_TYPE; -using OHOS::HDI::Vibrator::V1_2::HapticCapacity; -using OHOS::HDI::Vibrator::V1_2::HapticPaket; -using OHOS::HDI::Vibrator::V1_2::HapticEvent; -using OHOS::HDI::Vibrator::V1_1::HdfEffectInfo; -using OHOS::HDI::Vibrator::V1_3::HdfWaveInformation; -#ifdef OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM -using OHOS::HDI::Vibrator::V1_1::HdfEffectType; -using OHOS::HDI::Vibrator::V1_1::HDF_EFFECT_TYPE_TIME; -using OHOS::HDI::Vibrator::V1_1::HDF_EFFECT_TYPE_PRIMITIVE; -using OHOS::HDI::Vibrator::V1_1::HDF_EFFECT_TYPE_BUTT; -using OHOS::HDI::Vibrator::V1_1::TimeEffect; -using OHOS::HDI::Vibrator::V1_1::PrimitiveEffect; -using OHOS::HDI::Vibrator::V1_1::CompositeEffect; -using OHOS::HDI::Vibrator::V1_1::HdfCompositeEffect; -#endif // OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM +using OHOS::HDI::Vibrator::V2_0::HdfVibratorMode; +using OHOS::HDI::Vibrator::V2_0::HDF_VIBRATOR_MODE_ONCE; +using OHOS::HDI::Vibrator::V2_0::HDF_VIBRATOR_MODE_PRESET; +using OHOS::HDI::Vibrator::V2_0::HDF_VIBRATOR_MODE_HDHAPTIC; +using OHOS::HDI::Vibrator::V2_0::HDF_VIBRATOR_MODE_BUTT; +using OHOS::HDI::Vibrator::V2_0::CurvePoint; +using OHOS::HDI::Vibrator::V2_0::EVENT_TYPE; +using OHOS::HDI::Vibrator::V2_0::HapticCapacity; +using OHOS::HDI::Vibrator::V2_0::HapticPaket; +using OHOS::HDI::Vibrator::V2_0::HapticEvent; +using OHOS::HDI::Vibrator::V2_0::HdfEffectInfo; +using OHOS::HDI::Vibrator::V2_0::HdfWaveInformation; +using OHOS::HDI::Vibrator::V2_0::HdfVibratorPlugInfo; +using OHOS::HDI::Vibrator::V2_0::HdfVibratorInfo; +using OHOS::HDI::Vibrator::V2_0::HdfEffectType; +using OHOS::HDI::Vibrator::V2_0::HDF_EFFECT_TYPE_TIME; +using OHOS::HDI::Vibrator::V2_0::HDF_EFFECT_TYPE_PRIMITIVE; +using OHOS::HDI::Vibrator::V2_0::HDF_EFFECT_TYPE_BUTT; +using OHOS::HDI::Vibrator::V2_0::TimeEffect; +using OHOS::HDI::Vibrator::V2_0::PrimitiveEffect; +using OHOS::HDI::Vibrator::V2_0::CompositeEffect; +using OHOS::HDI::Vibrator::V2_0::HdfCompositeEffect; #endif // HDF_DRIVERS_INTERFACE_VIBRATOR + +using DevicePlugCallback = std::function; class IVibratorHdiConnection { public: IVibratorHdiConnection() = default; virtual ~IVibratorHdiConnection() = default; virtual int32_t ConnectHdi() = 0; - virtual int32_t StartOnce(uint32_t duration) = 0; - virtual int32_t Start(const std::string &effectType) = 0; + virtual int32_t StartOnce(const VibratorIdentifierIPC &identifier, uint32_t duration) = 0; + virtual int32_t Start(const VibratorIdentifierIPC &identifier, const std::string &effectType) = 0; #ifdef HDF_DRIVERS_INTERFACE_VIBRATOR #ifdef OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM - virtual int32_t EnableCompositeEffect(const HdfCompositeEffect &hdfCompositeEffect) = 0; - virtual bool IsVibratorRunning() = 0; + virtual int32_t EnableCompositeEffect(const VibratorIdentifierIPC &identifier, + const HdfCompositeEffect &hdfCompositeEffect) = 0; + virtual bool IsVibratorRunning(const VibratorIdentifierIPC &identifier) = 0; #endif // OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM - virtual std::optional GetEffectInfo(const std::string &effect) = 0; - virtual int32_t Stop(HdfVibratorModeV1_2 mode) = 0; + virtual std::optional GetEffectInfo(const VibratorIdentifierIPC &identifier, + const std::string &effect) = 0; + virtual int32_t Stop(const VibratorIdentifierIPC &identifier, HdfVibratorMode mode) = 0; #endif // HDF_DRIVERS_INTERFACE_VIBRATOR virtual int32_t DestroyHdiConnection() = 0; - virtual int32_t GetDelayTime(int32_t mode, int32_t &delayTime) = 0; - virtual int32_t GetVibratorCapacity(VibratorCapacity &capacity) = 0; - virtual int32_t PlayPattern(const VibratePattern &pattern) = 0; - virtual int32_t StartByIntensity(const std::string &effect, int32_t intensity) = 0; + virtual int32_t GetDelayTime(const VibratorIdentifierIPC &identifier, int32_t mode, int32_t &delayTime) = 0; + virtual int32_t GetVibratorCapacity(const VibratorIdentifierIPC &identifier, VibratorCapacity &capacity) = 0; + virtual int32_t PlayPattern(const VibratorIdentifierIPC &identifier, const VibratePattern &pattern) = 0; + virtual int32_t StartByIntensity(const VibratorIdentifierIPC &identifier, const std::string &effect, + int32_t intensity) = 0; #ifdef HDF_DRIVERS_INTERFACE_VIBRATOR - virtual int32_t GetAllWaveInfo(std::vector &waveInfos) = 0; + virtual int32_t GetVibratorInfo(std::vector &hdfVibratorInfo) = 0; + virtual int32_t GetAllWaveInfo(const VibratorIdentifierIPC &identifier, + std::vector &waveInfos) = 0; + virtual int32_t GetVibratorIdList(const VibratorIdentifierIPC &identifier, + std::vector &hdfVibratorInfo) = 0; + virtual int32_t GetEffectInfo(const VibratorIdentifierIPC &identifier, const std::string &effectType, + HdfEffectInfo &effectInfo) = 0; #endif // HDF_DRIVERS_INTERFACE_VIBRATOR + virtual int32_t RegisterVibratorPlugCallback(DevicePlugCallback cb) = 0; + virtual DevicePlugCallback GetVibratorPlugCb() = 0; private: DISALLOW_COPY_AND_MOVE(IVibratorHdiConnection); diff --git a/services/miscdevice_service/hdi_connection/interface/include/vibrator_hdi_connection.h b/services/miscdevice_service/hdi_connection/interface/include/vibrator_hdi_connection.h index a604d2016174de254377ab5eff2944587a49ab73..d1cb5fe9a233a1145904c88ea2c737a4a23318ed 100644 --- a/services/miscdevice_service/hdi_connection/interface/include/vibrator_hdi_connection.h +++ b/services/miscdevice_service/hdi_connection/interface/include/vibrator_hdi_connection.h @@ -27,24 +27,35 @@ public: VibratorHdiConnection() = default; virtual ~VibratorHdiConnection() {} int32_t ConnectHdi() override; - int32_t StartOnce(uint32_t duration) override; - int32_t Start(const std::string &effectType) override; + int32_t StartOnce(const VibratorIdentifierIPC &identifier, uint32_t duration) override; + int32_t Start(const VibratorIdentifierIPC &identifier, const std::string &effectType) override; #ifdef HDF_DRIVERS_INTERFACE_VIBRATOR #ifdef OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM - int32_t EnableCompositeEffect(const HdfCompositeEffect &hdfCompositeEffect) override; - bool IsVibratorRunning() override; + int32_t EnableCompositeEffect(const VibratorIdentifierIPC &identifier, + const HdfCompositeEffect &hdfCompositeEffect) override; + bool IsVibratorRunning(const VibratorIdentifierIPC &identifier) override; #endif // OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM - std::optional GetEffectInfo(const std::string &effect) override; - int32_t Stop(HdfVibratorModeV1_2 mode) override; + std::optional GetEffectInfo(const VibratorIdentifierIPC &identifier, + const std::string &effect) override; + int32_t Stop(const VibratorIdentifierIPC &identifier, HdfVibratorMode mode) override; #endif // HDF_DRIVERS_INTERFACE_VIBRATOR int32_t DestroyHdiConnection() override; - int32_t GetDelayTime(int32_t mode, int32_t &delayTime) override; - int32_t GetVibratorCapacity(VibratorCapacity &capacity) override; - int32_t PlayPattern(const VibratePattern &pattern) override; - int32_t StartByIntensity(const std::string &effect, int32_t intensity) override; + int32_t GetDelayTime(const VibratorIdentifierIPC &identifier, int32_t mode, int32_t &delayTime) override; + int32_t GetVibratorCapacity(const VibratorIdentifierIPC &identifier, VibratorCapacity &capacity) override; + int32_t PlayPattern(const VibratorIdentifierIPC &identifier, const VibratePattern &pattern) override; + int32_t StartByIntensity(const VibratorIdentifierIPC &identifier, const std::string &effect, + int32_t intensity) override; #ifdef HDF_DRIVERS_INTERFACE_VIBRATOR - int32_t GetAllWaveInfo(std::vector &waveInfos) override; + int32_t GetVibratorInfo(std::vector &hdfVibratorInfo) override; + int32_t GetAllWaveInfo(const VibratorIdentifierIPC &identifier, + std::vector &waveInfos) override; + int32_t GetVibratorIdList(const VibratorIdentifierIPC &identifier, + std::vector &hdfVibratorInfo) override; + int32_t GetEffectInfo(const VibratorIdentifierIPC &identifier, const std::string &effectType, + HdfEffectInfo &effectInfo) override; #endif // HDF_DRIVERS_INTERFACE_VIBRATOR + int32_t RegisterVibratorPlugCallback(DevicePlugCallback cb) override; + DevicePlugCallback GetVibratorPlugCb() override; private: DISALLOW_COPY_AND_MOVE(VibratorHdiConnection); diff --git a/services/miscdevice_service/hdi_connection/interface/src/vibrator_hdi_connection.cpp b/services/miscdevice_service/hdi_connection/interface/src/vibrator_hdi_connection.cpp index a135b1c4b696da5feac1adadfae263f5be2ee9e4..97edd9d35f62dc969f6f533254acd72fe09e1e40 100644 --- a/services/miscdevice_service/hdi_connection/interface/src/vibrator_hdi_connection.cpp +++ b/services/miscdevice_service/hdi_connection/interface/src/vibrator_hdi_connection.cpp @@ -50,13 +50,13 @@ int32_t VibratorHdiConnection::ConnectHdi() return ret; } -int32_t VibratorHdiConnection::StartOnce(uint32_t duration) +int32_t VibratorHdiConnection::StartOnce(const VibratorIdentifierIPC &identifier, uint32_t duration) { CHKPR(iVibratorHdiConnection_, VIBRATOR_HDF_CONNECT_ERR); #ifdef HIVIEWDFX_HITRACE_ENABLE StartTrace(HITRACE_TAG_SENSORS, "StartOnce"); #endif // HIVIEWDFX_HITRACE_ENABLE - int32_t ret = iVibratorHdiConnection_->StartOnce(duration); + int32_t ret = iVibratorHdiConnection_->StartOnce(identifier, duration); #ifdef HIVIEWDFX_HITRACE_ENABLE FinishTrace(HITRACE_TAG_SENSORS); #endif // HIVIEWDFX_HITRACE_ENABLE @@ -67,13 +67,13 @@ int32_t VibratorHdiConnection::StartOnce(uint32_t duration) return ERR_OK; } -int32_t VibratorHdiConnection::Start(const std::string &effectType) +int32_t VibratorHdiConnection::Start(const VibratorIdentifierIPC &identifier, const std::string &effectType) { CHKPR(iVibratorHdiConnection_, VIBRATOR_HDF_CONNECT_ERR); #ifdef HIVIEWDFX_HITRACE_ENABLE StartTrace(HITRACE_TAG_SENSORS, "Start"); #endif // HIVIEWDFX_HITRACE_ENABLE - int32_t ret = iVibratorHdiConnection_->Start(effectType); + int32_t ret = iVibratorHdiConnection_->Start(identifier, effectType); #ifdef HIVIEWDFX_HITRACE_ENABLE FinishTrace(HITRACE_TAG_SENSORS); #endif // HIVIEWDFX_HITRACE_ENABLE @@ -86,13 +86,14 @@ int32_t VibratorHdiConnection::Start(const std::string &effectType) #ifdef HDF_DRIVERS_INTERFACE_VIBRATOR #ifdef OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM -int32_t VibratorHdiConnection::EnableCompositeEffect(const HdfCompositeEffect &hdfCompositeEffect) +int32_t VibratorHdiConnection::EnableCompositeEffect(const VibratorIdentifierIPC &identifier, + const HdfCompositeEffect &hdfCompositeEffect) { CHKPR(iVibratorHdiConnection_, VIBRATOR_HDF_CONNECT_ERR); #ifdef HIVIEWDFX_HITRACE_ENABLE StartTrace(HITRACE_TAG_SENSORS, "EnableCompositeEffect"); #endif // HIVIEWDFX_HITRACE_ENABLE - int32_t ret = iVibratorHdiConnection_->EnableCompositeEffect(hdfCompositeEffect); + int32_t ret = iVibratorHdiConnection_->EnableCompositeEffect(identifier, hdfCompositeEffect); #ifdef HIVIEWDFX_HITRACE_ENABLE FinishTrace(HITRACE_TAG_SENSORS); #endif // HIVIEWDFX_HITRACE_ENABLE @@ -103,14 +104,15 @@ int32_t VibratorHdiConnection::EnableCompositeEffect(const HdfCompositeEffect &h return ERR_OK; } -bool VibratorHdiConnection::IsVibratorRunning() +bool VibratorHdiConnection::IsVibratorRunning(const VibratorIdentifierIPC &identifier) { CHKPR(iVibratorHdiConnection_, false); - return iVibratorHdiConnection_->IsVibratorRunning(); + return iVibratorHdiConnection_->IsVibratorRunning(identifier); } #endif // OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM -std::optional VibratorHdiConnection::GetEffectInfo(const std::string &effect) +std::optional VibratorHdiConnection::GetEffectInfo(const VibratorIdentifierIPC &identifier, + const std::string &effect) { if (iVibratorHdiConnection_ == nullptr) { MISC_HILOGE("Connect hdi failed"); @@ -119,20 +121,20 @@ std::optional VibratorHdiConnection::GetEffectInfo(const std::str #ifdef HIVIEWDFX_HITRACE_ENABLE StartTrace(HITRACE_TAG_SENSORS, "GetEffectInfo"); #endif // HIVIEWDFX_HITRACE_ENABLE - std::optional ret = iVibratorHdiConnection_->GetEffectInfo(effect); + std::optional ret = iVibratorHdiConnection_->GetEffectInfo(identifier, effect); #ifdef HIVIEWDFX_HITRACE_ENABLE FinishTrace(HITRACE_TAG_SENSORS); #endif // HIVIEWDFX_HITRACE_ENABLE return ret; } -int32_t VibratorHdiConnection::Stop(HdfVibratorModeV1_2 mode) +int32_t VibratorHdiConnection::Stop(const VibratorIdentifierIPC &identifier, HdfVibratorMode mode) { CHKPR(iVibratorHdiConnection_, VIBRATOR_HDF_CONNECT_ERR); #ifdef HIVIEWDFX_HITRACE_ENABLE StartTrace(HITRACE_TAG_SENSORS, "Stop"); #endif // HIVIEWDFX_HITRACE_ENABLE - int32_t ret = iVibratorHdiConnection_->Stop(mode); + int32_t ret = iVibratorHdiConnection_->Stop(identifier, mode); #ifdef HIVIEWDFX_HITRACE_ENABLE FinishTrace(HITRACE_TAG_SENSORS); #endif // HIVIEWDFX_HITRACE_ENABLE @@ -144,22 +146,22 @@ int32_t VibratorHdiConnection::Stop(HdfVibratorModeV1_2 mode) } #endif // HDF_DRIVERS_INTERFACE_VIBRATOR -int32_t VibratorHdiConnection::GetDelayTime(int32_t mode, int32_t &delayTime) +int32_t VibratorHdiConnection::GetDelayTime(const VibratorIdentifierIPC &identifier, int32_t mode, int32_t &delayTime) { CHKPR(iVibratorHdiConnection_, VIBRATOR_HDF_CONNECT_ERR); - return iVibratorHdiConnection_->GetDelayTime(mode, delayTime); + return iVibratorHdiConnection_->GetDelayTime(identifier, mode, delayTime); } -int32_t VibratorHdiConnection::GetVibratorCapacity(VibratorCapacity &capacity) +int32_t VibratorHdiConnection::GetVibratorCapacity(const VibratorIdentifierIPC &identifier, VibratorCapacity &capacity) { CHKPR(iVibratorHdiConnection_, VIBRATOR_HDF_CONNECT_ERR); - return iVibratorHdiConnection_->GetVibratorCapacity(capacity); + return iVibratorHdiConnection_->GetVibratorCapacity(identifier, capacity); } -int32_t VibratorHdiConnection::PlayPattern(const VibratePattern &pattern) +int32_t VibratorHdiConnection::PlayPattern(const VibratorIdentifierIPC &identifier, const VibratePattern &pattern) { CHKPR(iVibratorHdiConnection_, VIBRATOR_HDF_CONNECT_ERR); - return iVibratorHdiConnection_->PlayPattern(pattern); + return iVibratorHdiConnection_->PlayPattern(identifier, pattern); } int32_t VibratorHdiConnection::DestroyHdiConnection() @@ -173,13 +175,14 @@ int32_t VibratorHdiConnection::DestroyHdiConnection() return ERR_OK; } -int32_t VibratorHdiConnection::StartByIntensity(const std::string &effect, int32_t intensity) +int32_t VibratorHdiConnection::StartByIntensity(const VibratorIdentifierIPC &identifier, const std::string &effect, + int32_t intensity) { CHKPR(iVibratorHdiConnection_, VIBRATOR_HDF_CONNECT_ERR); #ifdef HIVIEWDFX_HITRACE_ENABLE StartTrace(HITRACE_TAG_SENSORS, "StartByIntensity"); #endif // HIVIEWDFX_HITRACE_ENABLE - int32_t ret = iVibratorHdiConnection_->StartByIntensity(effect, intensity); + int32_t ret = iVibratorHdiConnection_->StartByIntensity(identifier, effect, intensity); #ifdef HIVIEWDFX_HITRACE_ENABLE FinishTrace(HITRACE_TAG_SENSORS); #endif // HIVIEWDFX_HITRACE_ENABLE @@ -191,12 +194,55 @@ int32_t VibratorHdiConnection::StartByIntensity(const std::string &effect, int32 } #ifdef HDF_DRIVERS_INTERFACE_VIBRATOR -int32_t VibratorHdiConnection::GetAllWaveInfo(std::vector &waveInfos) +int32_t VibratorHdiConnection::GetVibratorInfo(std::vector &hdfVibratorInfo) { CHKPR(iVibratorHdiConnection_, VIBRATOR_HDF_CONNECT_ERR); - return iVibratorHdiConnection_->GetAllWaveInfo(waveInfos); + return iVibratorHdiConnection_->GetVibratorInfo(hdfVibratorInfo); +} + +int32_t VibratorHdiConnection::GetAllWaveInfo(const VibratorIdentifierIPC &identifier, + std::vector &waveInfos) +{ + CHKPR(iVibratorHdiConnection_, VIBRATOR_HDF_CONNECT_ERR); + return iVibratorHdiConnection_->GetAllWaveInfo(identifier, waveInfos); +} + +int32_t VibratorHdiConnection::GetVibratorIdList(const VibratorIdentifierIPC &identifier, + std::vector &vibratorInfo) +{ + CHKPR(iVibratorHdiConnection_, VIBRATOR_HDF_CONNECT_ERR); + return iVibratorHdiConnection_->GetVibratorIdList(identifier, vibratorInfo); +} + +int32_t VibratorHdiConnection::GetEffectInfo(const VibratorIdentifierIPC &identifier, const std::string &effectType, + HdfEffectInfo &effectInfo) +{ + CHKPR(iVibratorHdiConnection_, VIBRATOR_HDF_CONNECT_ERR); + return iVibratorHdiConnection_->GetEffectInfo(identifier, effectType, effectInfo); } #endif // HDF_DRIVERS_INTERFACE_VIBRATOR +int32_t VibratorHdiConnection::RegisterVibratorPlugCallback(DevicePlugCallback cb) +{ + CHKPR(iVibratorHdiConnection_, VIBRATOR_HDF_CONNECT_ERR); +#ifdef HIVIEWDFX_HITRACE_ENABLE + StartTrace(HITRACE_TAG_SENSORS, "RegisterVibratorPlugCallback"); +#endif // HIVIEWDFX_HITRACE_ENABLE + int32_t ret = iVibratorHdiConnection_->RegisterVibratorPlugCallback(cb); +#ifdef HIVIEWDFX_HITRACE_ENABLE + FinishTrace(HITRACE_TAG_SENSORS); +#endif // HIVIEWDFX_HITRACE_ENABLE + if (ret != 0) { + MISC_HILOGE("RegisterVibratorPlugCallback failed"); + return VIBRATOR_ON_ERR; + } + return ERR_OK; +} + +DevicePlugCallback VibratorHdiConnection::GetVibratorPlugCb() +{ + CHKPP(iVibratorHdiConnection_); + return NULL; +} } // namespace Sensors } // namespace OHOS diff --git a/services/miscdevice_service/include/miscdevice_service.h b/services/miscdevice_service/include/miscdevice_service.h index 2c159524be4e7190d15986eb7ae0ce9a5896f767..b2f10abfeebb3360d6e9566321acf1b16451674c 100644 --- a/services/miscdevice_service/include/miscdevice_service.h +++ b/services/miscdevice_service/include/miscdevice_service.h @@ -36,6 +36,33 @@ enum class MiscdeviceServiceState { STATE_RUNNING, }; +struct VibratorControlInfo { + int motorCount; + std::unordered_map> vibratorThreads; + + VibratorControlInfo(const std::vector& motorIds) : motorCount(static_cast(motorIds.size())) { + for (int motorId : motorIds) { + vibratorThreads[motorId] = std::make_shared(); + } + } + + std::shared_ptr GetVibratorThread(int motorId) const { + auto it = vibratorThreads.find(motorId); + if (it != vibratorThreads.end()) { + return it->second; + } + return nullptr; + } +}; + +struct VibratorAllInfos{ + std::vector baseInfo; + VibratorControlInfo controlInfo; + VibratorCapacity capacityInfo; + std::vector waveInfo; + VibratorAllInfos(const std::vector& motorIds) : controlInfo(motorIds) {} +}; + class MiscdeviceService : public SystemAbility, public MiscdeviceServiceStub { DECLARE_SYSTEM_ABILITY(MiscdeviceService) MISCDEVICE_DECLARE_DELAYED_SP_SINGLETON(MiscdeviceService); @@ -49,36 +76,49 @@ public: bool IsLightAnimationValid(const LightAnimationIPC &animation); int32_t Dump(int32_t fd, const std::vector &args) override; void ProcessDeathObserver(const wptr &object); - virtual int32_t Vibrate(int32_t vibratorId, int32_t timeOut, int32_t usage, bool systemUsage) override; - virtual int32_t PlayVibratorEffect(int32_t vibratorId, const std::string &effect, - int32_t loopCount, int32_t usage, bool systemUsage) override; + virtual int32_t Vibrate(const VibratorIdentifierIPC& identifier, int32_t timeOut, + int32_t usage, bool systemUsage) override; + virtual int32_t PlayVibratorEffect(const VibratorIdentifierIPC& identifier, const std::string &effect, + int32_t loopCount, int32_t usage, bool systemUsage) override; #ifdef OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM - virtual int32_t PlayVibratorCustom(int32_t vibratorId, int32_t fd, int64_t offset, int64_t length, int32_t usage, - bool systemUsage, const VibrateParameter ¶meter) override; + virtual int32_t PlayVibratorCustom(const VibratorIdentifierIPC& identifier, int32_t fd, int64_t offset, + int64_t length, const CustomHapticInfoIPC& customHapticInfoIPC) override; #endif // OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM - virtual int32_t StopVibrator(int32_t vibratorId) override; - virtual int32_t StopVibratorByMode(int32_t vibratorId, const std::string &mode) override; - virtual int32_t IsSupportEffect(const std::string &effect, bool &state) override; + virtual int32_t StopVibrator(const VibratorIdentifierIPC& identifier) override; + virtual int32_t StopVibratorByMode(const VibratorIdentifierIPC& identifier, const std::string &mode) override; + virtual int32_t IsSupportEffect(const VibratorIdentifierIPC& identifier, const std::string &effect, + bool &state) override; virtual int32_t GetLightList(std::vector &lightInfoIpcList) override; virtual int32_t TurnOn(int32_t lightId, int32_t singleColor, const LightAnimationIPC &animation) override; virtual int32_t TurnOff(int32_t lightId) override; - virtual int32_t PlayPattern(const VibratePattern &pattern, int32_t usage, - bool systemUsage, const VibrateParameter ¶meter) override; - virtual int32_t GetDelayTime(int32_t &delayTime) override; + virtual int32_t PlayPattern(const VibratorIdentifierIPC& identifier, const VibratePattern &pattern, + const CustomHapticInfoIPC& customHapticInfoIPC) override; + virtual int32_t GetDelayTime(const VibratorIdentifierIPC& identifier, int32_t &delayTime) override; virtual int32_t TransferClientRemoteObject(const sptr &vibratorServiceClient) override; - virtual int32_t PlayPrimitiveEffect(int32_t vibratorId, const std::string &effect, int32_t intensity, - int32_t usage, bool systemUsage, int32_t count) override; - virtual int32_t GetVibratorCapacity(VibratorCapacity &capacity) override; + virtual int32_t PlayPrimitiveEffect(const VibratorIdentifierIPC& identifier, const std::string &effect, + const PrimitiveEffectIPC& primitiveEffectIPC) override; + virtual int32_t GetVibratorCapacity(const VibratorIdentifierIPC& identifier, VibratorCapacity &capacity) override; + virtual int32_t GetVibratorIdList(const VibratorIdentifierIPC& identifier, + std::vector& vibratorInfoIPC) override; + virtual int32_t GetEffectInfo(const VibratorIdentifierIPC& identifier, const std::string& effectType, + EffectInfoIPC& effectInfoIPC) override; + virtual int32_t SubscribeVibratorPlugInfo(const sptr &vibratorServiceClient) override; private: DISALLOW_COPY_AND_MOVE(MiscdeviceService); bool InitInterface(); bool InitLightInterface(); std::string GetPackageName(AccessTokenID tokenId); - void StartVibrateThread(VibrateInfo info); - int32_t StopVibratorService(int32_t vibratorId); - void StopVibrateThread(); - bool ShouldIgnoreVibrate(const VibrateInfo &info); +#ifdef OHOS_BUILD_ENABLE_VIBRATOR_PRESET_INFO + int32_t FastVibratorEffect(const VibrateInfo &info); +#endif // OHOS_BUILD_ENABLE_VIBRATOR_PRESET_INFO + void StartVibrateThread(VibrateInfo info, const VibratorIdentifierIPC& identifier); + int32_t StopVibratorService(const VibratorIdentifierIPC& identifier); + void SendMsgToClient(HdfVibratorPlugInfo info); + int32_t RegisterVibratorPlugCb(); + std::shared_ptr GetVibratorThread(const VibratorIdentifierIPC& identifier); + void StopVibrateThread(std::shared_ptr vibratorThread); + bool ShouldIgnoreVibrate(const VibrateInfo &info, const VibratorIdentifierIPC& identifier); std::string GetCurrentTime(); void MergeVibratorParmeters(const VibrateParameter ¶meter, VibratePackage &package); bool CheckVibratorParmeters(const VibrateParameter ¶meter); @@ -93,10 +133,24 @@ private: #ifdef OHOS_BUILD_ENABLE_DO_NOT_DISTURB void OnReceiveUserSwitchEvent(const EventFwk::CommonEventData &data); #endif // OHOS_BUILD_ENABLE_DO_NOT_DISTURB - int32_t CheckAuthAndParam(int32_t usage, const VibrateParameter ¶meter); + int32_t CheckAuthAndParam(int32_t usage, const VibrateParameter ¶meter, + const VibratorIdentifierIPC& identifier); int32_t PlayPatternCheckAuthAndParam(int32_t usage, const VibrateParameter ¶meter); int32_t PlayPrimitiveEffectCheckAuthAndParam(int32_t intensity, int32_t usage); int32_t PlayVibratorEffectCheckAuthAndParam(int32_t count, int32_t usage); + int32_t GetHapticCapacityInfo(const VibratorIdentifierIPC& identifier, VibratorCapacity& capacityInfo); + int32_t GetAllWaveInfo(const VibratorIdentifierIPC& identifier, std::vector& waveInfo); + int32_t GetHapticStartUpTime(const VibratorIdentifierIPC& identifier, int32_t mode, int32_t &startUpTime); + void FirstGetLocalVibratorInfo(); + std::vector CheckDeviceIdIsValid(const VibratorIdentifierIPC& identifier); + int32_t StartVibrateThreadControl(const VibratorIdentifierIPC& identifier, VibrateInfo& info); + bool UpdateVibratorAllInfo(const VibratorIdentifierIPC &identifier, const HdfVibratorPlugInfo &info, + VibratorAllInfos &vibratorAllInfos); + void ConvertToServerInfos(const std::vector &baseVibratorInfo, + const VibratorCapacity &vibratorCapacity, const std::vector &waveInfomation, + const HdfVibratorPlugInfo &info, VibratorAllInfos &vibratorAllInfos); + int32_t PerformVibrationControl(const VibratorIdentifierIPC& identifier, const VibratePattern& pattern, + VibrateInfo& info); std::mutex isVibrationPriorityReadyMutex_; static bool isVibrationPriorityReady_; VibratorHdiConnection &vibratorHdiConnection_ = VibratorHdiConnection::GetInstance(); @@ -106,14 +160,15 @@ private: std::vector lightInfos_; std::map miscDeviceIdMap_; MiscdeviceServiceState state_; - std::shared_ptr vibratorThread_ = nullptr; std::mutex vibratorThreadMutex_; sptr clientDeathObserver_ = nullptr; std::mutex clientDeathObserverMutex_; - std::map, int32_t> clientPidMap_; + static std::map, int32_t> clientPidMap_; std::mutex clientPidMapMutex_; std::mutex miscDeviceIdMapMutex_; std::mutex lightInfosMutex_; + std::mutex devicesManageMutex_; + static std::map devicesManageMap_; }; } // namespace Sensors } // namespace OHOS diff --git a/services/miscdevice_service/include/vibration_priority_manager.h b/services/miscdevice_service/include/vibration_priority_manager.h index 106c251661a513afb0df2c019ca1b5291ee4aaae..ebe6f36a1b1b91477de14a7e844aacb65dfed5e0 100644 --- a/services/miscdevice_service/include/vibration_priority_manager.h +++ b/services/miscdevice_service/include/vibration_priority_manager.h @@ -80,7 +80,8 @@ class VibrationPriorityManager { public: DISALLOW_COPY_AND_MOVE(VibrationPriorityManager); bool Init(); - VibrateStatus ShouldIgnoreVibrate(const VibrateInfo &vibrateInfo, std::shared_ptr vibratorThread); + VibrateStatus ShouldIgnoreVibrate(const VibrateInfo &vibrateInfo, + std::shared_ptr vibratorThread, const VibratorIdentifierIPC& identifier); #ifdef OHOS_BUILD_ENABLE_DO_NOT_DISTURB void InitDoNotDisturbData(); void ReregisterCurrentUserObserver(); @@ -91,7 +92,8 @@ public: #endif private: - bool IsCurrentVibrate(std::shared_ptr vibratorThread) const; + bool IsCurrentVibrate(std::shared_ptr vibratorThread, + const VibratorIdentifierIPC& identifier) const; bool IsLoopVibrate(const VibrateInfo &vibrateInfo) const; VibrateStatus ShouldIgnoreVibrate(const VibrateInfo &vibrateInfo, VibrateInfo currentVibrateInfo) const; #ifdef OHOS_BUILD_ENABLE_VIBRATOR_INPUT_METHOD diff --git a/services/miscdevice_service/include/vibrator_thread.h b/services/miscdevice_service/include/vibrator_thread.h index 14d5c02fa1ac672b5f27b9a555da3f6b5d7fe489..a62c492af7b3401ef82e654603799bd1f4f9c0a9 100644 --- a/services/miscdevice_service/include/vibrator_thread.h +++ b/services/miscdevice_service/include/vibrator_thread.h @@ -26,25 +26,34 @@ namespace OHOS { namespace Sensors { class VibratorThread : public Thread { public: - void UpdateVibratorEffect(const VibrateInfo &vibrateInfo); + void UpdateVibratorEffect(const VibrateInfo &vibrateInfo, const VibratorIdentifierIPC& identifier, + std::vector &waveInfos); VibrateInfo GetCurrentVibrateInfo(); + std::vector GetCurrentWaveInfo(); void SetExitStatus(bool status); void WakeUp(); - + void ResetVibrateInfo(); protected: virtual bool Run(); private: - int32_t PlayOnce(const VibrateInfo &info); - int32_t PlayEffect(const VibrateInfo &info); - int32_t PlayCustomByHdHptic(const VibrateInfo &info); - void HandleMultipleVibrations(); + VibratorIdentifierIPC GetCurrentVibrateParams(); + int32_t PlayOnce(const VibrateInfo &info, const VibratorIdentifierIPC& identifier); + int32_t PlayEffect(const VibrateInfo &info, const VibratorIdentifierIPC& identifier); + int32_t PlayCustomByHdHptic(const VibrateInfo &info, const VibratorIdentifierIPC& identifier); + void HandleMultipleVibrations(const VibratorIdentifierIPC& identifier); + VibrateInfo copyInfoWithIndexEvents(const VibrateInfo& originalInfo, const VibratorIdentifierIPC& identifier); #ifdef HDF_DRIVERS_INTERFACE_VIBRATOR - int32_t PlayCustomByCompositeEffect(const VibrateInfo &info); - int32_t PlayCompositeEffect(const VibrateInfo &info, const HdfCompositeEffect &hdfCompositeEffect); + int32_t PlayCustomByCompositeEffect(const VibrateInfo &info, const VibratorIdentifierIPC& identifier, + std::vector waveInfo); + int32_t PlayCompositeEffect(const VibrateInfo &info, const HdfCompositeEffect &hdfCompositeEffect, + const VibratorIdentifierIPC& identifier); #endif // HDF_DRIVERS_INTERFACE_VIBRATOR std::mutex currentVibrationMutex_; VibrateInfo currentVibration_; + std::vector waveInfos_; + std::mutex currentVibrateParamsMutex_; + VibratorIdentifierIPC currentVibrateParams_; std::mutex vibrateMutex_; std::condition_variable cv_; std::atomic exitFlag_ = false; diff --git a/services/miscdevice_service/src/miscdevice_service.cpp b/services/miscdevice_service/src/miscdevice_service.cpp index 4a07c4b7609a24d89ea63101ead5f3e6043c22f8..6a6a0f530924cf589b6af2dcce79ec8111777e1a 100644 --- a/services/miscdevice_service/src/miscdevice_service.cpp +++ b/services/miscdevice_service/src/miscdevice_service.cpp @@ -29,6 +29,7 @@ #include "sensors_errors.h" #include "vibration_priority_manager.h" +#include "vibrator_client_proxy.h" #ifdef HDF_DRIVERS_INTERFACE_LIGHT #include "v1_0/light_interface_proxy.h" @@ -64,31 +65,44 @@ constexpr int32_t INTENSITY_ADJUST_MAX = 100; constexpr int32_t FREQUENCY_ADJUST_MIN = -100; constexpr int32_t FREQUENCY_ADJUST_MAX = 100; constexpr int32_t INVALID_PID = -1; -constexpr int32_t VIBRATOR_ID = 0; constexpr int32_t BASE_YEAR = 1900; constexpr int32_t BASE_MON = 1; constexpr int32_t CONVERSION_RATE = 1000; -VibratorCapacity g_capacity; #ifdef OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM const std::string PHONE_TYPE = "phone"; #endif // OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM +#ifdef OHOS_BUILD_ENABLE_VIBRATOR_PRESET_INFO +constexpr int32_t SHORT_VIBRATOR_DURATION = 50; +#endif // OHOS_BUILD_ENABLE_VIBRATOR_PRESET_INFO } // namespace bool MiscdeviceService::isVibrationPriorityReady_ = false; +std::map MiscdeviceService::devicesManageMap_; +std::map, int32_t> MiscdeviceService::clientPidMap_; MiscdeviceService::MiscdeviceService() : SystemAbility(MISCDEVICE_SERVICE_ABILITY_ID, true), lightExist_(false), vibratorExist_(false), - state_(MiscdeviceServiceState::STATE_STOPPED), - vibratorThread_(nullptr) + state_(MiscdeviceServiceState::STATE_STOPPED) { MISC_HILOGD("Add SystemAbility"); } MiscdeviceService::~MiscdeviceService() { - StopVibrateThread(); + std::lock_guard lock(devicesManageMutex_); + auto it = devicesManageMap_.begin(); + while (it != devicesManageMap_.end()) { + int deviceId = it->first; + const VibratorControlInfo& vibratorControlInfo_ = it->second.controlInfo; + MISC_HILOGI("Device ID:%d, Motor Count:%d", deviceId, vibratorControlInfo_.motorCount); + VibratorIdentifierIPC identifier; + identifier.deviceId = deviceId; + identifier.vibratorId = -1; + StopVibratorService(identifier); + it = devicesManageMap_.erase(it); + } } void MiscdeviceService::OnDump() @@ -196,7 +210,6 @@ void MiscdeviceService::OnReceiveUserSwitchEvent(const EventFwk::CommonEventData } } #endif // OHOS_BUILD_ENABLE_DO_NOT_DISTURB - void MiscdeviceService::OnStart() { CALL_LOG_ENTER; @@ -230,6 +243,18 @@ void MiscdeviceService::OnStart() AddSystemAbilityListener(MEMORY_MANAGER_SA_ID); #endif // MEMMGR_ENABLE AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID); + RegisterVibratorPlugCb(); +} + +int32_t MiscdeviceService::RegisterVibratorPlugCb() +{ + auto ret = vibratorHdiConnection_.RegisterVibratorPlugCallback( + std::bind(&MiscdeviceService::SendMsgToClient, this, std::placeholders::_1)); + if (ret != ERR_OK) { + MISC_HILOGE("InitVibratorServiceImpl failed"); + return false; + } + return true; } void MiscdeviceService::OnStartFuzz() @@ -266,9 +291,7 @@ bool MiscdeviceService::InitInterface() MISC_HILOGE("InitVibratorServiceImpl failed"); return false; } - if (vibratorHdiConnection_.GetVibratorCapacity(g_capacity) != ERR_OK) { - MISC_HILOGE("GetVibratorCapacity failed"); - } + (void)FirstGetLocalVibratorInfo(); return true; } @@ -330,7 +353,7 @@ void MiscdeviceService::OnStop() #endif // MEMMGR_ENABLE } -bool MiscdeviceService::ShouldIgnoreVibrate(const VibrateInfo &info) +bool MiscdeviceService::ShouldIgnoreVibrate(const VibrateInfo &info, const VibratorIdentifierIPC& identifier) { std::lock_guard lock(isVibrationPriorityReadyMutex_); if (!isVibrationPriorityReady_) { @@ -338,14 +361,16 @@ bool MiscdeviceService::ShouldIgnoreVibrate(const VibrateInfo &info) return VIBRATION; } std::string curVibrateTime = GetCurrentTime(); - int32_t ret = PriorityManager->ShouldIgnoreVibrate(info, vibratorThread_); + auto vibratorThread_ = GetVibratorThread(identifier); + int32_t ret = PriorityManager->ShouldIgnoreVibrate(info, vibratorThread_, identifier); if (ret != VIBRATION) { MISC_HILOGE("ShouldIgnoreVibrate currentTime:%{public}s, ret:%{public}d", curVibrateTime.c_str(), ret); } return (ret != VIBRATION); } -int32_t MiscdeviceService::Vibrate(int32_t vibratorId, int32_t timeOut, int32_t usage, bool systemUsage) +int32_t MiscdeviceService::Vibrate(const VibratorIdentifierIPC& identifier, int32_t timeOut, int32_t usage, + bool systemUsage) { PermissionUtil &permissionUtil = PermissionUtil::GetInstance(); int32_t ret = permissionUtil.CheckVibratePermission(this->GetCallingTokenID(), VIBRATE_PERMISSION); @@ -373,18 +398,21 @@ int32_t MiscdeviceService::Vibrate(int32_t vibratorId, int32_t timeOut, int32_t }; std::lock_guard lock(vibratorThreadMutex_); std::string curVibrateTime = GetCurrentTime(); - if (ShouldIgnoreVibrate(info)) { - MISC_HILOGE("%{public}s:vibration is ignored and high priority is vibrating", curVibrateTime.c_str()); - return ERROR; + { + std::lock_guard lock(devicesManageMutex_); + if (StartVibrateThreadControl(identifier, info) != ERR_OK) { + MISC_HILOGE("%{public}s:vibration is ignored and high priority is vibrating or no vibration found", + curVibrateTime.c_str()); + return ERROR; + } } - StartVibrateThread(info); MISC_HILOGI("Start vibrator, currentTime:%{public}s, package:%{public}s, pid:%{public}d, usage:%{public}d," - "vibratorId:%{public}d, duration:%{public}d", curVibrateTime.c_str(), info.packageName.c_str(), info.pid, - info.usage, vibratorId, info.duration); + "deviceId:%{public}d, vibratorId:%{public}d, duration:%{public}d", curVibrateTime.c_str(), + info.packageName.c_str(), info.pid, info.usage, identifier.vibratorId, identifier.deviceId, info.duration); return NO_ERROR; } -int32_t MiscdeviceService::StopVibrator(int32_t vibratorId) +int32_t MiscdeviceService::StopVibrator(const VibratorIdentifierIPC& identifier) { PermissionUtil &permissionUtil = PermissionUtil::GetInstance(); int32_t ret = permissionUtil.CheckVibratePermission(this->GetCallingTokenID(), VIBRATE_PERMISSION); @@ -396,37 +424,54 @@ int32_t MiscdeviceService::StopVibrator(int32_t vibratorId) MISC_HILOGE("Result:%{public}d", ret); return PERMISSION_DENIED; } - return StopVibratorService(vibratorId); + std::lock_guard lock(devicesManageMutex_); + return StopVibratorService(identifier); } -int32_t MiscdeviceService::StopVibratorService(int32_t vibratorId) +int32_t MiscdeviceService::StopVibratorService(const VibratorIdentifierIPC& identifier) { std::lock_guard lock(vibratorThreadMutex_); -#if defined (OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM) && defined (HDF_DRIVERS_INTERFACE_VIBRATOR) - if ((vibratorThread_ == nullptr) || (!vibratorThread_->IsRunning() && - !vibratorHdiConnection_.IsVibratorRunning())) { + std::vector result = CheckDeviceIdIsValid(identifier); + int ignoreVibrateNum = 0; + if(result.empty()) { MISC_HILOGD("No vibration, no need to stop"); return ERROR; } - if (vibratorHdiConnection_.IsVibratorRunning()) { - vibratorHdiConnection_.Stop(HDF_VIBRATOR_MODE_PRESET); - vibratorHdiConnection_.Stop(HDF_VIBRATOR_MODE_HDHAPTIC); + for (const auto& paramIt : result) { + auto vibratorThread_ = GetVibratorThread(paramIt); + #if defined (OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM) && defined (HDF_DRIVERS_INTERFACE_VIBRATOR) + if ((vibratorThread_ == nullptr) || (!vibratorThread_->IsRunning() && + !vibratorHdiConnection_.IsVibratorRunning(paramIt))) { + MISC_HILOGD("No vibration, no need to stop"); + ignoreVibrateNum ++; + continue; + } + if (vibratorHdiConnection_.IsVibratorRunning(paramIt)) { + vibratorHdiConnection_.Stop(paramIt, HDF_VIBRATOR_MODE_PRESET); + vibratorHdiConnection_.Stop(paramIt, HDF_VIBRATOR_MODE_HDHAPTIC); + } + #else + if ((vibratorThread_ == nullptr) || (!vibratorThread_->IsRunning())) { + MISC_HILOGD("No vibration, no need to stop"); + ignoreVibrateNum ++; + continue; + } + #endif // OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM && HDF_DRIVERS_INTERFACE_VIBRATOR + StopVibrateThread(vibratorThread_); } -#else - if ((vibratorThread_ == nullptr) || (!vibratorThread_->IsRunning())) { + if(ignoreVibrateNum == result.size()) { MISC_HILOGD("No vibration, no need to stop"); return ERROR; } -#endif // OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM && HDF_DRIVERS_INTERFACE_VIBRATOR - StopVibrateThread(); std::string packageName = GetPackageName(GetCallingTokenID()); std::string curVibrateTime = GetCurrentTime(); - MISC_HILOGI("Stop vibrator, currentTime:%{public}s, package:%{public}s, pid:%{public}d, vibratorId:%{public}d", - curVibrateTime.c_str(), packageName.c_str(), GetCallingPid(), vibratorId); + MISC_HILOGI("Stop vibrator, currentTime:%{public}s, package:%{public}s, pid:%{public}d, deviceId:%{public}d," + "vibratorId:%{public}d", curVibrateTime.c_str(), packageName.c_str(), GetCallingPid(), identifier.deviceId, + identifier.vibratorId); return NO_ERROR; } -int32_t MiscdeviceService::PlayVibratorEffect(int32_t vibratorId, const std::string &effect, +int32_t MiscdeviceService::PlayVibratorEffect(const VibratorIdentifierIPC& identifier, const std::string &effect, int32_t count, int32_t usage, bool systemUsage) { int32_t checkResult = PlayVibratorEffectCheckAuthAndParam(count, usage); @@ -435,7 +480,7 @@ int32_t MiscdeviceService::PlayVibratorEffect(int32_t vibratorId, const std::str return checkResult; } #ifdef HDF_DRIVERS_INTERFACE_VIBRATOR - std::optional effectInfo = vibratorHdiConnection_.GetEffectInfo(effect); + std::optional effectInfo = vibratorHdiConnection_.GetEffectInfo(identifier, effect); if (!effectInfo) { MISC_HILOGE("GetEffectInfo fail"); return ERROR; @@ -461,14 +506,18 @@ int32_t MiscdeviceService::PlayVibratorEffect(int32_t vibratorId, const std::str }; std::lock_guard lock(vibratorThreadMutex_); std::string curVibrateTime = GetCurrentTime(); - if (ShouldIgnoreVibrate(info)) { - MISC_HILOGE("%{public}s:vibration is ignored and high priority is vibrating", curVibrateTime.c_str()); - return ERROR; + { + std::lock_guard lock(devicesManageMutex_); + if (StartVibrateThreadControl(identifier, info) != ERR_OK) { + MISC_HILOGE("%{public}s:vibration is ignored and high priority is vibrating or no vibration found", + curVibrateTime.c_str()); + return ERROR; + } } - StartVibrateThread(info); MISC_HILOGI("Start vibrator, currentTime:%{public}s, package:%{public}s, pid:%{public}d, usage:%{public}d," - "vibratorId:%{public}d, duration:%{public}d, effect:%{public}s, count:%{public}d", curVibrateTime.c_str(), - info.packageName.c_str(), info.pid, info.usage, vibratorId, info.duration, info.effect.c_str(), info.count); + "deviceId:%{public}d, vibratorId:%{public}d, duration:%{public}d, effect:%{public}s, count:%{public}d", + curVibrateTime.c_str(), info.packageName.c_str(), info.pid, info.usage, identifier.deviceId, + identifier.vibratorId, info.duration, info.effect.c_str(), info.count); return NO_ERROR; } @@ -491,34 +540,53 @@ int32_t MiscdeviceService::PlayVibratorEffectCheckAuthAndParam(int32_t count, in return ERR_OK; } -void MiscdeviceService::StartVibrateThread(VibrateInfo info) +void MiscdeviceService::StartVibrateThread(VibrateInfo info, const VibratorIdentifierIPC& identifier) { + auto vibratorThread_ = GetVibratorThread(identifier); if (vibratorThread_ == nullptr) { - vibratorThread_ = std::make_shared(); + MISC_HILOGD("No effective vibrator thread"); + return; } - StopVibrateThread(); +#ifdef OHOS_BUILD_ENABLE_VIBRATOR_PRESET_INFO + VibrateInfo currentVibrateInfo = vibratorThread_->GetCurrentVibrateInfo(); + if (info.duration <= SHORT_VIBRATOR_DURATION && currentVibrateInfo.duration <= SHORT_VIBRATOR_DURATION && + info.mode == VIBRATE_PRESET && currentVibrateInfo.mode == VIBRATE_PRESET && info.count == 1) { + vibratorThread_->UpdateVibratorEffect(info, identifier, waveInfo); + FastVibratorEffect(info, identifier); + } else { +#endif // OHOS_BUILD_ENABLE_VIBRATOR_PRESET_INFO + StopVibrateThread(vibratorThread_); #if defined (OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM) && defined (HDF_DRIVERS_INTERFACE_VIBRATOR) - if (vibratorHdiConnection_.IsVibratorRunning()) { - vibratorHdiConnection_.Stop(HDF_VIBRATOR_MODE_PRESET); - vibratorHdiConnection_.Stop(HDF_VIBRATOR_MODE_HDHAPTIC); + if (vibratorHdiConnection_.IsVibratorRunning(identifier)) { + vibratorHdiConnection_.Stop(identifier, HDF_VIBRATOR_MODE_PRESET); + vibratorHdiConnection_.Stop(identifier, HDF_VIBRATOR_MODE_HDHAPTIC); } #endif // OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM && HDF_DRIVERS_INTERFACE_VIBRATOR - vibratorThread_->UpdateVibratorEffect(info); + std::vector waveInfo; + if(GetAllWaveInfo(identifier, waveInfo) != ERR_OK) { + MISC_HILOGE("GetAllWaveInfo failed"); + return; + } + vibratorThread_->UpdateVibratorEffect(info, identifier, waveInfo); vibratorThread_->Start("VibratorThread"); +#ifdef OHOS_BUILD_ENABLE_VIBRATOR_PRESET_INFO +} +#endif // OHOS_BUILD_ENABLE_VIBRATOR_PRESET_INFO DumpHelper->SaveVibrateRecord(info); } -void MiscdeviceService::StopVibrateThread() +void MiscdeviceService::StopVibrateThread(std::shared_ptr vibratorThread) { - if ((vibratorThread_ != nullptr) && (vibratorThread_->IsRunning())) { - vibratorThread_->SetExitStatus(true); - vibratorThread_->WakeUp(); - vibratorThread_->NotifyExitSync(); - vibratorThread_->SetExitStatus(false); + if ((vibratorThread != nullptr) && (vibratorThread->IsRunning())) { + vibratorThread->SetExitStatus(true); + vibratorThread->WakeUp(); + vibratorThread->NotifyExitSync(); + vibratorThread->SetExitStatus(false); + vibratorThread->ResetVibrateInfo(); } } -int32_t MiscdeviceService::StopVibratorByMode(int32_t vibratorId, const std::string &mode) +int32_t MiscdeviceService::StopVibratorByMode(const VibratorIdentifierIPC& identifier, const std::string &mode) { std::lock_guard lock(vibratorThreadMutex_); PermissionUtil &permissionUtil = PermissionUtil::GetInstance(); @@ -531,35 +599,47 @@ int32_t MiscdeviceService::StopVibratorByMode(int32_t vibratorId, const std::str MISC_HILOGE("CheckVibratePermission failed, ret:%{public}d", ret); return PERMISSION_DENIED; } - if ((vibratorThread_ == nullptr) || (!vibratorThread_->IsRunning())) { -#if defined (OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM) && defined (HDF_DRIVERS_INTERFACE_VIBRATOR) - if (vibratorHdiConnection_.IsVibratorRunning()) { - vibratorHdiConnection_.Stop(HDF_VIBRATOR_MODE_PRESET); - vibratorHdiConnection_.Stop(HDF_VIBRATOR_MODE_HDHAPTIC); - MISC_HILOGD("StopVibratorByMode"); - return NO_ERROR; - } -#endif // OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM && HDF_DRIVERS_INTERFACE_VIBRATOR + std::vector result = CheckDeviceIdIsValid(identifier); + int ignoreVibrateNum = 0; + if(result.empty()) { MISC_HILOGD("No vibration, no need to stop"); return ERROR; } - const VibrateInfo info = vibratorThread_->GetCurrentVibrateInfo(); - if (info.mode != mode) { - MISC_HILOGD("Stop vibration information mismatch"); + for (const auto& paramIt : result) { + auto vibratorThread_ = GetVibratorThread(paramIt); + if ((vibratorThread_ == nullptr) || (!vibratorThread_->IsRunning() && + !vibratorHdiConnection_.IsVibratorRunning(paramIt))) { + MISC_HILOGD("No vibration, no need to stop"); + ignoreVibrateNum ++; + continue; + } + const VibrateInfo info = vibratorThread_->GetCurrentVibrateInfo(); + if (info.mode != mode) { + MISC_HILOGD("Stop vibration information mismatch"); + continue; + } + StopVibrateThread(vibratorThread_); + if (vibratorHdiConnection_.IsVibratorRunning(paramIt)) { + vibratorHdiConnection_.Stop(paramIt, HDF_VIBRATOR_MODE_PRESET); + } + } + if(ignoreVibrateNum == result.size()) { + MISC_HILOGD("No vibration, no need to stop"); return ERROR; } - StopVibrateThread(); std::string packageName = GetPackageName(GetCallingTokenID()); std::string curVibrateTime = GetCurrentTime(); - MISC_HILOGI("Stop vibrator, currentTime:%{public}s, package:%{public}s, pid:%{public}d, vibratorId:%{public}d," - "mode:%{public}s", curVibrateTime.c_str(), packageName.c_str(), GetCallingPid(), vibratorId, mode.c_str()); + MISC_HILOGI("Stop vibrator, currentTime:%{public}s, package:%{public}s, pid:%{public}d, deviceId:%{public}d," + "vibratorId:%{public}d, mode:%{public}s", curVibrateTime.c_str(), packageName.c_str(), GetCallingPid(), + identifier.deviceId, identifier.vibratorId, mode.c_str()); return NO_ERROR; } -int32_t MiscdeviceService::IsSupportEffect(const std::string &effect, bool &state) +int32_t MiscdeviceService::IsSupportEffect(const VibratorIdentifierIPC& identifier, const std::string &effect, + bool &state) { #ifdef HDF_DRIVERS_INTERFACE_VIBRATOR - std::optional effectInfo = vibratorHdiConnection_.GetEffectInfo(effect); + std::optional effectInfo = vibratorHdiConnection_.GetEffectInfo(identifier, effect); if (!effectInfo) { MISC_HILOGE("GetEffectInfo fail"); return ERROR; @@ -592,12 +672,13 @@ std::string MiscdeviceService::GetCurrentTime() } #ifdef OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM -int32_t MiscdeviceService::PlayVibratorCustom(int32_t vibratorId, int32_t fd, int64_t offset, int64_t length, - int32_t usage, bool systemUsage, const VibrateParameter ¶meter) +int32_t MiscdeviceService::PlayVibratorCustom(const VibratorIdentifierIPC& identifier, int32_t fd, + int64_t offset, int64_t length, const CustomHapticInfoIPC& customHapticInfoIPC) { - int32_t checkResult = CheckAuthAndParam(usage, parameter); + int32_t checkResult = CheckAuthAndParam(customHapticInfoIPC.usage, customHapticInfoIPC.parameter, identifier); if (checkResult != ERR_OK) { MISC_HILOGE("CheckAuthAndParam failed, ret:%{public}d", checkResult); + close(fd); return checkResult; } RawFileDescriptor rawFd; @@ -614,16 +695,21 @@ int32_t MiscdeviceService::PlayVibratorCustom(int32_t vibratorId, int32_t fd, in MISC_HILOGE("Decode effect error"); return ERROR; } - MergeVibratorParmeters(parameter, package); + MergeVibratorParmeters(customHapticInfoIPC.parameter, package); package.Dump(); VibrateInfo info = { .packageName = GetPackageName(GetCallingTokenID()), .pid = GetCallingPid(), .uid = GetCallingUid(), - .usage = usage, - .systemUsage = systemUsage, + .usage = customHapticInfoIPC.usage, + .systemUsage = customHapticInfoIPC.systemUsage, .package = package, }; + VibratorCapacity g_capacity; + if(GetHapticCapacityInfo(identifier, g_capacity) != ERR_OK) { + MISC_HILOGE("GetVibratorCapacity failed"); + return ERROR; + } if (g_capacity.isSupportHdHaptic) { info.mode = VIBRATE_CUSTOM_HD; } else if (g_capacity.isSupportPresetMapping) { @@ -633,19 +719,23 @@ int32_t MiscdeviceService::PlayVibratorCustom(int32_t vibratorId, int32_t fd, in } std::lock_guard lock(vibratorThreadMutex_); std::string curVibrateTime = GetCurrentTime(); - if (ShouldIgnoreVibrate(info)) { - MISC_HILOGE("%{public}s:vibration is ignored and high priority is vibrating", curVibrateTime.c_str()); - return ERROR; + { + std::lock_guard lock(devicesManageMutex_); + if (StartVibrateThreadControl(identifier, info) != ERR_OK) { + MISC_HILOGE("%{public}s:vibration is ignored and high priority is vibrating or no vibration found", + curVibrateTime.c_str()); + return ERROR; + } } - StartVibrateThread(info); MISC_HILOGI("Start vibrator, currentTime:%{public}s, package:%{public}s, pid:%{public}d, usage:%{public}d," "vibratorId:%{public}d, duration:%{public}d", curVibrateTime.c_str(), info.packageName.c_str(), info.pid, - info.usage, vibratorId, package.packageDuration); + info.usage, identifier.vibratorId, package.packageDuration); return NO_ERROR; } #endif // OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM -int32_t MiscdeviceService::CheckAuthAndParam(int32_t usage, const VibrateParameter ¶meter) +int32_t MiscdeviceService::CheckAuthAndParam(int32_t usage, const VibrateParameter ¶meter, + const VibratorIdentifierIPC& identifier) { PermissionUtil &permissionUtil = PermissionUtil::GetInstance(); int32_t ret = permissionUtil.CheckVibratePermission(this->GetCallingTokenID(), VIBRATE_PERMISSION); @@ -657,6 +747,11 @@ int32_t MiscdeviceService::CheckAuthAndParam(int32_t usage, const VibrateParamet MISC_HILOGE("CheckVibratePermission failed, ret:%{public}d", ret); return PERMISSION_DENIED; } + VibratorCapacity g_capacity; + if(GetHapticCapacityInfo(identifier, g_capacity) != ERR_OK) { + MISC_HILOGE("GetVibratorCapacity failed"); + return ERROR; + } if (!(g_capacity.isSupportHdHaptic || g_capacity.isSupportPresetMapping || g_capacity.isSupportTimeDelay)) { MISC_HILOGE("The device does not support this operation"); return IS_NOT_SUPPORTED; @@ -800,10 +895,29 @@ int32_t MiscdeviceService::Dump(int32_t fd, const std::vector &a return ERR_OK; } -int32_t MiscdeviceService::PlayPattern(const VibratePattern &pattern, int32_t usage, - bool systemUsage, const VibrateParameter ¶meter) +int32_t MiscdeviceService::PerformVibrationControl(const VibratorIdentifierIPC& identifier, const VibratePattern& pattern, + VibrateInfo& info) +{ + std::lock_guard lock(vibratorThreadMutex_); + std::string curVibrateTime = GetCurrentTime(); + { + std::lock_guard lock(devicesManageMutex_); + if (StartVibrateThreadControl(identifier, info) != ERR_OK) { + MISC_HILOGE("%{public}s:vibration is ignored and high priority is vibrating or no vibration found", + curVibrateTime.c_str()); + return ERROR; + } + } + MISC_HILOGI("Start vibrator, currentTime:%{public}s, package:%{public}s, pid:%{public}d, usage:%{public}d," + "duration:%{public}d", curVibrateTime.c_str(), info.packageName.c_str(), info.pid, info.usage, + pattern.patternDuration); + return ERR_OK; +} + +int32_t MiscdeviceService::PlayPattern(const VibratorIdentifierIPC& identifier, const VibratePattern &pattern, + const CustomHapticInfoIPC& customHapticInfoIPC) { - int32_t checkResult = PlayPatternCheckAuthAndParam(usage, parameter); + int32_t checkResult = PlayPatternCheckAuthAndParam(customHapticInfoIPC.usage, customHapticInfoIPC.parameter); if (checkResult != ERR_OK) { MISC_HILOGE("CheckAuthAndParam failed, ret:%{public}d", checkResult); return checkResult; @@ -815,45 +929,35 @@ int32_t MiscdeviceService::PlayPattern(const VibratePattern &pattern, int32_t us VibratePackage package = { .patterns = patterns }; - MergeVibratorParmeters(parameter, package); + MergeVibratorParmeters(customHapticInfoIPC.parameter, package); package.Dump(); VibrateInfo info = { .mode = VIBRATE_BUTT, .packageName = GetPackageName(GetCallingTokenID()), .pid = GetCallingPid(), .uid = GetCallingUid(), - .usage = usage, - .systemUsage = systemUsage + .usage = customHapticInfoIPC.usage, + .systemUsage = customHapticInfoIPC.systemUsage }; + VibratorCapacity g_capacity; + if(GetHapticCapacityInfo(identifier, g_capacity) != ERR_OK) { + MISC_HILOGE("GetVibratorCapacity failed"); + return ERROR; + } if (g_capacity.isSupportHdHaptic) { - std::lock_guard lock(vibratorThreadMutex_); - std::string curVibrateTime = GetCurrentTime(); - if (ShouldIgnoreVibrate(info)) { - MISC_HILOGE("%{public}s:vibration is ignored and high priority is vibrating", curVibrateTime.c_str()); - return ERROR; + int32_t result = PerformVibrationControl(identifier, pattern, info); + if (result != ERR_OK) { + MISC_HILOGE("PerformVibrationControl failed"); + return result; } - StartVibrateThread(info); - MISC_HILOGI("Start vibrator, currentTime:%{public}s, package:%{public}s, pid:%{public}d, usage:%{public}d," - "duration:%{public}d", curVibrateTime.c_str(), info.packageName.c_str(), info.pid, info.usage, - pattern.patternDuration); - return vibratorHdiConnection_.PlayPattern(package.patterns.front()); + return vibratorHdiConnection_.PlayPattern(identifier, package.patterns.front()); } else if (g_capacity.isSupportPresetMapping) { info.mode = VIBRATE_CUSTOM_COMPOSITE_EFFECT; } else if (g_capacity.isSupportTimeDelay) { info.mode = VIBRATE_CUSTOM_COMPOSITE_TIME; } info.package = package; - std::lock_guard lock(vibratorThreadMutex_); - std::string curVibrateTime = GetCurrentTime(); - if (ShouldIgnoreVibrate(info)) { - MISC_HILOGE("%{public}s:vibration is ignored and high priority is vibrating", curVibrateTime.c_str()); - return ERROR; - } - StartVibrateThread(info); - MISC_HILOGI("Start vibrator, currentTime:%{public}s, package:%{public}s, pid:%{public}d, usage:%{public}d," - "duration:%{public}d", curVibrateTime.c_str(), info.packageName.c_str(), info.pid, info.usage, - pattern.patternDuration); - return ERR_OK; + return PerformVibrationControl(identifier, pattern, info); } int32_t MiscdeviceService::PlayPatternCheckAuthAndParam(int32_t usage, const VibrateParameter ¶meter) @@ -875,11 +979,16 @@ int32_t MiscdeviceService::PlayPatternCheckAuthAndParam(int32_t usage, const Vib return ERR_OK; } -int32_t MiscdeviceService::GetDelayTime(int32_t &delayTime) +int32_t MiscdeviceService::GetDelayTime(const VibratorIdentifierIPC& identifier, int32_t &delayTime) { std::string packageName = GetPackageName(GetCallingTokenID()); MISC_HILOGD("GetDelayTime, package:%{public}s", packageName.c_str()); - return vibratorHdiConnection_.GetDelayTime(g_capacity.GetVibrateMode(), delayTime); + VibratorCapacity g_capacity; + if(GetHapticCapacityInfo(identifier, g_capacity) != ERR_OK) { + MISC_HILOGE("GetVibratorCapacity failed"); + return ERROR; + } + return vibratorHdiConnection_.GetDelayTime(identifier, g_capacity.GetVibrateMode(), delayTime); } bool MiscdeviceService::CheckVibratorParmeters(const VibrateParameter ¶meter) @@ -899,7 +1008,7 @@ void MiscdeviceService::MergeVibratorParmeters(const VibrateParameter ¶meter MISC_HILOGD("The adjust parameter is not need to merge"); return; } - parameter.Dump(); + MISC_HILOGI("intensity:%{public}d, frequency:%{public}d", parameter.intensity, parameter.frequency); for (VibratePattern &pattern : package.patterns) { for (VibrateEvent &event : pattern.events) { float intensityScale = static_cast(parameter.intensity) / INTENSITY_ADJUST_MAX; @@ -920,6 +1029,42 @@ void MiscdeviceService::MergeVibratorParmeters(const VibrateParameter ¶meter } } +void MiscdeviceService::SendMsgToClient(HdfVibratorPlugInfo info) +{ + std::lock_guard lock(clientPidMapMutex_); + MISC_HILOGW("%{public}p, %{public}d, %{public}d", this, clientPidMap_.size(), info.status); + for (auto it = clientPidMap_.begin(); it != clientPidMap_.end(); ++it) { + const sptr& key = it->first; + + sptr clientProxy = iface_cast(key); + if (clientProxy != nullptr) { + clientProxy->ProcessPlugEvent(info.status, info.deviceId); + } + } + std::lock_guard lockManage(devicesManageMutex_); + if(info.status == 0) { + auto it = devicesManageMap_.find(info.deviceId); + if (it != devicesManageMap_.end()) { + VibratorIdentifierIPC identifier; + identifier.deviceId = info.deviceId; + identifier.vibratorId = -1; + StopVibratorService(identifier); + devicesManageMap_.erase(it); + MISC_HILOGI("Device %{public}d is offline and removed from the map.", info.deviceId); + } else { + MISC_HILOGI("Device %{public}d is not in the map, so no action taken.", info.deviceId); + } + }else { + VibratorIdentifierIPC identifier; + identifier.deviceId = info.deviceId; + VibratorAllInfos newAllInfo({}); + if (!UpdateVibratorAllInfo(identifier, info, newAllInfo)) { + MISC_HILOGE("Update new vibrator info failed"); + return; + } + } +} + int32_t MiscdeviceService::TransferClientRemoteObject(const sptr &vibratorServiceClient) { auto clientPid = GetCallingPid(); @@ -937,17 +1082,31 @@ void MiscdeviceService::ProcessDeathObserver(const wptr &object) sptr client = object.promote(); int32_t clientPid = FindClientPid(client); VibrateInfo info; - { - std::lock_guard lock(vibratorThreadMutex_); - if (vibratorThread_ == nullptr) { - vibratorThread_ = std::make_shared(); + std::lock_guard lock(devicesManageMutex_); + for (const auto& pair : devicesManageMap_) { + int deviceId = pair.first; + const VibratorControlInfo& vibratorControlInfo_ = pair.second.controlInfo; + MISC_HILOGI("Device ID:%{public}d, , Motor Count:%{public}d", deviceId, vibratorControlInfo_.motorCount); + for (const auto& motorPair : vibratorControlInfo_.vibratorThreads) { + int motorId = motorPair.first; + { + std::lock_guard lock(vibratorThreadMutex_); + auto vibratorThread_ = motorPair.second; + if (vibratorThread_ == nullptr) { + MISC_HILOGE("MotorId:%{public}d, Vibrate thread no found in devicesManageMap_", motorId); + vibratorThread_ = std::make_shared(); + } + info = vibratorThread_->GetCurrentVibrateInfo(); + } + int32_t vibratePid = info.pid; + MISC_HILOGI("ClientPid:%{public}d, VibratePid:%{public}d", clientPid, vibratePid); + if ((clientPid != INVALID_PID) && (clientPid == vibratePid)) { + VibratorIdentifierIPC identifier; + identifier.deviceId = deviceId; + identifier.vibratorId = motorId; + StopVibratorService(identifier); + } } - info = vibratorThread_->GetCurrentVibrateInfo(); - } - int32_t vibratePid = info.pid; - MISC_HILOGI("ClientPid:%{public}d, VibratePid:%{public}d", clientPid, vibratePid); - if ((clientPid != INVALID_PID) && (clientPid == vibratePid)) { - StopVibratorService(VIBRATOR_ID); } UnregisterClientDeathRecipient(client); } @@ -968,6 +1127,21 @@ void MiscdeviceService::RegisterClientDeathRecipient(sptr vibrat } vibratorServiceClient->AddDeathRecipient(clientDeathObserver_); SaveClientPid(vibratorServiceClient, pid); + + // std::thread([this, vibratorServiceClient]() { + // std::this_thread::sleep_for(std::chrono::milliseconds(500)); + // std::lock_guard lockManage(devicesManageMutex_); + // if (devicesManageMap_.empty()) { + // MISC_HILOGI("No vibrator device online"); + // return; + // } + // for (auto &value : devicesManageMap_) { + // sptr clientProxy = iface_cast(vibratorServiceClient); + // if (clientProxy != nullptr) { + // clientProxy->ProcessPlugEvent(1, value.first); + // } + // } + // }).detach(); } void MiscdeviceService::UnregisterClientDeathRecipient(sptr vibratorServiceClient) @@ -1026,16 +1200,16 @@ void MiscdeviceService::DestroyClientPid(const sptr &vibratorServ clientPidMap_.erase(it); } -int32_t MiscdeviceService::PlayPrimitiveEffect(int32_t vibratorId, const std::string &effect, - int32_t intensity, int32_t usage, bool systemUsage, int32_t count) +int32_t MiscdeviceService::PlayPrimitiveEffect(const VibratorIdentifierIPC& identifier, + const std::string &effect, const PrimitiveEffectIPC& primitiveEffectIPC) { - int32_t checkResult = PlayPrimitiveEffectCheckAuthAndParam(intensity, usage); + int32_t checkResult = PlayPrimitiveEffectCheckAuthAndParam(primitiveEffectIPC.intensity, primitiveEffectIPC.usage); if (checkResult != ERR_OK) { MISC_HILOGE("CheckAuthAndParam failed, ret:%{public}d", checkResult); return checkResult; } #ifdef HDF_DRIVERS_INTERFACE_VIBRATOR - std::optional effectInfo = vibratorHdiConnection_.GetEffectInfo(effect); + std::optional effectInfo = vibratorHdiConnection_.GetEffectInfo(identifier, effect); if (!effectInfo) { MISC_HILOGE("GetEffectInfo fail"); return ERROR; @@ -1050,25 +1224,29 @@ int32_t MiscdeviceService::PlayPrimitiveEffect(int32_t vibratorId, const std::st .packageName = GetPackageName(GetCallingTokenID()), .pid = GetCallingPid(), .uid = GetCallingUid(), - .usage = usage, - .systemUsage = systemUsage, + .usage = primitiveEffectIPC.usage, + .systemUsage = primitiveEffectIPC.systemUsage, #ifdef HDF_DRIVERS_INTERFACE_VIBRATOR .duration = effectInfo->duration, #endif // HDF_DRIVERS_INTERFACE_VIBRATOR .effect = effect, - .count = count, - .intensity = intensity + .count = primitiveEffectIPC.count, + .intensity = primitiveEffectIPC.intensity }; std::lock_guard lock(vibratorThreadMutex_); std::string curVibrateTime = GetCurrentTime(); - if (ShouldIgnoreVibrate(info)) { - MISC_HILOGE("%{public}s:vibration is ignored and high priority is vibrating", curVibrateTime.c_str()); - return ERROR; + { + std::lock_guard lock(devicesManageMutex_); + if (StartVibrateThreadControl(identifier, info) != ERR_OK) { + MISC_HILOGE("%{public}s:vibration is ignored and high priority is vibrating or no vibration found", + curVibrateTime.c_str()); + return ERROR; + } } - StartVibrateThread(info); MISC_HILOGI("Start vibrator, currentTime:%{public}s, package:%{public}s, pid:%{public}d, usage:%{public}d," - "vibratorId:%{public}d, duration:%{public}d, effect:%{public}s, intensity:%{public}d", curVibrateTime.c_str(), - info.packageName.c_str(), info.pid, info.usage, vibratorId, info.duration, info.effect.c_str(), info.intensity); + "deviceId:%{public}d, vibratorId:%{public}d, duration:%{public}d, effect:%{public}s, intensity:%{public}d", + curVibrateTime.c_str(), info.packageName.c_str(), info.pid, info.usage, identifier.deviceId, + identifier.vibratorId, info.duration, info.effect.c_str(), info.intensity); return NO_ERROR; } @@ -1091,10 +1269,421 @@ int32_t MiscdeviceService::PlayPrimitiveEffectCheckAuthAndParam(int32_t intensit return ERR_OK; } -int32_t MiscdeviceService::GetVibratorCapacity(VibratorCapacity &capacity) +int32_t MiscdeviceService::GetVibratorIdList(const VibratorIdentifierIPC& identifier, + std::vector& vibratorInfoIPC) +{ + CALL_LOG_ENTER; + PermissionUtil &permissionUtil = PermissionUtil::GetInstance(); + int32_t ret = permissionUtil.CheckVibratePermission(this->GetCallingTokenID(), VIBRATE_PERMISSION); + if (ret != PERMISSION_GRANTED) { +#ifdef HIVIEWDFX_HISYSEVENT_ENABLE + HiSysEventWrite(HiSysEvent::Domain::MISCDEVICE, "VIBRATOR_PERMISSIONS_EXCEPTION", + HiSysEvent::EventType::SECURITY, "PKG_NAME", "GetVibratorIdList", "ERROR_CODE", ret); +#endif // HIVIEWDFX_HISYSEVENT_ENABLE + MISC_HILOGE("CheckVibratePermission failed, ret:%{public}d", ret); + return PERMISSION_DENIED; + } + identifier.Dump(); + if (devicesManageMap_.empty()) { + MISC_HILOGI("No vibrator device online"); + return NO_ERROR; + } + if ((identifier.deviceId == -1 && identifier.vibratorId == -1) || + (identifier.deviceId == -1 && identifier.vibratorId != -1)) { + for (auto &value : devicesManageMap_) { + vibratorInfoIPC.insert(vibratorInfoIPC.end(), value.second.baseInfo.begin(), + value.second.baseInfo.end()); + } + return NO_ERROR; + } else if (identifier.deviceId != -1 && identifier.vibratorId == -1) { + auto it = devicesManageMap_.find(identifier.deviceId); + if (it == devicesManageMap_.end()) { + MISC_HILOGD("Device manager map has no vibrator info"); + return NO_ERROR; + } + vibratorInfoIPC = it->second.baseInfo; + return NO_ERROR; + } else { + auto it = devicesManageMap_.find(identifier.deviceId); + if (it == devicesManageMap_.end()) { + MISC_HILOGD("Device manager map has no vibrator info"); + return NO_ERROR; + } + for (auto &value : it->second.baseInfo) { + if (identifier.vibratorId == value.vibratorId) { + vibratorInfoIPC.emplace_back(value); + } + } + return NO_ERROR; + } + return NO_ERROR; +} + +int32_t MiscdeviceService::GetEffectInfo(const VibratorIdentifierIPC& identifier, const std::string& effectType, + EffectInfoIPC& effectInfoIPC) { + CALL_LOG_ENTER; + PermissionUtil &permissionUtil = PermissionUtil::GetInstance(); + int32_t ret = permissionUtil.CheckVibratePermission(this->GetCallingTokenID(), VIBRATE_PERMISSION); + if (ret != PERMISSION_GRANTED) { +#ifdef HIVIEWDFX_HISYSEVENT_ENABLE + HiSysEventWrite(HiSysEvent::Domain::MISCDEVICE, "VIBRATOR_PERMISSIONS_EXCEPTION", + HiSysEvent::EventType::SECURITY, "PKG_NAME", "GetEffectInfo", "ERROR_CODE", ret); +#endif // HIVIEWDFX_HISYSEVENT_ENABLE + MISC_HILOGE("CheckVibratePermission failed, ret:%{public}d", ret); + return PERMISSION_DENIED; + } + identifier.Dump(); + if (devicesManageMap_.empty()) { + MISC_HILOGI("No vibrator device online"); + return NO_ERROR; + } + VibratorIdentifierIPC localIdentifier; + if (identifier.deviceId == -1) { + for (const auto& pair : devicesManageMap_) { + for (const auto& info : pair.second.baseInfo) { + info.isLocalVibrator ? (localIdentifier.deviceId = info.deviceId) : 0; + } + } + } + HdfEffectInfo hdfEffectInfo; + ret = vibratorHdiConnection_.GetEffectInfo((identifier.deviceId == -1) ? localIdentifier : identifier, + effectType, hdfEffectInfo); + if (ret != NO_ERROR) { + MISC_HILOGE("HDI::GetEffectInfo return error"); + return ERROR; + } + effectInfoIPC.duration = hdfEffectInfo.duration; + effectInfoIPC.isSupportEffect = hdfEffectInfo.isSupportEffect; + effectInfoIPC.Dump(); + return NO_ERROR; +} + +int32_t MiscdeviceService::SubscribeVibratorPlugInfo(const sptr &vibratorServiceClient) +{ + auto clientPid = GetCallingPid(); + if (clientPid < 0) { + MISC_HILOGE("ClientPid is invalid, clientPid:%{public}d", clientPid); + return ERROR; + } + if(vibratorServiceClient == nullptr) { + MISC_HILOGD("VibratorServiceClient is nullptr"); + return ERROR; + } + + std::thread([this, vibratorServiceClient]() { + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + std::lock_guard lockManage(devicesManageMutex_); + if (devicesManageMap_.empty()) { + MISC_HILOGI("No vibrator device online"); + return ERR_OK; + } + + for (auto &value : devicesManageMap_) { + sptr clientProxy = iface_cast(vibratorServiceClient); + if (clientProxy != nullptr) { + clientProxy->ProcessPlugEvent(1, value.first); + } + } + return ERR_OK; + }).detach(); + return ERR_OK; +} + +int32_t MiscdeviceService::GetVibratorCapacity(const VibratorIdentifierIPC& identifier, VibratorCapacity &capacity) +{ + CALL_LOG_ENTER; + VibratorCapacity g_capacity; + if(GetHapticCapacityInfo(identifier, g_capacity) != ERR_OK) { + MISC_HILOGE("GetVibratorCapacity failed"); + return ERROR; + } capacity = g_capacity; return ERR_OK; } + +// 手表短振快速下发不启动线程 +#ifdef OHOS_BUILD_ENABLE_VIBRATOR_PRESET_INFO +int32_t MiscdeviceService::FastVibratorEffect(const VibrateInfo &info) +{ + int32_t ret = VibratorDevice.StartByIntensity(info.effect, info.intensity); + if (ret != SUCCESS) { + MISC_HILOGE("Vibrate effect %{public}s failed.", info.effect.c_str()); + } + return NO_ERROR; +} +#endif // OHOS_BUILD_ENABLE_VIBRATOR_PRESET_INFO + +std::shared_ptr MiscdeviceService::GetVibratorThread(const VibratorIdentifierIPC& identifier) +{ + CALL_LOG_ENTER; + auto deviceIt = devicesManageMap_.find(identifier.deviceId); + if (deviceIt != devicesManageMap_.end()) { + auto thread = deviceIt->second.controlInfo.GetVibratorThread(identifier.vibratorId); + if (thread) { + MISC_HILOGI("Success: Vibrate thread found."); + return thread; + } else { + MISC_HILOGE("Failed: Vibrate thread no found."); + return nullptr; + } + } + return nullptr; +} + +int32_t MiscdeviceService::GetHapticCapacityInfo(const VibratorIdentifierIPC& identifier, + VibratorCapacity& capacityInfo) +{ + CALL_LOG_ENTER; + std::lock_guard lock(devicesManageMutex_); + if (identifier.deviceId == -1) { + for (const auto& pair : devicesManageMap_) { + for (const auto& info : pair.second.baseInfo) { + if (info.isLocalVibrator) { + capacityInfo = pair.second.capacityInfo; + return ERR_OK; + } + } + } + }else { + auto deviceIt = devicesManageMap_.find(identifier.deviceId); + if (deviceIt != devicesManageMap_.end()) { + capacityInfo = deviceIt->second.capacityInfo; + return ERR_OK; + } + } + MISC_HILOGE("No vibrator information found for device ID: %{public}d", identifier.deviceId); + return PARAMETER_ERROR; +} + +int32_t MiscdeviceService::GetAllWaveInfo(const VibratorIdentifierIPC& identifier, + std::vector& waveInfo) +{ + CALL_LOG_ENTER; + if (identifier.deviceId == -1) { + for (const auto& pair : devicesManageMap_) { + for (const auto& info : pair.second.baseInfo) { + if (info.isLocalVibrator) { + waveInfo = pair.second.waveInfo; + return ERR_OK; + } + } + } + }else { + auto deviceIt = devicesManageMap_.find(identifier.deviceId); + if (deviceIt != devicesManageMap_.end()) { + waveInfo = deviceIt->second.waveInfo; + return ERR_OK; + } + } + MISC_HILOGW("No vibrator information found for device ID: %{public}d", identifier.deviceId); + return ERR_OK; +} + +int32_t MiscdeviceService::GetHapticStartUpTime(const VibratorIdentifierIPC& identifier, int32_t mode, + int32_t &startUpTime) +{ + CALL_LOG_ENTER; + auto ret = vibratorHdiConnection_.GetDelayTime(identifier, mode, startUpTime); + if (ret != NO_ERROR) { + MISC_HILOGE("HDI::GetHapticStartUpTime return error"); + return ERROR; + } + return NO_ERROR; +} + +bool MiscdeviceService::UpdateVibratorAllInfo(const VibratorIdentifierIPC &identifier, + const HdfVibratorPlugInfo &info, VibratorAllInfos &vibratorAllInfos) +{ + CALL_LOG_ENTER; + std::vector baseInfo; + std::vector vibratorIdList; + int32_t ret = -1; + if (identifier.deviceId < 0 || (identifier.deviceId < 0 && identifier.vibratorId < 0)) { + ret = vibratorHdiConnection_.GetVibratorInfo(baseInfo); + } else { + ret = vibratorHdiConnection_.GetVibratorIdList(identifier, baseInfo); + } + if (ret != NO_ERROR || baseInfo.empty()) { + MISC_HILOGE("HDI::GetVibratorInfoList return error"); + return false; + } + for (auto& value: baseInfo) { + vibratorIdList.push_back(value.vibratorId); + } + VibratorAllInfos tVibratorInfo(vibratorIdList); + vibratorAllInfos = tVibratorInfo; + VibratorCapacity vibratorCapacity; + ret = vibratorHdiConnection_.GetVibratorCapacity(identifier, vibratorCapacity); + if (ret != NO_ERROR) { + MISC_HILOGE("HDI::GetHapticCapacity return error"); + return false; + } + std::vector waveInfo; + ret = vibratorHdiConnection_.GetAllWaveInfo(identifier, waveInfo); + if (ret != NO_ERROR) { + MISC_HILOGE("HDI::GetAllWaveInfo return error"); + return false; + } + (void)ConvertToServerInfos(baseInfo, vibratorCapacity, waveInfo, info, vibratorAllInfos); + devicesManageMap_.insert(std::make_pair(identifier.deviceId, vibratorAllInfos)); + return true; +} + +void MiscdeviceService::ConvertToServerInfos(const std::vector &baseVibratorInfo, + const VibratorCapacity &vibratorCapacity, const std::vector &waveInfomation, + const HdfVibratorPlugInfo &info, VibratorAllInfos& vibratorAllInfos) +{ + CALL_LOG_ENTER; + VibratorInfoIPC vibratorInfo; + for (auto infos : baseVibratorInfo) { + vibratorInfo.deviceId = infos.deviceId; + vibratorInfo.vibratorId = infos.vibratorId; + vibratorInfo.deviceName = "LocalVibrator"; + if (infos.isLocal != 1) { + vibratorInfo.deviceName = info.deviceName; + } + vibratorInfo.isSupportHdHaptic = vibratorCapacity.isSupportHdHaptic; + vibratorInfo.isLocalVibrator = infos.isLocal; + vibratorAllInfos.baseInfo.emplace_back(vibratorInfo); + MISC_HILOGW("HDI::HdfVibratorInfo deviceId:%{public}d, vibratorId:%{public}d, isLocalVibrator:%{public}d", + vibratorInfo.deviceId, vibratorInfo.vibratorId, vibratorInfo.isLocalVibrator); + } + vibratorAllInfos.capacityInfo = vibratorCapacity; + vibratorAllInfos.waveInfo = waveInfomation; +} + +void MiscdeviceService::FirstGetLocalVibratorInfo() +{ + CALL_LOG_ENTER; + std::vector vibratorInfo; + auto ret = vibratorHdiConnection_.GetVibratorInfo(vibratorInfo); + if (ret != NO_ERROR || vibratorInfo.empty()) { + MISC_HILOGW("Device not contain the local vibrator"); + return; + } + std::vector localInfo; + HdfVibratorPlugInfo mockInfo; + VibratorIdentifierIPC param; + for (auto &info : vibratorInfo) { + if (info.isLocal == 1) { + localInfo.emplace_back(info); + param.deviceId = info.deviceId; + } + } + VibratorCapacity capacity; + ret = vibratorHdiConnection_.GetVibratorCapacity(param, capacity); + if (ret != NO_ERROR) { + MISC_HILOGE("Get local hapticCapacity fail"); + return; + } + std::vector waveInfo; + ret = vibratorHdiConnection_.GetAllWaveInfo(param, waveInfo); + if (ret != NO_ERROR) { + MISC_HILOGE("Get local waveInfo fail"); + return; + } + std::vector vibratorIdList; + for (auto &value : localInfo) { + vibratorIdList.push_back(value.vibratorId); + } + VibratorAllInfos localVibratorInfo(vibratorIdList); + (void)ConvertToServerInfos(localInfo, capacity, waveInfo, mockInfo, localVibratorInfo); + devicesManageMap_.insert(std::make_pair(param.deviceId, localVibratorInfo)); +} + +int32_t MiscdeviceService::StartVibrateThreadControl(const VibratorIdentifierIPC& identifier, VibrateInfo& info) +{ + std::string curVibrateTime = GetCurrentTime(); + std::vector result = CheckDeviceIdIsValid(identifier); + if (result.empty()) { + MISC_HILOGE("No vibration found"); + return ERROR; + } + + int32_t ignoreVibrateNum = 0; + + const std::vector specialModes = { + VIBRATE_CUSTOM_HD, VIBRATE_CUSTOM_COMPOSITE_EFFECT, + VIBRATE_CUSTOM_COMPOSITE_TIME, VIBRATE_BUTT + }; + + std::unordered_set uniqueIndices; + if (std::find(specialModes.begin(), specialModes.end(), info.mode) != specialModes.end()) { + for (const auto& pattern : info.package.patterns) { + for (const auto& event : pattern.events) { + uniqueIndices.insert(event.index); + } + } + for (const auto& index : uniqueIndices) { + MISC_HILOGD("Info mode:%{public}s, vibratorIndex:%{public}d", info.mode.c_str(), index); + } + } + + for (const auto& paramIt : result) { + bool shouldProcess = uniqueIndices.empty() || + uniqueIndices.find(0) != uniqueIndices.end() || + uniqueIndices.find(paramIt.position) != uniqueIndices.end(); + + if (paramIt.isLocalVibrator && ShouldIgnoreVibrate(info, paramIt)) { + if (shouldProcess) { + ignoreVibrateNum++; + continue; + } + } + MISC_HILOGD("Info mode:111111111111111111111111"); + if (shouldProcess) { + MISC_HILOGD("Info mode:222222222222222222222222"); + StartVibrateThread(info, paramIt); + } + } + + return (ignoreVibrateNum == result.size()) ? ERROR : ERR_OK; +} + +std::vector MiscdeviceService::CheckDeviceIdIsValid(const VibratorIdentifierIPC& identifier) +{ + CALL_LOG_ENTER; + std::vector result; + + auto addToResult = [&](const auto& info) { + VibratorIdentifierIPC newIdentifier; + newIdentifier.deviceId = identifier.deviceId == -1 ? info.deviceId : identifier.deviceId; + newIdentifier.vibratorId = info.vibratorId; + newIdentifier.position = info.position; + newIdentifier.isLocalVibrator = info.isLocalVibrator; + result.push_back(newIdentifier); + MISC_HILOGD("Push result in list,:%{public}d,:%{public}d", newIdentifier.deviceId, newIdentifier.vibratorId); + }; + + auto processDevice = [&](const auto& device) { + for (const auto& info : device.second.baseInfo) { + bool shouldAdd = true; + if (identifier.deviceId == -1 && identifier.vibratorId != -1) { + shouldAdd = info.isLocalVibrator && info.vibratorId == identifier.vibratorId; + } else if (identifier.deviceId != -1 && identifier.vibratorId != -1) { + shouldAdd = info.vibratorId == identifier.vibratorId; + } else if (identifier.deviceId == -1 && identifier.vibratorId == -1) { + shouldAdd = info.isLocalVibrator; + } + + if (shouldAdd) { + addToResult(info); + } + } + }; + + if (identifier.deviceId != -1) { + auto deviceIt = devicesManageMap_.find(identifier.deviceId); + if (deviceIt != devicesManageMap_.end()) { + processDevice(*deviceIt); + } + } else { + for (const auto& pair : devicesManageMap_) { + processDevice(pair); + } + } + return result; +} } // namespace Sensors } // namespace OHOS diff --git a/services/miscdevice_service/src/vibration_priority_manager.cpp b/services/miscdevice_service/src/vibration_priority_manager.cpp index f17201de8a01593dab9f2ba509ddb4cc71e1ae3a..a8bb72eabba3fd92f9f5aa4347f582b176373863 100644 --- a/services/miscdevice_service/src/vibration_priority_manager.cpp +++ b/services/miscdevice_service/src/vibration_priority_manager.cpp @@ -675,32 +675,32 @@ bool VibrationPriorityManager::ShouldIgnoreInputMethod(const VibrateInfo &vibrat #endif // OHOS_BUILD_ENABLE_VIBRATOR_INPUT_METHOD VibrateStatus VibrationPriorityManager::ShouldIgnoreVibrate(const VibrateInfo &vibrateInfo, - std::shared_ptr vibratorThread) + std::shared_ptr vibratorThread, const VibratorIdentifierIPC& identifier) { UpdateStatus(); if (!IsSystemCalling() || vibrateInfo.systemUsage == false) { #ifdef OHOS_BUILD_ENABLE_DO_NOT_DISTURB - if (IgnoreAppVibrations(vibrateInfo)) { - MISC_HILOGD("Vibration is ignored for doNotDisturb, usage:%{public}d", vibrateInfo.usage); - return IGNORE_GLOBAL_SETTINGS; - } + if (IgnoreAppVibrations(vibrateInfo)) { + MISC_HILOGD("Vibration is ignored for doNotDisturb, usage:%{public}d", vibrateInfo.usage); + return IGNORE_GLOBAL_SETTINGS; + } #endif // OHOS_BUILD_ENABLE_DO_NOT_DISTURB - if ((vibrateInfo.usage == USAGE_ALARM || vibrateInfo.usage == USAGE_RING - || vibrateInfo.usage == USAGE_NOTIFICATION || vibrateInfo.usage == USAGE_COMMUNICATION) - && (miscAudioRingerMode_ == RINGER_MODE_SILENT)) { - MISC_HILOGD("Vibration is ignored for ringer mode:%{public}d", static_cast(miscAudioRingerMode_)); - return IGNORE_RINGER_MODE; - } - if (((vibrateInfo.usage == USAGE_TOUCH || vibrateInfo.usage == USAGE_MEDIA || vibrateInfo.usage == USAGE_UNKNOWN - || vibrateInfo.usage == USAGE_PHYSICAL_FEEDBACK || vibrateInfo.usage == USAGE_SIMULATE_REALITY) - && (miscFeedback_ == FEEDBACK_MODE_OFF)) + if ((vibrateInfo.usage == USAGE_ALARM || vibrateInfo.usage == USAGE_RING + || vibrateInfo.usage == USAGE_NOTIFICATION || vibrateInfo.usage == USAGE_COMMUNICATION) + && (miscAudioRingerMode_ == RINGER_MODE_SILENT)) { + MISC_HILOGD("Vibration is ignored for ringer mode:%{public}d", static_cast(miscAudioRingerMode_)); + return IGNORE_RINGER_MODE; + } + if (((vibrateInfo.usage == USAGE_TOUCH || vibrateInfo.usage == USAGE_MEDIA || vibrateInfo.usage == USAGE_UNKNOWN + || vibrateInfo.usage == USAGE_PHYSICAL_FEEDBACK || vibrateInfo.usage == USAGE_SIMULATE_REALITY) + && (miscFeedback_ == FEEDBACK_MODE_OFF)) #ifdef OHOS_BUILD_ENABLE_VIBRATOR_INPUT_METHOD - && !ShouldIgnoreInputMethod(vibrateInfo)) { + && !ShouldIgnoreInputMethod(vibrateInfo)) { #else // OHOS_BUILD_ENABLE_VIBRATOR_INPUT_METHOD - ) { + ) { #endif // OHOS_BUILD_ENABLE_VIBRATOR_INPUT_METHOD - MISC_HILOGD("Vibration is ignored for feedback:%{public}d", static_cast(miscFeedback_)); - return IGNORE_FEEDBACK; + MISC_HILOGD("Vibration is ignored for feedback:%{public}d", static_cast(miscFeedback_)); + return IGNORE_FEEDBACK; } } #ifdef OHOS_BUILD_ENABLE_VIBRATOR_CROWN @@ -713,7 +713,7 @@ VibrateStatus VibrationPriorityManager::ShouldIgnoreVibrate(const VibrateInfo &v MISC_HILOGD("There is no vibration, it can vibrate"); return VIBRATION; } - if (!IsCurrentVibrate(vibratorThread)) { + if (!IsCurrentVibrate(vibratorThread, identifier)) { MISC_HILOGD("There is no vibration at the moment, it can vibrate"); return VIBRATION; } @@ -724,10 +724,12 @@ VibrateStatus VibrationPriorityManager::ShouldIgnoreVibrate(const VibrateInfo &v return ShouldIgnoreVibrate(vibrateInfo, vibratorThread->GetCurrentVibrateInfo()); } -bool VibrationPriorityManager::IsCurrentVibrate(std::shared_ptr vibratorThread) const +bool VibrationPriorityManager::IsCurrentVibrate(std::shared_ptr vibratorThread, + const VibratorIdentifierIPC& identifier) const { #if defined(OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM) && defined(HDF_DRIVERS_INTERFACE_VIBRATOR) - return ((vibratorThread != nullptr) && (vibratorThread->IsRunning() || VibratorDevice.IsVibratorRunning())); + return ((vibratorThread != nullptr) && (vibratorThread->IsRunning() || + VibratorDevice.IsVibratorRunning(identifier))); #else return ((vibratorThread != nullptr) && (vibratorThread->IsRunning())); #endif // OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM && HDF_DRIVERS_INTERFACE_VIBRATOR diff --git a/services/miscdevice_service/src/vibrator_thread.cpp b/services/miscdevice_service/src/vibrator_thread.cpp index b680897c8e997e4d05206a7f5b9d7a6df5be211f..7d2030f0cd284534d314681970e9af0f4d1c4e5d 100644 --- a/services/miscdevice_service/src/vibrator_thread.cpp +++ b/services/miscdevice_service/src/vibrator_thread.cpp @@ -40,27 +40,30 @@ bool VibratorThread::Run() CALL_LOG_ENTER; prctl(PR_SET_NAME, VIBRATE_CONTROL_THREAD_NAME.c_str()); VibrateInfo info = GetCurrentVibrateInfo(); + VibratorIdentifierIPC identifier = GetCurrentVibrateParams(); + std::vector waveInfos = GetCurrentWaveInfo(); + MISC_HILOGD("info.mode:%{public}s, deviceId:%{public}d, vibratorId:%{public}d", info.mode.c_str(), identifier.deviceId, identifier.vibratorId); if (info.mode == VIBRATE_TIME) { - int32_t ret = PlayOnce(info); + int32_t ret = PlayOnce(info, identifier); if (ret != SUCCESS) { MISC_HILOGE("Play once vibration fail, package:%{public}s", info.packageName.c_str()); return false; } } else if (info.mode == VIBRATE_PRESET) { - int32_t ret = PlayEffect(info); + int32_t ret = PlayEffect(info, identifier); if (ret != SUCCESS) { MISC_HILOGE("Play effect vibration fail, package:%{public}s", info.packageName.c_str()); return false; } } else if (info.mode == VIBRATE_CUSTOM_HD) { - int32_t ret = PlayCustomByHdHptic(info); + int32_t ret = PlayCustomByHdHptic(info, identifier); if (ret != SUCCESS) { MISC_HILOGE("Play custom vibration by hd haptic fail, package:%{public}s", info.packageName.c_str()); return false; } } else if (info.mode == VIBRATE_CUSTOM_COMPOSITE_EFFECT || info.mode == VIBRATE_CUSTOM_COMPOSITE_TIME) { #ifdef HDF_DRIVERS_INTERFACE_VIBRATOR - int32_t ret = PlayCustomByCompositeEffect(info); + int32_t ret = PlayCustomByCompositeEffect(info, identifier, waveInfos); if (ret != SUCCESS) { MISC_HILOGE("Play custom vibration by composite effect fail, package:%{public}s", info.packageName.c_str()); return false; @@ -70,10 +73,10 @@ bool VibratorThread::Run() return false; } -int32_t VibratorThread::PlayOnce(const VibrateInfo &info) +int32_t VibratorThread::PlayOnce(const VibrateInfo &info, const VibratorIdentifierIPC& identifier) { std::unique_lock vibrateLck(vibrateMutex_); - int32_t ret = VibratorDevice.StartOnce(static_cast(info.duration)); + int32_t ret = VibratorDevice.StartOnce(identifier, static_cast(info.duration)); if (ret != SUCCESS) { MISC_HILOGE("StartOnce fail, duration:%{public}d", info.duration); return ERROR; @@ -81,7 +84,7 @@ int32_t VibratorThread::PlayOnce(const VibrateInfo &info) cv_.wait_for(vibrateLck, std::chrono::milliseconds(info.duration), [this] { return exitFlag_.load(); }); if (exitFlag_) { #ifdef HDF_DRIVERS_INTERFACE_VIBRATOR - VibratorDevice.Stop(HDF_VIBRATOR_MODE_ONCE); + VibratorDevice.Stop(identifier, HDF_VIBRATOR_MODE_ONCE); #endif // HDF_DRIVERS_INTERFACE_VIBRATOR MISC_HILOGD("Stop duration:%{public}d, package:%{public}s", info.duration, info.packageName.c_str()); return SUCCESS; @@ -89,13 +92,13 @@ int32_t VibratorThread::PlayOnce(const VibrateInfo &info) return SUCCESS; } -void VibratorThread::HandleMultipleVibrations() +void VibratorThread::HandleMultipleVibrations(const VibratorIdentifierIPC& identifier) { - if (VibratorDevice.IsVibratorRunning()) { - VibratorDevice.Stop(HDF_VIBRATOR_MODE_PRESET); - VibratorDevice.Stop(HDF_VIBRATOR_MODE_HDHAPTIC); + if (VibratorDevice.IsVibratorRunning(identifier)) { + VibratorDevice.Stop(identifier, HDF_VIBRATOR_MODE_PRESET); + VibratorDevice.Stop(identifier, HDF_VIBRATOR_MODE_HDHAPTIC); for (size_t i = 0; i < RETRY_NUMBER; i++) { - if (!VibratorDevice.IsVibratorRunning()) { + if (!VibratorDevice.IsVibratorRunning(identifier)) { MISC_HILOGI("No running vibration"); return; } @@ -105,17 +108,17 @@ void VibratorThread::HandleMultipleVibrations() } } -int32_t VibratorThread::PlayEffect(const VibrateInfo &info) +int32_t VibratorThread::PlayEffect(const VibrateInfo &info, const VibratorIdentifierIPC& identifier) { std::unique_lock vibrateLck(vibrateMutex_); for (int32_t i = 0; i < info.count; ++i) { std::string effect = info.effect; int32_t duration = info.duration; if (i >= 1) { /**Multiple vibration treatment*/ - HandleMultipleVibrations(); + HandleMultipleVibrations(identifier); duration += DELAY_TIME2; } - int32_t ret = VibratorDevice.StartByIntensity(effect, info.intensity); + int32_t ret = VibratorDevice.StartByIntensity(identifier, effect, info.intensity); if (ret != SUCCESS) { MISC_HILOGE("Vibrate effect %{public}s failed, ", effect.c_str()); return ERROR; @@ -123,7 +126,7 @@ int32_t VibratorThread::PlayEffect(const VibrateInfo &info) cv_.wait_for(vibrateLck, std::chrono::milliseconds(duration), [this] { return exitFlag_.load(); }); if (exitFlag_) { #ifdef HDF_DRIVERS_INTERFACE_VIBRATOR - VibratorDevice.Stop(HDF_VIBRATOR_MODE_PRESET); + VibratorDevice.Stop(identifier, HDF_VIBRATOR_MODE_PRESET); #endif // HDF_DRIVERS_INTERFACE_VIBRATOR MISC_HILOGD("Stop effect:%{public}s, package:%{public}s", effect.c_str(), info.packageName.c_str()); return SUCCESS; @@ -132,7 +135,7 @@ int32_t VibratorThread::PlayEffect(const VibrateInfo &info) return SUCCESS; } -int32_t VibratorThread::PlayCustomByHdHptic(const VibrateInfo &info) +int32_t VibratorThread::PlayCustomByHdHptic(const VibrateInfo &info, const VibratorIdentifierIPC& identifier) { std::unique_lock vibrateLck(vibrateMutex_); const std::vector &patterns = info.package.patterns; @@ -147,15 +150,15 @@ int32_t VibratorThread::PlayCustomByHdHptic(const VibrateInfo &info) cv_.wait_for(vibrateLck, std::chrono::milliseconds(delayTime), [this] { return exitFlag_.load(); }); if (exitFlag_) { #ifdef HDF_DRIVERS_INTERFACE_VIBRATOR - VibratorDevice.Stop(HDF_VIBRATOR_MODE_HDHAPTIC); + VibratorDevice.Stop(identifier, HDF_VIBRATOR_MODE_HDHAPTIC); #endif // HDF_DRIVERS_INTERFACE_VIBRATOR MISC_HILOGD("Stop hd haptic, package:%{public}s", info.packageName.c_str()); return SUCCESS; } #ifdef HDF_DRIVERS_INTERFACE_VIBRATOR - HandleMultipleVibrations(); + HandleMultipleVibrations(identifier); #endif // HDF_DRIVERS_INTERFACE_VIBRATOR - int32_t ret = VibratorDevice.PlayPattern(patterns[i]); + int32_t ret = VibratorDevice.PlayPattern(identifier, patterns[i]); if (ret != SUCCESS) { MISC_HILOGE("Vibrate hd haptic failed"); return ERROR; @@ -164,19 +167,49 @@ int32_t VibratorThread::PlayCustomByHdHptic(const VibrateInfo &info) return SUCCESS; } +VibrateInfo VibratorThread::copyInfoWithIndexEvents(const VibrateInfo& originalInfo, const VibratorIdentifierIPC& identifier) +{ + VibrateInfo newInfo = originalInfo; + VibratePackage newPackage; + int32_t parseDuration = 0; + + for (const auto& pattern : originalInfo.package.patterns) { + VibratePattern newPattern; + newPattern.startTime = pattern.startTime; + newPattern.patternDuration = pattern.patternDuration; + + for (const auto& event : pattern.events) { + if (event.index == 0 || event.index == identifier.position) { + newPattern.events.push_back(event); + parseDuration = event.duration; + } + } + + if (!newPattern.events.empty()) { + newPackage.patterns.push_back(newPattern); + } + } + + newInfo.package = newPackage; + newInfo.package.packageDuration = parseDuration; + return newInfo; +} + #ifdef HDF_DRIVERS_INTERFACE_VIBRATOR -int32_t VibratorThread::PlayCustomByCompositeEffect(const VibrateInfo &info) +int32_t VibratorThread::PlayCustomByCompositeEffect(const VibrateInfo &info, const VibratorIdentifierIPC& identifier, + std::vector waveInfo) { - auto &matcher = CustomVibrationMatcher::GetInstance(); + CustomVibrationMatcher matcher(identifier, waveInfo); HdfCompositeEffect hdfCompositeEffect; - if (info.mode == VIBRATE_CUSTOM_COMPOSITE_EFFECT) { + VibrateInfo newInfo = copyInfoWithIndexEvents(info, identifier); + if (newInfo.mode == VIBRATE_CUSTOM_COMPOSITE_EFFECT) { hdfCompositeEffect.type = HDF_EFFECT_TYPE_PRIMITIVE; - int32_t ret = matcher.TransformEffect(info.package, hdfCompositeEffect.compositeEffects); + int32_t ret = matcher.TransformEffect(newInfo.package, hdfCompositeEffect.compositeEffects); if (ret != SUCCESS) { MISC_HILOGE("Transform pattern to predefined wave fail"); return ERROR; } - } else if (info.mode == VIBRATE_CUSTOM_COMPOSITE_TIME) { + } else if (newInfo.mode == VIBRATE_CUSTOM_COMPOSITE_TIME) { hdfCompositeEffect.type = HDF_EFFECT_TYPE_TIME; int32_t ret = matcher.TransformTime(info.package, hdfCompositeEffect.compositeEffects); if (ret != SUCCESS) { @@ -184,10 +217,11 @@ int32_t VibratorThread::PlayCustomByCompositeEffect(const VibrateInfo &info) return ERROR; } } - return PlayCompositeEffect(info, hdfCompositeEffect); + return PlayCompositeEffect(newInfo, hdfCompositeEffect, identifier); } -int32_t VibratorThread::PlayCompositeEffect(const VibrateInfo &info, const HdfCompositeEffect &hdfCompositeEffect) +int32_t VibratorThread::PlayCompositeEffect(const VibrateInfo &info, const HdfCompositeEffect &hdfCompositeEffect, + const VibratorIdentifierIPC& identifier) { std::unique_lock vibrateLck(vibrateMutex_); HdfCompositeEffect effectsPart; @@ -205,7 +239,7 @@ int32_t VibratorThread::PlayCompositeEffect(const VibrateInfo &info, const HdfCo return ERROR; } if ((effectsPart.compositeEffects.size() >= COMPOSITE_EFFECT_PART) || (i == (effectSize - 1))) { - int32_t ret = VibratorDevice.EnableCompositeEffect(effectsPart); + int32_t ret = VibratorDevice.EnableCompositeEffect(identifier, effectsPart); if (ret != SUCCESS) { MISC_HILOGE("EnableCompositeEffect failed"); return ERROR; @@ -215,7 +249,7 @@ int32_t VibratorThread::PlayCompositeEffect(const VibrateInfo &info, const HdfCo effectsPart.compositeEffects.clear(); } if (exitFlag_) { - VibratorDevice.Stop(HDF_VIBRATOR_MODE_PRESET); + VibratorDevice.Stop(identifier, HDF_VIBRATOR_MODE_PRESET); MISC_HILOGD("Stop composite effect part, package:%{public}s", info.packageName.c_str()); return SUCCESS; } @@ -224,10 +258,13 @@ int32_t VibratorThread::PlayCompositeEffect(const VibrateInfo &info, const HdfCo } #endif // HDF_DRIVERS_INTERFACE_VIBRATOR -void VibratorThread::UpdateVibratorEffect(const VibrateInfo &info) +void VibratorThread::UpdateVibratorEffect(const VibrateInfo &info, const VibratorIdentifierIPC& identifier, + std::vector &waveInfos) { std::unique_lock lck(currentVibrationMutex_); currentVibration_ = info; + currentVibrateParams_ = identifier; + waveInfos_ = waveInfos; } VibrateInfo VibratorThread::GetCurrentVibrateInfo() @@ -236,6 +273,18 @@ VibrateInfo VibratorThread::GetCurrentVibrateInfo() return currentVibration_; } +VibratorIdentifierIPC VibratorThread::GetCurrentVibrateParams() +{ + std::unique_lock lck(currentVibrateParamsMutex_); + return currentVibrateParams_; +} + +std::vector VibratorThread::GetCurrentWaveInfo() +{ + std::unique_lock lck(currentVibrateParamsMutex_); + return waveInfos_; +} + void VibratorThread::SetExitStatus(bool status) { exitFlag_.store(status); @@ -246,5 +295,20 @@ void VibratorThread::WakeUp() MISC_HILOGD("Notify the vibratorThread"); cv_.notify_one(); } + +void VibratorThread::ResetVibrateInfo() +{ + std::unique_lock lck(currentVibrationMutex_); + currentVibration_.mode = ""; + currentVibration_.packageName = ""; + currentVibration_.pid = -1; + currentVibration_.uid = -1; + currentVibration_.usage = 0; + currentVibration_.systemUsage = false; + currentVibration_.duration = 0; + currentVibration_.effect = ""; + currentVibration_.count = 0; + currentVibration_.intensity = 0; +} } // namespace Sensors } // namespace OHOS diff --git a/test/fuzztest/service/getdelaytimestub_fuzzer/getdelaytimestub_fuzzer.cpp b/test/fuzztest/service/getdelaytimestub_fuzzer/getdelaytimestub_fuzzer.cpp index 34faf6d972cdde9febcc2a7bd84245e84eee5447..4dbff5c47112c5a965e7fd734850234330a0f076 100644 --- a/test/fuzztest/service/getdelaytimestub_fuzzer/getdelaytimestub_fuzzer.cpp +++ b/test/fuzztest/service/getdelaytimestub_fuzzer/getdelaytimestub_fuzzer.cpp @@ -31,7 +31,7 @@ namespace Sensors { using namespace Security::AccessToken; using Security::AccessToken::AccessTokenID; namespace { -constexpr size_t U32_AT_SIZE = 4; +constexpr size_t U32_AT_SIZE = 12; auto g_service = MiscdeviceDelayedSpSingleton::GetInstance(); const std::u16string VIBRATOR_INTERFACE_TOKEN = u"IMiscdeviceService"; } // namespace @@ -79,8 +79,11 @@ bool OnRemoteRequestFuzzTest(const uint8_t *data, size_t size) g_service->OnStartFuzz(); size_t startPos = 0; int32_t delayTime; + VibratorIdentifier identifier; + startPos += GetObject(data + startPos, size - startPos, identifier.deviceId); + startPos += GetObject(data + startPos, size - startPos, identifier.vibratorId); GetObject(data + startPos, size - startPos, delayTime); - g_service->GetDelayTime(delayTime); + g_service->GetDelayTime(identifier, delayTime); return true; } } // namespace Sensors diff --git a/test/fuzztest/service/getvibratorcapacitystub_fuzzer/getvibratorcapacitystub_fuzzer.cpp b/test/fuzztest/service/getvibratorcapacitystub_fuzzer/getvibratorcapacitystub_fuzzer.cpp index 4f64fac6593ed188b68d8b9f2819d6f22f922355..2e929a6b9859405147fe53e45622e9d31f9da6a7 100644 --- a/test/fuzztest/service/getvibratorcapacitystub_fuzzer/getvibratorcapacitystub_fuzzer.cpp +++ b/test/fuzztest/service/getvibratorcapacitystub_fuzzer/getvibratorcapacitystub_fuzzer.cpp @@ -31,7 +31,7 @@ namespace Sensors { using namespace Security::AccessToken; using Security::AccessToken::AccessTokenID; namespace { -constexpr size_t U32_AT_SIZE = 4; +constexpr size_t U32_AT_SIZE = 12; auto g_service = MiscdeviceDelayedSpSingleton::GetInstance(); const std::u16string VIBRATOR_INTERFACE_TOKEN = u"IMiscdeviceService"; } // namespace @@ -79,8 +79,11 @@ bool OnRemoteRequestFuzzTest(const uint8_t *data, size_t size) g_service->OnStartFuzz(); size_t startPos = 0; VibratorCapacity capacity; + VibratorIdentifier identifier; + startPos += GetObject(data + startPos, size - startPos, identifier.deviceId); + startPos += GetObject(data + startPos, size - startPos, identifier.vibratorId); GetObject(data + startPos, size - startPos, capacity.isSupportHdHaptic); - g_service->GetVibratorCapacity(capacity); + g_service->GetVibratorCapacity(identifier, capacity); return true; } } // namespace Sensors diff --git a/test/fuzztest/service/issupporteffectstub_fuzzer/issupporteffectstub_fuzzer.cpp b/test/fuzztest/service/issupporteffectstub_fuzzer/issupporteffectstub_fuzzer.cpp index 85550c40c8df2ec399e01f2d70bc5d7bed80a92c..f85d453af1ec4a96a16c11005839ac2dd1180522 100644 --- a/test/fuzztest/service/issupporteffectstub_fuzzer/issupporteffectstub_fuzzer.cpp +++ b/test/fuzztest/service/issupporteffectstub_fuzzer/issupporteffectstub_fuzzer.cpp @@ -31,7 +31,7 @@ namespace Sensors { using namespace Security::AccessToken; using Security::AccessToken::AccessTokenID; namespace { -constexpr size_t U32_AT_SIZE = 4; +constexpr size_t U32_AT_SIZE = 12; auto g_service = MiscdeviceDelayedSpSingleton::GetInstance(); const std::u16string VIBRATOR_INTERFACE_TOKEN = u"IMiscdeviceService"; } // namespace @@ -80,8 +80,11 @@ bool OnRemoteRequestFuzzTest(const uint8_t *data, size_t size) size_t startPos = 0; std::string effect = ""; bool state = false; + VibratorIdentifier identifier; + startPos += GetObject(data + startPos, size - startPos, identifier.deviceId); + startPos += GetObject(data + startPos, size - startPos, identifier.vibratorId); GetObject(data + startPos, size - startPos, state); - g_service->IsSupportEffect(effect, state); + g_service->IsSupportEffect(identifier, effect, state); return true; } } // namespace Sensors diff --git a/test/fuzztest/vibrator/BUILD.gn b/test/fuzztest/vibrator/BUILD.gn index e6d9a794e430565a8c86797e9b648225b393b888..cd10c8dda0f866667148245906d7120a992823ae 100644 --- a/test/fuzztest/vibrator/BUILD.gn +++ b/test/fuzztest/vibrator/BUILD.gn @@ -33,5 +33,20 @@ group("fuzztest") { "startvibrator_fuzzer:fuzztest", "startvibratoronce_fuzzer:fuzztest", "stopvibrator_fuzzer:fuzztest", + "getvibratoridlist_fuzzer:fuzztest", + "geteffectinfo_fuzzer:fuzztest", + "subscribevibrator_fuzzer:fuzztest", + "unsubscribevibrator_fuzzer:fuzztest", + "stopvibratorenhanced_fuzzer:fuzztest", + "startvibratoronceenhanced_fuzzer:fuzztest", + "startvibratorenhanced_fuzzer:fuzztest", + "setusageenhanced_fuzzer:fuzztest", + "setparametersenhanced_fuzzer:fuzztest", + "setloopcountenhanced_fuzzer:fuzztest", + "playvibratorcustomenhanced_fuzzer:fuzztest", + "playprimitiveeffectenhanced_fuzzer:fuzztest", + "playpatternenhanced_fuzzer:fuzztest", + "getdelaytimeenhanced_fuzzer:fuzztest", + "cancelenhanced_fuzzer:fuzztest", ] } diff --git a/test/fuzztest/vibrator/cancelenhanced_fuzzer/BUILD.gn b/test/fuzztest/vibrator/cancelenhanced_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..d2319cd410b97febbdfc2970665b05687f4d3dfb --- /dev/null +++ b/test/fuzztest/vibrator/cancelenhanced_fuzzer/BUILD.gn @@ -0,0 +1,51 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("./../../../../miscdevice.gni") + +ohos_fuzztest("CancelEnhancedFuzzTest") { + module_out_path = FUZZ_MODULE_OUT_PATH + + fuzz_config_file = "$SUBSYSTEM_DIR/test/fuzztest/vibrator/cancelenhanced_fuzzer" + + include_dirs = [ + "$SUBSYSTEM_DIR/frameworks/native/vibrator", + "$SUBSYSTEM_DIR/test/fuzztest/vibrator/cancelenhanced_fuzzer", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "cancelenhanced_fuzzer.cpp" ] + + deps = + [ "$SUBSYSTEM_DIR/frameworks/native/vibrator:vibrator_interface_native" ] + + external_deps = [ "c_utils:utils" ] +} + +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":CancelEnhancedFuzzTest", + ] +} diff --git a/test/fuzztest/vibrator/cancelenhanced_fuzzer/cancelenhanced_fuzzer.cpp b/test/fuzztest/vibrator/cancelenhanced_fuzzer/cancelenhanced_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..803ccb29808d378fedc35bc136f14621b138a98b --- /dev/null +++ b/test/fuzztest/vibrator/cancelenhanced_fuzzer/cancelenhanced_fuzzer.cpp @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "cancelenhanced_fuzzer.h" + +#include +#include +#include +#include + +#include "securec.h" +#include "vibrator_agent.h" + +namespace OHOS { +namespace { +constexpr size_t U32_AT_SIZE = 8; +} // namespace + +template +size_t GetObject(const uint8_t *data, size_t size, T &object) +{ + size_t objectSize = sizeof(object); + if (objectSize > size) { + return 0; + } + errno_t ret = memcpy_s(&object, objectSize, data, objectSize); + if (ret != EOK) { + return 0; + } + return objectSize; +} + +bool CancelEnhancedFuzzTest(const uint8_t *data, size_t size) +{ + if (data == nullptr || size < U32_AT_SIZE) { + return false; + } + VibratorIdentifier identifier; + size_t startPos = 0; + startPos += GetObject(data + startPos, size - startPos, identifier.deviceId); + GetObject(data + startPos, size - startPos, identifier.vibratorId); + + int32_t ret = OHOS::Sensors::CancelEnhanced(identifier); + if (ret != 0) { + return false; + } + return true; +} +} // namespace OHOS + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + OHOS::CancelEnhancedFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/vibrator/cancelenhanced_fuzzer/cancelenhanced_fuzzer.h b/test/fuzztest/vibrator/cancelenhanced_fuzzer/cancelenhanced_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..5b826f8c5d67b4e6c774387731f93f5751f11347 --- /dev/null +++ b/test/fuzztest/vibrator/cancelenhanced_fuzzer/cancelenhanced_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SENSOR_DISABLE_FUZZER_H +#define SENSOR_DISABLE_FUZZER_H + +#define FUZZ_PROJECT_NAME "cancelenhanced_fuzzer" + +#endif // SENSOR_DISABLE_FUZZER_H + diff --git a/test/fuzztest/vibrator/cancelenhanced_fuzzer/corpus/init b/test/fuzztest/vibrator/cancelenhanced_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..e010f5889b59a772ce45fc45b17e8a578984479c --- /dev/null +++ b/test/fuzztest/vibrator/cancelenhanced_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/vibrator/cancelenhanced_fuzzer/project.xml b/test/fuzztest/vibrator/cancelenhanced_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..2eb360c27f1b159e1b043e38846f10fcf37fa37c --- /dev/null +++ b/test/fuzztest/vibrator/cancelenhanced_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 120 + + 2048 + + diff --git a/test/fuzztest/vibrator/getdelaytimeenhanced_fuzzer/BUILD.gn b/test/fuzztest/vibrator/getdelaytimeenhanced_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..6fbc3eb5349ae49784430eb781ecd17d320e1b4f --- /dev/null +++ b/test/fuzztest/vibrator/getdelaytimeenhanced_fuzzer/BUILD.gn @@ -0,0 +1,56 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("./../../../../miscdevice.gni") + +ohos_fuzztest("GetDelayTimeEnhancedFuzzTest") { + module_out_path = FUZZ_MODULE_OUT_PATH + + fuzz_config_file = "$SUBSYSTEM_DIR/test/fuzztest/vibrator/getdelaytimeenhanced_fuzzer" + + include_dirs = [ + "$SUBSYSTEM_DIR/frameworks/native/vibrator", + "$SUBSYSTEM_DIR/test/fuzztest/vibrator/getdelaytimeenhanced_fuzzer", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "getdelaytimeenhanced_fuzzer.cpp" ] + + deps = + [ "$SUBSYSTEM_DIR/frameworks/native/vibrator:vibrator_interface_native" ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken_shared", + "access_token:libtokensetproc_shared", + "c_utils:utils", + ] +} + +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":GetDelayTimeEnhancedFuzzTest", + ] +} diff --git a/test/fuzztest/vibrator/getdelaytimeenhanced_fuzzer/corpus/init b/test/fuzztest/vibrator/getdelaytimeenhanced_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..e010f5889b59a772ce45fc45b17e8a578984479c --- /dev/null +++ b/test/fuzztest/vibrator/getdelaytimeenhanced_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/vibrator/getdelaytimeenhanced_fuzzer/getdelaytimeenhanced_fuzzer.cpp b/test/fuzztest/vibrator/getdelaytimeenhanced_fuzzer/getdelaytimeenhanced_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..185e6156cf0ad970ef5df1c105eb6e615845a4bd --- /dev/null +++ b/test/fuzztest/vibrator/getdelaytimeenhanced_fuzzer/getdelaytimeenhanced_fuzzer.cpp @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "getdelaytimeenhanced_fuzzer.h" + +#include +#include +#include +#include + +#include "accesstoken_kit.h" +#include "nativetoken_kit.h" +#include "securec.h" +#include "token_setproc.h" + +#include "vibrator_agent.h" + +namespace OHOS { +using namespace Security::AccessToken; +using Security::AccessToken::AccessTokenID; + +namespace { +constexpr size_t U32_AT_SIZE = 12; +} // namespace + +template +size_t GetObject(const uint8_t *data, size_t size, T &object) +{ + size_t objectSize = sizeof(object); + if (objectSize > size) { + return 0; + } + errno_t ret = memcpy_s(&object, objectSize, data, objectSize); + if (ret != EOK) { + return 0; + } + return objectSize; +} + +void SetUpTestCase() +{ + const char **perms = new (std::nothrow) const char *[1]; + if (perms == nullptr) { + return; + } + perms[0] = "ohos.permission.VIBRATE"; + TokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = 1, + .aclsNum = 0, + .dcaps = nullptr, + .perms = perms, + .acls = nullptr, + .processName = "GetDelayTimeEnhancedFuzzTest", + .aplStr = "system_core", + }; + uint64_t tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + AccessTokenKit::ReloadNativeTokenInfo(); + delete[] perms; +} + +bool GetDelayTimeEnhancedFuzzTest(const uint8_t *data, size_t size) +{ + if (data == nullptr || size < U32_AT_SIZE) { + return false; + } + SetUpTestCase(); + + VibratorIdentifier identifier; + size_t startPos = 0; + int32_t delayTime = 0; + startPos += GetObject(data + startPos, size - startPos, identifier.deviceId); + startPos += GetObject(data + startPos, size - startPos, identifier.vibratorId); + GetObject(data + startPos, size - startPos, delayTime); + + int32_t ret = OHOS::Sensors::GetDelayTimeEnhanced(identifier, delayTime); + if (ret == 0) { + return false; + } + return true; +} +} // namespace OHOS + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + OHOS::GetDelayTimeEnhancedFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/vibrator/getdelaytimeenhanced_fuzzer/getdelaytimeenhanced_fuzzer.h b/test/fuzztest/vibrator/getdelaytimeenhanced_fuzzer/getdelaytimeenhanced_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..4b97f10a09cf8619883e621abf85ce2729f1801d --- /dev/null +++ b/test/fuzztest/vibrator/getdelaytimeenhanced_fuzzer/getdelaytimeenhanced_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef GET_DELAY_TIME_FUZZER_H +#define GET_DELAY_TIME_FUZZER_H + +#define FUZZ_PROJECT_NAME "getdelaytimeenhanced_fuzzer" + +#endif // GET_DELAY_TIME_FUZZER_H \ No newline at end of file diff --git a/test/fuzztest/vibrator/getdelaytimeenhanced_fuzzer/project.xml b/test/fuzztest/vibrator/getdelaytimeenhanced_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..f2c5980f8968ea08aacefeae01e087733819695a --- /dev/null +++ b/test/fuzztest/vibrator/getdelaytimeenhanced_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 120 + + 2048 + + diff --git a/test/fuzztest/vibrator/geteffectinfo_fuzzer/BUILD.gn b/test/fuzztest/vibrator/geteffectinfo_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..3d6084ddb42a3a12301028c8ba22bb4d247eff76 --- /dev/null +++ b/test/fuzztest/vibrator/geteffectinfo_fuzzer/BUILD.gn @@ -0,0 +1,49 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("./../../../../miscdevice.gni") + +ohos_fuzztest("GetEffectInfoFuzzTest") { + module_out_path = FUZZ_MODULE_OUT_PATH + + fuzz_config_file = "$SUBSYSTEM_DIR/test/fuzztest/vibrator/geteffectinfo_fuzzer" + + include_dirs = [ + "$SUBSYSTEM_DIR/frameworks/native/vibrator", + "$SUBSYSTEM_DIR/test/fuzztest/vibrator/geteffectinfo_fuzzer", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "geteffectinfo_fuzzer.cpp" ] + + deps = + [ "$SUBSYSTEM_DIR/frameworks/native/vibrator:vibrator_interface_native" ] +} + +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":GetEffectInfoFuzzTest", + ] +} diff --git a/test/fuzztest/vibrator/geteffectinfo_fuzzer/corpus/init b/test/fuzztest/vibrator/geteffectinfo_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..c49c21aa8683c4d54af710059267afe15db14f96 --- /dev/null +++ b/test/fuzztest/vibrator/geteffectinfo_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/vibrator/geteffectinfo_fuzzer/geteffectinfo_fuzzer.cpp b/test/fuzztest/vibrator/geteffectinfo_fuzzer/geteffectinfo_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..890b176503d01ed8b7fca356a7472128f05e8233 --- /dev/null +++ b/test/fuzztest/vibrator/geteffectinfo_fuzzer/geteffectinfo_fuzzer.cpp @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "geteffectinfo_fuzzer.h" + +#include +#include +#include +#include + +#include "vibrator_agent.h" + +namespace OHOS { +bool GetEffectInfoFuzzTest(const uint8_t *data, size_t size) +{ + VibratorIdentifier identifier; + + if (size < sizeof(int32_t) * 2) { + identifier.deviceId = -1; + identifier.vibratorId = -1; + } else { + std::memcpy(&identifier.deviceId, data, sizeof(int32_t)); + std::memcpy(&identifier.vibratorId, data + sizeof(int32_t), sizeof(int32_t)); + } + EffectInfo effectInfo; + std::string effectType = "haptic.clock.timer"; + int32_t ret = OHOS::Sensors::GetEffectInfo(identifier, effectType, effectInfo); + if (ret == 0) { + return false; + } + return true; +} +} // namespace OHOS + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + OHOS::GetEffectInfoFuzzTest(data, size); + return 0; +} + + diff --git a/test/fuzztest/vibrator/geteffectinfo_fuzzer/geteffectinfo_fuzzer.h b/test/fuzztest/vibrator/geteffectinfo_fuzzer/geteffectinfo_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..d05fca9ca93468a96df22ad8c1940261ae5ace65 --- /dev/null +++ b/test/fuzztest/vibrator/geteffectinfo_fuzzer/geteffectinfo_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef GETEFFECTINFO_FUZZER_H +#define GETEFFECTINFO_FUZZER_H + +#define FUZZ_PROJECT_NAME "geteffectinfo_fuzzer" + +#endif // GETEFFECTINFO_FUZZER_H + diff --git a/test/fuzztest/vibrator/geteffectinfo_fuzzer/project.xml b/test/fuzztest/vibrator/geteffectinfo_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..20dc766db73742058c8300227a37ba63703fc683 --- /dev/null +++ b/test/fuzztest/vibrator/geteffectinfo_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 120 + + 2048 + + diff --git a/test/fuzztest/vibrator/getvibratoridlist_fuzzer/BUILD.gn b/test/fuzztest/vibrator/getvibratoridlist_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..53ac34d49e40149efb37b40836993c66be10b655 --- /dev/null +++ b/test/fuzztest/vibrator/getvibratoridlist_fuzzer/BUILD.gn @@ -0,0 +1,49 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("./../../../../miscdevice.gni") + +ohos_fuzztest("GetVibratorIdListFuzzTest") { + module_out_path = FUZZ_MODULE_OUT_PATH + + fuzz_config_file = "$SUBSYSTEM_DIR/test/fuzztest/vibrator/getvibratoridlist_fuzzer" + + include_dirs = [ + "$SUBSYSTEM_DIR/frameworks/native/vibrator", + "$SUBSYSTEM_DIR/test/fuzztest/vibrator/getvibratoridlist_fuzzer", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "getvibratoridlist_fuzzer.cpp" ] + + deps = + [ "$SUBSYSTEM_DIR/frameworks/native/vibrator:vibrator_interface_native" ] +} + +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":GetVibratorIdListFuzzTest", + ] +} diff --git a/test/fuzztest/vibrator/getvibratoridlist_fuzzer/corpus/init b/test/fuzztest/vibrator/getvibratoridlist_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..c49c21aa8683c4d54af710059267afe15db14f96 --- /dev/null +++ b/test/fuzztest/vibrator/getvibratoridlist_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/vibrator/getvibratoridlist_fuzzer/getvibratoridlist_fuzzer.cpp b/test/fuzztest/vibrator/getvibratoridlist_fuzzer/getvibratoridlist_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6af9af3e64576fc55977bc533110b053cec895c2 --- /dev/null +++ b/test/fuzztest/vibrator/getvibratoridlist_fuzzer/getvibratoridlist_fuzzer.cpp @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "getvibratoridlist_fuzzer.h" + +#include +#include +#include +#include + +#include "vibrator_agent.h" + +namespace OHOS { +bool GetVibratorIdListFuzzTest(const uint8_t *data, size_t size) +{ + VibratorIdentifier identifier; + + if (size < sizeof(int32_t) * 2) { + identifier.deviceId = -1; + identifier.vibratorId = -1; + } else { + std::memcpy(&identifier.deviceId, data, sizeof(int32_t)); + std::memcpy(&identifier.vibratorId, data + sizeof(int32_t), sizeof(int32_t)); + } + std::vector vibratorInfo; + int32_t ret = OHOS::Sensors::GetVibratorIdList(identifier, vibratorInfo); + if (ret == 0) { + return false; + } + return true; +} +} // namespace OHOS + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + OHOS::GetVibratorIdListFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/vibrator/getvibratoridlist_fuzzer/getvibratoridlist_fuzzer.h b/test/fuzztest/vibrator/getvibratoridlist_fuzzer/getvibratoridlist_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..e08154473bb0ef67cf70e5c25f5f5b5a3de24e15 --- /dev/null +++ b/test/fuzztest/vibrator/getvibratoridlist_fuzzer/getvibratoridlist_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef GETVIBRATORIDLIST_FUZZER_H +#define GETVIBRATORIDLIST_FUZZER_H + +#define FUZZ_PROJECT_NAME "getvibratoridlist_fuzzer" + +#endif // GETVIBRATORIDLIST_FUZZER_H + diff --git a/test/fuzztest/vibrator/getvibratoridlist_fuzzer/project.xml b/test/fuzztest/vibrator/getvibratoridlist_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..20dc766db73742058c8300227a37ba63703fc683 --- /dev/null +++ b/test/fuzztest/vibrator/getvibratoridlist_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 120 + + 2048 + + diff --git a/test/fuzztest/vibrator/playpatternenhanced_fuzzer/BUILD.gn b/test/fuzztest/vibrator/playpatternenhanced_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..551f3d811199dc3395b665c0e9a12b0c56c9e8f0 --- /dev/null +++ b/test/fuzztest/vibrator/playpatternenhanced_fuzzer/BUILD.gn @@ -0,0 +1,56 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("./../../../../miscdevice.gni") + +ohos_fuzztest("PlayPatternEnhancedFuzzTest") { + module_out_path = FUZZ_MODULE_OUT_PATH + + fuzz_config_file = "$SUBSYSTEM_DIR/test/fuzztest/vibrator/playpatternenhanced_fuzzer" + + include_dirs = [ + "$SUBSYSTEM_DIR/frameworks/native/vibrator", + "$SUBSYSTEM_DIR/test/fuzztest/vibrator/playpatternenhanced_fuzzer", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "playpatternenhanced_fuzzer.cpp" ] + + deps = + [ "$SUBSYSTEM_DIR/frameworks/native/vibrator:vibrator_interface_native" ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken_shared", + "access_token:libtokensetproc_shared", + "c_utils:utils", + ] +} + +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":PlayPatternEnhancedFuzzTest", + ] +} diff --git a/test/fuzztest/vibrator/playpatternenhanced_fuzzer/corpus/init b/test/fuzztest/vibrator/playpatternenhanced_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..65af8ee8d11bf23407ea34d4de49f7cbb6a2b791 --- /dev/null +++ b/test/fuzztest/vibrator/playpatternenhanced_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/vibrator/playpatternenhanced_fuzzer/playpatternenhanced_fuzzer.cpp b/test/fuzztest/vibrator/playpatternenhanced_fuzzer/playpatternenhanced_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..811a5685c2b64b164db9268a1702d4f9dffb1e62 --- /dev/null +++ b/test/fuzztest/vibrator/playpatternenhanced_fuzzer/playpatternenhanced_fuzzer.cpp @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "playpatternenhanced_fuzzer.h" + +#include +#include +#include +#include + +#include "accesstoken_kit.h" +#include "nativetoken_kit.h" +#include "securec.h" +#include "token_setproc.h" + +#include "vibrator_agent.h" + +namespace OHOS { +using namespace Security::AccessToken; +using Security::AccessToken::AccessTokenID; +namespace { +constexpr size_t U32_AT_SIZE = 20; +} // namespace + +template +size_t GetObject(const uint8_t *data, size_t size, T &object) +{ + size_t objectSize = sizeof(object); + if (objectSize > size) { + return 0; + } + errno_t ret = memcpy_s(&object, objectSize, data, objectSize); + if (ret != EOK) { + return 0; + } + return objectSize; +} + +void SetUpTestCase() +{ + const char **perms = new (std::nothrow) const char *[1]; + if (perms == nullptr) { + return; + } + perms[0] = "ohos.permission.VIBRATE"; + TokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = 1, + .aclsNum = 0, + .dcaps = nullptr, + .perms = perms, + .acls = nullptr, + .processName = "PlayPatternEnhancedFuzzTest", + .aplStr = "system_core", + }; + uint64_t tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + AccessTokenKit::ReloadNativeTokenInfo(); + delete[] perms; +} + +bool PlayPatternEnhancedFuzzTest(const uint8_t *data, size_t size) +{ + if (data == nullptr || size < U32_AT_SIZE) { + return false; + } + VibratorIdentifier identifier; + VibratorPattern vibratorPattern { 0 }; + size_t startPos = 0; + startPos += GetObject(data + startPos, size - startPos, identifier.deviceId); + startPos += GetObject(data + startPos, size - startPos, identifier.vibratorId); + startPos += GetObject(data + startPos, size - startPos, vibratorPattern.time); + startPos += GetObject(data + startPos, size - startPos, vibratorPattern.eventNum); + GetObject(data + startPos, size - startPos, vibratorPattern.patternDuration); + int32_t ret = OHOS::Sensors::PlayPatternEnhanced(identifier, vibratorPattern); + return ret == 0; +} +} // namespace OHOS + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + OHOS::PlayPatternEnhancedFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/vibrator/playpatternenhanced_fuzzer/playpatternenhanced_fuzzer.h b/test/fuzztest/vibrator/playpatternenhanced_fuzzer/playpatternenhanced_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..1d71ce9b6f80593d6e095d802f122431c1d0c82d --- /dev/null +++ b/test/fuzztest/vibrator/playpatternenhanced_fuzzer/playpatternenhanced_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PLAY_PATTERN_FUZZER_H +#define PLAY_PATTERN_FUZZER_H + +#define FUZZ_PROJECT_NAME "playpatternenhanced_fuzzer" + +#endif // PLAY_PATTERN_FUZZER_H \ No newline at end of file diff --git a/test/fuzztest/vibrator/playpatternenhanced_fuzzer/project.xml b/test/fuzztest/vibrator/playpatternenhanced_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..2eb360c27f1b159e1b043e38846f10fcf37fa37c --- /dev/null +++ b/test/fuzztest/vibrator/playpatternenhanced_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 120 + + 2048 + + diff --git a/test/fuzztest/vibrator/playprimitiveeffectenhanced_fuzzer/BUILD.gn b/test/fuzztest/vibrator/playprimitiveeffectenhanced_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..6c42ae1841cc3797c42ec54014e79c3ccc9e2923 --- /dev/null +++ b/test/fuzztest/vibrator/playprimitiveeffectenhanced_fuzzer/BUILD.gn @@ -0,0 +1,57 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("./../../../../miscdevice.gni") + +ohos_fuzztest("PlayPrimitiveEffectEnhancedFuzzTest") { + module_out_path = FUZZ_MODULE_OUT_PATH + + fuzz_config_file = + "$SUBSYSTEM_DIR/test/fuzztest/vibrator/playprimitiveeffectenhanced_fuzzer" + + include_dirs = [ + "$SUBSYSTEM_DIR/interfaces/inner_api/vibrator", + "$SUBSYSTEM_DIR/test/fuzztest/vibrator/playprimitiveeffectenhanced_fuzzer", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "playprimitiveeffectenhanced_fuzzer.cpp" ] + + deps = + [ "$SUBSYSTEM_DIR/frameworks/native/vibrator:vibrator_interface_native" ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken_shared", + "access_token:libtokensetproc_shared", + "c_utils:utils", + ] +} + +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":PlayPrimitiveEffectEnhancedFuzzTest", + ] +} diff --git a/test/fuzztest/vibrator/playprimitiveeffectenhanced_fuzzer/corpus/init b/test/fuzztest/vibrator/playprimitiveeffectenhanced_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..e010f5889b59a772ce45fc45b17e8a578984479c --- /dev/null +++ b/test/fuzztest/vibrator/playprimitiveeffectenhanced_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/vibrator/playprimitiveeffectenhanced_fuzzer/playprimitiveeffectenhanced_fuzzer.cpp b/test/fuzztest/vibrator/playprimitiveeffectenhanced_fuzzer/playprimitiveeffectenhanced_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bcc88dd1d770a3782fd67c8fce3330869f88e574 --- /dev/null +++ b/test/fuzztest/vibrator/playprimitiveeffectenhanced_fuzzer/playprimitiveeffectenhanced_fuzzer.cpp @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "playprimitiveeffectenhanced_fuzzer.h" + +#include "accesstoken_kit.h" +#include "nativetoken_kit.h" +#include "securec.h" +#include "token_setproc.h" + +#include "vibrator_agent.h" + +namespace OHOS { +namespace Sensors { +using namespace Security::AccessToken; +using Security::AccessToken::AccessTokenID; + +namespace { +constexpr size_t DATA_MIN_SIZE = 28; +constexpr char END_CHAR = '\0'; +constexpr size_t LEN = 20; +} // namespace + +template +size_t GetObject(const uint8_t *data, size_t size, T &object) +{ + size_t objectSize = sizeof(object); + if (objectSize > size) { + return 0; + } + errno_t ret = memcpy_s(&object, objectSize, data, objectSize); + if (ret != EOK) { + return 0; + } + return objectSize; +} + +void SetUpTestCase() +{ + const char **perms = new (std::nothrow) const char *[1]; + if (perms == nullptr) { + return; + } + perms[0] = "ohos.permission.VIBRATE"; + TokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = 1, + .aclsNum = 0, + .dcaps = nullptr, + .perms = perms, + .acls = nullptr, + .processName = "PlayPrimitiveEffectEnhancedFuzzTest", + .aplStr = "system_core", + }; + uint64_t tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + AccessTokenKit::ReloadNativeTokenInfo(); + delete[] perms; +} + +void PlayPrimitiveEffectEnhancedFuzzTest(const uint8_t *data, size_t size) +{ + SetUpTestCase(); + if (data == nullptr || size < DATA_MIN_SIZE) { + return; + } + VibratorIdentifier identifier; + size_t startPos = 0; + char effectId[LEN + 1]; + effectId[LEN] = END_CHAR; + startPos += GetObject(data + startPos, size - startPos, identifier.deviceId); + startPos += GetObject(data + startPos, size - startPos, identifier.vibratorId); + for (size_t i = 0; i < LEN; ++i) { + startPos += GetObject(data + startPos, size - startPos, effectId[i]); + } + int32_t intensity { 0 }; + OHOS::Sensors::PlayPrimitiveEffectEnhanced(identifier, effectId, intensity); +} +} // namespace Sensors +} // namespace OHOS + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + OHOS::Sensors::PlayPrimitiveEffectEnhancedFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/vibrator/playprimitiveeffectenhanced_fuzzer/playprimitiveeffectenhanced_fuzzer.h b/test/fuzztest/vibrator/playprimitiveeffectenhanced_fuzzer/playprimitiveeffectenhanced_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..5b45c097ea45657b9ae8154a4a21e0187e8768bd --- /dev/null +++ b/test/fuzztest/vibrator/playprimitiveeffectenhanced_fuzzer/playprimitiveeffectenhanced_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PLAY_PRIMITIVE_EFFECT_FUZZER_H +#define PLAY_PRIMITIVE_EFFECT_FUZZER_H + +#define FUZZ_PROJECT_NAME "playprimitiveeffectenhanced_fuzzer" + +#endif // PLAY_PRIMITIVE_EFFECT_FUZZER_H + diff --git a/test/fuzztest/vibrator/playprimitiveeffectenhanced_fuzzer/project.xml b/test/fuzztest/vibrator/playprimitiveeffectenhanced_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..f2c5980f8968ea08aacefeae01e087733819695a --- /dev/null +++ b/test/fuzztest/vibrator/playprimitiveeffectenhanced_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 120 + + 2048 + + diff --git a/test/fuzztest/vibrator/playvibratorcustom_fuzzer/playvibratorcustom_fuzzer.h b/test/fuzztest/vibrator/playvibratorcustom_fuzzer/playvibratorcustom_fuzzer.h index b190853f30bee36700e79c4eed71e98d6c2ba11b..94f4639ee77999ed7a6dcc5ed6fbb9480fd74a95 100644 --- a/test/fuzztest/vibrator/playvibratorcustom_fuzzer/playvibratorcustom_fuzzer.h +++ b/test/fuzztest/vibrator/playvibratorcustom_fuzzer/playvibratorcustom_fuzzer.h @@ -16,7 +16,7 @@ #ifndef SENSOR_DISABLE_FUZZER_H #define SENSOR_DISABLE_FUZZER_H -#define FUZZ_PROJECT_NAME "issupporteffect_fuzzer" +#define FUZZ_PROJECT_NAME "playvibratorcustom_fuzzer" #endif // SENSOR_DISABLE_FUZZER_H diff --git a/test/fuzztest/vibrator/playvibratorcustomenhanced_fuzzer/BUILD.gn b/test/fuzztest/vibrator/playvibratorcustomenhanced_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..a3d009fd2772f2e5f36a1ea2e673bff94fc958b9 --- /dev/null +++ b/test/fuzztest/vibrator/playvibratorcustomenhanced_fuzzer/BUILD.gn @@ -0,0 +1,51 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("./../../../../miscdevice.gni") + +ohos_fuzztest("PlayVibratorCustomEnhancedFuzzTest") { + module_out_path = FUZZ_MODULE_OUT_PATH + + fuzz_config_file = "$SUBSYSTEM_DIR/test/fuzztest/vibrator/playvibratorcustomenhanced_fuzzer" + + include_dirs = [ + "$SUBSYSTEM_DIR/frameworks/inner_api/vibrator", + "$SUBSYSTEM_DIR/test/fuzztest/vibrator/playvibratorcustomenhanced_fuzzer", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "playvibratorcustomenhanced_fuzzer.cpp" ] + + deps = + [ "$SUBSYSTEM_DIR/frameworks/native/vibrator:vibrator_interface_native" ] + + external_deps = [ "c_utils:utils" ] +} + +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":PlayVibratorCustomEnhancedFuzzTest", + ] +} diff --git a/test/fuzztest/vibrator/playvibratorcustomenhanced_fuzzer/corpus/init b/test/fuzztest/vibrator/playvibratorcustomenhanced_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..e010f5889b59a772ce45fc45b17e8a578984479c --- /dev/null +++ b/test/fuzztest/vibrator/playvibratorcustomenhanced_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/vibrator/playvibratorcustomenhanced_fuzzer/playvibratorcustomenhanced_fuzzer.cpp b/test/fuzztest/vibrator/playvibratorcustomenhanced_fuzzer/playvibratorcustomenhanced_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..60aad9ec7e9216d90b84b723a116755707fcb2e1 --- /dev/null +++ b/test/fuzztest/vibrator/playvibratorcustomenhanced_fuzzer/playvibratorcustomenhanced_fuzzer.cpp @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "playvibratorcustomenhanced_fuzzer.h" + +#include "securec.h" + +#include "vibrator_agent.h" + +namespace OHOS { +namespace Sensors { +namespace { +constexpr size_t DATA_MIN_SIZE = 28; +} // namespace + +template +size_t GetObject(const uint8_t *data, size_t size, T &object) +{ + size_t objectSize = sizeof(object); + if (objectSize > size) { + return 0; + } + errno_t ret = memcpy_s(&object, objectSize, data, objectSize); + if (ret != EOK) { + return 0; + } + return objectSize; +} + +void PlayVibratorCustomEnhancedFuzzTest(const uint8_t *data, size_t size) +{ + if (data == nullptr || size < DATA_MIN_SIZE) { + return; + } + VibratorIdentifier identifier; + size_t startPos = 0; + startPos += GetObject(data + startPos, size - startPos, identifier.deviceId); + startPos += GetObject(data + startPos, size - startPos, identifier.vibratorId); + int32_t fd { 0 }; + startPos += GetObject(data + startPos, size - startPos, fd); + int64_t offset { 0 }; + startPos += GetObject(data + startPos, size - startPos, offset); + int64_t length { 0 }; + GetObject(data + startPos, size - startPos, length); + OHOS::Sensors::PlayVibratorCustomEnhanced(identifier, fd, offset, length); +} +} // namespace Sensors +} // namespace OHOS + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + OHOS::Sensors::PlayVibratorCustomEnhancedFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/vibrator/playvibratorcustomenhanced_fuzzer/playvibratorcustomenhanced_fuzzer.h b/test/fuzztest/vibrator/playvibratorcustomenhanced_fuzzer/playvibratorcustomenhanced_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..e95e6f3b2e4af3f1bb46bbd6ca026033c057fa8e --- /dev/null +++ b/test/fuzztest/vibrator/playvibratorcustomenhanced_fuzzer/playvibratorcustomenhanced_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SENSOR_DISABLE_FUZZER_H +#define SENSOR_DISABLE_FUZZER_H + +#define FUZZ_PROJECT_NAME "playvibratorcustomenhanced_fuzzer" + +#endif // SENSOR_DISABLE_FUZZER_H + diff --git a/test/fuzztest/vibrator/playvibratorcustomenhanced_fuzzer/project.xml b/test/fuzztest/vibrator/playvibratorcustomenhanced_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..2eb360c27f1b159e1b043e38846f10fcf37fa37c --- /dev/null +++ b/test/fuzztest/vibrator/playvibratorcustomenhanced_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 120 + + 2048 + + diff --git a/test/fuzztest/vibrator/setloopcountenhanced_fuzzer/BUILD.gn b/test/fuzztest/vibrator/setloopcountenhanced_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..9c99b001ba576996d8d44b7f8270b800c2f20465 --- /dev/null +++ b/test/fuzztest/vibrator/setloopcountenhanced_fuzzer/BUILD.gn @@ -0,0 +1,51 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("./../../../../miscdevice.gni") + +ohos_fuzztest("SetLoopCountEnhancedFuzzTest") { + module_out_path = FUZZ_MODULE_OUT_PATH + + fuzz_config_file = "$SUBSYSTEM_DIR/test/fuzztest/vibrator/setloopcountenhanced_fuzzer" + + include_dirs = [ + "$SUBSYSTEM_DIR/frameworks/native/vibrator", + "$SUBSYSTEM_DIR/test/fuzztest/vibrator/setloopcountenhanced_fuzzer", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "setloopcountenhanced_fuzzer.cpp" ] + + deps = + [ "$SUBSYSTEM_DIR/frameworks/native/vibrator:vibrator_interface_native" ] + + external_deps = [ "c_utils:utils" ] +} + +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":SetLoopCountEnhancedFuzzTest", + ] +} diff --git a/test/fuzztest/vibrator/setloopcountenhanced_fuzzer/corpus/init b/test/fuzztest/vibrator/setloopcountenhanced_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..65af8ee8d11bf23407ea34d4de49f7cbb6a2b791 --- /dev/null +++ b/test/fuzztest/vibrator/setloopcountenhanced_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/vibrator/setloopcountenhanced_fuzzer/project.xml b/test/fuzztest/vibrator/setloopcountenhanced_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..2eb360c27f1b159e1b043e38846f10fcf37fa37c --- /dev/null +++ b/test/fuzztest/vibrator/setloopcountenhanced_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 120 + + 2048 + + diff --git a/test/fuzztest/vibrator/setloopcountenhanced_fuzzer/setloopcountenhanced_fuzzer.cpp b/test/fuzztest/vibrator/setloopcountenhanced_fuzzer/setloopcountenhanced_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2b7af74d9bbae72dc51a5630c86ca1a46693b3f1 --- /dev/null +++ b/test/fuzztest/vibrator/setloopcountenhanced_fuzzer/setloopcountenhanced_fuzzer.cpp @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "setloopcountenhanced_fuzzer.h" + +#include +#include +#include +#include + +#include "securec.h" +#include "vibrator_agent.h" + +namespace OHOS { +namespace { +constexpr size_t DATA_MIN_SIZE = 12; +} // namespace + +template +size_t GetObject(const uint8_t *data, size_t size, T &object) +{ + size_t objectSize = sizeof(object); + if (objectSize > size) { + return 0; + } + errno_t ret = memcpy_s(&object, objectSize, data, objectSize); + if (ret != EOK) { + return 0; + } + return objectSize; +} + +bool SetLoopCountEnhancedFuzzTest(const uint8_t *data, size_t size) +{ + if (data == nullptr || size < DATA_MIN_SIZE) { + return false; + } + + VibratorIdentifier identifier; + size_t startPos = 0; + int32_t count = 0; + startPos += GetObject(data + startPos, size - startPos, identifier.deviceId); + startPos += GetObject(data + startPos, size - startPos, identifier.vibratorId); + GetObject(data + startPos, size - startPos, count); + + bool ret = OHOS::Sensors::SetLoopCountEnhanced(identifier, count); + if ((count <= 0 && ret == true) || ((count > 0 && ret == false))) { + return false; + } + return true; +} +} // namespace OHOS + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + OHOS::SetLoopCountEnhancedFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/vibrator/setloopcountenhanced_fuzzer/setloopcountenhanced_fuzzer.h b/test/fuzztest/vibrator/setloopcountenhanced_fuzzer/setloopcountenhanced_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..7d1de1a52d2ffcc2ef82105a90625cf4db6f8723 --- /dev/null +++ b/test/fuzztest/vibrator/setloopcountenhanced_fuzzer/setloopcountenhanced_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SENSOR_DISABLE_FUZZER_H +#define SENSOR_DISABLE_FUZZER_H + +#define FUZZ_PROJECT_NAME "setloopcountenhanced_fuzzer" + +#endif // SENSOR_DISABLE_FUZZER_H + diff --git a/test/fuzztest/vibrator/setparametersenhanced_fuzzer/BUILD.gn b/test/fuzztest/vibrator/setparametersenhanced_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..a95d6ee1160b561faeadfcb2ae5a1d521d94b5ea --- /dev/null +++ b/test/fuzztest/vibrator/setparametersenhanced_fuzzer/BUILD.gn @@ -0,0 +1,57 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("./../../../../miscdevice.gni") + +ohos_fuzztest("SetParametersEnhancedFuzzTest") { + module_out_path = FUZZ_MODULE_OUT_PATH + + fuzz_config_file = + "$SUBSYSTEM_DIR/test/fuzztest/vibrator/setparametersenhanced_fuzzer" + + include_dirs = [ + "$SUBSYSTEM_DIR/frameworks/native/vibrator", + "$SUBSYSTEM_DIR/test/fuzztest/vibrator/setparametersenhanced_fuzzer", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "setparametersenhanced_fuzzer.cpp" ] + + deps = + [ "$SUBSYSTEM_DIR/frameworks/native/vibrator:vibrator_interface_native" ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken_shared", + "access_token:libtokensetproc_shared", + "c_utils:utils", + ] +} + +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":SetParametersEnhancedFuzzTest", + ] +} diff --git a/test/fuzztest/vibrator/setparametersenhanced_fuzzer/corpus/init b/test/fuzztest/vibrator/setparametersenhanced_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..65af8ee8d11bf23407ea34d4de49f7cbb6a2b791 --- /dev/null +++ b/test/fuzztest/vibrator/setparametersenhanced_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/vibrator/setparametersenhanced_fuzzer/project.xml b/test/fuzztest/vibrator/setparametersenhanced_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..2eb360c27f1b159e1b043e38846f10fcf37fa37c --- /dev/null +++ b/test/fuzztest/vibrator/setparametersenhanced_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 120 + + 2048 + + diff --git a/test/fuzztest/vibrator/setparametersenhanced_fuzzer/setparametersenhanced_fuzzer.cpp b/test/fuzztest/vibrator/setparametersenhanced_fuzzer/setparametersenhanced_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..188276c6914247b66e5c2bf48a119c07eec5c2bf --- /dev/null +++ b/test/fuzztest/vibrator/setparametersenhanced_fuzzer/setparametersenhanced_fuzzer.cpp @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "setparametersenhanced_fuzzer.h" + +#include +#include +#include +#include + +#include "accesstoken_kit.h" +#include "nativetoken_kit.h" +#include "securec.h" +#include "token_setproc.h" + +#include "vibrator_agent.h" + +namespace OHOS { +using namespace Security::AccessToken; +using Security::AccessToken::AccessTokenID; +namespace { +constexpr size_t U32_AT_SIZE = 20; +} // namespace + +template +size_t GetObject(const uint8_t *data, size_t size, T &object) +{ + size_t objectSize = sizeof(object); + if (objectSize > size) { + return 0; + } + errno_t ret = memcpy_s(&object, objectSize, data, objectSize); + if (ret != EOK) { + return 0; + } + return objectSize; +} + +void SetUpTestCase() +{ + const char **perms = new (std::nothrow) const char *[1]; + if (perms == nullptr) { + return; + } + perms[0] = "ohos.permission.VIBRATE"; + TokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = 1, + .aclsNum = 0, + .dcaps = nullptr, + .perms = perms, + .acls = nullptr, + .processName = "FreeVibratorPackageTest", + .aplStr = "system_core", + }; + uint64_t tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + AccessTokenKit::ReloadNativeTokenInfo(); + delete[] perms; +} + +bool SetParametersEnhancedFuzzTest(const uint8_t *data, size_t size) +{ + if (data == nullptr || size < U32_AT_SIZE) { + return false; + } + SetUpTestCase(); + VibratorParameter parameter { 0 }; + VibratorIdentifier identifier; + size_t startPos = 0; + startPos += GetObject(data + startPos, size - startPos, identifier.deviceId); + startPos += GetObject(data + startPos, size - startPos, identifier.vibratorId); + startPos += GetObject(data + startPos, size - startPos, parameter.intensity); + startPos += GetObject(data + startPos, size - startPos, parameter.frequency); + GetObject(data + startPos, size - startPos, parameter.reserved); + return OHOS::Sensors::SetParametersEnhanced(identifier, parameter); +} +} // namespace OHOS + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + OHOS::SetParametersEnhancedFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/vibrator/setparametersenhanced_fuzzer/setparametersenhanced_fuzzer.h b/test/fuzztest/vibrator/setparametersenhanced_fuzzer/setparametersenhanced_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..d5ec47cf628a1716eb9f066ec3aaa4a8ec2a58f9 --- /dev/null +++ b/test/fuzztest/vibrator/setparametersenhanced_fuzzer/setparametersenhanced_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SET_PARAMETERS_FUZZER_H +#define SET_PARAMETERS_FUZZER_H + +#define FUZZ_PROJECT_NAME "setparametersenhanced_fuzzer" + +#endif // SET_PARAMETERS_FUZZER_H \ No newline at end of file diff --git a/test/fuzztest/vibrator/setusageenhanced_fuzzer/BUILD.gn b/test/fuzztest/vibrator/setusageenhanced_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..41433d71061f554096c8b6c9d9bac51b3d6f81ad --- /dev/null +++ b/test/fuzztest/vibrator/setusageenhanced_fuzzer/BUILD.gn @@ -0,0 +1,52 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("./../../../../miscdevice.gni") + +ohos_fuzztest("SetUsageEnhancedFuzzTest") { + module_out_path = FUZZ_MODULE_OUT_PATH + + fuzz_config_file = + "$SUBSYSTEM_DIR/test/fuzztest/vibrator/setusageenhanced_fuzzer" + + include_dirs = [ + "$SUBSYSTEM_DIR/frameworks/native/vibrator", + "$SUBSYSTEM_DIR/test/fuzztest/vibrator/setusageenhanced_fuzzer", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "setusageenhanced_fuzzer.cpp" ] + + deps = + [ "$SUBSYSTEM_DIR/frameworks/native/vibrator:vibrator_interface_native" ] + + external_deps = [ "c_utils:utils" ] +} + +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":SetUsageEnhancedFuzzTest", + ] +} diff --git a/test/fuzztest/vibrator/setusageenhanced_fuzzer/corpus/init b/test/fuzztest/vibrator/setusageenhanced_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..65af8ee8d11bf23407ea34d4de49f7cbb6a2b791 --- /dev/null +++ b/test/fuzztest/vibrator/setusageenhanced_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/vibrator/setusageenhanced_fuzzer/project.xml b/test/fuzztest/vibrator/setusageenhanced_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..2eb360c27f1b159e1b043e38846f10fcf37fa37c --- /dev/null +++ b/test/fuzztest/vibrator/setusageenhanced_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 120 + + 2048 + + diff --git a/test/fuzztest/vibrator/setusageenhanced_fuzzer/setusageenhanced_fuzzer.cpp b/test/fuzztest/vibrator/setusageenhanced_fuzzer/setusageenhanced_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f71acd9c9ac4f4b8511e85ca0c8cf43a66e8932e --- /dev/null +++ b/test/fuzztest/vibrator/setusageenhanced_fuzzer/setusageenhanced_fuzzer.cpp @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "setusageenhanced_fuzzer.h" + +#include +#include +#include +#include + +#include "securec.h" +#include "vibrator_agent.h" + +namespace OHOS { +namespace { +constexpr size_t DATA_MIN_SIZE = 12; +} // namespace + +template +size_t GetObject(const uint8_t *data, size_t size, T &object) +{ + size_t objectSize = sizeof(object); + if (objectSize > size) { + return 0; + } + errno_t ret = memcpy_s(&object, objectSize, data, objectSize); + if (ret != EOK) { + return 0; + } + return objectSize; +} + +bool SetUsageEnhancedFuzzTest(const uint8_t *data, size_t size) +{ + if (data == nullptr || size < DATA_MIN_SIZE) { + return; + } + VibratorIdentifier identifier; + size_t startPos = 0; + int32_t usage = 0; + startPos += GetObject(data + startPos, size - startPos, identifier.deviceId); + startPos += GetObject(data + startPos, size - startPos, identifier.vibratorId); + GetObject(data + startPos, size - startPos, usage); + + bool ret = OHOS::Sensors::SetUsageEnhanced(identifier, usage); + if ((((usage < 0) || (usage >= USAGE_MAX)) && ret == true) || + (((usage > 0) && (usage < USAGE_MAX)) && ret != false)) { + return false; + } + return true; +} +} // namespace OHOS + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + OHOS::SetUsageEnhancedFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/vibrator/setusageenhanced_fuzzer/setusageenhanced_fuzzer.h b/test/fuzztest/vibrator/setusageenhanced_fuzzer/setusageenhanced_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..6c501972d4ed57435024824c3f8c892101dce4ad --- /dev/null +++ b/test/fuzztest/vibrator/setusageenhanced_fuzzer/setusageenhanced_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SENSOR_DISABLE_FUZZER_H +#define SENSOR_DISABLE_FUZZER_H + +#define FUZZ_PROJECT_NAME "setusageenhanced_fuzzer" + +#endif // SENSOR_DISABLE_FUZZER_H + diff --git a/test/fuzztest/vibrator/startvibratorenhanced_fuzzer/BUILD.gn b/test/fuzztest/vibrator/startvibratorenhanced_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..1f86deac120fa4564fcc3a6b713b75afbd5177ee --- /dev/null +++ b/test/fuzztest/vibrator/startvibratorenhanced_fuzzer/BUILD.gn @@ -0,0 +1,51 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("./../../../../miscdevice.gni") + +ohos_fuzztest("StartVibratorEnhancedFuzzTest") { + module_out_path = FUZZ_MODULE_OUT_PATH + + fuzz_config_file = "$SUBSYSTEM_DIR/test/fuzztest/vibrator/startvibratorenhanced_fuzzer" + + include_dirs = [ + "$SUBSYSTEM_DIR/frameworks/native/vibrator", + "$SUBSYSTEM_DIR/test/fuzztest/vibrator/startvibratorenhanced_fuzzer", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "startvibratorenhanced_fuzzer.cpp" ] + + deps = + [ "$SUBSYSTEM_DIR/frameworks/native/vibrator:vibrator_interface_native" ] + + external_deps = [ "c_utils:utils" ] +} + +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":StartVibratorEnhancedFuzzTest", + ] +} diff --git a/test/fuzztest/vibrator/startvibratorenhanced_fuzzer/corpus/init b/test/fuzztest/vibrator/startvibratorenhanced_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..e010f5889b59a772ce45fc45b17e8a578984479c --- /dev/null +++ b/test/fuzztest/vibrator/startvibratorenhanced_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/vibrator/startvibratorenhanced_fuzzer/project.xml b/test/fuzztest/vibrator/startvibratorenhanced_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..2eb360c27f1b159e1b043e38846f10fcf37fa37c --- /dev/null +++ b/test/fuzztest/vibrator/startvibratorenhanced_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 120 + + 2048 + + diff --git a/test/fuzztest/vibrator/startvibratorenhanced_fuzzer/startvibratorenhanced_fuzzer.cpp b/test/fuzztest/vibrator/startvibratorenhanced_fuzzer/startvibratorenhanced_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a1b6c510ac79b3d00f87f0713a46f6d86e00118f --- /dev/null +++ b/test/fuzztest/vibrator/startvibratorenhanced_fuzzer/startvibratorenhanced_fuzzer.cpp @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "startvibratorenhanced_fuzzer.h" + +#include +#include +#include +#include + +#include "securec.h" +#include "vibrator_agent.h" + +namespace OHOS { +namespace { +constexpr size_t U32_AT_SIZE = 28; +constexpr char END_CHAR = '\0'; +constexpr size_t LEN = 20; +} // namespace + +template +size_t GetObject(const uint8_t *data, size_t size, T &object) +{ + size_t objectSize = sizeof(object); + if (objectSize > size) { + return 0; + } + errno_t ret = memcpy_s(&object, objectSize, data, objectSize); + if (ret != EOK) { + return 0; + } + return objectSize; +} + +bool StartVibratorEnhancedFuzzTest(const uint8_t *data, size_t size) +{ + if (data == nullptr || size < U32_AT_SIZE) { + return false; + } + VibratorIdentifier identifier; + size_t startPos = 0; + char effectId[LEN + 1]; + effectId[LEN] = END_CHAR; + startPos += GetObject(data + startPos, size - startPos, identifier.deviceId); + startPos += GetObject(data + startPos, size - startPos, identifier.vibratorId); + for (size_t i = 0; i < LEN; ++i) { + startPos += GetObject(data + startPos, size - startPos, effectId[i]); + } + + int32_t ret = OHOS::Sensors::StartVibratorEnhanced(identifier, effectId); + int32_t ret2 = std::strcmp(effectId, "haptic.clock.timer"); + if ((ret2 != 0 && ret == 0) || (ret2 == 0 && ret != 0)) { + return false; + } + return true; +} +} // namespace OHOS + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + OHOS::StartVibratorEnhancedFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/vibrator/startvibratorenhanced_fuzzer/startvibratorenhanced_fuzzer.h b/test/fuzztest/vibrator/startvibratorenhanced_fuzzer/startvibratorenhanced_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..e224624d253c0300a7e30083b9bd5d148978b196 --- /dev/null +++ b/test/fuzztest/vibrator/startvibratorenhanced_fuzzer/startvibratorenhanced_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SENSOR_DISABLE_FUZZER_H +#define SENSOR_DISABLE_FUZZER_H + +#define FUZZ_PROJECT_NAME "startvibratorenhanced_fuzzer" + +#endif // SENSOR_DISABLE_FUZZER_H + diff --git a/test/fuzztest/vibrator/startvibratoronceenhanced_fuzzer/BUILD.gn b/test/fuzztest/vibrator/startvibratoronceenhanced_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..1e13ead8784c5606ce97f276beba84d5c66b48f4 --- /dev/null +++ b/test/fuzztest/vibrator/startvibratoronceenhanced_fuzzer/BUILD.gn @@ -0,0 +1,51 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("./../../../../miscdevice.gni") + +ohos_fuzztest("StartVibratorOnceEnhancedFuzzTest") { + module_out_path = FUZZ_MODULE_OUT_PATH + + fuzz_config_file = "$SUBSYSTEM_DIR/test/fuzztest/vibrator/startvibratoronceenhanced_fuzzer" + + include_dirs = [ + "$SUBSYSTEM_DIR/frameworks/native/vibrator", + "$SUBSYSTEM_DIR/test/fuzztest/vibrator/startvibratoronceenhanced_fuzzer", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "startvibratoronceenhanced_fuzzer.cpp" ] + + deps = + [ "$SUBSYSTEM_DIR/frameworks/native/vibrator:vibrator_interface_native" ] + + external_deps = [ "c_utils:utils" ] +} + +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":StartVibratorOnceEnhancedFuzzTest", + ] +} diff --git a/test/fuzztest/vibrator/startvibratoronceenhanced_fuzzer/corpus/init b/test/fuzztest/vibrator/startvibratoronceenhanced_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..e010f5889b59a772ce45fc45b17e8a578984479c --- /dev/null +++ b/test/fuzztest/vibrator/startvibratoronceenhanced_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/vibrator/startvibratoronceenhanced_fuzzer/project.xml b/test/fuzztest/vibrator/startvibratoronceenhanced_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..2eb360c27f1b159e1b043e38846f10fcf37fa37c --- /dev/null +++ b/test/fuzztest/vibrator/startvibratoronceenhanced_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 120 + + 2048 + + diff --git a/test/fuzztest/vibrator/startvibratoronceenhanced_fuzzer/startvibratoronceenhanced_fuzzer.cpp b/test/fuzztest/vibrator/startvibratoronceenhanced_fuzzer/startvibratoronceenhanced_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bf4d3bf509125cfd16dc28a372d9559023a4155e --- /dev/null +++ b/test/fuzztest/vibrator/startvibratoronceenhanced_fuzzer/startvibratoronceenhanced_fuzzer.cpp @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "startvibratoronceenhanced_fuzzer.h" + +#include +#include +#include + +#include "securec.h" +#include "vibrator_agent.h" + +namespace { +constexpr int32_t MAX_VIBRATOR_TIME = 1800000; +constexpr int32_t MIN_VIBRATOR_TIME = 0; +constexpr size_t U32_AT_SIZE = 12; +} // namespace + +namespace OHOS { +template +size_t GetObject(const uint8_t *data, size_t size, T &object) +{ + size_t objectSize = sizeof(object); + if (objectSize > size) { + return 0; + } + errno_t ret = memcpy_s(&object, objectSize, data, objectSize); + if (ret != EOK) { + return 0; + } + return objectSize; +} + +bool StartVibratorOnceEnhancedFuzzTest(const uint8_t *data, size_t size) +{ + if (data == nullptr || size < U32_AT_SIZE) { + return false; + } + VibratorIdentifier identifier; + size_t startPos = 0; + int32_t duration = 0; + startPos += GetObject(data + startPos, size - startPos, identifier.deviceId); + startPos += GetObject(data + startPos, size - startPos, identifier.vibratorId); + GetObject(data + startPos, size - startPos, duration); + + int32_t ret = OHOS::Sensors::StartVibratorOnceEnhanced(identifier, duration); + if (((duration <= MIN_VIBRATOR_TIME || duration > MAX_VIBRATOR_TIME) && ret == 0) || + ((duration > MIN_VIBRATOR_TIME && duration <= MAX_VIBRATOR_TIME) && ret != 0)) { + return false; + } + return true; +} +} // namespace OHOS + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + OHOS::StartVibratorOnceEnhancedFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/vibrator/startvibratoronceenhanced_fuzzer/startvibratoronceenhanced_fuzzer.h b/test/fuzztest/vibrator/startvibratoronceenhanced_fuzzer/startvibratoronceenhanced_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..fb402ed4d4f46dc2e760c6885c79b3123b681eb5 --- /dev/null +++ b/test/fuzztest/vibrator/startvibratoronceenhanced_fuzzer/startvibratoronceenhanced_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SENSOR_DISABLE_FUZZER_H +#define SENSOR_DISABLE_FUZZER_H + +#define FUZZ_PROJECT_NAME "startvibratoronceenhanced_fuzzer" + +#endif // SENSOR_DISABLE_FUZZER_H + diff --git a/test/fuzztest/vibrator/stopvibratorenhanced_fuzzer/BUILD.gn b/test/fuzztest/vibrator/stopvibratorenhanced_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..8a8b2c8663ebc45ad593b5dd374771c9cd2df1a9 --- /dev/null +++ b/test/fuzztest/vibrator/stopvibratorenhanced_fuzzer/BUILD.gn @@ -0,0 +1,51 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("./../../../../miscdevice.gni") + +ohos_fuzztest("StopVibratorEnhancedFuzzTest") { + module_out_path = FUZZ_MODULE_OUT_PATH + + fuzz_config_file = "$SUBSYSTEM_DIR/test/fuzztest/vibrator/stopvibratorenhanced_fuzzer" + + include_dirs = [ + "$SUBSYSTEM_DIR/frameworks/native/vibrator", + "$SUBSYSTEM_DIR/test/fuzztest/vibrator/stopvibratorenhanced_fuzzer", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "stopvibratorenhanced_fuzzer.cpp" ] + + deps = + [ "$SUBSYSTEM_DIR/frameworks/native/vibrator:vibrator_interface_native" ] + + external_deps = [ "c_utils:utils" ] +} + +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":StopVibratorEnhancedFuzzTest", + ] +} diff --git a/test/fuzztest/vibrator/stopvibratorenhanced_fuzzer/corpus/init b/test/fuzztest/vibrator/stopvibratorenhanced_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..e010f5889b59a772ce45fc45b17e8a578984479c --- /dev/null +++ b/test/fuzztest/vibrator/stopvibratorenhanced_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/vibrator/stopvibratorenhanced_fuzzer/project.xml b/test/fuzztest/vibrator/stopvibratorenhanced_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..2eb360c27f1b159e1b043e38846f10fcf37fa37c --- /dev/null +++ b/test/fuzztest/vibrator/stopvibratorenhanced_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 120 + + 2048 + + diff --git a/test/fuzztest/vibrator/stopvibratorenhanced_fuzzer/stopvibratorenhanced_fuzzer.cpp b/test/fuzztest/vibrator/stopvibratorenhanced_fuzzer/stopvibratorenhanced_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..899bfd9bf0491f8dc859bcc614667c260a5da90d --- /dev/null +++ b/test/fuzztest/vibrator/stopvibratorenhanced_fuzzer/stopvibratorenhanced_fuzzer.cpp @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "stopvibratorenhanced_fuzzer.h" + +#include +#include +#include +#include + +#include "securec.h" +#include "vibrator_agent.h" + +namespace OHOS { +namespace { +constexpr size_t U32_AT_SIZE = 28; +constexpr size_t LEN = 20; +} // namespace + +template +size_t GetObject(const uint8_t *data, size_t size, T &object) +{ + size_t objectSize = sizeof(object); + if (objectSize > size) { + return 0; + } + errno_t ret = memcpy_s(&object, objectSize, data, objectSize); + if (ret != EOK) { + return 0; + } + return objectSize; +} + +bool StopVibratorEnhancedFuzzTest(const uint8_t *data, size_t size) +{ + if (data == nullptr || size < U32_AT_SIZE) { + return false; + } + VibratorIdentifier identifier; + size_t startPos = 0; + char mode[LEN + 1]; + startPos += GetObject(data + startPos, size - startPos, identifier.deviceId); + startPos += GetObject(data + startPos, size - startPos, identifier.vibratorId); + for (size_t i = 0; i < LEN; ++i) { + startPos += GetObject(data + startPos, size - startPos, mode[i]); + } + + int32_t ret = OHOS::Sensors::StopVibratorEnhanced(identifier, mode); + int32_t ret2 = strcmp(mode, "time") != 0 && strcmp(mode, "preset"); + if ((ret2 != 0 && ret == 0) || (ret2 == 0 && ret != 0)) { + return false; + } + return true; +} +} // namespace OHOS + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + OHOS::StopVibratorEnhancedFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/vibrator/stopvibratorenhanced_fuzzer/stopvibratorenhanced_fuzzer.h b/test/fuzztest/vibrator/stopvibratorenhanced_fuzzer/stopvibratorenhanced_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..b15118302b77f3e953e0d0fc5d53e045baa42d21 --- /dev/null +++ b/test/fuzztest/vibrator/stopvibratorenhanced_fuzzer/stopvibratorenhanced_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SENSOR_DISABLE_FUZZER_H +#define SENSOR_DISABLE_FUZZER_H + +#define FUZZ_PROJECT_NAME "stopvibratorenhanced_fuzzer" + +#endif // SENSOR_DISABLE_FUZZER_H + diff --git a/test/fuzztest/vibrator/subscribevibrator_fuzzer/BUILD.gn b/test/fuzztest/vibrator/subscribevibrator_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..938d643fe6a84c1bd1ac171d29547c3a8236f6a3 --- /dev/null +++ b/test/fuzztest/vibrator/subscribevibrator_fuzzer/BUILD.gn @@ -0,0 +1,49 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("./../../../../miscdevice.gni") + +ohos_fuzztest("UnSubscribeVibratorFuzzTest") { + module_out_path = FUZZ_MODULE_OUT_PATH + + fuzz_config_file = "$SUBSYSTEM_DIR/test/fuzztest/vibrator/unsubscribevibrator_fuzzer" + + include_dirs = [ + "$SUBSYSTEM_DIR/frameworks/native/vibrator", + "$SUBSYSTEM_DIR/test/fuzztest/vibrator/unsubscribevibrator_fuzzer", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "unsubscribevibrator_fuzzer.cpp" ] + + deps = + [ "$SUBSYSTEM_DIR/frameworks/native/vibrator:vibrator_interface_native" ] +} + +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":UnSubscribeVibratorFuzzTest", + ] +} diff --git a/test/fuzztest/vibrator/subscribevibrator_fuzzer/corpus/init b/test/fuzztest/vibrator/subscribevibrator_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..c49c21aa8683c4d54af710059267afe15db14f96 --- /dev/null +++ b/test/fuzztest/vibrator/subscribevibrator_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/vibrator/subscribevibrator_fuzzer/project.xml b/test/fuzztest/vibrator/subscribevibrator_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..20dc766db73742058c8300227a37ba63703fc683 --- /dev/null +++ b/test/fuzztest/vibrator/subscribevibrator_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 120 + + 2048 + + diff --git a/test/fuzztest/vibrator/subscribevibrator_fuzzer/unsubscribevibrator_fuzzer.cpp b/test/fuzztest/vibrator/subscribevibrator_fuzzer/unsubscribevibrator_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1c1cad4d706fc67e0a99286fceffbc688351bde7 --- /dev/null +++ b/test/fuzztest/vibrator/subscribevibrator_fuzzer/unsubscribevibrator_fuzzer.cpp @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "unsubscribevibrator_fuzzer.h" + +#include +#include +#include +#include + +#include "vibrator_agent.h" + +namespace OHOS { +void CallbackTest(VibratorDeviceInfo *deviceInfo){ + return; +} + +bool UnSubscribeVibratorFuzzTest(const uint8_t *data, size_t size) +{ + VibratorUser user = { + .callback = CallbackTest, + .userData = nullptr, + }; + int32_t ret = OHOS::Sensors::UnSubscribeVibrator(user); + if (ret == 0) { + return false; + } + return true; +} +} // namespace OHOS + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + OHOS::UnSubscribeVibratorFuzzTest(data, size); + return 0; +} + + diff --git a/test/fuzztest/vibrator/subscribevibrator_fuzzer/unsubscribevibrator_fuzzer.h b/test/fuzztest/vibrator/subscribevibrator_fuzzer/unsubscribevibrator_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..ec087a6b01421ae74525605436c36260bbf9e2c1 --- /dev/null +++ b/test/fuzztest/vibrator/subscribevibrator_fuzzer/unsubscribevibrator_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef UNSUBSCRIBEVIBRATOR_FUZZER_H +#define UNSUBSCRIBEVIBRATOR_FUZZER_H + +#define FUZZ_PROJECT_NAME "unsubscribevibrator_fuzzer" + +#endif // GETEFFECTINFO_FUZZER_H + diff --git a/test/fuzztest/vibrator/unsubscribevibrator_fuzzer/BUILD.gn b/test/fuzztest/vibrator/unsubscribevibrator_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..374374bce7de6a0bab67298fe5f1156f4d7e4725 --- /dev/null +++ b/test/fuzztest/vibrator/unsubscribevibrator_fuzzer/BUILD.gn @@ -0,0 +1,49 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("./../../../../miscdevice.gni") + +ohos_fuzztest("SubscribeVibratorFuzzTest") { + module_out_path = FUZZ_MODULE_OUT_PATH + + fuzz_config_file = "$SUBSYSTEM_DIR/test/fuzztest/vibrator/subscribevibrator_fuzzer" + + include_dirs = [ + "$SUBSYSTEM_DIR/frameworks/native/vibrator", + "$SUBSYSTEM_DIR/test/fuzztest/vibrator/subscribevibrator_fuzzer", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "subscribevibrator_fuzzer.cpp" ] + + deps = + [ "$SUBSYSTEM_DIR/frameworks/native/vibrator:vibrator_interface_native" ] +} + +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":SubscribeVibratorFuzzTest", + ] +} diff --git a/test/fuzztest/vibrator/unsubscribevibrator_fuzzer/corpus/init b/test/fuzztest/vibrator/unsubscribevibrator_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..c49c21aa8683c4d54af710059267afe15db14f96 --- /dev/null +++ b/test/fuzztest/vibrator/unsubscribevibrator_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/vibrator/unsubscribevibrator_fuzzer/project.xml b/test/fuzztest/vibrator/unsubscribevibrator_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..20dc766db73742058c8300227a37ba63703fc683 --- /dev/null +++ b/test/fuzztest/vibrator/unsubscribevibrator_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 120 + + 2048 + + diff --git a/test/fuzztest/vibrator/unsubscribevibrator_fuzzer/subscribevibrator_fuzzer.cpp b/test/fuzztest/vibrator/unsubscribevibrator_fuzzer/subscribevibrator_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cec137adc8bb12adfd1715199724ead646c9ef37 --- /dev/null +++ b/test/fuzztest/vibrator/unsubscribevibrator_fuzzer/subscribevibrator_fuzzer.cpp @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "subscribevibrator_fuzzer.h" + +#include +#include +#include +#include + +#include "vibrator_agent.h" + +namespace OHOS { +void CallbackTest(VibratorDeviceInfo *deviceInfo){ + return; +} + +bool SubscribeVibratorFuzzTest(const uint8_t *data, size_t size) +{ + VibratorUser user = { + .callback = CallbackTest, + .userData = nullptr, + }; + int32_t ret = OHOS::Sensors::SubscribeVibrator(user); + if (ret == 0) { + return false; + } + return true; +} +} // namespace OHOS + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + OHOS::SubscribeVibratorFuzzTest(data, size); + return 0; +} + + diff --git a/test/fuzztest/vibrator/unsubscribevibrator_fuzzer/subscribevibrator_fuzzer.h b/test/fuzztest/vibrator/unsubscribevibrator_fuzzer/subscribevibrator_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..f30d5f6d4f01d5bc0cb6b150559f524123e4c451 --- /dev/null +++ b/test/fuzztest/vibrator/unsubscribevibrator_fuzzer/subscribevibrator_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SUBSCRIBEVIBRATOR_FUZZER_H +#define SUBSCRIBEVIBRATOR_FUZZER_H + +#define FUZZ_PROJECT_NAME "subscribevibrator_fuzzer" + +#endif // GETEFFECTINFO_FUZZER_H + diff --git a/test/unittest/vibrator/js/VibratorPatternJsunit.test.js b/test/unittest/vibrator/js/VibratorPatternJsunit.test.js index 16e247216bfb118093e2deb162b5df6a580ec306..156dd3d8fb0cc572329655f5d2ff83dd4a1d4442 100644 --- a/test/unittest/vibrator/js/VibratorPatternJsunit.test.js +++ b/test/unittest/vibrator/js/VibratorPatternJsunit.test.js @@ -1389,4 +1389,125 @@ describe("VibratorJsTest", function () { done(); } }) + + /* + * @tc.name: VibratorJsTest019 + * @tc.desc: Test for getting the vibrator list. + * @tc.number: SUB_SensorSystem_Vibrator_JsTest_0190 + */ + it("VibratorJsTest019", 0, async function (done) { + try { + const vibrators = await GetVibratorList(); + console.info('Vibrator List:', vibrators); + expect(vibrators).toBeDefined(); + expect(Array.isArray(vibrators)).toBe(true); + done(); + } catch (error) { + console.error('VibratorJsTest019 failed with error:', error); + expect(false).toBe(true); + done(); + } + }) + + /* + * @tc.name: VibratorJsTest020 + * @tc.desc: Test for getting the vibrator list synchronously. + * @tc.number: SUB_SensorSystem_Vibrator_JsTest_0200 + */ + it("VibratorJsTest020", 0, function (done) { + try { + const vibrators = GetVibratorListSync(); + expect(vibrators).toBeDefined(); + expect(Array.isArray(vibrators)).toBe(true); + expect(vibrators.length).toBeGreaterThan(0); + done(); + } catch (error) { + console.error('VibratorJsTest020 failed with error:', error); + expect(false).toBe(true); + done(); + } + }) + + /* + * @tc.name: VibratorJsTest021 + * @tc.desc: Test for checking support for effect types. + * @tc.number: SUB_SensorSystem_Vibrator_JsTest_0210 + */ + it("VibratorJsTest021", 0, async function (done) { + const effectType = "effect1"; + try { + const effectInfo = await isSupportEffectInfo(effectType, params); + expect(effectInfo).toBeUndefined(); + expect(typeof effectInfo).toBe('object'); + done(); + } catch (error) { + console.error('VibratorJsTest021 failed with error:', error); + expect(false).toBe(true); + done(); + } + }) + + /* + * @tc.name: VibratorJsTest022 + * @tc.desc: Test for checking support for effect types synchronously. + * @tc.number: SUB_SensorSystem_Vibrator_JsTest_0220 + */ + it("VibratorJsTest022", 0, function (done) { + const effectType = "effect1"; + try { + const effectInfo = isSupportEffectInfoSync(effectType); + expect(effectInfo).toBeDefined(); + expect(typeof effectInfo).toBe('object'); + done(); + } catch (error) { + console.error('VibratorJsTest022 failed with error:', error); + expect(false).toBe(true); + done(); + } + }) + + /* + * @tc.name: VibratorJsTest023 + * @tc.desc: Test the on function for VIBRATOR_DEVICE_STATE_CHANGE with valid and invalid parameters. + * @tc.number: SUB_SensorSystem_Vibrator_JsTest_0230 + */ + it("VibratorJsTest023", 0, function (done) { + try { + const validCallback = function (deviceInfo) { + console.info('Valid callback executed with deviceInfo:', deviceInfo); + expect(deviceInfo).toBeDefined(); + expect(typeof deviceInfo).toBe('object'); + }; + on(VibratorStateEventType.VIBRATOR_DEVICE_STATE_CHANGE, validCallback); + done(); + } catch (error) { + console.error('VibratorJsTest023 failed with error:', error); + expect(false).toBe(true); + done(); + } + }) + + /* + * @tc.name: VibratorJsTest023 + * @tc.desc: Test the off function for VIBRATOR_DEVICE_STATE_CHANGE events. + * @tc.number: SUB_SensorSystem_Vibrator_JsTest_0230 + */ + it("VibratorJsTest012", 0, function (done) { + const eventType = VibratorStateEventType.VIBRATOR_DEVICE_STATE_CHANG + const callback = jest.fn((info) => { + vibratorInfo = info; + }); + try { + on(eventType, callback); + off(eventType, callback); + expect(() => { + off(eventType, null); + }).not.toThrow(); + done(); + } catch (error) { + console.error('VibratorJsTest012 failed with error:', error); + expect(false).toBe(true); + done(); + } + }) }) \ No newline at end of file diff --git a/test/unittest/vibrator/native/vibrator_agent_test.cpp b/test/unittest/vibrator/native/vibrator_agent_test.cpp index 9c735de6a541c70169e24a20bd79464a55a41bdc..a4766d0b3701b103acddd751f3b5ee8207f28a61 100644 --- a/test/unittest/vibrator/native/vibrator_agent_test.cpp +++ b/test/unittest/vibrator/native/vibrator_agent_test.cpp @@ -66,6 +66,14 @@ HapInfoParams g_infoManagerTestInfoParms = { .instIndex = 0, .appIDDesc = "vibratorAgentTest" }; + +void TestCallBack(VibratorDeviceInfo *deviceInfo) { + return; +} + +constexpr VibratorUser testUser = { + .callback = TestCallBack, +}; } // namespace class VibratorAgentTest : public testing::Test { @@ -1423,5 +1431,1386 @@ HWTEST_F(VibratorAgentTest, VibratePatternTest, TestSize.Level1) ASSERT_EQ(ret->patternDuration, 1000); ret = nullptr; } + +bool IsSupportVibratorEffectEnhanced(const VibratorIdentifier identifier, const char* effectId) +{ + bool state { false }; + IsSupportEffectEnhanced(identifier, effectId, &state); + return state; +} + +HWTEST_F(VibratorAgentTest, StartVibratorEnhancedTest_001, TestSize.Level1) +{ + MISC_HILOGI("StartVibratorEnhancedTest_001 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool isSupport = IsSupportVibratorEffectEnhanced(identifier, VIBRATOR_TYPE_CLOCK_TIMER); + if (isSupport) { + int32_t ret = StartVibratorEnhanced(identifier, VIBRATOR_TYPE_CLOCK_TIMER); + ASSERT_EQ(ret, 0); + } else { + ASSERT_EQ(isSupport, false); + } +} + +HWTEST_F(VibratorAgentTest, StartVibratorEnhancedTest_002, TestSize.Level1) +{ + MISC_HILOGI("StartVibratorEnhancedTest_002 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + int32_t ret = StartVibratorEnhanced(identifier, ""); + ASSERT_NE(ret, 0); +} + +HWTEST_F(VibratorAgentTest, StartVibratorEnhancedTest_003, TestSize.Level1) +{ + MISC_HILOGI("StartVibratorTest_003 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + int32_t ret = StartVibratorEnhanced(identifier, nullptr); + ASSERT_NE(ret, 0); +} + +HWTEST_F(VibratorAgentTest, StartVibratorOnceEnhancedTest_001, TestSize.Level0) +{ + MISC_HILOGI("StartVibratorOnceEnhancedTest_001 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + int32_t ret = StartVibratorOnceEnhanced(identifier, 300); + ASSERT_EQ(ret, 0); +} + +HWTEST_F(VibratorAgentTest, StartVibratorOnceEnhancedTest_002, TestSize.Level1) +{ + MISC_HILOGI("StartVibratorOnceEnhancedTest_002 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + int32_t ret = StartVibratorOnceEnhanced(identifier, 0); + ASSERT_NE(ret, 0); +} + +HWTEST_F(VibratorAgentTest, StartVibratorOnceEnhancedTest_003, TestSize.Level1) +{ + MISC_HILOGI("StartVibratorOnceEnhancedTest_003 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + int32_t ret = StartVibratorOnceEnhanced(identifier, 1800000); + ASSERT_EQ(ret, 0); +} + +HWTEST_F(VibratorAgentTest, StartVibratorOnceEnhancedTest_004, TestSize.Level1) +{ + MISC_HILOGI("StartVibratorOnceEnhancedTest_004 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + int32_t ret = StartVibratorOnceEnhanced(identifier, 1800001); + ASSERT_NE(ret, 0); +} + +HWTEST_F(VibratorAgentTest, StopVibratorEnhancedTest_001, TestSize.Level1) +{ + MISC_HILOGI("StopVibratorEnhancedTest_001 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + int32_t ret = StopVibratorEnhanced(identifier, "time"); + ASSERT_EQ(ret, 0); +} + +HWTEST_F(VibratorAgentTest, StopVibratorEnhancedTest_002, TestSize.Level1) +{ + MISC_HILOGI("StopVibratorEnhancedTest_002 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + int32_t ret = StopVibratorEnhanced(identifier, "preset"); + ASSERT_NE(ret, 0); +} + +HWTEST_F(VibratorAgentTest, StopVibratorEnhancedTest_003, TestSize.Level1) +{ + MISC_HILOGI("StopVibratorEnhancedTest_003 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + int32_t ret = StopVibratorEnhanced(identifier, ""); + ASSERT_NE(ret, 0); +} + +HWTEST_F(VibratorAgentTest, StopVibratorEnhancedTest_004, TestSize.Level1) +{ + MISC_HILOGI("StopVibratorEnhancedTest_004 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + int32_t ret = StopVibratorEnhanced(identifier, nullptr); + ASSERT_NE(ret, 0); +} + +HWTEST_F(VibratorAgentTest, StopVibratorEnhancedTest_005, TestSize.Level1) +{ + MISC_HILOGI("StopVibratorEnhancedTest_005 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + int32_t ret = StartVibratorOnceEnhanced(identifier, 300); + ASSERT_EQ(ret, 0); + ret = StopVibratorEnhanced(identifier, "time"); + ASSERT_EQ(ret, 0); +} + +HWTEST_F(VibratorAgentTest, SetLoopCountEnhanced_001, TestSize.Level1) +{ + MISC_HILOGI("SetLoopCountEnhanced_001 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool ret = SetLoopCountEnhanced(identifier, 300); + ASSERT_TRUE(ret); +} + +HWTEST_F(VibratorAgentTest, SetLoopCountEnhanced_002, TestSize.Level1) +{ + MISC_HILOGI("SetLoopCount_002 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool ret = SetLoopCountEnhanced(identifier, -1); + ASSERT_FALSE(ret); +} + +HWTEST_F(VibratorAgentTest, SetLoopCountEnhanced_003, TestSize.Level1) +{ + MISC_HILOGI("SetLoopCountEnhanced_003 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool ret = SetLoopCountEnhanced(identifier, 0); + ASSERT_FALSE(ret); +} + +HWTEST_F(VibratorAgentTest, SetUsageEnhanced_001, TestSize.Level1) +{ + MISC_HILOGI("SetUsageEnhanced_001 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool ret = SetUsageEnhanced(identifier, 0); + ASSERT_TRUE(ret); +} + +HWTEST_F(VibratorAgentTest, SetUsageEnhanced_002, TestSize.Level1) +{ + MISC_HILOGI("SetUsageEnhanced_002 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool ret = SetUsageEnhanced(identifier, -1); + ASSERT_FALSE(ret); +} + +HWTEST_F(VibratorAgentTest, SetUsageEnhanced_003, TestSize.Level1) +{ + MISC_HILOGI("SetUsage_003 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool ret = SetUsageEnhanced(identifier, USAGE_MAX); + ASSERT_FALSE(ret); +} + +HWTEST_F(VibratorAgentTest, PlayVibratorCustomEnhanced_001, TestSize.Level0) +{ + MISC_HILOGI("PlayVibratorCustomEnhanced_001 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool isSupport = IsSupportVibratorCustomEnhanced(identifier); + if (isSupport) { + FileDescriptor fileDescriptor("/data/test/vibrator/coin_drop.json"); + MISC_HILOGD("Test fd:%{public}d", fileDescriptor.fd); + struct stat64 statbuf = { 0 }; + if (fstat64(fileDescriptor.fd, &statbuf) == 0) { + int32_t ret = PlayVibratorCustomEnhanced(identifier, fileDescriptor.fd, 0, statbuf.st_size); + ASSERT_EQ(ret, 0); + } + std::this_thread::sleep_for(std::chrono::milliseconds(TIME_WAIT_FOR_OP)); + } else { + ASSERT_EQ(isSupport, false); + } + CancelEnhanced(identifier); +} + +HWTEST_F(VibratorAgentTest, PlayVibratorCustomEnhanced_002, TestSize.Level1) +{ + MISC_HILOGI("PlayVibratorCustomEnhanced_002 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool isSupport = IsSupportVibratorCustomEnhanced(identifier); + if (isSupport) { + FileDescriptor fileDescriptor("/data/test/vibrator/on_carpet.json"); + MISC_HILOGD("Test fd:%{public}d", fileDescriptor.fd); + struct stat64 statbuf = { 0 }; + if (fstat64(fileDescriptor.fd, &statbuf) == 0) { + int32_t ret = PlayVibratorCustomEnhanced(identifier, fileDescriptor.fd, 0, statbuf.st_size); + ASSERT_EQ(ret, 0); + } + std::this_thread::sleep_for(std::chrono::milliseconds(TIME_WAIT_FOR_OP)); + } else { + ASSERT_EQ(isSupport, false); + } + CancelEnhanced(identifier); +} + +HWTEST_F(VibratorAgentTest, PlayVibratorCustomEnhanced_003, TestSize.Level1) +{ + MISC_HILOGI("PlayVibratorCustomEnhanced_003 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool isSupport = (IsSupportVibratorCustomEnhanced(identifier) && + IsSupportVibratorEffectEnhanced(identifier, VIBRATOR_TYPE_FAIL)); + if (isSupport) { + bool flag = SetLoopCountEnhanced(identifier, 2); + ASSERT_TRUE(flag); + int32_t ret = StartVibratorEnhanced(identifier, VIBRATOR_TYPE_FAIL); + ASSERT_EQ(ret, 0); + FileDescriptor fileDescriptor("/data/test/vibrator/on_carpet.json"); + MISC_HILOGD("Test fd:%{public}d", fileDescriptor.fd); + struct stat64 statbuf = { 0 }; + if (fstat64(fileDescriptor.fd, &statbuf) == 0) { + ret = PlayVibratorCustomEnhanced(identifier, fileDescriptor.fd, 0, statbuf.st_size); + ASSERT_NE(ret, 0); + } + std::this_thread::sleep_for(std::chrono::milliseconds(TIME_WAIT_FOR_OP)); + } else { + ASSERT_EQ(isSupport, false); + } + CancelEnhanced(identifier); +} + +HWTEST_F(VibratorAgentTest, PlayVibratorCustomEnhanced_004, TestSize.Level1) +{ + MISC_HILOGI("PlayVibratorCustomEnhanced_004 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool isSupport = (IsSupportVibratorCustomEnhanced(identifier) && + IsSupportVibratorEffectEnhanced(identifier, VIBRATOR_TYPE_FAIL)); + if (isSupport) { + bool flag = SetUsageEnhanced(identifier, USAGE_ALARM); + ASSERT_TRUE(flag); + int32_t ret = StartVibratorEnhanced(identifier, VIBRATOR_TYPE_FAIL); + ASSERT_EQ(ret, 0); + FileDescriptor fileDescriptor("/data/test/vibrator/on_carpet.json"); + MISC_HILOGD("Test fd:%{public}d", fileDescriptor.fd); + struct stat64 statbuf = { 0 }; + if (fstat64(fileDescriptor.fd, &statbuf) == 0) { + ret = PlayVibratorCustomEnhanced(identifier, fileDescriptor.fd, 0, statbuf.st_size); + ASSERT_NE(ret, 0); + } + std::this_thread::sleep_for(std::chrono::milliseconds(TIME_WAIT_FOR_OP)); + } else { + ASSERT_EQ(isSupport, false); + } + CancelEnhanced(identifier); +} + +HWTEST_F(VibratorAgentTest, PlayVibratorCustomEnhanced_005, TestSize.Level1) +{ + MISC_HILOGI("PlayVibratorCustomEnhanced_005 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool isSupport = (IsSupportVibratorCustomEnhanced(identifier) && + IsSupportVibratorEffectEnhanced(identifier, VIBRATOR_TYPE_FAIL)); + if (isSupport) { + bool flag = SetUsageEnhanced(identifier, USAGE_UNKNOWN); + ASSERT_TRUE(flag); + int32_t ret = StartVibratorEnhanced(identifier, VIBRATOR_TYPE_FAIL); + ASSERT_EQ(ret, 0); + FileDescriptor fileDescriptor("/data/test/vibrator/on_carpet.json"); + MISC_HILOGD("Test fd:%{public}d", fileDescriptor.fd); + struct stat64 statbuf = { 0 }; + if (fstat64(fileDescriptor.fd, &statbuf) == 0) { + ret = PlayVibratorCustomEnhanced(identifier, fileDescriptor.fd, 0, statbuf.st_size); + ASSERT_EQ(ret, 0); + } + std::this_thread::sleep_for(std::chrono::milliseconds(TIME_WAIT_FOR_OP)); + } else { + ASSERT_EQ(isSupport, false); + } + CancelEnhanced(identifier); +} + +HWTEST_F(VibratorAgentTest, PlayVibratorCustomEnhanced_006, TestSize.Level1) +{ + MISC_HILOGI("PlayVibratorCustomEnhanced_006 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool isSupport = (IsSupportVibratorCustomEnhanced(identifier) && + IsSupportVibratorEffectEnhanced(identifier, VIBRATOR_TYPE_FAIL)); + if (isSupport) { + FileDescriptor fileDescriptor("/data/test/vibrator/on_carpet.json"); + MISC_HILOGD("Test fd:%{public}d", fileDescriptor.fd); + struct stat64 statbuf = { 0 }; + if (fstat64(fileDescriptor.fd, &statbuf) == 0) { + bool flag = SetUsageEnhanced(identifier, USAGE_ALARM); + ASSERT_TRUE(flag); + int32_t ret = PlayVibratorCustomEnhanced(identifier, fileDescriptor.fd, 0, statbuf.st_size); + ASSERT_EQ(ret, 0); + ret = StartVibratorEnhanced(identifier, VIBRATOR_TYPE_FAIL); + ASSERT_NE(ret, 0); + } + std::this_thread::sleep_for(std::chrono::milliseconds(TIME_WAIT_FOR_OP)); + } else { + ASSERT_EQ(isSupport, false); + } + CancelEnhanced(identifier); +} + +HWTEST_F(VibratorAgentTest, PlayVibratorCustomEnhanced_007, TestSize.Level1) +{ + MISC_HILOGI("PlayVibratorCustomEnhanced_007 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool isSupport = (IsSupportVibratorCustomEnhanced(identifier) && + IsSupportVibratorEffectEnhanced(identifier, VIBRATOR_TYPE_FAIL)); + if (isSupport) { + FileDescriptor fileDescriptor("/data/test/vibrator/on_carpet.json"); + MISC_HILOGD("Test fd:%{public}d", fileDescriptor.fd); + struct stat64 statbuf = { 0 }; + if (fstat64(fileDescriptor.fd, &statbuf) == 0) { + bool flag = SetUsageEnhanced(identifier, USAGE_UNKNOWN); + ASSERT_TRUE(flag); + int32_t ret = PlayVibratorCustomEnhanced(identifier, fileDescriptor.fd, 0, statbuf.st_size); + ASSERT_EQ(ret, 0); + ret = StartVibratorEnhanced(identifier, VIBRATOR_TYPE_FAIL); + ASSERT_EQ(ret, 0); + } + std::this_thread::sleep_for(std::chrono::milliseconds(TIME_WAIT_FOR_OP)); + } else { + ASSERT_EQ(isSupport, false); + } + CancelEnhanced(identifier); +} + +HWTEST_F(VibratorAgentTest, PlayVibratorCustomEnhanced_008, TestSize.Level1) +{ + MISC_HILOGI("PlayVibratorCustomEnhanced_008 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool isSupport = IsSupportVibratorCustomEnhanced(identifier); + if (isSupport) { + bool flag = SetUsageEnhanced(identifier, USAGE_ALARM); + ASSERT_TRUE(flag); + int32_t ret = StartVibratorOnceEnhanced(identifier, 500); + ASSERT_EQ(ret, 0); + FileDescriptor fileDescriptor("/data/test/vibrator/on_carpet.json"); + MISC_HILOGD("Test fd:%{public}d", fileDescriptor.fd); + struct stat64 statbuf = { 0 }; + if (fstat64(fileDescriptor.fd, &statbuf) == 0) { + ret = PlayVibratorCustomEnhanced(identifier, fileDescriptor.fd, 0, statbuf.st_size); + ASSERT_NE(ret, 0); + } + std::this_thread::sleep_for(std::chrono::milliseconds(TIME_WAIT_FOR_OP)); + } else { + ASSERT_EQ(isSupport, false); + } + CancelEnhanced(identifier); +} + +HWTEST_F(VibratorAgentTest, PlayVibratorCustomEnhanced_009, TestSize.Level1) +{ + MISC_HILOGI("PlayVibratorCustomEnhanced_009 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool isSupport = IsSupportVibratorCustomEnhanced(identifier); + if (isSupport) { + bool flag = SetUsage(USAGE_UNKNOWN); + ASSERT_TRUE(flag); + int32_t ret = StartVibratorOnceEnhanced(identifier, 500); + ASSERT_EQ(ret, 0); + FileDescriptor fileDescriptor("/data/test/vibrator/on_carpet.json"); + MISC_HILOGD("Test fd:%{public}d", fileDescriptor.fd); + struct stat64 statbuf = { 0 }; + if (fstat64(fileDescriptor.fd, &statbuf) == 0) { + ret = PlayVibratorCustomEnhanced(identifier, fileDescriptor.fd, 0, statbuf.st_size); + ASSERT_EQ(ret, 0); + } + std::this_thread::sleep_for(std::chrono::milliseconds(TIME_WAIT_FOR_OP)); + } else { + ASSERT_EQ(isSupport, false); + } + CancelEnhanced(identifier); +} + +HWTEST_F(VibratorAgentTest, PlayVibratorCustomEnhanced_010, TestSize.Level1) +{ + MISC_HILOGI("PlayVibratorCustomEnhanced_010 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool isSupport = IsSupportVibratorCustomEnhanced(identifier); + if (isSupport) { + FileDescriptor fileDescriptor("/data/test/vibrator/on_carpet.json"); + MISC_HILOGD("Test fd:%{public}d", fileDescriptor.fd); + struct stat64 statbuf = { 0 }; + if (fstat64(fileDescriptor.fd, &statbuf) == 0) { + bool flag = SetUsageEnhanced(identifier, USAGE_ALARM); + ASSERT_TRUE(flag); + int32_t ret = PlayVibratorCustomEnhanced(identifier, fileDescriptor.fd, 0, statbuf.st_size); + ASSERT_EQ(ret, 0); + ret = StartVibratorOnceEnhanced(identifier, 500); + ASSERT_NE(ret, 0); + } + std::this_thread::sleep_for(std::chrono::milliseconds(TIME_WAIT_FOR_OP)); + } else { + ASSERT_EQ(isSupport, false); + } + CancelEnhanced(identifier); +} + +HWTEST_F(VibratorAgentTest, PlayVibratorCustomEnhanced_011, TestSize.Level1) +{ + MISC_HILOGI("PlayVibratorCustomEnhanced_011 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool isSupport = IsSupportVibratorCustomEnhanced(identifier); + if (isSupport) { + FileDescriptor fileDescriptor("/data/test/vibrator/on_carpet.json"); + MISC_HILOGD("Test fd:%{public}d", fileDescriptor.fd); + struct stat64 statbuf = { 0 }; + if (fstat64(fileDescriptor.fd, &statbuf) == 0) { + bool flag = SetUsageEnhanced(identifier, USAGE_UNKNOWN); + ASSERT_TRUE(flag); + int32_t ret = PlayVibratorCustomEnhanced(identifier, fileDescriptor.fd, 0, statbuf.st_size); + ASSERT_EQ(ret, 0); + ret = StartVibratorOnceEnhanced(identifier, 500); + ASSERT_EQ(ret, 0); + } + std::this_thread::sleep_for(std::chrono::milliseconds(TIME_WAIT_FOR_OP)); + } else { + ASSERT_EQ(isSupport, false); + } + CancelEnhanced(identifier); +} + +HWTEST_F(VibratorAgentTest, PlayVibratorCustomEnhanced_012, TestSize.Level1) +{ + MISC_HILOGI("PlayVibratorCustomEnhanced_012 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool isSupport = IsSupportVibratorCustomEnhanced(identifier); + if (isSupport) { + FileDescriptor fileDescriptor("/data/test/vibrator/test_128_event.json"); + MISC_HILOGD("Test fd:%{public}d", fileDescriptor.fd); + struct stat64 statbuf = { 0 }; + if (fstat64(fileDescriptor.fd, &statbuf) == 0) { + int32_t ret = PlayVibratorCustomEnhanced(identifier, fileDescriptor.fd, 0, statbuf.st_size); + ASSERT_EQ(ret, 0); + } + std::this_thread::sleep_for(std::chrono::milliseconds(TIME_WAIT_FOR_OP)); + } else { + ASSERT_EQ(isSupport, false); + } + CancelEnhanced(identifier); +} + +HWTEST_F(VibratorAgentTest, PlayVibratorCustomEnhanced_013, TestSize.Level1) +{ + MISC_HILOGI("PlayVibratorCustomEnhanced_013 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool isSupport = IsSupportVibratorCustomEnhanced(identifier); + if (isSupport) { + FileDescriptor fileDescriptor("/data/test/vibrator/test_invalid_type.json"); + MISC_HILOGD("Test fd:%{public}d", fileDescriptor.fd); + struct stat64 statbuf = { 0 }; + if (fstat64(fileDescriptor.fd, &statbuf) == 0) { + int32_t ret = PlayVibratorCustomEnhanced(identifier, fileDescriptor.fd, 0, statbuf.st_size); + ASSERT_NE(ret, 0); + } + } else { + ASSERT_EQ(isSupport, false); + } +} + +HWTEST_F(VibratorAgentTest, PlayVibratorCustomEnhanced_014, TestSize.Level1) +{ + MISC_HILOGI("PlayVibratorCustomEnhanced_014 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool isSupport = IsSupportVibratorCustomEnhanced(identifier); + if (isSupport) { + FileDescriptor fileDescriptor("/data/test/vibrator/test_invalid_startTime.json"); + MISC_HILOGD("Test fd:%{public}d", fileDescriptor.fd); + struct stat64 statbuf = { 0 }; + if (fstat64(fileDescriptor.fd, &statbuf) == 0) { + int32_t ret = PlayVibratorCustomEnhanced(identifier, fileDescriptor.fd, 0, statbuf.st_size); + ASSERT_NE(ret, 0); + } + } else { + ASSERT_EQ(isSupport, false); + } +} + +HWTEST_F(VibratorAgentTest, PlayVibratorCustomEnhanced_015, TestSize.Level1) +{ + MISC_HILOGI("PlayVibratorCustomEnhanced_015 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool isSupport = IsSupportVibratorCustomEnhanced(identifier); + if (isSupport) { + FileDescriptor fileDescriptor("/data/test/vibrator/test_invalid_duration.json"); + MISC_HILOGD("Test fd:%{public}d", fileDescriptor.fd); + struct stat64 statbuf = { 0 }; + if (fstat64(fileDescriptor.fd, &statbuf) == 0) { + int32_t ret = PlayVibratorCustomEnhanced(identifier, fileDescriptor.fd, 0, statbuf.st_size); + ASSERT_NE(ret, 0); + } + } else { + ASSERT_EQ(isSupport, false); + } +} + +HWTEST_F(VibratorAgentTest, PlayVibratorCustomEnhanced_016, TestSize.Level1) +{ + MISC_HILOGI("PlayVibratorCustomEnhanced_016 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool isSupport = IsSupportVibratorCustomEnhanced(identifier); + if (isSupport) { + FileDescriptor fileDescriptor("/data/test/vibrator/test_invalid_intensity.json"); + MISC_HILOGD("Test fd:%{public}d", fileDescriptor.fd); + struct stat64 statbuf = { 0 }; + if (fstat64(fileDescriptor.fd, &statbuf) == 0) { + int32_t ret = PlayVibratorCustomEnhanced(identifier, fileDescriptor.fd, 0, statbuf.st_size); + ASSERT_NE(ret, 0); + } + } else { + ASSERT_EQ(isSupport, false); + } +} + +HWTEST_F(VibratorAgentTest, PlayVibratorCustomEnhanced_017, TestSize.Level1) +{ + MISC_HILOGI("PlayVibratorCustomEnhanced_017 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool isSupport = IsSupportVibratorCustomEnhanced(identifier); + if (isSupport) { + FileDescriptor fileDescriptor("/data/test/vibrator/test_invalid_frequency.json"); + MISC_HILOGD("Test fd:%{public}d", fileDescriptor.fd); + struct stat64 statbuf = { 0 }; + if (fstat64(fileDescriptor.fd, &statbuf) == 0) { + int32_t ret = PlayVibratorCustomEnhanced(identifier, fileDescriptor.fd, 0, statbuf.st_size); + ASSERT_NE(ret, 0); + } + } else { + ASSERT_EQ(isSupport, false); + } +} + +HWTEST_F(VibratorAgentTest, PlayVibratorCustomEnhanced_018, TestSize.Level1) +{ + MISC_HILOGI("PlayVibratorCustomEnhanced_018 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool isSupport = IsSupportVibratorCustomEnhanced(identifier); + if (isSupport) { + FileDescriptor fileDescriptor("/data/test/vibrator/test_129_event.json"); + MISC_HILOGD("Test fd:%{public}d", fileDescriptor.fd); + struct stat64 statbuf = { 0 }; + if (fstat64(fileDescriptor.fd, &statbuf) == 0) { + int32_t ret = PlayVibratorCustomEnhanced(identifier, fileDescriptor.fd, 0, statbuf.st_size); + ASSERT_NE(ret, 0); + } + } else { + ASSERT_EQ(isSupport, false); + } +} + +HWTEST_F(VibratorAgentTest, PlayVibratorCustomEnhanced_019, TestSize.Level1) +{ + MISC_HILOGI("PlayVibratorCustomEnhanced_019 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool isSupport = IsSupportVibratorCustomEnhanced(identifier); + if (isSupport) { + FileDescriptor fileDescriptor("/data/test/vibrator/test_big_file_size.json"); + MISC_HILOGD("Test fd:%{public}d", fileDescriptor.fd); + struct stat64 statbuf = { 0 }; + if (fstat64(fileDescriptor.fd, &statbuf) == 0) { + int32_t ret = PlayVibratorCustomEnhanced(identifier, fileDescriptor.fd, 0, statbuf.st_size); + ASSERT_NE(ret, 0); + } + } else { + ASSERT_EQ(isSupport, false); + } +} + +HWTEST_F(VibratorAgentTest, PlayVibratorCustomEnhanced_020, TestSize.Level1) +{ + MISC_HILOGI("PlayVibratorCustomEnhanced_020 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool isSupport = IsSupportVibratorCustomEnhanced(identifier); + if (isSupport) { + FileDescriptor fileDescriptor("/data/test/vibrator/test_event_overlap_1.json"); + MISC_HILOGD("Test fd:%{public}d", fileDescriptor.fd); + struct stat64 statbuf = { 0 }; + if (fstat64(fileDescriptor.fd, &statbuf) == 0) { + int32_t ret = PlayVibratorCustomEnhanced(identifier, fileDescriptor.fd, 0, statbuf.st_size); + ASSERT_EQ(ret, 0); + } + } else { + ASSERT_EQ(isSupport, false); + } + CancelEnhanced(identifier); +} + +HWTEST_F(VibratorAgentTest, PlayVibratorCustomEnhanced_021, TestSize.Level1) +{ + MISC_HILOGI("PlayVibratorCustomEnhanced_021 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool isSupport = IsSupportVibratorCustomEnhanced(identifier); + if (isSupport) { + FileDescriptor fileDescriptor("/data/test/vibrator/test_event_overlap_2.json"); + MISC_HILOGD("Test fd:%{public}d", fileDescriptor.fd); + struct stat64 statbuf = { 0 }; + if (fstat64(fileDescriptor.fd, &statbuf) == 0) { + int32_t ret = PlayVibratorCustomEnhanced(identifier, fileDescriptor.fd, 0, statbuf.st_size); + ASSERT_EQ(ret, 0); + } + } else { + ASSERT_EQ(isSupport, false); + } + CancelEnhanced(identifier); +} + +HWTEST_F(VibratorAgentTest, PlayVibratorCustomEnhanced_022, TestSize.Level1) +{ + MISC_HILOGI("PlayVibratorCustomEnhanced_022 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool isSupport = IsSupportVibratorCustomEnhanced(identifier); + if (isSupport) { + FileDescriptor fileDescriptor("/data/test/vibrator/Jet_N2O.he"); + MISC_HILOGD("Test fd:%{public}d", fileDescriptor.fd); + struct stat64 statbuf = { 0 }; + if (fstat64(fileDescriptor.fd, &statbuf) == 0) { + int32_t ret = PlayVibratorCustomEnhanced(identifier, fileDescriptor.fd, 0, statbuf.st_size); + ASSERT_EQ(ret, 0); + } + std::this_thread::sleep_for(std::chrono::milliseconds(TIME_WAIT_FOR_OP)); + } else { + ASSERT_EQ(isSupport, false); + } + CancelEnhanced(identifier); +} + +HWTEST_F(VibratorAgentTest, PlayVibratorCustomEnhanced_023, TestSize.Level1) +{ + MISC_HILOGI("PlayVibratorCustomEnhanced_023 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool isSupport = IsSupportVibratorCustomEnhanced(identifier); + if (isSupport) { + FileDescriptor fileDescriptor("/data/test/vibrator/Racing_Start.he"); + MISC_HILOGD("Test fd:%{public}d", fileDescriptor.fd); + struct stat64 statbuf = { 0 }; + if (fstat64(fileDescriptor.fd, &statbuf) == 0) { + int32_t ret = PlayVibratorCustomEnhanced(identifier, fileDescriptor.fd, 0, statbuf.st_size); + ASSERT_EQ(ret, 0); + } + std::this_thread::sleep_for(std::chrono::milliseconds(TIME_WAIT_FOR_OP)); + } else { + ASSERT_EQ(isSupport, false); + } + CancelEnhanced(identifier); +} + +HWTEST_F(VibratorAgentTest, SetParametersEnhanced_001, TestSize.Level1) +{ + MISC_HILOGI("SetParametersEnhanced_001 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + VibratorParameter parameter = { + .intensity = -1, + .frequency = -15 + }; + bool ret = SetParametersEnhanced(identifier, parameter); + ASSERT_FALSE(ret); +} + +HWTEST_F(VibratorAgentTest, SetParametersEnhanced_002, TestSize.Level1) +{ + MISC_HILOGI("SetParametersEnhanced_002 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + VibratorParameter parameter = { + .intensity = 70, + .frequency = 150 + }; + bool ret = SetParametersEnhanced(identifier, parameter); + ASSERT_FALSE(ret); +} + +HWTEST_F(VibratorAgentTest, SetParametersEnhanced_003, TestSize.Level1) +{ + MISC_HILOGI("SetParametersEnhanced_003 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool isSupport = IsSupportVibratorCustomEnhanced(identifier); + if (isSupport) { + FileDescriptor fileDescriptor("/data/test/vibrator/coin_drop.json"); + MISC_HILOGD("Test fd:%{public}d", fileDescriptor.fd); + struct stat64 statbuf = { 0 }; + if (fstat64(fileDescriptor.fd, &statbuf) == 0) { + VibratorParameter parameter = { + .intensity = 50, + .frequency = -15 + }; + bool flag = SetParametersEnhanced(identifier, parameter); + ASSERT_TRUE(flag); + int32_t ret = PlayVibratorCustomEnhanced(identifier, fileDescriptor.fd, 0, statbuf.st_size); + ASSERT_EQ(ret, 0); + } + std::this_thread::sleep_for(std::chrono::milliseconds(TIME_WAIT_FOR_OP)); + } else { + ASSERT_EQ(isSupport, false); + } + CancelEnhanced(identifier); +} + +HWTEST_F(VibratorAgentTest, SetParametersEnhanced_004, TestSize.Level1) +{ + MISC_HILOGI("SetParametersEnhanced_004 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool isSupport = IsSupportVibratorCustomEnhanced(identifier); + if (isSupport) { + FileDescriptor fileDescriptor("/data/test/vibrator/on_carpet.json"); + MISC_HILOGD("Test fd:%{public}d", fileDescriptor.fd); + struct stat64 statbuf = { 0 }; + if (fstat64(fileDescriptor.fd, &statbuf) == 0) { + VibratorParameter parameter = { + .intensity = 33, + .frequency = 55 + }; + bool flag = SetParametersEnhanced(identifier, parameter); + ASSERT_TRUE(flag); + int32_t ret = PlayVibratorCustomEnhanced(identifier, fileDescriptor.fd, 0, statbuf.st_size); + ASSERT_EQ(ret, 0); + } + std::this_thread::sleep_for(std::chrono::milliseconds(TIME_WAIT_FOR_OP)); + } else { + ASSERT_EQ(isSupport, false); + } + CancelEnhanced(identifier); +} + +HWTEST_F(VibratorAgentTest, CancelEnhanced_001, TestSize.Level1) +{ + MISC_HILOGI("CancelEnhanced_001 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + int32_t ret = CancelEnhanced(identifier); + ASSERT_NE(ret, 0); +} + +HWTEST_F(VibratorAgentTest, CancelEnhanced_002, TestSize.Level1) +{ + MISC_HILOGI("CancelEnhanced_002 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool isSupport = IsSupportVibratorCustomEnhanced(identifier); + if (isSupport) { + FileDescriptor fileDescriptor("/data/test/vibrator/coin_drop.json"); + MISC_HILOGD("Test fd:%{public}d", fileDescriptor.fd); + struct stat64 statbuf = { 0 }; + if (fstat64(fileDescriptor.fd, &statbuf) == 0) { + int32_t ret = PlayVibratorCustomEnhanced(identifier, fileDescriptor.fd, 0, statbuf.st_size); + ASSERT_EQ(ret, 0); + ret = CancelEnhanced(identifier); + ASSERT_EQ(ret, 0); + } + } else { + ASSERT_EQ(isSupport, false); + } +} + +HWTEST_F(VibratorAgentTest, CancelEnhanced_003, TestSize.Level1) +{ + MISC_HILOGI("CancelEnhanced_003 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + int32_t ret = StartVibratorOnceEnhanced(identifier, 500); + ASSERT_EQ(ret, 0); + ret = CancelEnhanced(identifier); + ASSERT_EQ(ret, 0); +} + +HWTEST_F(VibratorAgentTest, CancelEnhanced_004, TestSize.Level1) +{ + MISC_HILOGI("CancelEnhanced_004 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + if (IsSupportVibratorEffectEnhanced(identifier, VIBRATOR_TYPE_FAIL)) { + int32_t ret = StartVibratorEnhanced(identifier, VIBRATOR_TYPE_FAIL); + ASSERT_EQ(ret, 0); + ret = CancelEnhanced(identifier); + ASSERT_EQ(ret, 0); + } + ASSERT_TRUE(true); +} + +HWTEST_F(VibratorAgentTest, IsSupportEffectEnhanced_001, TestSize.Level1) +{ + MISC_HILOGI("IsSupportEffectEnhanced_001 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool state { false }; + int32_t ret = IsSupportEffectEnhanced(identifier, VIBRATOR_TYPE_CLOCK_TIMER, &state); + ASSERT_EQ(ret, 0); + if (state) { + ret = StartVibratorEnhanced(identifier, VIBRATOR_TYPE_CLOCK_TIMER); + ASSERT_EQ(ret, 0); + CancelEnhanced(identifier); + } else { + MISC_HILOGI("Do not support %{public}s", VIBRATOR_TYPE_CLOCK_TIMER); + } +} + +HWTEST_F(VibratorAgentTest, IsSupportEffectEnhanced_002, TestSize.Level1) +{ + MISC_HILOGI("IsSupportEffectEnhanced_002 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool state { false }; + int32_t ret = IsSupportEffectEnhanced(identifier, "haptic.xxx.yyy", &state); + ASSERT_EQ(ret, 0); + ASSERT_FALSE(state); +} + +HWTEST_F(VibratorAgentTest, IsSupportEffectEnhanced_003, TestSize.Level1) +{ + MISC_HILOGI("IsSupportEffectEnhanced_003 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool state { false }; + int32_t ret = IsSupportEffectEnhanced(identifier, nullptr, &state); + ASSERT_NE(ret, 0); + ASSERT_FALSE(state); +} + +HWTEST_F(VibratorAgentTest, IsSupportEffectEnhanced_004, TestSize.Level1) +{ + MISC_HILOGI("IsSupportEffectEnhanced_004 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool state { false }; + int32_t ret = IsSupportEffectEnhanced(identifier, VIBRATOR_TYPE_FAIL, &state); + ASSERT_EQ(ret, 0); + if (state) { + ret = StartVibratorEnhanced(identifier, VIBRATOR_TYPE_FAIL); + ASSERT_EQ(ret, 0); + CancelEnhanced(identifier); + } else { + MISC_HILOGI("Do not support %{public}s", VIBRATOR_TYPE_FAIL); + } +} + +HWTEST_F(VibratorAgentTest, IsSupportEffectEnhanced_005, TestSize.Level1) +{ + MISC_HILOGI("IsSupportEffectEnhanced_005 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool state { false }; + int32_t ret = IsSupportEffectEnhanced(identifier, VIBRATOR_TYPE_CHARGING, &state); + ASSERT_EQ(ret, 0); + if (state) { + ret = StartVibratorEnhanced(identifier, VIBRATOR_TYPE_CHARGING); + ASSERT_EQ(ret, 0); + CancelEnhanced(identifier); + } else { + MISC_HILOGI("Do not support %{public}s", VIBRATOR_TYPE_CHARGING); + } +} + +HWTEST_F(VibratorAgentTest, IsSupportEffectEnhanced_006, TestSize.Level1) +{ + MISC_HILOGI("IsSupportEffectEnhanced_006 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool state { false }; + int32_t ret = IsSupportEffectEnhanced(identifier, VIBRATOR_TYPE_LONG_PRESS_HEAVY, &state); + ASSERT_EQ(ret, 0); + if (state) { + ret = StartVibratorEnhanced(identifier, VIBRATOR_TYPE_LONG_PRESS_HEAVY); + ASSERT_EQ(ret, 0); + CancelEnhanced(identifier); + } else { + MISC_HILOGI("Do not support %{public}s", VIBRATOR_TYPE_LONG_PRESS_HEAVY); + } +} + +HWTEST_F(VibratorAgentTest, IsSupportEffectEnhanced_007, TestSize.Level1) +{ + MISC_HILOGI("IsSupportEffectEnhanced_007 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool state { false }; + int32_t ret = IsSupportEffectEnhanced(identifier, VIBRATOR_TYPE_LONG_PRESS_LIGHT, &state); + ASSERT_EQ(ret, 0); + if (state) { + ret = StartVibratorEnhanced(identifier, VIBRATOR_TYPE_LONG_PRESS_LIGHT); + ASSERT_EQ(ret, 0); + CancelEnhanced(identifier); + } else { + MISC_HILOGI("Do not support %{public}s", VIBRATOR_TYPE_LONG_PRESS_LIGHT); + } +} + +HWTEST_F(VibratorAgentTest, IsSupportEffectEnhanced_008, TestSize.Level1) +{ + MISC_HILOGI("IsSupportEffectEnhanced_008 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool state { false }; + int32_t ret = IsSupportEffectEnhanced(identifier, VIBRATOR_TYPE_LONG_PRESS_MEDIUM, &state); + ASSERT_EQ(ret, 0); + if (state) { + ret = StartVibratorEnhanced(identifier, VIBRATOR_TYPE_LONG_PRESS_MEDIUM); + ASSERT_EQ(ret, 0); + CancelEnhanced(identifier); + } else { + MISC_HILOGI("Do not support %{public}s", VIBRATOR_TYPE_LONG_PRESS_MEDIUM); + } +} + +HWTEST_F(VibratorAgentTest, IsSupportEffectEnhanced_009, TestSize.Level1) +{ + MISC_HILOGI("IsSupportEffectEnhanced_009 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool state { false }; + int32_t ret = IsSupportEffectEnhanced(identifier, VIBRATOR_TYPE_SLIDE_LIGHT, &state); + ASSERT_EQ(ret, 0); + if (state) { + ret = StartVibratorEnhanced(identifier, VIBRATOR_TYPE_SLIDE_LIGHT); + ASSERT_EQ(ret, 0); + CancelEnhanced(identifier); + } else { + MISC_HILOGI("Do not support %{public}s", VIBRATOR_TYPE_SLIDE_LIGHT); + } +} + +HWTEST_F(VibratorAgentTest, IsSupportEffectEnhanced_010, TestSize.Level1) +{ + MISC_HILOGI("IsSupportEffectEnhanced_010 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool state { false }; + int32_t ret = IsSupportEffectEnhanced(identifier, VIBRATOR_TYPE_THRESHOID, &state); + ASSERT_EQ(ret, 0); + if (state) { + ret = StartVibratorEnhanced(identifier, VIBRATOR_TYPE_THRESHOID); + ASSERT_EQ(ret, 0); + CancelEnhanced(identifier); + } else { + MISC_HILOGI("Do not support %{public}s", VIBRATOR_TYPE_THRESHOID); + } +} + +HWTEST_F(VibratorAgentTest, GetDelayTimeEnhanced_001, TestSize.Level1) +{ + MISC_HILOGI("GetDelayTimeEnhanced_001 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool isSupport = IsSupportVibratorCustomEnhanced(identifier); + if (isSupport) { + int32_t delayTime { -1 }; + int32_t ret = GetDelayTimeEnhanced(identifier, delayTime); + ASSERT_EQ(ret, 0); + } else { + ASSERT_EQ(isSupport, false); + } +} + +HWTEST_F(VibratorAgentTest, PlayPatternEnhanced_001, TestSize.Level1) +{ + MISC_HILOGI("PlayPatternEnhanced_001 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool isSupport = IsSupportVibratorCustomEnhanced(identifier); + if (isSupport) { + int32_t delayTime { -1 }; + int32_t ret = GetDelayTimeEnhanced(identifier, delayTime); + ASSERT_EQ(ret, 0); + MISC_HILOGD("delayTime:%{public}d", delayTime); + FileDescriptor fileDescriptor("/data/test/vibrator/coin_drop.json"); + MISC_HILOGD("fd:%{public}d", fileDescriptor.fd); + VibratorFileDescription vfd; + VibratorPackage package; + struct stat64 statbuf = { 0 }; + if (fstat64(fileDescriptor.fd, &statbuf) == 0) { + vfd.fd = fileDescriptor.fd; + vfd.offset = 0; + vfd.length = statbuf.st_size; + ret = PreProcess(vfd, package); + ASSERT_EQ(ret, 0); + for (int32_t i = 0; i < package.patternNum; ++i) { + if (i == 0) { + std::this_thread::sleep_for(std::chrono::milliseconds(package.patterns[i].time)); + } else { + std::this_thread::sleep_for(std::chrono::milliseconds(package.patterns[i].time) - + std::chrono::milliseconds(package.patterns[i - 1].time)); + } + ASSERT_EQ(SetUsageEnhanced(identifier, USAGE_UNKNOWN), true); + MISC_HILOGD("pointNum:%{public}d", package.patterns[i].events[i].pointNum); + ret = PlayPatternEnhanced(identifier, package.patterns[i]); + ASSERT_EQ(ret, 0); + } + } + ret = FreeVibratorPackage(package); + ASSERT_EQ(ret, 0); + CancelEnhanced(identifier); + } else { + ASSERT_EQ(isSupport, false); + } +} + +HWTEST_F(VibratorAgentTest, PlayPrimitiveEffectEnhanced_001, TestSize.Level1) +{ + MISC_HILOGI("PlayPrimitiveEffectEnhanced_001 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + int32_t ret = PlayPrimitiveEffectEnhanced(identifier, nullptr, INTENSITY_HIGH); + ASSERT_EQ(ret, PARAMETER_ERROR); +} + +HWTEST_F(VibratorAgentTest, PlayPrimitiveEffectEnhanced_002, TestSize.Level1) +{ + MISC_HILOGI("PlayPrimitiveEffectEnhanced_002 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool state { false }; + int32_t ret = IsSupportEffectEnhanced(identifier, VIBRATOR_TYPE_SLIDE, &state); + ASSERT_EQ(ret, 0); + if (state) { + ret = PlayPrimitiveEffectEnhanced(identifier, VIBRATOR_TYPE_SLIDE, INTENSITY_INVALID); + ASSERT_EQ(ret, PARAMETER_ERROR); + } else { + MISC_HILOGI("Do not support %{public}s", VIBRATOR_TYPE_SLIDE); + } +} + +HWTEST_F(VibratorAgentTest, PlayPrimitiveEffectEnhanced_003, TestSize.Level1) +{ + MISC_HILOGI("PlayPrimitiveEffectEnhanced_003 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool state { false }; + int32_t ret = IsSupportEffectEnhanced(identifier, VIBRATOR_TYPE_SLIDE, &state); + ASSERT_EQ(ret, 0); + if (state) { + ret = PlayPrimitiveEffectEnhanced(identifier, VIBRATOR_TYPE_SLIDE, INTENSITY_LOW); + ASSERT_EQ(ret, 0); + std::this_thread::sleep_for(std::chrono::milliseconds(TIME_WAIT_FOR_OP)); + CancelEnhanced(identifier); + } else { + MISC_HILOGI("Do not support %{public}s", VIBRATOR_TYPE_SLIDE); + } +} + +HWTEST_F(VibratorAgentTest, PlayPrimitiveEffectEnhanced_004, TestSize.Level1) +{ + MISC_HILOGI("PlayPrimitiveEffectEnhanced_004 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool state { false }; + int32_t ret = IsSupportEffectEnhanced(identifier, VIBRATOR_TYPE_SLIDE, &state); + ASSERT_EQ(ret, 0); + if (state) { + ret = PlayPrimitiveEffectEnhanced(identifier, VIBRATOR_TYPE_SLIDE, INTENSITY_MEDIUM); + ASSERT_EQ(ret, 0); + std::this_thread::sleep_for(std::chrono::milliseconds(TIME_WAIT_FOR_OP)); + CancelEnhanced(identifier); + } else { + MISC_HILOGI("Do not support %{public}s", VIBRATOR_TYPE_SLIDE); + } +} + +HWTEST_F(VibratorAgentTest, PlayPrimitiveEffectEnhanced_005, TestSize.Level1) +{ + MISC_HILOGI("PlayPrimitiveEffectEnhanced_005 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool state { false }; + int32_t ret = IsSupportEffectEnhanced(identifier, VIBRATOR_TYPE_SLIDE, &state); + ASSERT_EQ(ret, 0); + if (state) { + ret = PlayPrimitiveEffectEnhanced(identifier, VIBRATOR_TYPE_SLIDE, INTENSITY_HIGH); + ASSERT_EQ(ret, 0); + std::this_thread::sleep_for(std::chrono::milliseconds(TIME_WAIT_FOR_OP)); + CancelEnhanced(identifier); + } else { + MISC_HILOGI("Do not support %{public}s", VIBRATOR_TYPE_SLIDE); + } +} + +HWTEST_F(VibratorAgentTest, IsHdHapticSupportedEnhanced_001, TestSize.Level1) +{ + MISC_HILOGI("IsHdHapticSupportedEnhanced_001 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + bool isSupport = (IsSupportVibratorCustomEnhanced(identifier) && IsHdHapticSupportedEnhanced(identifier)); + if (isSupport) { + FileDescriptor fileDescriptor("/data/test/vibrator/coin_drop.json"); + MISC_HILOGD("Test fd:%{public}d", fileDescriptor.fd); + struct stat64 statbuf = { 0 }; + if (fstat64(fileDescriptor.fd, &statbuf) == 0) { + int32_t ret = PlayVibratorCustomEnhanced(identifier, fileDescriptor.fd, 0, statbuf.st_size); + ASSERT_EQ(ret, 0); + } + std::this_thread::sleep_for(std::chrono::milliseconds(TIME_WAIT_FOR_OP)); + } else { + ASSERT_EQ(isSupport, false); + } + CancelEnhanced(identifier); +} + +HWTEST_F(VibratorAgentTest, GetVibratorIdList_001, TestSize.Level1) +{ + MISC_HILOGI("GetVibratorIdList_001 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + std::vector result; + int32_t ret = GetVibratorIdList(identifier, result); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); +} + +HWTEST_F(VibratorAgentTest, GetVibratorIdList_002, TestSize.Level1) +{ + MISC_HILOGI("GetVibratorIdList_002 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = 1, + }; + std::vector result; + int32_t ret = GetVibratorIdList(identifier, result); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); +} + +HWTEST_F(VibratorAgentTest, GetVibratorIdList_003, TestSize.Level1) +{ + MISC_HILOGI("GetVibratorIdList_003 in"); + VibratorIdentifier identifier = { + .deviceId = 1, + .vibratorId = -1, + }; + std::vector result; + int32_t ret = GetVibratorIdList(identifier, result); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); +} + +HWTEST_F(VibratorAgentTest, GetVibratorIdList_004, TestSize.Level1) +{ + MISC_HILOGI("GetVibratorIdList_004 in"); + VibratorIdentifier identifier = { + .deviceId = 1, + .vibratorId = 1, + }; + std::vector result; + int32_t ret = GetVibratorIdList(identifier, result); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); +} + +HWTEST_F(VibratorAgentTest, GetVibratorIdList_005, TestSize.Level1) +{ + MISC_HILOGI("GetVibratorIdList_005 in"); + VibratorIdentifier identifier = { + .deviceId = -9999, + .vibratorId = 1, + }; + std::vector result; + int32_t ret = GetVibratorIdList(identifier, result); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); +} + +HWTEST_F(VibratorAgentTest, GetEffectInfo_001, TestSize.Level1) +{ + MISC_HILOGI("GetEffectInfo_001 in"); + VibratorIdentifier identifier = { + .deviceId = 1, + .vibratorId = -1, + }; + std::string effectType = ""; + EffectInfo result; + int32_t ret = GetEffectInfo(identifier, effectType, result); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); +} + +HWTEST_F(VibratorAgentTest, GetEffectInfo_002, TestSize.Level1) +{ + MISC_HILOGI("GetEffectInfo_002 in"); + VibratorIdentifier identifier = { + .deviceId = -1, + .vibratorId = -1, + }; + std::string effectType = ""; + EffectInfo result; + int32_t ret = GetEffectInfo(identifier, effectType, result); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); +} + +HWTEST_F(VibratorAgentTest, SubscribeVibrator_001, TestSize.Level1) +{ + MISC_HILOGI("SubscribeVibrator_001 in"); + int32_t ret = SubscribeVibrator(testUser); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); +} + +HWTEST_F(VibratorAgentTest, SubscribeVibrator_002, TestSize.Level1) +{ + VibratorUser invalidUser = { + .callback = nullptr, + }; + MISC_HILOGI("SubscribeVibrator_002 in"); + int32_t ret = SubscribeVibrator(invalidUser); + ASSERT_EQ(ret, OHOS::Sensors::ERROR); +} + +HWTEST_F(VibratorAgentTest, UnSubscribeVibrator_001, TestSize.Level1) +{ + MISC_HILOGI("UnSubscribeVibrator_001 in"); + int32_t ret = UnSubscribeVibrator(testUser); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + ret = UnSubscribeVibrator(testUser); + ASSERT_EQ(ret, OHOS::Sensors::CALLBACK_UNSUBSCRIBED); +} } // namespace Sensors } // namespace OHOS diff --git a/utils/common/include/sensors_errors.h b/utils/common/include/sensors_errors.h index 5214aa5c0ffab13d01cf72443262c060e267a936..90e88e6af3a0759f3a4b37306a741c2789931894 100644 --- a/utils/common/include/sensors_errors.h +++ b/utils/common/include/sensors_errors.h @@ -30,6 +30,7 @@ enum ErrorCode : int32_t { PARAMETER_ERROR = 401, // Use this error code when the input parameter type or range does not match. IS_NOT_SUPPORTED = 801, // Use this error code when capability not supported. DEVICE_OPERATION_FAILED = 14600101, // Use this error code when operating the device fail. + CALLBACK_UNSUBSCRIBED = 14600102, //Use this error code when the user callback function is deregistered repeatedly. }; enum { diff --git a/utils/common/include/vibrator_infos.h b/utils/common/include/vibrator_infos.h index 140d3c290def85b668221aa90833d379e032343c..8b653fe18d717ec4e1a3ebd8b7664da1b9b62546 100644 --- a/utils/common/include/vibrator_infos.h +++ b/utils/common/include/vibrator_infos.h @@ -128,13 +128,60 @@ struct VibrateInfo { VibratePackage package; }; -struct VibrateParameter : public Parcelable { +struct VibrateParameter { int32_t intensity = 100; // from 0 to 100 int32_t frequency = 0; // from -100 to 100 int32_t reserved = 0; +}; + + +struct VibratorInfoIPC : public Parcelable{ + int32_t deviceId = -1; + int32_t vibratorId = -1; + std::string deviceName = ""; + bool isSupportHdHaptic; + bool isLocalVibrator; + int32_t position = 0; + void Dump() const; + bool Marshalling(Parcel &parcel) const; + static VibratorInfoIPC* Unmarshalling(Parcel &data); +}; + +struct VibratorIdentifierIPC : public Parcelable { + int32_t deviceId = -1; + int32_t vibratorId = -1; + int32_t position = 0; + bool isLocalVibrator; + void Dump() const; + bool Marshalling(Parcel &parcel) const; + static VibratorIdentifierIPC* Unmarshalling(Parcel &data); +}; + +struct EffectInfoIPC : public Parcelable{ + int32_t duration = -1; + bool isSupportEffect; + void Dump() const; + bool Marshalling(Parcel &parcel) const; + static EffectInfoIPC* Unmarshalling(Parcel &data); +}; + +struct CustomHapticInfoIPC : public Parcelable{ + int32_t usage = 0; + bool systemUsage; + VibrateParameter parameter; + void Dump() const; + bool Marshalling(Parcel &parcel) const; + static CustomHapticInfoIPC* Unmarshalling(Parcel &data); +}; + +struct PrimitiveEffectIPC : public Parcelable{ + int32_t intensity = 0; + int32_t usage = 0; + bool systemUsage; + int32_t count = 0; void Dump() const; bool Marshalling(Parcel &parcel) const; - static VibrateParameter* Unmarshalling(Parcel &data); + static PrimitiveEffectIPC* Unmarshalling(Parcel &data); }; } // namespace Sensors } // namespace OHOS diff --git a/utils/common/src/vibrator_infos.cpp b/utils/common/src/vibrator_infos.cpp index e373e0a82e19f65b22b4e26c01ed93bfcc16d07b..70be0feee6af6453e5fe7a1c232f76938b5dd2a1 100644 --- a/utils/common/src/vibrator_infos.cpp +++ b/utils/common/src/vibrator_infos.cpp @@ -224,36 +224,286 @@ VibratePattern* VibratePattern::Unmarshalling(Parcel &data) return pattern; } -void VibrateParameter::Dump() const +bool VibratorInfoIPC::Marshalling(Parcel &parcel) const { - MISC_HILOGI("intensity:%{public}d, frequency:%{public}d", intensity, frequency); + if (!parcel.WriteInt32(deviceId)) { + MISC_HILOGE("Write deviceId failed"); + return false; + } + if (!parcel.WriteInt32(vibratorId)) { + MISC_HILOGE("Write vibratorId failed"); + return false; + } + if (!parcel.WriteString(deviceName)) { + MISC_HILOGE("Write vibratorId failed"); + return false; + } + if (!parcel.WriteBool(isSupportHdHaptic)) { + MISC_HILOGE("Write isSupportHdHaptic failed"); + return false; + } + if (!parcel.WriteBool(isLocalVibrator)) { + MISC_HILOGE("Write isLocalVibrator failed"); + return false; + } + return true; } -bool VibrateParameter::Marshalling(Parcel &parcel) const +VibratorInfoIPC* VibratorInfoIPC::Unmarshalling(Parcel &data) { - if (!parcel.WriteInt32(intensity)) { - MISC_HILOGE("Write parameter's intensity failed"); + auto vibratorInfoIPC = new (std::nothrow) VibratorInfoIPC(); + if (vibratorInfoIPC == nullptr) { + MISC_HILOGE("Read init vibratorInfoIPC failed"); + return nullptr; + } + if (!data.ReadInt32(vibratorInfoIPC->deviceId)) { + MISC_HILOGE("Read deviceId failed"); + vibratorInfoIPC = nullptr; + return vibratorInfoIPC; + } + if (!data.ReadInt32(vibratorInfoIPC->vibratorId)) { + MISC_HILOGE("Read vibratorId failed"); + vibratorInfoIPC = nullptr; + return vibratorInfoIPC; + } + if (!data.ReadString(vibratorInfoIPC->deviceName)) { + MISC_HILOGE("Read deviceName failed"); + vibratorInfoIPC = nullptr; + return vibratorInfoIPC; + } + if (!data.ReadBool(vibratorInfoIPC->isSupportHdHaptic)) { + MISC_HILOGE("Read isSupportHdHaptic failed"); + vibratorInfoIPC = nullptr; + return vibratorInfoIPC; + } + if (!data.ReadBool(vibratorInfoIPC->isLocalVibrator)) { + MISC_HILOGE("Read isLocalVibrator failed"); + vibratorInfoIPC = nullptr; + return vibratorInfoIPC; + } + return vibratorInfoIPC; +} + +void VibratorInfoIPC::Dump() const +{ + std::string retStr; + retStr = "deviceId: "+ std::to_string(deviceId) + " "; + retStr += ("vibratorId: " + std::to_string(vibratorId) + " "); + retStr += ("deviceName: " + deviceName + " "); + retStr += ("isSupportHdHaptic: " + (isSupportHdHaptic? std::string("true"):std::string("false")) + " "); + MISC_HILOGI("VibratorInfoIPC: [%{public}s]", retStr.c_str()); +} + +void VibratorIdentifierIPC::Dump() const +{ + MISC_HILOGI("deviceId:%{public}d, vibratorId:%{public}d", deviceId, vibratorId); +} + +bool VibratorIdentifierIPC::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteInt32(deviceId)) { + MISC_HILOGE("Write parameter's deviceId failed"); return false; } - if (!parcel.WriteInt32(frequency)) { - MISC_HILOGE("Write parameter's frequency failed"); + if (!parcel.WriteInt32(vibratorId)) { + MISC_HILOGE("Write parameter's vibratorId failed"); return false; } return true; } -VibrateParameter* VibrateParameter::Unmarshalling(Parcel &data) +VibratorIdentifierIPC* VibratorIdentifierIPC::Unmarshalling(Parcel &data) { - auto parameter = new (std::nothrow) VibrateParameter(); - if (parameter == nullptr) { + auto identifier = new (std::nothrow) VibratorIdentifierIPC(); + if (identifier == nullptr) { MISC_HILOGE("Read init parameter failed"); return nullptr; } - if (!(data.ReadInt32(parameter->intensity)) && !(data.ReadInt32(parameter->frequency))) { - MISC_HILOGE("Read parameter's intensity failed"); - parameter = nullptr; + if (!(data.ReadInt32(identifier->deviceId))) { + MISC_HILOGE("Read parameter's deviceId or vibratorId failed"); + identifier = nullptr; + } + if (!(data.ReadInt32(identifier->vibratorId))) { + MISC_HILOGE("Read parameter's deviceId or vibratorId failed"); + identifier = nullptr; + } + return identifier; +} + +bool EffectInfoIPC::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteInt32(duration)) { + MISC_HILOGE("Write duration failed"); + return false; + } + if (!parcel.WriteBool(isSupportEffect)) { + MISC_HILOGE("Write isSupportEffect failed"); + return false; + } + return true; +} + +EffectInfoIPC* EffectInfoIPC::Unmarshalling(Parcel &data) +{ + auto effectInfoIPC = new (std::nothrow) EffectInfoIPC(); + if (effectInfoIPC == nullptr) { + MISC_HILOGE("Read init EffectInfoIPC failed"); + return nullptr; + } + if (!data.ReadInt32(effectInfoIPC->duration)) { + MISC_HILOGE("Read duration failed"); + effectInfoIPC = nullptr; + return effectInfoIPC; + } + if (!data.ReadBool(effectInfoIPC->isSupportEffect)) { + MISC_HILOGE("Read isSupportEffect failed"); + effectInfoIPC = nullptr; + return effectInfoIPC; } - return parameter; + return effectInfoIPC; } + +void EffectInfoIPC::Dump() const +{ + std::string retStr; + retStr = "duration: "+ std::to_string(duration) + " "; + retStr += ("isSupportEffect: " + (isSupportEffect? std::string("true"):std::string("false"))); + MISC_HILOGI("EffectInfoIPC: [%{public}s]", retStr.c_str()); +} + +bool CustomHapticInfoIPC::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteInt32(usage)) { + MISC_HILOGE("Write usage failed"); + return false; + } + if (!parcel.WriteBool(systemUsage)) { + MISC_HILOGE("Write systemUsage failed"); + return false; + } + if (!parcel.WriteInt32(parameter.intensity)) { + MISC_HILOGE("Write intensity failed"); + return false; + } + if (!parcel.WriteInt32(parameter.frequency)) { + MISC_HILOGE("Write frequency failed"); + return false; + } + if (!parcel.WriteInt32(parameter.reserved)) { + MISC_HILOGE("Write reserved failed"); + return false; + } + return true; +} + +CustomHapticInfoIPC* CustomHapticInfoIPC::Unmarshalling(Parcel &data) +{ + auto customHapticInfoIPC = new (std::nothrow) CustomHapticInfoIPC(); + if (customHapticInfoIPC == nullptr) { + MISC_HILOGE("Read init EffectInfoIPC failed"); + return nullptr; + } + if (!data.ReadInt32(customHapticInfoIPC->usage)) { + MISC_HILOGE("Read usage failed"); + customHapticInfoIPC = nullptr; + return customHapticInfoIPC; + } + if (!data.ReadBool(customHapticInfoIPC->systemUsage)) { + MISC_HILOGE("Read systemUsage failed"); + customHapticInfoIPC = nullptr; + return customHapticInfoIPC; + } + if (!data.ReadInt32(customHapticInfoIPC->parameter.intensity)) { + MISC_HILOGE("Read intensity failed"); + customHapticInfoIPC = nullptr; + return customHapticInfoIPC; + } + if (!data.ReadInt32(customHapticInfoIPC->parameter.frequency)) { + MISC_HILOGE("Read frequency failed"); + customHapticInfoIPC = nullptr; + return customHapticInfoIPC; + } + if (!data.ReadInt32(customHapticInfoIPC->parameter.reserved)) { + MISC_HILOGE("Read reserved failed"); + customHapticInfoIPC = nullptr; + return customHapticInfoIPC; + } + return customHapticInfoIPC; +} + +void CustomHapticInfoIPC::Dump() const +{ + std::string retStr; + retStr = "usage: "+ std::to_string(usage) + " "; + retStr += "systemUsage: " + std::to_string(systemUsage) + " "; + retStr += "parameter.intensity: " + std::to_string(parameter.intensity) + " "; + retStr += "parameter.intensity: " + std::to_string(parameter.frequency) + " "; + retStr += "parameter.intensity: " + std::to_string(parameter.reserved) + " "; + MISC_HILOGI("CustomHapticInfoIPC: [%{public}s]", retStr.c_str()); +} + +bool PrimitiveEffectIPC::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteInt32(intensity)) { + MISC_HILOGE("Write intensity failed"); + return false; + } + if (!parcel.WriteInt32(usage)) { + MISC_HILOGE("Write usage failed"); + return false; + } + if (!parcel.WriteBool(systemUsage)) { + MISC_HILOGE("Write systemUsage failed"); + return false; + } + if (!parcel.WriteInt32(count)) { + MISC_HILOGE("Write count failed"); + return false; + } + return true; +} + +PrimitiveEffectIPC* PrimitiveEffectIPC::Unmarshalling(Parcel &data) +{ + auto primitiveEffectIPC = new (std::nothrow) PrimitiveEffectIPC(); + if (primitiveEffectIPC == nullptr) { + MISC_HILOGE("Read init PrimitiveEffectIPC failed"); + return nullptr; + } + if (!data.ReadInt32(primitiveEffectIPC->intensity)) { + MISC_HILOGE("Read intensity failed"); + primitiveEffectIPC = nullptr; + return primitiveEffectIPC; + } + if (!data.ReadInt32(primitiveEffectIPC->usage)) { + MISC_HILOGE("Read usage failed"); + primitiveEffectIPC = nullptr; + return primitiveEffectIPC; + } + + if (!data.ReadBool(primitiveEffectIPC->systemUsage)) { + MISC_HILOGE("Read systemUsage failed"); + primitiveEffectIPC = nullptr; + return primitiveEffectIPC; + } + + if (!data.ReadInt32(primitiveEffectIPC->count)) { + MISC_HILOGE("Read count failed"); + primitiveEffectIPC = nullptr; + return primitiveEffectIPC; + } + return primitiveEffectIPC; +} + +void PrimitiveEffectIPC::Dump() const +{ + std::string retStr; + retStr = "intensity: "+ std::to_string(intensity) + " "; + retStr += "usage: " + std::to_string(usage) + " "; + retStr += "systemUsage: " + std::to_string(systemUsage) + " "; + retStr += "count: " + std::to_string(count) + " "; + MISC_HILOGI("PrimitiveEffectIPC: [%{public}s]", retStr.c_str()); +} + } // namespace Sensors } // namespace OHOS