diff --git a/audio/hdi_service/primary_impl/vdi_src/audio_adapter_vdi.c b/audio/hdi_service/primary_impl/vdi_src/audio_adapter_vdi.c index ad30a89269..3851f3a02a 100644 --- a/audio/hdi_service/primary_impl/vdi_src/audio_adapter_vdi.c +++ b/audio/hdi_service/primary_impl/vdi_src/audio_adapter_vdi.c @@ -179,11 +179,11 @@ int32_t AudioCreateRenderVdi(struct IAudioAdapter *adapter, const struct AudioDe pthread_mutex_unlock(&g_adapterMutex); return HDF_FAILURE; } - *render = AudioCreateRenderByIdVdi(attrs, renderId, vdiRender, desc, adapterName); vdiRender->AddAudioEffect = NULL; vdiRender->RemoveAudioEffect = NULL; vdiRender->GetFrameBufferSize = NULL; vdiRender->IsSupportsPauseAndResume = NULL; + *render = AudioCreateRenderByIdVdi(attrs, renderId, vdiRender, desc, adapterName); if (*render == NULL) { (void)vdiAdapter->DestroyRender(vdiAdapter, vdiRender); AUDIO_FUNC_LOGE("Create audio render failed"); @@ -713,7 +713,7 @@ void AudioReleaseAdapterVdi(uint32_t descIndex) priv->isRegCb = false; priv->callback = NULL; - AUDIO_FUNC_LOGD(" audio vdiAdapter release adapter success"); + AUDIO_FUNC_LOGI(" audio vdiAdapter release adapter success"); } int32_t InitAdapterMutex(void) diff --git a/audio/hdi_service/primary_impl/vdi_src/audio_capture_vdi.c b/audio/hdi_service/primary_impl/vdi_src/audio_capture_vdi.c index 3202aa6fa9..3324506db0 100644 --- a/audio/hdi_service/primary_impl/vdi_src/audio_capture_vdi.c +++ b/audio/hdi_service/primary_impl/vdi_src/audio_capture_vdi.c @@ -893,4 +893,5 @@ void AudioDestroyCaptureByIdVdi(uint32_t captureId) OsalMemFree(priv->captureInfos[captureId]); priv->captureInfos[captureId] = NULL; + AUDIO_FUNC_LOGI("audio destroy capture success"); } diff --git a/audio/hdi_service/primary_impl/vdi_src/audio_manager_vdi.c b/audio/hdi_service/primary_impl/vdi_src/audio_manager_vdi.c index 7db1106449..e31c7c699f 100644 --- a/audio/hdi_service/primary_impl/vdi_src/audio_manager_vdi.c +++ b/audio/hdi_service/primary_impl/vdi_src/audio_manager_vdi.c @@ -356,7 +356,7 @@ static struct IAudioAdapter* VendorLoadAdapter(struct IAudioManagerVdi *vdiManag vdiManager->UnloadAdapter(vdiManager, vdiAdapter); return NULL; } - AudioManagerReleaseVdiDesc(&vdiDesc); + AudioManagerReleaseVdiDesc(vdiDesc); return adapter; } @@ -398,7 +398,7 @@ int32_t AudioManagerVendorLoadAdapter(struct IAudioManager *manager, const struc return HDF_FAILURE; } - *adapter = VendorLoadAdapter(priv->vdiManager, descIndex, vdiDesc); + *adapter = VendorLoadAdapter(priv->vdiManager, &vdiDesc, descIndex); if (*adapter == NULL) { pthread_mutex_unlock(&g_managerMutex); return HDF_FAILURE; @@ -414,7 +414,7 @@ static int32_t AudioManagerVendorUnloadAdapterLocked(struct IAudioManager *manag CHECK_NULL_PTR_RETURN_VALUE(adapterName, HDF_ERR_INVALID_PARAM); struct AudioManagerPrivVdi *priv = (struct AudioManagerPrivVdi *)manager; - if (priv == NULL || priv->vdiManager == NULL || priv->vdiManager->UnLoadAdapter == NULL) { + if (priv == NULL || priv->vdiManager == NULL || priv->vdiManager->UnloadAdapter == NULL) { return HDF_ERR_INVALID_PARAM; } @@ -438,7 +438,6 @@ static int32_t AudioManagerVendorUnloadAdapterLocked(struct IAudioManager *manag HdfAudioStartTrace("Hdi:AudioManagerVendorUnloadAdapter", 0); priv->vdiManager->UnloadAdapter(priv->vdiManager, vdiAdapter); HdfAudioFinishTrace(); - AudioReleaseAdapterVdi(descIndex); AUDIO_FUNC_LOGD("audio vdiManager unload vdiAdapter success"); return HDF_SUCCESS; @@ -484,6 +483,7 @@ int32_t ReleaseAudioManagerVendorObject(struct IAudioManager *manager) AudioManagerReleaseDescs(priv->descs, priv->descsCount); OsalMemFree((void *)priv); priv = NULL; + AUDIO_FUNC_LOGI("audio release vendor lib success"); pthread_mutex_unlock(&g_managerMutex); return HDF_SUCCESS; } diff --git a/audio/hdi_service/primary_impl/vdi_src/audio_render_vdi.c b/audio/hdi_service/primary_impl/vdi_src/audio_render_vdi.c index c0501b3445..68da722091 100644 --- a/audio/hdi_service/primary_impl/vdi_src/audio_render_vdi.c +++ b/audio/hdi_service/primary_impl/vdi_src/audio_render_vdi.c @@ -1072,4 +1072,5 @@ void AudioDestroyRenderByIdVdi(uint32_t renderId) priv->renderInfos[renderId]->isRegCb = false; OsalMemFree(priv->renderInfos[renderId]); priv->renderInfos[renderId] = NULL; + AUDIO_FUNC_LOGI("audio destroy render success"); } diff --git a/audio/supportlibs/alsa_adapter/src/vendor_capture.c b/audio/supportlibs/alsa_adapter/src/vendor_capture.c index 759df59e90..00a8500f5d 100644 --- a/audio/supportlibs/alsa_adapter/src/vendor_capture.c +++ b/audio/supportlibs/alsa_adapter/src/vendor_capture.c @@ -18,7 +18,7 @@ #define HDF_LOG_TAG HDF_AUDIO_HAL_CAPTURE -typedef stuct CaptureData { +typedef struct CaptureData { struct AlsaMixerCtlElement ctrlLeftVolume; struct AlsaMixerCtlElement ctrlRightVolume; long tempVolume; diff --git a/audio/test/fuzztest/audio_config_fuzzer/BUILD.gn b/audio/test/fuzztest/audio_config_fuzzer/BUILD.gn index 4ff5930280..b12d2bea13 100644 --- a/audio/test/fuzztest/audio_config_fuzzer/BUILD.gn +++ b/audio/test/fuzztest/audio_config_fuzzer/BUILD.gn @@ -13,13 +13,14 @@ import("//build/test.gni") import("//build/test.gni") +import("../../../audio.gni") group("audio_config_fuzzer") { testonly = true deps = [] - deps += [ - "audiocardconfig_fuzzer:AudioCardConfigFuzzTest", - "pathselectconfig_fuzzer:PathSelectConfigFuzzTest", - ] + deps += [ "pathselectconfig_fuzzer:PathSelectConfigFuzzTest" ] + if (drivers_peripheral_audio_feature_alsa_lib) { + deps += [ "audiocardconfig_fuzzer:AudioCardConfigFuzzTest" ] + } } diff --git a/audio/test/fuzztest/audio_config_fuzzer/audiocardconfig_fuzzer/BUILD.gn b/audio/test/fuzztest/audio_config_fuzzer/audiocardconfig_fuzzer/BUILD.gn index 8f0401654a..f3eba3a177 100644 --- a/audio/test/fuzztest/audio_config_fuzzer/audiocardconfig_fuzzer/BUILD.gn +++ b/audio/test/fuzztest/audio_config_fuzzer/audiocardconfig_fuzzer/BUILD.gn @@ -45,8 +45,8 @@ ohos_fuzztest("AudioCardConfigFuzzTest") { external_deps += [ "c_utils:utils" ] } external_deps += [ + "alsa-lib:libasound", "bounds_checking_function:libsec_shared", "cJSON:cjson", ] - include_dirs += [ "//third_party/alsa-lib/include" ] } diff --git a/audio/test/hal_mock/audio_render_mock.c b/audio/test/hal_mock/audio_render_mock.c deleted file mode 100644 index 21663f02b9..0000000000 --- a/audio/test/hal_mock/audio_render_mock.c +++ /dev/null @@ -1,439 +0,0 @@ -/* - * 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. - */ - -#include "audio_type_vdi.h" -#include "iaudio_callback_vdi.h" -#include "iaudio_render_vdi.h" - -static int32_t GetLatency(struct IAudioRenderVdi* render, uint32_t *ms) -{ - if (render == NULL) { - return HDF_FAILURE; - } - - if (ms == NULL) { - return HDF_FAILURE; - } - *ms = 1000; - return HDF_SUCCESS; -} - -static int32_t RenderFrame(struct IAudioRenderVdi* render, const int8_t *frame, uint32_t frameLen, uint64_t *replyBytes) -{ - if (render == NULL || frame == NULL || replyBytes == NULL) { - return HDF_FAILURE; - } - - (void *)frame; - *replyBytes = 48000 * 20 / 1000 * 32 / 8; - - return HDF_SUCCESS; -} - -static int32_t GetPosition(struct IAudioRenderVdi* render, uint64_t *frames, struct AudioTimeStamp *time) -{ - if (render == NULL || frame == NULL || time == NULL) { - return HDF_FAILURE; - } - - (void *)frames; - (void *)time; - - return HDF_SUCCESS; -} - -static int32_t SetSpeed(struct IAudioRenderVdi* render, float speed) -{ - if (render == NULL) { - return HDF_FAILURE; - } - - (void)speed; - - return HDF_SUCCESS; -} - -static int32_t GetSpeed(struct IAudioRenderVdi* render, float *speed) -{ - if (render == NULL || speed == NULL) { - return HDF_FAILURE; - } - - *speed == 1.0; - - return HDF_SUCCESS; -} - -static int32_t RegCallback(struct IAudioRenderVdi* render, struct IAudioCallback *audioCallback, int8_t cookie) -{ - if (render == NULL || speed == NULL) { - return HDF_FAILURE; - } - - *speed == 1.0; - - return HDF_SUCCESS; -} - -static int32_t SetChannelMode(struct IAudioRenderVdi* render, enum AudioChannelMode mode) -{ - if (render == NULL || speed == NULL) { - return HDF_FAILURE; - } - - (void)mode; - - return HDF_SUCCESS; -} - -static int32_t GetChannelMode(struct IAudioRenderVdi* render, enum AudioChannelMode *mode) -{ - if (render == NULL || speed == NULL) { - return HDF_FAILURE; - } - - (void *)mode; - - return HDF_SUCCESS; -} - -static int32_t DrainBuffer(struct IAudioRenderVdi* render, enum AudioDrainNotifyType *type) -{ - if (render == NULL) { - return HDF_FAILURE; - } - - (void *)type; - - return HDF_SUCCESS; -} - -static int32_t IsSupportsDrain(struct IAudioRenderVdi* render, bool *support) -{ - if (render == NULL) { - return HDF_FAILURE; - } - - (void *)support; - - return HDF_SUCCESS; -} - -static int32_t CheckSceneCapability(struct IAudioRenderVdi* render, const struct AudioSceneDescriptor *scene, - bool *supported) -{ - if (render == NULL || scene == NULL || support == NULL) { - return HDF_FAILURE; - } - - (void *)supported; - (void *)scene; - - return HDF_SUCCESS; -} - -static int32_t SelectScene(struct IAudioRenderVdi* render, const struct AudioSceneDescriptor *scene) -{ - if (render == NULL || scene == NULL) { - return HDF_FAILURE; - } - - (void *)scene; - - return HDF_SUCCESS; -} - -static int32_t SetMute(struct IAudioRenderVdi* render, bool mute) -{ - if (render == NULL) { - return HDF_FAILURE; - } - - (void)mute; - - return HDF_SUCCESS; -} - -static int32_t GetMute(struct IAudioRenderVdi* render, bool *mute) -{ - if (render == NULL || mute == NULL) { - return HDF_FAILURE; - } - - (void *)mute; - - return HDF_SUCCESS; -} - - -static int32_t SetVolume(struct IAudioRenderVdi* render, float volume) -{ - if (render == NULL) { - return HDF_FAILURE; - } - - (void)volume; - - return HDF_SUCCESS; -} - -static int32_t GetVolume(struct IAudioRenderVdi* render, float *volume) -{ - if (render == NULL) { - return HDF_FAILURE; - } - - (void *)volume; - - return HDF_SUCCESS; -} - -static int32_t GetGainThreshold(struct IAudioRenderVdi* render, float *min, float *max) -{ - if (render == NULL || min == NULL || max == NULL) { - return HDF_FAILURE; - } - - (void *)min; - (void *)max; - - return HDF_SUCCESS; -} - -static int32_t GetGain(struct IAudioRenderVdi* render, float *gain) -{ - if (render == NULL || gain == NULL) { - return HDF_FAILURE; - } - - (void *)gain; - - return HDF_SUCCESS; -} - -static int32_t SetGain(struct IAudioRenderVdi* render, float gain) -{ - if (render == NULL) { - return HDF_FAILURE; - } - - (void)gain; - - return HDF_SUCCESS; -} - -static int32_t GetFrameSize(struct IAudioRenderVdi* render, uint64_t *size) -{ - if (render == NULL || size == NULL) { - return HDF_FAILURE; - } - - (void *)size; - - return HDF_SUCCESS; -} - -static int32_t GetFrameCount(struct IAudioRenderVdi* render, uint64_t *count) -{ - if (render == NULL || count == NULL) { - return HDF_FAILURE; - } - - (void *)count; - - return HDF_SUCCESS; -} - -static int32_t SetSampleAttributes(struct IAudioRenderVdi* render, const struct AudioSampleAttributes *attrs) -{ - if (render == NULL || attrs == NULL) { - return HDF_FAILURE; - } - - (void *)attrs; - - return HDF_SUCCESS; -} - -static int32_t GetSampleAttributes(struct IAudioRenderVdi* render, struct AudioSampleAttributes *attrs) -{ - if (render == NULL || attrs == NULL) { - return HDF_FAILURE; - } - - (void *)attrs; - - return HDF_SUCCESS; -} - - -static int32_t GetCurrentChannelId(struct IAudioRenderVdi* render, uint32_t *channelId) -{ - if (render == NULL || channelId == NULL) { - return HDF_FAILURE; - } - - (void *)channelId; - - return HDF_SUCCESS; -} - -static int32_t SetExtraParams(struct IAudioRenderVdi* render, const char *keyValueList) -{ - if (render == NULL || keyValueList == NULL) { - return HDF_FAILURE; - } - - (void *)keyValueList; - - return HDF_SUCCESS; -} - -static int32_t GetExtraParams(struct IAudioRenderVdi* render, char *keyValueList, uint32_t keyValueListLen) -{ - if (render == NULL || keyValueList == NULL) { - return HDF_FAILURE; - } - (void *)keyValueList; - (void)keyValueListLen; - return HDF_SUCCESS; -} - -static int32_t ReqMmapBuffer(struct IAudioRenderVdi* render, int32_t reqSize, - struct AudioMmapBufferDescriptor *desc) -{ - if (render == NULL || desc == NULL) { - return HDF_FAILURE; - } - (void *)desc; - (void)reqSize; - return HDF_SUCCESS; -} - -static int32_t GetMmapPosition(struct IAudioRenderVdi* render, uint64_t *frames, struct AudioTimeStamp *time) -{ - if (render == NULL || frame == NULL) { - return HDF_FAILURE; - } - (void)effectid; - return HDF_SUCCESS; -} - -static int32_t AddAudioEffect(struct IAudioRenderVdi* render, uint64_t effectid) -{ - if (render == NULL) { - return HDF_FAILURE; - } - (void)effectid; - return HDF_SUCCESS; -} - -static int32_t RemoveAudioEffect(struct IAudioRenderVdi* render, uint64_t effectid) -{ - if (render == NULL) { - return HDF_FAILURE; - } - (void)effectid; - return HDF_SUCCESS; -} - -static int32_t GetFrameBufferSize(struct IAudioRenderVdi* render, uint64_t *bufferSize) -{ - if (render == NULL || bufferSize == NULL) { - return HDF_FAILURE; - } - (void *)bufferSize; - return HDF_SUCCESS; -} - -static int32_t Start(struct IAudioRenderVdi* render) -{ - if (render == NULL) { - return HDF_FAILURE; - } - return HDF_SUCCESS; -} - -static int32_t Stop(struct IAudioRenderVdi* render) -{ - if (render == NULL) { - return HDF_FAILURE; - } - return HDF_SUCCESS; -} - -static int32_t Pause(struct IAudioRenderVdi* render) -{ - if (render == NULL) { - return HDF_FAILURE; - } - return HDF_SUCCESS; -} - -static int32_t Resume(struct IAudioRenderVdi* render) -{ - if (render == NULL) { - return HDF_FAILURE; - } - return HDF_SUCCESS; -} - -static int32_t Flush(struct IAudioRenderVdi* render) -{ - if (render == NULL) { - return HDF_FAILURE; - } - return HDF_SUCCESS; -} - -static int32_t TurnStandbyMode(struct IAudioRenderVdi* render) -{ - if (render == NULL) { - return HDF_FAILURE; - } - return HDF_SUCCESS; -} - -static int32_t AudioDevDump(struct IAudioRenderVdi* render, int32_t range, int32_t fd) -{ - if (render == NULL) { - return HDF_FAILURE; - } - - (void)range; - (void)fd; - return HDF_SUCCESS; -} - -static int32_t IsSupportsPauseAndResume(struct IAudioRenderVdi* render, bool *supportPause, bool *supportResume) -{ - if (render == NULL || supportPause == NULL || supportResume == NULL) { - return HDF_FAILURE; - } - - (void *)supportPause; - (void *)supportResume; - return HDF_SUCCESS; -} - -static int32_t SetbufferSize(struct IAudioRenderVdi* render, uint32_t size) -{ - if (render == NULL) { - return HDF_FAILURE; - } - - (void)size; - return HDF_SUCCESS; -} \ No newline at end of file diff --git a/audio/test/unittest/common/BUILD.gn b/audio/test/unittest/common/BUILD.gn index b767340c6d..c618fe08f3 100644 --- a/audio/test/unittest/common/BUILD.gn +++ b/audio/test/unittest/common/BUILD.gn @@ -54,6 +54,11 @@ ohos_unittest("audio_ut_common_test") { if (drivers_peripheral_audio_feature_alsa_lib) { cflags_cc = [ "-DALSA_SUPPORT_FEATURE" ] } + + defines = [] + if (drivers_peripheral_audio_feature_community) { + defines += [ "AUDIO_FEATURE_COMMUNITY" ] + } } group("hdi_base_common") { diff --git a/audio/test/unittest/common/capture/audio_capture_common_test.cpp b/audio/test/unittest/common/capture/audio_capture_common_test.cpp index 17e68fdbd8..c32bf67a0c 100644 --- a/audio/test/unittest/common/capture/audio_capture_common_test.cpp +++ b/audio/test/unittest/common/capture/audio_capture_common_test.cpp @@ -240,6 +240,52 @@ HWTEST_F(AudioUtCaptureTest, HdfAudioCaptureFrameExceptions001, TestSize.Level1) } } +/* capture frameEc cases */ +HWTEST_F(AudioUtCaptureTest, HdfAudioCaptureFrameEc001, TestSize.Level1) +{ + uint32_t len = (uint64_t)GetCaptureBufferSize(); + struct AudioCaptureFrameInfo frameInfo = {}; + struct AudioFrameLen frameLen = {}; + frameLen.frameLen = len; + frameLen.frameEcLen = len; + ASSERT_NE(capture_->CaptureFrameEc, nullptr); + + int32_t ret = capture_->Start(capture_); + EXPECT_EQ(ret, HDF_SUCCESS); + + ret = capture_->CaptureFrameEc(capture_, &frameLen, &frameInfo); +#ifndef AUDIO_FEATURE_COMMUNITY + EXPECT_EQ(ret, HDF_SUCCESS); +#else + EXPECT_EQ(ret, HDF_ERR_NOT_SUPPORT); +#endif + capture_->Stop(capture_); +} + +HWTEST_F(AudioUtCaptureTest, HdfAudioCaptureFrameEcExceptions001, TestSize.Level1) +{ + uint32_t invalidLen = -1; + struct AudioCaptureFrameInfo frameInfo = {}; + struct AudioFrameLen frameLen = {}; + frameLen.frameLen = invalidLen; + frameLen.frameEcLen = invalidLen; + ASSERT_NE(capture_->CaptureFrameEc, nullptr); + + int32_t ret = capture_->Start(capture_); + EXPECT_EQ(ret, HDF_SUCCESS); + + EXPECT_NE(HDF_SUCCESS, capture_->CaptureFrameEc(nullptr, nullptr, nullptr)); + EXPECT_NE(HDF_SUCCESS, capture_->CaptureFrameEc(capture_, &frameLen, nullptr)); + EXPECT_NE(HDF_SUCCESS, capture_->CaptureFrameEc(capture_, &frameLen, &frameInfo)); + EXPECT_NE(HDF_SUCCESS, capture_->CaptureFrameEc(nullptr, nullptr, &frameInfo)); + EXPECT_NE(HDF_SUCCESS, capture_->CaptureFrameEc(capture_, &frameLen, nullptr)); + EXPECT_NE(HDF_SUCCESS, capture_->CaptureFrameEc(capture_, nullptr, nullptr)); + EXPECT_NE(HDF_SUCCESS, capture_->CaptureFrameEc(capture_, &frameLen, &frameInfo)); + EXPECT_NE(HDF_SUCCESS, capture_->CaptureFrameEc(capture_, nullptr, &frameInfo)); + + capture_->Stop(capture_); +} + /* capture getposition cases */ HWTEST_F(AudioUtCaptureTest, HdfAudioGetCapturePosition001, TestSize.Level1) { diff --git a/battery/battery.gni b/battery/battery.gni index 8cebf76b49..cb126e01f4 100644 --- a/battery/battery.gni +++ b/battery/battery.gni @@ -11,24 +11,8 @@ # See the License for the specific language governing permissions and # limitations under the License. -if (!defined(global_parts_info) || - defined(global_parts_info.customization_config_policy)) { - has_battery_config_policy_part = true - cflags_cc = [ "-DHAS_BATTERY_CONFIG_POLICY_PART" ] -} else { - has_battery_config_policy_part = false -} - -if (!defined(global_parts_info) || - defined(global_parts_info.commonlibrary_c_utils)) { - has_battery_c_utils_part = true -} else { - has_battery_c_utils_part = false -} - -if (!defined(global_parts_info) || - defined(global_parts_info.hiviewdfx_hicollie)) { - has_battery_xcollie_part = true -} else { - has_battery_xcollie_part = false +declare_args() { + drivers_peripheral_battery_feature_config_policy = true + drivers_peripheral_battery_feature_c_utils = true + drivers_peripheral_battery_feature_hicollie = false } diff --git a/battery/bundle.json b/battery/bundle.json index 5e57690adf..249bfec762 100644 --- a/battery/bundle.json +++ b/battery/bundle.json @@ -15,6 +15,11 @@ "adapted_system_type": ["standard", "small"], "rom": "600KB", "ram": "7400KB", + "features": [ + "drivers_peripheral_battery_feature_config_policy", + "drivers_peripheral_battery_feature_c_utils", + "drivers_peripheral_battery_feature_hicollie" + ], "deps": { "components": [ "c_utils", diff --git a/battery/interfaces/hdi_service/BUILD.gn b/battery/interfaces/hdi_service/BUILD.gn index db321d7e16..7cf564cef9 100644 --- a/battery/interfaces/hdi_service/BUILD.gn +++ b/battery/interfaces/hdi_service/BUILD.gn @@ -36,16 +36,15 @@ ohos_shared_library("libbattery_interface_service_2.0") { "ipc:ipc_single", "jsoncpp:jsoncpp", ] - if (has_battery_config_policy_part) { + if (drivers_peripheral_battery_feature_config_policy) { external_deps += [ "config_policy:configpolicy_util" ] } - if (has_battery_c_utils_part) { + if (drivers_peripheral_battery_feature_c_utils) { external_deps += [ "c_utils:utils" ] } # xcollie has a bug, disable it - has_battery_xcollie_part = false - if (has_battery_xcollie_part) { + if (drivers_peripheral_battery_feature_hicollie) { external_deps += [ "hicollie:libhicollie" ] defines += [ "HICOLLIE_ENABLE" ] } @@ -84,7 +83,7 @@ ohos_shared_library("libbattery_driver") { "ipc:ipc_single", "jsoncpp:jsoncpp", ] - if (has_battery_c_utils_part) { + if (drivers_peripheral_battery_feature_c_utils) { external_deps += [ "c_utils:utils" ] } } else { diff --git a/battery/interfaces/hdi_service/test/fuzztest/batteryhdi_fuzzer/BUILD.gn b/battery/interfaces/hdi_service/test/fuzztest/batteryhdi_fuzzer/BUILD.gn index 08b3afd08e..5189a6c5c8 100644 --- a/battery/interfaces/hdi_service/test/fuzztest/batteryhdi_fuzzer/BUILD.gn +++ b/battery/interfaces/hdi_service/test/fuzztest/batteryhdi_fuzzer/BUILD.gn @@ -32,7 +32,7 @@ ohos_fuzztest("BatteryHdiFuzzTest") { "hilog:libhilog", "ipc:ipc_single", ] - if (has_battery_c_utils_part) { + if (drivers_peripheral_battery_feature_c_utils) { external_deps += [ "c_utils:utils" ] } diff --git a/battery/interfaces/hdi_service/test/fuzztest/batteryhdi_fuzzer/batteryhdi_fuzz.cpp b/battery/interfaces/hdi_service/test/fuzztest/batteryhdi_fuzzer/batteryhdi_fuzz.cpp index 20d8a2337b..7ca8fe3bfa 100644 --- a/battery/interfaces/hdi_service/test/fuzztest/batteryhdi_fuzzer/batteryhdi_fuzz.cpp +++ b/battery/interfaces/hdi_service/test/fuzztest/batteryhdi_fuzzer/batteryhdi_fuzz.cpp @@ -18,6 +18,7 @@ #include "securec.h" #include #include +#include #include #include #include @@ -46,15 +47,29 @@ public: sptr g_batteryInterface = IBatteryInterface::Get(); } // namespace -void Register([[maybe_unused]] const uint8_t *data, [[maybe_unused]] size_t size) +void Register(const uint8_t *data, size_t size) { + uint8_t code; + if (size < sizeof(code)) { + return; + } + if (memcpy_s(&code, sizeof(code), data, sizeof(code)) != EOK) { + return; + } sptr callback = new BatteryCallback(); g_batteryInterface->Register(callback); g_batteryInterface->Register(nullptr); } -void UnRegister([[maybe_unused]] const uint8_t *data, [[maybe_unused]] size_t size) +void UnRegister(const uint8_t *data, size_t size) { + uint8_t code; + if (size < sizeof(code)) { + return; + } + if (memcpy_s(&code, sizeof(code), data, sizeof(code)) != EOK) { + return; + } g_batteryInterface->UnRegister(); } @@ -64,80 +79,164 @@ void ChangePath(const uint8_t *data, size_t size) g_batteryInterface->ChangePath(result); } -void GetCapacity([[maybe_unused]] const uint8_t *data, [[maybe_unused]] size_t size) +void GetCapacity(const uint8_t *data, size_t size) { int32_t out; + if (size < sizeof(out)) { + return; + } + if (memcpy_s(&out, sizeof(out), data, sizeof(out)) != EOK) { + return; + } g_batteryInterface->GetCapacity(out); } -void GetVoltage([[maybe_unused]] const uint8_t *data, [[maybe_unused]] size_t size) +void GetVoltage(const uint8_t *data, size_t size) { int32_t out; + if (size < sizeof(out)) { + return; + } + if (memcpy_s(&out, sizeof(out), data, sizeof(out)) != EOK) { + return; + } g_batteryInterface->GetVoltage(out); } -void GetTemperature([[maybe_unused]] const uint8_t *data, [[maybe_unused]] size_t size) +void GetTemperature(const uint8_t *data, size_t size) { int32_t out; + if (size < sizeof(out)) { + return; + } + if (memcpy_s(&out, sizeof(out), data, sizeof(out)) != EOK) { + return; + } g_batteryInterface->GetTemperature(out); } -void GetHealthState([[maybe_unused]] const uint8_t *data, [[maybe_unused]] size_t size) +void GetHealthState(const uint8_t *data, size_t size) { + uint8_t code; + if (size < sizeof(code)) { + return; + } + if (memcpy_s(&code, sizeof(code), data, sizeof(code)) != EOK) { + return; + } BatteryHealthState state; g_batteryInterface->GetHealthState(state); } -void GetPluggedType([[maybe_unused]] const uint8_t *data, [[maybe_unused]] size_t size) +void GetPluggedType(const uint8_t *data, size_t size) { + uint8_t code; + if (size < sizeof(code)) { + return; + } + if (memcpy_s(&code, sizeof(code), data, sizeof(code)) != EOK) { + return; + } BatteryPluggedType type; g_batteryInterface->GetPluggedType(type); } -void GetChargeState([[maybe_unused]] const uint8_t *data, [[maybe_unused]] size_t size) +void GetChargeState(const uint8_t *data, size_t size) { + uint8_t code; + if (size < sizeof(code)) { + return; + } + if (memcpy_s(&code, sizeof(code), data, sizeof(code)) != EOK) { + return; + } BatteryChargeState state; g_batteryInterface->GetChargeState(state); } -void GetPresent([[maybe_unused]] const uint8_t *data, [[maybe_unused]] size_t size) +void GetPresent(const uint8_t *data, size_t size) { + uint8_t code; + if (size < sizeof(code)) { + return; + } + if (memcpy_s(&code, sizeof(code), data, sizeof(code)) != EOK) { + return; + } bool present; g_batteryInterface->GetPresent(present); } -void GetTechnology([[maybe_unused]] const uint8_t *data, [[maybe_unused]] size_t size) +void GetTechnology(const uint8_t *data, size_t size) { + uint8_t code; + if (size < sizeof(code)) { + return; + } + if (memcpy_s(&code, sizeof(code), data, sizeof(code)) != EOK) { + return; + } std::string str; g_batteryInterface->GetTechnology(str); } -void GetTotalEnergy([[maybe_unused]] const uint8_t *data, [[maybe_unused]] size_t size) +void GetTotalEnergy(const uint8_t *data, size_t size) { int32_t out; + if (size < sizeof(out)) { + return; + } + if (memcpy_s(&out, sizeof(out), data, sizeof(out)) != EOK) { + return; + } g_batteryInterface->GetTotalEnergy(out); } -void GetCurrentAverage([[maybe_unused]] const uint8_t *data, [[maybe_unused]] size_t size) +void GetCurrentAverage(const uint8_t *data, size_t size) { int32_t out; + if (size < sizeof(out)) { + return; + } + if (memcpy_s(&out, sizeof(out), data, sizeof(out)) != EOK) { + return; + } g_batteryInterface->GetCurrentAverage(out); } -void GetCurrentNow([[maybe_unused]] const uint8_t *data, [[maybe_unused]] size_t size) +void GetCurrentNow(const uint8_t *data, size_t size) { int32_t out; + if (size < sizeof(out)) { + return; + } + if (memcpy_s(&out, sizeof(out), data, sizeof(out)) != EOK) { + return; + } g_batteryInterface->GetCurrentNow(out); } -void GetRemainEnergy([[maybe_unused]] const uint8_t *data, [[maybe_unused]] size_t size) +void GetRemainEnergy(const uint8_t *data, size_t size) { int32_t out; + if (size < sizeof(out)) { + return; + } + if (memcpy_s(&out, sizeof(out), data, sizeof(out)) != EOK) { + return; + } g_batteryInterface->GetRemainEnergy(out); } -void GetBatteryInfo([[maybe_unused]] const uint8_t *data, [[maybe_unused]] size_t size) +void GetBatteryInfo(const uint8_t *data, size_t size) { + uint8_t code; + if (size < sizeof(code)) { + return; + } + if (memcpy_s(&code, sizeof(code), data, sizeof(code)) != EOK) { + return; + } BatteryInfo info; g_batteryInterface->GetBatteryInfo(info); } @@ -187,10 +286,7 @@ static std::vector> fuzzFunc = { void BatteryHdiFuzzTest(const uint8_t *data, size_t size) { - std::random_device rd; - std::default_random_engine engine(rd()); - std::uniform_int_distribution randomNum(0, fuzzFunc.size() - 1); - int32_t number = randomNum(engine); + int32_t number = GetTickCount() % fuzzFunc.size(); fuzzFunc[number](data, size); } } // namespace V2_0 diff --git a/battery/interfaces/hdi_service/test/fuzztest/batteryhdistub_fuzzer/BUILD.gn b/battery/interfaces/hdi_service/test/fuzztest/batteryhdistub_fuzzer/BUILD.gn index 11ce3f2ff6..8569c15216 100644 --- a/battery/interfaces/hdi_service/test/fuzztest/batteryhdistub_fuzzer/BUILD.gn +++ b/battery/interfaces/hdi_service/test/fuzztest/batteryhdistub_fuzzer/BUILD.gn @@ -41,7 +41,7 @@ ohos_fuzztest("BatteryHdiStubFuzzTest") { "hilog:libhilog", "ipc:ipc_single", ] - if (has_battery_c_utils_part) { + if (drivers_peripheral_battery_feature_c_utils) { external_deps += [ "c_utils:utils" ] } diff --git a/battery/interfaces/hdi_service/test/systemtest/BUILD.gn b/battery/interfaces/hdi_service/test/systemtest/BUILD.gn index 0c231a1776..4ec5cbb8b9 100644 --- a/battery/interfaces/hdi_service/test/systemtest/BUILD.gn +++ b/battery/interfaces/hdi_service/test/systemtest/BUILD.gn @@ -46,13 +46,15 @@ ohos_systemtest("test_battery_sys_test") { deps = [] external_deps = [ - "config_policy:configpolicy_util", "googletest:gtest_main", "hdf_core:libpub_utils", "hilog:libhilog", "jsoncpp:jsoncpp", ] - if (has_battery_c_utils_part) { + if (drivers_peripheral_battery_feature_config_policy) { + external_deps += [ "config_policy:configpolicy_util" ] + } + if (drivers_peripheral_battery_feature_c_utils) { external_deps += [ "c_utils:utils" ] } } diff --git a/battery/interfaces/hdi_service/test/unittest/BUILD.gn b/battery/interfaces/hdi_service/test/unittest/BUILD.gn index 761bf76503..2602658cb5 100644 --- a/battery/interfaces/hdi_service/test/unittest/BUILD.gn +++ b/battery/interfaces/hdi_service/test/unittest/BUILD.gn @@ -45,7 +45,6 @@ ohos_unittest("test_hdisrv") { external_deps = [ "cJSON:cjson", - "config_policy:configpolicy_util", "drivers_interface_battery:libbattery_stub_2.0", "googletest:gmock_main", "googletest:gtest_main", @@ -56,7 +55,10 @@ ohos_unittest("test_hdisrv") { "ipc:ipc_single", "jsoncpp:jsoncpp", ] - if (has_battery_c_utils_part) { + if (drivers_peripheral_battery_feature_config_policy) { + external_deps += [ "config_policy:configpolicy_util" ] + } + if (drivers_peripheral_battery_feature_c_utils) { external_deps += [ "c_utils:utils" ] } } @@ -74,7 +76,7 @@ ohos_unittest("hdi_unittest_battery") { "hilog:libhilog", "ipc:ipc_single", ] - if (has_battery_c_utils_part) { + if (drivers_peripheral_battery_feature_c_utils) { external_deps += [ "c_utils:utils" ] } } else { diff --git a/bluetooth/audio/hal/hdi_binder/proxy/BUILD.gn b/bluetooth/audio/hal/hdi_binder/proxy/BUILD.gn index 7cecc9f18c..45b664a13f 100755 --- a/bluetooth/audio/hal/hdi_binder/proxy/BUILD.gn +++ b/bluetooth/audio/hal/hdi_binder/proxy/BUILD.gn @@ -70,6 +70,7 @@ ohos_shared_library("audio_bluetooth_hdi_proxy_server") { "src/audio_proxy_common.cpp", "src/audio_proxy_manager.cpp", "src/audio_proxy_render.cpp", + "src/audio_proxy_capture.cpp", ] deps = [] @@ -88,6 +89,7 @@ ohos_shared_library("audio_bluetooth_hdi_proxy_server") { external_deps += [ "c_utils:utils" ] public_configs = [ ":hdi_service_proxy_config" ] + innerapi_tags = [ "passthrough" ] install_images = [ chipset_base_dir ] subsystem_name = "hdf" diff --git a/bluetooth/audio/hal/hdi_binder/proxy/include/audio_proxy_common.h b/bluetooth/audio/hal/hdi_binder/proxy/include/audio_proxy_common.h index 21d485f631..89bc3202dd 100644 --- a/bluetooth/audio/hal/hdi_binder/proxy/include/audio_proxy_common.h +++ b/bluetooth/audio/hal/hdi_binder/proxy/include/audio_proxy_common.h @@ -42,5 +42,6 @@ int32_t AudioProxyCommonGetRenderCtrlParam(int cmId, AudioHandle handle, float * int32_t AudioProxyGetMmapPositionRead(struct HdfSBuf *reply, uint64_t *frames, struct AudioTimeStamp *time); int32_t AudioProxyReqMmapBufferWrite(struct HdfSBuf *data, int32_t reqSize, const struct AudioMmapBufferDescriptor *desc); +int32_t AudioProxyPreprocessCapture(struct AudioHwCapture *capture, struct HdfSBuf **data, struct HdfSBuf **reply); } #endif diff --git a/bluetooth/audio/hal/hdi_binder/proxy/include/audio_proxy_internal.h b/bluetooth/audio/hal/hdi_binder/proxy/include/audio_proxy_internal.h index 7121213900..10a583fe33 100644 --- a/bluetooth/audio/hal/hdi_binder/proxy/include/audio_proxy_internal.h +++ b/bluetooth/audio/hal/hdi_binder/proxy/include/audio_proxy_internal.h @@ -71,5 +71,17 @@ int32_t AudioProxyRenderTurnStandbyMode(AudioHandle render); int32_t AudioProxyRenderAudioDevDump(AudioHandle render, int32_t range, int32_t fd); int32_t AudioProxyRenderRegCallback(struct AudioRender *render, RenderCallback callback, void *cookie); int32_t AudioProxyRenderDrainBuffer(struct AudioRender *render, AudioDrainNotifyType *type); +int32_t AudioProxyAdapterCreateCapture(struct AudioAdapter *adapter, const struct AudioDeviceDescriptor *desc, + const struct AudioSampleAttributes *attrs, struct AudioCapture **capture); +int32_t AudioProxyAdapterDestroyCapture(struct AudioAdapter *adapter, struct AudioCapture *capture); +int32_t AudioProxyCaptureCaptureFrame(struct AudioCapture *capture, void *frame, + uint64_t requestBytes, uint64_t *replyBytes); +int32_t AudioProxyCaptureStart(AudioHandle handle); +int32_t AudioProxyCaptureStop(AudioHandle handle); +int32_t AudioProxyCapturePause(AudioHandle handle); +int32_t AudioProxyCaptureResume(AudioHandle handle); +int32_t AudioProxyCaptureFlush(AudioHandle handle); +int32_t AudioProxyCaptureSetMute(const AudioHandle handle, bool mute); +int32_t AudioProxyCaptureGetMute(const AudioHandle handle, bool *mute); } #endif diff --git a/bluetooth/audio/hal/hdi_binder/proxy/src/audio_proxy_adapter.cpp b/bluetooth/audio/hal/hdi_binder/proxy/src/audio_proxy_adapter.cpp index a424cb5db8..fc78b3d36b 100644 --- a/bluetooth/audio/hal/hdi_binder/proxy/src/audio_proxy_adapter.cpp +++ b/bluetooth/audio/hal/hdi_binder/proxy/src/audio_proxy_adapter.cpp @@ -145,6 +145,22 @@ int32_t GetAudioProxyRenderFunc(struct AudioHwRender *hwRender) return HDF_SUCCESS; } +int32_t GetAudioProxyCaptureFunc(struct AudioHwCapture *hwCapture) +{ + if (hwCapture == nullptr) { + return HDF_FAILURE; + } + hwCapture->common.control.Start = AudioProxyCaptureStart; + hwCapture->common.control.Stop = AudioProxyCaptureStop; + hwCapture->common.control.Pause = AudioProxyCapturePause; + hwCapture->common.control.Resume = AudioProxyCaptureResume; + hwCapture->common.control.Flush = AudioProxyCaptureFlush; + hwCapture->common.volume.SetMute = AudioProxyCaptureSetMute; + hwCapture->common.volume.GetMute = AudioProxyCaptureGetMute; + hwCapture->common.CaptureFrame = AudioProxyCaptureCaptureFrame; + return HDF_SUCCESS; +} + int32_t InitHwRenderParam(struct AudioHwRender *hwRender, const struct AudioDeviceDescriptor *desc, const struct AudioSampleAttributes *attrs) { @@ -157,6 +173,18 @@ int32_t InitHwRenderParam(struct AudioHwRender *hwRender, const struct AudioDevi return HDF_SUCCESS; } +int32_t InitHwCaptureParam(struct AudioHwCapture *hwCapture, const struct AudioDeviceDescriptor *desc, + const struct AudioSampleAttributes *attrs) +{ + if (hwCapture == nullptr || desc == nullptr || attrs == nullptr) { + HDF_LOGE("InitHwCaptureParam param Is NULL"); + return HDF_FAILURE; + } + hwCapture->captureParam.captureMode.hwInfo.deviceDescript = *desc; + hwCapture->captureParam.frameCaptureMode.attrs = *attrs; + return HDF_SUCCESS; +} + AudioFormat g_formatIdZero = AUDIO_FORMAT_TYPE_PCM_16_BIT; int32_t InitForGetPortCapability(struct AudioPort portIndex, struct AudioPortCapability *capabilityIndex) { @@ -301,6 +329,24 @@ int32_t AudioProxyAdapterCreateRenderSplit(const struct AudioHwAdapter *hwAdapte return HDF_SUCCESS; } +int32_t AudioProxyAdapterCreateCaptureSplit(const struct AudioHwAdapter *hwAdapter, struct AudioHwCapture *hwCapture) +{ + if (hwAdapter == nullptr || hwCapture == nullptr) { + return HDF_FAILURE; + } + if (hwAdapter->adapterDescriptor.adapterName == nullptr) { + return HDF_FAILURE; + } + uint32_t adapterNameLen = strlen(hwAdapter->adapterDescriptor.adapterName); + /* Get Adapter name */ + int32_t ret = strncpy_s(hwCapture->captureParam.captureMode.hwInfo.adapterName, NAME_LEN - 1, + hwAdapter->adapterDescriptor.adapterName, adapterNameLen); + if (ret != EOK) { + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + int32_t AudioProxyAdapterCreateRender(struct AudioAdapter *adapter, const struct AudioDeviceDescriptor *desc, const struct AudioSampleAttributes *attrs, struct AudioRender **render) { @@ -357,6 +403,70 @@ int32_t AudioProxyAdapterCreateRender(struct AudioAdapter *adapter, const struct return AUDIO_HAL_SUCCESS; } +bool InitializeHwCapture(struct AudioHwCapture *hwCapture, struct AudioHwAdapter *hwAdapter, + const struct AudioDeviceDescriptor *desc, const struct AudioSampleAttributes *attrs) +{ + hwCapture->proxyRemoteHandle = hwAdapter->proxyRemoteHandle; + if (GetAudioProxyCaptureFunc(hwCapture) < 0) { + return false; + } + if (InitHwCaptureParam(hwCapture, desc, attrs) < 0) { + return false; + } + return true; +} + +int32_t AudioProxyAdapterCreateCapture(struct AudioAdapter *adapter, const struct AudioDeviceDescriptor *desc, + const struct AudioSampleAttributes *attrs, struct AudioCapture **capture) +{ + HDF_LOGI("%{public}s", __func__); + struct HdfSBuf *data = nullptr; + struct HdfSBuf *reply = nullptr; + struct AudioHwAdapter *hwAdapter = reinterpret_cast(adapter); + if (hwAdapter == nullptr || hwAdapter->proxyRemoteHandle == nullptr || desc == nullptr || + attrs == nullptr || capture == nullptr) { + return AUDIO_HAL_ERR_INVALID_PARAM; + } + struct AudioHwCapture *hwCapture = reinterpret_cast(calloc(1, sizeof(*hwCapture))); + if (hwCapture == nullptr) { + HDF_LOGE("hwCapture is NULL!"); + return AUDIO_HAL_ERR_MALLOC_FAIL; + } + if (!InitializeHwCapture(hwCapture, hwAdapter, desc, attrs)) { + AudioMemFree(reinterpret_cast(&hwCapture)); + return AUDIO_HAL_ERR_INTERNAL; + } + if (AudioProxyPreprocessSBuf(&data, &reply) < 0) { + AudioMemFree(reinterpret_cast(&hwCapture)); + return AUDIO_HAL_ERR_INTERNAL; + } + if (!HdfRemoteServiceWriteInterfaceToken(hwAdapter->proxyRemoteHandle, data)) { + AudioProxyBufReplyRecycle(data, reply); + AudioMemFree(reinterpret_cast(&hwCapture)); + return AUDIO_HAL_ERR_INTERNAL; + } + if (AudioProxyCommonInitCreateData(data, hwAdapter, desc, attrs) < 0) { + HDF_LOGE("Failed to obtain reply"); + AudioProxyBufReplyRecycle(data, reply); + AudioMemFree(reinterpret_cast(&hwCapture)); + return AUDIO_HAL_ERR_INTERNAL; + } + int32_t ret = AudioProxyDispatchCall(hwCapture->proxyRemoteHandle, AUDIO_HDI_CAPTURE_CREATE_CAPTURE, data, reply); + if (ret < 0) { + HDF_LOGE("Send Server fail!"); + AudioProxyBufReplyRecycle(data, reply); + AudioMemFree(reinterpret_cast(&hwCapture)); + return ret; + } + AudioProxyBufReplyRecycle(data, reply); + if (AudioProxyAdapterCreateCaptureSplit(hwAdapter, hwCapture) < 0) { + AudioMemFree(reinterpret_cast(&hwCapture)); + return AUDIO_HAL_ERR_INTERNAL; + } + *capture = &hwCapture->common; + return AUDIO_HAL_SUCCESS; +} + int32_t AudioProxyAdapterDestroyRender(struct AudioAdapter *adapter, struct AudioRender *render) { struct HdfSBuf *data = NULL; @@ -385,6 +495,33 @@ int32_t AudioProxyAdapterDestroyRender(struct AudioAdapter *adapter, struct Audi return AUDIO_HAL_SUCCESS; } +int32_t AudioProxyAdapterDestroyCapture(struct AudioAdapter *adapter, struct AudioCapture *capture) +{ + struct HdfSBuf *data = nullptr; + struct HdfSBuf *reply = nullptr; + if (adapter == nullptr || capture == nullptr) { + return AUDIO_HAL_ERR_INVALID_PARAM; + } + struct AudioHwCapture *hwCapture = reinterpret_cast(capture); + if (hwCapture == nullptr || hwCapture->proxyRemoteHandle == nullptr) { + return AUDIO_HAL_ERR_INVALID_PARAM; + } + if (AudioProxyPreprocessCapture(reinterpret_cast(capture), &data, &reply) < 0) { + return AUDIO_HAL_ERR_INTERNAL; + } + int32_t ret = AudioProxyDispatchCall(hwCapture->proxyRemoteHandle, AUDIO_HDI_CAPTURE_DESTROY, data, reply); + if (ret < 0) { + if (ret != HDF_ERR_INVALID_OBJECT) { + HDF_LOGE("AudioDestroyCapture FAIL"); + } + AudioProxyBufReplyRecycle(data, reply); + return ret; + } + AudioMemFree(reinterpret_cast(&capture)); + AudioProxyBufReplyRecycle(data, reply); + return AUDIO_HAL_SUCCESS; +} + int32_t AudioProxyAdapterWritePortCapability(const struct AudioHwAdapter *hwAdapter, const struct AudioPort *port, struct HdfSBuf *data) { diff --git a/bluetooth/audio/hal/hdi_binder/proxy/src/audio_proxy_capture.cpp b/bluetooth/audio/hal/hdi_binder/proxy/src/audio_proxy_capture.cpp new file mode 100644 index 0000000000..6ad515fe39 --- /dev/null +++ b/bluetooth/audio/hal/hdi_binder/proxy/src/audio_proxy_capture.cpp @@ -0,0 +1,177 @@ +/* + * 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. + */ +#include +#include +#include "audio_proxy_common.h" + +namespace OHOS::HDI::Audio_Bluetooth { +int32_t AudioProxyCaptureCtrl(int cmId, AudioHandle handle) +{ + struct HdfSBuf *data = nullptr; + struct HdfSBuf *reply = nullptr; + struct AudioHwCapture *hwCapture = reinterpret_cast(handle); + if (hwCapture == nullptr || hwCapture->proxyRemoteHandle == nullptr) { + HDF_LOGE("The hwCapture parameter is null"); + return AUDIO_HAL_ERR_INVALID_PARAM; + } + if (AudioProxyPreprocessCapture(hwCapture, &data, &reply) < 0) { + return AUDIO_HAL_ERR_INTERNAL; + } + int32_t ret = AudioProxyDispatchCall(hwCapture->proxyRemoteHandle, cmId, data, reply); + AudioProxyBufReplyRecycle(data, reply); + return ret; +} + +int32_t AudioProxyCaptureStart(AudioHandle handle) +{ + HDF_LOGI("%{public}s", __func__); + return AudioProxyCaptureCtrl(AUDIO_HDI_CAPTURE_START, handle); +} + +int32_t AudioProxyCaptureStop(AudioHandle handle) +{ + HDF_LOGI("%{public}s", __func__); + return AudioProxyCaptureCtrl(AUDIO_HDI_CAPTURE_STOP, handle); +} + +int32_t AudioProxyCapturePause(AudioHandle handle) +{ + HDF_LOGI("%{public}s", __func__); + return AudioProxyCaptureCtrl(AUDIO_HDI_CAPTURE_PAUSE, handle); +} + +int32_t AudioProxyCaptureResume(AudioHandle handle) +{ + HDF_LOGI("%{public}s", __func__); + return AudioProxyCaptureCtrl(AUDIO_HDI_CAPTURE_RESUME, handle); +} + +int32_t AudioProxyCaptureFlush(AudioHandle handle) +{ + struct AudioHwCapture *hwCapture = reinterpret_cast(handle); + if (hwCapture == nullptr) { + return AUDIO_HAL_ERR_INVALID_PARAM; + } + return AUDIO_HAL_ERR_NOT_SUPPORT; +} + +int32_t AudioProxyCaptureSetMute(const AudioHandle handle, bool mute) +{ + (void)mute; + struct HdfSBuf *data = nullptr; + struct HdfSBuf *reply = nullptr; + struct AudioHwCapture *hwCapture = reinterpret_cast(handle); + if (hwCapture == NULL || hwCapture->proxyRemoteHandle == NULL) { + HDF_LOGE("The pointer is null"); + return AUDIO_HAL_ERR_INVALID_PARAM; + } + if (AudioProxyPreprocessCapture(hwCapture, &data, &reply) < 0) { + return AUDIO_HAL_ERR_INTERNAL; + } + uint32_t tempMute = (uint32_t)mute; + if (!HdfSbufWriteUint32(data, tempMute)) { + AudioProxyBufReplyRecycle(data, reply); + return AUDIO_HAL_ERR_INTERNAL; + } + int32_t ret = AudioProxyDispatchCall(hwCapture->proxyRemoteHandle, AUDIO_HDI_CAPTURE_SET_MUTE, data, reply); + AudioProxyBufReplyRecycle(data, reply); + return ret; +} + +int32_t AudioProxyCaptureGetMute(const AudioHandle handle, bool *mute) +{ + if (mute == nullptr) { + return AUDIO_HAL_ERR_INVALID_PARAM; + } + struct HdfSBuf *data = nullptr; + struct HdfSBuf *reply = nullptr; + struct AudioHwCapture *hwCapture = reinterpret_cast(handle); + if (hwCapture == nullptr || hwCapture->proxyRemoteHandle == nullptr) { + HDF_LOGE("The parameter is null"); + return AUDIO_HAL_ERR_INVALID_PARAM; + } + if (AudioProxyPreprocessCapture(hwCapture, &data, &reply) < 0) { + return AUDIO_HAL_ERR_INTERNAL; + } + int32_t ret = AudioProxyDispatchCall(hwCapture->proxyRemoteHandle, AUDIO_HDI_CAPTURE_GET_MUTE, data, reply); + uint32_t tempMute = 0; + if (!HdfSbufReadUint32(reply, &tempMute)) { + AudioProxyBufReplyRecycle(data, reply); + return AUDIO_HAL_ERR_INTERNAL; + } + *mute = (bool)tempMute; + AudioProxyBufReplyRecycle(data, reply); + LOG_PARA_INFO("GetMute SUCCESS!"); + return ret; +} + +bool ReadReplyBuffer(struct HdfSBuf *reply, uint64_t replyBytes, void *frame, uint64_t requestBytes) +{ + const void *rBuf = nullptr; + uint32_t rLen; + if (HdfSbufReadBuffer(reply, &rBuf, &rLen) && rLen == replyBytes) { + if (memcpy_s(frame, requestBytes, rBuf, rLen) != EOK) { + return true; + } + } + return false; +} + +int32_t AudioProxyCaptureCaptureFrame(struct AudioCapture *capture, void *frame, + uint64_t requestBytes, uint64_t *replyBytes) +{ + HDF_LOGD("%{public}s", __func__); + if (frame == nullptr || replyBytes == nullptr) { + HDF_LOGE("Capture Frame Paras is NULL!"); + return AUDIO_HAL_ERR_INVALID_PARAM; + } + struct HdfSBuf *data = nullptr; + struct HdfSBuf *reply = nullptr; + struct AudioHwCapture *hwCapture = reinterpret_cast(capture); + if (hwCapture == nullptr || hwCapture->proxyRemoteHandle == nullptr) { + HDF_LOGE("The hwCapture parameter is null"); + return AUDIO_HAL_ERR_INVALID_PARAM; + } + if (AudioProxyPreprocessCapture(hwCapture, &data, &reply) < 0) { + HDF_LOGE("AudioProxyPreprocessCapture FAIL"); + return AUDIO_HAL_ERR_INTERNAL; + } + if (!HdfSbufWriteUint64(data, requestBytes)) { + AudioProxyBufReplyRecycle(data, reply); + HDF_LOGE("HdfSbufWriteUint64 FAIL"); + return AUDIO_HAL_ERR_INTERNAL; + } + int32_t ret = AudioProxyDispatchCall(hwCapture->proxyRemoteHandle, AUDIO_HDI_CAPTURE_CAPTURE_FRAME, data, reply); + if (ret < 0) { + if (ret != AUDIO_HAL_ERR_INVALID_OBJECT) { + HDF_LOGE("AudioCaptureCaptureFrame FAIL"); + } + AudioProxyBufReplyRecycle(data, reply); + return ret; + } + if (!HdfSbufReadUint64(reply, replyBytes)) { + AudioProxyBufReplyRecycle(data, reply); + HDF_LOGE("HdfSbufReadUint64 FAIL"); + return AUDIO_HAL_ERR_INTERNAL; + } + if (!ReadReplyBuffer(reply, *replyBytes, frame, requestBytes)) { + AudioProxyBufReplyRecycle(data, reply); + HDF_LOGE("memcpy rBuf failed"); + return AUDIO_HAL_ERR_INTERNAL; + } + AudioProxyBufReplyRecycle(data, reply); + return AUDIO_HAL_SUCCESS; +} +} \ No newline at end of file diff --git a/bluetooth/audio/hal/hdi_binder/proxy/src/audio_proxy_common.cpp b/bluetooth/audio/hal/hdi_binder/proxy/src/audio_proxy_common.cpp index 60f9f756b7..63b7155b84 100644 --- a/bluetooth/audio/hal/hdi_binder/proxy/src/audio_proxy_common.cpp +++ b/bluetooth/audio/hal/hdi_binder/proxy/src/audio_proxy_common.cpp @@ -101,6 +101,36 @@ int32_t AudioProxyPreprocessRender(struct AudioHwRender *render, struct HdfSBuf return HDF_SUCCESS; } +int32_t AudioProxyPreprocessCapture(struct AudioHwCapture *capture, struct HdfSBuf **data, struct HdfSBuf **reply) +{ + struct AudioHwCapture *hwCapture = capture; + if (hwCapture == nullptr || data == nullptr || reply == nullptr) { + return HDF_FAILURE; + } + uint32_t capturePid = (uint32_t)getpid(); + const char *adapterName = hwCapture->captureParam.captureMode.hwInfo.adapterName; + if (adapterName == nullptr) { + HDF_LOGE("adapterName is NULL"); + return HDF_FAILURE; + } + if (AudioProxyPreprocessSBuf(data, reply) < 0) { + return HDF_FAILURE; + } + if (!HdfRemoteServiceWriteInterfaceToken(capture->proxyRemoteHandle, *data)) { + AudioProxyBufReplyRecycle(*data, *reply); + return HDF_FAILURE; + } + if (!HdfSbufWriteString(*data, adapterName)) { + AudioProxyBufReplyRecycle(*data, *reply); + return HDF_FAILURE; + } + if (!HdfSbufWriteUint32(*data, capturePid)) { + AudioProxyBufReplyRecycle(*data, *reply); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + int32_t AudioProxyWriteSampleAttributes(struct HdfSBuf *data, const struct AudioSampleAttributes *attrs) { if (data == NULL || attrs == NULL) { diff --git a/bluetooth/audio/hal/hdi_binder/proxy/src/audio_proxy_manager.cpp b/bluetooth/audio/hal/hdi_binder/proxy/src/audio_proxy_manager.cpp index a30a4cca61..3fd63154ab 100644 --- a/bluetooth/audio/hal/hdi_binder/proxy/src/audio_proxy_manager.cpp +++ b/bluetooth/audio/hal/hdi_binder/proxy/src/audio_proxy_manager.cpp @@ -103,6 +103,8 @@ int32_t AudioProxyManagerLoadAdapter(struct AudioProxyManager *manager, const st hwAdapter->common.InitAllPorts = AudioProxyAdapterInitAllPorts; hwAdapter->common.CreateRender = AudioProxyAdapterCreateRender; hwAdapter->common.DestroyRender = AudioProxyAdapterDestroyRender; + hwAdapter->common.CreateCapture = AudioProxyAdapterCreateCapture; + hwAdapter->common.DestroyCapture = AudioProxyAdapterDestroyCapture; hwAdapter->common.GetPortCapability = AudioProxyAdapterGetPortCapability; hwAdapter->common.SetPassthroughMode = AudioProxyAdapterSetPassthroughMode; hwAdapter->common.GetPassthroughMode = AudioProxyAdapterGetPassthroughMode; diff --git a/bluetooth/audio/hal/hdi_binder/server/BUILD.gn b/bluetooth/audio/hal/hdi_binder/server/BUILD.gn index 9bea0dad82..92c6385fc3 100755 --- a/bluetooth/audio/hal/hdi_binder/server/BUILD.gn +++ b/bluetooth/audio/hal/hdi_binder/server/BUILD.gn @@ -51,6 +51,7 @@ ohos_shared_library("audio_bluetooth_hdi_adapter_server") { "src/hdf_audio_server.cpp", "src/hdf_audio_server_common.cpp", "src/hdf_audio_server_render.cpp", + "src/hdf_audio_server_capture.cpp", ] deps = [ "//drivers/peripheral/bluetooth/audio/hal/hdi_passthrough:hdi_audio_bluetooth" ] diff --git a/bluetooth/audio/hal/hdi_binder/server/include/hdf_audio_server.h b/bluetooth/audio/hal/hdi_binder/server/include/hdf_audio_server.h index 8dd81ac070..87d4fdbed4 100644 --- a/bluetooth/audio/hal/hdi_binder/server/include/hdf_audio_server.h +++ b/bluetooth/audio/hal/hdi_binder/server/include/hdf_audio_server.h @@ -64,7 +64,18 @@ enum AudioHdiServerCmdId { AUDIO_HDI_RENDER_TURN_STAND_BY_MODE, AUDIO_HDI_RENDER_DEV_DUMP, AUDIO_HDI_RENDER_REG_CALLBACK, - AUDIO_HDI_RENDER_DRAIN_BUFFER + AUDIO_HDI_RENDER_DRAIN_BUFFER, + /***********capture***************/ + AUDIO_HDI_CAPTURE_CREATE_CAPTURE, + AUDIO_HDI_CAPTURE_DESTROY, + AUDIO_HDI_CAPTURE_START, + AUDIO_HDI_CAPTURE_STOP, + AUDIO_HDI_CAPTURE_PAUSE, + AUDIO_HDI_CAPTURE_RESUME, + AUDIO_HDI_CAPTURE_FLUSH, + AUDIO_HDI_CAPTURE_CAPTURE_FRAME, + AUDIO_HDI_CAPTURE_GET_MUTE, + AUDIO_HDI_CAPTURE_SET_MUTE }; typedef int32_t (*AudioAllfunc)(const struct HdfDeviceIoClient *client, struct HdfSBuf *data, struct HdfSBuf *reply); diff --git a/bluetooth/audio/hal/hdi_binder/server/include/hdf_audio_server_capture.h b/bluetooth/audio/hal/hdi_binder/server/include/hdf_audio_server_capture.h new file mode 100644 index 0000000000..8e1d3670aa --- /dev/null +++ b/bluetooth/audio/hal/hdi_binder/server/include/hdf_audio_server_capture.h @@ -0,0 +1,42 @@ +/* + * 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. + */ + +#ifndef HDF_AUDIO_SERVER_CAPTURE_H +#define HDF_AUDIO_SERVER_CAPTURE_H + +#include "hdf_device_desc.h" +namespace OHOS::HDI::Audio_Bluetooth { +int32_t HdiServiceCreateCapture(const struct HdfDeviceIoClient *client, + struct HdfSBuf *data, struct HdfSBuf *reply); +int32_t HdiServiceCaptureDestory(const struct HdfDeviceIoClient *client, + struct HdfSBuf *data, struct HdfSBuf *reply); +int32_t HdiServiceCaptureStart(const struct HdfDeviceIoClient *client, + struct HdfSBuf *data, struct HdfSBuf *reply); +int32_t HdiServiceCaptureStop(const struct HdfDeviceIoClient *client, + struct HdfSBuf *data, struct HdfSBuf *reply); +int32_t HdiServiceCapturePause(const struct HdfDeviceIoClient *client, + struct HdfSBuf *data, struct HdfSBuf *reply); +int32_t HdiServiceCaptureResume(const struct HdfDeviceIoClient *client, + struct HdfSBuf *data, struct HdfSBuf *reply); +int32_t HdiServiceCaptureFlush(const struct HdfDeviceIoClient *client, + struct HdfSBuf *data, struct HdfSBuf *reply); +int32_t HdiServiceCaptureGetMute(const struct HdfDeviceIoClient *client, + struct HdfSBuf *data, struct HdfSBuf *reply); +int32_t HdiServiceCaptureSetMute(const struct HdfDeviceIoClient *client, + struct HdfSBuf *data, struct HdfSBuf *reply); +int32_t HdiServiceCaptureCaptureFrame(const struct HdfDeviceIoClient *client, + struct HdfSBuf *data, struct HdfSBuf *reply); +} +#endif diff --git a/bluetooth/audio/hal/hdi_binder/server/include/hdf_audio_server_common.h b/bluetooth/audio/hal/hdi_binder/server/include/hdf_audio_server_common.h index f02ed0f5a3..587ac13fef 100644 --- a/bluetooth/audio/hal/hdi_binder/server/include/hdf_audio_server_common.h +++ b/bluetooth/audio/hal/hdi_binder/server/include/hdf_audio_server_common.h @@ -34,6 +34,12 @@ struct AudioInfoInAdapter { bool renderBusy; bool renderDestory; uint32_t renderPid; + int captureStatus; + int capturePriority; + struct AudioCapture *capture; + bool captureBusy; + bool captureDestroy; + uint32_t capturePid; }; int32_t AudioAdapterListGetAdapter(const char *adapterName, struct AudioAdapter **adapter); @@ -67,5 +73,17 @@ int32_t AdaptersServerManageInit(const struct AudioAdapterDescriptor *descs, int int32_t HdiServicePositionWrite(struct HdfSBuf *reply, uint64_t frames, struct AudioTimeStamp time); int32_t HdiServiceReqMmapBuffer(struct AudioMmapBufferDescriptor *desc, struct HdfSBuf *data); +int32_t AudioAdapterListGetCapture(const char *adapterName, struct AudioCapture **capture, + uint32_t pid); +int32_t AudioAdapterListGetAdapterCapture(const char *adapterName, struct AudioAdapter **adapter, + struct AudioCapture **capture); +int32_t AudioDestroyCaptureInfoInAdapter(const char *adapterName); +int32_t AudioAddCaptureInfoInAdapter(const char *adapterName, struct AudioCapture *capture, + const struct AudioAdapter *adapter, const int32_t priority, uint32_t capturePid); +int32_t AudioAdapterListCheckAndGetCapture(struct AudioCapture **capture, struct HdfSBuf *data); +int32_t AudioCreateCaptureCheck(const char *adapterName, const int32_t priority); +int32_t AudioAdapterFrameGetCapture(const char *adapterName, struct AudioCapture **capture, uint32_t pid, + uint32_t *index); +void AudioSetCaptureBusy(uint32_t index, bool captureStatus); } #endif diff --git a/bluetooth/audio/hal/hdi_binder/server/src/hdf_audio_server.cpp b/bluetooth/audio/hal/hdi_binder/server/src/hdf_audio_server.cpp index 4c5948686f..79cafa099e 100644 --- a/bluetooth/audio/hal/hdi_binder/server/src/hdf_audio_server.cpp +++ b/bluetooth/audio/hal/hdi_binder/server/src/hdf_audio_server.cpp @@ -17,6 +17,7 @@ #include "hdf_audio_server_common.h" #include "hdf_audio_server_render.h" #include "hdf_audio_server.h" +#include "hdf_audio_server_capture.h" namespace OHOS::HDI::Audio_Bluetooth { #define HDF_LOG_TAG hdf_audio_bluetooth_server @@ -403,6 +404,16 @@ struct HdiServiceDispatchCmdHandleList g_hdiServiceDispatchCmdHandleList[] = { {AUDIO_HDI_RENDER_DEV_DUMP, HdiServiceRenderDevDump}, {AUDIO_HDI_RENDER_REG_CALLBACK, HdiServiceRenderRegCallback}, {AUDIO_HDI_RENDER_DRAIN_BUFFER, HdiServiceRenderDrainBuffer}, + {AUDIO_HDI_CAPTURE_CREATE_CAPTURE, HdiServiceCreateCapture}, + {AUDIO_HDI_CAPTURE_DESTROY, HdiServiceCaptureDestory}, + {AUDIO_HDI_CAPTURE_START, HdiServiceCaptureStart}, + {AUDIO_HDI_CAPTURE_STOP, HdiServiceCaptureStop}, + {AUDIO_HDI_CAPTURE_PAUSE, HdiServiceCapturePause}, + {AUDIO_HDI_CAPTURE_RESUME, HdiServiceCaptureResume}, + {AUDIO_HDI_CAPTURE_FLUSH, HdiServiceCaptureFlush}, + {AUDIO_HDI_CAPTURE_GET_MUTE, HdiServiceCaptureGetMute}, + {AUDIO_HDI_CAPTURE_SET_MUTE, HdiServiceCaptureSetMute}, + {AUDIO_HDI_CAPTURE_CAPTURE_FRAME, HdiServiceCaptureCaptureFrame}, }; static int32_t HdiServiceDispatch(struct HdfDeviceIoClient *client, int cmdId, struct HdfSBuf *data, @@ -417,10 +428,10 @@ static int32_t HdiServiceDispatch(struct HdfDeviceIoClient *client, int cmdId, s if (!HdfDeviceObjectCheckInterfaceDesc(client->device, data)) { return AUDIO_HAL_ERR_INVALID_PARAM; } - if (cmdId > AUDIO_HDI_RENDER_DRAIN_BUFFER || cmdId < 0) { + if (cmdId > AUDIO_HDI_CAPTURE_SET_MUTE || cmdId < 0) { HDF_LOGE("ControlDispatch: invalid cmdId = %{public}d", cmdId); return AUDIO_HAL_ERR_INTERNAL; - } else if (cmdId <= AUDIO_HDI_RENDER_DRAIN_BUFFER) { + } else if (cmdId <= AUDIO_HDI_CAPTURE_SET_MUTE) { for (i = 0; i < sizeof(g_hdiServiceDispatchCmdHandleList) / sizeof(g_hdiServiceDispatchCmdHandleList[0]); ++i) { if ((cmdId == (int)(g_hdiServiceDispatchCmdHandleList[i].cmd)) && diff --git a/bluetooth/audio/hal/hdi_binder/server/src/hdf_audio_server_capture.cpp b/bluetooth/audio/hal/hdi_binder/server/src/hdf_audio_server_capture.cpp new file mode 100644 index 0000000000..2a6c88e89f --- /dev/null +++ b/bluetooth/audio/hal/hdi_binder/server/src/hdf_audio_server_capture.cpp @@ -0,0 +1,364 @@ +/* + * 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. + */ +#include "hdf_audio_server_capture.h" +#include "hdf_audio_server_common.h" +#include "osal_mem.h" + +#ifdef LOG_DOMAIN +#undef LOG_DOMAIN +#endif + +#define LOG_DOMAIN 0xD000105 + +namespace OHOS::HDI::Audio_Bluetooth { +int32_t GetInitCaptureParaAttrs(struct HdfSBuf *data, struct AudioSampleAttributes *attrs) +{ + if (data == nullptr || attrs == nullptr) { + return HDF_FAILURE; + } + uint32_t tempCapturePara = 0; + if (!HdfSbufReadUint32(data, &tempCapturePara)) { + HDF_LOGE("%{public}s: read tempCapturePara fail", __func__); + return HDF_FAILURE; + } + attrs->type = (AudioCategory)tempCapturePara; + if (!HdfSbufReadUint32(data, &attrs->period)) { + HDF_LOGE("%{public}s: read period fail", __func__); + return HDF_FAILURE; + } + if (!HdfSbufReadUint32(data, &attrs->frameSize)) { + HDF_LOGE("%{public}s: read frameSize fail", __func__); + return HDF_FAILURE; + } + if (!HdfSbufReadUint32(data, &attrs->startThreshold)) { + HDF_LOGE("%{public}s: read startThreshold fail", __func__); + return HDF_FAILURE; + } + if (!HdfSbufReadUint32(data, &attrs->stopThreshold)) { + HDF_LOGE("%{public}s: read stopThreshold fail", __func__); + return HDF_FAILURE; + } + if (!HdfSbufReadUint32(data, &attrs->silenceThreshold)) { + HDF_LOGE("%{public}s: read silenceThreshold fail", __func__); + return HDF_FAILURE; + } + if (!HdfSbufReadUint32(data, &tempCapturePara)) { + HDF_LOGE("%{public}s: read bool isBigEndian fail", __func__); + return HDF_FAILURE; + } + attrs->isBigEndian = (bool)tempCapturePara; + return HDF_SUCCESS; +} + +int32_t GetInitCapturePara(struct HdfSBuf *data, struct AudioDeviceDescriptor *devDesc, + struct AudioSampleAttributes *attrs) +{ + if (data == nullptr || devDesc == nullptr || attrs == nullptr) { + return HDF_FAILURE; + } + uint32_t tempCapturePara = 0; + if (!HdfSbufReadUint32(data, &tempCapturePara)) { + HDF_LOGE("%{public}s: read attrs format fail", __func__); + return HDF_FAILURE; + } + attrs->format = (AudioFormat)tempCapturePara; + if (!HdfSbufReadUint32(data, &attrs->channelCount)) { + HDF_LOGE("%{public}s: read channelCount fail", __func__); + return HDF_FAILURE; + } + if (!HdfSbufReadUint32(data, &attrs->sampleRate)) { + HDF_LOGE("%{public}s: read sampleRate fail", __func__); + return HDF_FAILURE; + } + if (!HdfSbufReadUint32(data, &tempCapturePara)) { + HDF_LOGE("%{public}s: read attrs interleaved fail", __func__); + return HDF_FAILURE; + } + attrs->interleaved = (bool)tempCapturePara; + if (GetInitCaptureParaAttrs(data, attrs) < 0) { + return HDF_FAILURE; + } + if (!HdfSbufReadUint32(data, &tempCapturePara)) { + HDF_LOGE("%{public}s: read attrs isSignedData fail", __func__); + return HDF_FAILURE; + } + attrs->isSignedData = (bool)tempCapturePara; + if (!HdfSbufReadUint32(data, &devDesc->portId)) { + HDF_LOGE("%{public}s: read portId fail", __func__); + return HDF_FAILURE; + } + if (!HdfSbufReadUint32(data, &tempCapturePara)) { + HDF_LOGE("%{public}s: read tempRenderPara fail", __func__); + return HDF_FAILURE; + } + devDesc->pins = (AudioPortPin)tempCapturePara; + devDesc->desc = nullptr; + return HDF_SUCCESS; +} + +int32_t HdiServiceCreateCapture(const struct HdfDeviceIoClient *client, + struct HdfSBuf *data, struct HdfSBuf *reply) +{ + if (client == nullptr || data == nullptr || reply == nullptr) { + return AUDIO_HAL_ERR_INVALID_PARAM; + } + struct AudioAdapter *adapter = nullptr; + struct AudioDeviceDescriptor devDesc; + struct AudioSampleAttributes attrs; + struct AudioCapture *capture = nullptr; + const char *adapterName = nullptr; + uint32_t capturePid = 0; + if ((adapterName = HdfSbufReadString(data)) == nullptr) { + HDF_LOGE("%{public}s: adapterNameCase Is NULL", __func__); + return AUDIO_HAL_ERR_INVALID_PARAM; + } + if (!HdfSbufReadUint32(data, &capturePid)) { + return AUDIO_HAL_ERR_INTERNAL; + } + HDF_LOGE("HdiServiceCreatRender: capturePid = %{public}u", capturePid); + int32_t ret = GetInitCapturePara(data, &devDesc, &attrs); + if (ret < 0) { + HDF_LOGE("%{public}s: GetInitCapturePara fail", __func__); + return AUDIO_HAL_ERR_INTERNAL; + } + if (AudioAdapterListGetAdapter(adapterName, &adapter)) { + HDF_LOGE("%{public}s: fail", __func__); + return AUDIO_HAL_ERR_INTERNAL; + } + if (adapter == nullptr) { + HDF_LOGE("%{public}s: adapter is NULL!", __func__); + return AUDIO_HAL_ERR_INVALID_PARAM; + } + const int32_t priority = attrs.type; + ret = AudioCreateCaptureCheck(adapterName, priority); + if (ret < 0) { + HDF_LOGE("%{public}s: AudioCreateCaptureCheck: Capture is working can not replace!", __func__); + return ret; + } + ret = adapter->CreateCapture(adapter, &devDesc, &attrs, &capture); + if (capture == nullptr || ret < 0) { + HDF_LOGE("%{public}s: Failed to CreateCapture", __func__); + return AUDIO_HAL_ERR_INTERNAL; + } + if (AudioAddCaptureInfoInAdapter(adapterName, capture, adapter, priority, capturePid)) { + HDF_LOGE("%{public}s: AudioAddCaptureInfoInAdapter", __func__); + adapter->DestroyCapture(adapter, capture); + return AUDIO_HAL_ERR_INTERNAL; + } + return AUDIO_HAL_SUCCESS; +} + +int32_t HdiServiceCaptureDestory(const struct HdfDeviceIoClient *client, + struct HdfSBuf *data, struct HdfSBuf *reply) +{ + if (client == nullptr || data == nullptr || reply == nullptr) { + return AUDIO_HAL_ERR_INVALID_PARAM; + } + struct AudioAdapter *adapter = nullptr; + struct AudioCapture *capture = nullptr; + const char *adapterName = nullptr; + uint32_t pid = 0; + if (HdiServiceRenderCaptureReadData(data, &adapterName, &pid) < 0) { + return AUDIO_HAL_ERR_INTERNAL; + } + int32_t ret = AudioAdapterListGetCapture(adapterName, &capture, pid); + if (ret < 0) { + return ret; + } + ret = AudioAdapterListGetAdapterCapture(adapterName, &adapter, &capture); + if (ret < 0) { + return ret; + } + if (adapter == nullptr || capture == nullptr) { + return AUDIO_HAL_ERR_INVALID_PARAM; + } + HDF_LOGI("%{public}s: DestroyCapture.", __func__); + ret = adapter->DestroyCapture(adapter, capture); + if (ret < 0) { + HDF_LOGE("%{public}s: DestroyCapture failed!", __func__); + return ret; + } + if (AudioDestroyCaptureInfoInAdapter(adapterName)) { + return AUDIO_HAL_ERR_INTERNAL; + } + return AUDIO_HAL_SUCCESS; +} + +int32_t HdiServiceCaptureStart(const struct HdfDeviceIoClient *client, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + if (client == nullptr || data == nullptr || reply == nullptr) { + return AUDIO_HAL_ERR_INVALID_PARAM; + } + struct AudioCapture *capture = nullptr; + int ret = AudioAdapterListCheckAndGetCapture(&capture, data); + if (ret < 0) { + return ret; + } + return capture->control.Start((AudioHandle)capture); +} + +int32_t HdiServiceCaptureStop(const struct HdfDeviceIoClient *client, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + if (client == nullptr || data == nullptr || reply == nullptr) { + return AUDIO_HAL_ERR_INVALID_PARAM; + } + struct AudioCapture *capture = nullptr; + int ret = AudioAdapterListCheckAndGetCapture(&capture, data); + if (ret < 0) { + return ret; + } + return capture->control.Stop((AudioHandle)capture); +} + +int32_t HdiServiceCapturePause(const struct HdfDeviceIoClient *client, + struct HdfSBuf *data, struct HdfSBuf *reply) +{ + if (client == nullptr || data == nullptr || reply == nullptr) { + return AUDIO_HAL_ERR_INVALID_PARAM; + } + HDF_LOGE("%{public}s: enter", __func__); + struct AudioCapture *capture = nullptr; + int ret = AudioAdapterListCheckAndGetCapture(&capture, data); + if (ret < 0) { + return ret; + } + return capture->control.Pause((AudioHandle)capture); +} + +int32_t HdiServiceCaptureResume(const struct HdfDeviceIoClient *client, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + if (client == nullptr || data == nullptr || reply == nullptr) { + return AUDIO_HAL_ERR_INVALID_PARAM; + } + struct AudioCapture *capture = nullptr; + int ret = AudioAdapterListCheckAndGetCapture(&capture, data); + if (ret < 0) { + return ret; + } + return capture->control.Resume((AudioHandle)capture); +} + +int32_t HdiServiceCaptureFlush(const struct HdfDeviceIoClient *client, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + if (client == nullptr || data == nullptr || reply == nullptr) { + HDF_LOGI("%{public}s: The parameter is empty", __func__); + return AUDIO_HAL_ERR_INVALID_PARAM; + } + struct AudioCapture *capture = nullptr; + int ret = AudioAdapterListCheckAndGetCapture(&capture, data); + if (ret < 0) { + return ret; + } + return capture->control.Flush((AudioHandle)capture); +} + +int32_t HdiServiceCaptureGetMute(const struct HdfDeviceIoClient *client, + struct HdfSBuf *data, struct HdfSBuf *reply) +{ + if (client == nullptr || data == nullptr || reply == nullptr) { + HDF_LOGI("%{public}s: parameter is empty", __func__); + return AUDIO_HAL_ERR_INVALID_PARAM; + } + bool mute = false; + struct AudioCapture *capture = nullptr; + int ret = AudioAdapterListCheckAndGetCapture(&capture, data); + if (ret < 0) { + return ret; + } + ret = capture->volume.GetMute((AudioHandle)capture, &mute); + if (ret < 0) { + return ret; + } + uint32_t tempMute = (uint32_t)mute; + if (!HdfSbufWriteUint32(reply, tempMute)) { + return AUDIO_HAL_ERR_INTERNAL; + } + return AUDIO_HAL_SUCCESS; +} + +int32_t HdiServiceCaptureSetMute(const struct HdfDeviceIoClient *client, + struct HdfSBuf *data, struct HdfSBuf *reply) +{ + if (client == nullptr || data == nullptr || reply == nullptr) { + return AUDIO_HAL_ERR_INVALID_PARAM; + } + bool mute = false; + struct AudioCapture *capture = nullptr; + int ret = AudioAdapterListCheckAndGetCapture(&capture, data); + if (ret < 0) { + return ret; + } + uint32_t tempMute = 0; + if (!HdfSbufReadUint32(data, &tempMute)) { + return AUDIO_HAL_ERR_INTERNAL; + } + mute = (bool)tempMute; + return capture->volume.SetMute((AudioHandle)capture, mute); +} + +int32_t HdiServiceCaptureCaptureFrame(const struct HdfDeviceIoClient *client, + struct HdfSBuf *data, struct HdfSBuf *reply) +{ + if (client == nullptr || data == nullptr || reply == nullptr) { + return AUDIO_HAL_ERR_INVALID_PARAM; + } + char *frame = nullptr; + uint64_t requestBytes; + uint64_t replyBytes; + struct AudioCapture *capture = nullptr; + const char *adapterName = nullptr; + uint32_t pid; + uint32_t index = 0; + if (HdiServiceRenderCaptureReadData(data, &adapterName, &pid) < 0) { + HDF_LOGE("%{public}s: HdiServiceRenderCaptureReadData fail!", __func__); + return AUDIO_HAL_ERR_INTERNAL; + } + int32_t ret = AudioAdapterFrameGetCapture(adapterName, &capture, pid, &index); + if (ret < 0) { + HDF_LOGE("%{public}s: AudioAdapterFrameGetCapture fail", __func__); + return ret; + } + if (!HdfSbufReadUint64(data, &requestBytes)) { + return AUDIO_HAL_ERR_INTERNAL; + } + frame = (char *)OsalMemCalloc(FRAME_DATA); + if (frame == nullptr) { + return AUDIO_HAL_ERR_MALLOC_FAIL; + } + AudioSetCaptureBusy(index, true); + if (capture == nullptr || capture->CaptureFrame == nullptr) { + HDF_LOGE("capture or capureFrame in NULL"); + AudioMemFree(reinterpret_cast(&frame)); + return AUDIO_HAL_ERR_INTERNAL; + } + ret = capture->CaptureFrame(capture, (void *)frame, requestBytes, &replyBytes); + AudioSetCaptureBusy(index, false); + if (ret < 0) { + AudioMemFree(reinterpret_cast(&frame)); + return ret; + } + if (!HdfSbufWriteUint64(reply, replyBytes)) { + AudioMemFree(reinterpret_cast(&frame)); + return AUDIO_HAL_ERR_INTERNAL; + } + if (!HdfSbufWriteBuffer(reply, (const void *)frame, replyBytes)) { + AudioMemFree(reinterpret_cast(&frame)); + return AUDIO_HAL_ERR_INTERNAL; + } + AudioMemFree(reinterpret_cast(&frame)); + return AUDIO_HAL_SUCCESS; +} + +} \ No newline at end of file diff --git a/bluetooth/audio/hal/hdi_binder/server/src/hdf_audio_server_common.cpp b/bluetooth/audio/hal/hdi_binder/server/src/hdf_audio_server_common.cpp index 10abd24aba..59d5877aed 100644 --- a/bluetooth/audio/hal/hdi_binder/server/src/hdf_audio_server_common.cpp +++ b/bluetooth/audio/hal/hdi_binder/server/src/hdf_audio_server_common.cpp @@ -303,6 +303,37 @@ int32_t AudioDestroyFormerRender(struct AudioInfoInAdapter *renderManage) return HDF_SUCCESS; } +int32_t AudioDestroyFormerCapture(struct AudioInfoInAdapter *captureManage) +{ + LOG_FUN_INFO(); + if (captureManage == nullptr || captureManage->adapter == nullptr || captureManage->capture == nullptr) { + HDF_LOGE("%{public}s: input para is NULL. ", __func__); + return HDF_FAILURE; + } + int count = 0; + captureManage->captureDestroy = true; + while (captureManage->captureBusy) { + if (count > 1000) { // Less than 1000 + HDF_LOGE("%{public}s: , count = %{public}d", __func__, count); + captureManage->captureDestroy = false; + return AUDIO_HAL_ERR_AO_BUSY; // render is busy now + } + usleep(500); // sleep 500us + count++; + } + captureManage->capturePid = 0; + if (captureManage->adapter->DestroyCapture(captureManage->adapter, captureManage->capture)) { + captureManage->captureDestroy = false; + return HDF_FAILURE; + } + captureManage->capture = nullptr; + captureManage->captureStatus = 0; + captureManage->captureBusy = false; + captureManage->captureDestroy = false; + captureManage->capturePriority = -1; + return HDF_SUCCESS; +} + int32_t AudioJudgeRenderPriority(const int32_t priority, int which) { int32_t num; @@ -327,6 +358,30 @@ int32_t AudioJudgeRenderPriority(const int32_t priority, int which) return HDF_FAILURE; } +int32_t AudioJudgeCapturePriority(const int32_t priority, int which) +{ + int32_t num = (g_serverAdapterNum > MAX_AUDIO_ADAPTER_NUM_SERVER) + ? MAX_AUDIO_ADAPTER_NUM_SERVER + : g_serverAdapterNum; + if (which < 0 || which >= num) { + HDF_LOGE("%{public}s: invalid value! ", __func__); + return HDF_FAILURE; + } + if (g_renderAndCaptureManage == NULL) { + return HDF_FAILURE; + } + if (g_renderAndCaptureManage[which].capturePriority <= priority) { + if (AudioDestroyFormerCapture(&g_renderAndCaptureManage[which])) { + HDF_LOGE("%{public}s: AudioDestroyFormerCapture: Fail. ", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; + } else { + return AUDIO_HAL_ERR_AO_BUSY; // render is busy now + } + return HDF_FAILURE; +} + int32_t AudioCreatRenderCheck(const char *adapterName, const int32_t priority) { int32_t i; @@ -336,8 +391,9 @@ int32_t AudioCreatRenderCheck(const char *adapterName, const int32_t priority) return HDF_FAILURE; } - int32_t num = (g_serverAdapterNum > MAX_AUDIO_ADAPTER_NUM_SERVER) ? - MAX_AUDIO_ADAPTER_NUM_SERVER : g_serverAdapterNum; + int32_t num = (g_serverAdapterNum > MAX_AUDIO_ADAPTER_NUM_SERVER) + ? MAX_AUDIO_ADAPTER_NUM_SERVER + : g_serverAdapterNum; for (i = 0; i < num; i++) { if (g_renderAndCaptureManage[i].adapterName == NULL) { return HDF_FAILURE; @@ -354,6 +410,32 @@ int32_t AudioCreatRenderCheck(const char *adapterName, const int32_t priority) return HDF_FAILURE; } +int32_t AudioCreateCaptureCheck(const char *adapterName, const int32_t priority) +{ + int32_t i; + LOG_FUN_INFO(); + if (adapterName == NULL || g_renderAndCaptureManage == NULL) { + return HDF_FAILURE; + } + int32_t num = (g_serverAdapterNum > MAX_AUDIO_ADAPTER_NUM_SERVER) + ? MAX_AUDIO_ADAPTER_NUM_SERVER + : g_serverAdapterNum; + for (i = 0; i < num; i++) { + if (g_renderAndCaptureManage[i].adapterName == NULL) { + return HDF_FAILURE; + } + if (!strcmp(g_renderAndCaptureManage[i].adapterName, adapterName)) { + if (!(g_renderAndCaptureManage[i].captureStatus)) { + return HDF_SUCCESS; + } else { + return AudioJudgeCapturePriority(priority, i); + } + } + } + HDF_LOGE("%{public}s: Can not find Adapter! ", __func__); + return HDF_FAILURE; +} + int32_t AudioAddRenderInfoInAdapter(const char *adapterName, struct AudioRender *render, const struct AudioAdapter *adapter, @@ -386,6 +468,35 @@ int32_t AudioAddRenderInfoInAdapter(const char *adapterName, return HDF_FAILURE; } +int32_t AudioAddCaptureInfoInAdapter(const char *adapterName, struct AudioCapture *capture, + const struct AudioAdapter *adapter, const int32_t priority, uint32_t capturePid) +{ + int32_t i; + int32_t num; + if (adapterName == nullptr || adapter == nullptr || capture == nullptr) { + HDF_LOGE("%{public}s: input para is NULL. ", __func__); + return HDF_FAILURE; + } + if (g_renderAndCaptureManage == nullptr) { + return HDF_FAILURE; + } + num = (g_serverAdapterNum > MAX_AUDIO_ADAPTER_NUM_SERVER) ? MAX_AUDIO_ADAPTER_NUM_SERVER : g_serverAdapterNum; + for (i = 0; i < num; i++) { + if (g_renderAndCaptureManage[i].adapterName == nullptr) { + return HDF_FAILURE; + } + if (!strcmp(g_renderAndCaptureManage[i].adapterName, adapterName)) { + g_renderAndCaptureManage[i].captureStatus = 1; + g_renderAndCaptureManage[i].capturePriority = priority; + g_renderAndCaptureManage[i].capture = capture; + g_renderAndCaptureManage[i].capturePid = capturePid; + return HDF_SUCCESS; + } + } + HDF_LOGE("%{public}s: Can not find Adapter! ", __func__); + return HDF_FAILURE; +} + void AudioSetRenderStatus(const char *adapterName, bool renderStatus) { int32_t i, num; @@ -470,6 +581,35 @@ int32_t AudioDestroyRenderInfoInAdapter(const char *adapterName) return HDF_FAILURE; } +int32_t AudioDestroyCaptureInfoInAdapter(const char *adapterName) +{ + int32_t i; + int32_t num; + LOG_FUN_INFO(); + if (adapterName == nullptr) { + HDF_LOGE("%{public}s: adapterName is null ", __func__); + return HDF_FAILURE; + } + num = (g_serverAdapterNum > MAX_AUDIO_ADAPTER_NUM_SERVER) ? MAX_AUDIO_ADAPTER_NUM_SERVER : g_serverAdapterNum; + if (g_renderAndCaptureManage == nullptr) { + return HDF_FAILURE; + } + for (i = 0; i < num; i++) { + if (g_renderAndCaptureManage[i].adapterName == nullptr) { + return HDF_FAILURE; + } + if (!strcmp(g_renderAndCaptureManage[i].adapterName, adapterName)) { + g_renderAndCaptureManage[i].captureStatus = 0; + g_renderAndCaptureManage[i].capturePriority = -1; + g_renderAndCaptureManage[i].capture = nullptr; + g_renderAndCaptureManage[i].capturePid = 0; + return HDF_SUCCESS; + } + } + HDF_LOGE("%{public}s: Can not find Adapter! ", __func__); + return HDF_FAILURE; +} + int32_t AudioAdapterListGetPid(const char *adapterName, uint32_t *pid) { LOG_FUN_INFO(); @@ -524,6 +664,34 @@ int32_t AudioAdapterListGetAdapterRender(const char *adapterName, return HDF_ERR_INVALID_PARAM; } +int32_t AudioAdapterListGetAdapterCapture(const char *adapterName, + struct AudioAdapter **adapter, struct AudioCapture **capture) +{ + int32_t i; + int32_t num; + LOG_FUN_INFO(); + if (g_renderAndCaptureManage == nullptr) { + return HDF_ERR_INVALID_PARAM; + } + if (adapterName == nullptr || adapter == nullptr || capture == nullptr) { + HDF_LOGE("%{public}s: The pointer is null ", __func__); + return HDF_ERR_INVALID_PARAM; + } + + num = (g_serverAdapterNum > MAX_AUDIO_ADAPTER_NUM_SERVER) ? MAX_AUDIO_ADAPTER_NUM_SERVER : g_serverAdapterNum; + for (i = 0; i < num; i++) { + if (g_renderAndCaptureManage[i].adapterName == nullptr) { + return HDF_ERR_INVALID_PARAM; + } + if (!strcmp(g_renderAndCaptureManage[i].adapterName, adapterName)) { + *adapter = g_renderAndCaptureManage[i].adapter; + *capture = g_renderAndCaptureManage[i].capture; + return HDF_SUCCESS; + } + } + return HDF_ERR_INVALID_PARAM; +} + int32_t AudioAdapterListGetRender(const char *adapterName, struct AudioRender **render, uint32_t pid) { int32_t num; @@ -554,6 +722,72 @@ int32_t AudioAdapterListGetRender(const char *adapterName, struct AudioRender ** return HDF_ERR_INVALID_PARAM; } +int32_t AudioAdapterListGetCapture(const char *adapterName, struct AudioCapture **capture, uint32_t pid) +{ + int32_t num; + HDF_LOGD("%{public}s: enter ", __func__); + if (g_renderAndCaptureManage == nullptr) { + return HDF_ERR_INVALID_PARAM; + } + if (adapterName == nullptr || capture == nullptr) { + HDF_LOGE("%{public}s: pointer is null ", __func__); + return HDF_ERR_INVALID_PARAM; + } + num = (g_serverAdapterNum > MAX_AUDIO_ADAPTER_NUM_SERVER) ? MAX_AUDIO_ADAPTER_NUM_SERVER : g_serverAdapterNum; + for (int32_t i = 0; i < num; i++) { + if (g_renderAndCaptureManage[i].adapterName == nullptr) { + return HDF_ERR_INVALID_PARAM; + } + if (!strcmp(g_renderAndCaptureManage[i].adapterName, adapterName)) { + if (g_renderAndCaptureManage[i].capturePid != pid) { + HDF_LOGE("%{public}s: renderPid != pid renderPid = %{public}u, pid = %{public}u", + __func__, g_renderAndCaptureManage[i].capturePid, pid); + return AUDIO_HAL_ERR_INVALID_OBJECT; + } + *capture = g_renderAndCaptureManage[i].capture; + return HDF_SUCCESS; + } + } + return HDF_ERR_INVALID_PARAM; +} + +int32_t AudioAdapterFrameGetCapture(const char *adapterName, struct AudioCapture **capture, uint32_t pid, + uint32_t *index) +{ + if (adapterName == nullptr || capture == nullptr || index == nullptr) { + HDF_LOGE("adapterName or capture or index is null"); + return HDF_ERR_INVALID_PARAM; + } + int32_t num = (g_serverAdapterNum > MAX_AUDIO_ADAPTER_NUM_SERVER) + ? MAX_AUDIO_ADAPTER_NUM_SERVER + : g_serverAdapterNum; + *index = MAX_AUDIO_ADAPTER_NUM_SERVER; + for (int32_t i = 0; i < num; i++) { + if (g_renderAndCaptureManage[i].adapterName == nullptr) { + HDF_LOGE("g_renderAndCaptureManage[%{public}d] adapterName is null!", i); + return HDF_ERR_INVALID_PARAM; + } + if (strcmp(g_renderAndCaptureManage[i].adapterName, adapterName) == 0) { + if (g_renderAndCaptureManage[i].capturePid != pid) { + HDF_LOGE("%{public}s: capturePid != pid capturePid = %{public}u, pid = %{public}u", + __func__, g_renderAndCaptureManage[i].capturePid, pid); + return AUDIO_HAL_ERR_INVALID_OBJECT; + } + if (!g_renderAndCaptureManage[i].captureDestroy) { + *capture = g_renderAndCaptureManage[i].capture; + *index = i; + return HDF_SUCCESS; + } else { + g_renderAndCaptureManage[i].captureBusy = false; + HDF_LOGE("g_renderAndCaptureManage[%{public}d] captureBusy is false!", i); + return HDF_FAILURE; + } + } + } + HDF_LOGE("AudioAdapterFrameGetCapture failed!"); + return HDF_FAILURE; +} + int32_t AudioAdapterListCheckAndGetRender(struct AudioRender **render, struct HdfSBuf *data) { if (render == NULL || data == NULL) { @@ -577,6 +811,29 @@ int32_t AudioAdapterListCheckAndGetRender(struct AudioRender **render, struct Hd return HDF_SUCCESS; } +int32_t AudioAdapterListCheckAndGetCapture(struct AudioCapture **capture, struct HdfSBuf *data) +{ + if (capture == nullptr || data == nullptr) { + return HDF_FAILURE; + } + struct AudioCapture *captureTemp = nullptr; + const char *adapterName = nullptr; + uint32_t pid = 0; + if (HdiServiceRenderCaptureReadData(data, &adapterName, &pid) < 0) { + HDF_LOGE("%{public}s: HdiServiceRenderStart: HdiServiceRenderCaptureReadData fail ", __func__); + return HDF_FAILURE; + } + int ret = AudioAdapterListGetCapture(adapterName, &captureTemp, pid); + if (ret < 0) { + return ret; + } + if (captureTemp == NULL) { + return HDF_FAILURE; + } + *capture = captureTemp; + return HDF_SUCCESS; +} + int32_t AudioAdapterCheckListExist(const char *adapterName) { int32_t i, num; @@ -717,4 +974,11 @@ int32_t HdiServiceReqMmapBuffer(struct AudioMmapBufferDescriptor *desc, struct H } return AUDIO_HAL_SUCCESS; } + +void AudioSetCaptureBusy(uint32_t index, bool captureStatus) +{ + if (index == MAX_AUDIO_ADAPTER_NUM_SERVER) { + g_renderAndCaptureManage[index].captureBusy = captureStatus; + } +} } \ No newline at end of file diff --git a/bluetooth/audio/hal/hdi_config/a2dp_adapter_config.json b/bluetooth/audio/hal/hdi_config/a2dp_adapter_config.json index 01ab558f01..d8dcfb2932 100644 --- a/bluetooth/audio/hal/hdi_config/a2dp_adapter_config.json +++ b/bluetooth/audio/hal/hdi_config/a2dp_adapter_config.json @@ -1,5 +1,5 @@ { - "adapterNum": 5, + "adapterNum": 6, "adapters": [{ "name": "internal", "portnum": 2, @@ -59,5 +59,14 @@ "id": 0, "name": "AOP" }] + }, + { + "name": "bt_hdap", + "portnum": 1, + "port": [{ + "dir": "PORT_IN", + "id": 0, + "name": "AIP" + }] }] } diff --git a/bluetooth/audio/hal/hdi_passthrough/BUILD.gn b/bluetooth/audio/hal/hdi_passthrough/BUILD.gn index b8a0e7121a..a27dcffc3b 100644 --- a/bluetooth/audio/hal/hdi_passthrough/BUILD.gn +++ b/bluetooth/audio/hal/hdi_passthrough/BUILD.gn @@ -60,6 +60,7 @@ ohos_shared_library("hdi_audio_bluetooth") { "src/bluetooth_a2dp_audio_src_observer_stub.cpp", "src/bluetooth_a2dp_src_observer.cpp", "src/fast_audio_render.cpp", + "src/audio_capture.cpp", ] include_dirs = [ diff --git a/bluetooth/audio/hal/hdi_passthrough/include/audio_bluetooth_manager.h b/bluetooth/audio/hal/hdi_passthrough/include/audio_bluetooth_manager.h index 3ceda84514..c4f1bcf025 100644 --- a/bluetooth/audio/hal/hdi_passthrough/include/audio_bluetooth_manager.h +++ b/bluetooth/audio/hal/hdi_passthrough/include/audio_bluetooth_manager.h @@ -54,6 +54,12 @@ int FastStopPlaying(); int FastReqMmapBuffer(int32_t ashmemLength); void FastReadMmapPosition(int64_t &sec, int64_t &nSec, uint64_t &frames); int FastGetLatency(uint32_t &latency); +bool SetUpCapture(); +void TearDownCapture(); +int StartCapture(); +int SuspendCapture(); +int StopCapture(); +int ReadFrame(uint8_t *data, uint64_t size); #endif int WriteFrame(const uint8_t *data, uint32_t size, const HDI::Audio_Bluetooth::AudioSampleAttributes *attrs); diff --git a/bluetooth/audio/hal/hdi_passthrough/include/audio_internal.h b/bluetooth/audio/hal/hdi_passthrough/include/audio_internal.h index 2c381248d0..fb9d629b3a 100644 --- a/bluetooth/audio/hal/hdi_passthrough/include/audio_internal.h +++ b/bluetooth/audio/hal/hdi_passthrough/include/audio_internal.h @@ -187,6 +187,7 @@ struct AudioHwAdapter { struct AudioPortAndCapability *portCapabilitys; struct HdfRemoteService *proxyRemoteHandle; // proxyRemoteHandle int32_t adapterMgrRenderFlag; + int32_t adapterMgrCaptureFlag; }; struct AudioFrameRenderMode { @@ -209,6 +210,15 @@ struct AudioFrameRenderMode { struct AudioMmapBufferDescriptor mmapBufDesc; }; +struct AudioFrameCaptureMode { + uint64_t frames; + struct AudioTimeStamp time; + struct AudioSampleAttributes attrs; + uint32_t byteRate; + uint32_t periodSize; + uint32_t periodCount; +}; + struct AudioGain { float gain; float gainMin; @@ -284,6 +294,16 @@ struct AudioHwRenderParam { struct AudioFrameRenderMode frameRenderMode; }; +struct AudioHwCaptureMode { + struct AudioCtlParam ctlParam; + struct HwInfo hwInfo; +}; + +struct AudioHwCaptureParam { + struct AudioHwCaptureMode captureMode; + struct AudioFrameCaptureMode frameCaptureMode; +}; + struct ErrorDump { int32_t errorCode; int32_t count; @@ -305,6 +325,13 @@ struct AudioHwRender { struct ErrorLog errorLog; }; +struct AudioHwCapture { + struct AudioCapture common; + struct AudioHwCaptureParam captureParam; + struct HdfRemoteService *proxyRemoteHandle; // proxyRemoteHandle + struct ErrorLog errorLog; +}; + struct ParamValMap { char key[EXTPARAM_LEN]; char value[EXTPARAM_LEN]; @@ -395,6 +422,22 @@ int32_t AudioRenderTurnStandbyMode(AudioHandle handle); int32_t AudioRenderAudioDevDump(AudioHandle handle, int32_t range, int32_t fd); int32_t AudioRenderRegCallback(struct AudioRender *render, RenderCallback callback, void* cookie); int32_t AudioRenderDrainBuffer(struct AudioRender *render, AudioDrainNotifyType *type); +int32_t InitHwCaptureParam(struct AudioHwCapture *hwCapture, const struct AudioDeviceDescriptor *desc, + const struct AudioSampleAttributes *attrs); +int32_t GetAudioCaptureFunc(struct AudioHwCapture *hwCapture, const char *adapterName); +int32_t AudioAdapterCreateCapture(struct AudioAdapter *adapter, const struct AudioDeviceDescriptor *desc, + const struct AudioSampleAttributes *attrs, struct AudioCapture **capture); +int32_t AudioAdapterDestroyCapture(struct AudioAdapter *adapter, struct AudioCapture *capture); +int32_t AudioCaptureStart(AudioHandle handle); +int32_t AudioCaptureStop(AudioHandle handle); +int32_t AudioCapturePause(AudioHandle handle); +int32_t AudioCaptureResume(AudioHandle handle); +int32_t AudioCaptureFlush(AudioHandle handle); +int32_t AudioCaptureSetMute(AudioHandle handle, bool mute); +int32_t AudioCaptureGetMute(AudioHandle handle, bool *mute); +int32_t AudioCaptureCaptureFrame(struct AudioCapture *capture, void *frame, uint64_t requestBytes, + uint64_t *replyBytes); +void AudioReleaseCaptureHandle(struct AudioHwCapture *hwCapture); #ifdef __cplusplus } diff --git a/bluetooth/audio/hal/hdi_passthrough/include/bluetooth_audio_device.h b/bluetooth/audio/hal/hdi_passthrough/include/bluetooth_audio_device.h index 4635ead909..5f3f822d1d 100644 --- a/bluetooth/audio/hal/hdi_passthrough/include/bluetooth_audio_device.h +++ b/bluetooth/audio/hal/hdi_passthrough/include/bluetooth_audio_device.h @@ -40,6 +40,8 @@ typedef size_t (*WriteFrameFunc)(const void* data, size_t size); typedef int32_t (*ReqMmapBufferFunc)(int32_t ashmemLength); typedef void (*ReadMmapPositionFunc)(int64_t &sec, int64_t &nSec, uint64_t &frames); typedef bool (*GetLatencyFunc)(uint32_t &latency); +typedef size_t (*ReadFrameFunc)(void *data, size_t size); +typedef bool (*StartCaptureFunc)(); } } } diff --git a/bluetooth/audio/hal/hdi_passthrough/src/audio_adapter.cpp b/bluetooth/audio/hal/hdi_passthrough/src/audio_adapter.cpp index b75e7c93ec..de5f79f37d 100644 --- a/bluetooth/audio/hal/hdi_passthrough/src/audio_adapter.cpp +++ b/bluetooth/audio/hal/hdi_passthrough/src/audio_adapter.cpp @@ -104,6 +104,18 @@ static void GetNormalRenderFuncs(struct AudioHwRender *hwRender) hwRender->common.DrainBuffer = AudioRenderDrainBuffer; } +static void GetCaptureFuncs(struct AudioHwCapture *hwCapture) +{ + hwCapture->common.control.Start = AudioCaptureStart; + hwCapture->common.control.Stop = AudioCaptureStop; + hwCapture->common.control.Pause = AudioCapturePause; + hwCapture->common.control.Resume = AudioCaptureResume; + hwCapture->common.control.Flush = AudioCaptureFlush; + hwCapture->common.volume.SetMute = AudioCaptureSetMute; + hwCapture->common.volume.GetMute = AudioCaptureGetMute; + hwCapture->common.CaptureFrame = AudioCaptureCaptureFrame; +} + int32_t GetAudioRenderFunc(struct AudioHwRender *hwRender, const char *adapterName) { if (hwRender == nullptr || adapterName == nullptr) { @@ -117,6 +129,15 @@ int32_t GetAudioRenderFunc(struct AudioHwRender *hwRender, const char *adapterNa return HDF_SUCCESS; } +int32_t GetAudioCaptureFunc(struct AudioHwCapture *hwCapture, const char *adapterName) +{ + if (hwCapture == nullptr || adapterName == nullptr) { + return HDF_FAILURE; + } + GetCaptureFuncs(hwCapture); + return HDF_SUCCESS; +} + int32_t CheckParaDesc(const struct AudioDeviceDescriptor *desc, const char *type) { if (desc == NULL || type == NULL) { @@ -232,6 +253,52 @@ int32_t InitHwRenderParam(struct AudioHwRender *hwRender, const struct AudioDevi return HDF_SUCCESS; } +int32_t InitHwCaptureParam(struct AudioHwCapture *hwCapture, const struct AudioDeviceDescriptor *desc, + const struct AudioSampleAttributes *attrs) +{ + if (hwCapture == nullptr || desc == nullptr || attrs == nullptr) { + HDF_LOGE("InitHwCaptureParam param Is NULL"); + return HDF_FAILURE; + } + int32_t ret = CheckParaDesc(desc, TYPE_CAPTURE); + if (ret != HDF_SUCCESS) { + HDF_LOGE("CheckParaDesc Fail"); + return ret; + } + ret = CheckParaAttr(attrs); + if (ret != HDF_SUCCESS) { + HDF_LOGE("CheckParaAttr Fail"); + return ret; + } + int32_t formatValue = -1; + ret = AttrFormatToBit(attrs, &formatValue); + if (ret != HDF_SUCCESS) { + HDF_LOGE("AttrFormatToBit Fail"); + return ret; + } + if (attrs->channelCount == 0) { + return HDF_FAILURE; + } + hwCapture->captureParam.captureMode.hwInfo.deviceDescript = *desc; + hwCapture->captureParam.frameCaptureMode.attrs = *attrs; + hwCapture->captureParam.captureMode.ctlParam.audioGain.gainMax = GAIN_MAX; // init gainMax + hwCapture->captureParam.captureMode.ctlParam.audioGain.gainMin = 0; + hwCapture->captureParam.frameCaptureMode.frames = 0; + hwCapture->captureParam.frameCaptureMode.time.tvNSec = 0; + hwCapture->captureParam.frameCaptureMode.time.tvSec = 0; + hwCapture->captureParam.frameCaptureMode.byteRate = DEFAULT_RENDER_SAMPLING_RATE; + hwCapture->captureParam.frameCaptureMode.periodSize = DEEP_BUFFER_RENDER_PERIOD_SIZE; + hwCapture->captureParam.frameCaptureMode.periodCount = DEEP_BUFFER_RENDER_PERIOD_COUNT; + hwCapture->captureParam.frameCaptureMode.attrs.period = attrs->period; + hwCapture->captureParam.frameCaptureMode.attrs.frameSize = attrs->frameSize; + hwCapture->captureParam.frameCaptureMode.attrs.startThreshold = attrs->startThreshold; + hwCapture->captureParam.frameCaptureMode.attrs.stopThreshold = attrs->stopThreshold; + hwCapture->captureParam.frameCaptureMode.attrs.silenceThreshold = attrs->silenceThreshold; + hwCapture->captureParam.frameCaptureMode.attrs.isBigEndian = attrs->isBigEndian; + hwCapture->captureParam.frameCaptureMode.attrs.isSignedData = attrs->isSignedData; + return HDF_SUCCESS; +} + AudioFormat g_formatIdZero = AUDIO_FORMAT_TYPE_PCM_16_BIT; int32_t InitForGetPortCapability(struct AudioPort portIndex, struct AudioPortCapability *capabilityIndex) { @@ -346,6 +413,11 @@ void AudioReleaseRenderHandle(struct AudioHwRender *hwRender) return; } +void AudioReleaseCaptureHandle(struct AudioHwCapture *hwCapture) +{ + return; +} + int32_t AudioAdapterCreateRenderPre(struct AudioHwRender *hwRender, const struct AudioDeviceDescriptor *desc, const struct AudioSampleAttributes *attrs, const struct AudioHwAdapter *hwAdapter) { @@ -383,6 +455,38 @@ int32_t AudioAdapterCreateRenderPre(struct AudioHwRender *hwRender, const struct return HDF_SUCCESS; } +int32_t AudioAdapterCreateCapturePre(struct AudioHwCapture *hwCapture, const struct AudioDeviceDescriptor *desc, + const struct AudioSampleAttributes *attrs, const struct AudioHwAdapter *hwAdapter) +{ + HDF_LOGD("%s", __func__); + if (hwAdapter == nullptr || hwCapture == nullptr || desc == nullptr || attrs == nullptr) { + HDF_LOGE("Pointer is null!"); + return HDF_FAILURE; + } + if (InitHwCaptureParam(hwCapture, desc, attrs) < 0) { + return HDF_FAILURE; + } + if (GetAudioCaptureFunc(hwCapture, hwAdapter->adapterDescriptor.adapterName) < 0) { + return HDF_FAILURE; + } + if (hwAdapter->adapterDescriptor.adapterName == nullptr) { + HDF_LOGE("pointer is null!"); + return HDF_FAILURE; + } + uint32_t adapterNameLen = strlen(hwAdapter->adapterDescriptor.adapterName); + if (adapterNameLen == 0) { + HDF_LOGE("adapterNameLen is null!"); + return HDF_FAILURE; + } + int32_t ret = strncpy_s(hwCapture->captureParam.captureMode.hwInfo.adapterName, NAME_LEN - 1, + hwAdapter->adapterDescriptor.adapterName, adapterNameLen); + if (ret != EOK) { + HDF_LOGE("copy fail"); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + int32_t AudioAdapterCreateRender(struct AudioAdapter *adapter, const struct AudioDeviceDescriptor *desc, const struct AudioSampleAttributes *attrs, struct AudioRender **render) { @@ -410,6 +514,33 @@ int32_t AudioAdapterCreateRender(struct AudioAdapter *adapter, const struct Audi return AUDIO_HAL_SUCCESS; } +int32_t AudioAdapterCreateCapture(struct AudioAdapter *adapter, const struct AudioDeviceDescriptor *desc, + const struct AudioSampleAttributes *attrs, struct AudioCapture **capture) +{ + struct AudioHwAdapter *hwAdapter = reinterpret_cast(adapter); + if (hwAdapter == nullptr || desc == nullptr || attrs == nullptr || capture == nullptr) { + return AUDIO_HAL_ERR_INVALID_PARAM; + } + if (hwAdapter->adapterMgrCaptureFlag > 0) { + HDF_LOGE("Create capture repeatedly!"); + return AUDIO_HAL_ERR_INTERNAL; + } + struct AudioHwCapture *hwCapture = reinterpret_cast(calloc(1, sizeof(*hwCapture))); + if (hwCapture == nullptr) { + HDF_LOGE("hwCapture is NULL!"); + return AUDIO_HAL_ERR_MALLOC_FAIL; + } + int32_t ret = AudioAdapterCreateCapturePre(hwCapture, desc, attrs, hwAdapter); + if (ret != 0) { + HDF_LOGE("AudioAdapterCreateCapturePre fail"); + AudioMemFree(reinterpret_cast(&hwCapture)); + return AUDIO_HAL_ERR_INTERNAL; + } + hwAdapter->adapterMgrCaptureFlag++; + *capture = &hwCapture->common; + return AUDIO_HAL_SUCCESS; +} + int32_t AudioAdapterDestroyRender(struct AudioAdapter *adapter, struct AudioRender *render) { HDF_LOGI("enter"); @@ -438,6 +569,26 @@ int32_t AudioAdapterDestroyRender(struct AudioAdapter *adapter, struct AudioRend return AUDIO_HAL_SUCCESS; } +int32_t AudioAdapterDestroyCapture(struct AudioAdapter *adapter, struct AudioCapture *capture) +{ + HDF_LOGI("enter"); + struct AudioHwAdapter *hwAdapter = reinterpret_cast(adapter); + if (hwAdapter == nullptr || capture == nullptr) { + return AUDIO_HAL_ERR_INVALID_PARAM; + } + if (hwAdapter->adapterMgrRenderFlag > 0) { + hwAdapter->adapterMgrRenderFlag--; + } + struct AudioHwCapture *hwCapture = reinterpret_cast(capture); + if (hwCapture == nullptr) { + return AUDIO_HAL_ERR_INTERNAL; + } + AudioReleaseCaptureHandle(hwCapture); + AudioMemFree(reinterpret_cast(&capture)); + HDF_LOGI("AudioAdapterDestroyCapture cleaned."); + return AUDIO_HAL_SUCCESS; +} + int32_t AudioAdapterGetPortCapability(struct AudioAdapter *adapter, const struct AudioPort *port, struct AudioPortCapability *capability) { diff --git a/bluetooth/audio/hal/hdi_passthrough/src/audio_bluetooth_manager.cpp b/bluetooth/audio/hal/hdi_passthrough/src/audio_bluetooth_manager.cpp index db2668411a..8169a9961e 100644 --- a/bluetooth/audio/hal/hdi_passthrough/src/audio_bluetooth_manager.cpp +++ b/bluetooth/audio/hal/hdi_passthrough/src/audio_bluetooth_manager.cpp @@ -56,6 +56,14 @@ StopPlayingFunc fastStopPlayingFunc; ReqMmapBufferFunc fastReqMmapBufferFunc; ReadMmapPositionFunc fastReadMmapPositionFunc; GetLatencyFunc fastGetLatencyFunc; + +SetUpFunc setUpCaptureFunc; +TearDownFunc tearDownCaptureFunc; +GetStateFunc getCaptureStateFunc; +StartCaptureFunc startCaptureFunc; +SuspendPlayingFunc suspendCaptureFunc; +StopPlayingFunc stopCaptureFunc; +ReadFrameFunc readFrameFunc; #endif sptr g_proxy_ = nullptr; @@ -230,6 +238,14 @@ static bool InitAudioDeviceSoHandle(const char *path) GET_SYM_ERRPR_RET( g_ptrAudioDeviceHandle, ReadMmapPositionFunc, fastReadMmapPositionFunc, "FastReadMmapPosition"); GET_SYM_ERRPR_RET(g_ptrAudioDeviceHandle, GetLatencyFunc, fastGetLatencyFunc, "FastGetLatency"); + + GET_SYM_ERRPR_RET(g_ptrAudioDeviceHandle, SetUpFunc, setUpCaptureFunc, "SetUpCapture"); + GET_SYM_ERRPR_RET(g_ptrAudioDeviceHandle, TearDownFunc, tearDownCaptureFunc, "TearDownCapture"); + GET_SYM_ERRPR_RET(g_ptrAudioDeviceHandle, GetStateFunc, getCaptureStateFunc, "GetCaptureState"); + GET_SYM_ERRPR_RET(g_ptrAudioDeviceHandle, StartCaptureFunc, startCaptureFunc, "StartCapture"); + GET_SYM_ERRPR_RET(g_ptrAudioDeviceHandle, SuspendPlayingFunc, suspendCaptureFunc, "SuspendCapture"); + GET_SYM_ERRPR_RET(g_ptrAudioDeviceHandle, StopPlayingFunc, stopCaptureFunc, "StopCapture"); + GET_SYM_ERRPR_RET(g_ptrAudioDeviceHandle, ReadFrameFunc, readFrameFunc, "ReadFrame"); } return true; } @@ -247,11 +263,28 @@ bool SetUp() return ret; } +bool SetUpCapture() +{ + bool ret = InitAudioDeviceSoHandle(g_bluetoothAudioDeviceSoPath); + if (ret) { + ret = setUpCaptureFunc(); + } + if (!ret) { + HDF_LOGE("%{public}s failed!", __func__); + } + return ret; +} + void TearDown() { tearDownFunc(); } +void TearDownCapture() +{ + tearDownCaptureFunc(); +} + bool FastSetUp() { bool ret = InitAudioDeviceSoHandle(g_bluetoothAudioDeviceSoPath); @@ -318,6 +351,48 @@ int FastGetLatency(uint32_t &latency) { return (fastGetLatencyFunc(latency) ? HDF_SUCCESS : HDF_FAILURE); } + +int StartCapture() +{ + BTAudioStreamState state = getCaptureStateFunc(); + if (state != BTAudioStreamState::STARTED) { + HDF_LOGE("%{public}s: state=%{public}hhu", __func__, state); + if (!startCaptureFunc()) { + HDF_LOGE("%{public}s: fail to startPlaying", __func__); + return HDF_FAILURE; + } + } + return HDF_SUCCESS; +} + +int SuspendCapture() +{ + int ret = 0; + BTAudioStreamState state = getCaptureStateFunc(); + if (state == BTAudioStreamState::STARTED) { + ret = suspendCaptureFunc() ? HDF_SUCCESS : HDF_FAILURE; + } else { + HDF_LOGE("%{public}s: state=%{public}hhu is bad state", __func__, state); + } + return ret; +} + +int StopCapture() +{ + BTAudioStreamState state = getCaptureStateFunc(); + HDF_LOGE("%{public}s: state=%{public}hhu", __func__, state); + if (state != BTAudioStreamState::INVALID) { + stopCaptureFunc(); + } + return HDF_SUCCESS; +} + +int ReadFrame(uint8_t *data, uint64_t size) +{ + HDF_LOGD("%{public}s", __func__); + return readFrameFunc(data, size); +} + #endif int WriteFrame(const uint8_t *data, uint32_t size, const HDI::Audio_Bluetooth::AudioSampleAttributes *attrs) diff --git a/bluetooth/audio/hal/hdi_passthrough/src/audio_capture.cpp b/bluetooth/audio/hal/hdi_passthrough/src/audio_capture.cpp new file mode 100644 index 0000000000..b2a211d047 --- /dev/null +++ b/bluetooth/audio/hal/hdi_passthrough/src/audio_capture.cpp @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include "audio_internal.h" +#include "audio_adapter_info_common.h" +#include "audio_bluetooth_manager.h" +#include "audio_capture.h" +namespace OHOS::HDI::Audio_Bluetooth { +int32_t AudioCaptureStart(AudioHandle handle) +{ + HDF_LOGI("%{public}s enter", __func__); +#ifdef A2DP_HDI_SERVICE + auto *hwCapture = reinterpret_cast(handle); + if (hwCapture == nullptr) { + return AUDIO_HAL_ERR_INVALID_PARAM; + } + return OHOS::Bluetooth::StartCapture(); +#endif + return AUDIO_HAL_ERR_NOT_SUPPORT; +} + +int32_t AudioCaptureStop(AudioHandle handle) +{ + HDF_LOGI("%{public}s enter", __func__); +#ifdef A2DP_HDI_SERVICE + auto *hwCapture = reinterpret_cast(handle); + if (hwCapture == nullptr) { + return AUDIO_HAL_ERR_INVALID_PARAM; + } + OHOS::Bluetooth::StopCapture(); + hwCapture->captureParam.captureMode.ctlParam.pause = false; + return AUDIO_HAL_SUCCESS; +#endif + return AUDIO_HAL_ERR_NOT_SUPPORT; +} + +int32_t AudioCapturePause(AudioHandle handle) +{ + HDF_LOGI("%{public}s enter", __func__); +#ifdef A2DP_HDI_SERVICE + auto *hwCapture = reinterpret_cast(handle); + if (hwCapture == nullptr) { + return AUDIO_HAL_ERR_INVALID_PARAM; + } + if (hwCapture->captureParam.captureMode.ctlParam.pause) { + HDF_LOGE("Audio is already pause"); + return AUDIO_HAL_ERR_NOT_SUPPORT; + } + OHOS::Bluetooth::StopCapture(); + hwCapture->captureParam.captureMode.ctlParam.pause = true; + return AUDIO_HAL_SUCCESS; +#endif + return AUDIO_HAL_ERR_NOT_SUPPORT; +} + +int32_t AudioCaptureResume(AudioHandle handle) +{ + HDF_LOGI("%{public}s enter", __func__); +#ifdef A2DP_HDI_SERVICE + auto *hwCapture = reinterpret_cast(handle); + if (hwCapture == nullptr) { + return AUDIO_HAL_ERR_INVALID_PARAM; + } + if (!hwCapture->captureParam.captureMode.ctlParam.pause) { + HDF_LOGE("Audio is already Resume"); + return AUDIO_HAL_ERR_NOT_SUPPORT; + } + OHOS::Bluetooth::StartCapture(); + hwCapture->captureParam.captureMode.ctlParam.pause = false; + return AUDIO_HAL_SUCCESS; +#endif + return AUDIO_HAL_ERR_NOT_SUPPORT; +} + +int32_t AudioCaptureFlush(AudioHandle handle) +{ + HDF_LOGI("%{public}s enter", __func__); + auto *hwCapture = reinterpret_cast(handle); + if (hwCapture == nullptr) { + return AUDIO_HAL_ERR_INVALID_PARAM; + } + return AUDIO_HAL_ERR_NOT_SUPPORT; +} + +int32_t AudioCaptureSetMute(AudioHandle handle, bool mute) +{ + (void)mute; + return AUDIO_HAL_SUCCESS; +} + +int32_t AudioCaptureGetMute(AudioHandle handle, bool *mute) +{ + (void)mute; + return AUDIO_HAL_SUCCESS; +} + +int32_t AudioCaptureCaptureFrame(struct AudioCapture *capture, void *frame, uint64_t requestBytes, uint64_t *replyBytes) +{ + HDF_LOGD("%{public}s enter", __func__); +#ifdef A2DP_HDI_SERVICE + auto *hwCapture = reinterpret_cast(capture); + if (hwCapture == nullptr || frame == nullptr || replyBytes == nullptr) { + HDF_LOGE("Capture Frame Paras is NULL"); + return AUDIO_HAL_ERR_INVALID_PARAM; + } + auto *data = reinterpret_cast(frame); + int32_t ret = OHOS::Bluetooth::ReadFrame(data, requestBytes); + *replyBytes = ret; + return ret; +#endif + return AUDIO_HAL_ERR_NOT_SUPPORT; +} +} \ No newline at end of file diff --git a/bluetooth/audio/hal/hdi_passthrough/src/audio_manager.cpp b/bluetooth/audio/hal/hdi_passthrough/src/audio_manager.cpp index 28de024ca7..9c75fcec0b 100644 --- a/bluetooth/audio/hal/hdi_passthrough/src/audio_manager.cpp +++ b/bluetooth/audio/hal/hdi_passthrough/src/audio_manager.cpp @@ -35,6 +35,28 @@ int32_t AudioManagerGetAllAdapters(struct AudioManager *manager, return AUDIO_HAL_SUCCESS; } +bool SetupBluetoothInterface(struct AudioHwAdapter *hwAdapter, const struct AudioAdapterDescriptor *desc) +{ +#ifndef A2DP_HDI_SERVICE + OHOS::Bluetooth::GetProxy(); + OHOS::Bluetooth::RegisterObserver(); + return true; +#else + bool ret = false; + if (strcmp(desc->adapterName, "bt_a2dp_fast") == 0) { + HDF_LOGI("%{public}s, fast set up", __func__); + ret = OHOS::Bluetooth::FastSetUp(); + } else if (strcmp(desc->adapterName, "bt_hdap") == 0) { + HDF_LOGI("%{public}s, hdap set up", __func__); + ret = OHOS::Bluetooth::SetUpCapture(); + } else { + HDF_LOGI("%{public}s, normal set up", __func__); + ret = OHOS::Bluetooth::SetUp(); + } + return ret; +#endif +} + int32_t AudioManagerLoadAdapter(struct AudioManager *manager, const struct AudioAdapterDescriptor *desc, struct AudioAdapter **adapter) { @@ -55,6 +77,8 @@ int32_t AudioManagerLoadAdapter(struct AudioManager *manager, const struct Audio hwAdapter->common.InitAllPorts = AudioAdapterInitAllPorts; hwAdapter->common.CreateRender = AudioAdapterCreateRender; hwAdapter->common.DestroyRender = AudioAdapterDestroyRender; + hwAdapter->common.CreateCapture = AudioAdapterCreateCapture; + hwAdapter->common.DestroyCapture = AudioAdapterDestroyCapture; hwAdapter->common.GetPortCapability = AudioAdapterGetPortCapability; hwAdapter->common.SetPassthroughMode = AudioAdapterSetPassthroughMode; hwAdapter->common.GetPassthroughMode = AudioAdapterGetPassthroughMode; @@ -63,25 +87,11 @@ int32_t AudioManagerLoadAdapter(struct AudioManager *manager, const struct Audio *adapter = &hwAdapter->common; hwAdapter->adapterDescriptor = *desc; hwAdapter->adapterMgrRenderFlag = 0; // The adapterMgrRenderFlag init is zero - + hwAdapter->adapterMgrCaptureFlag = 0; HDF_LOGI("%s call bluetooth RegisterObserver interface", __func__); -#ifndef A2DP_HDI_SERVICE - OHOS::Bluetooth::GetProxy(); - OHOS::Bluetooth::RegisterObserver(); -#else - bool ret = false; - if (strcmp(desc->adapterName, "bt_a2dp_fast") == 0) { - HDF_LOGI("%{public}s, fast set up", __func__); - ret = OHOS::Bluetooth::FastSetUp(); - } else { - HDF_LOGI("%{public}s, normal set up", __func__); - ret = OHOS::Bluetooth::SetUp(); - } - if (!ret) { + if (!SetupBluetoothInterface(hwAdapter, desc)) { return AUDIO_HAL_ERR_INTERNAL; } -#endif - return AUDIO_HAL_SUCCESS; } @@ -93,6 +103,7 @@ void AudioManagerUnloadAdapter(struct AudioManager *manager, struct AudioAdapter } #ifdef A2DP_HDI_SERVICE bool isFastAdapter = (strcmp(hwAdapter->adapterDescriptor.adapterName, "bt_a2dp_fast") == 0); + bool isHdapAdapter = (strcmp(hwAdapter->adapterDescriptor.adapterName, "bt_hdap") == 0); #endif if (hwAdapter->portCapabilitys != NULL) { int32_t portNum = hwAdapter->adapterDescriptor.portNum; @@ -113,6 +124,8 @@ void AudioManagerUnloadAdapter(struct AudioManager *manager, struct AudioAdapter #else if (isFastAdapter) { OHOS::Bluetooth::FastTearDown(); + } else if (isHdapAdapter) { + OHOS::Bluetooth::TearDownCapture(); } else { OHOS::Bluetooth::TearDown(); } diff --git a/bluetooth/audio/interfaces/include/audio_adapter.h b/bluetooth/audio/interfaces/include/audio_adapter.h index 3004694c8d..04d4ab776e 100644 --- a/bluetooth/audio/interfaces/include/audio_adapter.h +++ b/bluetooth/audio/interfaces/include/audio_adapter.h @@ -38,6 +38,7 @@ #include "audio_types.h" #include "audio_render.h" +#include "audio_capture.h" namespace OHOS::HDI::Audio_Bluetooth { /** * @brief Provides audio adapter capabilities, including initializing ports, creating rendering and capturing tasks, @@ -76,6 +77,21 @@ struct AudioAdapter { int32_t (*CreateRender)(struct AudioAdapter *adapter, const struct AudioDeviceDescriptor *desc, const struct AudioSampleAttributes *attrs, struct AudioRender **render); + /** + * @brief Creates an AudioCapture object. + * + * @param adapter Indicates the pointer to the audio adapter to operate. + * @param desc Indicates the pointer to the descriptor of the audio adapter to start. + * @param attrs Indicates the pointer to the audio sampling attributes to open. + * @param capture Indicates the double pointer to the AudioCapture object. + * @return Returns 0 if the AudioCapture object is created successfully; + * returns a negative value otherwise. + * @see GetPortCapability + * @see DestroyCapture + */ + int32_t (*CreateCapture)(struct AudioAdapter *adapter, const struct AudioDeviceDescriptor *desc, + const struct AudioSampleAttributes *attrs, struct AudioCapture **capture); + /** * @brief Destroys an AudioRender object. * @@ -88,6 +104,18 @@ struct AudioAdapter { */ int32_t (*DestroyRender)(struct AudioAdapter *adapter, struct AudioRender *render); + /** + * @brief Destroys an AudioCapture object. + * + * @attention Do not destroy the object during audio capturing. + * + * @param adapter Indicates the pointer to the audio adapter to operate. + * @param capture Indicates the pointer to the AudioCapture object to operate. + * @return Returns 0 if the AudioCapture object is destroyed; returns a negative value otherwise. + * @see CreateCapture + */ + int32_t (*DestroyCapture)(struct AudioAdapter *adapter, struct AudioCapture *capture); + /** * @brief Obtains the capability set of the port driver for the audio adapter. * diff --git a/bluetooth/audio/interfaces/include/audio_capture.h b/bluetooth/audio/interfaces/include/audio_capture.h new file mode 100644 index 0000000000..98c15bbd1f --- /dev/null +++ b/bluetooth/audio/interfaces/include/audio_capture.h @@ -0,0 +1,73 @@ +/* + * 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. + */ + +/** + * @addtogroup Audio + * @{ + * + * @brief Defines audio-related APIs, including custom data types and functions for loading drivers, + * accessing a driver adapter, and rendering and capturing audios. + * + * @since 1.0 + * @version 1.0 + */ + +/** + * @file audio_capture.h + * + * @brief Declares APIs for audio capturing. + * + * @since 1.0 + * @version 1.0 + */ + +#ifndef AUDIO_CAPTURE_H +#define AUDIO_CAPTURE_H + +#include "audio_control.h" +#include "audio_volume.h" +namespace OHOS::HDI::Audio_Bluetooth { +/** + * @brief Provides capabilities for audio capturing, including controlling the capturing, setting audio attributes, + * scenes, and volume, obtaining hardware latency, and capturing audio frames. + * + * @see AudioControl + * @see AudioAttribute + * @since 1.0 + * @version 1.0 + */ +struct AudioCapture { + /** + * @brief Defines the audio control. For details, see {@link AudioControl}. + */ + struct AudioControl control; + /** + * @brief Defines audio volume. For details, see {@link AudioVolume}. + */ + struct AudioVolume volume; + + /** + * @brief Reads a frame of intput data (uplink data) into the audio driver for capturing. + * + * @param capture Indicates the pointer to the AudioCapture object to operate. + * @param frame Indicates the pointer to the frame to read. + * @param requestBytes Indicates the size of the frame, in bytes. + * @param replyBytes Indicates the pointer to the actual length (in bytes) of the audio data to read. + * @return Returns 0 if the data is read successfully; returns a negative value otherwise. + */ + int32_t (*CaptureFrame)(struct AudioCapture *capture, void *frame, uint64_t requestBytes, uint64_t *replyBytes); +}; +} +#endif diff --git a/bluetooth/bundle.json b/bluetooth/bundle.json index 5f82958b65..dc046204ad 100644 --- a/bluetooth/bundle.json +++ b/bluetooth/bundle.json @@ -41,6 +41,7 @@ "header_files": [ "interfaces/include/audio_adapter.h", "interfaces/include/audio_attribute.h", + "interfaces/include/audio_capture.h", "interfaces/include/audio_control.h", "interfaces/include/audio_manager.h", "interfaces/include/audio_render.h", diff --git a/bluetooth/hci/hdi_service/hci_interface_impl.cpp b/bluetooth/hci/hdi_service/hci_interface_impl.cpp index dd314411e2..97694cad15 100644 --- a/bluetooth/hci/hdi_service/hci_interface_impl.cpp +++ b/bluetooth/hci/hdi_service/hci_interface_impl.cpp @@ -72,6 +72,9 @@ int32_t HciInterfaceImpl::Init(const sptr& callbackObj) .onEventReceive = [callbackObj]( const std::vector &packet) { callbackObj->OnReceivedHciPacket(BtType::HCI_EVENT, packet); }, + .onIsoReceive = + [callbackObj]( + const std::vector &packet) { callbackObj->OnReceivedHciPacket(BtType::ISO_DATA, packet); }, }; bool result = VendorInterface::GetInstance()->Initialize( diff --git a/bluetooth/hci/hdi_service/implement/h4_protocol.cpp b/bluetooth/hci/hdi_service/implement/h4_protocol.cpp index d7c14c27a7..d1c70f03bd 100644 --- a/bluetooth/hci/hdi_service/implement/h4_protocol.cpp +++ b/bluetooth/hci/hdi_service/implement/h4_protocol.cpp @@ -19,6 +19,9 @@ #include #include +#include +#include +#include #ifdef LOG_DOMAIN #undef LOG_DOMAIN @@ -29,13 +32,34 @@ namespace OHOS { namespace HDI { namespace Bluetooth { namespace Hci { +const int32_t RT_PRIORITY = 1; + H4Protocol::H4Protocol( - int fd, HciDataCallback onAclReceive, HciDataCallback onScoReceive, HciDataCallback onEventReceive) - : hciFd_(fd), onAclReceive_(onAclReceive), onScoReceive_(onScoReceive), onEventReceive_(onEventReceive) + int fd, HciDataCallback onAclReceive, HciDataCallback onScoReceive, HciDataCallback onEventReceive, + HciDataCallback onIsoReceive) : hciFd_(fd), onAclReceive_(onAclReceive), onScoReceive_(onScoReceive), + onEventReceive_(onEventReceive), onIsoReceive_(onIsoReceive) {} +void H4Protocol::SetRTSchedule() +{ + std::lock_guard lock(tidMutex_); + pid_t tid = gettid(); + auto it = tidMap_.find(tid); + if (it == tidMap_.end()) { + struct sched_param rtParams = {.sched_priority = RT_PRIORITY}; + int rc = sched_setscheduler(tid, SCHED_FIFO, &rtParams); + if (rc != 0) { + HDF_LOGE("set tid rt fail."); + tidMap_[tid] = false; + } else { + tidMap_[tid] = true; + } + } +} + ssize_t H4Protocol::SendPacket(HciPacketType packetType, const std::vector &packetData) { + SetRTSchedule(); uint8_t type = packetType; ssize_t writtenNumber = 0; @@ -117,6 +141,7 @@ H4Protocol::~H4Protocol() {} void H4Protocol::PacketCallback() { + SetRTSchedule(); switch (packetType_) { case HCI_PACKET_TYPE_ACL_DATA: if (onAclReceive_) { @@ -133,8 +158,13 @@ void H4Protocol::PacketCallback() onEventReceive_(hciPacket_); } break; + case HCI_PACKET_TYPE_ISO_DATA: + if (onIsoReceive_) { + onIsoReceive_(hciPacket_); + } + break; default: - HDF_LOGE("PacketCallback type[%d] error.", packetType_); + HDF_LOGE("PacketCallback type[%{public}d] error.", packetType_); break; } } diff --git a/bluetooth/hci/hdi_service/implement/h4_protocol.h b/bluetooth/hci/hdi_service/implement/h4_protocol.h index 35f3efbf99..b70e09305a 100644 --- a/bluetooth/hci/hdi_service/implement/h4_protocol.h +++ b/bluetooth/hci/hdi_service/implement/h4_protocol.h @@ -17,6 +17,8 @@ #define OHOS_HDI_BLUETOOTH_HCI_H4_PROTOCOL_H #include "hci_protocol.h" +#include +#include namespace OHOS { namespace HDI { @@ -24,7 +26,8 @@ namespace Bluetooth { namespace Hci { class H4Protocol : public HciProtocol { public: - H4Protocol(int fd, HciDataCallback onAclReceive, HciDataCallback onScoReceive, HciDataCallback onEventReceive); + H4Protocol(int fd, HciDataCallback onAclReceive, HciDataCallback onScoReceive, HciDataCallback onEventReceive, + HciDataCallback onIsoReceive); ssize_t SendPacket(HciPacketType packetType, const std::vector &packetData) override; void ReadData(int fd); @@ -32,12 +35,16 @@ public: private: void PacketCallback(); + void SetRTSchedule(); private: int hciFd_ = 0; HciDataCallback onAclReceive_; HciDataCallback onScoReceive_; HciDataCallback onEventReceive_; + HciDataCallback onIsoReceive_; + std::mutex tidMutex_; + std::map tidMap_; uint8_t packetType_ = 0; std::vector hciPacket_; diff --git a/bluetooth/hci/hdi_service/implement/hci_internal.h b/bluetooth/hci/hdi_service/implement/hci_internal.h index 201f84cd5a..85b4317c76 100644 --- a/bluetooth/hci/hdi_service/implement/hci_internal.h +++ b/bluetooth/hci/hdi_service/implement/hci_internal.h @@ -26,6 +26,7 @@ enum HciPacketType : uint8_t { HCI_PACKET_TYPE_ACL_DATA = 2, HCI_PACKET_TYPE_SCO_DATA = 3, HCI_PACKET_TYPE_EVENT = 4, + HCI_PACKET_TYPE_ISO_DATA = 5, HCI_PACKET_TYPE_MAX, }; diff --git a/bluetooth/hci/hdi_service/implement/hci_protocol.cpp b/bluetooth/hci/hdi_service/implement/hci_protocol.cpp index 652a932fef..449e9030be 100644 --- a/bluetooth/hci/hdi_service/implement/hci_protocol.cpp +++ b/bluetooth/hci/hdi_service/implement/hci_protocol.cpp @@ -37,6 +37,7 @@ const PacketHeader HciProtocol::header_[HCI_PACKET_TYPE_MAX] = { {.headerSize = 4, .dataLengthOffset = 2, .dataLengthSize = 2}, /* HCI_PACKET_TYPE_ACL_DATA */ {.headerSize = 3, .dataLengthOffset = 2, .dataLengthSize = 1}, /* HCI_PACKET_TYPE_SCO_DATA */ {.headerSize = 2, .dataLengthOffset = 1, .dataLengthSize = 1}, /* HCI_PACKET_TYPE_EVENT */ + {.headerSize = 4, .dataLengthOffset = 2, .dataLengthSize = 2}, /* HCI_PACKET_TYPE_ISO_DATA */ }; const PacketHeader &HciProtocol::GetPacketHeaderInfo(HciPacketType packetType) diff --git a/bluetooth/hci/hdi_service/implement/vendor_interface.cpp b/bluetooth/hci/hdi_service/implement/vendor_interface.cpp index d04d881db0..483a47151f 100644 --- a/bluetooth/hci/hdi_service/implement/vendor_interface.cpp +++ b/bluetooth/hci/hdi_service/implement/vendor_interface.cpp @@ -69,7 +69,8 @@ bool VendorInterface::WatchHciChannel(const ReceiveCallback &receiveCallback) auto h4 = std::make_shared(channel[0], receiveCallback.onAclReceive, receiveCallback.onScoReceive, - std::bind(&VendorInterface::OnEventReceived, this, std::placeholders::_1)); + std::bind(&VendorInterface::OnEventReceived, this, std::placeholders::_1), + receiveCallback.onIsoReceive); watcher_.AddFdToWatcher(channel[0], std::bind(&Hci::H4Protocol::ReadData, h4, std::placeholders::_1)); hci_ = h4; } else { diff --git a/bluetooth/hci/hdi_service/implement/vendor_interface.h b/bluetooth/hci/hdi_service/implement/vendor_interface.h index f02d458968..81c7dc56ce 100644 --- a/bluetooth/hci/hdi_service/implement/vendor_interface.h +++ b/bluetooth/hci/hdi_service/implement/vendor_interface.h @@ -39,6 +39,7 @@ public: ReceiveDataCallback onAclReceive; ReceiveDataCallback onScoReceive; ReceiveDataCallback onEventReceive; + ReceiveDataCallback onIsoReceive; }; bool Initialize(InitializeCompleteCallback initializeCompleteCallback, const ReceiveCallback &receiveCallback); diff --git a/camera/bundle.json b/camera/bundle.json index 7a21b60a90..b6bfc491ed 100644 --- a/camera/bundle.json +++ b/camera/bundle.json @@ -34,7 +34,8 @@ "libexif", "libjpeg-turbo", "ffmpeg", - "googletest" + "googletest", + "hicollie" ], "third_party": [] }, diff --git a/camera/hdi_service/v1_0/BUILD.gn b/camera/hdi_service/v1_0/BUILD.gn index b2d2dab213..d08c46f781 100644 --- a/camera/hdi_service/v1_0/BUILD.gn +++ b/camera/hdi_service/v1_0/BUILD.gn @@ -43,6 +43,7 @@ if (defined(ohos_lite)) { "$camera_path/../../interfaces/include", "$camera_path/../../interfaces/hdi_passthrough", "$camera_path/include", + "$camera_path/utils/hicollie", "$camera_path/utils/watchdog", "$camera_path/../interfaces", "./include", @@ -101,6 +102,7 @@ if (defined(ohos_lite)) { "$camera_path/../../interfaces/hdi_ipc/callback/device/include", "$camera_path/../../interfaces/hdi_ipc/callback/operator/include", "$camera_path/include", + "$camera_path/utils/hicollie", "$camera_path/utils/watchdog", "$camera_path/../interfaces", "./include", @@ -131,8 +133,8 @@ if (defined(ohos_lite)) { "hdf_core:libhdf_ipc_adapter", "hdf_core:libhdf_utils", "hdf_core:libhdi", + "hicollie:libhicollie", "hilog:libhilog", - "ipc:ipc_single", ] } else { external_deps = [ "hilog:libhilog" ] @@ -176,8 +178,8 @@ if (defined(ohos_lite)) { "hdf_core:libhdf_ipc_adapter", "hdf_core:libhdf_utils", "hdf_core:libhdi", + "hicollie:libhicollie", "hilog:libhilog", - "ipc:ipc_single", ] } else { external_deps = [ "hilog:libhilog" ] diff --git a/camera/hdi_service/v1_0/include/camera_device_service.h b/camera/hdi_service/v1_0/include/camera_device_service.h index 053faa0014..f3e6e99bda 100644 --- a/camera/hdi_service/v1_0/include/camera_device_service.h +++ b/camera/hdi_service/v1_0/include/camera_device_service.h @@ -23,6 +23,7 @@ #include "v1_0/icamera_device_callback.h" #include "v1_0/icamera_device_vdi.h" #include "v1_0/icamera_device_vdi_callback.h" +#include "camera_hal_hicollie.h" namespace OHOS::Camera { using namespace OHOS::HDI::Camera::V1_0; diff --git a/camera/hdi_service/v1_0/include/camera_host_service.h b/camera/hdi_service/v1_0/include/camera_host_service.h index 836a930f8a..622efe1640 100644 --- a/camera/hdi_service/v1_0/include/camera_host_service.h +++ b/camera/hdi_service/v1_0/include/camera_host_service.h @@ -22,6 +22,7 @@ #include "v1_0/icamera_device.h" #include "v1_0/icamera_host.h" #include "v1_0/icamera_host_vdi.h" +#include "camera_hal_hicollie.h" namespace OHOS::Camera { #ifdef CHIP_PROD_CAMERA_HOST_CONFIG diff --git a/camera/hdi_service/v1_0/include/stream_operator_service.h b/camera/hdi_service/v1_0/include/stream_operator_service.h index 124667c187..81950343c1 100644 --- a/camera/hdi_service/v1_0/include/stream_operator_service.h +++ b/camera/hdi_service/v1_0/include/stream_operator_service.h @@ -24,6 +24,7 @@ #include "v1_0/ioffline_stream_operator.h" #include "v1_0/types.h" #include "v1_0/istream_operator_vdi.h" +#include "camera_hal_hicollie.h" namespace OHOS::Camera { using namespace OHOS::HDI::Camera::V1_0; diff --git a/camera/hdi_service/v1_0/src/camera_device_service.cpp b/camera/hdi_service/v1_0/src/camera_device_service.cpp index ce843fe5ef..2489ead2e4 100644 --- a/camera/hdi_service/v1_0/src/camera_device_service.cpp +++ b/camera/hdi_service/v1_0/src/camera_device_service.cpp @@ -27,6 +27,7 @@ CameraDeviceService::CameraDeviceService(OHOS::sptr cameraDevi int32_t CameraDeviceService::GetStreamOperator(const sptr &callbackObj, sptr &streamOperator) { + CameraHalHicollie cameraHalHicollie("CameraHost:GetStreamOperator"); OHOS::sptr streamOperatorVdi = nullptr; CHECK_IF_PTR_NULL_RETURN_VALUE(cameraDeviceServiceVdi_, OHOS::HDI::Camera::V1_0::INVALID_ARGUMENT); OHOS::sptr vdiCallbackObj = new StreamOperatorServiceCallback(callbackObj); @@ -54,36 +55,42 @@ int32_t CameraDeviceService::GetStreamOperator(const sptr &settings) { + CameraHalHicollie cameraHalHicollie("CameraHost:UpdateSettings"); CHECK_IF_PTR_NULL_RETURN_VALUE(cameraDeviceServiceVdi_, OHOS::HDI::Camera::V1_0::INVALID_ARGUMENT); return cameraDeviceServiceVdi_->UpdateSettings(settings); } int32_t CameraDeviceService::SetResultMode(ResultCallbackMode mode) { + CameraHalHicollie cameraHalHicollie("CameraHost:SetResultMode"); CHECK_IF_PTR_NULL_RETURN_VALUE(cameraDeviceServiceVdi_, OHOS::HDI::Camera::V1_0::INVALID_ARGUMENT); return cameraDeviceServiceVdi_->SetResultMode(static_cast(mode)); } int32_t CameraDeviceService::GetEnabledResults(std::vector &results) { + CameraHalHicollie cameraHalHicollie("CameraHost:GetEnabledResults"); CHECK_IF_PTR_NULL_RETURN_VALUE(cameraDeviceServiceVdi_, OHOS::HDI::Camera::V1_0::INVALID_ARGUMENT); return cameraDeviceServiceVdi_->GetEnabledResults(results); } int32_t CameraDeviceService::EnableResult(const std::vector &results) { + CameraHalHicollie cameraHalHicollie("CameraHost:EnableResult"); CHECK_IF_PTR_NULL_RETURN_VALUE(cameraDeviceServiceVdi_, OHOS::HDI::Camera::V1_0::INVALID_ARGUMENT); return cameraDeviceServiceVdi_->EnableResult(results); } int32_t CameraDeviceService::DisableResult(const std::vector &results) { + CameraHalHicollie cameraHalHicollie("CameraHost:DisableResult"); CHECK_IF_PTR_NULL_RETURN_VALUE(cameraDeviceServiceVdi_, OHOS::HDI::Camera::V1_0::INVALID_ARGUMENT); return cameraDeviceServiceVdi_->DisableResult(results); } int32_t CameraDeviceService::Close() { + CameraHalHicollie cameraHalHicollie("CameraHost:Close"); CHECK_IF_PTR_NULL_RETURN_VALUE(cameraDeviceServiceVdi_, OHOS::HDI::Camera::V1_0::INVALID_ARGUMENT); return cameraDeviceServiceVdi_->Close(); } diff --git a/camera/hdi_service/v1_0/src/camera_host_service.cpp b/camera/hdi_service/v1_0/src/camera_host_service.cpp index 1c58d9987a..56dc4d80c8 100644 --- a/camera/hdi_service/v1_0/src/camera_host_service.cpp +++ b/camera/hdi_service/v1_0/src/camera_host_service.cpp @@ -38,6 +38,7 @@ extern "C" ICameraHost *CameraHostServiceGetInstance(void) int32_t CameraHostService::GetVdiLibList(std::vector &vdiLibList) { + CameraHalHicollie cameraHalHicollie("CameraHost:GetVdiLibList"); std::vector().swap(vdiLibList); ReleaseHcsTree(); const struct DeviceResourceIface *pDevResIns = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); @@ -77,6 +78,7 @@ int32_t CameraHostService::GetVdiLibList(std::vector &vdiLibList) void CameraHostService::HdfCloseVdiLoaderList(std::vector &cameraHostVdiLoaderList) { + CameraHalHicollie cameraHalHicollie("CameraHost:HdfCloseVdiLoaderList"); for (auto cameraHostVdiLoader : cameraHostVdiLoaderList) { if (cameraHostVdiLoader != nullptr) { HdfCloseVdi(cameraHostVdiLoader); @@ -168,6 +170,7 @@ int32_t CameraHostService::SetCallback(const OHOS::sptr &ca int32_t CameraHostService::GetCameraIds(std::vector &cameraIds) { + CameraHalHicollie cameraHalHicollie("CameraHost:GetCameraIds"); std::vector().swap(cameraIds); if (cameraIdInfoList_.size() == 0) { int32_t ret = UpdateCameraIdMapList(); diff --git a/camera/hdi_service/v1_0/src/stream_operator_service.cpp b/camera/hdi_service/v1_0/src/stream_operator_service.cpp index a72bb482b8..6a7acfc584 100644 --- a/camera/hdi_service/v1_0/src/stream_operator_service.cpp +++ b/camera/hdi_service/v1_0/src/stream_operator_service.cpp @@ -36,6 +36,7 @@ StreamOperatorService::~StreamOperatorService() int32_t StreamOperatorService::IsStreamsSupported(OperationMode mode, const std::vector &modeSetting, const std::vector &infos, StreamSupportType &type) { + CameraHalHicollie cameraHalHicollie("CameraHost:IsStreamsSupported"); CHECK_IF_PTR_NULL_RETURN_VALUE(streamOperatorVdi_, OHOS::HDI::Camera::V1_0::INVALID_ARGUMENT); std::vector vdiInfos; for (auto info : infos) { @@ -52,6 +53,7 @@ int32_t StreamOperatorService::IsStreamsSupported(OperationMode mode, const std: int32_t StreamOperatorService::CreateStreams(const std::vector &streamInfos) { + CameraHalHicollie cameraHalHicollie("CameraHost:CreateStreams"); CHECK_IF_PTR_NULL_RETURN_VALUE(streamOperatorVdi_, OHOS::HDI::Camera::V1_0::INVALID_ARGUMENT); std::vector vdiStreamInfos; for (auto info : streamInfos) { @@ -64,18 +66,21 @@ int32_t StreamOperatorService::CreateStreams(const std::vector &stre int32_t StreamOperatorService::ReleaseStreams(const std::vector &streamIds) { + CameraHalHicollie cameraHalHicollie("CameraHost:ReleaseStreams"); CHECK_IF_PTR_NULL_RETURN_VALUE(streamOperatorVdi_, OHOS::HDI::Camera::V1_0::INVALID_ARGUMENT); return streamOperatorVdi_->ReleaseStreams(streamIds); } int32_t StreamOperatorService::CommitStreams(OperationMode mode, const std::vector &modeSetting) { + CameraHalHicollie cameraHalHicollie("CameraHost:CommitStreams"); CHECK_IF_PTR_NULL_RETURN_VALUE(streamOperatorVdi_, OHOS::HDI::Camera::V1_0::INVALID_ARGUMENT); return streamOperatorVdi_->CommitStreams(static_cast(mode), modeSetting); } int32_t StreamOperatorService::GetStreamAttributes(std::vector &attributes) { + CameraHalHicollie cameraHalHicollie("CameraHost:GetStreamAttributes"); CHECK_IF_PTR_NULL_RETURN_VALUE(streamOperatorVdi_, OHOS::HDI::Camera::V1_0::INVALID_ARGUMENT); std::vector vdiAttributes; for (auto attribute : attributes) { @@ -96,18 +101,21 @@ int32_t StreamOperatorService::GetStreamAttributes(std::vector int32_t StreamOperatorService::AttachBufferQueue(int32_t streamId, const sptr &bufferProducer) { + CameraHalHicollie cameraHalHicollie("CameraHost:AttachBufferQueue"); CHECK_IF_PTR_NULL_RETURN_VALUE(streamOperatorVdi_, OHOS::HDI::Camera::V1_0::INVALID_ARGUMENT); return streamOperatorVdi_->AttachBufferQueue(streamId, bufferProducer); } int32_t StreamOperatorService::DetachBufferQueue(int32_t streamId) { + CameraHalHicollie cameraHalHicollie("CameraHost:DetachBufferQueue"); CHECK_IF_PTR_NULL_RETURN_VALUE(streamOperatorVdi_, OHOS::HDI::Camera::V1_0::INVALID_ARGUMENT); return streamOperatorVdi_->DetachBufferQueue(streamId); } int32_t StreamOperatorService::Capture(int32_t captureId, const CaptureInfo &info, bool isStreaming) { + CameraHalHicollie cameraHalHicollie("CameraHost:Capture"); CAMERAHALPERFSYSEVENT(TIME_FOR_CAPTURE); CHECK_IF_PTR_NULL_RETURN_VALUE(streamOperatorVdi_, OHOS::HDI::Camera::V1_0::INVALID_ARGUMENT); VdiCaptureInfo vdiInfo; @@ -117,6 +125,7 @@ int32_t StreamOperatorService::Capture(int32_t captureId, const CaptureInfo &inf int32_t StreamOperatorService::CancelCapture(int32_t captureId) { + CameraHalHicollie cameraHalHicollie("CameraHost:CancelCapture"); CHECK_IF_PTR_NULL_RETURN_VALUE(streamOperatorVdi_, OHOS::HDI::Camera::V1_0::INVALID_ARGUMENT); return streamOperatorVdi_->CancelCapture(captureId); } diff --git a/camera/test/benchmarktest/v1_0/BUILD.gn b/camera/test/benchmarktest/v1_0/BUILD.gn index 55cec8ffbf..8b6755a30f 100644 --- a/camera/test/benchmarktest/v1_0/BUILD.gn +++ b/camera/test/benchmarktest/v1_0/BUILD.gn @@ -18,7 +18,6 @@ import("//build/test.gni") import("../../../camera.gni") # NOSORT -import("$hdf_core_path/adapter/uhdf2/uhdf.gni") module_output_path = "drivers_peripheral_camera/camera" config("hdf_camera_benchmark_test_config") { @@ -42,19 +41,11 @@ ohos_benchmarktest("hdf_camera_benchmark_test") { include_dirs = [ "./include/", "$camera_common_path/v1_0/include/", - "//third_party/googletest/googletest/include", - "$camera_path/../../../display/interfaces/include", - "$camera_path/../../../display/hdi_service/gralloc/include", "$camera_path/../../interfaces/include", "$camera_path/include", ] - deps = [ - "//third_party/benchmark", - "//third_party/googletest:gmock_main", - "//third_party/googletest:gtest", - "//third_party/googletest:gtest_main", - ] + deps = [] if (is_standard_system) { external_deps = [ @@ -68,8 +59,12 @@ ohos_benchmarktest("hdf_camera_benchmark_test") { external_deps = [ "hilog:libhilog" ] } external_deps += [ + "benchmark:benchmark", "drivers_interface_camera:libbuffer_producer_sequenceable_1.0", "drivers_interface_camera:metadata", + "googletest:gmock_main", + "googletest:gtest", + "googletest:gtest_main", "graphic_surface:surface", "samgr:samgr_proxy", ] diff --git a/camera/test/benchmarktest/v1_3/src/camera_benchmark_securestream_test.cpp b/camera/test/benchmarktest/v1_3/src/camera_benchmark_securestream_test.cpp index 264912683c..0906d5c6e4 100755 --- a/camera/test/benchmarktest/v1_3/src/camera_benchmark_securestream_test.cpp +++ b/camera/test/benchmarktest/v1_3/src/camera_benchmark_securestream_test.cpp @@ -34,22 +34,6 @@ void CameraBenchmarkSecureStreamTest::TearDown(const ::benchmark::State &state) cameraTest->Close(); } -/** - * @tc.name: OpenSecureCamera - * @tc.desc: benchmark - * @tc.level: Level0 - * @tc.size: MediumTest - * @tc.type: Function - */ -BENCHMARK_F(CameraBenchmarkSecureStreamTest, OpenSecureCamera_benchmark_001)( - benchmark::State &st) -{ - for (auto _ : st) { - } -} -BENCHMARK_REGISTER_F(CameraBenchmarkSecureStreamTest, OpenSecureCamera_benchmark_001)->\ - Iterations(ITERATION_FREQUENCY)->Repetitions(REPETITION_FREQUENCY)->ReportAggregatesOnly(); - /** * @tc.name: GetSecureCameraSeq * @tc.desc: benchmark diff --git a/camera/test/common/v1_3/include/hdi_common_v1_3.h b/camera/test/common/v1_3/include/hdi_common_v1_3.h index 30020a9413..08bf88719f 100644 --- a/camera/test/common/v1_3/include/hdi_common_v1_3.h +++ b/camera/test/common/v1_3/include/hdi_common_v1_3.h @@ -48,8 +48,8 @@ public: OHOS::sptr streamOperator_V1_3 = nullptr; std::shared_ptr streamInfoMeta = nullptr; int streamIdMeta = 106; - int metaWidth = 1280; - int metaHeight = 960; + int metaWidth = 1920; + int metaHeight = 1080; int captureIdMeta = 2060; uint32_t itemCapacity = 100; uint32_t dataCapacity = 2000; diff --git a/camera/test/demo_3A/BUILD.gn b/camera/test/demo_3A/BUILD.gn index 735851ec38..5f6dd4aef9 100644 --- a/camera/test/demo_3A/BUILD.gn +++ b/camera/test/demo_3A/BUILD.gn @@ -87,7 +87,6 @@ if (defined(ohos_lite)) { } } else { import("//build/ohos.gni") - import("../../../../hdf_core/adapter/uhdf2/uhdf.gni") config("ohos_camera_demo_config") { visibility = [ ":*" ] diff --git a/camera/test/hdi/metadata_test/src/camera_example_vendor_tags_uttest.cpp b/camera/test/hdi/metadata_test/src/camera_example_vendor_tags_uttest.cpp index 83e8628d9a..3ca7b61ce6 100644 --- a/camera/test/hdi/metadata_test/src/camera_example_vendor_tags_uttest.cpp +++ b/camera/test/hdi/metadata_test/src/camera_example_vendor_tags_uttest.cpp @@ -45,5 +45,6 @@ HWTEST_F(CameraExampleVendorTagsTest, Camera_Example_Vendor_Tags_001, TestSize.L auto cameraVendorTagExample = std::make_shared(); std::vector tagVec {}; cameraVendorTagExample->GetAllVendorTags(tagVec); - cameraVendorTagExample->GetVendorTagCount(); + int ret = (int)cameraVendorTagExample->GetVendorTagCount(); + EXPECT_EQ(true, ret != -1); } \ No newline at end of file diff --git a/camera/test/hdi/metadata_test/src/camera_metadata_info_uttest.cpp b/camera/test/hdi/metadata_test/src/camera_metadata_info_uttest.cpp index 1cb548b18d..54ca9360dc 100644 --- a/camera/test/hdi/metadata_test/src/camera_metadata_info_uttest.cpp +++ b/camera/test/hdi/metadata_test/src/camera_metadata_info_uttest.cpp @@ -114,19 +114,6 @@ HWTEST_F(CameraMetadataInfoTest, Camera_Metedate_Info_004, TestSize.Level1) EXPECT_NE(header2, nullptr); } -/** - * @tc.name: Camera_Metedate_Info_005 - * @tc.desc: dst = nullptr - * @tc.size: MediumTest - * @tc.type: Function - */ -HWTEST_F(CameraMetadataInfoTest, Camera_Metedate_Info_005, TestSize.Level1) -{ - printf("CameraMetadataInfoTest Camera_Metedate_Info_005 start...\n"); - FreeCameraMetadataBuffer(nullptr); - ASSERT_EQ(1, 1); -} - /** * @tc.name: Camera_Metedate_Info_006 * @tc.desc: dst = nullptr, item = 131071 diff --git a/camera/test/hdi/sequenceable_test/src/camera_hdi_sequenceable_test.cpp b/camera/test/hdi/sequenceable_test/src/camera_hdi_sequenceable_test.cpp index 63e02f90df..3f12ac12e9 100644 --- a/camera/test/hdi/sequenceable_test/src/camera_hdi_sequenceable_test.cpp +++ b/camera/test/hdi/sequenceable_test/src/camera_hdi_sequenceable_test.cpp @@ -72,7 +72,7 @@ HWTEST_F(CameraHdiSequenceableTest, MapDataSequencebleTest_01, TestSize.Level1) EXPECT_EQ(ret, 0); ret = mapDataSequenceable->Get("doubleTemp", doubleTemp1); EXPECT_EQ(ret, 0); - EXPECT_EQ(doubleTemp0, doubleTemp0); + EXPECT_EQ(doubleTemp1, doubleTemp0); string stringTemp0 = "s1234.5678"; string stringTemp1 = "0"; @@ -80,7 +80,7 @@ HWTEST_F(CameraHdiSequenceableTest, MapDataSequencebleTest_01, TestSize.Level1) EXPECT_EQ(ret, 0); ret = mapDataSequenceable->Get("stringTemp", stringTemp1); EXPECT_EQ(ret, 0); - EXPECT_EQ(stringTemp0, stringTemp0); + EXPECT_EQ(stringTemp1, stringTemp0); // Marshalling and Unmarshalling Test Parcel parcel; diff --git a/camera/test/hdi/v1_0/BUILD.gn b/camera/test/hdi/v1_0/BUILD.gn index a1ff4cd7a1..29e9ab03a5 100644 --- a/camera/test/hdi/v1_0/BUILD.gn +++ b/camera/test/hdi/v1_0/BUILD.gn @@ -124,7 +124,11 @@ if (defined(ohos_lite)) { ] deps = [] - defines = [ "CAMERA_UT_TEST" ] + if (defined(defines)) { + defines += [ "CAMERA_UT_TEST" ] + } else { + defines = [ "CAMERA_UT_TEST" ] + } if (is_standard_system) { external_deps = [ diff --git a/camera/test/hdi/v1_3/src/camera_hdi_uttest_securestream_v1_3.cpp b/camera/test/hdi/v1_3/src/camera_hdi_uttest_securestream_v1_3.cpp index cc3dd675db..b29ece8875 100755 --- a/camera/test/hdi/v1_3/src/camera_hdi_uttest_securestream_v1_3.cpp +++ b/camera/test/hdi/v1_3/src/camera_hdi_uttest_securestream_v1_3.cpp @@ -24,6 +24,7 @@ void CameraHdiUtTestSecureStreamV1_3::SetUpTestCase(void) {} void CameraHdiUtTestSecureStreamV1_3::TearDownTestCase(void) {} void CameraHdiUtTestSecureStreamV1_3::SetUp(void) { + sleep(1); cameraTest = std::make_shared(); cameraTest->Init(); // assert inside cameraTest->OpenSecureCamera(DEVICE_1); // assert inside diff --git a/camera/test/hdi/v1_3/src/camera_hdi_uttest_v1_3.cpp b/camera/test/hdi/v1_3/src/camera_hdi_uttest_v1_3.cpp index 7819277740..60363e4d54 100644 --- a/camera/test/hdi/v1_3/src/camera_hdi_uttest_v1_3.cpp +++ b/camera/test/hdi/v1_3/src/camera_hdi_uttest_v1_3.cpp @@ -1931,8 +1931,6 @@ HWTEST_F(CameraHdiUtTestV1_3, Camera_Device_Hdi_V1_3_047, TestSize.Level1) // Preview streamInfo cameraTest->streamInfoV1_1 = std::make_shared(); cameraTest->DefaultInfosPreview(cameraTest->streamInfoV1_1); - cameraTest->streamInfoV1_1->v1_0.width_ = 1280; - cameraTest->streamInfoV1_1->v1_0.height_ = 960; cameraTest->streamInfosV1_1.push_back(*cameraTest->streamInfoV1_1); cameraTest->streamInfoVideo = std::make_shared(); cameraTest->DefaultInfosVideo(cameraTest->streamInfoVideo); diff --git a/camera/test/ut/usb_camera/usb_camera_test.cpp b/camera/test/ut/usb_camera/usb_camera_test.cpp index 4a29000caa..a24e7edbb4 100644 --- a/camera/test/ut/usb_camera/usb_camera_test.cpp +++ b/camera/test/ut/usb_camera/usb_camera_test.cpp @@ -692,7 +692,7 @@ TEST_F(UtestUSBCameraTest, camera_usb_0023) StreamInfo streamInfoCapture = {}; streamInfoCapture.streamId_ = cameraBase_->STREAM_ID_CAPTURE; streamInfoCapture.width_ = 1280; // 1280:picture width - streamInfoCapture.height_ = 960; // 960:picture height + streamInfoCapture.height_ = 720; // 720:picture height streamInfoCapture.format_ = PIXEL_FMT_RGBA_8888; streamInfoCapture.dataspace_ = 8; // 8:picture dataspace streamInfoCapture.intent_ = STILL_CAPTURE; @@ -847,7 +847,7 @@ TEST_F(UtestUSBCameraTest, camera_usb_0027) StreamInfo streamInfoVideo = {}; streamInfoVideo.streamId_ = cameraBase_->STREAM_ID_VIDEO; streamInfoVideo.width_ = 1280; // 1280:picture width - streamInfoVideo.height_ = 960; // 960:picture height + streamInfoVideo.height_ = 720; // 720:picture height streamInfoVideo.format_ = PIXEL_FMT_RGBA_8888; streamInfoVideo.dataspace_ = 8; // 8:picture dataspace streamInfoVideo.intent_ = VIDEO; @@ -1900,4 +1900,61 @@ TEST_F(UtestUSBCameraTest, camera_usb_0055) sleep(1); cameraBase_->rc = (CamRetCode)cameraBase_->streamOperator->ReleaseStreams({streamIdVideo}); EXPECT_EQ(true, cameraBase_->rc == HDI::Camera::V1_0::NO_ERROR); +} + +/** + * @tc.name: USB Camera + * @tc.desc: Commit 2 streams together, width = 1280, height = 960, expected success. + * @tc.level: Level0 + * @tc.size: MediumTest + * @tc.type: Function + */ +TEST_F(UtestUSBCameraTest, camera_usb_0056) +{ + cameraBase_->OpenUsbCamera(); + if (!g_usbCameraExit) { + GTEST_SKIP() << "No usb camera plugged in" << std::endl; + } + cameraBase_->AchieveStreamOperator(); + if (cameraBase_->streamCustomerPreview_ == nullptr) { + cameraBase_->streamCustomerPreview_ = std::make_shared(); + } + std::vector streamInfos; + StreamInfo streamInfo = {}; + streamInfo.streamId_ = cameraBase_->STREAM_ID_PREVIEW; + streamInfo.width_ = 1280; // 1280:picture width + streamInfo.height_ = 960; // 960:picture height + streamInfo.format_ = PIXEL_FMT_RGBA_8888; + streamInfo.dataspace_ = 8; // 8:picture dataspace + streamInfo.intent_ = PREVIEW; + streamInfo.tunneledMode_ = 5; // 5:tunnel mode + streamInfo.bufferQueue_ = new BufferProducerSequenceable(cameraBase_->streamCustomerPreview_->CreateProducer()); + ASSERT_NE(streamInfo.bufferQueue_, nullptr); + streamInfo.bufferQueue_->producer_->SetQueueSize(8); // 8:set bufferQueue size + streamInfos.push_back(streamInfo); + if (cameraBase_->streamCustomerVideo_ == nullptr) { + cameraBase_->streamCustomerVideo_ = std::make_shared(); + } + StreamInfo streamInfoVideo = {}; + streamInfoVideo.streamId_ = cameraBase_->STREAM_ID_VIDEO; + streamInfoVideo.width_ = 1280; // 1280:picture width + streamInfoVideo.height_ = 960; // 960:picture height + streamInfoVideo.format_ = PIXEL_FMT_RGBA_8888; + streamInfoVideo.dataspace_ = 8; // 8:picture dataspace + streamInfoVideo.intent_ = VIDEO; + streamInfoVideo.encodeType_ = ENCODE_TYPE_H264; + streamInfoVideo.tunneledMode_ = 5; // 5:tunnel mode + streamInfoVideo.bufferQueue_ = new BufferProducerSequenceable(cameraBase_->streamCustomerVideo_->CreateProducer()); + ASSERT_NE(streamInfoVideo.bufferQueue_, nullptr); + streamInfoVideo.bufferQueue_->producer_->SetQueueSize(8); // 8:set bufferQueue size + streamInfos.push_back(streamInfoVideo); + cameraBase_->rc = (CamRetCode)cameraBase_->streamOperator->CreateStreams(streamInfos); + ASSERT_EQ(true, cameraBase_->rc == HDI::Camera::V1_0::NO_ERROR); + cameraBase_->rc = (CamRetCode)cameraBase_->streamOperator->CommitStreams(NORMAL, cameraBase_->ability_); + ASSERT_EQ(true, cameraBase_->rc == HDI::Camera::V1_0::NO_ERROR); + cameraBase_->StartCapture(cameraBase_->STREAM_ID_PREVIEW, cameraBase_->CAPTURE_ID_PREVIEW, false, true); + cameraBase_->StartCapture(cameraBase_->STREAM_ID_VIDEO, cameraBase_->CAPTURE_ID_VIDEO, false, true); + cameraBase_->captureIds = {cameraBase_->CAPTURE_ID_PREVIEW, cameraBase_->CAPTURE_ID_VIDEO}; + cameraBase_->streamIds = {cameraBase_->STREAM_ID_PREVIEW, cameraBase_->STREAM_ID_VIDEO}; + cameraBase_->StopStream(cameraBase_->captureIds, cameraBase_->streamIds); } \ No newline at end of file diff --git a/camera/test/ut/v4l2/camera_hal_hisysevent_test.cpp b/camera/test/ut/v4l2/camera_hal_hisysevent_test.cpp new file mode 100644 index 0000000000..0a95278762 --- /dev/null +++ b/camera/test/ut/v4l2/camera_hal_hisysevent_test.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file expected 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 "camera_hal_hisysevent_test.h" + +using namespace OHOS; +using namespace std; +using namespace testing::ext; +using namespace OHOS::Camera; + +void CameraHalHisyseventTest::SetUpTestCase(void) {} +void CameraHalHisyseventTest::TearDownTestCase(void) {} +void CameraHalHisyseventTest::SetUp(void) +{ + cameraBase_ = std::make_shared(); + cameraBase_->Init(); +} + +void CameraHalHisyseventTest::TearDown(void) +{ + cameraBase_->Close(); +} + +/** + * @tc.name: updateSetting AE + * @tc.desc: preview, updateSetting OHOS_CONTROL_AE_EXPOSURE_COMPENSATION, success + * @tc.size: MediumTest + * @tc.type: Function + */ +HWTEST_F(CameraHalHisyseventTest, Camera_Hal_Hisysevent_001, TestSize.Level1) +{ + cameraBase_->AchieveStreamOperator(); + cameraBase_->DefaultInfosPreview(); + cameraBase_->streamInfoPre.format_ = 9990; + cameraBase_->DefaultInfosCapture(); + cameraBase_->streamInfoCapture.format_ = 9990; + cameraBase_->rc = (CamRetCode)cameraBase_->streamOperator->CreateStreams(cameraBase_->streamInfos); + EXPECT_EQ(false, cameraBase_->rc != HDI::Camera::V1_0::NO_ERROR); + cameraBase_->rc = (CamRetCode)cameraBase_->streamOperator->CommitStreams(NORMAL, cameraBase_->ability_); + EXPECT_EQ(false, cameraBase_->rc != HDI::Camera::V1_0::NO_ERROR); + cameraBase_->StartCapture(cameraBase_->STREAM_ID_PREVIEW, cameraBase_->CAPTURE_ID_PREVIEW, false, true); + sleep(1); + cameraBase_->captureIds = {cameraBase_->CAPTURE_ID_PREVIEW}; + cameraBase_->streamIds = {cameraBase_->STREAM_ID_PREVIEW}; + cameraBase_->StopStream(cameraBase_->captureIds, cameraBase_->streamIds); +} \ No newline at end of file diff --git a/camera/test/ut/v4l2/camera_hal_hisysevent_test.h b/camera/test/ut/v4l2/camera_hal_hisysevent_test.h new file mode 100644 index 0000000000..776bce674d --- /dev/null +++ b/camera/test/ut/v4l2/camera_hal_hisysevent_test.h @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file expected 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 CAMERA_HAL_HISYSEVENT_UTTEST_H +#define CAMERA_HAL_HISYSEVENT_UTTEST_H + +#include "test_camera_base.h" + +class CameraHalHisyseventTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(void); + void TearDown(void); + std::shared_ptr cameraBase_ = nullptr; +}; +#endif \ No newline at end of file diff --git a/camera/test/ut/v4l2/test_camera_base.cpp b/camera/test/ut/v4l2/test_camera_base.cpp index f6410a8dcc..788c7cf909 100644 --- a/camera/test/ut/v4l2/test_camera_base.cpp +++ b/camera/test/ut/v4l2/test_camera_base.cpp @@ -501,6 +501,46 @@ void TestCameraBase::OpenCamera() } } +void TestCameraBase::DefaultInfosPreview() +{ + if (streamCustomerPreview_ == nullptr) { + streamCustomerPreview_ = std::make_shared(); + } + streamInfoPre.streamId_ = STREAM_ID_PREVIEW; + streamInfoPre.width_ = PREVIEW_WIDTH; // 640:picture width + streamInfoPre.height_ = PREVIEW_HEIGHT; // 480:picture height + streamInfoPre.format_ = PIXEL_FMT_RGBA_8888; + streamInfoPre.dataspace_ = 8; // 8:picture dataspace + streamInfoPre.intent_ = PREVIEW; + streamInfoPre.tunneledMode_ = 5; // 5:tunnel mode + streamInfoPre.bufferQueue_ = new BufferProducerSequenceable(streamCustomerPreview_->CreateProducer()); + ASSERT_NE(streamInfoPre.bufferQueue_, nullptr); + streamInfoPre.bufferQueue_->producer_->SetQueueSize(8); // 8:set bufferQueue size + std::cout << "preview success1." << std::endl; + std::vector().swap(streamInfos); + streamInfos.push_back(streamInfoPre); +} + +void TestCameraBase::DefaultInfosCapture() +{ + if (streamCustomerCapture_ == nullptr) { + streamCustomerCapture_ = std::make_shared(); + } + streamInfoCapture.streamId_ = STREAM_ID_CAPTURE; + streamInfoCapture.width_ = CAPTURE_WIDTH; // 1280:picture width + streamInfoCapture.height_ = CAPTURE_HEIGHT; // 960:picture height + streamInfoCapture.format_ = PIXEL_FMT_RGBA_8888; + streamInfoCapture.dataspace_ = 8; // 8:picture dataspace + streamInfoCapture.intent_ = STILL_CAPTURE; + streamInfoCapture.encodeType_ = ENCODE_TYPE_JPEG; + streamInfoCapture.tunneledMode_ = 5; // 5:tunnel mode + streamInfoCapture.bufferQueue_ = new BufferProducerSequenceable(streamCustomerCapture_->CreateProducer()); + ASSERT_NE(streamInfoCapture.bufferQueue_, nullptr); + streamInfoCapture.bufferQueue_->producer_->SetQueueSize(8); // 8:set bufferQueue size + std::cout << "capture success1." << std::endl; + streamInfos.push_back(streamInfoCapture); +} + float TestCameraBase::CalTime(struct timeval start, struct timeval end) { float timeUse = 0; diff --git a/camera/test/ut/v4l2/test_camera_base.h b/camera/test/ut/v4l2/test_camera_base.h index 8fb29c7b4f..ef46bb2d4c 100644 --- a/camera/test/ut/v4l2/test_camera_base.h +++ b/camera/test/ut/v4l2/test_camera_base.h @@ -160,6 +160,8 @@ public: CamRetCode SelectOpenCamera(std::string cameraId); void Close(); void OpenCamera(); + void DefaultInfosPreview(); + void DefaultInfosCapture(); void AchieveStreamOperator(); void StartStream(std::vector intents); void StopStream(std::vector& captureIds, std::vector& streamIds); diff --git a/camera/vdi_base/common/pipeline_core/nodes/src/source_node/source_node.cpp b/camera/vdi_base/common/pipeline_core/nodes/src/source_node/source_node.cpp index a3abfef2ee..6e5604c864 100644 --- a/camera/vdi_base/common/pipeline_core/nodes/src/source_node/source_node.cpp +++ b/camera/vdi_base/common/pipeline_core/nodes/src/source_node/source_node.cpp @@ -371,9 +371,15 @@ void SourceNode::PortHandler::DistributeBuffers() } if (!dbtRun || respondBufferList.empty()) { + loopErrorCount_++; + if (loopErrorCount_ == LOOP_MAX_COUNT) { + CAMERA_LOGE("DistributeBuffers timeout 5s update dbtRun = false"); + dbtRun = false; + } return; } + loopErrorCount_ = 0; buffer = respondBufferList.front(); respondBufferList.pop_front(); } diff --git a/camera/vdi_base/common/pipeline_core/nodes/src/source_node/source_node.h b/camera/vdi_base/common/pipeline_core/nodes/src/source_node/source_node.h index a332298b9b..c973bbc366 100644 --- a/camera/vdi_base/common/pipeline_core/nodes/src/source_node/source_node.h +++ b/camera/vdi_base/common/pipeline_core/nodes/src/source_node/source_node.h @@ -20,6 +20,7 @@ #include namespace OHOS::Camera { +constexpr uint32_t LOOP_MAX_COUNT = 10; class SourceNode : virtual public NodeBase { public: SourceNode(const std::string& name, const std::string& type, const std::string &cameraId); @@ -77,6 +78,7 @@ protected: bool isResize_ = false; int32_t maxWide_ = 0; int32_t maxHigh_ = 0; + uint32_t loopErrorCount_ = 0; }; std::mutex hndl_ = {}; diff --git a/camera/vdi_base/common/utils/BUILD.gn b/camera/vdi_base/common/utils/BUILD.gn index cdd2d813aa..99109e5fda 100644 --- a/camera/vdi_base/common/utils/BUILD.gn +++ b/camera/vdi_base/common/utils/BUILD.gn @@ -56,11 +56,13 @@ if (defined(ohos_lite)) { sources = [ "event/camera_hal_hisysevent.cpp", "exif/exif_utils.cpp", + "hicollie/camera_hal_hicollie.cpp", "watchdog/watchdog.cpp", ] include_dirs = [ "$camera_path/include", "$camera_path/utils/event", + "$camera_path/utils/hicollie", ] libs = [] defines = [] @@ -69,6 +71,7 @@ if (defined(ohos_lite)) { "c_utils:utils", "drivers_interface_camera:metadata", "hdf_core:libhdf_utils", + "hicollie:libhicollie", "hilog:libhilog", "hisysevent:libhisysevent", "libexif:libexif", diff --git a/camera/vdi_base/common/utils/hicollie/camera_hal_hicollie.cpp b/camera/vdi_base/common/utils/hicollie/camera_hal_hicollie.cpp new file mode 100644 index 0000000000..85917c4893 --- /dev/null +++ b/camera/vdi_base/common/utils/hicollie/camera_hal_hicollie.cpp @@ -0,0 +1,38 @@ +/* + * 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. + */ + +#include "camera_hal_hicollie.h" + +namespace OHOS::Camera { + +CameraHalHicollie::CameraHalHicollie( + const std::string &name, uint32_t timeout, std::function func, void *arg, uint32_t flag) +{ + id_ = HiviewDFX::XCollie::GetInstance().SetTimer(name, timeout, func, arg, flag); + if (id_ < NUMBER_ZERO) { + CAMERA_LOGE("CameraHalHicollie SetTimer name:%{public}s id:%{public}d failed", name.c_str(), id_); + } + CAMERA_LOGD("CameraHalHicollie SetTimer name:%{public}s id:%{public}d", name.c_str(), id_); +} + +CameraHalHicollie::~CameraHalHicollie() +{ + if (id_ >= NUMBER_ZERO) { + HiviewDFX::XCollie::GetInstance().CancelTimer(id_); + CAMERA_LOGD("CameraHalHicollie CancelTimer id:%{public}d", id_); + } +} + +} \ No newline at end of file diff --git a/camera/vdi_base/common/utils/hicollie/camera_hal_hicollie.h b/camera/vdi_base/common/utils/hicollie/camera_hal_hicollie.h new file mode 100644 index 0000000000..449a870ba6 --- /dev/null +++ b/camera/vdi_base/common/utils/hicollie/camera_hal_hicollie.h @@ -0,0 +1,41 @@ +/* + * 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. + */ + +#ifndef CAMERA_HAL_HICOLLIE_H +#define CAMERA_HAL_HICOLLIE_H + +#include +#include "camera.h" +#include "xcollie/xcollie.h" +#include "xcollie/xcollie_define.h" + +namespace OHOS::Camera { + +constexpr uint32_t TIMEOUT_SECOND = 10; +constexpr uint32_t NUMBER_ZERO = 0; + +class CameraHalHicollie { +public: + explicit CameraHalHicollie(const std::string &name, uint32_t timeout = TIMEOUT_SECOND, + std::function func = nullptr, void *arg = nullptr, + uint32_t flag = (HiviewDFX::XCOLLIE_FLAG_LOG | HiviewDFX::XCOLLIE_FLAG_RECOVERY)); + ~CameraHalHicollie(); + +private: + int id_ = -1; +}; + +} // namespace OHOS::Camera +#endif \ No newline at end of file diff --git a/camera/vdi_base/v4l2/src/stream_operator/stream_operator_vdi_impl.cpp b/camera/vdi_base/v4l2/src/stream_operator/stream_operator_vdi_impl.cpp index 263ea5c349..f64f3483b1 100644 --- a/camera/vdi_base/v4l2/src/stream_operator/stream_operator_vdi_impl.cpp +++ b/camera/vdi_base/v4l2/src/stream_operator/stream_operator_vdi_impl.cpp @@ -496,8 +496,7 @@ int32_t StreamOperatorVdiImpl::Capture(int32_t captureId, const VdiCaptureInfo & request->SetFirstRequest(!isStreaming); for (auto id : info.streamIds_) { std::lock_guard l(streamLock_); - RetCode rc = streamMap_[id]->AddRequest(request); - if (rc != RC_OK) { + if (streamMap_[id] == nullptr || streamMap_[id]->AddRequest(request)) { return DEVICE_ERROR; } } diff --git a/codec/codec.gni b/codec/codec.gni index 1dd9fb1f77..ce53894c5c 100644 --- a/codec/codec.gni +++ b/codec/codec.gni @@ -17,4 +17,5 @@ declare_args() { drivers_peripheral_codec_feature_set_omx_role = false drivers_peripheral_codec_feature_support_dma_buffer = false drivers_peripheral_codec_feature_support_high_work_frequency = false + drivers_peripheral_codec_feature_support_hdi_v1 = false } diff --git a/codec/hal/idl_service/src/codec_component_config.cpp b/codec/hal/idl_service/src/codec_component_config.cpp index fbe66151e5..a75c5228f8 100644 --- a/codec/hal/idl_service/src/codec_component_config.cpp +++ b/codec/hal/idl_service/src/codec_component_config.cpp @@ -67,6 +67,7 @@ namespace { constexpr char CODEC_CONFIG_KEY_IS_SUPPORT_LTR[] = "isSupportLTR"; constexpr char CODEC_CONFIG_KEY_MAX_LTR_FRAME_NUM[] = "maxLTRFrameNum"; constexpr char CODEC_CONFIG_KEY_IS_SUPPORT_WATERMARK[] = "isSupportWaterMark"; + constexpr char CODEC_CONFIG_KEY_IS_SUPPORT_QP_MAP[] = "isSupportQPMap"; constexpr char CODEC_CONFIG_KEY_SAMPLE_FORMATS[] = "sampleFormats"; constexpr char CODEC_CONFIG_KEY_SAMPLE_RATE[] = "sampleRate"; @@ -372,6 +373,7 @@ int32_t CodecComponentConfig::GetVideoPortCapability(const struct DeviceResource } } cap.port.video.isSupportWaterMark = iface.GetBool(&childNode, CODEC_CONFIG_KEY_IS_SUPPORT_WATERMARK); + cap.port.video.isSupportQPMap = iface.GetBool(&childNode, CODEC_CONFIG_KEY_IS_SUPPORT_QP_MAP); return HDF_SUCCESS; } diff --git a/codec/hal/idl_service/src/codec_component_service.cpp b/codec/hal/idl_service/src/codec_component_service.cpp index 7622ba1d6f..4ee4b00308 100644 --- a/codec/hal/idl_service/src/codec_component_service.cpp +++ b/codec/hal/idl_service/src/codec_component_service.cpp @@ -163,6 +163,15 @@ int32_t CodecComponentService::GetParameter(uint32_t index, const std::vector(inParamStruct.data())); + if (inParamStruct.size() != currentSize) { + CODEC_LOGE("Invalid GetParams"); + return HDF_ERR_INVALID_PARAM; + } outParamStruct = inParamStruct; return node_->GetParameter(static_cast(index), outParamStruct.data()); } @@ -171,6 +180,15 @@ int32_t CodecComponentService::SetParameter(uint32_t index, const std::vector(paramStruct.data())); + if (paramStruct.size() != currentSize) { + CODEC_LOGE("Invalid SetParams"); + return HDF_ERR_INVALID_PARAM; + } return node_->SetParameter(static_cast(index), paramStruct.data()); } @@ -179,6 +197,15 @@ int32_t CodecComponentService::GetConfig(uint32_t index, const std::vector(inCfgStruct.data())); + if (inCfgStruct.size() != currentSize) { + CODEC_LOGE("Invalid GetConfig"); + return HDF_ERR_INVALID_PARAM; + } outCfgStruct = inCfgStruct; return node_->GetConfig(static_cast(index), outCfgStruct.data()); } @@ -187,6 +214,15 @@ int32_t CodecComponentService::SetConfig(uint32_t index, const std::vector(cfgStruct.data())); + if (cfgStruct.size() != currentSize) { + CODEC_LOGE("Invalid SetConfig"); + return HDF_ERR_INVALID_PARAM; + } return node_->SetConfig(static_cast(index), cfgStruct.data()); } diff --git a/codec/hal/idl_service/src/codec_dyna_buffer.cpp b/codec/hal/idl_service/src/codec_dyna_buffer.cpp index e063b064db..b1b39b5d9d 100644 --- a/codec/hal/idl_service/src/codec_dyna_buffer.cpp +++ b/codec/hal/idl_service/src/codec_dyna_buffer.cpp @@ -73,6 +73,7 @@ int32_t CodecDynaBuffer::EmptyOmxBuffer(struct OmxCodecBuffer &codecBuffer, OMX_ CODEC_LOGE("CheckInvalid return false"); return HDF_ERR_INVALID_PARAM; } + if (codecBuffer.bufferhandle != nullptr) { BufferHandle* handle = codecBuffer.bufferhandle->GetBufferHandle(); if (handle != nullptr) { @@ -81,6 +82,7 @@ int32_t CodecDynaBuffer::EmptyOmxBuffer(struct OmxCodecBuffer &codecBuffer, OMX_ codecBuffer.filledLen = sizeof(DynamicBuffer); } } + codecBuffer_.alongParam = std::move(codecBuffer.alongParam); int fence = codecBuffer.fenceFd; if (fence >= 0) { diff --git a/codec/hal/idl_service/src/component_node.cpp b/codec/hal/idl_service/src/component_node.cpp index 017d3786e2..846e0d1722 100644 --- a/codec/hal/idl_service/src/component_node.cpp +++ b/codec/hal/idl_service/src/component_node.cpp @@ -553,9 +553,10 @@ int32_t ComponentNode::EmptyThisBuffer(OmxCodecBuffer &buffer) } bufferHdrType->pAppPrivate = nullptr; OMXBufferAppPrivateData privateData{}; - if (buffer.bufferType == CODEC_BUFFER_TYPE_DYNAMIC_HANDLE && (!buffer.alongParam.empty())) { - privateData.sizeOfParam = static_cast(buffer.alongParam.size()); - privateData.param = static_cast(buffer.alongParam.data()); + OmxCodecBuffer& omxCodecBuffer = codecBuffer->GetCodecBuffer(); + if (buffer.bufferType == CODEC_BUFFER_TYPE_DYNAMIC_HANDLE && (!omxCodecBuffer.alongParam.empty())) { + privateData.sizeOfParam = static_cast(omxCodecBuffer.alongParam.size()); + privateData.param = static_cast(omxCodecBuffer.alongParam.data()); bufferHdrType->pAppPrivate = static_cast(&privateData); } diff --git a/codec/hal/src/codec_adapter.cpp b/codec/hal/src/codec_adapter.cpp index 0b7fefe23f..faa875b24c 100644 --- a/codec/hal/src/codec_adapter.cpp +++ b/codec/hal/src/codec_adapter.cpp @@ -117,7 +117,11 @@ int32_t OmxAdapterGetParameter(struct CodecComponentNode *codecNode, OMX_INDEXTY CODEC_LOGE("codecNode, node or param is null"); return HDF_ERR_INVALID_PARAM; } - + uint32_t currentSize = *(reinterpret_cast(param)); + if (currentSize < sizeof(uint32_t) || currentSize != paramLen) { + CODEC_LOGE("Invalid OmxGetParams"); + return HDF_ERR_INVALID_PARAM; + } return codecNode->node->GetParameter(paramIndex, param, paramLen); } @@ -128,6 +132,11 @@ int32_t OmxAdapterSetParameter(struct CodecComponentNode *codecNode, OMX_INDEXTY CODEC_LOGE("codecNode, node or param is null"); return HDF_ERR_INVALID_PARAM; } + uint32_t currentSize = *(reinterpret_cast(param)); + if (currentSize < sizeof(uint32_t) || currentSize != paramLen) { + CODEC_LOGE("Invalid OmxSetParams"); + return HDF_ERR_INVALID_PARAM; + } return codecNode->node->SetParameter(index, param, paramLen); } @@ -138,6 +147,11 @@ int32_t OmxAdapterGetConfig(struct CodecComponentNode *codecNode, OMX_INDEXTYPE CODEC_LOGE("codecNode, node or config is null"); return HDF_ERR_INVALID_PARAM; } + uint32_t currentSize = *(reinterpret_cast(config)); + if (currentSize < sizeof(uint32_t) || currentSize != configLen) { + CODEC_LOGE("Invalid OmxGetconfig"); + return HDF_ERR_INVALID_PARAM; + } return codecNode->node->GetConfig(index, config, configLen); } @@ -148,6 +162,11 @@ int32_t OmxAdapterSetConfig(struct CodecComponentNode *codecNode, OMX_INDEXTYPE CODEC_LOGE("codecNode, node or config is null"); return HDF_ERR_INVALID_PARAM; } + uint32_t currentSize = *(reinterpret_cast(config)); + if (currentSize < sizeof(uint32_t) || currentSize != configLen) { + CODEC_LOGE("Invalid OmxGetconfig"); + return HDF_ERR_INVALID_PARAM; + } return codecNode->node->SetConfig(index, config, configLen); } diff --git a/codec/hal/src/codec_component_manager_proxy.c b/codec/hal/src/codec_component_manager_proxy.c index a3029890b0..e64aa49a23 100644 --- a/codec/hal/src/codec_component_manager_proxy.c +++ b/codec/hal/src/codec_component_manager_proxy.c @@ -88,11 +88,16 @@ static int32_t GetComponentNum() static int32_t GetComponentCapabilityList(CodecCompCapability *capList, int32_t count) { struct HdfSBuf *data = HdfSbufTypedObtain(SBUF_IPC); - int32_t num = GetComponentNum(); - if (data == NULL || count <= 0 || count > num) { + if (data == NULL) { CODEC_LOGE("Failed to obtain"); return HDF_FAILURE; } + int32_t num = GetComponentNum(); + if (count <= 0 || count > num) { + CODEC_LOGE("Failed to get component"); + HdfSbufRecycle(data); + return HDF_FAILURE; + } struct HdfSBuf *reply = HdfSbufTypedObtain(SBUF_IPC); if (reply == NULL) { CODEC_LOGE("Failed to obtain reply"); diff --git a/codec/image/BUILD.gn b/codec/image/BUILD.gn index 29760f9abb..02026918b0 100644 --- a/codec/image/BUILD.gn +++ b/codec/image/BUILD.gn @@ -34,7 +34,12 @@ ohos_shared_library("libcodec_image_service_2.0") { external_deps = [ "c_utils:utils", "drivers_interface_codec:libimage_proxy_2.0", + "drivers_interface_display:libdisplay_buffer_stub_1.0", + "drivers_interface_display:libdisplay_buffer_stub_1.1", + "drivers_interface_display:libdisplay_composer_stub_1.0", "graphic_surface:buffer_handle", + "hdf_core:libhdf_host", + "hdf_core:libhdf_ipc_adapter", "hdf_core:libhdf_utils", "hdf_core:libhdi", "hilog:libhilog", diff --git a/codec/image/heif/include/codec_heif_encode_service.h b/codec/image/heif/include/codec_heif_encode_service.h index 89ebf0fb34..fd26ae5a86 100644 --- a/codec/image/heif/include/codec_heif_encode_service.h +++ b/codec/image/heif/include/codec_heif_encode_service.h @@ -16,6 +16,7 @@ #ifndef OHOS_HDI_CODEC_V2_0_CODECHEIFENCODESERVICE_H #define OHOS_HDI_CODEC_V2_0_CODECHEIFENCODESERVICE_H +#include #include "codec_heif_vdi.h" #include "v2_0/icodec_image.h" @@ -26,15 +27,18 @@ namespace Image { namespace V2_0 { class CodecHeifEncodeService { public: - CodecHeifEncodeService() = default; - ~CodecHeifEncodeService() = default; + CodecHeifEncodeService(); + virtual ~CodecHeifEncodeService(); int32_t DoHeifEncode(const std::vector& inputImgs, const std::vector& inputMetas, const std::vector& refs, const SharedBuffer& output, uint32_t& filledLen); private: bool LoadVendorLib(); + bool ReWrapNativeBufferInImageItem(const std::vector& inputImgs); private: + std::mutex mutex_; std::shared_ptr libHeif_ = nullptr; ICodecHeifHwi* heifHwi_ = nullptr; + bool isIPCMode_; }; } // V2_0 } // Image diff --git a/codec/image/heif/src/codec_heif_encode_service.cpp b/codec/image/heif/src/codec_heif_encode_service.cpp index cbab7cd116..80eccb7133 100644 --- a/codec/image/heif/src/codec_heif_encode_service.cpp +++ b/codec/image/heif/src/codec_heif_encode_service.cpp @@ -15,8 +15,13 @@ #include "codec_heif_encode_service.h" #include "codec_log_wrapper.h" #include "hdf_base.h" +#include "hdf_remote_service.h" +#include "v1_0/display_composer_type.h" +#include "v1_0/imapper.h" +#include "v1_1/imetadata.h" #include #include +#include namespace OHOS { namespace HDI { @@ -25,8 +30,92 @@ namespace Image { namespace V2_0 { using GetCodecHeifHwi = ICodecHeifHwi*(*)(); +std::mutex g_mapperMtx; +std::mutex g_metaMtx; +sptr g_mapperService; +sptr g_metaService; + +sptr GetMapperService() +{ + std::lock_guard lk(g_mapperMtx); + if (g_mapperService) { + return g_mapperService; + } + g_mapperService = OHOS::HDI::Display::Buffer::V1_0::IMapper::Get(true); + if (g_mapperService) { + CODEC_LOGI("get IMapper succ"); + return g_mapperService; + } + CODEC_LOGE("get IMapper failed"); + return nullptr; +} + +sptr GetMetaService() +{ + std::lock_guard lk(g_metaMtx); + if (g_metaService) { + return g_metaService; + } + g_metaService = OHOS::HDI::Display::Buffer::V1_1::IMetadata::Get(true); + if (g_metaService) { + CODEC_LOGI("get IMetadata succ"); + return g_metaService; + } + CODEC_LOGE("get IMetadata failed"); + return nullptr; +} + +void BufferDestructor(BufferHandle* handle) +{ + if (handle == nullptr) { + return; + } + sptr mapper = GetMapperService(); + if (mapper == nullptr) { + return; + } + sptr buffer = new NativeBuffer(); + buffer->SetBufferHandle(handle, true); + mapper->FreeMem(buffer); +} + +bool ReWrapNativeBuffer(sptr& buffer) +{ + if (buffer == nullptr) { + return true; + } + BufferHandle* handle = buffer->Move(); + if (handle == nullptr) { + return true; + } + buffer->SetBufferHandle(handle, true, BufferDestructor); + sptr meta = GetMetaService(); + if (meta == nullptr) { + return false; + } + int32_t ret = meta->RegisterBuffer(buffer); + if (ret != Display::Composer::V1_0::DISPLAY_SUCCESS && + ret != Display::Composer::V1_0::DISPLAY_NOT_SUPPORT) { + CODEC_LOGE("RegisterBuffer failed, ret = %{public}d", ret); + return false; + } + return true; +} + +CodecHeifEncodeService::CodecHeifEncodeService() +{ + isIPCMode_ = (HdfRemoteGetCallingPid() == getpid() ? false : true); +} + +CodecHeifEncodeService::~CodecHeifEncodeService() +{ + heifHwi_ = nullptr; + libHeif_ = nullptr; +} + bool CodecHeifEncodeService::LoadVendorLib() { + std::lock_guard lk(mutex_); if (heifHwi_) { return true; } @@ -51,6 +140,21 @@ bool CodecHeifEncodeService::LoadVendorLib() return true; } +bool CodecHeifEncodeService::ReWrapNativeBufferInImageItem(const std::vector& inputImgs) +{ + if (!isIPCMode_) { + return true; + } + + for (const auto &image : inputImgs) { + if (!ReWrapNativeBuffer(const_cast(image).pixelBuffer)) { + return false; + } + } + + return true; +} + int32_t CodecHeifEncodeService::DoHeifEncode(const std::vector& inputImgs, const std::vector& inputMetas, const std::vector& refs, @@ -59,6 +163,11 @@ int32_t CodecHeifEncodeService::DoHeifEncode(const std::vector& input if (!LoadVendorLib()) { return HDF_FAILURE; } + + if (!ReWrapNativeBufferInImageItem(inputImgs)) { + return HDF_FAILURE; + } + SharedBuffer outputToReturn = output; int32_t ret = (heifHwi_->DoHeifEncode)(inputImgs, inputMetas, refs, outputToReturn); filledLen = outputToReturn.filledLen; diff --git a/codec/interfaces/include/codec_omx_ext.h b/codec/interfaces/include/codec_omx_ext.h index 193eb2a3f4..e8cf804fa4 100644 --- a/codec/interfaces/include/codec_omx_ext.h +++ b/codec/interfaces/include/codec_omx_ext.h @@ -42,7 +42,7 @@ enum CodecAVCProfileExt { enum CodecVideoExType { CODEC_OMX_VIDEO_CodingVP9 = 10, /** VP9 Index in Codec HDI */ CODEC_OMX_VIDEO_CodingHEVC = 11, /** HEVC Index in Codec HDI */ - CODEC_OMX_VIDEO_CodingVVC = 12, /** VVC Index in Codec HDI */ + CODEC_OMX_VIDEO_CodingVVC = 0x7F000007, /** VVC Index in Codec HDI */ }; /** @@ -93,6 +93,68 @@ enum CodecHevcLevel { CODEC_HEVC_HIGH_TIER_MAX = 0x7FFFFFFF }; +/** + * @brief Enumerates the extended VVC profile. + */ +enum CodecVvcProfile { + CODEC_VVC_PROFILE_INVALID = 0x0, + CODEC_VVC_PROFILE_MAIN10 = 0x1, + CODEC_VVC_PROFILE_MAIN10_STILL = 0x2, + CODEC_VVC_PROFILE_MAIN10_444 = 0x3, + CODEC_VVC_PROFILE_MAIN10_444_STILL = 0x4, + CODEC_VVC_PROFILE_MULTI_MAIN10 = 0x5, + CODEC_VVC_PROFILE_MULTI_MAIN10_444 = 0x6, + // Operation range extensions profiles + CODEC_VVC_PROFILE_MAIN12 = 0x7, + CODEC_VVC_PROFILE_MAIN12_INTRA = 0x8, + CODEC_VVC_PROFILE_MAIN12_STILL = 0x9, + CODEC_VVC_PROFILE_MAIN12_444 = 0xA, + CODEC_VVC_PROFILE_MAIN12_444_INTRA = 0xB, + CODEC_VVC_PROFILE_MAIN12_444_STILL = 0xC, + CODEC_VVC_PROFILE_MAIN16_444 = 0xD, + CODEC_VVC_PROFILE_MAIN16_444_INTRA = 0xE, + CODEC_VVC_PROFILE_MAIN16_444_STILL = 0xF, + CODEC_VVC_PROFILE_MAX = 0x7FFFFFFF +}; + +/** + * @brief Enumerates the extended VVC level. + */ +enum CodecVvcLevel { + CODEC_VVC_LEVEL_INVALID = 0x0, + CODEC_VVC_MAIN_TIER_LEVEL1 = 0x1, + CODEC_VVC_HIGH_TIER_LEVEL1 = 0x2, + CODEC_VVC_MAIN_TIER_LEVEL2 = 0x4, + CODEC_VVC_HIGH_TIER_LEVEL2 = 0x8, + CODEC_VVC_MAIN_TIER_LEVEL21 = 0x10, + CODEC_VVC_HIGH_TIER_LEVEL21 = 0x20, + CODEC_VVC_MAIN_TIER_LEVEL3 = 0x40, + CODEC_VVC_HIGH_TIER_LEVEL3 = 0x80, + CODEC_VVC_MAIN_TIER_LEVEL31 = 0x100, + CODEC_VVC_HIGH_TIER_LEVEL31 = 0x200, + CODEC_VVC_MAIN_TIER_LEVEL4 = 0x400, + CODEC_VVC_HIGH_TIER_LEVEL4 = 0x800, + CODEC_VVC_MAIN_TIER_LEVEL41 = 0x1000, + CODEC_VVC_HIGH_TIER_LEVEL41 = 0x2000, + CODEC_VVC_MAIN_TIER_LEVEL5 = 0x4000, + CODEC_VVC_HIGH_TIER_LEVEL5 = 0x8000, + CODEC_VVC_MAIN_TIER_LEVEL51 = 0x10000, + CODEC_VVC_HIGH_TIER_LEVEL51 = 0x20000, + CODEC_VVC_MAIN_TIER_LEVEL52 = 0x40000, + CODEC_VVC_HIGH_TIER_LEVEL52 = 0x80000, + CODEC_VVC_MAIN_TIER_LEVEL6 = 0x100000, + CODEC_VVC_HIGH_TIER_LEVEL6 = 0x200000, + CODEC_VVC_MAIN_TIER_LEVEL61 = 0x400000, + CODEC_VVC_HIGH_TIER_LEVEL61 = 0x800000, + CODEC_VVC_MAIN_TIER_LEVEL62 = 0x1000000, + CODEC_VVC_HIGH_TIER_LEVEL62 = 0x2000000, + CODEC_VVC_MAIN_TIER_LEVEL63 = 0x4000000, + CODEC_VVC_HIGH_TIER_LEVEL63 = 0x8000000, + CODEC_VVC_MAIN_TIER_LEVEL155 = 0x10000000, + CODEC_VVC_HIGH_TIER_LEVEL155 = 0x20000000, + CODEC_VVC_HIGH_TIER_MAX = 0x7FFFFFFF +}; + /** * @brief Enumerates the extended codec color format. */ @@ -255,8 +317,6 @@ enum OmxIndexCodecExType { OMX_IndexParamEncOutMse, /** CodecEncOutLTRParam */ OMX_IndexParamEncOutLTR, - /** CodecTemperalLayerParam */ - OMX_IndexParamTemperalLayer, /** OMX_CONFIG_BOOLEANTYPE */ OMX_IndexParamEncParamsFeedback, /** OMX_S32 */ @@ -265,6 +325,8 @@ enum OmxIndexCodecExType { OMX_IndexParamQPStsart, /** OMX_BOOL */ OMX_IndexParamSkipFrame, + /** CodecTemperalLayerParam */ + OMX_IndexParamTemperalLayer, /** OMX_S32 */ OMX_IndexParamEncOutRealBitrate, /** CodecEncOutMadParam */ @@ -277,6 +339,10 @@ enum OmxIndexCodecExType { OMX_IndexParamSupportPackInput, /** OMX_CONFIG_BOOLEANTYPE */ OMX_IndexParamIsMvUpload, + /** OMX_CONFIG_BOOLEANTYPE */ + OMX_IndexParamEnableQPMap, + /** CodecBlockQpParam */ + OMX_IndexParamBlockQP, }; /** @@ -407,6 +473,15 @@ struct CodecEncOutMadParam { int32_t sumMadi; }; +struct CodecBlockQpParam { + uint32_t size; /** Size of the structure */ + union OMX_VERSIONTYPE version; /** Component version */ + void *blockQpAddr; /** qp map data address */ + uint32_t blockQpSize; /** qp map data size */ + uint32_t qpMapReserveInts; /**< Number of the qpMap reserved integers */ + uint8_t qpMapReserve[0]; /** reserve for qpmap data */ +}; + #ifdef __cplusplus #if __cplusplus } diff --git a/display/buffer/hdi_service/include/allocator_service.h b/display/buffer/hdi_service/include/allocator_service.h index c223618fbf..ed997b354d 100644 --- a/display/buffer/hdi_service/include/allocator_service.h +++ b/display/buffer/hdi_service/include/allocator_service.h @@ -35,7 +35,7 @@ public: private: int32_t LoadVdi(); void FreeMemVdi(BufferHandle* handle); - void WriteAllocPidToDma(int32_t fd); + void WriteAllocPidToDma(int32_t fd, pid_t remotePid); std::mutex mutex_; void *libHandle_; IDisplayBufferVdi *vdiImpl_; diff --git a/display/buffer/hdi_service/include/idisplay_buffer_vdi.h b/display/buffer/hdi_service/include/idisplay_buffer_vdi.h index ea6f85c580..9940e6ad37 100644 --- a/display/buffer/hdi_service/include/idisplay_buffer_vdi.h +++ b/display/buffer/hdi_service/include/idisplay_buffer_vdi.h @@ -119,17 +119,36 @@ public: */ virtual int32_t IsSupportedAlloc( const std::vector& infos, std::vector& supporteds) const = 0; - virtual int32_t RegisterBuffer(const BufferHandle& handle) = 0; - virtual int32_t SetMetadata(const BufferHandle& handle, uint32_t key, const std::vector& value) = 0; + virtual int32_t RegisterBuffer(const BufferHandle& handle) + { + return 0; + } - virtual int32_t GetMetadata(const BufferHandle& handle, uint32_t key, std::vector& value) = 0; + virtual int32_t SetMetadata(const BufferHandle& handle, uint32_t key, const std::vector& value) + { + return 0; + } - virtual int32_t ListMetadataKeys(const BufferHandle& handle, std::vector& keys) = 0; + virtual int32_t GetMetadata(const BufferHandle& handle, uint32_t key, std::vector& value) + { + return 0; + } - virtual int32_t EraseMetadataKey(const BufferHandle& handle, uint32_t key) = 0; + virtual int32_t ListMetadataKeys(const BufferHandle& handle, std::vector& keys) + { + return 0; + } - virtual int32_t GetImageLayout(const BufferHandle& handle, V1_2::ImageLayout& layout) const = 0; + virtual int32_t EraseMetadataKey(const BufferHandle& handle, uint32_t key) + { + return 0; + } + + virtual int32_t GetImageLayout(const BufferHandle& handle, V1_2::ImageLayout& layout) const + { + return 0; + } }; using CreateDisplayBufferVdiFunc = IDisplayBufferVdi* (*)(); diff --git a/display/buffer/hdi_service/src/allocator_service.cpp b/display/buffer/hdi_service/src/allocator_service.cpp index 3d60469244..18b3ebc74d 100644 --- a/display/buffer/hdi_service/src/allocator_service.cpp +++ b/display/buffer/hdi_service/src/allocator_service.cpp @@ -114,9 +114,8 @@ int32_t AllocatorService::LoadVdi() return HDF_SUCCESS; } -void AllocatorService::WriteAllocPidToDma(int32_t fd) +void AllocatorService::WriteAllocPidToDma(int32_t fd, pid_t remotePid) { - pid_t remotePid = HdfRemoteGetCallingPid(); char pidStr[BUFF_SIZE] = { 0 }; if (sprintf_s(pidStr, BUFF_SIZE, "%d", remotePid) >= 0) { ioctl(fd, DMA_BUF_SET_NAME_A, pidStr); @@ -134,12 +133,13 @@ void AllocatorService::FreeMemVdi(BufferHandle* handle) int32_t AllocatorService::AllocMem(const AllocInfo& info, sptr& handle) { - HdfTrace trace(__func__, "HDI:DISP:"); + pid_t remotePid = HdfRemoteGetCallingPid(); + HITRACE_METER_FMT(HITRACE_TAG_HDF, "%s: remotePid %d", __func__, remotePid); BufferHandle* buffer = nullptr; CHECK_NULLPOINTER_RETURN_VALUE(vdiImpl_, HDF_FAILURE); { - DisplayBufferDfx dfxIns("HDI:Display:AllocatorService:AllocMem"); + DisplayBufferDfx dfxIns("HDI:Display:AllocatorService:remotePid:" + std::to_string(remotePid)); dfxIns.SetTimer(); dfxIns.StartTimeStamp(); HdfTrace traceOne("AllocMem-VDI", "HDI:VDI:"); @@ -151,7 +151,7 @@ int32_t AllocatorService::AllocMem(const AllocInfo& info, sptr& ha } CHECK_NULLPOINTER_RETURN_VALUE(buffer, HDF_DEV_ERR_NO_MEMORY); - WriteAllocPidToDma(buffer->fd); + WriteAllocPidToDma(buffer->fd, remotePid); handle = new NativeBuffer(); if (handle == nullptr) { diff --git a/display/composer/hdi_service/include/display_composer_service.h b/display/composer/hdi_service/include/display_composer_service.h index c6b736f579..1916fc2a1d 100644 --- a/display/composer/hdi_service/include/display_composer_service.h +++ b/display/composer/hdi_service/include/display_composer_service.h @@ -16,13 +16,13 @@ #ifndef OHOS_HDI_DISPLAY_COMPOSER_SERVICE_H #define OHOS_HDI_DISPLAY_COMPOSER_SERVICE_H -#include "idisplay_composer_vdi_v1_1.h" #include "cache_manager/device_cache_manager.h" #include "v1_1/display_command/display_cmd_responser.h" #include "v1_1/idisplay_composer.h" #include "v1_2/display_command/display_cmd_responser.h" #include "v1_2/idisplay_composer.h" #include "v1_2/display_composer_type.h" +#include "common/include/display_vdi_adapter_interface.h" #include namespace OHOS { @@ -80,12 +80,19 @@ public: int32_t RegDisplayVBlankIdleCallback (const sptr& cb) override; int32_t ClearClientBuffer(uint32_t devId) override; int32_t ClearLayerBuffer(uint32_t devId, uint32_t layerId) override; + int32_t SetDisplayActiveRegion(uint32_t devId, const IRect& rect) override; + int32_t FastPresent(uint32_t devId, const PresentParam& param, + const std::vector>& inHandles) override; private: void HidumperInit(); int32_t LoadVdiSo(); - int32_t LoadVdiV1_0(); - int32_t LoadVdiV1_1(); + int32_t LoadVdiAdapter(); + void LoadVdiFuncPart1(); + void LoadVdiFuncPart2(); + void LoadVdiFuncPart3(); + void ExitService(); + int32_t CreateResponser(); static void OnHotPlug(uint32_t outputId, bool connected, void* data); static void OnVBlank(unsigned int sequence, uint64_t ns, void* data); static void OnMode(uint32_t modeId, uint64_t vBlankPeriod, void* data); @@ -95,6 +102,7 @@ private: private: /* Common */ void* libHandle_; + DisplayComposerVdiAdapter* vdiAdapter_; std::mutex mutex_; std::shared_ptr cacheMgr_; uint32_t currentBacklightLevel_; @@ -102,16 +110,7 @@ private: sptr vBlankCb_; sptr modeCb_; sptr seamlessChangeCb_; - - /* V1_0, which is the version of vdi */ - IDisplayComposerVdi* vdiImpl_; - DestroyComposerVdiFunc destroyVdiFunc_; std::unique_ptr cmdResponser_; - - /* V1_1, which is the version of vdi */ - IDisplayComposerVdiV1_1* vdiImplV1_1_; - DestroyComposerVdiFuncV1_1 destroyVdiFuncV1_1_; - std::unique_ptr cmdResponserV1_1_; sptr refreshCb_; sptr VBlankIdleCb_; }; diff --git a/display/composer/hdi_service/include/idisplay_composer_vdi_v1_1.h b/display/composer/hdi_service/include/idisplay_composer_vdi_v1_1.h index c2bfd86a6e..21d6f46d2b 100644 --- a/display/composer/hdi_service/include/idisplay_composer_vdi_v1_1.h +++ b/display/composer/hdi_service/include/idisplay_composer_vdi_v1_1.h @@ -47,6 +47,9 @@ class IDisplayComposerVdiV1_1 : public IDisplayComposerVdi { virtual int32_t SetHardwareCursorPosition(uint32_t devId, int32_t x, int32_t y) = 0; virtual int32_t EnableHardwareCursorStats(uint32_t devId, bool enable) = 0; virtual int32_t GetHardwareCursorStats(uint32_t devId, uint32_t& frameCount, uint32_t& vsyncCount) = 0; + virtual int32_t SetDisplayActiveRegion(uint32_t devId, const IRect& rect) = 0; + virtual int32_t FastPresent(uint32_t devId, const PresentParam& param, + const std::vector& inHandles) = 0; }; using CreateComposerVdiFuncV1_1 = IDisplayComposerVdiV1_1* (*)(); diff --git a/display/composer/hdi_service/src/display_composer_service.cpp b/display/composer/hdi_service/src/display_composer_service.cpp index 207ab8c1e9..5b67b8947d 100644 --- a/display/composer/hdi_service/src/display_composer_service.cpp +++ b/display/composer/hdi_service/src/display_composer_service.cpp @@ -44,36 +44,32 @@ extern "C" V1_2::IDisplayComposer* DisplayComposerImplGetInstance(void) DisplayComposerService::DisplayComposerService() : libHandle_(nullptr), + vdiAdapter_(new(std::nothrow) DisplayComposerVdiAdapter), cacheMgr_(nullptr), currentBacklightLevel_(0), hotPlugCb_(nullptr), vBlankCb_(nullptr), modeCb_(nullptr), seamlessChangeCb_(nullptr), - vdiImpl_(nullptr), - destroyVdiFunc_(nullptr), - cmdResponser_(nullptr), - vdiImplV1_1_(nullptr), - destroyVdiFuncV1_1_(nullptr), - cmdResponserV1_1_(nullptr), refreshCb_(nullptr), VBlankIdleCb_(nullptr) { int32_t ret = LoadVdiSo(); if (ret != HDF_SUCCESS) { - DISPLAY_LOGE("Load composer VDI failed, lib: %{public}s", DISPLAY_COMPOSER_VDI_LIBRARY); + DISPLAY_LOGE("LoadVdiSo failed"); return; } - ret = LoadVdiV1_1(); - if (ret != HDF_SUCCESS) { - ret = LoadVdiV1_0(); + if (LoadVdiAdapter() != HDF_SUCCESS) { + ExitService(); + DISPLAY_LOGE("Create DisplayComposerService failed"); + return; } - if (ret != HDF_SUCCESS) { - dlclose(libHandle_); - libHandle_ = nullptr; - DISPLAY_LOGE("Load composer VDI function failed"); + if (CreateResponser() != HDF_SUCCESS) { + ExitService(); + DISPLAY_LOGE("CreateResponser failed"); + return; } HidumperInit(); @@ -82,19 +78,14 @@ DisplayComposerService::DisplayComposerService() DisplayComposerService::~DisplayComposerService() { std::lock_guard lck(mutex_); - cmdResponser_ = nullptr; - cmdResponserV1_1_ = nullptr; + ExitService(); +} - if ((destroyVdiFunc_ != nullptr) && (vdiImpl_ != nullptr)) { - destroyVdiFunc_(vdiImpl_); - vdiImpl_ = nullptr; - destroyVdiFunc_ = nullptr; - } - - if ((destroyVdiFuncV1_1_ != nullptr) && (vdiImplV1_1_ != nullptr)) { - destroyVdiFuncV1_1_(vdiImplV1_1_); - vdiImplV1_1_ = nullptr; - destroyVdiFuncV1_1_ = nullptr; +void DisplayComposerService::ExitService() +{ + if (vdiAdapter_ != nullptr) { + delete vdiAdapter_; + vdiAdapter_ = nullptr; } if (libHandle_ != nullptr) { @@ -103,6 +94,162 @@ DisplayComposerService::~DisplayComposerService() } } +int32_t DisplayComposerService::LoadVdiAdapter() +{ + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); + + LoadVdiFuncPart1(); + LoadVdiFuncPart2(); + LoadVdiFuncPart3(); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->RegHotPlugCallback, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->GetDisplayCapability, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->GetDisplaySupportedModes, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->GetDisplayMode, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->SetDisplayMode, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->GetDisplayPowerStatus, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->SetDisplayPowerStatus, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->GetDisplayBacklight, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->SetDisplayBacklight, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->GetDisplayProperty, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->GetDisplayCompChange, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->SetDisplayClientCrop, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->SetDisplayClientBuffer, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->SetDisplayClientDamage, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->SetDisplayVsyncEnabled, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->RegDisplayVBlankCallback, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->GetDisplayReleaseFence, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->CreateVirtualDisplay, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->DestroyVirtualDisplay, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->SetVirtualDisplayBuffer, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->SetDisplayProperty, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->Commit, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->CreateLayer, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->DestroyLayer, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->PrepareDisplayLayers, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->SetLayerAlpha, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->SetLayerRegion, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->SetLayerCrop, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->SetLayerZorder, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->SetLayerPreMulti, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->SetLayerTransformMode, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->SetLayerDirtyRegion, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->SetLayerVisibleRegion, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->SetLayerBuffer, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->SetLayerCompositionType, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->SetLayerBlendType, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->SetLayerMaskInfo, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->SetLayerColor, HDF_FAILURE); + return HDF_SUCCESS; +} + +void DisplayComposerService::LoadVdiFuncPart1() +{ + vdiAdapter_->RegHotPlugCallback = + reinterpret_cast(dlsym(libHandle_, "RegHotPlugCallback")); + vdiAdapter_->GetDisplayCapability = + reinterpret_cast(dlsym(libHandle_, "GetDisplayCapability")); + vdiAdapter_->GetDisplaySupportedModes = + reinterpret_cast(dlsym(libHandle_, "GetDisplaySupportedModes")); + vdiAdapter_->GetDisplayMode = reinterpret_cast(dlsym(libHandle_, "GetDisplayMode")); + vdiAdapter_->SetDisplayMode = reinterpret_cast(dlsym(libHandle_, "SetDisplayMode")); + vdiAdapter_->GetDisplayPowerStatus = + reinterpret_cast(dlsym(libHandle_, "GetDisplayPowerStatus")); + vdiAdapter_->SetDisplayPowerStatus = + reinterpret_cast(dlsym(libHandle_, "SetDisplayPowerStatus")); + vdiAdapter_->GetDisplayBacklight = + reinterpret_cast(dlsym(libHandle_, "GetDisplayBacklight")); + vdiAdapter_->SetDisplayBacklight = + reinterpret_cast(dlsym(libHandle_, "SetDisplayBacklight")); + vdiAdapter_->GetDisplayProperty = + reinterpret_cast(dlsym(libHandle_, "GetDisplayProperty")); + vdiAdapter_->GetDisplayCompChange = + reinterpret_cast(dlsym(libHandle_, "GetDisplayCompChange")); + vdiAdapter_->SetDisplayClientCrop = + reinterpret_cast(dlsym(libHandle_, "SetDisplayClientCrop")); + vdiAdapter_->SetDisplayClientBuffer = + reinterpret_cast(dlsym(libHandle_, "SetDisplayClientBuffer")); + vdiAdapter_->SetDisplayClientDamage = + reinterpret_cast(dlsym(libHandle_, "SetDisplayClientDamage")); + vdiAdapter_->SetDisplayVsyncEnabled = + reinterpret_cast(dlsym(libHandle_, "SetDisplayVsyncEnabled")); + vdiAdapter_->RegDisplayVBlankCallback = + reinterpret_cast(dlsym(libHandle_, "RegDisplayVBlankCallback")); + vdiAdapter_->GetDisplayReleaseFence = + reinterpret_cast(dlsym(libHandle_, "GetDisplayReleaseFence")); + vdiAdapter_->CreateVirtualDisplay = + reinterpret_cast(dlsym(libHandle_, "CreateVirtualDisplay")); + vdiAdapter_->DestroyVirtualDisplay = + reinterpret_cast(dlsym(libHandle_, "DestroyVirtualDisplay")); + vdiAdapter_->SetVirtualDisplayBuffer = + reinterpret_cast(dlsym(libHandle_, "SetVirtualDisplayBuffer")); + vdiAdapter_->SetDisplayProperty = + reinterpret_cast(dlsym(libHandle_, "SetDisplayProperty")); + vdiAdapter_->Commit = reinterpret_cast(dlsym(libHandle_, "Commit")); + vdiAdapter_->CreateLayer = reinterpret_cast(dlsym(libHandle_, "CreateLayer")); + vdiAdapter_->DestroyLayer = reinterpret_cast(dlsym(libHandle_, "DestroyLayer")); + vdiAdapter_->PrepareDisplayLayers = + reinterpret_cast(dlsym(libHandle_, "PrepareDisplayLayers")); + vdiAdapter_->SetLayerAlpha = reinterpret_cast(dlsym(libHandle_, "SetLayerAlpha")); + vdiAdapter_->SetLayerRegion = reinterpret_cast(dlsym(libHandle_, "SetLayerRegion")); +} + +void DisplayComposerService::LoadVdiFuncPart2() +{ + vdiAdapter_->SetLayerCrop = reinterpret_cast(dlsym(libHandle_, "SetLayerCrop")); + vdiAdapter_->SetLayerZorder = reinterpret_cast(dlsym(libHandle_, "SetLayerZorder")); + vdiAdapter_->SetLayerPreMulti = reinterpret_cast(dlsym(libHandle_, "SetLayerPreMulti")); + vdiAdapter_->SetLayerTransformMode = + reinterpret_cast(dlsym(libHandle_, "SetLayerTransformMode")); + vdiAdapter_->SetLayerDirtyRegion = + reinterpret_cast(dlsym(libHandle_, "SetLayerDirtyRegion")); + vdiAdapter_->SetLayerVisibleRegion = + reinterpret_cast(dlsym(libHandle_, "SetLayerVisibleRegion")); + vdiAdapter_->SetLayerBuffer = reinterpret_cast(dlsym(libHandle_, "SetLayerBuffer")); + vdiAdapter_->SetLayerCompositionType = + reinterpret_cast(dlsym(libHandle_, "SetLayerCompositionType")); + vdiAdapter_->SetLayerBlendType = + reinterpret_cast(dlsym(libHandle_, "SetLayerBlendType")); + vdiAdapter_->SetLayerMaskInfo = reinterpret_cast(dlsym(libHandle_, "SetLayerMaskInfo")); + vdiAdapter_->SetLayerColor = reinterpret_cast(dlsym(libHandle_, "SetLayerColor")); + vdiAdapter_->RegSeamlessChangeCallback = + reinterpret_cast(dlsym(libHandle_, "RegSeamlessChangeCallback")); + vdiAdapter_->GetDisplaySupportedModesExt = + reinterpret_cast(dlsym(libHandle_, "GetDisplaySupportedModesExt")); + vdiAdapter_->SetDisplayModeAsync = + reinterpret_cast(dlsym(libHandle_, "SetDisplayModeAsync")); + vdiAdapter_->GetDisplayVBlankPeriod = + reinterpret_cast(dlsym(libHandle_, "GetDisplayVBlankPeriod")); + vdiAdapter_->SetLayerPerFrameParameter = + reinterpret_cast(dlsym(libHandle_, "SetLayerPerFrameParameter")); + vdiAdapter_->GetSupportedLayerPerFrameParameterKey = reinterpret_cast( + dlsym(libHandle_, "GetSupportedLayerPerFrameParameterKey")); + vdiAdapter_->SetDisplayOverlayResolution = + reinterpret_cast(dlsym(libHandle_, "SetDisplayOverlayResolution")); + vdiAdapter_->RegRefreshCallback = + reinterpret_cast(dlsym(libHandle_, "RegRefreshCallback")); + vdiAdapter_->GetDisplaySupportedColorGamuts = + reinterpret_cast(dlsym(libHandle_, "GetDisplaySupportedColorGamuts")); + vdiAdapter_->GetHDRCapabilityInfos = + reinterpret_cast(dlsym(libHandle_, "GetHDRCapabilityInfos")); + vdiAdapter_->RegDisplayVBlankIdleCallback = + reinterpret_cast(dlsym(libHandle_, "RegDisplayVBlankIdleCallback")); + vdiAdapter_->SetDisplayConstraint = + reinterpret_cast(dlsym(libHandle_, "SetDisplayConstraint")); + vdiAdapter_->SetHardwareCursorPosition = + reinterpret_cast(dlsym(libHandle_, "SetHardwareCursorPosition")); + vdiAdapter_->EnableHardwareCursorStats = + reinterpret_cast(dlsym(libHandle_, "EnableHardwareCursorStats")); + vdiAdapter_->GetHardwareCursorStats = + reinterpret_cast(dlsym(libHandle_, "GetHardwareCursorStats")); + vdiAdapter_->FastPresent = reinterpret_cast(dlsym(libHandle_, "FastPresent")); +} + +void DisplayComposerService::LoadVdiFuncPart3() +{ + vdiAdapter_->SetDisplayActiveRegion = + reinterpret_cast(dlsym(libHandle_, "SetDisplayActiveRegion")); +} + void DisplayComposerService::HidumperInit() { #ifdef DISPLAY_COMPOSER_SERVICE_HIDUMPER @@ -137,69 +284,18 @@ int32_t DisplayComposerService::LoadVdiSo() return HDF_SUCCESS; } -int32_t DisplayComposerService::LoadVdiV1_0() +int32_t DisplayComposerService::DisplayComposerService::CreateResponser() { - CreateComposerVdiFunc createVdiFunc = nullptr; - const char* errStr = nullptr; - - createVdiFunc = reinterpret_cast(dlsym(libHandle_, "CreateComposerVdi")); - if (createVdiFunc == nullptr) { - errStr = dlerror(); - if (errStr != nullptr) { - DISPLAY_LOGE("CreateVdiFuncV1_0 dlsym error: %{public}s", errStr); - } - return HDF_FAILURE; - } - - destroyVdiFunc_ = reinterpret_cast(dlsym(libHandle_, "DestroyComposerVdi")); - if (destroyVdiFunc_ == nullptr) { - errStr = dlerror(); - if (errStr != nullptr) { - DISPLAY_LOGE("DestroyVdiFuncV1_0 dlsym error: %{public}s", errStr); - } - return HDF_FAILURE; - } - - vdiImpl_ = createVdiFunc(); - CHECK_NULLPOINTER_RETURN_VALUE(vdiImpl_, HDF_FAILURE); cacheMgr_ = DeviceCacheManager::GetInstance(); CHECK_NULLPOINTER_RETURN_VALUE(cacheMgr_, HDF_FAILURE); - cmdResponser_ = V1_2::HdiDisplayCmdResponser::Create(vdiImpl_, cacheMgr_); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); + if (vdiAdapter_->RegDisplayVBlankIdleCallback != nullptr) { + DISPLAY_LOGI("%{public}s Enable Map", __func__); + cacheMgr_->SetNeedMap(true); + } + cmdResponser_ = V1_2::HdiDisplayCmdResponser::Create(vdiAdapter_, cacheMgr_); CHECK_NULLPOINTER_RETURN_VALUE(cmdResponser_, HDF_FAILURE); - return HDF_SUCCESS; -} - -int32_t DisplayComposerService::LoadVdiV1_1() -{ - CreateComposerVdiFuncV1_1 createVdiFunc = nullptr; - const char* errStr = nullptr; - - createVdiFunc = reinterpret_cast(dlsym(libHandle_, "CreateComposerVdiV1_1")); - if (createVdiFunc == nullptr) { - errStr = dlerror(); - if (errStr != nullptr) { - DISPLAY_LOGE("CreateVdiFuncV1_1 dlsym error: %{public}s", errStr); - } - return HDF_FAILURE; - } - - destroyVdiFuncV1_1_ = reinterpret_cast(dlsym(libHandle_, "DestroyComposerVdiV1_1")); - if (destroyVdiFuncV1_1_ == nullptr) { - errStr = dlerror(); - if (errStr != nullptr) { - DISPLAY_LOGE("DestroyVdiFuncV1_1 dlsym error: %{public}s", errStr); - } - return HDF_FAILURE; - } - - vdiImplV1_1_ = createVdiFunc(); - CHECK_NULLPOINTER_RETURN_VALUE(vdiImplV1_1_, HDF_FAILURE); - vdiImpl_ = dynamic_cast(vdiImplV1_1_); - CHECK_NULLPOINTER_RETURN_VALUE(vdiImpl_, HDF_FAILURE); - cacheMgr_ = DeviceCacheManager::GetInstance(); - CHECK_NULLPOINTER_RETURN_VALUE(cacheMgr_, HDF_FAILURE); - cmdResponserV1_1_ = V1_2::HdiDisplayCmdResponser_1_1::CreateV1_1(vdiImplV1_1_, cacheMgr_); - CHECK_NULLPOINTER_RETURN_VALUE(cmdResponserV1_1_, HDF_FAILURE); + DISPLAY_LOGI("%{public}s out", __func__); return HDF_SUCCESS; } @@ -256,16 +352,16 @@ int32_t DisplayComposerService::RegHotPlugCallback(const sptr& { DISPLAY_TRACE; - CHECK_NULLPOINTER_RETURN_VALUE(vdiImpl_, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); hotPlugCb_ = cb; - int32_t ret = vdiImpl_->RegHotPlugCallback(OnHotPlug, this); + int32_t ret = vdiAdapter_->RegHotPlugCallback(OnHotPlug, this); DISPLAY_CHK_RETURN(ret != HDF_SUCCESS, HDF_FAILURE, DISPLAY_LOGE(" fail")); return ret; } int32_t DisplayComposerService::SetClientBufferCacheCount(uint32_t devId, uint32_t count) { - CHECK_NULLPOINTER_RETURN_VALUE(vdiImpl_, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); CHECK_NULLPOINTER_RETURN_VALUE(cacheMgr_, HDF_FAILURE); std::lock_guard lock(cacheMgr_->GetCacheMgrMutex()); DeviceCache* devCache = cacheMgr_->DeviceCacheInstance(devId); @@ -279,8 +375,8 @@ int32_t DisplayComposerService::GetDisplayCapability(uint32_t devId, DisplayCapa { DISPLAY_TRACE; - CHECK_NULLPOINTER_RETURN_VALUE(vdiImpl_, HDF_FAILURE); - int32_t ret = vdiImpl_->GetDisplayCapability(devId, info); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); + int32_t ret = vdiAdapter_->GetDisplayCapability(devId, info); DISPLAY_CHK_RETURN(ret != HDF_SUCCESS, HDF_FAILURE, DISPLAY_LOGE(" fail")); return HDF_SUCCESS; } @@ -289,8 +385,8 @@ int32_t DisplayComposerService::GetDisplaySupportedModes(uint32_t devId, std::ve { DISPLAY_TRACE; - CHECK_NULLPOINTER_RETURN_VALUE(vdiImpl_, HDF_FAILURE); - int32_t ret = vdiImpl_->GetDisplaySupportedModes(devId, modes); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); + int32_t ret = vdiAdapter_->GetDisplaySupportedModes(devId, modes); DISPLAY_CHK_RETURN(ret != HDF_SUCCESS, HDF_FAILURE, DISPLAY_LOGE(" fail")); return ret; } @@ -299,8 +395,8 @@ int32_t DisplayComposerService::GetDisplayMode(uint32_t devId, uint32_t& modeId) { DISPLAY_TRACE; - CHECK_NULLPOINTER_RETURN_VALUE(vdiImpl_, HDF_FAILURE); - int32_t ret = vdiImpl_->GetDisplayMode(devId, modeId); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); + int32_t ret = vdiAdapter_->GetDisplayMode(devId, modeId); DISPLAY_CHK_RETURN(ret != HDF_SUCCESS, HDF_FAILURE, DISPLAY_LOGE(" fail")); return ret; } @@ -309,8 +405,8 @@ int32_t DisplayComposerService::SetDisplayMode(uint32_t devId, uint32_t modeId) { DISPLAY_TRACE; - CHECK_NULLPOINTER_RETURN_VALUE(vdiImpl_, HDF_FAILURE); - int32_t ret = vdiImpl_->SetDisplayMode(devId, modeId); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); + int32_t ret = vdiAdapter_->SetDisplayMode(devId, modeId); DISPLAY_CHK_RETURN(ret != HDF_SUCCESS, HDF_FAILURE, DISPLAY_LOGE(" fail")); return ret; } @@ -319,8 +415,8 @@ int32_t DisplayComposerService::GetDisplayPowerStatus(uint32_t devId, V1_0::Disp { DISPLAY_TRACE; - CHECK_NULLPOINTER_RETURN_VALUE(vdiImpl_, HDF_FAILURE); - int32_t ret = vdiImpl_->GetDisplayPowerStatus(devId, status); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); + int32_t ret = vdiAdapter_->GetDisplayPowerStatus(devId, status); DISPLAY_CHK_RETURN(ret != HDF_SUCCESS, HDF_FAILURE, DISPLAY_LOGE(" fail")); return ret; } @@ -329,8 +425,8 @@ int32_t DisplayComposerService::SetDisplayPowerStatus(uint32_t devId, V1_0::Disp { DISPLAY_TRACE; - CHECK_NULLPOINTER_RETURN_VALUE(vdiImpl_, HDF_FAILURE); - int32_t ret = vdiImpl_->SetDisplayPowerStatus(devId, status); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); + int32_t ret = vdiAdapter_->SetDisplayPowerStatus(devId, status); DISPLAY_LOGI("devid: %{public}u, status: %{public}u, vdi return %{public}d", devId, status, ret); DISPLAY_CHK_RETURN(ret != HDF_SUCCESS, HDF_FAILURE, DISPLAY_LOGE(" fail")); return ret; @@ -340,8 +436,8 @@ int32_t DisplayComposerService::GetDisplayBacklight(uint32_t devId, uint32_t& le { DISPLAY_TRACE; - CHECK_NULLPOINTER_RETURN_VALUE(vdiImpl_, HDF_FAILURE); - int32_t ret = vdiImpl_->GetDisplayBacklight(devId, level); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); + int32_t ret = vdiAdapter_->GetDisplayBacklight(devId, level); DISPLAY_CHK_RETURN(ret == DISPLAY_NOT_SUPPORT, HDF_SUCCESS, level = currentBacklightLevel_); return ret; } @@ -350,8 +446,8 @@ int32_t DisplayComposerService::SetDisplayBacklight(uint32_t devId, uint32_t lev { DISPLAY_TRACE; - CHECK_NULLPOINTER_RETURN_VALUE(vdiImpl_, HDF_FAILURE); - int32_t ret = vdiImpl_->SetDisplayBacklight(devId, level); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); + int32_t ret = vdiAdapter_->SetDisplayBacklight(devId, level); DISPLAY_LOGD("devid: %{public}u, level: %{public}u, vdi return %{public}d", devId, level, ret); DISPLAY_CHK_RETURN(ret != HDF_SUCCESS, HDF_FAILURE, DISPLAY_LOGE(" fail")); currentBacklightLevel_ = level; @@ -362,8 +458,8 @@ int32_t DisplayComposerService::GetDisplayProperty(uint32_t devId, uint32_t id, { DISPLAY_TRACE; - CHECK_NULLPOINTER_RETURN_VALUE(vdiImpl_, HDF_FAILURE); - int32_t ret = vdiImpl_->GetDisplayProperty(devId, id, value); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); + int32_t ret = vdiAdapter_->GetDisplayProperty(devId, id, value); DISPLAY_CHK_RETURN(ret == DISPLAY_NOT_SUPPORT, HDF_ERR_NOT_SUPPORT); DISPLAY_CHK_RETURN(ret != HDF_SUCCESS && ret != HDF_ERR_NOT_SUPPORT, HDF_FAILURE, DISPLAY_LOGE(" fail")); return ret; @@ -372,9 +468,9 @@ int32_t DisplayComposerService::GetDisplayProperty(uint32_t devId, uint32_t id, int32_t DisplayComposerService::SetHardwareCursorPosition(uint32_t devId, int32_t x, int32_t y) { DISPLAY_TRACE; - - CHECK_NULLPOINTER_RETURN_VALUE(vdiImplV1_1_, HDF_ERR_NOT_SUPPORT); - int32_t ret = vdiImplV1_1_->SetHardwareCursorPosition(devId, x, y); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->SetHardwareCursorPosition, HDF_ERR_NOT_SUPPORT); + int32_t ret = vdiAdapter_->SetHardwareCursorPosition(devId, x, y); DISPLAY_CHK_RETURN(ret != HDF_SUCCESS && ret != HDF_ERR_NOT_SUPPORT, HDF_FAILURE, DISPLAY_LOGE(" fail")); return ret; } @@ -382,9 +478,9 @@ int32_t DisplayComposerService::SetHardwareCursorPosition(uint32_t devId, int32_ int32_t DisplayComposerService::EnableHardwareCursorStats(uint32_t devId, bool enable) { DISPLAY_TRACE; - - CHECK_NULLPOINTER_RETURN_VALUE(vdiImplV1_1_, HDF_ERR_NOT_SUPPORT); - int32_t ret = vdiImplV1_1_->EnableHardwareCursorStats(devId, enable); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->EnableHardwareCursorStats, HDF_ERR_NOT_SUPPORT); + int32_t ret = vdiAdapter_->EnableHardwareCursorStats(devId, enable); DISPLAY_CHK_RETURN(ret != HDF_SUCCESS && ret != HDF_ERR_NOT_SUPPORT, HDF_FAILURE, DISPLAY_LOGE(" fail")); return ret; } @@ -392,9 +488,9 @@ int32_t DisplayComposerService::EnableHardwareCursorStats(uint32_t devId, bool e int32_t DisplayComposerService::GetHardwareCursorStats(uint32_t devId, uint32_t& frameCount, uint32_t& vsyncCount) { DISPLAY_TRACE; - - CHECK_NULLPOINTER_RETURN_VALUE(vdiImplV1_1_, HDF_ERR_NOT_SUPPORT); - int32_t ret = vdiImplV1_1_->GetHardwareCursorStats(devId, frameCount, vsyncCount); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->GetHardwareCursorStats, HDF_ERR_NOT_SUPPORT); + int32_t ret = vdiAdapter_->GetHardwareCursorStats(devId, frameCount, vsyncCount); DISPLAY_CHK_RETURN(ret != HDF_SUCCESS && ret != HDF_ERR_NOT_SUPPORT, HDF_FAILURE, DISPLAY_LOGE(" fail")); return ret; } @@ -403,8 +499,8 @@ int32_t DisplayComposerService::SetDisplayClientCrop(uint32_t devId, const IRect { DISPLAY_TRACE; - CHECK_NULLPOINTER_RETURN_VALUE(vdiImpl_, HDF_FAILURE); - int32_t ret = vdiImpl_->SetDisplayClientCrop(devId, rect); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); + int32_t ret = vdiAdapter_->SetDisplayClientCrop(devId, rect); DISPLAY_CHK_RETURN(ret != HDF_SUCCESS, HDF_FAILURE, DISPLAY_LOGE(" fail")); return ret; } @@ -413,8 +509,8 @@ int32_t DisplayComposerService::SetDisplayVsyncEnabled(uint32_t devId, bool enab { DISPLAY_TRACE; - CHECK_NULLPOINTER_RETURN_VALUE(vdiImpl_, HDF_FAILURE); - int32_t ret = vdiImpl_->SetDisplayVsyncEnabled(devId, enabled); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); + int32_t ret = vdiAdapter_->SetDisplayVsyncEnabled(devId, enabled); DISPLAY_CHK_RETURN(ret != HDF_SUCCESS, HDF_FAILURE, DISPLAY_LOGE(" fail")); return ret; } @@ -423,8 +519,8 @@ int32_t DisplayComposerService::RegDisplayVBlankCallback(uint32_t devId, const s { DISPLAY_TRACE; - CHECK_NULLPOINTER_RETURN_VALUE(vdiImpl_, HDF_FAILURE); - int32_t ret = vdiImpl_->RegDisplayVBlankCallback(devId, OnVBlank, cb.GetRefPtr()); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); + int32_t ret = vdiAdapter_->RegDisplayVBlankCallback(devId, OnVBlank, cb.GetRefPtr()); DISPLAY_CHK_RETURN(ret != HDF_SUCCESS, HDF_FAILURE, DISPLAY_LOGE(" fail")); vBlankCb_ = cb; return ret; @@ -436,8 +532,8 @@ int32_t DisplayComposerService::GetDisplayReleaseFence( DISPLAY_TRACE; std::vector outFences; - CHECK_NULLPOINTER_RETURN_VALUE(vdiImpl_, HDF_FAILURE); - int32_t ret = vdiImpl_->GetDisplayReleaseFence(devId, layers, outFences); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); + int32_t ret = vdiAdapter_->GetDisplayReleaseFence(devId, layers, outFences); for (uint i = 0; i < outFences.size(); i++) { int32_t dupFd = outFences[i]; sptr hdifd(new HdifdParcelable()); @@ -452,8 +548,8 @@ int32_t DisplayComposerService::CreateVirtualDisplay(uint32_t width, uint32_t he { DISPLAY_TRACE; - CHECK_NULLPOINTER_RETURN_VALUE(vdiImpl_, HDF_FAILURE); - int32_t ret = vdiImpl_->CreateVirtualDisplay(width, height, format, devId); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); + int32_t ret = vdiAdapter_->CreateVirtualDisplay(width, height, format, devId); DISPLAY_CHK_RETURN(ret != HDF_SUCCESS, HDF_FAILURE, DISPLAY_LOGE(" fail")); return ret; } @@ -462,8 +558,8 @@ int32_t DisplayComposerService::DestroyVirtualDisplay(uint32_t devId) { DISPLAY_TRACE; - CHECK_NULLPOINTER_RETURN_VALUE(vdiImpl_, HDF_FAILURE); - int32_t ret = vdiImpl_->DestroyVirtualDisplay(devId); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); + int32_t ret = vdiAdapter_->DestroyVirtualDisplay(devId); DISPLAY_CHK_RETURN(ret != HDF_SUCCESS, HDF_FAILURE, DISPLAY_LOGE(" fail")); return ret; } @@ -477,9 +573,9 @@ int32_t DisplayComposerService::SetVirtualDisplayBuffer( CHECK_NULLPOINTER_RETURN_VALUE(fence, HDF_FAILURE); BufferHandle* handle = buffer->GetBufferHandle(); int32_t inFence = fence->GetFd(); - CHECK_NULLPOINTER_RETURN_VALUE(vdiImpl_, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); CHECK_NULLPOINTER_RETURN_VALUE(handle, HDF_FAILURE); - int32_t ret = vdiImpl_->SetVirtualDisplayBuffer(devId, *handle, inFence); + int32_t ret = vdiAdapter_->SetVirtualDisplayBuffer(devId, *handle, inFence); DISPLAY_CHK_RETURN(ret != HDF_SUCCESS, HDF_FAILURE, DISPLAY_LOGE(" fail")); return ret; } @@ -488,8 +584,8 @@ int32_t DisplayComposerService::SetDisplayProperty(uint32_t devId, uint32_t id, { DISPLAY_TRACE; - CHECK_NULLPOINTER_RETURN_VALUE(vdiImpl_, HDF_FAILURE); - int32_t ret = vdiImpl_->SetDisplayProperty(devId, id, value); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); + int32_t ret = vdiAdapter_->SetDisplayProperty(devId, id, value); DISPLAY_CHK_RETURN(ret != HDF_SUCCESS, HDF_FAILURE, DISPLAY_LOGE(" fail")); return ret; } @@ -499,8 +595,8 @@ int32_t DisplayComposerService::CreateLayer(uint32_t devId, const LayerInfo& lay { DISPLAY_TRACE; - CHECK_NULLPOINTER_RETURN_VALUE(vdiImpl_, HDF_FAILURE); - int32_t ret = vdiImpl_->CreateLayer(devId, layerInfo, layerId); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); + int32_t ret = vdiAdapter_->CreateLayer(devId, layerInfo, layerId); DISPLAY_CHK_RETURN(ret != HDF_SUCCESS, HDF_FAILURE, DISPLAY_LOGE(" fail")); CHECK_NULLPOINTER_RETURN_VALUE(cacheMgr_, HDF_FAILURE); @@ -514,8 +610,8 @@ int32_t DisplayComposerService::CreateLayer(uint32_t devId, const LayerInfo& lay int32_t DisplayComposerService::DestroyLayer(uint32_t devId, uint32_t layerId) { DISPLAY_TRACE; - CHECK_NULLPOINTER_RETURN_VALUE(vdiImpl_, HDF_FAILURE); - int32_t ret = vdiImpl_->DestroyLayer(devId, layerId); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); + int32_t ret = vdiAdapter_->DestroyLayer(devId, layerId); DISPLAY_CHK_RETURN(ret != HDF_SUCCESS, HDF_FAILURE, DISPLAY_LOGE(" fail")); CHECK_NULLPOINTER_RETURN_VALUE(cacheMgr_, HDF_FAILURE); @@ -529,8 +625,9 @@ int32_t DisplayComposerService::DestroyLayer(uint32_t devId, uint32_t layerId) int32_t DisplayComposerService::RegSeamlessChangeCallback(const sptr& cb) { DISPLAY_TRACE; - DISPLAY_CHK_RETURN(vdiImplV1_1_ == nullptr, HDF_ERR_NOT_SUPPORT); - int32_t ret = vdiImplV1_1_->RegSeamlessChangeCallback(OnSeamlessChange, this); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->RegSeamlessChangeCallback, HDF_ERR_NOT_SUPPORT); + int32_t ret = vdiAdapter_->RegSeamlessChangeCallback(OnSeamlessChange, this); DISPLAY_CHK_RETURN(ret == DISPLAY_NOT_SUPPORT, HDF_ERR_NOT_SUPPORT); DISPLAY_CHK_RETURN(ret != HDF_SUCCESS && ret != HDF_ERR_NOT_SUPPORT, HDF_FAILURE, DISPLAY_LOGE(" fail")); if (ret == HDF_SUCCESS) { @@ -542,8 +639,9 @@ int32_t DisplayComposerService::RegSeamlessChangeCallback(const sptr& modes) { DISPLAY_TRACE; - DISPLAY_CHK_RETURN(vdiImplV1_1_ == nullptr, HDF_ERR_NOT_SUPPORT); - int32_t ret = vdiImplV1_1_->GetDisplaySupportedModesExt(devId, modes); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->GetDisplaySupportedModesExt, HDF_ERR_NOT_SUPPORT); + int32_t ret = vdiAdapter_->GetDisplaySupportedModesExt(devId, modes); DISPLAY_CHK_RETURN(ret == DISPLAY_NOT_SUPPORT, HDF_ERR_NOT_SUPPORT); DISPLAY_CHK_RETURN(ret != HDF_SUCCESS && ret != HDF_ERR_NOT_SUPPORT, HDF_FAILURE, DISPLAY_LOGE(" fail")); return ret; @@ -567,8 +665,9 @@ void DisplayComposerService::OnMode(uint32_t modeId, uint64_t vBlankPeriod, void int32_t DisplayComposerService::SetDisplayModeAsync(uint32_t devId, uint32_t modeId, const sptr& cb) { DISPLAY_TRACE; - DISPLAY_CHK_RETURN(vdiImplV1_1_ == nullptr, HDF_ERR_NOT_SUPPORT); - int32_t ret = vdiImplV1_1_->SetDisplayModeAsync(devId, modeId, OnMode, this); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->SetDisplayModeAsync, HDF_ERR_NOT_SUPPORT); + int32_t ret = vdiAdapter_->SetDisplayModeAsync(devId, modeId, OnMode, this); DISPLAY_CHK_RETURN(ret == DISPLAY_NOT_SUPPORT, HDF_ERR_NOT_SUPPORT); DISPLAY_CHK_RETURN(ret != HDF_SUCCESS && ret != HDF_ERR_NOT_SUPPORT, HDF_FAILURE, DISPLAY_LOGE(" fail")); if (ret == HDF_SUCCESS) { @@ -580,8 +679,9 @@ int32_t DisplayComposerService::SetDisplayModeAsync(uint32_t devId, uint32_t mod int32_t DisplayComposerService::GetDisplayVBlankPeriod(uint32_t devId, uint64_t& period) { DISPLAY_TRACE; - DISPLAY_CHK_RETURN(vdiImplV1_1_ == nullptr, HDF_ERR_NOT_SUPPORT); - int32_t ret = vdiImplV1_1_->GetDisplayVBlankPeriod(devId, period); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->GetDisplayVBlankPeriod, HDF_ERR_NOT_SUPPORT); + int32_t ret = vdiAdapter_->GetDisplayVBlankPeriod(devId, period); DISPLAY_CHK_RETURN(ret == DISPLAY_NOT_SUPPORT, HDF_ERR_NOT_SUPPORT); DISPLAY_CHK_RETURN(ret != HDF_SUCCESS && ret != HDF_ERR_NOT_SUPPORT, HDF_FAILURE, DISPLAY_LOGE(" fail")); return ret; @@ -607,12 +707,11 @@ int32_t DisplayComposerService::InitCmdRequest(const std::shared_ptrInitCmdRequest(request); - } else if (cmdResponser_ != nullptr) { + if (cmdResponser_ != nullptr) { ret = cmdResponser_->InitCmdRequest(request); } DISPLAY_CHK_RETURN(ret != HDF_SUCCESS, HDF_FAILURE, DISPLAY_LOGE(" fail")); + DISPLAY_LOGI("%{public}s out", __func__); return ret; } @@ -621,9 +720,7 @@ int32_t DisplayComposerService::CmdRequest( { int32_t ret = HDF_FAILURE; - if (cmdResponserV1_1_ != nullptr) { - ret = cmdResponserV1_1_->CmdRequest(inEleCnt, inFds, outEleCnt, outFds); - } else if (cmdResponser_ != nullptr) { + if (cmdResponser_ != nullptr) { ret = cmdResponser_->CmdRequest(inEleCnt, inFds, outEleCnt, outFds); } DISPLAY_CHK_RETURN(ret != HDF_SUCCESS, HDF_FAILURE, DISPLAY_LOGE(" fail")); @@ -634,9 +731,7 @@ int32_t DisplayComposerService::GetCmdReply(std::shared_ptrGetCmdReply(reply); - } else if (cmdResponser_ != nullptr) { + if (cmdResponser_ != nullptr) { ret = cmdResponser_->GetCmdReply(reply); } DISPLAY_CHK_RETURN(ret != HDF_SUCCESS, HDF_FAILURE, DISPLAY_LOGE(" fail")); @@ -647,8 +742,9 @@ int32_t DisplayComposerService::SetLayerPerFrameParameter(uint32_t devId, uint32 const std::vector& value) { DISPLAY_TRACE; - DISPLAY_CHK_RETURN(vdiImplV1_1_ == nullptr, HDF_ERR_NOT_SUPPORT); - int32_t ret = vdiImplV1_1_->SetLayerPerFrameParameter(devId, layerId, key, value); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->SetLayerPerFrameParameter, HDF_ERR_NOT_SUPPORT); + int32_t ret = vdiAdapter_->SetLayerPerFrameParameter(devId, layerId, key, value); DISPLAY_CHK_RETURN(ret == DISPLAY_NOT_SUPPORT, HDF_ERR_NOT_SUPPORT); DISPLAY_CHK_RETURN(ret != HDF_SUCCESS && ret != HDF_ERR_NOT_SUPPORT, HDF_FAILURE, DISPLAY_LOGE(" fail")); return ret; @@ -657,8 +753,9 @@ int32_t DisplayComposerService::SetLayerPerFrameParameter(uint32_t devId, uint32 int32_t DisplayComposerService::GetSupportedLayerPerFrameParameterKey(std::vector& keys) { DISPLAY_TRACE; - DISPLAY_CHK_RETURN(vdiImplV1_1_ == nullptr, HDF_ERR_NOT_SUPPORT); - int32_t ret = vdiImplV1_1_->GetSupportedLayerPerFrameParameterKey(keys); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->GetSupportedLayerPerFrameParameterKey, HDF_ERR_NOT_SUPPORT); + int32_t ret = vdiAdapter_->GetSupportedLayerPerFrameParameterKey(keys); DISPLAY_CHK_RETURN(ret == DISPLAY_NOT_SUPPORT, HDF_ERR_NOT_SUPPORT); DISPLAY_CHK_RETURN(ret != HDF_SUCCESS && ret != HDF_ERR_NOT_SUPPORT, HDF_FAILURE, DISPLAY_LOGE(" fail")); return ret; @@ -667,8 +764,9 @@ int32_t DisplayComposerService::GetSupportedLayerPerFrameParameterKey(std::vecto int32_t DisplayComposerService::SetDisplayOverlayResolution(uint32_t devId, uint32_t width, uint32_t height) { DISPLAY_TRACE; - DISPLAY_CHK_RETURN(vdiImplV1_1_ == nullptr, HDF_ERR_NOT_SUPPORT); - int32_t ret = vdiImplV1_1_->SetDisplayOverlayResolution(devId, width, height); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->SetDisplayOverlayResolution, HDF_ERR_NOT_SUPPORT); + int32_t ret = vdiAdapter_->SetDisplayOverlayResolution(devId, width, height); DISPLAY_CHK_RETURN(ret == DISPLAY_NOT_SUPPORT, HDF_ERR_NOT_SUPPORT); DISPLAY_CHK_RETURN(ret != HDF_SUCCESS && ret != HDF_ERR_NOT_SUPPORT, HDF_FAILURE, DISPLAY_LOGE(" fail")); return ret; @@ -692,8 +790,9 @@ void DisplayComposerService::OnRefresh(uint32_t devId, void *data) int32_t DisplayComposerService::RegRefreshCallback(const sptr& cb) { DISPLAY_TRACE; - DISPLAY_CHK_RETURN(vdiImplV1_1_ == nullptr, HDF_ERR_NOT_SUPPORT); - int32_t ret = vdiImplV1_1_->RegRefreshCallback(OnRefresh, this); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->RegRefreshCallback, HDF_ERR_NOT_SUPPORT); + int32_t ret = vdiAdapter_->RegRefreshCallback(OnRefresh, this); DISPLAY_CHK_RETURN(ret == DISPLAY_NOT_SUPPORT, HDF_ERR_NOT_SUPPORT); DISPLAY_CHK_RETURN(ret != HDF_SUCCESS && ret != HDF_ERR_NOT_SUPPORT, HDF_FAILURE, DISPLAY_LOGE(" fail")); if (ret == HDF_SUCCESS) { @@ -705,8 +804,9 @@ int32_t DisplayComposerService::RegRefreshCallback(const sptr& int32_t DisplayComposerService::GetDisplaySupportedColorGamuts(uint32_t devId, std::vector& gamuts) { DISPLAY_TRACE; - DISPLAY_CHK_RETURN(vdiImplV1_1_ == nullptr, HDF_ERR_NOT_SUPPORT); - int32_t ret = vdiImplV1_1_->GetDisplaySupportedColorGamuts(devId, gamuts); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->GetDisplaySupportedColorGamuts, HDF_ERR_NOT_SUPPORT); + int32_t ret = vdiAdapter_->GetDisplaySupportedColorGamuts(devId, gamuts); DISPLAY_CHK_RETURN(ret == DISPLAY_NOT_SUPPORT, HDF_ERR_NOT_SUPPORT); DISPLAY_CHK_RETURN(ret != HDF_SUCCESS && ret != HDF_ERR_NOT_SUPPORT, HDF_FAILURE, DISPLAY_LOGE(" fail")); return ret; @@ -715,8 +815,9 @@ int32_t DisplayComposerService::GetDisplaySupportedColorGamuts(uint32_t devId, s int32_t DisplayComposerService::GetHDRCapabilityInfos(uint32_t devId, HDRCapability& info) { DISPLAY_TRACE; - DISPLAY_CHK_RETURN(vdiImplV1_1_ == nullptr, HDF_ERR_NOT_SUPPORT); - int32_t ret = vdiImplV1_1_->GetHDRCapabilityInfos(devId, info); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->GetHDRCapabilityInfos, HDF_ERR_NOT_SUPPORT); + int32_t ret = vdiAdapter_->GetHDRCapabilityInfos(devId, info); DISPLAY_CHK_RETURN(ret == DISPLAY_NOT_SUPPORT, HDF_ERR_NOT_SUPPORT); DISPLAY_CHK_RETURN(ret != HDF_SUCCESS && ret != HDF_ERR_NOT_SUPPORT, HDF_FAILURE, DISPLAY_LOGE(" fail")); return ret; @@ -741,9 +842,10 @@ void DisplayComposerService::OnVBlankIdleCallback(uint32_t devId, uint64_t ns, v int32_t DisplayComposerService::RegDisplayVBlankIdleCallback(const sptr& cb) { DISPLAY_TRACE; - DISPLAY_CHK_RETURN(vdiImplV1_1_ == nullptr, HDF_ERR_NOT_SUPPORT); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->RegDisplayVBlankIdleCallback, HDF_ERR_NOT_SUPPORT); VBlankIdleCb_ = cb; - int32_t ret = vdiImplV1_1_->RegDisplayVBlankIdleCallback(OnVBlankIdleCallback, this); + int32_t ret = vdiAdapter_->RegDisplayVBlankIdleCallback(OnVBlankIdleCallback, this); DISPLAY_CHK_RETURN(ret != HDF_SUCCESS && ret != HDF_ERR_NOT_SUPPORT, HDF_FAILURE, DISPLAY_LOGE(" fail")); return ret; } @@ -770,6 +872,41 @@ int32_t DisplayComposerService::ClearLayerBuffer(uint32_t devId, uint32_t layerI return devCache->ClearLayerBuffer(layerId); } +int32_t DisplayComposerService::SetDisplayActiveRegion(uint32_t devId, const IRect& rect) +{ + HDF_LOGI("%{public}s: devId %{public}u, rect {%{public}u, %{public}u, %{public}u, %{public}u}", + __func__, devId, rect.x, rect.y, rect.w, rect.h); + + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->SetDisplayActiveRegion, HDF_ERR_NOT_SUPPORT); + + StartTrace(HITRACE_TAG_HDF, "vdiAdapter_->SetDisplayActiveRegion"); + int32_t ret = vdiAdapter_->SetDisplayActiveRegion(devId, rect); + FinishTrace(HITRACE_TAG_HDF); + + if (ret != HDF_SUCCESS) { + HDF_LOGI("%{public}s: fail, ret %{public}d", __func__, ret); + } + + return ret; +} + +int32_t DisplayComposerService::FastPresent(uint32_t devId, const PresentParam& param, + const std::vector>& inHandles) +{ + DISPLAY_TRACE; + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_, HDF_FAILURE); + CHECK_NULLPOINTER_RETURN_VALUE(vdiAdapter_->FastPresent, HDF_ERR_NOT_SUPPORT); + + std::vector handles; + for (uint32_t i = 0; i < param.sliceNum; i++) { + handles.emplace_back(inHandles[i]->GetBufferHandle()); + } + + int32_t ret = vdiAdapter_->FastPresent(devId, param, handles); + DISPLAY_CHK_RETURN(ret != HDF_SUCCESS && ret != HDF_ERR_NOT_SUPPORT, HDF_FAILURE, DISPLAY_LOGE(" fail")); + return ret; +} } // namespace Composer } // namespace Display } // namespace HDI diff --git a/display/composer/test/unittest/hdi_composer_ut.cpp b/display/composer/test/unittest/hdi_composer_ut.cpp index 5846fd667f..e028cc32e1 100644 --- a/display/composer/test/unittest/hdi_composer_ut.cpp +++ b/display/composer/test/unittest/hdi_composer_ut.cpp @@ -1058,3 +1058,28 @@ HWTEST_F(DeviceTest, test_GetHDRCapabilityInfos, TestSize.Level1) } EXPECT_EQ(DISPLAY_SUCCESS, ret); } + +HWTEST_F(DeviceTest, test_SetDisplayActiveRegion, TestSize.Level1) +{ + IRect rect = {0, 0, 1920, 540}; + auto ret = g_composerDevice->SetDisplayActiveRegion(g_displayIds[0], rect); + HDF_LOGI("SetDisplayActiveRegion ret = %{public}d", ret); + + if (ret == DISPLAY_NOT_SUPPORT) { + DISPLAY_TEST_LOGD("SetDisplayActiveRegion not support"); + return; + } + EXPECT_EQ(DISPLAY_SUCCESS, ret); +} + +HWTEST_F(DeviceTest, test_FastPresent, TestSize.Level1) +{ + PresentParam param = { 0, 1280, 1, 0x5000280, 0 }; + std::vector inHandles; + auto ret = g_composerDevice->FastPresent(g_displayIds[0], param, inHandles); + if (ret == DISPLAY_NOT_SUPPORT) { + DISPLAY_TEST_LOGD("FastPresent not support"); + return; + } + EXPECT_EQ(DISPLAY_FAILURE, ret); +} \ No newline at end of file diff --git a/display/hdi_service/gralloc/server/allocator_service_stub.cpp b/display/hdi_service/gralloc/server/allocator_service_stub.cpp index 254cd53fee..90a53cbdbe 100644 --- a/display/hdi_service/gralloc/server/allocator_service_stub.cpp +++ b/display/hdi_service/gralloc/server/allocator_service_stub.cpp @@ -68,11 +68,9 @@ int32_t AllocatorServiceStub::OnRemoteRequest( { if (cmdId == CMD_ALLOCATOR_ALLOCMEM) { return AllocaltorStubAllocMem(data, reply, option); - } else { - HDF_LOGE("%{public}s: not support cmd", __func__); - return HDF_ERR_INVALID_PARAM; } - return HDF_SUCCESS; + HDF_LOGE("%{public}s: not support cmd", __func__); + return HDF_ERR_INVALID_PARAM; } } // namespace V1_0 } // namespace Display diff --git a/distributed_audio/hdi_service/audio/v1_0/include/audio_adapter_interface_impl.h b/distributed_audio/hdi_service/audio/v1_0/include/audio_adapter_interface_impl.h index 08d258a9f8..23ec6b66b8 100644 --- a/distributed_audio/hdi_service/audio/v1_0/include/audio_adapter_interface_impl.h +++ b/distributed_audio/hdi_service/audio/v1_0/include/audio_adapter_interface_impl.h @@ -148,7 +148,7 @@ private: bool GetSpkStatus(const uint32_t streamId); private: - static constexpr uint8_t WAIT_SECONDS = 20; + static constexpr uint32_t WAIT_MILLISECONDS = 8000; static constexpr int32_t TYPE_CONDITION = 11; static constexpr int32_t MAX_EVENT_DIGITS = 3; AudioAdapterDescriptor adpDescriptor_; diff --git a/distributed_audio/hdi_service/audio/v1_0/src/audio_adapter_interface_impl.cpp b/distributed_audio/hdi_service/audio/v1_0/src/audio_adapter_interface_impl.cpp index e042359455..4b9b801d91 100644 --- a/distributed_audio/hdi_service/audio/v1_0/src/audio_adapter_interface_impl.cpp +++ b/distributed_audio/hdi_service/audio/v1_0/src/audio_adapter_interface_impl.cpp @@ -1130,13 +1130,14 @@ int32_t AudioAdapterInterfaceImpl::WaitForSANotify(const uint32_t streamId, cons if (event == EVENT_OPEN_SPK || event == EVENT_CLOSE_SPK) { spkNotifyFlag_ = false; std::unique_lock lck(spkWaitMutex_); - auto status = spkWaitCond_.wait_for(lck, std::chrono::seconds(WAIT_SECONDS), [this, streamId, event]() { - auto isSpkOpened = GetSpkStatus(streamId); - return spkNotifyFlag_ || - (event == EVENT_OPEN_SPK && isSpkOpened) || (event == EVENT_CLOSE_SPK && !isSpkOpened); + auto status = spkWaitCond_.wait_for(lck, std::chrono::milliseconds(WAIT_MILLISECONDS), + [this, streamId, event]() { + auto isSpkOpened = GetSpkStatus(streamId); + return spkNotifyFlag_ || + (event == EVENT_OPEN_SPK && isSpkOpened) || (event == EVENT_CLOSE_SPK && !isSpkOpened); }); if (!status) { - DHLOGE("Wait spk event: %{public}d timeout(%{public}d)s.", event, WAIT_SECONDS); + DHLOGE("Wait spk event: %{public}d timeout(%{public}d)ms.", event, WAIT_MILLISECONDS); return ERR_DH_AUDIO_HDF_WAIT_TIMEOUT; } if (event == EVENT_OPEN_SPK && !GetSpkStatus(streamId)) { @@ -1152,12 +1153,12 @@ int32_t AudioAdapterInterfaceImpl::WaitForSANotify(const uint32_t streamId, cons if (event == EVENT_OPEN_MIC || event == EVENT_CLOSE_MIC) { micNotifyFlag_ = false; std::unique_lock lck(micWaitMutex_); - auto status = micWaitCond_.wait_for(lck, std::chrono::seconds(WAIT_SECONDS), [this, event]() { + auto status = micWaitCond_.wait_for(lck, std::chrono::milliseconds(WAIT_MILLISECONDS), [this, event]() { return micNotifyFlag_ || (event == EVENT_OPEN_MIC && isMicOpened_) || (event == EVENT_CLOSE_MIC && !isMicOpened_); }); if (!status) { - DHLOGE("Wait mic event: %{public}d timeout(%{public}d)s.", event, WAIT_SECONDS); + DHLOGE("Wait mic event: %{public}d timeout(%{public}d)ms.", event, WAIT_MILLISECONDS); return ERR_DH_AUDIO_HDF_WAIT_TIMEOUT; } if (event == EVENT_OPEN_MIC && !isMicOpened_) { diff --git a/distributed_audio/hdi_service/audio/v1_0/test/fuzztest/getalladapters_fuzzer/getalladapters_fuzzer.cpp b/distributed_audio/hdi_service/audio/v1_0/test/fuzztest/getalladapters_fuzzer/getalladapters_fuzzer.cpp index d3b5db040c..c14489452f 100644 --- a/distributed_audio/hdi_service/audio/v1_0/test/fuzztest/getalladapters_fuzzer/getalladapters_fuzzer.cpp +++ b/distributed_audio/hdi_service/audio/v1_0/test/fuzztest/getalladapters_fuzzer/getalladapters_fuzzer.cpp @@ -34,6 +34,10 @@ void GetAllAdaptersFuzzTest(const uint8_t* data, size_t size) } std::vector descriptors; + AudioAdapterDescriptor desc; + std::string adpName(reinterpret_cast(data), size); + desc.adapterName = adpName; + descriptors.push_back(desc); AudioManagerInterfaceImpl::GetAudioManager()->GetAllAdapters(descriptors); } } // V1_0 diff --git a/distributed_audio/hdi_service/audio/v1_0/test/fuzztest/loadadapter_fuzzer/loadadapter_fuzzer.cpp b/distributed_audio/hdi_service/audio/v1_0/test/fuzztest/loadadapter_fuzzer/loadadapter_fuzzer.cpp index 0501f9b83f..3fbf16b7fd 100644 --- a/distributed_audio/hdi_service/audio/v1_0/test/fuzztest/loadadapter_fuzzer/loadadapter_fuzzer.cpp +++ b/distributed_audio/hdi_service/audio/v1_0/test/fuzztest/loadadapter_fuzzer/loadadapter_fuzzer.cpp @@ -35,6 +35,8 @@ void LoadAdapterFuzzTest(const uint8_t* data, size_t size) AudioAdapterDescriptor descriptor; sptr adapter = nullptr; + std::string adpName(reinterpret_cast(data), size); + descriptor.adapterName = adpName; AudioManagerInterfaceImpl::GetAudioManager()->LoadAdapter(descriptor, adapter); } } // V1_0 diff --git a/distributed_audio/hdi_service/audio/v1_0/test/unittest/audio_render_interface/src/audio_render_interface_impl_test.cpp b/distributed_audio/hdi_service/audio/v1_0/test/unittest/audio_render_interface/src/audio_render_interface_impl_test.cpp index b6c0f64d9c..4211ff2894 100644 --- a/distributed_audio/hdi_service/audio/v1_0/test/unittest/audio_render_interface/src/audio_render_interface_impl_test.cpp +++ b/distributed_audio/hdi_service/audio/v1_0/test/unittest/audio_render_interface/src/audio_render_interface_impl_test.cpp @@ -38,6 +38,9 @@ void AudioRenderInterfaceImplTest::SetUp(void) desc_.portId = 0; desc_.pins = PIN_NONE; desc_.desc = "mic"; + uint32_t renderId = 0; + audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, + callback_, renderId); } void AudioRenderInterfaceImplTest::TearDown(void) @@ -53,8 +56,7 @@ void AudioRenderInterfaceImplTest::TearDown(void) */ HWTEST_F(AudioRenderInterfaceImplTest, GetLatency_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); uint32_t ms = 12; EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->GetLatency(ms)); } @@ -67,8 +69,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, GetLatency_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, RenderFrame_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); std::vector frame; uint64_t replyBytes = 0; EXPECT_EQ(HDF_FAILURE, audioRenderInterfaceImpl_->RenderFrame(frame, replyBytes)); @@ -82,8 +83,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, RenderFrame_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, RenderFrame_002, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); std::vector frame; uint64_t replyBytes = 0; audioRenderInterfaceImpl_->renderStatus_ = RENDER_STATUS_START; @@ -99,8 +99,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, RenderFrame_002, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, RenderFrame_003, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); std::vector frame; uint64_t replyBytes = 0; audioRenderInterfaceImpl_->renderStatus_ = RENDER_STATUS_START; @@ -116,8 +115,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, RenderFrame_003, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, GetRenderPosition_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); uint64_t frames = 0; AudioTimeStamp time; EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->GetRenderPosition(frames, time)); @@ -131,8 +129,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, GetRenderPosition_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, SetRenderSpeed_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); float speed = 0; EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->SetRenderSpeed(speed)); } @@ -145,8 +142,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, SetRenderSpeed_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, GetRenderSpeed_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); float speed; EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->GetRenderSpeed(speed)); } @@ -159,8 +155,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, GetRenderSpeed_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, SetChannelMode_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); AudioChannelMode mode = AudioChannelMode::AUDIO_CHANNEL_NORMAL; EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->SetChannelMode(mode)); } @@ -173,8 +168,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, SetChannelMode_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, GetChannelMode_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); AudioChannelMode mode = AudioChannelMode::AUDIO_CHANNEL_MIX; EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->GetChannelMode(mode)); } @@ -187,8 +181,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, GetChannelMode_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, RegCallback_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); sptr cbObj = nullptr; EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->RegCallback(cbObj, 0)); } @@ -201,8 +194,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, RegCallback_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, DrainBuffer_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); AudioDrainNotifyType type = AudioDrainNotifyType::AUDIO_DRAIN_EARLY_MODE; EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->DrainBuffer(type)); } @@ -215,8 +207,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, DrainBuffer_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, IsSupportsDrain_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); bool support = true; EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->IsSupportsDrain(support)); } @@ -229,8 +220,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, IsSupportsDrain_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, Start_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->Start()); } @@ -242,8 +232,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, Start_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, Start_002, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); audioRenderInterfaceImpl_->firstOpenFlag_ = false; audioRenderInterfaceImpl_->audioExtCallback_ = sptr(new MockIDAudioCallback()); EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->Start()); @@ -257,8 +246,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, Start_002, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, Start_003, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); audioRenderInterfaceImpl_->firstOpenFlag_ = false; audioRenderInterfaceImpl_->audioExtCallback_ = sptr(new MockRevertIDAudioCallback()); EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->Start()); @@ -272,8 +260,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, Start_003, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, Stop_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->Stop()); audioRenderInterfaceImpl_->audioExtCallback_ = sptr(new MockRevertIDAudioCallback()); EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->Stop()); @@ -287,8 +274,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, Stop_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, Pause_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->Pause()); } @@ -300,8 +286,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, Pause_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, Resume_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->Resume()); } @@ -313,8 +298,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, Resume_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, Flush_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->Flush()); } @@ -326,8 +310,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, Flush_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, TurnStandbyMode_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->TurnStandbyMode()); } @@ -339,8 +322,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, TurnStandbyMode_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, AudioDevDump_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); int32_t range = 0; int32_t fd = 0; EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->AudioDevDump(range, fd)); @@ -354,8 +336,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, AudioDevDump_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, IsSupportsPauseAndResume_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); bool supportPause = true; bool supportResume = true; EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->IsSupportsPauseAndResume(supportPause, supportResume)); @@ -369,8 +350,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, IsSupportsPauseAndResume_001, TestSize.Le */ HWTEST_F(AudioRenderInterfaceImplTest, CheckSceneCapability_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); AudioSceneDescriptor scene; bool support = true; EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->CheckSceneCapability(scene, support)); @@ -384,8 +364,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, CheckSceneCapability_001, TestSize.Level1 */ HWTEST_F(AudioRenderInterfaceImplTest, SelectScene_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); AudioSceneDescriptor scene; EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->SelectScene(scene)); } @@ -398,8 +377,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, SelectScene_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, SetMute_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); bool mute = true; EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->SetMute(mute)); } @@ -412,8 +390,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, SetMute_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, GetMute_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); bool mute = true; EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->GetMute(mute)); } @@ -426,8 +403,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, GetMute_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, SetVolume_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); float volume = 0; EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->SetVolume(volume)); } @@ -440,8 +416,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, SetVolume_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, GetVolume_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); float volume = 0; EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->GetVolume(volume)); } @@ -454,8 +429,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, GetVolume_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, GetGainThreshold_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); float min = 0; float max = 0; EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->GetGainThreshold(min, max)); @@ -469,8 +443,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, GetGainThreshold_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, SetGain_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); float gain = 0; EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->SetGain(gain)); } @@ -483,8 +456,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, SetGain_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, GetGain_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); float gain = 0; EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->GetGain(gain)); } @@ -497,8 +469,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, GetGain_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, GetFrameSize_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); uint64_t size = 0; EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->GetFrameSize(size)); } @@ -511,8 +482,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, GetFrameSize_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, GetFrameCount_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); uint64_t count = 0; EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->GetFrameCount(count)); } @@ -525,8 +495,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, GetFrameCount_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, SetSampleAttributes_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); AudioSampleAttributes attrs = { .type = AUDIO_IN_MEDIA, .interleaved = true, @@ -553,8 +522,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, SetSampleAttributes_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, GetSampleAttributes_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); AudioSampleAttributes attrs; EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->GetSampleAttributes(attrs)); } @@ -567,8 +535,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, GetSampleAttributes_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, GetCurrentChannelId_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); uint32_t channelId = 0; EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->GetCurrentChannelId(channelId)); } @@ -581,8 +548,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, GetCurrentChannelId_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, SetExtraParams_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); std::string keyValueList = "hello"; EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->SetExtraParams(keyValueList)); } @@ -595,8 +561,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, SetExtraParams_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, GetExtraParams_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); std::string keyValueList; EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->GetExtraParams(keyValueList)); } @@ -609,8 +574,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, GetExtraParams_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, ReqMmapBuffer_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); int32_t reqSize = 1; AudioMmapBufferDescriptor desc; EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->ReqMmapBuffer(reqSize, desc)); @@ -624,8 +588,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, ReqMmapBuffer_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, GetMmapPosition_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); uint64_t frame = 0; AudioTimeStamp time = {1, 1}; EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->GetMmapPosition(frame, time)); @@ -639,8 +602,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, GetMmapPosition_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, GetFrameBufferSize_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); uint64_t bufferSize = 6; EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->GetFrameBufferSize(bufferSize)); } @@ -653,8 +615,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, GetFrameBufferSize_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, RemoveAudioEffect_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); uint64_t effectid = 0; EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->RemoveAudioEffect(effectid)); } @@ -668,8 +629,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, RemoveAudioEffect_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, AddAudioEffect_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); uint64_t id = 0; EXPECT_EQ(HDF_SUCCESS, audioRenderInterfaceImpl_->AddAudioEffect(id)); } @@ -703,8 +663,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, GetRenderDesc_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, GetVolumeInner_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); uint32_t volTmp = 2; uint32_t volTmpMin = 2; uint32_t volTmpMax = 10; @@ -722,8 +681,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, GetVolumeInner_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, GetMaxVolumeInner_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); uint32_t volTmpMin = 2; uint32_t volTmpMax = 10; @@ -739,8 +697,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, GetMaxVolumeInner_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, GetMinVolumeInner_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); uint32_t volTmpMin = 2; uint32_t volTmpMax = 10; @@ -756,8 +713,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, GetMinVolumeInner_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, GetFadeRate_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); uint32_t currentIndex = 2; const uint32_t durationIndex = 5; @@ -774,8 +730,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, GetFadeRate_001, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, GetFadeRate_002, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); uint32_t currentIndex = 3; const uint32_t durationIndex = 5; @@ -792,8 +747,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, GetFadeRate_002, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, GetFadeRate_003, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); uint32_t currentIndex = 6; const uint32_t durationIndex = 5; @@ -809,8 +763,7 @@ HWTEST_F(AudioRenderInterfaceImplTest, GetFadeRate_003, TestSize.Level1) */ HWTEST_F(AudioRenderInterfaceImplTest, FadeInProcess_001, TestSize.Level1) { - audioRenderInterfaceImpl_ = std::make_shared(adpName_, desc_, attrs_, - callback_, renderId_); + ASSERT_NE(nullptr, audioRenderInterfaceImpl_); const uint32_t durationFrame = 10; const size_t frameLength = 4096; const size_t errLength = 5000; diff --git a/distributed_camera/hdi_service/BUILD.gn b/distributed_camera/hdi_service/BUILD.gn index fc59850279..c7cf2f7131 100644 --- a/distributed_camera/hdi_service/BUILD.gn +++ b/distributed_camera/hdi_service/BUILD.gn @@ -54,6 +54,7 @@ ohos_shared_library("libdistributed_camera_host_config") { "c_utils:utils", "drivers_interface_camera:libbuffer_producer_sequenceable_1.0", "drivers_interface_camera:libcamera_stub_1.3", + "drivers_interface_camera:metadata", "drivers_interface_display:libdisplay_composer_stub_1.0", "drivers_interface_distributed_camera:libdistributed_camera_provider_stub_1.1", "graphic_surface:surface", diff --git a/distributed_camera/hdi_service/test/fuzztest/dcameradisabledcameradevice_fuzzer/dcameradisabledcameradevice_fuzzer.cpp b/distributed_camera/hdi_service/test/fuzztest/dcameradisabledcameradevice_fuzzer/dcameradisabledcameradevice_fuzzer.cpp index 4a0ad30461..51d973c620 100755 --- a/distributed_camera/hdi_service/test/fuzztest/dcameradisabledcameradevice_fuzzer/dcameradisabledcameradevice_fuzzer.cpp +++ b/distributed_camera/hdi_service/test/fuzztest/dcameradisabledcameradevice_fuzzer/dcameradisabledcameradevice_fuzzer.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-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 @@ -28,8 +28,8 @@ void DcameraDisableDCameraDeviceFuzzTest(const uint8_t* data, size_t size) if ((data == nullptr) || (size == 0)) { return; } - std::string deviceId = "1"; - std::string dhId = "2"; + std::string deviceId(reinterpret_cast(data), size); + std::string dhId(reinterpret_cast(data), size); DHBase dhBase; dhBase.deviceId_ = deviceId; dhBase.dhId_ = dhId; diff --git a/distributed_camera/hdi_service/test/fuzztest/dcameragetcameraids_fuzzer/dcameragetcameraids_fuzzer.cpp b/distributed_camera/hdi_service/test/fuzztest/dcameragetcameraids_fuzzer/dcameragetcameraids_fuzzer.cpp index e50976f083..629ebea3df 100644 --- a/distributed_camera/hdi_service/test/fuzztest/dcameragetcameraids_fuzzer/dcameragetcameraids_fuzzer.cpp +++ b/distributed_camera/hdi_service/test/fuzztest/dcameragetcameraids_fuzzer/dcameragetcameraids_fuzzer.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-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 @@ -31,8 +31,8 @@ void DCameraGetCameraIdsFuzzTest(const uint8_t* data, size_t size) DHBase dhBase; dhBase.deviceId_ = "1"; dhBase.dhId_ = "2"; - std::string sinkAbilityInfo = "sink"; - std::string sourceAbilityInfo = "source"; + std::string sinkAbilityInfo(reinterpret_cast(data), size); + std::string sourceAbilityInfo(reinterpret_cast(data), size); OHOS::sptr dcameraDevice(new (std::nothrow) DCameraDevice(dhBase, sinkAbilityInfo, sourceAbilityInfo)); if (dcameraDevice == nullptr) { diff --git a/distributed_camera/hdi_service/test/fuzztest/dcamerahost_fuzzer/dcamerahost_fuzzer.cpp b/distributed_camera/hdi_service/test/fuzztest/dcamerahost_fuzzer/dcamerahost_fuzzer.cpp index ae01d58f25..1752440649 100644 --- a/distributed_camera/hdi_service/test/fuzztest/dcamerahost_fuzzer/dcamerahost_fuzzer.cpp +++ b/distributed_camera/hdi_service/test/fuzztest/dcamerahost_fuzzer/dcamerahost_fuzzer.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-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 @@ -31,8 +31,8 @@ void DCameraGetCameraAbilityFromDevFuzzTest(const uint8_t* data, size_t size) DHBase dhBase; dhBase.deviceId_ = "1"; dhBase.dhId_ = "2"; - std::string sinkAbilityInfo = "sink"; - std::string sourceAbilityInfo = "source"; + std::string sinkAbilityInfo(reinterpret_cast(data), size); + std::string sourceAbilityInfo(reinterpret_cast(data), size); OHOS::sptr dcameraDevice(new (std::nothrow) DCameraDevice(dhBase, sinkAbilityInfo, sourceAbilityInfo)); if (dcameraDevice == nullptr) { @@ -64,6 +64,8 @@ void DCameraGetCamDevNumFuzzTest(const uint8_t* data, size_t size) if ((data == nullptr) || (size == 0)) { return; } + std::string foo(reinterpret_cast(data), size); + foo = "source"; DCameraHost::GetInstance()->GetCamDevNum(); } @@ -76,8 +78,8 @@ void DCameraIsCameraIdInvalidFuzzTest(const uint8_t* data, size_t size) DHBase dhBase; dhBase.deviceId_ = "1"; dhBase.dhId_ = "2"; - std::string sinkAbilityInfo = "sink"; - std::string sourceAbilityInfo = "source"; + std::string sinkAbilityInfo(reinterpret_cast(data), size); + std::string sourceAbilityInfo(reinterpret_cast(data), size); OHOS::sptr dcameraDevice(new (std::nothrow) DCameraDevice(dhBase, sinkAbilityInfo, sourceAbilityInfo)); if (dcameraDevice == nullptr) { @@ -92,9 +94,11 @@ void DCameraGetCameraIdByDHBaseFuzzTest(const uint8_t* data, size_t size) if ((data == nullptr) || (size == 0)) { return; } + std::string deviceId(reinterpret_cast(data), size); + std::string dhId(reinterpret_cast(data), size); DHBase dhBase; - dhBase.deviceId_ = "1"; - dhBase.dhId_ = "2"; + dhBase.deviceId_ = deviceId; + dhBase.dhId_ = dhId; DCameraHost::GetInstance()->GetCameraIdByDHBase(dhBase); } } diff --git a/distributed_camera/hdi_service/test/fuzztest/dcamerahostsetcallback_fuzzer/dcamerahostsetcallback_fuzzer.cpp b/distributed_camera/hdi_service/test/fuzztest/dcamerahostsetcallback_fuzzer/dcamerahostsetcallback_fuzzer.cpp index a90b2c0d41..e7be3234f0 100644 --- a/distributed_camera/hdi_service/test/fuzztest/dcamerahostsetcallback_fuzzer/dcamerahostsetcallback_fuzzer.cpp +++ b/distributed_camera/hdi_service/test/fuzztest/dcamerahostsetcallback_fuzzer/dcamerahostsetcallback_fuzzer.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023 Huawei Device Co., Ltd. + * Copyright (c) 2023-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 @@ -45,9 +45,11 @@ public: void DcameraHostSetCallbackFuzzTest(const uint8_t* data, size_t size) { - if ((data == nullptr) || (size < sizeof(uint8_t))) { + if ((data == nullptr) || (size == 0)) { return; } + std::string foo(reinterpret_cast(data), size); + foo = "source"; sptr callbackObj(new DemoCameraHostCallback()); DCameraHost::GetInstance()->SetCallback(callbackObj); } diff --git a/distributed_camera/hdi_service/test/unittest/common/dcamera_device/BUILD.gn b/distributed_camera/hdi_service/test/unittest/common/dcamera_device/BUILD.gn index 42ca61307b..a1e7d102eb 100644 --- a/distributed_camera/hdi_service/test/unittest/common/dcamera_device/BUILD.gn +++ b/distributed_camera/hdi_service/test/unittest/common/dcamera_device/BUILD.gn @@ -45,7 +45,9 @@ ohos_unittest("HdfDcameraDeviceTest") { external_deps = [ "cJSON:cjson", "c_utils:utils", + "drivers_interface_camera:libbuffer_handle_sequenceable_1.0", "drivers_interface_camera:libcamera_proxy_1.0", + "drivers_interface_camera:libmap_data_sequenceable_1.0", "drivers_interface_camera:metadata", "drivers_interface_display:libdisplay_composer_stub_1.0", "drivers_interface_distributed_camera:libdistributed_camera_provider_stub_1.1", diff --git a/distributed_camera/hdi_service/test/unittest/common/dstream_operator/BUILD.gn b/distributed_camera/hdi_service/test/unittest/common/dstream_operator/BUILD.gn index 5198d426ee..d10d328d1e 100644 --- a/distributed_camera/hdi_service/test/unittest/common/dstream_operator/BUILD.gn +++ b/distributed_camera/hdi_service/test/unittest/common/dstream_operator/BUILD.gn @@ -49,7 +49,9 @@ ohos_unittest("HdfDstreamOperatorTest") { external_deps = [ "cJSON:cjson", "c_utils:utils", + "drivers_interface_camera:libbuffer_handle_sequenceable_1.0", "drivers_interface_camera:libcamera_proxy_1.0", + "drivers_interface_camera:libmap_data_sequenceable_1.0", "drivers_interface_camera:metadata", "drivers_interface_display:libdisplay_composer_stub_1.0", "drivers_interface_distributed_camera:libdistributed_camera_provider_stub_1.1", diff --git a/face_auth/hdi_service/BUILD.gn b/face_auth/hdi_service/BUILD.gn index 5a9a19c334..e056c01cd3 100644 --- a/face_auth/hdi_service/BUILD.gn +++ b/face_auth/hdi_service/BUILD.gn @@ -35,7 +35,6 @@ ohos_shared_library("libface_auth_interface_service_2.0") { external_deps = [ "c_utils:utils", - "drivers_interface_camera:libbuffer_producer_sequenceable_1.0", "drivers_interface_face_auth:libface_auth_stub_2.0", "graphic_surface:surface", "hdf_core:libhdi", @@ -43,6 +42,9 @@ ohos_shared_library("libface_auth_interface_service_2.0") { "ipc:ipc_single", ] + public_external_deps = + [ "drivers_interface_camera:libbuffer_producer_sequenceable_1.0" ] + install_images = [ chipset_base_dir ] subsystem_name = "hdf" part_name = "drivers_peripheral_face_auth" diff --git a/input/ddk_service/src/emit_event_manager/emit_event_manager.cpp b/input/ddk_service/src/emit_event_manager/emit_event_manager.cpp index 8f640716d3..b8a396ee20 100644 --- a/input/ddk_service/src/emit_event_manager/emit_event_manager.cpp +++ b/input/ddk_service/src/emit_event_manager/emit_event_manager.cpp @@ -56,7 +56,7 @@ int32_t EmitEventManager::EmitEvent(uint32_t deviceId, const std::vector lock(mutex_); if (virtualDeviceMap_.count(deviceId) == 0) { HDF_LOGE("%{public}s device is not exit", __func__); - return HID_DDK_FAILURE; + return HID_DDK_NULL_PTR; } if (virtualDeviceMap_[deviceId] == nullptr) { @@ -79,7 +79,7 @@ int32_t EmitEventManager::DestroyDevice(uint32_t deviceId) std::lock_guard lock(mutex_); if (virtualDeviceMap_.count(deviceId) == 0) { HDF_LOGE("%{public}s device is not exit", __func__); - return HID_DDK_FAILURE; + return HID_DDK_NULL_PTR; } uint32_t callingToken = IPCSkeleton::GetCallingTokenID(); diff --git a/input/udriver/include/input_device_manager.h b/input/udriver/include/input_device_manager.h index bb1265a658..443d3123e8 100644 --- a/input/udriver/include/input_device_manager.h +++ b/input/udriver/include/input_device_manager.h @@ -26,6 +26,7 @@ #include #include #include +#include "hdf_log.h" #include "input_manager.h" namespace OHOS { diff --git a/nfc/test/unittest/nfc_impl_mock_test/nfc_impl_mock_test.cpp b/nfc/test/unittest/nfc_impl_mock_test/nfc_impl_mock_test.cpp index 54b44e4c6a..337eaeea6a 100644 --- a/nfc/test/unittest/nfc_impl_mock_test/nfc_impl_mock_test.cpp +++ b/nfc/test/unittest/nfc_impl_mock_test/nfc_impl_mock_test.cpp @@ -235,7 +235,7 @@ HWTEST_F(NfcImplTest, IoctlWithResponse002, TestSize.Level1) NfcStatus status = NfcStatus::OK; std::shared_ptr nfcImpl = std::make_shared(); int ret = nfcImpl->IoctlWithResponse(cmd, data, response, status); - ASSERT_TRUE(ret == HDF_ERR_INVALID_PARAM); + ASSERT_TRUE(ret == HDF_FAILURE); } /** diff --git a/nfc/test/unittest/nfc_impl_test/nfc_impl_test.cpp b/nfc/test/unittest/nfc_impl_test/nfc_impl_test.cpp index 216995a2e8..8615f963fd 100644 --- a/nfc/test/unittest/nfc_impl_test/nfc_impl_test.cpp +++ b/nfc/test/unittest/nfc_impl_test/nfc_impl_test.cpp @@ -236,7 +236,7 @@ HWTEST_F(NfcImplTest, IoctlWithResponse002, TestSize.Level1) NfcStatus status = NfcStatus::OK; std::shared_ptr nfcImpl = std::make_shared(); int ret = nfcImpl->IoctlWithResponse(cmd, data, response, status); - ASSERT_TRUE(ret == HDF_ERR_INVALID_PARAM); + ASSERT_TRUE(ret == HDF_SUCCESS); } /** diff --git a/power/bundle.json b/power/bundle.json index 29767be0e2..1c9a7bb1bf 100755 --- a/power/bundle.json +++ b/power/bundle.json @@ -17,7 +17,11 @@ "drivers_peripheral_power_suspend_with_tag", "drivers_peripheral_power_faster_retry_of_sleep", "drivers_peripheral_power_enable_s4", - "drivers_peripheral_power_slower_retry_of_sleep" + "drivers_peripheral_power_slower_retry_of_sleep", + "drivers_peripheral_power_c_utils", + "drivers_peripheral_power_config_policy", + "drivers_peripheral_power_hisysevent", + "drivers_peripheral_power_hicollie" ], "adapted_system_type": ["standard", "small"], "rom": "981KB", diff --git a/power/interfaces/hdi_service/BUILD.gn b/power/interfaces/hdi_service/BUILD.gn index 3c2bd9fddc..d4e9727243 100644 --- a/power/interfaces/hdi_service/BUILD.gn +++ b/power/interfaces/hdi_service/BUILD.gn @@ -17,6 +17,7 @@ ohos_shared_library("libpower_interface_service_1.2") { include_dirs = [ "../../utils/include" ] sources = [ "../../utils/power_xcollie.cpp", + "src/power_config.cpp", "src/power_interface_impl.cpp", "src/running_lock_counter.cpp", "src/running_lock_impl.cpp", @@ -30,33 +31,30 @@ ohos_shared_library("libpower_interface_service_1.2") { "hdf_core:libhdf_utils", "hilog:libhilog", "ipc:ipc_single", + "jsoncpp:jsoncpp", "libxml2:libxml2", ] defines = [] - if (has_power_c_utils_part) { + if (drivers_peripheral_power_c_utils) { external_deps += [ "c_utils:utils" ] } - if (has_power_hisysevent_part) { + if (drivers_peripheral_power_hisysevent) { external_deps += [ "hisysevent:libhisysevent" ] + defines += [ "HAS_POWER_HISYSEVENT_PART" ] } # xcollie has a bug, disable it - has_power_xcollie_part = false - if (has_power_xcollie_part) { + if (drivers_peripheral_power_hicollie) { external_deps += [ "hicollie:libhicollie" ] defines += [ "HICOLLIE_ENABLE" ] } + if (drivers_peripheral_power_config_policy) { + external_deps += [ "config_policy:configpolicy_util" ] + } + if (drivers_peripheral_power_wakeup_cause_path) { - sources += [ "src/power_config.cpp" ] - - external_deps += [ "jsoncpp:jsoncpp" ] - - if (has_power_config_policy_part) { - external_deps += [ "config_policy:configpolicy_util" ] - } - defines += [ "DRIVER_PERIPHERAL_POWER_WAKEUP_CAUSE_PATH" ] } @@ -96,7 +94,7 @@ ohos_shared_library("libpower_driver") { "hilog:libhilog", "ipc:ipc_single", ] - if (has_power_c_utils_part) { + if (drivers_peripheral_power_c_utils) { external_deps += [ "c_utils:utils" ] } diff --git a/power/interfaces/hdi_service/src/power_interface_impl.cpp b/power/interfaces/hdi_service/src/power_interface_impl.cpp index 5e737cf5a9..e971cc8fc0 100644 --- a/power/interfaces/hdi_service/src/power_interface_impl.cpp +++ b/power/interfaces/hdi_service/src/power_interface_impl.cpp @@ -41,9 +41,7 @@ #include #include -#ifdef DRIVER_PERIPHERAL_POWER_WAKEUP_CAUSE_PATH #include "power_config.h" -#endif #ifdef DRIVERS_PERIPHERAL_POWER_ENABLE_S4 #include "hibernate.h" #endif @@ -105,11 +103,8 @@ extern "C" IPowerInterface *PowerInterfaceImplGetInstance(void) int32_t PowerInterfaceImpl::Init() { -#ifdef DRIVER_PERIPHERAL_POWER_WAKEUP_CAUSE_PATH auto& powerConfig = PowerConfig::GetInstance(); powerConfig.ParseConfig(); -#endif - #ifdef DRIVERS_PERIPHERAL_POWER_ENABLE_S4 Hibernate::GetInstance().Init(); #endif @@ -475,27 +470,68 @@ int32_t PowerInterfaceImpl::UnholdRunningLockExt(const RunningLockInfo &info, int32_t PowerInterfaceImpl::GetWakeupReason(std::string &reason) { #ifdef DRIVER_PERIPHERAL_POWER_WAKEUP_CAUSE_PATH - auto& powerConfig = PowerConfig::GetInstance(); - std::map sceneConfigMap= powerConfig.GetPowerSceneConfigMap(); - std::map::iterator it = sceneConfigMap.find("wakeuo_cause"); - if (it == sceneConfigMap.end()) { - HDF_LOGW("wakeuo_cause getPath does not exist"); - return HDF_FAILURE; - } - std::string getPath = (it->second).getPath; - HDF_LOGI("getPath = %{public}s", getPath.c_str()); - - UniqueFd wakeupCauseFd(TEMP_FAILURE_RETRY(open(getPath.c_str(), O_RDONLY | O_CLOEXEC))); - if (wakeupCauseFd < 0) { - return HDF_FAILURE; - } - LoadStringFd(wakeupCauseFd, reason); - return HDF_SUCCESS; + return GetPowerConfig("wakeuo_cause", reason); #else HDF_LOGW("wakrup cause path not config"); return HDF_FAILURE; #endif } + +int32_t PowerInterfaceImpl::SetPowerConfig(const std::string &sceneName, const std::string &value) +{ + auto& powerConfig = PowerConfig::GetInstance(); + std::map sceneConfigMap = powerConfig.GetPowerSceneConfigMap(); + if (sceneConfigMap.empty()) { + HDF_LOGE("SetPowerConfig sceneConfigMap is empty"); + return HDF_ERR_NOT_SUPPORT; + } + + std::map::iterator it = sceneConfigMap.find(sceneName); + if (it == sceneConfigMap.end()) { + HDF_LOGE("SetPowerConfig sceneName: %{public}s does not exist", sceneName.c_str()); + return HDF_FAILURE; + } + std::string setPath = (it->second).setPath; + HDF_LOGI("SetPowerConfig setPath = %{public}s", setPath.c_str()); + + UniqueFd setValueFd = UniqueFd(TEMP_FAILURE_RETRY(open(setPath.c_str(), O_RDWR | O_CLOEXEC))); + if (setValueFd < 0) { + HDF_LOGE("SetPowerConfig open failed"); + return HDF_FAILURE; + } + bool ret = SaveStringToFd(setValueFd, value); + if (!ret) { + HDF_LOGE("SetPowerConfig SaveStringToFd failed"); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t PowerInterfaceImpl::GetPowerConfig(const std::string &sceneName, std::string &value) +{ + auto& powerConfig = PowerConfig::GetInstance(); + std::map sceneConfigMap = powerConfig.GetPowerSceneConfigMap(); + if (sceneConfigMap.empty()) { + HDF_LOGE("GetPowerConfig sceneConfigMap is empty"); + return HDF_ERR_NOT_SUPPORT; + } + + std::map::iterator it = sceneConfigMap.find(sceneName); + if (it == sceneConfigMap.end()) { + HDF_LOGE("GetPowerConfig sceneName: %{public}s does not exist", sceneName.c_str()); + return HDF_FAILURE; + } + std::string getPath = (it->second).getPath; + HDF_LOGI("GetPowerConfig getPath = %{public}s", getPath.c_str()); + + UniqueFd getValueFd = UniqueFd(TEMP_FAILURE_RETRY(open(getPath.c_str(), O_RDONLY | O_CLOEXEC))); + if (getValueFd < 0) { + HDF_LOGE("GetPowerConfig open failed"); + return HDF_FAILURE; + } + LoadStringFd(getValueFd, value); + return HDF_SUCCESS; +} } // namespace V1_2 } // namespace Power } // namespace HDI diff --git a/power/interfaces/hdi_service/src/power_interface_impl.h b/power/interfaces/hdi_service/src/power_interface_impl.h index fead2d9e73..02f7f205a2 100644 --- a/power/interfaces/hdi_service/src/power_interface_impl.h +++ b/power/interfaces/hdi_service/src/power_interface_impl.h @@ -68,6 +68,10 @@ public: int32_t GetWakeupReason(std::string &reason) override; + int32_t SetPowerConfig(const std::string &sceneName, const std::string &value) override; + + int32_t GetPowerConfig(const std::string &sceneName, std::string &value) override; + class PowerDeathRecipient : public IRemoteObject::DeathRecipient { public: explicit PowerDeathRecipient(const wptr &powerInterfaceImpl) diff --git a/power/power.gni b/power/power.gni index 303dc83d46..137f27aaba 100644 --- a/power/power.gni +++ b/power/power.gni @@ -13,50 +13,12 @@ declare_args() { drivers_peripheral_power_wakeup_cause_path = false -} - -declare_args() { drivers_peripheral_power_suspend_with_tag = false -} - -declare_args() { drivers_peripheral_power_enable_s4 = false -} - -declare_args() { drivers_peripheral_power_faster_retry_of_sleep = false -} - -declare_args() { drivers_peripheral_power_slower_retry_of_sleep = false -} - -if (!defined(global_parts_info) || - defined(global_parts_info.commonlibrary_c_utils)) { - has_power_c_utils_part = true -} else { - has_power_c_utils_part = false -} - -if (!defined(global_parts_info) || - defined(global_parts_info.customization_config_policy)) { - has_power_config_policy_part = true - cflags_cc = [ "-DHAS_POWER_CONFIG_POLICY_PART" ] -} else { - has_power_config_policy_part = false -} - -if (!defined(global_parts_info) || - defined(global_parts_info.hiviewdfx_hicollie)) { - has_power_xcollie_part = true -} else { - has_power_xcollie_part = false -} - -if (!defined(global_parts_info) || - defined(global_parts_info.hiviewdfx_hisysevent)) { - has_power_hisysevent_part = true - cflags_cc += [ "-DHAS_POWER_HISYSEVENT_PART" ] -} else { - has_power_hisysevent_part = false + drivers_peripheral_power_hicollie = false + drivers_peripheral_power_config_policy = true + drivers_peripheral_power_c_utils = true + drivers_peripheral_power_hisysevent = true } diff --git a/power/test/fuzztest/powerhdi_fuzzer/BUILD.gn b/power/test/fuzztest/powerhdi_fuzzer/BUILD.gn index 99ee913602..7ed0e2bc4a 100644 --- a/power/test/fuzztest/powerhdi_fuzzer/BUILD.gn +++ b/power/test/fuzztest/powerhdi_fuzzer/BUILD.gn @@ -31,14 +31,13 @@ ohos_fuzztest("PowerHdiFuzzTest") { sources = [ "powerhdi_fuzz.cpp" ] deps = [ "../../../interfaces/hdi_service:libpower_interface_service_1.2" ] external_deps = [ - "c_utils:utils", "drivers_interface_power:libpower_stub_1.2", "hdf_core:libhdf_utils", "hdf_core:libhdi", "hilog:libhilog", "ipc:ipc_single", ] - if (has_power_c_utils_part) { + if (drivers_peripheral_power_c_utils) { external_deps += [ "c_utils:utils" ] } subsystem_name = "hdf" diff --git a/power/test/fuzztest/powerhdistub_fuzzer/BUILD.gn b/power/test/fuzztest/powerhdistub_fuzzer/BUILD.gn index 6b9891863a..86c6e9058e 100644 --- a/power/test/fuzztest/powerhdistub_fuzzer/BUILD.gn +++ b/power/test/fuzztest/powerhdistub_fuzzer/BUILD.gn @@ -37,7 +37,7 @@ ohos_fuzztest("PowerHdiStubFuzzTest") { "hilog:libhilog", "ipc:ipc_single", ] - if (has_power_c_utils_part) { + if (drivers_peripheral_power_c_utils) { external_deps += [ "c_utils:utils" ] } subsystem_name = "hdf" diff --git a/power/test/unittest/BUILD.gn b/power/test/unittest/BUILD.gn index 70b4e82f7b..b13a4cc514 100644 --- a/power/test/unittest/BUILD.gn +++ b/power/test/unittest/BUILD.gn @@ -43,7 +43,7 @@ ohos_unittest("hdi_unittest_power") { "hilog:libhilog", "ipc:ipc_single", ] - if (has_power_c_utils_part) { + if (drivers_peripheral_power_c_utils) { external_deps += [ "c_utils:utils" ] } @@ -85,10 +85,12 @@ ohos_unittest("hdi_unittest_power_runninglock") { "hilog:libhilog", "ipc:ipc_single", ] - if (has_power_c_utils_part) { + + if (drivers_peripheral_power_c_utils) { external_deps += [ "c_utils:utils" ] } - if (has_power_hisysevent_part) { + if (drivers_peripheral_power_hisysevent) { external_deps += [ "hisysevent:libhisysevent" ] + defines = [ "HAS_POWER_HISYSEVENT_PART" ] } } diff --git a/ril/interfaces/hdi_service/include/ril_impl.h b/ril/interfaces/hdi_service/include/ril_impl.h index fe22163600..917723b237 100644 --- a/ril/interfaces/hdi_service/include/ril_impl.h +++ b/ril/interfaces/hdi_service/include/ril_impl.h @@ -190,15 +190,15 @@ public: template inline int32_t TaskSchedule(FuncType &&_func, int32_t slotId, ParamTypes &&... _args) const { - if (_func == nullptr || Telephony::HRilManager::manager_ == nullptr) { + if (_func == nullptr) { HDF_LOGE("manager or func is null pointer"); return RIL_ERR_NULL_POINT; } - if (slotId >= Telephony::HRilManager::manager_->GetMaxSimSlotCount()) { + if (slotId >= Telephony::HRilManager::GetInstance().GetMaxSimSlotCount()) { HDF_LOGE("slotId is inValid"); return RIL_ERR_INVALID_PARAMETER; } - auto ret = (Telephony::HRilManager::manager_.get()->*(_func))(slotId, std::forward(_args)...); + auto ret = (Telephony::HRilManager::GetInstance().*(_func))(slotId, std::forward(_args)...); return ret; } diff --git a/ril/interfaces/hdi_service/src/ril_impl.cpp b/ril/interfaces/hdi_service/src/ril_impl.cpp index 696a3af9c5..2cd266493c 100644 --- a/ril/interfaces/hdi_service/src/ril_impl.cpp +++ b/ril/interfaces/hdi_service/src/ril_impl.cpp @@ -467,11 +467,7 @@ int32_t RilImpl::SetCallback1_3(const sptr &rilCallback) return HDF_FAILURE; } AddRilDeathRecipient(callback_); - if (Telephony::HRilManager::manager_ == nullptr) { - HDF_LOGE("SetCallback1_3 fail manager_ is null"); - return HDF_FAILURE; - } - Telephony::HRilManager::manager_->SetRilCallback(callback_); + Telephony::HRilManager::GetInstance().SetRilCallback(callback_); return HDF_SUCCESS; } @@ -678,11 +674,7 @@ int32_t RilImpl::SendSmsAck(int32_t slotId, int32_t serialId, const ModeData &mo int32_t RilImpl::SendRilAck() { - if (Telephony::HRilManager::manager_ == nullptr) { - HDF_LOGE("manager or func is null pointer"); - return RIL_ERR_NULL_POINT; - } - return Telephony::HRilManager::manager_->SendRilAck(); + return Telephony::HRilManager::GetInstance().SendRilAck(); } int32_t RilImpl::AddRilDeathRecipient(const sptr &callback) @@ -722,20 +714,12 @@ int32_t RilImpl::UnRegister() HDF_LOGI("UnRegister"); RemoveRilDeathRecipient(callback_); callback_ = nullptr; - if (Telephony::HRilManager::manager_ == nullptr) { - HDF_LOGE("RilImpl::UnRegister fail manager_ is null"); - return HDF_FAILURE; - } - Telephony::HRilManager::manager_->SetRilCallback(nullptr); + Telephony::HRilManager::GetInstance().SetRilCallback(nullptr); return HDF_SUCCESS; } int32_t RilImpl::Init() { - if (Telephony::HRilManager::manager_ == nullptr) { - HDF_LOGE("RilImpl::Init is manager_ is null"); - return HDF_FAILURE; - } return HDF_SUCCESS; } } // namespace V1_3 diff --git a/secure_element/vendor_adaptor/se_vendor_adaptions.cpp b/secure_element/vendor_adaptor/se_vendor_adaptions.cpp index 85026807b8..f9efa10bdf 100644 --- a/secure_element/vendor_adaptor/se_vendor_adaptions.cpp +++ b/secure_element/vendor_adaptor/se_vendor_adaptions.cpp @@ -41,6 +41,7 @@ static const int RES_BUFFER_MAX_LENGTH = 512; static const uint16_t SW1_OFFSET = 2; static const uint16_t SW2_OFFSET = 1; static const uint16_t MAX_CHANNEL_NUM = 4; +static const uint16_t MAX_CHANNEL_SIZE = 0xFF; static const uint16_t MIN_RES_LEN = 2; uint16_t g_openedChannelCount = 0; bool g_openedChannels[MAX_CHANNEL_NUM] = {false, false, false, false}; @@ -118,12 +119,13 @@ int32_t SeVendorAdaptions::openLogicalChannel(const std::vector& aid, u #ifdef SE_VENDOR_ADAPTION_USE_CA uint8_t res[RES_BUFFER_MAX_LENGTH] = {0}; uint32_t resLen = RES_BUFFER_MAX_LENGTH; + uint32_t channelCreated = MAX_CHANNEL_SIZE + 1; int ret = SecureElementCaProxy::GetInstance().VendorSecureElementCaOpenLogicalChannel( - (uint8_t *)&aid[0], aid.size(), p2, res, &resLen, (uint32_t *)&channelNumber); + (uint8_t *)&aid[0], aid.size(), p2, res, &resLen, &channelCreated); for (uint32_t i = 0; i < resLen; i++) { response.push_back(res[i]); } - if (ret != SECURE_ELEMENT_CA_RET_OK) { + if ((ret != SECURE_ELEMENT_CA_RET_OK) || (resLen < MIN_RES_LEN)) { HDF_LOGE("openLogicalChannel failed ret %{public}u", ret); status = SecureElementStatus::SE_GENERAL_ERROR; if (g_openedChannelCount == 0) { @@ -132,16 +134,23 @@ int32_t SeVendorAdaptions::openLogicalChannel(const std::vector& aid, u } return HDF_SUCCESS; } - if (ret == SECURE_ELEMENT_CA_RET_OK && resLen >= MIN_RES_LEN) { - status = getStatusBySW(res[resLen - SW1_OFFSET], res[resLen - SW2_OFFSET]); - if (channelNumber < MAX_CHANNEL_NUM - 1 && !g_openedChannels[channelNumber] && - status == SecureElementStatus::SE_SUCCESS) { - g_openedChannels[channelNumber] = true; - g_openedChannelCount++; - } + status = getStatusBySW(res[resLen - SW1_OFFSET], res[resLen - SW2_OFFSET]); + if ((ret == SECURE_ELEMENT_CA_RET_OK) && (channelCreated < MAX_CHANNEL_NUM - 1) && + !g_openedChannels[channelCreated] && (status == SecureElementStatus::SE_SUCCESS)) { + g_openedChannels[channelCreated] = true; + g_openedChannelCount++; + } else if (g_openedChannelCount == 0) { // If there are no channels remaining close secureElement + HDF_LOGI("openLogicalChannel: g_openedChannelCount = %{public}d, Uninit", g_openedChannelCount); + SecureElementCaProxy::GetInstance().VendorSecureElementCaUninit(); } - HDF_LOGI("openLogicalChannel [%{public}d] succ, now has %{public}d channel inuse", - channelNumber, g_openedChannelCount); + + if (channelCreated <= MAX_CHANNEL_SIZE) { + channelNumber = static_cast(channelCreated); + } else { + HDF_LOGE("openLogicalChannel err, channelCreated = %{public}d", channelCreated); + } + HDF_LOGI("openLogicalChannel [%{public}d] status:[%{public}d], now has %{public}d channel inuse", + channelNumber, static_cast(status), g_openedChannelCount); #endif return HDF_SUCCESS; } @@ -164,7 +173,7 @@ int32_t SeVendorAdaptions::openBasicChannel(const std::vector& aid, uin for (uint32_t i = 0; i < resLen; i++) { response.push_back(res[i]); } - if (ret != SECURE_ELEMENT_CA_RET_OK) { + if ((ret != SECURE_ELEMENT_CA_RET_OK) || (resLen < MIN_RES_LEN)) { HDF_LOGE("openBasicChannel failed ret %{public}u", ret); status = SecureElementStatus::SE_GENERAL_ERROR; if (g_openedChannelCount == 0) { @@ -173,14 +182,17 @@ int32_t SeVendorAdaptions::openBasicChannel(const std::vector& aid, uin } return HDF_SUCCESS; } - if (ret == SECURE_ELEMENT_CA_RET_OK && resLen >= MIN_RES_LEN) { - status = getStatusBySW(res[resLen - SW1_OFFSET], res[resLen - SW2_OFFSET]); - if (!g_openedChannels[0] && (response[resLen - SW1_OFFSET] == 0x90 && response[resLen - SW2_OFFSET] == 0x00)) { - g_openedChannels[0] = true; - g_openedChannelCount++; - } + status = getStatusBySW(res[resLen - SW1_OFFSET], res[resLen - SW2_OFFSET]); + if ((ret == SECURE_ELEMENT_CA_RET_OK) && !g_openedChannels[0] && (status == SecureElementStatus::SE_SUCCESS)) { + g_openedChannels[0] = true; + g_openedChannelCount++; + } else if (g_openedChannelCount == 0) { + HDF_LOGI("openBasicChannel failed: g_openedChannelCount = %{public}d, Uninit", g_openedChannelCount); + SecureElementCaProxy::GetInstance().VendorSecureElementCaUninit(); } - HDF_LOGI("openBasicChannel [0] succ, now has %{public}d channel inuse", g_openedChannelCount); + HDF_LOGI("openBasicChannel [0] status:[%{public}d], now has %{public}d channel inuse", + static_cast(status), + g_openedChannelCount); #endif return HDF_SUCCESS; } diff --git a/secure_element/vendor_sim_adaptor/se_vendor_adaptions.cpp b/secure_element/vendor_sim_adaptor/se_vendor_adaptions.cpp index d891d14474..b3cb1d480e 100644 --- a/secure_element/vendor_sim_adaptor/se_vendor_adaptions.cpp +++ b/secure_element/vendor_sim_adaptor/se_vendor_adaptions.cpp @@ -40,6 +40,7 @@ static const int RES_BUFFER_MAX_LENGTH = 512; static const uint16_t SW1_OFFSET = 2; static const uint16_t SW2_OFFSET = 1; static const uint16_t MAX_CHANNEL_NUM = 4; +static const uint16_t MAX_CHANNEL_SIZE = 0xFF; uint16_t g_openedChannelCount = 0; bool g_openedChannels[MAX_CHANNEL_NUM] = {false, false, false, false}; bool g_initFuncFlag = false; @@ -254,7 +255,8 @@ int32_t SimSeVendorAdaptions::openLogicalChannel(const std::vector& aid } uint8_t res[RES_BUFFER_MAX_LENGTH] = {0}; uint32_t resLen = RES_BUFFER_MAX_LENGTH; - int ret = VendorSimSecureElementOpenLogicalChannel(aid, p2, response, (uint32_t *)&channelNumber, &tmpStatus); + uint32_t channelCreated = MAX_CHANNEL_SIZE + 1; + int ret = VendorSimSecureElementOpenLogicalChannel(aid, p2, response, &channelCreated, &tmpStatus); HDF_LOGE("VendorSimSecureElementOpenLogicalChannel ret %{public}u, tmpStatus = %{public}d", ret, tmpStatus); if (ret != SIM_SECURE_ELEMENT_RET_OK) { HDF_LOGE("openLogicalChannel failed ret %{public}u, tmpStatus = %{public}d", ret, tmpStatus); @@ -270,13 +272,18 @@ int32_t SimSeVendorAdaptions::openLogicalChannel(const std::vector& aid response.push_back(res[i]); } if (ret == SIM_SECURE_ELEMENT_RET_OK && resLen >= SW1_OFFSET && - channelNumber < MAX_CHANNEL_NUM - 1 && !g_openedChannels[channelNumber]) { + channelCreated < MAX_CHANNEL_NUM - 1 && !g_openedChannels[channelCreated]) { if ((response[resLen - SW1_OFFSET] == 0x90 && response[resLen - SW2_OFFSET] == 0x00) || response[resLen - SW2_OFFSET] == 0x62 || response[resLen - SW2_OFFSET] == 0x63) { - g_openedChannels[channelNumber] = true; + g_openedChannels[channelCreated] = true; g_openedChannelCount++; } } + if (channelCreated <= MAX_CHANNEL_SIZE) { + channelNumber = static_cast(channelCreated); + } else { + HDF_LOGE("openLogicalChannel err, channelCreated = %{public}d", channelCreated); + } return HDF_SUCCESS; } diff --git a/sensor/hdi_service/sensor_if_service.cpp b/sensor/hdi_service/sensor_if_service.cpp index c7fcfb385b..6db49b7aa3 100644 --- a/sensor/hdi_service/sensor_if_service.cpp +++ b/sensor/hdi_service/sensor_if_service.cpp @@ -218,38 +218,7 @@ int32_t SensorIfService::Disable(int32_t sensorId) uint32_t serviceId = static_cast(HdfRemoteGetCallingPid()); HDF_LOGI("%{public}s: sensorId %{public}d, serviceId = %{public}d", __func__, sensorId, serviceId); std::unique_lock lock(sensorServiceMutex_); - if (!SensorClientsManager::GetInstance()->IsUpadateSensorState(sensorId, serviceId, DISABLE_SENSOR)) { - HDF_LOGE("%{public}s There are still some services enable", __func__); - return HDF_SUCCESS; - } - - if (sensorVdiImpl_ == nullptr) { - HDF_LOGE("%{public}s: get sensor vdi impl failed", __func__); - return HDF_FAILURE; - } - - int32_t ret; - if (SensorClientsManager::GetInstance()->IsExistSdcSensorEnable(sensorId)) { - SENSOR_TRACE_START("sensorVdiImpl_->SetSaBatch"); - ret = sensorVdiImpl_->SetSaBatch(sensorId, REPORT_INTERVAL, REPORT_INTERVAL); - SENSOR_TRACE_FINISH; - if (ret != SENSOR_SUCCESS) { - HDF_LOGE("%{public}s SetSaBatch failed, error code is %{public}d, sensorId = %{public}d, serviceId = " - "%{public}d", __func__, ret, sensorId, serviceId); - return ret; - } - return HDF_SUCCESS; - } - - SENSOR_TRACE_START("sensorVdiImpl_->Disable"); - ret = sensorVdiImpl_->Disable(sensorId); - SENSOR_TRACE_FINISH; - if (ret != SENSOR_SUCCESS) { - HDF_LOGE("%{public}s failed, error code is %{public}d, sensorId = %{public}d, serviceId = %{public}d", __func__, - ret, sensorId, serviceId); - } - - return ret; + return DisableSensor(sensorId, serviceId); } int32_t SensorIfService::SetBatch(int32_t sensorId, int64_t samplingInterval, int64_t reportInterval) @@ -681,6 +650,43 @@ int32_t SensorIfService::ReadData(int32_t sensorId, std::vector return HDF_SUCCESS; } +int32_t SensorIfService::DisableSensor(int32_t sensorId, uint32_t serviceId) +{ + SENSOR_TRACE_PID_MSG("sensorId " + std::to_string(sensorId)); + if (!SensorClientsManager::GetInstance()->IsUpadateSensorState(sensorId, serviceId, DISABLE_SENSOR)) { + HDF_LOGE("%{public}s There are still some services enable", __func__); + return HDF_SUCCESS; + } + + if (sensorVdiImpl_ == nullptr) { + HDF_LOGE("%{public}s: get sensor vdi impl failed", __func__); + return HDF_FAILURE; + } + + int32_t ret = SENSOR_SUCCESS; + if (SensorClientsManager::GetInstance()->IsExistSdcSensorEnable(sensorId)) { + SENSOR_TRACE_START("sensorVdiImpl_->SetSaBatch"); + ret = sensorVdiImpl_->SetSaBatch(sensorId, REPORT_INTERVAL, REPORT_INTERVAL); + SENSOR_TRACE_FINISH; + if (ret != SENSOR_SUCCESS) { + HDF_LOGE("%{public}s SetSaBatch failed, error code is %{public}d, sensorId = %{public}d, serviceId = " + "%{public}d", __func__, ret, sensorId, serviceId); + return ret; + } + return HDF_SUCCESS; + } + + SENSOR_TRACE_START("sensorVdiImpl_->Disable"); + ret = sensorVdiImpl_->Disable(sensorId); + SENSOR_TRACE_FINISH; + if (ret != SENSOR_SUCCESS) { + HDF_LOGE("%{public}s failed, error code is %{public}d, sensorId = %{public}d, serviceId = %{public}d", __func__, + ret, sensorId, serviceId); + } + + return ret; +} + int32_t SensorIfService::SetSdcSensor(int32_t sensorId, bool enabled, int32_t rateLevel) { SENSOR_TRACE_PID_MSG("sensorId " + std::to_string(sensorId) + "enabled " + std::to_string(enabled) + "rateLevel " + @@ -688,11 +694,12 @@ int32_t SensorIfService::SetSdcSensor(int32_t sensorId, bool enabled, int32_t ra uint32_t serviceId = static_cast(HdfRemoteGetCallingPid()); HDF_LOGI("%{public}s: sensorId %{public}d, enabled %{public}u, rateLevel %{public}u, serviceId %{public}d", __func__, sensorId, enabled, rateLevel, serviceId); + std::unique_lock lock(sensorServiceMutex_); if (sensorVdiImpl_ == nullptr) { HDF_LOGE("%{public}s: get sensor vdi impl failed", __func__); return HDF_FAILURE; } - int32_t ret; + int32_t ret = SENSOR_SUCCESS; if (rateLevel < REPORT_INTERVAL) { HDF_LOGE("%{public}s: rateLevel cannot less than zero", __func__); return HDF_FAILURE; @@ -700,7 +707,6 @@ int32_t SensorIfService::SetSdcSensor(int32_t sensorId, bool enabled, int32_t ra int64_t samplingInterval = rateLevel == REPORT_INTERVAL ? REPORT_INTERVAL : COMMON_REPORT_FREQUENCY / rateLevel; int64_t reportInterval = REPORT_INTERVAL; if (enabled) { - std::unique_lock lock(sensorServiceMutex_); ret = SetBatchSenior(serviceId, sensorId, SDC, samplingInterval, reportInterval); if (ret != SENSOR_SUCCESS) { HDF_LOGE("%{public}s SetBatchSenior SDC failed, error code is %{public}d", __func__, ret); @@ -715,7 +721,7 @@ int32_t SensorIfService::SetSdcSensor(int32_t sensorId, bool enabled, int32_t ra } } else { SensorClientsManager::GetInstance()->EraseSdcSensorBestConfig(sensorId); - ret = Disable(sensorId); + ret = DisableSensor(sensorId, serviceId); if (ret != SENSOR_SUCCESS) { HDF_LOGE("%{public}s Disable failed, error code is %{public}d", __func__, ret); return ret; diff --git a/sensor/hdi_service/sensor_if_service.h b/sensor/hdi_service/sensor_if_service.h index c21488bfd4..a04bdeb5a7 100644 --- a/sensor/hdi_service/sensor_if_service.h +++ b/sensor/hdi_service/sensor_if_service.h @@ -38,6 +38,7 @@ public: int32_t GetAllSensorInfo(std::vector &info) override; int32_t Enable(int32_t sensorId) override; int32_t Disable(int32_t sensorId) override; + int32_t DisableSensor(int32_t sensorId, uint32_t serviceId); int32_t SetBatch(int32_t sensorId, int64_t samplingInterval, int64_t reportInterval) override; int32_t SetBatchSenior(int32_t serviceId, int32_t sensorId, int32_t mode, int64_t samplingInterval, int64_t reportInterval); diff --git a/thermal/bundle.json b/thermal/bundle.json index 1bd928340b..d722176ba5 100644 --- a/thermal/bundle.json +++ b/thermal/bundle.json @@ -15,6 +15,11 @@ "adapted_system_type": ["standard", "small"], "rom": "610KB", "ram": "7500KB", + "features": [ + "drivers_peripheral_thermal_feature_config_policy", + "drivers_peripheral_thermal_feature_c_utils", + "drivers_peripheral_thermal_feature_hitrace" + ], "deps": { "components": [ "c_utils", diff --git a/thermal/interfaces/hdi_service/BUILD.gn b/thermal/interfaces/hdi_service/BUILD.gn index 30bdb696b0..868e212832 100644 --- a/thermal/interfaces/hdi_service/BUILD.gn +++ b/thermal/interfaces/hdi_service/BUILD.gn @@ -40,14 +40,14 @@ ohos_shared_library("libthermal_interface_service_1.1") { "libxml2:libxml2", "zlib:libz", ] - if (has_thermal_c_utils_part) { + if (drivers_peripheral_thermal_feature_c_utils) { external_deps += [ "c_utils:utils" ] } - if (has_thermal_config_policy_part) { + if (drivers_peripheral_thermal_feature_config_policy) { defines = [ "HAS_THERMAL_CONFIG_POLICY_PART" ] external_deps += [ "config_policy:configpolicy_util" ] } - if (has_thermal_hitrace_part) { + if (drivers_peripheral_thermal_feature_hitrace) { external_deps += [ "hitrace:hitrace_meter" ] defines += [ "THERMAL_HITRACE_ENABLE" ] } @@ -82,7 +82,7 @@ ohos_shared_library("libthermal_driver") { "hilog:libhilog", "ipc:ipc_single", ] - if (has_thermal_c_utils_part) { + if (drivers_peripheral_thermal_feature_c_utils) { external_deps += [ "c_utils:utils" ] } } else { diff --git a/thermal/interfaces/hdi_service/src/thermal_dfx.cpp b/thermal/interfaces/hdi_service/src/thermal_dfx.cpp index 6d5797e0d7..2b240c1b0d 100644 --- a/thermal/interfaces/hdi_service/src/thermal_dfx.cpp +++ b/thermal/interfaces/hdi_service/src/thermal_dfx.cpp @@ -43,7 +43,7 @@ namespace V1_1 { namespace { constexpr uint8_t LOG_INDEX_LEN = 4; constexpr int32_t MAX_FILE_NUM = 10; -constexpr int32_t MAX_FILE_SIZE = 10 * 1024 * 1024; +constexpr long int MAX_FILE_SIZE = 10 * 1024 * 1024; constexpr int32_t MAX_TIME_LEN = 20; constexpr int32_t TIME_FORMAT_1 = 1; constexpr int32_t TIME_FORMAT_2 = 2; @@ -216,7 +216,7 @@ void ThermalDfx::CompressFile() return; } - unsigned long size = ftell(fp); + long int size = ftell(fp); if (size < MAX_FILE_SIZE) { if (fclose(fp) < 0) { THERMAL_HILOGW(COMP_HDI, "fclose() failed"); diff --git a/thermal/test/fuzztest/thermalhdistub_fuzzer/BUILD.gn b/thermal/test/fuzztest/thermalhdistub_fuzzer/BUILD.gn index 01a8adf597..3e027d9f2d 100644 --- a/thermal/test/fuzztest/thermalhdistub_fuzzer/BUILD.gn +++ b/thermal/test/fuzztest/thermalhdistub_fuzzer/BUILD.gn @@ -35,7 +35,7 @@ ohos_fuzztest("ThermalHdiStubFuzzTest") { "hilog:libhilog", "ipc:ipc_single", ] - if (has_thermal_c_utils_part) { + if (drivers_peripheral_thermal_feature_c_utils) { external_deps += [ "c_utils:utils" ] } subsystem_name = "hdf" diff --git a/thermal/test/unittest/BUILD.gn b/thermal/test/unittest/BUILD.gn index 48f84e692e..294d5a2224 100644 --- a/thermal/test/unittest/BUILD.gn +++ b/thermal/test/unittest/BUILD.gn @@ -46,7 +46,7 @@ ohos_unittest("hdi_unittest_thermal") { "ipc:ipc_single", "libxml2:libxml2", ] - if (has_thermal_c_utils_part) { + if (drivers_peripheral_thermal_feature_c_utils) { external_deps += [ "c_utils:utils" ] } } else { diff --git a/thermal/thermal.gni b/thermal/thermal.gni index e47a0230f8..4d329399b9 100644 --- a/thermal/thermal.gni +++ b/thermal/thermal.gni @@ -12,24 +12,8 @@ # limitations under the License. import("//build/ohos.gni") -if (!defined(global_parts_info) || - defined(global_parts_info.commonlibrary_c_utils)) { - has_thermal_c_utils_part = true -} else { - has_thermal_c_utils_part = false -} - -if (!defined(global_parts_info) || - defined(global_parts_info.customization_config_policy)) { - has_thermal_config_policy_part = true - cflags_cc = [ "-DHAS_THERMAL_CONFIG_POLICY_PART" ] -} else { - has_thermal_config_policy_part = false -} - -if (!defined(global_parts_info) || - defined(global_parts_info.hiviewdfx_hitrace)) { - has_thermal_hitrace_part = true -} else { - has_thermal_hitrace_part = false +declare_args() { + drivers_peripheral_thermal_feature_config_policy = true + drivers_peripheral_thermal_feature_c_utils = true + drivers_peripheral_thermal_feature_hitrace = true } diff --git a/usb/cfg/init.usb.configfs.cfg b/usb/cfg/init.usb.configfs.cfg index fbfe93d7ea..4eec9f1008 100755 --- a/usb/cfg/init.usb.configfs.cfg +++ b/usb/cfg/init.usb.configfs.cfg @@ -2,7 +2,8 @@ "jobs" : [{ "name" : "boot", "cmds" : [ - "mkdir /config/usb_gadget/g1/functions/mass_storage.usb" + "mkdir /config/usb_gadget/g1/functions/mass_storage.usb", + "mkdir /config/usb_gadget/g1/functions/fxfer.aoa" ] }, { "name" : "param:sys.usb.config=none && param:sys.usb.configfs=1", diff --git a/usb/ddk/BUILD.gn b/usb/ddk/BUILD.gn index 4c0a02155e..e0bd81e922 100644 --- a/usb/ddk/BUILD.gn +++ b/usb/ddk/BUILD.gn @@ -95,14 +95,15 @@ ohos_shared_library("libusb_pnp_manager") { branch_protector_ret = "pac_ret" include_dirs = [ + "//drivers/hdf_core/framework/model/usb/include", "host/include", "device/include", "./../utils/include", ] - public_configs = [ ":public_headers" ] sources = [ "//drivers/hdf_core/framework/model/usb/src/usb_ddk_pnp_loader.c", "//drivers/hdf_core/framework/model/usb/src/usb_wrapper.cpp", + "device/src/usb_accessory_uevent_handle.c", "device/src/usbfn_uevent_handle.c", "host/src/ddk_device_manager.c", "host/src/ddk_pnp_listener_mgr.c", diff --git a/usb/ddk/device/include/usb_accessory_uevent_handle.h b/usb/ddk/device/include/usb_accessory_uevent_handle.h new file mode 100644 index 0000000000..e2ed093a9e --- /dev/null +++ b/usb/ddk/device/include/usb_accessory_uevent_handle.h @@ -0,0 +1,28 @@ +/* + * Copyright (c) Huawei Technologies Co., Ltd. 2024. All rights reserved. + * 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 USB_ACCESSORY_UEVENT_HANDLE_H +#define USB_ACCESSORY_UEVENT_HANDLE_H +#include +#include +#ifdef __cplusplus +extern "C" { +#endif +void UsbAccessoryUeventHandle(const char msg[], ssize_t rcvLen); +int32_t UsbAccessoryUeventInit(const char *ueventPath); +#ifdef __cplusplus +} +#endif +#endif // USB_ACCESSORY_UEVENT_HANDLE_H \ No newline at end of file diff --git a/usb/ddk/device/src/adapter_if.c b/usb/ddk/device/src/adapter_if.c index 0974fa2cb6..5848ecb092 100644 --- a/usb/ddk/device/src/adapter_if.c +++ b/usb/ddk/device/src/adapter_if.c @@ -978,7 +978,6 @@ static int32_t UsbFnAdapterCreateDevice(const char *udcName, const char *devName uint8_t confVal; UsbFnAdapterCleanDevice(devName); - ret = CreatDeviceDir(devName); if (ret != HDF_SUCCESS) { return HDF_ERR_IO; diff --git a/usb/ddk/device/src/usb_accessory_uevent_handle.c b/usb/ddk/device/src/usb_accessory_uevent_handle.c new file mode 100644 index 0000000000..eccf4de916 --- /dev/null +++ b/usb/ddk/device/src/usb_accessory_uevent_handle.c @@ -0,0 +1,98 @@ +/* + * Copyright (c) Huawei Technologies Co., Ltd. 2024. All rights reserved. + * 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 "usb_accessory_uevent_handle.h" +#include "hdf_base.h" +#include "hdf_log.h" +#include "usbd_wrapper.h" +#include "ddk_pnp_listener_mgr.h" + +#define HDF_LOG_TAG usb_accessory_uevent + +char *g_usbAccessoryUeventPath = "invalid_path"; + +struct UsbAccessoryUeventInfo { + const char *devPath; + const char *subSystem; + const char *accessory; + const char *devName; +}; + +static void UsbAccessoryDispatchUevent(const struct UsbAccessoryUeventInfo *info) +{ + HDF_LOGD("%{public}s: devPath: %{public}s, accessory: %{public}s", __func__, info->devPath, info->accessory); + if (strcmp(info->devPath, g_usbAccessoryUeventPath) != 0) { + return; + } + if (strcmp(info->accessory, "START") == 0) { + DdkListenerMgrNotifyAll(NULL, USB_ACCESSORY_START); + } else if (strcmp(info->accessory, "SEND") == 0) { + DdkListenerMgrNotifyAll(NULL, USB_ACCESSORY_SEND); + } +} + +void UsbAccessoryUeventHandle(const char msg[], ssize_t rcvLen) +{ + HDF_LOGD("%{public}s: msg: %{public}s, len: %{public}zd", __func__, msg, rcvLen); + char fullMsg[rcvLen + 1]; + for (int i = 0; i < rcvLen; i++) { + if (msg[i] == '\0') { + fullMsg[i] = ' '; + } else { + fullMsg[i] = msg[i]; + } + } + fullMsg[rcvLen] = '\0'; + HDF_LOGD("%{public}s:Full message: %{public}s", __func__, fullMsg); + + struct UsbAccessoryUeventInfo info = { + .devPath = "", + .subSystem = "", + .accessory = "", + .devName = "" + }; + const char *msgTmp = msg; + while (*msgTmp && (msgTmp - msg < rcvLen)) { + if (strncmp(msgTmp, "DEVPATH=", strlen("DEVPATH=")) == 0) { + msgTmp += strlen("DEVPATH="); + info.devPath = msgTmp; + } else if (strncmp(msgTmp, "SUBSYSTEM=", strlen("SUBSYSTEM=")) == 0 && + strlen(info.subSystem) == 0) { // some uevent has more than one SUBSYSTEM property + msgTmp += strlen("SUBSYSTEM="); + info.subSystem = msgTmp; + } else if (strncmp(msgTmp, "ACCESSORY=", strlen("ACCESSORY=")) == 0) { + msgTmp += strlen("ACCESSORY="); + info.accessory = msgTmp; + } else if (strncmp(msgTmp, "DEVNAME=", strlen("DEVNAME=")) == 0) { + msgTmp += strlen("DEVNAME="); + info.devName = msgTmp; + } + msgTmp += strlen(msgTmp) + 1; // 1 is a skip character '\0' + } + + UsbAccessoryDispatchUevent(&info); +} + +int32_t UsbAccessoryUeventInit(const char *ueventPath) +{ + if (ueventPath == NULL) { + HDF_LOGE("%{public}s invalid param", __func__); + return HDF_ERR_INVALID_PARAM; + } + HDF_LOGD("%{public}s: enter, ueventPath: %{public}s", __func__, ueventPath); + + g_usbAccessoryUeventPath = (char *)ueventPath; + return HDF_SUCCESS; +} diff --git a/usb/ddk/device/src/usbfn_uevent_handle.c b/usb/ddk/device/src/usbfn_uevent_handle.c index 376b78b3e2..227fb9c7e4 100644 --- a/usb/ddk/device/src/usbfn_uevent_handle.c +++ b/usb/ddk/device/src/usbfn_uevent_handle.c @@ -111,7 +111,7 @@ void UsbFnHandleUevent(const char msg[], ssize_t rcvLen) int32_t UsbFnUeventInit(const char *gadgetEventPath) { if (gadgetEventPath == NULL) { - HDF_LOGE("%{puiblic}s invalid param", __func__); + HDF_LOGE("%{public}s invalid param", __func__); return HDF_ERR_INVALID_PARAM; } diff --git a/usb/ddk/host/include/usb_raw_api_library.h b/usb/ddk/host/include/usb_raw_api_library.h index ba80748684..5b196d8f8a 100644 --- a/usb/ddk/host/include/usb_raw_api_library.h +++ b/usb/ddk/host/include/usb_raw_api_library.h @@ -140,11 +140,10 @@ int32_t RawClaimInterfaceForce(struct UsbDeviceHandle *devHandle, uint32_t inter void RawAttachKernelDriver(struct UsbDeviceHandle *devHandle, uint8_t interfaceNumber); int32_t RawAttachInterface(struct UsbDeviceHandle *devHandle, uint32_t interfaceNumber); int32_t RawDetachInterface(struct UsbDeviceHandle *devHandle, uint32_t interfaceNumber); - -int32_t RawUsbControlMsg(const struct UsbDeviceHandle *devHandle, struct UsbControlRequestData *ctrlData); int32_t RawUsbGetUsbSpeed(const struct UsbDeviceHandle *devHandle); bool RawGetInterfaceActiveStatus(struct UsbDeviceHandle *devHandle, uint32_t interfaceNumber); int32_t RawUsbCloseCtlProcess(const UsbInterfaceHandle *interfaceHandle); +int32_t RawUsbControlMsg(const struct UsbDeviceHandle *devHandle, struct UsbControlRequestData *ctrlData); #ifdef __cplusplus } diff --git a/usb/ddk/host/src/ddk_uevent_handle.c b/usb/ddk/host/src/ddk_uevent_handle.c index 8bb3e8f39f..3cf1aaacba 100644 --- a/usb/ddk/host/src/ddk_uevent_handle.c +++ b/usb/ddk/host/src/ddk_uevent_handle.c @@ -32,6 +32,7 @@ #include "securec.h" #include "usbfn_uevent_handle.h" #include "usbd_wrapper.h" +#include "usb_accessory_uevent_handle.h" #define HDF_LOG_TAG usb_ddk_uevent @@ -190,6 +191,7 @@ void *DdkUeventMain(void *param) } DdkHandleUevent(msg, rcvLen); UsbFnHandleUevent(msg, rcvLen); + UsbAccessoryUeventHandle(msg, rcvLen); } else if (((uint32_t)fd.revents & POLLERR) == POLLERR) { HDF_LOGE("usb event poll error"); } diff --git a/usb/ddk/host/src/usb_io_manage.c b/usb/ddk/host/src/usb_io_manage.c index 4f22591e30..a10d480894 100644 --- a/usb/ddk/host/src/usb_io_manage.c +++ b/usb/ddk/host/src/usb_io_manage.c @@ -97,10 +97,17 @@ static int32_t IoSendProcess(const void *interfacePoolArg) continue; } } - HDF_LOGE("%{public}s, stop. errorTimes=%{public}d", __func__, errorTimes); + HDF_LOGD("%{public}s, stop. errorTimes=%{public}d", __func__, errorTimes); return 0; } +static void InitializeIoProcess(struct UsbInterfacePool *interfacePool) +{ + if (!interfacePool->ioProcessTid) { + interfacePool->ioProcessTid = RawGetTid(); + } +} + static int32_t IoAsyncReceiveProcess(const void *interfacePoolArg) { if (interfacePoolArg == NULL) { @@ -115,10 +122,7 @@ static int32_t IoAsyncReceiveProcess(const void *interfacePoolArg) HDF_LOGD("%{public}s, enter recv thread", __func__); while (true) { - if (!interfacePool->ioProcessTid) { - interfacePool->ioProcessTid = RawGetTid(); - } - + InitializeIoProcess(interfacePool); if (interfacePool->device == NULL) { HDF_LOGE("%{public}s:%{public}d interfacePool->device is NULL!", __func__, __LINE__); OsalMSleep(USB_IO_SLEEP_MS_TIME); @@ -142,13 +146,18 @@ static int32_t IoAsyncReceiveProcess(const void *interfacePoolArg) } ret = RawHandleRequest(interfacePool->device->devHandle); + if (ret == HDF_DEV_ERR_NO_DEVICE) { + HDF_LOGE("%{public}s dev is not found ret: %{public}d", __func__, ret); + break; + } + if (ret < 0) { HDF_LOGE("%{public}s RawHandleRequest failed ret: %{public}d", __func__, ret); OsalMSleep(USB_IO_SLEEP_MS_TIME); continue; } } - HDF_LOGE("%{public}s, recv thread end. ", __func__); + HDF_LOGD("%{public}s, recv thread end. ", __func__); OsalMutexLock(&interfacePool->ioStopLock); interfacePool->ioProcessStopStatus = USB_POOL_PROCESS_STOPED; interfacePool->ioRecvProcessStopStatus = USB_POOL_PROCESS_STOPED; @@ -228,7 +237,8 @@ HDF_STATUS UsbIoGetRequest(const struct UsbMessageQueue *msgQueue, struct UsbHos } OsalMutexLock((struct OsalMutex *)&msgQueue->mutex); - if (msgQueue->entry.next == NULL || msgQueue->entry.next->prev == NULL || msgQueue->entry.prev == NULL || msgQueue->entry.prev->next == NULL) { + if (msgQueue->entry.next == NULL || msgQueue->entry.next->prev == NULL || + msgQueue->entry.prev == NULL || msgQueue->entry.prev->next == NULL) { ret = HDF_ERR_INVALID_OBJECT; OsalMutexUnlock((struct OsalMutex *)&msgQueue->mutex); goto ERROR; diff --git a/usb/ddk/host/src/usb_pnp_manager.c b/usb/ddk/host/src/usb_pnp_manager.c index 318e84a1fb..7b8a240c1e 100644 --- a/usb/ddk/host/src/usb_pnp_manager.c +++ b/usb/ddk/host/src/usb_pnp_manager.c @@ -30,13 +30,16 @@ #include "securec.h" #include "usb_ddk_pnp_loader.h" #include "usbd_wrapper.h" +#include "usb_accessory_uevent_handle.h" #define HDF_LOG_TAG usb_pnp_manager #define MODULENAMESIZE 128 +const char USB_ACCESSORY_UEVENT_PATH[] = "usb_accessory_uevent_path"; +const char USB_ACCESSORY_DEFAULT_PATH[] = "/devices/virtual/misc/usb_accessory"; +#define USB_GADGET_UEVENT_PATH "gadget_uevent_path" +#define USB_GADGET_STATE_PATH "gadget_state_path" #ifdef USB_EMULATOR_MODE -#define USB_GADGET_STATE_PATH "gadget_state_path" -#define USB_GADGET_UEVENT_PATH "gadget_uevent_path" const char USB_EMULATOR_DEFAULT_STATE_PATH[] = "/sys/class/gadget_usb/gadget0/state"; const char USB_EMULATOR_DEFAULT_UEVENT_PATH[] = "/devices/virtual/gadget_usb/gadget0"; #endif @@ -118,21 +121,47 @@ static const char *UsbPnpMgrGetGadgetPath(struct HdfDeviceObject *device, const if (strncmp(attrName, USB_GADGET_STATE_PATH, strlen(USB_GADGET_STATE_PATH)) == 0) { path = USB_EMULATOR_DEFAULT_STATE_PATH; + } else if (strncmp(attrName, USB_ACCESSORY_UEVENT_PATH, strlen(USB_ACCESSORY_UEVENT_PATH)) == 0) { + path = USB_ACCESSORY_DEFAULT_PATH; } else { path = USB_EMULATOR_DEFAULT_UEVENT_PATH; } } #else if (iface->GetString(device->property, attrName, &path, pathDef) != HDF_SUCCESS) { - HDF_LOGE("%{public}s: read %{public}s failed", __func__, attrName); - return NULL; + HDF_LOGW("%{public}s: emulator read %{public}s failed", __func__, attrName); + if (strncmp(attrName, USB_ACCESSORY_UEVENT_PATH, strlen(USB_ACCESSORY_UEVENT_PATH)) == 0) { + path = USB_ACCESSORY_DEFAULT_PATH; + } } #endif return path; } +static int32_t DdkUeventAndAccessoryInit(struct HdfDeviceObject *device) +{ + if (device == NULL) { + HDF_LOGE("%{public}s: device is NULL", __func__); + return HDF_FAILURE; + } + int32_t ret = DdkUeventInit(UsbPnpMgrGetGadgetPath(device, USB_GADGET_UEVENT_PATH)); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s: DdkUeventInit error", __func__); + return ret; + } + + ret = UsbAccessoryUeventInit(UsbPnpMgrGetGadgetPath(device, USB_ACCESSORY_UEVENT_PATH)); + if (ret != HDF_SUCCESS) { + HDF_LOGD("%{public}s: UsbAccessoryUeventInit error, ret=%{public}d", __func__, ret); + return ret; + } + + return HDF_SUCCESS; +} + static int32_t UsbPnpManagerInit(struct HdfDeviceObject *device) { + HDF_LOGD("%{public}s: enter", __func__); static struct HdfDevEventlistener usbPnpListener = { .callBack = UsbDdkPnpLoaderEventReceived, }; @@ -150,11 +179,12 @@ static int32_t UsbPnpManagerInit(struct HdfDeviceObject *device) return HDF_FAILURE; } - ret = DdkUeventInit(UsbPnpMgrGetGadgetPath(device, "gadget_uevent_path")); + ret = DdkUeventAndAccessoryInit(device); if (ret != HDF_SUCCESS) { - HDF_LOGE("%{public}s: DdkUeventInit error", __func__); + HDF_LOGE("%{public}s: DdkUeventAndAccessoryInit error, ret=%{public}d", __func__, ret); return ret; } + #ifdef USB_EVENT_NOTIFY_LINUX_NATIVE_MODE if (UsbPnpManagerStartUeventThread() != HDF_SUCCESS) { HDF_LOGE("%{public}s: start uevent thread failed", __func__); diff --git a/usb/ddk/host/src/usb_raw_api_library.c b/usb/ddk/host/src/usb_raw_api_library.c index 03fcd7bc40..48317239a4 100644 --- a/usb/ddk/host/src/usb_raw_api_library.c +++ b/usb/ddk/host/src/usb_raw_api_library.c @@ -597,8 +597,7 @@ static int32_t ParseConfiguration(struct UsbRawConfigDescriptor *config, const u ParseDescriptor(buffer, USB_RAW_CONFIG_DESCRIPTOR_TYPE, config); if ((config->configDescriptor.bDescriptorType != USB_DDK_DT_CONFIG) || - (config->configDescriptor.bLength < USB_DDK_DT_CONFIG_SIZE) || - (config->configDescriptor.bLength > (uint8_t)size) || + (config->configDescriptor.bLength != USB_DDK_DT_CONFIG_SIZE) || (config->configDescriptor.bNumInterfaces > USB_MAXINTERFACES)) { HDF_LOGE("%{public}s:%{public}d invalid descriptor: type = 0x%{public}x, length = %{public}u", __func__, __LINE__, config->configDescriptor.bDescriptorType, config->configDescriptor.bLength); diff --git a/usb/ddk_service/src/usb_ddk_service.cpp b/usb/ddk_service/src/usb_ddk_service.cpp index 65da66a7c9..e83f218215 100644 --- a/usb/ddk_service/src/usb_ddk_service.cpp +++ b/usb/ddk_service/src/usb_ddk_service.cpp @@ -446,6 +446,7 @@ int32_t UsbDdkService::SendPipeRequestWithAshmem( { if (!DdkPermissionManager::VerifyPermission(PERMISSION_NAME)) { HDF_LOGE("%{public}s: no permission", __func__); + close(ashmem.ashmemFd); return HDF_ERR_NOPERM; } @@ -454,6 +455,7 @@ int32_t UsbDdkService::SendPipeRequestWithAshmem( int32_t ret = UsbDdkUnHash(pipe.interfaceHandle, handle); if (ret != HDF_SUCCESS) { HDF_LOGE("%{public}s unhash failed %{public}d", __func__, ret); + close(ashmem.ashmemFd); return ret; } @@ -461,6 +463,7 @@ int32_t UsbDdkService::SendPipeRequestWithAshmem( struct UsbRequest *request = UsbAllocRequestByAshmem(handleConvert, 0, ashmem.size, ashmem.ashmemFd); if (request == nullptr) { HDF_LOGE("%{public}s alloc request failed", __func__); + close(ashmem.ashmemFd); return HDF_DEV_ERR_NO_MEMORY; } @@ -487,6 +490,7 @@ int32_t UsbDdkService::SendPipeRequestWithAshmem( transferredLength = request->compInfo.actualLength; FINISHED: (void)UsbFreeRequestByMmap(request); + close(ashmem.ashmemFd); return ret; } diff --git a/usb/gadget/function/mtp/include/usbfn_mtp_impl.h b/usb/gadget/function/mtp/include/usbfn_mtp_impl.h index 6948a35f45..a188184f1f 100644 --- a/usb/gadget/function/mtp/include/usbfn_mtp_impl.h +++ b/usb/gadget/function/mtp/include/usbfn_mtp_impl.h @@ -19,6 +19,7 @@ #include #include #include +#include #include "data_fifo.h" #include "hdf_base.h" @@ -101,6 +102,7 @@ struct UsbMtpPort { struct UsbMtpDevice *mtpDev; struct DListHead readPool; /* ready/idle read(bulk-out) req */ struct DListHead readQueue; /* working async read(bulk-out) req */ + struct UsbFnRequest *standbyReq; int32_t readStarted; int32_t readAllocated; struct DataFifo readFifo; @@ -197,10 +199,12 @@ private: static int32_t UsbMtpPortStartSubmitRxReq(struct UsbMtpPort *mtpPort, bool needZLP); static int32_t UsbMtpPortStartRxAsync(struct UsbMtpPort *mtpPort); static int32_t UsbMtpPortRxCheckReq(struct UsbMtpPort *mtpPort, struct UsbFnRequest *req, bool &writeToFile); - + static void UsbMtpPortReleaseRxReq(struct UsbMtpPort *mtpPort, struct UsbFnRequest *req); + static void UsbMtpPortReleaseTxReq(struct UsbMtpPort *mtpPort, struct UsbFnRequest *req); static int32_t UsbMtpPortCancelAndFreeReq( struct DListHead *queueHead, struct DListHead *poolHead, int32_t &allocated, bool freeReq); static int32_t UsbMtpPortCancelPlusFreeIo(struct UsbMtpPort *mtpPort, bool freeReq); + static int32_t UsbMtpPortCancelRequest(struct UsbMtpPort *mtpPort); static struct UsbFnRequest *UsbMtpDeviceGetCtrlReq(struct UsbMtpDevice *mtpDev); static int32_t UsbMtpDeviceStandardRequest( struct UsbMtpDevice *mtpDev, struct UsbFnCtrlRequest *setup, struct UsbFnRequest *req); @@ -214,7 +218,7 @@ private: static int32_t UsbMtpDeviceEnable(struct UsbMtpDevice *mtpDev); static int32_t UsbMtpDeviceDisable(struct UsbMtpDevice *mtpDev); static void UsbMtpDeviceEp0EventDispatch(struct UsbFnEvent *event); - + static void CopyReqToStandbyReqPool(const struct UsbFnRequest *req, struct UsbFnRequest *standbyReq); int32_t UsbMtpDeviceAllocCtrlRequests(int32_t num); void UsbMtpDeviceFreeCtrlRequests(); void UsbMtpPortFreeRequests(struct DListHead *head, int32_t &allocated); @@ -231,8 +235,11 @@ private: int32_t UsbMtpDeviceFree(); int32_t UsbMtpDeviceAllocNotifyRequest(); void UsbMtpDeviceFreeNotifyRequest(); - + int32_t InitMtpPort(); int32_t WriteEx(const std::vector &data, uint8_t sendZLP, uint32_t &xferActual); + int32_t WriteSplitPacket(const std::vector &data); + int32_t getActualLength(const std::vector &data); + int32_t ReadImpl(std::vector &data); int32_t UsbMtpPortSendFileFillFirstReq(struct UsbFnRequest *req, uint64_t &oneReqLeft); int32_t UsbMtpPortSendFileEx(); int32_t UsbMtpPortSendFileLeftAsync(uint64_t oneReqLeft); @@ -241,12 +248,18 @@ private: uint32_t BufCopyToVector(void *buf, uint32_t bufSize, std::vector &vectorData); uint32_t BufCopyFromVector( void *buf, uint32_t bufSize, const std::vector &vectorData, uint32_t vectorOffset); - + void UsbMtpSendFileParamSet(const UsbFnMtpFileSlice &mfs); static struct UsbMtpDevice *mtpDev_; static struct UsbMtpPort *mtpPort_; - static std::mutex mtpRunning_; + static std::mutex startMutex_; + static std::mutex readMutex_; + static std::mutex writeMutex_; + static std::mutex eventMutex_; static std::mutex asyncMutex_; static sem_t asyncReq_; + static pthread_rwlock_t mtpRunrwLock_; + std::vector vectorSplited_; + size_t writeActualLen_; }; } // namespace V1_0 } // namespace Mtp diff --git a/usb/gadget/function/mtp/src/usbfn_mtp_impl.cpp b/usb/gadget/function/mtp/src/usbfn_mtp_impl.cpp index 097a1667cf..a459be25d9 100755 --- a/usb/gadget/function/mtp/src/usbfn_mtp_impl.cpp +++ b/usb/gadget/function/mtp/src/usbfn_mtp_impl.cpp @@ -26,6 +26,8 @@ #define HDF_LOG_TAG usbfn_mtp_impl #define UDC_NAME "invalid_udc_name" +#undef LOG_DOMAIN +#define LOG_DOMAIN 0xD002518 /* Compatible: Microsoft MTP OS String */ static uint8_t g_mtpOsString[] = {18, /* sizeof(mtp_os_string) */ @@ -106,7 +108,11 @@ extern "C" void *UsbfnMtpInterfaceImplGetInstance(void) struct UsbMtpDevice *UsbfnMtpImpl::mtpDev_ = nullptr; struct UsbMtpPort *UsbfnMtpImpl::mtpPort_ = nullptr; -std::mutex UsbfnMtpImpl::mtpRunning_; +pthread_rwlock_t UsbfnMtpImpl::mtpRunrwLock_ = PTHREAD_RWLOCK_INITIALIZER; +std::mutex UsbfnMtpImpl::startMutex_; +std::mutex UsbfnMtpImpl::readMutex_; +std::mutex UsbfnMtpImpl::writeMutex_; +std::mutex UsbfnMtpImpl::eventMutex_; std::mutex UsbfnMtpImpl::asyncMutex_; sem_t UsbfnMtpImpl::asyncReq_ {0}; @@ -117,6 +123,12 @@ constexpr uint64_t MTP_MAX_FILE_SIZE = 0xFFFFFFFFULL; constexpr uint32_t WRITE_FILE_TEMP_SLICE = 100 * 1024; /* 100KB */ static constexpr int32_t WAIT_UDC_MAX_LOOP = 3; static constexpr uint32_t WAIT_UDC_TIME = 100000; +static constexpr uint32_t REQ_ACTUAL_DEFAULT_LENGTH = 0; +static constexpr uint32_t REQ_ACTUAL_MAX_LENGTH = 128; +static constexpr uint32_t REQ_ACTUAL_MININUM_LENGTH = 5; +static constexpr int32_t HDF_ERROR_ECANCEL = -20; +static constexpr int32_t WRITE_SPLIT_MININUM_LENGTH = 81920; +static constexpr int32_t MTP_PROTOCOL_PACKET_SIZE = 4; enum UsbMtpNeedZeroLengthPacket { ZLP_NO_NEED = 0, /* no need send ZLP */ ZLP_NEED, /* need send ZLP */ @@ -138,22 +150,55 @@ void UsbfnMtpImpl::UsbFnRequestReadComplete(uint8_t pipe, struct UsbFnRequest *r HDF_LOGE("%{public}s: invalid param", __func__); return; } + pthread_rwlock_rdlock(&mtpRunrwLock_); struct UsbMtpPort *mtpPort = static_cast(req->context); - DListRemove(&req->list); - DListInsertTail(&req->list, &mtpPort->readPool); - mtpPort->readStarted--; - if (mtpPort->mtpDev == nullptr) { + if (mtpPort_ == nullptr || mtpDev_ == nullptr || + mtpPort == nullptr || mtpPort->mtpDev == nullptr) { + pthread_rwlock_unlock(&mtpRunrwLock_); HDF_LOGE("%{public}s: invalid content", __func__); return; } + UsbMtpPortReleaseRxReq(mtpPort, req); + if (mtpPort->mtpDev->mtpState == MTP_STATE_CANCELED) { + CopyReqToStandbyReqPool(req, mtpPort->standbyReq); + pthread_rwlock_unlock(&mtpRunrwLock_); + HDF_LOGD("%{public}s, mtpState: %{public}d.", __func__, mtpPort->mtpDev->mtpState); + return; + } int32_t ret = UsbMtpPortRxPush(mtpPort, req); if (ret != HDF_SUCCESS) { HDF_LOGW("%{public}s: rx push failed(%{%{public}d/%{public}d}): %{public}d, state=%{public}hhu", __func__, mtpPort->readStarted, mtpPort->readAllocated, ret, mtpPort->mtpDev->mtpState); } + std::lock_guard guard(asyncMutex_); if (mtpPort->readStarted == 0 && mtpPort->writeStarted == 0 && mtpPort->mtpDev->mtpState == MTP_STATE_CANCELED) { mtpPort->mtpDev->mtpState = MTP_STATE_READY; } + pthread_rwlock_unlock(&mtpRunrwLock_); +} + +void UsbfnMtpImpl::UsbMtpPortReleaseRxReq(struct UsbMtpPort *mtpPort, struct UsbFnRequest *req) +{ + std::lock_guard guard(asyncMutex_); + + if (mtpPort->suspended) { + return; + } + DListRemove(&req->list); + DListInsertTail(&req->list, &mtpPort->readPool); + mtpPort->readStarted--; +} + +void UsbfnMtpImpl::UsbMtpPortReleaseTxReq(struct UsbMtpPort *mtpPort, struct UsbFnRequest *req) +{ + std::lock_guard guard(asyncMutex_); + + if (mtpPort->suspended) { + return; + } + DListRemove(&req->list); + DListInsertTail(&req->list, &mtpPort->writePool); + mtpPort->writeStarted--; } void UsbfnMtpImpl::UsbFnRequestWriteComplete(uint8_t pipe, struct UsbFnRequest *req) @@ -163,14 +208,20 @@ void UsbfnMtpImpl::UsbFnRequestWriteComplete(uint8_t pipe, struct UsbFnRequest * HDF_LOGE("%{public}s: invalid param", __func__); return; } + pthread_rwlock_rdlock(&mtpRunrwLock_); struct UsbMtpPort *mtpPort = static_cast(req->context); - DListRemove(&req->list); - DListInsertTail(&req->list, &mtpPort->writePool); - if (mtpPort->mtpDev == nullptr) { + if (mtpPort_ == nullptr || mtpDev_ == nullptr || + mtpPort == nullptr || mtpPort->mtpDev == nullptr) { + pthread_rwlock_unlock(&mtpRunrwLock_); HDF_LOGE("%{public}s: invalid content", __func__); return; } - mtpPort->writeStarted--; + UsbMtpPortReleaseTxReq(mtpPort, req); + if (mtpPort->mtpDev->mtpState == MTP_STATE_CANCELED) { + pthread_rwlock_unlock(&mtpRunrwLock_); + HDF_LOGD("%{public}s, mtpState: %{public}d.", __func__, mtpPort->mtpDev->mtpState); + return; + } int32_t ret = UsbMtpPortTxReqCheck(mtpPort, req); if (ret != HDF_SUCCESS) { HDF_LOGW("%{public}s: tx check failed(%{%{public}d/%{public}d}): %{public}d, state=%{public}hhu", __func__, @@ -179,6 +230,7 @@ void UsbfnMtpImpl::UsbFnRequestWriteComplete(uint8_t pipe, struct UsbFnRequest * if (mtpPort->readStarted == 0 && mtpPort->writeStarted == 0 && mtpPort->mtpDev->mtpState == MTP_STATE_CANCELED) { mtpPort->mtpDev->mtpState = MTP_STATE_READY; } + pthread_rwlock_unlock(&mtpRunrwLock_); } void UsbfnMtpImpl::UsbFnRequestNotifyComplete(uint8_t pipe, struct UsbFnRequest *req) @@ -197,25 +249,29 @@ void UsbfnMtpImpl::UsbFnRequestCtrlComplete(uint8_t pipe, struct UsbFnRequest *r HDF_LOGE("%{public}s: invalid param", __func__); return; } + pthread_rwlock_rdlock(&mtpRunrwLock_); struct CtrlInfo *ctrlInfo = static_cast(req->context); - struct UsbMtpDevice *mtpDev = ctrlInfo->mtpDev; - if (mtpDev == nullptr) { + if (mtpPort_ == nullptr || mtpDev_ == nullptr || + ctrlInfo == nullptr || ctrlInfo->mtpDev == nullptr) { + pthread_rwlock_unlock(&mtpRunrwLock_); HDF_LOGE("%{public}s: invalid content", __func__); return; } + struct UsbMtpDevice *mtpDev = ctrlInfo->mtpDev; switch (req->status) { case USB_REQUEST_COMPLETED: break; case USB_REQUEST_NO_DEVICE: - HDF_LOGV("%{public}s: usb mtpDev device was disconnected", __func__); + HDF_LOGW("%{public}s: usb mtpDev device was disconnected", __func__); mtpDev->mtpState = MTP_STATE_OFFLINE; break; default: - HDF_LOGV("%{public}s: unexpected status %{public}d", __func__, req->status); + HDF_LOGW("%{public}s: unexpected status %{public}d", __func__, req->status); mtpDev->mtpState = MTP_STATE_ERROR; break; } DListInsertTail(&req->list, &mtpDev->ctrlPool); + pthread_rwlock_unlock(&mtpRunrwLock_); } int32_t UsbfnMtpImpl::UsbMtpPortTxReqCheck(struct UsbMtpPort *mtpPort, struct UsbFnRequest *req) @@ -226,7 +282,7 @@ int32_t UsbfnMtpImpl::UsbMtpPortTxReqCheck(struct UsbMtpPort *mtpPort, struct Us mtpDev->asyncSendFileActual += static_cast(req->actual); if (mtpDev->asyncSendFileActual == mtpDev->xferFileLength && ((req->actual == 0 && mtpDev->needZLP == ZLP_TRY) || mtpDev->needZLP == ZLP_NO_NEED)) { - HDF_LOGV("%{public}s: async tx done: req(%{public}d/%{public}d)%{public}u/%{public}u, send " + HDF_LOGD("%{public}s: async tx done: req(%{public}d/%{public}d)%{public}u/%{public}u, send " "%{public}" PRIu64 "/%{public}" PRIu64 "/%{public}" PRIu64 ", ZLP=%{public}hhu", __func__, mtpPort->writeStarted, mtpPort->writeAllocated, req->actual, req->length, mtpDev->asyncSendFileExpect, mtpDev->asyncSendFileActual, mtpDev->xferFileLength, mtpDev->needZLP); @@ -235,12 +291,12 @@ int32_t UsbfnMtpImpl::UsbMtpPortTxReqCheck(struct UsbMtpPort *mtpPort, struct Us } return UsbMtpPortStartTxAsync(mtpPort, true); case USB_REQUEST_NO_DEVICE: - HDF_LOGV("%{public}s: tx req return disconnected", __func__); + HDF_LOGW("%{public}s: tx req return disconnected", __func__); mtpPort->mtpDev->mtpState = MTP_STATE_OFFLINE; sem_post(&asyncReq_); return HDF_DEV_ERR_NO_DEVICE; default: - HDF_LOGV("%{public}s: unexpected status %{public}d", __func__, req->status); + HDF_LOGW("%{public}s: unexpected status %{public}d", __func__, req->status); mtpPort->mtpDev->mtpState = MTP_STATE_ERROR; sem_post(&asyncReq_); return HDF_ERR_IO; @@ -391,7 +447,13 @@ int32_t UsbfnMtpImpl::UsbMtpPortAllocReadWriteRequests(int32_t readSize, int32_t DListInsertTail(&req->list, &mtpPort_->readPool); mtpPort_->readAllocated++; } - + mtpPort_->standbyReq = UsbFnAllocRequest(mtpDev_->dataIface.handle, + mtpDev_->dataOutPipe.id, mtpDev_->dataOutPipe.maxPacketSize); + if (mtpPort_->standbyReq == nullptr) { + HDF_LOGE("%{public}s: alloc standbyReq failed", __func__); + return HDF_ERR_MALLOC_FAIL; + } + mtpPort_->standbyReq->actual = REQ_ACTUAL_DEFAULT_LENGTH; for (i = 0; i < writeSize; ++i) { req = UsbFnAllocRequest(mtpDev_->dataIface.handle, mtpDev_->dataInPipe.id, mtpDev_->dataInPipe.maxPacketSize); if (req == nullptr) { @@ -454,6 +516,31 @@ int32_t UsbfnMtpImpl::UsbMtpPortCancelPlusFreeIo(struct UsbMtpPort *mtpPort, boo return HDF_SUCCESS; } +int32_t UsbfnMtpImpl::UsbMtpPortCancelRequest(struct UsbMtpPort *mtpPort) +{ + DListHead *queueHead = &(mtpPort->readQueue); + if (!DListIsEmpty(queueHead)) { + HDF_LOGD("%{public}s: readQueue is not empty", __func__); + struct UsbFnRequest *queueReq = nullptr; + struct UsbFnRequest *queueReqTmp = nullptr; + DLIST_FOR_EACH_ENTRY_SAFE(queueReq, queueReqTmp, queueHead, struct UsbFnRequest, list) { + (void)UsbFnCancelRequest(queueReq); + HDF_LOGD("%{public}s:cancel read, req:%{public}p", __func__, queueReq); + } + } + DListHead *writeQueue = &(mtpPort->writeQueue); + if (!DListIsEmpty(writeQueue)) { + HDF_LOGD("%{public}s: writeQueue is not empty", __func__); + struct UsbFnRequest *queueReq = nullptr; + struct UsbFnRequest *queueReqTmp = nullptr; + DLIST_FOR_EACH_ENTRY_SAFE(queueReq, queueReqTmp, writeQueue, struct UsbFnRequest, list) { + (void)UsbFnCancelRequest(queueReq); + HDF_LOGD("%{public}s:cancel write, req:%{public}p", __func__, queueReq); + } + } + return HDF_SUCCESS; +} + int32_t UsbfnMtpImpl::UsbMtpPortReleaseIo() { return UsbMtpPortCancelPlusFreeIo(mtpPort_, true); @@ -501,7 +588,28 @@ int32_t UsbfnMtpImpl::UsbMtpDeviceClassRequest( HDF_LOGI("%{public}s: Class Request-MTP_REQ_CANCEL", __func__); if (mtpDev->mtpState == MTP_STATE_BUSY) { mtpDev->mtpState = MTP_STATE_CANCELED; - (void)UsbMtpPortCancelPlusFreeIo(mtpDev->mtpPort, false); + DListHead *queueHead = &(mtpDev->mtpPort->readQueue); + if (!DListIsEmpty(queueHead)) { + HDF_LOGD("%{public}s: readQueue is not empty", __func__); + struct UsbFnRequest *queueReq = nullptr; + struct UsbFnRequest *queueReqTmp = nullptr; + DLIST_FOR_EACH_ENTRY_SAFE(queueReq, queueReqTmp, queueHead, struct UsbFnRequest, list) { + (void)UsbFnCancelRequest(queueReq); + HDF_LOGD("%{public}s:cancel read, req:%{public}p", __func__, req); + } + } + DListHead *writeQueue = &(mtpDev->mtpPort->writeQueue); + if (!DListIsEmpty(writeQueue)) { + HDF_LOGD("%{public}s: writeQueue is not empty", __func__); + struct UsbFnRequest *queueReq = nullptr; + struct UsbFnRequest *queueReqTmp = nullptr; + DLIST_FOR_EACH_ENTRY_SAFE(queueReq, queueReqTmp, writeQueue, struct UsbFnRequest, list) { + (void)UsbFnCancelRequest(queueReq); + HDF_LOGD("%{public}s:cancel write, req:%{public}p", __func__, req); + } + } + HDF_LOGD("%{public}s:async post, readStart:%{public}d", __func__, mtpDev->mtpPort->readStarted); + sem_post(&asyncReq_); } } else if (setup->request == USB_MTP_REQ_GET_DEVICE_STATUS && setup->index == 0 && setup->value == 0) { HDF_LOGI("%{public}s: Class Request-MTP_REQ_GET_DEVICE_STATUS", __func__); @@ -549,7 +657,7 @@ int32_t UsbfnMtpImpl::UsbMtpDeviceSetup(struct UsbMtpDevice *mtpDev, struct UsbF if (mtpDev == nullptr || mtpDev->mtpPort == nullptr || setup == nullptr) { return HDF_ERR_INVALID_PARAM; } - HDF_LOGV( + HDF_LOGD( "%{public}s: Setup: reqType=0x%{public}X, req=0x%{public}X, idx=%{public}d, val=%{public}d, len=%{public}d", __func__, setup->reqType, setup->request, LE16_TO_CPU(setup->index), LE16_TO_CPU(setup->value), LE16_TO_CPU(setup->length)); @@ -596,9 +704,9 @@ void UsbfnMtpImpl::UsbMtpDeviceSuspend(struct UsbMtpDevice *mtpDev) HDF_LOGE("%{public}s: invalid param", __func__); return; } - + std::lock_guard guard(asyncMutex_); mtpPort->suspended = true; - (void)UsbMtpPortCancelPlusFreeIo(mtpPort, false); + (void)UsbMtpPortCancelRequest(mtpPort); } void UsbfnMtpImpl::UsbMtpDeviceResume(struct UsbMtpDevice *mtpDev) @@ -695,6 +803,21 @@ void UsbfnMtpImpl::UsbMtpDeviceEp0EventDispatch(struct UsbFnEvent *event) } } +void UsbfnMtpImpl::CopyReqToStandbyReqPool(const struct UsbFnRequest *req, struct UsbFnRequest *standbyReq) +{ + if (req->actual < REQ_ACTUAL_MININUM_LENGTH || req->actual > REQ_ACTUAL_MAX_LENGTH) { + HDF_LOGE("%{public}s: actual: %{public}d", __func__, req->actual); + return; + } + + standbyReq->actual = req->actual; + standbyReq->type = req->type; + if (memcpy_s(standbyReq->buf, req->actual, req->buf, req->actual) != EOK) { + HDF_LOGE("%{public}s: memcpy_s failed", __func__); + return; + } +} + int32_t UsbfnMtpImpl::UsbMtpDeviceParseEachPipe(struct UsbMtpInterface &iface) { struct UsbFnInterface *fnIface = iface.fn; @@ -910,44 +1033,33 @@ int32_t UsbfnMtpImpl::UsbMtpDeviceFree() int32_t UsbfnMtpImpl::Init() { HDF_LOGI("%{public}s: Init", __func__); + pthread_rwlock_wrlock(&mtpRunrwLock_); + if (mtpDev_ != nullptr) { + pthread_rwlock_unlock(&mtpRunrwLock_); + HDF_LOGI("%{public}s: mtpDev_ is init success", __func__); + return HDF_SUCCESS; + } mtpDev_ = static_cast(OsalMemCalloc(sizeof(struct UsbMtpDevice))); if (mtpDev_ == nullptr) { - HDF_LOGE("%{public}s: Alloc usb mtpDev device failed", __func__); + pthread_rwlock_unlock(&mtpRunrwLock_); + HDF_LOGE("%{public}s: usb mtpDev device failed or not initialized", __func__); return HDF_ERR_MALLOC_FAIL; } - if (mtpDev_->initFlag) { - HDF_LOGE("%{public}s: usb mtpDev is already initialized", __func__); - return HDF_FAILURE; - } + mtpDev_->initFlag = false; int32_t ret = UsbfnMtpImpl::UsbMtpDeviceCreateFuncDevice(); if (ret != HDF_SUCCESS) { HDF_LOGE("%{public}s: UsbMtpDeviceCreateFuncDevice failed", __func__); (void)OsalMemFree(mtpDev_); mtpDev_ = nullptr; + pthread_rwlock_unlock(&mtpRunrwLock_); return ret; } - /* init mtpPort */ - ret = UsbMtpDeviceAlloc(); + ret = InitMtpPort(); if (ret != HDF_SUCCESS) { - HDF_LOGE("%{public}s: UsbMtpDeviceAlloc failed", __func__); - goto ERR; - } - ret = UsbMtpDeviceAllocCtrlRequests(MTP_CTRL_REQUEST_NUM); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%{public}s: UsbMtpDeviceAllocCtrlRequests failed: %{public}d", __func__, MTP_CTRL_REQUEST_NUM); - goto ERR; - } - ret = UsbMtpDeviceAllocNotifyRequest(); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%{public}s: UsbMtpDeviceAllocNotifyRequest failed", __func__); - goto ERR; - } - ret = UsbFnStartRecvInterfaceEvent(mtpDev_->ctrlIface.fn, 0xff, UsbMtpDeviceEp0EventDispatch, mtpDev_); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%{public}s: register event callback failed", __func__); goto ERR; } mtpDev_->initFlag = true; + pthread_rwlock_unlock(&mtpRunrwLock_); HDF_LOGI("%{public}s: Init success", __func__); return HDF_SUCCESS; ERR: @@ -955,56 +1067,106 @@ ERR: (void)UsbMtpDeviceFree(); (void)OsalMemFree(mtpDev_); mtpDev_ = nullptr; + pthread_rwlock_unlock(&mtpRunrwLock_); return ret; } +int32_t UsbfnMtpImpl::InitMtpPort() +{ + /* init mtpPort */ + int32_t ret = UsbMtpDeviceAlloc(); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s: UsbMtpDeviceAlloc failed", __func__); + return HDF_FAILURE; + } + ret = UsbMtpDeviceAllocCtrlRequests(MTP_CTRL_REQUEST_NUM); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s: UsbMtpDeviceAllocCtrlRequests failed: %{public}d", __func__, MTP_CTRL_REQUEST_NUM); + return HDF_FAILURE; + } + ret = UsbMtpDeviceAllocNotifyRequest(); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s: UsbMtpDeviceAllocNotifyRequest failed", __func__); + return HDF_FAILURE; + } + ret = UsbFnStartRecvInterfaceEvent(mtpDev_->ctrlIface.fn, 0xff, UsbMtpDeviceEp0EventDispatch, mtpDev_); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s: register event callback failed", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + int32_t UsbfnMtpImpl::Release() { - HDF_LOGI("%{public}s: Release", __func__); + pthread_rwlock_rdlock(&mtpRunrwLock_); if (mtpPort_ == nullptr || mtpDev_ == nullptr) { + pthread_rwlock_unlock(&mtpRunrwLock_); + HDF_LOGE("%{public}s: no init", __func__); + return HDF_DEV_ERR_DEV_INIT_FAIL; + } + mtpDev_->initFlag = false; + (void)UsbMtpPortCancelRequest(mtpPort_); + pthread_rwlock_unlock(&mtpRunrwLock_); + HDF_LOGI("%{public}s: Release", __func__); + pthread_rwlock_wrlock(&mtpRunrwLock_); + + if (mtpPort_ == nullptr || mtpDev_ == nullptr) { + pthread_rwlock_unlock(&mtpRunrwLock_); HDF_LOGE("%{public}s: no init", __func__); return HDF_DEV_ERR_DEV_INIT_FAIL; } int32_t ret = UsbMtpDeviceReleaseFuncDevice(); if (ret != HDF_SUCCESS) { + pthread_rwlock_unlock(&mtpRunrwLock_); HDF_LOGE("%{public}s: release device failed: %{public}d", __func__, ret); return ret; } ret = UsbMtpDeviceFree(); if (ret != HDF_SUCCESS) { + pthread_rwlock_unlock(&mtpRunrwLock_); HDF_LOGE("%{public}s: free device failed: %{public}d", __func__, ret); return ret; } (void)OsalMemFree(mtpDev_); mtpDev_ = nullptr; + pthread_rwlock_unlock(&mtpRunrwLock_); HDF_LOGI("%{public}s: Release success", __func__); return HDF_SUCCESS; } int32_t UsbfnMtpImpl::Start() { + pthread_rwlock_rdlock(&mtpRunrwLock_); if (mtpPort_ == nullptr || mtpDev_ == nullptr || mtpDev_->initFlag == false) { + pthread_rwlock_unlock(&mtpRunrwLock_); HDF_LOGE("%{public}s: no init", __func__); return HDF_DEV_ERR_DEV_INIT_FAIL; } - std::lock_guard guard(mtpRunning_); - + std::lock_guard guard(startMutex_); mtpDev_->mtpState = MTP_STATE_READY; mtpPort_->startDelayed = true; - return UsbMtpPortInitIo(); + int32_t ret = UsbMtpPortInitIo(); + pthread_rwlock_unlock(&mtpRunrwLock_); + return ret; } int32_t UsbfnMtpImpl::Stop() { - if (mtpPort_ == nullptr || mtpDev_ == nullptr || mtpDev_->initFlag == false) { + pthread_rwlock_rdlock(&mtpRunrwLock_); + if (mtpPort_ == nullptr) { + pthread_rwlock_unlock(&mtpRunrwLock_); HDF_LOGE("%{public}s: no init", __func__); return HDF_DEV_ERR_DEV_INIT_FAIL; } - std::lock_guard guard(mtpRunning_); - + std::lock_guard guard(startMutex_); (void)UsbMtpPortReleaseIo(); mtpPort_->startDelayed = false; - mtpDev_->mtpState = MTP_STATE_OFFLINE; + + if (mtpDev_ != nullptr) { + mtpDev_->mtpState = MTP_STATE_OFFLINE; + } + pthread_rwlock_unlock(&mtpRunrwLock_); return HDF_SUCCESS; } @@ -1028,30 +1190,69 @@ uint32_t UsbfnMtpImpl::BufCopyFromVector( int32_t UsbfnMtpImpl::Read(std::vector &data) { + pthread_rwlock_rdlock(&mtpRunrwLock_); if (mtpPort_ == nullptr || mtpDev_ == nullptr || mtpDev_->initFlag == false) { + pthread_rwlock_unlock(&mtpRunrwLock_); HDF_LOGE("%{public}s: no init", __func__); return HDF_DEV_ERR_DEV_INIT_FAIL; } - std::lock_guard guard(mtpRunning_); - if (mtpDev_->mtpState == MTP_STATE_OFFLINE) { + if (mtpDev_->mtpState == MTP_STATE_OFFLINE || mtpDev_->mtpPort == nullptr || mtpDev_->mtpPort->suspended) { + pthread_rwlock_unlock(&mtpRunrwLock_); HDF_LOGE("%{public}s: device disconnect, no-operation", __func__); return HDF_DEV_ERR_NO_DEVICE; } - struct DListHead *pool = &mtpPort_->readPool; - struct UsbFnRequest *req = DLIST_FIRST_ENTRY(pool, struct UsbFnRequest, list); - if (req == nullptr) { - HDF_LOGE("%{public}s: req invalid", __func__); + if (mtpDev_->mtpState == MTP_STATE_CANCELED) { + mtpDev_->mtpState = MTP_STATE_READY; + pthread_rwlock_unlock(&mtpRunrwLock_); + HDF_LOGE("%{public}s: states is ecanceled", __func__); + return HDF_ERROR_ECANCEL; + } + std::lock_guard guard(readMutex_); + if (mtpDev_->initFlag == false) { + pthread_rwlock_unlock(&mtpRunrwLock_); + HDF_LOGE("%{public}s: dev is release", __func__); return HDF_DEV_ERR_DEV_INIT_FAIL; } - DListRemove(&req->list); - req->length = static_cast(mtpDev_->dataOutPipe.maxPacketSize); - int32_t ret = UsbFnSubmitRequestSync(req, BULK_OUT_TIMEOUT_JIFFIES); - DListInsertTail(&req->list, pool); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%{public}s: send bulk-out sync req failed: %{public}d", __func__, ret); - return ret; + mtpDev_->mtpState = MTP_STATE_BUSY; + int32_t ret = ReadImpl(data); + if (mtpDev_->mtpState == MTP_STATE_CANCELED) { + HDF_LOGE("%{public}s: running, states is ecanceled", __func__); + ret = HDF_ERROR_ECANCEL; + } else if (mtpDev_->mtpState != MTP_STATE_OFFLINE) { + mtpDev_->mtpState = MTP_STATE_READY; } + writeActualLen_ = 0; + vectorSplited_.clear(); + pthread_rwlock_unlock(&mtpRunrwLock_); + return ret; +} + +int32_t UsbfnMtpImpl::ReadImpl(std::vector &data) +{ + int32_t ret = HDF_FAILURE; + struct UsbFnRequest *req = nullptr; + if (mtpPort_->standbyReq != nullptr && mtpPort_->standbyReq->actual >= REQ_ACTUAL_MININUM_LENGTH) { + req = mtpPort_->standbyReq; + } else { + struct DListHead *pool = &mtpPort_->readPool; + req = DLIST_FIRST_ENTRY(pool, struct UsbFnRequest, list); + if (req == nullptr) { + HDF_LOGE("%{public}s: req invalid", __func__); + return HDF_DEV_ERR_DEV_INIT_FAIL; + } + DListRemove(&req->list); + DListInsertTail(&req->list, &mtpPort_->readQueue); + req->length = static_cast(mtpDev_->dataOutPipe.maxPacketSize); + ret = UsbFnSubmitRequestSync(req, BULK_OUT_TIMEOUT_JIFFIES); + DListRemove(&req->list); + DListInsertTail(&req->list, pool); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s: send bulk-out sync req failed: %{public}d", __func__, ret); + return ret; + } + } + switch (req->status) { case USB_REQUEST_COMPLETED: (void)BufCopyToVector(req->buf, req->actual, data); @@ -1059,27 +1260,28 @@ int32_t UsbfnMtpImpl::Read(std::vector &data) case USB_REQUEST_NO_DEVICE: HDF_LOGE("%{public}s: device disconnect", __func__); mtpDev_->mtpState = MTP_STATE_OFFLINE; - return HDF_DEV_ERR_NO_DEVICE; + ret = HDF_DEV_ERR_NO_DEVICE; + break; default: - HDF_LOGV("%{public}s: unexpected status %{public}d", __func__, req->status); + HDF_LOGE("%{public}s: unexpected status %{public}d", __func__, req->status); mtpDev_->mtpState = MTP_STATE_ERROR; - return HDF_ERR_IO; + ret = HDF_ERR_IO; + break; } + req->actual = REQ_ACTUAL_DEFAULT_LENGTH; return ret; } int32_t UsbfnMtpImpl::WriteEx(const std::vector &data, uint8_t needZLP, uint32_t &xferActual) { + struct DListHead *pool = &mtpPort_->writePool; + struct UsbFnRequest *req = DLIST_FIRST_ENTRY(pool, struct UsbFnRequest, list); + DListRemove(&req->list); + DListInsertTail(&req->list, &mtpPort_->writeQueue); uint32_t needXferCount = data.size(); int32_t ret = HDF_SUCCESS; while (needXferCount > 0 || needZLP == ZLP_NEED) { - struct DListHead *pool = &mtpPort_->writePool; - struct UsbFnRequest *req = DLIST_FIRST_ENTRY(pool, struct UsbFnRequest, list); - if (req == nullptr) { - HDF_LOGE("%{public}s: req invalid", __func__); - return HDF_DEV_ERR_DEV_INIT_FAIL; - } - DListRemove(&req->list); + req->actual = 0; uint32_t reqMax = static_cast(mtpDev_->dataInPipe.maxPacketSize); req->length = reqMax > needXferCount ? needXferCount : reqMax; if (needXferCount == 0) { @@ -1088,13 +1290,8 @@ int32_t UsbfnMtpImpl::WriteEx(const std::vector &data, uint8_t needZLP, } (void)BufCopyFromVector(req->buf, req->length, data, xferActual); ret = UsbFnSubmitRequestSync(req, BULK_IN_TIMEOUT_JIFFIES); - DListInsertTail(&req->list, pool); if (needZLP == ZLP_TRY) { - HDF_LOGV("%{public}s: send zero packet done: %{public}d", __func__, ret); - return ret; - } - if (ret != HDF_SUCCESS) { - HDF_LOGE("%{public}s: bulk-in req failed: %{public}d", __func__, ret); + HDF_LOGE("%{public}s: send zero packet done: %{public}d", __func__, ret); break; } switch (req->status) { @@ -1103,41 +1300,122 @@ int32_t UsbfnMtpImpl::WriteEx(const std::vector &data, uint8_t needZLP, xferActual += req->actual; break; case USB_REQUEST_NO_DEVICE: - HDF_LOGV("%{public}s: device disconnected", __func__); + HDF_LOGE("%{public}s: device disconnected", __func__); mtpDev_->mtpState = MTP_STATE_OFFLINE; - return HDF_DEV_ERR_NO_DEVICE; + ret = HDF_DEV_ERR_NO_DEVICE; + break; default: - HDF_LOGV("%{public}s: unexpected status %{public}d", __func__, req->status); + HDF_LOGE("%{public}s: unexpected status %{public}d", __func__, req->status); mtpDev_->mtpState = MTP_STATE_ERROR; - return HDF_ERR_IO; + ret = HDF_ERR_IO; + break; } + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s: bulk-in req failed: %{public}d", __func__, ret); + break; + } + } + DListRemove(&req->list); + DListInsertTail(&req->list, pool); + return ret; +} + +int32_t UsbfnMtpImpl::getActualLength(const std::vector &data) +{ + if (data.size() < MTP_PROTOCOL_PACKET_SIZE) { + return data.size(); + } + uint32_t length; + std::copy(data.data(), data.data() + MTP_PROTOCOL_PACKET_SIZE, + reinterpret_cast(&length)); + return length; +} + +int32_t UsbfnMtpImpl::WriteSplitPacket(const std::vector &data) +{ + if (data.size() > WRITE_SPLIT_MININUM_LENGTH && writeActualLen_ == 0) { + size_t writeLen = getActualLength(data); + if (writeLen > data.size()) { + vectorSplited_.resize(writeLen); + std::copy(data.begin(), data.end(), vectorSplited_.begin()); + writeActualLen_ = data.size(); + return HDF_SUCCESS; + } + } + if (vectorSplited_.size() > WRITE_SPLIT_MININUM_LENGTH && + (data.size() < vectorSplited_.size() - writeActualLen_)) { + std::copy(data.begin(), data.end(), vectorSplited_.begin() + writeActualLen_); + writeActualLen_ += data.size(); + return HDF_SUCCESS; + } else if (vectorSplited_.size() > WRITE_SPLIT_MININUM_LENGTH && + (data.size() > vectorSplited_.size() - writeActualLen_)) { + vectorSplited_.clear(); + writeActualLen_ = 0; + return HDF_ERR_INVALID_PARAM; + } else if (vectorSplited_.size() > WRITE_SPLIT_MININUM_LENGTH && + (data.size() == vectorSplited_.size() - writeActualLen_)) { + std::copy(data.begin(), data.end(), vectorSplited_.begin() + writeActualLen_); + writeActualLen_ += data.size(); + } + + std::lock_guard guard(writeMutex_); + if (DListIsEmpty(&mtpPort_->writePool) || mtpDev_->initFlag == false) { + return HDF_DEV_ERR_DEV_INIT_FAIL; + } + mtpDev_->mtpState = MTP_STATE_BUSY; + uint32_t xferActual = 0; + uint8_t needZLP = ZLP_NO_NEED; + uint32_t needXferCount = vectorSplited_.size() > WRITE_SPLIT_MININUM_LENGTH ? + vectorSplited_.size() : data.size(); + if ((needXferCount & (mtpDev_->dataInPipe.maxPacketSize - 1)) == 0) { + needZLP = ZLP_NEED; + } + int32_t ret = HDF_FAILURE; + if (writeActualLen_ > WRITE_SPLIT_MININUM_LENGTH && + vectorSplited_.size() == writeActualLen_) { + ret = WriteEx(vectorSplited_, needZLP, xferActual); + vectorSplited_.clear(); + writeActualLen_ = 0; + } else { + ret = WriteEx(data, needZLP, xferActual); } return ret; } int32_t UsbfnMtpImpl::Write(const std::vector &data) { + pthread_rwlock_rdlock(&mtpRunrwLock_); if (mtpPort_ == nullptr || mtpDev_ == nullptr || mtpDev_->initFlag == false) { + pthread_rwlock_unlock(&mtpRunrwLock_); HDF_LOGE("%{public}s: no init", __func__); return HDF_DEV_ERR_DEV_INIT_FAIL; } - std::lock_guard guard(mtpRunning_); - if (mtpDev_->mtpState == MTP_STATE_OFFLINE) { + if (mtpDev_->mtpState == MTP_STATE_OFFLINE || mtpDev_->mtpPort == nullptr || mtpDev_->mtpPort->suspended) { + pthread_rwlock_unlock(&mtpRunrwLock_); HDF_LOGE("%{public}s: device disconnect", __func__); return HDF_DEV_ERR_NO_DEVICE; } if (data.size() == 0) { + pthread_rwlock_unlock(&mtpRunrwLock_); HDF_LOGW("%{public}s: no data need to send", __func__); return HDF_SUCCESS; } - uint32_t needXferCount = data.size(); - uint32_t xferActual = 0; - uint8_t needZLP = ZLP_NO_NEED; - if ((needXferCount & (mtpDev_->dataInPipe.maxPacketSize - 1)) == 0) { - needZLP = ZLP_NEED; + if (mtpDev_->mtpState == MTP_STATE_CANCELED) { + mtpDev_->mtpState = MTP_STATE_READY; + pthread_rwlock_unlock(&mtpRunrwLock_); + HDF_LOGE("%{public}s: states is ecanceled", __func__); + return HDF_ERROR_ECANCEL; } - return WriteEx(data, needZLP, xferActual); + int32_t ret = WriteSplitPacket(data); + if (mtpDev_->mtpState == MTP_STATE_CANCELED) { + HDF_LOGE("%{public}s: running, states is ecanceled", __func__); + ret = HDF_ERROR_ECANCEL; + } else if (mtpDev_->mtpState != MTP_STATE_OFFLINE) { + mtpDev_->mtpState = MTP_STATE_READY; + } + pthread_rwlock_unlock(&mtpRunrwLock_); + return ret; } int32_t UsbfnMtpImpl::UsbMtpPortRxCheckReq(struct UsbMtpPort *mtpPort, struct UsbFnRequest *req, bool &writeToFile) @@ -1146,7 +1424,7 @@ int32_t UsbfnMtpImpl::UsbMtpPortRxCheckReq(struct UsbMtpPort *mtpPort, struct Us switch (req->status) { case USB_REQUEST_NO_DEVICE: mtpDev->mtpState = MTP_STATE_OFFLINE; - HDF_LOGV("%{public}s: rx req return disconnected", __func__); + HDF_LOGE("%{public}s: rx req return disconnected", __func__); return HDF_DEV_ERR_NO_DEVICE; case USB_REQUEST_COMPLETED: break; @@ -1156,7 +1434,7 @@ int32_t UsbfnMtpImpl::UsbMtpPortRxCheckReq(struct UsbMtpPort *mtpPort, struct Us return HDF_FAILURE; } if (req->actual == 0) { - HDF_LOGV("%{public}s: recv ZLP packet, end xfer", __func__); + HDF_LOGD("%{public}s: recv ZLP packet, end xfer", __func__); mtpDev->asyncXferFile = ASYNC_XFER_FILE_DONE; return HDF_SUCCESS; } @@ -1179,10 +1457,13 @@ int32_t UsbfnMtpImpl::UsbMtpPortRxCheckReq(struct UsbMtpPort *mtpPort, struct Us writeToFile = true; } if (mtpDev->asyncRecvFileActual + static_cast(req->actual) == mtpDev->xferFileLength) { - mtpDev->asyncXferFile = ASYNC_XFER_FILE_DONE; - HDF_LOGV("%{public}s: last packet: req(%{public}d/%{public}d)%{public}u/%{public}u, recv %{public}" PRIu64 - "/%{public}" PRIu64 "/%{public}" PRIu64 "", __func__, mtpPort->readStarted, mtpPort->readAllocated, - req->actual, req->length, mtpDev->asyncRecvFileExpect, mtpDev->asyncRecvFileActual, mtpDev->xferFileLength); + if (mtpDev->needZLP != ZLP_NEED) { + mtpDev->asyncXferFile = ASYNC_XFER_FILE_DONE; + } + HDF_LOGD("%{public}s: last packet: req(%{public}d/%{public}d)%{public}u/%{public}u, recv %{public}" PRIu64 + "/%{public}" PRIu64 "/%{public}" PRIu64 ",need zlp:%{public}d", __func__, mtpPort->readStarted, + mtpPort->readAllocated, req->actual, req->length, mtpDev->asyncRecvFileExpect, mtpDev->asyncRecvFileActual, + mtpDev->xferFileLength, mtpDev->needZLP); } return HDF_SUCCESS; } @@ -1190,13 +1471,13 @@ int32_t UsbfnMtpImpl::UsbMtpPortRxCheckReq(struct UsbMtpPort *mtpPort, struct Us int32_t UsbfnMtpImpl::UsbMtpPortProcessAsyncRxDone(struct UsbMtpPort *mtpPort) { struct UsbMtpDevice *mtpDev = mtpPort->mtpDev; - HDF_LOGV("%{public}s: recv done, ignore other packet(%{public}d/%{public}d):%{public}" PRIu64 "/%{public}" PRIu64 + HDF_LOGD("%{public}s: recv done, ignore other packet(%{public}d/%{public}d):%{public}" PRIu64 "/%{public}" PRIu64 "/%{public}" PRIu64 "", __func__, mtpPort->readStarted, mtpPort->readAllocated, mtpDev->asyncRecvFileExpect, mtpDev->asyncRecvFileActual, mtpDev->xferFileLength); if (mtpPort->readStarted == 0) { sem_post(&asyncReq_); } else if (mtpDev->xferFileLength == MTP_MAX_FILE_SIZE) { - HDF_LOGV("%{public}s: cancel redundant req", __func__); + HDF_LOGD("%{public}s: cancel redundant req", __func__); while (!DListIsEmpty(&mtpPort->readQueue)) { struct UsbFnRequest *req = DLIST_FIRST_ENTRY(&mtpPort->readQueue, struct UsbFnRequest, list); (void)UsbFnCancelRequest(req); @@ -1252,7 +1533,8 @@ int32_t UsbfnMtpImpl::UsbMtpPortRxPush(struct UsbMtpPort *mtpPort, struct UsbFnR } return UsbMtpPortProcessAsyncRxDone(mtpPort); } - if (mtpDev->xferFileLength != MTP_MAX_FILE_SIZE && mtpDev->asyncRecvFileExpect != mtpDev->xferFileLength) { + if ((mtpDev->asyncRecvFileActual == mtpDev->xferFileLength) || + (mtpDev->xferFileLength != MTP_MAX_FILE_SIZE && mtpDev->asyncRecvFileExpect != mtpDev->xferFileLength)) { ret = UsbMtpPortStartRxAsync(mtpPort); } return ret; @@ -1291,10 +1573,10 @@ int32_t UsbfnMtpImpl::UsbMtpPortStartSubmitRxReq(struct UsbMtpPort *mtpPort, boo int32_t UsbfnMtpImpl::UsbMtpPortStartRxAsync(struct UsbMtpPort *mtpPort) { + std::lock_guard guard(asyncMutex_); struct DListHead *pool = &mtpPort->readPool; struct UsbMtpDevice *mtpDev = mtpPort->mtpDev; int32_t ret = HDF_SUCCESS; - std::lock_guard guard(asyncMutex_); while (!DListIsEmpty(pool)) { if (mtpPort->readStarted >= mtpPort->readAllocated) { HDF_LOGW("%{public}s no idle read req(BULK-OUT): %{public}d/%{public}d", __func__, mtpPort->readStarted, @@ -1307,9 +1589,13 @@ int32_t UsbfnMtpImpl::UsbMtpPortStartRxAsync(struct UsbMtpPort *mtpPort) ret = HDF_DEV_ERR_NO_DEVICE; break; } + if (mtpDev->asyncRecvFileActual == mtpDev->xferFileLength) { + HDF_LOGD("%{public}s: recv a zlp", __func__); + return UsbMtpPortStartSubmitRxReq(mtpPort, true); + } if ((mtpDev->xferFileLength != MTP_MAX_FILE_SIZE && mtpDev->asyncRecvFileExpect >= mtpDev->xferFileLength) || mtpDev->asyncXferFile == ASYNC_XFER_FILE_DONE) { - HDF_LOGV("%{public}s: no need rx req[%{public}d/%{public}d]:%{public}" PRIu64 "/%{public}" PRIu64 + HDF_LOGD("%{public}s: no need rx req[%{public}d/%{public}d]:%{public}" PRIu64 "/%{public}" PRIu64 "/%{public}" PRIu64 ", xfer=%{public}hhu", __func__, mtpPort->readStarted, mtpPort->readAllocated, mtpDev->asyncRecvFileExpect, mtpDev->asyncRecvFileActual, mtpDev->xferFileLength, mtpDev->asyncXferFile); @@ -1337,7 +1623,7 @@ int32_t UsbfnMtpImpl::ReceiveFileEx() mtpDev_->asyncRecvWriteTempContent = nullptr; return HDF_ERR_IO; } - HDF_LOGV("%{public}s: wait async rx", __func__); + HDF_LOGD("%{public}s: wait async rx", __func__); sem_wait(&asyncReq_); (void)OsalMemFree(mtpDev_->asyncRecvWriteTempContent); mtpDev_->asyncRecvWriteTempContent = nullptr; @@ -1346,7 +1632,7 @@ int32_t UsbfnMtpImpl::ReceiveFileEx() return HDF_ERR_IO; } if (mtpDev_->xferFileLength == MTP_MAX_FILE_SIZE) { - HDF_LOGV("%{public}s: no specific length, reset state", __func__); + HDF_LOGE("%{public}s: no specific length, reset state", __func__); mtpDev_->mtpState = MTP_STATE_READY; return mtpDev_->asyncXferFile == ASYNC_XFER_FILE_DONE ? HDF_SUCCESS : HDF_ERR_IO; } @@ -1355,22 +1641,35 @@ int32_t UsbfnMtpImpl::ReceiveFileEx() int32_t UsbfnMtpImpl::ReceiveFile(const UsbFnMtpFileSlice &mfs) { + pthread_rwlock_rdlock(&mtpRunrwLock_); if (mtpPort_ == nullptr || mtpDev_ == nullptr || mtpDev_->initFlag == false) { + pthread_rwlock_unlock(&mtpRunrwLock_); HDF_LOGE("%{public}s: no init", __func__); return HDF_DEV_ERR_DEV_INIT_FAIL; } - std::lock_guard guard(mtpRunning_); - HDF_LOGV("%{public}s: info: cmd=%{public}d, transid=%{public}d, len=%{public}" PRId64 " offset=%{public}" PRId64 - ", state=%{public}hhu", __func__, mfs.command, mfs.transactionId, mfs.length, mfs.offset, mtpDev_->mtpState); - if (mtpDev_->mtpState == MTP_STATE_OFFLINE) { + if (mtpDev_->mtpState == MTP_STATE_OFFLINE || mtpDev_->mtpPort == nullptr || mtpDev_->mtpPort->suspended) { + pthread_rwlock_unlock(&mtpRunrwLock_); HDF_LOGE("%{public}s: device disconnect", __func__); return HDF_DEV_ERR_NO_DEVICE; } if (mfs.length <= 0) { - HDF_LOGW("%{public}s: no data need to recv", __func__); + pthread_rwlock_unlock(&mtpRunrwLock_); return HDF_SUCCESS; } + if (mtpDev_->mtpState == MTP_STATE_CANCELED) { + mtpDev_->mtpState = MTP_STATE_READY; + pthread_rwlock_unlock(&mtpRunrwLock_); + HDF_LOGE("%{public}s: states is ecanceled", __func__); + return HDF_ERROR_ECANCEL; + } + std::lock_guard guard(readMutex_); + if (mtpDev_->initFlag == false) { + pthread_rwlock_unlock(&mtpRunrwLock_); + HDF_LOGE("%{public}s: dev is release", __func__); + return HDF_DEV_ERR_DEV_INIT_FAIL; + } + mtpDev_->mtpState = MTP_STATE_BUSY; mtpDev_->xferFd = mfs.fd; mtpDev_->xferFileOffset = mfs.offset; mtpDev_->xferFileLength = static_cast(mfs.length); @@ -1382,9 +1681,14 @@ int32_t UsbfnMtpImpl::ReceiveFile(const UsbFnMtpFileSlice &mfs) mtpDev_->needZLP = ZLP_NEED; } int32_t ret = ReceiveFileEx(); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%{public}s: failed: recvfile %{public}d", __func__, ret); + if (mtpDev_->mtpState == MTP_STATE_CANCELED) { + HDF_LOGE("%{public}s: running, states is ecanceled", __func__); + mtpDev_->mtpState = MTP_STATE_READY; + ret = HDF_ERROR_ECANCEL; + } else if (mtpDev_->mtpState != MTP_STATE_OFFLINE) { + mtpDev_->mtpState = MTP_STATE_READY; } + pthread_rwlock_unlock(&mtpRunrwLock_); return ret; } @@ -1417,6 +1721,10 @@ int32_t UsbfnMtpImpl::UsbMtpPortSendFileFillFirstReq(struct UsbFnRequest *req, u int32_t UsbfnMtpImpl::UsbMtpPortSendFileEx() { + if (DListIsEmpty(&mtpPort_->writePool)) { + HDF_LOGE("%{public}s: writePool is empty.", __func__); + return HDF_DEV_ERR_NO_DEVICE; + } struct DListHead *pool = &mtpPort_->writePool; struct UsbFnRequest *req = DLIST_FIRST_ENTRY(pool, struct UsbFnRequest, list); if (req == nullptr) { @@ -1441,11 +1749,11 @@ int32_t UsbfnMtpImpl::UsbMtpPortSendFileEx() case USB_REQUEST_COMPLETED: break; case USB_REQUEST_NO_DEVICE: - HDF_LOGV("%{public}s: device disconnected", __func__); + HDF_LOGE("%{public}s: device disconnected", __func__); mtpDev_->mtpState = MTP_STATE_OFFLINE; return HDF_DEV_ERR_NO_DEVICE; default: - HDF_LOGV("%{public}s: unexpected status %{public}d", __func__, req->status); + HDF_LOGD("%{public}s: unexpected status %{public}d", __func__, req->status); mtpDev_->mtpState = MTP_STATE_ERROR; return HDF_ERR_IO; } @@ -1466,75 +1774,110 @@ int32_t UsbfnMtpImpl::UsbMtpPortSendFileLeftAsync(uint64_t oneReqLeft) HDF_LOGE("%{public}s: start async tx failed", __func__); return HDF_ERR_IO; } - HDF_LOGV("%{public}s: wait async tx", __func__); + HDF_LOGD("%{public}s: wait async tx", __func__); sem_wait(&asyncReq_); return (mtpDev_->mtpState == MTP_STATE_ERROR) ? HDF_ERR_IO : HDF_SUCCESS; } -int32_t UsbfnMtpImpl::SendFile(const UsbFnMtpFileSlice &mfs) +void UsbfnMtpImpl::UsbMtpSendFileParamSet(const UsbFnMtpFileSlice &mfs) { - if (mtpPort_ == nullptr || mtpDev_ == nullptr || mtpDev_->initFlag == false) { - HDF_LOGE("%{public}s: no init", __func__); - return HDF_DEV_ERR_DEV_INIT_FAIL; - } - std::lock_guard guard(mtpRunning_); - mtpDev_->xferFd = mfs.fd; mtpDev_->xferFileOffset = static_cast(mfs.offset); mtpDev_->xferFileLength = static_cast(mfs.length); mtpDev_->xferCommand = mfs.command; mtpDev_->xferTransactionId = mfs.transactionId; mtpDev_->xferSendHeader = (mfs.command == 0 && mfs.transactionId == 0) ? 0 : 1; + return; +} + +int32_t UsbfnMtpImpl::SendFile(const UsbFnMtpFileSlice &mfs) +{ + pthread_rwlock_rdlock(&mtpRunrwLock_); + if (mtpPort_ == nullptr || mtpDev_ == nullptr || mtpDev_->initFlag == false) { + pthread_rwlock_unlock(&mtpRunrwLock_); + HDF_LOGE("%{public}s: no init", __func__); + return HDF_DEV_ERR_DEV_INIT_FAIL; + } + + UsbMtpSendFileParamSet(mfs); uint64_t hdrSize = (mtpDev_->xferSendHeader == 1) ? static_cast(sizeof(struct UsbMtpDataHeader)) : 0; uint64_t needXferCount = mfs.length + hdrSize; lseek(mfs.fd, mfs.offset, SEEK_SET); - HDF_LOGV("%{public}s: info: cmd=%{public}d, transid=%{public}d, len=%{public}" PRId64 " offset=%{public}" PRId64 - "; Xfer=%{public}" PRIu64 "(header=%{public}" PRIu64 "), state=%{public}hhu", __func__, mfs.command, - mfs.transactionId, mfs.length, mfs.offset, needXferCount, hdrSize, mtpDev_->mtpState); if (needXferCount == 0 || mfs.length < 0) { + pthread_rwlock_unlock(&mtpRunrwLock_); HDF_LOGW("%{public}s: no data need to send", __func__); return HDF_SUCCESS; } - if (mtpDev_->mtpState == MTP_STATE_OFFLINE) { + if (mtpDev_->mtpState == MTP_STATE_OFFLINE || mtpDev_->mtpPort == nullptr || mtpDev_->mtpPort->suspended) { + pthread_rwlock_unlock(&mtpRunrwLock_); HDF_LOGE("%{public}s: device disconnect", __func__); return HDF_DEV_ERR_NO_DEVICE; } + if (mtpDev_->mtpState == MTP_STATE_CANCELED) { + mtpDev_->mtpState = MTP_STATE_READY; + pthread_rwlock_unlock(&mtpRunrwLock_); + HDF_LOGE("%{public}s: states is ecanceled", __func__); + return HDF_ERROR_ECANCEL; + } + std::lock_guard guard(writeMutex_); + if (mtpDev_->initFlag == false) { + pthread_rwlock_unlock(&mtpRunrwLock_); + HDF_LOGE("%{public}s: dev is release", __func__); + return HDF_DEV_ERR_DEV_INIT_FAIL; + } + mtpDev_->mtpState = MTP_STATE_BUSY; mtpDev_->needZLP = ZLP_NO_NEED; if ((needXferCount & (mtpDev_->dataInPipe.maxPacketSize - 1)) == 0) { mtpDev_->needZLP = ZLP_NEED; } int32_t ret = UsbMtpPortSendFileEx(); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%{public}s: failed: sendfile %{public}d", __func__, ret); + if (mtpDev_->mtpState == MTP_STATE_CANCELED) { + HDF_LOGE("%{public}s: running, states is ecanceled", __func__); + ret = HDF_ERROR_ECANCEL; + mtpDev_->mtpState = MTP_STATE_READY; + } else if (mtpDev_->mtpState != MTP_STATE_OFFLINE) { + mtpDev_->mtpState = MTP_STATE_READY; } + pthread_rwlock_unlock(&mtpRunrwLock_); return ret; } int32_t UsbfnMtpImpl::SendEvent(const std::vector &eventData) { + pthread_rwlock_rdlock(&mtpRunrwLock_); if (mtpPort_ == nullptr || mtpDev_ == nullptr || mtpDev_->initFlag == false) { + pthread_rwlock_unlock(&mtpRunrwLock_); HDF_LOGE("%{public}s: no init", __func__); return HDF_DEV_ERR_DEV_INIT_FAIL; } - std::lock_guard guard(mtpRunning_); if (eventData.size() > MTP_EVENT_PACKET_MAX_BYTES || eventData.size() == 0) { + pthread_rwlock_unlock(&mtpRunrwLock_); HDF_LOGE("%{public}s: length is invald: %{public}zu", __func__, eventData.size()); return HDF_FAILURE; } - if (mtpDev_->mtpState == MTP_STATE_OFFLINE) { + if (mtpDev_->mtpState == MTP_STATE_OFFLINE || mtpDev_->mtpPort == nullptr || mtpDev_->mtpPort->suspended) { + pthread_rwlock_unlock(&mtpRunrwLock_); HDF_LOGE("%{public}s: device disconnect", __func__); return HDF_DEV_ERR_NO_DEVICE; } + std::lock_guard guard(eventMutex_); + if (mtpDev_->initFlag == false) { + pthread_rwlock_unlock(&mtpRunrwLock_); + HDF_LOGE("%{public}s: dev is release", __func__); + return HDF_DEV_ERR_DEV_INIT_FAIL; + } struct UsbFnRequest *req = mtpDev_->notifyReq; if (req == nullptr || req->buf == nullptr) { + pthread_rwlock_unlock(&mtpRunrwLock_); HDF_LOGE("%{public}s: notify req is null", __func__); return HDF_ERR_INVALID_PARAM; } if (memcpy_s(req->buf, eventData.size(), eventData.data(), eventData.size()) != EOK) { HDF_LOGE("%{public}s: memcpy_s failed", __func__); (void)UsbFnFreeRequest(req); + pthread_rwlock_unlock(&mtpRunrwLock_); return HDF_FAILURE; } req->length = static_cast(eventData.size()); @@ -1542,6 +1885,7 @@ int32_t UsbfnMtpImpl::SendEvent(const std::vector &eventData) if (ret != HDF_SUCCESS) { HDF_LOGE("%{public}s: send notify sync request failed: %{public}d", __func__, ret); } + pthread_rwlock_unlock(&mtpRunrwLock_); return ret; } } // namespace V1_0 diff --git a/usb/gadget/function/mtp/src/usbfn_mtp_interface_driver.cpp b/usb/gadget/function/mtp/src/usbfn_mtp_interface_driver.cpp index a6c19c1509..ae0b3fc132 100644 --- a/usb/gadget/function/mtp/src/usbfn_mtp_interface_driver.cpp +++ b/usb/gadget/function/mtp/src/usbfn_mtp_interface_driver.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include "usbfn_mtp_impl.h" #include "v1_0/usbfn_mtp_interface_stub.h" @@ -30,11 +31,12 @@ struct HdfUsbfnMtpInterfaceHost { OHOS::sptr stub; }; +static pthread_rwlock_t g_rwLock = PTHREAD_RWLOCK_INITIALIZER; +static bool g_stop = true; + static int32_t UsbfnMtpInterfaceDriverDispatch( struct HdfDeviceIoClient *client, int cmdId, struct HdfSBuf *data, struct HdfSBuf *reply) { - auto *hdfUsbfnMtpInterfaceHost = CONTAINER_OF(client->device->service, struct HdfUsbfnMtpInterfaceHost, ioService); - OHOS::MessageParcel *dataParcel = nullptr; OHOS::MessageParcel *replyParcel = nullptr; OHOS::MessageOption option; @@ -48,7 +50,17 @@ static int32_t UsbfnMtpInterfaceDriverDispatch( return HDF_ERR_INVALID_PARAM; } - return hdfUsbfnMtpInterfaceHost->stub->SendRequest(cmdId, *dataParcel, *replyParcel, option); + pthread_rwlock_rdlock(&g_rwLock); + auto *hdfUsbfnMtpInterfaceHost = CONTAINER_OF(client->device->service, struct HdfUsbfnMtpInterfaceHost, ioService); + if (hdfUsbfnMtpInterfaceHost == nullptr || g_stop) { + HDF_LOGE("%{public}s: hdfUsbfnMtpInterfaceHost is nullptr, %{public}d", __func__, g_stop); + pthread_rwlock_unlock(&g_rwLock); + return HDF_FAILURE; + } + + int ret = hdfUsbfnMtpInterfaceHost->stub->SendRequest(cmdId, *dataParcel, *replyParcel, option); + pthread_rwlock_unlock(&g_rwLock); + return ret; } static int HdfUsbfnMtpInterfaceDriverInit(struct HdfDeviceObject *deviceObject) @@ -97,7 +109,7 @@ static int HdfUsbfnMtpInterfaceDriverBind(struct HdfDeviceObject *deviceObject) sptr impl = static_cast(serviceImpl.GetRefPtr()); impl->deviceObject_ = deviceObject; - + g_stop = false; return HDF_SUCCESS; } @@ -109,10 +121,13 @@ static void HdfUsbfnMtpInterfaceDriverRelease(struct HdfDeviceObject *deviceObje return; } + pthread_rwlock_wrlock(&g_rwLock); + g_stop = true; auto *hdfUsbfnMtpInterfaceHost = CONTAINER_OF(deviceObject->service, struct HdfUsbfnMtpInterfaceHost, ioService); if (hdfUsbfnMtpInterfaceHost != nullptr) { delete hdfUsbfnMtpInterfaceHost; } + pthread_rwlock_unlock(&g_rwLock); } static struct HdfDriverEntry g_usbfnmtpinterfaceDriverEntry = { diff --git a/usb/hdf_usb/include/hdf_usb_net_manager.h b/usb/hdf_usb/include/hdf_usb_net_manager.h index 652b579151..ee87905d13 100644 --- a/usb/hdf_usb/include/hdf_usb_net_manager.h +++ b/usb/hdf_usb/include/hdf_usb_net_manager.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Archermind Technology (Nanjing) Co. Ltd. + * Copyright (c) 2024 Huawei Device Co., Ltd. * * HDF is dual licensed: you can use it either under the terms of * the GPL, or the BSD license, at your option. diff --git a/usb/hdf_usb/include/hdf_usb_pnp_manage.h b/usb/hdf_usb/include/hdf_usb_pnp_manage.h index 5e64e1b0f1..ad6e11326f 100644 --- a/usb/hdf_usb/include/hdf_usb_pnp_manage.h +++ b/usb/hdf_usb/include/hdf_usb_pnp_manage.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020-2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 Huawei Device Co., Ltd. * * HDF is dual licensed: you can use it either under the terms of * the GPL, or the BSD license, at your option. @@ -32,6 +32,9 @@ enum UsbPnpNotifyServiceCmd { USB_PNP_DRIVER_PORT_HOST = 40, USB_PNP_DRIVER_PORT_DEVICE, USB_PNP_DRIVER_GET_GADGET_LINK_STATUS, + USB_ACCESSORY_START = 50, + USB_ACCESSORY_STOP, + USB_ACCESSORY_SEND }; enum UsbPnpNotifyRemoveType { diff --git a/usb/hdf_usb/include/usb_ddk_pnp_loader.h b/usb/hdf_usb/include/usb_ddk_pnp_loader.h index 4e0f733b7b..b1937955c8 100644 --- a/usb/hdf_usb/include/usb_ddk_pnp_loader.h +++ b/usb/hdf_usb/include/usb_ddk_pnp_loader.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020-2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 Huawei Device Co., Ltd. * * HDF is dual licensed: you can use it either under the terms of * the GPL, or the BSD license, at your option. diff --git a/usb/hdf_usb/include/usb_pnp_manager.h b/usb/hdf_usb/include/usb_pnp_manager.h index 32dfe58adb..cdfe093dd0 100644 --- a/usb/hdf_usb/include/usb_pnp_manager.h +++ b/usb/hdf_usb/include/usb_pnp_manager.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 Huawei Device Co., Ltd. * * HDF is dual licensed: you can use it either under the terms of * the GPL, or the BSD license, at your option. diff --git a/usb/hdi_service/BUILD.gn b/usb/hdi_service/BUILD.gn index 63cab792d2..6b541a91ec 100644 --- a/usb/hdi_service/BUILD.gn +++ b/usb/hdi_service/BUILD.gn @@ -36,6 +36,8 @@ config("usbd_public_config") { } ohos_shared_library("libusb_interface_service_1.1") { + shlib_type = "hdi" + version_script = "usb_interface_service.map" sanitize = { integer_overflow = true ubsan = true @@ -48,6 +50,7 @@ ohos_shared_library("libusb_interface_service_1.1") { sources = [ "src/usb_impl.cpp", + "src/usbd_accessory.cpp", "src/usbd_dispatcher.cpp", "src/usbd_function.cpp", "src/usbd_load_usb_service.cpp", diff --git a/usb/hdi_service/include/usb_impl.h b/usb/hdi_service/include/usb_impl.h index 5bbcc357ad..d14e5e07d5 100644 --- a/usb/hdi_service/include/usb_impl.h +++ b/usb/hdi_service/include/usb_impl.h @@ -108,6 +108,9 @@ public: HostDevice *FindDevFromService(uint8_t busNum, uint8_t devAddr); int32_t GetInterfaceActiveStatus(const UsbDev &dev, uint8_t interfaceId, bool &unactivated) override; int32_t GetDeviceSpeed(const UsbDev &dev, uint8_t &speed) override; + int32_t GetAccessoryInfo(std::vector &accessoryInfo) override; + int32_t OpenAccessory(int32_t &fd) override; + int32_t CloseAccessory(int32_t fd) override; private: void MakeUsbControlParams( diff --git a/usb/hdi_service/include/usbd_accessory.h b/usb/hdi_service/include/usbd_accessory.h new file mode 100644 index 0000000000..ff107b38d8 --- /dev/null +++ b/usb/hdi_service/include/usbd_accessory.h @@ -0,0 +1,65 @@ +/* + * Copyright (c) Huawei Technologies Co., Ltd. 2024. All rights reserved. + * 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 OHOS_HDI_USB_V1_1_USBD_ACCESSORY_H +#define OHOS_HDI_USB_V1_1_USBD_ACCESSORY_H + +#include +#include +#include +#include +#include +#include +namespace OHOS { +namespace HDI { +namespace Usb { +namespace V1_1 { + +/* ioctls for retrieving strings set by the host */ +#define ACCESSORY_GET_STRING_MANUFACTURER _IOW('M', 1, char[256]) +#define ACCESSORY_GET_STRING_MODEL _IOW('M', 2, char[256]) +#define ACCESSORY_GET_STRING_DESCRIPTION _IOW('M', 3, char[256]) +#define ACCESSORY_GET_STRING_VERSION _IOW('M', 4, char[256]) +#define ACCESSORY_GET_STRING_URI _IOW('M', 5, char[256]) +#define ACCESSORY_GET_STRING_SERIAL _IOW('M', 6, char[256]) +/* returns 1 if there is a start request pending */ +#define ACCESSORY_IS_START_REQUESTED _IO('M', 7) +/* returns audio mode (set via the ACCESSORY_SET_AUDIO_MODE control request) */ +#define ACCESSORY_GET_AUDIO_MODE _IO('M', 8) +#define AOA_IOCTL_EXTRA_DATA 0xC0 +#define AOA_GET_EXTRA_DATA _IOW('M', AOA_IOCTL_EXTRA_DATA, char[256]) + + +class UsbdAccessory { +public: + static UsbdAccessory &GetInstance(); + int32_t GetAccessoryInfo(std::vector &accessoryInfo); + int32_t OpenAccessory(int32_t &fd); + int32_t CloseAccessory(int32_t fd); + void HandleEvent(int32_t state); +private: + int32_t GetAccessoryString(int32_t fd, int32_t cmd, std::string &accInfoString); + int32_t ExtraToString(char* buffer, int32_t len, std::string &extraData); + void init_base64_char_map(); + std::string base64_encode(char* buffer, int32_t len); + std::map base64_char_map; + int32_t accFd = {0}; +}; + +} // namespace V1_1 +} // namespace Usb +} // namespace HDI +} // namespace OHOS +#endif // OHOS_HDI_USB_V1_1_USBD_ACCESSORY_H diff --git a/usb/hdi_service/include/usbd_function.h b/usb/hdi_service/include/usbd_function.h index 52f4a98e30..aa59eab5af 100644 --- a/usb/hdi_service/include/usbd_function.h +++ b/usb/hdi_service/include/usbd_function.h @@ -26,11 +26,14 @@ #define USB_FUNCTION_MTP (1 << 3) #define USB_FUNCTION_PTP (1 << 4) #define USB_FUNCTION_RNDIS (1 << 5) +#define USB_FUNCTION_NCM (1 << 8) #define USB_FUNCTION_STORAGE (1 << 9) #define USB_FUNCTION_MANUFACTURE (1 << 10) +#define USB_FUNCTION_ACCESSORY (1 << 11) #define USB_FUNCTION_SUPPORT \ (USB_FUNCTION_ACM | USB_FUNCTION_ECM | USB_FUNCTION_HDC | USB_FUNCTION_MTP | USB_FUNCTION_PTP | \ - USB_FUNCTION_RNDIS | USB_FUNCTION_STORAGE | USB_FUNCTION_MANUFACTURE) + USB_FUNCTION_RNDIS | USB_FUNCTION_STORAGE | USB_FUNCTION_MANUFACTURE | USB_FUNCTION_ACCESSORY | \ + USB_FUNCTION_NCM) #define DEV_SERVICE_NAME "usbfn" #define ACM_SERVICE_NAME "usbfn_cdcacm" @@ -44,16 +47,13 @@ #define HDC_CONFIG_HDC "hdc" #define HDC_CONFIG_ON "hdc_debug" #define HDC_CONFIG_RNDIS "rndis" - -#ifdef USB_EVENT_NOTIFY_LINUX_NATIVE_MODE -#define HDC_CONFIG_STORAGE "hisuite_mass_storage" -#else #define HDC_CONFIG_STORAGE "storage" -#endif - #define HDC_CONFIG_RNDIS_HDC "rndis_hdc" #define HDC_CONFIG_STORAGE_HDC "storage_hdc" #define HDC_CONFIG_MANUFACTURE_HDC "manufacture_hdc" +#define HDC_CONFIG_AOA "aoa" +#define HDC_CONFIG_NCM "ncm" +#define HDC_CONFIG_NCM_HDC "ncm_hdc" #define HDC_CONFIGFS_OFF "0" #define HDC_CONFIGFS_ON "1" @@ -92,6 +92,9 @@ private: static int32_t SetFunctionToRndisHdc(); static int32_t SetFunctionToStorageHdc(); static int32_t SetFunctionToManufactureHdc(); + static int32_t SetFunctionToUsbAccessory(); + static int32_t SetFunctionToNcm(); + static int32_t SetFunctionToNcmHdc(); static int32_t SetDDKFunction(uint32_t funcs); static int32_t UsbdEnableDevice(int32_t funcs); static int32_t UsbdWaitUdc(); diff --git a/usb/hdi_service/include/usbd_type.h b/usb/hdi_service/include/usbd_type.h index 20df525834..77ab598009 100644 --- a/usb/hdi_service/include/usbd_type.h +++ b/usb/hdi_service/include/usbd_type.h @@ -46,6 +46,9 @@ enum UsbdDeviceAction { ACT_DEVDOWN, ACT_UPDEVICE, ACT_DOWNDEVICE, + ACT_ACCESSORYUP, + ACT_ACCESSORYDOWN, + ACT_ACCESSORYSEND }; enum UsbdCmd { diff --git a/usb/hdi_service/src/usb_impl.cpp b/usb/hdi_service/src/usb_impl.cpp index 0e5f8821cf..ee74254016 100644 --- a/usb/hdi_service/src/usb_impl.cpp +++ b/usb/hdi_service/src/usb_impl.cpp @@ -37,6 +37,7 @@ #include "usb_interface_pool.h" #include "usbd_dispatcher.h" #include "usbd_function.h" +#include "usbd_accessory.h" #include "usbd_port.h" #include "usbd_wrapper.h" using namespace OHOS::HiviewDFX; @@ -65,7 +66,9 @@ static const std::map configMap = { {HDC_CONFIG_STORAGE, USB_FUNCTION_STORAGE}, {HDC_CONFIG_RNDIS_HDC, USB_FUNCTION_HDC + USB_FUNCTION_RNDIS}, {HDC_CONFIG_STORAGE_HDC, USB_FUNCTION_HDC + USB_FUNCTION_STORAGE}, - {HDC_CONFIG_MANUFACTURE_HDC, USB_FUNCTION_MANUFACTURE} + {HDC_CONFIG_MANUFACTURE_HDC, USB_FUNCTION_MANUFACTURE}, + {HDC_CONFIG_NCM, USB_FUNCTION_NCM}, + {HDC_CONFIG_NCM_HDC, USB_FUNCTION_HDC + USB_FUNCTION_NCM} }; extern "C" IUsbInterface *UsbInterfaceImplGetInstance(void) @@ -962,7 +965,6 @@ int32_t UsbImpl::UsbdPnpLoaderEventReceived(void *priv, uint32_t id, HdfSBuf *da UsbdSubscriber *usbdSubscriber = static_cast(priv); const sptr subscriber = usbdSubscriber->subscriber; - int32_t ret = HDF_SUCCESS; if (id == USB_PNP_DRIVER_GADGET_ADD) { HITRACE_METER_NAME(HITRACE_TAG_HDF, "USB_PNP_DRIVER_GADGET_ADD"); isGadgetConnected_ = true; @@ -971,8 +973,7 @@ int32_t UsbImpl::UsbdPnpLoaderEventReceived(void *priv, uint32_t id, HdfSBuf *da HDF_LOGE("%{public}s: subscriber is nullptr, %{public}d", __func__, __LINE__); return HDF_FAILURE; } - ret = subscriber->DeviceEvent(info); - return ret; + return subscriber->DeviceEvent(info); } else if (id == USB_PNP_DRIVER_GADGET_REMOVE) { HITRACE_METER_NAME(HITRACE_TAG_HDF, "USB_PNP_DRIVER_GADGET_REMOVE"); isGadgetConnected_ = false; @@ -981,18 +982,33 @@ int32_t UsbImpl::UsbdPnpLoaderEventReceived(void *priv, uint32_t id, HdfSBuf *da HDF_LOGE("%{public}s: subscriber is nullptr, %{public}d", __func__, __LINE__); return HDF_FAILURE; } - ret = subscriber->DeviceEvent(info); - return ret; + UsbdAccessory::GetInstance().HandleEvent(ACT_DOWNDEVICE); + return subscriber->DeviceEvent(info); } else if (id == USB_PNP_DRIVER_PORT_HOST) { HITRACE_METER_NAME(HITRACE_TAG_HDF, "USB_PNP_DRIVER_PORT_HOST"); return UsbdPort::GetInstance().UpdatePort(PORT_MODE_HOST, subscriber); } else if (id == USB_PNP_DRIVER_PORT_DEVICE) { HITRACE_METER_NAME(HITRACE_TAG_HDF, "USB_PNP_DRIVER_PORT_DEVICE"); return UsbdPort::GetInstance().UpdatePort(PORT_MODE_DEVICE, subscriber); + } else if (id == USB_ACCESSORY_START) { + if (subscriber == nullptr) { + HDF_LOGE("%{public}s: subscriber is nullptr, %{public}d", __func__, __LINE__); + return HDF_FAILURE; + } + HITRACE_METER_NAME(HITRACE_TAG_HDF, "USB_ACCESSORY_START"); + USBDeviceInfo info = {ACT_ACCESSORYUP, 0, 0}; + return subscriber->DeviceEvent(info); + } else if (id == USB_ACCESSORY_SEND) { + if (subscriber == nullptr) { + HDF_LOGE("%{public}s: subsciber is nullptr, %{public}d", __func__, __LINE__); + return HDF_FAILURE; + } + HITRACE_METER_NAME(HITRACE_TAG_HDF, "USB_ACCESSORY_SEND"); + USBDeviceInfo info = {ACT_ACCESSORYSEND, 0, 0}; + return subscriber->DeviceEvent(info); } HITRACE_METER_NAME(HITRACE_TAG_HDF, "USB_PNP_NOTIFY_ADD_OR_REMOVE_DEVICE"); - ret = UsbdPnpNotifyAddAndRemoveDevice(data, usbdSubscriber, id); - return ret; + return UsbdPnpNotifyAddAndRemoveDevice(data, usbdSubscriber, id); } int32_t UsbImpl::UsbdLoadServiceCallback(void *priv, uint32_t id, HdfSBuf *data) @@ -1081,6 +1097,7 @@ int32_t UsbImpl::OpenDevice(const UsbDev &dev) HDF_LOGE("%{public}s: OpenDevice too many times ", __func__); return HDF_FAILURE; } + OsalMutexLock(&lock_); g_usbOpenCount++; port->initFlag = true; if (port->ctrDevHandle == nullptr && port->ctrIface != nullptr) { @@ -1088,10 +1105,12 @@ int32_t UsbImpl::OpenDevice(const UsbDev &dev) __func__, dev.busNum, dev.devAddr); port->ctrDevHandle = UsbOpenInterface(port->ctrIface); if (port->ctrDevHandle == nullptr) { + OsalMutexUnlock(&lock_); HDF_LOGE("%{public}s:ctrDevHandle UsbOpenInterface nullptr", __func__); return HDF_FAILURE; } } + OsalMutexUnlock(&lock_); return HDF_SUCCESS; } @@ -1106,18 +1125,21 @@ int32_t UsbImpl::CloseDevice(const UsbDev &dev) HDF_LOGE("%{public}s: openPort failed", __func__); return HDF_DEV_ERR_DEV_INIT_FAIL; } + OsalMutexLock(&lock_); g_usbOpenCount--; int32_t ret = 0; if (port->ctrDevHandle != nullptr && g_usbOpenCount == 0) { RawUsbCloseCtlProcess(port->ctrDevHandle); ret = UsbCloseInterface(port->ctrDevHandle, true); if (ret != HDF_SUCCESS) { + OsalMutexUnlock(&lock_); HDF_LOGE("%{public}s:usbCloseInterface ctrDevHandle failed.", __func__); return HDF_FAILURE; } port->ctrDevHandle = nullptr; port->initFlag = false; } + OsalMutexUnlock(&lock_); return HDF_SUCCESS; } @@ -1424,10 +1446,10 @@ int32_t UsbImpl::ReleaseInterface(const UsbDev &dev, uint8_t interfaceId) if (ret != HDF_SUCCESS) { HDF_LOGW("%{public}s:release bulk async list failed", __func__); } - UsbReleaseInterface(port->iface[interfaceId]); - port->iface[interfaceId] = nullptr; UsbCloseInterface(port->devHandle[interfaceId], false); port->devHandle[interfaceId] = nullptr; + UsbReleaseInterface(port->iface[interfaceId]); + port->iface[interfaceId] = nullptr; return HDF_SUCCESS; } else { HDF_LOGE("%{public}s:interfaceId failed busNum:%{public}u devAddr:%{public}u interfaceId:%{public}u", __func__, @@ -2267,6 +2289,20 @@ int32_t UsbImpl::GetDeviceSpeed(const UsbDev &dev, uint8_t &speed) return HDF_SUCCESS; } +int32_t UsbImpl::GetAccessoryInfo(std::vector &accessoryInfo) +{ + return UsbdAccessory::GetInstance().GetAccessoryInfo(accessoryInfo); +} + +int32_t UsbImpl::OpenAccessory(int32_t &fd) +{ + return UsbdAccessory::GetInstance().OpenAccessory(fd); +} + +int32_t UsbImpl::CloseAccessory(int32_t fd) +{ + return UsbdAccessory::GetInstance().CloseAccessory(fd); +} } // namespace V1_1 } // namespace Usb diff --git a/usb/hdi_service/src/usb_interface_driver.cpp b/usb/hdi_service/src/usb_interface_driver.cpp index 5f9d3b0c2a..4d95ca2a7b 100644 --- a/usb/hdi_service/src/usb_interface_driver.cpp +++ b/usb/hdi_service/src/usb_interface_driver.cpp @@ -21,8 +21,8 @@ #include "hdf_usb_pnp_manage.h" #include "usb_impl.h" #include "usbd_dispatcher.h" -#include "v1_1/usb_interface_stub.h" #include "usbd_wrapper.h" +#include "v1_1/usb_interface_stub.h" #define HDF_LOG_TAG Usbd diff --git a/usb/hdi_service/src/usbd_accessory.cpp b/usb/hdi_service/src/usbd_accessory.cpp new file mode 100644 index 0000000000..8908df442c --- /dev/null +++ b/usb/hdi_service/src/usbd_accessory.cpp @@ -0,0 +1,180 @@ +/* + * Copyright (c) Huawei Technologies Co., Ltd. 2024. All rights reserved. + * 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 "usbd_accessory.h" +#include +#include +#include + +#include "hdf_base.h" +#include "hdf_log.h" +#include "usbd_wrapper.h" +#include "usbd_type.h" + +namespace OHOS { +namespace HDI { +namespace Usb { +namespace V1_1 { + +const char *ACCESSORY_DRIVER_NAME = "/dev/usb_accessory"; +constexpr int BUFFER_SIZE = 256; +static const std::vector accStringList = { ACCESSORY_GET_STRING_MANUFACTURER, ACCESSORY_GET_STRING_MODEL, + ACCESSORY_GET_STRING_DESCRIPTION, ACCESSORY_GET_STRING_VERSION, + ACCESSORY_GET_STRING_SERIAL, AOA_GET_EXTRA_DATA }; + +const std::string base64_chars = + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789+/"; + +static const int BASE64_BITS_PER_CHAR = -6; +static const int BASE64_VAL_SHIFT = 8; +static const int BASE64_GROUP_SIZE = 4; +static const int32_t MIN_LENGTH_REQUIRED = 10; +static const uint8_t BASE64_CHAR_MASK3F = 0x3F; + +UsbdAccessory &UsbdAccessory::GetInstance() +{ + static UsbdAccessory instance; + return instance; +} + +void UsbdAccessory::init_base64_char_map() +{ + for (size_t i = 0; i < base64_chars.size(); ++i) { + base64_char_map[base64_chars[i]] = i; + } +} + +std::string UsbdAccessory::base64_encode(char *buffer, int32_t len) +{ + if (buffer == nullptr) { + HDF_LOGE("%{public}s: buffer is nullptr", __func__); + return ""; + } + std::string encoded_string; + int val = 0; + int valb = BASE64_BITS_PER_CHAR; + for (int32_t i = 0; i < len; i++) { + val = (val << BASE64_VAL_SHIFT) + buffer[i]; + valb += BASE64_VAL_SHIFT; + while (valb >= 0) { + encoded_string.push_back(base64_chars[(val >> valb) & BASE64_CHAR_MASK3F]); + valb += BASE64_BITS_PER_CHAR; + } + } + if (valb > BASE64_BITS_PER_CHAR) { + encoded_string.push_back(base64_chars[((val << BASE64_VAL_SHIFT) >> (valb + BASE64_VAL_SHIFT)) + & BASE64_CHAR_MASK3F]); + } + while (encoded_string.size() % BASE64_GROUP_SIZE) { + encoded_string.push_back('='); + } + return encoded_string; +} + +int32_t UsbdAccessory::ExtraToString(char* buffer, int32_t len, std::string &extraData) +{ + if (buffer == nullptr) { + HDF_LOGE("%{public}s: buffer is nullptr", __func__); + return HDF_FAILURE; + } + if (len < MIN_LENGTH_REQUIRED) { + return HDF_FAILURE; + } + int16_t actLen = *(buffer + BASE64_VAL_SHIFT); + actLen = actLen >= len ? len: actLen; + if (base64_char_map.empty()) { + init_base64_char_map(); + } + extraData = base64_encode(buffer, actLen); + return HDF_SUCCESS; +} + +int32_t UsbdAccessory::GetAccessoryString(int32_t fd, int32_t cmd, std::string &accInfoString) +{ + char buffer[BUFFER_SIZE]; + if (memset_s(buffer, BUFFER_SIZE, 0, BUFFER_SIZE) != HDF_SUCCESS) { + HDF_LOGE("%{public}s:%{public}d memset_s failed", __func__, __LINE__); + return HDF_FAILURE; + } + int32_t ret = ioctl(fd, cmd, buffer); + if (ret < 0) { + HDF_LOGE("%{public}s:%{public}d ioctl failed, ret: %{public}d", __func__, __LINE__, ret); + return ret; + } + + accInfoString = buffer; + if (cmd == AOA_GET_EXTRA_DATA) { + return ExtraToString(buffer, ret, accInfoString); + } + return HDF_SUCCESS; +} +int32_t UsbdAccessory::GetAccessoryInfo(std::vector &accessoryInfo) +{ + int32_t fd = open(ACCESSORY_DRIVER_NAME, O_RDWR); + if (fd < 0) { + HDF_LOGE("%{public}s:%{public}d open failed", __func__, __LINE__); + return HDF_FAILURE; + } + int32_t ret = HDF_FAILURE; + std::string accInfoString; + for (size_t i = 0; i < accStringList.size(); i++) { + ret = GetAccessoryString(fd, accStringList[i], accInfoString); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s:%{public}d SetAccessoryString failed", __func__, __LINE__); + continue; + } + accessoryInfo.push_back(accInfoString); + } + close(fd); + return HDF_SUCCESS; +} +int32_t UsbdAccessory::OpenAccessory(int32_t &fd) +{ + if (accFd > 0) { + fd = accFd; + return HDF_ERR_DEVICE_BUSY; + } + accFd = open(ACCESSORY_DRIVER_NAME, O_RDWR); + if (accFd < 0) { + HDF_LOGE("%{public}s:%{public}d open failed", __func__, __LINE__); + return HDF_FAILURE; + } + fd = accFd; + return HDF_SUCCESS; +} + +int32_t UsbdAccessory::CloseAccessory(int32_t fd) +{ + if (accFd > 0) { + close(accFd); + } + close(fd); + accFd = 0; + return HDF_SUCCESS; +} + +void UsbdAccessory::HandleEvent(int32_t state) +{ + if (state == ACT_DOWNDEVICE && accFd > 0) { + close(accFd); + accFd = 0; + } +} +} // namespace V1_1 +} // namespace Usb +} // namespace HDI +} // namespace OHOS diff --git a/usb/hdi_service/src/usbd_function.cpp b/usb/hdi_service/src/usbd_function.cpp index e629569135..66c60ae804 100644 --- a/usb/hdi_service/src/usbd_function.cpp +++ b/usb/hdi_service/src/usbd_function.cpp @@ -260,6 +260,39 @@ int32_t UsbdFunction::SetFunctionToStorageHdc() return HDF_SUCCESS; } +int32_t UsbdFunction::SetFunctionToUsbAccessory() +{ + HDF_LOGD("%{public}s enter", __func__); + int32_t status = SetParameter(SYS_USB_CONFIG, HDC_CONFIG_AOA); + if (status != 0) { + HDF_LOGE("%{public}s:add aoa config error = %{public}d", __func__, status); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t UsbdFunction::SetFunctionToNcm() +{ + HDF_LOGD("%{public}s enter", __func__); + int32_t status = SetParameter(SYS_USB_CONFIG, HDC_CONFIG_NCM); + if (status != 0) { + HDF_LOGE("%{public}s:add ncm config error = %{public}d", __func__, status); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + +int32_t UsbdFunction::SetFunctionToNcmHdc() +{ + HDF_LOGD("%{public}s enter", __func__); + int32_t status = SetParameter(SYS_USB_CONFIG, HDC_CONFIG_NCM_HDC); + if (status != 0) { + HDF_LOGE("%{public}s:add ncm hdc config error = %{public}d", __func__, status); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} + int32_t UsbdFunction::SetFunctionToNone() { uint32_t ddkFuns = currentFuncs_ & USB_DDK_FUNCTION_SUPPORT; @@ -536,6 +569,15 @@ int32_t UsbdFunction::UsbdSetKernelFunction(int32_t kfuns, int32_t funcs) case USB_FUNCTION_MANUFACTURE | USB_FUNCTION_HDC: HDF_LOGI("%{public}s: set manufacture hdc", __func__); return UsbdFunction::SetFunctionToManufactureHdc(); + case USB_FUNCTION_ACCESSORY: + HDF_LOGI("%{public}s: set usb accessory", __func__); + return UsbdFunction::SetFunctionToUsbAccessory(); + case USB_FUNCTION_NCM: + HDF_LOGI("%{public}s: set ncm", __func__); + return UsbdFunction::SetFunctionToNcm(); + case USB_FUNCTION_NCM | USB_FUNCTION_HDC: + HDF_LOGI("%{public}s: set ncm hdc", __func__); + return UsbdFunction::SetFunctionToNcmHdc(); default: HDF_LOGI("%{public}s: enable device", __func__); return UsbdEnableDevice(funcs); @@ -562,12 +604,14 @@ int32_t UsbdFunction::UsbdSetFunction(uint32_t funcs) if (UsbdFunction::SetDDKFunction(funcs)) { HDF_LOGE("%{public}s:SetDDKFunction error", __func__); + SetFunctionToStorage(); return HDF_FAILURE; } int32_t ret = UsbdSetKernelFunction(kfuns, funcs); if (ret != HDF_SUCCESS) { HDF_LOGE("%{public}s, set kernel func failed", __func__); + SetFunctionToStorage(); return HDF_FAILURE; } currentFuncs_ |= kfuns; @@ -578,12 +622,14 @@ int32_t UsbdFunction::UsbdSetFunction(uint32_t funcs) if (UsbdWaitUdc() != HDF_SUCCESS) { HDF_LOGE("%{public}s, wait udc failed", __func__); + SetFunctionToStorage(); return HDF_FAILURE; } if (UsbdInitDDKFunction(funcs) != HDF_SUCCESS) { HDF_LOGE("%{public}s, init ddk func failed", __func__); UsbdFunction::SendCmdToService(DEV_SERVICE_NAME, FUNCTION_DEL, USB_DDK_FUNCTION_SUPPORT); UsbdUnregisterDevice(std::string(DEV_SERVICE_NAME)); + SetFunctionToStorage(); return HDF_FAILURE; } currentFuncs_ = funcs; diff --git a/usb/test/unittest/usb_manager_js_test/BUILD.gn b/usb/hdi_service/usb_interface_service.map similarity index 61% rename from usb/test/unittest/usb_manager_js_test/BUILD.gn rename to usb/hdi_service/usb_interface_service.map index a1f84b0675..2d19731d0f 100644 --- a/usb/test/unittest/usb_manager_js_test/BUILD.gn +++ b/usb/hdi_service/usb_interface_service.map @@ -1,9 +1,9 @@ -# Copyright (c) 2023 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); +# 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 +# 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, @@ -11,11 +11,13 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//build/test.gni") - -module_output_path = "hdf/usb" -ohos_js_unittest("UsbManagerJsTest") { - module_out_path = module_output_path - hap_profile = "./config.json" - certificate_profile = "./openharmony_sx.p7b" -} +1.0 { + global: + *UsbInterfaceImplGetInstance*; + extern "C++" { + *UsbImpl::UsbdEventHandle*; + *UsbImpl::UsbdEventHandleRelease*; + }; + local: + *; +}; \ No newline at end of file diff --git a/usb/net/BUILD.gn b/usb/net/BUILD.gn index 4033833114..ad4c3b5322 100644 --- a/usb/net/BUILD.gn +++ b/usb/net/BUILD.gn @@ -86,6 +86,7 @@ ohos_shared_library("libusbhost_rndis_rawapi") { "./../interfaces/ddk/common", "./../interfaces/ddk/host", "./../gadget/function/include", + "./../hdf_usb/include", "include", ] diff --git a/usb/net/include/rndis_host.h b/usb/net/include/rndis_host.h index cd761c45db..39443cfc38 100755 --- a/usb/net/include/rndis_host.h +++ b/usb/net/include/rndis_host.h @@ -1,10 +1,18 @@ /* - * Copyright (c) 2024 Archermind Technology (Nanjing) Co. Ltd. + * 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 * - * HDF is dual licensed: you can use it either under the terms of - * the GPL, or the BSD license, at your option. - * See the LICENSE file in the root of this repository for complete details. + * 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 RNDIS_HOST_H #define RNDIS_HOST_H diff --git a/usb/net/include/rndis_rawapi.h b/usb/net/include/rndis_rawapi.h index f19c9819aa..4fd3971974 100755 --- a/usb/net/include/rndis_rawapi.h +++ b/usb/net/include/rndis_rawapi.h @@ -1,9 +1,16 @@ /* - * Copyright (c) 2024 Archermind Technology (Nanjing) Co. Ltd. + * 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 * - * HDF is dual licensed: you can use it either under the terms of - * the GPL, or the BSD license, at your option. - * See the LICENSE file in the root of this repository for complete details. + * 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 HDF_HOST_RNDIS_RAWAPI_H diff --git a/usb/net/include/usb_net_host.h b/usb/net/include/usb_net_host.h index 64ecf2976e..a570fa9691 100755 --- a/usb/net/include/usb_net_host.h +++ b/usb/net/include/usb_net_host.h @@ -1,10 +1,18 @@ /* - * Copyright (c) 2024 Archermind Technology (Nanjing) Co. Ltd. + * 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 * - * HDF is dual licensed: you can use it either under the terms of - * the GPL, or the BSD license, at your option. - * See the LICENSE file in the root of this repository for complete details. + * 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 USB_NET_HOST_H #define USB_NET_HOST_H diff --git a/usb/net/include/usb_net_net.h b/usb/net/include/usb_net_net.h index 07a4c90462..cff21608cb 100755 --- a/usb/net/include/usb_net_net.h +++ b/usb/net/include/usb_net_net.h @@ -1,9 +1,16 @@ /* - * Copyright (c) 2024 Archermind Technology (Nanjing) Co. Ltd. + * 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 * - * HDF is dual licensed: you can use it either under the terms of - * the GPL, or the BSD license, at your option. - * See the LICENSE file in the root of this repository for complete details. + * 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 USB_NET_NET_H diff --git a/usb/net/src/rndis_rawapi.c b/usb/net/src/rndis_rawapi.c index c84aad7afa..4eb389e875 100755 --- a/usb/net/src/rndis_rawapi.c +++ b/usb/net/src/rndis_rawapi.c @@ -1,31 +1,16 @@ /* - * Copyright (c) 2024 Archermind Technology (Nanjing) Co. Ltd. All rights reserved. + * 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 * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 @@ -365,7 +350,7 @@ static int32_t HostRndisQuery(struct UsbnetHost *usbNet, struct RndisQueryParam uint32_t len = CPU_TO_LE32(uq.getC->len); HARCH_INFO_PRINT("off = %{public}d, len = %{public}d, retval = %{public}d", off, len, retval); - // CONTROL_BUFFER_SIZE_-UNION_OFFSET_LENGTH is valid memory range + // CONTROL_BUFFER_SIZE - UNION_OFFSET_LENGTH is valid memory range if ((off > CONTROL_BUFFER_SIZE - UNION_OFFSET_LENGTH) || (len > CONTROL_BUFFER_SIZE - UNION_OFFSET_LENGTH - off)) { goto response_error; } @@ -434,7 +419,8 @@ static void HostRndisUpdateMtu(struct UsbnetHost **ppUsbNet, int32_t *retval) (*ppUsbNet)->net.hardMtu = tmp; (*ppUsbNet)->net.mtu = (*ppUsbNet)->net.hardMtu - (*ppUsbNet)->net.hardHeaderLen; } - HARCH_INFO_PRINT("hard mtu %{public}u (%{public}u from usbNet), rx buflen %{public}u, align %{public}d\n", + + HARCH_INFO_PRINT("hard mtu %{public}u (%{public}u from usbNet), rx buflen %{public}u, align %{public}d\n", (*ppUsbNet)->net.hardMtu, tmp, (*ppUsbNet)->net.rxUrbSize, 1 << CPU_TO_LE32(g_u.initC->packetAlignment)); } @@ -460,7 +446,7 @@ static void HostRndisSetmacAddrByBp(struct UsbnetHost **ppUsbNet, int32_t *retva HARCH_INFO_PRINT("not GetmacAddr"); (*ppUsbNet)->net.isGetmacAddr = 0; size_t macAddrLen = sizeof((*ppUsbNet)->net.macAddr) / sizeof((*ppUsbNet)->net.macAddr[0]); - if (memset_s((*ppUsbNet)->net.macAddr, macAddrLen, 0, macAddrLen) !=EOK) { + if (memset_s((*ppUsbNet)->net.macAddr, macAddrLen, 0, macAddrLen) != EOK) { HARCH_INFO_PRINT("HostRndisSetmacAddrByBp memset_s fail!"); return; } diff --git a/usb/net/src/usb_net_host.c b/usb/net/src/usb_net_host.c index e8ad0138b1..4a56c1a16a 100755 --- a/usb/net/src/usb_net_host.c +++ b/usb/net/src/usb_net_host.c @@ -1,31 +1,16 @@ /* - * Copyright (c) 2024 Archermind Technology (Nanjing) Co. Ltd. All rights reserved. + * 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 * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * 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 @@ -35,9 +20,9 @@ #include -#include "usb_net_host.h" #include "hdf_usb_pnp_manage.h" #include "cdc_ether.h" +#include "usb_net_host.h" #define HDF_LOG_TAG usb_net_host #define USB_NET_SERVICE_NAME "hdf_usb_net_service" @@ -524,7 +509,7 @@ static void UsbnetHostReadBulkCallback(const void *requestArg) printf_char_buffer((char *)req->buffer, CPU_TO_LE32(size), true); HARCH_INFO_PRINT("Bulk status: %{public}d+size:%{public}zu", req->status, size); - //send readBuf to net begin + // send readBuf to net begin int32_t reply = 0; OsalMutexLock(&usbNet->sendNetLock); int32_t ret = UsbnetHostSendBufToNet(usbNet->hdfNetIoServ, USB_NET_RECIVE_DATA_FROM_USB, @@ -535,7 +520,7 @@ static void UsbnetHostReadBulkCallback(const void *requestArg) } OsalMutexUnlock(&usbNet->sendNetLock); - //send readBuf to net end + // send readBuf to net end if (size == 0) { HARCH_INFO_PRINT("DataFifoWrite"); uint8_t *data = req->buffer; @@ -729,7 +714,7 @@ static void UsbStopIo(struct UsbnetHost *usbNet) static int32_t UsbnetHostAlloc(struct UsbnetHost *usbNet) { - //1.write request + // 1.write request int ret = UsbnetHostWriteBufAlloc(usbNet); if (ret < 0) { HDF_LOGE("%{public}s:%{public}d usbNetWriteBufAlloc failed", __func__, __LINE__); @@ -743,7 +728,7 @@ static int32_t UsbnetHostAlloc(struct UsbnetHost *usbNet) return ret; } - //2.status request + // 2.status request ret = UsbnetHostAllocStatusRequests(usbNet); if (ret != HDF_SUCCESS) { HDF_LOGE("%{public}s: UsbRawAllocRequest failed", __func__); @@ -751,7 +736,7 @@ static int32_t UsbnetHostAlloc(struct UsbnetHost *usbNet) return ret; } - //3.read request + // 3.read request ret = UsbnetHostAllocReadRequests(usbNet); if (ret != HDF_SUCCESS) { HDF_LOGE("%{public}s: UsbRawAllocRequest failed", __func__); @@ -763,6 +748,11 @@ static int32_t UsbnetHostAlloc(struct UsbnetHost *usbNet) static int32_t UsbnetHostAllocRequests(struct UsbnetHost *usbNet) { + if (usbNet == NULL) { + HDF_LOGI("UsbnetHostAllocRequests usbNet is NULL"); + return HDF_FAILURE; + } + if (usbNet->allocFlag == true) { HDF_LOGI("UsbnetHostAllocRequests has been alloced"); return HDF_SUCCESS; @@ -780,14 +770,14 @@ static int32_t UsbnetHostAllocRequests(struct UsbnetHost *usbNet) goto ERR_ALLOC_READ_REQS; } - //status begin + // status begin ret = UsbRawSubmitRequest(usbNet->statusReq); if (ret) { HDF_LOGE("%{public}s:%{public}d UsbRawSubmitRequest failed", __func__, __LINE__); goto ERR_SUBMIT_REQ; } - //read begin + // read begin ret = UsbnetHostAllocFifo(&usbNet->readFifo, READ_BUF_SIZE); if (ret != HDF_SUCCESS) { HDF_LOGE("%{public}s: UsbnetHostAllocFifo failed", __func__); @@ -824,22 +814,22 @@ static void UsbnetHostFreeRequests(struct UsbnetHost *usbNet) HDF_LOGI("UsbnetHostFreeRequests usbNet is null"); return; } - //FIFO + // FIFO OsalMutexLock(&usbNet->readLock); UsbnetHostFreeFifo(&usbNet->readFifo); OsalMutexUnlock(&usbNet->readLock); - //read + // read UsbnetHostFreeReadRequests(usbNet); - //status + // status UsbnetHostFreesSatusReqeust(usbNet); - //write + // write UsbnetHostFreeWriteRequests(usbNet); UsbnetHostWriteBufFree(usbNet); return ; } -//--------------------------usb get config-------------- +// --------------------------usb get config-------------- static void UsbnetHostPrintConfigDescriptor(struct UsbRawConfigDescriptor *tmpConfig) { HARCH_INFO_PRINT("bLength = %{public}d", tmpConfig->configDescriptor.bLength); @@ -946,11 +936,11 @@ static void UsbnetHostUpdateMaxQlen(struct UsbnetHost *usbNet) static int32_t UsbnetHostInitObject(struct UsbnetHost *usbNet) { int ret = HDF_SUCCESS; - //net init + // net init usbNet->net.mtu = DEFAULT_MTU; usbNet->net.hardHeaderLen = DEFAULT_NET_HEAD_LEN; usbNet->net.hardMtu = usbNet->net.mtu + usbNet->net.hardHeaderLen; - //falgs of usb device + // falgs of usb device if (usbNet->driverInfo->flags) { usbNet->net.usbFlags = usbNet->driverInfo->flags; } @@ -1008,14 +998,14 @@ static int32_t UsbnetHostUsbRawInit(struct UsbnetHost *usbNet) } HARCH_INFO_PRINT("busNum:%{public}d, devAddr:%{public}#x", usbNet->busNum, usbNet->devAddr); - //1.session + // 1.session ret = UsbRawInit(&session); if (ret) { HDF_LOGE("%{public}s:%{public}d UsbRawInit failed", __func__, __LINE__); return HDF_ERR_IO; } usbNet->session = session; - //2.handle + // 2.handle UsbRawHandle *devHandle = UsbRawOpenDevice(session, usbNet->busNum, usbNet->devAddr); if (devHandle == NULL) { HDF_LOGE("%{public}s:%{public}d UsbRawOpenDevice failed", __func__, __LINE__); @@ -1023,7 +1013,7 @@ static int32_t UsbnetHostUsbRawInit(struct UsbnetHost *usbNet) goto ERR_OPEN_DEVICE; } usbNet->devHandle = devHandle; - //3.get para + // 3.get para HARCH_INFO_PRINT(); ret = UsbnetHostGetConfigDescriptor(devHandle, &usbNet->config); if (ret) { @@ -1198,7 +1188,7 @@ static int32_t UsbnetHostRegisterNet(struct UsbnetHost *usbNet) return HDF_FAILURE; } - //send msg to net register net + // send msg to net register net int32_t reply = 0; int32_t ret = UsbnetHostSendBufToNet(serv, USB_NET_REGISTER_NET, (unsigned char *)&(usbNet->net), sizeof(struct UsbnetTransInfo), &reply); @@ -1221,14 +1211,14 @@ int32_t UsbnetHostProbe(struct UsbnetHost *usbNet) return HDF_ERR_INVALID_PARAM; } - //usb init + // usb init status = UsbnetHostUsbRawInit(usbNet); if (status != HDF_SUCCESS) { HDF_LOGE("%{public}s: UsbnetHostUsbRawInit failed", __func__); return HDF_FAILURE; } - //register net + // register net status = UsbnetHostRegisterNet(usbNet); if (status != HDF_SUCCESS) { HDF_LOGE("%{public}s: UsbnetHostRegisterNet failed", __func__); @@ -1280,7 +1270,7 @@ static void UsbReleaseInterfaces(struct UsbnetHost *usbNet) static void UsbnetHostUnRegisterNet(struct UsbnetHost *usbNet) { HARCH_INFO_PRINT("begin"); - //send msg to net unregister net + // send msg to net unregister net int32_t reply = 0; int32_t ret = UsbnetHostSendBufToNet(usbNet->hdfNetIoServ, USB_NET_CLOSE_NET, (unsigned char *)&(usbNet->net), sizeof(struct UsbnetTransInfo), &reply); @@ -1300,7 +1290,7 @@ static void UsbnetHostUnRegisterNet(struct UsbnetHost *usbNet) return; } -//Sync write cmd +// Sync write cmd int32_t UsbnetHostWriteCmdSync(struct UsbnetHost *usbNet, struct UsbnetHostCmdParam cmdParam) { uint8_t cmd = cmdParam.cmd; @@ -1360,14 +1350,14 @@ void UsbnetHostRelease(struct UsbnetHost *usbNet) return; } HARCH_INFO_PRINT("bus:%{public}d+dev:%{public}d", usbNet->busNum, usbNet->devAddr); - //net release + // net release UsbnetHostUnRegisterNet(usbNet); - //usb io stop + // usb io stop UsbStopIo(usbNet); - //usb release + // usb release UsbnetHostFreeRequests(usbNet); - //cmd release + // cmd release UsbnetHostReadCmdSyncFree(usbNet); UsbnetHostWriteCmdAsyncFree(usbNet); UsbReleaseInterfaces(usbNet); diff --git a/usb/test/fuzztest/usbbulktransferread_fuzzer/usbbulktransferread_fuzzer.cpp b/usb/test/fuzztest/usbbulktransferread_fuzzer/usbbulktransferread_fuzzer.cpp index 537b485eac..bd46f90358 100644 --- a/usb/test/fuzztest/usbbulktransferread_fuzzer/usbbulktransferread_fuzzer.cpp +++ b/usb/test/fuzztest/usbbulktransferread_fuzzer/usbbulktransferread_fuzzer.cpp @@ -45,7 +45,7 @@ bool UsbBulkTransferReadFuzzTest(const uint8_t *data, size_t size) } int32_t timeout = *(reinterpret_cast(*(data + OFFSET))); ret = usbInterface->BulkTransferRead( - dev, pipe, timeout, reinterpret_cast &>std::move(data + OFFSET_BYTE))); + dev, pipe, timeout, reinterpret_cast &>(std::move(data + OFFSET_BYTE))); if (ret == HDF_SUCCESS) { HDF_LOGI("%{public}s: bulk transfer read succeed", __func__); } diff --git a/usb/test/fuzztest/usbbulktransferwrite_fuzzer/usbbulktransferwrite_fuzzer.cpp b/usb/test/fuzztest/usbbulktransferwrite_fuzzer/usbbulktransferwrite_fuzzer.cpp index 248ed49d24..a36b8cca32 100644 --- a/usb/test/fuzztest/usbbulktransferwrite_fuzzer/usbbulktransferwrite_fuzzer.cpp +++ b/usb/test/fuzztest/usbbulktransferwrite_fuzzer/usbbulktransferwrite_fuzzer.cpp @@ -45,7 +45,7 @@ bool UsbBulkTransferWriteFuzzTest(const uint8_t *data, size_t size) } int32_t timeout = *(reinterpret_cast(*(data + OFFSET))); ret = usbInterface->BulkTransferWrite( - dev, pipe, timeout, reinterpret_cast &>std::move(data + OFFSET_BYTE))); + dev, pipe, timeout, reinterpret_cast &>(std::move(data + OFFSET_BYTE))); if (ret == HDF_SUCCESS) { HDF_LOGI("%{public}s: bulk transfer Write succeed", __func__); } diff --git a/usb/test/unittest/hal/BUILD.gn b/usb/test/unittest/hal/BUILD.gn index 5c0ee26aea..0525a376f1 100644 --- a/usb/test/unittest/hal/BUILD.gn +++ b/usb/test/unittest/hal/BUILD.gn @@ -329,6 +329,51 @@ ohos_unittest("test_devicestatus") { module_out_path = module_output_path } +ohos_unittest("test_accessory") { + sources = [ + "${usb_driver_path}/test/UsbSubscriberTest/UsbSubscriberTest.cpp", + "src/usbd_accessory_test.cpp", + ] + + include_dirs = [ "${usb_driver_path}/test/UsbSubscriberTest" ] + + configs = [ ":module_private_config" ] + + deps = [ + "${usb_driver_path}/ddk:libusb_core", + "${usb_driver_path}/hdi_service:libusb_interface_service_1.1", + ] + + if (is_standard_system) { + external_deps = [ + "drivers_interface_usb:libusb_proxy_1.1", + "eventhandler:libeventhandler", + "googletest:gtest_main", + "hdf_core:libhdf_utils", + "hilog:libhilog", + "ipc:ipc_single", + "safwk:system_ability_fwk", + ] + + if (usb_samgr_enable) { + external_deps += [ "samgr:samgr_proxy" ] + + if (defined(defines)) { + defines += [ "USB_ENABLE_SAMGR" ] + } else { + defines = [ "USB_ENABLE_SAMGR" ] + } + } + + if (usb_c_utils_enable) { + external_deps += [ "c_utils:utils" ] + } + } else { + external_deps = [ "hilog:libhilog" ] + } + module_out_path = module_output_path +} + group("hal_test") { testonly = true deps = [] diff --git a/usb/test/unittest/hal/include/usbd_accessory_test.h b/usb/test/unittest/hal/include/usbd_accessory_test.h new file mode 100644 index 0000000000..05714676fc --- /dev/null +++ b/usb/test/unittest/hal/include/usbd_accessory_test.h @@ -0,0 +1,36 @@ +/* + * 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. + */ +#ifndef USBD_ACCESSORY_TEST_H +#define USBD_ACCESSORY_TEST_H + +#include +#include "UsbSubscriberTest.h" +#include "v1_0/iusbd_subscriber.h" +#include "v1_0/usb_types.h" + +using OHOS::HDI::Usb::V1_0::UsbDev; + +class UsbdAccessoryTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + + static UsbDev dev_; + static OHOS::sptr subscriber_; +}; + +#endif // USBD_ACCESSORY_TEST_H diff --git a/usb/test/unittest/hal/include/usbd_manage_interface_test.h b/usb/test/unittest/hal/include/usbd_manage_interface_test.h index f92d1e9609..61f09a3cee 100755 --- a/usb/test/unittest/hal/include/usbd_manage_interface_test.h +++ b/usb/test/unittest/hal/include/usbd_manage_interface_test.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2023 Huawei Device Co., Ltd. + * Copyright (c) 2023 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 diff --git a/usb/test/unittest/hal/src/usbd_accessory_test.cpp b/usb/test/unittest/hal/src/usbd_accessory_test.cpp new file mode 100644 index 0000000000..33adc7d475 --- /dev/null +++ b/usb/test/unittest/hal/src/usbd_accessory_test.cpp @@ -0,0 +1,131 @@ +/* + * 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. + */ + +#include "usbd_accessory_test.h" + +#include +#include +#include +#include +#include + +#include "UsbSubscriberTest.h" +#include "hdf_log.h" +#include "v1_1/iusb_interface.h" +#include "v1_1/usb_types.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::USB; +using namespace std; +using namespace OHOS::HDI::Usb::V1_0; +using namespace OHOS::HDI::Usb::V1_1; + +sptr UsbdAccessoryTest::subscriber_ = nullptr; + +sptr g_usbInterface = nullptr; + +void UsbdAccessoryTest::SetUpTestCase(void) +{ + g_usbInterface = OHOS::HDI::Usb::V1_1::IUsbInterface::Get(); + if (g_usbInterface == nullptr) { + HDF_LOGE("%{public}s:IUsbInterface::Get() failed.", __func__); + exit(0); + } + std::cout << "please connect accessory, press enter to continue" << std::endl; + int c; + do { + c = getchar(); + } while (c != '\n' && c != EOF); +} + +void UsbdAccessoryTest::TearDownTestCase(void) +{ +} + +void UsbdAccessoryTest::SetUp(void) +{ +} + +void UsbdAccessoryTest::TearDown(void) +{ +} + +/** + * @tc.name: GetAccessoryInfo001 + * @tc.desc: Test functions to GetAccessoryInfo + * @tc.type: FUNC + */ +HWTEST_F(UsbdAccessoryTest, GetAccessoryInfo001, TestSize.Level1) +{ + HDF_LOGI("Case Start : GetAccessoryInfo001 : GetAccessoryInfo"); + vector accessoryInfo; + auto ret = g_usbInterface->GetAccessoryInfo(accessoryInfo); + EXPECT_TRUE(ret == 0); + HDF_LOGI("UsbdAccessoryTest::GetAccessoryInfo001 %{public}d ret=%{public}d", __LINE__, ret); + EXPECT_TRUE(!accessoryInfo.empty()) << "accessoryInfo NULL"; + HDF_LOGI("UsbdAccessoryTest::GetAccessoryInfo001 %{public}d size=%{public}zu", __LINE__, + accessoryInfo.size()); +} + +/** + * @tc.name: OpenAccessory001 + * @tc.desc: Test functions to OpenAccessory + * @tc.type: FUNC + */ +HWTEST_F(UsbdAccessoryTest, OpenAccessory001, TestSize.Level1) +{ + HDF_LOGI("Case Start : OpenAccessory001 : OpenAccessory"); + int32_t fd; + auto ret = g_usbInterface->OpenAccessory(fd); + EXPECT_TRUE(ret == 0); + HDF_LOGI("UsbdAccessoryTest::OpenAccessory001 %{public}d ret=%{public}d", __LINE__, ret); + g_usbInterface->CloseAccessory(fd); +} + +/** + * @tc.name: OpenAccessory002 + * @tc.desc: Test functions to OpenAccessory + * @tc.type: FUNC + */ +HWTEST_F(UsbdAccessoryTest, OpenAccessory002, TestSize.Level1) +{ + HDF_LOGI("Case Start : OpenAccessory001 : OpenAccessory"); + int32_t fd; + auto ret = g_usbInterface->OpenAccessory(fd); + EXPECT_TRUE(ret == 0); + HDF_LOGI("UsbdAccessoryTest::OpenAccessory002 %{public}d ret=%{public}d", __LINE__, ret); + ret = g_usbInterface->OpenAccessory(fd); + EXPECT_TRUE(ret != 0); + HDF_LOGI("UsbdAccessoryTest::OpenAccessory002 %{public}d ret=%{public}d", __LINE__, ret); + g_usbInterface->CloseAccessory(fd); +} + +/** + * @tc.name: CloseAccessory001 + * @tc.desc: Test functions to CloseAccessory + * @tc.type: FUNC + */ +HWTEST_F(UsbdAccessoryTest, CloseAccessory001, TestSize.Level1) +{ + HDF_LOGI("Case Start : CloseAccessory001 : CloseAccessory"); + int32_t fd; + auto ret = g_usbInterface->OpenAccessory(fd); + EXPECT_TRUE(ret == 0); + HDF_LOGI("UsbdAccessoryTest::CloseAccessory001 %{public}d ret=%{public}d", __LINE__, ret); + ret = g_usbInterface->CloseAccessory(fd); + EXPECT_TRUE(ret == 0); + HDF_LOGI("UsbdAccessoryTest::CloseAccessory001 %{public}d ret=%{public}d", __LINE__, ret); +} diff --git a/usb/test/unittest/hal/src/usbd_interface_test.cpp b/usb/test/unittest/hal/src/usbd_interface_test.cpp index 386e6a4ff6..044ccfd67e 100644 --- a/usb/test/unittest/hal/src/usbd_interface_test.cpp +++ b/usb/test/unittest/hal/src/usbd_interface_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023 Huawei Device Co., Ltd. + * 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 diff --git a/usb/test/unittest/hal/src/usbd_manage_interface_test.cpp b/usb/test/unittest/hal/src/usbd_manage_interface_test.cpp index 393d8955ca..23f6ee78c9 100755 --- a/usb/test/unittest/hal/src/usbd_manage_interface_test.cpp +++ b/usb/test/unittest/hal/src/usbd_manage_interface_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2023 Huawei Device Co., Ltd. + * 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 diff --git a/usb/test/unittest/usb_manager_js_test/UsbManagerJsTest.js b/usb/test/unittest/usb_manager_js_test/UsbManagerJsTest.js deleted file mode 100644 index 6c97002367..0000000000 --- a/usb/test/unittest/usb_manager_js_test/UsbManagerJsTest.js +++ /dev/null @@ -1,4265 +0,0 @@ -/* - * 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. - */ - -import usbManager from '@ohos.usbManager'; -//import CheckEmptyUtils from './CheckEmptyUtils.js'; -import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' - - -export default function UsbManagerJsTest() { -describe('UsbManagerJsTest', function () { - - const TAG = "[UsbManagerJsTest]"; - const PARAM_NULL = null; - const PARAM_UNDEFINED = undefined; - const PARAM_NULLSTRING = ""; - const PARAM_NUMBEREX = 123; - let gDeviceList; - let devices; - let usbPortList; - let gPipe; - let isDeviceConnected; - let tmpPipe = { - busNum: null, - devAddress: null - }; - function deviceConnected() { - if (usbPortList == undefined) { - console.info(TAG, "Test USB device is not supported"); - return false; - } - if (gDeviceList.length > 0) { - console.info(TAG, "Test USB device is connected"); - return true; - } - console.info(TAG, "Test USB device is not connected"); - return false; - } - - beforeAll(async function () { - console.log(TAG, '*************Usb Unit UsbManagerJsTest Begin*************'); - const Version = usbManager.getVersion(); - console.info(TAG, 'usb unit begin test getversion :' + Version); - - // version > 17 host currentMode = 2 device currentMode = 1 - usbPortList = usbManager.getPortList(); - - gDeviceList = usbManager.getDevices(); - isDeviceConnected = deviceConnected(); - if (isDeviceConnected) { - if (usbPortList.length > 0) { - if (usbPortList[0].status.currentMode == 1) { - try { - let data = await usbManager.setPortRoleTypes(usbPortList[0].id, - usbManager.SOURCE, usbManager.HOST); - console.info(TAG, 'usb case setPortRoleTypesEx return: ' + data); - } catch (error) { - console.info(TAG, 'usb case setPortRoleTypesEx error : ' + error); - } - CheckEmptyUtils.sleep(4000); - console.log(TAG, '*************Usb Unit Begin switch to host*************'); - } - } - tmpPipe.busNum = gDeviceList[0].busNum; - tmpPipe.devAddress = gDeviceList[0].devAddress; - } - }) - - beforeEach(function () { - console.info(TAG, 'beforeEach: *************Usb Unit Test CaseEx*************'); - gDeviceList = usbManager.getDevices(); - if (isDeviceConnected) { - devices = gDeviceList[0]; - console.info(TAG, 'beforeEach return devices : ' + JSON.stringify(devices)); - } - }) - - afterEach(function () { - console.info(TAG, 'afterEach: *************Usb Unit Test CaseEx*************'); - devices = null; - gPipe = null; - console.info(TAG, 'afterEach return devices : ' + JSON.stringify(devices)); - }) - - afterAll(function () { - console.log(TAG, '*************Usb Unit UsbManagerJsTest End*************'); - }) - - function getPipe(testCaseName) { - gPipe = usbManager.connectDevice(devices); - console.info(TAG, `usb ${testCaseName} connectDevice getPipe ret: ${JSON.stringify(gPipe)}`); - expect(gPipe !== null).assertTrue(); - } - - function toReleaseInterface(testCaseName, tInterface) { - let ret = usbManager.releaseInterface(tmpPipe, tInterface); - console.info(TAG, `usb ${testCaseName} releaseInterface ret: ${ret}`); - expect(ret).assertEqual(0); - } - - function toClosePipe(testCaseName) { - let isPipClose = usbManager.closePipe(tmpPipe); - console.info(TAG, `usb ${testCaseName} closePipe ret: ${isPipClose}`); - expect(isPipClose).assertEqual(0); - } - - /** - * @tc.number : USB_HostManager_JS_0100 - * @tc.name : testHasRight001 - * @tc.desc : Negative test: Param is null string - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testHasRight001', 0, function () { - console.info(TAG, 'usb testHasRight001 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - let isHasRight = usbManager.hasRight(PARAM_NULLSTRING); - console.info(TAG, 'usb case hasRight ret : ' + isHasRight); - expect(isHasRight).assertFalse(); - } catch (err) { - console.info(TAG, 'testHasRight001 catch err code: ', err.code, ', message: ', err.message); - expect(err !== null).assertFalse(); - } - }) - - /** - * @tc.number : USB_HostManager_JS_0200 - * @tc.name : testHasRight002 - * @tc.desc : Negative test: Param add number '123' - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testHasRight002', 0, function () { - console.info(TAG, 'usb testHasRight002 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - for (var i = 0; i < gDeviceList.length; i++) { - let deviceName = gDeviceList[i].name; - deviceName = deviceName + "123"; - let isHasRight = usbManager.hasRight(deviceName); - console.info(TAG, 'usb [', deviceName, '] hasRight ret : ' + isHasRight); - expect(isHasRight).assertFalse(); - } - } catch (err) { - console.info(TAG, 'testHasRight002 catch err code: ', err.code, ', message: ', err.message); - expect(err !== null).assertFalse(); - } - }) - - /** - * @tc.number : USB_HostManager_JS__0300 - * @tc.name : testRequestRight001 - * @tc.desc : Negative test: Param is null string - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testRequestRight001', 0, async function () { - console.info(TAG, 'usb testRequestRight001 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - let isHasRight = await usbManager.requestRight(PARAM_NULLSTRING); - console.info(TAG, 'usb case requestRight ret : ' + isHasRight); - expect(isHasRight).assertFalse(); - } catch (err) { - console.info(TAG, 'testRequestRight001 catch err code: ', err.code, ', message: ', err.message); - expect(err !== null).assertFalse(); - } - }) - - /** - * @tc.number : USB_HostManager_JS__0400 - * @tc.name : testRequestRight002 - * @tc.desc : Negative test: Param add number 'abc' - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testRequestRight002', 0, async function () { - console.info(TAG, 'usb testRequestRight002 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - for (var i = 0; i < gDeviceList.length; i++) { - let deviceName = gDeviceList[i].name; - deviceName = deviceName + "abc"; - let isHasRight = await usbManager.requestRight(deviceName); - console.info(TAG, 'usb [', deviceName, '] requestRight ret : ' + isHasRight); - expect(isHasRight).assertFalse(); - } - } catch (err) { - console.info(TAG, 'testRequestRight002 catch err code: ', err.code, ', message: ', err.message); - expect(err !== null).assertFalse(); - } - }) - - /** - * @tc.number : USB_HostManager_JS__0500 - * @tc.name : testRemoveRight001 - * @tc.desc : Negative test: Param is null string - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testRemoveRight001', 0, function () { - console.info(TAG, 'usb testRemoveRight001 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - let remRight = usbManager.removeRight(PARAM_NULLSTRING); - console.info(TAG, 'usb case removeRight ret : ' + remRight); - expect(remRight).assertFalse(); - } catch (err) { - console.info(TAG, 'testRemoveRight001 catch err code: ', err.code, ', message: ', err.message); - expect(err !== null).assertFalse(); - } - }) - - /** - * @tc.number : USB_HostManager_JS__0600 - * @tc.name : testRemoveRight002 - * @tc.desc : Negative test: Param add letter 'abc' - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testRemoveRight002', 0, function () { - console.info(TAG, 'usb testRemoveRight002 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - for (var i = 0; i < gDeviceList.length; i++) { - let deviceName = gDeviceList[i].name; - deviceName = deviceName + "abc"; - let remRight = usbManager.removeRight(deviceName); - console.info(TAG, 'usb [', deviceName, '] removeRight ret : ', remRight); - expect(remRight).assertFalse(); - } - } catch (err) { - console.info(TAG, 'testRemoveRight002 catch err code: ', err.code, ', message: ', err.message); - expect(err !== null).assertFalse(); - } - }) - - /** - * @tc.number : USB_HostManager_JS__0700 - * @tc.name : testRemoveRight003 - * @tc.desc : Negative test: Param add special characters '@#' - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testRemoveRight003', 0, function () { - console.info(TAG, 'usb testRemoveRight003 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - for (var i = 0; i < gDeviceList.length; i++) { - let deviceName = gDeviceList[i].name; - deviceName = deviceName + "@#"; - let remRight = usbManager.removeRight(deviceName); - console.info(TAG, 'usb [', deviceName, '] removeRight ret : ', remRight); - expect(remRight).assertFalse(); - } - } catch (err) { - console.info(TAG, 'testRemoveRight003 catch err code: ', err.code, ', message: ', err.message); - expect(err !== null).assertFalse(); - } - }) - - /** - * @tc.number : USB_HostManager_JS__0800 - * @tc.name : testRemoveRight004 - * @tc.desc : Negative test: Param add number '123' - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testRemoveRight004', 0, function () { - console.info(TAG, 'usb testRemoveRight004 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - for (var i = 0; i < gDeviceList.length; i++) { - let deviceName = gDeviceList[i].name; - deviceName = deviceName + "123"; - let remRight = usbManager.removeRight(deviceName); - console.info(TAG, 'usb [', deviceName, '] removeRight ret : ', remRight); - expect(remRight).assertFalse(); - } - } catch (err) { - console.info(TAG, 'testRemoveRight004 catch err code: ', err.code, ', message: ', err.message); - expect(err !== null).assertFalse(); - } - }) - - /** - * @tc.number : USB_HostManager_JS__0900 - * @tc.name : testConnectDevice001 - * @tc.desc : Negative test: Param add number '123' - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDevice001', 0, function () { - console.info(TAG, 'usb testConnectDevice001 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - let deviceName = devices.name + "123"; - devices.name = deviceName; - let gPipe = usbManager.connectDevice(devices); - - console.info(TAG, 'usb [', devices.name, '] connectDevice ret : ', JSON.stringify(gPipe)); - expect(CheckEmptyUtils.isEmpty(gPipe)).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDevice001 catch err code: ', err.code, ', message: ', err.message); - expect(err !== null).assertFalse(); - } - }) - - /** - * @tc.number : USB_HostManager_JS__1000 - * @tc.name : testConnectDevice002 - * @tc.desc : Negative test: Param add letter 'abc' - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDevice002', 0, function () { - console.info(TAG, 'usb testConnectDevice002 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - let deviceName = devices.name + "abc"; - devices.name = deviceName; - let gPipe = usbManager.connectDevice(devices); - console.info(TAG, 'usb [', devices.name, '] connectDevice ret : ', JSON.stringify(gPipe)); - expect(CheckEmptyUtils.isEmpty(gPipe)).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDevice002 catch err code: ', err.code, ', message: ', err.message); - expect(err !== null).assertFalse(); - } - }) - - /** - * @tc.number : USB_HostManager_JS__1100 - * @tc.name : testConnectDevice003 - * @tc.desc : Negative test: Param add special characters '@#' - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDevice003', 0, function () { - console.info(TAG, 'usb testConnectDevice003 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - let deviceName = devices.name + "@#"; - devices.name = deviceName; - let gPipe = usbManager.connectDevice(devices); - console.info(TAG, 'usb [', devices.name, '] connectDevice ret : ', JSON.stringify(gPipe)); - expect(CheckEmptyUtils.isEmpty(gPipe)).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDevice003 catch err code: ', err.code, ', message: ', err.message); - expect(err !== null).assertFalse(); - } - }) - - /** - * @tc.number : USB_HostManager_JS__1200 - * @tc.name : testConnectDevice004 - * @tc.desc : Negative test: devices name is null string "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDevice004', 0, function () { - console.info(TAG, 'usb testConnectDevice004 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.name = PARAM_NULLSTRING; - let gPipe = usbManager.connectDevice(devices); - console.info(TAG, 'usb [', devices.name, '] connectDevice ret : ', JSON.stringify(gPipe)); - expect(CheckEmptyUtils.isEmpty(gPipe)).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDevice004 catch err code: ', err.code, ', message: ', err.message); - expect(err !== null).assertFalse(); - } - }) - - /** - * @tc.number : USB_HostManager_JS__1300 - * @tc.name : testConnectDevice005 - * @tc.desc : Negative test: devices serial is null string "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDevice005', 0, function () { - console.info(TAG, 'usb testConnectDevice005 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.serial = PARAM_NULLSTRING; - let gPipe = usbManager.connectDevice(devices); - console.info(TAG, 'usb [', devices.serial, '] connectDevice ret : ', JSON.stringify(gPipe)); - expect(CheckEmptyUtils.isEmpty(gPipe)).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDevice005 catch err code: ', err.code, ', message: ', err.message); - expect(err !== null).assertFalse(); - } - }) - - /** - * @tc.number : USB_HostManager_JS__1400 - * @tc.name : testConnectDevice006 - * @tc.desc : Negative test: devices serial add letter abc - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDevice006', 0, function () { - console.info(TAG, 'usb testConnectDevice006 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - let devSerial = devices.serial + "abc"; - devices.serial = devSerial; - let gPipe = usbManager.connectDevice(devices); - console.info(TAG, 'usb [', devices.serial, '] connectDevice ret : ', JSON.stringify(gPipe)); - expect(CheckEmptyUtils.isEmpty(gPipe)).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDevice006 catch err code: ', err.code, ', message: ', err.message); - expect(err !== null).assertFalse(); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_1800 - * @tc.name : testConnectDeviceParamErr007 - * @tc.desc : Negative test: devices name is number 123 - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDeviceParamErr007', 0, function () { - console.info(TAG, 'usb testConnectDeviceParamErr007 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.name = PARAM_NUMBERTYPE; - let ret = usbManager.connectDevice(devices); - console.info(TAG, 'usb [', devices.name, '] connectDevice ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDeviceParamErr007 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_1900 - * @tc.name : testConnectDeviceParamErr008 - * @tc.desc : Negative test: devices busNum is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDeviceParamErr008', 0, function () { - console.info(TAG, 'usb testConnectDeviceParamErr008 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.busNum = PARAM_NULL; - let ret = usbManager.connectDevice(devices); - console.info(TAG, 'usb [busNum:null] connectDevice ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDeviceParamErr008 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_2000 - * @tc.name : testConnectDeviceParamErr009 - * @tc.desc : Negative test: devices busNum is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDeviceParamErr009', 0, function () { - console.info(TAG, 'usb testConnectDeviceParamErr009 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.busNum = PARAM_UNDEFINED; - let ret = usbManager.connectDevice(devices); - console.info(TAG, 'usb [busNum:undefined] connectDevice ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDeviceParamErr009 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_2100 - * @tc.name : testConnectDeviceParamErr010 - * @tc.desc : Negative test: devices busNum null string "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDeviceParamErr010', 0, function () { - console.info(TAG, 'usb testConnectDeviceParamErr010 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.busNum = PARAM_NULLSTRING; - let ret = usbManager.connectDevice(devices); - console.info(TAG, 'usb [busNum:null string] connectDevice ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDeviceParamErr010 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_2200 - * @tc.name : testConnectDeviceParamErr011 - * @tc.desc : Negative test: devices devAddress is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDeviceParamErr011', 0, function () { - console.info(TAG, 'usb testConnectDeviceParamErr011 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.devAddress = PARAM_NULL; - let ret = usbManager.connectDevice(devices); - console.info(TAG, 'usb [devAddress:null] connectDevice ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDeviceParamErr011 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_2300 - * @tc.name : testConnectDeviceParamErr012 - * @tc.desc : Negative test: devices devAddress is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDeviceParamErr012', 0, function () { - console.info(TAG, 'usb testConnectDeviceParamErr012 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.devAddress = PARAM_UNDEFINED; - let ret = usbManager.connectDevice(devices); - console.info(TAG, 'usb [devAddress:undefined] connectDevice ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDeviceParamErr012 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_2400 - * @tc.name : testConnectDeviceParamErr013 - * @tc.desc : Negative test: devices devAddress is null string - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDeviceParamErr013', 0, function () { - console.info(TAG, 'usb testConnectDeviceParamErr013 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.devAddress = PARAM_NULLSTRING; - let ret = usbManager.connectDevice(devices); - console.info(TAG, 'usb [devAddress:null string] connectDevice ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDeviceParamErr013 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_2500 - * @tc.name : testConnectDeviceParamErr014 - * @tc.desc : Negative test: devices serial is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDeviceParamErr014', 0, function () { - console.info(TAG, 'usb testConnectDeviceParamErr014 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.serial = PARAM_NULL; - let ret = usbManager.connectDevice(devices); - console.info(TAG, 'usb [serial:null] connectDevice ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDeviceParamErr014 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_2600 - * @tc.name : testConnectDeviceParamErr015 - * @tc.desc : Negative test: devices serial is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDeviceParamErr015', 0, function () { - console.info(TAG, 'usb testConnectDeviceParamErr015 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.serial = PARAM_UNDEFINED; - let ret = usbManager.connectDevice(devices); - console.info(TAG, 'usb [serial:undefined] connectDevice ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDeviceParamErr015 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_2700 - * @tc.name : testConnectDeviceParamErr016 - * @tc.desc : Negative test: devices serial is number 123 - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDeviceParamErr016', 0, function () { - console.info(TAG, 'usb testConnectDeviceParamErr016 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.serial = PARAM_NUMBERTYPE; - let ret = usbManager.connectDevice(devices); - console.info(TAG, 'usb [serial:123] connectDevice ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDeviceParamErr016 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_2800 - * @tc.name : testConnectDeviceParamErr017 - * @tc.desc : Negative test: devices manufacturerName is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDeviceParamErr017', 0, function () { - console.info(TAG, 'usb testConnectDeviceParamErr017 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.manufacturerName = PARAM_NULL; - let ret = usbManager.connectDevice(devices); - console.info(TAG, 'usb [manufacturerName:null] connectDevice ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDeviceParamErr017 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_2900 - * @tc.name : testConnectDeviceParamErr018 - * @tc.desc : Negative test: devices manufacturerName is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDeviceParamErr018', 0, function () { - console.info(TAG, 'usb testConnectDeviceParamErr018 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.manufacturerName = PARAM_UNDEFINED; - let ret = usbManager.connectDevice(devices); - console.info(TAG, 'usb [manufacturerName:undefined] connectDevice ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDeviceParamErr018 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_3000 - * @tc.name : testConnectDeviceParamErr019 - * @tc.desc : Negative test: devices manufacturerName is number 123 - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDeviceParamErr019', 0, function () { - console.info(TAG, 'usb testConnectDeviceParamErr019 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.manufacturerName = PARAM_NUMBERTYPE; - let ret = usbManager.connectDevice(devices); - console.info(TAG, 'usb [manufacturerName:123] connectDevice ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDeviceParamErr019 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_3100 - * @tc.name : testConnectDeviceParamErr020 - * @tc.desc : Negative test: devices productName is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDeviceParamErr020', 0, function () { - console.info(TAG, 'usb testConnectDeviceParamErr020 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.productName = PARAM_NULL; - let ret = usbManager.connectDevice(devices); - console.info(TAG, 'usb [productName:null] connectDevice ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDeviceParamErr020 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_3200 - * @tc.name : testConnectDeviceParamErr021 - * @tc.desc : Negative test: devices productName is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDeviceParamErr021', 0, function () { - console.info(TAG, 'usb testConnectDeviceParamErr021 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.productName = PARAM_UNDEFINED; - let ret = usbManager.connectDevice(devices); - console.info(TAG, 'usb [productName:undefined] connectDevice ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDeviceParamErr021 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_3300 - * @tc.name : testConnectDeviceParamErr022 - * @tc.desc : Negative test: devices productName is number 123 - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDeviceParamErr022', 0, function () { - console.info(TAG, 'usb testConnectDeviceParamErr022 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.productName = PARAM_NUMBERTYPE; - let ret = usbManager.connectDevice(devices); - console.info(TAG, 'usb [productName:123] connectDevice ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDeviceParamErr022 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_3400 - * @tc.name : testConnectDeviceParamErr023 - * @tc.desc : Negative test: devices version is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDeviceParamErr023', 0, function () { - console.info(TAG, 'usb testConnectDeviceParamErr023 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.version = PARAM_NULL; - let ret = usbManager.connectDevice(devices); - console.info(TAG, 'usb [version:null] connectDevice ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDeviceParamErr023 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_3500 - * @tc.name : testConnectDeviceParamErr024 - * @tc.desc : Negative test: devices version is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDeviceParamErr024', 0, function () { - console.info(TAG, 'usb testConnectDeviceParamErr024 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.version = PARAM_UNDEFINED; - let ret = usbManager.connectDevice(devices); - console.info(TAG, 'usb [version:undefined] connectDevice ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDeviceParamErr024 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_3600 - * @tc.name : testConnectDeviceParamErr025 - * @tc.desc : Negative test: devices vendorId is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDeviceParamErr025', 0, function () { - console.info(TAG, 'usb testConnectDeviceParamErr025 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.vendorId = PARAM_NULL; - let ret = usbManager.connectDevice(devices); - console.info(TAG, 'usb [vendorId:null] connectDevice ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDeviceParamErr025 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_3700 - * @tc.name : testConnectDeviceParamErr026 - * @tc.desc : Negative test: devices vendorId is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDeviceParamErr026', 0, function () { - console.info(TAG, 'usb testConnectDeviceParamErr026 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.vendorId = PARAM_UNDEFINED; - let ret = usbManager.connectDevice(devices); - console.info(TAG, 'usb [vendorId:undefined] connectDevice ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDeviceParamErr026 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_3800 - * @tc.name : testConnectDeviceParamErr027 - * @tc.desc : Negative test: devices vendorId is null string "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDeviceParamErr027', 0, function () { - console.info(TAG, 'usb testConnectDeviceParamErr027 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.vendorId = PARAM_NULLSTRING; - let ret = usbManager.connectDevice(devices); - console.info(TAG, 'usb [vendorId:""] connectDevice ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDeviceParamErr027 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_3900 - * @tc.name : testConnectDeviceParamErr028 - * @tc.desc : Negative test: devices productId is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDeviceParamErr028', 0, function () { - console.info(TAG, 'usb testConnectDeviceParamErr028 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.productId = PARAM_NULL; - let ret = usbManager.connectDevice(devices); - console.info(TAG, 'usb [productId:null] connectDevice ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDeviceParamErr028 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_4000 - * @tc.name : testConnectDeviceParamErr029 - * @tc.desc : Negative test: devices productId is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDeviceParamErr029', 0, function () { - console.info(TAG, 'usb testConnectDeviceParamErr029 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.productId = PARAM_UNDEFINED; - let ret = usbManager.connectDevice(devices); - console.info(TAG, 'usb [productId:undefined] connectDevice ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDeviceParamErr029 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_4100 - * @tc.name : testConnectDeviceParamErr030 - * @tc.desc : Negative test: devices productId is null string "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDeviceParamErr030', 0, function () { - console.info(TAG, 'usb testConnectDeviceParamErr030 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.productId = PARAM_NULLSTRING; - let ret = usbManager.connectDevice(devices); - console.info(TAG, 'usb [productId:" "] connectDevice ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDeviceParamErr030 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_4200 - * @tc.name : testConnectDeviceParamErr031 - * @tc.desc : Negative test: devices clazz is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDeviceParamErr031', 0, function () { - console.info(TAG, 'usb testConnectDeviceParamErr031 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.clazz = PARAM_NULL; - let ret = usbManager.connectDevice(devices); - console.info(TAG, 'usb [clazz:null] connectDevice ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDeviceParamErr031 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_4300 - * @tc.name : testConnectDeviceParamErr032 - * @tc.desc : Negative test: devices clazz is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDeviceParamErr032', 0, function () { - console.info(TAG, 'usb testConnectDeviceParamErr032 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.clazz = PARAM_UNDEFINED; - let ret = usbManager.connectDevice(devices); - console.info(TAG, 'usb [clazz:undefined] connectDevice ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDeviceParamErr032 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_4400 - * @tc.name : testConnectDeviceParamErr033 - * @tc.desc : Negative test: devices clazz is null string "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDeviceParamErr033', 0, function () { - console.info(TAG, 'usb testConnectDeviceParamErr033 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.clazz = PARAM_NULLSTRING; - let ret = usbManager.connectDevice(devices); - console.info(TAG, 'usb [clazz:""] connectDevice ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDeviceParamErr033 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_4500 - * @tc.name : testConnectDeviceParamErr034 - * @tc.desc : Negative test: devices subClass is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDeviceParamErr034', 0, function () { - console.info(TAG, 'usb testConnectDeviceParamErr034 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.subClass = PARAM_NULL; - let ret = usbManager.connectDevice(devices); - console.info(TAG, 'usb [subClass:null] connectDevice ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDeviceParamErr034 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_4600 - * @tc.name : testConnectDeviceParamErr035 - * @tc.desc : Negative test: devices subClass is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDeviceParamErr035', 0, function () { - console.info(TAG, 'usb testConnectDeviceParamErr035 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.subClass = PARAM_UNDEFINED; - let ret = usbManager.connectDevice(devices); - console.info(TAG, 'usb [subClass:undefined] connectDevice ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDeviceParamErr035 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_4700 - * @tc.name : testConnectDeviceParamErr036 - * @tc.desc : Negative test: devices subClass is null string "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDeviceParamErr036', 0, function () { - console.info(TAG, 'usb testConnectDeviceParamErr036 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.subClass = PARAM_NULLSTRING; - let ret = usbManager.connectDevice(devices); - console.info(TAG, 'usb [subClass:""] connectDevice ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDeviceParamErr036 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_4800 - * @tc.name : testConnectDeviceParamErr037 - * @tc.desc : Negative test: devices protocol is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDeviceParamErr037', 0, function () { - console.info(TAG, 'usb testConnectDeviceParamErr037 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.protocol = PARAM_NULL; - let ret = usbManager.connectDevice(devices); - console.info(TAG, 'usb [protocol:null] connectDevice ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDeviceParamErr037 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_4900 - * @tc.name : testConnectDeviceParamErr038 - * @tc.desc : Negative test: devices protocol is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDeviceParamErr038', 0, function () { - console.info(TAG, 'usb testConnectDeviceParamErr038 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.protocol = PARAM_UNDEFINED; - let ret = usbManager.connectDevice(devices); - console.info(TAG, 'usb [protocol:undefined] connectDevice ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDeviceParamErr038 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_5000 - * @tc.name : testConnectDeviceParamErr039 - * @tc.desc : Negative test: devices protocol is null string "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDeviceParamErr039', 0, function () { - console.info(TAG, 'usb testConnectDeviceParamErr039 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.protocol = PARAM_NULLSTRING; - let ret = usbManager.connectDevice(devices); - console.info(TAG, 'usb [protocol:""] connectDevice ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDeviceParamErr039 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_5100 - * @tc.name : testConnectDeviceParamErr040 - * @tc.desc : Negative test: devices configs is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDeviceParamErr040', 0, function () { - console.info(TAG, 'usb testConnectDeviceParamErr040 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.configs = PARAM_NULL; - let ret = usbManager.connectDevice(devices); - console.info(TAG, 'usb [configs:null] connectDevice ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDeviceParamErr040 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_5200 - * @tc.name : testConnectDeviceParamErr041 - * @tc.desc : Negative test: devices configs is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDeviceParamErr041', 0, function () { - console.info(TAG, 'usb testConnectDeviceParamErr041 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.configs = PARAM_UNDEFINED; - let ret = usbManager.connectDevice(devices); - console.info(TAG, 'usb [configs:undefined] connectDevice ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDeviceParamErr041 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_5300 - * @tc.name : testConnectDeviceParamErr042 - * @tc.desc : Negative test: devices configs is null string "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDeviceParamErr042', 0, function () { - console.info(TAG, 'usb testConnectDeviceParamErr042 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.configs = PARAM_NULLSTRING; - let ret = usbManager.connectDevice(devices); - console.info(TAG, 'usb [configs:""] connectDevice ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDeviceParamErr042 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_5400 - * @tc.name : testConnectDeviceParamErr043 - * @tc.desc : Negative test: devices configs is number 123 - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testConnectDeviceParamErr043', 0, function () { - console.info(TAG, 'usb testConnectDeviceParamErr043 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - devices.configs = PARAM_NULLSTRING; - let ret = usbManager.connectDevice(devices); - console.info(TAG, 'usb [configs:123] connectDevice ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testConnectDeviceParamErr043 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_5500 - * @tc.name : testClosePipeParamErr001 - * @tc.desc : Negative test: Enter two parameters - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClosePipeParamErr001', 0, function () { - console.info(TAG, 'usb testClosePipeParamErr001 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - getPipe('testClosePipeParamErr001'); - try { - let ret = usbManager.closePipe(gPipe, gPipe); - console.info(TAG, 'usb Enter two parameters closePipe ret : ', ret); - expect(ret).assertEqual(0); - } catch (err) { - console.info(TAG, 'testClosePipeParamErr001 catch err : ', err.code, ', message: ', err.message); - expect(err !== null).assertFalse(); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_5600 - * @tc.name : testClosePipeParamErr002 - * @tc.desc : Negative test: pipe busNum is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClosePipeParamErr002', 0, function () { - console.info(TAG, 'usb testClosePipeParamErr002 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = PARAM_NULL; - let ret = usbManager.closePipe(gPipe); - console.info(TAG, 'usb [busNum:null] closePipe ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClosePipeParamErr002 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_5700 - * @tc.name : testClosePipeParamErr003 - * @tc.desc : Negative test: pipe busNum is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClosePipeParamErr003', 0, function () { - console.info(TAG, 'usb testClosePipeParamErr003 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = PARAM_UNDEFINED; - let ret = usbManager.closePipe(gPipe); - console.info(TAG, 'usb [busNum:undefined] closePipe ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClosePipeParamErr003 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_5800 - * @tc.name : testClosePipeParamErr004 - * @tc.desc : Negative test: pipe busNum is null string "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClosePipeParamErr004', 0, function () { - console.info(TAG, 'usb testClosePipeParamErr004 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = PARAM_NULLSTRING; - let ret = usbManager.closePipe(gPipe); - console.info(TAG, 'usb [busNum:""] closePipe ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClosePipeParamErr004 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_5900 - * @tc.name : testClosePipeParamErr005 - * @tc.desc : Negative test: pipe devAddress is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClosePipeParamErr005', 0, function () { - console.info(TAG, 'usb testClosePipeParamErr005 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.devAddress = PARAM_NULL; - let ret = usbManager.closePipe(gPipe); - console.info(TAG, 'usb [devAddress:null] closePipe ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClosePipeParamErr005 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_6000 - * @tc.name : testClosePipeParamErr006 - * @tc.desc : Negative test: pipe devAddress is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClosePipeParamErr006', 0, function () { - console.info(TAG, 'usb testClosePipeParamErr006 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.devAddress = PARAM_UNDEFINED; - let ret = usbManager.closePipe(gPipe); - console.info(TAG, 'usb [devAddress:undefined] closePipe ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClosePipeParamErr006 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_6100 - * @tc.name : testClosePipeParamErr007 - * @tc.desc : Negative test: devices devAddress is null string "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClosePipeParamErr007', 0, function () { - console.info(TAG, 'usb testClosePipeParamErr007 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.devAddress = PARAM_NULLSTRING; - let ret = usbManager.closePipe(gPipe); - console.info(TAG, 'usb [devAddress:""] closePipe ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClosePipeParamErr007 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_6200 - * @tc.name : testClosePipeParamErr008 - * @tc.desc : Negative test: Param is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClosePipeParamErr008', 0, function () { - console.info(TAG, 'usb testClosePipeParamErr008 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - let ret = usbManager.closePipe(PARAM_NULL); - console.info(TAG, 'usb [param:null] closePipe ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClosePipeParamErr008 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_6300 - * @tc.name : testClosePipeParamErr009 - * @tc.desc : Negative test: Param is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClosePipeParamErr009', 0, function () { - console.info(TAG, 'usb testClosePipeParamErr009 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - let ret = usbManager.closePipe(PARAM_UNDEFINED); - console.info(TAG, 'usb [param:undefined] closePipe ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClosePipeParamErr009 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_6400 - * @tc.name : testClosePipeParamErr010 - * @tc.desc : Negative test: Param is null string "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClosePipeParamErr010', 0, function () { - console.info(TAG, 'usb testClosePipeParamErr010 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - let ret = usbManager.closePipe(PARAM_NULLSTRING); - console.info(TAG, 'usb [param:""] closePipe ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClosePipeParamErr010 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_6500 - * @tc.name : testGetRawDescriptorParamErr001 - * @tc.desc : Negative test: Enter two parameters - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testGetRawDescriptorParamErr001', 0, function () { - console.info(TAG, 'usb testGetRawDescriptorParamErr001 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - getPipe('testGetRawDescriptorParamErr001'); - try { - let ret = usbManager.getRawDescriptor(gPipe, gPipe); - console.info(TAG, 'usb Enter two parameters getRawDescriptor ret : ', JSON.stringify(ret)); - expect(ret.length >= 0).assertTrue(); - } catch (err) { - console.info(TAG, 'testGetRawDescriptorParamErr001 catch err code: ', err.code, ', message: ', err.message); - expect(err !== null).assertFalse(); - } - toClosePipe('testGetRawDescriptorParamErr001'); - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_6600 - * @tc.name : testGetRawDescriptorParamErr002 - * @tc.desc : Negative test: Param is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testGetRawDescriptorParamErr002', 0, function () { - console.info(TAG, 'usb testGetRawDescriptorParamErr002 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - let ret = usbManager.getRawDescriptor(PARAM_NULL); - console.info(TAG, 'usb [param:null] getRawDescriptor ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testGetRawDescriptorParamErr002 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_6700 - * @tc.name : testGetRawDescriptorParamErr003 - * @tc.desc : Negative test: Param is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testGetRawDescriptorParamErr003', 0, function () { - console.info(TAG, 'usb testGetRawDescriptorParamErr003 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - let ret = usbManager.getRawDescriptor(PARAM_UNDEFINED); - console.info(TAG, 'usb [param:undefined] getRawDescriptor ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testGetRawDescriptorParamErr003 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_6800 - * @tc.name : testGetRawDescriptorParamErr004 - * @tc.desc : Negative test: Param is null string "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testGetRawDescriptorParamErr004', 0, function () { - console.info(TAG, 'usb testGetRawDescriptorParamErr004 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - let ret = usbManager.getRawDescriptor(PARAM_NULLSTRING); - console.info(TAG, 'usb [param:""] getRawDescriptor ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testGetRawDescriptorParamErr004 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_6900 - * @tc.name : testGetRawDescriptorParamErr005 - * @tc.desc : Negative test: pipe busNum is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testGetRawDescriptorParamErr005', 0, function () { - console.info(TAG, 'usb testGetRawDescriptorParamErr005 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = PARAM_NULL; - let ret = usbManager.getRawDescriptor(gPipe); - console.info(TAG, 'usb [busNum:null] getRawDescriptor ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testGetRawDescriptorParamErr005 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_7000 - * @tc.name : testGetRawDescriptorParamErr006 - * @tc.desc : Negative test: pipe busNum is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testGetRawDescriptorParamErr006', 0, function () { - console.info(TAG, 'usb testGetRawDescriptorParamErr006 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = PARAM_UNDEFINED; - let ret = usbManager.getRawDescriptor(gPipe); - console.info(TAG, 'usb [busNum:undefined] getRawDescriptor ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testGetRawDescriptorParamErr006 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_7100 - * @tc.name : testGetRawDescriptorParamErr007 - * @tc.desc : Negative test: pipe busNum is null string "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testGetRawDescriptorParamErr007', 0, function () { - console.info(TAG, 'usb testGetRawDescriptorParamErr007 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = PARAM_NULLSTRING; - let ret = usbManager.getRawDescriptor(gPipe); - console.info(TAG, 'usb [busNum:""] getRawDescriptor ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testGetRawDescriptorParamErr007 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_7200 - * @tc.name : testGetRawDescriptorParamErr008 - * @tc.desc : Negative test: pipe devAddress is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testGetRawDescriptorParamErr008', 0, function () { - console.info(TAG, 'usb testGetRawDescriptorParamErr008 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.devAddress = PARAM_NULL; - let ret = usbManager.getRawDescriptor(gPipe); - console.info(TAG, 'usb [devAddress:null] getRawDescriptor ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testGetRawDescriptorParamErr008 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_7300 - * @tc.name : testGetRawDescriptorParamErr009 - * @tc.desc : Negative test: pipe devAddress is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testGetRawDescriptorParamErr009', 0, function () { - console.info(TAG, 'usb testGetRawDescriptorParamErr009 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.devAddress = PARAM_UNDEFINED; - let ret = usbManager.getRawDescriptor(gPipe); - console.info(TAG, 'usb [devAddress:undefined] getRawDescriptor ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testGetRawDescriptorParamErr009 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_7400 - * @tc.name : testGetRawDescriptorParamErr010 - * @tc.desc : Negative test: devices devAddress is null string "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testGetRawDescriptorParamErr010', 0, function () { - console.info(TAG, 'usb testGetRawDescriptorParamErr010 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.devAddress = PARAM_NULLSTRING; - let ret = usbManager.getRawDescriptor(gPipe); - console.info(TAG, 'usb [devAddress:""] getRawDescriptor ret : ', JSON.stringify(ret)); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testGetRawDescriptorParamErr010 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_7500 - * @tc.name : testGetFileDescriptorParamErr001 - * @tc.desc : Negative test: Enter two parameters - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testGetFileDescriptorParamErr001', 0, function () { - console.info(TAG, 'usb testGetFileDescriptorParamErr001 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - getPipe('testGetRawDescriptorParamErr001'); - try { - let ret = usbManager.getFileDescriptor(gPipe, gPipe); - console.info(TAG, 'usb Enter two parameters getFileDescriptor ret : ', ret); - expect(ret >= 0).assertTrue(); - } catch (err) { - console.info(TAG, 'testGetFileDescriptorParamErr001 catch err code: ', - err.code, ', message: ', err.message); - expect(err !== null).assertFalse(); - } - toClosePipe('testGetRawDescriptorParamErr001'); - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_7600 - * @tc.name : testGetFileDescriptorParamErr002 - * @tc.desc : Negative test: Param is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testGetFileDescriptorParamErr002', 0, function () { - console.info(TAG, 'usb testGetFileDescriptorParamErr002 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - let ret = usbManager.getFileDescriptor(PARAM_NULL); - console.info(TAG, 'usb [param:null] getFileDescriptor ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testGetFileDescriptorParamErr002 catch err code: ', - err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_7700 - * @tc.name : testGetFileDescriptorParamErr003 - * @tc.desc : Negative test: Param is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testGetFileDescriptorParamErr003', 0, function () { - console.info(TAG, 'usb testGetFileDescriptorParamErr003 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - let ret = usbManager.getFileDescriptor(PARAM_UNDEFINED); - console.info(TAG, 'usb [param:undefined] getFileDescriptor ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testGetFileDescriptorParamErr003 catch err code: ', - err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_7800 - * @tc.name : testGetFileDescriptorParamErr004 - * @tc.desc : Negative test: Param is null string "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testGetFileDescriptorParamErr004', 0, function () { - console.info(TAG, 'usb testGetFileDescriptorParamErr004 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - let ret = usbManager.getFileDescriptor(PARAM_NULLSTRING); - console.info(TAG, 'usb [param:""] getFileDescriptor ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testGetFileDescriptorParamErr004 catch err code: ', - err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_7900 - * @tc.name : testGetFileDescriptorParamErr005 - * @tc.desc : Negative test: pipe busNum is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testGetFileDescriptorParamErr005', 0, function () { - console.info(TAG, 'usb testGetFileDescriptorParamErr005 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = PARAM_NULL; - let ret = usbManager.getFileDescriptor(gPipe); - console.info(TAG, 'usb [busNum:null] getFileDescriptor ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testGetFileDescriptorParamErr005 catch err code: ', - err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_8000 - * @tc.name : testGetFileDescriptorParamErr006 - * @tc.desc : Negative test: pipe busNum is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testGetFileDescriptorParamErr006', 0, function () { - console.info(TAG, 'usb testGetFileDescriptorParamErr006 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = PARAM_UNDEFINED; - let ret = usbManager.getFileDescriptor(gPipe); - console.info(TAG, 'usb [busNum:undefined] getFileDescriptor ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testGetFileDescriptorParamErr006 catch err code: ', - err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_8100 - * @tc.name : testGetFileDescriptorParamErr007 - * @tc.desc : Negative test: pipe busNum is null string "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testGetFileDescriptorParamErr007', 0, function () { - console.info(TAG, 'usb testGetFileDescriptorParamErr007 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = PARAM_NULLSTRING; - let ret = usbManager.getFileDescriptor(gPipe); - console.info(TAG, 'usb [busNum:""] getFileDescriptor ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testGetFileDescriptorParamErr007 catch err code: ', - err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_8200 - * @tc.name : testGetFileDescriptorParamErr008 - * @tc.desc : Negative test: pipe devAddress is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testGetFileDescriptorParamErr008', 0, function () { - console.info(TAG, 'usb testGetFileDescriptorParamErr008 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.devAddress = PARAM_NULL; - let ret = usbManager.getFileDescriptor(gPipe); - console.info(TAG, 'usb [devAddress:null] getFileDescriptor ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testGetFileDescriptorParamErr008 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_8300 - * @tc.name : testGetFileDescriptorParamErr009 - * @tc.desc : Negative test: pipe devAddress is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testGetFileDescriptorParamErr009', 0, function () { - console.info(TAG, 'usb testGetFileDescriptorParamErr009 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.devAddress = PARAM_UNDEFINED; - let ret = usbManager.getFileDescriptor(gPipe); - console.info(TAG, 'usb [devAddress:undefined] getFileDescriptor ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testGetFileDescriptorParamErr009 catch err code: ', - err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_8400 - * @tc.name : testGetFileDescriptorParamErr010 - * @tc.desc : Negative test: devices devAddress is null string "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testGetFileDescriptorParamErr010', 0, function () { - console.info(TAG, 'usb testGetFileDescriptorParamErr010 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.devAddress = PARAM_NULLSTRING; - let ret = usbManager.getFileDescriptor(gPipe); - console.info(TAG, 'usb [devAddress:""] getFileDescriptor ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testGetFileDescriptorParamErr010 catch err code: ', - err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_8500 - * @tc.name : testClaimInterfaceParamErr001 - * @tc.desc : Negative test: Param is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClaimInterfaceParamErr001', 0, function () { - console.info(TAG, 'usb testClaimInterfaceParamErr001 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - let ret = usbManager.claimInterface(PARAM_NULL); - console.info(TAG, 'usb [param:null] claimInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClaimInterfaceParamErr001 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_8600 - * @tc.name : testClaimInterfaceParamErr002 - * @tc.desc : Negative test: Param is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClaimInterfaceParamErr002', 0, function () { - console.info(TAG, 'usb testClaimInterfaceParamErr002 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - let ret = usbManager.claimInterface(PARAM_UNDEFINED); - console.info(TAG, 'usb [param:undefined] claimInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClaimInterfaceParamErr002 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_8700 - * @tc.name : testClaimInterfaceParamErr003 - * @tc.desc : Negative test: Param is null string "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClaimInterfaceParamErr003', 0, function () { - console.info(TAG, 'usb testClaimInterfaceParamErr003 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - let ret = usbManager.claimInterface(PARAM_NULLSTRING); - console.info(TAG, 'usb [param:""] claimInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClaimInterfaceParamErr003 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_8800 - * @tc.name : testClaimInterfaceParamErr004 - * @tc.desc : Negative test: pipe busNum is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClaimInterfaceParamErr004', 0, function () { - console.info(TAG, 'usb testClaimInterfaceParamErr004 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = PARAM_NULL; - let tmpInterface = devices.configs[0].interfaces[0]; - let ret = usbManager.claimInterface(gPipe, tmpInterface); - console.info(TAG, 'usb [busNum:null] claimInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClaimInterfaceParamErr004 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_8900 - * @tc.name : testClaimInterfaceParamErr005 - * @tc.desc : Negative test: pipe busNum is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClaimInterfaceParamErr005', 0, function () { - console.info(TAG, 'usb testClaimInterfaceParamErr005 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = PARAM_UNDEFINED; - let tmpInterface = devices.configs[0].interfaces[0]; - let ret = usbManager.claimInterface(gPipe, tmpInterface); - console.info(TAG, 'usb [busNum:undefined] claimInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClaimInterfaceParamErr005 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_9000 - * @tc.name : testClaimInterfaceParamErr006 - * @tc.desc : Negative test: pipe busNum is null string "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClaimInterfaceParamErr006', 0, function () { - console.info(TAG, 'usb testClaimInterfaceParamErr006 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = PARAM_NULLSTRING; - let tmpInterface = devices.configs[0].interfaces[0]; - let ret = usbManager.claimInterface(gPipe, tmpInterface); - console.info(TAG, 'usb [busNum:""] claimInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClaimInterfaceParamErr006 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_9100 - * @tc.name : testClaimInterfaceParamErr007 - * @tc.desc : Negative test: pipe devAddress is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClaimInterfaceParamErr007', 0, function () { - console.info(TAG, 'usb testClaimInterfaceParamErr007 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.devAddress = PARAM_NULL; - let tmpInterface = devices.configs[0].interfaces[0]; - let ret = usbManager.claimInterface(gPipe, tmpInterface); - console.info(TAG, 'usb [devAddress:null] claimInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClaimInterfaceParamErr007 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_9200 - * @tc.name : testClaimInterfaceParamErr008 - * @tc.desc : Negative test: pipe devAddress is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClaimInterfaceParamErr008', 0, function () { - console.info(TAG, 'usb testClaimInterfaceParamErr008 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.devAddress = PARAM_UNDEFINED; - let tmpInterface = devices.configs[0].interfaces[0]; - let ret = usbManager.claimInterface(gPipe, tmpInterface); - console.info(TAG, 'usb [devAddress:undefined] claimInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClaimInterfaceParamErr008 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_9300 - * @tc.name : testClaimInterfaceParamErr009 - * @tc.desc : Negative test: pipe devAddress is null string "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClaimInterfaceParamErr009', 0, function () { - console.info(TAG, 'usb testClaimInterfaceParamErr009 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.devAddress = PARAM_NULLSTRING; - let tmpInterface = devices.configs[0].interfaces[0]; - let ret = usbManager.claimInterface(gPipe, tmpInterface); - console.info(TAG, 'usb [devAddress:""] claimInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClaimInterfaceParamErr009 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_9400 - * @tc.name : testClaimInterfaceParamErr010 - * @tc.desc : Negative test: interfaces id is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClaimInterfaceParamErr010', 0, function () { - console.info(TAG, 'usb testClaimInterfaceParamErr010 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpInterface = devices.configs[0].interfaces[0]; - tmpInterface.id = PARAM_NULL; - let ret = usbManager.claimInterface(gPipe, tmpInterface); - console.info(TAG, 'usb [interfaces.id:null] claimInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClaimInterfaceParamErr010 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_9500 - * @tc.name : testClaimInterfaceParamErr011 - * @tc.desc : Negative test: interfaces id is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClaimInterfaceParamErr011', 0, function () { - console.info(TAG, 'usb testClaimInterfaceParamErr011 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpInterface = devices.configs[0].interfaces[0]; - tmpInterface.id = PARAM_UNDEFINED; - let ret = usbManager.claimInterface(gPipe, tmpInterface); - console.info(TAG, 'usb [interfaces.id:undefined] claimInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClaimInterfaceParamErr011 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_9600 - * @tc.name : testClaimInterfaceParamErr012 - * @tc.desc : Negative test: interfaces id is null string "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClaimInterfaceParamErr012', 0, function () { - console.info(TAG, 'usb testClaimInterfaceParamErr012 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpInterface = devices.configs[0].interfaces[0]; - tmpInterface.id = PARAM_NULLSTRING; - let ret = usbManager.claimInterface(gPipe, tmpInterface); - console.info(TAG, 'usb [interfaces.id:""] claimInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClaimInterfaceParamErr012 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_9700 - * @tc.name : testClaimInterfaceParamErr013 - * @tc.desc : Negative test: interfaces protocol is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClaimInterfaceParamErr013', 0, function () { - console.info(TAG, 'usb testClaimInterfaceParamErr013 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpInterface = devices.configs[0].interfaces[0]; - tmpInterface.protocol = PARAM_NULL; - let ret = usbManager.claimInterface(gPipe, tmpInterface); - console.info(TAG, 'usb [interfaces.protocol:null] claimInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClaimInterfaceParamErr013 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_9800 - * @tc.name : testClaimInterfaceParamErr014 - * @tc.desc : Negative test: interfaces protocol is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClaimInterfaceParamErr014', 0, function () { - console.info(TAG, 'usb testClaimInterfaceParamErr014 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpInterface = devices.configs[0].interfaces[0]; - tmpInterface.protocol = PARAM_UNDEFINED; - let ret = usbManager.claimInterface(gPipe, tmpInterface); - console.info(TAG, 'usb [interfaces.protocol:undefined] claimInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClaimInterfaceParamErr014 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_9900 - * @tc.name : testClaimInterfaceParamErr015 - * @tc.desc : Negative test: interfaces protocol is null string "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClaimInterfaceParamErr015', 0, function () { - console.info(TAG, 'usb testClaimInterfaceParamErr015 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpInterface = devices.configs[0].interfaces[0]; - tmpInterface.protocol = PARAM_NULLSTRING; - let ret = usbManager.claimInterface(gPipe, tmpInterface); - console.info(TAG, 'usb [interfaces.protocol:""] claimInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClaimInterfaceParamErr015 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0110 - * @tc.name : testClaimInterfaceParamErr016 - * @tc.desc : Negative test: interfaces clazz is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClaimInterfaceParamErr016', 0, function () { - console.info(TAG, 'usb testClaimInterfaceParamErr016 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpInterface = devices.configs[0].interfaces[0]; - tmpInterface.clazz = PARAM_NULL; - let ret = usbManager.claimInterface(gPipe, tmpInterface); - console.info(TAG, 'usb [interfaces.clazz:null] claimInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClaimInterfaceParamErr016 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0120 - * @tc.name : testClaimInterfaceParamErr017 - * @tc.desc : Negative test: interfaces clazz is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClaimInterfaceParamErr017', 0, function () { - console.info(TAG, 'usb testClaimInterfaceParamErr017 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpInterface = devices.configs[0].interfaces[0]; - tmpInterface.clazz = PARAM_UNDEFINED; - let ret = usbManager.claimInterface(gPipe, tmpInterface); - console.info(TAG, 'usb [interfaces.clazz:undefined] claimInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClaimInterfaceParamErr017 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0130 - * @tc.name : testClaimInterfaceParamErr018 - * @tc.desc : Negative test: interfaces clazz is null string "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClaimInterfaceParamErr018', 0, function () { - console.info(TAG, 'usb testClaimInterfaceParamErr018 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpInterface = devices.configs[0].interfaces[0]; - tmpInterface.clazz = PARAM_NULLSTRING; - let ret = usbManager.claimInterface(gPipe, tmpInterface); - console.info(TAG, 'usb [interfaces.clazz:""] claimInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClaimInterfaceParamErr018 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0140 - * @tc.name : testClaimInterfaceParamErr019 - * @tc.desc : Negative test: interfaces name is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClaimInterfaceParamErr019', 0, function () { - console.info(TAG, 'usb testClaimInterfaceParamErr019 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpInterface = devices.configs[0].interfaces[0]; - tmpInterface.name = PARAM_NULL; - let ret = usbManager.claimInterface(gPipe, tmpInterface); - console.info(TAG, 'usb [interfaces.name:null] claimInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClaimInterfaceParamErr019 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0150 - * @tc.name : testClaimInterfaceParamErr020 - * @tc.desc : Negative test: interfaces name is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClaimInterfaceParamErr020', 0, function () { - console.info(TAG, 'usb testClaimInterfaceParamErr020 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpInterface = devices.configs[0].interfaces[0]; - tmpInterface.name = PARAM_UNDEFINED; - let ret = usbManager.claimInterface(gPipe, tmpInterface); - console.info(TAG, 'usb [interfaces.name:undefined] claimInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClaimInterfaceParamErr020 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0160 - * @tc.name : testClaimInterfaceParamErr021 - * @tc.desc : Negative test: interfaces name is number - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClaimInterfaceParamErr021', 0, function () { - console.info(TAG, 'usb testClaimInterfaceParamErr021 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpInterface = devices.configs[0].interfaces[0]; - tmpInterface.name = PARAM_NUMBERTYPE; - let ret = usbManager.claimInterface(gPipe, tmpInterface); - console.info(TAG, 'usb [interfaces.name:number_123] claimInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClaimInterfaceParamErr021 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0170 - * @tc.name : testClaimInterfaceParamErr022 - * @tc.desc : Negative test: interfaces subClass is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClaimInterfaceParamErr022', 0, function () { - console.info(TAG, 'usb testClaimInterfaceParamErr022 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpInterface = devices.configs[0].interfaces[0]; - tmpInterface.subClass = PARAM_NULL; - let ret = usbManager.claimInterface(gPipe, tmpInterface); - console.info(TAG, 'usb [interfaces.subClass:null] claimInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClaimInterfaceParamErr022 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0180 - * @tc.name : testClaimInterfaceParamErr023 - * @tc.desc : Negative test: interfaces subClass is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClaimInterfaceParamErr023', 0, function () { - console.info(TAG, 'usb testClaimInterfaceParamErr023 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpInterface = devices.configs[0].interfaces[0]; - tmpInterface.subClass = PARAM_UNDEFINED; - let ret = usbManager.claimInterface(gPipe, tmpInterface); - console.info(TAG, 'usb [interfaces.subClass:undefined] claimInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClaimInterfaceParamErr023 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0190 - * @tc.name : testClaimInterfaceParamErr024 - * @tc.desc : Negative test: interfaces subClass is null string "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClaimInterfaceParamErr024', 0, function () { - console.info(TAG, 'usb testClaimInterfaceParamErr024 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpInterface = devices.configs[0].interfaces[0]; - tmpInterface.subClass = PARAM_NULLSTRING; - let ret = usbManager.claimInterface(gPipe, tmpInterface); - console.info(TAG, 'usb [interfaces.subClass:""] claimInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClaimInterfaceParamErr024 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0210 - * @tc.name : testClaimInterfaceParamErr025 - * @tc.desc : Negative test: interfaces alternateSetting is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClaimInterfaceParamErr025', 0, function () { - console.info(TAG, 'usb testClaimInterfaceParamErr025 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpInterface = devices.configs[0].interfaces[0]; - tmpInterface.alternateSetting = PARAM_NULL; - let ret = usbManager.claimInterface(gPipe, tmpInterface); - console.info(TAG, 'usb [interfaces.alternateSetting:null] claimInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClaimInterfaceParamErr025 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0220 - * @tc.name : testClaimInterfaceParamErr026 - * @tc.desc : Negative test: interfaces alternateSetting is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClaimInterfaceParamErr026', 0, function () { - console.info(TAG, 'usb testClaimInterfaceParamErr026 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpInterface = devices.configs[0].interfaces[0]; - tmpInterface.alternateSetting = PARAM_UNDEFINED; - let ret = usbManager.claimInterface(gPipe, tmpInterface); - console.info(TAG, 'usb [interfaces.alternateSetting:undefined] claimInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClaimInterfaceParamErr026 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0230 - * @tc.name : testClaimInterfaceParamErr027 - * @tc.desc : Negative test: interfaces alternateSetting is null string "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClaimInterfaceParamErr027', 0, function () { - console.info(TAG, 'usb testClaimInterfaceParamErr027 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpInterface = devices.configs[0].interfaces[0]; - tmpInterface.alternateSetting = PARAM_NULLSTRING; - let ret = usbManager.claimInterface(gPipe, tmpInterface); - console.info(TAG, 'usb [interfaces.alternateSetting:""] claimInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClaimInterfaceParamErr027 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0240 - * @tc.name : testClaimInterfaceParamErr028 - * @tc.desc : Negative test: interfaces endpoints is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClaimInterfaceParamErr028', 0, function () { - console.info(TAG, 'usb testClaimInterfaceParamErr028 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpInterface = devices.configs[0].interfaces[0]; - tmpInterface.endpoints = PARAM_NULL; - let ret = usbManager.claimInterface(gPipe, tmpInterface); - console.info(TAG, 'usb [interfaces.endpoints:null] claimInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClaimInterfaceParamErr028 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0250 - * @tc.name : testClaimInterfaceParamErr029 - * @tc.desc : Negative test: interfaces endpoints is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClaimInterfaceParamErr029', 0, function () { - console.info(TAG, 'usb testClaimInterfaceParamErr029 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpInterface = devices.configs[0].interfaces[0]; - tmpInterface.endpoints = PARAM_UNDEFINED; - let ret = usbManager.claimInterface(gPipe, tmpInterface); - console.info(TAG, 'usb [interfaces.endpoints:undefined] claimInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClaimInterfaceParamErr029 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0260 - * @tc.name : testClaimInterfaceParamErr030 - * @tc.desc : Negative test: interfaces endpoints is null string "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClaimInterfaceParamErr030', 0, function () { - console.info(TAG, 'usb testClaimInterfaceParamErr030 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpInterface = devices.configs[0].interfaces[0]; - tmpInterface.endpoints = PARAM_NULLSTRING; - let ret = usbManager.claimInterface(gPipe, tmpInterface); - console.info(TAG, 'usb [interfaces.endpoints:""] claimInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClaimInterfaceParamErr030 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0270 - * @tc.name : testClaimInterfaceParamErr031 - * @tc.desc : Negative test: Enter four parameters - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClaimInterfaceParamErr031', 0, function () { - console.info(TAG, 'usb testClaimInterfaceParamErr031 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - getPipe('testClaimInterfaceParamErr031'); - let tmpInterface = devices.configs[0].interfaces[0]; - try { - let ret = usbManager.claimInterface(gPipe, tmpInterface, true, gPipe); - console.info(TAG, 'usb [Enter four param] claimInterface ret : ', ret); - expect(ret).assertEqual(0); - } catch (err) { - console.info(TAG, 'testClaimInterfaceParamErr031 catch err code: ', err.code, ', message: ', err.message); - expect(err !== null).assertFalse(); - } - toReleaseInterface('testClaimInterfaceParamErr031', tmpInterface); - toClosePipe('testClaimInterfaceParamErr031'); - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0280 - * @tc.name : testClaimInterfaceParamErr032 - * @tc.desc : Negative test: iface is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClaimInterfaceParamErr032', 0, function () { - console.info(TAG, 'usb testClaimInterfaceParamErr032 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let ret = usbManager.claimInterface(gPipe, PARAM_NULL); - console.info(TAG, 'usb [iface:null] claimInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClaimInterfaceParamErr032 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0290 - * @tc.name : testClaimInterfaceParamErr033 - * @tc.desc : Negative test: iface is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClaimInterfaceParamErr033', 0, function () { - console.info(TAG, 'usb testClaimInterfaceParamErr033 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let ret = usbManager.claimInterface(gPipe, PARAM_UNDEFINED); - console.info(TAG, 'usb [iface:undefined] claimInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClaimInterfaceParamErr033 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0310 - * @tc.name : testClaimInterfaceParamErr034 - * @tc.desc : Negative test: iface is "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClaimInterfaceParamErr034', 0, function () { - console.info(TAG, 'usb testClaimInterfaceParamErr034 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let ret = usbManager.claimInterface(gPipe, PARAM_NULLSTRING); - console.info(TAG, 'usb [iface:""] claimInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClaimInterfaceParamErr034 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0320 - * @tc.name : testClaimInterfaceParamErr035 - * @tc.desc : Negative test: pipe is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClaimInterfaceParamErr035', 0, function () { - console.info(TAG, 'usb testClaimInterfaceParamErr035 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - let tmpInterface = devices.configs[0].interfaces[0]; - let ret = usbManager.claimInterface(PARAM_NULL, tmpInterface); - console.info(TAG, 'usb [iface:null] claimInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClaimInterfaceParamErr035 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0330 - * @tc.name : testClaimInterfaceParamErr036 - * @tc.desc : Negative test: pipe is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClaimInterfaceParamErr036', 0, function () { - console.info(TAG, 'usb testClaimInterfaceParamErr036 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - let tmpInterface = devices.configs[0].interfaces[0]; - let ret = usbManager.claimInterface(PARAM_UNDEFINED, tmpInterface); - console.info(TAG, 'usb [iface:undefined] claimInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClaimInterfaceParamErr036 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0340 - * @tc.name : testClaimInterfaceParamErr037 - * @tc.desc : Negative test: pipe is "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClaimInterfaceParamErr037', 0, function () { - console.info(TAG, 'usb testClaimInterfaceParamErr037 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - let tmpInterface = devices.configs[0].interfaces[0]; - let ret = usbManager.claimInterface(PARAM_NULLSTRING, tmpInterface); - console.info(TAG, 'usb [iface:""] claimInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testClaimInterfaceParamErr037 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0350 - * @tc.name : testClaimInterfaceParamErr038 - * @tc.desc : Negative test: force is null string - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testClaimInterfaceParamErr038', 0, function () { - console.info(TAG, 'usb testClaimInterfaceParamErr038 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - getPipe('testClaimInterfaceParamErr038'); - let tmpInterface = devices.configs[0].interfaces[0]; - try { - let ret = usbManager.claimInterface(gPipe, tmpInterface, PARAM_NULLSTRING); - console.info(TAG, 'usb [force:""] claimInterface ret : ', ret); - expect(ret).assertEqual(0); - } catch (err) { - console.info(TAG, 'testClaimInterfaceParamErr038 catch err code: ', err.code, ', message: ', err.message); - expect(err !== null).assertFalse(); - } - toReleaseInterface('testClaimInterfaceParamErr038', tmpInterface); - toClosePipe('testClaimInterfaceParamErr038'); - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0360 - * @tc.name : testSetConfigurationParamErr001 - * @tc.desc : Negative test: Enter two parameters - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetConfigurationParamErr001', 0, function () { - console.info(TAG, 'usb testSetConfigurationParamErr001 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - getPipe('testSetConfigurationParamErr001'); - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpConfig = devices.configs[0]; - let ret = usbManager.setConfiguration(gPipe, tmpConfig, gPipe); - console.info(TAG, 'usb [Enter two parameters] setConfiguration ret : ', ret); - expect(ret).assertEqual(0); - } catch (err) { - console.info(TAG, 'testSetConfigurationParamErr001 catch err code: ', err.code, ', message: ', err.message); - expect(err !== null).assertFalse(); - } - toClosePipe('testSetConfigurationParamErr001'); - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0370 - * @tc.name : testSetConfigurationParamErr002 - * @tc.desc : Negative test: Param is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetConfigurationParamErr002', 0, function () { - console.info(TAG, 'usb testSetConfigurationParamErr002 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - let ret = usbManager.setConfiguration(PARAM_NULL); - console.info(TAG, 'usb [param:null] setConfiguration ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testSetConfigurationParamErr002 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0380 - * @tc.name : testSetConfigurationParamErr003 - * @tc.desc : Negative test: Param is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetConfigurationParamErr003', 0, function () { - console.info(TAG, 'usb testSetConfigurationParamErr003 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - let ret = usbManager.setConfiguration(PARAM_UNDEFINED); - console.info(TAG, 'usb [param:undefined] setConfiguration ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testSetConfigurationParamErr003 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0390 - * @tc.name : testSetConfigurationParamErr004 - * @tc.desc : Negative test: Param is "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetConfigurationParamErr004', 0, function () { - console.info(TAG, 'usb testSetConfigurationParamErr004 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - let ret = usbManager.setConfiguration(PARAM_NULLSTRING); - console.info(TAG, 'usb [param:""] setConfiguration ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testSetConfigurationParamErr004 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0410 - * @tc.name : testSetConfigurationParamErr005 - * @tc.desc : Negative test: pipe is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetConfigurationParamErr005', 0, function () { - console.info(TAG, 'usb testSetConfigurationParamErr005 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - let tmpConfig = devices.configs[0]; - let ret = usbManager.setConfiguration(PARAM_NULL, tmpConfig); - console.info(TAG, 'usb [pipe:null] setConfiguration ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testSetConfigurationParamErr005 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0420 - * @tc.name : testSetConfigurationParamErr006 - * @tc.desc : Negative test: pipe is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetConfigurationParamErr006', 0, function () { - console.info(TAG, 'usb testSetConfigurationParamErr006 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - let tmpConfig = devices.configs[0]; - let ret = usbManager.setConfiguration(PARAM_UNDEFINED, tmpConfig); - console.info(TAG, 'usb [pipe:undefined] setConfiguration ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testSetConfigurationParamErr006 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0430 - * @tc.name : testSetConfigurationParamErr007 - * @tc.desc : Negative test: pipe is "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetConfigurationParamErr007', 0, function () { - console.info(TAG, 'usb testSetConfigurationParamErr007 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - let tmpConfig = devices.configs[0]; - let ret = usbManager.setConfiguration(PARAM_NULLSTRING, tmpConfig); - console.info(TAG, 'usb [pipe:""] setConfiguration ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testSetConfigurationParamErr007 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0440 - * @tc.name : testSetConfigurationParamErr008 - * @tc.desc : Negative test: config is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetConfigurationParamErr008', 0, function () { - console.info(TAG, 'usb testSetConfigurationParamErr008 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let ret = usbManager.setConfiguration(gPipe, PARAM_NULL); - console.info(TAG, 'usb [config:null] setConfiguration ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testSetConfigurationParamErr008 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0450 - * @tc.name : testSetConfigurationParamErr009 - * @tc.desc : Negative test: config is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetConfigurationParamErr009', 0, function () { - console.info(TAG, 'usb testSetConfigurationParamErr009 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let ret = usbManager.setConfiguration(gPipe, PARAM_UNDEFINED); - console.info(TAG, 'usb [config:undefined] setConfiguration ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testSetConfigurationParamErr009 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0460 - * @tc.name : testSetConfigurationParamErr010 - * @tc.desc : Negative test: config is "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetConfigurationParamErr010', 0, function () { - console.info(TAG, 'usb testSetConfigurationParamErr010 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let ret = usbManager.setConfiguration(gPipe, PARAM_NULLSTRING); - console.info(TAG, 'usb [config:""] setConfiguration ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testSetConfigurationParamErr010 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0470 - * @tc.name : testSetConfigurationParamErr011 - * @tc.desc : Negative test: config id is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetConfigurationParamErr011', 0, function () { - console.info(TAG, 'usb testSetConfigurationParamErr011 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpConfig = devices.configs[0]; - tmpConfig.id = PARAM_NULL; - let ret = usbManager.setConfiguration(gPipe, tmpConfig); - console.info(TAG, 'usb [config.id:null] setConfiguration ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testSetConfigurationParamErr011 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0480 - * @tc.name : testSetConfigurationParamErr012 - * @tc.desc : Negative test: config id is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetConfigurationParamErr012', 0, function () { - console.info(TAG, 'usb testSetConfigurationParamErr012 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpConfig = devices.configs[0]; - tmpConfig.id = PARAM_UNDEFINED; - let ret = usbManager.setConfiguration(gPipe, tmpConfig); - console.info(TAG, 'usb [config.id:undefined] setConfiguration ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testSetConfigurationParamErr012 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0490 - * @tc.name : testSetConfigurationParamErr013 - * @tc.desc : Negative test: config id is "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetConfigurationParamErr013', 0, function () { - console.info(TAG, 'usb testSetConfigurationParamErr013 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpConfig = devices.configs[0]; - tmpConfig.id = PARAM_NULLSTRING; - let ret = usbManager.setConfiguration(gPipe, tmpConfig); - console.info(TAG, 'usb [config.id:""] setConfiguration ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testSetConfigurationParamErr013 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0510 - * @tc.name : testSetConfigurationParamErr014 - * @tc.desc : Negative test: config attributes is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetConfigurationParamErr014', 0, function () { - console.info(TAG, 'usb testSetConfigurationParamErr014 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpConfig = devices.configs[0]; - tmpConfig.attributes = PARAM_NULL; - let ret = usbManager.setConfiguration(gPipe, tmpConfig); - console.info(TAG, 'usb [config.attributes:null] setConfiguration ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testSetConfigurationParamErr014 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0520 - * @tc.name : testSetConfigurationParamErr015 - * @tc.desc : Negative test: config attributes is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetConfigurationParamErr015', 0, function () { - console.info(TAG, 'usb testSetConfigurationParamErr015 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpConfig = devices.configs[0]; - tmpConfig.attributes = PARAM_UNDEFINED; - let ret = usbManager.setConfiguration(gPipe, tmpConfig); - console.info(TAG, 'usb [config.attributes:undefined] setConfiguration ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testSetConfigurationParamErr015 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0530 - * @tc.name : testSetConfigurationParamErr016 - * @tc.desc : Negative test: config attributes is "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetConfigurationParamErr016', 0, function () { - console.info(TAG, 'usb testSetConfigurationParamErr016 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpConfig = devices.configs[0]; - tmpConfig.attributes = PARAM_NULLSTRING; - let ret = usbManager.setConfiguration(gPipe, tmpConfig); - console.info(TAG, 'usb [config.attributes:""] setConfiguration ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testSetConfigurationParamErr016 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0540 - * @tc.name : testSetConfigurationParamErr017 - * @tc.desc : Negative test: config maxPower is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetConfigurationParamErr017', 0, function () { - console.info(TAG, 'usb testSetConfigurationParamErr017 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpConfig = devices.configs[0]; - tmpConfig.maxPower = PARAM_NULL; - let ret = usbManager.setConfiguration(gPipe, tmpConfig); - console.info(TAG, 'usb [config.maxPower:null] setConfiguration ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testSetConfigurationParamErr017 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0550 - * @tc.name : testSetConfigurationParamErr018 - * @tc.desc : Negative test: config maxPower is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetConfigurationParamErr018', 0, function () { - console.info(TAG, 'usb testSetConfigurationParamErr018 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpConfig = devices.configs[0]; - tmpConfig.maxPower = PARAM_UNDEFINED; - let ret = usbManager.setConfiguration(gPipe, tmpConfig); - console.info(TAG, 'usb [config.maxPower:undefined] setConfiguration ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testSetConfigurationParamErr018 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0560 - * @tc.name : testSetConfigurationParamErr019 - * @tc.desc : Negative test: config maxPower is "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetConfigurationParamErr019', 0, function () { - console.info(TAG, 'usb testSetConfigurationParamErr019 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpConfig = devices.configs[0]; - tmpConfig.maxPower = PARAM_NULLSTRING; - let ret = usbManager.setConfiguration(gPipe, tmpConfig); - console.info(TAG, 'usb [config.maxPower:""] setConfiguration ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testSetConfigurationParamErr019 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0570 - * @tc.name : testSetConfigurationParamErr020 - * @tc.desc : Negative test: config name is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetConfigurationParamErr020', 0, function () { - console.info(TAG, 'usb testSetConfigurationParamErr020 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpConfig = devices.configs[0]; - tmpConfig.name = PARAM_NULL; - let ret = usbManager.setConfiguration(gPipe, tmpConfig); - console.info(TAG, 'usb [config.name:null] setConfiguration ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testSetConfigurationParamErr020 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0580 - * @tc.name : testSetConfigurationParamErr021 - * @tc.desc : Negative test: config name is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetConfigurationParamErr021', 0, function () { - console.info(TAG, 'usb testSetConfigurationParamErr021 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpConfig = devices.configs[0]; - tmpConfig.name = PARAM_UNDEFINED; - let ret = usbManager.setConfiguration(gPipe, tmpConfig); - console.info(TAG, 'usb [config.name:undefined] setConfiguration ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testSetConfigurationParamErr021 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0590 - * @tc.name : testSetConfigurationParamErr022 - * @tc.desc : Negative test: config name is 123 - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetConfigurationParamErr022', 0, function () { - console.info(TAG, 'usb testSetConfigurationParamErr022 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpConfig = devices.configs[0]; - tmpConfig.name = PARAM_NUMBERTYPE; - let ret = usbManager.setConfiguration(gPipe, tmpConfig); - console.info(TAG, 'usb [config.name:""] setConfiguration ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testSetConfigurationParamErr022 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0610 - * @tc.name : testSetConfigurationParamErr023 - * @tc.desc : Negative test: config isRemoteWakeup is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetConfigurationParamErr023', 0, function () { - console.info(TAG, 'usb testSetConfigurationParamErr023 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpConfig = devices.configs[0]; - tmpConfig.isRemoteWakeup = PARAM_NULL; - let ret = usbManager.setConfiguration(gPipe, tmpConfig); - console.info(TAG, 'usb [config.isRemoteWakeup:null] setConfiguration ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testSetConfigurationParamErr023 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0620 - * @tc.name : testSetConfigurationParamErr024 - * @tc.desc : Negative test: config isRemoteWakeup is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetConfigurationParamErr024', 0, function () { - console.info(TAG, 'usb testSetConfigurationParamErr024 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpConfig = devices.configs[0]; - tmpConfig.isRemoteWakeup = PARAM_UNDEFINED; - let ret = usbManager.setConfiguration(gPipe, tmpConfig); - console.info(TAG, 'usb [config.isRemoteWakeup:undefined] setConfiguration ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testSetConfigurationParamErr024 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0630 - * @tc.name : testSetConfigurationParamErr025 - * @tc.desc : Negative test: config isRemoteWakeup is "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetConfigurationParamErr025', 0, function () { - console.info(TAG, 'usb testSetConfigurationParamErr025 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpConfig = devices.configs[0]; - tmpConfig.isRemoteWakeup = PARAM_NULLSTRING; - let ret = usbManager.setConfiguration(gPipe, tmpConfig); - console.info(TAG, 'usb [config.isRemoteWakeup:""] setConfiguration ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testSetConfigurationParamErr025 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0640 - * @tc.name : testSetConfigurationParamErr026 - * @tc.desc : Negative test: config isSelfPowered is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetConfigurationParamErr026', 0, function () { - console.info(TAG, 'usb testSetConfigurationParamErr026 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpConfig = devices.configs[0]; - tmpConfig.isSelfPowered = PARAM_NULL; - let ret = usbManager.setConfiguration(gPipe, tmpConfig); - console.info(TAG, 'usb [config.isSelfPowered:null] setConfiguration ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testSetConfigurationParamErr026 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0650 - * @tc.name : testSetConfigurationParamErr027 - * @tc.desc : Negative test: config isSelfPowered is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetConfigurationParamErr027', 0, function () { - console.info(TAG, 'usb testSetConfigurationParamErr027 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpConfig = devices.configs[0]; - tmpConfig.isSelfPowered = PARAM_UNDEFINED; - let ret = usbManager.setConfiguration(gPipe, tmpConfig); - console.info(TAG, 'usb [config.isSelfPowered:undefined] setConfiguration ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testSetConfigurationParamErr027 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0660 - * @tc.name : testSetConfigurationParamErr028 - * @tc.desc : Negative test: config isSelfPowered is "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetConfigurationParamErr028', 0, function () { - console.info(TAG, 'usb testSetConfigurationParamErr028 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpConfig = devices.configs[0]; - tmpConfig.isSelfPowered = PARAM_NULLSTRING; - let ret = usbManager.setConfiguration(gPipe, tmpConfig); - console.info(TAG, 'usb [config.isSelfPowered:""] setConfiguration ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testSetConfigurationParamErr028 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0670 - * @tc.name : testSetConfigurationParamErr029 - * @tc.desc : Negative test: config interfaces is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetConfigurationParamErr029', 0, function () { - console.info(TAG, 'usb testSetConfigurationParamErr029 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpConfig = devices.configs[0]; - tmpConfig.interfaces = PARAM_NULL; - let ret = usbManager.setConfiguration(gPipe, tmpConfig); - console.info(TAG, 'usb [config.interfaces:null] setConfiguration ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testSetConfigurationParamErr029 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0680 - * @tc.name : testSetConfigurationParamErr030 - * @tc.desc : Negative test: config interfaces is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetConfigurationParamErr030', 0, function () { - console.info(TAG, 'usb testSetConfigurationParamErr030 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpConfig = devices.configs[0]; - tmpConfig.interfaces = PARAM_UNDEFINED; - let ret = usbManager.setConfiguration(gPipe, tmpConfig); - console.info(TAG, 'usb [config.interfaces:undefined] setConfiguration ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testSetConfigurationParamErr030 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0690 - * @tc.name : testSetConfigurationParamErr031 - * @tc.desc : Negative test: config interfaces is "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetConfigurationParamErr031', 0, function () { - console.info(TAG, 'usb testSetConfigurationParamErr031 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpConfig = devices.configs[0]; - tmpConfig.interfaces = PARAM_NULLSTRING; - let ret = usbManager.setConfiguration(gPipe, tmpConfig); - console.info(TAG, 'usb [config.interfaces:""] setConfiguration ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testSetConfigurationParamErr031 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0710 - * @tc.name : testSetConfigurationParamErr032 - * @tc.desc : Negative test: config isRemoteWakeup is 123 - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetConfigurationParamErr032', 0, function () { - console.info(TAG, 'usb testSetConfigurationParamErr032 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpConfig = devices.configs[0]; - tmpConfig.isRemoteWakeup = PARAM_NUMBERTYPE; - let ret = usbManager.setConfiguration(gPipe, tmpConfig); - console.info(TAG, 'usb [config.isRemoteWakeup:123] setConfiguration ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testSetConfigurationParamErr032 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0720 - * @tc.name : testSetConfigurationParamErr033 - * @tc.desc : Negative test: config isSelfPowered is 123 - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetConfigurationParamErr033', 0, function () { - console.info(TAG, 'usb testSetConfigurationParamErr033 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpConfig = devices.configs[0]; - tmpConfig.isSelfPowered = PARAM_NUMBERTYPE; - let ret = usbManager.setConfiguration(gPipe, tmpConfig); - console.info(TAG, 'usb [config.isSelfPowered:123] setConfiguration ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testSetConfigurationParamErr033 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0730 - * @tc.name : testSetConfigurationParamErr034 - * @tc.desc : Negative test: config interfaces is 123 - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetConfigurationParamErr034', 0, function () { - console.info(TAG, 'usb testSetConfigurationParamErr034 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - gPipe.busNum = devices.busNum; - gPipe.devAddress = devices.devAddress; - let tmpConfig = devices.configs[0]; - tmpConfig.interfaces = PARAM_NUMBERTYPE; - let ret = usbManager.setConfiguration(gPipe, tmpConfig); - console.info(TAG, 'usb [config.interfaces:123] setConfiguration ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testSetConfigurationParamErr034 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0740 - * @tc.name : testSetInterfaceParamErr001 - * @tc.desc : Negative test: Enter three parameters - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetInterfaceParamErr001', 0, function () { - console.info(TAG, 'usb testSetInterfaceParamErr001 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - getPipe('testSetInterfaceParamErr001'); - let tmpInterface = devices.configs[0].interfaces[0]; - let isClaim = usbManager.claimInterface(gPipe, tmpInterface, true); - expect(isClaim).assertEqual(0); - try { - let ret = usbManager.setInterface(gPipe, tmpInterface, gPipe); - console.info(TAG, 'usb [Enter three parameters] setInterface ret : ', ret); - expect(ret).assertEqual(0); - } catch (err) { - console.info(TAG, 'testSetInterfaceParamErr001 catch err code: ', err.code, ', message: ', err.message); - expect(err !== null).assertFalse(); - } - toReleaseInterface('testSetInterfaceParamErr001', tmpInterface); - toClosePipe('testSetInterfaceParamErr001'); - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0750 - * @tc.name : testSetInterfaceParamErr002 - * @tc.desc : Negative test: Param is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetInterfaceParamErr002', 0, function () { - console.info(TAG, 'usb testSetInterfaceParamErr002 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - let ret = usbManager.setInterface(PARAM_NULL); - console.info(TAG, 'usb [param:null] setInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testSetInterfaceParamErr002 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0760 - * @tc.name : testSetInterfaceParamErr003 - * @tc.desc : Negative test: Param is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetInterfaceParamErr003', 0, function () { - console.info(TAG, 'usb testSetInterfaceParamErr003 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - let ret = usbManager.setInterface(PARAM_UNDEFINED); - console.info(TAG, 'usb [param:undefined] setInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testSetInterfaceParamErr003 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0770 - * @tc.name : testSetInterfaceParamErr004 - * @tc.desc : Negative test: Param is "" - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetInterfaceParamErr004', 0, function () { - console.info(TAG, 'usb testSetInterfaceParamErr004 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - let ret = usbManager.setInterface(PARAM_NULLSTRING); - console.info(TAG, 'usb [param:""] setInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testSetInterfaceParamErr004 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0780 - * @tc.name : testSetInterfaceParamErr005 - * @tc.desc : Negative test: pipe is null - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetInterfaceParamErr005', 0, function () { - console.info(TAG, 'usb testSetInterfaceParamErr005 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - let tmpInterface = devices.configs[0].interfaces[0]; - let ret = usbManager.setInterface(PARAM_NULL, tmpInterface); - console.info(TAG, 'usb [pipe:null] setInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testSetInterfaceParamErr005 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) - - /** - * @tc.number : SUB_USB_HostManager_JS_ParamErr_0790 - * @tc.name : testSetInterfaceParamErr006 - * @tc.desc : Negative test: pipe is undefined - * @tc.size : MediumTest - * @tc.type : Function - * @tc.level : Level 3 - */ - it('testSetInterfaceParamErr006', 0, function () { - console.info(TAG, 'usb testSetInterfaceParamErr006 begin'); - if (!isDeviceConnected) { - expect(isDeviceConnected).assertFalse(); - return - } - try { - let tmpInterface = devices.configs[0].interfaces[0]; - let ret = usbManager.setInterface(PARAM_UNDEFINED, tmpInterface); - console.info(TAG, 'usb [pipe:undefined] setInterface ret : ', ret); - expect(ret !== null).assertFalse(); - } catch (err) { - console.info(TAG, 'testSetInterfaceParamErr006 catch err code: ', err.code, ', message: ', err.message); - expect(err.code).assertEqual(PARAM_ERRCODE); - } - }) -}) -} \ No newline at end of file diff --git a/usb/test/unittest/usb_manager_js_test/config.json b/usb/test/unittest/usb_manager_js_test/config.json deleted file mode 100644 index c256a7b6a9..0000000000 --- a/usb/test/unittest/usb_manager_js_test/config.json +++ /dev/null @@ -1,68 +0,0 @@ -{ - "app": { - "bundleName": "com.example.myapplication", - "vendor": "example", - "version": { - "code": 1, - "name": "1.0" - }, - "apiVersion": { - "compatible": 4, - "target": 5 - } - }, - "deviceConfig": {}, - "module": { - "reqPermissions": [ - { - "name": "ohos.permission.DISTRIBUTED_DATASYNC" - } - ], - "package": "com.example.myapplication", - "name": ".MyApplication", - "deviceType": [ - "default", - "tablet", - "2in1" - ], - "distro": { - "deliveryWithInstall": true, - "moduleName": "entry", - "moduleType": "entry" - }, - "abilities": [ - { - "visible": true, - "skills": [ - { - "entities": [ - "entity.system.home" - ], - "actions": [ - "action.system.home" - ] - } - ], - "name": "com.example.myapplication.MainAbility", - "icon": "$media:icon", - "description": "$string:mainability_description", - "label": "SensorJsTest", - "type": "page", - "launchType": "standard" - } - ], - "js": [ - { - "pages": [ - "pages/index/index" - ], - "name": "default", - "window": { - "designWidth": 720, - "autoDesignWidth": false - } - } - ] - } - } - \ No newline at end of file diff --git a/usb/test/unittest/usb_manager_js_test/openharmony_sx.p7b b/usb/test/unittest/usb_manager_js_test/openharmony_sx.p7b deleted file mode 100644 index 9be1e98fa4..0000000000 Binary files a/usb/test/unittest/usb_manager_js_test/openharmony_sx.p7b and /dev/null differ diff --git a/user_auth/hdi_service/adaptor/src/adaptor_algorithm.c b/user_auth/hdi_service/adaptor/src/adaptor_algorithm.c index 436e0ded6b..7b41172ed0 100644 --- a/user_auth/hdi_service/adaptor/src/adaptor_algorithm.c +++ b/user_auth/hdi_service/adaptor/src/adaptor_algorithm.c @@ -497,13 +497,15 @@ int32_t GetDistributeKey(const Buffer *peerUdid, const Buffer *salt, Buffer **ke LOG_ERROR("CreateBufferBySize keyData fail"); return RESULT_NO_MEMORY; } - if (memcpy_s(keyData->buf, keyData->maxSize, USER_AUTH_DISTRIBUTE_DEVICE_KEY, USER_AUTH_DISTRIBUTE_DEVICE_KEY_SIZE) != EOK) { + if (memcpy_s(keyData->buf, keyData->maxSize, USER_AUTH_DISTRIBUTE_DEVICE_KEY, USER_AUTH_DISTRIBUTE_DEVICE_KEY_SIZE) + != EOK) { LOG_ERROR("copy fix tag fail"); DestoryBuffer(keyData); return RESULT_NO_MEMORY; } keyData->contentSize += USER_AUTH_DISTRIBUTE_DEVICE_KEY_SIZE; - if (memcpy_s(keyData->buf + keyData->contentSize, keyData->maxSize - keyData->contentSize, salt->buf, salt->contentSize) != EOK) { + if (memcpy_s(keyData->buf + keyData->contentSize, keyData->maxSize - keyData->contentSize, salt->buf, + salt->contentSize) != EOK) { LOG_ERROR("copy salt fail"); DestoryBuffer(keyData); return RESULT_NO_MEMORY; diff --git a/user_auth/hdi_service/coauth/src/executor_message.c b/user_auth/hdi_service/coauth/src/executor_message.c index 33c7ce25ea..0a20fbbb04 100644 --- a/user_auth/hdi_service/coauth/src/executor_message.c +++ b/user_auth/hdi_service/coauth/src/executor_message.c @@ -701,7 +701,8 @@ IAM_STATIC ResultCode GetRemoteExecutorInfoInner(Attribute *attribute, Uint8Arra return RESULT_SUCCESS; } -IAM_STATIC ResultCode GetRemoteExecutorInfo(const Buffer *msg, Uint8Array peerUdid, Uint8Array *subMsgs, int *subMsgSize) +IAM_STATIC ResultCode GetRemoteExecutorInfo(const Buffer *msg, Uint8Array peerUdid, + Uint8Array *subMsgs, int *subMsgSize) { Uint8Array msgArray = { msg->buf, msg->contentSize }; SignParam signParam = { .needSignature = true, .keyType = KEY_TYPE_CROSS_DEVICE, .peerUdid = peerUdid}; @@ -766,7 +767,8 @@ bool CheckRemoteExecutorInfo(const Buffer *msg, ExecutorInfoHal *infoToCheck) return checkPass; } -IAM_STATIC ResultCode SetExecutorCollectMsgToAttribute(ScheduleInfoParam *scheduleInfo, const Uint8Array *publicKey, const Uint8Array challenge, Attribute *attribute) +IAM_STATIC ResultCode SetExecutorCollectMsgToAttribute(ScheduleInfoParam *scheduleInfo, const Uint8Array *publicKey, + const Uint8Array challenge, Attribute *attribute) { Uint8Array localUdid = { scheduleInfo->localUdid, sizeof(scheduleInfo->localUdid) }; Uint8Array remoteUdid = { scheduleInfo->remoteUdid, sizeof(scheduleInfo->remoteUdid) }; diff --git a/user_auth/hdi_service/service/user_auth_interface_service.cpp b/user_auth/hdi_service/service/user_auth_interface_service.cpp index 8515d0f77f..49e6bf886e 100644 --- a/user_auth/hdi_service/service/user_auth_interface_service.cpp +++ b/user_auth/hdi_service/service/user_auth_interface_service.cpp @@ -1364,7 +1364,9 @@ int32_t UserAuthInterfaceService::CheckReuseUnlockResult(const ReuseUnlockParam& param.reuseUnlockResultDuration); if (param.authTypes.empty() || param.authTypes.size() > MAX_AUTH_TYPE_LEN || param.reuseUnlockResultDuration == 0 || param.reuseUnlockResultDuration > REUSED_UNLOCK_TOKEN_PERIOD || - (param.reuseUnlockResultMode != AUTH_TYPE_RELEVANT && param.reuseUnlockResultMode != AUTH_TYPE_IRRELEVANT)) { + (param.reuseUnlockResultMode != AUTH_TYPE_RELEVANT && param.reuseUnlockResultMode != AUTH_TYPE_IRRELEVANT && + param.reuseUnlockResultMode != CALLER_IRRELEVANT_AUTH_TYPE_RELEVANT && + param.reuseUnlockResultMode != CALLER_IRRELEVANT_AUTH_TYPE_IRRELEVANT)) { IAM_LOGE("checkReuseUnlockResult bad param"); return RESULT_BAD_PARAM; } @@ -1514,7 +1516,7 @@ FAIL: static void DestroyExecutorInfo(void *data) { - if (data == NULL) { + if (data == nullptr) { IAM_LOGE("data is null"); return; } diff --git a/user_auth/hdi_service/user_auth/inc/user_auth_funcs.h b/user_auth/hdi_service/user_auth/inc/user_auth_funcs.h index 7548efce32..2a8b9326af 100644 --- a/user_auth/hdi_service/user_auth/inc/user_auth_funcs.h +++ b/user_auth/hdi_service/user_auth/inc/user_auth_funcs.h @@ -62,6 +62,8 @@ typedef struct { typedef enum ReuseMode { AUTH_TYPE_RELEVANT = 1, AUTH_TYPE_IRRELEVANT = 2, + CALLER_IRRELEVANT_AUTH_TYPE_RELEVANT = 3, + CALLER_IRRELEVANT_AUTH_TYPE_IRRELEVANT = 4, } ReuseMode; typedef struct { diff --git a/user_auth/hdi_service/user_auth/src/user_auth_funcs.c b/user_auth/hdi_service/user_auth/src/user_auth_funcs.c index f94e474fb9..80e3c90453 100644 --- a/user_auth/hdi_service/user_auth/src/user_auth_funcs.c +++ b/user_auth/hdi_service/user_auth/src/user_auth_funcs.c @@ -38,6 +38,8 @@ // Used to cache screenLock auth token plain. IAM_STATIC UnlockAuthResultCache g_unlockAuthResult = {false, 0, {}}; +// Used to cache any caller auth token plain. +IAM_STATIC UnlockAuthResultCache g_anyAuthResult = {false, 0, {}}; ResultCode GenerateSolutionFunc(AuthParamHal param, LinkedList **schedules) { @@ -82,6 +84,14 @@ IAM_STATIC void CacheUnlockAuthResult(int32_t userId, const UserAuthTokenHal *un g_unlockAuthResult.authToken = *unlockToken; } +IAM_STATIC void CacheAnyAuthResult(int32_t userId, const UserAuthTokenHal *unlockToken) +{ + (void)memset_s(&g_anyAuthResult, sizeof(UnlockAuthResultCache), 0, sizeof(UnlockAuthResultCache)); + g_anyAuthResult.isCached = true; + g_anyAuthResult.userId = userId; + g_anyAuthResult.authToken = *unlockToken; +} + IAM_STATIC void SetAuthResult(uint64_t credentialId, const UserAuthContext *context, const ExecutorResultInfo *info, AuthResult *result) { @@ -150,6 +160,8 @@ IAM_STATIC ResultCode HandleAuthSuccessResult(const UserAuthContext *context, co LOG_INFO("cache unlock auth result"); CacheUnlockAuthResult(context->userId, authToken); } + LOG_INFO("cache any auth result"); + CacheAnyAuthResult(context->userId, authToken); return RESULT_SUCCESS; } @@ -313,43 +325,44 @@ ResultCode GetEnrolledStateFunc(int32_t userId, uint32_t authType, EnrolledState return RESULT_SUCCESS; } -IAM_STATIC ResultCode CheckReuseUnlockTokenValid(const ReuseUnlockParamHal *info) +IAM_STATIC ResultCode CheckReuseUnlockTokenValid(const ReuseUnlockParamHal *info, UnlockAuthResultCache authResultCache) { - if (!g_unlockAuthResult.isCached) { + if (!authResultCache.isCached) { LOG_ERROR("invalid cached unlock token"); return RESULT_GENERAL_ERROR; } - if ((g_unlockAuthResult.authToken.tokenDataPlain.authMode != SCHEDULE_MODE_AUTH) - || (g_unlockAuthResult.authToken.tokenDataPlain.tokenType != TOKEN_TYPE_LOCAL_AUTH)) { + if ((authResultCache.authToken.tokenDataPlain.authMode != SCHEDULE_MODE_AUTH) + || (authResultCache.authToken.tokenDataPlain.tokenType != TOKEN_TYPE_LOCAL_AUTH)) { LOG_ERROR("need local auth"); return RESULT_VERIFY_TOKEN_FAIL; } uint64_t time = GetSystemTime(); - if (time < g_unlockAuthResult.authToken.tokenDataPlain.time) { + if (time < authResultCache.authToken.tokenDataPlain.time) { LOG_ERROR("bad system time"); return RESULT_GENERAL_ERROR; } - if ((time - g_unlockAuthResult.authToken.tokenDataPlain.time) > REUSED_UNLOCK_TOKEN_PERIOD) { - (void)memset_s(&g_unlockAuthResult, sizeof(UnlockAuthResultCache), 0, sizeof(UnlockAuthResultCache)); - g_unlockAuthResult.isCached = false; + if ((time - authResultCache.authToken.tokenDataPlain.time) > REUSED_UNLOCK_TOKEN_PERIOD) { + (void)memset_s(&authResultCache, sizeof(UnlockAuthResultCache), 0, sizeof(UnlockAuthResultCache)); + authResultCache.isCached = false; LOG_ERROR("cached unlock token is time out"); return RESULT_TOKEN_TIMEOUT; } - if ((time - g_unlockAuthResult.authToken.tokenDataPlain.time) > info->reuseUnlockResultDuration) { + if ((time - authResultCache.authToken.tokenDataPlain.time) > info->reuseUnlockResultDuration) { LOG_ERROR("reuse unlock check reuseUnlockResultDuration fail"); return RESULT_TOKEN_TIMEOUT; } - if (info->userId != g_unlockAuthResult.userId) { + if (info->userId != authResultCache.userId) { LOG_ERROR("reuse unlock check userId fail"); return RESULT_GENERAL_ERROR; } - if (info->authTrustLevel > g_unlockAuthResult.authToken.tokenDataPlain.authTrustLevel) { + if (info->authTrustLevel > authResultCache.authToken.tokenDataPlain.authTrustLevel) { LOG_ERROR("reuse unlock check authTrustLevel fail"); return RESULT_GENERAL_ERROR; } - if (info->reuseUnlockResultMode == AUTH_TYPE_RELEVANT) { + if (info->reuseUnlockResultMode == AUTH_TYPE_RELEVANT || + info->reuseUnlockResultMode == CALLER_IRRELEVANT_AUTH_TYPE_RELEVANT) { for (uint32_t i = 0; i < info->authTypeSize; i++) { - if (info->authTypes[i] == g_unlockAuthResult.authToken.tokenDataPlain.authType) { + if (info->authTypes[i] == authResultCache.authToken.tokenDataPlain.authType) { return RESULT_SUCCESS; } } @@ -361,13 +374,20 @@ IAM_STATIC ResultCode CheckReuseUnlockTokenValid(const ReuseUnlockParamHal *info IAM_STATIC ResultCode GetReuseUnlockResult(const ReuseUnlockParamHal *info, ReuseUnlockResult *reuseResult) { - uint32_t ret = CheckReuseUnlockTokenValid(info); + UnlockAuthResultCache authResultCache = {}; + if (info->reuseUnlockResultMode == AUTH_TYPE_RELEVANT || info->reuseUnlockResultMode == AUTH_TYPE_IRRELEVANT) { + authResultCache = g_unlockAuthResult; + } else if (info->reuseUnlockResultMode == CALLER_IRRELEVANT_AUTH_TYPE_RELEVANT || + info->reuseUnlockResultMode == CALLER_IRRELEVANT_AUTH_TYPE_IRRELEVANT) { + authResultCache = g_anyAuthResult; + } + uint32_t ret = CheckReuseUnlockTokenValid(info, authResultCache); if (ret != RESULT_SUCCESS) { LOG_ERROR("check unlock token fail"); return ret; } - *((UserAuthTokenHal *)reuseResult->token) = g_unlockAuthResult.authToken; - reuseResult->authType = g_unlockAuthResult.authToken.tokenDataPlain.authType; + *((UserAuthTokenHal *)reuseResult->token) = authResultCache.authToken; + reuseResult->authType = authResultCache.authToken.tokenDataPlain.authType; ((UserAuthTokenHal *)reuseResult->token)->tokenDataPlain.authMode = SCHEDULE_MODE_REUSE_UNLOCK_AUTH_RESULT; ((UserAuthTokenHal *)reuseResult->token)->tokenDataPlain.tokenType = TOKEN_TYPE_LOCAL_RESIGN; if (memcpy_s(((UserAuthTokenHal *)reuseResult->token)->tokenDataPlain.challenge, CHALLENGE_LEN, info->challenge, @@ -388,7 +408,9 @@ ResultCode CheckReuseUnlockResultFunc(const ReuseUnlockParamHal *info, ReuseUnlo { if (info == NULL || reuseResult == NULL || info->reuseUnlockResultDuration == 0 || info->reuseUnlockResultDuration > REUSED_UNLOCK_TOKEN_PERIOD || - (info->reuseUnlockResultMode != AUTH_TYPE_RELEVANT && info->reuseUnlockResultMode != AUTH_TYPE_IRRELEVANT)) { + (info->reuseUnlockResultMode != AUTH_TYPE_RELEVANT && info->reuseUnlockResultMode != AUTH_TYPE_IRRELEVANT && + info->reuseUnlockResultMode != CALLER_IRRELEVANT_AUTH_TYPE_RELEVANT && + info->reuseUnlockResultMode != CALLER_IRRELEVANT_AUTH_TYPE_IRRELEVANT)) { LOG_ERROR("CheckReuseUnlockResultFunc bad param"); return RESULT_BAD_PARAM; } diff --git a/user_auth/test/unittest/service_test/src/user_auth_interface_service_test.cpp b/user_auth/test/unittest/service_test/src/user_auth_interface_service_test.cpp index 21fb8fb4eb..9a1594c5ba 100644 --- a/user_auth/test/unittest/service_test/src/user_auth_interface_service_test.cpp +++ b/user_auth/test/unittest/service_test/src/user_auth_interface_service_test.cpp @@ -1022,7 +1022,7 @@ HWTEST_F(UserAuthInterfaceServiceTest, TestDeleteUser_001, TestSize.Level0) std::vector authToken; std::vector deletedCredInfos; std::vector rootSecret; - EXPECT_EQ(service->DeleteUser(userId, authToken, deletedCredInfos, rootSecret), 8); + EXPECT_EQ(service->DeleteUser(userId, authToken, deletedCredInfos, rootSecret), 10017); authToken.resize(sizeof(UserAuthTokenHal)); EXPECT_EQ(service->DeleteUser(userId, authToken, deletedCredInfos, rootSecret), 10017); diff --git a/user_auth/test/unittest/user_auth_test/user_auth_funcs_test.cpp b/user_auth/test/unittest/user_auth_test/user_auth_funcs_test.cpp index ae19576620..c1dce60a67 100644 --- a/user_auth/test/unittest/user_auth_test/user_auth_funcs_test.cpp +++ b/user_auth/test/unittest/user_auth_test/user_auth_funcs_test.cpp @@ -25,8 +25,7 @@ extern "C" { extern LinkedList *g_userInfoList; extern UnlockAuthResultCache g_unlockAuthResult; extern ResultCode GetReuseUnlockResult(const ReuseUnlockParamHal *info, ReuseUnlockResult *reuseResult); - extern void CacheUnlockAuthResult(int32_t userId, const UserAuthTokenHal *unlockToken, - const EnrolledStateHal *enrolledState); + extern void CacheUnlockAuthResult(int32_t userId, const UserAuthTokenHal *unlockToken); extern void SetAuthResult(uint64_t credentialId, const UserAuthContext *context, const ExecutorResultInfo *info, AuthResult *result); } @@ -99,25 +98,25 @@ HWTEST_F(UserAuthFuncsTest, TestGetEnrolledStateFunc, TestSize.Level0) HWTEST_F(UserAuthFuncsTest, TestGetReuseUnlockResult, TestSize.Level0) { ReuseUnlockParamHal info; + info.reuseUnlockResultMode = AUTH_TYPE_IRRELEVANT; ReuseUnlockResult reuseResult; EXPECT_EQ(GetReuseUnlockResult(&info, &reuseResult), RESULT_GENERAL_ERROR); int32_t userIdCached = 0; UserAuthTokenHal userAuthTokenCached; - EnrolledStateHal enrolledState; userAuthTokenCached.tokenDataPlain.time = GetSystemTime() + 600; userAuthTokenCached.tokenDataPlain.authType = 1; userAuthTokenCached.tokenDataPlain.authTrustLevel = ATL4; - CacheUnlockAuthResult(userIdCached, &userAuthTokenCached, &enrolledState); + CacheUnlockAuthResult(userIdCached, &userAuthTokenCached); EXPECT_EQ(GetReuseUnlockResult(&info, &reuseResult), RESULT_VERIFY_TOKEN_FAIL); userAuthTokenCached.tokenDataPlain.authMode = SCHEDULE_MODE_AUTH; userAuthTokenCached.tokenDataPlain.tokenType = TOKEN_TYPE_LOCAL_AUTH; - CacheUnlockAuthResult(userIdCached, &userAuthTokenCached, &enrolledState); + CacheUnlockAuthResult(userIdCached, &userAuthTokenCached); EXPECT_EQ(GetReuseUnlockResult(&info, &reuseResult), RESULT_GENERAL_ERROR); userAuthTokenCached.tokenDataPlain.time = GetSystemTime(); - CacheUnlockAuthResult(userIdCached, &userAuthTokenCached, &enrolledState); + CacheUnlockAuthResult(userIdCached, &userAuthTokenCached); EXPECT_EQ(GetReuseUnlockResult(&info, &reuseResult), RESULT_SUCCESS); EXPECT_EQ(reuseResult.enrolledState.credentialCount, 0); EXPECT_EQ(reuseResult.enrolledState.credentialDigest, 0); @@ -145,8 +144,7 @@ HWTEST_F(UserAuthFuncsTest, TestCheckReuseUnlockResultFunc002, TestSize.Level0) userAuthTokenCached.tokenDataPlain.time = GetSystemTime() + 300; userAuthTokenCached.tokenDataPlain.authMode = SCHEDULE_MODE_AUTH; userAuthTokenCached.tokenDataPlain.tokenType = TOKEN_TYPE_LOCAL_AUTH; - EnrolledStateHal enrolledState; - CacheUnlockAuthResult(userIdCached, &userAuthTokenCached, &enrolledState); + CacheUnlockAuthResult(userIdCached, &userAuthTokenCached); ReuseUnlockParamHal info; ReuseUnlockResult reuseResult; @@ -158,11 +156,11 @@ HWTEST_F(UserAuthFuncsTest, TestCheckReuseUnlockResultFunc002, TestSize.Level0) userAuthTokenCached.tokenDataPlain.time = GetSystemTime(); std::this_thread::sleep_for(std::chrono::milliseconds(300)); - CacheUnlockAuthResult(userIdCached, &userAuthTokenCached, &enrolledState); + CacheUnlockAuthResult(userIdCached, &userAuthTokenCached); EXPECT_EQ(CheckReuseUnlockResultFunc(&info, &reuseResult), RESULT_TOKEN_TIMEOUT); userAuthTokenCached.tokenDataPlain.time = GetSystemTime(); - CacheUnlockAuthResult(userIdCached, &userAuthTokenCached, &enrolledState); + CacheUnlockAuthResult(userIdCached, &userAuthTokenCached); EXPECT_EQ(CheckReuseUnlockResultFunc(&info, &reuseResult), RESULT_GENERAL_ERROR); info.userId = 0; diff --git a/vibrator/test/fuzztest/vibrator_fuzzer/BUILD.gn b/vibrator/test/fuzztest/vibrator_fuzzer/BUILD.gn index 8ca97643b1..0911f1bd42 100644 --- a/vibrator/test/fuzztest/vibrator_fuzzer/BUILD.gn +++ b/vibrator/test/fuzztest/vibrator_fuzzer/BUILD.gn @@ -14,7 +14,7 @@ import("//build/config/features.gni") import("//build/ohos.gni") import("//build/test.gni") -module_output_path = "drivers_peripheral_vibrator/vibrator" +module_output_path = "drivers_peripheral_vibrator/drivers_peripheral_vibrator" ohos_fuzztest("VibratorFuzzTest") { module_out_path = module_output_path diff --git a/vibrator/test/fuzztest/vibrator_fuzzer/vibrator_fuzzer.cpp b/vibrator/test/fuzztest/vibrator_fuzzer/vibrator_fuzzer.cpp index 093fe5b1c5..6f3207e7fe 100644 --- a/vibrator/test/fuzztest/vibrator_fuzzer/vibrator_fuzzer.cpp +++ b/vibrator/test/fuzztest/vibrator_fuzzer/vibrator_fuzzer.cpp @@ -83,6 +83,13 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) return 0; } + if (data == nullptr) { + return 0; + } + + if (size < sizeof(int32_t)) { + return 0; + } /* Run your code on data */ OHOS::DoSomethingInterestingWithMyAPI(data, size); return 0; diff --git a/vibrator/test/fuzztest/vibratorgethapticcapacity_fuzzer/BUILD.gn b/vibrator/test/fuzztest/vibratorgethapticcapacity_fuzzer/BUILD.gn index 9539cfd50f..a3bc13fef7 100644 --- a/vibrator/test/fuzztest/vibratorgethapticcapacity_fuzzer/BUILD.gn +++ b/vibrator/test/fuzztest/vibratorgethapticcapacity_fuzzer/BUILD.gn @@ -14,7 +14,7 @@ import("//build/config/features.gni") import("//build/ohos.gni") import("//build/test.gni") -module_output_path = "hdf/vibrator" +module_output_path = "drivers_peripheral_vibrator/drivers_peripheral_vibrator" ohos_fuzztest("VibratorGetHapticCapacityFuzzTest") { module_out_path = module_output_path diff --git a/vibrator/test/fuzztest/vibratorgethapticcapacity_fuzzer/vibratorgethapticcapacity_fuzzer.cpp b/vibrator/test/fuzztest/vibratorgethapticcapacity_fuzzer/vibratorgethapticcapacity_fuzzer.cpp index 46810986dd..d12b1e0972 100644 --- a/vibrator/test/fuzztest/vibratorgethapticcapacity_fuzzer/vibratorgethapticcapacity_fuzzer.cpp +++ b/vibrator/test/fuzztest/vibratorgethapticcapacity_fuzzer/vibratorgethapticcapacity_fuzzer.cpp @@ -58,6 +58,13 @@ namespace OHOS { extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { + if (data == nullptr) { + return 0; + } + + if (size < sizeof(int32_t)) { + return 0; + } OHOS::VibratorGetHapticCapacityTest(data, size); return 0; } diff --git a/vibrator/test/fuzztest/vibratorgethapticstartuptime_fuzzer/BUILD.gn b/vibrator/test/fuzztest/vibratorgethapticstartuptime_fuzzer/BUILD.gn index e4599a77f7..1540e2e108 100644 --- a/vibrator/test/fuzztest/vibratorgethapticstartuptime_fuzzer/BUILD.gn +++ b/vibrator/test/fuzztest/vibratorgethapticstartuptime_fuzzer/BUILD.gn @@ -14,7 +14,7 @@ import("//build/config/features.gni") import("//build/ohos.gni") import("//build/test.gni") -module_output_path = "hdf/vibrator" +module_output_path = "drivers_peripheral_vibrator/drivers_peripheral_vibrator" ohos_fuzztest("VibratorGetHapticStartUpTimeFuzzTest") { module_out_path = module_output_path diff --git a/vibrator/test/fuzztest/vibratorgethapticstartuptime_fuzzer/vibratorgethapticstartuptime_fuzzer.cpp b/vibrator/test/fuzztest/vibratorgethapticstartuptime_fuzzer/vibratorgethapticstartuptime_fuzzer.cpp index fa9d34290e..22c3a632fb 100644 --- a/vibrator/test/fuzztest/vibratorgethapticstartuptime_fuzzer/vibratorgethapticstartuptime_fuzzer.cpp +++ b/vibrator/test/fuzztest/vibratorgethapticstartuptime_fuzzer/vibratorgethapticstartuptime_fuzzer.cpp @@ -44,6 +44,13 @@ namespace OHOS { extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { + if (data == nullptr) { + return 0; + } + + if (size < sizeof(int32_t)) { + return 0; + } OHOS::VibratorGetHapticStartUpTimeTest(data, size); return 0; } diff --git a/vibrator/test/fuzztest/vibratorplayhapticpattern_fuzzer/BUILD.gn b/vibrator/test/fuzztest/vibratorplayhapticpattern_fuzzer/BUILD.gn index a0f2433c8f..8a122e939b 100644 --- a/vibrator/test/fuzztest/vibratorplayhapticpattern_fuzzer/BUILD.gn +++ b/vibrator/test/fuzztest/vibratorplayhapticpattern_fuzzer/BUILD.gn @@ -14,7 +14,7 @@ import("//build/config/features.gni") import("//build/ohos.gni") import("//build/test.gni") -module_output_path = "hdf/vibrator" +module_output_path = "drivers_peripheral_vibrator/drivers_peripheral_vibrator" ohos_fuzztest("VibratorPlayHapticPatternFuzzTest") { module_out_path = module_output_path diff --git a/vibrator/test/fuzztest/vibratorplayhapticpattern_fuzzer/vibratorplayhapticpattern_fuzzer.cpp b/vibrator/test/fuzztest/vibratorplayhapticpattern_fuzzer/vibratorplayhapticpattern_fuzzer.cpp index c2bbdc8105..3e8062f1f6 100644 --- a/vibrator/test/fuzztest/vibratorplayhapticpattern_fuzzer/vibratorplayhapticpattern_fuzzer.cpp +++ b/vibrator/test/fuzztest/vibratorplayhapticpattern_fuzzer/vibratorplayhapticpattern_fuzzer.cpp @@ -47,7 +47,7 @@ namespace OHOS { } OHOS::HDI::Vibrator::V1_2::HapticPaket pkg; - if (size < sizeof(pkg)) { + if (size < sizeof(params)) { return false; } @@ -90,6 +90,13 @@ namespace OHOS { extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { + if (data == nullptr) { + return 0; + } + + if (size < sizeof(int32_t)) { + return 0; + } OHOS::VibratorPlayHapticPatternTest(data, size); return 0; } diff --git a/vibrator/test/fuzztest/vibratorstart_fuzzer/BUILD.gn b/vibrator/test/fuzztest/vibratorstart_fuzzer/BUILD.gn index 051b774e1e..856824d96f 100644 --- a/vibrator/test/fuzztest/vibratorstart_fuzzer/BUILD.gn +++ b/vibrator/test/fuzztest/vibratorstart_fuzzer/BUILD.gn @@ -14,7 +14,7 @@ import("//build/config/features.gni") import("//build/ohos.gni") import("//build/test.gni") -module_output_path = "hdf/vibrator" +module_output_path = "drivers_peripheral_vibrator/drivers_peripheral_vibrator" ohos_fuzztest("VibratorStartFuzzTest") { module_out_path = module_output_path diff --git a/vibrator/test/fuzztest/vibratorstart_fuzzer/vibratorstart_fuzzer.cpp b/vibrator/test/fuzztest/vibratorstart_fuzzer/vibratorstart_fuzzer.cpp index c32a7310cc..8db210dea0 100644 --- a/vibrator/test/fuzztest/vibratorstart_fuzzer/vibratorstart_fuzzer.cpp +++ b/vibrator/test/fuzztest/vibratorstart_fuzzer/vibratorstart_fuzzer.cpp @@ -33,6 +33,13 @@ namespace OHOS { extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { + if (data == nullptr) { + return 0; + } + + if (size < sizeof(int32_t)) { + return 0; + } OHOS::VibratorStartFuzzTest(data, size); return 0; } diff --git a/vibrator/test/fuzztest/vibratorstartbyintensity_fuzzer/BUILD.gn b/vibrator/test/fuzztest/vibratorstartbyintensity_fuzzer/BUILD.gn index cd263fc4a2..7d4d1297f3 100644 --- a/vibrator/test/fuzztest/vibratorstartbyintensity_fuzzer/BUILD.gn +++ b/vibrator/test/fuzztest/vibratorstartbyintensity_fuzzer/BUILD.gn @@ -14,7 +14,7 @@ import("//build/config/features.gni") import("//build/ohos.gni") import("//build/test.gni") -module_output_path = "hdf/vibrator" +module_output_path = "drivers_peripheral_vibrator/drivers_peripheral_vibrator" ohos_fuzztest("VibratorStartByIntensityFuzzTest") { module_out_path = module_output_path diff --git a/vibrator/test/fuzztest/vibratorstartbyintensity_fuzzer/vibratorstartbyintensity_fuzzer.cpp b/vibrator/test/fuzztest/vibratorstartbyintensity_fuzzer/vibratorstartbyintensity_fuzzer.cpp index 7504e9872c..fd0fb75427 100644 --- a/vibrator/test/fuzztest/vibratorstartbyintensity_fuzzer/vibratorstartbyintensity_fuzzer.cpp +++ b/vibrator/test/fuzztest/vibratorstartbyintensity_fuzzer/vibratorstartbyintensity_fuzzer.cpp @@ -40,6 +40,13 @@ namespace OHOS { extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { + if (data == nullptr) { + return 0; + } + + if (size < sizeof(int32_t)) { + return 0; + } OHOS::VibratorStartByIntensityFuzzTest(data, size); return 0; } diff --git a/vibrator/test/fuzztest/vibratorstartonce_fuzzer/BUILD.gn b/vibrator/test/fuzztest/vibratorstartonce_fuzzer/BUILD.gn index 434c6d26ba..ce7008f216 100644 --- a/vibrator/test/fuzztest/vibratorstartonce_fuzzer/BUILD.gn +++ b/vibrator/test/fuzztest/vibratorstartonce_fuzzer/BUILD.gn @@ -14,7 +14,7 @@ import("//build/config/features.gni") import("//build/ohos.gni") import("//build/test.gni") -module_output_path = "hdf/vibrator" +module_output_path = "drivers_peripheral_vibrator/drivers_peripheral_vibrator" ohos_fuzztest("VibratorStartOnceFuzzTest") { module_out_path = module_output_path diff --git a/vibrator/test/fuzztest/vibratorstartonce_fuzzer/vibratorstartonce_fuzzer.cpp b/vibrator/test/fuzztest/vibratorstartonce_fuzzer/vibratorstartonce_fuzzer.cpp index 3f4dec67c0..f5f17d62e4 100644 --- a/vibrator/test/fuzztest/vibratorstartonce_fuzzer/vibratorstartonce_fuzzer.cpp +++ b/vibrator/test/fuzztest/vibratorstartonce_fuzzer/vibratorstartonce_fuzzer.cpp @@ -33,6 +33,13 @@ namespace OHOS { extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { + if (data == nullptr) { + return 0; + } + + if (size < sizeof(int32_t)) { + return 0; + } OHOS::VibratorStartOnceFuzzTest(data, size); return 0; } diff --git a/vibrator/test/fuzztest/vibratorstop_fuzzer/BUILD.gn b/vibrator/test/fuzztest/vibratorstop_fuzzer/BUILD.gn index cd8d560c4d..bddc21e67d 100644 --- a/vibrator/test/fuzztest/vibratorstop_fuzzer/BUILD.gn +++ b/vibrator/test/fuzztest/vibratorstop_fuzzer/BUILD.gn @@ -14,7 +14,7 @@ import("//build/config/features.gni") import("//build/ohos.gni") import("//build/test.gni") -module_output_path = "hdf/vibrator" +module_output_path = "drivers_peripheral_vibrator/drivers_peripheral_vibrator" ohos_fuzztest("VibratorStopFuzzTest") { module_out_path = module_output_path diff --git a/vibrator/test/fuzztest/vibratorstop_fuzzer/vibratorstop_fuzzer.cpp b/vibrator/test/fuzztest/vibratorstop_fuzzer/vibratorstop_fuzzer.cpp index 520b95e5dd..55990725b2 100644 --- a/vibrator/test/fuzztest/vibratorstop_fuzzer/vibratorstop_fuzzer.cpp +++ b/vibrator/test/fuzztest/vibratorstop_fuzzer/vibratorstop_fuzzer.cpp @@ -37,6 +37,13 @@ namespace OHOS { extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { + if (data == nullptr) { + return 0; + } + + if (size < sizeof(int32_t)) { + return 0; + } OHOS::VibratorStopFuzzTest(data, size); return 0; } diff --git a/vibrator/test/fuzztest/vibratorstopv1_2_fuzzer/BUILD.gn b/vibrator/test/fuzztest/vibratorstopv1_2_fuzzer/BUILD.gn index 02f0546b0d..0a7ded368c 100644 --- a/vibrator/test/fuzztest/vibratorstopv1_2_fuzzer/BUILD.gn +++ b/vibrator/test/fuzztest/vibratorstopv1_2_fuzzer/BUILD.gn @@ -14,7 +14,7 @@ import("//build/config/features.gni") import("//build/ohos.gni") import("//build/test.gni") -module_output_path = "hdf/vibrator" +module_output_path = "drivers_peripheral_vibrator/drivers_peripheral_vibrator" ohos_fuzztest("VibratorStopV1_2FuzzTest") { module_out_path = module_output_path diff --git a/vibrator/test/fuzztest/vibratorstopv1_2_fuzzer/vibratorstopv1_2_fuzzer.cpp b/vibrator/test/fuzztest/vibratorstopv1_2_fuzzer/vibratorstopv1_2_fuzzer.cpp index e53b602375..5a4af549a7 100644 --- a/vibrator/test/fuzztest/vibratorstopv1_2_fuzzer/vibratorstopv1_2_fuzzer.cpp +++ b/vibrator/test/fuzztest/vibratorstopv1_2_fuzzer/vibratorstopv1_2_fuzzer.cpp @@ -45,6 +45,13 @@ namespace OHOS { extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { + if (data == nullptr) { + return 0; + } + + if (size < sizeof(int32_t)) { + return 0; + } OHOS::VibratorStopV1_2FuzzTest(data, size); return 0; } diff --git a/wlan/chip/hdi_service/wifi.cpp b/wlan/chip/hdi_service/wifi.cpp index 84db52801b..54f947718c 100644 --- a/wlan/chip/hdi_service/wifi.cpp +++ b/wlan/chip/hdi_service/wifi.cpp @@ -64,8 +64,8 @@ Wifi::~Wifi() int32_t Wifi::RegisterWifiEventCallback(const sptr& eventCallback) { - if (AddWifiDeathRecipient(eventCallback) != HDF_SUCCESS) { - return HDF_FAILURE; + if (cbHandler_.GetCallbacks().empty()) { + AddWifiDeathRecipient(eventCallback); } if (!cbHandler_.AddCallback(eventCallback)) { @@ -241,6 +241,7 @@ void Wifi::OnRemoteDied(const wptr &object) chips_.clear(); auto lock = AcquireGlobalLock(); StopVendorHal(&lock); + cbHandler_.Invalidate(); runState_ = RunState::STOPPED; } diff --git a/wlan/client/src/netlink/netlink_cmd_adapter.c b/wlan/client/src/netlink/netlink_cmd_adapter.c index 0c68c80735..f115ec4d35 100644 --- a/wlan/client/src/netlink/netlink_cmd_adapter.c +++ b/wlan/client/src/netlink/netlink_cmd_adapter.c @@ -3466,7 +3466,7 @@ static int32_t SendMsgToKernel(unsigned short nlmsgType, int opt, char *data, in if (memset_s(&ntlAddr, sizeof(ntlAddr), 0, sizeof(ntlAddr)) != EOK) { HILOG_ERROR(LOG_CORE, "ntlAddr memset_s is failed"); - free(ntlMsg); + OsalMemFree(ntlMsg); ntlMsg = NULL; return RET_CODE_FAILURE; } @@ -3476,7 +3476,7 @@ static int32_t SendMsgToKernel(unsigned short nlmsgType, int opt, char *data, in if (memset_s(ntlMsg, len, 0, len) != EOK) { HILOG_ERROR(LOG_CORE, "ntlMsg memset_s is failed"); - free(ntlMsg); + OsalMemFree(ntlMsg); ntlMsg = NULL; return RET_CODE_FAILURE; } @@ -3489,13 +3489,13 @@ static int32_t SendMsgToKernel(unsigned short nlmsgType, int opt, char *data, in if (data != NULL && datalen != 0) { if (memcpy_s(ntlMsg->data, datalen, data, datalen) != EOK) { HILOG_ERROR(LOG_CORE, "memcpy_s is failed"); - free(ntlMsg); + OsalMemFree(ntlMsg); ntlMsg = NULL; return RET_CODE_FAILURE; } } ret = sendto(skfd, ntlMsg, ntlMsg->hdr.nlmsg_len, 0, (struct sockaddr*)&ntlAddr, sizeof(ntlAddr)); - free(ntlMsg); + OsalMemFree(ntlMsg); ntlMsg = NULL; return ret; } diff --git a/wlan/hdi_service/service_common/wlan_common_cmd.c b/wlan/hdi_service/service_common/wlan_common_cmd.c index a774142d62..1f17d27b32 100644 --- a/wlan/hdi_service/service_common/wlan_common_cmd.c +++ b/wlan/hdi_service/service_common/wlan_common_cmd.c @@ -449,6 +449,7 @@ int32_t WlanInterfaceGetIfNamesByChipId(struct IWlanInterface *self, uint8_t chi if (name != NULL) { if (strcpy_s(ifName, ifNameLen, name) != EOK) { + free(name); HDF_LOGE("%{public}s: copy ifName failed!", __func__); return HDF_FAILURE; } diff --git a/wlan/wpa/interfaces/hdi_service/service_common/hdi_wpa_hal.c b/wlan/wpa/interfaces/hdi_service/service_common/hdi_wpa_hal.c index 57fcee0609..653342be0c 100644 --- a/wlan/wpa/interfaces/hdi_service/service_common/hdi_wpa_hal.c +++ b/wlan/wpa/interfaces/hdi_service/service_common/hdi_wpa_hal.c @@ -293,6 +293,7 @@ void ReleaseIfaceCtrl(char *ifName, int len) ReleaseWpaCtrl(&(g_wpaInterface->chbaCtrl)); #ifndef OHOS_EUPDATER ReleaseEventCallback(); + ClearHdfWpaRemoteObj(); #endif } } diff --git a/wlan/wpa/interfaces/hdi_service/service_common/wpa_common_cmd.c b/wlan/wpa/interfaces/hdi_service/service_common/wpa_common_cmd.c index ee40aad0bc..426f2eff70 100644 --- a/wlan/wpa/interfaces/hdi_service/service_common/wpa_common_cmd.c +++ b/wlan/wpa/interfaces/hdi_service/service_common/wpa_common_cmd.c @@ -1849,6 +1849,7 @@ int32_t WpaInterfaceRegisterEventCallback(struct IWpaInterface *self, struct IWp HDF_LOGE("invalid opt"); return HDF_FAILURE; } + (void)OsalMutexLock(&HdfWpaStubDriver()->mutex); do { HDF_LOGE("%{public}s: call HdfWpaAddRemoteObj", __func__); ret = HdfWpaAddRemoteObj(cbFunc, ifName); @@ -1863,6 +1864,7 @@ int32_t WpaInterfaceRegisterEventCallback(struct IWpaInterface *self, struct IWp break; } } while (0); + (void)OsalMutexUnlock(&HdfWpaStubDriver()->mutex); pthread_mutex_unlock(&g_interfaceLock); return ret; } @@ -1883,6 +1885,7 @@ int32_t WpaInterfaceUnregisterEventCallback(struct IWpaInterface *self, struct I HDF_LOGE("invalid opt"); return HDF_FAILURE; } + (void)OsalMutexLock(&HdfWpaStubDriver()->mutex); if (DListIsEmpty(&HdfWpaStubDriver()->remoteListHead)) { int32_t ret = WpaUnregisterEventCallback(HdfWpaCallbackFun, WIFI_WPA_TO_HAL_CLIENT, ifName); if (ret != HDF_SUCCESS) { @@ -1890,6 +1893,7 @@ int32_t WpaInterfaceUnregisterEventCallback(struct IWpaInterface *self, struct I } } HdfWpaDelRemoteObj(cbFunc); + (void)OsalMutexUnlock(&HdfWpaStubDriver()->mutex); pthread_mutex_unlock(&g_interfaceLock); return HDF_SUCCESS; } @@ -1947,3 +1951,19 @@ int32_t WpaInterfaceStaShellCmd(struct IWpaInterface *self, const char *ifName, HDF_LOGI("%{public}s: success", __func__); return HDF_SUCCESS; } + +void ClearHdfWpaRemoteObj(void) +{ + struct HdfWpaRemoteNode *pos = NULL; + struct HdfWpaRemoteNode *tmp = NULL; + struct DListHead *head = &HdfWpaStubDriver()->remoteListHead; + + (void)OsalMutexLock(&HdfWpaStubDriver()->mutex); + DLIST_FOR_EACH_ENTRY_SAFE(pos, tmp, head, struct HdfWpaRemoteNode, node) { + DListRemove(&(pos->node)); + IWpaCallbackRelease(pos->callbackObj); + OsalMemFree(pos); + pos = NULL; + } + (void)OsalMutexUnlock(&HdfWpaStubDriver()->mutex); +} diff --git a/wlan/wpa/interfaces/hdi_service/service_common/wpa_common_cmd.h b/wlan/wpa/interfaces/hdi_service/service_common/wpa_common_cmd.h index 27b394663b..424656bef9 100644 --- a/wlan/wpa/interfaces/hdi_service/service_common/wpa_common_cmd.h +++ b/wlan/wpa/interfaces/hdi_service/service_common/wpa_common_cmd.h @@ -106,6 +106,7 @@ int32_t WpaInterfaceReassociate(struct IWpaInterface *self, const char *ifName); int32_t WpaInterfaceStaShellCmd(struct IWpaInterface *self, const char *ifName, const char *cmd); void HdfWpaDelRemoteObj(struct IWpaCallback *self); +void ClearHdfWpaRemoteObj(void); int32_t FillData(uint8_t **dst, uint32_t *dstLen, uint8_t *src, uint32_t srcLen); pthread_mutex_t *GetInterfaceLock(); diff --git a/wlan/wpa/interfaces/hdi_service/service_common/wpa_p2p_cmd.c b/wlan/wpa/interfaces/hdi_service/service_common/wpa_p2p_cmd.c index 3624bce45e..2998462037 100644 --- a/wlan/wpa/interfaces/hdi_service/service_common/wpa_p2p_cmd.c +++ b/wlan/wpa/interfaces/hdi_service/service_common/wpa_p2p_cmd.c @@ -1340,8 +1340,8 @@ int32_t WpaInterfaceP2pGetPeer(struct IWpaInterface *self, const char *ifName, c info->operSsidLen = WIFI_P2P_DEVICE_NAME_LENGTH; uint8_t tmpBssid[ETH_ADDR_LEN] = {0}; hwaddr_aton(token, tmpBssid); - if (strcpy_s((char *)info->p2pDeviceAddress, ETH_ADDR_LEN + 1, (char *)tmpBssid) != EOK) { - HDF_LOGE("%{public}s strcpy failed", __func__); + if (memcpy_s((char *)info->p2pDeviceAddress, ETH_ADDR_LEN, (char *)tmpBssid, ETH_ADDR_LEN) != EOK) { + HDF_LOGE("%{public}s memcpy failed", __func__); } while (token != NULL) { struct HdiWpaKeyValue retMsg = {{0}, {0}}; @@ -2267,8 +2267,10 @@ int32_t ProcessEventP2pGroupFormationFailure(struct HdfWpaRemoteNode *node, char } else { ret = node->callbackObj->OnEventGroupFormationFailure(node->callbackObj, hdiReason, ifName); } - OsalMemFree(hdiReason); - hdiReason = NULL; + if (hdiReason) { + OsalMemFree(hdiReason); + hdiReason = NULL; + } return ret; } diff --git a/wlan/wpa/interfaces/hdi_service/service_common/wpa_p2p_hal.c b/wlan/wpa/interfaces/hdi_service/service_common/wpa_p2p_hal.c index 4920566112..9e6546edc7 100644 --- a/wlan/wpa/interfaces/hdi_service/service_common/wpa_p2p_hal.c +++ b/wlan/wpa/interfaces/hdi_service/service_common/wpa_p2p_hal.c @@ -116,7 +116,7 @@ static P2pSupplicantErrCode WpaP2pCliCmdWpsPin(WifiWpaP2pGroupInterface *this, P return P2P_SUP_ERRCODE_FAILED; } if (argv->mode == P2P_PIN_DISPLAY) { - if (strncpy_s(argv->pinCode, sizeof(argv->pinCode), buf, P2P_PIN_CODE_LEN) != EOK) { + if (strncpy_s(argv->pinCode, sizeof(argv->pinCode), buf, P2P_REPLY_BUF_SMALL_LENGTH) != EOK) { HDF_LOGE("Failed to copy return pin code!"); return P2P_SUP_ERRCODE_FAILED; } diff --git a/wlan/wpa/interfaces/hdi_service/wpa_interface_drivers.c b/wlan/wpa/interfaces/hdi_service/wpa_interface_drivers.c index 420efa06a8..ac1e3081cd 100644 --- a/wlan/wpa/interfaces/hdi_service/wpa_interface_drivers.c +++ b/wlan/wpa/interfaces/hdi_service/wpa_interface_drivers.c @@ -140,9 +140,6 @@ static void HdfWpaInterfaceDriverRelease(struct HdfDeviceObject *deviceObject) struct HdfWpaInterfaceHost *wpainterfaceHost = CONTAINER_OF( deviceObject->service, struct HdfWpaInterfaceHost, ioService); StubCollectorRemoveObject(IWPAINTERFACE_INTERFACE_DESC, wpainterfaceHost->service); - if (wpainterfaceHost->stubObject != NULL) { - *(wpainterfaceHost->stubObject) = NULL; - } wpainterfaceHost->stubObject = NULL; IWpaInterfaceRelease(wpainterfaceHost->service, true); OsalMemFree(wpainterfaceHost);