diff --git a/interfaces/plugin/BUILD.gn b/interfaces/plugin/BUILD.gn index b59b518441affd68fcc93acc4274f7e992c3882c..a708db15960ff8f5ee4a836104b15601a03aeacc 100644 --- a/interfaces/plugin/BUILD.gn +++ b/interfaces/plugin/BUILD.gn @@ -21,6 +21,8 @@ ohos_shared_library("sensor") { "//third_party/libuv/include", "//utils/native/base/include", "./include", + "//base/sensors/sensor/utils/include", + "//foundation/ace/napi/interfaces/innerkits/napi", ] defines = [ "APP_LOG_TAG = \"sensroJs\"", diff --git a/interfaces/plugin/include/async_callback_info.h b/interfaces/plugin/include/async_callback_info.h new file mode 100644 index 0000000000000000000000000000000000000000..1b609643d409f4f064532160f8bd8a5ef2e590e4 --- /dev/null +++ b/interfaces/plugin/include/async_callback_info.h @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef ASYNC_CALLBACK_INFO_H +#define ASYNC_CALLBACK_INFO_H + +#include "napi/native_api.h" +#include "napi/native_node_api.h" +#include "refbase.h" +#include "sensor_agent_type.h" +#include "sensor_log.h" +#include "sensors_errors.h" + +namespace OHOS { +namespace Sensors { +using std::vector; +using std::string; +using namespace OHOS::HiviewDFX; +static constexpr HiLogLabel LABEL = {LOG_CORE, 0xD002708, "SensorJsAPI"}; +constexpr int32_t THREE_DIMENSIONAL_MATRIX_LENGTH = 9; +constexpr static int32_t DATA_LENGTH = 16; +constexpr int32_t CALLBACK_NUM = 3; +enum CallbackDataType { + FAIL = -1, + OFF_CALLBACK = 0, + ON_CALLBACK = 1, + ONCE_CALLBACK = 2, + GET_GEOMAGNETIC_FIELD = 3, + GET_ALTITUDE = 4, + GET_GEOMAGNITIC_DIP = 5, + GET_ANGLE_MODIFY = 6, + CREATE_ROTATION_MATRIX = 7, + TRANSFORM_COORDINATE_SYSTEM = 8, + CREATE_QUATERNION = 9, + GET_DIRECTION = 10, + ROTATION_INCLINATION_MATRIX = 11, + GET_SENSOR_LIST = 12, + GET_SINGLE_SENSOR = 13 +}; + +struct GeomagneticData { + float x; + float y; + float z; + float geomagneticDip; + float deflectionAngle; + float levelIntensity; + float totalIntensity; +}; + +struct RationMatrixData { + float rotationMatrix[THREE_DIMENSIONAL_MATRIX_LENGTH]; + float inclinationMatrix[THREE_DIMENSIONAL_MATRIX_LENGTH]; +}; + +struct SensorData { + int32_t sensorTypeId; + uint32_t dataLength; + float data[DATA_LENGTH]; + int64_t timestamp; +}; + +struct ReserveData { + float reserve[DATA_LENGTH]; + int32_t length; +}; + +union CallbackData { + SensorData sensorData; + GeomagneticData geomagneticData; + RationMatrixData rationMatrixData; + ReserveData reserveData; +}; + +struct BusinessError { + int32_t code; + string message; + string name; + string stack; +}; + +class AsyncCallbackInfo : public RefBase { +public: + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + uv_work_t *work = nullptr; + napi_deferred deferred = nullptr; + napi_ref callback[CALLBACK_NUM] = { 0 }; + CallbackData data; + BusinessError error; + CallbackDataType type; + vector sensorInfos; + sptr callbackInfo = nullptr; + + AsyncCallbackInfo(napi_env env, CallbackDataType type) : env(env), type(type) {} + ~AsyncCallbackInfo() + { + CALL_LOG_ENTER; + if (asyncWork != nullptr) { + SEN_HILOGD("Delete async work"); + napi_delete_async_work(env, asyncWork); + } + for (int32_t i = 0; i < CALLBACK_NUM; ++i) { + if (callback[i] != nullptr) { + SEN_HILOGD("Delete reference, i: %{public}d", i); + napi_delete_reference(env, callback[i]); + } + } + if (work != nullptr) { + delete work; + work = nullptr; + } + } + +private: +}; +} // namespace Sensors +} // namespace OHOS +#endif // ASYNC_CALLBACK_INFO_H \ No newline at end of file diff --git a/interfaces/plugin/include/sensor_js.h b/interfaces/plugin/include/sensor_js.h old mode 100755 new mode 100644 index 00d01db9892937b5db2c372609e232eac7f93c73..8f5b1afb0d1db3a6ef2f2147ae42fb9a33cca120 --- a/interfaces/plugin/include/sensor_js.h +++ b/interfaces/plugin/include/sensor_js.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -14,11 +14,12 @@ */ #ifndef SENSOR_JS_H #define SENSOR_JS_H - #include "sensor_agent.h" -#include "errors.h" - -static int32_t UnsubscribeSensor(int32_t sensorTypeId); +namespace OHOS { +namespace Sensors { +static bool UnsubscribeSensor(int32_t sensorTypeId); static void DataCallbackImpl(SensorEvent *event); -static int32_t SubscribeSensor(int32_t sensorTypeId, int64_t interval, RecordSensorCallback callback); +static bool SubscribeSensor(int32_t sensorTypeId, int64_t interval, RecordSensorCallback callback); +} // namespace Sensors +} // namespace OHOS #endif // SENSOR_JS_H \ No newline at end of file diff --git a/interfaces/plugin/include/sensor_napi_utils.h b/interfaces/plugin/include/sensor_napi_utils.h index 12d0385b4e4fe78659fb95f47c565ef2fc1610f3..aaf3623d563db4948261e24992ae9b1a77ed7279 100644 --- a/interfaces/plugin/include/sensor_napi_utils.h +++ b/interfaces/plugin/include/sensor_napi_utils.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -18,140 +18,151 @@ #include #include -#include "napi/native_api.h" -#include "napi/native_node_api.h" - -#include "sensor_agent.h" - +#include "async_callback_info.h" +#include "refbase.h" +namespace OHOS { +namespace Sensors { using std::vector; using std::string; - -const int32_t THREE_DIMENSIONAL_MATRIX_LENGTH = 9; -const int32_t FOUR_DIMENSIONAL_MATRIX_LENGTH = 16; -const int32_t QUATERNION_LENGTH = 4; -const int32_t ROTATION_VECTOR_LENGTH = 3; -struct GeomagneticData { - float x; - float y; - float z; - float geomagneticDip; - float deflectionAngle; - float levelIntensity; - float totalIntensity; -}; - -struct RationMatrixData { - float rotationMatrix[THREE_DIMENSIONAL_MATRIX_LENGTH]; - float inclinationMatrix[THREE_DIMENSIONAL_MATRIX_LENGTH]; -}; - -struct SensorData { - int32_t sensorTypeId; - uint32_t dataLength; - float data[16]; - int64_t timestamp; -}; - -struct ReserveData { - float reserve[16]; - int32_t length; -}; - -union CallbackData { - SensorData sensorData; - GeomagneticData geomagneticData; - RationMatrixData rationMatrixData; - ReserveData reserveData; -}; - -struct BusinessError { - int32_t code; - string message; - string name; - string stack; -}; - -typedef enum CallbackDataType { - FAIL = -1, - OFF_CALLBACK = 0, - ON_CALLBACK = 1, - ONCE_CALLBACK = 2, - GET_GEOMAGNETIC_FIELD = 3, - GET_ALTITUDE = 4, - GET_GEOMAGNITIC_DIP = 5, - GET_ANGLE_MODIFY = 6, - CREATE_ROTATION_MATRIX = 7, - TRANSFORM_COORDINATE_SYSTEM = 8, - CREATE_QUATERNION = 9, - GET_DIRECTION = 10, - ROTATION_INCLINATION_MATRIX = 11, - GET_SENSOR_LIST = 12, - GET_SINGLE_SENSOR = 13 -} CallbackDataType; - -struct AsyncCallbackInfo { - napi_env env; - napi_async_work asyncWork; - napi_deferred deferred; - napi_ref callback[1] = { 0 }; - CallbackData data; - BusinessError error; - CallbackDataType type; - vector sensorInfos; -}; - -using ConvertDataFunc = void(*)(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]); - -bool IsSameValue(napi_env env, napi_value lhs, napi_value rhs); - -bool IsMatchType(napi_env env, napi_value value, napi_valuetype type); - -napi_value GetNapiInt32(int32_t number, napi_env env); - -int32_t GetCppInt32(napi_value value, napi_env env); - -bool GetCppBool(napi_value value, napi_env env); - -void EmitAsyncCallbackWork(AsyncCallbackInfo *async_callback_info); - -void EmitUvEventLoop(AsyncCallbackInfo **async_callback_info); - -int64_t GetCppInt64(napi_value value, napi_env env); - -napi_value NapiGetNamedProperty(napi_value jsonObject, string name, napi_env env); - -napi_value GetUndefined(napi_env env); - -void EmitPromiseWork(AsyncCallbackInfo *asyncCallbackInfo); - -bool IsMatchArrayType(napi_env env, napi_value value, napi_typedarray_type type); - -vector GetCppArrayFloat(napi_env env, napi_value value); - -float GetCppFloat(napi_env env, napi_value value); - -napi_value GreateBusinessError(napi_env env, int32_t errCode, string errMessage, +using ConvertDataFunc = bool(*)(const napi_env &env, sptr asyncCallbackInfo, + napi_value result[2]); + +bool IsSameValue(const napi_env &env, const napi_value &lhs, const napi_value &rhs); +bool IsMatchType(const napi_env &env, const napi_value &value, const napi_valuetype &type); +bool IsMatchArrayType(const napi_env &env, const napi_value &value); +bool GetCppInt32(const napi_env &env, const napi_value &value, int32_t &number); +bool GetCppDouble(const napi_env &env, const napi_value &value, double &number); +bool GetCppBool(const napi_env &env, const napi_value &value); +bool GetFloatArray(const napi_env &env, const napi_value &value, vector &array); +bool GetCppInt64(const napi_env &env, const napi_value &value, int64_t &number); +napi_value GetNamedProperty(const napi_env &env, const napi_value &object, string name); +bool GetCppFloat(const napi_env &env, const napi_value &value, float &number); +napi_value GetNapiInt32(const napi_env &env, int32_t number); +void EmitAsyncCallbackWork(sptr asyncCallbackInfo); +void EmitUvEventLoop(sptr asyncCallbackInfo); +void EmitPromiseWork(sptr asyncCallbackInfo); + +napi_value GreateBusinessError(const napi_env &env, int32_t errCode, string errMessage, string errName, string errStack); - -bool IsMatchArrayType(napi_env env, napi_value value); - -void ConvertToFailData(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]); - -void ConvertToNoData(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]); - -void ConvertToGeomagneticData(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]); - -void ConvertToNumber(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]); - -void ConvertToArray(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]); - -void ConvertToRotationMatrix(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]); - -void ConvertToSensorData(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]); - -void CreateNapiArray(napi_env env, float *data, int32_t dataLength, napi_value result); - -void ConvertToSensorInfos(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]); - -void ConvertToSingleSensor(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]); +bool ConvertToFailData(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]); +bool ConvertToGeomagneticData(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]); +bool ConvertToNumber(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]); +bool ConvertToArray(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]); +bool ConvertToRotationMatrix(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]); +bool ConvertToSensorData(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]); +bool CreateNapiArray(const napi_env &env, float *data, int32_t dataLength, napi_value &result); +bool ConvertToSensorInfos(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]); +bool ConvertToSingleSensor(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]); + +#define GET_AND_THROW_NAPI_ERROR(env, message) \ + do { \ + const napi_extended_error_info* errorInfo = nullptr; \ + napi_get_last_error_info((env), &errorInfo); \ + bool isPending = false; \ + napi_is_exception_pending((env), &isPending); \ + if (!isPending && errorInfo != nullptr) { \ + std::string errDesc = std::string(__FUNCTION__) + ": " + #message + " fail. "; \ + std::string errorMessage = \ + errorInfo->error_message != nullptr ? errorInfo->error_message : "empty error message"; \ + errDesc += errorMessage; \ + napi_throw_error((env), nullptr, errDesc.c_str()); \ + } \ + } while (0) + +#define CHKNCR(env, cond, message, retVal) \ + do { \ + if (!(cond)) { \ + SEN_HILOGE("(%{public}s)", #message); \ + auto errDesc = std::string(__FUNCTION__) + ": " + #message; \ + napi_throw_error(env, nullptr, errDesc.c_str()); \ + return retVal; \ + } \ + } while (0) + +#define CHKNCP(env, cond, message) \ + do { \ + if (!(cond)) { \ + SEN_HILOGE("(%{public}s)", #message); \ + auto errDesc = std::string(__FUNCTION__) + ": " + #message; \ + napi_throw_error(env, nullptr, errDesc.c_str()); \ + return nullptr; \ + } \ + } while (0) + +#define CHKNCF(env, cond, message) \ + do { \ + if (!(cond)) { \ + SEN_HILOGE("(%{public}s)", #message); \ + auto errDesc = std::string(__FUNCTION__) + ": " + #message; \ + napi_throw_error(env, nullptr, errDesc.c_str()); \ + return false; \ + } \ + } while (0) + +#define CHKNCV(env, cond, message) \ + do { \ + if (!(cond)) { \ + SEN_HILOGE("(%{public}s)", #message); \ + auto errDesc = std::string(__FUNCTION__) + ": " + #message; \ + napi_throw_error(env, nullptr, errDesc.c_str()); \ + return; \ + } \ + } while (0) + +#define CHKNCC(env, cond, message) \ + { \ + if (!(cond)) { \ + SEN_HILOGW("(%{public}s)", #message); \ + auto errDesc = std::string(__FUNCTION__) + ": " + #message; \ + napi_throw_error(env, nullptr, errDesc.c_str()); \ + continue; \ + } \ + } + +#define CHKNRR(env, state, message, retVal) \ + do { \ + if ((state) != napi_ok) { \ + SEN_HILOGE("(%{public}s) fail", #message); \ + GET_AND_THROW_NAPI_ERROR((env), (message)); \ + return retVal; \ + } \ + } while (0) + +#define CHKNRP(env, state, message) \ + do { \ + if ((state) != napi_ok) { \ + SEN_HILOGE("(%{public}s) fail", #message); \ + GET_AND_THROW_NAPI_ERROR((env), (message)); \ + return nullptr; \ + } \ + } while (0) + +#define CHKNRF(env, state, message) \ + do { \ + if ((state) != napi_ok) { \ + SEN_HILOGE("(%{public}s) fail", #message); \ + GET_AND_THROW_NAPI_ERROR((env), (message)); \ + return false; \ + } \ + } while (0) + +#define CHKNRV(env, state, message) \ + do { \ + if ((state) != napi_ok) { \ + SEN_HILOGE("(%{public}s) fail", #message); \ + GET_AND_THROW_NAPI_ERROR((env), (message)); \ + return; \ + } \ + } while (0) + +#define CHKNRC(env, state, message) \ + { \ + if ((state) != napi_ok) { \ + SEN_HILOGW("(%{public}s) fail", #message); \ + GET_AND_THROW_NAPI_ERROR((env), (message)); \ + continue; \ + } \ + } +} // namespace Sensors +} // namespace OHOS #endif // SENSOR_NAPI_UTILS_H diff --git a/interfaces/plugin/include/sensor_system_js.h b/interfaces/plugin/include/sensor_system_js.h index 3b8dd9bd2530dfde679813c3a4d9df1324629dff..6235883ff28af95f1a3ce1317dc0e228e3e1fe7c 100644 --- a/interfaces/plugin/include/sensor_system_js.h +++ b/interfaces/plugin/include/sensor_system_js.h @@ -16,7 +16,8 @@ #define SENSOR_SYSTEM_JS_H #include "napi/native_api.h" #include "napi/native_node_api.h" - +namespace OHOS { +namespace Sensors { napi_value SubscribeAccelerometer(napi_env env, napi_callback_info info); napi_value UnsubscribeAccelerometer(napi_env env, napi_callback_info info); napi_value SubscribeCompass(napi_env env, napi_callback_info info); @@ -44,5 +45,6 @@ napi_value SubscribeMagnetic(napi_env env, napi_callback_info info); napi_value UnsubscribeMagnetic(napi_env env, napi_callback_info info); napi_value SubscribeHall(napi_env env, napi_callback_info info); napi_value UnsubscribeHall(napi_env env, napi_callback_info info); - +} // namespace Sensors +} // namespace OHOS #endif // SENSOR_SYSTEM_JS_H \ No newline at end of file diff --git a/interfaces/plugin/src/sensor_js.cpp b/interfaces/plugin/src/sensor_js.cpp index af18c587579d6ea94d5c230a32dfd060d6a281e2..c0cc3a63b1477eb6330a93b02186e62624c60589 100644 --- a/interfaces/plugin/src/sensor_js.cpp +++ b/interfaces/plugin/src/sensor_js.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -27,158 +27,188 @@ #include "geomagnetic_field.h" -#include "hilog/log.h" #include "napi/native_api.h" #include "napi/native_node_api.h" #include "refbase.h" #include "securec.h" -#include "sensor_agent.h" #include "sensor_algorithm.h" #include "sensor_napi_utils.h" #include "sensor_system_js.h" +namespace OHOS { +namespace Sensors { +namespace { +constexpr int32_t QUATERNION_LENGTH = 4; +constexpr int32_t ROTATION_VECTOR_LENGTH = 3; +constexpr int32_t REPORTING_INTERVAL = 200000000; +constexpr int32_t INVALID_SENSOR_ID = -1; +} -using namespace OHOS::HiviewDFX; -static constexpr HiLogLabel LABEL = {LOG_CORE, 0xD002708, "SensorJsAPI"}; - -const int32_t REPORTING_INTERVAL = 200000000; - -static std::map g_onceCallbackInfos; -static std::map> g_onCallbackInfos; +static std::mutex onMutex_; +static std::mutex onceMutex_; +static std::map>> g_onceCallbackInfos; +static std::map>> g_onCallbackInfos; +static bool CheckSubscribe(int32_t sensorTypeId) +{ + std::lock_guard onCallbackLock(onMutex_); + auto iter = g_onCallbackInfos.find(sensorTypeId); + CHKCF((iter != g_onCallbackInfos.end()), "No client subscribe"); + return true; +} -static void DataCallbackImpl(SensorEvent *event) +static bool copySensorData(sptr callbackInfo, SensorEvent *event) { - if (event == nullptr) { - HiLog::Error(LABEL, "%{public}s event is null", __func__); - return; + CHKPF(callbackInfo); + CHKPF(event); + callbackInfo->data.sensorData.sensorTypeId = event->sensorTypeId; + callbackInfo->data.sensorData.dataLength = event->dataLen; + callbackInfo->data.sensorData.timestamp = event->timestamp; + auto data = reinterpret_cast(event->data); + CHKPF(data); + if (memcpy_s(callbackInfo->data.sensorData.data, event->dataLen, data, event->dataLen) != EOK) { + SEN_HILOGE("Copy data failed"); + return false; } + return true; +} + +static void EmitOnCallback(SensorEvent *event) +{ + CHKPV(event); int32_t sensorTypeId = event->sensorTypeId; - float *data = (float *)(event->data); - if (g_onCallbackInfos.find(sensorTypeId) != g_onCallbackInfos.end()) { - for (uint32_t i = 0; i < g_onCallbackInfos[sensorTypeId].size(); ++i) { - g_onCallbackInfos[sensorTypeId][i]->data.sensorData.sensorTypeId = sensorTypeId; - g_onCallbackInfos[sensorTypeId][i]->data.sensorData.dataLength = event->dataLen; - g_onCallbackInfos[sensorTypeId][i]->data.sensorData.timestamp = event->timestamp; - errno_t ret = memcpy_s(g_onCallbackInfos[sensorTypeId][i]->data.sensorData.data, - event->dataLen, data, event->dataLen); - if (ret != EOK) { - HiLog::Error(LABEL, "%{public}s copy data failed", __func__); - return; - } - g_onCallbackInfos[sensorTypeId][i]->type = ON_CALLBACK; - EmitUvEventLoop(&g_onCallbackInfos[sensorTypeId][i]); + CHKCV(CheckSubscribe(sensorTypeId), "No client subscribe"); + + std::lock_guard onCallbackLock(onMutex_); + auto onCallbackInfos = g_onCallbackInfos[sensorTypeId]; + for (auto &onCallbackInfo : onCallbackInfos) { + if (!copySensorData(onCallbackInfo, event)) { + SEN_HILOGE("Copy sensor data failed"); + continue; } + EmitUvEventLoop(onCallbackInfo); } +} - if (g_onceCallbackInfos.find(sensorTypeId) == g_onceCallbackInfos.end()) { - return; - } - struct AsyncCallbackInfo *onceCallbackInfo = g_onceCallbackInfos[sensorTypeId]; - onceCallbackInfo->data.sensorData.sensorTypeId = sensorTypeId; - onceCallbackInfo->data.sensorData.dataLength = event->dataLen; - onceCallbackInfo->data.sensorData.timestamp = event->timestamp; - errno_t ret = memcpy_s(onceCallbackInfo->data.sensorData.data, event->dataLen, data, event->dataLen); - if (ret != EOK) { - HiLog::Error(LABEL, "%{public}s copy data failed", __func__); - return; - } - onceCallbackInfo->type = ONCE_CALLBACK; - EmitUvEventLoop(&g_onceCallbackInfos[sensorTypeId]); - if (g_onCallbackInfos.find(sensorTypeId) == g_onCallbackInfos.end()) { - HiLog::Debug(LABEL, "%{public}s no subscription to change sensor data, need to cancel registration", __func__); - UnsubscribeSensor(sensorTypeId); +static void EmitOnceCallback(SensorEvent *event) +{ + CHKPV(event); + int32_t sensorTypeId = event->sensorTypeId; + std::lock_guard onceCallbackLock(onceMutex_); + auto iter = g_onceCallbackInfos.find(sensorTypeId); + CHKCV((iter != g_onceCallbackInfos.end()), "No client subscribe once"); + + auto onceCallbackInfos = g_onceCallbackInfos[sensorTypeId]; + for (auto &onceCallbackInfo : onceCallbackInfos) { + if (!copySensorData(onceCallbackInfo, event)) { + SEN_HILOGE("Copy sensor data failed"); + continue; + } + EmitUvEventLoop(onceCallbackInfo); } + g_onceCallbackInfos[sensorTypeId].clear(); g_onceCallbackInfos.erase(sensorTypeId); + + CHKCV((!CheckSubscribe(sensorTypeId)), "Has client subscribe, not need cancel subscribe"); + UnsubscribeSensor(sensorTypeId); +} + +static void DataCallbackImpl(SensorEvent *event) +{ + CHKPV(event); + EmitOnCallback(event); + EmitOnceCallback(event); } static const SensorUser user = { .callback = DataCallbackImpl }; -static int32_t UnsubscribeSensor(int32_t sensorTypeId) +static bool UnsubscribeSensor(int32_t sensorTypeId) { - HiLog::Info(LABEL, "%{public}s in", __func__); - int32_t ret = DeactivateSensor(sensorTypeId, &user); - if (ret != OHOS::ERR_OK) { - HiLog::Error(LABEL, "%{public}s DeactivateSensor failed", __func__); - return ret; - } - ret = UnsubscribeSensor(sensorTypeId, &user); - if (ret != OHOS::ERR_OK) { - HiLog::Error(LABEL, "%{public}s UnsubscribeSensor failed", __func__); - return ret; - } - HiLog::Info(LABEL, "%{public}s left", __func__); - return 0; + CALL_LOG_ENTER; + CHKCF((DeactivateSensor(sensorTypeId, &user) == SUCCESS), "DeactivateSensor failed"); + CHKCF((UnsubscribeSensor(sensorTypeId, &user) == SUCCESS), "UnsubscribeSensor failed"); + return true; } -static int32_t SubscribeSensor(int32_t sensorTypeId, int64_t interval, RecordSensorCallback callback) +static bool SubscribeSensor(int32_t sensorTypeId, int64_t interval, RecordSensorCallback callback) { - HiLog::Info(LABEL, "%{public}s in, sensorTypeId: %{public}d", __func__, sensorTypeId); - int32_t ret = SubscribeSensor(sensorTypeId, &user); - if (ret != OHOS::ERR_OK) { - HiLog::Error(LABEL, "%{public}s subscribeSensor failed", __func__); - return ret; - } - ret = SetBatch(sensorTypeId, &user, interval, 0); - if (ret != OHOS::ERR_OK) { - HiLog::Error(LABEL, "%{public}s set batch failed", __func__); - return ret; + CALL_LOG_ENTER; + CHKCF((SubscribeSensor(sensorTypeId, &user) == ERR_OK), "SubscribeSensor failed"); + CHKCF((SetBatch(sensorTypeId, &user, interval, 0) == ERR_OK), "Set batch failed"); + CHKCF((ActivateSensor(sensorTypeId, &user) == ERR_OK), "ActivateSensor failed"); + return true; +} + +static bool IsOnceSubscribed(napi_env env, int32_t sensorTypeId, napi_value callback) +{ + CALL_LOG_ENTER; + if (auto iter = g_onceCallbackInfos.find(sensorTypeId); iter == g_onceCallbackInfos.end()) { + SEN_HILOGW("already subscribed, sensorTypeId: %{public}d", sensorTypeId); + return false; } - ret = ActivateSensor(sensorTypeId, &user); - if (ret != OHOS::ERR_OK) { - HiLog::Error(LABEL, "%{public}s activateSensor failed", __func__); - return ret; + + std::vector> callbackInfos = g_onceCallbackInfos[sensorTypeId]; + for (auto callbackInfo : callbackInfos) { + CHKNCC(env, (callbackInfo != nullptr), "callbackInfo is null"); + napi_value sensorCallback = nullptr; + CHKNRF(env, napi_get_reference_value(env, callbackInfo->callback[0], &sensorCallback), + "napi_get_reference_value"); + if (IsSameValue(env, callback, sensorCallback)) { + return true; + } } - return 0; + return false; +} + +static void UpdateOnceCallback(napi_env env, int32_t sensorTypeId, napi_value callback) +{ + CALL_LOG_ENTER; + std::lock_guard onceCallbackLock(onceMutex_); + CHKNCV(env, !IsOnceSubscribed(env, sensorTypeId, callback), "The callback has been subscribed"); + + sptr asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo(env, ONCE_CALLBACK); + CHKPV(asyncCallbackInfo); + CHKNRV(env, napi_create_reference(env, callback, 1, &asyncCallbackInfo->callback[0]), + "napi_create_reference"); + std::vector> callbackInfos = g_onceCallbackInfos[sensorTypeId]; + callbackInfos.push_back(asyncCallbackInfo); + g_onceCallbackInfos[sensorTypeId] = callbackInfos; } static napi_value Once(napi_env env, napi_callback_info info) { - HiLog::Info(LABEL, "%{public}s in", __func__); + CALL_LOG_ENTER; size_t argc = 2; napi_value args[2] = { 0 }; napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, NULL)); - - if (argc != 2) { - HiLog::Error(LABEL, "%{public}s Invalid input, number of argument should be two", __func__); - return nullptr; - } - if (!IsMatchType(env, args[0], napi_number) || !IsMatchType(env, args[1], napi_function)) { - HiLog::Error(LABEL, "%{public}s argument is invalid", __func__); - return nullptr; - } - int32_t sensorTypeId = GetCppInt32(args[0], env); - AsyncCallbackInfo *asyncCallbackInfo = new AsyncCallbackInfo { - .env = env, - .asyncWork = nullptr, - .deferred = nullptr, - }; - napi_create_reference(env, args[1], 1, &asyncCallbackInfo->callback[0]); - g_onceCallbackInfos[sensorTypeId] = asyncCallbackInfo; - if (g_onCallbackInfos.find(sensorTypeId) == g_onCallbackInfos.end()) { - HiLog::Debug(LABEL, "%{public}s no subscription to change sensor data, registration is required", __func__); - int32_t ret = SubscribeSensor(sensorTypeId, 200000000, DataCallbackImpl); - if (ret != OHOS::ERR_OK) { - HiLog::Error(LABEL, "%{public}s subscribe Sensor failed", __func__); - g_onceCallbackInfos.erase(sensorTypeId); - return nullptr; - } - } - HiLog::Info(LABEL, "%{public}s left", __func__); + CHKNRP(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr), "napi_get_cb_info"); + CHKNCP(env, (argc == 2), "The number of parameters is not valid"); + CHKNCP(env, IsMatchType(env, args[0], napi_number), "Wrong argument type, should be number"); + CHKNCP(env, IsMatchType(env, args[1], napi_function), "Wrong argument type, should be function"); + int32_t sensorTypeId = INVALID_SENSOR_ID; + CHKNCP(env, GetCppInt32(env, args[0], sensorTypeId), "Wrong argument type, get number fail"); + + if (!CheckSubscribe(sensorTypeId)) { + SEN_HILOGD("No subscription to change sensor data, registration is required"); + CHKNCP(env, SubscribeSensor(sensorTypeId, REPORTING_INTERVAL, DataCallbackImpl), "SubscribeSensor failed"); + } + UpdateOnceCallback(env, sensorTypeId, args[1]); return nullptr; } static bool IsSubscribed(napi_env env, int32_t sensorTypeId, napi_value callback) { - HiLog::Info(LABEL, "%{public}s in, sensorTypeId: %{public}d", __func__, sensorTypeId); - if (g_onCallbackInfos.find(sensorTypeId) == g_onCallbackInfos.end()) { + CALL_LOG_ENTER; + if (auto iter = g_onCallbackInfos.find(sensorTypeId); iter == g_onCallbackInfos.end()) { + SEN_HILOGW("already subscribe, sensorTypeId: %{public}d", sensorTypeId); return false; } - std::vector callbackInfos = g_onCallbackInfos[sensorTypeId]; + std::vector> callbackInfos = g_onCallbackInfos[sensorTypeId]; for (auto callbackInfo : callbackInfos) { + CHKNCC(env, (callbackInfo != nullptr), "callbackInfo is null"); napi_value sensorCallback = nullptr; - napi_get_reference_value(env, callbackInfo->callback[0], &sensorCallback); + CHKNRF(env, napi_get_reference_value(env, callbackInfo->callback[0], &sensorCallback), + "napi_get_reference_value"); if (IsSameValue(env, callback, sensorCallback)) { return true; } @@ -188,90 +218,70 @@ static bool IsSubscribed(napi_env env, int32_t sensorTypeId, napi_value callback static void UpdateCallbackInfos(napi_env env, int32_t sensorTypeId, napi_value callback) { - if (IsSubscribed(env, sensorTypeId, callback)) { - HiLog::Debug(LABEL, "%{public}s the callback has been subscribed", __func__); - return; - } - AsyncCallbackInfo *asyncCallbackInfo = new AsyncCallbackInfo { - .env = env, - .asyncWork = nullptr, - .deferred = nullptr, - .type = ON_CALLBACK, - }; - napi_create_reference(env, callback, 1, &asyncCallbackInfo->callback[0]); - std::vector callbackInfos = g_onCallbackInfos[sensorTypeId]; + CALL_LOG_ENTER; + std::lock_guard onCallbackLock(onMutex_); + CHKNCV(env, !IsSubscribed(env, sensorTypeId, callback), "This callback has been subscribed"); + sptr asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo(env, ON_CALLBACK); + CHKPV(asyncCallbackInfo); + CHKNRV(env, napi_create_reference(env, callback, 1, &asyncCallbackInfo->callback[0]), + "napi_create_reference"); + std::vector> callbackInfos = g_onCallbackInfos[sensorTypeId]; callbackInfos.push_back(asyncCallbackInfo); g_onCallbackInfos[sensorTypeId] = callbackInfos; } static napi_value On(napi_env env, napi_callback_info info) { - HiLog::Debug(LABEL, "%{public}s in", __func__); + CALL_LOG_ENTER; size_t argc = 3; napi_value args[3] = { 0 }; napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, NULL)); - if (argc <= 1 || argc > 3) { - HiLog::Error(LABEL, "%{public}s the number of input parameters does not match", __func__); - return nullptr; - } - if (!IsMatchType(env, args[0], napi_number) || !IsMatchType(env, args[1], napi_function)) { - HiLog::Error(LABEL, "%{public}s the first parameter should be napi_number type", __func__); - return nullptr; - } - int32_t sensorTypeId = GetCppInt32(args[0], env); + CHKNRP(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr), "napi_get_cb_info"); + CHKNCP(env, ((argc == 2) || (argc == 3)), "The number of parameters is not valid"); + CHKNCP(env, IsMatchType(env, args[0], napi_number), "Wrong argument type, should be number"); + CHKNCP(env, IsMatchType(env, args[1], napi_function), "Wrong argument type, should be function"); + + int32_t sensorTypeId = INVALID_SENSOR_ID; + CHKNCP(env, GetCppInt32(env, args[0], sensorTypeId), "Wrong argument type, get number fail"); int64_t interval = REPORTING_INTERVAL; + if (argc == 3) { - napi_value value = NapiGetNamedProperty(args[2], "interval", env); - if (!IsMatchType(env, value, napi_number)) { - HiLog::Error(LABEL, "%{public}s argument should be napi_number type", __func__); - return nullptr; - } - interval = GetCppInt64(value, env); - HiLog::Debug(LABEL, "%{public}s interval is %{public}" PRId64, __func__, interval); - } - int32_t ret = SubscribeSensor(sensorTypeId, interval, DataCallbackImpl); - if (ret != OHOS::ERR_OK) { - HiLog::Error(LABEL, "%{public}s subscribeSensor failed", __func__); - return nullptr; + napi_value value = GetNamedProperty(env, args[2], "interval"); + CHKNCP(env, IsMatchType(env, value, napi_number), "Wrong argument type, interval should be number"); + CHKNCP(env, GetCppInt64(env, value, interval), "Wrong argument type, get INT64 number fail"); + SEN_HILOGD("Interval is %{public}" PRId64, interval); } + CHKNCP(env, SubscribeSensor(sensorTypeId, interval, DataCallbackImpl), "SubscribeSensor failed"); UpdateCallbackInfos(env, sensorTypeId, args[1]); - HiLog::Debug(LABEL, "%{public}s end", __func__); return nullptr; } static void RemoveAllCallback(napi_env env, int32_t sensorTypeId) { - std::vector callbackInfos = g_onCallbackInfos[sensorTypeId]; - for (auto callbackInfo : callbackInfos) { - napi_delete_reference(env, callbackInfo->callback[0]); - callbackInfo->callback[0] = nullptr; - delete callbackInfo; - callbackInfo = nullptr; - } + CALL_LOG_ENTER; + std::lock_guard onCallbackLock(onMutex_); + g_onCallbackInfos[sensorTypeId].clear(); g_onCallbackInfos.erase(sensorTypeId); } static uint32_t RemoveCallback(napi_env env, int32_t sensorTypeId, napi_value callback) { - std::vector callbackInfos = g_onCallbackInfos[sensorTypeId]; - std::vector::iterator iter; - for (iter = callbackInfos.begin(); iter != callbackInfos.end(); ++iter) { - if (*iter == nullptr || (*iter)->callback[0] == nullptr) { - continue; - } + CALL_LOG_ENTER; + std::lock_guard onCallbackLock(onMutex_); + std::vector> callbackInfos = g_onCallbackInfos[sensorTypeId]; + for (auto iter = callbackInfos.begin(); iter != callbackInfos.end(); ++iter) { + CHKPC(*iter); napi_value sensorCallback = nullptr; - napi_get_reference_value(env, (*iter)->callback[0], &sensorCallback); + CHKNRC(env, napi_get_reference_value(env, (*iter)->callback[0], &sensorCallback), + "napi_get_reference_value"); if (IsSameValue(env, callback, sensorCallback)) { - napi_delete_reference(env, (*iter)->callback[0]); - (*iter)->callback[0] = nullptr; - delete *iter; - *iter = nullptr; callbackInfos.erase(iter++); + SEN_HILOGD("Remove callback success"); break; } } if (callbackInfos.empty()) { + SEN_HILOGD("No subscription to change sensor data"); g_onCallbackInfos.erase(sensorTypeId); return 0; } @@ -281,69 +291,58 @@ static uint32_t RemoveCallback(napi_env env, int32_t sensorTypeId, napi_value ca static napi_value Off(napi_env env, napi_callback_info info) { - HiLog::Info(LABEL, "%{public}s in", __func__); + CALL_LOG_ENTER; size_t argc = 2; napi_value args[2] = { 0 }; napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, NULL)); - if (argc < 1 || argc > 2 || !IsMatchType(env, args[0], napi_number)) { - HiLog::Error(LABEL, "%{public}s Invalid input", __func__); - return nullptr; - } - int32_t sensorTypeId = GetCppInt32(args[0], env); - if (g_onCallbackInfos.find(sensorTypeId) == g_onCallbackInfos.end() - || (argc == 2 && !IsSubscribed(env, sensorTypeId, args[1]))) { - HiLog::Error(LABEL, "%{public}s should subscribe first", __func__); - return nullptr; - } - if (argc == 2 && RemoveCallback(env, sensorTypeId, args[1]) != 0) { - HiLog::Debug(LABEL, "%{public}s there are other client registrations as well", __func__); - return nullptr; - } + CHKNRP(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr), "napi_get_cb_info"); + CHKNCP(env, ((argc == 1) || (argc == 2)), "The number of parameters is not valid"); + CHKNCP(env, IsMatchType(env, args[0], napi_number), "Wrong argument type, should be number"); + int32_t sensorTypeId = INVALID_SENSOR_ID; + CHKNCP(env, GetCppInt32(env, args[0], sensorTypeId), "Wrong argument type, get number fail"); + CHKNCP(env, (CheckSubscribe(sensorTypeId)), "Should subscribe first"); + if (argc == 1) { RemoveAllCallback(env, sensorTypeId); + } else { + CHKNCP(env, IsMatchType(env, args[1], napi_function), "Wrong argument type, should be function"); + CHKNCP(env, (RemoveCallback(env, sensorTypeId, args[1]) == 0), + "There are other client subscribe as well, not need unsubscribe"); } - int32_t ret = UnsubscribeSensor(sensorTypeId); - if (ret != OHOS::ERR_OK) { - HiLog::Error(LABEL, "%{public}s UnsubscribeSensor failed", __func__); - } + CHKNCP(env, UnsubscribeSensor(sensorTypeId), "UnsubscribeSensor failed"); return nullptr; } static napi_value GetGeomagneticField(napi_env env, napi_callback_info info) { - HiLog::Info(LABEL, "%{public}s in", __func__); + CALL_LOG_ENTER; size_t argc = 3; napi_value args[3] = { 0 }; napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr)); - if (argc < 2 || argc > 3) { - HiLog::Error(LABEL, "%{public}s the number of input parameters does not match", __func__); - return nullptr; - } - if (!IsMatchType(env, args[0], napi_object) || !IsMatchType(env, args[1], napi_number)) { - HiLog::Error(LABEL, "%{public}s argument is invalid", __func__); - return nullptr; - } - napi_value napiLatitude = NapiGetNamedProperty(args[0], "latitude", env); + CHKNRP(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr), "napi_get_cb_info"); + CHKNCP(env, ((argc == 2) || (argc == 3)), "The number of parameters is not valid"); + CHKNCP(env, IsMatchType(env, args[0], napi_object), "Wrong argument type, should be object"); + CHKNCP(env, IsMatchType(env, args[1], napi_number), "Wrong argument type, should be number"); + + napi_value napiLatitude = GetNamedProperty(env, args[0], "latitude"); + CHKNCP(env, (napiLatitude != nullptr), "napiLatitude is null"); double latitude = 0; - napi_get_value_double(env, napiLatitude, &latitude); - napi_value napiLongitude = NapiGetNamedProperty(args[0], "longitude", env); + CHKNCP(env, GetCppDouble(env, napiLatitude, latitude), "Get latitude fail"); + napi_value napiLongitude = GetNamedProperty(env, args[0], "longitude"); + CHKNCP(env, (napiLongitude != nullptr), "napiLongitude is null"); double longitude = 0; - napi_get_value_double(env, napiLongitude, &longitude); - napi_value napiAltitude = NapiGetNamedProperty(args[0], "altitude", env); + CHKNCP(env, GetCppDouble(env, napiLongitude, longitude), "Get longitude fail"); + napi_value napiAltitude = GetNamedProperty(env, args[0], "altitude"); + CHKNCP(env, (napiAltitude != nullptr), "napiAltitude is null"); double altitude = 0; - napi_get_value_double(env, napiAltitude, &altitude); + CHKNCP(env, GetCppDouble(env, napiAltitude, altitude), "Get altitude fail"); int64_t timeMillis = 0; - timeMillis = GetCppInt64(args[1], env); + CHKNCP(env, GetCppInt64(env, args[1], timeMillis), "Get timeMillis fail"); GeomagneticField geomagneticField(latitude, longitude, altitude, timeMillis); - AsyncCallbackInfo *asyncCallbackInfo = new AsyncCallbackInfo { - .env = env, - .asyncWork = nullptr, - .deferred = nullptr, - .type = GET_GEOMAGNETIC_FIELD, - }; + sptr asyncCallbackInfo = + new (std::nothrow) AsyncCallbackInfo(env, GET_GEOMAGNETIC_FIELD); + CHKPP(asyncCallbackInfo); asyncCallbackInfo->data.geomagneticData = { .x = geomagneticField.ObtainX(), .y = geomagneticField.ObtainY(), @@ -353,451 +352,419 @@ static napi_value GetGeomagneticField(napi_env env, napi_callback_info info) .levelIntensity = geomagneticField.ObtainLevelIntensity(), .totalIntensity = geomagneticField.ObtainTotalIntensity(), }; + if (argc == 2) { - napi_deferred deferred = nullptr; napi_value promise = nullptr; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - asyncCallbackInfo->deferred = deferred; + CHKNRP(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise), + "napi_create_promise"); EmitPromiseWork(asyncCallbackInfo); return promise; } - if (!IsMatchType(env, args[2], napi_function)) { - HiLog::Error(LABEL, "%{public}s argument should be function type", __func__); - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - return nullptr; - } - napi_create_reference(env, args[2], 1, &asyncCallbackInfo->callback[0]); + CHKNCP(env, IsMatchType(env, args[2], napi_function), "Wrong argument type, should be function"); + CHKNRP(env, napi_create_reference(env, args[2], 1, &asyncCallbackInfo->callback[0]), + "napi_create_reference"); EmitAsyncCallbackWork(asyncCallbackInfo); return nullptr; } static napi_value TransformCoordinateSystem(napi_env env, napi_callback_info info) { + CALL_LOG_ENTER; size_t argc = 3; napi_value args[3] = { 0 }; napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr)); - if (argc < 2 || argc > 3 || !IsMatchArrayType(env, args[0]) || !IsMatchType(env, args[1], napi_object)) { - HiLog::Error(LABEL, "%{public}s the number of input parameters does not match", __func__); - return nullptr; - } - std::vector inRotationVector = GetCppArrayFloat(env, args[0]); - napi_value napiAxisX = NapiGetNamedProperty(args[1], "axisX", env); - napi_value napiAxisY = NapiGetNamedProperty(args[1], "axisY", env); - if ((!IsMatchType(env, napiAxisX, napi_number)) || (!IsMatchType(env, napiAxisY, napi_number))) { - HiLog::Error(LABEL, "%{public}s argument should be napi_number type", __func__); - return nullptr; - } - int32_t axisX = GetCppInt32(napiAxisX, env); - int32_t axisY = GetCppInt32(napiAxisY, env); - AsyncCallbackInfo *asyncCallbackInfo = new AsyncCallbackInfo { - .env = env, - .asyncWork = nullptr, - .deferred = nullptr, - .type = TRANSFORM_COORDINATE_SYSTEM, - }; - int32_t inRotationVectorLength = static_cast(inRotationVector.size()); - std::vector outRotationVector(inRotationVectorLength); - std::unique_ptr sensorAlgorithm = std::make_unique(); - int32_t ret = sensorAlgorithm->transformCoordinateSystem(inRotationVector, axisX, axisY, outRotationVector); + CHKNRP(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr), "napi_get_cb_info"); + CHKNCP(env, ((argc == 2) || (argc == 3)), "The number of parameters is not valid"); + CHKNCP(env, IsMatchArrayType(env, args[0]), "Wrong argument type, should be array"); + CHKNCP(env, IsMatchType(env, args[1], napi_object), "Wrong argument type, should be object"); + + std::vector inRotationVector; + CHKNCP(env, GetFloatArray(env, args[0], inRotationVector), "Wrong argument type, get inRotationVector fail"); + napi_value napiAxisX = GetNamedProperty(env, args[1], "axisX"); + CHKNCP(env, (napiAxisX != nullptr), "napiAxisX is null"); + int32_t axisX = 0; + CHKNCP(env, GetCppInt32(env, napiAxisX, axisX), "Get axisY fail"); + napi_value napiAxisY = GetNamedProperty(env, args[1], "axisY"); + CHKNCP(env, (napiAxisY != nullptr), "napiAxisY is null"); + int32_t axisY = 0; + CHKNCP(env, GetCppInt32(env, napiAxisY, axisY), "Get axisY fail"); + + sptr asyncCallbackInfo = + new (std::nothrow) AsyncCallbackInfo(env, TRANSFORM_COORDINATE_SYSTEM); + CHKPP(asyncCallbackInfo); + size_t length = inRotationVector.size(); + std::vector outRotationVector(length); + SensorAlgorithm sensorAlgorithm; + int32_t ret = sensorAlgorithm.transformCoordinateSystem(inRotationVector, axisX, axisY, outRotationVector); if (ret != OHOS::ERR_OK) { - HiLog::Error(LABEL, "%{public}s EmitPromiseWork failed", __func__); + SEN_HILOGE("Transform coordinate system fail"); asyncCallbackInfo->type = FAIL; asyncCallbackInfo->error.code = ret; } else { - for (int32_t i = 0; i < inRotationVectorLength; i++) { + for (size_t i = 0; i < length; ++i) { asyncCallbackInfo->data.reserveData.reserve[i] = outRotationVector[i]; } - asyncCallbackInfo->data.reserveData.length = inRotationVectorLength; + asyncCallbackInfo->data.reserveData.length = length; } if (argc == 2) { - napi_deferred deferred = nullptr; napi_value promise = nullptr; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - asyncCallbackInfo->deferred = deferred; + CHKNRP(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise), "napi_create_promise"); EmitPromiseWork(asyncCallbackInfo); return promise; } - if (!IsMatchType(env, args[2], napi_function)) { - HiLog::Error(LABEL, "%{public}s argument should be napi_function type", __func__); - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - return nullptr; - } - napi_create_reference(env, args[2], 1, &asyncCallbackInfo->callback[0]); + CHKNCP(env, IsMatchType(env, args[2], napi_function), "Wrong argument type, should be function"); + CHKNRP(env, napi_create_reference(env, args[2], 1, &asyncCallbackInfo->callback[0]), + "napi_create_reference"); EmitAsyncCallbackWork(asyncCallbackInfo); return nullptr; } static napi_value GetAngleModify(napi_env env, napi_callback_info info) { + CALL_LOG_ENTER; size_t argc = 3; napi_value args[3] = { 0 }; napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr)); - if (argc < 2 || argc > 4 || !IsMatchArrayType(env, args[0]) || !IsMatchArrayType(env, args[1])) { - HiLog::Info(LABEL, "%{public}s argument error", __func__); - return nullptr; - } - AsyncCallbackInfo *asyncCallbackInfo = new AsyncCallbackInfo { - .env = env, - .asyncWork = nullptr, - .deferred = nullptr, - .type = GET_ANGLE_MODIFY, - }; - std::vector curRotationVector = GetCppArrayFloat(env, args[0]); - std::vector preRotationVector = GetCppArrayFloat(env, args[1]); + CHKNRP(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr), "napi_get_cb_info"); + CHKNCP(env, ((argc == 2) || (argc == 3)), "The number of parameters is not valid"); + CHKNCP(env, IsMatchArrayType(env, args[0]), "Wrong argument type, the first parameter should be array"); + CHKNCP(env, IsMatchArrayType(env, args[1]), "Wrong argument type, the second parameter should be array"); + + sptr asyncCallbackInfo = + new (std::nothrow) AsyncCallbackInfo(env, GET_ANGLE_MODIFY); + CHKPP(asyncCallbackInfo); + std::vector curRotationVector; + CHKNCP(env, GetFloatArray(env, args[0], curRotationVector), "Wrong argument type, get curRotationVector fail"); + std::vector preRotationVector; + CHKNCP(env, GetFloatArray(env, args[1], preRotationVector), "Wrong argument type, get preRotationVector fail"); + std::vector angleChange(ROTATION_VECTOR_LENGTH); - std::unique_ptr sensorAlgorithm = std::make_unique(); - int32_t ret = sensorAlgorithm->getAngleModify(curRotationVector, preRotationVector, angleChange); + SensorAlgorithm sensorAlgorithm; + int32_t ret = sensorAlgorithm.getAngleModify(curRotationVector, preRotationVector, angleChange); if (ret != OHOS::ERR_OK) { - HiLog::Error(LABEL, "%{public}s failed", __func__); + SEN_HILOGE("Get angle modify fail"); asyncCallbackInfo->type = FAIL; asyncCallbackInfo->error.code = ret; } else { asyncCallbackInfo->data.reserveData.length = ROTATION_VECTOR_LENGTH; - for (int32_t i = 0; i < ROTATION_VECTOR_LENGTH; i++) { + for (int32_t i = 0; i < ROTATION_VECTOR_LENGTH; ++i) { asyncCallbackInfo->data.reserveData.reserve[i] = angleChange[i]; } } if (argc == 2) { - napi_deferred deferred = nullptr; napi_value promise = nullptr; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - asyncCallbackInfo->deferred = deferred; + CHKNRP(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise), + "napi_create_promise"); EmitPromiseWork(asyncCallbackInfo); return promise; } - if (!IsMatchType(env, args[2], napi_function)) { - HiLog::Error(LABEL, "%{public}s parameter should be napi_fouction type", __func__); - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - return nullptr; - } - napi_create_reference(env, args[2], 1, &asyncCallbackInfo->callback[0]); + CHKNCP(env, IsMatchType(env, args[2], napi_function), "Wrong argument type, should be function"); + CHKNRP(env, napi_create_reference(env, args[2], 1, &asyncCallbackInfo->callback[0]), + "napi_create_reference"); EmitAsyncCallbackWork(asyncCallbackInfo); return nullptr; } static napi_value GetDirection(napi_env env, napi_callback_info info) { + CALL_LOG_ENTER; size_t argc = 3; napi_value args[3] = { 0 }; napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, NULL)); - if (argc < 1 || argc > 2 || !IsMatchArrayType(env, args[0])) { - HiLog::Error(LABEL, "%{public}s the number of input parameters does not match", __func__); - return nullptr; - } - AsyncCallbackInfo *asyncCallbackInfo = new AsyncCallbackInfo { - .env = env, - .asyncWork = nullptr, - .deferred = nullptr, - .type = GET_DIRECTION, - }; - std::vector rotationMatrix = GetCppArrayFloat(env, args[0]); + CHKNRP(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr), "napi_get_cb_info fail"); + CHKNCP(env, ((argc == 1) || (argc == 2)), "The number of parameters is not valid"); + CHKNCP(env, IsMatchArrayType(env, args[0]), "Wrong argument type, should be array"); + + sptr asyncCallbackInfo = + new (std::nothrow) AsyncCallbackInfo(env, GET_DIRECTION); + CHKPP(asyncCallbackInfo); + std::vector rotationMatrix; + CHKNCP(env, GetFloatArray(env, args[0], rotationMatrix), "Wrong argument type, get rotationMatrix fail"); std::vector rotationAngle(ROTATION_VECTOR_LENGTH); - std::unique_ptr sensorAlgorithm = std::make_unique(); - int32_t ret = sensorAlgorithm->getDirection(rotationMatrix, rotationAngle); + SensorAlgorithm sensorAlgorithm; + int32_t ret = sensorAlgorithm.getDirection(rotationMatrix, rotationAngle); if (ret != OHOS::ERR_OK) { - HiLog::Error(LABEL, "%{public}s failed", __func__); + SEN_HILOGE("Get direction fail"); asyncCallbackInfo->type = FAIL; asyncCallbackInfo->error.code = ret; } else { asyncCallbackInfo->data.reserveData.length = ROTATION_VECTOR_LENGTH; - for (int32_t i = 0; i < ROTATION_VECTOR_LENGTH; i++) { + for (int32_t i = 0; i < ROTATION_VECTOR_LENGTH; ++i) { asyncCallbackInfo->data.reserveData.reserve[i] = rotationAngle[i]; } } if (argc == 1) { - napi_deferred deferred = nullptr; napi_value promise = nullptr; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - asyncCallbackInfo->deferred = deferred; + CHKNRP(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise), + "napi_create_promise"); EmitPromiseWork(asyncCallbackInfo); return promise; } - if (!IsMatchType(env, args[1], napi_function)) { - HiLog::Error(LABEL, "%{public}s argument should be napi_function type", __func__); - napi_value result; - napi_get_undefined(env, &result); - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - return result; - } - napi_create_reference(env, args[1], 1, &asyncCallbackInfo->callback[0]); + CHKNCP(env, IsMatchType(env, args[1], napi_function), "Wrong argument type, should be function"); + CHKNRP(env, napi_create_reference(env, args[1], 1, &asyncCallbackInfo->callback[0]), + "napi_create_reference"); EmitAsyncCallbackWork(asyncCallbackInfo); return nullptr; } static napi_value CreateQuaternion(napi_env env, napi_callback_info info) { + CALL_LOG_ENTER; size_t argc = 2; napi_value args[2] = { 0 }; napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr)); - if (argc < 1 || argc > 2 || !IsMatchArrayType(env, args[0])) { - HiLog::Error(LABEL, "%{public}s argument error", __func__); - return nullptr; - } - AsyncCallbackInfo *asyncCallbackInfo = new AsyncCallbackInfo { - .env = env, - .asyncWork = nullptr, - .deferred = nullptr, - .type = CREATE_QUATERNION, - }; - std::vector rotationVector = GetCppArrayFloat(env, args[0]); + CHKNRP(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr), "napi_get_cb_info"); + CHKNCP(env, ((argc == 1) || (argc == 2)), "The number of parameters is not valid"); + CHKNCP(env, IsMatchArrayType(env, args[0]), "Wrong argument type, should be array"); + + sptr asyncCallbackInfo = + new (std::nothrow) AsyncCallbackInfo(env, CREATE_QUATERNION); + CHKPP(asyncCallbackInfo); + std::vector rotationVector; + CHKNCP(env, GetFloatArray(env, args[0], rotationVector), + "Wrong argument type, get rotationVector fail"); std::vector quaternion(QUATERNION_LENGTH); - std::unique_ptr sensorAlgorithm = std::make_unique(); - int32_t ret = sensorAlgorithm->createQuaternion(rotationVector, quaternion); + SensorAlgorithm sensorAlgorithm; + int32_t ret = sensorAlgorithm.createQuaternion(rotationVector, quaternion); if (ret != OHOS::ERR_OK) { - HiLog::Error(LABEL, "%{public}s failed", __func__); + SEN_HILOGE("Create quaternin fail"); asyncCallbackInfo->type = FAIL; asyncCallbackInfo->error.code = ret; } else { asyncCallbackInfo->data.reserveData.length = QUATERNION_LENGTH; - for (int32_t i = 0; i < QUATERNION_LENGTH; i++) { + for (int32_t i = 0; i < QUATERNION_LENGTH; ++i) { asyncCallbackInfo->data.reserveData.reserve[i] = quaternion[i]; } } if (argc == 1) { - napi_deferred deferred = nullptr; napi_value promise = nullptr; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - asyncCallbackInfo->deferred = deferred; + CHKNRP(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise), + "napi_create_promise"); EmitPromiseWork(asyncCallbackInfo); return promise; } - if (!IsMatchType(env, args[1], napi_function)) { - HiLog::Error(LABEL, "%{public}s argument should be function", __func__); - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - return nullptr; - } - napi_create_reference(env, args[1], 1, &asyncCallbackInfo->callback[0]); + CHKNCP(env, IsMatchType(env, args[1], napi_function), "Wrong argument type, should be function"); + CHKNRP(env, napi_create_reference(env, args[1], 1, &asyncCallbackInfo->callback[0]), + "napi_create_reference"); EmitAsyncCallbackWork(asyncCallbackInfo); return nullptr; } static napi_value GetAltitude(napi_env env, napi_callback_info info) { + CALL_LOG_ENTER; size_t argc = 3; napi_value args[3] = { 0 }; napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr)); - if (argc < 2 || argc > 3 || !IsMatchType(env, args[0], napi_number) - || !IsMatchType(env, args[1], napi_number)) { - HiLog::Error(LABEL, "%{public}s Invalid input", __func__); - return nullptr; - } - AsyncCallbackInfo *asyncCallbackInfo = new AsyncCallbackInfo { - .env = env, - .asyncWork = nullptr, - .deferred = nullptr, - .type = GET_ALTITUDE, - }; - float seaPressure = GetCppFloat(env, args[0]); - float currentPressure = GetCppFloat(env, args[1]); + CHKNRP(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr), "napi_get_cb_info"); + CHKNCP(env, ((argc == 2) || (argc == 3)), "The number of parameters is not valid"); + CHKNCP(env, IsMatchType(env, args[0], napi_number), "Wrong argument type, should be number"); + CHKNCP(env, IsMatchType(env, args[1], napi_number), "Wrong argument type, should be number"); + + sptr asyncCallbackInfo = + new (std::nothrow) AsyncCallbackInfo(env, GET_ALTITUDE); + CHKPP(asyncCallbackInfo); + float seaPressure = 0; + CHKNCP(env, GetCppFloat(env, args[0], seaPressure), "Wrong argument type, get seaPressure fail"); + float currentPressure = 0; + CHKNCP(env, GetCppFloat(env, args[1], currentPressure), "Wrong argument type, get currentPressure fail"); float altitude = 0; - std::unique_ptr sensorAlgorithm = std::make_unique(); - int32_t ret = sensorAlgorithm->getAltitude(seaPressure, currentPressure, &altitude); + SensorAlgorithm sensorAlgorithm; + int32_t ret = sensorAlgorithm.getAltitude(seaPressure, currentPressure, &altitude); if (ret != OHOS::ERR_OK) { - HiLog::Error(LABEL, "%{public}s failed", __func__); + SEN_HILOGE("Get altitude fail"); asyncCallbackInfo->type = FAIL; asyncCallbackInfo->error.code = ret; } else { asyncCallbackInfo->data.reserveData.reserve[0] = altitude; } if (argc == 2) { - napi_deferred deferred = nullptr; napi_value promise = nullptr; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - asyncCallbackInfo->deferred = deferred; + CHKNRP(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise), + "napi_create_promise"); EmitPromiseWork(asyncCallbackInfo); return promise; } - if (!IsMatchType(env, args[2], napi_function)) { - HiLog::Error(LABEL, "%{public}s parameter should be napi_fouction type", __func__); - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - return nullptr; - } - napi_create_reference(env, args[2], 1, &asyncCallbackInfo->callback[0]); + CHKNCP(env, IsMatchType(env, args[2], napi_function), "Wrong argument type, should be function"); + CHKNRP(env, napi_create_reference(env, args[2], 1, &asyncCallbackInfo->callback[0]), + "napi_create_reference"); EmitAsyncCallbackWork(asyncCallbackInfo); return nullptr; } static napi_value GetGeomagneticDip(napi_env env, napi_callback_info info) { + CALL_LOG_ENTER; size_t argc = 2; napi_value args[2] = { 0 }; napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr)); - if (argc < 1 || argc > 2 || !IsMatchArrayType(env, args[0])) { - HiLog::Error(LABEL, "%{public}s Invalid input", __func__); - return nullptr; - } - AsyncCallbackInfo *asyncCallbackInfo = new AsyncCallbackInfo { - .env = env, - .asyncWork = nullptr, - .deferred = nullptr, - .type = GET_GEOMAGNITIC_DIP, - }; - std::vector inclinationMatrix = GetCppArrayFloat(env, args[0]); + CHKNRP(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr), "napi_get_cb_info"); + CHKNCP(env, ((argc == 1) || (argc == 2)), "The number of parameters is not valid"); + CHKNCP(env, IsMatchArrayType(env, args[0]), "Wrong argument type, should be array"); + + sptr asyncCallbackInfo = + new (std::nothrow) AsyncCallbackInfo(env, GET_GEOMAGNITIC_DIP); + CHKPP(asyncCallbackInfo); + std::vector inclinationMatrix; + CHKNCP(env, GetFloatArray(env, args[0], inclinationMatrix), + "Wrong argument type, get inclinationMatrix fail"); float geomagneticDip = 0; - std::unique_ptr sensorAlgorithm = std::make_unique(); - int32_t ret = sensorAlgorithm->getGeomagneticDip(inclinationMatrix, &geomagneticDip); + SensorAlgorithm sensorAlgorithm; + int32_t ret = sensorAlgorithm.getGeomagneticDip(inclinationMatrix, &geomagneticDip); if (ret != OHOS::ERR_OK) { - HiLog::Error(LABEL, "%{public}s failed", __func__); + SEN_HILOGE("Get geomagnetic dip fail"); asyncCallbackInfo->type = FAIL; asyncCallbackInfo->error.code = ret; } else { asyncCallbackInfo->data.reserveData.reserve[0] = geomagneticDip; } if (argc == 1) { - napi_deferred deferred = nullptr; napi_value promise = nullptr; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - asyncCallbackInfo->deferred = deferred; + CHKNRP(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise), + "napi_create_promise"); EmitPromiseWork(asyncCallbackInfo); return promise; } - if (!IsMatchType(env, args[1], napi_function)) { - HiLog::Error(LABEL, "%{public}s argument should be function", __func__); - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - return nullptr; - } - napi_create_reference(env, args[1], 1, &asyncCallbackInfo->callback[0]); + CHKNCP(env, IsMatchType(env, args[1], napi_function), "Wrong argument type, should be function"); + CHKNRP(env, napi_create_reference(env, args[1], 1, &asyncCallbackInfo->callback[0]), + "napi_create_reference"); EmitAsyncCallbackWork(asyncCallbackInfo); return nullptr; } -static napi_value CreateRotationMatrix(napi_env env, napi_callback_info info) +static napi_value createRotationAndInclination(const napi_env &env, napi_value args[], size_t argc) { - size_t argc = 3; - napi_value args[3] = { 0 }; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, NULL)); - if (argc < 1 || argc > 3 || !IsMatchArrayType(env, args[0])) { - HiLog::Info(LABEL, "%{public}s argument error", __func__); - return nullptr; - } - AsyncCallbackInfo *asyncCallbackInfo = new AsyncCallbackInfo { - .env = env, - .asyncWork = nullptr, - .deferred = nullptr, - .type = CREATE_ROTATION_MATRIX, - }; - std::unique_ptr sensorAlgorithm = std::make_unique(); - if (argc == 1 || (argc == 2 && IsMatchType(env, args[1], napi_function))) { - std::vector rotationVector = GetCppArrayFloat(env, args[0]); - std::vector rotationMatrix(THREE_DIMENSIONAL_MATRIX_LENGTH); - int32_t ret = sensorAlgorithm->createRotationMatrix(rotationVector, rotationMatrix); - if (ret != OHOS::ERR_OK) { - HiLog::Error(LABEL, "%{public}s failed", __func__); - asyncCallbackInfo->type = FAIL; - asyncCallbackInfo->error.code = ret; - } else { - asyncCallbackInfo->data.reserveData.length = THREE_DIMENSIONAL_MATRIX_LENGTH; - for (int32_t i = 0; i < THREE_DIMENSIONAL_MATRIX_LENGTH; i++) { - asyncCallbackInfo->data.reserveData.reserve[i] = rotationMatrix[i]; - } - } - if (argc == 1) { - napi_deferred deferred = nullptr; - napi_value promise = nullptr; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - asyncCallbackInfo->deferred = deferred; - EmitPromiseWork(asyncCallbackInfo); - return promise; - } - napi_create_reference(env, args[1], 1, &asyncCallbackInfo->callback[0]); - EmitAsyncCallbackWork(asyncCallbackInfo); - return nullptr; - } - - if (!IsMatchArrayType(env, args[1]) || (argc == 3 && !IsMatchType(env, args[2], napi_function))) { - HiLog::Info(LABEL, "%{public}s argument error", __func__); - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - return nullptr; - } - asyncCallbackInfo->type = ROTATION_INCLINATION_MATRIX; - std::vector gravity = GetCppArrayFloat(env, args[0]); - std::vector geomagnetic = GetCppArrayFloat(env, args[1]); + CALL_LOG_ENTER; + CHKNCP(env, ((argc == 2) || (argc == 3)), "The number of parameters is not valid"); + std::vector gravity; + CHKNCP(env, GetFloatArray(env, args[0], gravity), "Wrong argument type, get gravity fail"); + std::vector geomagnetic; + CHKNCP(env, GetFloatArray(env, args[1], geomagnetic), "Wrong argument type, get geomagnetic fail"); std::vector rotation(THREE_DIMENSIONAL_MATRIX_LENGTH); std::vector inclination(THREE_DIMENSIONAL_MATRIX_LENGTH); - int32_t ret = sensorAlgorithm->createRotationAndInclination(gravity, geomagnetic, rotation, inclination); + sptr asyncCallbackInfo = + new (std::nothrow) AsyncCallbackInfo(env, ROTATION_INCLINATION_MATRIX); + CHKPP(asyncCallbackInfo); + SensorAlgorithm sensorAlgorithm; + int32_t ret = sensorAlgorithm.createRotationAndInclination(gravity, geomagnetic, rotation, inclination); if (ret != OHOS::ERR_OK) { - HiLog::Error(LABEL, "%{public}s failed", __func__); + SEN_HILOGE("Create rotation and inclination matrix fail"); asyncCallbackInfo->type = FAIL; asyncCallbackInfo->error.code = ret; } else { - for (int32_t i = 0; i < THREE_DIMENSIONAL_MATRIX_LENGTH; i++) { + asyncCallbackInfo->data.reserveData.length = THREE_DIMENSIONAL_MATRIX_LENGTH; + for (int32_t i = 0; i < THREE_DIMENSIONAL_MATRIX_LENGTH; ++i) { asyncCallbackInfo->data.rationMatrixData.rotationMatrix[i] = rotation[i]; } - for (int32_t i = 0; i < THREE_DIMENSIONAL_MATRIX_LENGTH; i++) { + for (int32_t i = 0; i < THREE_DIMENSIONAL_MATRIX_LENGTH; ++i) { asyncCallbackInfo->data.rationMatrixData.inclinationMatrix[i] = inclination[i]; } } if (argc == 2) { - napi_deferred deferred = nullptr; napi_value promise = nullptr; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - asyncCallbackInfo->deferred = deferred; + CHKNRP(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise), + "napi_create_promise"); EmitPromiseWork(asyncCallbackInfo); return promise; } - napi_create_reference(env, args[2], 1, &asyncCallbackInfo->callback[0]); + CHKNCP(env, IsMatchType(env, args[2], napi_function), "Wrong argument type, should be function"); + CHKNRP(env, napi_create_reference(env, args[2], 1, &asyncCallbackInfo->callback[0]), + "napi_create_reference"); EmitAsyncCallbackWork(asyncCallbackInfo); return nullptr; } +static napi_value GetRotationMatrix(const napi_env &env, napi_value args[], size_t argc) +{ + CALL_LOG_ENTER; + CHKNCP(env, ((argc == 1) || (argc == 2)), "The number of parameters is not valid"); + std::vector rotationVector; + CHKNCP(env, GetFloatArray(env, args[0], rotationVector), + "Wrong argument type, get rotationVector fail"); + + sptr asyncCallbackInfo = + new (std::nothrow) AsyncCallbackInfo(env, CREATE_ROTATION_MATRIX); + CHKPP(asyncCallbackInfo); + std::vector rotationMatrix(THREE_DIMENSIONAL_MATRIX_LENGTH); + SensorAlgorithm sensorAlgorithm; + int32_t ret = sensorAlgorithm.createRotationMatrix(rotationVector, rotationMatrix); + if (ret != OHOS::ERR_OK) { + SEN_HILOGE("Create rotation matrix fail"); + asyncCallbackInfo->type = FAIL; + asyncCallbackInfo->error.code = ret; + } else { + asyncCallbackInfo->data.reserveData.length = THREE_DIMENSIONAL_MATRIX_LENGTH; + for (int32_t i = 0; i < THREE_DIMENSIONAL_MATRIX_LENGTH; ++i) { + asyncCallbackInfo->data.reserveData.reserve[i] = rotationMatrix[i]; + } + } + + if (argc == 1) { + napi_value promise = nullptr; + CHKNRP(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise), + "napi_create_promise"); + EmitPromiseWork(asyncCallbackInfo); + return promise; + } + CHKNCP(env, IsMatchType(env, args[1], napi_function), "Wrong argument type, should be function"); + CHKNRP(env, napi_create_reference(env, args[1], 1, &asyncCallbackInfo->callback[0]), + "napi_create_reference"); + EmitAsyncCallbackWork(asyncCallbackInfo); + return nullptr; +} + +static napi_value CreateRotationMatrix(napi_env env, napi_callback_info info) +{ + CALL_LOG_ENTER; + size_t argc = 3; + napi_value args[3] = { 0 }; + napi_value thisVar = nullptr; + CHKNRP(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr), "napi_get_cb_info"); + CHKNCP(env, ((argc >= 1) && (argc <= 3)), "The number of parameters is not valid"); + CHKNCP(env, IsMatchArrayType(env, args[0]), "Wrong argument type, should be array"); + + if (argc == 1 || (argc == 2 && IsMatchType(env, args[1], napi_function))) { + return GetRotationMatrix(env, args, argc); + } else if (IsMatchArrayType(env, args[1])) { + return createRotationAndInclination(env, args, argc); + } + return nullptr; +} + static napi_value GetSensorList(napi_env env, napi_callback_info info) { - HiLog::Info(LABEL, "%{public}s in", __func__); + CALL_LOG_ENTER; size_t argc = 1; napi_value args[1] = { 0 }; napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, NULL)); - if (argc != 1) { - HiLog::Error(LABEL, "%{public}s the number of input parameters does not match", __func__); - return nullptr; - } + CHKNRP(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr), "napi_get_cb_info"); + CHKNCP(env, (argc <= 1), "The number of parameters is not valid"); + sptr asyncCallbackInfo = + new (std::nothrow) AsyncCallbackInfo(env, GET_SENSOR_LIST); + CHKPP(asyncCallbackInfo); + SensorInfo *sensorInfos = nullptr; int32_t count = 0; - AsyncCallbackInfo *asyncCallbackInfo = new AsyncCallbackInfo { - .env = env, - .asyncWork = nullptr, - .deferred = nullptr, - .type = GET_SENSOR_LIST, - }; int32_t ret = GetAllSensors(&sensorInfos, &count); if (ret != OHOS::ERR_OK) { - HiLog::Error(LABEL, "%{public}s get sensor list failed", __func__); + SEN_HILOGE("Get sensor list fail"); asyncCallbackInfo->type = FAIL; asyncCallbackInfo->error.code = ret; } else { - for (int32_t i = 0; i < count; i++) { + for (int32_t i = 0; i < count; ++i) { asyncCallbackInfo->sensorInfos.push_back(*(sensorInfos + i)); } + free(sensorInfos); + sensorInfos = nullptr; } if (argc == 0) { - napi_deferred deferred = nullptr; napi_value promise = nullptr; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - asyncCallbackInfo->deferred = deferred; + CHKNRP(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise), + "napi_create_promise"); EmitPromiseWork(asyncCallbackInfo); return promise; } - if (!IsMatchType(env, args[0], napi_function)) { - HiLog::Error(LABEL, "%{public}s argument should be napi_function type", __func__); - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - return nullptr; - } + CHKNCP(env, IsMatchType(env, args[0], napi_function), "Wrong argument type, should be function"); napi_create_reference(env, args[0], 1, &asyncCallbackInfo->callback[0]); EmitAsyncCallbackWork(asyncCallbackInfo); return nullptr; @@ -805,55 +772,46 @@ static napi_value GetSensorList(napi_env env, napi_callback_info info) static napi_value GetSingleSensor(napi_env env, napi_callback_info info) { - HiLog::Info(LABEL, "%{public}s in", __func__); + CALL_LOG_ENTER; size_t argc = 2; napi_value args[2] = { 0 }; napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, NULL)); - if (argc < 1 || argc > 2 || !IsMatchType(env, args[0], napi_number)) { - HiLog::Error(LABEL, "%{public}s the number of input parameters does not match", __func__); - return nullptr; - } - AsyncCallbackInfo *asyncCallbackInfo = new AsyncCallbackInfo { - .env = env, - .asyncWork = nullptr, - .deferred = nullptr, - .type = GET_SINGLE_SENSOR, - }; + CHKNRP(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr), "napi_get_cb_info"); + CHKNCP(env, ((argc == 1) || (argc == 2)), "The number of parameters is not valid"); + int32_t sensorTypeId = INVALID_SENSOR_ID; + CHKNCP(env, GetCppInt32(env, args[0], sensorTypeId), "Wrong argument type, get number fail"); + + sptr asyncCallbackInfo = + new (std::nothrow) AsyncCallbackInfo(env, GET_SINGLE_SENSOR); + CHKPP(asyncCallbackInfo); SensorInfo *sensorInfos = nullptr; int32_t count = 0; int32_t ret = GetAllSensors(&sensorInfos, &count); if (ret != OHOS::ERR_OK) { - HiLog::Error(LABEL, "%{public}s get sensorlist failed", __func__); + SEN_HILOGE("Get sensor list fail"); asyncCallbackInfo->type = FAIL; asyncCallbackInfo->error.code = ret; } else { - int32_t sensorTypeId = GetCppInt32(args[0], env); - for (int32_t i = 0; i < count; i++) { + for (int32_t i = 0; i < count; ++i) { if (sensorInfos[i].sensorTypeId == sensorTypeId) { asyncCallbackInfo->sensorInfos.push_back(*(sensorInfos + i)); break; } } if (asyncCallbackInfo->sensorInfos.empty()) { - HiLog::Error(LABEL, "%{public}s not find sensorTypeId: %{public}d", __func__, sensorTypeId); + SEN_HILOGE("Not find sensorTypeId: %{public}d", sensorTypeId); asyncCallbackInfo->type = FAIL; } + free(sensorInfos); + sensorInfos = nullptr; } if (argc == 1) { - napi_deferred deferred = nullptr; napi_value promise = nullptr; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - asyncCallbackInfo->deferred = deferred; + CHKNRP(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise), "napi_create_promise"); EmitPromiseWork(asyncCallbackInfo); return promise; } - if (!IsMatchType(env, args[1], napi_function)) { - HiLog::Error(LABEL, "%{public}s argument should be napi_function type", __func__); - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - return nullptr; - } + CHKNCP(env, IsMatchType(env, args[1], napi_function), "Wrong argument type, should be function"); napi_create_reference(env, args[1], 1, &asyncCallbackInfo->callback[0]); EmitAsyncCallbackWork(asyncCallbackInfo); return nullptr; @@ -863,57 +821,52 @@ static napi_value EnumClassConstructor(napi_env env, napi_callback_info info) { size_t argc = 0; napi_value args[1] = {0}; - napi_value res = nullptr; + napi_value ret = nullptr; void *data = nullptr; - napi_status status = napi_get_cb_info(env, info, &argc, args, &res, &data); - if (status != napi_ok) { - return nullptr; - } - return res; + CHKNRP(env, napi_get_cb_info(env, info, &argc, args, &ret, &data), "napi_get_cb_info"); + return ret; } static napi_value CreateEnumSensorType(napi_env env, napi_value exports) { napi_property_descriptor desc[] = { - DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_ACCELEROMETER", GetNapiInt32(SENSOR_TYPE_ID_ACCELEROMETER, env)), - DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_GYROSCOPE", GetNapiInt32(SENSOR_TYPE_ID_GYROSCOPE, env)), - DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_AMBIENT_LIGHT", GetNapiInt32(SENSOR_TYPE_ID_AMBIENT_LIGHT, env)), - DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_MAGNETIC_FIELD", GetNapiInt32(SENSOR_TYPE_ID_MAGNETIC_FIELD, env)), - DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_BAROMETER", GetNapiInt32(SENSOR_TYPE_ID_BAROMETER, env)), - DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_HALL", GetNapiInt32(SENSOR_TYPE_ID_HALL, env)), - DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_PROXIMITY", GetNapiInt32(SENSOR_TYPE_ID_PROXIMITY, env)), - DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_HUMIDITY", GetNapiInt32(SENSOR_TYPE_ID_HUMIDITY, env)), - DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_ORIENTATION", GetNapiInt32(SENSOR_TYPE_ID_ORIENTATION, env)), - DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_GRAVITY", GetNapiInt32(SENSOR_TYPE_ID_GRAVITY, env)), + DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_ACCELEROMETER", GetNapiInt32(env, SENSOR_TYPE_ID_ACCELEROMETER)), + DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_GYROSCOPE", GetNapiInt32(env, SENSOR_TYPE_ID_GYROSCOPE)), + DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_AMBIENT_LIGHT", GetNapiInt32(env, SENSOR_TYPE_ID_AMBIENT_LIGHT)), + DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_MAGNETIC_FIELD", GetNapiInt32(env, SENSOR_TYPE_ID_MAGNETIC_FIELD)), + DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_BAROMETER", GetNapiInt32(env, SENSOR_TYPE_ID_BAROMETER)), + DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_HALL", GetNapiInt32(env, SENSOR_TYPE_ID_HALL)), + DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_PROXIMITY", GetNapiInt32(env, SENSOR_TYPE_ID_PROXIMITY)), + DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_HUMIDITY", GetNapiInt32(env, SENSOR_TYPE_ID_HUMIDITY)), + DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_ORIENTATION", GetNapiInt32(env, SENSOR_TYPE_ID_ORIENTATION)), + DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_GRAVITY", GetNapiInt32(env, SENSOR_TYPE_ID_GRAVITY)), DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_LINEAR_ACCELERATION", - GetNapiInt32(SENSOR_TYPE_ID_LINEAR_ACCELERATION, env)), + GetNapiInt32(env, SENSOR_TYPE_ID_LINEAR_ACCELERATION)), DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_ROTATION_VECTOR", - GetNapiInt32(SENSOR_TYPE_ID_ROTATION_VECTOR, env)), + GetNapiInt32(env, SENSOR_TYPE_ID_ROTATION_VECTOR)), DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_AMBIENT_TEMPERATURE", - GetNapiInt32(SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, env)), + GetNapiInt32(env, SENSOR_TYPE_ID_AMBIENT_TEMPERATURE)), DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED", - GetNapiInt32(SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, env)), + GetNapiInt32(env, SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED)), DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED", - GetNapiInt32(SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, env)), + GetNapiInt32(env, SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED)), DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_SIGNIFICANT_MOTION", - GetNapiInt32(SENSOR_TYPE_ID_SIGNIFICANT_MOTION, env)), + GetNapiInt32(env, SENSOR_TYPE_ID_SIGNIFICANT_MOTION)), DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_PEDOMETER_DETECTION", - GetNapiInt32(SENSOR_TYPE_ID_PEDOMETER_DETECTION, env)), - DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_PEDOMETER", GetNapiInt32(SENSOR_TYPE_ID_PEDOMETER, env)), - DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_HEART_RATE", GetNapiInt32(SENSOR_TYPE_ID_HEART_RATE, env)), - DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_WEAR_DETECTION", GetNapiInt32(SENSOR_TYPE_ID_WEAR_DETECTION, env)), + GetNapiInt32(env, SENSOR_TYPE_ID_PEDOMETER_DETECTION)), + DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_PEDOMETER", GetNapiInt32(env, SENSOR_TYPE_ID_PEDOMETER)), + DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_HEART_RATE", GetNapiInt32(env, SENSOR_TYPE_ID_HEART_RATE)), + DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_WEAR_DETECTION", GetNapiInt32(env, SENSOR_TYPE_ID_WEAR_DETECTION)), DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED", - GetNapiInt32(SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, env)), + GetNapiInt32(env, SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED)), }; napi_value result = nullptr; - napi_define_class(env, "SensorType", NAPI_AUTO_LENGTH, EnumClassConstructor, nullptr, - sizeof(desc) / sizeof(*desc), desc, &result); - napi_set_named_property(env, exports, "SensorType", result); + CHKNRP(env, napi_define_class(env, "SensorType", NAPI_AUTO_LENGTH, EnumClassConstructor, nullptr, + sizeof(desc) / sizeof(*desc), desc, &result), "napi_define_class"); + CHKNRP(env, napi_set_named_property(env, exports, "SensorType", result), "napi_set_named_property fail"); return exports; } -EXTERN_C_START - static napi_value Init(napi_env env, napi_value exports) { napi_property_descriptor desc[] = { @@ -958,16 +911,16 @@ static napi_value Init(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("subscribeHall", SubscribeHall), DECLARE_NAPI_FUNCTION("unsubscribeHall", UnsubscribeHall), }; - NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(napi_property_descriptor), desc)); - CreateEnumSensorType(env, exports); + CHKNRP(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(napi_property_descriptor), desc), + "napi_define_properties"); + CHKNCP(env, CreateEnumSensorType(env, exports), "Create enum sensor type fail"); return exports; } -EXTERN_C_END static napi_module _module = { .nm_version = 1, .nm_flags = 0, - .nm_filename = NULL, + .nm_filename = nullptr, .nm_register_func = Init, .nm_modname = "sensor", .nm_priv = ((void *)0), @@ -978,3 +931,5 @@ extern "C" __attribute__((constructor)) void RegisterModule(void) { napi_module_register(&_module); } +} // namespace Sensors +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/plugin/src/sensor_napi_utils.cpp b/interfaces/plugin/src/sensor_napi_utils.cpp index 7625f82d788f4a679c0f91d612315df2e3af8f67..3d5edf474f611533c0e2eee5bfa450c2edd8b905 100644 --- a/interfaces/plugin/src/sensor_napi_utils.cpp +++ b/interfaces/plugin/src/sensor_napi_utils.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 20212 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 @@ -15,128 +15,104 @@ #include "sensor_napi_utils.h" -#include #include #include #include -#include "hilog/log.h" - +namespace OHOS { +namespace Sensors { using namespace OHOS::HiviewDFX; -static constexpr HiLogLabel LABEL = {LOG_CORE, 0xD002708, "SensorJsAPI"}; - -bool IsSameValue(napi_env env, napi_value lhs, napi_value rhs) +bool IsSameValue(const napi_env &env, const napi_value &lhs, const napi_value &rhs) { + CALL_LOG_ENTER; bool result = false; - napi_strict_equals(env, lhs, rhs, &result); + CHKNRF(env, napi_strict_equals(env, lhs, rhs, &result), "napi_strict_equals"); return result; } -bool IsMatchType(napi_env env, napi_value value, napi_valuetype type) +bool IsMatchType(const napi_env &env, const napi_value &value, const napi_valuetype &type) { + CALL_LOG_ENTER; napi_valuetype paramType = napi_undefined; - napi_typeof(env, value, ¶mType); - if (paramType != type) { - HiLog::Error(LABEL, "%{public}s failed", __func__); - return false; - } - return true; + CHKNRF(env, napi_typeof(env, value, ¶mType), "napi_typeof"); + return paramType == type; } -bool IsMatchArrayType(napi_env env, napi_value value) +bool IsMatchArrayType(const napi_env &env, const napi_value &value) { + CALL_LOG_ENTER; bool result = false; - napi_is_array(env, value, &result); + CHKNRF(env, napi_is_array(env, value, &result), "napi_is_array"); return result; } -vector GetCppArrayFloat(napi_env env, napi_value value) +bool GetFloatArray(const napi_env &env, const napi_value &value, vector &array) { + CALL_LOG_ENTER; uint32_t arrayLength = 0; - napi_get_array_length(env, value, &arrayLength); - if (arrayLength <= 0) { - HiLog::Error(LABEL, "%{public}s The array is empty", __func__); - return vector(); - } - vector paramArrays; - for (size_t i = 0; i < arrayLength; i++) { - napi_value napiElement = nullptr; - napi_get_element(env, value, i, &napiElement); - - napi_valuetype valuetype0 = napi_undefined; - napi_typeof(env, napiElement, &valuetype0); - if (valuetype0 != napi_number) { - HiLog::Error(LABEL, "%{public}s Wrong argument type. Numbers expected", __func__); - return vector(); - } - double value0 = 0; - napi_get_value_double(env, napiElement, &value0); - paramArrays.push_back(static_cast(value0)); - } - return paramArrays; -} - -bool IsMatchArrayType(napi_env env, napi_value value, napi_typedarray_type type) -{ - napi_typedarray_type paramType = napi_int8_array; - size_t length; - void *data = nullptr; - napi_value arraybuffer = nullptr; - size_t byteOffset; - napi_get_typedarray_info(env, value, ¶mType, &length, &data, &arraybuffer, &byteOffset); - if (paramType != type) { - HiLog::Error(LABEL, "%{public}s paramType:%{public}d type:%{public}d failed", __func__, paramType, type); - return false; + CHKNRF(env, napi_get_array_length(env, value, &arrayLength), "napi_get_array_length"); + for (size_t i = 0; i < arrayLength; ++i) { + napi_value element = nullptr; + CHKNRF(env, napi_get_element(env, value, i, &element), "napi_get_element"); + CHKNCF(env, IsMatchType(env, element, napi_number), "Wrong argument type. Number or function expected"); + double value = 0; + CHKNCF(env, GetCppDouble(env, element, value), "Wrong argument type. get double fail"); + array.push_back(static_cast(value)); } return true; } -napi_value GetNapiInt32(int32_t number, napi_env env) +napi_value GetNamedProperty(const napi_env &env, const napi_value &object, string name) { + CALL_LOG_ENTER; napi_value value = nullptr; - napi_create_int32(env, number, &value); + CHKNRP(env, napi_get_named_property(env, object, name.c_str(), &value), + "napi_get_named_property"); return value; } -napi_value NapiGetNamedProperty(napi_value jsonObject, string name, napi_env env) +bool GetCppDouble(const napi_env &env, const napi_value &value, double &number) { - napi_value value = nullptr; - napi_get_named_property(env, jsonObject, name.c_str(), &value); - return value; + CALL_LOG_ENTER; + CHKNRF(env, napi_get_value_double(env, value, &number), "napi_get_value_double"); + return true; } -float GetCppFloat(napi_env env, napi_value value) +bool GetCppFloat(const napi_env &env, const napi_value &value, float &number) { - double number; - napi_get_value_double(env, value, &number); - return static_cast(number); + CALL_LOG_ENTER; + double result = 0; + CHKNCF(env, GetCppDouble(env, value, result), "Get cpp double fail"); + number = static_cast(result); + return true; } -int32_t GetCppInt32(napi_value value, napi_env env) +bool GetCppInt32(const napi_env &env, const napi_value &value, int32_t &number) { - int32_t number; - napi_get_value_int32(env, value, &number); - return number; + CALL_LOG_ENTER; + CHKNRF(env, napi_get_value_int32(env, value, &number), "napi_get_value_int32"); + return true; } -int64_t GetCppInt64(napi_value value, napi_env env) +bool GetCppInt64(const napi_env &env, const napi_value &value, int64_t &number) { - int64_t number; - napi_get_value_int64(env, value, &number); - return number; + CALL_LOG_ENTER; + CHKNRF(env, napi_get_value_int64(env, value, &number), "napi_get_value_int64"); + return true; } -bool GetCppBool(napi_value value, napi_env env) +bool GetCppBool(const napi_env &env, const napi_value &value) { - bool number; - napi_get_value_bool(env, value, &number); + CALL_LOG_ENTER; + bool number = false; + CHKNRF(env, napi_get_value_bool(env, value, &number), "napi_get_value_bool"); return number; } -napi_value GetUndefined(napi_env env) +napi_value GetNapiInt32(const napi_env &env, int32_t number) { - napi_value value; - napi_get_undefined(env, &value); + napi_value value = nullptr; + CHKNRP(env, napi_create_int32(env, number, &value), "napi_create_int32"); return value; } @@ -167,7 +143,6 @@ std::map> g_sensorAttributeList = { std::map g_convertfuncList = { {FAIL, ConvertToFailData}, - {OFF_CALLBACK, ConvertToNoData}, {ON_CALLBACK, ConvertToSensorData}, {ONCE_CALLBACK, ConvertToSensorData}, {GET_GEOMAGNETIC_FIELD, ConvertToGeomagneticData}, @@ -183,315 +158,350 @@ std::map g_convertfuncList = { {GET_SINGLE_SENSOR, ConvertToSingleSensor}, }; -void getJsonObject(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result) +bool getJsonObject(const napi_env &env, sptr asyncCallbackInfo, napi_value &result) { - napi_value x = nullptr; - napi_create_double(env, asyncCallbackInfo->data.geomagneticData.x, &x); - napi_set_named_property(env, result, "x", x); - - napi_value y = nullptr; - napi_create_double(env, asyncCallbackInfo->data.geomagneticData.y, &y); - napi_set_named_property(env, result, "y", y); - - napi_value z = nullptr; - napi_create_double(env, asyncCallbackInfo->data.geomagneticData.z, &z); - napi_set_named_property(env, result, "z", z); - - napi_value geomagneticDip = nullptr; - napi_create_double(env, asyncCallbackInfo->data.geomagneticData.geomagneticDip, &geomagneticDip); - napi_set_named_property(env, result, "geomagneticDip", geomagneticDip); - - napi_value deflectionAngle = nullptr; - napi_create_double(env, asyncCallbackInfo->data.geomagneticData.deflectionAngle, &deflectionAngle); - napi_set_named_property(env, result, "deflectionAngle", deflectionAngle); - - napi_value levelIntensity = nullptr; - napi_create_double(env, asyncCallbackInfo->data.geomagneticData.levelIntensity, &levelIntensity); - napi_set_named_property(env, result, "levelIntensity", levelIntensity); - - napi_value totalIntensity = nullptr; - napi_create_double(env, asyncCallbackInfo->data.geomagneticData.totalIntensity, &totalIntensity); - napi_set_named_property(env, result, "totalIntensity", totalIntensity); + CHKPF(asyncCallbackInfo); + CHKNRF(env, napi_create_object(env, &result), "napi_create_object"); + napi_value value = nullptr; + CHKNRF(env, napi_create_double(env, asyncCallbackInfo->data.geomagneticData.x, &value), "napi_create_double"); + CHKNRF(env, napi_set_named_property(env, result, "x", value), "napi_set_named_property"); + + value = nullptr; + CHKNRF(env, napi_create_double(env, asyncCallbackInfo->data.geomagneticData.y, &value), "napi_create_double"); + CHKNRF(env, napi_set_named_property(env, result, "y", value), "napi_set_named_property"); + + value = nullptr; + CHKNRF(env, napi_create_double(env, asyncCallbackInfo->data.geomagneticData.z, &value), "napi_create_double"); + CHKNRF(env, napi_set_named_property(env, result, "z", value), "napi_set_named_property"); + + value = nullptr; + CHKNRF(env, napi_create_double(env, asyncCallbackInfo->data.geomagneticData.geomagneticDip, &value), + "napi_create_double"); + CHKNRF(env, napi_set_named_property(env, result, "geomagneticDip", value), "napi_set_named_property"); + + value = nullptr; + CHKNRF(env, napi_create_double(env, asyncCallbackInfo->data.geomagneticData.deflectionAngle, &value), + "napi_create_double"); + CHKNRF(env, napi_set_named_property(env, result, "deflectionAngle", value), "napi_set_named_property"); + + value = nullptr; + CHKNRF(env, napi_create_double(env, asyncCallbackInfo->data.geomagneticData.levelIntensity, &value), + "napi_create_double"); + CHKNRF(env, napi_set_named_property(env, result, "levelIntensity", value), "napi_set_named_property"); + + value = nullptr; + CHKNRF(env, napi_create_double(env, asyncCallbackInfo->data.geomagneticData.totalIntensity, &value), + "napi_create_double"); + CHKNRF(env, napi_set_named_property(env, result, "totalIntensity", value), "napi_set_named_property"); + return true; } -void ConvertToSensorInfo(napi_env env, SensorInfo sensorInfo, napi_value result) +bool ConvertToSensorInfo(const napi_env &env, SensorInfo sensorInfo, napi_value &result) { - napi_value sensorName = nullptr; - napi_create_string_latin1(env, sensorInfo.sensorName, NAPI_AUTO_LENGTH, &sensorName); - napi_set_named_property(env, result, "sensorName", sensorName); - - napi_value vendorName = nullptr; - napi_create_string_latin1(env, sensorInfo.vendorName, NAPI_AUTO_LENGTH, &vendorName); - napi_set_named_property(env, result, "vendorName", vendorName); - - napi_value firmwareVersion = nullptr; - napi_create_string_latin1(env, sensorInfo.firmwareVersion, NAPI_AUTO_LENGTH, &firmwareVersion); - napi_set_named_property(env, result, "firmwareVersion", firmwareVersion); - - napi_value hardwareVersion = nullptr; - napi_create_string_latin1(env, sensorInfo.hardwareVersion, NAPI_AUTO_LENGTH, &hardwareVersion); - napi_set_named_property(env, result, "hardwareVersion", hardwareVersion); - - napi_value sensorTypeId = nullptr; - napi_create_double(env, sensorInfo.sensorTypeId, &sensorTypeId); - napi_set_named_property(env, result, "sensorTypeId", sensorTypeId); - - napi_value maxRange = nullptr; - napi_create_double(env, sensorInfo.maxRange, &maxRange); - napi_set_named_property(env, result, "maxRange", maxRange); - - napi_value precision = nullptr; - napi_create_double(env, sensorInfo.precision, &precision); - napi_set_named_property(env, result, "precision", precision); - - napi_value power = nullptr; - napi_create_double(env, sensorInfo.power, &power); - napi_set_named_property(env, result, "power", power); + CALL_LOG_ENTER; + CHKNRF(env, napi_create_object(env, &result), "napi_create_object"); + napi_value value = nullptr; + CHKNRF(env, napi_create_string_latin1(env, sensorInfo.sensorName, NAPI_AUTO_LENGTH, &value), + "napi_create_string_latin1"); + CHKNRF(env, napi_set_named_property(env, result, "sensorName", value), "napi_set_named_property"); + + value = nullptr; + CHKNRF(env, napi_create_string_latin1(env, sensorInfo.vendorName, NAPI_AUTO_LENGTH, &value), + "napi_create_string_latin1"); + CHKNRF(env, napi_set_named_property(env, result, "vendorName", value), "napi_set_named_property"); + + value = nullptr; + CHKNRF(env, napi_create_string_latin1(env, sensorInfo.firmwareVersion, NAPI_AUTO_LENGTH, &value), + "napi_create_string_latin1"); + CHKNRF(env, napi_set_named_property(env, result, "firmwareVersion", value), "napi_set_named_property"); + + value = nullptr; + CHKNRF(env, napi_create_string_latin1(env, sensorInfo.hardwareVersion, NAPI_AUTO_LENGTH, &value), + "napi_create_string_latin1"); + CHKNRF(env, napi_set_named_property(env, result, "hardwareVersion", value), "napi_set_named_property"); + + value = nullptr; + CHKNRF(env, napi_create_double(env, sensorInfo.sensorTypeId, &value), "napi_create_double"); + CHKNRF(env, napi_set_named_property(env, result, "sensorTypeId", value), "napi_set_named_property"); + + value = nullptr; + CHKNRF(env, napi_create_double(env, sensorInfo.maxRange, &value), "napi_create_double"); + CHKNRF(env, napi_set_named_property(env, result, "maxRange", value), "napi_set_named_property"); + + value = nullptr; + CHKNRF(env, napi_create_double(env, sensorInfo.precision, &value), "napi_create_double"); + CHKNRF(env, napi_set_named_property(env, result, "precision", value), "napi_set_named_property"); + + value = nullptr; + CHKNRF(env, napi_create_double(env, sensorInfo.power, &value), "napi_create_double"); + CHKNRF(env, napi_set_named_property(env, result, "power", value), "napi_set_named_property"); + return true; } -void ConvertToSingleSensor(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]) +bool ConvertToSingleSensor(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]) { - napi_get_undefined(env, &result[0]); - napi_create_object(env, &result[1]); - ConvertToSensorInfo(env, asyncCallbackInfo->sensorInfos[0], result[1]); + CALL_LOG_ENTER; + CHKPF(asyncCallbackInfo); + return ConvertToSensorInfo(env, asyncCallbackInfo->sensorInfos[0], result[1]); } -void ConvertToSensorInfos(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]) +bool ConvertToSensorInfos(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]) { - napi_get_undefined(env, &result[0]); - napi_create_array(env, &result[1]); - for (size_t i = 0; i < asyncCallbackInfo->sensorInfos.size(); i++) { - napi_value sensorInfo = nullptr; - napi_create_object(env, &sensorInfo); - ConvertToSensorInfo(env, asyncCallbackInfo->sensorInfos[i], sensorInfo); - napi_set_element(env, result[1], i, sensorInfo); + CALL_LOG_ENTER; + CHKPF(asyncCallbackInfo); + CHKNRF(env, napi_create_array(env, &result[1]), "napi_create_array"); + auto sensorInfos = asyncCallbackInfo->sensorInfos; + for (uint32_t i = 0; i < sensorInfos.size(); ++i) { + napi_value value = nullptr; + CHKNCF(env, ConvertToSensorInfo(env, sensorInfos[i], value), "Convert sensor info fail"); + CHKNRF(env, napi_set_element(env, result[1], i, value), "napi_set_element"); } + return true; } -void ConvertToFailData(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]) +bool ConvertToFailData(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]) { + CALL_LOG_ENTER; + CHKPF(asyncCallbackInfo); result[0] = GreateBusinessError(env, asyncCallbackInfo->error.code, asyncCallbackInfo->error.message, asyncCallbackInfo->error.name, asyncCallbackInfo->error.stack); - napi_get_undefined(env, &result[1]); + CHKPF(result[0]); + return true; } -void ConvertToSensorData(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]) +bool ConvertToSensorData(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]) { - napi_get_undefined(env, &result[0]); + CHKPF(asyncCallbackInfo); int32_t sensorTypeId = asyncCallbackInfo->data.sensorData.sensorTypeId; - if (g_sensorAttributeList.find(sensorTypeId) == g_sensorAttributeList.end() - || g_sensorAttributeList[sensorTypeId].size() - > (asyncCallbackInfo->data.sensorData.dataLength / sizeof(float))) { - HiLog::Error(LABEL, "%{public}s count of sensorTypeId is zero", __func__); - return; - } - std::vector sensorAttribute = g_sensorAttributeList[sensorTypeId]; - napi_create_object(env, &result[1]); + CHKNCF(env, (g_sensorAttributeList.find(sensorTypeId) != g_sensorAttributeList.end()), "Invalid sensor type"); + size_t size = g_sensorAttributeList[sensorTypeId].size(); + uint32_t dataLenth = asyncCallbackInfo->data.sensorData.dataLength / sizeof(float); + CHKNCF(env, (size <= dataLenth), "Data length mismatch"); + + CHKNRF(env, napi_create_object(env, &result[1]), "napi_create_object"); napi_value message = nullptr; - for (size_t i = 0; i < sensorAttribute.size(); i++) { - napi_create_double(env, asyncCallbackInfo->data.sensorData.data[i], &message); - napi_set_named_property(env, result[1], sensorAttribute[i].c_str(), message); + auto sensorAttributes = g_sensorAttributeList[sensorTypeId]; + for (uint32_t i = 0; i < size; ++i) { + CHKNRF(env, napi_create_double(env, asyncCallbackInfo->data.sensorData.data[i], &message), + "napi_create_double"); + CHKNRF(env, napi_set_named_property(env, result[1], sensorAttributes[i].c_str(), message), + "napi_set_named_property"); message = nullptr; } - napi_create_int64(env, asyncCallbackInfo->data.sensorData.timestamp, &message); - napi_set_named_property(env, result[1], "timestamp", message); -} -void ConvertToNoData(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]) -{ - napi_get_undefined(env, &result[1]); - napi_get_undefined(env, &result[0]); + CHKNRF(env, napi_create_int64(env, asyncCallbackInfo->data.sensorData.timestamp, &message), + "napi_create_int64"); + CHKNRF(env, napi_set_named_property(env, result[1], "timestamp", message), "napi_set_named_property"); + return true; } -void ConvertToGeomagneticData(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]) +bool ConvertToGeomagneticData(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]) { - napi_get_undefined(env, &result[0]); - napi_create_object(env, &result[1]); - getJsonObject(env, asyncCallbackInfo, result[1]); + CALL_LOG_ENTER; + return getJsonObject(env, asyncCallbackInfo, result[1]); } -void ConvertToNumber(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]) +bool ConvertToNumber(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]) { - napi_get_undefined(env, &result[0]); - napi_create_double(env, static_cast(asyncCallbackInfo->data.reserveData.reserve[0]), &result[1]); + CALL_LOG_ENTER; + CHKPF(asyncCallbackInfo); + napi_status status = + napi_create_double(env, static_cast(asyncCallbackInfo->data.reserveData.reserve[0]), &result[1]); + CHKNRF(env, status, "napi_create_double"); + return true; } -void ConvertToArray(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]) +bool ConvertToArray(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]) { - napi_get_undefined(env, &result[0]); - napi_create_array(env, &result[1]); - CreateNapiArray(env, asyncCallbackInfo->data.reserveData.reserve, + CALL_LOG_ENTER; + CHKPF(asyncCallbackInfo); + bool ret = CreateNapiArray(env, asyncCallbackInfo->data.reserveData.reserve, asyncCallbackInfo->data.reserveData.length, result[1]); + CHKNCF(env, ret, "Create napi array fail"); + return true; } -void ConvertToRotationMatrix(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]) +bool ConvertToRotationMatrix(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]) { - napi_get_undefined(env, &result[0]); - napi_create_object(env, &result[1]); + CALL_LOG_ENTER; + CHKPF(asyncCallbackInfo); napi_value rotation = nullptr; - napi_create_array(env, &rotation); - CreateNapiArray(env, asyncCallbackInfo->data.rationMatrixData.rotationMatrix, + bool ret = CreateNapiArray(env, asyncCallbackInfo->data.rationMatrixData.rotationMatrix, THREE_DIMENSIONAL_MATRIX_LENGTH, rotation); + CHKNCF(env, ret, "Create napi array rotation fail"); + napi_value inclination = nullptr; - napi_create_array(env, &inclination); - CreateNapiArray(env, asyncCallbackInfo->data.rationMatrixData.inclinationMatrix, + ret = CreateNapiArray(env, asyncCallbackInfo->data.rationMatrixData.inclinationMatrix, THREE_DIMENSIONAL_MATRIX_LENGTH, inclination); - napi_set_named_property(env, result[1], "rotation", rotation); - napi_set_named_property(env, result[1], "inclination", inclination); + CHKNCF(env, ret, "Create napi array inclination fail"); + + CHKNRF(env, napi_create_object(env, &result[1]), "napi_create_object"); + CHKNRF(env, napi_set_named_property(env, result[1], "rotation", rotation), + "napi_set_named_property"); + CHKNRF(env, napi_set_named_property(env, result[1], "inclination", inclination), + "napi_set_named_property"); + return true; } -napi_value GreateBusinessError(napi_env env, int32_t errCode, string errMessage, string errName, string errStack) +napi_value GreateBusinessError(const napi_env &env, int32_t errCode, string errMessage, + string errName, string errStack) { + CALL_LOG_ENTER; napi_value result = nullptr; - napi_value code = nullptr; - napi_value message = nullptr; - napi_value name = nullptr; - napi_value stack = nullptr; - NAPI_CALL(env, napi_create_int32(env, errCode, &code)); - NAPI_CALL(env, napi_create_string_utf8(env, errMessage.data(), NAPI_AUTO_LENGTH, &message)); - NAPI_CALL(env, napi_create_string_utf8(env, errName.data(), NAPI_AUTO_LENGTH, &name)); - NAPI_CALL(env, napi_create_string_utf8(env, errStack.data(), NAPI_AUTO_LENGTH, &stack)); - NAPI_CALL(env, napi_create_object(env, &result)); - NAPI_CALL(env, napi_set_named_property(env, result, "code", code)); - NAPI_CALL(env, napi_set_named_property(env, result, "message", message)); - NAPI_CALL(env, napi_set_named_property(env, result, "name", name)); - NAPI_CALL(env, napi_set_named_property(env, result, "stack", stack)); + CHKNRP(env, napi_create_object(env, &result), "napi_create_object"); + napi_value value = nullptr; + CHKNRP(env, napi_create_int32(env, errCode, &value), "napi_create_int32"); + CHKNRP(env, napi_set_named_property(env, result, "code", value), "napi_set_named_property"); + + value = nullptr; + CHKNRP(env, napi_create_string_utf8(env, errMessage.data(), NAPI_AUTO_LENGTH, &value), + "napi_create_string_utf8"); + CHKNRP(env, napi_set_named_property(env, result, "message", value), "napi_set_named_property"); + + value = nullptr; + CHKNRP(env, napi_create_string_utf8(env, errName.data(), NAPI_AUTO_LENGTH, &value), + "napi_create_string_utf8"); + CHKNRP(env, napi_set_named_property(env, result, "name", value), "napi_set_named_property"); + + value = nullptr; + CHKNRP(env, napi_create_string_utf8(env, errStack.data(), NAPI_AUTO_LENGTH, &value), + "napi_create_string_utf8"); + CHKNRP(env, napi_set_named_property(env, result, "stack", value), "napi_set_named_property"); return result; } -void CreateNapiArray(napi_env env, float *data, int32_t dataLength, napi_value result) +bool CreateNapiArray(const napi_env &env, float data[], int32_t dataLength, napi_value &result) { - for (int32_t index = 0; index < dataLength; index++) { + CHKNRF(env, napi_create_array(env, &result), "napi_create_array"); + for (int32_t i = 0; i < dataLength; ++i) { napi_value message = nullptr; - napi_create_double(env, data[index], &message); - napi_set_element(env, result, index, message); + CHKNRF(env, napi_create_double(env, data[i], &message), "napi_create_double"); + CHKNRF(env, napi_set_element(env, result, i, message), "napi_set_element"); } + return true; } -void EmitAsyncCallbackWork(AsyncCallbackInfo *asyncCallbackInfo) +void EmitAsyncCallbackWork(sptr asyncCallbackInfo) { - HiLog::Debug(LABEL, "%{public}s begin", __func__); - if (asyncCallbackInfo == nullptr) { - HiLog::Error(LABEL, "%{public}s asyncCallbackInfo is null", __func__); - return; - } + CALL_LOG_ENTER; + CHKPV(asyncCallbackInfo); napi_value resourceName = nullptr; - if (napi_create_string_utf8(asyncCallbackInfo->env, "AsyncCallback", NAPI_AUTO_LENGTH, &resourceName) != napi_ok) { - HiLog::Error(LABEL, "%{public}s create string utf8 failed", __func__); - return; - } - napi_create_async_work( - asyncCallbackInfo->env, nullptr, resourceName, + CHKNRV(asyncCallbackInfo->env, napi_create_string_utf8(asyncCallbackInfo->env, "AsyncCallback", + NAPI_AUTO_LENGTH, &resourceName), "napi_create_string_utf8"); + // Make the reference count of asyncCallbackInfo add 1, and the function exits the non-destructor + asyncCallbackInfo->callbackInfo = asyncCallbackInfo; + napi_status status = napi_create_async_work(asyncCallbackInfo->env, nullptr, resourceName, [](napi_env env, void* data) {}, [](napi_env env, napi_status status, void* data) { - HiLog::Debug(LABEL, "%{public}s napi_create_async_work in", __func__); - AsyncCallbackInfo *asyncCallbackInfo = reinterpret_cast(data); - if (asyncCallbackInfo == nullptr) { - HiLog::Error(LABEL, "%{public}s asyncCallbackInfo is null", __func__); - return; - } - napi_value callback; - napi_get_reference_value(env, asyncCallbackInfo->callback[0], &callback); + CALL_LOG_ENTER; + CHKPV(data); + sptr asyncCallbackInfo = reinterpret_cast(data)->callbackInfo; + CHKPV(asyncCallbackInfo); + // The reference count of asyncCallbackInfo is subtracted by 1, and the function exits the destructor + asyncCallbackInfo->callbackInfo = nullptr; + napi_value callback = nullptr; + CHKNRV(env, napi_get_reference_value(env, asyncCallbackInfo->callback[0], &callback), + "napi_get_reference_value"); napi_value callResult = nullptr; napi_value result[2] = {0}; - if (g_convertfuncList.find(asyncCallbackInfo->type) == g_convertfuncList.end()) { - HiLog::Error(LABEL, "%{public}s type invalid", __func__); - return; - } - g_convertfuncList[asyncCallbackInfo->type](env, asyncCallbackInfo, result); - napi_call_function(env, nullptr, callback, 2, result, &callResult); - napi_delete_reference(env, asyncCallbackInfo->callback[0]); - napi_delete_async_work(env, asyncCallbackInfo->asyncWork); - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - HiLog::Debug(LABEL, "%{public}s napi_create_async_work left", __func__); + CHKNCV(env, (g_convertfuncList.find(asyncCallbackInfo->type) != g_convertfuncList.end()), + "Callback type invalid in async work"); + bool ret = g_convertfuncList[asyncCallbackInfo->type](env, asyncCallbackInfo, result); + CHKNCV(env, ret, "Create napi data fail in async work"); + CHKNRV(env, napi_call_function(env, nullptr, callback, 2, result, &callResult), + "napi_call_function"); }, - asyncCallbackInfo, &asyncCallbackInfo->asyncWork); - - napi_queue_async_work(asyncCallbackInfo->env, asyncCallbackInfo->asyncWork); - HiLog::Debug(LABEL, "%{public}s end", __func__); + asyncCallbackInfo.GetRefPtr(), &asyncCallbackInfo->asyncWork); + if (status != napi_ok + || napi_queue_async_work(asyncCallbackInfo->env, asyncCallbackInfo->asyncWork) != napi_ok) { + SEN_HILOGE("Create async work fail"); + // The reference count of asyncCallbackInfo is subtracted by 1, and the function exits the destructor + asyncCallbackInfo->callbackInfo = nullptr; + } } -void EmitUvEventLoop(AsyncCallbackInfo **asyncCallbackInfo) +void EmitUvEventLoop(sptr asyncCallbackInfo) { + CALL_LOG_ENTER; + CHKPV(asyncCallbackInfo); uv_loop_s *loop(nullptr); - if (asyncCallbackInfo == nullptr || *asyncCallbackInfo == nullptr - || (*asyncCallbackInfo)->env == nullptr) { - HiLog::Error(LABEL, "%{public}s asyncCallbackInfo is null", __func__); - return; - } - napi_get_uv_event_loop((*asyncCallbackInfo)->env, &loop); - if (loop == nullptr) { - HiLog::Error(LABEL, "%{public}s loop is null", __func__); - return; - } + CHKNRV(asyncCallbackInfo->env, napi_get_uv_event_loop(asyncCallbackInfo->env, &loop), + "napi_get_uv_event_loop"); + CHKPV(loop); uv_work_t *work = new(std::nothrow) uv_work_t; - if (work == nullptr) { - HiLog::Error(LABEL, "%{public}s work is null", __func__); - return; - } - work->data = reinterpret_cast(asyncCallbackInfo); - uv_queue_work(loop, work, [] (uv_work_t *work) { }, [] (uv_work_t *work, int status) { - AsyncCallbackInfo *asyncCallbackInfo = *reinterpret_cast(work->data); - if (asyncCallbackInfo == nullptr || asyncCallbackInfo->env == nullptr - || asyncCallbackInfo->callback[0] == nullptr) { - HiLog::Error(LABEL, "%{public}s asyncCallbackInfo is null", __func__); - return; - } + CHKPV(work); + asyncCallbackInfo->callbackInfo = asyncCallbackInfo; + asyncCallbackInfo->work = work; + work->data = asyncCallbackInfo.GetRefPtr(); + int32_t ret = uv_queue_work(loop, work, [] (uv_work_t *work) { }, [] (uv_work_t *work, int status) { + CALL_LOG_ENTER; + CHKPV(work); + CHKPV(work->data); + sptr asyncCallbackInfo = + reinterpret_cast(work->data)->callbackInfo; + CHKPV(asyncCallbackInfo); + asyncCallbackInfo->callbackInfo = nullptr; napi_env env = asyncCallbackInfo->env; - napi_value undefined = nullptr; - napi_get_undefined(env, &undefined); napi_value callback = nullptr; - napi_get_reference_value(env, asyncCallbackInfo->callback[0], &callback); + CHKNRV(env, napi_get_reference_value(env, asyncCallbackInfo->callback[0], &callback), + "napi_get_reference_value"); napi_value callResult = nullptr; napi_value result[2] = {0}; - if (g_convertfuncList.find(asyncCallbackInfo->type) == g_convertfuncList.end()) { - HiLog::Error(LABEL, "%{public}s type invalid", __func__); - return; - } + CHKNCV(env, (g_convertfuncList.find(asyncCallbackInfo->type) != g_convertfuncList.end()), + "Asynccallback Type invalid in uv work"); g_convertfuncList[asyncCallbackInfo->type](env, asyncCallbackInfo, result); - napi_call_function(env, undefined, callback, 1, &result[1], &callResult); - if (asyncCallbackInfo->type != ON_CALLBACK) { - napi_delete_reference(env, asyncCallbackInfo->callback[0]); - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - } + CHKNRV(env, napi_call_function(env, nullptr, callback, 1, &result[1], &callResult), "napi_call_function"); + CHKPV(work); delete work; work = nullptr; }); + if (ret != 0) { + SEN_HILOGE("uv_queue_work fail"); + asyncCallbackInfo->callbackInfo = nullptr; + CHKPV(work); + delete work; + work = nullptr; + } } -void EmitPromiseWork(AsyncCallbackInfo *asyncCallbackInfo) +void EmitPromiseWork(sptr asyncCallbackInfo) { - if (asyncCallbackInfo == nullptr) { - HiLog::Error(LABEL, "%s asyncCallbackInfo is nullptr", __func__); - return; - } + CALL_LOG_ENTER; + CHKPV(asyncCallbackInfo); napi_value resourceName = nullptr; - napi_create_string_latin1(asyncCallbackInfo->env, "Promise", NAPI_AUTO_LENGTH, &resourceName); - napi_create_async_work( - asyncCallbackInfo->env, nullptr, resourceName, [](napi_env env, void* data) {}, + CHKNRV(asyncCallbackInfo->env, napi_create_string_latin1(asyncCallbackInfo->env, "Promise", + NAPI_AUTO_LENGTH, &resourceName), "napi_create_string_latin1"); + // Make the reference count of asyncCallbackInfo add 1, and the function exits the non-destructor + asyncCallbackInfo->callbackInfo = asyncCallbackInfo; + napi_status status = napi_create_async_work(asyncCallbackInfo->env, nullptr, resourceName, + [](napi_env env, void* data) {}, [](napi_env env, napi_status status, void* data) { - AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; - if (asyncCallbackInfo == nullptr) { - HiLog::Error(LABEL, "%{public}s asyncCallbackInfo is null", __func__); - return; - } + CALL_LOG_ENTER; + CHKPV(data); + sptr asyncCallbackInfo = reinterpret_cast(data)->callbackInfo; + CHKPV(asyncCallbackInfo); + // The reference count of asyncCallbackInfo is subtracted by 1, and the function exits the destructor + asyncCallbackInfo->callbackInfo = nullptr; napi_value result[2] = {0}; - if (g_convertfuncList.find(asyncCallbackInfo->type) == g_convertfuncList.end()) { - HiLog::Error(LABEL, "%{public}s type invalid", __func__); - return; - } - g_convertfuncList[asyncCallbackInfo->type](env, asyncCallbackInfo, result); + CHKNCV(env, (g_convertfuncList.find(asyncCallbackInfo->type) != g_convertfuncList.end()), + "Callback type invalid in promise"); + bool ret = g_convertfuncList[asyncCallbackInfo->type](env, asyncCallbackInfo, result); + CHKNCV(env, ret, "Create napi data fail in promise"); if (asyncCallbackInfo->type == FAIL) { - napi_reject_deferred(env, asyncCallbackInfo->deferred, result[0]); + CHKNRV(env, napi_reject_deferred(env, asyncCallbackInfo->deferred, result[0]), + "napi_reject_deferred"); } else { - napi_resolve_deferred(env, asyncCallbackInfo->deferred, result[1]); + CHKNRV(env, napi_resolve_deferred(env, asyncCallbackInfo->deferred, result[1]), + "napi_resolve_deferred"); } - napi_delete_async_work(env, asyncCallbackInfo->asyncWork); - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; }, - (void*)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); - napi_queue_async_work(asyncCallbackInfo->env, asyncCallbackInfo->asyncWork); -} \ No newline at end of file + asyncCallbackInfo.GetRefPtr(), &asyncCallbackInfo->asyncWork); + if (status != napi_ok + || napi_queue_async_work(asyncCallbackInfo->env, asyncCallbackInfo->asyncWork) != napi_ok) { + SEN_HILOGE("Create async work fail"); + // The reference count of asyncCallbackInfo is subtracted by 1, and the function exits the destructor + asyncCallbackInfo->callbackInfo = nullptr; + } +} +} // namespace Sensors +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/plugin/src/sensor_system_js.cpp b/interfaces/plugin/src/sensor_system_js.cpp index d17ada02c2545ddd404f2ddcc21eb9a54fe44542..39d4cbb54c212ab761c8f28b55d344a9d6555a81 100644 --- a/interfaces/plugin/src/sensor_system_js.cpp +++ b/interfaces/plugin/src/sensor_system_js.cpp @@ -16,7 +16,8 @@ #include "hilog/log.h" #include "sensor_agent_type.h" - +namespace OHOS { +namespace Sensors { using namespace OHOS::HiviewDFX; static constexpr HiLogLabel LABEL = {LOG_CORE, 0xD002708, "SensorSystemJs"}; @@ -191,3 +192,5 @@ napi_value UnsubscribeHall(napi_env env, napi_callback_info info) HiLog::Debug(LABEL, "%{public}s in", __func__); return Unsubscribe(env, info, SENSOR_TYPE_ID_HALL); } +} // namespace Sensors +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/plugin/test/unittest/ExampleJsunit.test.js b/interfaces/plugin/test/unittest/ExampleJsunit.test.js index b7c00665b2e088890485a542d38b73bebb978fe0..ff75e1a6ba0e6c22079db42b8182b275e54c2ca8 100644 --- a/interfaces/plugin/test/unittest/ExampleJsunit.test.js +++ b/interfaces/plugin/test/unittest/ExampleJsunit.test.js @@ -83,11 +83,13 @@ describe("SensorJsTest", function () { expect(false).assertTrue(); done(); } - sensor.on(-1, onSensorCallback); - setTimeout(()=>{ + try { + sensor.on(-1, onSensorCallback); + } catch (error) { + console.info(error); expect(true).assertTrue(); done(); - }, 500); + } }) /* @@ -113,19 +115,20 @@ describe("SensorJsTest", function () { * @tc.type: FUNC * @tc.require: Issue Number */ - it("SensorJsTest004", 0, function () { + it("SensorJsTest004", 0, function (done) { console.info('----------------------SensorJsTest004---------------------------'); function onSensorCallback(data) { console.info('SensorJsTest004 on error'); expect(false).assertTrue(); done(); } - sensor.on(0, onSensorCallback, {'interval': 100000000}, 5); - setTimeout(()=>{ + try { + sensor.on(0, onSensorCallback, {'interval': 100000000}, 5); + } catch (error) { + console.info(error); expect(true).assertTrue(); done(); - }, 500); - console.info('----------------------SensorJsTest004--------------------------- end'); + } }) /* @@ -154,11 +157,13 @@ describe("SensorJsTest", function () { expect(false).assertTrue(); done(); } - sensor.once(-1, onceSensorCallback); - setTimeout(()=>{ + try { + sensor.once(-1, onceSensorCallback); + } catch (error) { + console.info(error); expect(true).assertTrue(); done(); - }, 500); + } }) /* @@ -167,17 +172,19 @@ describe("SensorJsTest", function () { * @tc.type: FUNC * @tc.require: Issue Number */ - it("SensorJsTest007", 0, function () { + it("SensorJsTest007", 0, function (done) { function onceSensorCallback(data) { console.info('SensorJsTest007 on error'); expect(false).assertTrue(); done(); } - sensor.once(0, onceSensorCallback, 5); - setTimeout(()=>{ + try{ + sensor.once(0, onceSensorCallback, 5); + } catch (error) { + console.info(error); expect(true).assertTrue(); done(); - }, 500); + } }) /* @@ -187,11 +194,13 @@ describe("SensorJsTest", function () { * @tc.require: Issue Number */ it("SensorJsTest008", 0, async function (done) { - sensor.off(-1, callback); - setTimeout(()=>{ + try { + sensor.off(-1, callback); + } catch (error) { + console.info(error); expect(true).assertTrue(); done(); - }, 500); + } }) /* @@ -226,11 +235,13 @@ describe("SensorJsTest", function () { expect(false).assertTrue(); done(); } - sensor.off(1000000, onSensorCallback); - setTimeout(()=>{ + try { + sensor.off(1000000, onSensorCallback); + } catch (error) { + console.info(error); expect(true).assertTrue(); done(); - }, 500); + } }) /* @@ -262,6 +273,10 @@ describe("SensorJsTest", function () { setTimeout(()=>{ console.info('----------------------SensorJsTest012 off in---------------------------'); sensor.off(0, callback); + console.info('----------------------SensorJsTest012 off end---------------------------'); + }, 500); + setTimeout(()=>{ + console.info('----------------------SensorJsTest012 off in---------------------------'); sensor.off(0, callback2); console.info('----------------------SensorJsTest012 off end---------------------------'); done(); @@ -274,9 +289,14 @@ describe("SensorJsTest", function () { * @tc.type: FUNC * @tc.require: Issue Number */ - it("SensorJsTest013", 0, function () { - sensor.off(0, 5); - expect(true).assertTrue(); + it("SensorJsTest013", 0, function (done) { + try { + sensor.off(0, 5); + } catch (error) { + console.info(error); + expect(true).assertTrue(); + done(); + } }) /* @@ -291,8 +311,7 @@ describe("SensorJsTest", function () { sensor.once(0, callback2); setTimeout(()=>{ console.info('----------------------SensorJsTest014 off in---------------------------'); - sensor.off(0, callback); - sensor.off(0, callback2); + sensor.off(0); console.info('----------------------SensorJsTest014 off end---------------------------'); done(); }, 1000); @@ -311,6 +330,10 @@ describe("SensorJsTest", function () { setTimeout(()=>{ console.info('----------------------SensorJsTest015 off in---------------------------'); sensor.off(0, callback); + console.info('----------------------SensorJsTest015 off end---------------------------'); + }, 500); + setTimeout(()=>{ + console.info('----------------------SensorJsTest015 off in---------------------------'); sensor.off(0, callback2); console.info('----------------------SensorJsTest015 off end---------------------------'); done(); diff --git a/utils/include/sensor_log.h b/utils/include/sensor_log.h old mode 100755 new mode 100644 index aaf115f99fdc9235b7723c97ebab231d758155b0..b252ddc585a1eb8396580e8fa69dcc83bf5f9abc --- a/utils/include/sensor_log.h +++ b/utils/include/sensor_log.h @@ -23,11 +23,11 @@ namespace { constexpr uint32_t SENSOR_LOG_DOMAIN = 0xD002800; } // namespace #ifndef SENSOR_FUNC_FMT -#define SENSOR_FUNC_FMT "in %{public}s, #%{public}d, " +#define SENSOR_FUNC_FMT "in %{public}s, " #endif #ifndef SENSOR_FUNC_INFO -#define SENSOR_FUNC_INFO __FUNCTION__, __LINE__ +#define SENSOR_FUNC_INFO __FUNCTION__ #endif #define SEN_HILOGD(fmt, ...) do { \ diff --git a/utils/include/sensors_errors.h b/utils/include/sensors_errors.h index 28eca4f5faf8916e0179a3eb3f38d5f615e50b0b..f7ced51e22c4903d60a2923a0e4c5f586f874b93 100644 --- a/utils/include/sensors_errors.h +++ b/utils/include/sensors_errors.h @@ -246,6 +246,22 @@ private: } \ } while (0) +#define CHKCF(cond, message) \ + do { \ + if (!(cond)) { \ + SEN_HILOGE("CK(%{public}s), %{public}s", #cond, message); \ + return false; \ + } \ + } while (0) + +#define CHKCV(cond, message) \ + do { \ + if (!(cond)) { \ + SEN_HILOGE("CK(%{public}s), %{public}s", #cond, message); \ + return; \ + } \ + } while (0) + #define CHKPP(cond) \ do { \ if ((cond) == nullptr) { \