diff --git a/bundle.json b/bundle.json index f1ff2dadd5f624ede2226bc80cdca2fe6092c438..f3ffe280a01a343a19116b42f65e5ca0faf94e70 100644 --- a/bundle.json +++ b/bundle.json @@ -27,7 +27,6 @@ "ability_base", "ability_runtime", "access_token", - "bounds_checking_function", "bundle_framework", "common_event_service", "c_utils", @@ -39,7 +38,6 @@ "hitrace", "ipc", "init", - "json", "memmgr", "napi", "os_account", diff --git a/frameworks/js/ani/vibrator/include/ani_utils.h b/frameworks/js/ani/vibrator/include/ani_utils.h index 663a794dbe6a1477a0f09e0c0bb4c60fd6fb9d3d..807c874bc937f7ec89bf44be3402efaabce6d8e9 100644 --- a/frameworks/js/ani/vibrator/include/ani_utils.h +++ b/frameworks/js/ani/vibrator/include/ani_utils.h @@ -176,7 +176,12 @@ bool UnionAccessor::TryConvertArray(std::vector &value) std::cerr << "Object_GetPropertyByName_Double length failed" << std::endl; return false; } - for (int i = 0; i < int(length); i++) { + int64_t lengthValue = static_cast(length); + if (lengthValue < 0 || lengthValue > INT64_MAX) { + std::cerr << "Invalid length" << std::endl; + return false; + } + for (int64_t i = 0; i < lengthValue; i++) { ani_ref ref; if (ANI_OK != env_->Object_CallMethodByName_Ref(obj_, "$_get", "I:Lstd/core/Object;", &ref, (ani_int)i)) { std::cerr << "Object_GetPropertyByName_Ref failed" << std::endl; @@ -200,7 +205,12 @@ bool UnionAccessor::TryConvertArray(std::vector &value) std::cerr << "Object_GetPropertyByName_Double length failed" << std::endl; return false; } - for (int i = 0; i < int(length); i++) { + int64_t lengthValue = static_cast(length); + if (lengthValue < 0 || lengthValue > INT64_MAX) { + std::cerr << "Invalid length" << std::endl; + return false; + } + for (int64_t i = 0; i < lengthValue; i++) { ani_ref ref; if (ANI_OK != env_->Object_CallMethodByName_Ref(obj_, "$_get", "I:Lstd/core/Object;", &ref, (ani_int)i)) { std::cerr << "Object_GetPropertyByName_Ref failed" << std::endl; @@ -224,7 +234,12 @@ bool UnionAccessor::TryConvertArray(std::vector &value) std::cerr << "Object_GetPropertyByName_Double length failed" << std::endl; return false; } - for (int i = 0; i < int(length); i++) { + int64_t lengthValue = static_cast(length); + if (lengthValue < 0 || lengthValue > INT64_MAX) { + std::cerr << "Invalid length" << std::endl; + return false; + } + for (int64_t i = 0; i < lengthValue; i++) { ani_ref ref; if (ANI_OK != env_->Object_CallMethodByName_Ref(obj_, "$_get", "I:Lstd/core/Object;", &ref, (ani_int)i)) { std::cerr << "Object_GetPropertyByName_Ref failed" << std::endl; @@ -270,8 +285,12 @@ bool UnionAccessor::TryConvertArray(std::vector &value std::cerr << "Object_GetPropertyByName_Double length failed" << std::endl; return false; } - - for (int i = 0; i < int(length); i++) { + int64_t lengthValue = static_cast(length); + if (lengthValue < 0 || lengthValue > INT64_MAX) { + std::cerr << "Invalid length" << std::endl; + return false; + } + for (int64_t i = 0; i < lengthValue; i++) { ani_ref ref; if (ANI_OK != env_->Object_CallMethodByName_Ref(obj_, "$_get", "I:Lstd/core/Object;", &ref, (ani_int)i)) { std::cerr << "Object_GetPropertyByName_Double length failed" << std::endl; @@ -327,7 +346,10 @@ std::optional OptionalAccessor::Convert() } ani_size strSize; - env_->String_GetUTF8Size(static_cast(obj_), &strSize); + auto status = env_->String_GetUTF8Size(static_cast(obj_), &strSize); + if (status != ANI_OK) { + return std::nullopt; + } std::vector buffer(strSize + 1); char* utf8_buffer = buffer.data(); diff --git a/frameworks/js/ani/vibrator/src/vibrator_ani.cpp b/frameworks/js/ani/vibrator/src/vibrator_ani.cpp index 47870c33098854fe03690687479fb0e12832642a..3686e63eda2f2667bc205478bc549c1ee3876b76 100644 --- a/frameworks/js/ani/vibrator/src/vibrator_ani.cpp +++ b/frameworks/js/ani/vibrator/src/vibrator_ani.cpp @@ -22,7 +22,6 @@ #include #include "miscdevice_log.h" #include "vibrator_agent.h" -#include #undef LOG_TAG #define LOG_TAG "VibratorAni" @@ -106,7 +105,6 @@ static void ThrowBusinessError(ani_env *env, int errCode, std::string&& errMsg) return; } env->ThrowError(static_cast(errorObject)); - return; } static bool ParserParamFromVibrateTime(ani_env *env, ani_object effect, VibrateInfo &vibrateInfo) @@ -125,7 +123,7 @@ static bool ParserParamFromVibrateTime(ani_env *env, ani_object effect, VibrateI MISC_HILOGE("Failed to get property named duration"); return false; } - vibrateInfo.duration = static_cast(duration); + vibrateInfo.duration = static_cast(duration); MISC_HILOGD("vibrateInfo.duration: %{public}d", vibrateInfo.duration); return true; } @@ -153,8 +151,6 @@ static bool SetVibrateProperty(ani_env* env, ani_object effect, const char* prop } propertyValue = static_cast(result); - MISC_HILOGD("\"%{public}s\": %{public}d", propertyName, propertyValue); - return true; } @@ -213,7 +209,7 @@ static bool SetVibratePropertyInt64(ani_env* env, ani_object effect, const char* } propertyValue = static_cast(result); - MISC_HILOGD("\"%{public}s\": %{public}" PRId64, propertyName, propertyValue); + MISC_HILOGD("\"%{public}s\": %{public}lld", propertyName, propertyValue); return true; } @@ -239,19 +235,19 @@ static bool ParserParamFromVibrateFromFile(ani_env *env, ani_object effect, Vibr MISC_HILOGE("Failed to get property named fd"); return false; } - vibrateInfo.fd = static_cast(fd); + vibrateInfo.fd = static_cast(fd); MISC_HILOGD("vibrateInfo.type: %{public}s, vibrateInfo.fd: %{public}d", typeStr.c_str(), vibrateInfo.fd); SetVibratePropertyInt64(env, static_cast(hapticFd), "offset", vibrateInfo.offset); - MISC_HILOGD("vibrateInfo.offset: %{public}" PRId64, vibrateInfo.offset); + MISC_HILOGD("vibrateInfo.offset: %{public}lld", vibrateInfo.offset); int64_t fdSize = GetFileSize(vibrateInfo.fd); - if (!(vibrateInfo.offset >= 0) && (vibrateInfo.offset <= fdSize)) { + if ((vibrateInfo.offset < 0) || (vibrateInfo.offset > fdSize)) { MISC_HILOGE("The parameter of offset is invalid"); return false; } vibrateInfo.length = fdSize - vibrateInfo.offset; SetVibratePropertyInt64(env, static_cast(hapticFd), "length", vibrateInfo.length); - MISC_HILOGD("vibrateInfo.length: %{public}" PRId64, vibrateInfo.length); + MISC_HILOGD("vibrateInfo.length: %{public}lld", vibrateInfo.length); return true; } @@ -306,19 +302,19 @@ static bool GetPropertyAsDouble(ani_env* env, ani_object obj, const char* proper ani_boolean isUndefined = false; if (env->Object_GetPropertyByName_Ref(obj, propertyName, &propRef) != ANI_OK) { - MISC_HILOGE("GetPropertyAsDouble: Failed to get property '%{punlic}s'", propertyName); + MISC_HILOGE("GetPropertyAsDouble: Failed to get property:%{public}s", propertyName); return false; } env->Reference_IsUndefined(propRef, &isUndefined); if (isUndefined) { - MISC_HILOGE("GetPropertyAsDouble: Property '%{punlic}s' is undefined", propertyName); + MISC_HILOGE("GetPropertyAsDouble: Property:%{public}s is undefined", propertyName); return false; } if (env->Object_CallMethodByName_Double(static_cast(propRef), "doubleValue", nullptr, outValue) != ANI_OK) { - MISC_HILOGE("GetPropertyAsDouble: Failed to call 'doubleValue' on property '%{punlic}s'", propertyName); + MISC_HILOGE("GetPropertyAsDouble: Failed to call 'doubleValue' on property:%{public}s", propertyName); return false; } @@ -402,7 +398,7 @@ static bool ParsePointsArray(ani_env *env, ani_object parentObject, VibratorEven return false; } - event.pointNum = static_cast(sizePoints); + event.pointNum = static_cast(sizePoints); if (static_cast(sizePoints) > 0) { if (!ParseVibratorCurvePointArray(env, static_cast(points), diff --git a/frameworks/js/napi/vibrator/include/vibrator_napi_utils.h b/frameworks/js/napi/vibrator/include/vibrator_napi_utils.h index 8e5a8b6baa8ef883919a0f4f115d08ee5f8a4ce2..a4b80a98e81d53dfc0c03a9212dc4ec6cb17c5bf 100644 --- a/frameworks/js/napi/vibrator/include/vibrator_napi_utils.h +++ b/frameworks/js/napi/vibrator/include/vibrator_napi_utils.h @@ -27,7 +27,6 @@ #include "sensors_errors.h" #include "vibrator_agent.h" -#include "vibrator_agent_type.h" namespace OHOS { namespace Sensors { @@ -104,8 +103,8 @@ bool IsMatchType(const napi_env &env, const napi_value &value, const napi_valuet 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); bool GetInt64Value(const napi_env &env, const napi_value &value, int64_t &result); +bool GetDoubleValue(const napi_env &env, const napi_value &value, double &result); bool GetStringValue(const napi_env &env, const napi_value &value, string &result); bool GetPropertyBool(const napi_env &env, const napi_value &value, const std::string &type, bool &result); bool GetPropertyItem(const napi_env &env, const napi_value &value, const std::string &type, napi_value &item); diff --git a/frameworks/js/napi/vibrator/include/vibrator_pattern_js.h b/frameworks/js/napi/vibrator/include/vibrator_pattern_js.h index 625668113b1b2f29bbf46b8cbcb217ad8a9d3545..b23d6caa0210bb01b8a68f2f45a5b33f3b80dca5 100644 --- a/frameworks/js/napi/vibrator/include/vibrator_pattern_js.h +++ b/frameworks/js/napi/vibrator/include/vibrator_pattern_js.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * 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 @@ -19,8 +19,6 @@ #include "napi/native_api.h" #include "napi/native_node_api.h" -#include "vibrator_agent_type.h" - namespace OHOS { namespace Sensors { enum VibrateTag { diff --git a/frameworks/js/napi/vibrator/src/vibrator_js.cpp b/frameworks/js/napi/vibrator/src/vibrator_js.cpp index 9b5b707ab13f56ec6c484dc3acc8e9e87b311ddb..82efe49aefe2f19952279e1915cabee8ee2f88e7 100644 --- a/frameworks/js/napi/vibrator/src/vibrator_js.cpp +++ b/frameworks/js/napi/vibrator/src/vibrator_js.cpp @@ -675,7 +675,12 @@ static napi_value IsSupportEffect(napi_env env, napi_callback_info info) sptr asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo(env); CHKPP(asyncCallbackInfo); asyncCallbackInfo->callbackType = IS_SUPPORT_EFFECT_CALLBACK; - asyncCallbackInfo->error.code = IsSupportEffect(effectId.c_str(), &asyncCallbackInfo->isSupportEffect); + bool isSupportEffect = false; + int32_t ret = IsSupportEffect(effectId.c_str(), &isSupportEffect); + if (ret == PERMISSION_DENIED || ret == PARAMETER_ERROR) { + asyncCallbackInfo->error.code = ret; + } + asyncCallbackInfo->isSupportEffect = isSupportEffect; if ((argc > 1) && (IsMatchType(env, args[1], napi_function))) { return EmitAsyncWork(args[1], asyncCallbackInfo); } diff --git a/frameworks/js/napi/vibrator/src/vibrator_napi_utils.cpp b/frameworks/js/napi/vibrator/src/vibrator_napi_utils.cpp index 20fccaa60c329855bbdec750d53990323859b5f9..92540df513407415cfcabfba62ae4eb9b2a21566 100644 --- a/frameworks/js/napi/vibrator/src/vibrator_napi_utils.cpp +++ b/frameworks/js/napi/vibrator/src/vibrator_napi_utils.cpp @@ -135,6 +135,7 @@ bool IsMatchArrayType(const napi_env &env, const napi_value &value) bool IsMatchType(const napi_env &env, const napi_value &value, const napi_valuetype &type) { + CALL_LOG_ENTER; napi_valuetype paramType = napi_undefined; napi_status ret = napi_typeof(env, value, ¶mType); if ((ret != napi_ok) || (paramType != type)) { @@ -165,23 +166,23 @@ bool GetInt32Value(const napi_env &env, const napi_value &value, int32_t &result return true; } -bool GetDoubleValue(const napi_env &env, const napi_value &value, double &result) +bool GetInt64Value(const napi_env &env, const napi_value &value, int64_t &result) { CALL_LOG_ENTER; napi_valuetype valuetype = napi_undefined; CHKCF(napi_typeof(env, value, &valuetype) == napi_ok, "napi_typeof failed"); CHKCF((valuetype == napi_number), "Wrong argument type. Number expected"); - CHKCF(napi_get_value_double(env, value, &result) == napi_ok, "napi_get_value_double failed"); + CHKCF(napi_get_value_int64(env, value, &result) == napi_ok, "napi_get_value_int64 failed"); return true; } -bool GetInt64Value(const napi_env &env, const napi_value &value, int64_t &result) +bool GetDoubleValue(const napi_env &env, const napi_value &value, double &result) { CALL_LOG_ENTER; napi_valuetype valuetype = napi_undefined; CHKCF(napi_typeof(env, value, &valuetype) == napi_ok, "napi_typeof failed"); CHKCF((valuetype == napi_number), "Wrong argument type. Number expected"); - CHKCF(napi_get_value_int64(env, value, &result) == napi_ok, "napi_get_value_int64 failed"); + CHKCF(napi_get_value_double(env, value, &result) == napi_ok, "napi_get_value_double failed"); return true; } @@ -258,7 +259,7 @@ bool GetPropertyInt32(const napi_env &env, const napi_value &value, const std::s bool exist = false; napi_status status = napi_has_named_property(env, value, type.c_str(), &exist); if (status != napi_ok || !exist) { - MISC_HILOGD("Can not find %{public}s property", type.c_str()); + MISC_HILOGE("Can not find %{public}s property", type.c_str()); return false; } CHKCF((napi_get_named_property(env, value, type.c_str(), &item) == napi_ok), "napi get property fail"); diff --git a/frameworks/js/napi/vibrator/src/vibrator_pattern_js.cpp b/frameworks/js/napi/vibrator/src/vibrator_pattern_js.cpp index 84976774357615bcd397a7b3ddd6ff5961739529..920384f288855de154a966a1bf772c3e618eefd1 100644 --- a/frameworks/js/napi/vibrator/src/vibrator_pattern_js.cpp +++ b/frameworks/js/napi/vibrator/src/vibrator_pattern_js.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * 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 @@ -24,6 +24,7 @@ #include "miscdevice_log.h" #include "vibrator_napi_error.h" #include "vibrator_napi_utils.h" +#include "vibrator_agent_type.h" #undef LOG_TAG #define LOG_TAG "VibratorPatternJs" @@ -119,6 +120,7 @@ bool VibratorPatternBuilder::ParsePoints(const napi_env &env, const napi_value & } event.points.push_back(point); } + MISC_HILOGE("ParsePoints out"); return true; } @@ -163,6 +165,7 @@ bool VibratorPatternBuilder::ParseOptions(const napi_env &env, const napi_value } else { event.index = 0; } + MISC_HILOGI("ParseOptions out"); return true; } diff --git a/frameworks/native/vibrator/include/vibrator_service_client.h b/frameworks/native/vibrator/include/vibrator_service_client.h index bf5fc3aaa5d97c707a1497dde6e44fad2bfc6c3f..d01e193721669b2a83dd81abac32882146307217 100644 --- a/frameworks/native/vibrator/include/vibrator_service_client.h +++ b/frameworks/native/vibrator/include/vibrator_service_client.h @@ -119,7 +119,7 @@ private: int32_t patternStartTime, VibrateEvent &vibrateEvent); static VibratorCurvePoint* GetCurveListAfterModulation(const std::vector& modInterval, const VibratorEvent &beforeModEvent, int32_t patternOffset); - static int32_t ModulateEventWithoutCurvePoints(std::vector& modInterval, + static int32_t ModulateEventWithoutCurvePoints(const std::vector& modInterval, int32_t patternStartTime, const VibratorEvent &beforeModEvent, VibratorEvent &afterModEvent); static void FreePartiallyAllocatedVibratorPatterns(VibratorPattern** patterns, int32_t partialIdx); static int32_t ModulateVibratorPattern(const VibratorEvent &modulationCurve, @@ -133,8 +133,6 @@ private: int32_t val, int32_t& idx); static void ConvertVibratorEventsToCurveIntervals(const VibratorEvent &vibratorEvent, int32_t patternTimeOffset, std::vector& curveInterval); - static void ModulateSingleCurvePoint(const VibratorCurveInterval &modulationInterval, - const VibratorCurveInterval &originalInterval, VibratorCurvePoint& point); static int32_t RestrictIntensityRange(int32_t intensity); static int32_t RestrictFrequencyRange(int32_t frequency); void WriteVibratorHiSysIPCEvent(IMiscdeviceServiceIpcCode code, int32_t ret); diff --git a/frameworks/native/vibrator/src/vibrator_client_stub.cpp b/frameworks/native/vibrator/src/vibrator_client_stub.cpp index 6d0b16d87319643db773081cbbfe6ef6dfd31ac6..d4bcb08b7d4fb94bb595d9702d689cd0871627c2 100644 --- a/frameworks/native/vibrator/src/vibrator_client_stub.cpp +++ b/frameworks/native/vibrator/src/vibrator_client_stub.cpp @@ -58,7 +58,7 @@ int32_t VibratorClientStub::OnRemoteRequest(uint32_t code, MessageParcel &data, } int result = ProcessPlugEvent(eventCode, deviceId, vibratorCnt); if (result != NO_ERROR) { - MISC_HILOGE("Process plug event failed"); + MISC_HILOGE("ProcessPlugEvent failed"); } return NO_ERROR; } diff --git a/frameworks/native/vibrator/src/vibrator_service_client.cpp b/frameworks/native/vibrator/src/vibrator_service_client.cpp index 62f5cc1e17bc5537fe1ae129eda5a5d93f9da800..bca7ab5a73efac7b63c3438268d937c85d9e065d 100644 --- a/frameworks/native/vibrator/src/vibrator_service_client.cpp +++ b/frameworks/native/vibrator/src/vibrator_service_client.cpp @@ -52,6 +52,8 @@ static constexpr int32_t MAX_PATTERN_NUM = 1000; static constexpr int32_t CURVE_POINT_NUM_MIN = 4; static constexpr int32_t CURVE_POINT_NUM_MAX = 16; static constexpr int32_t EVENT_NUM_MAX = 16; +static_assert(INTENSITY_UPPER_BOUND != INTENSITY_LOWER_BOUND, "upper bound and lower bound cannot be the same"); + using namespace OHOS::HiviewDFX; namespace { @@ -445,6 +447,15 @@ int32_t VibratorServiceClient::GetDelayTime(const VibratorIdentifier &identifier int32_t VibratorServiceClient::InitPlayPattern(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(); + if (ret != ERR_OK) { + MISC_HILOGE("InitServiceClient failed, ret:%{public}d", ret); + return MISC_NATIVE_GET_SERVICE_ERR; + } +#ifdef HIVIEWDFX_HITRACE_ENABLE + StartTrace(HITRACE_TAG_SENSORS, "PlayPattern"); +#endif // HIVIEWDFX_HITRACE_ENABLE VibratePattern vibratePattern = {}; vibratePattern.startTime = pattern.time; if (pattern.eventNum < 0 || pattern.eventNum > MAX_PATTERN_EVENT_NUM) { @@ -463,6 +474,12 @@ int32_t VibratorServiceClient::InitPlayPattern(const VibratorIdentifier &identif event.intensity = pattern.events[i].intensity; event.frequency = pattern.events[i].frequency; event.index = pattern.events[i].index; + if ((pattern.events[i].pointNum < CURVE_POINT_NUM_MIN) || (pattern.events[i].pointNum > CURVE_POINT_NUM_MAX)) { + MISC_HILOGE("The size of curve point is out of bounds, size:%{public}d", pattern.events[i].pointNum); + vibratePattern.events.emplace_back(event); + vibratePattern.patternDuration = pattern.patternDuration; + continue; + } for (int32_t j = 0; j < pattern.events[i].pointNum; ++j) { if (pattern.events[i].points == nullptr) { MISC_HILOGE("VibratorEvent's points is null"); @@ -488,7 +505,7 @@ int32_t VibratorServiceClient::InitPlayPattern(const VibratorIdentifier &identif vibrateIdentifier.vibratorId = identifier.vibratorId; std::lock_guard clientLock(clientMutex_); CHKPR(miscdeviceProxy_, ERROR); - int32_t ret = miscdeviceProxy_->PlayPattern(vibrateIdentifier, vibratePattern, customHapticInfoIPC); + ret = miscdeviceProxy_->PlayPattern(vibrateIdentifier, vibratePattern, customHapticInfoIPC); WriteOtherHiSysIPCEvent(IMiscdeviceServiceIpcCode::COMMAND_PLAY_PATTERN, ret); return ret; } @@ -517,7 +534,6 @@ int32_t VibratorServiceClient::PlayPattern(const VibratorIdentifier &identifier, int32_t VibratorServiceClient::ConvertVibratorPackage(const VibratorPackage& inPkg, VibratePackageIPC &outPkg) { - outPkg.patternNum = inPkg.patternNum; outPkg.packageDuration = inPkg.packageDuration; for (int32_t i = 0; i < inPkg.patternNum; ++i) { if (inPkg.patterns == nullptr) { @@ -619,7 +635,7 @@ int32_t VibratorServiceClient::StopVibrateBySessionId(const VibratorIdentifier & FinishTrace(HITRACE_TAG_SENSORS); #endif // HIVIEWDFX_HITRACE_ENABLE if (ret != ERR_OK) { - MISC_HILOGD("StopVibrateBySessionId failed, ret:%{public}d, sessionId:%{public}d", ret, sessionId); + MISC_HILOGE("StopVibrateBySessionId failed, ret:%{public}d, sessionId:%{public}d", ret, sessionId); } return ret; } @@ -1143,7 +1159,7 @@ int32_t VibratorServiceClient::ModulateVibratorEvent(const VibratorEvent &modula return ModulateEventWithCurvePoints(modInterval, patternStartTime, beforeModulationEvent, afterModulationEvent); } -int32_t VibratorServiceClient::ModulateEventWithoutCurvePoints(std::vector& modInterval, +int32_t VibratorServiceClient::ModulateEventWithoutCurvePoints(const std::vector& modInterval, int32_t patternStartTime, const VibratorEvent &beforeModEvent, VibratorEvent &afterModEvent) { afterModEvent = beforeModEvent; @@ -1187,8 +1203,6 @@ VibratorCurvePoint* VibratorServiceClient::GetCurveListAfterModulation( const std::vector& modInterval, const VibratorEvent &beforeModEvent, int32_t patternOffset) { - // There are atmost (modulationCurve.pointNum + beforeModulationEvent.pointNum + 1) - // VibratorCurvePoints after modulation VibratorCurvePoint* curvePoints = static_cast( calloc(beforeModEvent.pointNum, sizeof(VibratorCurvePoint))); if (curvePoints == nullptr) { @@ -1257,15 +1271,6 @@ void VibratorServiceClient::ConvertVibratorEventsToCurveIntervals( } } -void VibratorServiceClient::ModulateSingleCurvePoint(const VibratorCurveInterval &modulationInterval, - const VibratorCurveInterval &originalInterval, VibratorCurvePoint& point) -{ - static_assert(INTENSITY_UPPER_BOUND != INTENSITY_LOWER_BOUND, "upper bound and lower bound cannot be the same"); - point.frequency = RestrictFrequencyRange(modulationInterval.frequency + originalInterval.frequency); - point.intensity = RestrictIntensityRange( - modulationInterval.intensity * originalInterval.intensity / (INTENSITY_UPPER_BOUND - INTENSITY_LOWER_BOUND)); -} - int32_t VibratorServiceClient::RestrictFrequencyRange(int32_t frequency) { if (frequency > FREQUENCY_UPPER_BOUND) { diff --git a/frameworks/native/vibrator/vibrator_agent.cpp b/frameworks/native/vibrator/vibrator_agent.cpp index 70a7dbcb0055e477eb7ee0199684bd8db13e8e37..a8785d08825f3d3ff4f0c36685025633d8ad402f 100644 --- a/frameworks/native/vibrator/vibrator_agent.cpp +++ b/frameworks/native/vibrator/vibrator_agent.cpp @@ -351,12 +351,12 @@ int32_t SeekTimeOnPackage(int32_t seekTime, const VibratorPackage &completePacka return SUCCESS; } -int32_t ModulatePackage(const VibratorCurvePoint* modulationCurve, const int32_t curvePointNum, const int32_t duration, +int32_t ModulatePackage(VibratorCurvePoint* modulationCurve, const int32_t curvePointNum, const int32_t duration, const VibratorPackage &beforeModulationPackage, VibratorPackage &afterModulationPackage) { VibratorEvent modulationEvent{.type = EVENT_TYPE_CONTINUOUS, .time = 0, .duration = duration, .intensity = -1, .frequency = -1, .index = 0, .pointNum = curvePointNum, - .points = const_cast(modulationCurve)}; + .points = modulationCurve}; int32_t ret = VibratorServiceClient::ModulatePackage( modulationEvent, beforeModulationPackage, afterModulationPackage); if (ret != ERR_OK) { diff --git a/interfaces/inner_api/vibrator/vibrator_agent.h b/interfaces/inner_api/vibrator/vibrator_agent.h index e453a44eea2254e472bdcc35fd4363fa50fd7e8a..1fdb5c97ac49ac3aca3589f70e7623ae2b891841 100644 --- a/interfaces/inner_api/vibrator/vibrator_agent.h +++ b/interfaces/inner_api/vibrator/vibrator_agent.h @@ -195,7 +195,7 @@ int32_t SeekTimeOnPackage(int32_t seekTime, const VibratorPackage &completePacka * @return 0 indicates success, otherwise indicates failure. * @since 20 */ -int32_t ModulatePackage(const VibratorCurvePoint* modulationCurve, const int32_t curvePointNum, const int32_t duration, +int32_t ModulatePackage(VibratorCurvePoint* modulationCurve, const int32_t curvePointNum, const int32_t duration, const VibratorPackage &beforeModulationPackage, VibratorPackage &afterModulationPackage); /** diff --git a/services/miscdevice_service/BUILD.gn b/services/miscdevice_service/BUILD.gn index b002741ab64ea16fcf6cfbd4a002bb7b46b17464..cd081c8f9733330dd4b67a43663eb693563935f1 100644 --- a/services/miscdevice_service/BUILD.gn +++ b/services/miscdevice_service/BUILD.gn @@ -76,7 +76,9 @@ ohos_shared_library("libmiscdevice_service") { "access_token:libaccesstoken_sdk", "access_token:libtokenid_sdk", "cJSON:cjson", + "common_event_service:cesfwk_innerkits", "data_share:datashare_consumer", + "drivers_interface_vibrator:libvibrator_proxy_2.0", "hilog:libhilog", "safwk:system_ability_fwk", "samgr:samgr_proxy", @@ -84,6 +86,7 @@ ohos_shared_library("libmiscdevice_service") { if (miscdevice_feature_vibrator_input_method_enable) { external_deps += [ + "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "os_account:os_account_innerkits", ] @@ -190,7 +193,9 @@ ohos_static_library("libmiscdevice_service_static") { "access_token:libaccesstoken_sdk", "access_token:libtokenid_sdk", "cJSON:cjson", + "common_event_service:cesfwk_innerkits", "data_share:datashare_consumer", + "drivers_interface_vibrator:libvibrator_proxy_2.0", "hilog:libhilog", "safwk:system_ability_fwk", "samgr:samgr_proxy", @@ -198,6 +203,7 @@ ohos_static_library("libmiscdevice_service_static") { if (miscdevice_feature_vibrator_input_method_enable) { external_deps += [ + "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "os_account:os_account_innerkits", ] 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 35fb7fb256e78d82a695e4e34308d0fa58cdab53..f553abd7b903d520215d69c0cb767346a33fd923 100644 --- a/services/miscdevice_service/haptic_matcher/src/custom_vibration_matcher.cpp +++ b/services/miscdevice_service/haptic_matcher/src/custom_vibration_matcher.cpp @@ -41,7 +41,7 @@ constexpr int32_t EFFECT_ID_BOUNDARY = 1000; constexpr int32_t DURATION_MAX = 1600; #endif // HDF_DRIVERS_INTERFACE_VIBRATOR constexpr float CURVE_INTENSITY_SCALE = 100.00; -constexpr float EPSILON = 0.00001; +const float EPSILON = 0.00001; #ifdef HDF_DRIVERS_INTERFACE_VIBRATOR constexpr int32_t SLICE_STEP = 50; constexpr int32_t CONTINUOUS_VIBRATION_DURATION_MIN = 15; @@ -63,9 +63,9 @@ CustomVibrationMatcher::CustomVibrationMatcher() return; } if (!hdfWaveInfos_.empty()) { - for (auto it = hdfWaveInfos_.begin(); it != hdfWaveInfos_.end(); ++it) { + for (const auto &info : hdfWaveInfos_) { MISC_HILOGI("waveId:%{public}d, intensity:%{public}f, frequency:%{public}f, duration:%{public}d", - it->waveId, it->intensity, it->frequency, it->duration); + info.waveId, info.intensity, info.frequency, info.duration); } NormalizedWaveInfo(); } @@ -91,10 +91,10 @@ void CustomVibrationMatcher::NormalizedWaveInfo() float maxIntensity = firstIt->intensity; float minFrequency = firstIt->frequency; float maxFrequency = firstIt->frequency; - for (auto it = hdfWaveInfos_.begin(); it != hdfWaveInfos_.end(); ++it) { - maxIntensity = (maxIntensity > it->intensity) ? maxIntensity : it->intensity; - minFrequency = (minFrequency < it->frequency) ? minFrequency : it->frequency; - maxFrequency = (maxFrequency > it->frequency) ? maxFrequency : it->frequency; + for (const auto &info : hdfWaveInfos_) { + maxIntensity = (maxIntensity > info.intensity) ? maxIntensity : info.intensity; + minFrequency = (minFrequency < info.frequency) ? minFrequency : info.frequency; + maxFrequency = (maxFrequency > info.frequency) ? maxFrequency : info.frequency; } float intensityEqualValue = maxIntensity / INTENSITY_MAX; @@ -103,16 +103,16 @@ void CustomVibrationMatcher::NormalizedWaveInfo() MISC_HILOGE("The equal value of intensity or frequency is zero"); return; } - for (auto it = hdfWaveInfos_.begin(); it != hdfWaveInfos_.end(); ++it) { + for (const auto &info : hdfWaveInfos_) { std::vector normalizedValue; - normalizedValue.push_back(static_cast(it->intensity / intensityEqualValue)); - normalizedValue.push_back(static_cast((it->frequency - minFrequency) / frequencyEqualValue)); - normalizedValue.push_back(it->duration); - waveInfos_[it->waveId] = normalizedValue; + normalizedValue.push_back(static_cast(info.intensity / intensityEqualValue)); + normalizedValue.push_back(static_cast((info.frequency - minFrequency) / frequencyEqualValue)); + normalizedValue.push_back(info.duration); + waveInfos_[info.waveId] = normalizedValue; } - for (auto it = waveInfos_.begin(); it != waveInfos_.end(); ++it) { + for (const auto &info : waveInfos_) { MISC_HILOGI("waveId:%{public}d, intensity:%{public}d, frequency:%{public}d, duration:%{public}d", - it->first, it->second[0], it->second[1], it->second[WAVE_INFO_DIMENSION - 1]); + info.first, info.second[0], info.second[1], info.second[WAVE_INFO_DIMENSION - 1]); } #endif // HDF_DRIVERS_INTERFACE_VIBRATOR } 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 8004672b63e97485aca2e6d361e3eae923012731..e81ca33523924bbff781b9325ff0d2b9ac4637fa 100644 --- a/services/miscdevice_service/hdi_connection/adapter/src/hdi_connection.cpp +++ b/services/miscdevice_service/hdi_connection/adapter/src/hdi_connection.cpp @@ -306,11 +306,14 @@ int32_t HdiConnection::PlayPatternBySessionId(const VibratorIdentifierIPC &ident void HdiConnection::GetVibratorPackage(const VibratePackageIPC &packageIPC, VibratorPackage &package) { package.packageduration = packageIPC.packageDuration; - for (int32_t i = 0; i < packageIPC.patternNum; ++i) { - int32_t patternNum = static_cast(packageIPC.patterns[i].events.size()); - package.patternNum = patternNum; + int32_t patternNum = static_cast(packageIPC.patterns.size()); + package.patternNum = patternNum; + for (int32_t i = 0; i < patternNum; ++i) { HapticPaket paket; - for (int32_t j = 0; j < patternNum; ++j) { + paket.time = packageIPC.patterns[i].startTime; + int32_t eventNum = static_cast(packageIPC.patterns[i].events.size()); + paket.eventNum = eventNum; + for (int32_t j = 0; j < eventNum; ++j) { HapticEvent hapticEvent = {}; hapticEvent.type = static_cast(packageIPC.patterns[i].events[j].tag); hapticEvent.time = packageIPC.patterns[i].events[j].time; diff --git a/services/miscdevice_service/src/miscdevice_service.cpp b/services/miscdevice_service/src/miscdevice_service.cpp index 1ea805e57e55b9b900ecae698109a1d40fa264f0..3c9d9aebd3f85b1e74e8cfef2c07b3a42271d9a3 100644 --- a/services/miscdevice_service/src/miscdevice_service.cpp +++ b/services/miscdevice_service/src/miscdevice_service.cpp @@ -923,8 +923,8 @@ int32_t MiscdeviceService::PlayPattern(const VibratorIdentifierIPC& identifier, .pid = GetCallingPid(), .uid = GetCallingUid(), .usage = customHapticInfoIPC.usage, - .sessionId = sessionId, - .systemUsage = customHapticInfoIPC.systemUsage + .systemUsage = customHapticInfoIPC.systemUsage, + .sessionId = sessionId }; VibratorCapacity capacity; if (GetHapticCapacityInfo(identifier, capacity) != ERR_OK) { @@ -1004,7 +1004,6 @@ int32_t MiscdeviceService::StopVibrateBySessionId(const VibratorIdentifierIPC &i MISC_HILOGE("CheckVibratePermission failed, ret:%{public}d", ret); return PERMISSION_DENIED; } - std::lock_guard lock(devicesManageMutex_); std::vector result = CheckDeviceIdIsValid(identifier); size_t ignoreVibrateNum = 0; if (result.empty()) { @@ -1019,7 +1018,7 @@ int32_t MiscdeviceService::StopVibrateBySessionId(const VibratorIdentifierIPC &i continue; } if (vibratorHdiConnection_.IsVibratorRunning(paramIt)) { - vibratorHdiConnection_.StopVibrateBySessionId(identifier, sessionId); + vibratorHdiConnection_.StopVibrateBySessionId(paramIt, sessionId); } } if (ignoreVibrateNum == result.size()) { @@ -1376,7 +1375,6 @@ int32_t MiscdeviceService::GetVibratorList(const VibratorIdentifierIPC& identifi GetOnlineVibratorInfo(); } std::lock_guard lockManage(devicesManageMutex_); - int32_t ret; if ((identifier.deviceId == -1) && (identifier.vibratorId == -1)) { for (auto &value : devicesManageMap_) { vibratorInfoIPC.insert(vibratorInfoIPC.end(), value.second.baseInfo.begin(), @@ -1385,7 +1383,7 @@ int32_t MiscdeviceService::GetVibratorList(const VibratorIdentifierIPC& identifi } else if ((identifier.deviceId == -1) && (identifier.vibratorId != -1)) { VibratorIdentifierIPC actIdentifier; actIdentifier.vibratorId = identifier.vibratorId; - ret = GetLocalDeviceId(actIdentifier.deviceId); + int32_t ret = GetLocalDeviceId(actIdentifier.deviceId); if (ret == NO_ERROR) { ret = GetOneVibrator(actIdentifier, vibratorInfoIPC); if (ret != NO_ERROR) { @@ -1401,8 +1399,7 @@ int32_t MiscdeviceService::GetVibratorList(const VibratorIdentifierIPC& identifi } vibratorInfoIPC = it->second.baseInfo; } else { // ((identifier.deviceId != -1) && (identifier.vibratorId != -1)) - ret = GetOneVibrator(identifier, vibratorInfoIPC); - if (ret != NO_ERROR) { + if (GetOneVibrator(identifier, vibratorInfoIPC) != NO_ERROR) { MISC_HILOGI("DeviceId %{public}d has no vibratorId %{public}d info", identifier.deviceId, identifier.vibratorId); } diff --git a/services/miscdevice_service/src/vibration_priority_manager.cpp b/services/miscdevice_service/src/vibration_priority_manager.cpp index 865fb5ffe368541ad0e3d1da557bf34dcb1e8bc2..0b3ce3fc59fbf8ba3be7cda41fbfa4ea63127fbb 100644 --- a/services/miscdevice_service/src/vibration_priority_manager.cpp +++ b/services/miscdevice_service/src/vibration_priority_manager.cpp @@ -106,11 +106,11 @@ bool VibrationPriorityManager::Init() MISC_HILOGE("Get feedback failed"); } miscFeedback_ = feedback; - MISC_HILOGI("feedback:%{public}d", feedback); #ifdef HIVIEWDFX_HISYSEVENT_ENABLE HiSysEventWrite(HiSysEvent::Domain::MISCDEVICE, "SWITCHES_TOGGLE", HiSysEvent::EventType::BEHAVIOR, "SWITCH_TYPE", "feedback", "STATUS", feedback); #endif // HIVIEWDFX_HISYSEVENT_ENABLE + MISC_HILOGI("feedback:%{public}d", feedback); int32_t ringerMode = miscAudioRingerMode_; if (GetIntValue(SETTING_RINGER_MODE_KEY, ringerMode) != ERR_OK) { MISC_HILOGE("Get ringerMode failed"); diff --git a/test/fuzztest/service/BUILD.gn b/test/fuzztest/service/BUILD.gn index 96dcaf5e6b3116e42f5e9fb6ff8b4d8c68a092b9..777a7c13517e38492c8fad29ec2165f4c43d286b 100644 --- a/test/fuzztest/service/BUILD.gn +++ b/test/fuzztest/service/BUILD.gn @@ -36,9 +36,9 @@ group("fuzztest") { "turnonstub_fuzzer:fuzztest", "vibratestub_fuzzer:fuzztest", "vibratoronremoterequest_fuzzer:fuzztest", + "subscribevibratorpluginfostub_fuzzer:fuzztest", "playpackagebysessionidstub_fuzzer:fuzztest", "stopvibratebysessionidstub_fuzzer:fuzztest", - "subscribevibratorpluginfostub_fuzzer:fuzztest", ] if (miscdevice_feature_vibrator_custom) { diff --git a/test/fuzztest/vibrator/BUILD.gn b/test/fuzztest/vibrator/BUILD.gn index 3745b9a0753cabdc3d3df653e2e1ee9251930488..7d2dea6c5865fe33bc7b29d8259489e3dde62628 100644 --- a/test/fuzztest/vibrator/BUILD.gn +++ b/test/fuzztest/vibrator/BUILD.gn @@ -48,12 +48,11 @@ group("fuzztest") { "playpatternenhanced_fuzzer:fuzztest", "getdelaytimeenhanced_fuzzer:fuzztest", "cancelenhanced_fuzzer:fuzztest", + "handlevibratordata_fuzzer:fuzztest", + "issupportvibratorcustom_fuzzer:fuzztest", "playpackagebysessionid_fuzzer:fuzztest", "playpatternbysessionid_fuzzer:fuzztest", "stopvibratebysessionid_fuzzer:fuzztest", - "handlevibratordata_fuzzer:fuzztest", - "issupportvibratorcustom_fuzzer:fuzztest", "ishdhapticsupported_fuzzer:fuzztest", - "modulatepackage_fuzzer:fuzztest", ] } diff --git a/test/fuzztest/vibrator/handlevibratordata_fuzzer/handlevibratordata_fuzzer.cpp b/test/fuzztest/vibrator/handlevibratordata_fuzzer/handlevibratordata_fuzzer.cpp index c2f5f9c145a1575eba21712b83908c4e270f4397..aae3a20ff699df80c378f45bbb98ee957bbe7ac3 100644 --- a/test/fuzztest/vibrator/handlevibratordata_fuzzer/handlevibratordata_fuzzer.cpp +++ b/test/fuzztest/vibrator/handlevibratordata_fuzzer/handlevibratordata_fuzzer.cpp @@ -25,7 +25,7 @@ constexpr size_t DATA_MIN_SIZE = 8; } // namespace template -size_t GetObject(const uint8_t *data, size_t size, T &object) +static size_t GetObject(const uint8_t *data, size_t size, T &object) { size_t objectSize = sizeof(object); if (objectSize > size) { @@ -43,9 +43,8 @@ void HandleVibratorDataFuzzTest(const uint8_t *data, size_t size) if (data == nullptr || size < DATA_MIN_SIZE) { return; } - size_t startPos = 0; VibratorStatusEvent statusEvent; - startPos += GetObject(data + startPos, size - startPos, statusEvent.deviceId); + size_t startPos = GetObject(data, size, statusEvent.deviceId); GetObject(data + startPos, size - startPos, statusEvent.vibratorCnt); VibratorServiceClient::GetInstance().HandleVibratorData(statusEvent); } diff --git a/test/fuzztest/vibrator/issupportvibratorcustom_fuzzer/issupportvibratorcustom_fuzzer.cpp b/test/fuzztest/vibrator/issupportvibratorcustom_fuzzer/issupportvibratorcustom_fuzzer.cpp index 149f6f2cae4737d0e45495219911ebaa608b5b1d..27880484c50815652719e450fd2cdb948d8b62c0 100644 --- a/test/fuzztest/vibrator/issupportvibratorcustom_fuzzer/issupportvibratorcustom_fuzzer.cpp +++ b/test/fuzztest/vibrator/issupportvibratorcustom_fuzzer/issupportvibratorcustom_fuzzer.cpp @@ -26,7 +26,7 @@ constexpr size_t DATA_MIN_SIZE = 8; } // namespace template -size_t GetObject(const uint8_t *data, size_t size, T &object) +static size_t GetObject(const uint8_t *data, size_t size, T &object) { size_t objectSize = sizeof(object); if (objectSize > size) { @@ -44,9 +44,8 @@ void IsSupportVibratorCustomFuzzTest(const uint8_t *data, size_t size) if (data == nullptr || size < DATA_MIN_SIZE) { return; } - size_t startPos = 0; VibratorIdentifier identifier; - startPos += GetObject(data + startPos, size - startPos, identifier.deviceId); + size_t startPos = GetObject(data, size, identifier.deviceId); GetObject(data + startPos, size - startPos, identifier.vibratorId); OHOS::Sensors::IsSupportVibratorCustomEnhanced(identifier); OHOS::Sensors::IsSupportVibratorCustom(); diff --git a/test/fuzztest/vibrator/modulatepackage_fuzzer/BUILD.gn b/test/fuzztest/vibrator/modulatepackage_fuzzer/BUILD.gn deleted file mode 100644 index 4abebaea5a31da3c95666e52247b335853e0ce4a..0000000000000000000000000000000000000000 --- a/test/fuzztest/vibrator/modulatepackage_fuzzer/BUILD.gn +++ /dev/null @@ -1,56 +0,0 @@ -# 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("ModulatePackageFuzzTest") { - module_out_path = FUZZ_MODULE_OUT_PATH - - fuzz_config_file = "$SUBSYSTEM_DIR/test/fuzztest/vibrator/modulatepackage_fuzzer" - - include_dirs = [ - "$SUBSYSTEM_DIR/frameworks/native/vibrator", - "$SUBSYSTEM_DIR/test/fuzztest/vibrator/modulatepackage_fuzzer", - ] - - cflags = [ - "-g", - "-O0", - "-Wno-unused-variable", - "-fno-omit-frame-pointer", - ] - - sources = [ "modulatepackage_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 - ":ModulatePackageFuzzTest", - ] -} diff --git a/test/fuzztest/vibrator/modulatepackage_fuzzer/corpus/init b/test/fuzztest/vibrator/modulatepackage_fuzzer/corpus/init deleted file mode 100644 index 65af8ee8d11bf23407ea34d4de49f7cbb6a2b791..0000000000000000000000000000000000000000 --- a/test/fuzztest/vibrator/modulatepackage_fuzzer/corpus/init +++ /dev/null @@ -1,14 +0,0 @@ -# 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/modulatepackage_fuzzer/modulatepackage_fuzzer.cpp b/test/fuzztest/vibrator/modulatepackage_fuzzer/modulatepackage_fuzzer.cpp deleted file mode 100644 index d35f6b05a2e9159b0c00db9b4e540d44c8e4938b..0000000000000000000000000000000000000000 --- a/test/fuzztest/vibrator/modulatepackage_fuzzer/modulatepackage_fuzzer.cpp +++ /dev/null @@ -1,107 +0,0 @@ -/* - * 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 "modulatepackage_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; -VibratorCurvePoint vibratorCurvePoint{ - .time = 0, - .intensity = 100, - .frequency = 100 -}; - -VibratorEvent vibratorEvent{ - .type = EVENT_TYPE_CONTINUOUS, - .time = 0, - .duration = 500, - .intensity = 100, - .frequency = 100, - .index = 0, - .pointNum = 1, - .points = &vibratorCurvePoint -}; - -VibratorPattern vibratorPattern{ - .time = 500, - .eventNum = 10, - .patternDuration = 5000, - .events = &vibratorEvent -}; - -VibratorPackage beforeModulationPackage { - .patternNum = 1, - .packageDuration = 5000, - .patterns = &vibratorPattern -}; -} // 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 ModulatePackageFuzzTest(const uint8_t *data, size_t size) -{ - if (data == nullptr || size < U32_AT_SIZE) { - return false; - } - VibratorCurvePoint modulationCurve { - .time = 100, - .intensity = 0, - .frequency = 0 - }; - size_t startPos = 0; - startPos += GetObject(data + startPos, size - startPos, modulationCurve.intensity); - GetObject(data + startPos, size - startPos, modulationCurve.frequency); - int32_t curvePointNum = 1; - int32_t duration = 300; - VibratorPackage afterModulationPackage; - OHOS::Sensors::ModulatePackage(&modulationCurve, curvePointNum, duration, - beforeModulationPackage, afterModulationPackage); - return true; -} -} // namespace OHOS - -extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) -{ - OHOS::ModulatePackageFuzzTest(data, size); - return 0; -} \ No newline at end of file diff --git a/test/fuzztest/vibrator/modulatepackage_fuzzer/modulatepackage_fuzzer.h b/test/fuzztest/vibrator/modulatepackage_fuzzer/modulatepackage_fuzzer.h deleted file mode 100644 index 434d78b3aa39016005707ee633eb098d101ec8d3..0000000000000000000000000000000000000000 --- a/test/fuzztest/vibrator/modulatepackage_fuzzer/modulatepackage_fuzzer.h +++ /dev/null @@ -1,21 +0,0 @@ -/* - * 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 MODULATE_PACKAGE_FUZZER_H -#define MODULATE_PACKAGE_FUZZER_H - -#define FUZZ_PROJECT_NAME "modulatepackage_fuzzer" - -#endif // MODULATE_PACKAGE_FUZZER_H \ No newline at end of file diff --git a/test/fuzztest/vibrator/modulatepackage_fuzzer/project.xml b/test/fuzztest/vibrator/modulatepackage_fuzzer/project.xml deleted file mode 100644 index 2eb360c27f1b159e1b043e38846f10fcf37fa37c..0000000000000000000000000000000000000000 --- a/test/fuzztest/vibrator/modulatepackage_fuzzer/project.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - 1000 - - 120 - - 2048 - - diff --git a/test/unittest/light/light_agent_test.cpp b/test/unittest/light/light_agent_test.cpp index 9715930c09d487ea50e48f26fa5145b1b1779477..ae000fc95ead241a46073ed8b46f1ac14f7ce095 100644 --- a/test/unittest/light/light_agent_test.cpp +++ b/test/unittest/light/light_agent_test.cpp @@ -17,10 +17,10 @@ #include #include "accesstoken_kit.h" -#include "nativetoken_kit.h" -#include "token_setproc.h" #include "light_agent.h" +#include "nativetoken_kit.h" #include "sensors_errors.h" +#include "token_setproc.h" #undef LOG_TAG #define LOG_TAG "LightAgentTest" @@ -85,10 +85,9 @@ void LightAgentTest::SetUpTestCase() void LightAgentTest::TearDownTestCase() { + ASSERT_NE(0, tokenID_); int32_t ret = AccessTokenKit::DeleteToken(tokenID_); - if (tokenID_ != 0) { - ASSERT_EQ(RET_SUCCESS, ret); - } + ASSERT_EQ(RET_SUCCESS, ret); } /** diff --git a/test/unittest/vibrator/js/ExampleJsunit.test.js b/test/unittest/vibrator/js/ExampleJsunit.test.js index 968802b45c4f1f07e2a12599edfd77c0009e1136..db29bb51ff8116e3c9cb1780942a8e4bcc98e0b8 100644 --- a/test/unittest/vibrator/js/ExampleJsunit.test.js +++ b/test/unittest/vibrator/js/ExampleJsunit.test.js @@ -1279,12 +1279,12 @@ describe("VibratorJsTest", function () { */ it("VibratorJsTest042", 0, async function (done) { try { - const vibrators = vibrator.getVibratorInfoSync(); - if (vibrators.length === 0) { - console.warn('vibrators is null, ending test case.'); + const vibratorsList = vibrator.getVibratorInfoSync(); + if (vibratorsList.length === 0) { + console.warn('vibratorsList is null, ending test case.'); done(); } - expect(Array.isArray(vibrators)).assertEqual(true); + expect(Array.isArray(vibratorsList)).assertEqual(true); done(); } catch (error) { console.error('VibratorJsTest042 failed with error:', error); @@ -1303,12 +1303,12 @@ describe("VibratorJsTest", function () { deviceId: -1, vibratorId: -1 }; - const vibrators = vibrator.getVibratorInfoSync(vibratorInfoParam); - if (vibrators.length === 0) { - console.warn('vibrators is null, ending test case.'); + const vibratorsList = vibrator.getVibratorInfoSync(vibratorInfoParam); + if (vibratorsList.length === 0) { + console.warn('vibratorsList is null, ending test case.'); done(); } - expect(Array.isArray(vibrators)).assertEqual(true); + expect(Array.isArray(vibratorsList)).assertEqual(true); done(); } catch (error) { console.error('VibratorJsTest043 failed with error:', error); @@ -1323,9 +1323,9 @@ describe("VibratorJsTest", function () { */ it("VibratorJsTest044", 0, function (done) { try { - const vibrators = vibrator.getVibratorInfoSync(); - if (vibrators.length === 0) { - console.warn('vibrators is null, ending test case.'); + const vibratorsList = vibrator.getVibratorInfoSync(); + if (vibratorsList.length === 0) { + console.warn('vibratorsList is null, ending test case.'); done(); } const validCallback = function (statusEvent) { @@ -1354,17 +1354,17 @@ describe("VibratorJsTest", function () { */ it("VibratorJsTest045", 0, async function (done) { try { - const vibrators = vibrator.getVibratorInfoSync(); - if (vibrators.length === 0) { - console.warn('vibrators is null, ending test case.'); + const vibratorsList = vibrator.getVibratorInfoSync(); + if (vibratorsList.length === 0) { + console.warn('vibratorsList is null, ending test case.'); done(); } await vibrator.startVibration({ type: "time", duration: 500 }, { - id: vibrators[0].vibratorId, - deviceId: vibrators[0].deviceId, + id: vibratorsList[0].vibratorId, + deviceId: vibratorsList[0].deviceId, usage: "alarm" }, (error) => { if (error) { @@ -1391,17 +1391,17 @@ describe("VibratorJsTest", function () { */ it("VibratorJsTest046", 0, async function (done) { try { - const vibrators = vibrator.getVibratorInfoSync(); - if (vibrators.length === 0) { - console.warn('vibrators is null, ending test case.'); + const vibratorsList = vibrator.getVibratorInfoSync(); + if (vibratorsList.length === 0) { + console.warn('vibratorsList is null, ending test case.'); done(); } await vibrator.startVibration({ type: "time", duration: 500 }, { - id: vibrators[0].vibratorId, - deviceId: vibrators[0].deviceId, + id: vibratorsList[0].vibratorId, + deviceId: vibratorsList[0].deviceId, usage: "alarm" }, (error) => { if (error) { @@ -1413,8 +1413,8 @@ describe("VibratorJsTest", function () { done(); }); const vibratorInfoParam = { - deviceId: vibrators[0].deviceId, - vibratorId: vibrators[0].vibratorId + deviceId: vibratorsList[0].deviceId, + vibratorId: vibratorsList[0].vibratorId }; await vibrator.stopVibration(vibratorInfoParam); console.info("stopVibration success"); @@ -1433,14 +1433,14 @@ describe("VibratorJsTest", function () { it("VibratorJsTest047", 0, async function (done) { try { const effectId = "haptic.clock.timer"; - const vibrators = vibrator.getVibratorInfoSync(); - if (vibrators.length === 0) { - console.warn('vibrators is null, ending test case.'); + const vibratorsList = vibrator.getVibratorInfoSync(); + if (vibratorsList.length === 0) { + console.warn('vibratorsList is null, ending test case.'); done(); } const vibratorInfoParam = { - deviceId: vibrators[0].deviceId, - vibratorId: vibrators[0].vibratorId + deviceId: vibratorsList[0].deviceId, + vibratorId: vibratorsList[0].vibratorId }; const jsEffectInfo = vibrator.getEffectInfoSync(effectId, vibratorInfoParam); if (!jsEffectInfo.isEffectSupported) { @@ -1463,9 +1463,9 @@ describe("VibratorJsTest", function () { */ it("VibratorJsTest048", 0, async function (done) { try { - const vibrators = vibrator.getVibratorInfoSync(); - if (vibrators.length === 0) { - console.warn('vibrators is null, ending test case.'); + const vibratorsList = vibrator.getVibratorInfoSync(); + if (vibratorsList.length === 0) { + console.warn('vibratorsList is null, ending test case.'); done(); } const effectId = "haptic.clock.timer"; @@ -1490,14 +1490,14 @@ describe("VibratorJsTest", function () { */ it("VibratorJsTest049", 0, async function (done) { try { - const vibrators = vibrator.getVibratorInfoSync(); - if (vibrators.length === 0) { - console.warn('vibrators is null, ending test case.'); + const vibratorsList = vibrator.getVibratorInfoSync(); + if (vibratorsList.length === 0) { + console.warn('vibratorsList is null, ending test case.'); done(); } const effectId = "haptic.clock.timer"; const vibratorInfoParam = { - deviceId: vibrators[0].deviceId, + deviceId: vibratorsList[0].deviceId, }; const jsEffectInfo = vibrator.getEffectInfoSync(effectId, vibratorInfoParam); if (!jsEffectInfo.isEffectSupported) { @@ -3582,6 +3582,7 @@ describe("VibratorJsTest", function () { } else { console.info('This device is not supportEffect'); expect(true).assertTrue(); + done(); } }) @@ -3617,6 +3618,7 @@ describe("VibratorJsTest", function () { } else { console.info('This device is not supportEffect'); expect(true).assertTrue(); + done(); } }) @@ -3652,6 +3654,7 @@ describe("VibratorJsTest", function () { } else { console.info('This device is not supportEffect'); expect(true).assertTrue(); + done(); } }) }) diff --git a/test/unittest/vibrator/js/config.json b/test/unittest/vibrator/js/config.json index e5ff85146c2c33ffdcbc57657f21b86fbfba106e..cf70146affa147eda81aa3282d6ea2a5d5a6061b 100644 --- a/test/unittest/vibrator/js/config.json +++ b/test/unittest/vibrator/js/config.json @@ -18,7 +18,8 @@ "deviceType": [ "default", "tablet", - "2in1" + "2in1", + "wearable" ], "distro": { "deliveryWithInstall": true, diff --git a/test/unittest/vibrator/native/vibrator_agent_modulation_test.cpp b/test/unittest/vibrator/native/vibrator_agent_modulation_test.cpp index 9cf8bbfc732a887c2251b37f3a11630b73d7a673..d4d8f0d306953181363d428d6a57227de216756f 100644 --- a/test/unittest/vibrator/native/vibrator_agent_modulation_test.cpp +++ b/test/unittest/vibrator/native/vibrator_agent_modulation_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025-2029 Huawei Device Co., Ltd. + * 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 @@ -13,12 +13,15 @@ * limitations under the License. */ +#include +#include #include #include #include #include #include + #include "accesstoken_kit.h" #include "nativetoken_kit.h" #include "parameters.h" @@ -36,6 +39,8 @@ namespace OHOS { namespace Sensors { using namespace testing::ext; +using namespace Security::AccessToken; +using Security::AccessToken::AccessTokenID; namespace { constexpr int32_t CONT_TYPE_NO_CURVE_EVENT_IDX_9 = 9; @@ -54,11 +59,9 @@ constexpr int32_t TIME_WAIT_FOR_OP = 2000; constexpr int32_t TIME_WAIT_FOR_EACH_CASE = 200; constexpr int32_t TEST_SUCCESS = 0; constexpr int32_t TEST_FAILED = -1; +constexpr AccessTokenID INVALID_TOKEN_ID = 0; } -using namespace Security::AccessToken; -using Security::AccessToken::AccessTokenID; - PermissionStateFull g_infoManagerTestState = { .grantFlags = {1}, .grantStatus = {PermissionState::PERMISSION_GRANTED}, @@ -75,10 +78,10 @@ HapPolicyParams g_infoManagerTestPolicyPrams = { }; HapInfoParams g_infoManagerTestInfoParms = { - .bundleName = "vibratoragent_test", + .bundleName = "vibratoragentmodulation_test", .userID = 1, .instIndex = 0, - .appIDDesc = "vibratorAgentTest" + .appIDDesc = "vibratorAgentModulationTest" }; class VibratorAgentModulationTest : public testing::Test { @@ -87,7 +90,6 @@ public: static void TearDownTestCase(); void SetUp(); void TearDown(); -private: static AccessTokenID tokenID_; }; @@ -98,8 +100,11 @@ void VibratorAgentModulationTest::SetUpTestCase() AccessTokenIDEx tokenIdEx = {0}; tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams); tokenID_ = tokenIdEx.tokenIdExStruct.tokenID; - ASSERT_NE(0, tokenID_); - ASSERT_EQ(0, SetSelfTokenID(tokenID_)); + if (tokenID_ != 0) { + MISC_HILOGI("acquire token successfully"); + ASSERT_EQ(0, SetSelfTokenID(tokenID_)); + } + MISC_HILOGE("failed to acquire token"); } void VibratorAgentModulationTest::TearDownTestCase() @@ -145,41 +150,28 @@ int32_t PlayModulatedPattern(const VibratorPackage& package) } return TEST_SUCCESS; } - -void PrintVibratorPackageInfo(const VibratorPackage& package, std::string functionName) +// this print function required when debugging failure of testcase +void PrintVibratorPackageInfo(const VibratorPackage& package, const std::string& functionName) { - MISC_HILOGI("FunctionName:%{public}s data, package patternNum:%{public}d", functionName.c_str(), - package.patternNum); - MISC_HILOGI("FunctionName:%{public}s data, package packageDuration:%{public}d", functionName.c_str(), - package.packageDuration); + MISC_HILOGI("FunctionName:%{public}s data, package patternNum:%{public}d, package packageDuration:%{public}d", + functionName.c_str(), package.patternNum, package.packageDuration); for (int32_t i = 0; i < package.patternNum; i++) { - MISC_HILOGI("FunctionName:%{public}s data, pattern time:%{public}d", functionName.c_str(), - package.patterns[i].time); - MISC_HILOGI("FunctionName:%{public}s data, pattern patternDuration:%{public}d", functionName.c_str(), - package.patterns[i].patternDuration); - MISC_HILOGI("FunctionName:%{public}s data, pattern eventNum:%{public}d", functionName.c_str(), - package.patterns[i].eventNum); + MISC_HILOGI("FunctionName:%{public}s data, pattern time:%{public}d, pattern patternDuration:%{public}d," + "pattern eventNum:%{public}d", functionName.c_str(), package.patterns[i].time, + package.patterns[i].patternDuration, package.patterns[i].eventNum); for (int32_t j = 0; j < package.patterns[i].eventNum; j++) { - MISC_HILOGI("FunctionName:%{public}s data, event type:%{public}d", functionName.c_str(), - static_cast(package.patterns[i].events[j].type)); - MISC_HILOGI("FunctionName:%{public}s data, event time:%{public}d", functionName.c_str(), - package.patterns[i].events[j].time); - MISC_HILOGI("FunctionName:%{public}s data, event duration:%{public}d", functionName.c_str(), - package.patterns[i].events[j].duration); - MISC_HILOGI("FunctionName:%{public}s data, event intensity:%{public}d", functionName.c_str(), - package.patterns[i].events[j].intensity); - MISC_HILOGI("FunctionName:%{public}s data, event frequency:%{public}d", functionName.c_str(), - package.patterns[i].events[j].frequency); - MISC_HILOGI("FunctionName:%{public}s data, event index:%{public}d", functionName.c_str(), - package.patterns[i].events[j].index); - MISC_HILOGI("FunctionName:%{public}s data, event pointNum:%{public}d", functionName.c_str(), - package.patterns[i].events[j].pointNum); + MISC_HILOGI("FunctionName:%{public}s data, event type:%{public}d, event time:%{public}d, " + "event duration:%{public}d, intensity:%{public}d, frequency:%{public}d, index:%{public}d, " + "pointNum:%{public}d", functionName.c_str(), + static_cast(package.patterns[i].events[j].type), + package.patterns[i].events[j].time, package.patterns[i].events[j].duration, + package.patterns[i].events[j].intensity, package.patterns[i].events[j].frequency, + package.patterns[i].events[j].index, package.patterns[i].events[j].pointNum); for (int32_t k = 0; k < package.patterns[i].events[j].pointNum; k++) { - MISC_HILOGI("FunctionName:%{public}s data, points time:%{public}d", functionName.c_str(), - package.patterns[i].events[j].points[k].time); - MISC_HILOGI("FunctionName:%{public}s data, points intensity:%{public}d", functionName.c_str(), - package.patterns[i].events[j].points[k].intensity); - MISC_HILOGI("FunctionName:%{public}s data, points frequency:%{public}d", functionName.c_str(), + MISC_HILOGI("FunctionName:%{public}s data, points time:%{public}d, points intensity:%{public}d, " + "points frequency:%{public}d", functionName.c_str(), + package.patterns[i].events[j].points[k].time, + package.patterns[i].events[j].points[k].intensity, package.patterns[i].events[j].points[k].frequency); } } @@ -349,7 +341,12 @@ HWTEST_F(VibratorAgentModulationTest, ModulateNonContinuousType, TestSize.Level1 ASSERT_TRUE(IsEventIdentical(pattern.events[eventIdx], patternAfterMod.events[eventIdx])); } } - ASSERT_EQ(PlayModulatedPattern(packageAfterModulation), TEST_SUCCESS); + if (tokenID_ != INVALID_TOKEN_ID) { + MISC_HILOGI("start to play modulated pattern"); + ASSERT_EQ(PlayModulatedPattern(packageAfterModulation), TEST_SUCCESS); + } else { + MISC_HILOGW("unable to play modulated pattern due to privilege issue, skip"); + } ASSERT_EQ(FreeVibratorPackage(package), 0); ASSERT_EQ(FreeVibratorPackage(packageAfterModulation), 0); ASSERT_EQ(FreeVibratorPackage(modulationPackage), 0); @@ -428,7 +425,12 @@ HWTEST_F(VibratorAgentModulationTest, ContinuousTypeWithCurvePoint, TestSize.Lev FreeEvent(expectedEvent); } } - ASSERT_EQ(PlayModulatedPattern(packageAfterModulation), TEST_SUCCESS); + if (tokenID_ != INVALID_TOKEN_ID) { + MISC_HILOGI("start to play modulated pattern"); + ASSERT_EQ(PlayModulatedPattern(packageAfterModulation), TEST_SUCCESS); + } else { + MISC_HILOGW("unable to play modulated pattern due to privilege issue, skip"); + } ASSERT_EQ(FreeVibratorPackage(package), 0); ASSERT_EQ(FreeVibratorPackage(packageAfterModulation), 0); ASSERT_EQ(FreeVibratorPackage(modulationPackage), 0); @@ -466,7 +468,12 @@ HWTEST_F(VibratorAgentModulationTest, ContinuousTypeWithoutCurvePoint, TestSize. FreeEvent(expectedEvent); } } - ASSERT_EQ(PlayModulatedPattern(packageAfterModulation), TEST_SUCCESS); + if (tokenID_ != INVALID_TOKEN_ID) { + MISC_HILOGI("start to play modulated pattern"); + ASSERT_EQ(PlayModulatedPattern(packageAfterModulation), TEST_SUCCESS); + } else { + MISC_HILOGW("unable to play modulated pattern due to privilege issue, skip"); + } ASSERT_EQ(FreeVibratorPackage(package), 0); ASSERT_EQ(FreeVibratorPackage(packageAfterModulation), 0); ASSERT_EQ(FreeVibratorPackage(modulationPackage), 0); @@ -546,7 +553,12 @@ HWTEST_F(VibratorAgentModulationTest, ContinuousTypeWithCurvePointAndEventStartT FreeEvent(expectedEvent); } } - ASSERT_EQ(PlayModulatedPattern(packageAfterModulation), TEST_SUCCESS); + if (tokenID_ != INVALID_TOKEN_ID) { + MISC_HILOGI("start to play modulated pattern"); + ASSERT_EQ(PlayModulatedPattern(packageAfterModulation), TEST_SUCCESS); + } else { + MISC_HILOGW("unable to play modulated pattern due to privilege issue, skip"); + } ASSERT_EQ(FreeVibratorPackage(package), 0); ASSERT_EQ(FreeVibratorPackage(packageAfterModulation), 0); ASSERT_EQ(FreeVibratorPackage(modulationPackage), 0); @@ -681,7 +693,12 @@ HWTEST_F(VibratorAgentModulationTest, FadeInFadeOut, TestSize.Level1) FreeEvent(expectedEvent); } } - ASSERT_EQ(PlayModulatedPattern(packageAfterModulation), TEST_SUCCESS); + if (tokenID_ != INVALID_TOKEN_ID) { + MISC_HILOGI("start to play modulated pattern"); + ASSERT_EQ(PlayModulatedPattern(packageAfterModulation), TEST_SUCCESS); + } else { + MISC_HILOGW("unable to play modulated pattern due to privilege issue, skip"); + } ASSERT_EQ(FreeVibratorPackage(package), 0); ASSERT_EQ(FreeVibratorPackage(packageAfterModulation), 0); free(modulationCurve); diff --git a/utils/common/include/vibrator_infos.h b/utils/common/include/vibrator_infos.h index e9f6a0c5a1aeb09095571c7d88f873fecf9f7d91..270052493f0670b31e7e573053a35577acf3769e 100644 --- a/utils/common/include/vibrator_infos.h +++ b/utils/common/include/vibrator_infos.h @@ -98,7 +98,6 @@ struct VibratePackage { }; struct VibratePackageIPC : public Parcelable { - int32_t patternNum = 0; int32_t packageDuration = 0; std::vector patterns; void Dump() const; diff --git a/utils/common/src/file_utils.cpp b/utils/common/src/file_utils.cpp index fff2eacc41fa6d20e4977c3e3dc98ebaefb379ec..134983a8d68ab6d1b0148ba0ef979f83fb66d095 100755 --- a/utils/common/src/file_utils.cpp +++ b/utils/common/src/file_utils.cpp @@ -113,7 +113,7 @@ int32_t GetFileName(const int32_t &fd, std::string &fileName) return ERROR; } - ret = readlink(buf, filePath, FILE_PATH_MAX); + ret = readlink(buf, filePath, FILE_PATH_MAX - 1); if (ret < 0 || ret >= FILE_PATH_MAX) { MISC_HILOGE("readlink failed with %{public}d", errno); return ERROR; diff --git a/utils/common/src/vibrator_infos.cpp b/utils/common/src/vibrator_infos.cpp index 881f949a5cb000d1aa3f9fd432721775ff775d3c..20aa75187f4a30dbeff853b808260b1b5d22b2d4 100644 --- a/utils/common/src/vibrator_infos.cpp +++ b/utils/common/src/vibrator_infos.cpp @@ -21,6 +21,10 @@ namespace OHOS { namespace Sensors { +namespace { +constexpr int32_t MAX_PATTERN_NUM = 1000; +} // namespace + void VibratePattern::Dump() const { int32_t size = static_cast(events.size()); @@ -241,15 +245,11 @@ bool VibratePackageIPC::Marshalling(Parcel &parcel) const MISC_HILOGE("Write packageDuration failed"); return false; } - if (!parcel.WriteInt32(patternNum)) { + if (!parcel.WriteInt32(static_cast(patterns.size()))) { MISC_HILOGE("Write pattern's patternNum failed"); return false; } - if (patternNum != static_cast(patterns.size())) { - MISC_HILOGE("patternNum does not match patterns size"); - return false; - } - for (int32_t i = 0; i < patternNum; ++i) { + for (size_t i = 0; i < patterns.size(); ++i) { if (!parcel.WriteInt32(patterns[i].startTime)) { MISC_HILOGE("Write pattern's startTime failed"); return false; @@ -322,17 +322,22 @@ VibratePackageIPC* VibratePackageIPC::Unmarshalling(Parcel &data) return package; } int32_t patternNum{ 0 }; - if (!(data.ReadInt32(patternNum)) || patternNum > MAX_EVENT_SIZE) { + if (!data.ReadInt32(patternNum) || patternNum < 0 || patternNum > MAX_PATTERN_NUM) { MISC_HILOGE("Read patternNum failed or patternNum exceed the maximum"); delete package; package = nullptr; return package; } - package->patternNum = patternNum; for (int32_t i = 0; i < patternNum; ++i) { VibratePattern pattern; - if (!(data.ReadInt32(pattern.startTime)) || !(data.ReadInt32(pattern.patternDuration))) { - MISC_HILOGE("Read pattern basic info failed"); + if (!data.ReadInt32(pattern.startTime)) { + MISC_HILOGE("Read pattern startTime failed"); + delete package; + package = nullptr; + return package; + } + if (!data.ReadInt32(pattern.patternDuration)) { + MISC_HILOGE("Read pattern patternDuration failed"); delete package; package = nullptr; return package; @@ -353,6 +358,12 @@ VibratePackageIPC* VibratePackageIPC::Unmarshalling(Parcel &data) package = nullptr; return package; } + if (tag != VibrateTag::EVENT_TAG_CONTINUOUS && tag != VibrateTag::EVENT_TAG_TRANSIENT) { + MISC_HILOGE("Invalid tag value"); + delete package; + package = nullptr; + return package; + } event.tag = static_cast(tag); if (!data.ReadInt32(event.time) || !data.ReadInt32(event.duration) || !data.ReadInt32(event.intensity) || !data.ReadInt32(event.frequency) || !data.ReadInt32(event.index)) { @@ -636,6 +647,7 @@ CustomHapticInfoIPC* CustomHapticInfoIPC::Unmarshalling(Parcel &data) } if (!data.ReadUint32(customHapticInfoIPC->parameter.sessionId)) { MISC_HILOGE("Read sessionId failed"); + delete customHapticInfoIPC; customHapticInfoIPC = nullptr; return customHapticInfoIPC; } diff --git a/utils/haptic_decoder/interface/vibrator_decoder_creator.cpp b/utils/haptic_decoder/interface/vibrator_decoder_creator.cpp index b20d143fa44224b47b82baee8384554a46b3af7d..d2b5f4a84f0ca1bc78d5bfdafd3ad2fc75c4b19d 100644 --- a/utils/haptic_decoder/interface/vibrator_decoder_creator.cpp +++ b/utils/haptic_decoder/interface/vibrator_decoder_creator.cpp @@ -38,6 +38,8 @@ IVibratorDecoder *VibratorDecoderCreator::CreateDecoder(const JsonParser &parser HEVibratorDecoderFactory factory; return factory.CreateDecoder(); } + MISC_HILOGE("Create decoder fail"); + return nullptr; } bool VibratorDecoderCreator::CheckJsonMetadata(const JsonParser &parser) diff --git a/utils/tools/haptic_format_converter/.gitignore b/utils/tools/haptic_format_converter/.gitignore deleted file mode 100644 index 472ecfa9b8f13c4e45e0977b54207ad5979f00ed..0000000000000000000000000000000000000000 --- a/utils/tools/haptic_format_converter/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -output_dir/* -*/output_dir/* -__pycache__/* -*/__pycache__/* diff --git a/utils/tools/haptic_format_converter/README.md b/utils/tools/haptic_format_converter/README.md deleted file mode 100644 index bf420273013dffd1cb02857592fe11486986f459..0000000000000000000000000000000000000000 --- a/utils/tools/haptic_format_converter/README.md +++ /dev/null @@ -1,48 +0,0 @@ -## Introduction - -This is a python script to convert between OH Haptic JSON and HE Haptic JSON formats. - -## Requirements - -- Python 3.8+ -- `pip3 install jsonschema` if needed - -## Usage -``` -usage: converter.py [-h] [-o OUTPUT] -f {oh,he_v1,he_v2} [-s SCHEMA_DIR] [-v] input - -Convert between OH Haptic JSON and HE Haptic JSON formats. - -positional arguments: - input Path to the input JSON file or directory. - -options: - -h, --help show this help message and exit - -o OUTPUT, --output OUTPUT - Path to the output directory (default: input directory with '_out' suffix). - -f {oh,he_v1,he_v2}, --format {oh,he_v1,he_v2} - Target format: 'oh', 'he_v1', or 'he_v2'. - -s SCHEMA_DIR, --schema_dir SCHEMA_DIR - Directory containing JSON schema files (default: 'schemas'). - -v, --version_suffix Include version suffix ('_v1' or '_v2') in output HE file names. - -``` - - -## Run command example - -convert oh to he_v2 - -``` -./converter.py ../tests/test_data/oh_sample.json -o output_dir -f he_v2 - -``` - - -## Test command example - -Need add more test cases to cover corner case - -``` -python3 -m unittest discover -s tests -``` diff --git a/utils/tools/haptic_format_converter/converter/__init__.py b/utils/tools/haptic_format_converter/converter/__init__.py deleted file mode 100644 index 0985da10bf2f5835269174ce3199a486b432bd6a..0000000000000000000000000000000000000000 --- a/utils/tools/haptic_format_converter/converter/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright (c) 2024 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. - -# converter/__init__.py -from .converter import ( - convert_oh_to_he_v1, - convert_oh_to_he_v2, - convert_he_v1_to_oh, - convert_he_v2_to_oh, - convert_he_v1_to_v2, - convert_he_v2_to_v1 -) diff --git a/utils/tools/haptic_format_converter/converter/converter.py b/utils/tools/haptic_format_converter/converter/converter.py deleted file mode 100644 index d67341d8eec27739e66d9ae403d5cc8ed08c9fbe..0000000000000000000000000000000000000000 --- a/utils/tools/haptic_format_converter/converter/converter.py +++ /dev/null @@ -1,635 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright (c) 2024 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. - -""" -Haptic JSON Converter - -This tool converts between OH Haptic JSON and HE Haptic JSON formats (v1 and v2). - -Version: v0.0.1 - -Usage: - converter.py [-o ] -f [-s ] [-v] - -Arguments: - input Path to the input JSON file or directory. - -o, --output Path to the output directory (default: input directory with '_out' suffix). - -f, --format Target format: 'oh', 'he_v1', or 'he_v2'. - -s, --schema_dir Directory containing JSON schema files (default: 'schemas'). - -v, --version_suffix Include version suffix ('_v1' or '_v2') in output HE file names. -""" - -import json -import argparse -import os -from pathlib import Path -import logging -from typing import Union, Dict, Any, Tuple - -import jsonschema -from jsonschema import validate - -# Configure logging -logging.basicConfig(level=logging.INFO, - format='%(asctime)s - %(levelname)s - %(message)s') - -# Constants for target formats -FORMAT_OH = 'oh' -FORMAT_HE_V1 = 'he_v1' -FORMAT_HE_V2 = 'he_v2' - -# Type alias for JSON data -JsonData = Dict[str, Any] - - -def load_schema(file_path: Union[str, Path]) -> JsonData: - """ - Load a JSON schema from the specified file. - - Args: - file_path (Union[str, Path]): Path to the JSON schema file. - - Returns: - JsonData: Parsed JSON schema. - """ - file_path = Path(file_path) - try: - with file_path.open('r', encoding='utf-8') as file: - return json.load(file) - except (FileNotFoundError, json.JSONDecodeError) as err: - logging.error("Error loading schema from %s: %s", file_path, err) - raise - - -def read_json(file_path: Union[str, Path]) -> JsonData: - """ - Read JSON data from a file. - - Args: - file_path (Union[str, Path]): Path to the JSON file. - - Returns: - JsonData: Parsed JSON data. - """ - file_path = Path(file_path) - try: - with file_path.open('r', encoding='utf-8') as file: - return json.load(file) - except (FileNotFoundError, json.JSONDecodeError) as err: - logging.error("Error reading JSON file %s: %s", file_path, err) - raise - - -def write_json(data: JsonData, file_path: Path) -> None: - """ - Write JSON data to a file. - - Args: - data (JsonData): JSON data to write. - file_path (Path): Path to the output file. - """ - try: - file_path.parent.mkdir(parents=True, exist_ok=True) - with file_path.open('w', encoding='utf-8') as file: - json.dump(data, file, indent=2) - except (OSError, json.JSONDecodeError) as err: - logging.error("Error writing JSON file %s: %s", file_path, err) - raise - - -def validate_json(data: JsonData, schema: JsonData) -> Tuple[bool, Union[None, jsonschema.exceptions.ValidationError]]: - """ - Validate JSON data against a schema. - - Args: - data (JsonData): JSON data to validate. - schema (JsonData): JSON schema to validate against. - - Returns: - Tuple[bool, Union[None, jsonschema.exceptions.ValidationError]]: Validation result and error if invalid. - """ - try: - validate(data, schema) - return True, None - except jsonschema.exceptions.ValidationError as err: - return False, err - - -def convert_oh_to_he_v1(oh_data: JsonData) -> JsonData: - """ - Convert OH JSON data to HE v1 format. - - Args: - oh_data (JsonData): OH JSON data. - - Returns: - JsonData: Converted HE v1 JSON data. - """ - he_data = { - "Metadata": { - "Version": 1 - }, - "Pattern": [] - } - - for channel in oh_data['Channels']: - for pattern in channel['Pattern']: - event = pattern['Event'] - he_event = { - "Type": event['Type'], - "RelativeTime": event['StartTime'], - "Parameters": { - "Intensity": event['Parameters']['Intensity'], - "Frequency": event['Parameters']['Frequency'] - } - } - if event['Type'] == 'continuous': - he_event['Duration'] = event['Duration'] - if 'Curve' in event['Parameters']: - he_event['Parameters']['Curve'] = [ - { - "Time": curve_point['Time'], - "Intensity": curve_point.get('Intensity', 0), - "Frequency": curve_point.get('Frequency', 0) - } - for curve_point in event['Parameters']['Curve'] - ] - else: - # Add default curve information if 'Curve' is not in parameters - he_event['Parameters']['Curve'] = [ - { - "Time": time, - "Intensity": 100, - "Frequency": 0 - } - for time in range(4) # Add four default points to satisfy CURVE_POINT_NUM_MIN - ] - he_data['Pattern'].append(he_event) - - return he_data - - -def convert_oh_to_he_v2(oh_data: JsonData) -> JsonData: - """ - Convert OH JSON data to HE v2 format. - - Args: - oh_data (JsonData): OH JSON data. - - Returns: - JsonData: Converted HE v2 JSON data. - """ - he_v2_data = { - "Metadata": { - "Version": 2 - }, - "PatternList": [] - } - - current_pattern = None - last_event_end_time = -1 # Tracks the end time of the last event in the current pattern - - for channel in oh_data["Channels"]: - for pattern in channel["Pattern"]: - event = pattern["Event"] - event_start_time = event["StartTime"] - event_end_time = event_start_time + \ - (event["Duration"] if event["Type"] == - "continuous" else 48) # Default transient duration - - if current_pattern is None or not isinstance(current_pattern, dict) or len(current_pattern.get("Pattern", [])) >= 16 \ - or (last_event_end_time != -1 and event_start_time - last_event_end_time > 1000): - if current_pattern and isinstance(current_pattern, dict): - he_v2_data["PatternList"].append(current_pattern) - current_pattern = { - "AbsoluteTime": event_start_time, - "Pattern": [] - } - - if event["Type"] == "continuous": - he_event = { - "Type": event["Type"], - "RelativeTime": event_start_time - current_pattern["AbsoluteTime"], - "Duration": event["Duration"], - "Parameters": { - "Intensity": event["Parameters"]["Intensity"], - "Frequency": event["Parameters"].get("Frequency", 50) - } - } - if "Curve" in event["Parameters"]: - he_event["Parameters"]["Curve"] = [ - { - "Time": point["Time"], - "Intensity": point.get("Intensity", 100), - # Assigning default value of 0 if Frequency is None - "Frequency": point.get("Frequency", 0) - } - for point in event["Parameters"]["Curve"] - if "Intensity" in point or "Frequency" in point - ] - else: - # Add default curve information if 'Curve' is not in parameters - he_event["Parameters"]["Curve"] = [ - { - "Time": time, - "Intensity": 100, - "Frequency": 0 - } - for time in range(0, 4) # Add four default points to satisfy least need curve in hev2 - ] - current_pattern["Pattern"].append(he_event) - else: - he_event = { - "Type": event["Type"], - "RelativeTime": event_start_time - current_pattern["AbsoluteTime"], - "Parameters": { - "Intensity": event["Parameters"]["Intensity"], - "Frequency": event["Parameters"].get("Frequency", 50) - } - } - current_pattern["Pattern"].append(he_event) - last_event_end_time = event_end_time - - if current_pattern: - he_v2_data["PatternList"].append(current_pattern) - - return he_v2_data - - -def convert_he_v1_to_v2(he_v1_data: JsonData) -> JsonData: - """ - Convert HE V1 JSON data to HE V2 format. - - Args: - data (JsonData): HE V1 JSON data. - - Returns: - JsonData: Converted HE V2 JSON data. - """ - converted_data = { - "Metadata": { - "Version": 2 - }, - "PatternList": [] - } - - current_pattern = None - last_event_end_time = -1 # Tracks the end time of the last event in the current pattern - - for event in he_v1_data["Pattern"]: - event_start_time = event["RelativeTime"] - event_end_time = event_start_time + \ - (event["Duration"] if event["Type"] == "continuous" else 48) - - if current_pattern is None or not isinstance(current_pattern, dict) or len(current_pattern.get("Pattern", [])) >= 16 \ - or (last_event_end_time != -1 and event_start_time - last_event_end_time > 1000): - if current_pattern and isinstance(current_pattern, dict): - converted_data["PatternList"].append(current_pattern) - current_pattern = { - "AbsoluteTime": event_start_time, - "Pattern": [] - } - - # Order of dictionary insertion matters - event_dict = { - "Type": event["Type"], - "RelativeTime": event_start_time - current_pattern["AbsoluteTime"] - } - - if event["Type"] == "continuous": - event_dict["Duration"] = event["Duration"] - - event_dict["Parameters"] = event["Parameters"] - - current_pattern["Pattern"].append(event_dict) - last_event_end_time = event_end_time - - if current_pattern: - converted_data["PatternList"].append(current_pattern) - - return converted_data - - -def convert_he_v2_to_v1(he_v2_data: JsonData) -> JsonData: - """ - Convert HE v2 JSON data to HE v1 format. - - Args: - he_v2_data (JsonData): HE v2 JSON data. - - Returns: - JsonData: Converted HE v1 JSON data. - """ - he_v1_data = { - "Metadata": { - "Version": 1 - }, - "Pattern": [] - } - - for pattern_list_entry in he_v2_data['PatternList']: - for event in pattern_list_entry['Pattern']: - he_v1_event = event.copy() - he_v1_event['RelativeTime'] = event['RelativeTime'] + \ - pattern_list_entry['AbsoluteTime'] - he_v1_data['Pattern'].append(he_v1_event) - - return he_v1_data - - -def clamp(value: float, min_value: float, max_value: float) -> float: - """ - Clamp a value between a minimum and maximum value. - - Args: - value (float): Value to clamp. - min_value (float): Minimum value. - max_value (float): Maximum value. - - Returns: - float: Clamped value. - """ - return max(min_value, min(value, max_value)) - - -def convert_he_v1_to_oh(he_v1_data: JsonData) -> JsonData: - """ - Convert HE v1 JSON data to OH format. - - Args: - he_v1_data (JsonData): HE v1 JSON data. - - Returns: - JsonData: Converted OH JSON data. - """ - output_data: JsonData = { - "MetaData": { - "Version": 1.0, - "ChannelNumber": 1 - }, - "Channels": [{ - "Parameters": { - "Index": 0 - }, - "Pattern": [] - }] - } - - for pattern in he_v1_data.get('Pattern', []): - event = { - "Event": { - "Type": pattern['Type'], - "StartTime": pattern['RelativeTime'], - "Parameters": { - "Intensity": clamp(pattern['Parameters']['Intensity'], 0, 100), - "Frequency": clamp(pattern['Parameters'].get('Frequency', 50), -100, 100) - } - } - } - if pattern['Type'] == 'continuous': - event['Event']['Duration'] = pattern['Duration'] - event['Event']['Parameters']['Curve'] = [ - { - "Time": point['Time'], - "Intensity": clamp(point.get('Intensity', 100), 0, 100), - "Frequency": clamp(point.get('Frequency', 0), -100, 100) - } - for point in pattern['Parameters'].get('Curve', []) - ] - output_data['Channels'][0]['Pattern'].append(event) - - return output_data - - -def convert_he_v2_to_oh(he_v2_data: JsonData) -> JsonData: - """ - Convert HE v2 JSON data to OH format. - - Args: - he_v2_data (JsonData): HE v2 JSON data. - - Returns: - JsonData: Converted OH JSON data. - """ - event_num_max = 128 - - output_data = { - "MetaData": { - "Version": 1.0, - "ChannelNumber": 1 - }, - "Channels": [ - { - "Parameters": { - "Index": 0 - }, - "Pattern": [] - } - ] - } - - all_events = [] - - for pattern_list_entry in he_v2_data.get('PatternList', []): - absolute_time = pattern_list_entry.get('AbsoluteTime', 0) - for pattern in pattern_list_entry.get('Pattern', []): - if pattern['Type'] == 'continuous': - event = { - "Event": { - "Type": pattern['Type'], - "StartTime": absolute_time + pattern.get('RelativeTime', 0), - "Duration": clamp(pattern.get('Duration', 1000), 1, 5000), - "Parameters": { - "Intensity": clamp(pattern['Parameters'].get('Intensity', 100), 0, 100), - "Frequency": clamp(pattern['Parameters'].get('Frequency', 50), -100, 100), - "Curve": [ - { - "Time": clamp(point.get('Time', 0), 0, 10000), - "Intensity": clamp(point.get('Intensity', 100), 0, 100), - "Frequency": clamp(point.get('Frequency', 0), -100, 100) - } - for point in pattern['Parameters'].get('Curve', []) - ] - } - } - } - else: - event = { - "Event": { - "Type": pattern['Type'], - "StartTime": absolute_time + pattern.get('RelativeTime', 0), - "Parameters": { - "Intensity": clamp(pattern['Parameters'].get('Intensity', 100), 0, 100), - "Frequency": clamp(pattern['Parameters'].get('Frequency', 50), -100, 100) - } - } - } - all_events.append(event) - - all_events.sort(key=lambda e: e['Event']['StartTime']) - - for event in all_events: - index = event['Event'].get('Index', 0) - channel_found = False - - for channel in output_data['Channels']: - if channel['Parameters']['Index'] == index: - if len(channel['Pattern']) < event_num_max: - channel['Pattern'].append(event) - channel_found = True - break - - if not channel_found: - if len(output_data['Channels']) < 3: - new_channel = { - "Parameters": { - "Index": index - }, - "Pattern": [event] - } - output_data['Channels'].append(new_channel) - - return output_data - - -def process_file(input_file: Union[str, Path], output_dir: Union[str, Path], target_format: str, schema_dir: Union[str, Path], version_suffix: bool) -> None: - """ - Process a single JSON file and convert it to the target format. - - Args: - input_file (Union[str, Path]): Path to the input JSON file. - output_dir (Union[str, Path]): Path to the output directory. - target_format (str): Target format: 'oh', 'he_v1', or 'he_v2'. - schema_dir (Union[str, Path]): Directory containing JSON schema files. - version_suffix (bool): Include version suffix ('_v1' or '_v2') in output HE file names. - """ - input_file = Path(input_file) - output_dir = Path(output_dir) - schema_dir = Path(schema_dir) - - try: - input_data = read_json(input_file) - - # Load schemas - schemas = { - FORMAT_OH: load_schema(os.path.join(schema_dir, 'oh_schema.json')), - FORMAT_HE_V1: load_schema(os.path.join(schema_dir, 'he_v1_schema.json')), - FORMAT_HE_V2: load_schema(os.path.join(schema_dir, 'he_v2_schema.json')), - } - - # Determine the schema to validate against - input_format = None - for in_format, schema in schemas.items(): - is_valid, _ = validate_json(input_data, schema) - if is_valid: - input_format = in_format - break - - if not input_format: - logging.error("No valid schema found for file %s", input_file) - return - - # Define a mapping of conversion functions and output extensions - conversion_map = { - (FORMAT_OH, FORMAT_HE_V1): (convert_oh_to_he_v1, '_v1.he', '.he'), - (FORMAT_OH, FORMAT_HE_V2): (convert_oh_to_he_v2, '_v2.he', '.he'), - (FORMAT_HE_V1, FORMAT_OH): (convert_he_v1_to_oh, '.json', '.json'), - (FORMAT_HE_V1, FORMAT_HE_V2): (convert_he_v1_to_v2, '_v2.he', '.he'), - (FORMAT_HE_V2, FORMAT_OH): (convert_he_v2_to_oh, '.json', '.json'), - (FORMAT_HE_V2, FORMAT_HE_V1): (convert_he_v2_to_v1, '_v1.he', '.he'), - } - - # Perform conversion based on input format and target format - if (input_format, target_format) in conversion_map: - convert_func, versioned_ext, default_ext = conversion_map[(input_format, target_format)] - output_data = convert_func(input_data) - output_ext = versioned_ext if version_suffix else default_ext - else: - output_data = input_data if input_format in [FORMAT_OH, FORMAT_HE_V1, FORMAT_HE_V2] else None - output_ext = '.json' if input_format == FORMAT_OH else (f'_{input_format.lower()}.he' if version_suffix else '.he') - if output_data is None: - logging.error("Unsupported input format for file %s", input_file) - return - - # Validate the output data with the target format schema - target_schema = schemas[target_format] - is_valid, error = validate_json(output_data, target_schema) - if not is_valid: - logging.error("Validation error for the converted data against %s schema: %s", target_format, error) - return - - output_file = output_dir / (input_file.stem + output_ext) - write_json(output_data, output_file) - except (FileNotFoundError, json.JSONDecodeError, jsonschema.exceptions.ValidationError) as err: - logging.error("Error processing file %s: %s", input_file, err) - - -def process_directory(input_dir: Union[str, Path], output_dir: Union[str, Path], target_format: str, schema_dir: Union[str, Path], version_suffix: bool) -> None: - """ - Process all JSON files in a directory and convert them to the target format. - - Args: - input_dir (Union[str, Path]): Path to the input directory. - output_dir (Union[str, Path]): Path to the output directory. - target_format (str): Target format: 'oh', 'he_v1', or 'he_v2'. - schema_dir (Union[str, Path]): Directory containing JSON schema files. - version_suffix (bool): Include version suffix ('_v1' or '_v2') in output HE file names. - """ - input_dir = Path(input_dir) - output_dir = Path(output_dir) - - for root, _, files in os.walk(input_dir): - for file in files: - if file.endswith('.json') or file.endswith('.he'): - input_file = os.path.join(root, file) - process_file(input_file, output_dir, target_format, - schema_dir, version_suffix) - - -def main() -> None: - """ - Main entry point of the script. Parses arguments and processes the input accordingly. - """ - parser = argparse.ArgumentParser( - description="Convert between OH Haptic JSON and HE Haptic JSON formats.") - parser.add_argument("input", type=Path, - help="Path to the input JSON file or directory.") - parser.add_argument("-o", "--output", type=Path, - help="Path to the output dir (default: input dir with '_out' suffix).") - parser.add_argument("-f", "--format", choices=[FORMAT_OH, FORMAT_HE_V1, FORMAT_HE_V2], - required=True, help="Target format: 'oh', 'he_v1', or 'he_v2'.") - parser.add_argument("-s", "--schema_dir", type=Path, default=Path("schemas"), - help="Directory containing JSON schema files (default: 'schemas').") - parser.add_argument("-v", "--version_suffix", action="store_true", - help="Include version suffix ('_v1' or '_v2') in output HE file names.") - - args = parser.parse_args() - - if args.input.is_file(): - input_file = args.input - output_dir = args.output or args.input.parent - process_file(input_file, output_dir, args.format, - args.schema_dir, args.version_suffix) - elif args.input.is_dir(): - input_dir = args.input - output_dir = args.output or input_dir.with_name( - input_dir.name + '_out') - process_directory(input_dir, output_dir, args.format, - args.schema_dir, args.version_suffix) - else: - raise ValueError(f"Invalid input path: {args.input}") - -if __name__ == "__main__": - main() diff --git a/utils/tools/haptic_format_converter/converter/schemas/he_v1_schema.json b/utils/tools/haptic_format_converter/converter/schemas/he_v1_schema.json deleted file mode 100644 index a3f561dd1b706ec25b27dbfeef5b854db9059066..0000000000000000000000000000000000000000 --- a/utils/tools/haptic_format_converter/converter/schemas/he_v1_schema.json +++ /dev/null @@ -1,148 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "HE HapticJsonSchema V1", - "type": "object", - "properties": { - "Metadata": { - "type": "object", - "properties": { - "Version": { - "type": "integer", - "enum": [1], - "description": "Supported version is 1" - } - }, - "required": ["Version"] - }, - "Pattern": { - "type": "array", - "items": { - "$ref": "#/definitions/Event" - }, - "minItems": 1, - "maxItems": 16, - "description": "List of events in the pattern. Required and only applicable for version 1." - } - }, - "definitions": { - "Event": { - "type": "object", - "properties": { - "Type": { - "type": "string", - "enum": ["transient", "continuous"], - "description": "Type of the event, can be transient or continuous" - }, - "Duration": { - "type": "integer", - "minimum": 1, - "maximum": 5000, - "description": "Duration of the event in milliseconds. Only applicable for continuous events." - }, - "Index": { - "type": "integer", - "minimum": 0, - "maximum": 2, - "default": 0, - "description": "Index of the event" - }, - "RelativeTime": { - "type": "integer", - "minimum": 0, - "description": "Relative start time of the event within the pattern" - }, - "Parameters": { - "type": "object", - "properties": { - "Intensity": { - "type": "integer", - "minimum": 0, - "maximum": 100, - "description": "Intensity of the event" - }, - "Frequency": { - "type": "integer", - "minimum": -100, - "maximum": 150, - "description": "Frequency of the event" - }, - "Curve": { - "type": "array", - "items": { - "type": "object", - "properties": { - "Time": { - "type": "integer", - "minimum": 0, - "description": "Relative time of the curve point within the event duration" - }, - "Intensity": { - "type": "integer", - "minimum": 0, - "maximum": 100, - "description": "Intensity of the curve point, scaled from 0 to 100" - }, - "Frequency": { - "type": "integer", - "minimum": -100, - "maximum": 100, - "description": "Frequency of the curve point" - } - }, - "required": ["Time", "Intensity", "Frequency"] - }, - "minItems": 4, - "maxItems": 16, - "description": "Curve points defining the haptic effect over time. Only applicable for continuous events." - } - }, - "required": ["Intensity", "Frequency"] - } - }, - "required": ["Type", "RelativeTime", "Parameters"], - "if": { - "properties": { "Type": { "const": "transient" } } - }, - "then": { - "properties": { - "Duration": { - "const": 48, - "description": "Duration for transient events is fixed to 48 milliseconds" - }, - "Parameters": { - "properties": { - "Frequency": { - "minimum": -50, - "maximum": 150 - } - } - } - } - }, - "else": { - "properties": { - "Parameters": { - "properties": { - "Frequency": { - "minimum": 0, - "maximum": 100 - }, - "Curve": { - "minItems": 4, - "maxItems": 16 - } - }, - "required": ["Curve"] - }, - "Duration": { - "minimum": 1, - "maximum": 5000 - } - }, - "required": ["Duration"] - } - } - }, - "required": ["Metadata", "Pattern"] -} - diff --git a/utils/tools/haptic_format_converter/converter/schemas/he_v2_schema.json b/utils/tools/haptic_format_converter/converter/schemas/he_v2_schema.json deleted file mode 100644 index e5e03d49eccee445750a3cbc0cab6cb7ec98a0e3..0000000000000000000000000000000000000000 --- a/utils/tools/haptic_format_converter/converter/schemas/he_v2_schema.json +++ /dev/null @@ -1,164 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "HE HapticJsonSchema V2", - "type": "object", - "properties": { - "Metadata": { - "type": "object", - "properties": { - "Version": { - "type": "integer", - "enum": [2], - "description": "Supported version is 2" - } - }, - "required": ["Version"] - }, - "PatternList": { - "type": "array", - "items": { - "type": "object", - "properties": { - "AbsoluteTime": { - "type": "integer", - "minimum": 0, - "description": "Absolute start time of the pattern. Should be greater than the previous pattern's start time." - }, - "Pattern": { - "type": "array", - "items": { - "$ref": "#/definitions/Event" - }, - "minItems": 1, - "maxItems": 16, - "description": "List of events in the pattern" - } - }, - "required": ["AbsoluteTime", "Pattern"] - }, - "minItems": 1, - "description": "List of patterns with absolute start times. Required and only applicable for version 2." - } - }, - "definitions": { - "Event": { - "type": "object", - "properties": { - "Type": { - "type": "string", - "enum": ["transient", "continuous"], - "description": "Type of the event, can be transient or continuous" - }, - "Duration": { - "type": "integer", - "minimum": 1, - "maximum": 5000, - "description": "Duration of the event in milliseconds. Only applicable for continuous events." - }, - "Index": { - "type": "integer", - "minimum": 0, - "maximum": 2, - "default": 0, - "description": "Index of the event" - }, - "RelativeTime": { - "type": "integer", - "minimum": 0, - "description": "Relative start time of the event within the pattern" - }, - "Parameters": { - "type": "object", - "properties": { - "Intensity": { - "type": "integer", - "minimum": 0, - "maximum": 100, - "description": "Intensity of the event" - }, - "Frequency": { - "type": "integer", - "minimum": -100, - "maximum": 150, - "description": "Frequency of the event" - }, - "Curve": { - "type": "array", - "items": { - "type": "object", - "properties": { - "Time": { - "type": "integer", - "minimum": 0, - "description": "Relative time of the curve point within the event duration" - }, - "Intensity": { - "type": "integer", - "minimum": 0, - "maximum": 100, - "description": "Intensity of the curve point, scaled from 0 to 100" - }, - "Frequency": { - "type": "integer", - "minimum": -100, - "maximum": 100, - "description": "Frequency of the curve point" - } - }, - "required": ["Time", "Intensity", "Frequency"] - }, - "minItems": 4, - "maxItems": 16, - "description": "Curve points defining the haptic effect over time. Only applicable for continuous events." - } - }, - "required": ["Intensity", "Frequency"] - } - }, - "required": ["Type", "RelativeTime", "Parameters"], - "if": { - "properties": { "Type": { "const": "transient" } } - }, - "then": { - "properties": { - "Duration": { - "const": 48, - "description": "Duration for transient events is fixed to 48 milliseconds" - }, - "Parameters": { - "properties": { - "Frequency": { - "minimum": -50, - "maximum": 150 - } - } - } - } - }, - "else": { - "properties": { - "Parameters": { - "properties": { - "Frequency": { - "minimum": 0, - "maximum": 100 - }, - "Curve": { - "minItems": 4, - "maxItems": 16 - } - }, - "required": ["Curve"] - }, - "Duration": { - "minimum": 1, - "maximum": 5000 - } - }, - "required": ["Duration"] - } - } - }, - "required": ["Metadata", "PatternList"] -} - diff --git a/utils/tools/haptic_format_converter/converter/schemas/oh_schema.json b/utils/tools/haptic_format_converter/converter/schemas/oh_schema.json deleted file mode 100644 index e2b1ae64f95a7f37d8c1704cff99375dc8067705..0000000000000000000000000000000000000000 --- a/utils/tools/haptic_format_converter/converter/schemas/oh_schema.json +++ /dev/null @@ -1,175 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "OH Haptic JSON Schema", - "type": "object", - "properties": { - "MetaData": { - "type": "object", - "properties": { - "Version": { - "type": "number", - "const": 1.0 - }, - "ChannelNumber": { - "type": "integer", - "minimum": 1, - "maximum": 3 - } - }, - "required": ["Version", "ChannelNumber"], - "additionalProperties": false - }, - "Channels": { - "type": "array", - "minItems": 1, - "maxItems": 3, - "items": { - "type": "object", - "properties": { - "Parameters": { - "type": "object", - "properties": { - "Index": { - "type": "integer", - "minimum": 0, - "maximum": 2 - } - }, - "required": ["Index"], - "additionalProperties": false - }, - "Pattern": { - "type": "array", - "maxItems": 128, - "items": { - "type": "object", - "properties": { - "Event": { - "type": "object", - "properties": { - "Type": { - "type": "string", - "enum": ["continuous", "transient"] - }, - "StartTime": { - "type": "integer", - "minimum": 0, - "maximum": 1800000 - }, - "Duration": { - "type": "integer", - "minimum": 0, - "maximum": 5000 - }, - "Parameters": { - "type": "object", - "properties": { - "Intensity": { - "type": "integer", - "minimum": 0, - "maximum": 100 - }, - "Frequency": { - "type": "integer", - "minimum": 0, - "maximum": 100 - }, - "Curve": { - "type": "array", - "minItems": 4, - "maxItems": 16, - "items": { - "type": "object", - "properties": { - "Time": { - "type": "integer", - "minimum": 0 - }, - "Intensity": { - "type": "integer", - "minimum": 0, - "maximum": 100 - }, - "Frequency": { - "type": "integer", - "minimum": -100, - "maximum": 100 - } - }, - "required": ["Time"], - "anyOf": [ - { - "required": ["Intensity"] - }, - { - "required": ["Frequency"] - } - ], - "additionalProperties": false - } - } - }, - "additionalProperties": false - } - }, - "required": ["Type", "StartTime"], - "allOf": [ - { - "if": { - "properties": { - "Type": { - "const": "continuous" - } - } - }, - "then": { - "properties": { - "Parameters": { - "required": ["Intensity", "Frequency"] - } - }, - "required": ["Duration"] - } - }, - { - "if": { - "properties": { - "Type": { - "const": "transient" - } - } - }, - "then": { - "properties": { - "Duration": { - "const": 48 - }, - "Parameters": { - "required": ["Intensity"], - "properties": { - "Frequency": { - "default": 50 - } - } - } - } - } - } - ], - "additionalProperties": false - } - }, - "required": ["Event"], - "additionalProperties": false - } - } - }, - "required": ["Parameters", "Pattern"], - "additionalProperties": false - } - } - }, - "required": ["MetaData", "Channels"], - "additionalProperties": false -} - diff --git a/utils/tools/haptic_format_converter/requirements.txt b/utils/tools/haptic_format_converter/requirements.txt deleted file mode 100644 index d89304b1a89d0f441beaefdc5ae5de22c95f06a2..0000000000000000000000000000000000000000 --- a/utils/tools/haptic_format_converter/requirements.txt +++ /dev/null @@ -1 +0,0 @@ -jsonschema diff --git a/utils/tools/haptic_format_converter/tests/__init__.py b/utils/tools/haptic_format_converter/tests/__init__.py deleted file mode 100644 index 0985da10bf2f5835269174ce3199a486b432bd6a..0000000000000000000000000000000000000000 --- a/utils/tools/haptic_format_converter/tests/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright (c) 2024 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. - -# converter/__init__.py -from .converter import ( - convert_oh_to_he_v1, - convert_oh_to_he_v2, - convert_he_v1_to_oh, - convert_he_v2_to_oh, - convert_he_v1_to_v2, - convert_he_v2_to_v1 -) diff --git a/utils/tools/haptic_format_converter/tests/test_converter.py b/utils/tools/haptic_format_converter/tests/test_converter.py deleted file mode 100644 index 7f431fe3830406b77a23c25ecc65c534bea7d611..0000000000000000000000000000000000000000 --- a/utils/tools/haptic_format_converter/tests/test_converter.py +++ /dev/null @@ -1,141 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright (c) 2024 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. -""" -Haptic JSON Converter testcases - -run `python3 -m unittest discover -s tests` in repo base folder: - -""" - -import unittest -from pathlib import Path -import json - -from converter.converter import ( - convert_oh_to_he_v1, - convert_oh_to_he_v2, - convert_he_v1_to_oh, - convert_he_v2_to_oh, - convert_he_v1_to_v2, - convert_he_v2_to_v1 -) - - -class TestConverter(unittest.TestCase): - - def setUp(self): - self.schema_dir = Path('converter/schemas') - self.test_data_dir = Path('tests/test_data') - self.output_dir = Path('converter/output_dir') - self.output_dir.mkdir(parents=True, exist_ok=True) - - def read_json(self, file_path): - with open(file_path, 'r', encoding='utf-8') as file: - return json.load(file) - - def test_oh_to_he_v1(self): - input_data = self.read_json(self.test_data_dir / 'oh_sample.json') - expected_output = self.read_json( - self.test_data_dir / 'oh_sample_to_he_v1.he') - converted_data = convert_oh_to_he_v1(input_data) - self.assertEqual(converted_data, expected_output) - - def test_oh_to_he_v2(self): - input_data = self.read_json(self.test_data_dir / 'oh_sample.json') - expected_output = self.read_json( - self.test_data_dir / 'oh_sample_to_he_v2.he') - converted_data = convert_oh_to_he_v2(input_data) - self.assertEqual(converted_data, expected_output) - - def test_he_v1_to_oh(self): - input_data = self.read_json(self.test_data_dir / 'he_v1_sample.he') - expected_output = self.read_json( - self.test_data_dir / 'he_v1_sample_to_oh.json') - converted_data = convert_he_v1_to_oh(input_data) - self.assertEqual(converted_data, expected_output) - - def test_he_v2_to_oh(self): - input_data = self.read_json(self.test_data_dir / 'he_v2_sample.he') - expected_output = self.read_json( - self.test_data_dir / 'he_v2_sample_to_oh.json') - converted_data = convert_he_v2_to_oh(input_data) - self.assertEqual(converted_data, expected_output) - - def test_he_v1_to_v2(self): - input_data = self.read_json(self.test_data_dir / 'he_v1_sample.he') - expected_output = self.read_json( - self.test_data_dir / 'he_v1_sample_to_he_v2.he') - converted_data = convert_he_v1_to_v2(input_data) - self.assertEqual(converted_data, expected_output) - - def test_he_v2_to_v1(self): - input_data = self.read_json(self.test_data_dir / 'he_v2_sample.he') - expected_output = self.read_json( - self.test_data_dir / 'he_v2_sample_to_he_v1.he') - converted_data = convert_he_v2_to_v1(input_data) - self.assertEqual(converted_data, expected_output) - - def test_he_v1_to_v2_to_v1(self): - input_data = self.read_json(self.test_data_dir / 'he_v1_sample.he') - expected_output1 = self.read_json( - self.test_data_dir / 'he_v1_sample_to_he_v2.he') - converted_data1 = convert_he_v1_to_v2(input_data) - self.assertEqual(converted_data1, expected_output1) - converted_data2 = convert_he_v2_to_v1(converted_data1) - self.assertEqual(converted_data2, input_data) - - def test_he_v2_to_he_v1_to_he_v2(self): - input_data = self.read_json(self.test_data_dir / 'he_v2_sample.he') - expected_output1 = self.read_json( - self.test_data_dir / 'he_v2_sample_to_he_v1.he') - converted_data1 = convert_he_v2_to_v1(input_data) - self.assertEqual(converted_data1, expected_output1) - converted_data2 = convert_he_v1_to_v2(converted_data1) - self.assertEqual(converted_data2, input_data) - - def test_oh_to_he_v2_to_oh(self): - input_data = self.read_json(self.test_data_dir / 'oh_sample_1.json') - expected_output1 = self.read_json( - self.test_data_dir / 'oh_sample_to_he_v2.he') - converted_data1 = convert_oh_to_he_v2(input_data) - self.assertEqual(converted_data1, expected_output1) - converted_data2 = convert_he_v2_to_oh(converted_data1) - self.assertEqual(converted_data2, input_data) - - def test_he_v2_to_oh_to_he_v2(self): - input_data = self.read_json(self.test_data_dir / 'he_v2_sample.he') - expected_output1 = self.read_json( - self.test_data_dir / 'he_v2_sample_to_oh.json') - converted_data1 = convert_he_v2_to_oh(input_data) - self.assertEqual(converted_data1, expected_output1) - converted_data2 = convert_oh_to_he_v2(converted_data1) - self.assertEqual(converted_data2, input_data) - - def test_oh_to_he_v2_with_default_curve(self): - input_data = self.read_json(self.test_data_dir / 'oh_no_curve_sample.json') - expected_output = self.read_json( - self.test_data_dir / 'oh_no_curve_sample_to_he_v2.json') - converted_data = convert_oh_to_he_v2(input_data) - self.assertEqual(converted_data, expected_output) - - def test_oh_to_he_v1_with_default_curve(self): - input_data = self.read_json(self.test_data_dir / 'oh_no_curve_sample.json') - expected_output = self.read_json( - self.test_data_dir / 'oh_no_curve_sample_to_he_v1.json') - converted_data = convert_oh_to_he_v1(input_data) - self.assertEqual(converted_data, expected_output) - -if __name__ == '__main__': - unittest.main() diff --git a/utils/tools/haptic_format_converter/tests/test_data/he_v1_sample.he b/utils/tools/haptic_format_converter/tests/test_data/he_v1_sample.he deleted file mode 100644 index 5a833850977cbf2d459063bf935fff9e7fcf8c06..0000000000000000000000000000000000000000 --- a/utils/tools/haptic_format_converter/tests/test_data/he_v1_sample.he +++ /dev/null @@ -1,46 +0,0 @@ -{ - "Metadata": { - "Version": 1 - }, - "Pattern": [ - { - "Type": "transient", - "RelativeTime": 0, - "Parameters": { - "Intensity": 100, - "Frequency": 100 - } - }, - { - "Type": "continuous", - "RelativeTime": 500, - "Duration": 1000, - "Parameters": { - "Intensity": 75, - "Frequency": 100, - "Curve": [ - { - "Time": 0, - "Intensity": 50, - "Frequency": 0 - }, - { - "Time": 100, - "Intensity": 70, - "Frequency": 10 - }, - { - "Time": 300, - "Intensity": 80, - "Frequency": 20 - }, - { - "Time": 500, - "Intensity": 100, - "Frequency": 30 - } - ] - } - } - ] -} diff --git a/utils/tools/haptic_format_converter/tests/test_data/he_v1_sample_to_he_v2.he b/utils/tools/haptic_format_converter/tests/test_data/he_v1_sample_to_he_v2.he deleted file mode 100644 index c9fa3f9d68f3f6cfde1a22098bedcfb5abc02d25..0000000000000000000000000000000000000000 --- a/utils/tools/haptic_format_converter/tests/test_data/he_v1_sample_to_he_v2.he +++ /dev/null @@ -1,51 +0,0 @@ -{ - "Metadata": { - "Version": 2 - }, - "PatternList": [ - { - "AbsoluteTime": 0, - "Pattern": [ - { - "Type": "transient", - "RelativeTime": 0, - "Parameters": { - "Intensity": 100, - "Frequency": 100 - } - }, - { - "Type": "continuous", - "RelativeTime": 500, - "Duration": 1000, - "Parameters": { - "Intensity": 75, - "Frequency": 100, - "Curve": [ - { - "Time": 0, - "Intensity": 50, - "Frequency": 0 - }, - { - "Time": 100, - "Intensity": 70, - "Frequency": 10 - }, - { - "Time": 300, - "Intensity": 80, - "Frequency": 20 - }, - { - "Time": 500, - "Intensity": 100, - "Frequency": 30 - } - ] - } - } - ] - } - ] -} diff --git a/utils/tools/haptic_format_converter/tests/test_data/he_v1_sample_to_oh.json b/utils/tools/haptic_format_converter/tests/test_data/he_v1_sample_to_oh.json deleted file mode 100644 index 4af4fa9f6d8f8a7da5a19fc6abdaf9747d6c64a4..0000000000000000000000000000000000000000 --- a/utils/tools/haptic_format_converter/tests/test_data/he_v1_sample_to_oh.json +++ /dev/null @@ -1,58 +0,0 @@ -{ - "MetaData": { - "Version": 1.0, - "ChannelNumber": 1 - }, - "Channels": [ - { - "Parameters": { - "Index": 0 - }, - "Pattern": [ - { - "Event": { - "Type": "transient", - "StartTime": 0, - "Parameters": { - "Intensity": 100, - "Frequency": 100 - } - } - }, - { - "Event": { - "Type": "continuous", - "StartTime": 500, - "Duration": 1000, - "Parameters": { - "Intensity": 75, - "Frequency": 100, - "Curve": [ - { - "Time": 0, - "Intensity": 50, - "Frequency": 0 - }, - { - "Time": 100, - "Intensity": 70, - "Frequency": 10 - }, - { - "Time": 300, - "Intensity": 80, - "Frequency": 20 - }, - { - "Time": 500, - "Intensity": 100, - "Frequency": 30 - } - ] - } - } - } - ] - } - ] -} \ No newline at end of file diff --git a/utils/tools/haptic_format_converter/tests/test_data/he_v2_sample.he b/utils/tools/haptic_format_converter/tests/test_data/he_v2_sample.he deleted file mode 100644 index a6abf48901fcb3543abe6a16fbc8b32fa214c70c..0000000000000000000000000000000000000000 --- a/utils/tools/haptic_format_converter/tests/test_data/he_v2_sample.he +++ /dev/null @@ -1,95 +0,0 @@ -{ - "Metadata": { - "Version": 2 - }, - "PatternList": [ - { - "AbsoluteTime": 0, - "Pattern": [ - { - "Type": "transient", - "RelativeTime": 0, - "Parameters": { - "Intensity": 100, - "Frequency": 100 - } - }, - { - "Type": "continuous", - "RelativeTime": 500, - "Duration": 1000, - "Parameters": { - "Intensity": 75, - "Frequency": 100, - "Curve": [ - { - "Time": 0, - "Intensity": 50, - "Frequency": 0 - }, - { - "Time": 100, - "Intensity": 70, - "Frequency": 10 - }, - { - "Time": 300, - "Intensity": 80, - "Frequency": 20 - }, - { - "Time": 500, - "Intensity": 100, - "Frequency": 30 - } - ] - } - } - ] - }, - { - "AbsoluteTime": 5000, - "Pattern": [ - { - "Type": "transient", - "RelativeTime": 0, - "Parameters": { - "Intensity": 80, - "Frequency": 100 - } - }, - { - "Type": "continuous", - "RelativeTime":200, - "Duration": 1500, - "Parameters": { - "Intensity": 60, - "Frequency": 90, - "Curve": [ - { - "Time": 0, - "Intensity": 30, - "Frequency": -10 - }, - { - "Time": 200, - "Intensity": 50, - "Frequency": 0 - }, - { - "Time": 600, - "Intensity": 70, - "Frequency": 10 - }, - { - "Time": 1500, - "Intensity": 90, - "Frequency": 20 - } - ] - } - } - ] - } - ] -} diff --git a/utils/tools/haptic_format_converter/tests/test_data/he_v2_sample_to_he_v1.he b/utils/tools/haptic_format_converter/tests/test_data/he_v2_sample_to_he_v1.he deleted file mode 100644 index 018bb0316e8abc1e9386761d4940e4f42cf73b7c..0000000000000000000000000000000000000000 --- a/utils/tools/haptic_format_converter/tests/test_data/he_v2_sample_to_he_v1.he +++ /dev/null @@ -1,85 +0,0 @@ -{ - "Metadata": { - "Version": 1 - }, - "Pattern": [ - { - "Type": "transient", - "RelativeTime": 0, - "Parameters": { - "Intensity": 100, - "Frequency": 100 - } - }, - { - "Type": "continuous", - "RelativeTime": 500, - "Duration": 1000, - "Parameters": { - "Intensity": 75, - "Frequency": 100, - "Curve": [ - { - "Time": 0, - "Intensity": 50, - "Frequency": 0 - }, - { - "Time": 100, - "Intensity": 70, - "Frequency": 10 - }, - { - "Time": 300, - "Intensity": 80, - "Frequency": 20 - }, - { - "Time": 500, - "Intensity": 100, - "Frequency": 30 - } - ] - } - }, - { - "Type": "transient", - "RelativeTime": 5000, - "Parameters": { - "Intensity": 80, - "Frequency": 100 - } - }, - { - "Type": "continuous", - "RelativeTime": 5200, - "Duration": 1500, - "Parameters": { - "Intensity": 60, - "Frequency": 90, - "Curve": [ - { - "Time": 0, - "Intensity": 30, - "Frequency": -10 - }, - { - "Time": 200, - "Intensity": 50, - "Frequency": 0 - }, - { - "Time": 600, - "Intensity": 70, - "Frequency": 10 - }, - { - "Time": 1500, - "Intensity": 90, - "Frequency": 20 - } - ] - } - } - ] -} \ No newline at end of file diff --git a/utils/tools/haptic_format_converter/tests/test_data/he_v2_sample_to_oh.json b/utils/tools/haptic_format_converter/tests/test_data/he_v2_sample_to_oh.json deleted file mode 100644 index 73f0359dda2e9b9c2846cc9dd45faaca6f1b6a11..0000000000000000000000000000000000000000 --- a/utils/tools/haptic_format_converter/tests/test_data/he_v2_sample_to_oh.json +++ /dev/null @@ -1,101 +0,0 @@ -{ - "MetaData": { - "Version": 1.0, - "ChannelNumber": 1 - }, - "Channels": [ - { - "Parameters": { - "Index": 0 - }, - "Pattern": [ - { - "Event": { - "Type": "transient", - "StartTime": 0, - "Parameters": { - "Intensity": 100, - "Frequency": 100 - } - } - }, - { - "Event": { - "Type": "continuous", - "StartTime": 500, - "Duration": 1000, - "Parameters": { - "Intensity": 75, - "Frequency": 100, - "Curve": [ - { - "Time": 0, - "Intensity": 50, - "Frequency": 0 - }, - { - "Time": 100, - "Intensity": 70, - "Frequency": 10 - }, - { - "Time": 300, - "Intensity": 80, - "Frequency": 20 - }, - { - "Time": 500, - "Intensity": 100, - "Frequency": 30 - } - ] - } - } - }, - { - "Event": { - "Type": "transient", - "StartTime": 5000, - "Parameters": { - "Intensity": 80, - "Frequency": 100 - } - } - }, - { - "Event": { - "Type": "continuous", - "StartTime": 5200, - "Duration": 1500, - "Parameters": { - "Intensity": 60, - "Frequency": 90, - "Curve": [ - { - "Time": 0, - "Intensity": 30, - "Frequency": -10 - }, - { - "Time": 200, - "Intensity": 50, - "Frequency": 0 - }, - { - "Time": 600, - "Intensity": 70, - "Frequency": 10 - }, - { - "Time": 1500, - "Intensity": 90, - "Frequency": 20 - } - ] - } - } - } - ] - } - ] -} diff --git a/utils/tools/haptic_format_converter/tests/test_data/oh_no_curve_sample.json b/utils/tools/haptic_format_converter/tests/test_data/oh_no_curve_sample.json deleted file mode 100644 index 909ae11b081673197cdbfac10658ee2a97d7d91a..0000000000000000000000000000000000000000 --- a/utils/tools/haptic_format_converter/tests/test_data/oh_no_curve_sample.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "MetaData": { - "Version": 1.0, - "ChannelNumber": 1 - }, - "Channels": [ - { - "Parameters": { - "Index": 0 - }, - "Pattern": [ - { - "Event": { - "Type": "continuous", - "StartTime": 100, - "Duration": 1200, - "Parameters": { - "Intensity": 90, - "Frequency": 60 - } - } - } - ] - } - ] -} - diff --git a/utils/tools/haptic_format_converter/tests/test_data/oh_no_curve_sample_to_he_v1.json b/utils/tools/haptic_format_converter/tests/test_data/oh_no_curve_sample_to_he_v1.json deleted file mode 100644 index b7ceb33ab727d595470633695929e7ad4cd618b8..0000000000000000000000000000000000000000 --- a/utils/tools/haptic_format_converter/tests/test_data/oh_no_curve_sample_to_he_v1.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "Metadata": { - "Version": 1 - }, - "Pattern": [ - { - "Type": "continuous", - "RelativeTime": 100, - "Duration": 1200, - "Parameters": { - "Intensity": 90, - "Frequency": 60, - "Curve": [ - { - "Time": 0, - "Intensity": 100, - "Frequency": 0 - }, - { - "Time": 1, - "Intensity": 100, - "Frequency": 0 - }, - { - "Time": 2, - "Intensity": 100, - "Frequency": 0 - }, - { - "Time": 3, - "Intensity": 100, - "Frequency": 0 - } - ] - } - } - ] -} \ No newline at end of file diff --git a/utils/tools/haptic_format_converter/tests/test_data/oh_no_curve_sample_to_he_v2.json b/utils/tools/haptic_format_converter/tests/test_data/oh_no_curve_sample_to_he_v2.json deleted file mode 100644 index f6af7199a1502abb122eac861e4595f38c2da399..0000000000000000000000000000000000000000 --- a/utils/tools/haptic_format_converter/tests/test_data/oh_no_curve_sample_to_he_v2.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "Metadata": { - "Version": 2 - }, - "PatternList": [ - { - "AbsoluteTime": 100, - "Pattern": [ - { - "Type": "continuous", - "RelativeTime": 0, - "Duration": 1200, - "Parameters": { - "Intensity": 90, - "Frequency": 60, - "Curve": [ - {"Time": 0, "Intensity": 100, "Frequency": 0}, - {"Time": 1, "Intensity": 100, "Frequency": 0}, - {"Time": 2, "Intensity": 100, "Frequency": 0}, - {"Time": 3, "Intensity": 100, "Frequency": 0} - ] - } - } - ] - } - ] -} - diff --git a/utils/tools/haptic_format_converter/tests/test_data/oh_sample.json b/utils/tools/haptic_format_converter/tests/test_data/oh_sample.json deleted file mode 100644 index 3284233ee931dbaaf3af2f50f859cee6d3878121..0000000000000000000000000000000000000000 --- a/utils/tools/haptic_format_converter/tests/test_data/oh_sample.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "MetaData": { - "Version": 1.0, - "ChannelNumber": 1 - }, - "Channels": [ - { - "Parameters": { - "Index": 0 - }, - "Pattern": [ - { - "Event": { - "Type": "transient", - "StartTime": 0, - "Parameters": { - "Intensity": 100, - "Frequency": 100 - } - } - }, - { - "Event": { - "Type": "continuous", - "StartTime": 500, - "Duration": 1000, - "Parameters": { - "Intensity": 75, - "Frequency": 100, - "Curve": [ - { - "Time": 0, - "Intensity": 50 - }, - { - "Time": 100, - "Intensity": 70 - }, - { - "Time": 300, - "Intensity": 80 - }, - { - "Time": 500, - "Intensity": 100 - } - ] - } - } - } - ] - } - ] -} - diff --git a/utils/tools/haptic_format_converter/tests/test_data/oh_sample_1.json b/utils/tools/haptic_format_converter/tests/test_data/oh_sample_1.json deleted file mode 100644 index 0145eb1fce5cca3993500cc82b7669885166900e..0000000000000000000000000000000000000000 --- a/utils/tools/haptic_format_converter/tests/test_data/oh_sample_1.json +++ /dev/null @@ -1,58 +0,0 @@ -{ - "MetaData": { - "Version": 1.0, - "ChannelNumber": 1 - }, - "Channels": [ - { - "Parameters": { - "Index": 0 - }, - "Pattern": [ - { - "Event": { - "Type": "transient", - "StartTime": 0, - "Parameters": { - "Intensity": 100, - "Frequency": 100 - } - } - }, - { - "Event": { - "Type": "continuous", - "StartTime": 500, - "Duration": 1000, - "Parameters": { - "Intensity": 75, - "Frequency": 100, - "Curve": [ - { - "Time": 0, - "Intensity": 50, - "Frequency": 0 - }, - { - "Time": 100, - "Intensity": 70, - "Frequency": 0 - }, - { - "Time": 300, - "Intensity": 80, - "Frequency": 0 - }, - { - "Time": 500, - "Intensity": 100, - "Frequency": 0 - } - ] - } - } - } - ] - } - ] -} diff --git a/utils/tools/haptic_format_converter/tests/test_data/oh_sample_to_he_v1.he b/utils/tools/haptic_format_converter/tests/test_data/oh_sample_to_he_v1.he deleted file mode 100644 index db6c7cd6bfa388af3e335ca384c8d9eb05128592..0000000000000000000000000000000000000000 --- a/utils/tools/haptic_format_converter/tests/test_data/oh_sample_to_he_v1.he +++ /dev/null @@ -1,46 +0,0 @@ -{ - "Metadata": { - "Version": 1 - }, - "Pattern": [ - { - "Type": "transient", - "RelativeTime": 0, - "Parameters": { - "Intensity": 100, - "Frequency": 100 - } - }, - { - "Type": "continuous", - "RelativeTime": 500, - "Duration": 1000, - "Parameters": { - "Intensity": 75, - "Frequency": 100, - "Curve": [ - { - "Time": 0, - "Intensity": 50, - "Frequency": 0 - }, - { - "Time": 100, - "Intensity": 70, - "Frequency": 0 - }, - { - "Time": 300, - "Intensity": 80, - "Frequency": 0 - }, - { - "Time": 500, - "Intensity": 100, - "Frequency": 0 - } - ] - } - } - ] -} \ No newline at end of file diff --git a/utils/tools/haptic_format_converter/tests/test_data/oh_sample_to_he_v2.he b/utils/tools/haptic_format_converter/tests/test_data/oh_sample_to_he_v2.he deleted file mode 100644 index dace96546e744203d8833cf39f50918577ba5a76..0000000000000000000000000000000000000000 --- a/utils/tools/haptic_format_converter/tests/test_data/oh_sample_to_he_v2.he +++ /dev/null @@ -1,51 +0,0 @@ -{ - "Metadata": { - "Version": 2 - }, - "PatternList": [ - { - "AbsoluteTime": 0, - "Pattern": [ - { - "Type": "transient", - "RelativeTime": 0, - "Parameters": { - "Intensity": 100, - "Frequency": 100 - } - }, - { - "Type": "continuous", - "RelativeTime": 500, - "Duration": 1000, - "Parameters": { - "Intensity": 75, - "Frequency": 100, - "Curve": [ - { - "Time": 0, - "Intensity": 50, - "Frequency": 0 - }, - { - "Time": 100, - "Intensity": 70, - "Frequency": 0 - }, - { - "Time": 300, - "Intensity": 80, - "Frequency": 0 - }, - { - "Time": 500, - "Intensity": 100, - "Frequency": 0 - } - ] - } - } - ] - } - ] -} \ No newline at end of file