diff --git a/frameworks/js/napi/BUILD.gn b/frameworks/js/napi/BUILD.gn index b6f97fdd62a3c0d30b1bed6d9ccb2d1ea1ae9ced..09fcc71c759f59890fa1ac85217bffe567ea17ae 100644 --- a/frameworks/js/napi/BUILD.gn +++ b/frameworks/js/napi/BUILD.gn @@ -37,7 +37,10 @@ ohos_shared_library("libsensor") { "src/sensor_napi_utils.cpp", "src/sensor_system_js.cpp", ] - deps = [ "$SUBSYSTEM_DIR/frameworks/native:sensor_interface_native" ] + deps = [ + "$SUBSYSTEM_DIR/frameworks/native:sensor_interface_native", + "$SUBSYSTEM_DIR/utils/common:libsensor_utils", + ] external_deps = [ "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", diff --git a/frameworks/js/napi/include/async_callback_info.h b/frameworks/js/napi/include/async_callback_info.h index fe9b012a30b9b16cc65d1a5acf79805695df7c86..00de47486980571e8ccd7675bf0118f43b80991d 100644 --- a/frameworks/js/napi/include/async_callback_info.h +++ b/frameworks/js/napi/include/async_callback_info.h @@ -72,7 +72,7 @@ struct RationMatrixData { float inclinationMatrix[THREE_DIMENSIONAL_MATRIX_LENGTH]; }; -struct SensorData { +struct CallbackSensorData { int32_t sensorTypeId; uint32_t dataLength; float data[DATA_LENGTH]; @@ -86,7 +86,7 @@ struct ReserveData { }; union CallbackData { - SensorData sensorData; + CallbackSensorData sensorData; GeomagneticData geomagneticData; RationMatrixData rationMatrixData; ReserveData reserveData; diff --git a/frameworks/native/include/sensor_agent_proxy.h b/frameworks/native/include/sensor_agent_proxy.h index 702b43d35933f3d11a5b27b90e7b996a69236356..556756ad5603f5651cc61bc6a21959988cc98d8b 100644 --- a/frameworks/native/include/sensor_agent_proxy.h +++ b/frameworks/native/include/sensor_agent_proxy.h @@ -42,6 +42,7 @@ public: int32_t UnsubscribeSensor(int32_t sensorId, const SensorUser *user); int32_t SetMode(int32_t sensorId, const SensorUser *user, int32_t mode); int32_t SetOption(int32_t sensorId, const SensorUser *user, int32_t option); + void SetIsChannelCreated(bool isChannelCreated); int32_t GetAllSensors(SensorInfo **sensorInfo, int32_t *count) const; int32_t SuspendSensors(int32_t pid); int32_t ResumeSensors(int32_t pid); @@ -56,7 +57,7 @@ private: int32_t DestroySensorDataChannel(); int32_t ConvertSensorInfos() const; void ClearSensorInfos() const; - std::set GetSubscribeUser(int32_t sensorId); + std::set GetSubscribeUserCallback(int32_t sensorId); static std::recursive_mutex subscribeMutex_; static std::mutex chanelMutex_; OHOS::sptr dataChannel_ = nullptr; @@ -70,4 +71,4 @@ private: #define SENSOR_AGENT_IMPL OHOS::DelayedSingleton::GetInstance() } // namespace Sensors } // namespace OHOS -#endif // endif SENSOR_PROXY_H \ No newline at end of file +#endif // endif SENSOR_PROXY_H \ No newline at end of file diff --git a/frameworks/native/include/sensor_service_client.h b/frameworks/native/include/sensor_service_client.h index 47033caebb36652932ef32f6c69f7c7d414e35f5..2e584ec0a5b8638f52c421a466b67aeb8151981f 100755 --- a/frameworks/native/include/sensor_service_client.h +++ b/frameworks/native/include/sensor_service_client.h @@ -60,6 +60,7 @@ private: void UpdateSensorInfoMap(int32_t sensorId, int64_t samplingPeriod, int64_t maxReportDelay); void DeleteSensorInfoItem(int32_t sensorId); int32_t CreateSocketChannel(); + void ReenableSensor(); std::mutex clientMutex_; sptr serviceDeathObserver_ = nullptr; sptr sensorServer_ = nullptr; @@ -76,4 +77,4 @@ private: }; } // namespace Sensors } // namespace OHOS -#endif // SENSOR_SERVICE_CLIENT_H \ No newline at end of file +#endif // SENSOR_SERVICE_CLIENT_H \ No newline at end of file diff --git a/frameworks/native/src/fd_listener.cpp b/frameworks/native/src/fd_listener.cpp index 4b8cbe1df1645dba1e690588588004653c428ce3..174fc169a68ef49dfca4c461b3a43bbddf8bd77a 100644 --- a/frameworks/native/src/fd_listener.cpp +++ b/frameworks/native/src/fd_listener.cpp @@ -28,7 +28,7 @@ namespace Sensors { using namespace OHOS::AppExecFwk; namespace { constexpr int32_t MAX_DATA_BUF_SIZE = 256; -} // namespace +} void FdListener::SetChannel(SensorDataChannel *channel) { diff --git a/frameworks/native/src/geomagnetic_field.cpp b/frameworks/native/src/geomagnetic_field.cpp index e0ac5c49a1ff8bf012d72a772cd84446b3cecb8a..5b96e7667c624dcb72f90111f6c1941c0df0c819 100644 --- a/frameworks/native/src/geomagnetic_field.cpp +++ b/frameworks/native/src/geomagnetic_field.cpp @@ -111,7 +111,7 @@ std::vector> polynomialsDerivative(GAUSSIAN_COEFFICIENT_DIMEN std::vector relativeRadiusPower(GAUSSIAN_COEFFICIENT_DIMENSION + 2); std::vector sinMLongitude(GAUSSIAN_COEFFICIENT_DIMENSION); std::vector cosMLongitude(GAUSSIAN_COEFFICIENT_DIMENSION); -} // namespace +} GeomagneticField::GeomagneticField(float latitude, float longitude, float altitude, int64_t timeMillis) { diff --git a/frameworks/native/src/sensor_agent_proxy.cpp b/frameworks/native/src/sensor_agent_proxy.cpp index 0cdfbe2d2f4b387943ab5374da6324dd4287ade8..53b1715ea2632ac5a6b72f362f0080e0f5f30daf 100644 --- a/frameworks/native/src/sensor_agent_proxy.cpp +++ b/frameworks/native/src/sensor_agent_proxy.cpp @@ -17,6 +17,7 @@ #include +#include "print_sensor_data.h" #include "securec.h" #include "sensor_errors.h" #include "sensor_service_client.h" @@ -48,7 +49,7 @@ SensorAgentProxy::~SensorAgentProxy() ClearSensorInfos(); } -std::set SensorAgentProxy::GetSubscribeUser(int32_t sensorId) +std::set SensorAgentProxy::GetSubscribeUserCallback(int32_t sensorId) { std::lock_guard subscribeLock(subscribeMutex_); auto iter = subscribeMap_.find(sensorId); @@ -56,7 +57,14 @@ std::set SensorAgentProxy::GetSubscribeUser(int32_t sensorId SEN_HILOGE("Sensor is not subscribed"); return {}; } - return {iter->second}; + std::set callback; + for (const auto &it : iter->second) { + auto ret = callback.insert(it->callback); + if (!ret.second) { + SEN_HILOGE("callback insert fail"); + } + } + return callback; } void SensorAgentProxy::HandleSensorData(SensorEvent *events, @@ -70,16 +78,22 @@ void SensorAgentProxy::HandleSensorData(SensorEvent *events, SensorEvent eventStream; for (int32_t i = 0; i < num; ++i) { eventStream = events[i]; - std::set users = GetSubscribeUser(eventStream.sensorTypeId); - for (const auto &user : users) { - CHKPV(user); - RecordSensorCallback fun = user->callback; - CHKPV(fun); - fun(&eventStream); + auto callbacks = GetSubscribeUserCallback(eventStream.sensorTypeId); + for (const auto &callback : callbacks) { + CHKPV(callback); + callback(&eventStream); + PrintSensorData::GetInstance().ControlSensorClientPrint(callback, eventStream); } } } +void SensorAgentProxy::SetIsChannelCreated(bool isChannelCreated) +{ + CALL_LOG_ENTER; + std::lock_guard chanelLock(chanelMutex_); + isChannelCreated_ = isChannelCreated; +} + int32_t SensorAgentProxy::CreateSensorDataChannel() { CALL_LOG_ENTER; @@ -245,6 +259,9 @@ int32_t SensorAgentProxy::SubscribeSensor(int32_t sensorId, const SensorUser *us if (!status.second) { SEN_HILOGD("User has been subscribed"); } + if (PrintSensorData::GetInstance().IsContinuousType(sensorId)) { + PrintSensorData::GetInstance().SavePrintUserInfo(user->callback); + } return OHOS::Sensors::SUCCESS; } @@ -278,6 +295,9 @@ int32_t SensorAgentProxy::UnsubscribeSensor(int32_t sensorId, const SensorUser * if (unsubscribeSet.empty()) { unsubscribeMap_.erase(sensorId); } + if (PrintSensorData::GetInstance().IsContinuousType(sensorId)) { + PrintSensorData::GetInstance().RemovePrintUserInfo(user->callback); + } return OHOS::Sensors::SUCCESS; } diff --git a/frameworks/native/src/sensor_service_client.cpp b/frameworks/native/src/sensor_service_client.cpp index 7d6ceeecaf068f56a755338116f88d5c5b636a71..cb2aa8913017a6d77b9da64171b208d6428f4ba0 100644 --- a/frameworks/native/src/sensor_service_client.cpp +++ b/frameworks/native/src/sensor_service_client.cpp @@ -24,6 +24,7 @@ #include "hisysevent.h" #include "hitrace_meter.h" #include "ipc_skeleton.h" +#include "sensor_agent_proxy.h" #include "sensor_errors.h" #include "sensor_service_proxy.h" #include "system_ability_definition.h" @@ -218,6 +219,23 @@ int32_t SensorServiceClient::DestroyDataChannel() return ret; } +void SensorServiceClient::ReenableSensor() +{ + CALL_LOG_ENTER; + std::lock_guard mapLock(mapMutex_); + for (const auto &it : sensorInfoMap_) { + if (sensorServer_ != nullptr) { + sensorServer_->EnableSensor(it.first, it.second.GetSamplingPeriodNs(), it.second.GetMaxReportDelayNs()); + } + } + if (!isConnected_) { + SEN_HILOGD("Previous socket channel status is false, not need retry creat socket channel"); + return; + } + Disconnect(); + CreateSocketChannel(); +} + void SensorServiceClient::ProcessDeathObserver(const wptr &object) { CALL_LOG_ENTER; @@ -246,6 +264,7 @@ void SensorServiceClient::ProcessDeathObserver(const wptr &object if (InitServiceClient() != ERR_OK) { SEN_HILOGE("InitServiceClient failed"); dataChannel_->DestroySensorDataChannel(); + SENSOR_AGENT_IMPL->SetIsChannelCreated(false); return; } if (sensorServer_ != nullptr && sensorClientStub_ != nullptr) { @@ -256,18 +275,7 @@ void SensorServiceClient::ProcessDeathObserver(const wptr &object } } } - std::lock_guard mapLock(mapMutex_); - for (const auto &it : sensorInfoMap_) { - if (sensorServer_ != nullptr) { - sensorServer_->EnableSensor(it.first, it.second.GetSamplingPeriodNs(), it.second.GetMaxReportDelayNs()); - } - } - if (!isConnected_) { - SEN_HILOGD("Previous socket channel status is false, not need retry creat socket channel"); - return; - } - Disconnect(); - CreateSocketChannel(); + ReenableSensor(); } void SensorServiceClient::UpdateSensorInfoMap(int32_t sensorId, int64_t samplingPeriod, int64_t maxReportDelay) diff --git a/hisysevent.yaml b/hisysevent.yaml old mode 100755 new mode 100644 diff --git a/interfaces/kits/c/oh_sensor.h b/interfaces/kits/c/oh_sensor.h index 3c9b54ddf85220bdfe35af49a08ff63b2b3fa8a3..f5021bfe04b46932c9b73d156ab9cc825a2b6aa4 100644 --- a/interfaces/kits/c/oh_sensor.h +++ b/interfaces/kits/c/oh_sensor.h @@ -45,8 +45,10 @@ extern "C" { * @param infos - Double pointer to the information about all sensors on the device. * For details, see {@link Sensor_Info}. * @param count - Pointer to the number of sensors on the device. - * @return Returns SENSOR_SUCCESS if the operation is successful; - * returns an error code defined in {@link Sensor_Result} otherwise. + * @return Returns SENSOR_SUCCESS if the operation is successful; returns the following error code otherwise. + * {@link SENSOR_PARAMETER_ERROR} Parameter check failed. For example, the parameter is invalid, + * or the parameter type passed in is incorrect.\n + * {@link SENSOR_SERVICE_EXCEPTION} The sensor service is abnormal.\n * * @since 11 */ @@ -65,8 +67,11 @@ Sensor_Result OH_Sensor_GetInfos(Sensor_Info **infos, uint32_t *count); * For details, see {@link Sensor_SubscriptionAttribute}. * @param subscriber - Pointer to the subscriber information, which is used to specify the callback function for * reporting the sensor data. For details, see {@link Sensor_Subscriber}. - * @return Returns SENSOR_SUCCESS if the operation is successful; - * returns an error code defined in {@link Sensor_Result} otherwise. + * @return Returns SENSOR_SUCCESS if the operation is successful; returns the following error code otherwise. + * {@link SENSOR_PERMISSION_DENIED} Permission verification failed.\n + * {@link SENSOR_PARAMETER_ERROR} Parameter check failed. For example, the parameter is invalid, + * or the parameter type passed in is incorrect.\n + * {@link SENSOR_SERVICE_EXCEPTION} The sensor service is abnormal.\n * @permission ohos.permission.ACCELEROMETER or ohos.permission.GYROSCOPE or * ohos.permission.ACTIVITY_MOTION or ohos.permission.READ_HEALTH_DATA * @since 11 diff --git a/interfaces/kits/c/oh_sensor_type.h b/interfaces/kits/c/oh_sensor_type.h index e0ab040e90cae5eb0224b1267f3dbc1b33515cfe..cd4f6cbe100ca86b845d8096c58272e3e2c121f2 100644 --- a/interfaces/kits/c/oh_sensor_type.h +++ b/interfaces/kits/c/oh_sensor_type.h @@ -91,11 +91,21 @@ typedef enum Sensor_Type { * @since 11 */ SENSOR_TYPE_GRAVITY = 257, + /** + * Linear acceleration sensor. + * @since 13 + */ + SENSOR_TYPE_LINEAR_ACCELERATION = 258, /** * Rotation vector sensor. * @since 11 */ SENSOR_TYPE_ROTATION_VECTOR = 259, + /** + * Game rotation vector sensor. + * @since 13 + */ + SENSOR_TYPE_GAME_ROTATION_VECTOR = 262, /** * Pedometer detection sensor. * @since 11 @@ -120,23 +130,23 @@ typedef enum Sensor_Type { */ typedef enum Sensor_Result { /** - * The operation is successful. + * @error The operation is successful. * @since 11 */ SENSOR_SUCCESS = 0, /** - * Permission verification failed. + * @error Permission verification failed. * @since 11 */ SENSOR_PERMISSION_DENIED = 201, /** - * Parameter check failed. For example, a mandatory parameter is not passed in, + * @error Parameter check failed. For example, a mandatory parameter is not passed in, * or the parameter type passed in is incorrect. * @since 11 */ SENSOR_PARAMETER_ERROR = 401, /** - * The sensor service is abnormal. + * @error The sensor service is abnormal. * @since 11 */ SENSOR_SERVICE_EXCEPTION = 14500101, @@ -277,35 +287,35 @@ typedef struct Sensor_Event Sensor_Event; /** * @brief Obtains the sensor type. * - * @param Sensor_Event - Pointer to the sensor data information. + * @param sensorEvent - Pointer to the sensor data information. * @param sensorType - Pointer to the sensor type. * @return Returns SENSOR_SUCCESS if the operation is successful; * returns an error code defined in {@link Sensor_Result} otherwise. * @since 11 */ -int32_t OH_SensorEvent_GetType(Sensor_Event* Sensor_Event, Sensor_Type *sensorType); +int32_t OH_SensorEvent_GetType(Sensor_Event* sensorEvent, Sensor_Type *sensorType); /** * @brief Obtains the timestamp of sensor data. * - * @param Sensor_Event - Pointer to the sensor data information. + * @param sensorEvent - Pointer to the sensor data information. * @param timestamp - Pointer to the timestamp. * @return Returns SENSOR_SUCCESS if the operation is successful; * returns an error code defined in {@link Sensor_Result} otherwise. * @since 11 */ -int32_t OH_SensorEvent_GetTimestamp(Sensor_Event* Sensor_Event, int64_t *timestamp); +int32_t OH_SensorEvent_GetTimestamp(Sensor_Event* sensorEvent, int64_t *timestamp); /** * @brief Obtains the accuracy of sensor data. * - * @param Sensor_Event - Pointer to the sensor data information. + * @param sensorEvent - Pointer to the sensor data information. * @param accuracy - Pointer to the accuracy. * @return Returns SENSOR_SUCCESS if the operation is successful; * returns an error code defined in {@link Sensor_Result} otherwise. * @since 11 */ -int32_t OH_SensorEvent_GetAccuracy(Sensor_Event* Sensor_Event, Sensor_Accuracy *accuracy); +int32_t OH_SensorEvent_GetAccuracy(Sensor_Event* sensorEvent, Sensor_Accuracy *accuracy); /** * @brief Obtains sensor data. The data length and content depend on the sensor type. @@ -314,7 +324,9 @@ int32_t OH_SensorEvent_GetAccuracy(Sensor_Event* Sensor_Event, Sensor_Accuracy * * the x, y, and z axes of the device, respectively, in m/s2. * SENSOR_TYPE_GYROSCOPE: data[0], data[1], and data[2], indicating the angular velocity of rotation around * the x, y, and z axes of the device, respectively, in rad/s. - * SENSOR_TYPE_AMBIENT_LIGHT: data[0], indicating the ambient light intensity, in lux. + * SENSOR_TYPE_AMBIENT_LIGHT: data[0], indicating the ambient light intensity, in lux. Since api version 12, + * two additional data will be returned, where data[1] indicating the color temperature, in kelvin; data[2] + * indicating the infrared luminance, in cd/m2. * SENSOR_TYPE_MAGNETIC_FIELD: data[0], data[1], and data[2], indicating the magnetic field strength around * the x, y, and z axes of the device, respectively, in μT. * SENSOR_TYPE_BAROMETER: data[0], indicating the atmospheric pressure, in hPa. @@ -332,15 +344,20 @@ int32_t OH_SensorEvent_GetAccuracy(Sensor_Event* Sensor_Event, Sensor_Accuracy * * The value 1 means that the number of detected steps changes. * SENSOR_TYPE_PEDOMETER: data[0], indicating the number of steps a user has walked. * SENSOR_TYPE_HEART_RATE: data[0], indicating the heart rate value. + * SENSOR_TYPE_LINEAR_ACCELERATION: Supported from api version 13. data[0], data[1], and data[2], indicating the + * linear acceleration around the x, y, and z axes of the device, respectively, in m/s2. + * SENSOR_TYPE_GAME_ROTATION_VECTOR: Supported from api version 13. data[0], data[1], and data[2], indicating the + * rotation angles of a device around the x, y, and z axes, respectively, in degree. data[3] indicates the rotation + * vector. * - * @param Sensor_Event - Pointer to the sensor data information. + * @param sensorEvent - Pointer to the sensor data information. * @param data - Double pointer to the sensor data. * @param length - Pointer to the array length. * @return Returns SENSOR_SUCCESS if the operation is successful; * returns an error code defined in {@link Sensor_Result} otherwise. * @since 11 */ -int32_t OH_SensorEvent_GetData(Sensor_Event* Sensor_Event, float **data, uint32_t *length); +int32_t OH_SensorEvent_GetData(Sensor_Event* sensorEvent, float **data, uint32_t *length); /** * @brief Defines the sensor subscription ID, which uniquely identifies a sensor. @@ -371,7 +388,7 @@ int32_t OH_Sensor_DestroySubscriptionId(Sensor_SubscriptionId *id); * @brief Obtains the sensor type. * * @param id - Pointer to the sensor subscription ID. - * @param id - Pointer to the sensor type. + * @param sensorType - Pointer to the sensor type. * @return Returns SENSOR_SUCCESS if the operation is successful; * returns an error code defined in {@link Sensor_Result} otherwise. * @since 11 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/include/sensor_event_callback.h b/services/hdi_connection/adapter/include/sensor_event_callback.h index f1c62ff6733f7e42c441f660c70a824c516a8edd..33a72dbbf1d14941b02a7ab6db875aed6ea7a4e5 100644 --- a/services/hdi_connection/adapter/include/sensor_event_callback.h +++ b/services/hdi_connection/adapter/include/sensor_event_callback.h @@ -30,14 +30,7 @@ class SensorEventCallback : public ISensorCallback { public: virtual ~SensorEventCallback() {} int32_t OnDataEvent(const HdfSensorEvents &event) override; -private: - void ControlSensorPrint(const SensorData &sensorData); - void PrintSensorData(const SensorData &sensorData); - int32_t GetDataDimension(int32_t sensorId); - int64_t postureLastTs_ = 0; - int64_t ambientLightLastTs_ = 0; - int64_t magneticFieldLastTs_ = 0; }; -} // namespace Sensors -} // namespace OHOS +} // namespace Sensors +} // namespace OHOS #endif // SENSOR_EVENT_CALLBACK_H diff --git a/services/hdi_connection/adapter/src/hdi_connection.cpp b/services/hdi_connection/adapter/src/hdi_connection.cpp index 977697dd6ac59848c8cad19142eacfcf46d418d9..c186868fe4eb2f4c7433c578b642cfe735f1224d 100644 --- a/services/hdi_connection/adapter/src/hdi_connection.cpp +++ b/services/hdi_connection/adapter/src/hdi_connection.cpp @@ -37,7 +37,7 @@ using OHOS::HDI::Sensor::V2_0::ISensorCallback; using OHOS::HDI::Sensor::V2_0::HdfSensorInformation; namespace { sptr g_sensorInterface = nullptr; -sptr g_eventCallback = nullptr; +sptr g_eventCallback = nullptr; std::map g_sensorBasicInfoMap; std::mutex g_sensorBasicInfoMutex; constexpr int32_t GET_HDI_SERVICE_COUNT = 25; @@ -55,8 +55,8 @@ int32_t HdiConnection::ConnectHdi() while (retry < GET_HDI_SERVICE_COUNT) { g_sensorInterface = ISensorInterface::Get(); if (g_sensorInterface != nullptr) { - SEN_HILOGI("Connect V2_0 hdi success"); - g_eventCallback = new (std::nothrow) SensorEventCallback(); + SEN_HILOGI("Connect v2_0 hdi success"); + g_eventCallback = new (std::nothrow) SensorEventCallback(); CHKPR(g_eventCallback, ERR_NO_INIT); RegisterHdiDeathRecipient(); return ERR_OK; @@ -193,7 +193,7 @@ int32_t HdiConnection::DestroyHdiConnection() SEN_HILOGE("Unregister is failed"); return ret; } - g_eventCallback = nullptr; + g_eventCallback = nullptr; UnregisterHdiDeathRecipient(); return ERR_OK; } @@ -220,6 +220,12 @@ void HdiConnection::UpdateSensorBasicInfo(int32_t sensorId, int64_t samplingPeri SensorBasicInfo sensorBasicInfo; sensorBasicInfo.SetSamplingPeriodNs(samplingPeriodNs); sensorBasicInfo.SetMaxReportDelayNs(maxReportDelayNs); + auto it = g_sensorBasicInfoMap.find(sensorId); + if (it != g_sensorBasicInfoMap.end()) { + if (g_sensorBasicInfoMap[sensorId].GetSensorState()) { + sensorBasicInfo.SetSensorState(true); + } + } g_sensorBasicInfoMap[sensorId] = sensorBasicInfo; } @@ -269,7 +275,7 @@ void HdiConnection::ProcessDeathObserver(const wptr &object) CHKPV(hdiService); CHKPV(hdiDeathObserver_); hdiService->RemoveDeathRecipient(hdiDeathObserver_); - g_eventCallback = nullptr; + g_eventCallback = nullptr; Reconnect(); } @@ -311,5 +317,5 @@ void HdiConnection::Reconnect() } } } -} // namespace Sensors -} // namespace OHOS +} // namespace Sensors +} // namespace OHOS diff --git a/services/hdi_connection/adapter/src/sensor_event_callback.cpp b/services/hdi_connection/adapter/src/sensor_event_callback.cpp index 19c830f8c0206f3d5f00877d8be807e7711e785a..93a021f84eb8f94e9dedabd3b054563ce5a7ecd7 100644 --- a/services/hdi_connection/adapter/src/sensor_event_callback.cpp +++ b/services/hdi_connection/adapter/src/sensor_event_callback.cpp @@ -17,6 +17,7 @@ #include #include "hdi_connection.h" +#include "print_sensor_data.h" #include "sensor_agent_type.h" #include "sensor_errors.h" @@ -29,14 +30,6 @@ using namespace OHOS::HiviewDFX; namespace { std::unique_ptr HdiConnection_ = std::make_unique(); constexpr int32_t HEADPOSTURE_DATA_SIZE = 20; -constexpr int64_t LOG_INTERVAL = 60000000000; -enum { - ONE_DIMENSION = 1, - TWO_DIMENSION = 2, - THREE_DIMENSION = 3, - SEVEN_DIMENSION = 7, - DEFAULT_DIMENSION = 16 -}; const std::set g_sensorTypeTrigger = { SENSOR_TYPE_ID_PROXIMITY, SENSOR_TYPE_ID_DROP_DETECTION, @@ -87,71 +80,11 @@ int32_t SensorEventCallback::OnDataEvent(const HdfSensorEvents &event) sensorData.data[i] = event.data[i]; } } - ControlSensorPrint(sensorData); + PrintSensorData::GetInstance().ControlSensorHdiPrint(sensorData); std::unique_lock lk(ISensorHdiConnection::dataMutex_); (void)(reportDataCallback_->*(reportDataCb_))(&sensorData, reportDataCallback_); ISensorHdiConnection::dataCondition_.notify_one(); return ERR_OK; } - -void SensorEventCallback::ControlSensorPrint(const SensorData &sensorData) -{ - if (sensorData.sensorTypeId == SENSOR_TYPE_ID_HALL_EXT || sensorData.sensorTypeId == SENSOR_TYPE_ID_PROXIMITY - || sensorData.sensorTypeId == SENSOR_TYPE_ID_HALL) { - PrintSensorData(sensorData); - } - if ((sensorData.sensorTypeId == SENSOR_TYPE_ID_POSTURE) - && ((postureLastTs_ == 0) || (sensorData.timestamp - postureLastTs_ >= LOG_INTERVAL))) { - PrintSensorData(sensorData); - postureLastTs_ = sensorData.timestamp; - } - if ((sensorData.sensorTypeId == SENSOR_TYPE_ID_AMBIENT_LIGHT) - && ((ambientLightLastTs_ == 0) || (sensorData.timestamp - ambientLightLastTs_ >= LOG_INTERVAL))) { - PrintSensorData(sensorData); - ambientLightLastTs_ = sensorData.timestamp; - } - if ((sensorData.sensorTypeId == SENSOR_TYPE_ID_MAGNETIC_FIELD) - && ((magneticFieldLastTs_ == 0) || (sensorData.timestamp - magneticFieldLastTs_ >= LOG_INTERVAL))) { - PrintSensorData(sensorData); - magneticFieldLastTs_ = sensorData.timestamp; - } -} - -void SensorEventCallback::PrintSensorData(const SensorData &sensorData) -{ - std::string str; - str += "sensorId: " + std::to_string(sensorData.sensorTypeId) + ", "; - str += "timestamp: " + std::to_string(sensorData.timestamp) + ", "; - int32_t dataDim = GetDataDimension(sensorData.sensorTypeId); - auto data = reinterpret_cast(sensorData.data); - for (int32_t i = 0; i < dataDim; ++i) { - str.append(std::to_string(*data)); - if (i != dataDim - 1) { - str.append(", "); - } - ++data; - } - str.append("\n"); - SEN_HILOGI("SensorData: %{public}s", str.c_str()); -} - -int32_t SensorEventCallback::GetDataDimension(int32_t sensorId) -{ - switch (sensorId) { - case SENSOR_TYPE_ID_HALL: - case SENSOR_TYPE_ID_PROXIMITY: - return ONE_DIMENSION; - case SENSOR_TYPE_ID_HALL_EXT: - return TWO_DIMENSION; - case SENSOR_TYPE_ID_POSTURE: - return SEVEN_DIMENSION; - case SENSOR_TYPE_ID_AMBIENT_LIGHT: - case SENSOR_TYPE_ID_MAGNETIC_FIELD: - return THREE_DIMENSION; - default: - SEN_HILOGW("Unknown sensorId:%{public}d, size:%{public}d", sensorId, DEFAULT_DIMENSION); - return DEFAULT_DIMENSION; - } -} } // namespace Sensors } // namespace OHOS \ No newline at end of file diff --git a/services/include/sensor_service.h b/services/include/sensor_service.h index 67d9b4b0bcc613c17d5e60368254c82a3ed4e738..174aec478e8280fcc6ac4130e0ea2893bb9f1ffe 100644 --- a/services/include/sensor_service.h +++ b/services/include/sensor_service.h @@ -70,6 +70,7 @@ public: private: DISALLOW_COPY_AND_MOVE(SensorService); void OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId) override; + bool CheckParameter(int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs); class PermStateChangeCb : public Security::AccessToken::PermStateChangeCallbackCustomize { public: @@ -117,6 +118,6 @@ private: }; #define POWER_POLICY SensorPowerPolicy::GetInstance() -} // namespace Sensors -} // namespace OHOS -#endif // SENSOR_SERVICE_H +} // namespace Sensors +} // namespace OHOS +#endif // SENSOR_SERVICE_H diff --git a/services/src/sensor_service.cpp b/services/src/sensor_service.cpp index eef9a2f37e133c116e5b7e2fdeb20aa22a8193f0..b95a90db4ee5869c8bd632fcec989cdb03f4db96 100644 --- a/services/src/sensor_service.cpp +++ b/services/src/sensor_service.cpp @@ -27,6 +27,7 @@ #endif // MEMMGR_ENABLE #include "permission_util.h" +#include "print_sensor_data.h" #include "securec.h" #include "sensor.h" #include "sensor_dump.h" @@ -45,7 +46,7 @@ const bool G_REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(g_sensorSer constexpr int32_t INVALID_PID = -1; constexpr int64_t MAX_EVENT_COUNT = 1000; std::atomic_bool g_isRegister = false; -} // namespace +} // namespace SensorService::SensorService() : SystemAbility(SENSOR_SERVICE_ABILITY_ID, true), state_(SensorServiceState::STATE_STOPPED) @@ -254,12 +255,21 @@ bool SensorService::CheckSensorId(int32_t sensorId) return true; } -ErrCode SensorService::EnableSensor(int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs) +bool SensorService::CheckParameter(int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs) { - CALL_LOG_ENTER; if ((!CheckSensorId(sensorId)) || ((samplingPeriodNs != 0L) && ((maxReportDelayNs / samplingPeriodNs) > MAX_EVENT_COUNT))) { SEN_HILOGE("sensorId is invalid or maxReportDelayNs exceeded the maximum value"); + return false; + } + return true; +} + +ErrCode SensorService::EnableSensor(int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs) +{ + CALL_LOG_ENTER; + if (!CheckParameter(sensorId, samplingPeriodNs, maxReportDelayNs)) { + SEN_HILOGE("sensorId, maxReportDelayNs or maxReportDelayNs is invalid"); return ERR_NO_INIT; } int32_t pid = GetCallingPid(); @@ -279,6 +289,7 @@ ErrCode SensorService::EnableSensor(int32_t sensorId, int64_t samplingPeriodNs, if (isReportActiveInfo_) { ReportActiveInfo(sensorId, pid); } + PrintSensorData::GetInstance().ResetHdiCounter(sensorId); return ERR_OK; } auto ret = SaveSubscriber(sensorId, samplingPeriodNs, maxReportDelayNs); @@ -302,6 +313,7 @@ ErrCode SensorService::EnableSensor(int32_t sensorId, int64_t samplingPeriodNs, if (isReportActiveInfo_) { ReportActiveInfo(sensorId, pid); } + PrintSensorData::GetInstance().ResetHdiCounter(sensorId); return ret; } @@ -607,5 +619,5 @@ void SensorService::PermStateChangeCb::PermStateChangeCallback(Security::AccessT server_->clientInfo_.ChangeSensorPerm(result.tokenID, result.permissionName, (result.permStateChangeType != 0)); } -} // namespace Sensors -} // namespace OHOS +} // namespace Sensors +} // namespace OHOS diff --git a/test/unittest/interfaces/inner_api/drop_detection_test.cpp b/test/unittest/interfaces/inner_api/drop_detection_test.cpp index cfae3d7a5821e286c7195b00397509f5859d0d8d..a1bd4f3dff75e47887e01219c4d8e927ec950769 100644 --- a/test/unittest/interfaces/inner_api/drop_detection_test.cpp +++ b/test/unittest/interfaces/inner_api/drop_detection_test.cpp @@ -83,10 +83,6 @@ void DropDetectionDataCallbackImpl(SensorEvent *event) return; } DropDetectionData *dropDetectionData = reinterpret_cast(event[0].data); - if (dropDetectionData == nullptr) { - SEN_HILOGE("dropDetectionData is nullptr"); - return; - } SEN_HILOGD("sensorId:%{public}d, version:%{public}d, dataLen:%{public}u, status:%{public}f", event[0].sensorTypeId, event[0].version, event[0].dataLen, dropDetectionData->status); } @@ -106,10 +102,6 @@ void DropDetectionDataCallbackImpl2(SensorEvent *event) return; } DropDetectionData *dropDetectionData = reinterpret_cast(event[0].data); - if (dropDetectionData == nullptr) { - SEN_HILOGE("dropDetectionData is nullptr"); - return; - } SEN_HILOGD("sensorId:%{public}d, version:%{public}d, dataLen:%{public}u, status:%{public}f", event[0].sensorTypeId, event[0].version, event[0].dataLen, dropDetectionData->status); } diff --git a/test/unittest/interfaces/js/sensor/PedometerDetectionJsunit.test.js b/test/unittest/interfaces/js/sensor/PedometerDetectionJsunit.test.js index 37bc1313517ced30d86a0d7fa4ae1842502c4def..ca9326f94b89a13f1fd991f857c3f3a876ef056b 100644 --- a/test/unittest/interfaces/js/sensor/PedometerDetectionJsunit.test.js +++ b/test/unittest/interfaces/js/sensor/PedometerDetectionJsunit.test.js @@ -81,7 +81,7 @@ describe("PedometerDetectionJsTest", function () { * @tc.name: PedometerDetectionJsTest * @tc.desc: verify app info is not null * @tc.type: FUNC - * @tc.require: Issue Number + * @tc.require: AR000HPEMR * @tc.size: MediumTest * @tc.type: Function * @tc.level: Level 1 @@ -129,7 +129,7 @@ describe("PedometerDetectionJsTest", function () { * @tc.name: PedometerDetectionJsTest * @tc.desc: verify app info is not null * @tc.type: FUNC - * @tc.require: Issue Number + * @tc.require: AR000HPEMR * @tc.size: MediumTest * @tc.type: Function * @tc.level: Level 1 @@ -173,7 +173,7 @@ describe("PedometerDetectionJsTest", function () { * @tc.name: PedometerDetectionJsTest * @tc.desc: verify app info is not null * @tc.type: FUNC - * @tc.require: Issue Number + * @tc.require: AR000HPEMR * @tc.size: MediumTest * @tc.type: Function * @tc.level: Level 1 @@ -221,7 +221,7 @@ describe("PedometerDetectionJsTest", function () { * @tc.name: PedometerDetectionJsTest * @tc.desc: verify app info is not null * @tc.type: FUNC - * @tc.require: Issue Number + * @tc.require: AR000HPEMR * @tc.size: MediumTest * @tc.type: Function * @tc.level: Level 1 @@ -269,7 +269,7 @@ describe("PedometerDetectionJsTest", function () { * @tc.name: PedometerDetectionJsTest * @tc.desc: verify app info is not null * @tc.type: FUNC - * @tc.require: Issue Number + * @tc.require: AR000HPEMR * @tc.size: MediumTest * @tc.type: Function * @tc.level: Level 1 @@ -313,7 +313,7 @@ describe("PedometerDetectionJsTest", function () { * @tc.name: PedometerDetectionJsTest * @tc.desc: verify app info is not null * @tc.type: FUNC - * @tc.require: Issue Number + * @tc.require: AR000HPEMR * @tc.size: MediumTest * @tc.type: Function * @tc.level: Level 1 @@ -356,7 +356,7 @@ describe("PedometerDetectionJsTest", function () { * @tc.name: PedometerDetectionJsTest * @tc.desc: verify app info is not null * @tc.type: FUNC - * @tc.require: Issue Number + * @tc.require: AR000HPEMR * @tc.size: MediumTest * @tc.type: Function * @tc.level: Level 1 @@ -405,7 +405,7 @@ describe("PedometerDetectionJsTest", function () { * @tc.name: PedometerDetectionJsTest * @tc.desc: verify app info is not null * @tc.type: FUNC - * @tc.require: Issue Number + * @tc.require: AR000HPEMR * @tc.size: MediumTest * @tc.type: Function * @tc.level: Level 1 @@ -457,7 +457,7 @@ describe("PedometerDetectionJsTest", function () { * @tc.name: PedometerDetectionJsTest * @tc.desc: verify app info is not null * @tc.type: FUNC - * @tc.require: Issue Number + * @tc.require: AR000HPEMR * @tc.size: MediumTest * @tc.type: Function * @tc.level: Level 1 @@ -506,7 +506,7 @@ describe("PedometerDetectionJsTest", function () { * @tc.name: PedometerDetectionJsTest * @tc.desc: verify app info is not null * @tc.type: FUNC - * @tc.require: Issue Number + * @tc.require: AR000HPEMR * @tc.size: MediumTest * @tc.type: Function * @tc.level: Level 1 diff --git a/test/unittest/interfaces/js/sensor/common/CommonConstants.js b/test/unittest/interfaces/js/sensor/common/CommonConstants.js index fb6a2a2e49026c5982222d9a3d6e2eb445a0c824..abc4a087105ae189b34e200bfd7427cd537b8806 100644 --- a/test/unittest/interfaces/js/sensor/common/CommonConstants.js +++ b/test/unittest/interfaces/js/sensor/common/CommonConstants.js @@ -43,12 +43,12 @@ 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; /** - * eps + * Eps */ static EPS = 0.01; diff --git a/test/unittest/interfaces/js/sensor/config.json b/test/unittest/interfaces/js/sensor/config.json index aabb3f4b8a5544b29581e64aedf217387cef1dfd..435079f98c0281c4efd6a1517338ce41b1942a05 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", + "2inl" ], "distro": { "deliveryWithInstall": true, diff --git a/utils/common/BUILD.gn b/utils/common/BUILD.gn index 48bce26e0b22d0f7f21321a598905ed917336150..0d522496a5c8929deed3cd9e944219f72686bf9f 100644 --- a/utils/common/BUILD.gn +++ b/utils/common/BUILD.gn @@ -18,6 +18,7 @@ ohos_shared_library("libsensor_utils") { sources = [ "src/active_info.cpp", "src/permission_util.cpp", + "src/print_sensor_data.cpp", "src/report_data_callback.cpp", "src/sensor.cpp", "src/sensor_basic_data_channel.cpp", diff --git a/utils/common/include/print_sensor_data.h b/utils/common/include/print_sensor_data.h new file mode 100644 index 0000000000000000000000000000000000000000..3997069234ddcef3e0be78c0dc3b975e0449ef7e --- /dev/null +++ b/utils/common/include/print_sensor_data.h @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PRINT_SENSOR_DATA +#define PRINT_SENSOR_DATA + +#include + +#include "singleton.h" + +#include "sensor_agent_type.h" +#include "sensor_data_event.h" + +namespace OHOS { +namespace Sensors { + + +class PrintSensorData : public Singleton { +public: + PrintSensorData() = default; + virtual ~PrintSensorData() {}; + void ControlSensorClientPrint(const RecordSensorCallback callback, const SensorEvent &event); + void ControlSensorHdiPrint(const SensorData &sensorData); + void ResetHdiCounter(int32_t sensorId); + bool IsContinuousType(int32_t sensorId); + void SavePrintUserInfo(const RecordSensorCallback callback); + void RemovePrintUserInfo(const RecordSensorCallback callback); + +private: + void PrintClientData(const SensorEvent &event); + void PrintHdiData(const SensorData &sensorData); + int32_t GetDataDimension(int32_t sensorId); + struct LogPrintInfo { + int32_t count { 0 }; + int64_t lastTime { 0 }; + }; + std::mutex hdiLoginfoMutex_; + std::mutex clientLoginfoMutex_; + LogPrintInfo info_; + std::map hdiLoginfo_ = { + {SENSOR_TYPE_ID_ACCELEROMETER, info_}, + {SENSOR_TYPE_ID_GYROSCOPE, info_}, + {SENSOR_TYPE_ID_POSTURE, info_}, + {SENSOR_TYPE_ID_AMBIENT_LIGHT, info_}, + {SENSOR_TYPE_ID_AMBIENT_LIGHT1, info_}, + {SENSOR_TYPE_ID_MAGNETIC_FIELD, info_}, + }; + std::map clientLoginfo_; +}; +} // namespace Sensors +} // namespace OHOS +#endif // PRINT_SENSOR_DATA diff --git a/utils/common/src/print_sensor_data.cpp b/utils/common/src/print_sensor_data.cpp new file mode 100644 index 0000000000000000000000000000000000000000..45881fdbdc1af297a11ec018233f9254de4f3e17 --- /dev/null +++ b/utils/common/src/print_sensor_data.cpp @@ -0,0 +1,213 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "print_sensor_data.h" + +#include +#include + +#include "sensor_errors.h" + +#undef LOG_TAG +#define LOG_TAG "PrintSensorData" + +namespace OHOS { +namespace Sensors { +namespace { +enum { + ONE_DIMENSION = 1, + TWO_DIMENSION = 2, + THREE_DIMENSION = 3, + SEVEN_DIMENSION = 7, + DEFAULT_DIMENSION = 16 +}; +constexpr int64_t LOG_INTERVAL = 60000000000L; +constexpr int32_t FIRST_PRINT_TIMES = 20; +constexpr float LOG_FORMAT_DIVIDER = 1e9f; + +const std::vector g_triggerSensorType = { + SENSOR_TYPE_ID_HALL_EXT, + SENSOR_TYPE_ID_PROXIMITY, + SENSOR_TYPE_ID_HALL, + SENSOR_TYPE_ID_WEAR_DETECTION, +}; +const std::vector g_continuousSensorType = { + SENSOR_TYPE_ID_ACCELEROMETER, + SENSOR_TYPE_ID_POSTURE, + SENSOR_TYPE_ID_AMBIENT_LIGHT, + SENSOR_TYPE_ID_AMBIENT_LIGHT1, + SENSOR_TYPE_ID_GYROSCOPE, + SENSOR_TYPE_ID_MAGNETIC_FIELD, +}; +} + +void PrintSensorData::ControlSensorHdiPrint(const SensorData &sensorData) +{ + auto triggerIt = std::find(g_triggerSensorType.begin(), g_triggerSensorType.end(), sensorData.sensorTypeId); + if (triggerIt != g_triggerSensorType.end()) { + PrintHdiData(sensorData); + } + std::lock_guard hdiLoginfoLock(hdiLoginfoMutex_); + auto it = hdiLoginfo_.find(sensorData.sensorTypeId); + if (it == hdiLoginfo_.end()) { + return; + } + if (it->second.count < FIRST_PRINT_TIMES) { + PrintHdiData(sensorData); + if (it->second.count == FIRST_PRINT_TIMES - 1) { + it->second.lastTime = sensorData.timestamp; + } + it->second.count++; + } else { + if (sensorData.timestamp - it->second.lastTime >= LOG_INTERVAL) { + PrintHdiData(sensorData); + it->second.lastTime = sensorData.timestamp; + } + } +} + +void PrintSensorData::PrintHdiData(const SensorData &sensorData) +{ + std::string str; + str += "sensorId: " + std::to_string(sensorData.sensorTypeId) + ", "; + str += "timestamp: " + std::to_string(sensorData.timestamp / LOG_FORMAT_DIVIDER) + ", "; + int32_t dataDim = GetDataDimension(sensorData.sensorTypeId); + auto data = reinterpret_cast(sensorData.data); + CHKPV(data); + for (int32_t i = 0; i < dataDim; ++i) { + str.append(std::to_string(*data)); + if (i != dataDim - 1) { + str.append(", "); + } + ++data; + } + str.append("\n"); + SEN_HILOGI("SensorData: %{public}s", str.c_str()); +} + +int32_t PrintSensorData::GetDataDimension(int32_t sensorId) +{ + switch (sensorId) { + case SENSOR_TYPE_ID_HALL: + case SENSOR_TYPE_ID_PROXIMITY: + case SENSOR_TYPE_ID_WEAR_DETECTION: + return ONE_DIMENSION; + case SENSOR_TYPE_ID_HALL_EXT: + return TWO_DIMENSION; + case SENSOR_TYPE_ID_POSTURE: + return SEVEN_DIMENSION; + case SENSOR_TYPE_ID_AMBIENT_LIGHT: + case SENSOR_TYPE_ID_AMBIENT_LIGHT1: + case SENSOR_TYPE_ID_ACCELEROMETER: + case SENSOR_TYPE_ID_GYROSCOPE: + case SENSOR_TYPE_ID_MAGNETIC_FIELD: + return THREE_DIMENSION; + default: + SEN_HILOGW("Unknown sensorId:%{public}d, size:%{public}d", sensorId, DEFAULT_DIMENSION); + return DEFAULT_DIMENSION; + } +} + +void PrintSensorData::ControlSensorClientPrint(const RecordSensorCallback callback, const SensorEvent &event) +{ + auto triggerIt = std::find(g_triggerSensorType.begin(), g_triggerSensorType.end(), event.sensorTypeId); + if (triggerIt != g_triggerSensorType.end()) { + PrintClientData(event); + } + + auto continuosIt = std::find(g_continuousSensorType.begin(), g_continuousSensorType.end(), event.sensorTypeId); + if (continuosIt == g_continuousSensorType.end()) { + return; + } + std::lock_guard clientLoginfoLock(clientLoginfoMutex_); + auto it = clientLoginfo_.find(callback); + if (it == clientLoginfo_.end()) { + return; + } + if (it->second.count < FIRST_PRINT_TIMES) { + PrintClientData(event); + if (it->second.count == FIRST_PRINT_TIMES - 1) { + it->second.lastTime = event.timestamp; + } + it->second.count++; + } else { + if (event.timestamp - it->second.lastTime >= LOG_INTERVAL) { + PrintClientData(event); + it->second.lastTime = event.timestamp; + } + } +} + +void PrintSensorData::PrintClientData(const SensorEvent &event) +{ + std::string str; + str += "sensorId: " + std::to_string(event.sensorTypeId) + ", "; + str += "timestamp: " + std::to_string(event.timestamp / LOG_FORMAT_DIVIDER) + ", "; + int32_t dataDim = GetDataDimension(event.sensorTypeId); + auto data = reinterpret_cast(event.data); + CHKPV(data); + for (int32_t i = 0; i < dataDim; ++i) { + str.append(std::to_string(*data)); + if (i != dataDim - 1) { + str.append(", "); + } + ++data; + } + str.append("\n"); + SEN_HILOGI("SensorData: %{public}s", str.c_str()); +} + +bool PrintSensorData::IsContinuousType(int32_t sensorId) +{ + return std::find(g_continuousSensorType.begin(), g_continuousSensorType.end(), + sensorId) != g_continuousSensorType.end(); +} + +void PrintSensorData::SavePrintUserInfo(const RecordSensorCallback callback) +{ + CHKPV(callback); + std::lock_guard clientLoginfoLock(clientLoginfoMutex_); + if (clientLoginfo_.find(callback) != clientLoginfo_.end()) { + return; + } + LogPrintInfo info; + auto status = clientLoginfo_.insert(std::make_pair(callback, info)); + if (!status.second) { + SEN_HILOGD("callback has been saved"); + } +} + +void PrintSensorData::RemovePrintUserInfo(const RecordSensorCallback callback) +{ + CHKPV(callback); + std::lock_guard clientLoginfoLock(clientLoginfoMutex_); + if (clientLoginfo_.find(callback) == clientLoginfo_.end()) { + return; + } + clientLoginfo_.erase(callback); +} + +void PrintSensorData::ResetHdiCounter(int32_t sensorId) +{ + std::lock_guard hdiLoginfoLock(hdiLoginfoMutex_); + auto it = hdiLoginfo_.find(sensorId); + if (it == hdiLoginfo_.end()) { + return; + } + it->second.count = 0; + it->second.lastTime = 0; +} +} // namespace Sensors +} // namespace OHOS diff --git a/vibration_convert/core/algorithm/conversion/src/conversion_fft.cpp b/vibration_convert/core/algorithm/conversion/src/conversion_fft.cpp index 11bdb3a878ebcba7f24ca97f7ea0849075269bea..2abedb2ff93a8f09597244ab74f91e3544647cc8 100644 --- a/vibration_convert/core/algorithm/conversion/src/conversion_fft.cpp +++ b/vibration_convert/core/algorithm/conversion/src/conversion_fft.cpp @@ -27,7 +27,7 @@ namespace Sensors { namespace { constexpr int32_t SPECTRUM_COUNT_MAX { 8192 }; constexpr int32_t MAX_FFT_SIZE { 10240 }; -} // namespace +} // namespace int32_t ConversionFFT::Init(const FFTInputPara &fftPara) { @@ -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]); @@ -248,7 +248,7 @@ int32_t ConversionOctave::Init(float samplingRate, int32_t nBandsInTheFFT, int32 // 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_; @@ -268,6 +268,8 @@ int32_t ConversionOctave::Init(float samplingRate, int32_t nBandsInTheFFT, int32 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; @@ -288,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; @@ -322,5 +324,5 @@ int32_t ConversionOctave::Calculate(const std::vector &fftData) } return Sensors::SUCCESS; } -} // namespace Sensors -} // namespace OHOS \ No newline at end of file +} // namespace Sensors +} // namespace OHOS \ No newline at end of file diff --git a/vibration_convert/core/algorithm/conversion/src/conversion_mfcc.cpp b/vibration_convert/core/algorithm/conversion/src/conversion_mfcc.cpp index a1e282a693420ad2ce1fa69581cd4f534db9cee2..7f0bbcf74f0009e5332e3269ebc3c5436a04fe47 100644 --- a/vibration_convert/core/algorithm/conversion/src/conversion_mfcc.cpp +++ b/vibration_convert/core/algorithm/conversion/src/conversion_mfcc.cpp @@ -28,7 +28,7 @@ namespace Sensors { namespace { constexpr double BANDS_MIN_THRESHOLD { 0.000001 }; constexpr uint32_t MEL_FILTERS_OR_COEFFS_MAX { 4096 * 4096 }; -} // namespace +} // namespace int32_t ConversionMfcc::HandleMelFilterAndLogSquare(const std::vector &powerSpectrum) { @@ -223,16 +223,15 @@ 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) { filterHzPos[i] = OHOS::Sensors::ConvertHtkHz(nextMel); @@ -261,7 +260,7 @@ int32_t ConversionMfcc::FiltersMel(int32_t nFft, MfccInputPara para, } } melBasis = OHOS::Sensors::TransposeMatrix(nMels, basis); - return melBasis.empty() ? Sensor::ERROR : Sensors::SUCCESS; + return melBasis.empty() ? Sensors::ERROR : Sensors::SUCCESS; } -} // namespace Sensors -} // namespace OHOS \ No newline at end of file +} // namespace Sensors +} // namespace OHOS \ No newline at end of file diff --git a/vibration_convert/core/native/src/vibration_convert_core.cpp b/vibration_convert/core/native/src/vibration_convert_core.cpp index 571cca78d06b291ad88d097230f339023668d46f..3c4043d17ccd164d079fbe8982d9bfb9e24e3080 100644 --- a/vibration_convert/core/native/src/vibration_convert_core.cpp +++ b/vibration_convert/core/native/src/vibration_convert_core.cpp @@ -109,6 +109,7 @@ int32_t VibrationConvertCore::GetAudioData() } return Sensors::SUCCESS; } + int32_t VibrationConvertCore::ConvertAudioToHaptic(const AudioSetting &audioSetting, const std::vector &audioData, std::vector &hapticEvents) { @@ -293,7 +294,7 @@ double VibrationConvertCore::CalcRmsLowerData(size_t dataSize, const std::vector if (newDrwIdx.size() > 0) { for (int32_t i = 0; i < RMSE_LOWDELTA_ITERATION_TIMES; i++) { int32_t j = newDrwIdx[0]; - lowerDelta = rmseRange * (RMSE_LOWDELTA_RATIO_HIGH - i * RMSE_LOWDELTA_RATIO_STEP ) + rmseMin; + lowerDelta = rmseRange * (RMSE_LOWDELTA_RATIO_HIGH - i * RMSE_LOWDELTA_RATIO_STEP) + rmseMin; if ((rmse[j] > lowerDelta) || (rmse[j + 1] > lowerDelta)) { break; } @@ -679,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(data.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(data[i]); + localData.push_back(data[i]); } double unzeroDensity = 0.0; int32_t unzeroCount = 0; @@ -775,7 +776,7 @@ void VibrationConvertCore::TranslateAnchorPoint(const std::vector &l } void VibrationConvertCore::TranslateAnchorPoint(int32_t amplitudePeakPos, int32_t &litudePeakIdx, - ouble &litudePeakTime) + double &litudePeakTime) { bool useAbsTimeFlag = systemPara_.useAbsTimeFlag; amplitudePeakIdx = static_cast(round(1.0 * amplitudePeakPos / ENERGY_HOP_LEN)); @@ -791,7 +792,7 @@ std::vector VibrationConvertCore::DetectFrequency(const std::vector &rmseIntensityNorm) { CALL_LOG_ENTER; - std::vector zcr = frequencyEstimation_.GetZeroCrossingRate(data, FRAME_LEN, ENERGY_HOP_LEN); + std::vector zcr = frequencyEstimation_.GetZeroCrossingRate(data, FRAME_LEN, ENERGY_HOP_LEN); for (auto &elem : zcr) { elem = elem * SAMPLE_RATE * F_HALF; } @@ -1022,7 +1023,7 @@ void VibrationConvertCore::OutputAllContinuousEventByUnseg(const std::vector durations; FillDefaultContinuousEvents(rmseTimeNorm, times, durations); int32_t ret = InsertTransientEvent(rmseTimeNorm, transientIndex, transientEventFlags, - times, durations); + times, durations); if (ret != Sensors::SUCCESS) { SEN_HILOGE("InsertTransientEvent failed"); return; @@ -1030,7 +1031,7 @@ void VibrationConvertCore::OutputAllContinuousEventByUnseg(const std::vector continuousEvents; for (size_t i = 0; i < times.size(); i++) { continuousEvents.push_back(ContinuousEvent(times[i], durations[i], - intensityData[i].rmseIntensityNorm, freqNorm[i])); + intensityData[i].rmseIntensityNorm, freqNorm[i])); } MergeContinuousEvents(continuousEvents); } diff --git a/vibration_convert/core/utils/include/utils.h b/vibration_convert/core/utils/include/utils.h index 07689309dbbdb69263aa8f7964c13fa343b1778b..9d692826ede3bab5186a50a17ab1cb05031677e6 100644 --- a/vibration_convert/core/utils/include/utils.h +++ b/vibration_convert/core/utils/include/utils.h @@ -46,7 +46,7 @@ constexpr double F_HALF = 0.5; constexpr double F_THREE = 3.0; constexpr double SAMPLE_IN_MS = 1000.0; constexpr double INTERSITY_BOUNDARY_POINT = 0.25; -constexpr double INTERSITY_NUMBER_BOUNDARY_POINT = 0.75; +constexpr double INTERSITY_NUMBER_BOUNDARY_POINT = 0.75; } // namespace enum WindowType { @@ -56,9 +56,9 @@ enum WindowType { }; enum FilterMethod{ - LOW_RESONANT_FILTER = 1, - HIGH_RESONANT_FILTER = 2, - BAND_PASS_FILTER = 3, + 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; @@ -207,4 +201,4 @@ inline double ConvertHtkHz(double mels) } } // namespace Sensors } // namespace OHOS -#endif // CONVERSION_UTILS_H \ No newline at end of file +#endif // CONVERSION_UTILS_H \ No newline at end of file diff --git a/vibration_convert/core/utils/src/utils.cpp b/vibration_convert/core/utils/src/utils.cpp index dded5ba1424c0f3cedb649f70048fce2c2dcccfc..2ef73e36fc6bfed5ac84810cb9121c9b5682ce52 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; }