diff --git a/bundle.json b/bundle.json index 1f60658af12fe30ba5ec55111265e8d8825c517c..264a55f87edf139832fed29a31ab5df038843304 100644 --- a/bundle.json +++ b/bundle.json @@ -37,7 +37,7 @@ "init", "selinux_adapter", "cJSON", - "runtime_core" + "runtime_core" ], "third_party": [] }, diff --git a/frameworks/js/ani/include/sensor_ani.h b/frameworks/js/ani/include/sensor_ani.h index be11ac1711c37a0a90df2978ea5e93a182a7a27d..cc306ac64b052753ede234091df6688d0aa9ea19 100644 --- a/frameworks/js/ani/include/sensor_ani.h +++ b/frameworks/js/ani/include/sensor_ani.h @@ -117,15 +117,11 @@ public: ~AsyncCallbackInfo() { CALL_LOG_ENTER; - if (type != ONCE_CALLBACK) { - for (int32_t i = 0; i < CALLBACK_NUM; ++i) { - if (callback[i] != nullptr) { - SEN_HILOGD("Delete reference, i:%{public}d", i); - env->GlobalReference_Delete(callback[i]); - callback[i] = nullptr; - env = nullptr; - vm = nullptr; - } + for (int32_t i = 0; i < CALLBACK_NUM; ++i) { + if (callback[i] != nullptr) { + SEN_HILOGD("Delete reference, i:%{public}d", i); + env->GlobalReference_Delete(callback[i]); + callback[i] = nullptr; } } } diff --git a/frameworks/js/ani/src/sensor_ani.cpp b/frameworks/js/ani/src/sensor_ani.cpp index 84f037ec0cc57b6ffcc0c2137be575e0c43c75bf..f6532aad1385bace2328d07f22c5952acfb06522 100644 --- a/frameworks/js/ani/src/sensor_ani.cpp +++ b/frameworks/js/ani/src/sensor_ani.cpp @@ -628,13 +628,14 @@ static int32_t RemoveCallback(ani_env *env, int32_t sensorTypeId, ani_object cal return callbackInfos.size(); } -static int32_t UnsubscribeSensor(int32_t sensorTypeId) +static int32_t UnaniSubscribeSensor(int32_t sensorTypeId) { int32_t ret = DeactivateSensor(sensorTypeId, &user); if (ret != ERR_OK) { SEN_HILOGE("DeactivateSensor failed"); return ret; } + return UnsubscribeSensor(sensorTypeId, &user); } @@ -671,9 +672,9 @@ static void Off([[maybe_unused]] ani_env *env, ani_string type, ani_object callb SEN_HILOGW("There are other client subscribe system js api as well, not need unsubscribe"); return; } - int32_t ret = UnsubscribeSensor(sensorTypeId); + int32_t ret = UnaniSubscribeSensor(sensorTypeId); if (ret == PARAMETER_ERROR || ret == PERMISSION_DENIED) { - ThrowBusinessError(env, ret, "UnsubscribeSensor fail"); + ThrowBusinessError(env, ret, "UnaniSubscribeSensor fail"); } return; } diff --git a/frameworks/js/napi/BUILD.gn b/frameworks/js/napi/BUILD.gn index 7fde7b06be299fd86a6758fa692fb50a3e7181c7..23f37569a7584d99b2db2eb029b6ce939e2bd63f 100644 --- a/frameworks/js/napi/BUILD.gn +++ b/frameworks/js/napi/BUILD.gn @@ -45,6 +45,7 @@ ohos_shared_library("libsensor") { "hilog:libhilog", "ipc:ipc_single", "napi:ace_napi", + "samgr:samgr_proxy", ] relative_install_dir = "module" part_name = "sensor" diff --git a/frameworks/native/include/sensor_client_proxy.h b/frameworks/native/include/sensor_client_proxy.h index a2a5ca18d68c05fb9785b24dd0dcfad1037ec1ef..3358373c634b3ea5474549f135886d8458539a52 100755 --- a/frameworks/native/include/sensor_client_proxy.h +++ b/frameworks/native/include/sensor_client_proxy.h @@ -12,10 +12,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #ifndef SENSOR_CLIENT_PROXY_H #define SENSOR_CLIENT_PROXY_H - +#include #include "iremote_proxy.h" #include "sensor_agent_type.h" diff --git a/frameworks/native/src/sensor_agent_proxy.cpp b/frameworks/native/src/sensor_agent_proxy.cpp index d86e4e87b113b0dd69e12844212f3f30a0136350..a2d84089316edcec23d79d8bf31344a5b3dbcbac 100644 --- a/frameworks/native/src/sensor_agent_proxy.cpp +++ b/frameworks/native/src/sensor_agent_proxy.cpp @@ -102,7 +102,7 @@ void SensorAgentProxy::SetIsChannelCreated(bool isChannelCreated) int32_t SensorAgentProxy::CreateSensorDataChannel() { - SEN_HILOGI("In"); + CALL_LOG_ENTER; std::lock_guard chanelLock(chanelMutex_); if (isChannelCreated_) { SEN_HILOGI("The channel has already been created"); @@ -121,23 +121,20 @@ int32_t SensorAgentProxy::CreateSensorDataChannel() SEN_HILOGE("Create data channel failed, ret:%{public}d", ret); return ret; } - { - SensorXcollie SensorXcollie("SensorAgentProxy:TransferDataChannel", XCOLLIE_TIMEOUT_5S); - ret = SEN_CLIENT.TransferDataChannel(dataChannel_); - } + SensorXcollie sensorXcollie("SensorAgentProxy:TransferDataChannel", XCOLLIE_TIMEOUT_5S); + ret = SEN_CLIENT.TransferDataChannel(dataChannel_); if (ret != ERR_OK) { auto destroyRet = dataChannel_->DestroySensorDataChannel(); SEN_HILOGE("Transfer data channel failed, ret:%{public}d, destroyRet:%{public}d", ret, destroyRet); return ret; } isChannelCreated_ = true; - SEN_HILOGI("Done"); return ERR_OK; } int32_t SensorAgentProxy::DestroySensorDataChannel() { - SEN_HILOGI("In"); + CALL_LOG_ENTER; std::lock_guard chanelLock(chanelMutex_); if (!isChannelCreated_) { SEN_HILOGI("Channel has been destroyed"); @@ -149,16 +146,13 @@ int32_t SensorAgentProxy::DestroySensorDataChannel() SEN_HILOGE("Destroy data channel failed, ret:%{public}d", ret); return ret; } - { - SensorXcollie SensorXcollie("SensorAgentProxy:DestroyDataChannel", XCOLLIE_TIMEOUT_5S); - ret = SEN_CLIENT.DestroyDataChannel(); - } + SensorXcollie sensorXcollie("SensorAgentProxy:DestroyDataChannel", XCOLLIE_TIMEOUT_5S); + ret = SEN_CLIENT.DestroyDataChannel(); if (ret != ERR_OK) { SEN_HILOGE("Destroy service data channel fail, ret:%{public}d", ret); return ret; } isChannelCreated_ = false; - SEN_HILOGI("Done"); return ERR_OK; } @@ -187,11 +181,8 @@ int32_t SensorAgentProxy::ActivateSensor(const SensorDescription &sensorDesc, co SEN_HILOGE("Subscribe user first"); return ERROR; } - int32_t ret = 0; - { - SensorXcollie SensorXcollie("SensorAgentProxy:EnableSensor", XCOLLIE_TIMEOUT_15S); - ret = SEN_CLIENT.EnableSensor(sensorDesc, samplingInterval_, reportInterval_); - } + SensorXcollie sensorXcollie("SensorAgentProxy:EnableSensor", XCOLLIE_TIMEOUT_15S); + int32_t ret = SEN_CLIENT.EnableSensor(sensorDesc, samplingInterval_, reportInterval_); if (ret != 0) { SEN_HILOGE("Enable sensor failed, ret:%{public}d", ret); subscribeSet.erase(user); @@ -212,8 +203,7 @@ int32_t SensorAgentProxy::DeactivateSensor(const SensorDescription &sensorDesc, CHKPR(user, OHOS::Sensors::ERROR); CHKPR(user->callback, OHOS::Sensors::ERROR); std::lock_guard subscribeLock(subscribeMutex_); - if (!(SEN_CLIENT.IsValid(sensorDesc) || - ((!SEN_CLIENT.IsValid(sensorDesc)) && subscribeMap_.find(sensorDesc) != subscribeMap_.end()))) { + if ((!SEN_CLIENT.IsValid(sensorDesc)) && subscribeMap_.find(sensorDesc) == subscribeMap_.end()) { SEN_HILOGE("sensorDesc is invalid, deviceIndex:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); return PARAMETER_ERROR; @@ -234,15 +224,12 @@ int32_t SensorAgentProxy::DeactivateSensor(const SensorDescription &sensorDesc, subscribeSet.erase(user); if (subscribeSet.empty()) { subscribeMap_.erase(sensorDesc); - int32_t ret = 0; - { - if (!SEN_CLIENT.IsValid(sensorDesc)) { - SEN_HILOGW("No need to call DisableSensor"); - return OHOS::Sensors::SUCCESS; - } - SensorXcollie SensorXcollie("SensorAgentProxy:DisableSensor", XCOLLIE_TIMEOUT_15S); - ret = SEN_CLIENT.DisableSensor(sensorDesc); + if (!SEN_CLIENT.IsValid(sensorDesc)) { + SEN_HILOGW("No need to call DisableSensor"); + return OHOS::Sensors::SUCCESS; } + SensorXcollie sensorXcollie("SensorAgentProxy:DisableSensor", XCOLLIE_TIMEOUT_15S); + int32_t ret = SEN_CLIENT.DisableSensor(sensorDesc); if (ret != 0) { SEN_HILOGE("DisableSensor failed, ret:%{public}d", ret); return ret; @@ -325,8 +312,7 @@ int32_t SensorAgentProxy::UnsubscribeSensor(const SensorDescription &sensorDesc, CHKPR(user->callback, OHOS::Sensors::ERROR); { std::lock_guard subscribeLock(subscribeMutex_); - if (!(SEN_CLIENT.IsValid(sensorDesc) || - ((!SEN_CLIENT.IsValid(sensorDesc)) && unsubscribeMap_.find(sensorDesc) != unsubscribeMap_.end()))) { + if ((!SEN_CLIENT.IsValid(sensorDesc)) && unsubscribeMap_.find(sensorDesc) == unsubscribeMap_.end()) { SEN_HILOGE("sensorDesc is invalid, deviceIndex:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); return PARAMETER_ERROR; @@ -399,11 +385,8 @@ void SensorAgentProxy::ClearSensorInfos() const int32_t SensorAgentProxy::ConvertSensorInfos() const { CALL_LOG_ENTER; - std::vector sensorList; - { - SensorXcollie SensorXcollie("SensorAgentProxy:GetSensorList", XCOLLIE_TIMEOUT_5S); - sensorList = SEN_CLIENT.GetSensorList(); - } + SensorXcollie sensorXcollie("SensorAgentProxy:GetSensorList", XCOLLIE_TIMEOUT_5S); + std::vector sensorList = SEN_CLIENT.GetSensorList(); if (sensorList.empty()) { SEN_HILOGE("Get sensor lists failed"); return ERROR; @@ -473,7 +456,6 @@ int32_t SensorAgentProxy::GetDeviceSensors(int32_t deviceId, SensorInfo **single } } std::vector singleDevSensors; - SensorXcollie SensorXcollie("SensorAgentProxy:ConvertSensorInfosByDevice", XCOLLIE_TIMEOUT_5S); int32_t ret = SEN_CLIENT.GetSensorListByDevice(deviceId, singleDevSensors); if (ret != ERR_OK || singleDevSensors.empty()) { SEN_HILOGE("Get device sensor lists failed"); @@ -629,11 +611,8 @@ int32_t SensorAgentProxy::SuspendSensors(int32_t pid) SEN_HILOGE("Pid is invalid, pid:%{public}d", pid); return PARAMETER_ERROR; } - int32_t ret = 0; - { - SensorXcollie SensorXcollie("SensorAgentProxy:SuspendSensors", XCOLLIE_TIMEOUT_5S); - ret = SEN_CLIENT.SuspendSensors(pid); - } + SensorXcollie sensorXcollie("SensorAgentProxy:SuspendSensors", XCOLLIE_TIMEOUT_5S); + int32_t ret = SEN_CLIENT.SuspendSensors(pid); if (ret != ERR_OK) { SEN_HILOGD("Suspend sensors failed, ret:%{public}d", ret); } @@ -647,11 +626,8 @@ int32_t SensorAgentProxy::ResumeSensors(int32_t pid) SEN_HILOGE("Pid is invalid, pid:%{public}d", pid); return PARAMETER_ERROR; } - int32_t ret = 0; - { - SensorXcollie SensorXcollie("SensorAgentProxy:ResumeSensors", XCOLLIE_TIMEOUT_5S); - ret = SEN_CLIENT.ResumeSensors(pid); - } + SensorXcollie sensorXcollie("SensorAgentProxy:ResumeSensors", XCOLLIE_TIMEOUT_5S); + int32_t ret = SEN_CLIENT.ResumeSensors(pid); if (ret != ERR_OK) { SEN_HILOGD("Resume sensors failed, ret:%{public}d", ret); } @@ -674,11 +650,8 @@ int32_t SensorAgentProxy::GetSensorActiveInfos(int32_t pid, sensorActiveInfos_ = nullptr; } std::vector activeInfoList; - int32_t ret = 0; - { - SensorXcollie SensorXcollie("SensorAgentProxy:GetActiveInfoList", XCOLLIE_TIMEOUT_5S); - ret = SEN_CLIENT.GetActiveInfoList(pid, activeInfoList); - } + SensorXcollie sensorXcollie("SensorAgentProxy:GetActiveInfoList", XCOLLIE_TIMEOUT_5S); + int32_t ret = SEN_CLIENT.GetActiveInfoList(pid, activeInfoList); if (ret != ERR_OK) { SEN_HILOGE("Get active info list failed, ret:%{public}d", ret); return ret; @@ -712,11 +685,8 @@ int32_t SensorAgentProxy::Register(SensorActiveInfoCB callback) { CHKPR(callback, OHOS::Sensors::ERROR); CHKPR(dataChannel_, INVALID_POINTER); - int32_t ret = 0; - { - SensorXcollie SensorXcollie("SensorAgentProxy:Register", XCOLLIE_TIMEOUT_5S); - ret = SEN_CLIENT.Register(callback, dataChannel_); - } + SensorXcollie sensorXcollie("SensorAgentProxy:Register", XCOLLIE_TIMEOUT_5S); + int32_t ret = SEN_CLIENT.Register(callback, dataChannel_); if (ret != ERR_OK) { SEN_HILOGE("Register sensor active info callback failed, ret:%{public}d", ret); } @@ -726,11 +696,8 @@ int32_t SensorAgentProxy::Register(SensorActiveInfoCB callback) int32_t SensorAgentProxy::Unregister(SensorActiveInfoCB callback) { CHKPR(callback, OHOS::Sensors::ERROR); - int32_t ret = 0; - { - SensorXcollie SensorXcollie("SensorAgentProxy:Unregister", XCOLLIE_TIMEOUT_5S); - ret = SEN_CLIENT.Unregister(callback); - } + SensorXcollie sensorXcollie("SensorAgentProxy:Unregister", XCOLLIE_TIMEOUT_5S); + int32_t ret = SEN_CLIENT.Unregister(callback); if (ret != ERR_OK) { SEN_HILOGE("Unregister sensor active info callback failed, ret:%{public}d", ret); } @@ -739,11 +706,8 @@ int32_t SensorAgentProxy::Unregister(SensorActiveInfoCB callback) int32_t SensorAgentProxy::ResetSensors() const { - int32_t ret = 0; - { - SensorXcollie SensorXcollie("SensorAgentProxy:ResetSensors", XCOLLIE_TIMEOUT_5S); - ret = SEN_CLIENT.ResetSensors(); - } + SensorXcollie sensorXcollie("SensorAgentProxy:ResetSensors", XCOLLIE_TIMEOUT_5S); + int32_t ret = SEN_CLIENT.ResetSensors(); if (ret != ERR_OK) { SEN_HILOGE("Reset sensors failed, ret:%{public}d", ret); } @@ -763,10 +727,7 @@ int32_t SensorAgentProxy::SubscribeSensorPlug(const SensorUser *user) CHKPR(user->plugCallback, OHOS::Sensors::ERROR); int32_t ret = 0; - { - SensorXcollie SensorXcollie("SensorAgentProxy:CreateClientRemoteObject()", XCOLLIE_TIMEOUT_5S); - ret = SEN_CLIENT.CreateClientRemoteObject(); - } + ret = SEN_CLIENT.CreateClientRemoteObject(); if (ret != ERR_OK) { SEN_HILOGE("CreateClientRemoteObject failed, ret:%{public}d", ret); return ret; @@ -831,7 +792,6 @@ bool SensorAgentProxy::UpdateSensorInfo(const SensorPlugData &info) int32_t ret = 0; if (subscribeMap_.find({info.deviceId, info.sensorTypeId, info.sensorId, info.location}) != subscribeMap_.end()) { - SensorXcollie SensorXcollie("SensorAgentProxy:DisableSensor", XCOLLIE_TIMEOUT_15S); ret = SEN_CLIENT.DisableSensor({info.deviceId, info.sensorTypeId, info.sensorId, info.location}); } if (ret != 0) { diff --git a/frameworks/native/src/sensor_client_stub.cpp b/frameworks/native/src/sensor_client_stub.cpp index 81ac153fe46c05c8dcf6ca5091ec08d72a4851be..49075ec14a95aa682859cbce1819de32d397eebb 100644 --- a/frameworks/native/src/sensor_client_stub.cpp +++ b/frameworks/native/src/sensor_client_stub.cpp @@ -13,6 +13,7 @@ * limitations under the License. */ +#include #include "sensor_client_stub.h" #include "sensor_agent_proxy.h" diff --git a/interfaces/inner_api/sensor_agent_type.h b/interfaces/inner_api/sensor_agent_type.h index 3a020696efa24c687756871f2bcc9ad3976e3abc..4447b446f7f21bf5670cf9086cca6ab870830bbf 100644 --- a/interfaces/inner_api/sensor_agent_type.h +++ b/interfaces/inner_api/sensor_agent_type.h @@ -535,7 +535,7 @@ typedef struct HeadPostureData { } HeadPostureData; typedef struct DropDetectionData { - float status = 0.0; + float status = 0.0F; } DropDetectionData; typedef struct SensorActiveInfo { diff --git a/rust/utils/socket_ipc_rust_ffi/src/stream_buffer.rs b/rust/utils/socket_ipc_rust_ffi/src/stream_buffer.rs index 35cb254f367d740ecb69f7150072ca68e91cf8b2..48b57faac06c1b14ad1a81986574c99b2f3eba8d 100644 --- a/rust/utils/socket_ipc_rust_ffi/src/stream_buffer.rs +++ b/rust/utils/socket_ipc_rust_ffi/src/stream_buffer.rs @@ -163,12 +163,10 @@ impl StreamBuffer { } } fn get_error_status_remark(&self) -> *const c_char { - // Creating a new C-compatible string will never fail, - // because the supplied bytes always contain greater than 0. - let s: CString = match self.rw_error_status { - ErrorStatus::Ok => CString::new("OK").unwrap_or_default(), - ErrorStatus::Read => CString::new("READ_ERROR").unwrap_or_default(), - ErrorStatus::Write => CString::new("WRITE_ERROR").unwrap_or_default(), + let s: &[c_char] = match self.rw_error_status { + ErrorStatus::Ok => b"OK\0", + ErrorStatus::Read => b"READ_ERROR\0", + ErrorStatus::Write => b"WRITE_ERROR\0", }; s.as_ptr() } diff --git a/rust/utils/socket_ipc_rust_ffi/src/stream_buffer/ffi.rs b/rust/utils/socket_ipc_rust_ffi/src/stream_buffer/ffi.rs index a72de8fd503959e33d74e7d80d32f112342d966b..a56ef5dc5bfed0dde1f8edaf18a5a55d5b93a72c 100644 --- a/rust/utils/socket_ipc_rust_ffi/src/stream_buffer/ffi.rs +++ b/rust/utils/socket_ipc_rust_ffi/src/stream_buffer/ffi.rs @@ -176,7 +176,6 @@ pub unsafe extern "C" fn StreamBufferChkRWError(object: *const StreamBuffer) -> pub unsafe extern "C" fn StreamBufferGetErrorStatusRemark(object: *const StreamBuffer) -> *const c_char { info!(LOG_LABEL, "enter StreamBufferGetErrorStatusRemark"); if let Some(obj) = StreamBuffer::as_ref(object) { - // SAFETY: The Rust side creates a CString string and this function should be called only here obj.get_error_status_remark() } else { std::ptr::null() diff --git a/services/hdi_connection/adapter/src/hdi_connection.cpp b/services/hdi_connection/adapter/src/hdi_connection.cpp index bead5ae9548e7d239bc6c44029924aacbe1a08b9..e587314823059a1268f19e5d38404df26ccb1838 100644 --- a/services/hdi_connection/adapter/src/hdi_connection.cpp +++ b/services/hdi_connection/adapter/src/hdi_connection.cpp @@ -61,7 +61,7 @@ int32_t HdiConnection::ConnectHdi() CALL_LOG_ENTER; int32_t retry = 0; while (retry < GET_HDI_SERVICE_COUNT) { - std::lock_guard sensorInterface(g_sensorInterfaceMutex); + std::lock_guard sensorInterfaceLock(g_sensorInterfaceMutex); g_sensorInterface = ISensorInterface::Get(); if (g_sensorInterface != nullptr) { SEN_HILOGI("Connect v3_0 hdi success"); @@ -80,14 +80,14 @@ int32_t HdiConnection::ConnectHdi() HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SENSOR, "HDF_SERVICE_EXCEPTION", HiSysEvent::EventType::FAULT, "PKG_NAME", "ConnectHdi", "ERROR_CODE", CONNECT_SENSOR_HDF_ERR); #endif // HIVIEWDFX_HISYSEVENT_ENABLE - SEN_HILOGE("Connect v3_0 hdi failed"); + SEN_HILOGE("Connect V3_0 hdi failed"); return ERR_NO_INIT; } int32_t HdiConnection::GetSensorList(std::vector &sensorList) { CALL_LOG_ENTER; - std::lock_guard sensorInterface(g_sensorInterfaceMutex); + std::lock_guard sensorInterfaceLock(g_sensorInterfaceMutex); CHKPR(g_sensorInterface, ERR_NO_INIT); std::vector sensorInfos; SensorXcollie sensorXcollie("HdiConnection:GetSensorList", XCOLLIE_TIMEOUT_5S); @@ -132,7 +132,7 @@ int32_t HdiConnection::EnableSensor(const SensorDescription &sensorDesc) { SEN_HILOGI("In, deviceIndex:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); - std::lock_guard sensorInterface(g_sensorInterfaceMutex); + std::lock_guard sensorInterfaceLock(g_sensorInterfaceMutex); CHKPR(g_sensorInterface, ERR_NO_INIT); SensorXcollie sensorXcollie("HdiConnection:EnableSensor", XCOLLIE_TIMEOUT_5S); int32_t ret = g_sensorInterface->Enable({sensorDesc.deviceId, sensorDesc.sensorType, @@ -155,7 +155,7 @@ int32_t HdiConnection::DisableSensor(const SensorDescription &sensorDesc) { SEN_HILOGI("In, deviceIndex:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); - std::lock_guard sensorInterface(g_sensorInterfaceMutex); + std::lock_guard sensorInterfaceLock(g_sensorInterfaceMutex); CHKPR(g_sensorInterface, ERR_NO_INIT); SensorXcollie sensorXcollie("HdiConnection:DisableSensor", XCOLLIE_TIMEOUT_5S); int32_t ret = g_sensorInterface->Disable({sensorDesc.deviceId, sensorDesc.sensorType, @@ -176,7 +176,7 @@ int32_t HdiConnection::DisableSensor(const SensorDescription &sensorDesc) int32_t HdiConnection::SetBatch(const SensorDescription &sensorDesc, int64_t samplingInterval, int64_t reportInterval) { - std::lock_guard sensorInterface(g_sensorInterfaceMutex); + std::lock_guard sensorInterfaceLock(g_sensorInterfaceMutex); CHKPR(g_sensorInterface, ERR_NO_INIT); SensorXcollie sensorXcollie("HdiConnection:SetBatch", XCOLLIE_TIMEOUT_5S); int32_t ret = g_sensorInterface->SetBatch({sensorDesc.deviceId, sensorDesc.sensorType, @@ -196,7 +196,7 @@ int32_t HdiConnection::SetBatch(const SensorDescription &sensorDesc, int64_t sam int32_t HdiConnection::SetMode(const SensorDescription &sensorDesc, int32_t mode) { CALL_LOG_ENTER; - std::lock_guard sensorInterface(g_sensorInterfaceMutex); + std::lock_guard sensorInterfaceLock(g_sensorInterfaceMutex); CHKPR(g_sensorInterface, ERR_NO_INIT); SensorXcollie sensorXcollie("HdiConnection:SetMode", XCOLLIE_TIMEOUT_5S); int32_t ret = g_sensorInterface->SetMode({sensorDesc.deviceId, sensorDesc.sensorType, @@ -216,7 +216,7 @@ int32_t HdiConnection::RegisterDataReport(ReportDataCb cb, sptr sensorInterface(g_sensorInterfaceMutex); + std::lock_guard sensorInterfaceLock(g_sensorInterfaceMutex); CHKPR(g_sensorInterface, ERR_NO_INIT); SensorXcollie sensorXcollie("HdiConnection:RegisterDataReport", XCOLLIE_TIMEOUT_5S); int32_t ret = g_sensorInterface->RegisterAsync(0, g_eventCallback); @@ -237,17 +237,20 @@ int32_t HdiConnection::DestroyHdiConnection() { CALL_LOG_ENTER; { - std::lock_guard sensorInterface(g_sensorInterfaceMutex); + std::lock_guard sensorInterfaceLock(g_sensorInterfaceMutex); CHKPR(g_sensorInterface, ERR_NO_INIT); - SensorXcollie unregisterAsyncXcollie("HdiConnection:UnregisterAsync", XCOLLIE_TIMEOUT_5S); - int32_t ret = g_sensorInterface->UnregisterAsync(DEFAULT_GROUP_ID, g_eventCallback); - if (ret != ERR_OK) { + int32_t ret = 0; + { + SensorXcollie unregisterAsyncXcollie("HdiConnection:UnregisterAsync", XCOLLIE_TIMEOUT_5S); + ret = g_sensorInterface->UnregisterAsync(DEFAULT_GROUP_ID, g_eventCallback); + if (ret != ERR_OK) { #ifdef HIVIEWDFX_HISYSEVENT_ENABLE - HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SENSOR, "HDF_SERVICE_EXCEPTION", - HiSysEvent::EventType::FAULT, "PKG_NAME", "DestroyHdiConnection", "ERROR_CODE", ret); + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SENSOR, "HDF_SERVICE_EXCEPTION", + HiSysEvent::EventType::FAULT, "PKG_NAME", "DestroyHdiConnection", "ERROR_CODE", ret); #endif // HIVIEWDFX_HISYSEVENT_ENABLE - SEN_HILOGE("UnregisterAsync is failed"); - return ret; + SEN_HILOGE("UnregisterAsync is failed"); + return ret; + } } SensorXcollie unRegSensorPlugCallBackXcollie("HdiConnection:UnRegSensorPlugCallBack", XCOLLIE_TIMEOUT_5S); ret = g_sensorInterface->UnRegSensorPlugCallBack(g_plugCallback); @@ -270,7 +273,7 @@ int32_t HdiConnection::RegSensorPlugCallback(DevicePlugCallback cb) { CALL_LOG_ENTER; CHKPR(cb, ERR_NO_INIT); - std::lock_guard sensorInterface(g_sensorInterfaceMutex); + std::lock_guard sensorInterfaceLock(g_sensorInterfaceMutex); CHKPR(g_sensorInterface, ERR_NO_INIT); reportPlugDataCb_ = cb; SensorXcollie sensorXcollie("HdiConnection:RegSensorPlugCallback", XCOLLIE_TIMEOUT_5S); @@ -369,7 +372,7 @@ void HdiConnection::RegisterHdiDeathRecipient() void HdiConnection::UnregisterHdiDeathRecipient() { CALL_LOG_ENTER; - std::lock_guard sensorInterface(g_sensorInterfaceMutex); + std::lock_guard sensorInterfaceLock(g_sensorInterfaceMutex); CHKPV(g_sensorInterface); CHKPV(hdiDeathObserver_); SensorXcollie sensorXcollie("HdiConnection:UnregisterHdiDeathRecipient", XCOLLIE_TIMEOUT_5S); @@ -383,7 +386,7 @@ void HdiConnection::ProcessDeathObserver(const wptr &object) CHKPV(hdiService); CHKPV(hdiDeathObserver_); { - std::lock_guard sensorInterface(g_sensorInterfaceMutex); + std::lock_guard sensorInterfaceLock(g_sensorInterfaceMutex); hdiService->RemoveDeathRecipient(hdiDeathObserver_); g_eventCallback = nullptr; } @@ -400,15 +403,18 @@ void HdiConnection::ReEnableSensor() sensorInfo.first.deviceId, sensorInfo.first.sensorType, sensorInfo.first.sensorId); continue; } - SensorXcollie setBatchXcollie("HdiConnection:Reconnect:SetBatch", XCOLLIE_TIMEOUT_5S); - int32_t ret = g_sensorInterface->SetBatch({sensorInfo.first.deviceId, sensorInfo.first.sensorType, - sensorInfo.first.sensorId, sensorInfo.first.location}, - info.GetSamplingPeriodNs(), info.GetMaxReportDelayNs()); - if (ret != ERR_OK) { - SEN_HILOGE("deviceIndex:%{public}d, sensortype:%{public}d, sensorId:%{public}d set batch fail," - "err:%{public}d", sensorInfo.first.deviceId, sensorInfo.first.sensorType, sensorInfo.first.sensorId, - ret); - continue; + int32_t ret = 0; + { + SensorXcollie setBatchXcollie("HdiConnection:Reconnect:SetBatch", XCOLLIE_TIMEOUT_5S); + ret = g_sensorInterface->SetBatch({sensorInfo.first.deviceId, sensorInfo.first.sensorType, + sensorInfo.first.sensorId, sensorInfo.first.location}, + info.GetSamplingPeriodNs(), info.GetMaxReportDelayNs()); + if (ret != ERR_OK) { + SEN_HILOGE("deviceIndex:%{public}d, sensortype:%{public}d, sensorId:%{public}d set batch fail," + "err:%{public}d", sensorInfo.first.deviceId, sensorInfo.first.sensorType, sensorInfo.first.sensorId, + ret); + continue; + } } SensorXcollie enableXcollie("HdiConnection:Reconnect:ReEnable", XCOLLIE_TIMEOUT_5S); ret = g_sensorInterface->Enable({sensorInfo.first.deviceId, sensorInfo.first.sensorType, @@ -430,12 +436,14 @@ void HdiConnection::Reconnect() return; } { - std::lock_guard sensorInterface(g_sensorInterfaceMutex); - SensorXcollie registerXcollie("HdiConnection:Reconnect:RegisterAsync", XCOLLIE_TIMEOUT_5S); - ret = g_sensorInterface->RegisterAsync(DEFAULT_GROUP_ID, g_eventCallback); - if (ret != ERR_OK) { - SEN_HILOGE("RegisterAsync callback fail"); - return; + std::lock_guard sensorInterfaceLock(g_sensorInterfaceMutex); + { + SensorXcollie registerXcollie("HdiConnection:Reconnect:RegisterAsync", XCOLLIE_TIMEOUT_5S); + ret = g_sensorInterface->RegisterAsync(DEFAULT_GROUP_ID, g_eventCallback); + if (ret != ERR_OK) { + SEN_HILOGE("RegisterAsync callback fail"); + return; + } } SensorXcollie regSensorPlugCallBackXcollie("HdiConnection:Reconnect:RegSensorPlugCallBack", XCOLLIE_TIMEOUT_5S); ret = g_sensorInterface->RegSensorPlugCallBack(g_plugCallback); @@ -450,14 +458,14 @@ void HdiConnection::Reconnect() SEN_HILOGE("Get sensor list fail"); return; } - std::lock_guard sensorInterface(g_sensorInterfaceMutex); + std::lock_guard sensorInterfaceLock(g_sensorInterfaceMutex); ReEnableSensor(); } int32_t HdiConnection::GetSensorListByDevice(int32_t deviceId, std::vector &singleDevSensors) { CALL_LOG_ENTER; - std::lock_guard sensorInterface(g_sensorInterfaceMutex); + std::lock_guard sensorInterfaceLock(g_sensorInterfaceMutex); CHKPR(g_sensorInterface, ERR_NO_INIT); std::vector sensorInfos; SensorXcollie sensorXcollie("HdiConnection:GetSensorListByDevice", XCOLLIE_TIMEOUT_5S); diff --git a/services/hdi_connection/interface/src/sensor_hdi_connection.cpp b/services/hdi_connection/interface/src/sensor_hdi_connection.cpp index f0ba3408bf246189a55dc04378fcddd63c13cbe6..8cd98e33d5213a8b53ed43d1d45038a5aeddec50 100644 --- a/services/hdi_connection/interface/src/sensor_hdi_connection.cpp +++ b/services/hdi_connection/interface/src/sensor_hdi_connection.cpp @@ -37,7 +37,7 @@ namespace { #ifdef BUILD_VARIANT_ENG constexpr float MAX_RANGE = 9999.0; constexpr float POWER = 20.0; -constexpr float RESOLUTION = 0.000001; +constexpr float RESOLITION = 0.000001; constexpr float MIN_SAMPLE_PERIOD_NS = 100000000; constexpr float MAX_SAMPLE_PERIOD_NS = 1000000000; const std::string VERSION_NAME = "1.0.1"; @@ -148,7 +148,7 @@ Sensor SensorHdiConnection::GenerateColorSensor() sensorColor.SetMaxRange(MAX_RANGE); sensorColor.SetSensorName("sensor_color"); sensorColor.SetVendorName("default_color"); - sensorColor.SetResolution(RESOLUTION); + sensorColor.SetResolution(RESOLITION); sensorColor.SetPower(POWER); sensorColor.SetMinSamplePeriodNs(MIN_SAMPLE_PERIOD_NS); sensorColor.SetMaxSamplePeriodNs(MAX_SAMPLE_PERIOD_NS); @@ -167,7 +167,7 @@ Sensor SensorHdiConnection::GenerateSarSensor() sensorSar.SetMaxRange(MAX_RANGE); sensorSar.SetSensorName("sensor_sar"); sensorSar.SetVendorName("default_sar"); - sensorSar.SetResolution(RESOLUTION); + sensorSar.SetResolution(RESOLITION); sensorSar.SetPower(POWER); sensorSar.SetMinSamplePeriodNs(MIN_SAMPLE_PERIOD_NS); sensorSar.SetMaxSamplePeriodNs(MAX_SAMPLE_PERIOD_NS); @@ -186,7 +186,7 @@ Sensor SensorHdiConnection::GenerateHeadPostureSensor() sensorHeadPosture.SetMaxRange(MAX_RANGE); sensorHeadPosture.SetSensorName("sensor_headPosture"); sensorHeadPosture.SetVendorName("default_headPosture"); - sensorHeadPosture.SetResolution(RESOLUTION); + sensorHeadPosture.SetResolution(RESOLITION); sensorHeadPosture.SetPower(POWER); sensorHeadPosture.SetMinSamplePeriodNs(MIN_SAMPLE_PERIOD_NS); sensorHeadPosture.SetMaxSamplePeriodNs(MAX_SAMPLE_PERIOD_NS); @@ -205,7 +205,7 @@ Sensor SensorHdiConnection::GenerateProximitySensor() sensorProximity.SetMaxRange(MAX_RANGE); sensorProximity.SetSensorName("sensor_proximity1"); sensorProximity.SetVendorName("default_proximity1"); - sensorProximity.SetResolution(RESOLUTION); + sensorProximity.SetResolution(RESOLITION); sensorProximity.SetPower(POWER); sensorProximity.SetMinSamplePeriodNs(MIN_SAMPLE_PERIOD_NS); sensorProximity.SetMaxSamplePeriodNs(MAX_SAMPLE_PERIOD_NS); diff --git a/test/unittest/interfaces/js/sensor/AmbientLightJsunit.test.js b/test/unittest/interfaces/js/sensor/AmbientLightJsunit.test.js deleted file mode 100644 index 5e32174730d796d162d1b6d5f9750f84fde38e39..0000000000000000000000000000000000000000 --- a/test/unittest/interfaces/js/sensor/AmbientLightJsunit.test.js +++ /dev/null @@ -1,575 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import CommonConstants from './CommonConstants'; -import sensor from '@ohos.sensor' - -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' - -describe("AmbientLightJsTest", function () { - function callback(data) { - console.info("callback" + JSON.stringify(data)); - expect(typeof(data.intensity)).assertEqual("number"); - expect(typeof(data.colorTemperature)).assertEqual("number"); - expect(typeof(data.infraredLuminance)).assertEqual("number"); - } - - function callback2(data) { - console.info("callback2" + JSON.stringify(data)); - expect(typeof(data.intensity)).assertEqual("number"); - expect(typeof(data.colorTemperature)).assertEqual("number"); - expect(typeof(data.infraredLuminance)).assertEqual("number"); - } - - beforeAll(function() { - /* - * @tc.setup: setup invoked before all testcases - */ - console.info('beforeAll called') - }) - - afterAll(function() { - /* - * @tc.teardown: teardown invoked after all testcases - */ - console.info('afterAll called') - }) - - beforeEach(function() { - /* - * @tc.setup: setup invoked before each testcases - */ - console.info('beforeEach called') - }) - - afterEach(function() { - /* - * @tc.teardown: teardown invoked after each testcases - */ - console.info('afterEach called') - }) - - /* - * @tc.number: AmbientLightJsTest_001 - * @tc.name: AmbientLightJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("AmbientLightJsTest_001", 0, async function (done) { - console.info('----------------------AmbientLightJsTest_001---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.AMBIENT_LIGHT, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - try { - sensor.on(sensor.SensorId.AMBIENT_LIGHT, callback); - setTimeout(() => { - sensor.off(sensor.SensorId.AMBIENT_LIGHT); - done(); - }, 500); - } catch (error) { - console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - }); - } catch (error) { - console.info('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) - - /* - * @tc.number: AmbientLightJsTest_002 - * @tc.name: AmbientLightJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("AmbientLightJsTest_002", 0, async function (done) { - console.info('----------------------AmbientLightJsTest_002---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.AMBIENT_LIGHT, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - try { - sensor.on(sensor.SensorId.AMBIENT_LIGHT, callback, {'interval': 100000000}); - setTimeout(() => { - sensor.off(sensor.SensorId.AMBIENT_LIGHT); - done(); - }, 500); - } catch (error) { - console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - }); - } catch (error) { - console.info('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) - - /* - * @tc.number: AmbientLightJsTest_003 - * @tc.name: AmbientLightJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("AmbientLightJsTest_003", 0, async function (done) { - console.info('----------------------AmbientLightJsTest_003---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.AMBIENT_LIGHT, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - function onSensorCallback(data) { - console.error('AmbientLightJsTest_003 callback in'); - expect(true).assertTrue(); - done(); - } - try { - sensor.on(sensor.SensorId.AMBIENT_LIGHT, onSensorCallback, {'interval': 100000000}, 5); - setTimeout(() => { - sensor.off(sensor.SensorId.AMBIENT_LIGHT); - done(); - }, 500); - } catch (error) { - console.info('On fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - }); - } catch (error) { - console.info('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) - - /* - * @tc.number: AmbientLightJsTest_004 - * @tc.name: AmbientLightJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("AmbientLightJsTest_004", 0, async function (done) { - console.info('----------------------AmbientLightJsTest_004---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.AMBIENT_LIGHT, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - try { - sensor.on(sensor.SensorId.AMBIENT_LIGHT, callback, {'interval': -100000000}); - sensor.off(sensor.SensorId.AMBIENT_LIGHT); - done(); - } catch (error) { - console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SERVICE_EXCEPTION_CODE); - expect(error.message).assertEqual(CommonConstants.SERVICE_EXCEPTION_MSG); - done(); - } - }); - } catch (error) { - console.info('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) - - /* - * @tc.number: AmbientLightJsTest_005 - * @tc.name: AmbientLightJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("AmbientLightJsTest_005", 0, async function (done) { - console.info('----------------------AmbientLightJsTest_005---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.AMBIENT_LIGHT, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - try { - sensor.once(sensor.SensorId.AMBIENT_LIGHT, callback); - setTimeout(() => { - expect(true).assertTrue(); - done(); - }, 500); - } catch (error) { - console.error('Once fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - }); - } catch (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) - - /* - * @tc.number: AmbientLightJsTest_006 - * @tc.name: AmbientLightJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("AmbientLightJsTest_006", 0, async function (done) { - console.info('----------------------AmbientLightJsTest_006---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.AMBIENT_LIGHT, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - try{ - sensor.once(sensor.SensorId.AMBIENT_LIGHT, callback, 5); - setTimeout(() => { - expect(true).assertTrue(); - done(); - }, 500); - } catch (error) { - console.error('Once fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - }); - } catch (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) - - /* - * @tc.number: AmbientLightJsTest_007 - * @tc.name: AmbientLightJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("AmbientLightJsTest_007", 0, async function (done) { - console.info('----------------------AmbientLightJsTest_007---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.AMBIENT_LIGHT, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - try{ - sensor.once(sensor.SensorId.AMBIENT_LIGHT, 5); - } catch (error) { - console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.PARAMETER_ERROR_CODE); - done(); - } - }); - } catch (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) - - /* - * @tc.number: AmbientLightJsTest_008 - * @tc.name: AmbientLightJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("AmbientLightJsTest_008", 0, async function (done) { - console.info('----------------------AmbientLightJsTest_008---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.AMBIENT_LIGHT, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - try { - sensor.off(-1, callback); - } catch (error) { - expect(error.code).assertEqual(CommonConstants.PARAMETER_ERROR_CODE); - done(); - } - }); - } catch (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) - - /* - * @tc.number: AmbientLightJsTest_009 - * @tc.name: AmbientLightJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("AmbientLightJsTest_009", 0, async function (done) { - console.info('----------------------AmbientLightJsTest_009---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.AMBIENT_LIGHT, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - try { - sensor.on(sensor.SensorId.AMBIENT_LIGHT, callback); - sensor.on(sensor.SensorId.AMBIENT_LIGHT, callback2); - setTimeout(() => { - sensor.off(sensor.SensorId.AMBIENT_LIGHT); - done(); - }, 1000); - } catch (error) { - console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - }); - } catch (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) - - /* - * @tc.number: AmbientLightJsTest_010 - * @tc.name: AmbientLightJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("AmbientLightJsTest_010", 0, async function (done) { - console.info('----------------------AmbientLightJsTest_010---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.AMBIENT_LIGHT, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - try { - sensor.on(sensor.SensorId.AMBIENT_LIGHT, callback); - sensor.on(sensor.SensorId.AMBIENT_LIGHT, callback2); - setTimeout(() => { - sensor.off(sensor.SensorId.AMBIENT_LIGHT, callback); - }, 500); - setTimeout(() => { - sensor.off(sensor.SensorId.AMBIENT_LIGHT, callback2); - done(); - }, 1000); - } catch (error) { - console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - }); - } catch (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) - - /* - * @tc.number: AmbientLightJsTest_011 - * @tc.name: AmbientLightJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("AmbientLightJsTest_011", 0, async function (done) { - console.info('----------------------AmbientLightJsTest_011---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.AMBIENT_LIGHT, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - try { - sensor.on(sensor.SensorId.AMBIENT_LIGHT, callback, {'interval': 100000000}); - sensor.once(sensor.SensorId.AMBIENT_LIGHT, callback2); - setTimeout(() => { - sensor.off(sensor.SensorId.AMBIENT_LIGHT); - done(); - }, 1000); - } catch (error) { - console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - }); - } catch (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) - - /* - * @tc.number: AmbientLightJsTest_012 - * @tc.name: AmbientLightJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("AmbientLightJsTest_012", 0, async function (done) { - console.info('----------------------AmbientLightJsTest_012---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.AMBIENT_LIGHT, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - try { - sensor.on(sensor.SensorId.AMBIENT_LIGHT, callback, {'interval': 100000000}); - sensor.on(sensor.SensorId.AMBIENT_LIGHT, callback2, {'interval': 100000000}); - setTimeout(() => { - sensor.off(sensor.SensorId.AMBIENT_LIGHT, callback); - }, 500); - setTimeout(() => { - sensor.off(sensor.SensorId.AMBIENT_LIGHT, callback2); - done(); - }, 1000); - } catch (error) { - console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - }); - } catch (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) - - /* - * @tc.number: AmbientLightJsTest_013 - * @tc.name: AmbientLightJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("AmbientLightJsTest_013", 0, async function (done) { - console.info('----------------------AmbientLightJsTest_013---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.AMBIENT_LIGHT, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - try { - sensor.on(sensor.SensorId.AMBIENT_LIGHT, callback, {'interval': 100000000}); - sensor.on(sensor.SensorId.AMBIENT_LIGHT, callback2, {'interval': 100000000}); - setTimeout(() => { - sensor.off(sensor.SensorId.AMBIENT_LIGHT); - done(); - }, 1000); - } catch (error) { - console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - }); - } catch (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) -}) diff --git a/test/unittest/interfaces/js/sensor/GravityJsTest.test.js b/test/unittest/interfaces/js/sensor/GravityJsTest.test.js deleted file mode 100644 index 07a5b46a2e9bab44983f0ae68eb6fa4709414153..0000000000000000000000000000000000000000 --- a/test/unittest/interfaces/js/sensor/GravityJsTest.test.js +++ /dev/null @@ -1,575 +0,0 @@ -/* - * 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 - * - * 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 CommonConstants from './CommonConstants'; -import sensor from '@ohos.sensor' - -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' - -describe("GravityJsTest", function () { - function callback(data) { - console.info("callback" + JSON.stringify(data)); - expect(typeof(data.x)).assertEqual("number"); - expect(typeof(data.y)).assertEqual("number"); - expect(typeof(data.z)).assertEqual("number"); - } - - function callback2(data) { - console.info("callback2" + JSON.stringify(data)); - expect(typeof(data.x)).assertEqual("number"); - expect(typeof(data.y)).assertEqual("number"); - expect(typeof(data.z)).assertEqual("number"); - } - - beforeAll(function() { - /* - * @tc.setup: setup invoked before all testcases - */ - console.info('beforeAll called') - }) - - afterAll(function() { - /* - * @tc.teardown: teardown invoked after all testcases - */ - console.info('afterAll called') - }) - - beforeEach(function() { - /* - * @tc.setup: setup invoked before each testcases - */ - console.info('beforeEach called') - }) - - afterEach(function() { - /* - * @tc.teardown: teardown invoked after each testcases - */ - console.info('afterEach called') - }) - - /* - * @tc.number: GravityJsTest_001 - * @tc.name: GravityJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("GravityJsTest_001", 0, async function (done) { - console.info('----------------------GravityJsTest_001---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.GRAVITY, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - try { - sensor.on(sensor.SensorId.GRAVITY, callback); - setTimeout(() => { - sensor.off(sensor.SensorId.GRAVITY); - done(); - }, 500); - } catch (error) { - console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - }); - } catch (error) { - console.info('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) - - /* - * @tc.number: GravityJsTest_002 - * @tc.name: GravityJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("GravityJsTest_002", 0, async function (done) { - console.info('----------------------GravityJsTest_002---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.GRAVITY, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - try { - sensor.on(sensor.SensorId.GRAVITY, callback, {'interval': 100000000}); - setTimeout(() => { - sensor.off(sensor.SensorId.GRAVITY); - done(); - }, 500); - } catch (error) { - console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - }); - } catch (error) { - console.info('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) - - /* - * @tc.number: GravityJsTest_003 - * @tc.name: GravityJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("GravityJsTest_003", 0, async function (done) { - console.info('----------------------GravityJsTest_003---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.GRAVITY, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - function onSensorCallback(data) { - console.error('GravityJsTest_003 callback in'); - expect(true).assertTrue(); - done(); - } - try { - sensor.on(sensor.SensorId.GRAVITY, onSensorCallback, {'interval': 100000000}, 5); - setTimeout(() => { - sensor.off(sensor.SensorId.GRAVITY); - done(); - }, 500); - } catch (error) { - console.info('On fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - }); - } catch (error) { - console.info('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) - - /* - * @tc.number: GravityJsTest_004 - * @tc.name: GravityJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("GravityJsTest_004", 0, async function (done) { - console.info('----------------------GravityJsTest_004---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.GRAVITY, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - try { - sensor.on(sensor.SensorId.GRAVITY, callback, {'interval': -100000000}); - sensor.off(sensor.SensorId.GRAVITY); - done(); - } catch (error) { - console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SERVICE_EXCEPTION_CODE); - expect(error.message).assertEqual(CommonConstants.SERVICE_EXCEPTION_MSG); - done(); - } - }); - } catch (error) { - console.info('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) - - /* - * @tc.number: GravityJsTest_005 - * @tc.name: GravityJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("GravityJsTest_005", 0, async function (done) { - console.info('----------------------GravityJsTest_005---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.GRAVITY, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - try { - sensor.once(sensor.SensorId.GRAVITY, callback); - setTimeout(() => { - expect(true).assertTrue(); - done(); - }, 500); - } catch (error) { - console.error('Once fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - }); - } catch (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) - - /* - * @tc.number: GravityJsTest_006 - * @tc.name: GravityJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("GravityJsTest_006", 0, async function (done) { - console.info('----------------------GravityJsTest_006---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.GRAVITY, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - try{ - sensor.once(sensor.SensorId.GRAVITY, callback, 5); - setTimeout(() => { - expect(true).assertTrue(); - done(); - }, 500); - } catch (error) { - console.error('Once fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - }); - } catch (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) - - /* - * @tc.number: GravityJsTest_007 - * @tc.name: GravityJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("GravityJsTest_007", 0, async function (done) { - console.info('----------------------GravityJsTest_007---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.GRAVITY, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - try{ - sensor.once(sensor.SensorId.GRAVITY, 5); - } catch (error) { - console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.PARAMETER_ERROR_CODE); - done(); - } - }); - } catch (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) - - /* - * @tc.number: GravityJsTest_008 - * @tc.name: GravityJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("GravityJsTest_008", 0, async function (done) { - console.info('----------------------GravityJsTest_008---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.GRAVITY, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - try { - sensor.off(-1, callback); - } catch (error) { - expect(error.code).assertEqual(CommonConstants.PARAMETER_ERROR_CODE); - done(); - } - }); - } catch (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) - - /* - * @tc.number: GravityJsTest_009 - * @tc.name: GravityJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("GravityJsTest_009", 0, async function (done) { - console.info('----------------------GravityJsTest_009---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.GRAVITY, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - try { - sensor.on(sensor.SensorId.GRAVITY, callback); - sensor.on(sensor.SensorId.GRAVITY, callback2); - setTimeout(() => { - sensor.off(sensor.SensorId.GRAVITY); - done(); - }, 1000); - } catch (error) { - console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - }); - } catch (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) - - /* - * @tc.number: GravityJsTest_010 - * @tc.name: GravityJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("GravityJsTest_010", 0, async function (done) { - console.info('----------------------GravityJsTest_010---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.GRAVITY, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - try { - sensor.on(sensor.SensorId.GRAVITY, callback); - sensor.on(sensor.SensorId.GRAVITY, callback2); - setTimeout(() => { - sensor.off(sensor.SensorId.GRAVITY, callback); - }, 500); - setTimeout(() => { - sensor.off(sensor.SensorId.GRAVITY, callback2); - done(); - }, 1000); - } catch (error) { - console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - }); - } catch (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) - - /* - * @tc.number: GravityJsTest_011 - * @tc.name: GravityJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("GravityJsTest_011", 0, async function (done) { - console.info('----------------------GravityJsTest_011---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.GRAVITY, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - try { - sensor.on(sensor.SensorId.GRAVITY, callback, {'interval': 100000000}); - sensor.once(sensor.SensorId.GRAVITY, callback2); - setTimeout(() => { - sensor.off(sensor.SensorId.GRAVITY); - done(); - }, 1000); - } catch (error) { - console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - }); - } catch (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) - - /* - * @tc.number: GravityJsTest_012 - * @tc.name: GravityJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("GravityJsTest_012", 0, async function (done) { - console.info('----------------------GravityJsTest_012---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.GRAVITY, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - try { - sensor.on(sensor.SensorId.GRAVITY, callback, {'interval': 100000000}); - sensor.on(sensor.SensorId.GRAVITY, callback2, {'interval': 100000000}); - setTimeout(() => { - sensor.off(sensor.SensorId.GRAVITY, callback); - }, 500); - setTimeout(() => { - sensor.off(sensor.SensorId.GRAVITY, callback2); - done(); - }, 1000); - } catch (error) { - console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - }); - } catch (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) - - /* - * @tc.number: GravityJsTest_013 - * @tc.name: GravityJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("GravityJsTest_013", 0, async function (done) { - console.info('----------------------GravityJsTest_013---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.GRAVITY, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - try { - sensor.on(sensor.SensorId.GRAVITY, callback, {'interval': 100000000}); - sensor.on(sensor.SensorId.GRAVITY, callback2, {'interval': 100000000}); - setTimeout(() => { - sensor.off(sensor.SensorId.GRAVITY); - done(); - }, 1000); - } catch (error) { - console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - }); - } catch (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) -}) diff --git a/test/unittest/interfaces/js/sensor/OrientationJs.test.js b/test/unittest/interfaces/js/sensor/OrientationJs.test.js deleted file mode 100644 index b9c4a9dd471e2533d773f91fe63805cd42fbee2a..0000000000000000000000000000000000000000 --- a/test/unittest/interfaces/js/sensor/OrientationJs.test.js +++ /dev/null @@ -1,575 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import CommonConstants from './CommonConstants'; -import sensor from '@ohos.sensor' - -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' - -describe("OrientationJsTest", function () { - function callback(data) { - console.info("callback" + JSON.stringify(data)); - expect(typeof(data.intensity)).assertEqual("number"); - expect(typeof(data.colorTemperature)).assertEqual("number"); - expect(typeof(data.infraredLuminance)).assertEqual("number"); - } - - function callback2(data) { - console.info("callback2" + JSON.stringify(data)); - expect(typeof(data.intensity)).assertEqual("number"); - expect(typeof(data.colorTemperature)).assertEqual("number"); - expect(typeof(data.infraredLuminance)).assertEqual("number"); - } - - beforeAll(function() { - /* - * @tc.setup: setup invoked before all testcases - */ - console.info('beforeAll called') - }) - - afterAll(function() { - /* - * @tc.teardown: teardown invoked after all testcases - */ - console.info('afterAll called') - }) - - beforeEach(function() { - /* - * @tc.setup: setup invoked before each testcases - */ - console.info('beforeEach called') - }) - - afterEach(function() { - /* - * @tc.teardown: teardown invoked after each testcases - */ - console.info('afterEach called') - }) - - /* - * @tc.number: OrientationJsTest_001 - * @tc.name: OrientationJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("OrientationJsTest_001", 0, async function (done) { - console.info('----------------------OrientationJsTest_001---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.ORIENTATION, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - try { - sensor.on(sensor.SensorId.ORIENTATION, callback); - setTimeout(() => { - sensor.off(sensor.SensorId.ORIENTATION); - done(); - }, 500); - } catch (error) { - console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - }); - } catch (error) { - console.info('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) - - /* - * @tc.number: OrientationJsTest_002 - * @tc.name: OrientationJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("OrientationJsTest_002", 0, async function (done) { - console.info('----------------------OrientationJsTest_002---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.ORIENTATION, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - try { - sensor.on(sensor.SensorId.ORIENTATION, callback, {'interval': 100000000}); - setTimeout(() => { - sensor.off(sensor.SensorId.ORIENTATION); - done(); - }, 500); - } catch (error) { - console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - }); - } catch (error) { - console.info('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) - - /* - * @tc.number: OrientationJsTest_003 - * @tc.name: OrientationJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("OrientationJsTest_003", 0, async function (done) { - console.info('----------------------OrientationJsTest_003---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.ORIENTATION, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - function onSensorCallback(data) { - console.error('OrientationJsTest_003 callback in'); - expect(true).assertTrue(); - done(); - } - try { - sensor.on(sensor.SensorId.ORIENTATION, onSensorCallback, {'interval': 100000000}, 5); - setTimeout(() => { - sensor.off(sensor.SensorId.ORIENTATION); - done(); - }, 500); - } catch (error) { - console.info('On fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - }); - } catch (error) { - console.info('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) - - /* - * @tc.number: OrientationJsTest_004 - * @tc.name: OrientationJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("OrientationJsTest_004", 0, async function (done) { - console.info('----------------------OrientationJsTest_004---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.ORIENTATION, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - try { - sensor.on(sensor.SensorId.ORIENTATION, callback, {'interval': -100000000}); - sensor.off(sensor.SensorId.ORIENTATION); - done(); - } catch (error) { - console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SERVICE_EXCEPTION_CODE); - expect(error.message).assertEqual(CommonConstants.SERVICE_EXCEPTION_MSG); - done(); - } - }); - } catch (error) { - console.info('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) - - /* - * @tc.number: OrientationJsTest_005 - * @tc.name: OrientationJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("OrientationJsTest_005", 0, async function (done) { - console.info('----------------------OrientationJsTest_005---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.ORIENTATION, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - try { - sensor.once(sensor.SensorId.ORIENTATION, callback); - setTimeout(() => { - expect(true).assertTrue(); - done(); - }, 500); - } catch (error) { - console.error('Once fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - }); - } catch (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) - - /* - * @tc.number: OrientationJsTest_006 - * @tc.name: OrientationJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("OrientationJsTest_006", 0, async function (done) { - console.info('----------------------OrientationJsTest_006---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.ORIENTATION, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - try{ - sensor.once(sensor.SensorId.ORIENTATION, callback, 5); - setTimeout(() => { - expect(true).assertTrue(); - done(); - }, 500); - } catch (error) { - console.error('Once fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - }); - } catch (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) - - /* - * @tc.number: OrientationJsTest_007 - * @tc.name: OrientationJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("OrientationJsTest_007", 0, async function (done) { - console.info('----------------------OrientationJsTest_007---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.ORIENTATION, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - try{ - sensor.once(sensor.SensorId.ORIENTATION, 5); - } catch (error) { - console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.PARAMETER_ERROR_CODE); - done(); - } - }); - } catch (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) - - /* - * @tc.number: OrientationJsTest_008 - * @tc.name: OrientationJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("OrientationJsTest_008", 0, async function (done) { - console.info('----------------------OrientationJsTest_008---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.ORIENTATION, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - try { - sensor.off(-1, callback); - } catch (error) { - expect(error.code).assertEqual(CommonConstants.PARAMETER_ERROR_CODE); - done(); - } - }); - } catch (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) - - /* - * @tc.number: OrientationJsTest_009 - * @tc.name: OrientationJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("OrientationJsTest_009", 0, async function (done) { - console.info('----------------------OrientationJsTest_009---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.ORIENTATION, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - try { - sensor.on(sensor.SensorId.ORIENTATION, callback); - sensor.on(sensor.SensorId.ORIENTATION, callback2); - setTimeout(() => { - sensor.off(sensor.SensorId.ORIENTATION); - done(); - }, 1000); - } catch (error) { - console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - }); - } catch (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) - - /* - * @tc.number: OrientationJsTest_010 - * @tc.name: OrientationJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("OrientationJsTest_010", 0, async function (done) { - console.info('----------------------OrientationJsTest_010---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.ORIENTATION, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - try { - sensor.on(sensor.SensorId.ORIENTATION, callback); - sensor.on(sensor.SensorId.ORIENTATION, callback2); - setTimeout(() => { - sensor.off(sensor.SensorId.ORIENTATION, callback); - }, 500); - setTimeout(() => { - sensor.off(sensor.SensorId.ORIENTATION, callback2); - done(); - }, 1000); - } catch (error) { - console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - }); - } catch (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) - - /* - * @tc.number: OrientationJsTest_011 - * @tc.name: OrientationJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("OrientationJsTest_011", 0, async function (done) { - console.info('----------------------OrientationJsTest_011---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.ORIENTATION, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - try { - sensor.on(sensor.SensorId.ORIENTATION, callback, {'interval': 100000000}); - sensor.once(sensor.SensorId.ORIENTATION, callback2); - setTimeout(() => { - sensor.off(sensor.SensorId.ORIENTATION); - done(); - }, 1000); - } catch (error) { - console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - }); - } catch (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) - - /* - * @tc.number: OrientationJsTest_012 - * @tc.name: OrientationJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("OrientationJsTest_012", 0, async function (done) { - console.info('----------------------OrientationJsTest_012---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.ORIENTATION, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - try { - sensor.on(sensor.SensorId.ORIENTATION, callback, {'interval': 100000000}); - sensor.on(sensor.SensorId.ORIENTATION, callback2, {'interval': 100000000}); - setTimeout(() => { - sensor.off(sensor.SensorId.ORIENTATION, callback); - }, 500); - setTimeout(() => { - sensor.off(sensor.SensorId.ORIENTATION, callback2); - done(); - }, 1000); - } catch (error) { - console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - }); - } catch (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) - - /* - * @tc.number: OrientationJsTest_013 - * @tc.name: OrientationJsTest - * @tc.desc: verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - * @tc.size: MediumTest - * @tc.type: Function - * @tc.level: Level 1 - */ - it("OrientationJsTest_013", 0, async function (done) { - console.info('----------------------OrientationJsTest_013---------------------------'); - try { - sensor.getSingleSensor(sensor.SensorId.ORIENTATION, (error, data) => { - if (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - try { - sensor.on(sensor.SensorId.ORIENTATION, callback, {'interval': 100000000}); - sensor.on(sensor.SensorId.ORIENTATION, callback2, {'interval': 100000000}); - setTimeout(() => { - sensor.off(sensor.SensorId.ORIENTATION); - done(); - }, 1000); - } catch (error) { - console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(false).assertTrue(); - done(); - } - }); - } catch (error) { - console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message); - expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE); - expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG); - done(); - } - }) -}) diff --git a/test/unittest/interfaces/js/sensor/SensorJsSync.test.js b/test/unittest/interfaces/js/sensor/SensorJsSync.test.js index 74a7cd4aaffab760c3d79f1df6272dbb46758826..038e900f47b11f61ea47997c64d1842dd4ad0c7a 100644 --- a/test/unittest/interfaces/js/sensor/SensorJsSync.test.js +++ b/test/unittest/interfaces/js/sensor/SensorJsSync.test.js @@ -125,26 +125,27 @@ describe("SensorSyncTest", function () { try { let ret = sensor.getSingleSensorByDeviceSync(sensor.SensorId.ACCELEROMETER); console.info('getSingleSensorByDeviceSync: ' + JSON.stringify(ret)); - if (Array.isArray(ret) && ret.length > 0) { - const sensorInfo = ret[0]; - const callback = (data) => { - console.info('Accelerometer data received: ' + JSON.stringify(data)); - }; - const sensorInfoParam = { - deviceId: sensorInfo.deviceId, - sensorIndex: sensorInfo.sensorIndex - }; - const options = { - interval: 10000000, - sensorInfoParam: sensorInfoParam - }; - sensor.on(sensorInfo.sensorId, callback, options); - sensor.off(sensorInfo.sensorId, sensorInfoParam, callback); - expect(true).assertTrue(); - } else { - console.info('No local accelerometer sensor found. Test case will return true.'); + if (!Array.isArray(ret) || ret.length === 0) { + console.info('No local sensors found. Test case will return true.'); expect(true).assertTrue(); + done(); + return; } + const sensorInfo = ret[0]; + const callback = (data) => { + console.info('Accelerometer data received: ' + JSON.stringify(data)); + }; + const sensorInfoParam = { + deviceId: sensorInfo.deviceId, + sensorIndex: sensorInfo.sensorIndex + }; + const options = { + interval: 10000000, + sensorInfoParam: sensorInfoParam + }; + sensor.on(sensorInfo.sensorId, callback, options); + sensor.off(sensorInfo.sensorId, sensorInfoParam, callback); + expect(true).assertTrue(); done(); } catch (err) { console.error('getSingleSensorByDeviceSync err: ' + JSON.stringify(err)); @@ -168,26 +169,27 @@ describe("SensorSyncTest", function () { try { let ret = sensor.getSingleSensorByDeviceSync(sensor.SensorId.ACCELEROMETER, validDeviceId); console.info(`getSingleSensorByDeviceSync deviceId=${validDeviceId}: ` + JSON.stringify(ret)); - if (Array.isArray(ret) && ret.length > 0) { - const sensorInfo = ret[0]; - const callback = (data) => { - console.info('Accelerometer data received: ' + JSON.stringify(data)); - }; - const sensorInfoParam = { - deviceId: sensorInfo.deviceId, - sensorIndex: sensorInfo.sensorIndex - }; - const options = { - interval: 10000000, - sensorInfoParam: sensorInfoParam - }; - sensor.on(sensorInfo.sensorId, callback, options); - sensor.off(sensorInfo.sensorId, sensorInfoParam, callback); - expect(true).assertTrue(); - } else { - console.info('No local accelerometer sensor found with the given deviceId. Test case will return true.'); + if (!Array.isArray(ret) || ret.length === 0) { + console.info('No local sensors found. Test case will return true.'); expect(true).assertTrue(); + done(); + return; } + const sensorInfo = ret[0]; + const callback = (data) => { + console.info('Accelerometer data received: ' + JSON.stringify(data)); + }; + const sensorInfoParam = { + deviceId: sensorInfo.deviceId, + sensorIndex: sensorInfo.sensorIndex + }; + const options = { + interval: 10000000, + sensorInfoParam: sensorInfoParam + }; + sensor.on(sensorInfo.sensorId, callback, options); + sensor.off(sensorInfo.sensorId, sensorInfoParam, callback); + expect(true).assertTrue(); done(); } catch (err) { console.error(`getSingleSensorByDeviceSync deviceId=${validDeviceId} err: ` + JSON.stringify(err)); @@ -258,26 +260,27 @@ describe("SensorSyncTest", function () { try { let ret = sensor.getSensorListByDeviceSync(); console.info('getSensorListByDeviceSync default device: ' + JSON.stringify(ret)); - if (Array.isArray(ret) && ret.length > 0) { - const sensorInfo = ret[0]; - const callback = (data) => { - console.info('Sensor data received: ' + JSON.stringify(data)); - }; - const sensorInfoParam = { - deviceId: sensorInfo.deviceId, - sensorIndex: sensorInfo.sensorIndex - }; - const options = { - interval: 10000000, - sensorInfoParam: sensorInfoParam - }; - sensor.on(sensorInfo.sensorId, callback, options); - sensor.off(sensorInfo.sensorId, sensorInfoParam, callback); - expect(true).assertTrue(); - } else { + if (!Array.isArray(ret) || ret.length === 0) { console.info('No local sensors found. Test case will return true.'); expect(true).assertTrue(); + done(); + return; } + const sensorInfo = ret[0]; + const callback = (data) => { + console.info('Sensor data received: ' + JSON.stringify(data)); + }; + const sensorInfoParam = { + deviceId: sensorInfo.deviceId, + sensorIndex: sensorInfo.sensorIndex + }; + const options = { + interval: 10000000, + sensorInfoParam: sensorInfoParam + }; + sensor.on(sensorInfo.sensorId, callback, options); + sensor.off(sensorInfo.sensorId, sensorInfoParam, callback); + expect(true).assertTrue(); done(); } catch (err) { console.error('getSensorListByDeviceSync default device err: ' + JSON.stringify(err)); @@ -301,26 +304,27 @@ describe("SensorSyncTest", function () { try { let ret = sensor.getSensorListByDeviceSync(validDeviceId); console.info(`getSensorListByDeviceSync deviceId=${validDeviceId}: ` + JSON.stringify(ret)); - if (Array.isArray(ret) && ret.length > 0) { - const sensorInfo = ret[0]; - const callback = (data) => { - console.info(`Sensor ${sensorInfo.type} data received: ` + JSON.stringify(data)); - }; - const sensorInfoParam = { - deviceId: sensorInfo.deviceId, - sensorIndex: sensorInfo.sensorIndex - }; - const options = { - interval: 10000000, - sensorInfoParam: sensorInfoParam - }; - sensor.on(sensorInfo.sensorId, callback, options); - sensor.off(sensorInfo.sensorId, sensorInfoParam, callback); - expect(true).assertTrue(); - } else { - console.info(`No local sensors found with deviceId=${validDeviceId}. Test case will return true.`); + if (!Array.isArray(ret) || ret.length === 0) { + console.info('No local sensors found. Test case will return true.'); expect(true).assertTrue(); + done(); + return; } + const sensorInfo = ret[0]; + const callback = (data) => { + console.info(`Sensor ${sensorInfo.type} data received: ` + JSON.stringify(data)); + }; + const sensorInfoParam = { + deviceId: sensorInfo.deviceId, + sensorIndex: sensorInfo.sensorIndex + }; + const options = { + interval: 10000000, + sensorInfoParam: sensorInfoParam + }; + sensor.on(sensorInfo.sensorId, callback, options); + sensor.off(sensorInfo.sensorId, sensorInfoParam, callback); + expect(true).assertTrue(); done(); } catch (err) { console.error(`getSensorListByDeviceSync deviceId=${validDeviceId} err: ` + JSON.stringify(err)); diff --git a/test/unittest/interfaces/js/sensor/common/CommonConstants.js b/test/unittest/interfaces/js/sensor/common/CommonConstants.js index c1aba095e52e08060eb0fcbef1a3f8c22cb429b7..abc4a087105ae189b34e200bfd7427cd537b8806 100755 --- a/test/unittest/interfaces/js/sensor/common/CommonConstants.js +++ b/test/unittest/interfaces/js/sensor/common/CommonConstants.js @@ -43,15 +43,35 @@ export default class CommonConstants { static SERVICE_EXCEPTION_CODE = 14500101; /** - * Exception code of sensorId no support + * Exception code of sensor not supported */ - static SENSOR_NO_SUPPORT_CODE = 14500102 + static SENSOR_NO_SUPPORT_CODE = 14500102; /** - * eps + * Eps */ static EPS = 0.01; + /** + * Delay time + */ + static DELAY_TIME = 1000; + + /** + * Sensor interval + */ + static SENSOR_INTERVAL = 100000000; + + /** + * Invalid sensor interval + */ + static INVALID_SENSOR_INTERVAL = -1; + + /** + * Invalid sensor id + */ + static INVALID_SENSOR_ID = -1; + /** * token id */ diff --git a/test/unittest/interfaces/js/sensor/config.json b/test/unittest/interfaces/js/sensor/config.json index aabb3f4b8a5544b29581e64aedf217387cef1dfd..675fc7e8d6bab860cd9cd9a2635f6b160b8ec796 100644 --- a/test/unittest/interfaces/js/sensor/config.json +++ b/test/unittest/interfaces/js/sensor/config.json @@ -57,7 +57,8 @@ "name": ".MyApplication", "deviceType": [ "default", - "tablet" + "tablet", + "2in1" ], "distro": { "deliveryWithInstall": true, diff --git a/utils/common/include/permission_util.h b/utils/common/include/permission_util.h index 49223da52f8b2543dfcf645b173386b35998017d..b073d147ba21ac307952e5d82c6a8f868cfbbdc3 100644 --- a/utils/common/include/permission_util.h +++ b/utils/common/include/permission_util.h @@ -16,6 +16,9 @@ #ifndef PERMISSION_UTIL_H #define PERMISSION_UTIL_H +#include +#include + #include "access_token.h" #include "singleton.h" diff --git a/utils/common/include/sensor_channel_info.h b/utils/common/include/sensor_channel_info.h index 26a715d5c1273f33b2bd8bcb30b671703454f123..70cc84ae6dcd97fcc866ad4735bd790eb76a31ed 100644 --- a/utils/common/include/sensor_channel_info.h +++ b/utils/common/include/sensor_channel_info.h @@ -16,7 +16,9 @@ #ifndef SENSOR_CHANNEL_INFO_H #define SENSOR_CHANNEL_INFO_H +#include #include +#include namespace OHOS { namespace Sensors { diff --git a/utils/common/include/sensor_data_event.h b/utils/common/include/sensor_data_event.h index 7eea424f070ee0fc20770ac68feed6fecd2e5e96..6b0eafafef10600ad51945d7cccb12634c980f30 100755 --- a/utils/common/include/sensor_data_event.h +++ b/utils/common/include/sensor_data_event.h @@ -59,14 +59,14 @@ struct ExtraSensorInfo { }; struct SensorPlugData { - int32_t deviceId; /**< Device ID */ - int32_t sensorTypeId; /**< Sensor type ID */ - int32_t sensorId; /**< Sensor ID */ - int32_t location; /**< Is the device a local device or an external device */ - std::string deviceName; /**< Device name */ - int32_t status; /**< Device on or out status */ - int32_t reserved; /**< Reserved */ - int64_t timestamp; /**< Time when sensor plug data was reported */ + int32_t deviceId = -1; /**< Device ID */ + int32_t sensorTypeId = -1; /**< Sensor type ID */ + int32_t sensorId = -1; /**< Sensor ID */ + int32_t location = -1; /**< Is the device a local device or an external device */ + std::string deviceName = ""; /**< Device name */ + int32_t status = -1; /**< Device on or out status */ + int32_t reserved = -1; /**< Reserved */ + int64_t timestamp = -1; /**< Time when sensor plug data was reported */ }; } // namespace Sensors } // namespace OHOS diff --git a/utils/common/include/sensor_xcollie.h b/utils/common/include/sensor_xcollie.h index 34f540559e3ce132ea171b36079a00eb1c0e689c..c0a4dd7bf4a07618d7a759ee06d313364da36d35 100644 --- a/utils/common/include/sensor_xcollie.h +++ b/utils/common/include/sensor_xcollie.h @@ -24,16 +24,17 @@ namespace OHOS { namespace Sensors { const unsigned int XCOLLIE_TIMEOUT_15S = 15; +const unsigned int XCOLLIE_TIMEOUT_10S = 10; const unsigned int XCOLLIE_TIMEOUT_5S = 5; class SensorXcollie { public: - SensorXcollie(const std::string& tag, unsigned int timeoutSeconds = 10, + SensorXcollie(const std::string& tag, unsigned int timeoutSeconds = XCOLLIE_TIMEOUT_10S, std::function func = nullptr, void *arg = nullptr, unsigned int flag = HiviewDFX::XCOLLIE_FLAG_LOG); ~SensorXcollie(); private: - int id_; + std::atomic_int32_t id_; std::string tag_; }; } // namespace Sensors diff --git a/utils/common/src/motion_plugin.cpp b/utils/common/src/motion_plugin.cpp index 4c0806855ca93eec1d367789f9cbcc156db89caf..a440ab272f9bcc822388d7b6c7fb641ccfb0b7d7 100644 --- a/utils/common/src/motion_plugin.cpp +++ b/utils/common/src/motion_plugin.cpp @@ -59,7 +59,6 @@ __attribute__((no_sanitize("cfi"))) void MotionTransformIfRequired(const std::st uint32_t state, SensorData* sensorData) { if (g_handle == nullptr) { - SEN_HILOGD("g_handle is nullptr"); return; } MotionTransformIfRequiredPtr func = (MotionTransformIfRequiredPtr)(dlsym(g_handle, "TransformIfRequired")); diff --git a/utils/common/src/permission_util.cpp b/utils/common/src/permission_util.cpp index c5f58f2274777064b81e3507ad236372de178ce6..a135a6d564435f2efa6d975446ad415053e37117 100644 --- a/utils/common/src/permission_util.cpp +++ b/utils/common/src/permission_util.cpp @@ -40,11 +40,10 @@ std::unordered_map PermissionUtil::sensorPermissions_ = { int32_t PermissionUtil::CheckSensorPermission(AccessTokenID callerToken, int32_t sensorTypeId) { - auto iter = sensorPermissions_.find(sensorTypeId); - if (iter == sensorPermissions_.end()) { + if (sensorPermissions_.find(sensorTypeId) == sensorPermissions_.end()) { return PERMISSION_GRANTED; } - std::string permissionName = iter->second; + std::string permissionName = sensorPermissions_[sensorTypeId]; int32_t ret = AccessTokenKit::VerifyAccessToken(callerToken, permissionName); if ((permissionName == ACTIVITY_MOTION_PERMISSION) || (permissionName == READ_HEALTH_DATA_PERMISSION)) { diff --git a/utils/ipc/src/stream_buffer.cpp b/utils/ipc/src/stream_buffer.cpp index 0b57bf85a3e5a80a0e15f45b6ebae62e42d6e626..5b5135ecfd39fa1e0252193bbfcb879d20ba8f0b 100644 --- a/utils/ipc/src/stream_buffer.cpp +++ b/utils/ipc/src/stream_buffer.cpp @@ -24,9 +24,7 @@ StreamBuffer::StreamBuffer(const StreamBuffer &buf) StreamBuffer &StreamBuffer::operator=(const StreamBuffer &other) { - if (this != &other) { - Clone(other); - } + Clone(other); return *this; } diff --git a/vibration_convert/core/algorithm/conversion/include/fft.h b/vibration_convert/core/algorithm/conversion/include/fft.h index a10afe7aba30a56ab1bcaabc28bad5059737d974..61da0537a017ca3ff245bd7193af430d83683deb 100644 --- a/vibration_convert/core/algorithm/conversion/include/fft.h +++ b/vibration_convert/core/algorithm/conversion/include/fft.h @@ -103,8 +103,6 @@ private: */ int32_t AlgRealFFT(FftParaAndResult ¶Res); int32_t AlgFFT(bool inverseTransform, FftParaAndResult ¶Res); - void Normalize(FftParaAndResult ¶Res); - int32_t PreprocessData(uint32_t numSamples, FftParaAndResult ¶Res); int32_t AlgInitFFT(); private: diff --git a/vibration_convert/core/algorithm/conversion/src/conversion_fft.cpp b/vibration_convert/core/algorithm/conversion/src/conversion_fft.cpp index e2e135bed8a4b476fb30e4d6fb3fe88537572f03..96bba820b32816fb9d1a6640e8578b0b637575d2 100644 --- a/vibration_convert/core/algorithm/conversion/src/conversion_fft.cpp +++ b/vibration_convert/core/algorithm/conversion/src/conversion_fft.cpp @@ -96,7 +96,7 @@ int32_t ConversionFFT::Process(const std::vector &values, int32_t &frame frameCount = 0; bool isFrameFull = false; size_t valuesSize = values.size(); - for (size_t j = 0; j < valuesSize; ++j) { + for (size_t j = 0; j < valuesSize; j++) { // add value to buffer at current pos if (pos_ < static_cast(fftResult_.buffer.size())) { fftResult_.buffer[pos_++] = static_cast(values[j]); @@ -115,7 +115,7 @@ int32_t ConversionFFT::Process(const std::vector &values, int32_t &frame // reset pos to start of hop pos_ = para_.windowSize - para_.hopSize; /** shift buffer back by one hop size. */ - for (int32_t i = 0; i < pos_; ++i) { + for (int32_t i = 0; i < pos_; i++) { fftResult_.buffer[i] = fftResult_.buffer[i + para_.hopSize]; } isFftCalcFinish_ = true; @@ -142,7 +142,7 @@ float ConversionFFT::GetSpectralFlatness() const } float geometricMean = 0.0F; float arithmaticMean = 0.0F; - for (int32_t i = 0; i < bins_; ++i) { + for (int32_t i = 0; i < bins_; i++) { if (fftResult_.magnitudes[i] != 0) { geometricMean += logf(fftResult_.magnitudes[i]); } @@ -158,7 +158,7 @@ float ConversionFFT::GetSpectralCentroid() const { float x = 0.0F; float y = 0.0F; - for (int32_t i = 0; i < bins_; ++i) { + for (int32_t i = 0; i < bins_; i++) { x += fabs(fftResult_.magnitudes[i]) * i; y += fabs(fftResult_.magnitudes[i]); } @@ -199,15 +199,15 @@ float ConversionIFFT::Process(const std::vector &mags, const std::vector< } // add to output // shift back by one hop - for (int32_t i = 0; i < (para_.fftSize - para_.hopSize); ++i) { + for (int32_t i = 0; i < (para_.fftSize - para_.hopSize); i++) { fftResult_.buffer[i] = fftResult_.buffer[i + para_.hopSize]; } // clear the end chunk - for (int32_t i = 0; i < para_.hopSize; ++i) { + for (int32_t i = 0; i < para_.hopSize; i++) { fftResult_.buffer[i + para_.fftSize - para_.hopSize] = 0.0F; } // merge new output - for (int32_t i = 0; i < para_.fftSize; ++i) { + for (int32_t i = 0; i < para_.fftSize; i++) { fftResult_.buffer[i] += ifftOut_[i]; } } @@ -238,14 +238,17 @@ int32_t ConversionOctave::Init(float samplingRate, int32_t nBandsInTheFFT, int32 // this isn't currently configurable (used once here then no effect), but here's some reasoning firstOctaveFrequency_ = 55.0F; // for each spectrum[] bin, calculate the mapping into the appropriate average[] bin. - spe2avg_ = MakeSharedArray(static_cast(nSpectrum_)); + auto spe2avg = new (std::nothrow) int32_t[nSpectrum_]; + CHKPR(spe2avg, Sensors::ERROR); + std::shared_ptr spe2avgShared(spe2avg, std::default_delete()); + spe2avg_ = std::move(spe2avgShared); int32_t avgIdx = 0; float averageFreq = firstOctaveFrequency_; // the "top" of the first averaging bin // we're looking for the "top" of the first spectrum bin, and i'm just sort of // guessing that this is where it is (or possibly spectrumFrequencySpan/2?) // ... either way it's probably close enough for these purposes float spectrumFreq = spectrumFrequencySpan_; - for (int32_t speIdx = 0; speIdx < nSpectrum_; ++speIdx) { + for (int32_t speIdx = 0; speIdx < nSpectrum_; speIdx++) { while (spectrumFreq > averageFreq) { ++avgIdx; averageFreq *= averageFrequencyIncrement_; @@ -254,9 +257,19 @@ int32_t ConversionOctave::Init(float samplingRate, int32_t nBandsInTheFFT, int32 spectrumFreq += spectrumFrequencySpan_; } nAverages_ = avgIdx; - averages_ = MakeSharedArray(static_cast(nAverages_)); - peaks_ = MakeSharedArray(static_cast(nAverages_)); - peakHoldTimes_ = MakeSharedArray(static_cast(nAverages_)); + auto averages = new (std::nothrow) float[nAverages_]; + CHKPR(averages, Sensors::ERROR); + std::shared_ptr averagesShared(averages, std::default_delete()); + averages_ = std::move(averagesShared); + auto peaks = new (std::nothrow) float[nAverages_]; + CHKPR(peaks, Sensors::ERROR); + std::shared_ptr peaksShared(peaks, std::default_delete()); + peaks_ = std::move(peaksShared); + auto peakHoldTimes = new (std::nothrow) int32_t[nAverages_]; + CHKPR(peakHoldTimes, Sensors::ERROR); + std::shared_ptr peakHoldTimesShared(peakHoldTimes, std::default_delete()); + peakHoldTimes_ = std::move(peakHoldTimesShared); + peakHoldTime_ = 0; peakDecayRate_ = 0.9F; linearEQIntercept_ = 1.0F; @@ -277,12 +290,12 @@ int32_t ConversionOctave::Calculate(const std::vector &fftData) int32_t lastAvgIdx = 0; // tracks when we've crossed into a new averaging bin, so store current average float sum = 0.0F; // running total of spectrum data int32_t count = 0; // count of spectrums accumulated (for averaging) - for (int32_t speIdx = 0; speIdx < nSpectrum_; ++speIdx) { + for (int32_t speIdx = 0; speIdx < nSpectrum_; speIdx++) { ++count; sum += (fftData[speIdx] * (linearEQIntercept_ + speIdx * linearEQSlope_)); int32_t avgIdx = *(spe2avg_.get() + speIdx); if (avgIdx != lastAvgIdx) { - for (int32_t j = lastAvgIdx; j < avgIdx; ++j) { + for (int32_t j = lastAvgIdx; j < avgIdx; j++) { *(averages_.get() + j) = sum / static_cast(count); } count = 0; @@ -295,7 +308,7 @@ int32_t ConversionOctave::Calculate(const std::vector &fftData) *(averages_.get() + lastAvgIdx) = sum / count; } // update the peaks separately - for (int32_t i = 0; i < nAverages_; ++i) { + for (int32_t i = 0; i < nAverages_; i++) { if (IsGreatOrEqual(*(averages_.get() + i), *(peaks_.get() + i))) { // save new peak level, also reset the hold timer *(peaks_.get() + i) = *(averages_.get() + i); diff --git a/vibration_convert/core/algorithm/conversion/src/conversion_mfcc.cpp b/vibration_convert/core/algorithm/conversion/src/conversion_mfcc.cpp index 126329b81c9a86b2306334886037535325c6f29d..f75da4b02e3d91a6d2eee75ea76c98ce14454dc7 100644 --- a/vibration_convert/core/algorithm/conversion/src/conversion_mfcc.cpp +++ b/vibration_convert/core/algorithm/conversion/src/conversion_mfcc.cpp @@ -101,9 +101,9 @@ int32_t ConversionMfcc::HandleDiscreteCosineTransform() SEN_HILOGE("numCoeffs_ should not be 0"); return Sensors::ERROR; } - for (uint32_t i = 0; i < numCoeffs_; i++) { + for (uint32_t i = 0; i < numCoeffs_; ++i) { coeffs_[i] = 0; - for (uint32_t j = 0; j < numFilters_; j++) { + for (uint32_t j = 0; j < numFilters_; ++j) { uint32_t idx = i + (j * numCoeffs_); coeffs_[i] += (dctMatrix_[idx] * melBands_[j]); } @@ -181,7 +181,7 @@ std::vector ConversionMfcc::GetMelFilterBank() const { std::vector melFilters; uint32_t num = numFilters_ * numBins_; - for (uint32_t i = 0; i < num; i++) { + for (uint32_t i = 0; i < num; ++i) { melFilters.emplace_back(melFilters_[i]); } return melFilters; @@ -197,8 +197,8 @@ int32_t ConversionMfcc::CreateDCTCoeffs() double w1 = 1.0 / (sqrt(numFilters_)); double w2 = sqrt(2.0 / numFilters_); // generate dct matrix - for (uint32_t i = 0; i < numCoeffs_; i++) { - for (uint32_t j = 0; j < numFilters_; j++) { + for (uint32_t i = 0; i < numCoeffs_; ++i) { + for (uint32_t j = 0; j < numFilters_; ++j) { uint32_t idx = i + (j * numCoeffs_); if (i == 0) { dctMatrix_[idx] = w1 * cos(k * (i + 1) * (j + F_HALF)); @@ -223,27 +223,26 @@ int32_t ConversionMfcc::FiltersMel(int32_t nFft, MfccInputPara para, fMax = sr / 2.0; } size_t nMels = static_cast(para.nMels); - double fMin = para.minFreq; frmCount = nFft / 2; std::vector basis(nMels * frmCount, 0.0); // generate mel frequencies. + double fMin = para.minFreq; double minMel = OHOS::Sensors::ConvertHtkMel(fMin); double maxMel = OHOS::Sensors::ConvertHtkMel(fMax); std::vector filterHzPos(nMels + 2); double stepMel = (maxMel - minMel) / (nMels + 1); double stepHz = static_cast(sr) / nFft; - double nextMel = minMel; - for (size_t i = 0; i < (nMels + 2); i++) { + for (size_t i = 0; i < (nMels + 2); ++i) { filterHzPos[i] = OHOS::Sensors::ConvertHtkHz(nextMel); nextMel += stepMel; } std::vector binFs(frmCount); - for (int32_t j = 0; j < frmCount; j++) { + for (int32_t j = 0; j < frmCount; ++j) { binFs[j] = stepHz * j; } int32_t index = 0; - for (size_t i = 2; i < filterHzPos.size(); i++) { + for (size_t i = 2; i < filterHzPos.size(); ++i) { double prevFreq = filterHzPos[i - 2]; double thisFreq = filterHzPos[i - 1]; double nextFreq = filterHzPos[i]; @@ -251,7 +250,7 @@ int32_t ConversionMfcc::FiltersMel(int32_t nFft, MfccInputPara para, SEN_HILOGE("The divisor cannot be 0"); return Sensors::ERROR; } - for (int32_t j = 0; j < frmCount; j++) { + for (int32_t j = 0; j < frmCount; ++j) { double binFreq = binFs[j]; double lower = (binFreq - prevFreq) / (thisFreq - prevFreq); double upper = (nextFreq - binFreq) / (nextFreq - thisFreq); @@ -261,11 +260,7 @@ int32_t ConversionMfcc::FiltersMel(int32_t nFft, MfccInputPara para, } } melBasis = OHOS::Sensors::TransposeMatrix(nMels, basis); - if (melBasis.empty()) { - SEN_HILOGE("melBasis is empty"); - return Sensors::ERROR; - } - return Sensors::SUCCESS; + return melBasis.empty() ? Sensors::ERROR : Sensors::SUCCESS; } } // namespace Sensors } // namespace OHOS \ No newline at end of file diff --git a/vibration_convert/core/algorithm/conversion/src/fft.cpp b/vibration_convert/core/algorithm/conversion/src/fft.cpp deleted file mode 100644 index 5d6077c81238a1f76b89dc9a626d27b7d721efda..0000000000000000000000000000000000000000 --- a/vibration_convert/core/algorithm/conversion/src/fft.cpp +++ /dev/null @@ -1,450 +0,0 @@ -/* - * 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 - * - * 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 "fft.h" - -#include -#include -#include -#include -#include - -#include "sensor_log.h" -#include "sensors_errors.h" - -#undef LOG_TAG -#define LOG_TAG "Fft" - -namespace OHOS { -namespace Sensors { -namespace { -constexpr uint32_t MAX_FAST_BITS { 16 }; -constexpr int32_t NUM_SAMPLES_MIN { 2 }; -constexpr double HAMMING_WND_UP { 0.54 }; -constexpr double HAMMING_WND_DOWN { 0.46 }; -constexpr float VOLUME_MIN { 0.000001 }; -constexpr double AMP_TO_DB_COEF { 20.0 }; -constexpr bool TRANSFORM_INVERSE_FLAG { true }; -} // namespace - -Fft::~Fft() -{ - if (fftBitTable_ == nullptr) { - return; - } - for (uint32_t i = 0; i < MAX_FAST_BITS; ++i) { - if (fftBitTable_[i] != nullptr) { - free(fftBitTable_[i]); - fftBitTable_[i] = nullptr; - } - } - free(fftBitTable_); - fftBitTable_ = nullptr; -} - -inline uint32_t Fft::FastReverseBits(uint32_t pos, uint32_t numBits) -{ - if (numBits <= MAX_FAST_BITS && numBits >= 1) { - return fftBitTable_[numBits - 1][pos]; - } - return ReverseBits(pos, numBits); -} - -int32_t Fft::AlgInitFFT() -{ - // use malloc for 16 byte alignment - fftBitTable_ = (uint32_t **)malloc(MAX_FAST_BITS * sizeof(uint32_t *)); - CHKPR(fftBitTable_, Sensors::ERROR); - uint32_t length = 2; - for (uint32_t j = 1; j <= MAX_FAST_BITS; ++j) { - fftBitTable_[j - 1] = (uint32_t *)malloc(length * sizeof(uint32_t)); - CHKPR(fftBitTable_[j - 1], Sensors::ERROR); - for (uint32_t i = 0; i < length; ++i) { - fftBitTable_[j - 1][i] = ReverseBits(i, j); - } - length <<= 1; - } - return Sensors::SUCCESS; -} - -/* - * Complex Fast Fourier Transform - */ -int32_t Fft::AlgFFT(bool inverseTransform, FftParaAndResult ¶Res) -{ - uint32_t numSamples = static_cast(paraRes.numSamples); - if (!IsPowerOfTwo(numSamples)) { - SEN_HILOGE("The parameter is invalid,numSamples:%{public}d", numSamples); - return Sensors::PARAMETER_ERROR; - } - if (PreprocessData(numSamples, paraRes) != Sensors::SUCCESS) { - SEN_HILOGE("PreprocessData failed"); - return Sensors::ERROR; - } - // Do the FFT itself... - int32_t blockEnd = 1; - double angleNumerator = inverseTransform ? -(2 * M_PI) : (2 * M_PI); - for (int32_t blockSize = 2; blockSize <= paraRes.numSamples; blockSize <<= 1) { - double deltaAngle = angleNumerator / static_cast(blockSize); - float twoSinMagnitude = sin(-2 * deltaAngle); - float oneSinMagnitude = sin(-deltaAngle); - float twoCosMagnitude = cos(-2 * deltaAngle); - float oneCosMagnitude = cos(-deltaAngle); - float w = 2 * oneCosMagnitude; - for (int32_t i = 0; i < paraRes.numSamples; i += blockSize) { - float secondAmpReal = twoCosMagnitude; - float firstAmpReal = oneCosMagnitude; - float thirdAmpImaginary = twoSinMagnitude; - float secondAmpImaginary = oneSinMagnitude; - for (int32_t j = i, n = 0; n < blockEnd; ++j, ++n) { - float zerothAmpReal = w * firstAmpReal - secondAmpReal; - secondAmpReal = firstAmpReal; - firstAmpReal = zerothAmpReal; - float firstAmpImaginary = w * secondAmpImaginary - thirdAmpImaginary; - thirdAmpImaginary = secondAmpImaginary; - secondAmpImaginary = firstAmpImaginary; - int32_t k = j + blockEnd; - float real = zerothAmpReal * paraRes.realOut[k] - firstAmpImaginary * paraRes.imagOut[k]; - float imaginary = zerothAmpReal * paraRes.imagOut[k] + firstAmpImaginary * paraRes.realOut[k]; - paraRes.realOut[k] = paraRes.realOut[j] - real; - paraRes.imagOut[k] = paraRes.imagOut[j] - imaginary; - paraRes.realOut[j] += real; - paraRes.imagOut[j] += imaginary; - } - } - blockEnd = blockSize; - } - // Need to normalize if inverse transform - if (inverseTransform) { - Normalize(paraRes); - } - return Sensors::SUCCESS; -} - -void Fft::Normalize(FftParaAndResult ¶Res) -{ - float denom = static_cast(paraRes.numSamples); - for (int32_t i = 0; i < paraRes.numSamples; ++i) { - paraRes.realOut[i] /= denom; - paraRes.imagOut[i] /= denom; - } -} - -int32_t Fft::PreprocessData(uint32_t numSamples, FftParaAndResult ¶Res) -{ - if ((fftBitTable_ == nullptr) && (AlgInitFFT() != Sensors::SUCCESS)) { - SEN_HILOGE("fftBitTable_ failed to allocate memory"); - return Sensors::ERROR; - } - uint32_t numBits = ObtainNumberOfBits(numSamples); - if (numBits < 1) { - SEN_HILOGE("numBits is an invalid value"); - return Sensors::ERROR; - } - // Do simultaneous data copy and bit-reversal ordering into outputs... - for (uint32_t i = 0; i < numSamples; ++i) { - uint32_t j = FastReverseBits(i, numBits); - paraRes.realOut[j] = paraRes.realIn[i]; - paraRes.imagOut[j] = (paraRes.imagIn.empty()) ? 0.0F : paraRes.imagIn[i]; - } - return Sensors::SUCCESS; -} - -/* - * Real Fast Fourier Transform - * - * This function was based on the code in Numerical Recipes in C. - * In Num. Rec., the inner loop is based on a single 1-based array - * of interleaved real and imaginary numbers. Because we have two - * separate zero-based arrays, our indices are quite different. - * Here is the correspondence between Num. Rec. indices and our indices: - * - * i1 <-> real[i] - * i2 <-> imag[i] - * i3 <-> real[n/2-i] - * i4 <-> imag[n/2-i] - */ -int32_t Fft::AlgRealFFT(FftParaAndResult ¶Res) -{ - if (paraRes.numSamples == 0) { - SEN_HILOGE("The divisor should not be 0"); - return Sensors::PARAMETER_ERROR; - } - int32_t half = paraRes.numSamples / 2; - float theta = M_PI / half; - for (int32_t i = 0; i < half; ++i) { - para_.realIn[i] = paraRes.realIn[2 * i]; - para_.imagIn[i] = paraRes.realIn[2 * i + 1]; - } - AlgFFT(!TRANSFORM_INVERSE_FLAG, para_); - float wtemp = static_cast(sin(F_HALF * theta)); - float wpr = -2.0 * wtemp * wtemp; - float wpi = static_cast(sin(theta)); - float wr = 1.0 + wpr; - float wi = wpi; - float previousHalfReal = 0.0F; - for (int32_t i = 1; i < (half / 2); ++i) { - int32_t i3 = half - i; - previousHalfReal = F_HALF * (para_.realOut[i] + para_.realOut[i3]); - float previousHalfIm = F_HALF * (para_.imagOut[i] - para_.imagOut[i3]); - float lastHalfReal = F_HALF * (para_.imagOut[i] + para_.imagOut[i3]); - float lastHalfIm = -F_HALF * (para_.realOut[i] - para_.realOut[i3]); - para_.realOut[i] = previousHalfReal + wr * lastHalfReal - wi * lastHalfIm; - para_.imagOut[i] = previousHalfIm + wr * lastHalfIm + wi * lastHalfReal; - para_.realOut[i3] = previousHalfReal - wr * lastHalfReal + wi * lastHalfIm; - para_.imagOut[i3] = -previousHalfIm + wr * lastHalfIm + wi * lastHalfReal; - wtemp = wr; - wr = wtemp * wpr - wi * wpi + wr; - wi = wi * wpr + wtemp * wpi + wi; - } - previousHalfReal = para_.realOut[0]; - para_.realOut[0] = previousHalfReal + para_.imagOut[0]; - para_.imagOut[0] = previousHalfReal - para_.imagOut[0]; - for (int32_t i = 0; i < half; ++i) { - paraRes.realOut[i] = para_.realOut[i]; - paraRes.imagOut[i] = para_.imagOut[i]; - } - return Sensors::SUCCESS; -} - -/* - * AlgPowerSpectrum - * - * This function computes the same as AlgRealFFT, above, but - * adds the squares of the real and imaginary part of each - * coefficient, extracting the power and throwing away the - * phase. - * - * For speed, it does not call AlgRealFFT, but duplicates some - * of its code. - */ -int32_t Fft::AlgPowerSpectrum(int32_t numSamples, const std::vector &in, std::vector &out) -{ - if (numSamples == 0) { - SEN_HILOGE("The divisor should not be 0"); - return Sensors::PARAMETER_ERROR; - } - int32_t half = numSamples / 2; - float theta = M_PI / half; - for (int32_t i = 0; i < half; ++i) { - para_.realIn[i] = in[2 * i]; - para_.imagIn[i] = in[2 * i + 1]; - } - AlgFFT(!TRANSFORM_INVERSE_FLAG, para_); - float wtemp = static_cast(sin(F_HALF * theta)); - float wpr = -2.0 * wtemp * wtemp; - float wpi = static_cast(sin(theta)); - float wr = 1.0 + wpr; - float wi = wpi; - float previousHalfReal = 0.0F; - float rt = 0.0F; - float it = 0.0F; - for (int32_t i = 1; i < (half / 2); ++i) { - int32_t i3 = half - i; - previousHalfReal = F_HALF * (para_.realOut[i] + para_.realOut[i3]); - float previousHalfIm = F_HALF * (para_.imagOut[i] - para_.imagOut[i3]); - float lastHalfReal = F_HALF * (para_.imagOut[i] + para_.imagOut[i3]); - float lastHalfIm = -F_HALF * (para_.realOut[i] - para_.realOut[i3]); - rt = previousHalfReal + wr * lastHalfReal - wi * lastHalfIm; - it = previousHalfIm + wr * lastHalfIm + wi * lastHalfReal; - out[i] = rt * rt + it * it; - rt = previousHalfReal - wr * lastHalfReal + wi * lastHalfIm; - it = -previousHalfIm + wr * lastHalfIm + wi * lastHalfReal; - out[i3] = rt * rt + it * it; - wr = (wtemp = wr) * wpr - wi * wpi + wr; - wi = wi * wpr + wtemp * wpi + wi; - } - rt = (previousHalfReal = para_.realOut[0]) + para_.imagOut[0]; - it = previousHalfReal - para_.imagOut[0]; - out[0] = rt * rt + it * it; - rt = para_.realOut[half / 2]; - it = para_.imagOut[half / 2]; - out[half / 2] = rt * rt + it * it; - return Sensors::SUCCESS; -} - -int32_t Fft::WindowFunc(int32_t whichFunction, int32_t numSamples, float *out) -{ - if (numSamples < NUM_SAMPLES_MIN) { - SEN_HILOGE("numSamples are less than 2"); - return Sensors::PARAMETER_ERROR; - } - switch (whichFunction) { - case WND_TYPE_BARTLETT: { - float samplesCount = static_cast(numSamples); - // Bartlett (triangular) window - for (int32_t i = 0; i < (numSamples / 2); ++i) { - out[i] *= i / (samplesCount / 2); - out[i + (numSamples / 2)] *= 1.0 - (i / (samplesCount / 2)); - } - return Sensors::SUCCESS; - } - case WND_TYPE_HAMMING: { - // Hamming - for (int32_t i = 0; i < numSamples; ++i) { - out[i] *= HAMMING_WND_UP - HAMMING_WND_DOWN * cos(2 * M_PI * i / (numSamples - 1)); - } - return Sensors::SUCCESS; - } - case WND_TYPE_HANNING: { - // Hanning - for (int32_t i = 0; i < numSamples; ++i) { - out[i] *= F_HALF - F_HALF * cos(2 * M_PI * i / (numSamples - 1)); - } - return Sensors::SUCCESS; - } - default: { - SEN_HILOGE("WindowType: %{public}d invalid", whichFunction); - return Sensors::ERROR; - } - } -} - -int32_t Fft::GenWindow(int32_t whichFunction, int32_t numSamples, std::vector &window) -{ - if (numSamples < NUM_SAMPLES_MIN) { - SEN_HILOGE("numSamples are less than 2"); - return Sensors::PARAMETER_ERROR; - } - switch (whichFunction) { - case WND_TYPE_BARTLETT: { - float samplesCount = static_cast(numSamples); - // Bartlett (triangular) window - for (int32_t i = 0; i < (numSamples / 2); ++i) { - window[i] = i / (samplesCount / 2); - window[i + (numSamples / 2)] = 1.0 - (i / (samplesCount / 2)); - } - return Sensors::SUCCESS; - } - case WND_TYPE_HAMMING: { - for (int32_t i = 0; i < numSamples; ++i) { - window[i] = HAMMING_WND_UP - HAMMING_WND_DOWN * cos(2 * M_PI * i / (numSamples - 1)); - } - return Sensors::SUCCESS; - } - case WND_TYPE_HANNING: { - // Hanning - for (int32_t i = 0; i < numSamples; ++i) { - window[i] = F_HALF - F_HALF * cos(2 * M_PI * i / (numSamples - 1)); - } - return Sensors::SUCCESS; - } - default: { - SEN_HILOGE("WindowType: %{public}d invalid", whichFunction); - return Sensors::ERROR; - } - } -} - -void Fft::Init(int32_t fftSize) -{ - fftSize_ = fftSize; - half_ = fftSize / 2; - - fftParaRes_ = FftParaAndResult(fftSize_); - para_ = FftParaAndResult(half_); -} - -std::vector Fft::GetReal() const -{ - return fftParaRes_.realOut; -} - -std::vector Fft::GetImg() const -{ - return fftParaRes_.imagOut; -} - -void Fft::CalcFFT(const std::vector &data, const std::vector &window) -{ - // windowing - for (int32_t i = 0; i < fftSize_; ++i) { - fftParaRes_.realIn[i] = data[i] * window[i]; - } - // fftParaRes_.realIn include realIn and imageIn! - AlgRealFFT(fftParaRes_); -} - -void Fft::ConvertPolar(std::vector &magnitude, std::vector &phase) -{ - for (int32_t i = 0; i < half_; ++i) { - /* compute power */ - float power = pow(fftParaRes_.realOut[i], 2) + pow(fftParaRes_.imagOut[i], 2); - /* compute magnitude and phase */ - magnitude[i] = sqrt(power); - phase[i] = atan2(fftParaRes_.imagOut[i], fftParaRes_.realOut[i]); - } -} - -/* Calculate the power spectrum */ -void Fft::CalculatePowerSpectrum(const std::vector &data, const std::vector &window, - std::vector &magnitude, std::vector &phase) -{ - CalcFFT(data, window); - ConvertPolar(magnitude, phase); -} - -void Fft::ConvertDB(const std::vector &in, std::vector &out) -{ - for (int32_t i = 0; i < half_; ++i) { - if (IsLessNotEqual(in[i], VOLUME_MIN)) { - // less than 0.1 nV - out[i] = 0.0F; // out of range - } else { - out[i] = AMP_TO_DB_COEF * log10(in[i] + 1); // get to to db scale - } - } -} - -void Fft::ConvertCart(const std::vector &magnitude, const std::vector &phase) -{ - /* get real and imag part */ - for (int32_t i = 0; i < half_; ++i) { - fftParaRes_.realIn[i] = magnitude[i] * cos(phase[i]); - fftParaRes_.imagIn[i] = magnitude[i] * sin(phase[i]); - } - /* zero negative frequencies */ - std::fill(fftParaRes_.realIn.begin() + half_, fftParaRes_.realIn.begin() + half_ + half_, 0); - std::fill(fftParaRes_.imagIn.begin() + half_, fftParaRes_.imagIn.begin() + half_ + half_, 0); -} - -void Fft::CalcIFFT(const std::vector &window, std::vector &finalOut) -{ - // second parameter indicates inverse transform - fftParaRes_.numSamples = fftSize_; - AlgFFT(TRANSFORM_INVERSE_FLAG, fftParaRes_); - for (int32_t i = 0; i < fftSize_; ++i) { - finalOut[i] += fftParaRes_.realOut[i] * window[i]; - } -} - -void Fft::InverseFFTComplex(const std::vector &window, const std::vector &real, - const std::vector &imaginary, std::vector &finalOut) -{ - for (int32_t i = 0; i < half_; ++i) { - fftParaRes_.realOut[i] = real[i]; - fftParaRes_.imagOut[i] = imaginary[i]; - } - CalcIFFT(window, finalOut); -} - -void Fft::InversePowerSpectrum(const std::vector &window, const std::vector &magnitude, - const std::vector &phase, std::vector &finalOut) -{ - ConvertCart(magnitude, phase); - CalcIFFT(window, finalOut); -} -} // namespace Sensors -} // namespace OHOS \ No newline at end of file diff --git a/vibration_convert/core/algorithm/frequency_estimation/include/frequency_estimation.h b/vibration_convert/core/algorithm/frequency_estimation/include/frequency_estimation.h deleted file mode 100644 index 5a6fbf0c0fbd2b4289fbc6febd748bce63bdec52..0000000000000000000000000000000000000000 --- a/vibration_convert/core/algorithm/frequency_estimation/include/frequency_estimation.h +++ /dev/null @@ -1,67 +0,0 @@ -/* - * 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 - * - * 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 FREQUENCY_ESTIMATION_H -#define FREQUENCY_ESTIMATION_H - -#include -#include -#include -#include - -#include "utils.h" - -namespace OHOS { -namespace Sensors { -/** -Conversion functions -*/ -class FrequencyEstimation { -public: - FrequencyEstimation() = default; - ~FrequencyEstimation() = default; - - /** - * @brief Get the zero crossing rate - * - * @param data Audio data. - * @param frmLength The length of a frame, usually to the nth power of 2. - * @param hopLength The length of the window to be processed in a frame, usually to the nth power of 2. - * - * @return std::vector Zero crossing rate'vector. - */ - std::vector GetZeroCrossingRate(const std::vector &data, int32_t frmLength, int32_t hopLength); - - /** - * @brief Invalid frequency processing - * The default value of freqReaderAbsFlag is true. - * - * @param frequencyHz The calculated frequency includes invalid frequencies. - * @param voiceSegmentFlag Set of voice and silent segment flags. - * @param rmseIntensityNorm Normalized intensity values. - * @param freqNorm Normalized frequency values. - */ - void FreqPostProcess(const std::vector &frequencyHz, const std::vector &voiceSegmentFlag, - const std::vector &rmseIntensityNorm, std::vector &freqNorm); - -private: - double Mean(const std::vector &data); - -private: - bool freqReaderAbsFlag_ { true }; -}; -} // namespace Sensors -} // namespace OHOS -#endif // FREQUENCY_ESTIMATION_H \ No newline at end of file diff --git a/vibration_convert/core/algorithm/frequency_estimation/src/frequency_estimation.cpp b/vibration_convert/core/algorithm/frequency_estimation/src/frequency_estimation.cpp deleted file mode 100644 index eadfa93bd45a4d7997eb8ed7ef58e7c8277b6b5d..0000000000000000000000000000000000000000 --- a/vibration_convert/core/algorithm/frequency_estimation/src/frequency_estimation.cpp +++ /dev/null @@ -1,107 +0,0 @@ -/* - * 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 - * - * 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 "frequency_estimation.h" - -#include -#include -#include - -#include "sensor_log.h" -#include "sensors_errors.h" - -#undef LOG_TAG -#define LOG_TAG "FrequencyEstimation" - -namespace OHOS { -namespace Sensors { -namespace { -constexpr double BASE_SEMITONE { 69.0 }; -constexpr double PITCH_INTERVAL_MIN { 12.0 }; -constexpr double LA_FREQUENCE { 440.0 }; -constexpr double PITCH_INTERVAL_MAX { 108.0 }; -} // namespace - -double FrequencyEstimation::Mean(const std::vector &data) -{ - if (data.empty()) { - SEN_HILOGE("data is empty"); - return 0.0; - } - double sumValue = accumulate(data.begin(), data.end(), 0.0); - return (sumValue / data.size()); -} - -void FrequencyEstimation::FreqPostProcess(const std::vector &frequencyHz, const std::vector &voiceSegmentFlag, - const std::vector &rmseIntensityNorm, std::vector &freqNorm) -{ - // Processing of effective values for filling in mute positions. - std::vector hzTrims; - int32_t ret = ProcessSilence(frequencyHz, voiceSegmentFlag, rmseIntensityNorm, hzTrims); - if (ret != Sensors::SUCCESS) { - SEN_HILOGE("ProcessSilence failed"); - return; - } - // Frequency conversion. - std::vector pitch(hzTrims.size(), 0.0); - for (size_t i = 0; i < hzTrims.size(); ++i) { - pitch[i] = BASE_SEMITONE + (PITCH_INTERVAL_MIN * log2(hzTrims[i] / LA_FREQUENCE)); - } - if (freqReaderAbsFlag_) { - freqNorm = OHOS::Sensors::NormalizePercentageRange(pitch, PITCH_INTERVAL_MIN, - (PITCH_INTERVAL_MIN + PITCH_INTERVAL_MAX)); - } else { - freqNorm = OHOS::Sensors::NormalizePercentageMin(pitch); - } - if (!freqNorm.empty() && (freqNorm.size() + 1) == rmseIntensityNorm.size()) { - freqNorm.push_back(freqNorm.back()); - } -} - -std::vector FrequencyEstimation::GetZeroCrossingRate(const std::vector &data, int32_t frmLength, int32_t hopLength) -{ - if (data.empty() || frmLength <= hopLength) { - SEN_HILOGE("data is empty or frmLength is less than hopLength"); - return {}; - } - size_t dataSize = data.size(); - size_t step = static_cast(frmLength - hopLength); - size_t frameNum = ceil(dataSize / step); - std::vector zcr(frameNum, 0.0); - std::vector oneFrmData; - auto it = data.begin(); - for (size_t i = 0; i < frameNum; ++i) { - int32_t beginIndex = i * step; - int32_t endIndex = std::min(beginIndex + frmLength, static_cast(dataSize)); - oneFrmData.assign(it + beginIndex, it + endIndex); - double curFrameMean = Mean(oneFrmData); - int32_t crossingN = 0; - size_t curFrameSize = oneFrmData.size(); - if (curFrameSize == 0) { - SEN_HILOGE("oneFrmData is empty"); - return {}; - } - for (size_t j = 0; j < (curFrameSize - 1); ++j) { - oneFrmData[j] = oneFrmData[j] - curFrameMean; - if (IsLessOrEqual(oneFrmData[j] * oneFrmData[j + 1], 0.0)) { - ++crossingN; - } - } - zcr[i] = (static_cast(crossingN) / curFrameSize); - } - return zcr; -} -} // namespace Sensors -} // namespace OHOS \ No newline at end of file diff --git a/vibration_convert/core/algorithm/onset/include/onset.h b/vibration_convert/core/algorithm/onset/include/onset.h deleted file mode 100644 index 6d0d1aeed935859170a5dc4effff96b4abc76f04..0000000000000000000000000000000000000000 --- a/vibration_convert/core/algorithm/onset/include/onset.h +++ /dev/null @@ -1,81 +0,0 @@ -/* - * 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 - * - * 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 ONSET_H -#define ONSET_H - -#include -#include -#include -#include -#include - -#include "peak_finder.h" - -namespace OHOS { -namespace Sensors { -struct OnsetInfo { - /** If True, detected onset events are backtracked to the nearest. preceding minimum of energy. - * This is primarily useful when using onsets as slice points for segmentation. - */ - bool backTrackFlag { false }; - /** Compute a spectral flux onset strength envelope. */ - std::vector envelopes; - std::vector idxs; - std::vector times; - void Clear() { - backTrackFlag = false; - envelopes.clear(); - idxs.clear(); - times.clear(); - } -}; - -class Onset { -public: - Onset() = default; - ~Onset() = default; - - /** - * @brief Locate note onset events by picking peaks in an onset strength envelope.. - * - * @param data audio time-series. - * @param nFft length of the windowed signal after padding with zeros. The number of rows in the STFT matrix D - * is (1 + n_fft/2). The default value, n_fft=2048 samples. - * @param hopLength If unspecified, defaults to win_length / 4. - * @param onsets - * - * @return Returns 0 if the operation is successful; returns a negative value otherwise. - */ - int32_t CheckOnset(const std::vector &data, int32_t nFft, int32_t hopLength, OnsetInfo &onsetInfo); - -private: - int32_t Sfft(const std::vector &data, int32_t hopLength, int32_t &frmCount, - std::vector &magnitudes, int32_t &numBins); - int32_t GetMelBias(int32_t numBins, int32_t nFft, size_t &frmCount, std::vector &melBias); - std::vector MatrixDot(size_t matrixAcols, const std::vector &matrixA, - size_t matrixBcols, const std::vector &matrixB); - std::vector MatrixDiff(size_t valueCols, const std::vector &values); - std::vector PowerDB(const std::vector &values); - std::optional Median(const std::vector &values); - std::optional Mean(const std::vector &values); - -private: - bool htkFlag_ { false }; - OnsetInfo onsetInfo_; -}; -} // namespace Sensors -} // namespace OHOS -#endif // ONSET_H \ No newline at end of file diff --git a/vibration_convert/core/algorithm/onset/src/onset.cpp b/vibration_convert/core/algorithm/onset/src/onset.cpp deleted file mode 100644 index 1602836359fedc31cf2f1e0e6897be52876d800a..0000000000000000000000000000000000000000 --- a/vibration_convert/core/algorithm/onset/src/onset.cpp +++ /dev/null @@ -1,265 +0,0 @@ -/* - * 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 - * - * 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 "onset.h" - -#include -#include -#include - -#include "conversion_fft.h" -#include "conversion_mfcc.h" -#include "sensor_log.h" -#include "sensors_errors.h" -#include "utils.h" - -#undef LOG_TAG -#define LOG_TAG "Onset" - -namespace OHOS { -namespace Sensors { -namespace { -// Effective threshold of note envelope -constexpr double C_ONSET_ENV_VALIDE_THRESHOLD = 0.0001; -constexpr double POWER_DB_COEF = 10.0; -constexpr size_t N_MELS_OR_FILTERS = 128; -/** 12 + 1 semitones*/ -constexpr uint32_t SEMITONE_NUM_COEFFS = 13; -constexpr double ONSET_PEAK_THRESHOLD_RATIO = 0.4; -constexpr double MIN_FREQ = 0.0; -constexpr double MAX_FREQ = SAMPLE_RATE / 2.0; -} // namespace - -std::vector Onset::MatrixDot(size_t matrixAcols, const std::vector &matrixA, - size_t matrixBcols, const std::vector &matrixB) -{ - if ((matrixAcols == 0) || (matrixBcols == 0)) { - SEN_HILOGE("Invalid parameter"); - return {}; - } - if ((matrixA.empty()) || (matrixB.empty())) { - SEN_HILOGE("matrixA or matrixB is empty"); - return {}; - } - size_t aRows = matrixA.size() / matrixAcols; - size_t bRows = matrixB.size() / matrixBcols; - std::vector result(aRows * matrixBcols); - for (size_t i = 0; i < aRows; ++i) { - for (size_t j = 0; j < matrixBcols; ++j) { - // bRows must equal to matrixAcols. - int32_t idx = j * aRows + i; - double sum = 0.0; - for (size_t k = 0; k < bRows; ++k) { - // Multiply each column of the matrixB by each row of the matrixA, and then sum it up. - sum += matrixA[k * aRows + i] * matrixB[j * bRows + k]; - } - result[idx] = sum; - } - } - return result; -} - -std::vector Onset::MatrixDiff(size_t valueCols, const std::vector &values) -{ - if ((valueCols == 0) || (values.empty())) { - SEN_HILOGE("Invalid parameter"); - return {}; - } - size_t valueRows = values.size() / valueCols; - std::vector result; - for (size_t i = 0; i < (valueCols - 1); ++i) { - for (size_t j = 0; j < valueRows; ++j) { - result.push_back(values[(i + 1) * valueRows + j] - values[i * valueRows + j]); - } - } - return result; -} - -std::optional Onset::Median(const std::vector &values) -{ - if (values.empty()) { - SEN_HILOGE("values is empty"); - return std::nullopt; - } - std::vector result = values; - sort(result.begin(), result.end()); - double valueMedian = result[result.size() / 2]; - return valueMedian; -} - -std::optional Onset::Mean(const std::vector &values) -{ - if (values.empty()) { - SEN_HILOGE("values is empty"); - return std::nullopt; - } - double sumValue = accumulate(values.begin(), values.end(), 0); - return sumValue / values.size(); -} - -// Need to subtract an offset value. -std::vector Onset::PowerDB(const std::vector &values) -{ - std::vector logSpectrum; - for (size_t i = 0; i < values.size(); ++i) { - logSpectrum.push_back(POWER_DB_COEF * log(std::max(EPS_MIN, values[i]))); - } - return logSpectrum; -} - -int32_t Onset::Sfft(const std::vector &data, int32_t hopLength, int32_t &frmCount, - std::vector &magnitudes, int32_t &numBins) -{ - if (data.empty()) { - SEN_HILOGE("data is empty"); - return Sensors::ERROR; - } - ConversionFFT convFft; - FFTInputPara fftPara; - fftPara.sampleRate = SAMPLE_RATE; - fftPara.fftSize = NFFT; - fftPara.hopSize = hopLength; - fftPara.windowSize = NFFT; - int32_t ret = convFft.Init(fftPara); - if (ret != Sensors::SUCCESS) { - SEN_HILOGE("Init failed"); - return Sensors::ERROR; - } - numBins = convFft.GetNumBins(); - ret = convFft.Process(data, frmCount, magnitudes); - if (ret != Sensors::SUCCESS) { - SEN_HILOGE("Process failed"); - return Sensors::ERROR; - } - return Sensors::SUCCESS; -} - -int32_t Onset::GetMelBias(int32_t numBins, int32_t nFft, size_t &frmCount, std::vector &melBias) -{ - MfccInputPara para; - para.sampleRate = SAMPLE_RATE; - para.nMels = static_cast(N_MELS_OR_FILTERS); - para.minFreq = MIN_FREQ; - para.maxFreq = MAX_FREQ; - // Use slaneyBias if htkFlag_ is true. - if (htkFlag_) { - ConversionMfcc mfcc; - uint32_t numCoeffs = SEMITONE_NUM_COEFFS; - if (mfcc.Init(numBins, numCoeffs, para) != Sensors::SUCCESS) { - SEN_HILOGE("Init failed"); - return Sensors::ERROR; - } - melBias = mfcc.GetMelFilterBank(); - frmCount = melBias.size() / N_MELS_OR_FILTERS; - return Sensors::SUCCESS; - } else { - ConversionMfcc mfcc; - if (mfcc.FiltersMel(nFft, para, frmCount, melBias) != Sensors::SUCCESS) { - SEN_HILOGE("FiltersMel failed"); - return Sensors::ERROR; - } - return Sensors::SUCCESS; - } -} - -int32_t Onset::CheckOnset(const std::vector &data, int32_t nFft, int32_t hopLength, OnsetInfo &onsetInfo) -{ - CALL_LOG_ENTER; - if ((data.size() < ONSET_HOP_LEN) || (nFft == 0) || (hopLength == 0)) { - SEN_HILOGE("Invalid parameter, data:%{public}zu, nFft:%{public}d, hopLength:%{public}d", - data.size(), nFft, hopLength); - return Sensors::PARAMETER_ERROR;; - } - std::vector magnitudes; - int32_t sfftFrmCount; - int32_t numBins; - if (Sfft(data, hopLength, sfftFrmCount, magnitudes, numBins) != Sensors::SUCCESS) { - SEN_HILOGE("Sfft failed"); - return Sensors::ERROR; - } - if (magnitudes.empty()) { - SEN_HILOGE("magnitudes is empty"); - return Sensors::ERROR; - } - std::vector frmMagnitudes; - for (size_t i = 0; i < magnitudes.size(); ++i) { - frmMagnitudes.push_back(static_cast(magnitudes[i])); - frmMagnitudes[i] = pow(frmMagnitudes[i], 2); - } - size_t biasFrmCount = 0; - std::vector melBias; - if (GetMelBias(numBins, nFft, biasFrmCount, melBias) != Sensors::SUCCESS) { - SEN_HILOGE("GetMelBias failed"); - return Sensors::ERROR; - } - std::vector onsetEnvelope = MatrixDot(biasFrmCount, melBias, sfftFrmCount, frmMagnitudes); - if (onsetEnvelope.empty()) { - SEN_HILOGE("onsetEnvelope is empty"); - return Sensors::ERROR; - } - std::vector dbEnvelope = PowerDB(onsetEnvelope); - if (dbEnvelope.empty()) { - SEN_HILOGE("dbEnvelope is empty"); - return Sensors::ERROR; - } - std::vector dbEnvelopeDiff = MatrixDiff(sfftFrmCount, dbEnvelope); - if (dbEnvelopeDiff.empty()) { - SEN_HILOGE("dbEnvelopeDiff is empty"); - return Sensors::ERROR; - } - for (size_t i = 0; i < dbEnvelopeDiff.size(); ++i) { - dbEnvelopeDiff[i] = (IsGreatNotEqual(dbEnvelopeDiff[i], 0.0)) ? dbEnvelopeDiff[i] : 0.0; - } - if (sfftFrmCount <= 1) { - SEN_HILOGE("sfftFrmCount is less than or equal to 1"); - return Sensors::ERROR; - } - size_t cols = sfftFrmCount - 1; - size_t rows = dbEnvelopeDiff.size() / cols; - onsetInfo_.Clear(); - std::vector oneFrmValues; - for (size_t i = 0; i < cols; ++i) { - oneFrmValues.assign(dbEnvelopeDiff.begin() + i * rows, dbEnvelopeDiff.begin() + ((i + 1) * rows)); - std::optional median = Median(oneFrmValues); - if (!median) { - SEN_HILOGE("Median failed"); - return Sensors::ERROR; - } - onsetInfo_.envelopes.push_back(median.value()); - } - double envelopeMax = *max_element(onsetInfo_.envelopes.begin(), onsetInfo_.envelopes.end()); - if (envelopeMax < C_ONSET_ENV_VALIDE_THRESHOLD) { - onsetInfo_.envelopes.clear(); - for (size_t i = 0; i < cols; ++i) { - oneFrmValues.assign(dbEnvelopeDiff.begin() + i * rows, dbEnvelopeDiff.begin() + ((i + 1) * rows)); - std::optional mean = Mean(oneFrmValues); - if (!mean) { - SEN_HILOGE("Mean failed"); - return Sensors::ERROR; - } - onsetInfo_.envelopes.push_back(mean.value()); - } - } - double tPerFrame = static_cast(hopLength) / SAMPLE_RATE; - PeakFinder peakFinder; - onsetInfo_.idxs = peakFinder.DetectPeak(onsetInfo_.envelopes, ONSET_PEAK_THRESHOLD_RATIO); - for (size_t i = 0; i < onsetInfo_.idxs.size(); ++i) { - onsetInfo_.times.push_back(onsetInfo_.idxs[i] * tPerFrame); - } - onsetInfo = onsetInfo_; - return Sensors::SUCCESS; -} -} // namespace Sensors -} // namespace OHOS \ No newline at end of file diff --git a/vibration_convert/core/native/include/audio_parsing.h b/vibration_convert/core/native/include/audio_parsing.h deleted file mode 100644 index fb837bfc06414cb847e5ad743fde9847c296992a..0000000000000000000000000000000000000000 --- a/vibration_convert/core/native/include/audio_parsing.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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 - * - * 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 AUDIO_PARSING_H -#define AUDIO_PARSING_H - -#include -#include -#include - -#include -#include - -#include "singleton.h" -#include "vibration_convert_type.h" - -namespace OHOS { -namespace Sensors { -class AudioParsing { -public: - explicit AudioParsing(const RawFileDescriptor &fd); - ~AudioParsing() = default; - int32_t GetAudioAttribute(AudioAttribute &audioAttribute) const; - int32_t GetAudioData(int32_t samplingInterval, AudioData &audioData) const; - int32_t ConvertAudioToHaptic(const AudioSetting &audioSetting, std::vector &hapticEvents); - int32_t ParseAudioFile(); - -private: - int32_t RawFileDescriptorCheck(); - void PrintAttributeChunk(); - -private: - RawFileDescriptor rawFd_; - AudioData audioData_; - AttributeChunk attributeChunk_; -}; -} // namespace Sensors -} // namespace OHOS -#endif // AUDIO_PARSING_H \ No newline at end of file diff --git a/vibration_convert/core/native/include/generate_vibration_json_file.h b/vibration_convert/core/native/include/generate_vibration_json_file.h deleted file mode 100644 index 57d4e7448eae75a2e193e88721c754e62b9b7860..0000000000000000000000000000000000000000 --- a/vibration_convert/core/native/include/generate_vibration_json_file.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - * 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 - * - * 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 GENERATE_VIBRATION_JSON_FILE_H -#define GENERATE_VIBRATION_JSON_FILE_H - -#include -#include - -#include - -#include "vibration_convert_type.h" - -namespace OHOS { -namespace Sensors { -class GenerateVibrationJsonFile { -public: - GenerateVibrationJsonFile() = default; - ~GenerateVibrationJsonFile() = default; - int32_t GenerateJsonFile(std::vector &hapticEvents); - template - int32_t DebugJsonFile(const std::string &pathName, const std::vector &srcDatas); -}; -} // namespace Sensors -} // namespace OHOS -#endif // GENERATE_VIBRATION_JSON_FILE_H \ No newline at end of file diff --git a/vibration_convert/core/native/include/vibration_convert_core.h b/vibration_convert/core/native/include/vibration_convert_core.h deleted file mode 100644 index 11238f622370e7813eda30493ad36486feb0987f..0000000000000000000000000000000000000000 --- a/vibration_convert/core/native/include/vibration_convert_core.h +++ /dev/null @@ -1,210 +0,0 @@ -/* - * 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 - * - * 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 VIBRATION_CONVERT_CORE_H -#define VIBRATION_CONVERT_CORE_H - -#include -#include - -#include - -#include "frequency_estimation.h" -#include "intensity_processor.h" -#include "onset.h" -#include "peak_finder.h" -#include "singleton.h" -#include "vibration_convert_type.h" - -namespace OHOS { -namespace Sensors { -/** - * Merge data with onset and transient -*/ -struct UnionTransientEvent { - bool transientEventFlag = false;; - int32_t onsetIdx { 0 }; - double onsetTime { 0.0 }; - - UnionTransientEvent() = default; - UnionTransientEvent(int32_t onsetIdx, double onsetTime, bool transientEventFlag = false) : - transientEventFlag(transientEventFlag), onsetIdx(onsetIdx), onsetTime(onsetTime) {} -}; - -struct IntensityData { - double rmseEnvelope { 0.0 }; - double rmseTimex { 0.0 }; - double rmseBand { 0.0 }; - int32_t rmseIntensityNorm { 0 }; - double rmseTimeNorm { 0.0 }; - - IntensityData() = default; - IntensityData(double envelope, double time, double band, int32_t intensityNorm, double timeNorm) : - rmseEnvelope(envelope), rmseTimex(time), rmseBand(band), rmseIntensityNorm(intensityNorm), - rmseTimeNorm(timeNorm) {} -}; - -struct ContinuousEvent { - double time { 0.0 }; - double duration { 0.0 }; - int32_t intensity { 0 }; - int32_t frequency { 0 }; - - ContinuousEvent(double time, double duration, int32_t intensity, int32_t frequency) : time(time), duration(duration), - intensity(intensity), frequency(frequency) {} -}; - -struct TransientEvent { - double time { 0.0 }; - int32_t intensity { 0 }; - int32_t frequency { 0 }; - - TransientEvent(double time, int32_t intensity, int32_t frequency) : time(time), intensity(intensity), - frequency(frequency) {} -}; - -/** - * @brief The system parameters for converting audio to vibration will be read out from the system parameter - * file in the future - */ -struct ConvertSystemParameters { - /** if the # flag is Yes, long and short events are stored in blocks, and if No, they are stored in - * chronological order*/ - bool blockStoreFlag { false }; - /** Has the onset alignment algorithm been used */ - bool onsetBacktrackFlag { false }; - /** Should use absolute time or window start time */ - bool useAbsTimeFlag { true }; - /** Linear processing for intensity. */ - bool intensityUseLinearFlag { true }; - /** Segmented envelope processing. */ - bool splitSegmentFlag { false }; - /** The energy difference within an envelope is less than c_ i_ combinate_ Delta is merged, - * with a value range of<5 */ - bool intensityCmbFlag { true }; - /** Monotonic merging within the envelope, if c_monotonicity_flag is true, - * c_slop_cmb_flag There's no need to deal. */ - bool monotonicityCmbFlag { false }; - /** Support monotonic adjacent point slopes less than c_slop_delta, and c_slop_cmb_flag with true then merge. */ - bool slopCmbFlag { false }; - /** When calculating intensity, align the center and add half frames of 0 at the beginning and end respectively. */ - bool centerPaddingFlag { true }; -}; - -class VibrationConvertCore : public Singleton { -public: - VibrationConvertCore() = default; - ~VibrationConvertCore() = default; - - /** - * @brief Convert audio files to haptic events. - * - * @param audioSetting: the set audio sampling threshold. For details, see {@link AudioSetting}. - * @param audioDatas: the audio data. - * @param hapticEvents: the information of the event, after translated. For details, see {@link HapticEvent}. - * - * @return Returns 0 if the operation is successful; returns a negative value otherwise. - */ - int32_t ConvertAudioToHaptic(const AudioSetting &audioSetting, const std::vector &audioDatas, - std::vector &hapticEvents); - -private: - DISALLOW_COPY_AND_MOVE(VibrationConvertCore); - int32_t ResampleAudioData(const std::vector &srcDatas); - std::vector PreprocessAudioData(); - int32_t PreprocessParameter(const std::vector &datas, int32_t &onsetHopLength, double &lowerDelta); - std::vector MapOnsetHop(const std::vector &drwIdxs, int32_t onsetHopLength); - double CalcRmsLowerData(size_t dataSize, const std::vector &rmses, const std::vector &newDrwIdxs); - int32_t CalcOnsetHopLength(const std::vector &datas, double rmseMax, size_t newDrwIdxLen, - bool &continuousEventFlag, int32_t &newOnsetHopLen); - /** - * Before vibration conversion, amplitude density is used to classify audio files, determine whether there are - * long events in the audio files, and adjust the onset detection window. - */ - int32_t IsIncludeContinuoustEvent(const std::vector &datas, int32_t &longestCount, - double &unzeroDensity, bool &isIncludeContinuoustEvent); - int32_t ConvertTransientEvent(const std::vector &datas, int32_t onsetHopLength, - std::vector &unionTransientEvents); - std::vector DetectOnset(const std::vector &audioDatas, int32_t onsetHopLength); - std::vector IsTransientEvent(const std::vector &datas, const std::vector &onsetIdxs); - void GetUnzeroCount(const std::vector &localDatas, int32_t &unzeroCount, double &unzeroDensity); - bool IsTransientEventFlag(int32_t unzeroCount, double unzeroDensity); - void TranslateAnchorPoint(const std::vector &litudePeakPos, - std::vector &unionTransientEvents); - void TranslateAnchorPoint(int32_t amplitudePeakPos, int32_t &litudePeakIdx, double &litudePeakTime); - int32_t DetectRmsIntensity(const std::vector &datas, double rmsILowerDelta, - std::vector &intensityDatas); - std::vector DetectFrequency(const std::vector &datas, const std::vector &rmseIntensityNorms); - std::vector StartTimeNormalize(int32_t rmseLen); - -private: - void OutputTransientEvents(const std::vector &unionTransientEvents, - const std::vector &intensityDatas, const std::vector &freqNorms, - std::vector &transientIndexs, std::vector &transientEventTimes); - void OutputTransientEventsByInsertTime(const std::vector &onsetTimes, - const std::vector &intensityDatas, const std::vector &freqNorms, - std::vector &transientIndexs, std::vector &transientEventTimes); - void GetIndex(const UnionTransientEvent &unionTransientEvent, const std::vector &intensityDatas); - void OutputTransientEventsAlign(const std::vector &unionTransientEvents, - const std::vector &intensityDatas, const std::vector &freqNorms, - std::vector &transientIndexs, std::vector &transientEventTimes); - void OutputTransientEventsDirect(const std::vector &unionTransientEvents, - const std::vector &intensityDatas, const std::vector &freqNorms, - std::vector &transientIndexs, std::vector &transientEventTimes); - void AddTransientEventData(TransientEvent transientEvent); - void OutputAllContinuousEvent(const std::vector &intensityDatas, - const std::vector transientIndexs, const std::vector &freqNorms, - const std::vector &transientEventFlags); - void OutputAllContinuousEventByUnseg(const std::vector &intensityDatas, - const std::vector transientIndexs, const std::vector &freqNorms, - const std::vector &transientEventFlags); - void FillDefaultContinuousEvents(const std::vector &rmseTimeNorms, std::vector ×, - std::vector &durations); - int32_t InsertTransientEvent(const std::vector &rmseTimeNorms, - const std::vector &transientIndexs, const std::vector &transientEventFlags, - std::vector ×, std::vector &durations); - void MergeContinuousEvents(const std::vector &interContinuousEvents); - void AddContinuousEventData(const ContinuousEvent &continuousEvent); - int32_t GetAudioData(); - void StoreHapticEvent(); - void StoreEventSequence(); - void StoreEventBlock(); - void CombinateContinuousEvents(const std::vector &continuousEvents, int32_t startIdx, int32_t endIdx); - /** - * Using transient events instead of onse - */ - void EmplaceOnsetTime(bool flag, int32_t idx, double time, std::vector &unionTransientEvents); - std::vector GetLocalEnvelope(const std::vector &datas); - bool GetRmseLowerDelta(double lowerDelta, const std::vector &rmses, double &lowestDelta); - bool GetTransientEventFlag(const std::vector &datas, int32_t onsetIdx); - std::vector GetTransientEventFlags(const std::vector &datas, const std::vector &onsetIdxs); - -private: - ConvertSystemParameters systemPara_; - AudioSetting audioSetting_; - std::vector srcAudioDatas_; - std::vector continuousEvents_; - std::vector transientEvents_; - std::vector hapticEvents_; - bool continuousEventExistFlag_ { false }; - IntensityProcessor intensityProcessor_; - FrequencyEstimation frequencyEstimation_; - PeakFinder peakFinder_; - Onset onset_; - int32_t onsetMinSkip_ { 0 }; -}; -} // namespace Sensors -} // namespace OHOS -#endif // VIBRATION_CONVERT_CORE_H \ No newline at end of file diff --git a/vibration_convert/core/native/include/vibration_convert_type.h b/vibration_convert/core/native/include/vibration_convert_type.h deleted file mode 100644 index 8d39a3c60c10780c10755ebd7fbb04f3383f2262..0000000000000000000000000000000000000000 --- a/vibration_convert/core/native/include/vibration_convert_type.h +++ /dev/null @@ -1,144 +0,0 @@ -/* - * 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 - * - * 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 VIBRATION_CONVERT_TYPE_H -#define VIBRATION_CONVERT_TYPE_H - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * @brief Enumerates basic event enumeration of haptic. - * - * @since 1.0 - */ -typedef enum EventTag { - /** Continuous event. */ - EVENT_TAG_CONTINUOUS = 0, - /** Transient event. */ - EVENT_TAG_TRANSIENT = 1, -} VibrateTag; - -/** - * @brief Basic event-parameters definition of haptic. - * - * The parameters include the haptic basic event enumeration, start time, duration, intensity and frequency. - * - * @since 1.0 - */ -struct HapticEvent { - /** Basic event enumeration of haptic. */ - VibrateTag vibrateTag; - /** Start time. */ - int32_t startTime { 0 }; - /** Duration. */ - int32_t duration { 0 }; - /** Intensity. */ - int32_t intensity { 0 }; - /** Frequency. */ - int32_t frequency { 0 }; -}; - -/** - * @brief Defines the audio setting parameters. - * - * The parameters include the setting transient detection treshold and intensity treshold and - * frequency treshold and frequency range. - * - * @since 1.0 - */ -struct AudioSetting { - /** 0-100. */ - int32_t transientDetection { 0 }; - /** 0-100. */ - int32_t intensityTreshold { 0 }; - /** 0-100. */ - int32_t frequencyTreshold { 0 }; - /**< Max frequency(Hz). */ - int32_t frequencyMaxValue { 0 }; - /**< Min frequency(Hz). */ - int32_t frequencyMinValue { 0 }; -}; - -/** - * @brief Defines the audio file attribute. - * - * Parameters include data sampling frequency, data sampling duration, raw data number. - * - * @since 1.0 - */ -struct AudioAttribute { - /** sampling frequency. */ - uint32_t sampleRate { 0 }; - /** data sampling duration. */ - uint32_t duration { 0 }; - /** number of raw data. */ - uint32_t dataCount { 0 }; -}; - -/** - * @brief Defines the audio file data. - * - * Parameters include the number of data after the sampling interval, - * audio data, and data maximum and minimum. - * - * @since 1.0 - */ -struct AudioData { - /** data minimum. */ - double min { 0.0 }; - /** data maximum. */ - double max { 0.0 }; - /** audio data. */ - std::vector audioDatas; -}; - -/** - * @brief Defines the audio file attribute. - * - * Parameters include ChunkID, ChunkSize, Format, FmtChannels, SampleRate, ByteRate, BitsPerSample. - * - * @since 1.0 - */ -struct AttributeChunk { - char chunkID[4] { 0 }; //'R','I','F','F' - uint32_t chunkSize { 0 }; - char format[4] { 0 }; //'W','A','V','E' - char fmtID[4] { 0 }; - uint32_t fmtSize { 0 }; - uint16_t fmtTag { 0 }; - uint16_t fmtChannels { 0 }; - uint32_t sampleRate { 0 }; - uint32_t byteRate { 0 }; - uint16_t blockAilgn { 0 }; - uint16_t bitsPerSample { 0 }; - char dataID[4] { 0 }; //'d','a','t','a' - uint32_t dataSize { 0 }; -}; - -struct RawFileDescriptor { - int32_t fd = 0; - int64_t offset = 0; - int64_t length = -1; -}; - -/** @} */ -#ifdef __cplusplus -}; -#endif -#endif // VIBRATION_CONVERT_TYPE_H diff --git a/vibration_convert/core/native/src/audio_parsing.cpp b/vibration_convert/core/native/src/audio_parsing.cpp deleted file mode 100644 index 4da33cb1ad5ea69ce7b0c3f98c09797033779da7..0000000000000000000000000000000000000000 --- a/vibration_convert/core/native/src/audio_parsing.cpp +++ /dev/null @@ -1,214 +0,0 @@ -/* - * 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 - * - * 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_parsing.h" - -#include -#include -#include -#include - -#include - -#include - -#include "generate_vibration_json_file.h" -#include "sensor_log.h" -#include "sensors_errors.h" -#include "vibration_convert_core.h" -#include "vibration_convert_type.h" - -#undef LOG_TAG -#define LOG_TAG "AudioParsing" - -namespace OHOS { -namespace Sensors { -namespace { -constexpr int32_t MIN_SAMPLE_COUNT = 4096; -constexpr uint32_t AUDIO_DATA_CONVERSION_FACTOR = INT32_MAX; -constexpr int32_t AUDIO_DATA_MAX_NUMBER = 100000; -constexpr int64_t LSEEK_FAIL = -1; -constexpr int32_t TIME_MS = 1000; -constexpr int32_t BITS_PER_BYTE = 8; -} // namespace - -AudioParsing::AudioParsing(const RawFileDescriptor &rawFd) -{ - CALL_LOG_ENTER; - SEN_HILOGD("handle:%{public}d, offset:%{public}" PRId64 ", length:%{public}" PRId64, - rawFd.fd, rawFd.offset, rawFd.length); - rawFd_ = rawFd; -} - -int32_t AudioParsing::RawFileDescriptorCheck() -{ - CALL_LOG_ENTER; - if ((rawFd_.fd < 0) || (rawFd_.offset < 0) || (rawFd_.length <= 0)) { - SEN_HILOGE("Invalid parameter"); - return Sensors::PARAMETER_ERROR; - } - struct stat64 statbuf = { 0 }; - if (fstat64(rawFd_.fd, &statbuf) != 0) { - SEN_HILOGE("fstat error, errno:%{public}d", errno); - return Sensors::ERROR; - } - int64_t fileSize = static_cast(statbuf.st_size); - if ((fileSize - rawFd_.offset) < rawFd_.length) { - SEN_HILOGE("Invalid parameter rawFd"); - return Sensors::PARAMETER_ERROR; - } - return Sensors::SUCCESS; -} - -int32_t AudioParsing::ParseAudioFile() -{ - CALL_LOG_ENTER; - if (RawFileDescriptorCheck() != Sensors::SUCCESS) { - SEN_HILOGE("RawFileDescriptorCheck failed"); - return Sensors::ERROR; - } - int64_t oft = lseek(rawFd_.fd, rawFd_.offset, SEEK_SET); - if (oft == LSEEK_FAIL) { - SEN_HILOGE("lseek fail, oft:%{public}" PRId64, oft); - return Sensors::ERROR; - } - (void)memset_s(&attributeChunk_, sizeof(AttributeChunk), 0, sizeof(AttributeChunk)); - if (rawFd_.length < sizeof(AttributeChunk)) { - SEN_HILOGE("Invalid parameter"); - return Sensors::PARAMETER_ERROR; - } - - ssize_t ret = read(rawFd_.fd, &attributeChunk_, sizeof(AttributeChunk)); - if (ret <= 0) { - SEN_HILOGE("read audio attribute failed, errno:%{public}d", errno); - return Sensors::ERROR; - } - if ((attributeChunk_.bitsPerSample == 0) || (attributeChunk_.fmtChannels == 0)) { - SEN_HILOGE("The divisor cannot be 0"); - return Sensors::ERROR; - } - size_t dataCount = attributeChunk_.dataSize / - ((attributeChunk_.bitsPerSample / BITS_PER_BYTE) * attributeChunk_.fmtChannels); - PrintAttributeChunk(); - int32_t *dataBuffer = static_cast(malloc(attributeChunk_.dataSize)); - CHKPR(dataBuffer, Sensors::ERROR); - (void)memset_s(dataBuffer, attributeChunk_.dataSize, 0, attributeChunk_.dataSize); - - if (rawFd_.length < attributeChunk_.dataSize) { - free(dataBuffer); - SEN_HILOGE("Invalid parameter"); - return Sensors::PARAMETER_ERROR; - } - - ret = read(rawFd_.fd, dataBuffer, attributeChunk_.dataSize); - if (ret <= 0) { - free(dataBuffer); - SEN_HILOGE("read audio data failed"); - return Sensors::ERROR; - } - for (size_t i = 0; i < dataCount; ++i) { - double data = static_cast(dataBuffer[i]) / AUDIO_DATA_CONVERSION_FACTOR; - audioData_.audioDatas.push_back(data); - } - audioData_.max = *std::max_element(audioData_.audioDatas.begin(), audioData_.audioDatas.end()); - audioData_.min = *std::min_element(audioData_.audioDatas.begin(), audioData_.audioDatas.end()); - free(dataBuffer); - return Sensors::SUCCESS; -} - -int32_t AudioParsing::GetAudioAttribute(AudioAttribute &audioAttribute) const -{ - CALL_LOG_ENTER; - if ((attributeChunk_.bitsPerSample == 0) || (attributeChunk_.fmtChannels == 0) || (attributeChunk_.byteRate == 0)) { - SEN_HILOGE("The divisor cannot be 0"); - return Sensors::ERROR; - } - audioAttribute.sampleRate = attributeChunk_.sampleRate; - audioAttribute.dataCount = attributeChunk_.dataSize / ((attributeChunk_.bitsPerSample / BITS_PER_BYTE) * - attributeChunk_.fmtChannels); - float dataSize = static_cast(attributeChunk_.dataSize); - audioAttribute.duration = static_cast(dataSize / attributeChunk_.byteRate * TIME_MS); - SEN_HILOGD("sampleRate:%{public}u, duration:%{public}u, dataCount:%{public}u", - audioAttribute.sampleRate, audioAttribute.duration, audioAttribute.dataCount); - return Sensors::SUCCESS; -} - -int32_t AudioParsing::GetAudioData(int32_t samplingInterval, AudioData &data) const -{ - CALL_LOG_ENTER; - if (audioData_.audioDatas.empty()) { - SEN_HILOGE("audioDatas is empty"); - return Sensors::ERROR; - } - size_t dataCount = audioData_.audioDatas.size(); - if (samplingInterval < 0) { - SEN_HILOGE("Invalid parameter"); - return Sensors::PARAMETER_ERROR; - } - if (samplingInterval == 0) { - if ((dataCount % AUDIO_DATA_MAX_NUMBER) == 0 && (dataCount >= AUDIO_DATA_MAX_NUMBER)) { - samplingInterval = dataCount / AUDIO_DATA_MAX_NUMBER; - } else { - samplingInterval = dataCount / AUDIO_DATA_MAX_NUMBER + 1; - } - } - for (size_t i = 0; i < dataCount; ++i) { - if (i % samplingInterval == 0) { - data.audioDatas.push_back(audioData_.audioDatas[i]); - } - } - data.max = audioData_.max; - data.min = audioData_.min; - SEN_HILOGD("min:%{public}lf, max:%{public}lf, audioDatas.size():%{public}zu", - data.min, data.max, data.audioDatas.size()); - return Sensors::SUCCESS; -} - -int32_t AudioParsing::ConvertAudioToHaptic(const AudioSetting &audioSetting, std::vector &hapticEvents) -{ - CALL_LOG_ENTER; - if (audioData_.audioDatas.size() < MIN_SAMPLE_COUNT) { - SEN_HILOGE("audioDatas less then MIN_SAMPLE_COUNT, audioDatas.size():%{public}zu", audioData_.audioDatas.size()); - return Sensors::ERROR; - } - VibrationConvertCore vibrationConvertCore; - if (vibrationConvertCore.ConvertAudioToHaptic(audioSetting, audioData_.audioDatas, hapticEvents) != Sensors::SUCCESS) { - SEN_HILOGE("ConvertAudioToHaptic failed"); - return Sensors::ERROR; - } - GenerateVibrationJsonFile generateJson; - generateJson.GenerateJsonFile(hapticEvents); - return Sensors::SUCCESS; -} - -void AudioParsing::PrintAttributeChunk() -{ - CALL_LOG_ENTER; - SEN_HILOGD("chunkID:%{public}.4s", attributeChunk_.chunkID); - SEN_HILOGD("chunkSize:%{public}u", attributeChunk_.chunkSize); - SEN_HILOGD("format:%{public}.4s", attributeChunk_.format); - SEN_HILOGD("fmtID:%{public}.4s", attributeChunk_.fmtID); - SEN_HILOGD("fmtSize:%{public}u", attributeChunk_.fmtSize); - SEN_HILOGD("fmtTag:%{public}hu", attributeChunk_.fmtTag); - SEN_HILOGD("fmtChannels:%{public}hu", attributeChunk_.fmtChannels); - SEN_HILOGD("sampleRate:%{public}u", attributeChunk_.sampleRate); - SEN_HILOGD("byteRate:%{public}u", attributeChunk_.byteRate); - SEN_HILOGD("blockAilgn:%{public}hu", attributeChunk_.blockAilgn); - SEN_HILOGD("bitsPerSample:%{public}hu", attributeChunk_.bitsPerSample); - SEN_HILOGD("dataID:%{public}.4s", attributeChunk_.dataID); - SEN_HILOGD("dataSize:%{public}u", attributeChunk_.dataSize); -} -} // namespace Sensors -} // namespace OHOS diff --git a/vibration_convert/core/native/src/generate_vibration_json_file.cpp b/vibration_convert/core/native/src/generate_vibration_json_file.cpp deleted file mode 100644 index 467290df7c4d3184246a8c0441e57b4cc83fc51a..0000000000000000000000000000000000000000 --- a/vibration_convert/core/native/src/generate_vibration_json_file.cpp +++ /dev/null @@ -1,97 +0,0 @@ -/* - * 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 - * - * 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 "generate_vibration_json_file.h" - -#include -#include -#include - -#include "json/json.h" - -#include "sensor_log.h" -#include "sensors_errors.h" - -#undef LOG_TAG -#define LOG_TAG "GenerateVibrationJsonFile" - -namespace OHOS { -namespace Sensors { - -int32_t GenerateVibrationJsonFile::GenerateJsonFile(std::vector &hapticEvents) -{ - Json::Value meta; - meta["Create"] = "2023-04-27"; - meta["Discription"] = "A json file format demo"; - meta["Version"] = 1.0; - meta["ChannelNumber"] = 1; - Json::Value root; - root["MetaData"] = meta; - Json::Value pattern; - for (const auto &event : hapticEvents) { - Json::Value eventValue; - eventValue["Type"] = ((event.vibrateTag != EVENT_TAG_TRANSIENT) ? "continuous" : "transient"); - eventValue["StartTime"] = event.startTime; - eventValue["Parameters"]["Intensity"] = event.intensity; - eventValue["Parameters"]["Frequency"] = event.frequency; - if (event.vibrateTag != EVENT_TAG_TRANSIENT) { - eventValue["Duration"] = event.duration; - } - Json::Value ev; - ev["Event"] = eventValue; - pattern.append(ev); - } - Json::Value channel; - channel["Parameters"]["Index"] = 1; - channel["Pattern"] = pattern; - Json::Value channels; - channels.append(channel); - root["Channels"] = channels; - std::ofstream ofs("demo.json", std::ios::out); - if (!ofs.is_open()) { - SEN_HILOGE("File open failed, errno:%{public}d", errno); - return Sensors::ERROR; - } - ofs << root << std::endl; - ofs.close(); - return Sensors::SUCCESS; -} - -template -int32_t GenerateVibrationJsonFile::DebugJsonFile(const std::string &pathName, const std::vector &srcDatas) -{ - if (access(pathName.c_str(), 0) != 0) { - SEN_HILOGE("File not exist, errno:%{public}d", errno); - return Sensors::ERROR; - } - if (srcDatas.empty()) { - SEN_HILOGE("srcDatas is empty"); - return Sensors::ERROR; - } - Json::Value dataValue; - for (const auto &data : srcDatas) { - dataValue.append(data); - } - std::ofstream ofs(pathName, std::ios::out); - if (!ofs.is_open()) { - SEN_HILOGE("File open failed, errno:%{public}d", errno); - return Sensors::ERROR; - } - ofs << dataValue << std::endl; - ofs.close(); - return Sensors::SUCCESS; -} -} // namespace Sensors -} // namespace OHOS diff --git a/vibration_convert/core/native/src/vibration_convert_core.cpp b/vibration_convert/core/native/src/vibration_convert_core.cpp index b03ce62c47e06163dcffce6326a46684386034ab..433a7ceda562a8c7ec6c0341e6e0cd625c933e4b 100644 --- a/vibration_convert/core/native/src/vibration_convert_core.cpp +++ b/vibration_convert/core/native/src/vibration_convert_core.cpp @@ -80,49 +80,47 @@ int32_t VibrationConvertCore::GetAudioData() SEN_HILOGE("ConvertTransientEvent failed"); return Sensors::ERROR; } - std::vector intensityDatas; - // Processing intensity data, output parameters:intensityDatas - ret = DetectRmsIntensity(data, rmsILowerDelta, intensityDatas); - if (ret != Sensors::SUCCESS) { + std::vector intensityData; + // Processing intensity data, output parameters:intensityData + if (DetectRmsIntensity(data, rmsILowerDelta, intensityData) != Sensors::SUCCESS) { SEN_HILOGE("DetectRmsIntensity failed"); - return ret; + return Sensors::ERROR; } // Frequency detection std::vector rmseIntensityNorm; - for (size_t i = 0; i < intensityDatas.size(); i++) { - rmseIntensityNorm.push_back(intensityDatas[i].rmseIntensityNorm); + for (size_t i = 0; i < intensityData.size(); i++) { + rmseIntensityNorm.push_back(intensityData[i].rmseIntensityNorm); } - std::vector freqNorms = DetectFrequency(data, rmseIntensityNorm); - if (freqNorms.empty()) { + std::vector freqNorm = DetectFrequency(data, rmseIntensityNorm); + if (freqNorm.empty()) { SEN_HILOGE("DetectFrequency failed"); return Sensors::ERROR; } std::vector transientIndexes; - std::vector transientEventTimes; - // Output all Transient events, output parameters: transientIndex transientEventTimes - OutputTransientEvents(unionTransientEvents, intensityDatas, freqNorms, transientIndexes, transientEventTimes); + std::vector transientEventTime; + // Output all Transient events, output parameters: transientIndex transientEventTime + OutputTransientEvents(unionTransientEvents, intensityData, freqNorm, transientIndexes, transientEventTime); if (continuousEventExistFlag_) { std::vector transientEventFlags; for (size_t i = 0; i < unionTransientEvents.size(); i++) { transientEventFlags.push_back(unionTransientEvents[i].transientEventFlag); } - OutputAllContinuousEvent(intensityDatas, transientIndexes, freqNorms, transientEventFlags); + OutputAllContinuousEvent(intensityData, transientIndexes, freqNorm, transientEventFlags); } return Sensors::SUCCESS; } + int32_t VibrationConvertCore::ConvertAudioToHaptic(const AudioSetting &audioSetting, - const std::vector &audioDatas, std::vector &hapticEvents) + const std::vector &audioData, std::vector &hapticEvents) { - CALL_LOG_ENTER; - if (audioDatas.empty()) { - SEN_HILOGE("audioDatas is empty"); + if (audioData.empty()) { + SEN_HILOGE("audioData is empty"); return Sensors::ERROR; } audioSetting_ = audioSetting; - int32_t ret = ResampleAudioData(audioDatas); - if (ret != Sensors::SUCCESS) { + if (ResampleAudioData(audioData) != Sensors::SUCCESS) { SEN_HILOGE("ResampleAudioData failed"); - return ret; + return Sensors::ERROR; } if (GetAudioData() != Sensors::SUCCESS) { SEN_HILOGE("GetAudioData failed"); @@ -135,18 +133,17 @@ int32_t VibrationConvertCore::ConvertAudioToHaptic(const AudioSetting &audioSett return Sensors::SUCCESS; } -int32_t VibrationConvertCore::ResampleAudioData(const std::vector &srcDatas) +int32_t VibrationConvertCore::ResampleAudioData(const std::vector &srcData) { - if (srcDatas.empty()) { - SEN_HILOGE("srcDatas is empty"); + if (srcData.empty()) { + SEN_HILOGE("srcData is empty"); return Sensors::ERROR; } - size_t originDataSize = srcDatas.size(); - srcAudioDatas_.clear(); - srcAudioDatas_.reserve(originDataSize); + size_t originDataSize = srcData.size(); + srcAudioData_.clear(); for (size_t i = 0; i < (originDataSize - 1); i += RESAMPLE_MULTIPLE) { - srcAudioDatas_.push_back(srcDatas[i]); - srcAudioDatas_.push_back(srcDatas[i+1]); + srcAudioData_.push_back(srcData[i]); + srcAudioData_.push_back(srcData[i + 1]); } return Sensors::SUCCESS; } @@ -154,12 +151,12 @@ int32_t VibrationConvertCore::ResampleAudioData(const std::vector &srcDa std::vector VibrationConvertCore::PreprocessAudioData() { CALL_LOG_ENTER; - if (srcAudioDatas_.empty()) { + if (srcAudioData_.empty()) { SEN_HILOGE("invalid parameter"); return {}; } - std::vector absData = srcAudioDatas_; - std::vector dstData = srcAudioDatas_; + std::vector absData = srcAudioData_; + std::vector dstData = srcAudioData_; int32_t silence = 0; int32_t preClearEnd = 0; int32_t absDataSize = static_cast(absData.size()); @@ -199,29 +196,29 @@ std::vector VibrationConvertCore::PreprocessAudioData() return dstData; } -int32_t VibrationConvertCore::PreprocessParameter(const std::vector &datas, int32_t &onsetHopLength, +int32_t VibrationConvertCore::PreprocessParameter(const std::vector &data, int32_t &onsetHopLength, double &lowerDelta) { CALL_LOG_ENTER; - if (datas.empty()) { - SEN_HILOGE("datas is empty"); + if (data.empty()) { + SEN_HILOGE("data is empty"); return Sensors::ERROR; } - std::vector rmses = intensityProcessor_.GetRMS(datas, ENERGY_HOP_LEN, systemPara_.centerPaddingFlag); + std::vector rmse = intensityProcessor_.GetRMS(data, ENERGY_HOP_LEN, systemPara_.centerPaddingFlag); OnsetInfo onsetInfo; - if (onset_.CheckOnset(datas, NFFT, onsetHopLength, onsetInfo) != Sensors::SUCCESS) { + if (onset_.CheckOnset(data, NFFT, onsetHopLength, onsetInfo) != Sensors::SUCCESS) { SEN_HILOGE("CheckOnset Failed"); return Sensors::ERROR; } - std::vector newDrwIdxs = MapOnsetHop(onsetInfo.idxs, onsetHopLength); - lowerDelta = CalcRmsLowerData(datas.size(), rmses, newDrwIdxs); - double rmseMax = *std::max_element(rmses.begin(), rmses.end()); - size_t newDrwIdxLen = newDrwIdxs.size(); + std::vector newDrwIdx = MapOnsetHop(onsetInfo.idx, onsetHopLength); + lowerDelta = CalcRmsLowerData(data.size(), rmse, newDrwIdx); + double rmseMax = *std::max_element(rmse.begin(), rmse.end()); + size_t newDrwIdxLen = newDrwIdx.size(); bool continuousEventFlag = false; int32_t newOnsetHopLen = onsetHopLength; // Amplitude density is used to classify audio files, determine whether there are long events in the audio file, // and adjust the onset detection window - if (CalcOnsetHopLength(datas, rmseMax, newDrwIdxLen, continuousEventFlag, newOnsetHopLen) != Sensors::SUCCESS) { + if (CalcOnsetHopLength(data, rmseMax, newDrwIdxLen, continuousEventFlag, newOnsetHopLen) != Sensors::SUCCESS) { SEN_HILOGE("CalcOnsetHopLength failed"); return Sensors::ERROR; } @@ -230,7 +227,7 @@ int32_t VibrationConvertCore::PreprocessParameter(const std::vector &dat return Sensors::SUCCESS; } -std::vector VibrationConvertCore::MapOnsetHop(const std::vector &drwIdxs, int32_t onsetHopLength) +std::vector VibrationConvertCore::MapOnsetHop(const std::vector &drwIdx, int32_t onsetHopLength) { if (onsetHopLength == 0) { SEN_HILOGE("onsetHopLength is equal to 0"); @@ -242,29 +239,29 @@ std::vector VibrationConvertCore::MapOnsetHop(const std::vector(round(static_cast(idx) / coef))); } return newIdx; } -bool VibrationConvertCore::GetRmseLowerDelta(double lowerDelta, const std::vector &rmses, double &deltaByTime) +bool VibrationConvertCore::GetRmseLowerDelta(double lowerDelta, const std::vector &rmse, double &deltaByTime) { - int32_t rmseSize = static_cast(rmses.size()); - double rmseMax = *std::max_element(rmses.begin(), rmses.end()); - double rmseMin = *std::min_element(rmses.begin(), rmses.end()); + int32_t rmseSize = static_cast(rmse.size()); + double rmseMax = *std::max_element(rmse.begin(), rmse.end()); + double rmseMin = *std::min_element(rmse.begin(), rmse.end()); double rmseRange = rmseMax - rmseMin; int32_t i = 0; deltaByTime = lowerDelta; for (i = 0; i < rmseSize; ++i) { - if (rmses[i] > lowerDelta) { + if (rmse[i] > lowerDelta) { break; } } double rmsTimePerFrame = static_cast(ENERGY_HOP_LEN) / SAMPLE_RATE; int32_t j = rmseSize - 1; for (; j >= 0 ; j = (j - 1)) { - if (rmses[j] > lowerDelta) { + if (rmse[j] > lowerDelta) { break; } } @@ -279,12 +276,12 @@ bool VibrationConvertCore::GetRmseLowerDelta(double lowerDelta, const std::vecto return false; } -double VibrationConvertCore::CalcRmsLowerData(size_t dataSize, const std::vector &rmses, - const std::vector &newDrwIdxs) +double VibrationConvertCore::CalcRmsLowerData(size_t dataSize, const std::vector &rmse, + const std::vector &newDrwIdx) { double soundSizeDelta = 0.0; - double rmseMax = *std::max_element(rmses.begin(), rmses.end()); - double rmseMin = *std::min_element(rmses.begin(), rmses.end()); + double rmseMax = *std::max_element(rmse.begin(), rmse.end()); + double rmseMin = *std::min_element(rmse.begin(), rmse.end()); double rmseRange = rmseMax - rmseMin; if (rmseMax > RMSEMAX_THRESHOLD_HIGH) { soundSizeDelta = rmseRange * RMSE_LOWDELTA_RATIO_HIGH + rmseMin; @@ -294,11 +291,11 @@ double VibrationConvertCore::CalcRmsLowerData(size_t dataSize, const std::vector soundSizeDelta = rmseRange * RMSE_LOWDELTA_RATIO_LOW + rmseMin; } double lowerDelta = 0.0; - if (newDrwIdxs.size() > 0) { + if (newDrwIdx.size() > 0) { for (int32_t i = 0; i < RMSE_LOWDELTA_ITERATION_TIMES; i++) { - int32_t j = newDrwIdxs[0]; - lowerDelta = rmseRange * (RMSE_LOWDELTA_RATIO_HIGH - i * RMSE_LOWDELTA_RATIO_STEP ) + rmseMin; - if ((rmses[j] > lowerDelta) || (rmses[j + 1] > lowerDelta)) { + int32_t j = newDrwIdx[0]; + lowerDelta = rmseRange * (RMSE_LOWDELTA_RATIO_HIGH - i * RMSE_LOWDELTA_RATIO_STEP) + rmseMin; + if ((rmse[j] > lowerDelta) || (rmse[j + 1] > lowerDelta)) { break; } } @@ -310,7 +307,7 @@ double VibrationConvertCore::CalcRmsLowerData(size_t dataSize, const std::vector return audioDurationDelta; } double soundDurationDelta = soundSizeDelta; - bool findFlag = GetRmseLowerDelta(soundSizeDelta, rmses, soundDurationDelta); + bool findFlag = GetRmseLowerDelta(soundSizeDelta, rmse, soundDurationDelta); if (findFlag) { return soundDurationDelta; } @@ -320,17 +317,17 @@ double VibrationConvertCore::CalcRmsLowerData(size_t dataSize, const std::vector return lowerDelta; } -int32_t VibrationConvertCore::CalcOnsetHopLength(const std::vector &datas, double rmseMax, +int32_t VibrationConvertCore::CalcOnsetHopLength(const std::vector &data, double rmseMax, size_t newDrwIdxLen, bool &continuousEventFlag, int32_t &newOnsetHopLen) { - if (datas.empty()) { - SEN_HILOGE("Invalid parameter"); + if (data.empty()) { + SEN_HILOGE("invalid parameter"); return Sensors::ERROR; } int32_t longestCount = 0; double unzeroDensity = 0.0; bool continuousEventExistFlag = false; - int32_t ret = IsIncludeContinuoustEvent(datas, longestCount, unzeroDensity, continuousEventExistFlag); + int32_t ret = IsIncludeContinuoustEvent(data, longestCount, unzeroDensity, continuousEventExistFlag); if (ret != Sensors::SUCCESS) { SEN_HILOGE("IsIncludeContinuoustEvent failed"); return ret; @@ -347,57 +344,57 @@ int32_t VibrationConvertCore::CalcOnsetHopLength(const std::vector &data return Sensors::SUCCESS; } -std::vector VibrationConvertCore::GetLocalEnvelope(const std::vector &datas) +std::vector VibrationConvertCore::GetLocalEnvelope(const std::vector &data) { - if (datas.empty()) { + if (data.empty()) { SEN_HILOGE("invalid parameter"); return {}; } - std::vector envelopes = datas; - for (auto &elem : envelopes) { + std::vector envelope = data; + for (auto &elem : envelope) { elem = std::fabs(elem); } - double threshold = COEF * (*std::max_element(envelopes.begin(), envelopes.end())); - for (auto &elem : envelopes) { + double threshold = COEF * (*std::max_element(envelope.begin(), envelope.end())); + for (auto &elem : envelope) { if (elem < threshold) { elem = 0; } } - size_t dataSize = envelopes.size(); + size_t dataSize = envelope.size(); for (size_t i = 0; i < dataSize; ++i) { if ((i + LOCAL_ENVELOPE_MAX_LEN) > dataSize) { break; } std::vector segmentEnvelope; for (size_t j = i; j < (i + LOCAL_ENVELOPE_MAX_LEN); ++j) { - segmentEnvelope.push_back(envelopes[j]); + segmentEnvelope.push_back(envelope[j]); } - envelopes[i] = *std::max_element(segmentEnvelope.begin(), segmentEnvelope.end()); + envelope[i] = *std::max_element(segmentEnvelope.begin(), segmentEnvelope.end()); } - return envelopes; + return envelope; } -int32_t VibrationConvertCore::IsIncludeContinuoustEvent(const std::vector &datas, +int32_t VibrationConvertCore::IsIncludeContinuoustEvent(const std::vector &data, int32_t &longestCount, double &unzeroDensity, bool &isIncludeContinuoustEvent) { // envelope must be a non-negative number. - std::vector envelopes = GetLocalEnvelope(datas); - if (envelopes.empty()) { + std::vector envelope = GetLocalEnvelope(data); + if (envelope.empty()) { SEN_HILOGE("GetLocalEnvelope failed"); return Sensors::ERROR; } - size_t envelopeSize = envelopes.size(); + size_t envelopeSize = envelope.size(); size_t j = 0; size_t k = 0; int32_t atLeastCnt = 2 * ENERGY_HOP_LEN; int32_t adsrCompleteStatus = ADSR_BOUNDARY_STATUS_NONE; std::vector countList; for (size_t i = 0; i < envelopeSize; ++i) { - if ((envelopes[i] >= EPS_MIN) && (adsrCompleteStatus == ADSR_BOUNDARY_STATUS_NONE)) { + if ((envelope[i] >= EPS_MIN) && (adsrCompleteStatus == ADSR_BOUNDARY_STATUS_NONE)) { j = i; adsrCompleteStatus = ADSR_BOUNDARY_STATUS_ONE; } - if ((envelopes[i] < EPS_MIN) && (adsrCompleteStatus == ADSR_BOUNDARY_STATUS_ONE)) { + if ((envelope[i] < EPS_MIN) && (adsrCompleteStatus == ADSR_BOUNDARY_STATUS_ONE)) { k = i; adsrCompleteStatus = ADSR_BOUNDARY_STATUS_BOTH; } @@ -524,27 +521,27 @@ void VibrationConvertCore::EmplaceOnsetTime(bool flag, int32_t idx, double time, } } -int32_t VibrationConvertCore::ConvertTransientEvent(const std::vector &datas, int32_t onsetHopLength, +int32_t VibrationConvertCore::ConvertTransientEvent(const std::vector &data, int32_t onsetHopLength, std::vector &unionTransientEvents) { CALL_LOG_ENTER; - if (datas.empty()) { - SEN_HILOGE("datas is empty"); + if (data.empty()) { + SEN_HILOGE("data is empty"); return Sensors::ERROR; } // Using System Methods to Detect Onset - std::vector unionTransientValues = DetectOnset(datas, onsetHopLength); + std::vector unionTransientValues = DetectOnset(data, onsetHopLength); // Is the onset just a transient event std::vector onsetIdxs; for (size_t i = 0; i < unionTransientValues.size(); i++) { onsetIdxs.push_back(unionTransientValues[i].onsetIdx); } - std::vector transientEventFlags = IsTransientEvent(datas, onsetIdxs); + std::vector transientEventFlags = IsTransientEvent(data, onsetIdxs); for (size_t i = 0; i < unionTransientValues.size(); i++) { unionTransientValues[i].transientEventFlag = transientEventFlags[i]; } IsolatedEnvelopeInfo isolatedEnvelopeInfo; - int32_t ret = peakFinder_.ObtainTransientByAmplitude(datas, isolatedEnvelopeInfo); + int32_t ret = peakFinder_.ObtainTransientByAmplitude(data, isolatedEnvelopeInfo); if (ret != Sensors::SUCCESS) { SEN_HILOGE("ObtainTransientByAmplitude failed"); return ret; @@ -584,18 +581,18 @@ int32_t VibrationConvertCore::ConvertTransientEvent(const std::vector &d return Sensors::SUCCESS; } -std::vector VibrationConvertCore::DetectOnset(const std::vector &datas, +std::vector VibrationConvertCore::DetectOnset(const std::vector &data, int32_t onsetHopLength) { OnsetInfo onsetInfo; - if (onset_.CheckOnset(datas, NFFT, onsetHopLength, onsetInfo) != Sensors::SUCCESS) { + if (onset_.CheckOnset(data, NFFT, onsetHopLength, onsetInfo) != Sensors::SUCCESS) { SEN_HILOGE("CheckOnset Failed"); return {}; } - onsetInfo.idxs = MapOnsetHop(onsetInfo.idxs, onsetHopLength); + onsetInfo.idx = MapOnsetHop(onsetInfo.idx, onsetHopLength); std::vector newIdx; std::vector newTime; - UniqueIdx(onsetInfo.idxs, onsetInfo.times, newIdx, newTime); + UniqueIdx(onsetInfo.idx, onsetInfo.time, newIdx, newTime); int32_t minSkip = ONSET_MINSKIP_MAX; if (newIdx.size() > 1) { std::vector idxDiff; @@ -624,10 +621,10 @@ std::vector VibrationConvertCore::DetectOnset(const std::ve return unionTransientEvents; } -bool VibrationConvertCore::GetTransientEventFlag(const std::vector &datas, int32_t onsetIdx) +bool VibrationConvertCore::GetTransientEventFlag(const std::vector &data, int32_t onsetIdx) { - if (datas.empty()) { - SEN_HILOGE("datas is empty"); + if (data.empty()) { + SEN_HILOGE("data is empty"); return false; } int32_t partLen = ONSET_ONE_WIN; @@ -638,25 +635,25 @@ bool VibrationConvertCore::GetTransientEventFlag(const std::vector &data if (beginIdx < 0) { beginIdx = 0; } - int32_t dataSize = static_cast(datas.size()); + int32_t dataSize = static_cast(data.size()); if (endIdx >= dataSize) { endIdx = dataSize - 1; } - std::vector localDatas; + std::vector localData; for (int32_t i = beginIdx; i <= endIdx; ++i) { - localDatas.push_back(datas[i]); + localData.push_back(data[i]); } double unzeroDensity = 0.0; int32_t unzeroCount = 0; // Output parameter: unzeroCnt unzeroDensity - GetUnzeroCount(localDatas, unzeroCount, unzeroDensity); + GetUnzeroCount(localData, unzeroCount, unzeroDensity); return IsTransientEventFlag(unzeroCount, unzeroDensity); } -std::vector VibrationConvertCore::GetTransientEventFlags(const std::vector &datas, +std::vector VibrationConvertCore::GetTransientEventFlags(const std::vector &data, const std::vector &onsetIdxs) { - if (datas.empty() || (onsetIdxs.size() <= 1)) { + if (data.empty() || (onsetIdxs.size() <= 1)) { SEN_HILOGE("Invalid parameter"); return {}; } @@ -683,13 +680,13 @@ std::vector VibrationConvertCore::GetTransientEventFlags(const std::vector if ((i != 0) && (beginIdx < onsetIdxs[i - 1] * ENERGY_HOP_LEN)) { beginIdx = onsetIdxs[i - 1] * ENERGY_HOP_LEN; } - int32_t dataSize = static_cast(datas.size()); + int32_t dataSize = static_cast(data.size()); if (endIdx >= dataSize) { endIdx = dataSize - 1; } std::vector localData; for (int32_t j = beginIdx; j <= endIdx; ++j) { - localData.push_back(datas[i]); + localData.push_back(data[i]); } double unzeroDensity = 0.0; int32_t unzeroCount = 0; @@ -699,33 +696,33 @@ std::vector VibrationConvertCore::GetTransientEventFlags(const std::vector return transientEventFlags; } -std::vector VibrationConvertCore::IsTransientEvent(const std::vector &datas, +std::vector VibrationConvertCore::IsTransientEvent(const std::vector &data, const std::vector &onsetIdxs) { - if (datas.empty() || onsetIdxs.empty()) { - SEN_HILOGE("datas or onsetIdxs is empty"); + if (data.empty() || onsetIdxs.empty()) { + SEN_HILOGE("data or onsetIdxs is empty"); return {}; } std::vector transientEventFlags; if (onsetIdxs.size() == 1) { - bool transientEventFlag = GetTransientEventFlag(datas, onsetIdxs[0]); + bool transientEventFlag = GetTransientEventFlag(data, onsetIdxs[0]); transientEventFlags.push_back(transientEventFlag); } else { - transientEventFlags = GetTransientEventFlags(datas, onsetIdxs); + transientEventFlags = GetTransientEventFlags(data, onsetIdxs); } return transientEventFlags; } -void VibrationConvertCore::GetUnzeroCount(const std::vector &localDatas, +void VibrationConvertCore::GetUnzeroCount(const std::vector &localData, int32_t &unzeroCount, double &unzeroDensity) { - if (localDatas.empty()) { + if (localData.empty()) { unzeroCount = 0; unzeroDensity = 0; - SEN_HILOGE("localDatas is empty"); + SEN_HILOGE("localData is empty"); return; } - std::vector envelope = localDatas; + std::vector envelope = localData; for (auto &elem : envelope) { elem = std::fabs(elem); if (elem < LOWER_AMP) { @@ -791,43 +788,43 @@ void VibrationConvertCore::TranslateAnchorPoint(int32_t amplitudePeakPos, int32_ } } -std::vector VibrationConvertCore::DetectFrequency(const std::vector &datas, - const std::vector &rmseIntensityNorms) +std::vector VibrationConvertCore::DetectFrequency(const std::vector &data, + const std::vector &rmseIntensityNorm) { CALL_LOG_ENTER; - std::vector zcrs = frequencyEstimation_.GetZeroCrossingRate(datas, FRAME_LEN, ENERGY_HOP_LEN); - for (auto &elem : zcrs) { + std::vector zcr = frequencyEstimation_.GetZeroCrossingRate(data, FRAME_LEN, ENERGY_HOP_LEN); + for (auto &elem : zcr) { elem = elem * SAMPLE_RATE * F_HALF; } std::vector voiceSegmentFlag = peakFinder_.GetVoiceSegmentFlag(); - std::vector freqNorms; - frequencyEstimation_.FreqPostProcess(zcrs, voiceSegmentFlag, rmseIntensityNorms, freqNorms); - return freqNorms; + std::vector freqNorm; + frequencyEstimation_.FreqPostProcess(zcr, voiceSegmentFlag, rmseIntensityNorm, freqNorm); + return freqNorm; } -int32_t VibrationConvertCore::DetectRmsIntensity(const std::vector &datas, double rmsILowerDelta, - std::vector &intensityDatas) +int32_t VibrationConvertCore::DetectRmsIntensity(const std::vector &data, double rmsILowerDelta, + std::vector &intensityData) { CALL_LOG_ENTER; - std::vector rmses = intensityProcessor_.GetRMS(datas, ENERGY_HOP_LEN, systemPara_.centerPaddingFlag); - if (rmses.empty()) { - SEN_HILOGE("rmses is empty"); + std::vector rmse = intensityProcessor_.GetRMS(data, ENERGY_HOP_LEN, systemPara_.centerPaddingFlag); + if (rmse.empty()) { + SEN_HILOGE("rmse is empty"); return Sensors::ERROR; } std::vector rmseTime; double rmsTimePerFrame = static_cast(ENERGY_HOP_LEN) / SAMPLE_RATE; - for (auto elem : rmses) { + for (auto elem : rmse) { rmseTime.push_back(elem * rmsTimePerFrame); } std::vector rmseBand; std::vector rmseNorm; - if (intensityProcessor_.RmseNormalize(rmses, rmsILowerDelta, rmseBand, rmseNorm) != Sensors::SUCCESS) { + if (intensityProcessor_.RmseNormalize(rmse, rmsILowerDelta, rmseBand, rmseNorm) != Sensors::SUCCESS) { SEN_HILOGE("RmseNormalize failed"); return Sensors::ERROR; } - std::vector rmseTimeNorms = StartTimeNormalize(rmses.size()); - std::vector ampLin = intensityProcessor_.VolumeInLinary(datas, ENERGY_HOP_LEN); - std::vector ampDb = intensityProcessor_.VolumeInDB(datas, ENERGY_HOP_LEN); + std::vector rmseTimeNorm = StartTimeNormalize(rmse.size()); + std::vector ampLin = intensityProcessor_.VolumeInLinary(data, ENERGY_HOP_LEN); + std::vector ampDb = intensityProcessor_.VolumeInDB(data, ENERGY_HOP_LEN); double ampDbMax = *std::max_element(ampDb.begin(), ampDb.end()); bool intensityUseLinearFlag = systemPara_.intensityUseLinearFlag; if (!intensityUseLinearFlag && (ampDbMax > AMPLITUDE_DB_MAX)) { @@ -835,8 +832,8 @@ int32_t VibrationConvertCore::DetectRmsIntensity(const std::vector &data rmseNorm[i] = ampDb[i] * DB_ZOOM_COEF; } } - for (size_t i = 0; i < rmses.size(); i++) { - intensityDatas.push_back(IntensityData(rmses[i], rmseTime[i], rmseBand[i], rmseNorm[i], rmseTimeNorms[i])); + for (size_t i = 0; i < rmse.size(); i++) { + intensityData.push_back(IntensityData(rmse[i], rmseTime[i], rmseBand[i], rmseNorm[i], rmseTimeNorm[i])); } return Sensors::SUCCESS; } @@ -844,18 +841,18 @@ int32_t VibrationConvertCore::DetectRmsIntensity(const std::vector &data std::vector VibrationConvertCore::StartTimeNormalize(int32_t rmseLen) { CALL_LOG_ENTER; - std::vector rmseTimeNorms; + std::vector rmseTimeNorm; double startTime = 0.0; for (int32_t i = 0; i < rmseLen; ++i) { - rmseTimeNorms.push_back(startTime); + rmseTimeNorm.push_back(startTime); startTime += FRAME_DURATION; } - return rmseTimeNorms; + return rmseTimeNorm; } void VibrationConvertCore::OutputTransientEvents(const std::vector &unionTransientEvents, - const std::vector &intensityDatas, const std::vector &freqNorms, - std::vector &transientIndexs, std::vector &transientEventTimes) + const std::vector &intensityData, const std::vector &freqNorm, + std::vector &transientIndex, std::vector &transientEventTime) { CALL_LOG_ENTER; bool onsetBacktrackFlag = systemPara_.onsetBacktrackFlag; @@ -864,50 +861,50 @@ void VibrationConvertCore::OutputTransientEvents(const std::vector &onsetTimes, - const std::vector &intensityDatas, const std::vector &freqNorms, - std::vector &transientIndexs, std::vector &transientEventTimes) + const std::vector &intensityData, const std::vector &freqNorm, + std::vector &transientIndex, std::vector &transientEventTime) { double rmsTimePerFrame = static_cast(ENERGY_HOP_LEN) / SAMPLE_RATE; for (size_t i = 0; i < onsetTimes.size(); ++i) { bool flag = false; size_t j = 0; - while (j < intensityDatas.size()) { - if ((onsetTimes[i] >= intensityDatas[j].rmseTimeNorm) && - (onsetTimes[i] < (intensityDatas[j].rmseTimeNorm + rmsTimePerFrame))) { + while (j < intensityData.size()) { + if ((onsetTimes[i] >= intensityData[j].rmseTimeNorm) && + (onsetTimes[i] < (intensityData[j].rmseTimeNorm + rmsTimePerFrame))) { flag = true; break; } ++j; } if (flag) { - auto it = std::find(transientIndexs.begin(), transientIndexs.end(), j); - if (it == transientIndexs.end()) { - size_t endIndex = std::min(j + MIN_SKIP, intensityDatas.size() - 1); + auto it = std::find(transientIndex.begin(), transientIndex.end(), j); + if (it == transientIndex.end()) { + size_t endIndex = std::min(j + MIN_SKIP, intensityData.size() - 1); // get max index. size_t maxIndex = j; - double maxRmseEnvelope = intensityDatas[j].rmseEnvelope; + double maxRmseEnvelope = intensityData[j].rmseEnvelope; for (size_t k = (j + 1); k < endIndex; k++) { - if (intensityDatas[k].rmseEnvelope > maxRmseEnvelope) { - maxRmseEnvelope = intensityDatas[k].rmseEnvelope; + if (intensityData[k].rmseEnvelope > maxRmseEnvelope) { + maxRmseEnvelope = intensityData[k].rmseEnvelope; maxIndex = k; } } double onsetTimeNorm = static_cast(round(SAMPLE_IN_MS * onsetTimes[i]) / SAMPLE_IN_MS); - transientEventTimes.push_back(onsetTimeNorm); - transientIndexs.push_back(j); - AddTransientEventData(TransientEvent(onsetTimeNorm, intensityDatas[maxIndex].rmseIntensityNorm, - freqNorms[maxIndex])); + transientEventTime.push_back(onsetTimeNorm); + transientIndex.push_back(j); + AddTransientEventData(TransientEvent(onsetTimeNorm, intensityData[maxIndex].rmseIntensityNorm, + freqNorm[maxIndex])); } } } @@ -925,16 +922,16 @@ void VibrationConvertCore::AddTransientEventData(TransientEvent transientEvent) } void VibrationConvertCore::GetIdex(const UnionTransientEvent &unionTransientEvent, - const std::vector &intensityDatas) + const std::vector &intensityData) { // get max index. size_t beginIndex = unionTransientEvent.onsetIdx; size_t endIndex = beginIndex + onsetMinSkip_; size_t maxIndex = beginIndex; - double maxRmseEnvelope = intensityDatas[beginIndex].rmseEnvelope; + double maxRmseEnvelope = intensityData[beginIndex].rmseEnvelope; for (size_t k = (beginIndex + 1); k < endIndex; k++) { - if (intensityDatas[k].rmseEnvelope > maxRmseEnvelope) { - maxRmseEnvelope = intensityDatas[k].rmseEnvelope; + if (intensityData[k].rmseEnvelope > maxRmseEnvelope) { + maxRmseEnvelope = intensityData[k].rmseEnvelope; maxIndex = k; } } @@ -946,10 +943,10 @@ void VibrationConvertCore::GetIdex(const UnionTransientEvent &unionTransientEven beginIndex = fromIndex; endIndex = unionTransientEvent.onsetIdx + 1; size_t minIndex = beginIndex; - double minRmseEnvelope = intensityDatas[beginIndex].rmseEnvelope; + double minRmseEnvelope = intensityData[beginIndex].rmseEnvelope; for (size_t k = (beginIndex + 1); k < endIndex; k++) { - if (intensityDatas[k].rmseEnvelope < minRmseEnvelope) { - minRmseEnvelope = intensityDatas[k].rmseEnvelope; + if (intensityData[k].rmseEnvelope < minRmseEnvelope) { + minRmseEnvelope = intensityData[k].rmseEnvelope; minIndex = k; } } @@ -959,73 +956,73 @@ void VibrationConvertCore::GetIdex(const UnionTransientEvent &unionTransientEven } void VibrationConvertCore::OutputTransientEventsAlign(const std::vector &unionTransientEvents, - const std::vector &intensityDatas, const std::vector &freqNorms, - std::vector &transientIndexs, std::vector &transientEventTimes) + const std::vector &intensityData, const std::vector &freqNorm, + std::vector &transientIndex, std::vector &transientEventTime) { size_t size = unionTransientEvents.size(); for (size_t i = 1; i < size; ++i) { if ((unionTransientEvents[i].onsetIdx != 0) && (unionTransientEvents[i - 1].onsetIdx == (unionTransientEvents[i].onsetIdx - 1))) { - auto it = find(transientIndexs.begin(), transientIndexs.end(), unionTransientEvents[i].onsetIdx); - if (it == transientIndexs.end()) { + auto it = find(transientIndex.begin(), transientIndex.end(), unionTransientEvents[i].onsetIdx); + if (it == transientIndex.end()) { int32_t index = unionTransientEvents[i].onsetIdx; - transientEventTimes.push_back(intensityDatas[index].rmseTimeNorm); - transientIndexs.push_back(index); - AddTransientEventData(TransientEvent(intensityDatas[index].rmseTimeNorm, - intensityDatas[index].rmseIntensityNorm, freqNorms[index])); + transientEventTime.push_back(intensityData[index].rmseTimeNorm); + transientIndex.push_back(index); + AddTransientEventData(TransientEvent(intensityData[index].rmseTimeNorm, + intensityData[index].rmseIntensityNorm, freqNorm[index])); continue; } } - GetIdex(unionTransientEvents[i], intensityDatas); - auto it = find(transientIndexs.begin(), transientIndexs.end(), minIndex); - if (it == transientIndexs.end()) { - transientEventTimes.push_back(intensityDatas[minIndex].rmseTimeNorm); - transientIndexs.push_back(minIndex); - AddTransientEventData(TransientEvent(intensityDatas[minIndex].rmseTimeNorm, - intensityDatas[maxIndex].rmseIntensityNorm, freqNorms[maxIndex])); + GetIdex(unionTransientEvents[i], intensityData); + auto it = find(transientIndex.begin(), transientIndex.end(), minIndex); + if (it == transientIndex.end()) { + transientEventTime.push_back(intensityData[minIndex].rmseTimeNorm); + transientIndex.push_back(minIndex); + AddTransientEventData(TransientEvent(intensityData[minIndex].rmseTimeNorm, + intensityData[maxIndex].rmseIntensityNorm, freqNorm[maxIndex])); } } } void VibrationConvertCore::OutputTransientEventsDirect(const std::vector &unionTransientEvents, - const std::vector &intensityDatas, const std::vector &freqNorms, - std::vector &transientIndexs, std::vector &transientEventTimes) + const std::vector &intensityData, const std::vector &freqNorm, + std::vector &transientIndex, std::vector &transientEventTime) { size_t size = unionTransientEvents.size(); for (size_t i = 0; i < size; ++i) { - auto it = find(transientIndexs.begin(), transientIndexs.end(), unionTransientEvents[i].onsetIdx); - if (it == transientIndexs.end()) { + auto it = find(transientIndex.begin(), transientIndex.end(), unionTransientEvents[i].onsetIdx); + if (it == transientIndex.end()) { int32_t index = unionTransientEvents[i].onsetIdx; - transientEventTimes.push_back(intensityDatas[index].rmseTimeNorm); - transientIndexs.push_back(index); - AddTransientEventData(TransientEvent(intensityDatas[index].rmseTimeNorm, - intensityDatas[index].rmseIntensityNorm, freqNorms[index])); + transientEventTime.push_back(intensityData[index].rmseTimeNorm); + transientIndex.push_back(index); + AddTransientEventData(TransientEvent(intensityData[index].rmseTimeNorm, + intensityData[index].rmseIntensityNorm, freqNorm[index])); } } } -void VibrationConvertCore::OutputAllContinuousEvent(const std::vector &intensityDatas, - const std::vector transientIndexs, const std::vector &freqNorms, +void VibrationConvertCore::OutputAllContinuousEvent(const std::vector &intensityData, + const std::vector transientIndex, const std::vector &freqNorm, const std::vector &transientEventFlags) { CALL_LOG_ENTER; if (!systemPara_.splitSegmentFlag) { - OutputAllContinuousEventByUnseg(intensityDatas, transientIndexs, freqNorms, transientEventFlags); + OutputAllContinuousEventByUnseg(intensityData, transientIndex, freqNorm, transientEventFlags); } } -void VibrationConvertCore::OutputAllContinuousEventByUnseg(const std::vector &intensityDatas, - const std::vector transientIndexs, const std::vector &freqNorms, +void VibrationConvertCore::OutputAllContinuousEventByUnseg(const std::vector &intensityData, + const std::vector transientIndex, const std::vector &freqNorm, const std::vector &transientEventFlags) { std::vector rmseTimeNorm; - for (size_t i = 0; i < intensityDatas.size(); i++) { - rmseTimeNorm.push_back(intensityDatas[i].rmseTimeNorm); + for (size_t i = 0; i < intensityData.size(); i++) { + rmseTimeNorm.push_back(intensityData[i].rmseTimeNorm); } std::vector times; std::vector durations; FillDefaultContinuousEvents(rmseTimeNorm, times, durations); - int32_t ret = InsertTransientEvent(rmseTimeNorm, transientIndexs, transientEventFlags, + int32_t ret = InsertTransientEvent(rmseTimeNorm, transientIndex, transientEventFlags, times, durations); if (ret != Sensors::SUCCESS) { SEN_HILOGE("InsertTransientEvent failed"); @@ -1034,46 +1031,46 @@ void VibrationConvertCore::OutputAllContinuousEventByUnseg(const std::vector continuousEvents; for (size_t i = 0; i < times.size(); i++) { continuousEvents.push_back(ContinuousEvent(times[i], durations[i], - intensityDatas[i].rmseIntensityNorm, freqNorms[i])); + intensityData[i].rmseIntensityNorm, freqNorm[i])); } MergeContinuousEvents(continuousEvents); } -void VibrationConvertCore::FillDefaultContinuousEvents(const std::vector &rmseTimeNorms, +void VibrationConvertCore::FillDefaultContinuousEvents(const std::vector &rmseTimeNorm, std::vector ×, std::vector &durations) { double value = 0.0; - for (size_t i = 0; i < rmseTimeNorms.size(); ++i) { + for (size_t i = 0; i < rmseTimeNorm.size(); ++i) { times.push_back(value); durations.push_back(FRAME_DURATION); value += FRAME_DURATION; } } -int32_t VibrationConvertCore::InsertTransientEvent(const std::vector &rmseTimeNorms, - const std::vector &transientIndexs, const std::vector &transientEventFlags, +int32_t VibrationConvertCore::InsertTransientEvent(const std::vector &rmseTimeNorm, + const std::vector &transientIndex, const std::vector &transientEventFlags, std::vector ×, std::vector &durations) { - if ((times.empty()) || (transientIndexs.size() != transientEventFlags.size())) { + if ((times.empty()) || (transientIndex.size() != transientEventFlags.size())) { SEN_HILOGE("times is empty"); return Sensors::ERROR; } for (size_t i = 0; i < (times.size() - 1); ++i) { - auto it = find(transientIndexs.begin(), transientIndexs.end(), i); - if (it == transientIndexs.end()) { + auto it = find(transientIndex.begin(), transientIndex.end(), i); + if (it == transientIndex.end()) { continue; } - int32_t index = it - transientIndexs.begin(); + int32_t index = it - transientIndex.begin(); double preDuration = 0.0; if (i > 0) { preDuration = durations[i - 1]; } double transientTime = transientEvents_[index].time; - double preInterDuration = transientTime - rmseTimeNorms[i]; - double postInterDuration = (rmseTimeNorms[i] + FRAME_DURATION) - (transientTime + TRANSIENT_DURATION_DEFAULT); + double preInterDuration = transientTime - rmseTimeNorm[i]; + double postInterDuration = (rmseTimeNorm[i] + FRAME_DURATION) - (transientTime + TRANSIENT_DURATION_DEFAULT); if (IsGreatOrEqual(preInterDuration, CONTINOUS_MIN_DURATION)) { - times[i] = rmseTimeNorms[i]; + times[i] = rmseTimeNorm[i]; durations[i] = preInterDuration; if (IsLessNotEqual(postInterDuration, CONTINOUS_MIN_DURATION)) { times[i + 1] = transientTime + TRANSIENT_DURATION_DEFAULT; @@ -1137,8 +1134,10 @@ void VibrationConvertCore::CombinateContinuousEvents(const std::vector 0) && (std::abs(slope2 - slope1) < slopDelta)) { ++mergeCnt; ++begIdx; @@ -1184,8 +1183,9 @@ void VibrationConvertCore::MergeContinuousEvents(const std::vector - -namespace OHOS { -namespace Sensors { -std::vector AudioSrcDatas = { - -1.07167597889201E-05, - 4.03729791287332E-06, - -7.82590905146207E-06, - 3.05969280134377E-07, - 7.12184328222065E-06, - -3.03215460917272E-06, - 9.08821220946265E-06, - 6.13942620475427E-06, - -0.000012067862371623, - -7.65803724789293E-06, - 1.38535085625335E-06, - -2.61832525438876E-07, - -1.25710883480678E-07, - 2.61069516227507E-07, - 0.00393714383244514, - 0.0 -}; -} // namespace Sensors -} // namespace OHOS -#endif // UT_TEST_DATA_H \ No newline at end of file diff --git a/vibration_convert/core/native/test/unittest/generate_json_test.cpp b/vibration_convert/core/native/test/unittest/generate_json_test.cpp deleted file mode 100644 index 67bdca0981a4f0b2471b9717654f9177f01b36e7..0000000000000000000000000000000000000000 --- a/vibration_convert/core/native/test/unittest/generate_json_test.cpp +++ /dev/null @@ -1,107 +0,0 @@ -/* - * 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 - * - * 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_utils.h" -#include "data.h" -#include "generate_vibration_json_file.h" -#include "sensor_log.h" -#include "sensors_errors.h" -#include "utils.h" -#include "vibration_convert_core.h" -#include "vibration_convert_type.h" - -#undef LOG_TAG -#define LOG_TAG "GenerateJsonFileTest" - -namespace OHOS { -namespace Sensors { -using namespace testing::ext; -using namespace OHOS::HiviewDFX; - -class GenerateJsonFileTest : public testing::Test { -public: - static void SetUpTestCase(); - static void TearDownTestCase(); - void SetUp(); - void TearDown(); -}; - -void GenerateJsonFileTest::SetUpTestCase() {} - -void GenerateJsonFileTest::TearDownTestCase() {} - -void GenerateJsonFileTest::SetUp() {} - -void GenerateJsonFileTest::TearDown() {} - -HWTEST_F(GenerateJsonFileTest, GenerateJsonFileTest_001, TestSize.Level1) -{ - HapticEvent event = { - .tag = EVENT_TAG_TRANSIENT, - .startTime = 10, - .duration = 30, - .intensity = 90, - .frequency = 100 - }; - HapticEvent event1 = { - .tag = EVENT_TAG_CONTINUOUS, - .startTime = 40, - .duration = 56, - .intensity = 90, - .frequency = 100 - }; - HapticEvent event2 = { - .tag = EVENT_TAG_CONTINUOUS, - .startTime = 97, - .duration = 86, - .intensity = 77, - .frequency = 80 - }; - HapticEvent event3 = { - .tag = EVENT_TAG_TRANSIENT, - .startTime = 200, - .duration = 30, - .intensity = 44, - .frequency = 55 - }; - std::vector vtEvents; - vtEvents.push_back(event); - vtEvents.push_back(event1); - vtEvents.push_back(event2); - vtEvents.push_back(event3); - OHOS::Sensors::GenerateVibrationJsonFile generateJson; - int32_t ret = generateJson.GenerateJsonFile(vtEvents); - EXPECT_EQ(ret, 0); -} -HWTEST_F(GenerateJsonFileTest, GenerateJsonFileTest_002, TestSize.Level1) -{ - AudioSetting audioSetting; - audioSetting.transientDetection = 30; - audioSetting.intensityTreshold = 30; - audioSetting.frequencyTreshold = 50; - audioSetting.frequencyMaxValue = 80; - audioSetting.frequencyMinValue = 20; - std::vector data = AudioSrcDatas; - std::vector vtEvents = {}; - VibrationConvertCore vibrationConvertCore; - int32_t ret = vibrationConvertCore.ConvertAudioToHaptic(audioSetting, data, vtEvents); - EXPECT_EQ(ret, 0); -} -} // namespace Sensors -} // namespace OHOS \ No newline at end of file diff --git a/vibration_convert/core/utils/include/utils.h b/vibration_convert/core/utils/include/utils.h index e51fa0562198c90700dbbebf7401e6103d75d2b9..fa614ce23f9c1642da22c98a4757c4663e54d7c4 100644 --- a/vibration_convert/core/utils/include/utils.h +++ b/vibration_convert/core/utils/include/utils.h @@ -55,10 +55,10 @@ enum WindowType { WND_TYPE_HANNING = 3, }; -enum FilterMethod{ - LOW_RESONANT_FILTER = 1, - HIGH_RESONANT_FILTER = 2, - BAND_PASS_FILTER = 3, +enum FilterMethod { + LOW_RESONANT_FILTER = 1, + HIGH_RESONANT_FILTER = 2, + BAND_PASS_FILTER = 3, }; bool IsPowerOfTwo(uint32_t x); @@ -182,12 +182,6 @@ inline bool IsEqual(const T& left, const T& right) return (std::abs(left - right) <= std::numeric_limits::epsilon()); } -template -decltype(auto) MakeSharedArray(size_t size) -{ - return std::shared_ptr(new T[size], std::default_delete()); -} - inline double ConvertHtkMel(double frequencies) { double mels = (frequencies - MIN_F) / FSP; diff --git a/vibration_convert/core/utils/src/utils.cpp b/vibration_convert/core/utils/src/utils.cpp index 12d09759642e8ba5724efd9b4ef88c9cd89b72e7..71e9ee6a2abf9c4df36ff1d0ec0f0ad030fd8796 100644 --- a/vibration_convert/core/utils/src/utils.cpp +++ b/vibration_convert/core/utils/src/utils.cpp @@ -33,7 +33,7 @@ namespace OHOS { namespace Sensors { -namespace{ +namespace { constexpr double PERCENTAGE_RANGE = 100.0; constexpr int32_t VOICE_MIN_INTENSITY_NORM = 25; constexpr size_t MAX_SIZE = 26460000; @@ -77,7 +77,7 @@ std::vector TransposeMatrix(size_t rows, const std::vector &valu size_t valuesSize = values.size(); SEN_HILOGD("valuesSize:%{public}zu", valuesSize); if ((rows == 0) || (valuesSize == 0) || (valuesSize > MAX_SIZE)) { - SEN_HILOGE("Parameter is invalid"); + SEN_HILOGE("Parameter error"); return {}; } std::vector dst(valuesSize, 0.0); @@ -100,7 +100,7 @@ int32_t UniqueIdx(const std::vector &idx, const std::vector &ti { CALL_LOG_ENTER; if (idx.size() != time.size()) { - SEN_HILOGE("Size of idx and time vectors not equal"); + SEN_HILOGE("size of idx and time vectors not equal"); return Sensors::ERROR; } int32_t oldIdxLen = static_cast(idx.size()); @@ -123,7 +123,7 @@ int32_t UniqueIdx(const std::vector &idx, const std::vector &ti ++i; } if (idxLen != oldIdxLen) { - SEN_HILOGI("idx unique process"); + SEN_HILOGI("Idx unique process"); } return Sensors::SUCCESS; }