From 39a5e9db4055107b8b425fd564fbe5ce42a3fc12 Mon Sep 17 00:00:00 2001 From: h00514358 Date: Fri, 30 Sep 2022 10:20:34 +0800 Subject: [PATCH] Add API exception handling Signed-off-by: h00514358 --- .../native/sensor/src/sensor_agent_proxy.cpp | 21 +- .../sensor/src/sensor_service_client.cpp | 6 +- interfaces/native/src/sensor_agent.cpp | 94 ++- interfaces/native/src/sensor_algorithm.cpp | 40 +- interfaces/plugin/BUILD.gn | 5 +- .../plugin/include/async_callback_info.h | 3 +- interfaces/plugin/include/sensor_js.h | 9 +- interfaces/plugin/include/sensor_napi_error.h | 37 + interfaces/plugin/include/sensor_napi_utils.h | 97 +-- interfaces/plugin/src/sensor_js.cpp | 693 +++++++++++++----- interfaces/plugin/src/sensor_napi_error.cpp | 58 ++ interfaces/plugin/src/sensor_napi_utils.cpp | 99 +-- services/sensor/src/sensor_service_stub.cpp | 8 +- utils/include/sensors_errors.h | 15 + 14 files changed, 788 insertions(+), 397 deletions(-) create mode 100755 interfaces/plugin/include/sensor_napi_error.h create mode 100755 interfaces/plugin/src/sensor_napi_error.cpp diff --git a/frameworks/native/sensor/src/sensor_agent_proxy.cpp b/frameworks/native/sensor/src/sensor_agent_proxy.cpp index 1fd37956..7b28161c 100644 --- a/frameworks/native/sensor/src/sensor_agent_proxy.cpp +++ b/frameworks/native/sensor/src/sensor_agent_proxy.cpp @@ -140,7 +140,7 @@ int32_t SensorAgentProxy::ActivateSensor(int32_t sensorId, const SensorUser *use } if (!SenClient.IsValid(sensorId)) { SEN_HILOGE("sensorId is invalid, %{public}d", sensorId); - return ERROR; + return PARAMETER_ERROR; } if ((g_subscribeMap.find(sensorId) == g_subscribeMap.end()) || (g_subscribeMap[sensorId] != user)) { SEN_HILOGE("subscribe sensorId first"); @@ -152,10 +152,9 @@ int32_t SensorAgentProxy::ActivateSensor(int32_t sensorId, const SensorUser *use if (ret != 0) { SEN_HILOGE("enable sensor failed, ret:%{public}d", ret); g_subscribeMap.erase(sensorId); - - return OHOS::Sensors::ERROR; + return ret; } - return OHOS::Sensors::SUCCESS; + return ret; } int32_t SensorAgentProxy::DeactivateSensor(int32_t sensorId, const SensorUser *user) const @@ -164,7 +163,7 @@ int32_t SensorAgentProxy::DeactivateSensor(int32_t sensorId, const SensorUser *u CHKPR(user->callback, OHOS::Sensors::ERROR); if (!SenClient.IsValid(sensorId)) { SEN_HILOGE("sensorId is invalid, %{public}d", sensorId); - return ERROR; + return PARAMETER_ERROR; } std::lock_guard subscribeLock(subscribeMutex_); if ((g_subscribeMap.find(sensorId) == g_subscribeMap.end()) || (g_subscribeMap[sensorId] != user)) { @@ -175,10 +174,10 @@ int32_t SensorAgentProxy::DeactivateSensor(int32_t sensorId, const SensorUser *u g_unsubscribeMap[sensorId] = user; int32_t ret = SenClient.DisableSensor(sensorId); if (ret != 0) { - SEN_HILOGE("disable sensor failed, ret:%{public}d", ret); - return OHOS::Sensors::ERROR; + SEN_HILOGE("DisableSensor failed, ret:%{public}d", ret); + return ret; } - return OHOS::Sensors::SUCCESS; + return ret; } int32_t SensorAgentProxy::SetBatch(int32_t sensorId, const SensorUser *user, int64_t samplingInterval, @@ -187,7 +186,7 @@ int32_t SensorAgentProxy::SetBatch(int32_t sensorId, const SensorUser *user, int CHKPR(user, OHOS::Sensors::ERROR); if (!SenClient.IsValid(sensorId)) { SEN_HILOGE("sensorId is invalid, %{public}d", sensorId); - return ERROR; + return PARAMETER_ERROR; } if (samplingInterval < 0 || reportInterval < 0) { SEN_HILOGE("samplingInterval or reportInterval is invalid"); @@ -210,7 +209,7 @@ int32_t SensorAgentProxy::SubscribeSensor(int32_t sensorId, const SensorUser *us CHKPR(user->callback, OHOS::Sensors::ERROR); if (!SenClient.IsValid(sensorId)) { SEN_HILOGE("sensorId is invalid, %{public}d", sensorId); - return ERROR; + return PARAMETER_ERROR; } int32_t ret = CreateSensorDataChannel(); if (ret != ERR_OK) { @@ -229,7 +228,7 @@ int32_t SensorAgentProxy::UnsubscribeSensor(int32_t sensorId, const SensorUser * CHKPR(user->callback, OHOS::Sensors::ERROR); if (!SenClient.IsValid(sensorId)) { SEN_HILOGE("sensorId is invalid, %{public}d", sensorId); - return ERROR; + return PARAMETER_ERROR; } std::lock_guard subscribeLock(subscribeMutex_); if (g_unsubscribeMap.find(sensorId) == g_unsubscribeMap.end() || g_unsubscribeMap[sensorId] != user) { diff --git a/frameworks/native/sensor/src/sensor_service_client.cpp b/frameworks/native/sensor/src/sensor_service_client.cpp index 26bcef24..df26d269 100755 --- a/frameworks/native/sensor/src/sensor_service_client.cpp +++ b/frameworks/native/sensor/src/sensor_service_client.cpp @@ -97,7 +97,7 @@ int32_t SensorServiceClient::EnableSensor(uint32_t sensorId, int64_t samplingPer CALL_LOG_ENTER; if (!IsValid(sensorId)) { SEN_HILOGE("sensorId is invalid"); - return SENSOR_NATIVE_SAM_ERR; + return PARAMETER_ERROR; } int32_t ret = InitServiceClient(); if (ret != ERR_OK) { @@ -119,7 +119,7 @@ int32_t SensorServiceClient::DisableSensor(uint32_t sensorId) CALL_LOG_ENTER; if (!IsValid(sensorId)) { SEN_HILOGE("sensorId is invalid"); - return SENSOR_NATIVE_SAM_ERR; + return PARAMETER_ERROR; } int32_t ret = InitServiceClient(); if (ret != ERR_OK) { @@ -141,7 +141,7 @@ int32_t SensorServiceClient::RunCommand(uint32_t sensorId, int32_t cmdType, int3 CALL_LOG_ENTER; if (!IsValid(sensorId)) { SEN_HILOGE("sensorId is invalid"); - return SENSOR_NATIVE_SAM_ERR; + return PARAMETER_ERROR; } int32_t ret = InitServiceClient(); if (ret != ERR_OK) { diff --git a/interfaces/native/src/sensor_agent.cpp b/interfaces/native/src/sensor_agent.cpp index b8e41868..06572fe6 100755 --- a/interfaces/native/src/sensor_agent.cpp +++ b/interfaces/native/src/sensor_agent.cpp @@ -20,91 +20,137 @@ using OHOS::HiviewDFX::HiLog; using OHOS::HiviewDFX::HiLogLabel; +using OHOS::Sensors::SensorAgentProxy; +using OHOS::Sensors::SERVICE_EXCEPTION; +using OHOS::Sensors::PARAMETER_ERROR; +using OHOS::Sensors::PERMISSION_DENIED; static const HiLogLabel LABEL = {LOG_CORE, OHOS::Sensors::SENSOR_LOG_DOMAIN, "SensorNativeAPI"}; -static const OHOS::Sensors::SensorAgentProxy *GetInstance() +static const SensorAgentProxy *GetInstance() { - const OHOS::Sensors::SensorAgentProxy *obj = OHOS::Sensors::SensorAgentProxy::GetSensorsObj(); + const SensorAgentProxy *obj = SensorAgentProxy::GetSensorsObj(); return obj; } +static int32_t NormalizeErrCode(int32_t code) +{ + switch (code) { + case PERMISSION_DENIED: { + return PERMISSION_DENIED; + } + case PARAMETER_ERROR: { + return PARAMETER_ERROR; + } + default: { + return SERVICE_EXCEPTION; + } + } +} + int32_t GetAllSensors(SensorInfo **sensorInfo, int32_t *count) { - const OHOS::Sensors::SensorAgentProxy *proxy = GetInstance(); + const SensorAgentProxy *proxy = GetInstance(); if (proxy == nullptr) { SEN_HILOGE("proxy is nullptr"); - return OHOS::Sensors::ERROR; + return SERVICE_EXCEPTION; + } + int32_t ret = proxy->GetAllSensors(sensorInfo, count); + if (ret != OHOS::ERR_OK) { + return NormalizeErrCode(ret); } - return proxy->GetAllSensors(sensorInfo, count); + return ret; } int32_t ActivateSensor(int32_t sensorId, const SensorUser *user) { - const OHOS::Sensors::SensorAgentProxy *proxy = GetInstance(); + const SensorAgentProxy *proxy = GetInstance(); if (proxy == nullptr) { SEN_HILOGE("proxy is nullptr"); - return OHOS::Sensors::ERROR; + return SERVICE_EXCEPTION; } - return proxy->ActivateSensor(sensorId, user); + int32_t ret = proxy->ActivateSensor(sensorId, user); + if (ret != OHOS::ERR_OK) { + return NormalizeErrCode(ret); + } + return ret; } int32_t DeactivateSensor(int32_t sensorId, const SensorUser *user) { - const OHOS::Sensors::SensorAgentProxy *proxy = GetInstance(); + const SensorAgentProxy *proxy = GetInstance(); if (proxy == nullptr) { SEN_HILOGE("proxy is nullptr"); - return OHOS::Sensors::ERROR; + return SERVICE_EXCEPTION; + } + int32_t ret = proxy->DeactivateSensor(sensorId, user); + if (ret != OHOS::ERR_OK) { + return NormalizeErrCode(ret); } - return proxy->DeactivateSensor(sensorId, user); + return ret; } int32_t SetBatch(int32_t sensorId, const SensorUser *user, int64_t samplingInterval, int64_t reportInterval) { - const OHOS::Sensors::SensorAgentProxy *proxy = GetInstance(); + const SensorAgentProxy *proxy = GetInstance(); if (proxy == nullptr) { SEN_HILOGE("proxy is nullptr"); - return OHOS::Sensors::ERROR; + return SERVICE_EXCEPTION; + } + int32_t ret = proxy->SetBatch(sensorId, user, samplingInterval, reportInterval); + if (ret != OHOS::ERR_OK) { + SEN_HILOGE("SetBatch failed"); + return NormalizeErrCode(ret); } - return proxy->SetBatch(sensorId, user, samplingInterval, reportInterval); + return ret; } int32_t SubscribeSensor(int32_t sensorId, const SensorUser *user) { - const OHOS::Sensors::SensorAgentProxy *proxy = GetInstance(); + const SensorAgentProxy *proxy = GetInstance(); if (proxy == nullptr) { SEN_HILOGE("proxy is nullptr"); - return OHOS::Sensors::ERROR; + return SERVICE_EXCEPTION; } - return proxy->SubscribeSensor(sensorId, user); + int32_t ret = proxy->SubscribeSensor(sensorId, user); + if (ret != OHOS::ERR_OK) { + SEN_HILOGE("SubscribeSensor failed"); + return NormalizeErrCode(ret); + } + return ret; } int32_t UnsubscribeSensor(int32_t sensorId, const SensorUser *user) { - const OHOS::Sensors::SensorAgentProxy *proxy = GetInstance(); + const SensorAgentProxy *proxy = GetInstance(); if (proxy == nullptr) { SEN_HILOGE("proxy is nullptr"); - return OHOS::Sensors::ERROR; + return SERVICE_EXCEPTION; + } + int32_t ret = proxy->UnsubscribeSensor(sensorId, user); + if (ret != OHOS::ERR_OK) { + SEN_HILOGE("UnsubscribeSensor failed"); + return NormalizeErrCode(ret); } - return proxy->UnsubscribeSensor(sensorId, user); + return ret; } int32_t SetMode(int32_t sensorId, const SensorUser *user, int32_t mode) { - const OHOS::Sensors::SensorAgentProxy *proxy = GetInstance(); + const SensorAgentProxy *proxy = GetInstance(); if (proxy == nullptr) { SEN_HILOGE("proxy is nullptr"); - return OHOS::Sensors::ERROR; + return SERVICE_EXCEPTION; } return proxy->SetMode(sensorId, user, mode); } int32_t SetOption(int32_t sensorId, const SensorUser *user, int32_t option) { - const OHOS::Sensors::SensorAgentProxy *proxy = GetInstance(); + const SensorAgentProxy *proxy = GetInstance(); if (proxy == nullptr) { SEN_HILOGE("proxy is nullptr"); - return OHOS::Sensors::ERROR; + return SERVICE_EXCEPTION; } return proxy->SetOption(sensorId, user, option); } \ No newline at end of file diff --git a/interfaces/native/src/sensor_algorithm.cpp b/interfaces/native/src/sensor_algorithm.cpp index 80da8de9..30fbc963 100644 --- a/interfaces/native/src/sensor_algorithm.cpp +++ b/interfaces/native/src/sensor_algorithm.cpp @@ -29,11 +29,11 @@ int32_t SensorAlgorithm::CreateQuaternion(std::vector rotationVector, std if (static_cast(rotationVector.size()) < ROTATION_VECTOR_LENGTH || static_cast(rotationVector.size()) > QUATERNION_LENGTH) { SEN_HILOGE("Invalid input rotationVector parameter"); - return OHOS::Sensors::ERROR; + return OHOS::Sensors::PARAMETER_ERROR; } if (static_cast(quaternion.size()) < QUATERNION_LENGTH) { SEN_HILOGE("Invalid input quaternion parameter"); - return OHOS::Sensors::ERROR; + return OHOS::Sensors::PARAMETER_ERROR; } if (static_cast(rotationVector.size()) == ROTATION_VECTOR_LENGTH) { quaternion[0] = 1 - static_cast((pow(rotationVector[0], 2) + pow(rotationVector[1], 2) @@ -53,11 +53,11 @@ int32_t SensorAlgorithm::TransformCoordinateSystemImpl(std::vector inRota { if ((axisX & 0x7C) != 0 || (axisX & 0x3) == 0) { SEN_HILOGE("axisX is invalid parameter"); - return OHOS::Sensors::ERROR; + return OHOS::Sensors::PARAMETER_ERROR; } if ((axisY & 0x7C) != 0 || (axisY & 0x3) == 0 || (axisX & 0x3) == (axisY & 0x3)) { SEN_HILOGE("axisY is invalid parameter"); - return OHOS::Sensors::ERROR; + return OHOS::Sensors::PARAMETER_ERROR; } int32_t axisZ = axisX ^ axisY; int32_t x = (axisX & 0x3) - 1; @@ -98,13 +98,13 @@ int32_t SensorAlgorithm::TransformCoordinateSystem(std::vector inRotation if (((inRotationMatrixLength != THREE_DIMENSIONAL_MATRIX_LENGTH) && (inRotationMatrixLength != FOUR_DIMENSIONAL_MATRIX_LENGTH)) || (inRotationMatrixLength != static_cast(outRotationMatrix.size()))) { SEN_HILOGE("Invalid input parameter"); - return OHOS::Sensors::ERROR; + return OHOS::Sensors::PARAMETER_ERROR; } if (inRotationMatrix == outRotationMatrix) { std::vector tempRotationMatrix(inRotationMatrixLength); if (TransformCoordinateSystemImpl(inRotationMatrix, axisX, axisY, tempRotationMatrix) != OHOS::Sensors::SUCCESS) { SEN_HILOGE("TransformCoordinateSystemImpl failed"); - return OHOS::Sensors::ERROR; + return OHOS::Sensors::PARAMETER_ERROR; } for (int32_t i = 0; i < inRotationMatrixLength; i++) { outRotationMatrix[i] = tempRotationMatrix[i]; @@ -118,7 +118,7 @@ int32_t SensorAlgorithm::GetAltitude(float seaPressure, float currentPressure, f { if (altitude == nullptr) { SEN_HILOGE("invalid parameter"); - return OHOS::Sensors::ERROR; + return OHOS::Sensors::PARAMETER_ERROR; } float coef = 1.0f / RECIPROCAL_COEFFICIENT; float rationOfStandardPressure = currentPressure / seaPressure; @@ -131,12 +131,12 @@ int32_t SensorAlgorithm::GetGeomagneticDip(std::vector inclinationMatrix, { if (geomagneticDip == nullptr) { SEN_HILOGE("invalid parameter"); - return OHOS::Sensors::ERROR; + return OHOS::Sensors::PARAMETER_ERROR; } int32_t matrixLength = static_cast(inclinationMatrix.size()); if (matrixLength != THREE_DIMENSIONAL_MATRIX_LENGTH && matrixLength != FOUR_DIMENSIONAL_MATRIX_LENGTH) { SEN_HILOGE("Invalid input parameter"); - return OHOS::Sensors::ERROR; + return OHOS::Sensors::PARAMETER_ERROR; } if (matrixLength == THREE_DIMENSIONAL_MATRIX_LENGTH) { *geomagneticDip = std::atan2(inclinationMatrix[5], inclinationMatrix[4]); @@ -151,19 +151,19 @@ int32_t SensorAlgorithm::GetAngleModify(std::vector curRotationMatrix, st { if (static_cast(angleChange.size()) < ROTATION_VECTOR_LENGTH) { SEN_HILOGE("invalid parameter"); - return OHOS::Sensors::ERROR; + return OHOS::Sensors::PARAMETER_ERROR; } int32_t curRotationMatrixLength = static_cast(curRotationMatrix.size()); int32_t preRotationMatrixLength = static_cast(preRotationMatrix.size()); if ((curRotationMatrixLength != FOUR_DIMENSIONAL_MATRIX_LENGTH) && (curRotationMatrixLength != THREE_DIMENSIONAL_MATRIX_LENGTH)) { SEN_HILOGE("Invalid input curRotationMatrix parameter"); - return OHOS::Sensors::ERROR; + return OHOS::Sensors::PARAMETER_ERROR; } if ((preRotationMatrixLength != FOUR_DIMENSIONAL_MATRIX_LENGTH) && (preRotationMatrixLength != THREE_DIMENSIONAL_MATRIX_LENGTH)) { SEN_HILOGE("Invalid input currotationMatrix parameter"); - return OHOS::Sensors::ERROR; + return OHOS::Sensors::PARAMETER_ERROR; } float curMatrix[THREE_DIMENSIONAL_MATRIX_LENGTH] = {0}; float preMatrix[THREE_DIMENSIONAL_MATRIX_LENGTH] = {0}; @@ -193,13 +193,13 @@ int32_t SensorAlgorithm::GetDirection(std::vector rotationMatrix, std::ve { if (static_cast(rotationAngle.size()) < ROTATION_VECTOR_LENGTH) { SEN_HILOGE("invalid parameter"); - return OHOS::Sensors::ERROR; + return OHOS::Sensors::PARAMETER_ERROR; } int32_t rotationMatrixLength = static_cast(rotationMatrix.size()); if ((rotationMatrixLength != FOUR_DIMENSIONAL_MATRIX_LENGTH) && (rotationMatrixLength != THREE_DIMENSIONAL_MATRIX_LENGTH)) { SEN_HILOGE("Invalid input rotationMatrix parameter"); - return OHOS::Sensors::ERROR; + return OHOS::Sensors::PARAMETER_ERROR; } int32_t dimension = ((rotationMatrixLength == FOUR_DIMENSIONAL_MATRIX_LENGTH) ? QUATERNION_LENGTH : ROTATION_VECTOR_LENGTH); @@ -219,13 +219,13 @@ int32_t SensorAlgorithm::CreateRotationMatrix(std::vector rotationVector, || ((rotationMatrixLength != FOUR_DIMENSIONAL_MATRIX_LENGTH) && (rotationMatrixLength != THREE_DIMENSIONAL_MATRIX_LENGTH))) { SEN_HILOGE("Invalid input rotationMatrix parameter"); - return OHOS::Sensors::ERROR; + return OHOS::Sensors::PARAMETER_ERROR; } std::vector quaternion(4); int32_t ret = CreateQuaternion(rotationVector, quaternion); if (ret != OHOS::Sensors::SUCCESS) { SEN_HILOGE("create quaternion failed"); - return OHOS::Sensors::ERROR; + return ret; } float squareOfX = 2 * static_cast(pow(quaternion[1], 2)); float squareOfY = 2 * static_cast(pow(quaternion[2], 2)); @@ -267,12 +267,12 @@ int32_t SensorAlgorithm::CreateRotationAndInclination(std::vector gravity if (static_cast(gravity.size()) < ROTATION_VECTOR_LENGTH || static_cast(geomagnetic.size()) < ROTATION_VECTOR_LENGTH) { SEN_HILOGE("Invalid input parameter"); - return OHOS::Sensors::ERROR; + return OHOS::Sensors::PARAMETER_ERROR; } float totalGravity = pow(gravity[0], 2) + pow(gravity[1], 2) + pow(gravity[2], 2); if (totalGravity < (0.01f * pow(GRAVITATIONAL_ACCELERATION, 2))) { SEN_HILOGE("Invalid input gravity parameter"); - return OHOS::Sensors::ERROR; + return OHOS::Sensors::PARAMETER_ERROR; } std::vector componentH(3); componentH[0] = geomagnetic[1] * gravity[2] - geomagnetic[2] * gravity[1]; @@ -282,7 +282,7 @@ int32_t SensorAlgorithm::CreateRotationAndInclination(std::vector gravity + pow(componentH[2], 2))); if (totalH < 0.1f) { SEN_HILOGE("The total strength of H is less than 0.1"); - return OHOS::Sensors::ERROR; + return OHOS::Sensors::PARAMETER_ERROR; } float reciprocalH = 1.0f / totalH; componentH[0] *= reciprocalH; @@ -302,7 +302,7 @@ int32_t SensorAlgorithm::CreateRotationAndInclination(std::vector gravity if ((rotationMatrixLength != 9 && rotationMatrixLength != 16) || (inclinationMatrixLength != 9 && inclinationMatrixLength != 16)) { SEN_HILOGE("Invalid input parameter"); - return OHOS::Sensors::ERROR; + return OHOS::Sensors::PARAMETER_ERROR; } float reciprocalE = 1.0f / static_cast(std::sqrt(pow(geomagnetic[0], 2) + pow(geomagnetic[1], 2) + pow(geomagnetic[2], 2))); diff --git a/interfaces/plugin/BUILD.gn b/interfaces/plugin/BUILD.gn index e4d75127..5b3f3909 100644 --- a/interfaces/plugin/BUILD.gn +++ b/interfaces/plugin/BUILD.gn @@ -13,7 +13,7 @@ #import("//build/config/ohos/rules.gni") import("//build/ohos.gni") -ohos_shared_library("sensor") { +ohos_shared_library("libsensor") { include_dirs = [ "//third_party/node/src", "//native_engine", @@ -30,6 +30,7 @@ ohos_shared_library("sensor") { ] sources = [ "./src/sensor_js.cpp", + "./src/sensor_napi_error.cpp", "./src/sensor_napi_utils.cpp", "./src/sensor_system_js.cpp", ] @@ -45,5 +46,5 @@ ohos_shared_library("sensor") { } group("sensor_js_target") { - deps = [ ":sensor" ] + deps = [ ":libsensor" ] } diff --git a/interfaces/plugin/include/async_callback_info.h b/interfaces/plugin/include/async_callback_info.h index 4f303e83..2d515f21 100644 --- a/interfaces/plugin/include/async_callback_info.h +++ b/interfaces/plugin/include/async_callback_info.h @@ -19,6 +19,7 @@ #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" @@ -89,7 +90,7 @@ union CallbackData { }; struct BusinessError { - int32_t code; + int32_t code { 0 }; string message; string name; string stack; diff --git a/interfaces/plugin/include/sensor_js.h b/interfaces/plugin/include/sensor_js.h index 3f4e8c34..bf75795c 100644 --- a/interfaces/plugin/include/sensor_js.h +++ b/interfaces/plugin/include/sensor_js.h @@ -14,15 +14,18 @@ */ #ifndef SENSOR_JS_H #define SENSOR_JS_H -#include "async_callback_info.h" + #include "napi/native_api.h" #include "napi/native_node_api.h" + +#include "async_callback_info.h" #include "sensor_agent.h" + namespace OHOS { namespace Sensors { -bool UnsubscribeSensor(int32_t sensorTypeId); +int32_t UnsubscribeSensor(int32_t sensorTypeId); void DataCallbackImpl(SensorEvent *event); -bool SubscribeSensor(int32_t sensorTypeId, int64_t interval, RecordSensorCallback callback); +int32_t SubscribeSensor(int32_t sensorTypeId, int64_t interval, RecordSensorCallback callback); napi_value Subscribe(napi_env env, napi_callback_info info, int32_t sensorTypeId, CallbackDataType type); napi_value Unsubscribe(napi_env env, napi_callback_info info, int32_t sensorTypeId); napi_value GetBodyState(napi_env env, napi_callback_info info); diff --git a/interfaces/plugin/include/sensor_napi_error.h b/interfaces/plugin/include/sensor_napi_error.h new file mode 100755 index 00000000..d5654088 --- /dev/null +++ b/interfaces/plugin/include/sensor_napi_error.h @@ -0,0 +1,37 @@ +/* + * 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 SENSOR_NAPI_ERROR_H +#define SENSOR_NAPI_ERROR_H + +#include + +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +#include "sensors_errors.h" + +namespace OHOS { +namespace Sensors { +const std::map ERROR_MESSAGES = { + {SERVICE_EXCEPTION, "Service exception."}, + {PERMISSION_DENIED, "Permission denied."}, + {PARAMETER_ERROR, "The parameter invalid."}, +}; + +napi_value CreateBusinessError(const napi_env &env, const int32_t errCode, const std::string &errMessage); +void ThrowErr(const napi_env &env, const int32_t errCode, const std::string &printMsg); +} // namespace Sensors +} // namespace OHOS +#endif // SENSOR_NAPI_ERROR_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 620bde48..6adfdb42 100644 --- a/interfaces/plugin/include/sensor_napi_utils.h +++ b/interfaces/plugin/include/sensor_napi_utils.h @@ -17,8 +17,10 @@ #include -#include "async_callback_info.h" #include "refbase.h" + +#include "async_callback_info.h" + namespace OHOS { namespace Sensors { using std::vector; @@ -29,21 +31,18 @@ using ConvertDataFunc = bool(*)(const napi_env &env, sptr asy 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 GetNativeInt32(const napi_env &env, const napi_value &value, int32_t &number); +bool GetNativeDouble(const napi_env &env, const napi_value &value, double &number); 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); +bool GetNativeInt64(const napi_env &env, const napi_value &value, int64_t &number); bool RegisterNapiCallback(const napi_env &env, const napi_value &value, napi_ref &callback); 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); +bool GetNativeFloat(const napi_env &env, const napi_value &value, float &number); napi_value GetNapiInt32(const napi_env &env, int32_t number); bool GetStringValue(const napi_env &env, const napi_value &value, string &result); 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 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]); @@ -59,85 +58,18 @@ bool CreateFailMessage(CallbackDataType type, int32_t code, string message, bool ConvertToBodyData(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]); bool ConvertToCompass(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) @@ -146,28 +78,17 @@ bool ConvertToCompass(const napi_env &env, sptr asyncCallback 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) \ +#define CHKNRF(env, state, message) \ do { \ if ((state) != napi_ok) { \ SEN_HILOGE("(%{public}s) fail", #message); \ - GET_AND_THROW_NAPI_ERROR((env), (message)); \ - return; \ + return false; \ } \ } 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/src/sensor_js.cpp b/interfaces/plugin/src/sensor_js.cpp index 7aea5a26..44b5b19a 100644 --- a/interfaces/plugin/src/sensor_js.cpp +++ b/interfaces/plugin/src/sensor_js.cpp @@ -16,19 +16,20 @@ #include #include -#include #include #include -#include #include #include -#include "geomagnetic_field.h" #include "refbase.h" #include "securec.h" + +#include "geomagnetic_field.h" #include "sensor_algorithm.h" +#include "sensor_napi_error.h" #include "sensor_napi_utils.h" #include "sensor_system_js.h" + namespace OHOS { namespace Sensors { namespace { @@ -163,21 +164,31 @@ const SensorUser user = { .callback = DataCallbackImpl }; -bool UnsubscribeSensor(int32_t sensorTypeId) +int32_t UnsubscribeSensor(int32_t sensorTypeId) { CALL_LOG_ENTER; - CHKCF((DeactivateSensor(sensorTypeId, &user) == SUCCESS), "DeactivateSensor failed"); - CHKCF((UnsubscribeSensor(sensorTypeId, &user) == SUCCESS), "UnsubscribeSensor failed"); - return true; + int32_t ret = DeactivateSensor(sensorTypeId, &user); + if (ret != ERR_OK) { + SEN_HILOGE("DeactivateSensor failed"); + return ret; + } + return UnsubscribeSensor(sensorTypeId, &user); } -bool SubscribeSensor(int32_t sensorTypeId, int64_t interval, RecordSensorCallback callback) +int32_t SubscribeSensor(int32_t sensorTypeId, int64_t interval, RecordSensorCallback callback) { 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; + int32_t ret = SubscribeSensor(sensorTypeId, &user); + if (ret != ERR_OK) { + SEN_HILOGE("SubscribeSensor failed"); + return ret; + } + ret = SetBatch(sensorTypeId, &user, interval, 0); + if (ret != ERR_OK) { + SEN_HILOGE("SetBatch failed"); + return ret; + } + return ActivateSensor(sensorTypeId, &user); } static bool IsOnceSubscribed(napi_env env, int32_t sensorTypeId, napi_value callback) @@ -189,7 +200,7 @@ static bool IsOnceSubscribed(napi_env env, int32_t sensorTypeId, napi_value call } std::vector> callbackInfos = g_onceCallbackInfos[sensorTypeId]; for (auto callbackInfo : callbackInfos) { - CHKNCC(env, (callbackInfo != nullptr), "callbackInfo is null"); + CHKPC(callbackInfo); if (callbackInfo->env != env) { continue; } @@ -207,11 +218,14 @@ static void UpdateOnceCallback(napi_env env, int32_t sensorTypeId, napi_value ca { CALL_LOG_ENTER; std::lock_guard onceCallbackLock(onceMutex_); - CHKNCV(env, !IsOnceSubscribed(env, sensorTypeId, callback), "The callback has been subscribed"); + CHKCV((!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"); + napi_status status = napi_create_reference(env, callback, 1, &asyncCallbackInfo->callback[0]); + if (status != napi_ok) { + ThrowErr(env, PARAMETER_ERROR, "napi_create_reference fail"); + return; + } std::vector> callbackInfos = g_onceCallbackInfos[sensorTypeId]; callbackInfos.push_back(asyncCallbackInfo); g_onceCallbackInfos[sensorTypeId] = callbackInfos; @@ -223,15 +237,27 @@ static napi_value Once(napi_env env, napi_callback_info info) size_t argc = 2; napi_value args[2] = { 0 }; napi_value thisVar = nullptr; - 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"); + napi_status status = napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr); + if (status != napi_ok || argc < 2) { + ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail or number of parameter invalid"); + return nullptr; + } + if ((!IsMatchType(env, args[0], napi_number)) || (!IsMatchType(env, args[1], napi_function))) { + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type"); + return nullptr; + } int32_t sensorTypeId = INVALID_SENSOR_ID; - CHKNCP(env, GetCppInt32(env, args[0], sensorTypeId), "Wrong argument type, get number fail"); + if (!GetNativeInt32(env, args[0], sensorTypeId)) { + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, get number fail"); + return nullptr; + } if (!CheckSubscribe(sensorTypeId)) { SEN_HILOGD("No subscription to change sensor data, registration is required"); - CHKNCP(env, SubscribeSensor(sensorTypeId, REPORTING_INTERVAL, DataCallbackImpl), "SubscribeSensor failed"); + int32_t ret = SubscribeSensor(sensorTypeId, REPORTING_INTERVAL, DataCallbackImpl); + if (ret != ERR_OK) { + ThrowErr(env, ret, "SubscribeSensor fail"); + return nullptr; + } } UpdateOnceCallback(env, sensorTypeId, args[1]); return nullptr; @@ -246,7 +272,7 @@ static bool IsSubscribed(napi_env env, int32_t sensorTypeId, napi_value callback } std::vector> callbackInfos = g_onCallbackInfos[sensorTypeId]; for (auto callbackInfo : callbackInfos) { - CHKNCC(env, (callbackInfo != nullptr), "callbackInfo is null"); + CHKPC(callbackInfo); if (callbackInfo->env != env) { continue; } @@ -264,11 +290,14 @@ static void UpdateCallbackInfos(napi_env env, int32_t sensorTypeId, napi_value c { CALL_LOG_ENTER; std::lock_guard onCallbackLock(onMutex_); - CHKNCV(env, !IsSubscribed(env, sensorTypeId, callback), "This callback has been subscribed"); + CHKCV((!IsSubscribed(env, sensorTypeId, callback)), "The 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"); + napi_status status = napi_create_reference(env, callback, 1, &asyncCallbackInfo->callback[0]); + if (status != napi_ok) { + ThrowErr(env, PARAMETER_ERROR, "napi_create_reference fail"); + return; + } std::vector> callbackInfos = g_onCallbackInfos[sensorTypeId]; callbackInfos.push_back(asyncCallbackInfo); g_onCallbackInfos[sensorTypeId] = callbackInfos; @@ -280,20 +309,42 @@ static napi_value On(napi_env env, napi_callback_info info) 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 == 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"); + napi_status status = napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr); + if (status != napi_ok || argc < 2) { + ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail or number of parameter invalid"); + return nullptr; + } + if ((!IsMatchType(env, args[0], napi_number)) || (!IsMatchType(env, args[1], napi_function))) { + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type"); + return nullptr; + } int32_t sensorTypeId = INVALID_SENSOR_ID; - CHKNCP(env, GetCppInt32(env, args[0], sensorTypeId), "Wrong argument type, get number fail"); + if (!GetNativeInt32(env, args[0], sensorTypeId)) { + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, get number fail"); + return nullptr; + } int64_t interval = REPORTING_INTERVAL; - if (argc == 3) { + if (argc >= 3) { + if (!IsMatchType(env, args[2], napi_object)) { + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, should be object"); + 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"); + if ((value == nullptr) || (!IsMatchType(env, value, napi_number))) { + ThrowErr(env, PARAMETER_ERROR, "Get interval fail or wrong argument type"); + return nullptr; + } + if (!GetNativeInt64(env, value, interval)) { + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, get number fail"); + return nullptr; + } SEN_HILOGD("Interval is %{public}" PRId64, interval); } - CHKNCP(env, SubscribeSensor(sensorTypeId, interval, DataCallbackImpl), "SubscribeSensor failed"); + int32_t ret = SubscribeSensor(sensorTypeId, interval, DataCallbackImpl); + if (ret != ERR_OK) { + ThrowErr(env, ret, "SubscribeSensor fail"); + return nullptr; + } UpdateCallbackInfos(env, sensorTypeId, args[1]); return nullptr; } @@ -306,7 +357,7 @@ static void RemoveAllCallback(napi_env env, int32_t sensorTypeId) g_onCallbackInfos.erase(sensorTypeId); } -static uint32_t RemoveCallback(napi_env env, int32_t sensorTypeId, napi_value callback) +static int32_t RemoveCallback(napi_env env, int32_t sensorTypeId, napi_value callback) { CALL_LOG_ENTER; std::lock_guard onCallbackLock(onMutex_); @@ -314,8 +365,10 @@ static uint32_t RemoveCallback(napi_env env, int32_t sensorTypeId, napi_value ca for (auto iter = callbackInfos.begin(); iter != callbackInfos.end(); ++iter) { CHKPC(*iter); napi_value sensorCallback = nullptr; - CHKNRC(env, napi_get_reference_value(env, (*iter)->callback[0], &sensorCallback), - "napi_get_reference_value"); + if (napi_get_reference_value(env, (*iter)->callback[0], &sensorCallback) != napi_ok) { + SEN_HILOGE("napi_get_reference_value fail"); + continue; + } if (IsSameValue(env, callback, sensorCallback)) { callbackInfos.erase(iter++); SEN_HILOGD("Remove callback success"); @@ -337,24 +390,34 @@ static napi_value Off(napi_env env, napi_callback_info info) size_t argc = 2; napi_value args[2] = { 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 == 2)), "The number of parameters is not valid"); - CHKNCP(env, IsMatchType(env, args[0], napi_number), "Wrong argument type, should be number"); + napi_status status = napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr); + if (status != napi_ok || argc == 0) { + ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail or number of parameter invalid"); + return nullptr; + } 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 ((!IsMatchType(env, args[0], napi_number)) || (!GetNativeInt32(env, args[0], sensorTypeId))) { + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type or get number fail"); + return nullptr; + } 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), + if (!IsMatchType(env, args[1], napi_function)) { + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, should be function"); + return nullptr; + } + CHKCP((RemoveCallback(env, sensorTypeId, args[1]) == 0), "There are other client subscribe as well, not need unsubscribe"); } if (CheckSystemSubscribe(sensorTypeId)) { SEN_HILOGW("There are other client subscribe system js api as well, not need unsubscribe"); return nullptr; } - CHKNCP(env, UnsubscribeSensor(sensorTypeId), "UnsubscribeSensor failed"); + int32_t ret = UnsubscribeSensor(sensorTypeId); + if (ret == PARAMETER_ERROR || ret == PERMISSION_DENIED) { + ThrowErr(env, ret, "UnsubscribeSensor fail"); + } return nullptr; } @@ -364,24 +427,49 @@ static napi_value GetGeomagneticField(napi_env env, napi_callback_info info) 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 == 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"); + if ((napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr) != napi_ok) || (argc < 2)) { + ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail or number of parameter invalid"); + return nullptr; + } + if ((!IsMatchType(env, args[0], napi_object)) || (!IsMatchType(env, args[1], napi_number))) { + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type"); + return nullptr; + } napi_value napiLatitude = GetNamedProperty(env, args[0], "latitude"); - CHKNCP(env, (napiLatitude != nullptr), "napiLatitude is null"); + if (napiLatitude == nullptr) { + ThrowErr(env, PARAMETER_ERROR, "napiLatitude is null"); + return nullptr; + } double latitude = 0; - CHKNCP(env, GetCppDouble(env, napiLatitude, latitude), "Get latitude fail"); + if (!GetNativeDouble(env, napiLatitude, latitude)) { + ThrowErr(env, PARAMETER_ERROR, "Get latitude fail"); + return nullptr; + } napi_value napiLongitude = GetNamedProperty(env, args[0], "longitude"); - CHKNCP(env, (napiLongitude != nullptr), "napiLongitude is null"); + if (napiLongitude == nullptr) { + ThrowErr(env, PARAMETER_ERROR, "napiLongitude is null"); + return nullptr; + } double longitude = 0; - CHKNCP(env, GetCppDouble(env, napiLongitude, longitude), "Get longitude fail"); + if (!GetNativeDouble(env, napiLongitude, longitude)) { + ThrowErr(env, PARAMETER_ERROR, "Get longitude fail"); + return nullptr; + } napi_value napiAltitude = GetNamedProperty(env, args[0], "altitude"); - CHKNCP(env, (napiAltitude != nullptr), "napiAltitude is null"); + if (napiAltitude == nullptr) { + ThrowErr(env, PARAMETER_ERROR, "napiAltitude is null"); + return nullptr; + } double altitude = 0; - CHKNCP(env, GetCppDouble(env, napiAltitude, altitude), "Get altitude fail"); + if (!GetNativeDouble(env, napiAltitude, altitude)) { + ThrowErr(env, PARAMETER_ERROR, "Get altitude fail"); + return nullptr; + } int64_t timeMillis = 0; - CHKNCP(env, GetCppInt64(env, args[1], timeMillis), "Get timeMillis fail"); + if (!GetNativeInt64(env, args[1], timeMillis)) { + ThrowErr(env, PARAMETER_ERROR, "Get timeMillis fail"); + return nullptr; + } GeomagneticField geomagneticField(latitude, longitude, altitude, timeMillis); sptr asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo(env, GET_GEOMAGNETIC_FIELD); @@ -397,14 +485,18 @@ static napi_value GetGeomagneticField(napi_env env, napi_callback_info info) }; if (argc == 2) { napi_value promise = nullptr; - CHKNRP(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise), - "napi_create_promise"); + if ((napi_create_promise(env, &asyncCallbackInfo->deferred, &promise)) != napi_ok) { + ThrowErr(env, PARAMETER_ERROR, "napi_create_promise fail"); + return nullptr; + } EmitPromiseWork(asyncCallbackInfo); return promise; } - 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"); + if (!IsMatchType(env, args[2], napi_function) || + (napi_create_reference(env, args[2], 1, &asyncCallbackInfo->callback[0]) != napi_ok)) { + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type or napi_create_reference fail "); + return nullptr; + } EmitAsyncCallbackWork(asyncCallbackInfo); return nullptr; } @@ -415,23 +507,45 @@ static napi_value TransformCoordinateSystem(napi_env env, napi_callback_info inf 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 == 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"); + napi_status status = napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr); + if ((status != napi_ok) || (argc < 2)) { + ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail or number of parameter invalid"); + return nullptr; + } + if ((!IsMatchArrayType(env, args[0])) || (!IsMatchType(env, args[1], napi_object))) { + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type"); + return nullptr; + } std::vector inRotationVector; - CHKNCP(env, GetFloatArray(env, args[0], inRotationVector), "Wrong argument type, get inRotationVector fail"); + if (!GetFloatArray(env, args[0], inRotationVector)) { + ThrowErr(env, PARAMETER_ERROR, "Get inRotationVector fail"); + return nullptr; + } size_t length = inRotationVector.size(); - CHKNCP(env, ((length == DATA_LENGTH) || (length == THREE_DIMENSIONAL_MATRIX_LENGTH)), - "Wrong inRotationVector length"); + if ((length != DATA_LENGTH) && (length != THREE_DIMENSIONAL_MATRIX_LENGTH)) { + ThrowErr(env, PARAMETER_ERROR, "Wrong inRotationVector length"); + return nullptr; + } napi_value napiAxisX = GetNamedProperty(env, args[1], "axisX"); - CHKNCP(env, (napiAxisX != nullptr), "napiAxisX is null"); + if (napiAxisX == nullptr) { + ThrowErr(env, PARAMETER_ERROR, "napiAxisX is null"); + return nullptr; + } int32_t axisX = 0; - CHKNCP(env, GetCppInt32(env, napiAxisX, axisX), "Get axisY fail"); + if (!GetNativeInt32(env, napiAxisX, axisX)) { + ThrowErr(env, PARAMETER_ERROR, "Get axisY fail"); + return nullptr; + } napi_value napiAxisY = GetNamedProperty(env, args[1], "axisY"); - CHKNCP(env, (napiAxisY != nullptr), "napiAxisY is null"); + if (napiAxisY == nullptr) { + ThrowErr(env, PARAMETER_ERROR, "napiAxisX is null"); + return nullptr; + } int32_t axisY = 0; - CHKNCP(env, GetCppInt32(env, napiAxisY, axisY), "Get axisY fail"); + if (!GetNativeInt32(env, napiAxisY, axisY)) { + ThrowErr(env, PARAMETER_ERROR, "Get axisY fail"); + return nullptr; + } sptr asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo(env, TRANSFORM_COORDINATE_SYSTEM); CHKPP(asyncCallbackInfo); @@ -450,13 +564,23 @@ static napi_value TransformCoordinateSystem(napi_env env, napi_callback_info inf } if (argc == 2) { napi_value promise = nullptr; - CHKNRP(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise), "napi_create_promise"); + status = napi_create_promise(env, &asyncCallbackInfo->deferred, &promise); + if (status != napi_ok) { + ThrowErr(env, PARAMETER_ERROR, "napi_create_promise fail"); + return nullptr; + } EmitPromiseWork(asyncCallbackInfo); return promise; } - 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"); + if (!IsMatchType(env, args[2], napi_function)) { + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, should be function"); + return nullptr; + } + status = napi_create_reference(env, args[2], 1, &asyncCallbackInfo->callback[0]); + if (status != napi_ok) { + ThrowErr(env, PARAMETER_ERROR, "napi_create_reference fail"); + return nullptr; + } EmitAsyncCallbackWork(asyncCallbackInfo); return nullptr; } @@ -467,18 +591,32 @@ static napi_value GetAngleModify(napi_env env, napi_callback_info info) 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 == 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"); + napi_status status = napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr); + if (status != napi_ok || argc < 2) { + ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail or number of parameter invalid"); + return nullptr; + } + if (!IsMatchArrayType(env, args[0])) { + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, should be array"); + return nullptr; + } + if (!IsMatchArrayType(env, args[1])) { + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, should be array"); + return nullptr; + } 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"); + if (!GetFloatArray(env, args[0], curRotationVector)) { + ThrowErr(env, PARAMETER_ERROR, "Get curRotationVector fail"); + return nullptr; + } std::vector preRotationVector; - CHKNCP(env, GetFloatArray(env, args[1], preRotationVector), "Wrong argument type, get preRotationVector fail"); - + if (!GetFloatArray(env, args[1], preRotationVector)) { + ThrowErr(env, PARAMETER_ERROR, "Get preRotationVector fail"); + return nullptr; + } std::vector angleChange(ROTATION_VECTOR_LENGTH); SensorAlgorithm sensorAlgorithm; int32_t ret = sensorAlgorithm.GetAngleModify(curRotationVector, preRotationVector, angleChange); @@ -494,14 +632,23 @@ static napi_value GetAngleModify(napi_env env, napi_callback_info info) } if (argc == 2) { napi_value promise = nullptr; - CHKNRP(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise), - "napi_create_promise"); + status = napi_create_promise(env, &asyncCallbackInfo->deferred, &promise); + if (status != napi_ok) { + ThrowErr(env, PARAMETER_ERROR, "napi_create_promise fail"); + return nullptr; + } EmitPromiseWork(asyncCallbackInfo); return promise; } - 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"); + if (!IsMatchType(env, args[2], napi_function)) { + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, should be function"); + return nullptr; + } + status = napi_create_reference(env, args[2], 1, &asyncCallbackInfo->callback[0]); + if (status != napi_ok) { + ThrowErr(env, PARAMETER_ERROR, "napi_create_reference fail"); + return nullptr; + } EmitAsyncCallbackWork(asyncCallbackInfo); return nullptr; } @@ -512,15 +659,23 @@ static napi_value GetDirection(napi_env env, napi_callback_info info) 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 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"); - + napi_status status = napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr); + if (status != napi_ok || argc == 0) { + ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail or number of parameter invalid"); + return nullptr; + } + if (!IsMatchArrayType(env, args[0])) { + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, should be array"); + return nullptr; + } 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"); + if (!GetFloatArray(env, args[0], rotationMatrix)) { + ThrowErr(env, PARAMETER_ERROR, "Get rotationMatrix fail"); + return nullptr; + } std::vector rotationAngle(ROTATION_VECTOR_LENGTH); SensorAlgorithm sensorAlgorithm; int32_t ret = sensorAlgorithm.GetDirection(rotationMatrix, rotationAngle); @@ -536,14 +691,23 @@ static napi_value GetDirection(napi_env env, napi_callback_info info) } if (argc == 1) { napi_value promise = nullptr; - CHKNRP(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise), - "napi_create_promise"); + status = napi_create_promise(env, &asyncCallbackInfo->deferred, &promise); + if (status != napi_ok) { + ThrowErr(env, PARAMETER_ERROR, "napi_create_promise fail"); + return nullptr; + } 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"); + if (!IsMatchType(env, args[1], napi_function)) { + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, should be function"); + return nullptr; + } + status = napi_create_reference(env, args[1], 1, &asyncCallbackInfo->callback[0]); + if (status != napi_ok) { + ThrowErr(env, PARAMETER_ERROR, "napi_create_reference fail"); + return nullptr; + } EmitAsyncCallbackWork(asyncCallbackInfo); return nullptr; } @@ -554,15 +718,23 @@ static napi_value CreateQuaternion(napi_env env, napi_callback_info info) size_t argc = 2; napi_value args[2] = { 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 == 2)), "The number of parameters is not valid"); - CHKNCP(env, IsMatchArrayType(env, args[0]), "Wrong argument type, should be array"); + napi_status status = napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr); + if (status != napi_ok || argc == 0) { + ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail or number of parameter invalid"); + return nullptr; + } + if (!IsMatchArrayType(env, args[0])) { + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, should be array"); + return nullptr; + } 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"); + if (!GetFloatArray(env, args[0], rotationVector)) { + ThrowErr(env, PARAMETER_ERROR, "Get rotationVector fail"); + return nullptr; + } std::vector quaternion(QUATERNION_LENGTH); SensorAlgorithm sensorAlgorithm; int32_t ret = sensorAlgorithm.CreateQuaternion(rotationVector, quaternion); @@ -578,14 +750,23 @@ static napi_value CreateQuaternion(napi_env env, napi_callback_info info) } if (argc == 1) { napi_value promise = nullptr; - CHKNRP(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise), - "napi_create_promise"); + status = napi_create_promise(env, &asyncCallbackInfo->deferred, &promise); + if (status != napi_ok) { + ThrowErr(env, PARAMETER_ERROR, "napi_create_promise fail"); + return nullptr; + } 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"); + if (!IsMatchType(env, args[1], napi_function)) { + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, should be function"); + return nullptr; + } + status = napi_create_reference(env, args[1], 1, &asyncCallbackInfo->callback[0]); + if (status != napi_ok) { + ThrowErr(env, PARAMETER_ERROR, "napi_create_reference fail"); + return nullptr; + } EmitAsyncCallbackWork(asyncCallbackInfo); return nullptr; } @@ -596,17 +777,28 @@ static napi_value GetAltitude(napi_env env, napi_callback_info info) 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 == 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"); + napi_status status = napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr); + if (status != napi_ok || argc < 2) { + ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail or number of parameter invalid"); + return nullptr; + } + if ((!IsMatchType(env, args[0], napi_number)) || (!IsMatchType(env, args[1], napi_number))) { + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type"); + return nullptr; + } 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"); + if (!GetNativeFloat(env, args[0], seaPressure)) { + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, get seaPressure fail"); + return nullptr; + } float currentPressure = 0; - CHKNCP(env, GetCppFloat(env, args[1], currentPressure), "Wrong argument type, get currentPressure fail"); + if (!GetNativeFloat(env, args[1], currentPressure)) { + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, get currentPressure fail"); + return nullptr; + } float altitude = 0; SensorAlgorithm sensorAlgorithm; int32_t ret = sensorAlgorithm.GetAltitude(seaPressure, currentPressure, &altitude); @@ -619,14 +811,23 @@ static napi_value GetAltitude(napi_env env, napi_callback_info info) } if (argc == 2) { napi_value promise = nullptr; - CHKNRP(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise), - "napi_create_promise"); + status = napi_create_promise(env, &asyncCallbackInfo->deferred, &promise); + if (status != napi_ok) { + ThrowErr(env, PARAMETER_ERROR, "napi_create_promise fail"); + return nullptr; + } EmitPromiseWork(asyncCallbackInfo); return promise; } - 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"); + if (!IsMatchType(env, args[2], napi_function)) { + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, should be function"); + return nullptr; + } + status = napi_create_reference(env, args[2], 1, &asyncCallbackInfo->callback[0]); + if (status != napi_ok) { + ThrowErr(env, PARAMETER_ERROR, "napi_create_reference fail"); + return nullptr; + } EmitAsyncCallbackWork(asyncCallbackInfo); return nullptr; } @@ -637,15 +838,23 @@ static napi_value GetGeomagneticDip(napi_env env, napi_callback_info info) size_t argc = 2; napi_value args[2] = { 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 == 2)), "The number of parameters is not valid"); - CHKNCP(env, IsMatchArrayType(env, args[0]), "Wrong argument type, should be array"); + napi_status status = napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr); + if (status != napi_ok || argc == 0) { + ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail or number of parameter invalid"); + return nullptr; + } + if (!IsMatchArrayType(env, args[0])) { + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, should be array"); + return nullptr; + } 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"); + if (!GetFloatArray(env, args[0], inclinationMatrix)) { + ThrowErr(env, PARAMETER_ERROR, "Get inclinationMatrix fail"); + return nullptr; + } float geomagneticDip = 0; SensorAlgorithm sensorAlgorithm; int32_t ret = sensorAlgorithm.GetGeomagneticDip(inclinationMatrix, &geomagneticDip); @@ -658,14 +867,23 @@ static napi_value GetGeomagneticDip(napi_env env, napi_callback_info info) } if (argc == 1) { napi_value promise = nullptr; - CHKNRP(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise), - "napi_create_promise"); + status = napi_create_promise(env, &asyncCallbackInfo->deferred, &promise); + if (status != napi_ok) { + ThrowErr(env, PARAMETER_ERROR, "napi_create_promise fail"); + return nullptr; + } 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"); + if (!IsMatchType(env, args[1], napi_function)) { + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, should be function"); + return nullptr; + } + status = napi_create_reference(env, args[1], 1, &asyncCallbackInfo->callback[0]); + if (status != napi_ok) { + ThrowErr(env, PARAMETER_ERROR, "napi_create_reference fail"); + return nullptr; + } EmitAsyncCallbackWork(asyncCallbackInfo); return nullptr; } @@ -673,11 +891,20 @@ static napi_value GetGeomagneticDip(napi_env env, napi_callback_info info) static napi_value CreateRotationAndInclination(const napi_env &env, napi_value args[], size_t argc) { CALL_LOG_ENTER; - CHKNCP(env, ((argc == 2) || (argc == 3)), "The number of parameters is not valid"); + if (argc < 2) { + ThrowErr(env, PARAMETER_ERROR, "The number of parameters is not valid"); + return nullptr; + } std::vector gravity; - CHKNCP(env, GetFloatArray(env, args[0], gravity), "Wrong argument type, get gravity fail"); + if (!GetFloatArray(env, args[0], gravity)) { + ThrowErr(env, PARAMETER_ERROR, "Get gravity fail"); + return nullptr; + } std::vector geomagnetic; - CHKNCP(env, GetFloatArray(env, args[1], geomagnetic), "Wrong argument type, get geomagnetic fail"); + if (!GetFloatArray(env, args[1], geomagnetic)) { + ThrowErr(env, PARAMETER_ERROR, "Get geomagnetic fail"); + return nullptr; + } std::vector rotation(THREE_DIMENSIONAL_MATRIX_LENGTH); std::vector inclination(THREE_DIMENSIONAL_MATRIX_LENGTH); sptr asyncCallbackInfo = @@ -698,16 +925,26 @@ static napi_value CreateRotationAndInclination(const napi_env &env, napi_value a asyncCallbackInfo->data.rationMatrixData.inclinationMatrix[i] = inclination[i]; } } + napi_status status; if (argc == 2) { napi_value promise = nullptr; - CHKNRP(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise), - "napi_create_promise"); + status = napi_create_promise(env, &asyncCallbackInfo->deferred, &promise); + if (status != napi_ok) { + ThrowErr(env, PARAMETER_ERROR, "napi_create_promise fail"); + return nullptr; + } EmitPromiseWork(asyncCallbackInfo); return promise; } - 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"); + if (!IsMatchType(env, args[2], napi_function)) { + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, should be function"); + return nullptr; + } + status = napi_create_reference(env, args[2], 1, &asyncCallbackInfo->callback[0]); + if (status != napi_ok) { + ThrowErr(env, PARAMETER_ERROR, "napi_create_reference fail"); + return nullptr; + } EmitAsyncCallbackWork(asyncCallbackInfo); return nullptr; } @@ -715,10 +952,15 @@ static napi_value CreateRotationAndInclination(const napi_env &env, napi_value a 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"); + if (argc < 1) { + ThrowErr(env, PARAMETER_ERROR, "The number of parameters is not valid"); + return nullptr; + } std::vector rotationVector; - CHKNCP(env, GetFloatArray(env, args[0], rotationVector), - "Wrong argument type, get rotationVector fail"); + if (!GetFloatArray(env, args[0], rotationVector)) { + ThrowErr(env, PARAMETER_ERROR, "Get rotationVector fail"); + return nullptr; + } sptr asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo(env, CREATE_ROTATION_MATRIX); CHKPP(asyncCallbackInfo); @@ -735,16 +977,26 @@ static napi_value GetRotationMatrix(const napi_env &env, napi_value args[], size asyncCallbackInfo->data.reserveData.reserve[i] = rotationMatrix[i]; } } + napi_status status; if (argc == 1) { napi_value promise = nullptr; - CHKNRP(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise), - "napi_create_promise"); + status = napi_create_promise(env, &asyncCallbackInfo->deferred, &promise); + if (status != napi_ok) { + ThrowErr(env, PARAMETER_ERROR, "napi_create_promise fail"); + return nullptr; + } 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"); + if (!IsMatchType(env, args[1], napi_function)) { + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, should be function"); + return nullptr; + } + status = napi_create_reference(env, args[1], 1, &asyncCallbackInfo->callback[0]); + if (status != napi_ok) { + ThrowErr(env, PARAMETER_ERROR, "napi_create_reference fail"); + return nullptr; + } EmitAsyncCallbackWork(asyncCallbackInfo); return nullptr; } @@ -755,13 +1007,22 @@ static napi_value CreateRotationMatrix(napi_env env, napi_callback_info info) 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"); + napi_status status = napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr); + if (status != napi_ok || argc == 0) { + ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail or number of parameter invalid"); + return nullptr; + } + if (!IsMatchArrayType(env, args[0])) { + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, should be array"); + return nullptr; + } 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); + } else { + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, should be array"); + return nullptr; } return nullptr; } @@ -772,8 +1033,11 @@ static napi_value GetSensorList(napi_env env, napi_callback_info info) size_t argc = 1; napi_value args[1] = { 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), "The number of parameters is not valid"); + napi_status status = napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr); + if (status != napi_ok) { + ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail"); + return nullptr; + } sptr asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo(env, GET_SENSOR_LIST); CHKPP(asyncCallbackInfo); @@ -791,13 +1055,23 @@ static napi_value GetSensorList(napi_env env, napi_callback_info info) } if (argc == 0) { napi_value promise = nullptr; - CHKNRP(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise), - "napi_create_promise"); + status = napi_create_promise(env, &asyncCallbackInfo->deferred, &promise); + if (status != napi_ok) { + ThrowErr(env, PARAMETER_ERROR, "napi_create_promise fail"); + return nullptr; + } EmitPromiseWork(asyncCallbackInfo); return promise; } - CHKNCP(env, IsMatchType(env, args[0], napi_function), "Wrong argument type, should be function"); - napi_create_reference(env, args[0], 1, &asyncCallbackInfo->callback[0]); + if (!IsMatchType(env, args[0], napi_function)) { + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, should be function"); + return nullptr; + } + status = napi_create_reference(env, args[0], 1, &asyncCallbackInfo->callback[0]); + if (status != napi_ok) { + ThrowErr(env, PARAMETER_ERROR, "napi_create_reference fail"); + return nullptr; + } EmitAsyncCallbackWork(asyncCallbackInfo); return nullptr; } @@ -808,10 +1082,16 @@ static napi_value GetSingleSensor(napi_env env, napi_callback_info info) size_t argc = 2; napi_value args[2] = { 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 == 2)), "The number of parameters is not valid"); + napi_status status = napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr); + if (status != napi_ok) { + ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail"); + return nullptr; + } int32_t sensorTypeId = INVALID_SENSOR_ID; - CHKNCP(env, GetCppInt32(env, args[0], sensorTypeId), "Wrong argument type, get number fail"); + if (!GetNativeInt32(env, args[0], sensorTypeId)) { + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, get number fail"); + return nullptr; + } sptr asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo(env, GET_SINGLE_SENSOR); CHKPP(asyncCallbackInfo); @@ -830,18 +1110,29 @@ static napi_value GetSingleSensor(napi_env env, napi_callback_info info) } } if (asyncCallbackInfo->sensorInfos.empty()) { - SEN_HILOGE("Not find sensorTypeId:%{public}d", sensorTypeId); - asyncCallbackInfo->type = FAIL; + ThrowErr(env, PARAMETER_ERROR, "Can't find the sensorId"); + return nullptr; } } if (argc == 1) { napi_value promise = nullptr; - CHKNRP(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise), "napi_create_promise"); + status = napi_create_promise(env, &asyncCallbackInfo->deferred, &promise); + if (status != napi_ok) { + ThrowErr(env, PARAMETER_ERROR, "napi_create_promise fail"); + return nullptr; + } EmitPromiseWork(asyncCallbackInfo); return promise; } - CHKNCP(env, IsMatchType(env, args[1], napi_function), "Wrong argument type, should be function"); - napi_create_reference(env, args[1], 1, &asyncCallbackInfo->callback[0]); + if (!IsMatchType(env, args[1], napi_function)) { + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, should be function"); + return nullptr; + } + status = napi_create_reference(env, args[1], 1, &asyncCallbackInfo->callback[0]); + if (status != napi_ok) { + ThrowErr(env, PARAMETER_ERROR, "napi_create_reference fail"); + return nullptr; + } EmitAsyncCallbackWork(asyncCallbackInfo); return nullptr; } @@ -853,29 +1144,29 @@ napi_value Subscribe(napi_env env, napi_callback_info info, int32_t sensorTypeId napi_value args[1] = { 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), "The number of parameters is not valid"); - CHKNCP(env, IsMatchType(env, args[0], napi_object), "Wrong argument type, should be object"); + CHKCP((argc == 1), "The number of parameters is not valid"); + CHKCP(IsMatchType(env, args[0], napi_object), "Wrong argument type, should be object"); string interval = "normal"; if ((sensorTypeId == SENSOR_TYPE_ID_ACCELEROMETER) || ((sensorTypeId == SENSOR_TYPE_ID_ORIENTATION) && (type != SUBSCRIBE_COMPASS)) || (sensorTypeId == SENSOR_TYPE_ID_GYROSCOPE)) { napi_value napiInterval = GetNamedProperty(env, args[0], "interval"); - CHKNCP(env, GetStringValue(env, napiInterval, interval), "get interval fail"); + CHKCP(GetStringValue(env, napiInterval, interval), "get interval fail"); } sptr asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo(env, type); CHKPP(asyncCallbackInfo); napi_value napiSuccess = GetNamedProperty(env, args[0], "success"); - CHKNCP(env, (napiSuccess != nullptr), "get napiSuccess fail"); - CHKNCP(env, RegisterNapiCallback(env, napiSuccess, asyncCallbackInfo->callback[0]), + CHKCP((napiSuccess != nullptr), "get napiSuccess fail"); + CHKCP(RegisterNapiCallback(env, napiSuccess, asyncCallbackInfo->callback[0]), "register callback fail"); napi_value napiFail = GetNamedProperty(env, args[0], "fail"); if (napiFail != nullptr) { SEN_HILOGD("has fail callback"); - CHKNCP(env, RegisterNapiCallback(env, napiFail, asyncCallbackInfo->callback[1]), + CHKCP(RegisterNapiCallback(env, napiFail, asyncCallbackInfo->callback[1]), "register callback fail"); } if (auto iter = g_samplingPeriod.find(interval); iter == g_samplingPeriod.end()) { - CHKNCP(env, (napiFail != nullptr), "input error, interval is invalid"); + CHKCP((napiFail != nullptr), "input error, interval is invalid"); CreateFailMessage(SUBSCRIBE_FAIL, INPUT_ERROR, "input error", asyncCallbackInfo); EmitAsyncCallbackWork(asyncCallbackInfo); return nullptr; @@ -883,7 +1174,7 @@ napi_value Subscribe(napi_env env, napi_callback_info info, int32_t sensorTypeId std::lock_guard subscribeCallbackLock(mutex_); bool ret = SubscribeSensor(sensorTypeId, g_samplingPeriod[interval], DataCallbackImpl); if (!ret) { - CHKNCP(env, (napiFail != nullptr), "subscribe fail"); + CHKCP((napiFail != nullptr), "subscribe fail"); CreateFailMessage(SUBSCRIBE_FAIL, SENSOR_SUBSCRIBE_FAILURE, "subscribe fail", asyncCallbackInfo); EmitAsyncCallbackWork(asyncCallbackInfo); return nullptr; @@ -899,14 +1190,14 @@ napi_value Unsubscribe(napi_env env, napi_callback_info info, int32_t sensorType napi_value args[1] = { 0 }; napi_value thisVar = nullptr; CHKNRP(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr), "napi_get_cb_info"); - CHKNCP(env, (argc == 0), "The number of parameters is not valid"); + CHKCP((argc == 0), "The number of parameters is not valid"); std::lock_guard subscribeCallbackLock(mutex_); g_subscribeCallbacks[sensorTypeId] = nullptr; if (CheckSubscribe(sensorTypeId)) { SEN_HILOGW("There are other client subscribe as well, not need unsubscribe"); return nullptr; } - CHKNCP(env, UnsubscribeSensor(sensorTypeId), "UnsubscribeSensor failed"); + CHKCP(UnsubscribeSensor(sensorTypeId), "UnsubscribeSensor failed"); return nullptr; } @@ -917,12 +1208,12 @@ napi_value GetBodyState(napi_env env, napi_callback_info info) napi_value args[1] = { 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), "The number of parameters is not valid"); - CHKNCP(env, IsMatchType(env, args[0], napi_object), "Wrong argument type, should be object"); + CHKCP((argc == 1), "The number of parameters is not valid"); + CHKCP(IsMatchType(env, args[0], napi_object), "Wrong argument type, should be object"); sptr asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo(env, GET_BODY_STATE); CHKPP(asyncCallbackInfo); napi_value napiSuccess = GetNamedProperty(env, args[0], "success"); - CHKNCP(env, RegisterNapiCallback(env, napiSuccess, asyncCallbackInfo->callback[0]), + CHKCP(RegisterNapiCallback(env, napiSuccess, asyncCallbackInfo->callback[0]), "register success callback fail"); std::lock_guard onBodyLock(bodyMutex_); asyncCallbackInfo->data.sensorData.data[0] = @@ -956,8 +1247,6 @@ static napi_value CreateEnumSensorType(napi_env env, napi_value exports) DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_GRAVITY", GetNapiInt32(env, SENSOR_TYPE_ID_GRAVITY)), DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_LINEAR_ACCELERATION", GetNapiInt32(env, SENSOR_TYPE_ID_LINEAR_ACCELERATION)), - DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_LINEAR_ACCELEROMETER", - GetNapiInt32(env, SENSOR_TYPE_ID_LINEAR_ACCELERATION)), DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_ROTATION_VECTOR", GetNapiInt32(env, SENSOR_TYPE_ID_ROTATION_VECTOR)), DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_AMBIENT_TEMPERATURE", @@ -972,7 +1261,6 @@ static napi_value CreateEnumSensorType(napi_env env, napi_value exports) 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_HEART_BEAT_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(env, SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED)), @@ -984,6 +1272,41 @@ static napi_value CreateEnumSensorType(napi_env env, napi_value exports) return exports; } +static napi_value CreateEnumSensorId(napi_env env, napi_value exports) +{ + napi_property_descriptor desc[] = { + DECLARE_NAPI_STATIC_PROPERTY("ACCELEROMETER", GetNapiInt32(env, SENSOR_TYPE_ID_ACCELEROMETER)), + DECLARE_NAPI_STATIC_PROPERTY("GYROSCOPE", GetNapiInt32(env, SENSOR_TYPE_ID_GYROSCOPE)), + DECLARE_NAPI_STATIC_PROPERTY("AMBIENT_LIGHT", GetNapiInt32(env, SENSOR_TYPE_ID_AMBIENT_LIGHT)), + DECLARE_NAPI_STATIC_PROPERTY("MAGNETIC_FIELD", GetNapiInt32(env, SENSOR_TYPE_ID_MAGNETIC_FIELD)), + DECLARE_NAPI_STATIC_PROPERTY("BAROMETER", GetNapiInt32(env, SENSOR_TYPE_ID_BAROMETER)), + DECLARE_NAPI_STATIC_PROPERTY("HALL", GetNapiInt32(env, SENSOR_TYPE_ID_HALL)), + DECLARE_NAPI_STATIC_PROPERTY("PROXIMITY", GetNapiInt32(env, SENSOR_TYPE_ID_PROXIMITY)), + DECLARE_NAPI_STATIC_PROPERTY("HUMIDITY", GetNapiInt32(env, SENSOR_TYPE_ID_HUMIDITY)), + DECLARE_NAPI_STATIC_PROPERTY("ORIENTATION", GetNapiInt32(env, SENSOR_TYPE_ID_ORIENTATION)), + DECLARE_NAPI_STATIC_PROPERTY("GRAVITY", GetNapiInt32(env, SENSOR_TYPE_ID_GRAVITY)), + DECLARE_NAPI_STATIC_PROPERTY("LINEAR_ACCELEROMETER", GetNapiInt32(env, SENSOR_TYPE_ID_LINEAR_ACCELERATION)), + DECLARE_NAPI_STATIC_PROPERTY("ROTATION_VECTOR", GetNapiInt32(env, SENSOR_TYPE_ID_ROTATION_VECTOR)), + DECLARE_NAPI_STATIC_PROPERTY("AMBIENT_TEMPERATURE", GetNapiInt32(env, SENSOR_TYPE_ID_AMBIENT_TEMPERATURE)), + DECLARE_NAPI_STATIC_PROPERTY("MAGNETIC_FIELD_UNCALIBRATED", + GetNapiInt32(env, SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED)), + DECLARE_NAPI_STATIC_PROPERTY("GYROSCOPE_UNCALIBRATED", + GetNapiInt32(env, SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED)), + DECLARE_NAPI_STATIC_PROPERTY("SIGNIFICANT_MOTION", GetNapiInt32(env, SENSOR_TYPE_ID_SIGNIFICANT_MOTION)), + DECLARE_NAPI_STATIC_PROPERTY("PEDOMETER_DETECTION", GetNapiInt32(env, SENSOR_TYPE_ID_PEDOMETER_DETECTION)), + DECLARE_NAPI_STATIC_PROPERTY("PEDOMETER", GetNapiInt32(env, SENSOR_TYPE_ID_PEDOMETER)), + DECLARE_NAPI_STATIC_PROPERTY("HEART_RATE", GetNapiInt32(env, SENSOR_TYPE_ID_HEART_RATE)), + DECLARE_NAPI_STATIC_PROPERTY("WEAR_DETECTION", GetNapiInt32(env, SENSOR_TYPE_ID_WEAR_DETECTION)), + DECLARE_NAPI_STATIC_PROPERTY("ACCELEROMETER_UNCALIBRATED", + GetNapiInt32(env, SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED)), + }; + napi_value result = nullptr; + CHKNRP(env, napi_define_class(env, "SensorId", NAPI_AUTO_LENGTH, EnumClassConstructor, nullptr, + sizeof(desc) / sizeof(*desc), desc, &result), "napi_define_class"); + CHKNRP(env, napi_set_named_property(env, exports, "SensorId", result), "napi_set_named_property fail"); + return exports; +} + static napi_value Init(napi_env env, napi_value exports) { napi_property_descriptor desc[] = { @@ -991,15 +1314,22 @@ static napi_value Init(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("once", Once), DECLARE_NAPI_FUNCTION("off", Off), DECLARE_NAPI_FUNCTION("getGeomagneticField", GetGeomagneticField), + DECLARE_NAPI_FUNCTION("getGeomagneticInfo", GetGeomagneticField), DECLARE_NAPI_FUNCTION("transformCoordinateSystem", TransformCoordinateSystem), + DECLARE_NAPI_FUNCTION("transformRotationMatrix", TransformCoordinateSystem), DECLARE_NAPI_FUNCTION("getAngleModify", GetAngleModify), + DECLARE_NAPI_FUNCTION("getAngleVariation", GetAngleModify), DECLARE_NAPI_FUNCTION("getDirection", GetDirection), + DECLARE_NAPI_FUNCTION("getOrientation", GetDirection), DECLARE_NAPI_FUNCTION("createQuaternion", CreateQuaternion), + DECLARE_NAPI_FUNCTION("getQuaternion", CreateQuaternion), DECLARE_NAPI_FUNCTION("getAltitude", GetAltitude), + DECLARE_NAPI_FUNCTION("getDeviceAltitude", GetAltitude), DECLARE_NAPI_FUNCTION("getGeomagneticDip", GetGeomagneticDip), + DECLARE_NAPI_FUNCTION("getInclination", GetGeomagneticDip), DECLARE_NAPI_FUNCTION("createRotationMatrix", CreateRotationMatrix), + DECLARE_NAPI_FUNCTION("getRotationMatrix", CreateRotationMatrix), DECLARE_NAPI_FUNCTION("getSensorList", GetSensorList), - DECLARE_NAPI_FUNCTION("getSensorLists", GetSensorList), DECLARE_NAPI_FUNCTION("getSingleSensor", GetSingleSensor), DECLARE_NAPI_FUNCTION("subscribeAccelerometer", SubscribeAccelerometer), DECLARE_NAPI_FUNCTION("unsubscribeAccelerometer", UnsubscribeAccelerometer), @@ -1031,7 +1361,8 @@ static napi_value Init(napi_env env, napi_value 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"); + CHKCP(CreateEnumSensorType(env, exports), "Create enum sensor type fail"); + CHKCP(CreateEnumSensorId(env, exports), "Create enum sensor id fail"); return exports; } diff --git a/interfaces/plugin/src/sensor_napi_error.cpp b/interfaces/plugin/src/sensor_napi_error.cpp new file mode 100755 index 00000000..1b2cc5e8 --- /dev/null +++ b/interfaces/plugin/src/sensor_napi_error.cpp @@ -0,0 +1,58 @@ +/* + * 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. + */ + +#include "sensor_napi_error.h" + +#include + +namespace OHOS { +namespace Sensors { +namespace { +constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SENSOR_LOG_DOMAIN, "SensorJsAPI"}; +} // namespace +napi_value CreateBusinessError(const napi_env &env, const int32_t errCode, const std::string &errMessage) +{ + napi_value businessError = nullptr; + napi_value code = nullptr; + napi_value msg = nullptr; + NAPI_CALL(env, napi_create_int32(env, errCode, &code)); + NAPI_CALL(env, napi_create_string_utf8(env, errMessage.c_str(), NAPI_AUTO_LENGTH, &msg)); + napi_create_error(env, nullptr, msg, &businessError); + napi_set_named_property(env, businessError, "code", code); + return businessError; +} + +std::optional GetNapiError(int32_t errorCode) +{ + auto iter = ERROR_MESSAGES.find(errorCode); + if (iter != ERROR_MESSAGES.end()) { + return iter->second; + } + return std::nullopt; +} + +void ThrowErr(const napi_env &env, const int32_t errCode, const std::string &printMsg) +{ + SEN_HILOGE("message: %{public}s, code: %{public}d", printMsg.c_str(), errCode); + auto msg = GetNapiError(errCode); + if (!msg) { + SEN_HILOGE("errCode: %{public}d is invalid", errCode); + return; + } + napi_value error = CreateBusinessError(env, errCode, msg.value()); + napi_throw(env, error); +} +} // 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 3a886307..3ae4f794 100644 --- a/interfaces/plugin/src/sensor_napi_utils.cpp +++ b/interfaces/plugin/src/sensor_napi_utils.cpp @@ -19,6 +19,8 @@ #include #include +#include "sensor_napi_error.h" + namespace OHOS { namespace Sensors { namespace { @@ -58,7 +60,7 @@ bool GetFloatArray(const napi_env &env, const napi_value &value, vector & 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"); + CHKNCF(env, GetNativeDouble(env, element, value), "Wrong argument type. get double fail"); array.push_back(static_cast(value)); } return true; @@ -79,37 +81,37 @@ napi_value GetNamedProperty(const napi_env &env, const napi_value &object, strin return value; } -bool GetCppDouble(const napi_env &env, const napi_value &value, double &number) +bool GetNativeDouble(const napi_env &env, const napi_value &value, double &number) { CALL_LOG_ENTER; CHKNRF(env, napi_get_value_double(env, value, &number), "napi_get_value_double"); return true; } -bool GetCppFloat(const napi_env &env, const napi_value &value, float &number) +bool GetNativeFloat(const napi_env &env, const napi_value &value, float &number) { CALL_LOG_ENTER; double result = 0; - CHKNCF(env, GetCppDouble(env, value, result), "Get cpp double fail"); + CHKNCF(env, GetNativeDouble(env, value, result), "Get cpp double fail"); number = static_cast(result); return true; } -bool GetCppInt32(const napi_env &env, const napi_value &value, int32_t &number) +bool GetNativeInt32(const napi_env &env, const napi_value &value, int32_t &number) { CALL_LOG_ENTER; CHKNRF(env, napi_get_value_int32(env, value, &number), "napi_get_value_int32"); return true; } -bool GetCppInt64(const napi_env &env, const napi_value &value, int64_t &number) +bool GetNativeInt64(const napi_env &env, const napi_value &value, int64_t &number) { CALL_LOG_ENTER; CHKNRF(env, napi_get_value_int64(env, value, &number), "napi_get_value_int64"); return true; } -bool GetCppBool(const napi_env &env, const napi_value &value) +bool GetNativeBool(const napi_env &env, const napi_value &value) { CALL_LOG_ENTER; bool number = false; @@ -291,8 +293,7 @@ bool ConvertToFailData(const napi_env &env, sptr asyncCallbac { CALL_LOG_ENTER; CHKPF(asyncCallbackInfo); - result[0] = GreateBusinessError(env, asyncCallbackInfo->error.code, asyncCallbackInfo->error.message, - asyncCallbackInfo->error.name, asyncCallbackInfo->error.stack); + result[0] = CreateBusinessError(env, asyncCallbackInfo->error.code, asyncCallbackInfo->error.message); CHKPF(result[0]); return true; } @@ -395,30 +396,6 @@ bool ConvertToRotationMatrix(const napi_env &env, sptr asyncC return true; } -napi_value GreateBusinessError(const napi_env &env, int32_t errCode, string errMessage, - string errName, string errStack) -{ - CALL_LOG_ENTER; - napi_value result = nullptr; - 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; -} - bool CreateNapiArray(const napi_env &env, float data[], int32_t dataLength, napi_value &result) { CHKNRF(env, napi_create_array(env, &result), "napi_create_array"); @@ -435,10 +412,11 @@ void EmitAsyncCallbackWork(sptr asyncCallbackInfo) CALL_LOG_ENTER; CHKPV(asyncCallbackInfo); napi_value resourceName = nullptr; - CHKNRV(asyncCallbackInfo->env, napi_create_string_utf8(asyncCallbackInfo->env, "AsyncCallback", - NAPI_AUTO_LENGTH, &resourceName), "napi_create_string_utf8"); + napi_env env = asyncCallbackInfo->env; + napi_status ret = napi_create_string_latin1(env, "AsyncCallback", NAPI_AUTO_LENGTH, &resourceName); + CHKCV((ret == napi_ok), "napi_create_string_latin1 fail"); asyncCallbackInfo->IncStrongRef(nullptr); - napi_status status = napi_create_async_work(asyncCallbackInfo->env, nullptr, resourceName, + napi_status status = napi_create_async_work(env, nullptr, resourceName, [](napi_env env, void* data) {}, [](napi_env env, napi_status status, void* data) { CALL_LOG_ENTER; @@ -455,23 +433,24 @@ void EmitAsyncCallbackWork(sptr asyncCallbackInfo) napi_value callResult = nullptr; napi_value result[2] = {0}; if (asyncCallbackInfo->type == SUBSCRIBE_FAIL) { - CHKNRV(env, napi_get_reference_value(env, asyncCallbackInfo->callback[1], &callback), - "napi_get_reference_value"); - CHKNRV(env, napi_create_string_utf8(env, asyncCallbackInfo->error.message.c_str(), - NAPI_AUTO_LENGTH, &result[0]), "napi_create_string_utf8"); - CHKNRV(env, napi_create_int32(env, asyncCallbackInfo->error.code, &result[1]), "napi_create_int32"); - CHKNRV(env, napi_call_function(env, nullptr, callback, 2, result, &callResult), - "napi_call_function"); + CHKCV((napi_get_reference_value(env, asyncCallbackInfo->callback[1], &callback) == napi_ok), + "napi_get_reference_value fail"); + CHKCV((napi_create_string_utf8(env, asyncCallbackInfo->error.message.c_str(), + NAPI_AUTO_LENGTH, &result[0]) == napi_ok), "napi_create_string_utf8 fail"); + CHKCV((napi_create_int32(env, asyncCallbackInfo->error.code, &result[1]) == napi_ok), + "napi_create_int32 fail"); + CHKCV((napi_call_function(env, nullptr, callback, 2, result, &callResult) == napi_ok), + "napi_call_function fail"); return; } - CHKNRV(env, napi_get_reference_value(env, asyncCallbackInfo->callback[0], &callback), - "napi_get_reference_value"); - CHKNCV(env, (g_convertfuncList.find(asyncCallbackInfo->type) != g_convertfuncList.end()), + CHKCV((napi_get_reference_value(env, asyncCallbackInfo->callback[0], &callback) == napi_ok), + "napi_get_reference_value fail"); + CHKCV((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"); + CHKCV(ret, "Create napi data fail in async work"); + CHKCV((napi_call_function(env, nullptr, callback, 2, result, &callResult) == napi_ok), + "napi_call_function fail"); }, asyncCallbackInfo.GetRefPtr(), &asyncCallbackInfo->asyncWork); if (status != napi_ok @@ -492,8 +471,7 @@ void EmitUvEventLoop(sptr asyncCallbackInfo) { CHKPV(asyncCallbackInfo); uv_loop_s *loop(nullptr); - CHKNRV(asyncCallbackInfo->env, napi_get_uv_event_loop(asyncCallbackInfo->env, &loop), - "napi_get_uv_event_loop"); + CHKCV((napi_get_uv_event_loop(asyncCallbackInfo->env, &loop) == napi_ok), "napi_get_uv_event_loop fail"); CHKPV(loop); uv_work_t *work = new(std::nothrow) uv_work_t; CHKPV(work); @@ -557,10 +535,11 @@ void EmitPromiseWork(sptr asyncCallbackInfo) CALL_LOG_ENTER; CHKPV(asyncCallbackInfo); napi_value resourceName = nullptr; - CHKNRV(asyncCallbackInfo->env, napi_create_string_latin1(asyncCallbackInfo->env, "Promise", - NAPI_AUTO_LENGTH, &resourceName), "napi_create_string_latin1"); + napi_env env = asyncCallbackInfo->env; + napi_status ret = napi_create_string_latin1(env, "Promise", NAPI_AUTO_LENGTH, &resourceName); + CHKCV((ret == napi_ok), "napi_create_string_latin1 fail"); asyncCallbackInfo->IncStrongRef(nullptr); - napi_status status = napi_create_async_work(asyncCallbackInfo->env, nullptr, resourceName, + napi_status status = napi_create_async_work(env, nullptr, resourceName, [](napi_env env, void* data) {}, [](napi_env env, napi_status status, void* data) { CALL_LOG_ENTER; @@ -574,16 +553,16 @@ void EmitPromiseWork(sptr asyncCallbackInfo) */ asyncCallbackInfo->DecStrongRef(nullptr); napi_value result[2] = {0}; - CHKNCV(env, (g_convertfuncList.find(asyncCallbackInfo->type) != g_convertfuncList.end()), + CHKCV((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"); + CHKCV(ret, "Callback type invalid in promise"); if (asyncCallbackInfo->type == FAIL) { - CHKNRV(env, napi_reject_deferred(env, asyncCallbackInfo->deferred, result[0]), - "napi_reject_deferred"); + CHKCV((napi_reject_deferred(env, asyncCallbackInfo->deferred, result[0]) == napi_ok), + "napi_reject_deferred fail"); } else { - CHKNRV(env, napi_resolve_deferred(env, asyncCallbackInfo->deferred, result[1]), - "napi_resolve_deferred"); + CHKCV((napi_resolve_deferred(env, asyncCallbackInfo->deferred, result[1]) == napi_ok), + "napi_resolve_deferred fail"); } }, asyncCallbackInfo.GetRefPtr(), &asyncCallbackInfo->asyncWork); diff --git a/services/sensor/src/sensor_service_stub.cpp b/services/sensor/src/sensor_service_stub.cpp index 98d1b1e7..bed7a011 100644 --- a/services/sensor/src/sensor_service_stub.cpp +++ b/services/sensor/src/sensor_service_stub.cpp @@ -84,7 +84,7 @@ ErrCode SensorServiceStub::SensorEnableInner(MessageParcel &data, MessageParcel HiSysEvent::Write(HiSysEvent::Domain::SENSOR, "SENSOR_VERIFY_ACCESS_TOKEN_FAIL", HiSysEvent::EventType::SECURITY, "PKG_NAME", "SensorEnableInner", "ERROR_CODE", ret); SEN_HILOGE("sensorId:%{public}u grant failed,result:%{public}d", sensorId, ret); - return ERR_PERMISSION_DENIED; + return PERMISSION_DENIED; } return EnableSensor(sensorId, data.ReadInt64(), data.ReadInt64()); } @@ -99,7 +99,7 @@ ErrCode SensorServiceStub::SensorDisableInner(MessageParcel &data, MessageParcel HiSysEvent::Write(HiSysEvent::Domain::SENSOR, "SENSOR_VERIFY_ACCESS_TOKEN_FAIL", HiSysEvent::EventType::SECURITY, "PKG_NAME", "SensorDisableInner", "ERROR_CODE", ret); SEN_HILOGE("sensorId:%{public}u grant failed,result:%{public}d", sensorId, ret); - return ERR_PERMISSION_DENIED; + return PERMISSION_DENIED; } return DisableSensor(sensorId); } @@ -114,7 +114,7 @@ ErrCode SensorServiceStub::GetSensorStateInner(MessageParcel &data, MessageParce HiSysEvent::Write(HiSysEvent::Domain::SENSOR, "SENSOR_VERIFY_ACCESS_TOKEN_FAIL", HiSysEvent::EventType::SECURITY, "PKG_NAME", "GetSensorStateInner", "ERROR_CODE", ret); SEN_HILOGE("sensorId:%{public}u grant failed, result:%{public}d", sensorId, ret); - return ERR_PERMISSION_DENIED; + return PERMISSION_DENIED; } return GetSensorState(sensorId); } @@ -129,7 +129,7 @@ ErrCode SensorServiceStub::RunCommandInner(MessageParcel &data, MessageParcel &r HiSysEvent::Write(HiSysEvent::Domain::SENSOR, "SENSOR_VERIFY_ACCESS_TOKEN_FAIL", HiSysEvent::EventType::SECURITY, "PKG_NAME", "RunCommandInner", "ERROR_CODE", ret); SEN_HILOGE("sensorId:%{public}u grant failed,result:%{public}d", sensorId, ret); - return ERR_PERMISSION_DENIED; + return PERMISSION_DENIED; } return RunCommand(sensorId, data.ReadUint32(), data.ReadUint32()); } diff --git a/utils/include/sensors_errors.h b/utils/include/sensors_errors.h index 754fc661..7c205893 100644 --- a/utils/include/sensors_errors.h +++ b/utils/include/sensors_errors.h @@ -23,6 +23,13 @@ namespace OHOS { namespace Sensors { +// Error code for user +enum ErrorCode : int32_t { + PERMISSION_DENIED = 201, // Use this error code when permission is denied. + PARAMETER_ERROR = 401, // Use this error code when the input parameter type or range does not match. + SERVICE_EXCEPTION = 14500101 // Use this error code when the service is exception. +}; + enum { MODULE_COMMON = 0x00, MODULE_SENSORS_DEVICE = 0x01, @@ -256,6 +263,14 @@ private: } \ } while (0) +#define CHKCP(cond, message) \ + do { \ + if (!(cond)) { \ + SEN_HILOGE("(%{public}s)", #message); \ + return nullptr; \ + } \ + } while (0) + #define CHKCV(cond, message) \ do { \ if (!(cond)) { \ -- Gitee