From 6f7d1648fbb926fee45852f15f6553b51560742c Mon Sep 17 00:00:00 2001 From: lixiangpeng5 Date: Tue, 27 May 2025 22:20:10 +0800 Subject: [PATCH] vibrator code commit Signed-off-by: lixiangpeng5 --- .../vibrator/include/vibrator_napi_utils.h | 31 + .../js/napi/vibrator/src/vibrator_js.cpp | 374 ++++- .../napi/vibrator/src/vibrator_napi_utils.cpp | 230 +++ .../vibrator/all/IMiscdeviceService.idl | 29 +- .../vibrator/include/i_vibrator_client.h | 4 + .../vibrator/include/vibrator_client_proxy.h | 70 + .../vibrator/include/vibrator_client_stub.h | 3 + .../include/vibrator_service_client.h | 57 +- .../vibrator/part/IMiscdeviceService.idl | 27 +- .../vibrator/src/vibrator_client_stub.cpp | 59 +- .../vibrator/src/vibrator_service_client.cpp | 387 ++++- frameworks/native/vibrator/vibrator_agent.cpp | 262 +++- .../inner_api/vibrator/vibrator_agent.h | 222 +++ .../inner_api/vibrator/vibrator_agent_type.h | 105 ++ .../include/custom_vibration_matcher.h | 1 + .../src/custom_vibration_matcher.cpp | 18 +- .../adapter/include/compatible_connection.h | 35 +- .../adapter/include/hdi_connection.h | 38 +- .../adapter/include/vibrator_plug_callback.h | 40 + .../adapter/src/compatible_connection.cpp | 56 +- .../adapter/src/hdi_connection.cpp | 177 ++- .../adapter/src/vibrator_plug_callback.cpp | 38 + .../include/miscdevice_service.h | 96 +- .../include/vibration_priority_manager.h | 6 +- .../include/vibrator_thread.h | 25 +- test/fuzztest/vibrator/BUILD.gn | 15 + .../vibrator/cancelenhanced_fuzzer/BUILD.gn | 51 + .../cancelenhanced_fuzzer.cpp | 67 + .../cancelenhanced_fuzzer.h | 22 + .../cancelenhanced_fuzzer/corpus/init | 14 + .../cancelenhanced_fuzzer/project.xml | 25 + .../getdelaytimeenhanced_fuzzer/BUILD.gn | 56 + .../getdelaytimeenhanced_fuzzer/corpus/init | 14 + .../getdelaytimeenhanced_fuzzer.cpp | 101 ++ .../getdelaytimeenhanced_fuzzer.h | 21 + .../getdelaytimeenhanced_fuzzer/project.xml | 25 + .../vibrator/geteffectinfo_fuzzer/BUILD.gn | 49 + .../vibrator/geteffectinfo_fuzzer/corpus/init | 14 + .../geteffectinfo_fuzzer.cpp | 53 + .../geteffectinfo_fuzzer.h | 22 + .../vibrator/geteffectinfo_fuzzer/project.xml | 25 + .../getvibratoridlist_fuzzer/BUILD.gn | 49 + .../getvibratoridlist_fuzzer/corpus/init | 14 + .../getvibratoridlist_fuzzer.cpp | 50 + .../getvibratoridlist_fuzzer.h | 22 + .../getvibratoridlist_fuzzer/project.xml | 25 + .../playpatternenhanced_fuzzer/BUILD.gn | 56 + .../playpatternenhanced_fuzzer/corpus/init | 14 + .../playpatternenhanced_fuzzer.cpp | 96 ++ .../playpatternenhanced_fuzzer.h | 21 + .../playpatternenhanced_fuzzer/project.xml | 25 + .../BUILD.gn | 57 + .../corpus/init | 14 + .../playprimitiveeffectenhanced_fuzzer.cpp | 98 ++ .../playprimitiveeffectenhanced_fuzzer.h | 22 + .../project.xml | 25 + .../playvibratorcustom_fuzzer.h | 2 +- .../BUILD.gn | 51 + .../corpus/init | 14 + .../playvibratorcustomenhanced_fuzzer.cpp | 66 + .../playvibratorcustomenhanced_fuzzer.h | 22 + .../project.xml | 25 + .../setloopcountenhanced_fuzzer/BUILD.gn | 51 + .../setloopcountenhanced_fuzzer/corpus/init | 14 + .../setloopcountenhanced_fuzzer/project.xml | 25 + .../setloopcountenhanced_fuzzer.cpp | 70 + .../setloopcountenhanced_fuzzer.h | 22 + .../setparametersenhanced_fuzzer/BUILD.gn | 57 + .../setparametersenhanced_fuzzer/corpus/init | 14 + .../setparametersenhanced_fuzzer/project.xml | 25 + .../setparametersenhanced_fuzzer.cpp | 96 ++ .../setparametersenhanced_fuzzer.h | 21 + .../vibrator/setusageenhanced_fuzzer/BUILD.gn | 52 + .../setusageenhanced_fuzzer/corpus/init | 14 + .../setusageenhanced_fuzzer/project.xml | 25 + .../setusageenhanced_fuzzer.cpp | 70 + .../setusageenhanced_fuzzer.h | 22 + .../startvibratorenhanced_fuzzer/BUILD.gn | 51 + .../startvibratorenhanced_fuzzer/corpus/init | 14 + .../startvibratorenhanced_fuzzer/project.xml | 25 + .../startvibratorenhanced_fuzzer.cpp | 75 + .../startvibratorenhanced_fuzzer.h | 22 + .../startvibratoronceenhanced_fuzzer/BUILD.gn | 51 + .../corpus/init | 14 + .../project.xml | 25 + .../startvibratoronceenhanced_fuzzer.cpp | 71 + .../startvibratoronceenhanced_fuzzer.h | 22 + .../stopvibratorenhanced_fuzzer/BUILD.gn | 51 + .../stopvibratorenhanced_fuzzer/corpus/init | 14 + .../stopvibratorenhanced_fuzzer/project.xml | 25 + .../stopvibratorenhanced_fuzzer.cpp | 73 + .../stopvibratorenhanced_fuzzer.h | 22 + .../subscribevibrator_fuzzer/BUILD.gn | 49 + .../subscribevibrator_fuzzer/corpus/init | 14 + .../subscribevibrator_fuzzer/project.xml | 25 + .../unsubscribevibrator_fuzzer.cpp | 50 + .../unsubscribevibrator_fuzzer.h | 22 + .../unsubscribevibrator_fuzzer/BUILD.gn | 49 + .../unsubscribevibrator_fuzzer/corpus/init | 14 + .../unsubscribevibrator_fuzzer/project.xml | 25 + .../subscribevibrator_fuzzer.cpp | 50 + .../subscribevibrator_fuzzer.h | 22 + .../vibrator/js/VibratorPatternJsunit.test.js | 121 ++ .../vibrator/native/vibrator_agent_test.cpp | 1389 +++++++++++++++++ utils/common/include/miscdevice_common.h | 15 + utils/common/include/vibrator_infos.h | 50 +- utils/common/src/file_utils.cpp | 2 - utils/common/src/vibrator_infos.cpp | 281 ++++ 108 files changed, 6801 insertions(+), 242 deletions(-) create mode 100644 frameworks/native/vibrator/include/vibrator_client_proxy.h create mode 100644 services/miscdevice_service/hdi_connection/adapter/include/vibrator_plug_callback.h create mode 100644 services/miscdevice_service/hdi_connection/adapter/src/vibrator_plug_callback.cpp create mode 100644 test/fuzztest/vibrator/cancelenhanced_fuzzer/BUILD.gn create mode 100644 test/fuzztest/vibrator/cancelenhanced_fuzzer/cancelenhanced_fuzzer.cpp create mode 100644 test/fuzztest/vibrator/cancelenhanced_fuzzer/cancelenhanced_fuzzer.h create mode 100644 test/fuzztest/vibrator/cancelenhanced_fuzzer/corpus/init create mode 100644 test/fuzztest/vibrator/cancelenhanced_fuzzer/project.xml create mode 100644 test/fuzztest/vibrator/getdelaytimeenhanced_fuzzer/BUILD.gn create mode 100644 test/fuzztest/vibrator/getdelaytimeenhanced_fuzzer/corpus/init create mode 100644 test/fuzztest/vibrator/getdelaytimeenhanced_fuzzer/getdelaytimeenhanced_fuzzer.cpp create mode 100644 test/fuzztest/vibrator/getdelaytimeenhanced_fuzzer/getdelaytimeenhanced_fuzzer.h create mode 100644 test/fuzztest/vibrator/getdelaytimeenhanced_fuzzer/project.xml create mode 100644 test/fuzztest/vibrator/geteffectinfo_fuzzer/BUILD.gn create mode 100644 test/fuzztest/vibrator/geteffectinfo_fuzzer/corpus/init create mode 100644 test/fuzztest/vibrator/geteffectinfo_fuzzer/geteffectinfo_fuzzer.cpp create mode 100644 test/fuzztest/vibrator/geteffectinfo_fuzzer/geteffectinfo_fuzzer.h create mode 100644 test/fuzztest/vibrator/geteffectinfo_fuzzer/project.xml create mode 100644 test/fuzztest/vibrator/getvibratoridlist_fuzzer/BUILD.gn create mode 100644 test/fuzztest/vibrator/getvibratoridlist_fuzzer/corpus/init create mode 100644 test/fuzztest/vibrator/getvibratoridlist_fuzzer/getvibratoridlist_fuzzer.cpp create mode 100644 test/fuzztest/vibrator/getvibratoridlist_fuzzer/getvibratoridlist_fuzzer.h create mode 100644 test/fuzztest/vibrator/getvibratoridlist_fuzzer/project.xml create mode 100644 test/fuzztest/vibrator/playpatternenhanced_fuzzer/BUILD.gn create mode 100644 test/fuzztest/vibrator/playpatternenhanced_fuzzer/corpus/init create mode 100644 test/fuzztest/vibrator/playpatternenhanced_fuzzer/playpatternenhanced_fuzzer.cpp create mode 100644 test/fuzztest/vibrator/playpatternenhanced_fuzzer/playpatternenhanced_fuzzer.h create mode 100644 test/fuzztest/vibrator/playpatternenhanced_fuzzer/project.xml create mode 100644 test/fuzztest/vibrator/playprimitiveeffectenhanced_fuzzer/BUILD.gn create mode 100644 test/fuzztest/vibrator/playprimitiveeffectenhanced_fuzzer/corpus/init create mode 100644 test/fuzztest/vibrator/playprimitiveeffectenhanced_fuzzer/playprimitiveeffectenhanced_fuzzer.cpp create mode 100644 test/fuzztest/vibrator/playprimitiveeffectenhanced_fuzzer/playprimitiveeffectenhanced_fuzzer.h create mode 100644 test/fuzztest/vibrator/playprimitiveeffectenhanced_fuzzer/project.xml create mode 100644 test/fuzztest/vibrator/playvibratorcustomenhanced_fuzzer/BUILD.gn create mode 100644 test/fuzztest/vibrator/playvibratorcustomenhanced_fuzzer/corpus/init create mode 100644 test/fuzztest/vibrator/playvibratorcustomenhanced_fuzzer/playvibratorcustomenhanced_fuzzer.cpp create mode 100644 test/fuzztest/vibrator/playvibratorcustomenhanced_fuzzer/playvibratorcustomenhanced_fuzzer.h create mode 100644 test/fuzztest/vibrator/playvibratorcustomenhanced_fuzzer/project.xml create mode 100644 test/fuzztest/vibrator/setloopcountenhanced_fuzzer/BUILD.gn create mode 100644 test/fuzztest/vibrator/setloopcountenhanced_fuzzer/corpus/init create mode 100644 test/fuzztest/vibrator/setloopcountenhanced_fuzzer/project.xml create mode 100644 test/fuzztest/vibrator/setloopcountenhanced_fuzzer/setloopcountenhanced_fuzzer.cpp create mode 100644 test/fuzztest/vibrator/setloopcountenhanced_fuzzer/setloopcountenhanced_fuzzer.h create mode 100644 test/fuzztest/vibrator/setparametersenhanced_fuzzer/BUILD.gn create mode 100644 test/fuzztest/vibrator/setparametersenhanced_fuzzer/corpus/init create mode 100644 test/fuzztest/vibrator/setparametersenhanced_fuzzer/project.xml create mode 100644 test/fuzztest/vibrator/setparametersenhanced_fuzzer/setparametersenhanced_fuzzer.cpp create mode 100644 test/fuzztest/vibrator/setparametersenhanced_fuzzer/setparametersenhanced_fuzzer.h create mode 100644 test/fuzztest/vibrator/setusageenhanced_fuzzer/BUILD.gn create mode 100644 test/fuzztest/vibrator/setusageenhanced_fuzzer/corpus/init create mode 100644 test/fuzztest/vibrator/setusageenhanced_fuzzer/project.xml create mode 100644 test/fuzztest/vibrator/setusageenhanced_fuzzer/setusageenhanced_fuzzer.cpp create mode 100644 test/fuzztest/vibrator/setusageenhanced_fuzzer/setusageenhanced_fuzzer.h create mode 100644 test/fuzztest/vibrator/startvibratorenhanced_fuzzer/BUILD.gn create mode 100644 test/fuzztest/vibrator/startvibratorenhanced_fuzzer/corpus/init create mode 100644 test/fuzztest/vibrator/startvibratorenhanced_fuzzer/project.xml create mode 100644 test/fuzztest/vibrator/startvibratorenhanced_fuzzer/startvibratorenhanced_fuzzer.cpp create mode 100644 test/fuzztest/vibrator/startvibratorenhanced_fuzzer/startvibratorenhanced_fuzzer.h create mode 100644 test/fuzztest/vibrator/startvibratoronceenhanced_fuzzer/BUILD.gn create mode 100644 test/fuzztest/vibrator/startvibratoronceenhanced_fuzzer/corpus/init create mode 100644 test/fuzztest/vibrator/startvibratoronceenhanced_fuzzer/project.xml create mode 100644 test/fuzztest/vibrator/startvibratoronceenhanced_fuzzer/startvibratoronceenhanced_fuzzer.cpp create mode 100644 test/fuzztest/vibrator/startvibratoronceenhanced_fuzzer/startvibratoronceenhanced_fuzzer.h create mode 100644 test/fuzztest/vibrator/stopvibratorenhanced_fuzzer/BUILD.gn create mode 100644 test/fuzztest/vibrator/stopvibratorenhanced_fuzzer/corpus/init create mode 100644 test/fuzztest/vibrator/stopvibratorenhanced_fuzzer/project.xml create mode 100644 test/fuzztest/vibrator/stopvibratorenhanced_fuzzer/stopvibratorenhanced_fuzzer.cpp create mode 100644 test/fuzztest/vibrator/stopvibratorenhanced_fuzzer/stopvibratorenhanced_fuzzer.h create mode 100644 test/fuzztest/vibrator/subscribevibrator_fuzzer/BUILD.gn create mode 100644 test/fuzztest/vibrator/subscribevibrator_fuzzer/corpus/init create mode 100644 test/fuzztest/vibrator/subscribevibrator_fuzzer/project.xml create mode 100644 test/fuzztest/vibrator/subscribevibrator_fuzzer/unsubscribevibrator_fuzzer.cpp create mode 100644 test/fuzztest/vibrator/subscribevibrator_fuzzer/unsubscribevibrator_fuzzer.h create mode 100644 test/fuzztest/vibrator/unsubscribevibrator_fuzzer/BUILD.gn create mode 100644 test/fuzztest/vibrator/unsubscribevibrator_fuzzer/corpus/init create mode 100644 test/fuzztest/vibrator/unsubscribevibrator_fuzzer/project.xml create mode 100644 test/fuzztest/vibrator/unsubscribevibrator_fuzzer/subscribevibrator_fuzzer.cpp create mode 100644 test/fuzztest/vibrator/unsubscribevibrator_fuzzer/subscribevibrator_fuzzer.h diff --git a/frameworks/js/napi/vibrator/include/vibrator_napi_utils.h b/frameworks/js/napi/vibrator/include/vibrator_napi_utils.h index 3cb87e7..97ba787 100644 --- a/frameworks/js/napi/vibrator/include/vibrator_napi_utils.h +++ b/frameworks/js/napi/vibrator/include/vibrator_napi_utils.h @@ -19,6 +19,7 @@ #include #include #include +#include #include "napi/native_api.h" #include "napi/native_node_api.h" @@ -34,10 +35,19 @@ 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, + VIBRATOR_STATE_CHANGE, }; struct VibrateInfo { @@ -67,10 +77,15 @@ public: napi_env env = nullptr; napi_async_work asyncWork = nullptr; napi_deferred deferred = nullptr; + uv_work_t *work = nullptr; napi_ref callback[CALLBACK_NUM] = {0}; AsyncCallbackError error; CallbackType callbackType = COMMON_CALLBACK; bool isSupportEffect {false}; + std::vector vibratorInfos; + int32_t arrayLength; + EffectInfo effectInfo; + VibratorStatusEvent statusEvent; std::string flag; AsyncCallbackInfo(napi_env env) : env(env) {} ~AsyncCallbackInfo(); @@ -80,8 +95,13 @@ 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 CreateInt64Property(napi_env env, napi_value &eventObj, const char* name, int64_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 IsSameValue(const napi_env &env, const napi_value &lhs, const napi_value &rhs); bool GetNapiInt32(const napi_env &env, const int32_t value, napi_value &result); bool GetInt32Value(const napi_env &env, const napi_value &value, int32_t &result); bool GetDoubleValue(const napi_env &env, const napi_value &value, double &result); @@ -94,13 +114,24 @@ 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); +void EmitUvEventLoop(sptr asyncCallbackInfo); bool ClearVibratorPattern(VibratorPattern &vibratorPattern); +void DeleteWork(uv_work_t *work); +void ReleaseCallback(sptr asyncCallbackInfo); } // namespace Sensors } // namespace OHOS #endif // VIBRATOR_NAPI_UTILS_H \ No newline at end of file diff --git a/frameworks/js/napi/vibrator/src/vibrator_js.cpp b/frameworks/js/napi/vibrator/src/vibrator_js.cpp index 0273505..6c04596 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,297 @@ 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_status status = napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); + if (status != napi_ok) { + MISC_HILOGE("napi_get_cb_info get params failed"); + return 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; + status = napi_create_array(env, &jsArray); + if (status != napi_ok) { + MISC_HILOGE("napi_create_array failed"); + return jsArray; + } + std::vector vibratorInfo; + int32_t ret = GetVibratorList(identifier, vibratorInfo); + if (ret == SUCCESS) { + int32_t length = 0; + for (auto& info : vibratorInfo) { + napi_value jsInfo = ConvertToJsVibratorInfo(env, info); + status = napi_set_element(env, jsArray, length++, jsInfo); + if (status != napi_ok) { + MISC_HILOGE("napi construct JS result array failed"); + jsArray = nullptr; + break; + } + } + } + return jsArray; +} + +static napi_value GetSupportEffectInfoSync(napi_env env, napi_callback_info info) +{ + CALL_LOG_ENTER; + size_t argc = 2; + napi_value args[2] = {0}; + napi_status status = napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); + if (status != napi_ok) { + MISC_HILOGE("napi_get_cb_info get params failed"); + return nullptr; + } + if ((argc == 0) || !IsMatchType(env, args[0], napi_string)) { + MISC_HILOGW("Parameter error, expect string"); + return nullptr; + } + std::string effectType; + if(!GetStringValue(env, args[0], effectType)) { + MISC_HILOGE("GetStringValue fail"); + return nullptr; + } + 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); + } else { + jsEffectInfo = ConvertToJsEffectInfo(env, effectInfo); + } + return jsEffectInfo; +} + +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 false; + } + 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); + if (IsSubscribed(env, vibratorEvent, callback)) { + MISC_HILOGW("The callback has been subscribed"); + return; + } + 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; + } + g_onCallbackInfos[vibratorEvent].push_back(asyncCallbackInfo); +} + +static int32_t UpdatePlugInfo(VibratorStatusEvent *statusEvent, sptr &asyncCallbackInfo) +{ + CALL_LOG_ENTER; + MISC_HILOGD("statusEvent : [ type = %{public}d, deviceId = %{public}d]", statusEvent->type, statusEvent->deviceId); + CHKPR(statusEvent, PARAMETER_ERROR); + if (statusEvent->type == PLUG_STATE_EVENT_UNKNOWN) { + MISC_HILOGE("UpdatePlugInfo failed"); + return PARAMETER_ERROR; + } + asyncCallbackInfo->statusEvent.type = statusEvent->type; + asyncCallbackInfo->statusEvent.deviceId = statusEvent->deviceId; + asyncCallbackInfo->statusEvent.timestamp = statusEvent->timestamp; + asyncCallbackInfo->statusEvent.vibratorCnt = statusEvent->vibratorCnt; + MISC_HILOGD("asyncCallbackInfo->statusEvent : [ VibratorPlugState = %{public}d, deviceId = %{public}d]", + asyncCallbackInfo->statusEvent.type, asyncCallbackInfo->statusEvent.deviceId); + return SUCCESS; +} + +void DataCallbackImpl(VibratorStatusEvent *statusEvent) +{ + CALL_LOG_ENTER; + CHKPV(statusEvent); + 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(statusEvent, callback); + EmitUvEventLoop(callback); + } + } + } +} + +const VibratorUser user = { + .callback = DataCallbackImpl +}; + +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 = SubscribeVibratorPlug(user); + if (ret != ERR_OK) { + ThrowErr(env, ret, "SubscribeVibratorPlug 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 callbackInfos.size(); + } + g_onCallbackInfos[eventType] = callbackInfos; + return callbackInfos.size(); +} + +static int32_t RemoveCallback(napi_env env, std::string& eventType, napi_value callback) +{ + CALL_LOG_ENTER; + std::lock_guard onCallbackLock(g_Mutex); + std::vector> callbackInfos = g_onCallbackInfos[eventType]; + for (auto iter = callbackInfos.begin(); iter != callbackInfos.end();) { + CHKPC(*iter); + if ((*iter)->env != env) { + continue; + } + napi_value VibratorCallback = nullptr; + if (napi_get_reference_value(env, (*iter)->callback[0], &VibratorCallback) != napi_ok) { + MISC_HILOGE("napi_get_reference_value fail"); + continue; + } + if (IsSameValue(env, callback, VibratorCallback)) { + iter = callbackInfos.erase(iter); + MISC_HILOGD("Remove callback success"); + break; + } else { + ++iter; + } + } + if (callbackInfos.empty()) { + MISC_HILOGD("No subscription to change data"); + 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) { + ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail or number of parameter invalid"); + return nullptr; + } + if ((!IsMatchType(env, args[0], napi_string))) { + 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 (argc == 1 || !(IsMatchType(env, args[1], napi_function))) { + subscribeSize = RemoveAllCallback(env, eventType); + } else if (IsMatchType(env, args[1], napi_function)) { + subscribeSize = RemoveCallback(env, eventType, args[1]); + } + if (subscribeSize > 0) { + MISC_HILOGW("There are other client subscribe system js api as well, not need unsubscribe"); + return nullptr; + } + + int32_t ret = UnSubscribeVibratorPlug(user); + if (ret != ERR_OK) { + ThrowErr(env, ret, "User callback unsubscribe fail"); + return nullptr; + } + return nullptr; +} + static napi_value CreateEnumHapticFeedback(const napi_env env, napi_value exports) { napi_value effectSoft = nullptr; @@ -789,6 +1117,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("getVibratorInfoSync", GetVibratorListSync), + DECLARE_NAPI_FUNCTION("getEffectInfoSync", 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 bebac3d..aff20df 100644 --- a/frameworks/js/napi/vibrator/src/vibrator_napi_utils.cpp +++ b/frameworks/js/napi/vibrator/src/vibrator_napi_utils.cpp @@ -78,6 +78,54 @@ bool CreateInt32Property(napi_env env, napi_value &eventObj, const char* name, i return true; } +bool CreateInt64Property(napi_env env, napi_value &eventObj, const char* name, int64_t value) +{ + CALL_LOG_ENTER; + napi_value propValue = nullptr; + napi_status status = napi_create_int64(env, value, &propValue); + if (status != napi_ok) { + MISC_HILOGE("napi_create_int64 fail"); + return false; + } + CHKCF((napi_set_named_property(env, eventObj, name, propValue) == napi_ok), "napi_set_named_property fail"); + 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 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; +} + bool IsMatchArrayType(const napi_env &env, const napi_value &value) { bool result = false; @@ -258,6 +306,7 @@ 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}, + {VIBRATOR_STATE_CHANGE, ConstructVibratorPlugInfoResult}, }; bool ConvertErrorToResult(const napi_env &env, sptr asyncCallbackInfo, napi_value &result) @@ -304,6 +353,111 @@ 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, "isHdHapticSupported", 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, "isEffectSupported", effectInfo.isSupportEffect)) { + MISC_HILOGE("Create effectInfo.isSupportEffect failed"); + return jsObject; + } + return jsObject; +} + +napi_value ConvertToJsVibratorPlungInfo(const napi_env& env, const VibratorStatusEvent& statusEvent) { + CALL_LOG_ENTER; + MISC_HILOGD("statusEvent: [type = %{public}d, deviceId = %{public}d]", statusEvent.type, statusEvent.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 (statusEvent.type == PLUG_STATE_EVENT_PLUG_IN) { + plugFlag = true; + } else if (statusEvent.type == PLUG_STATE_EVENT_PLUG_OUT) { + plugFlag = false; + } + MISC_HILOGD("plugFlag = %{public}s", plugFlag? "true":"false"); + if (!CreateBooleanProperty(env, jsObject, "isVibratorOnline", plugFlag)) { + MISC_HILOGE("Create plugFlag failed"); + return jsObject; + } + if (!CreateInt32Property(env, jsObject, "deviceId", statusEvent.deviceId)) { + MISC_HILOGE("Create statusEvent.deviceId failed"); + return jsObject; + } + if (!CreateInt64Property(env, jsObject, "timestamp", statusEvent.timestamp)) { + MISC_HILOGE("Create statusEvent.timestamp failed"); + return jsObject; + } + if (!CreateInt32Property(env, jsObject, "vibratorCnt", statusEvent.vibratorCnt)) { + MISC_HILOGE("Create statusEvent.vibratorCnt failed"); + return jsObject; + } + + return jsObject; +} + +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->statusEvent); + 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); @@ -372,6 +526,82 @@ void ExecuteCallBack(napi_env env, void *data) } } +void EmitUvEventLoop(sptr asyncCallbackInfo) +{ + CHKPV(asyncCallbackInfo); + uv_loop_s *loop(nullptr); + CHKCV((napi_get_uv_event_loop(asyncCallbackInfo->env, &loop) == napi_ok), "napi_get_uv_event_loop fail"); + CHKPV(loop); + uv_work_t *work = new(std::nothrow) uv_work_t; + CHKPV(work); + asyncCallbackInfo->IncStrongRef(nullptr); + work->data = asyncCallbackInfo.GetRefPtr(); + int32_t ret = uv_queue_work_with_qos(loop, work, [] (uv_work_t *work) { }, [] (uv_work_t *work, int status) { + CHKPV(work); + sptr asyncCallbackInfo(static_cast(work->data)); + DeleteWork(work); + /** + * After the asynchronous task is created, the asyncCallbackInfo reference count is reduced + * to 0 destruction, so you need to add 1 to the asyncCallbackInfo reference count when the + * asynchronous task is created, and subtract 1 from the reference count after the naked + * pointer is converted to a pointer when the asynchronous task is executed, the reference + * count of the smart pointer is guaranteed to be 1. + */ + asyncCallbackInfo->DecStrongRef(nullptr); + napi_env env = asyncCallbackInfo->env; + napi_value callback = nullptr; + if (napi_get_reference_value(env, asyncCallbackInfo->callback[0], &callback) != napi_ok) { + MISC_HILOGE("napi_get_reference_value fail"); + napi_throw_error(env, nullptr, "napi_get_reference_value fail"); + ReleaseCallback(asyncCallbackInfo); + return; + } + napi_value callResult = nullptr; + napi_value result[RESULT_LENGTH] = {0}; + if (!(g_convertFuncList.find(asyncCallbackInfo->callbackType) != g_convertFuncList.end())) { + MISC_HILOGE("asyncCallbackInfo type is invalid"); + napi_throw_error(env, nullptr, "asyncCallbackInfo type is invalid"); + ReleaseCallback(asyncCallbackInfo); + return; + } + bool state = g_convertFuncList[asyncCallbackInfo->callbackType](env, asyncCallbackInfo, result, + sizeof(result) / sizeof(napi_value)); + CHKCV(state, "Create napi data fail in async work"); + if (napi_call_function(env, nullptr, callback, 2, result, &callResult) != napi_ok) { + MISC_HILOGE("napi_call_function callback fail"); + napi_throw_error(env, nullptr, "napi_call_function callback fail"); + ReleaseCallback(asyncCallbackInfo); + return; + } + ReleaseCallback(asyncCallbackInfo); + }, uv_qos_default); + if (ret != 0) { + MISC_HILOGE("uv_queue_work_with_qos fail"); + asyncCallbackInfo->DecStrongRef(nullptr); + DeleteWork(work); + } +} + +void DeleteWork(uv_work_t *work) +{ + CHKPV(work); + delete work; + work = nullptr; +} + +void ReleaseCallback(sptr asyncCallbackInfo) +{ + CHKPV(asyncCallbackInfo); + if (asyncCallbackInfo->callbackType == VIBRATOR_STATE_CHANGE) { + napi_env env = asyncCallbackInfo->env; + CHKPV(env); + napi_ref callback = asyncCallbackInfo->callback[0]; + if (callback != nullptr) { + napi_delete_reference(env, callback); + } + } +} + void EmitAsyncCallbackWork(sptr asyncCallbackInfo) { CALL_LOG_ENTER; diff --git a/frameworks/native/vibrator/all/IMiscdeviceService.idl b/frameworks/native/vibrator/all/IMiscdeviceService.idl index 2e2ceea..b842fc7 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 GetVibratorList([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 8c83ed0..a286e7c 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 = 0, + }; IVibratorClient() = default; virtual ~IVibratorClient() = default; + virtual int ProcessPlugEvent(int32_t eventCode, int32_t deviceId, int32_t vibratorCnt) = 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 0000000..d29ac97 --- /dev/null +++ b/frameworks/native/vibrator/include/vibrator_client_proxy.h @@ -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. + */ + +#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, int32_t vibratorCnt) 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; + } + if (!dataParcel.WriteInt32(vibratorCnt)) { + MISC_HILOGE("Failed to write vibratorCnt 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 1f55bbd..a5a8756 100644 --- a/frameworks/native/vibrator/include/vibrator_client_stub.h +++ b/frameworks/native/vibrator/include/vibrator_client_stub.h @@ -28,6 +28,9 @@ 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, int32_t vibratorCnt) override; +private: + int64_t GetSystemTime(); }; } // 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 9b5d1c5..524b6bc 100644 --- a/frameworks/native/vibrator/include/vibrator_service_client.h +++ b/frameworks/native/vibrator/include/vibrator_service_client.h @@ -17,7 +17,11 @@ #define VIBRATOR_SERVICE_CLIENT_H #include +#include #include +#include +#include +#include #include "iremote_object.h" #include "singleton.h" @@ -26,6 +30,7 @@ #include "miscdevice_service_proxy.h" #include "vibrator_agent_type.h" #include "vibrator_client_stub.h" +#include "miscdevice_common.h" namespace OHOS { namespace Sensors { @@ -54,35 +59,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(VibratorStatusEvent statusEvent); + 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 GetVibratorList(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 +110,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 2415e99..d2e9f6f 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 GetVibratorList([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 f6dc8c4..11ffec9 100644 --- a/frameworks/native/vibrator/src/vibrator_client_stub.cpp +++ b/frameworks/native/vibrator/src/vibrator_client_stub.cpp @@ -18,11 +18,16 @@ #include "message_parcel.h" #include "miscdevice_log.h" +#include "vibrator_service_client.h" #undef LOG_TAG #define LOG_TAG "VibratorClientStub" namespace OHOS { namespace Sensors { +namespace { + constexpr int32_t TIME_CONVERSION_UNIT { 1000 }; +} //unnamespace +using OHOS::Sensors::VibratorServiceClient; int32_t VibratorClientStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) @@ -33,7 +38,59 @@ 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; + int32_t vibratorCnt = 0; + if (!data.ReadInt32(eventCode)) { + MISC_HILOGE("Read eventCode failed."); + return PARAMETER_ERROR; + } + if (!data.ReadInt32(deviceId)) { + MISC_HILOGE("Read deviceId failed."); + return PARAMETER_ERROR; + } + if (!data.ReadInt32(vibratorCnt)) { + MISC_HILOGE("Read vibratorCnt failed."); + return PARAMETER_ERROR; + } + int result = ProcessPlugEvent(eventCode, deviceId, vibratorCnt); + reply.WriteInt32(result); + return NO_ERROR; + } + } + return NO_ERROR; +} + +int64_t VibratorClientStub::GetSystemTime() +{ + struct timespec ts = { 0, 0 }; + if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) { + MISC_HILOGE("clock_gettime failed:%{public}d", errno); + return 0; + } + return (ts.tv_sec * TIME_CONVERSION_UNIT * TIME_CONVERSION_UNIT) + (ts.tv_nsec / TIME_CONVERSION_UNIT); +} + +int VibratorClientStub::ProcessPlugEvent(int32_t eventCode, int32_t deviceId, int32_t vibratorCnt) +{ + MISC_HILOGD("Begin, eventCode=%{public}d, deviceId:%{public}d, vibratorCnt:%{public}d", + eventCode, deviceId, vibratorCnt); + VibratorStatusEvent statusEvent = { + .type = static_cast(eventCode), + .deviceId = deviceId, + .vibratorCnt = vibratorCnt, + .timestamp = GetSystemTime(), + }; + auto &client = VibratorServiceClient::GetInstance(); + bool ret = client.HandleVibratorData(statusEvent); + if (!ret) { + MISC_HILOGE("Handle bibrator data failed, ret:%{public}d", ret); + return DEVICE_OPERATION_FAILED; + } + 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 9252808..ae317c5 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::ERROR; + } + 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(VibratorStatusEvent statusEvent) __attribute__((no_sanitize("cfi"))) +{ + CALL_LOG_ENTER; + if(statusEvent.type == PLUG_STATE_EVENT_PLUG_OUT) { + std::lock_guard VibratorEffectLock(vibratorEffectMutex_); + for (auto it = vibratorEffectMap_.begin(); it != vibratorEffectMap_.end(); ) { + if (it->first.deviceId == statusEvent.deviceId) { + it = vibratorEffectMap_.erase(it); + } else { + ++it; + } + } + } + std::lock_guard subscribeLock(subscribeMutex_); + auto callbacks = GetSubscribeUserCallback(statusEvent.deviceId); + MISC_HILOGD("callbacks.size() = %{public}d", callbacks.size()); + MISC_HILOGD("VibratorStatusEvent = [type = %{public}d, deviceId = %{public}d]", statusEvent.type, statusEvent.deviceId); + for (const auto &callback : callbacks) { + MISC_HILOGD("callback is run"); + if(callback != nullptr) + callback(&statusEvent); + } + 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::GetVibratorList(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, "GetVibratorList"); +#endif // HIVIEWDFX_HITRACE_ENABLE + ret = miscdeviceProxy_->GetVibratorList(param, vibratorInfoList); + WriteOtherHiSysIPCEvent(IMiscdeviceServiceIpcCode::COMMAND_GET_VIBRATOR_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; + } + for (auto &info : vibratorInfoList) { + VibratorInfos resInfo; + 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_LIST: + HiSysEventWrite(HiSysEvent::Domain::MISCDEVICE, "MISC_SERVICE_IPC_EXCEPTION", + HiSysEvent::EventType::FAULT, "PKG_NAME", "GetVibratorList", "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 af47f7b..4546b05 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; @@ -58,24 +53,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 +99,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 +125,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 +163,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 +182,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 +198,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 +207,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 +227,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 +294,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 +314,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 +362,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 +378,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 GetVibratorList(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.GetVibratorList(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 SubscribeVibratorPlug(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("SubscribeVibratorPlug failed, ret:%{public}d", ret); + return NormalizeErrCode(ret); + } + return SUCCESS; +} + +int32_t UnSubscribeVibratorPlug(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 859d7ea..e816e0d 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 GetVibratorList(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 SubscribeVibratorPlug(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 UnSubscribeVibratorPlug(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 9c33672..5df43ea 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,102 @@ 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 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 = false; +} 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 VibratorStatusEvent { + VibratorPlugState type = PLUG_STATE_EVENT_UNKNOWN; + int32_t deviceId = 0; + int32_t vibratorCnt = 0; + int64_t timestamp = 0; +} VibratorStatusEvent; + +/** + * @brief Defines the callback for data reporting by the sensor agent. + * + * @since 18 + */ +typedef void (*RecordVibratorPlugCallback)(VibratorStatusEvent *statusEvent); + +/** + * @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; /** @} */ #ifdef __cplusplus }; 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 1df08ed..206d558 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 27967db..9de12ef 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 954c274..fea52bf 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 GetVibratorList(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 0c4426f..27e1dbc 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 GetVibratorList(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 0000000..463f4a3 --- /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 ebecb24..02eb826 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::GetVibratorList(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 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 6d22d80..2de9e16 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,11 @@ #endif // HIVIEWDFX_HISYSEVENT_ENABLE #include "sensors_errors.h" +#include "vibrator_plug_callback.h" + +#ifdef HDF_DRIVERS_INTERFACE_VIBRATOR +using OHOS::HDI::Vibrator::V2_0::DeviceVibratorInfo; +#endif // HDF_DRIVERS_INTERFACE_VIBRATOR #undef LOG_TAG #define LOG_TAG "HdiConnection" @@ -29,9 +34,11 @@ 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() { @@ -40,6 +47,9 @@ int32_t HdiConnection::ConnectHdi() 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 +65,14 @@ int32_t HdiConnection::ConnectHdi() return ERR_INVALID_VALUE; } -int32_t HdiConnection::StartOnce(uint32_t duration) +int32_t HdiConnection::StartOnce(const VibratorIdentifierIPC &identifier, uint32_t duration) { CHKPR(vibratorInterface_, ERR_INVALID_VALUE); - int32_t ret = vibratorInterface_->StartOnce(duration); + DeviceVibratorInfo deviceVibratorInfo = { + .deviceId = identifier.deviceId, + .vibratorId = identifier.vibratorId + }; + int32_t ret = vibratorInterface_->StartOnce(deviceVibratorInfo, duration); if (ret < 0) { #ifdef HIVIEWDFX_HISYSEVENT_ENABLE HiSysEventWrite(HiSysEvent::Domain::MISCDEVICE, "VIBRATOR_HDF_SERVICE_EXCEPTION", @@ -70,7 +84,7 @@ int32_t HdiConnection::StartOnce(uint32_t duration) return ERR_OK; } -int32_t HdiConnection::Start(const std::string &effectType) +int32_t HdiConnection::Start(const VibratorIdentifierIPC &identifier, const std::string &effectType) { MISC_HILOGD("Time delay measurement:end time"); if (effectType.empty()) { @@ -78,7 +92,11 @@ int32_t HdiConnection::Start(const std::string &effectType) return VIBRATOR_ON_ERR; } CHKPR(vibratorInterface_, ERR_INVALID_VALUE); - int32_t ret = vibratorInterface_->Start(effectType); + DeviceVibratorInfo deviceVibratorInfo = { + .deviceId = identifier.deviceId, + .vibratorId = identifier.vibratorId + }; + int32_t ret = vibratorInterface_->Start(deviceVibratorInfo, effectType); if (ret < 0) { #ifdef HIVIEWDFX_HISYSEVENT_ENABLE HiSysEventWrite(HiSysEvent::Domain::MISCDEVICE, "VIBRATOR_HDF_SERVICE_EXCEPTION", @@ -91,7 +109,7 @@ 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 &identifier, const HdfCompositeEffect &hdfCompositeEffect) { MISC_HILOGD("Time delay measurement:end time"); if (hdfCompositeEffect.compositeEffects.empty()) { @@ -99,7 +117,11 @@ int32_t HdiConnection::EnableCompositeEffect(const HdfCompositeEffect &hdfCompos return VIBRATOR_ON_ERR; } CHKPR(vibratorInterface_, ERR_INVALID_VALUE); - int32_t ret = vibratorInterface_->EnableCompositeEffect(hdfCompositeEffect); + DeviceVibratorInfo deviceVibratorInfo = { + .deviceId = identifier.deviceId, + .vibratorId = identifier.vibratorId + }; + int32_t ret = vibratorInterface_->EnableCompositeEffect(deviceVibratorInfo, hdfCompositeEffect); if (ret < 0) { #ifdef HIVIEWDFX_HISYSEVENT_ENABLE HiSysEventWrite(HiSysEvent::Domain::MISCDEVICE, "VIBRATOR_HDF_SERVICE_EXCEPTION", @@ -111,23 +133,31 @@ int32_t HdiConnection::EnableCompositeEffect(const HdfCompositeEffect &hdfCompos return ERR_OK; } -bool HdiConnection::IsVibratorRunning() +bool HdiConnection::IsVibratorRunning(const VibratorIdentifierIPC &identifier) { bool state = false; CHKPR(vibratorInterface_, false); - vibratorInterface_->IsVibratorRunning(state); + DeviceVibratorInfo deviceVibratorInfo = { + .deviceId = identifier.deviceId, + .vibratorId = identifier.vibratorId + }; + vibratorInterface_->IsVibratorRunning(deviceVibratorInfo, state); return state; } #endif // OHOS_BUILD_ENABLE_VIBRATOR_CUSTOM -std::optional HdiConnection::GetEffectInfo(const std::string &effect) +std::optional HdiConnection::GetEffectInfo(const VibratorIdentifierIPC &identifier, const std::string &effect) { if (vibratorInterface_ == nullptr) { MISC_HILOGE("Connect v1_1 hdi failed"); return std::nullopt; } + DeviceVibratorInfo deviceVibratorInfo = { + .deviceId = identifier.deviceId, + .vibratorId = identifier.vibratorId + }; HdfEffectInfo effectInfo; - int32_t ret = vibratorInterface_->GetEffectInfo(effect, effectInfo); + int32_t ret = vibratorInterface_->GetEffectInfo(deviceVibratorInfo, effect, effectInfo); if (ret < 0) { #ifdef HIVIEWDFX_HISYSEVENT_ENABLE HiSysEventWrite(HiSysEvent::Domain::MISCDEVICE, "VIBRATOR_HDF_SERVICE_EXCEPTION", @@ -139,10 +169,14 @@ std::optional HdiConnection::GetEffectInfo(const std::string &eff return effectInfo; } -int32_t HdiConnection::Stop(HdfVibratorModeV1_2 mode) +int32_t HdiConnection::Stop(const VibratorIdentifierIPC &identifier, HdfVibratorMode mode) { CHKPR(vibratorInterface_, ERR_INVALID_VALUE); - int32_t ret = vibratorInterface_->StopV1_2(mode); + DeviceVibratorInfo deviceVibratorInfo = { + .deviceId = identifier.deviceId, + .vibratorId = identifier.vibratorId + }; + int32_t ret = vibratorInterface_->Stop(deviceVibratorInfo, mode); if (ret < 0) { #ifdef HIVIEWDFX_HISYSEVENT_ENABLE HiSysEventWrite(HiSysEvent::Domain::MISCDEVICE, "VIBRATOR_HDF_SERVICE_EXCEPTION", @@ -154,10 +188,14 @@ 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 &identifier, int32_t mode, int32_t &delayTime) { CHKPR(vibratorInterface_, ERR_INVALID_VALUE); - int32_t ret = vibratorInterface_->GetHapticStartUpTime(mode, delayTime); + DeviceVibratorInfo deviceVibratorInfo = { + .deviceId = identifier.deviceId, + .vibratorId = identifier.vibratorId + }; + int32_t ret = vibratorInterface_->GetHapticStartUpTime(deviceVibratorInfo, mode, delayTime); if (ret < 0) { #ifdef HIVIEWDFX_HISYSEVENT_ENABLE HiSysEventWrite(HiSysEvent::Domain::MISCDEVICE, "VIBRATOR_HDF_SERVICE_EXCEPTION", @@ -169,11 +207,15 @@ 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 &identifier, VibratorCapacity &capacity) { CHKPR(vibratorInterface_, ERR_INVALID_VALUE); HapticCapacity hapticCapacity; - int32_t ret = vibratorInterface_->GetHapticCapacity(hapticCapacity); + DeviceVibratorInfo deviceVibratorInfo = { + .deviceId = identifier.deviceId, + .vibratorId = identifier.vibratorId + }; + int32_t ret = vibratorInterface_->GetHapticCapacity(deviceVibratorInfo, hapticCapacity); if (ret < 0) { #ifdef HIVIEWDFX_HISYSEVENT_ENABLE HiSysEventWrite(HiSysEvent::Domain::MISCDEVICE, "VIBRATOR_HDF_SERVICE_EXCEPTION", @@ -189,7 +231,7 @@ int32_t HdiConnection::GetVibratorCapacity(VibratorCapacity &capacity) return ERR_OK; } -int32_t HdiConnection::PlayPattern(const VibratePattern &pattern) +int32_t HdiConnection::PlayPattern(const VibratorIdentifierIPC &identifier, const VibratePattern &pattern) { CHKPR(vibratorInterface_, ERR_INVALID_VALUE); HapticPaket packet = {}; @@ -215,7 +257,11 @@ int32_t HdiConnection::PlayPattern(const VibratePattern &pattern) } packet.events.emplace_back(hapticEvent); } - int32_t ret = vibratorInterface_->PlayHapticPattern(packet); + DeviceVibratorInfo deviceVibratorInfo = { + .deviceId = identifier.deviceId, + .vibratorId = identifier.vibratorId + }; + int32_t ret = vibratorInterface_->PlayHapticPattern(deviceVibratorInfo, packet); if (ret < 0) { #ifdef HIVIEWDFX_HISYSEVENT_ENABLE HiSysEventWrite(HiSysEvent::Domain::MISCDEVICE, "VIBRATOR_HDF_SERVICE_EXCEPTION", @@ -229,6 +275,18 @@ 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; } @@ -281,7 +339,8 @@ void HdiConnection::Reconnect() } } -int32_t HdiConnection::StartByIntensity(const std::string &effect, int32_t intensity) +int32_t HdiConnection::StartByIntensity(const VibratorIdentifierIPC &identifier, 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()) { @@ -289,7 +348,11 @@ int32_t HdiConnection::StartByIntensity(const std::string &effect, int32_t inten return VIBRATOR_ON_ERR; } CHKPR(vibratorInterface_, ERR_INVALID_VALUE); - int32_t ret = vibratorInterface_->StartByIntensity(effect, intensity); + DeviceVibratorInfo deviceVibratorInfo = { + .deviceId = identifier.deviceId, + .vibratorId = identifier.vibratorId + }; + int32_t ret = vibratorInterface_->StartByIntensity(deviceVibratorInfo, effect, intensity); if (ret < 0) { #ifdef HIVIEWDFX_HISYSEVENT_ENABLE HiSysEventWrite(HiSysEvent::Domain::MISCDEVICE, "VIBRATOR_HDF_SERVICE_EXCEPTION", @@ -301,16 +364,84 @@ 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 vibratorId = 1; - int32_t ret = vibratorInterface_->GetAllWaveInfo(vibratorId, waveInfos); + int32_t ret = vibratorInterface_->GetVibratorInfo(hdfVibratorInfo); + if (ret != ERR_OK) { + MISC_HILOGE("GetVibratorInfo failed"); + } + return ret; +} + +int32_t HdiConnection::GetAllWaveInfo(const VibratorIdentifierIPC &identifier, std::vector &waveInfos) +{ + CHKPR(vibratorInterface_, ERR_INVALID_VALUE); + DeviceVibratorInfo deviceVibratorInfo = { + .deviceId = identifier.deviceId, + .vibratorId = identifier.vibratorId + }; + int32_t ret = vibratorInterface_->GetAllWaveInfo(deviceVibratorInfo, waveInfos); if (ret != ERR_OK) { MISC_HILOGE("GetAllWaveInfo failed"); } return ret; } +int32_t HdiConnection::GetVibratorList(const VibratorIdentifierIPC &identifier, + std::vector &vibratorInfo) +{ + CHKPR(vibratorInterface_, ERR_INVALID_VALUE); + DeviceVibratorInfo deviceVibratorInfo = { + .deviceId = identifier.deviceId, + .vibratorId = identifier.vibratorId + }; + int32_t ret = vibratorInterface_->GetDeviceVibratorInfo(deviceVibratorInfo, vibratorInfo); + if (ret != ERR_OK) { + MISC_HILOGE("GetVibratorList failed"); + } + return ret; +} + +int32_t HdiConnection::GetEffectInfo(const VibratorIdentifierIPC &identifier, const std::string &effectType, + HdfEffectInfo &effectInfo) +{ + CHKPR(vibratorInterface_, ERR_INVALID_VALUE); + DeviceVibratorInfo deviceVibratorInfo = { + .deviceId = identifier.deviceId, + .vibratorId = identifier.vibratorId + }; + int32_t ret = vibratorInterface_->GetEffectInfo(deviceVibratorInfo, effectType, effectInfo); + if (ret != ERR_OK) { + MISC_HILOGE("GetVibratorList 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); + 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; + } + return ERR_OK; +} + +DevicePlugCallback HdiConnection::GetVibratorPlugCb() +{ + if (devicePlugCb_ == nullptr) { + MISC_HILOGE("GetVibratorPlugCb cannot be null"); + } + return devicePlugCb_; +} } // namespace Sensors } // namespace OHOS 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 0000000..52c9c20 --- /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/include/miscdevice_service.h b/services/miscdevice_service/include/miscdevice_service.h index c73c4ad..e73af9f 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& vibratorIds) : motorCount(static_cast(vibratorIds.size())) { + for (int motorId : vibratorIds) { + 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& vibratorIds) : controlInfo(vibratorIds) {} +}; + class MiscdeviceService : public SystemAbility, public MiscdeviceServiceStub { DECLARE_SYSTEM_ABILITY(MiscdeviceService) MISCDEVICE_DECLARE_DELAYED_SP_SINGLETON(MiscdeviceService); @@ -49,26 +76,33 @@ 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 GetVibratorList(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); @@ -76,12 +110,15 @@ private: bool InitLightInterface(); std::string GetPackageName(AccessTokenID tokenId); #ifdef OHOS_BUILD_ENABLE_VIBRATOR_PRESET_INFO - int32_t FastVibratorEffect(const VibrateInfo &info); + int32_t FastVibratorEffect(const VibrateInfo &info, const VibratorIdentifierIPC& identifier); #endif // OHOS_BUILD_ENABLE_VIBRATOR_PRESET_INFO - void StartVibrateThread(VibrateInfo info); - int32_t StopVibratorService(int32_t vibratorId); - void StopVibrateThread(); - bool ShouldIgnoreVibrate(const VibrateInfo &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); @@ -96,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 GetLocalVibratorInfo(); + 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(); @@ -109,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 106c251..ebe6f36 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 14d5c02..a62c492 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/test/fuzztest/vibrator/BUILD.gn b/test/fuzztest/vibrator/BUILD.gn index e6d9a79..cd10c8d 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 0000000..d2319cd --- /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 0000000..803ccb2 --- /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 0000000..5b826f8 --- /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 0000000..e010f58 --- /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 0000000..2eb360c --- /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 0000000..6fbc3eb --- /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 0000000..e010f58 --- /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 0000000..185e615 --- /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 0000000..4b97f10 --- /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 0000000..f2c5980 --- /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 0000000..3d6084d --- /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 0000000..c49c21a --- /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 0000000..890b176 --- /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 0000000..d05fca9 --- /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 0000000..20dc766 --- /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 0000000..53ac34d --- /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 0000000..c49c21a --- /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 0000000..d8be84e --- /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::GetVibratorList(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 0000000..e081544 --- /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 0000000..20dc766 --- /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 0000000..551f3d8 --- /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 0000000..65af8ee --- /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 0000000..811a568 --- /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 0000000..1d71ce9 --- /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 0000000..2eb360c --- /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 0000000..6c42ae1 --- /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 0000000..e010f58 --- /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 0000000..bcc88dd --- /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 0000000..5b45c09 --- /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 0000000..f2c5980 --- /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 b190853..94f4639 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 0000000..a3d009f --- /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 0000000..e010f58 --- /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 0000000..60aad9e --- /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 0000000..e95e6f3 --- /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 0000000..2eb360c --- /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 0000000..9c99b00 --- /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 0000000..65af8ee --- /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 0000000..2eb360c --- /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 0000000..2b7af74 --- /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 0000000..7d1de1a --- /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 0000000..a95d6ee --- /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 0000000..65af8ee --- /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 0000000..2eb360c --- /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 0000000..188276c --- /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 0000000..d5ec47c --- /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 0000000..41433d7 --- /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 0000000..65af8ee --- /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 0000000..2eb360c --- /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 0000000..f71acd9 --- /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 0000000..6c50197 --- /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 0000000..1f86dea --- /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 0000000..e010f58 --- /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 0000000..2eb360c --- /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 0000000..a1b6c51 --- /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 0000000..e224624 --- /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 0000000..1e13ead --- /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 0000000..e010f58 --- /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 0000000..2eb360c --- /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 0000000..bf4d3bf --- /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 0000000..fb402ed --- /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 0000000..8a8b2c8 --- /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 0000000..e010f58 --- /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 0000000..2eb360c --- /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 0000000..899bfd9 --- /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 0000000..b151183 --- /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 0000000..938d643 --- /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 0000000..c49c21a --- /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 0000000..20dc766 --- /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 0000000..04f53ec --- /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(VibratorStatusEvent *statusEvent){ + return; +} + +bool UnSubscribeVibratorFuzzTest(const uint8_t *data, size_t size) +{ + VibratorUser user = { + .callback = CallbackTest, + .userData = nullptr, + }; + int32_t ret = OHOS::Sensors::UnSubscribeVibratorPlug(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 0000000..ec087a6 --- /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 0000000..374374b --- /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 0000000..c49c21a --- /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 0000000..20dc766 --- /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 0000000..83c1e70 --- /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(VibratorStatusEvent *statusEvent){ + return; +} + +bool SubscribeVibratorFuzzTest(const uint8_t *data, size_t size) +{ + VibratorUser user = { + .callback = CallbackTest, + .userData = nullptr, + }; + int32_t ret = OHOS::Sensors::SubscribeVibratorPlug(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 0000000..f30d5f6 --- /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 16e2472..a3360a7 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 (statusEvent) { + console.info('Valid callback executed with statusEvent:', statusEvent); + expect(statusEvent).toBeDefined(); + expect(typeof statusEvent).toBe('object'); + }; + on("VibratorStateChange", 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 = "VibratorStateChange"; + 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 9c735de..09043b2 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 = GetVibratorList(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 = GetVibratorList(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 = GetVibratorList(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 = GetVibratorList(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 = GetVibratorList(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 = SubscribeVibratorPlug(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 = SubscribeVibratorPlug(invalidUser); + ASSERT_EQ(ret, OHOS::Sensors::ERROR); +} + +HWTEST_F(VibratorAgentTest, UnSubscribeVibrator_001, TestSize.Level1) +{ + MISC_HILOGI("UnSubscribeVibrator_001 in"); + int32_t ret = UnSubscribeVibratorPlug(testUser); + ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); + ret = UnSubscribeVibratorPlug(testUser); + ASSERT_EQ(ret, OHOS::Sensors::CALLBACK_UNSUBSCRIBED); +} } // namespace Sensors } // namespace OHOS diff --git a/utils/common/include/miscdevice_common.h b/utils/common/include/miscdevice_common.h index 9f69777..b3a8e6d 100755 --- a/utils/common/include/miscdevice_common.h +++ b/utils/common/include/miscdevice_common.h @@ -15,9 +15,24 @@ #ifndef MISCDEVICE_COMMON_H #define MISCDEVICE_COMMON_H +#include "vibrator_agent_type.h" namespace OHOS { namespace Sensors { +typedef struct VibratorEffectParameter { + int32_t loopCount = 1; + int32_t usage = USAGE_UNKNOWN; + bool systemUsage = false; + VibratorParameter vibratorParameter; +} VibratorEffectParameter; + +typedef struct PrimitiveEffect { + int32_t intensity = 0; + int32_t usage = 0; + bool systemUsage; + int32_t count = 0; +} PrimitiveEffect; + // These LightId correspond to logical lights enum LightId { LIGHT_ID_LED = 0, diff --git a/utils/common/include/vibrator_infos.h b/utils/common/include/vibrator_infos.h index 140d3c2..66086da 100644 --- a/utils/common/include/vibrator_infos.h +++ b/utils/common/include/vibrator_infos.h @@ -128,13 +128,59 @@ 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/file_utils.cpp b/utils/common/src/file_utils.cpp index 78419ef..26400bf 100755 --- a/utils/common/src/file_utils.cpp +++ b/utils/common/src/file_utils.cpp @@ -187,12 +187,10 @@ std::string ReadFd(const RawFileDescriptor &rawFd) int64_t fdSize = GetFileSize(rawFd.fd); if ((rawFd.offset < 0) || (rawFd.offset > fdSize)) { MISC_HILOGE("offset is invalid, offset:%{public}" PRId64, rawFd.offset); - close(rawFd.fd); return {}; } if ((rawFd.length <= 0) || (rawFd.length > fdSize - rawFd.offset)) { MISC_HILOGE("length is invalid, length:%{public}" PRId64, rawFd.length); - close(rawFd.fd); return {}; } FILE *fp = fdopen(rawFd.fd, "r"); diff --git a/utils/common/src/vibrator_infos.cpp b/utils/common/src/vibrator_infos.cpp index e393932..fa2b9f2 100644 --- a/utils/common/src/vibrator_infos.cpp +++ b/utils/common/src/vibrator_infos.cpp @@ -235,6 +235,112 @@ VibratePattern* VibratePattern::Unmarshalling(Parcel &data) return pattern; } +bool VibratorInfoIPC::Marshalling(Parcel &parcel) const +{ + 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; +} + +VibratorInfoIPC* VibratorInfoIPC::Unmarshalling(Parcel &data) +{ + 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(vibratorId)) { + MISC_HILOGE("Write parameter's vibratorId failed"); + return false; + } + return true; +} + +VibratorIdentifierIPC* VibratorIdentifierIPC::Unmarshalling(Parcel &data) +{ + auto identifier = new (std::nothrow) VibratorIdentifierIPC(); + if (identifier == nullptr) { + MISC_HILOGE("Read init parameter failed"); + return 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; +} + void VibrateParameter::Dump() const { MISC_HILOGI("intensity:%{public}d, frequency:%{public}d", intensity, frequency); @@ -267,5 +373,180 @@ VibrateParameter* VibrateParameter::Unmarshalling(Parcel &data) } return parameter; } + +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 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 -- Gitee