diff --git a/interfaces/native/BUILD.gn b/interfaces/native/BUILD.gn index 78b528ecd53571b212f265578ec718b3e7c7a4f7..6fc5e5a4db98a50df49f14d7cc50227c10dd25b2 100644 --- a/interfaces/native/BUILD.gn +++ b/interfaces/native/BUILD.gn @@ -38,7 +38,6 @@ ohos_shared_library("sensor_interface_native") { "$SUBSYSTEM_DIR/utils/include", "$SUBSYSTEM_DIR/interfaces/native/include", "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", - "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", ] deps = [ "$SUBSYSTEM_DIR/frameworks/native/sensor:libsensor_native", diff --git a/interfaces/native/include/geomagnetic_field.h b/interfaces/native/include/geomagnetic_field.h index fbd10bf1527abd6fe6bb46a3250e38bbe8074891..28a20a7252283d97141ce4c0924a801b170fdec1 100644 --- a/interfaces/native/include/geomagnetic_field.h +++ b/interfaces/native/include/geomagnetic_field.h @@ -28,62 +28,24 @@ class GeomagneticField { public: - GeomagneticField(float latitude, float longitude, float altitude, int64_t timeMillis); - ~GeomagneticField() = default; - - float obtainX(); - - float obtainY(); - - float obtainZ(); - - float obtainGeomagneticDip(); - - float obtainDeflectionAngle(); - - float obtainLevelIntensity(); - - float obtainTotalIntensity(); + float ObtainX(); + float ObtainY(); + float ObtainZ(); + float ObtainGeomagneticDip(); + float ObtainDeflectionAngle(); + float ObtainLevelIntensity(); + float ObtainTotalIntensity(); private: - float northComponent; - float eastComponent; - float downComponent; - static float geocentricLatitude; - static float geocentricLongitude; - static float geocentricRadius; - const static float EARTH_MAJOR_AXIS_RADIUS; - const static float EARTH_MINOR_AXIS_RADIUS; - const static float EARTH_REFERENCE_RADIUS; - const static float PRECISION; - const static float LATITUDE_MAX; - const static float LATITUDE_MIN; - const static float CONVERSION_FACTOR; - const static float DERIVATIVE_FACTOR; - const static int64_t WMM_BASE_TIME; - - const static float GAUSS_COEFFICIENT_G[13][13]; - const static float GAUSS_COEFFICIENT_H[13][13]; - const static float DELTA_GAUSS_COEFFICIENT_G[13][13]; - const static float DELTA_GAUSS_COEFFICIENT_H[13][13]; - const static int32_t GAUSSIAN_COEFFICIENT_DIMENSION; - static std::vector> schmidtQuasiNormalFactors; - - static std::vector> polynomials; - static std::vector> polynomialsDerivative; - static std::vector relativeRadiusPower; - static std::vector sinMLongitude; - static std::vector cosMLongitude; - - static std::vector> getSchmidtQuasiNormalFactors(int32_t expansionDegree); - void calculateGeomagneticComponent(double latDiffRad, int64_t timeMillis); - static void getLongitudeTrigonometric(); - static void getRelativeRadiusPower(); - static void calibrateGeocentricCoordinates(float latitude, float longitude, float altitude); - void initLegendreTable(int32_t expansionDegree, float thetaRad); - double toDegrees(double angrad); - static double toRadians(double angdeg); + std::vector> GetSchmidtQuasiNormalFactors(int32_t expansionDegree); + void CalculateGeomagneticComponent(double latDiffRad, int64_t timeMillis); + void GetLongitudeTrigonometric(); + void GetRelativeRadiusPower(); + void CalibrateGeocentricCoordinates(float latitude, float longitude, float altitude); + void InitLegendreTable(int32_t expansionDegree, float thetaRad); + double ToDegrees(double angrad); + double ToRadians(double angdeg); }; #endif // GEOMAGNETIC_FIELD_H \ No newline at end of file diff --git a/interfaces/native/src/geomagnetic_field.cpp b/interfaces/native/src/geomagnetic_field.cpp index fc77139195b7c92a5ea7a82050a2b32e5c04b626..254abf351f26c2f805ce51b0e72c468c2902da7e 100644 --- a/interfaces/native/src/geomagnetic_field.cpp +++ b/interfaces/native/src/geomagnetic_field.cpp @@ -18,23 +18,20 @@ using namespace OHOS::HiviewDFX; using namespace std; -static const HiLogLabel LABEL = {LOG_CORE, OHOS::SensorsLogDomain::SENSORS_INTERFACE, "GeomagneticField"}; - -const float GeomagneticField::EARTH_MAJOR_AXIS_RADIUS = 6378.137f; -const float GeomagneticField::EARTH_MINOR_AXIS_RADIUS = 6356.7523142f; -const float GeomagneticField::EARTH_REFERENCE_RADIUS = 6371.2f; -const float GeomagneticField::PRECISION = 1e-5f; -const float GeomagneticField::LATITUDE_MAX = 90.0f; -const float GeomagneticField::LATITUDE_MIN = -90.0f; -const float GeomagneticField::CONVERSION_FACTOR = 1000.0f; -const float GeomagneticField::DERIVATIVE_FACTOR = 1.0f; +namespace { +constexpr HiLogLabel LABEL = {LOG_CORE, OHOS::SensorsLogDomain::SENSORS_INTERFACE, "GeomagneticField"}; +constexpr float EARTH_MAJOR_AXIS_RADIUS = 6378.137f; +constexpr float EARTH_MINOR_AXIS_RADIUS = 6356.7523142f; +constexpr float EARTH_REFERENCE_RADIUS = 6371.2f; +constexpr float PRECISION = 1e-5f; +constexpr float LATITUDE_MAX = 90.0f; +constexpr float LATITUDE_MIN = -90.0f; +constexpr float CONVERSION_FACTOR = 1000.0f; +constexpr float DERIVATIVE_FACTOR = 1.0f; // the time from 1970-01-01 to 2020-01-01 as UTC milliseconds from the epoch -const int64_t GeomagneticField::WMM_BASE_TIME = 1580486400000; - -/** -* The following Gaussian coefficients are derived from the US/ United Kingdom World Magnetic Model 2020-2025. -*/ -const float GeomagneticField::GAUSS_COEFFICIENT_G[13][13] = { +constexpr int64_t WMM_BASE_TIME = 1580486400000; +// The following Gaussian coefficients are derived from the US/ United Kingdom World Magnetic Model 2020-2025. +constexpr float GAUSS_COEFFICIENT_G[13][13] = { {0.0f}, {-29404.5f, -1450.7f}, {-2500.0f, 2982.0f, 1676.8f}, @@ -49,8 +46,7 @@ const float GeomagneticField::GAUSS_COEFFICIENT_G[13][13] = { {3.0f, -1.4f, -2.5f, 2.4f, -0.9f, 0.3f, -0.7f, -0.1f, 1.4f, -0.6f, 0.2f, 3.1f}, {-2.0f, -0.1f, 0.5f, 1.3f, -1.2f, 0.7f, 0.3f, 0.5f, -0.2f, -0.5f, 0.1f, -1.1f, -0.3f} }; - -const float GeomagneticField::GAUSS_COEFFICIENT_H[13][13] = { +constexpr float GAUSS_COEFFICIENT_H[13][13] = { {0.0f}, {0.0f, 4652.9f}, {0.0f, -2991.6f, -734.8f}, @@ -65,8 +61,7 @@ const float GeomagneticField::GAUSS_COEFFICIENT_H[13][13] = { {0.0f, 0.0f, 2.6f, -0.5f, -0.4f, 0.6f, -0.2f, -1.7f, -1.6f, -3.0f, -2.0f, -2.6f}, {0.0f, -1.2f, 0.5f, 1.3f, -1.8f, 0.1f, 0.7f, -0.1f, 0.6f, 0.2f, -0.9f, 0.0f, 0.5f} }; - -const float GeomagneticField::DELTA_GAUSS_COEFFICIENT_G[13][13] = { +constexpr float DELTA_GAUSS_COEFFICIENT_G[13][13] = { {0.0f}, {6.7f, 7.7f}, {-11.5f, -7.1f, -2.2f}, @@ -81,8 +76,7 @@ const float GeomagneticField::DELTA_GAUSS_COEFFICIENT_G[13][13] = { {0.0f, -0.1f, 0.0f, 0.0f, 0.0f, -0.1f, 0.0f, 0.0f, -0.1f, -0.1f, -0.1f, -0.1f}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, -0.1f} }; - -const float GeomagneticField::DELTA_GAUSS_COEFFICIENT_H[13][13] = { +constexpr float DELTA_GAUSS_COEFFICIENT_H[13][13] = { {0.0f}, {0.0f, -25.1f}, {0.0f, -30.2f, -23.9f}, @@ -97,76 +91,82 @@ const float GeomagneticField::DELTA_GAUSS_COEFFICIENT_H[13][13] = { {0.0f, 0.0f, 0.1f, 0.0f, 0.2f, 0.0f, 0.0f, 0.1f, 0.0f, -0.1f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f, -0.1f, 0.1f, 0.0f, 0.0f, 0.0f, 0.1f, 0.0f, 0.0f, 0.0f, -0.1f} }; +constexpr int32_t GAUSSIAN_COEFFICIENT_DIMENSION = 13; +std::mutex mutex_; + +float northComponent; +float eastComponent; +float downComponent; +float geocentricLatitude; +float geocentricLongitude; +float geocentricRadius; -const int32_t GeomagneticField::GAUSSIAN_COEFFICIENT_DIMENSION = - sizeof(GAUSS_COEFFICIENT_G) / sizeof(GAUSS_COEFFICIENT_G[0]); -std::vector> GeomagneticField::schmidtQuasiNormalFactors; -std::vector GeomagneticField::relativeRadiusPower(GAUSSIAN_COEFFICIENT_DIMENSION + 2); -std::vector GeomagneticField::sinMLongitude(GAUSSIAN_COEFFICIENT_DIMENSION); -std::vector GeomagneticField::cosMLongitude(GAUSSIAN_COEFFICIENT_DIMENSION); -std::vector> GeomagneticField::polynomials(GAUSSIAN_COEFFICIENT_DIMENSION); -std::vector> GeomagneticField::polynomialsDerivative(GAUSSIAN_COEFFICIENT_DIMENSION); -float GeomagneticField::geocentricLatitude; -float GeomagneticField::geocentricLongitude; -float GeomagneticField::geocentricRadius; +std::vector> schmidtQuasiNormalFactors; +std::vector> polynomials(GAUSSIAN_COEFFICIENT_DIMENSION); +std::vector> polynomialsDerivative(GAUSSIAN_COEFFICIENT_DIMENSION); +std::vector relativeRadiusPower(GAUSSIAN_COEFFICIENT_DIMENSION + 2); +std::vector sinMLongitude(GAUSSIAN_COEFFICIENT_DIMENSION); +std::vector cosMLongitude(GAUSSIAN_COEFFICIENT_DIMENSION); +} GeomagneticField::GeomagneticField(float latitude, float longitude, float altitude, int64_t timeMillis) { - schmidtQuasiNormalFactors = getSchmidtQuasiNormalFactors(GAUSSIAN_COEFFICIENT_DIMENSION); + std::lock_guard geomagneticLock(mutex_); + schmidtQuasiNormalFactors = GetSchmidtQuasiNormalFactors(GAUSSIAN_COEFFICIENT_DIMENSION); float gcLatitude = fmax(LATITUDE_MIN + PRECISION, fmin(LATITUDE_MAX - PRECISION, latitude)); - calibrateGeocentricCoordinates(gcLatitude, longitude, altitude); - initLegendreTable(GAUSSIAN_COEFFICIENT_DIMENSION - 1, static_cast(M_PI / 2.0 - geocentricLatitude)); - getRelativeRadiusPower(); - double latDiffRad = toRadians(gcLatitude) - geocentricLatitude; - calculateGeomagneticComponent(latDiffRad, timeMillis); + CalibrateGeocentricCoordinates(gcLatitude, longitude, altitude); + InitLegendreTable(GAUSSIAN_COEFFICIENT_DIMENSION - 1, static_cast(M_PI / 2.0 - geocentricLatitude)); + GetRelativeRadiusPower(); + double latDiffRad = ToRadians(gcLatitude) - geocentricLatitude; + CalculateGeomagneticComponent(latDiffRad, timeMillis); } -std::vector> GeomagneticField::getSchmidtQuasiNormalFactors(int32_t expansionDegree) +std::vector> GeomagneticField::GetSchmidtQuasiNormalFactors(int32_t expansionDegree) { std::vector> schmidtQuasiNormFactors(expansionDegree + 1); schmidtQuasiNormFactors[0].resize(1); schmidtQuasiNormFactors[0][0] = 1.0f; - for (int32_t rowIndex = 1; rowIndex <= expansionDegree; rowIndex++) { - schmidtQuasiNormFactors[rowIndex].resize(rowIndex + 1); - schmidtQuasiNormFactors[rowIndex][0] = - schmidtQuasiNormFactors[rowIndex - 1][0] * (2 * rowIndex - 1) / static_cast(rowIndex); - for (int32_t columnIndex = 1; columnIndex <= rowIndex; columnIndex++) { - schmidtQuasiNormFactors[rowIndex][columnIndex] = schmidtQuasiNormFactors[rowIndex][columnIndex - 1] - * static_cast(sqrt((rowIndex - columnIndex + 1) * ((columnIndex == 1) ? 2 : 1) - / static_cast(rowIndex + columnIndex))); + for (int32_t row = 1; row <= expansionDegree; row++) { + schmidtQuasiNormFactors[row].resize(row + 1); + schmidtQuasiNormFactors[row][0] = + schmidtQuasiNormFactors[row - 1][0] * (2 * row - 1) / static_cast(row); + for (int32_t column = 1; column <= row; column++) { + schmidtQuasiNormFactors[row][column] = schmidtQuasiNormFactors[row][column - 1] + * static_cast(sqrt((row - column + 1) * ((column == 1) ? 2 : 1) + / static_cast(row + column))); } } return schmidtQuasiNormFactors; } -void GeomagneticField::calculateGeomagneticComponent(double latDiffRad, int64_t timeMillis) +void GeomagneticField::CalculateGeomagneticComponent(double latDiffRad, int64_t timeMillis) { HiLog::Info(LABEL, "%{public}s begin", __func__); float yearsSinceBase = (timeMillis - WMM_BASE_TIME) / (365.0f * 24.0f * 60.0f * 60.0f * 1000.0f); float inverseCosLatitude = DERIVATIVE_FACTOR / static_cast(cos(geocentricLatitude)); - getLongitudeTrigonometric(); + GetLongitudeTrigonometric(); float gcX = 0.0f; float gcY = 0.0f; float gcZ = 0.0f; - for (int32_t rowIndex = 1; rowIndex < GAUSSIAN_COEFFICIENT_DIMENSION; rowIndex++) { - for (int32_t columnIndex = 0; columnIndex <= rowIndex; columnIndex++) { - float g = GAUSS_COEFFICIENT_G[rowIndex][columnIndex] + yearsSinceBase - * DELTA_GAUSS_COEFFICIENT_G[rowIndex][columnIndex]; - float h = GAUSS_COEFFICIENT_H[rowIndex][columnIndex] + yearsSinceBase - * DELTA_GAUSS_COEFFICIENT_H[rowIndex][columnIndex]; - gcX += relativeRadiusPower[rowIndex + 2] - * (g * cosMLongitude[columnIndex] + h * sinMLongitude[columnIndex]) - * polynomialsDerivative[rowIndex][columnIndex] - * schmidtQuasiNormalFactors[rowIndex][columnIndex]; - gcY += relativeRadiusPower[rowIndex + 2] * columnIndex - * (g * sinMLongitude[columnIndex] - h * cosMLongitude[columnIndex]) - * polynomials[rowIndex][columnIndex] - * schmidtQuasiNormalFactors[rowIndex][columnIndex] + for (int32_t row = 1; row < GAUSSIAN_COEFFICIENT_DIMENSION; row++) { + for (int32_t column = 0; column <= row; column++) { + float g = GAUSS_COEFFICIENT_G[row][column] + yearsSinceBase + * DELTA_GAUSS_COEFFICIENT_G[row][column]; + float h = GAUSS_COEFFICIENT_H[row][column] + yearsSinceBase + * DELTA_GAUSS_COEFFICIENT_H[row][column]; + gcX += relativeRadiusPower[row + 2] + * (g * cosMLongitude[column] + h * sinMLongitude[column]) + * polynomialsDerivative[row][column] + * schmidtQuasiNormalFactors[row][column]; + gcY += relativeRadiusPower[row + 2] * column + * (g * sinMLongitude[column] - h * cosMLongitude[column]) + * polynomials[row][column] + * schmidtQuasiNormalFactors[row][column] * inverseCosLatitude; - gcZ -= (rowIndex + 1) * relativeRadiusPower[rowIndex + 2] - * (g * cosMLongitude[columnIndex] + h * sinMLongitude[columnIndex]) - * polynomials[rowIndex][columnIndex] - * schmidtQuasiNormalFactors[rowIndex][columnIndex]; + gcZ -= (row + 1) * relativeRadiusPower[row + 2] + * (g * cosMLongitude[column] + h * sinMLongitude[column]) + * polynomials[row][column] + * schmidtQuasiNormalFactors[row][column]; } northComponent = static_cast(gcX * cos(latDiffRad) + gcZ * sin(latDiffRad)); eastComponent = gcY; @@ -174,15 +174,15 @@ void GeomagneticField::calculateGeomagneticComponent(double latDiffRad, int64_t } } -void GeomagneticField::getLongitudeTrigonometric() +void GeomagneticField::GetLongitudeTrigonometric() { HiLog::Info(LABEL, "%{public}s begin", __func__); sinMLongitude[0] = 0.0f; cosMLongitude[0] = 1.0f; sinMLongitude[1] = static_cast(sin(geocentricLongitude)); cosMLongitude[1] = static_cast(cos(geocentricLongitude)); - for (int32_t index = 2; index < GAUSSIAN_COEFFICIENT_DIMENSION; ++index) { - int32_t x = index >> 1; + for (uint32_t index = 2; index < GAUSSIAN_COEFFICIENT_DIMENSION; ++index) { + uint32_t x = index >> 1; sinMLongitude[index] = (sinMLongitude[index - x] * cosMLongitude[x] + cosMLongitude[index - x] * sinMLongitude[x]); cosMLongitude[index] = (cosMLongitude[index - x] * cosMLongitude[x] @@ -190,7 +190,7 @@ void GeomagneticField::getLongitudeTrigonometric() } } -void GeomagneticField::getRelativeRadiusPower() +void GeomagneticField::GetRelativeRadiusPower() { HiLog::Info(LABEL, "%{public}s begin", __func__); relativeRadiusPower[0] = 1.0f; @@ -200,20 +200,20 @@ void GeomagneticField::getRelativeRadiusPower() } } -void GeomagneticField::calibrateGeocentricCoordinates(float latitude, float longitude, float altitude) +void GeomagneticField::CalibrateGeocentricCoordinates(float latitude, float longitude, float altitude) { HiLog::Info(LABEL, "%{public}s begin", __func__); float altitudeKm = altitude / CONVERSION_FACTOR; float a2 = EARTH_MAJOR_AXIS_RADIUS * EARTH_MAJOR_AXIS_RADIUS; float b2 = EARTH_MINOR_AXIS_RADIUS * EARTH_MINOR_AXIS_RADIUS; - double gdLatRad = toRadians(latitude); + double gdLatRad = ToRadians(latitude); float clat = static_cast(cos(gdLatRad)); float slat = static_cast(sin(gdLatRad)); float tlat = slat / clat; float latRad = static_cast(sqrt(a2 * clat * clat + b2 * slat * slat)); geocentricLatitude = static_cast(atan(tlat * (latRad * altitudeKm + b2) / (latRad * altitudeKm + a2))); - geocentricLongitude = static_cast(toRadians(longitude)); + geocentricLongitude = static_cast(ToRadians(longitude)); float radSq = altitudeKm * altitudeKm + 2 * altitudeKm * latRad + (a2 * a2 * clat * clat + b2 * b2 * slat * slat) @@ -221,7 +221,7 @@ void GeomagneticField::calibrateGeocentricCoordinates(float latitude, float long geocentricRadius = static_cast(sqrt(radSq)); } -void GeomagneticField::initLegendreTable(int32_t expansionDegree, float thetaRad) +void GeomagneticField::InitLegendreTable(int32_t expansionDegree, float thetaRad) { HiLog::Info(LABEL, "%{public}s begin", __func__); polynomials[0].resize(1); @@ -230,80 +230,88 @@ void GeomagneticField::initLegendreTable(int32_t expansionDegree, float thetaRad polynomialsDerivative[0][0] = 0.0f; float cosValue = static_cast(cos(thetaRad)); float sinValue = static_cast(sin(thetaRad)); - for (int32_t rowIndex = 1; rowIndex <= expansionDegree; rowIndex++) { - polynomials[rowIndex].resize(rowIndex + 1); - polynomialsDerivative[rowIndex].resize(rowIndex + 1); - for (int32_t columnIndex = 0; columnIndex <= rowIndex; columnIndex++) { - if (rowIndex == columnIndex) { - polynomials[rowIndex][columnIndex] = sinValue * polynomials[rowIndex - 1][columnIndex - 1]; - polynomialsDerivative[rowIndex][columnIndex] = cosValue * polynomials[rowIndex - 1][columnIndex - 1] - + sinValue * polynomialsDerivative[rowIndex - 1][columnIndex - 1]; - } else if (rowIndex == 1 || columnIndex == rowIndex - 1) { - polynomials[rowIndex][columnIndex] = cosValue * polynomials[rowIndex - 1][columnIndex]; - polynomialsDerivative[rowIndex][columnIndex] = -sinValue * polynomials[rowIndex - 1][columnIndex] - + cosValue * polynomialsDerivative[rowIndex - 1][columnIndex]; + for (int32_t row = 1; row <= expansionDegree; row++) { + polynomials[row].resize(row + 1); + polynomialsDerivative[row].resize(row + 1); + for (int32_t column = 0; column <= row; column++) { + if (row == column) { + polynomials[row][column] = sinValue * polynomials[row - 1][column - 1]; + polynomialsDerivative[row][column] = cosValue * polynomials[row - 1][column - 1] + + sinValue * polynomialsDerivative[row - 1][column - 1]; + } else if (row == 1 || column == row - 1) { + polynomials[row][column] = cosValue * polynomials[row - 1][column]; + polynomialsDerivative[row][column] = -sinValue * polynomials[row - 1][column] + + cosValue * polynomialsDerivative[row - 1][column]; } else { - float k = ((rowIndex - 1) * (rowIndex - 1) - columnIndex * columnIndex) - / static_cast((2 * rowIndex - 1) * (2 * rowIndex - 3)); - polynomials[rowIndex][columnIndex] = cosValue * polynomials[rowIndex - 1][columnIndex] - - k * polynomials[rowIndex - 2][columnIndex]; - polynomialsDerivative[rowIndex][columnIndex] = -sinValue * polynomials[rowIndex - 1][columnIndex] - + cosValue * polynomialsDerivative[rowIndex - 1][columnIndex] - - k * polynomialsDerivative[rowIndex - 2][columnIndex]; + float k = ((row - 1) * (row - 1) - column * column) + / static_cast((2 * row - 1) * (2 * row - 3)); + polynomials[row][column] = cosValue * polynomials[row - 1][column] + - k * polynomials[row - 2][column]; + polynomialsDerivative[row][column] = -sinValue * polynomials[row - 1][column] + + cosValue * polynomialsDerivative[row - 1][column] + - k * polynomialsDerivative[row - 2][column]; } } } } -float GeomagneticField::obtainX() +float GeomagneticField::ObtainX() { HiLog::Info(LABEL, "%{public}s begin", __func__); + std::lock_guard geomagneticLock(mutex_); return northComponent; } -float GeomagneticField::obtainY() +float GeomagneticField::ObtainY() { HiLog::Info(LABEL, "%{public}s begin", __func__); + std::lock_guard geomagneticLock(mutex_); return eastComponent; } -float GeomagneticField::obtainZ() +float GeomagneticField::ObtainZ() { HiLog::Info(LABEL, "%{public}s begin", __func__); + std::lock_guard geomagneticLock(mutex_); return downComponent; } -float GeomagneticField::obtainGeomagneticDip() +float GeomagneticField::ObtainGeomagneticDip() { - return static_cast(toDegrees(atan2(downComponent, obtainLevelIntensity()))); + std::lock_guard geomagneticLock(mutex_); + float horizontalIntensity = hypot(northComponent, eastComponent); + return static_cast(ToDegrees(atan2(downComponent, horizontalIntensity))); } -double GeomagneticField::toDegrees(double angrad) +double GeomagneticField::ToDegrees(double angrad) { return angrad * 180.0 / M_PI; } -double GeomagneticField::toRadians(double angdeg) +double GeomagneticField::ToRadians(double angdeg) { return angdeg / 180.0 * M_PI; } -float GeomagneticField::obtainDeflectionAngle() +float GeomagneticField::ObtainDeflectionAngle() { HiLog::Info(LABEL, "%{public}s begin", __func__); - return static_cast(toDegrees(atan2(eastComponent, northComponent))); + std::lock_guard geomagneticLock(mutex_); + return static_cast(ToDegrees(atan2(eastComponent, northComponent))); } -float GeomagneticField::obtainLevelIntensity() +float GeomagneticField::ObtainLevelIntensity() { HiLog::Info(LABEL, "%{public}s begin", __func__); + std::lock_guard geomagneticLock(mutex_); float horizontalIntensity = hypot(northComponent, eastComponent); return horizontalIntensity; } -float GeomagneticField::obtainTotalIntensity() +float GeomagneticField::ObtainTotalIntensity() { HiLog::Info(LABEL, "%{public}s begin", __func__); + std::lock_guard geomagneticLock(mutex_); float sumOfSquares = northComponent * northComponent + eastComponent * eastComponent + downComponent * downComponent; float totalIntensity = static_cast(sqrt(sumOfSquares)); diff --git a/interfaces/plugin/BUILD.gn b/interfaces/plugin/BUILD.gn index b59b518441affd68fcc93acc4274f7e992c3882c..6f84c7f7b0087f4ad0c2c051ba0d4acddfc3adb6 100644 --- a/interfaces/plugin/BUILD.gn +++ b/interfaces/plugin/BUILD.gn @@ -21,6 +21,8 @@ ohos_shared_library("sensor") { "//third_party/libuv/include", "//utils/native/base/include", "./include", + "//base/sensors/sensor/utils/include", + "//foundation/arkui/napi/interfaces/inner_api/napi", ] defines = [ "APP_LOG_TAG = \"sensroJs\"", diff --git a/interfaces/plugin/include/async_callback_info.h b/interfaces/plugin/include/async_callback_info.h new file mode 100644 index 0000000000000000000000000000000000000000..fc2922bfce4a2bdd1e003dd153243a972d003f29 --- /dev/null +++ b/interfaces/plugin/include/async_callback_info.h @@ -0,0 +1,134 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef ASYNC_CALLBACK_INFO_H +#define ASYNC_CALLBACK_INFO_H +#include + +#include "napi/native_api.h" +#include "napi/native_node_api.h" +#include "refbase.h" +#include "sensor_agent_type.h" +#include "sensor_log.h" +#include "sensors_errors.h" + +namespace OHOS { +namespace Sensors { +using std::vector; +using std::string; +using namespace OHOS::HiviewDFX; +static constexpr HiLogLabel LABEL = {LOG_CORE, 0xD002708, "SensorJsAPI"}; +constexpr int32_t THREE_DIMENSIONAL_MATRIX_LENGTH = 9; +constexpr static int32_t DATA_LENGTH = 16; +constexpr int32_t CALLBACK_NUM = 3; +enum CallbackDataType { + SUBSCRIBE_FAIL = -2, + FAIL = -1, + OFF_CALLBACK = 0, + ON_CALLBACK = 1, + ONCE_CALLBACK = 2, + GET_GEOMAGNETIC_FIELD = 3, + GET_ALTITUDE = 4, + GET_GEOMAGNITIC_DIP = 5, + GET_ANGLE_MODIFY = 6, + CREATE_ROTATION_MATRIX = 7, + TRANSFORM_COORDINATE_SYSTEM = 8, + CREATE_QUATERNION = 9, + GET_DIRECTION = 10, + ROTATION_INCLINATION_MATRIX = 11, + GET_SENSOR_LIST = 12, + GET_SINGLE_SENSOR = 13, + SUBSCRIBE_CALLBACK = 14, + SUBSCRIBE_COMPASS = 15, + GET_BODY_STATE = 16, +}; + +struct GeomagneticData { + float x; + float y; + float z; + float geomagneticDip; + float deflectionAngle; + float levelIntensity; + float totalIntensity; +}; + +struct RationMatrixData { + float rotationMatrix[THREE_DIMENSIONAL_MATRIX_LENGTH]; + float inclinationMatrix[THREE_DIMENSIONAL_MATRIX_LENGTH]; +}; + +struct SensorData { + int32_t sensorTypeId; + uint32_t dataLength; + float data[DATA_LENGTH]; + int64_t timestamp; +}; + +struct ReserveData { + float reserve[DATA_LENGTH]; + int32_t length; +}; + +union CallbackData { + SensorData sensorData; + GeomagneticData geomagneticData; + RationMatrixData rationMatrixData; + ReserveData reserveData; +}; + +struct BusinessError { + int32_t code; + string message; + string name; + string stack; +}; + +class AsyncCallbackInfo : public RefBase { +public: + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + uv_work_t *work = nullptr; + napi_deferred deferred = nullptr; + napi_ref callback[CALLBACK_NUM] = { 0 }; + CallbackData data; + BusinessError error; + CallbackDataType type; + vector sensorInfos; + + AsyncCallbackInfo(napi_env env, CallbackDataType type) : env(env), type(type) {} + ~AsyncCallbackInfo() + { + CALL_LOG_ENTER; + if (asyncWork != nullptr) { + SEN_HILOGD("Delete async work"); + napi_delete_async_work(env, asyncWork); + } + for (int32_t i = 0; i < CALLBACK_NUM; ++i) { + if (callback[i] != nullptr) { + SEN_HILOGD("Delete reference, i: %{public}d", i); + napi_delete_reference(env, callback[i]); + } + } + if (work != nullptr) { + delete work; + work = nullptr; + } + } + +private: +}; +} // namespace Sensors +} // namespace OHOS +#endif // ASYNC_CALLBACK_INFO_H \ No newline at end of file diff --git a/interfaces/plugin/include/sensor_js.h b/interfaces/plugin/include/sensor_js.h old mode 100755 new mode 100644 index bb38db195807fbbdbf7550c08865ca4246a0fc5f..3f4e8c344e011f882dc3ee2d715afcb6c974d5a2 --- a/interfaces/plugin/include/sensor_js.h +++ b/interfaces/plugin/include/sensor_js.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -14,10 +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 "sensor_agent.h" - -static int32_t UnsubscribeSensor(int32_t sensorTypeId); -static void DataCallbackImpl(SensorEvent *event); -static int32_t SubscribeSensor(int32_t sensorTypeId, int64_t interval, RecordSensorCallback callback); +namespace OHOS { +namespace Sensors { +bool UnsubscribeSensor(int32_t sensorTypeId); +void DataCallbackImpl(SensorEvent *event); +bool 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); +} // namespace Sensors +} // namespace OHOS #endif // SENSOR_JS_H \ No newline at end of file diff --git a/interfaces/plugin/include/sensor_napi_utils.h b/interfaces/plugin/include/sensor_napi_utils.h index 24141c147a30172575ac513a45dcc63345277f2a..469b337085c86360fd56233ca367e61a9faad5d2 100644 --- a/interfaces/plugin/include/sensor_napi_utils.h +++ b/interfaces/plugin/include/sensor_napi_utils.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,142 +16,159 @@ #define SENSOR_NAPI_UTILS_H #include -#include - -#include "napi/native_api.h" -#include "napi/native_node_api.h" - -#include "sensor_agent.h" +#include "async_callback_info.h" +#include "refbase.h" +namespace OHOS { +namespace Sensors { using std::vector; using std::string; - -const int32_t THREE_DIMENSIONAL_MATRIX_LENGTH = 9; -const int32_t FOUR_DIMENSIONAL_MATRIX_LENGTH = 16; -const int32_t QUATERNION_LENGTH = 4; -const int32_t ROTATION_VECTOR_LENGTH = 3; -struct GeomagneticData { - float x; - float y; - float z; - float geomagneticDip; - float deflectionAngle; - float levelIntensity; - float totalIntensity; -}; - -struct RationMatrixData { - float rotationMatrix[THREE_DIMENSIONAL_MATRIX_LENGTH]; - float inclinationMatrix[THREE_DIMENSIONAL_MATRIX_LENGTH]; -}; - -struct SensorData { - int32_t sensorTypeId; - uint32_t dataLength; - float data[16]; - int64_t timestamp; -}; - -struct ReserveData { - float reserve[16]; - int32_t length; -}; - -union CallbackData { - SensorData sensorData; - GeomagneticData geomagneticData; - RationMatrixData rationMatrixData; - ReserveData reserveData; -}; - -struct BusinessError { - int32_t code; - string message; - string name; - string stack; -}; - -typedef enum CallbackDataType { - FAIL = -1, - OFF_CALLBACK = 0, - ON_CALLBACK = 1, - ONCE_CALLBACK = 2, - GET_GEOMAGNETIC_FIELD = 3, - GET_ALTITUDE = 4, - GET_GEOMAGNITIC_DIP = 5, - GET_ANGLE_MODIFY = 6, - CREATE_ROTATION_MATRIX = 7, - TRANSFORM_COORDINATE_SYSTEM = 8, - CREATE_QUATERNION = 9, - GET_DIRECTION = 10, - ROTATION_INCLINATION_MATRIX = 11, - GET_SENSOR_LIST = 12, - GET_SINGLE_SENSOR = 13 -} CallbackDataType; - -struct AsyncCallbackInfo { - napi_env env; - napi_async_work asyncWork; - napi_deferred deferred; - napi_ref callback[1] = { 0 }; - CallbackData data; - BusinessError error; - CallbackDataType type; - vector sensorInfos; -}; - -using ConvertDataFunc = void(*)(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]); - -bool IsNapiValueSame(napi_env env, napi_value lhs, napi_value rhs); - -bool IsMatchType(napi_env env, napi_value value, napi_valuetype type); - -napi_value GetNapiInt32(int32_t number, napi_env env); - -int32_t GetCppInt32(napi_value value, napi_env env); - -bool GetCppBool(napi_value value, napi_env env); - -void EmitAsyncCallbackWork(AsyncCallbackInfo *async_callback_info); - -void EmitUvEventLoop(AsyncCallbackInfo **async_callback_info); - -int64_t GetCppInt64(napi_value value, napi_env env); - -napi_value NapiGetNamedProperty(napi_value jsonObject, string name, napi_env env); - -napi_value GetUndefined(napi_env env); - -void EmitPromiseWork(AsyncCallbackInfo *asyncCallbackInfo); - -bool IsMatchArrayType(napi_env env, napi_value value, napi_typedarray_type type); - -vector GetCppArrayFloat(napi_env env, napi_value value); - -float GetCppFloat(napi_env env, napi_value value); - -napi_value GreateBusinessError(napi_env env, int32_t errCode, string errMessage, +using ConvertDataFunc = bool(*)(const napi_env &env, sptr asyncCallbackInfo, + napi_value result[2]); + +bool IsSameValue(const napi_env &env, const napi_value &lhs, const napi_value &rhs); +bool IsMatchType(const napi_env &env, const napi_value &value, const napi_valuetype &type); +bool IsMatchArrayType(const napi_env &env, const napi_value &value); +bool GetCppInt32(const napi_env &env, const napi_value &value, int32_t &number); +bool GetCppDouble(const napi_env &env, const napi_value &value, double &number); +bool GetCppBool(const napi_env &env, const napi_value &value); +bool GetFloatArray(const napi_env &env, const napi_value &value, vector &array); +bool GetCppInt64(const napi_env &env, const napi_value &value, int64_t &number); +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); +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 IsMatchArrayType(napi_env env, napi_value value); - -void ConvertToFailData(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]); - -void ConvertToNoData(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]); - -void ConvertToGeomagneticData(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]); - -void ConvertToNumber(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]); - -void ConvertToArray(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]); - -void ConvertToRotationMatrix(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]); - -void ConvertToSensorData(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]); - -void CreateNapiArray(napi_env env, float *data, int32_t dataLength, napi_value result); - -void ConvertToSensorInfos(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]); - -void ConvertToSingleSensor(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]); +bool ConvertToFailData(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]); +bool ConvertToGeomagneticData(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]); +bool ConvertToNumber(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]); +bool ConvertToArray(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]); +bool ConvertToRotationMatrix(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]); +bool ConvertToSensorData(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]); +bool CreateNapiArray(const napi_env &env, float *data, int32_t dataLength, napi_value &result); +bool ConvertToSensorInfos(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]); +bool ConvertToSingleSensor(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]); +bool ConvertToBodyData(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]); +bool CreateFailMessage(CallbackDataType type, int32_t code, string message, + sptr &asyncCallbackInfo); +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) + +#define CHKNRF(env, state, message) \ + do { \ + if ((state) != napi_ok) { \ + SEN_HILOGE("(%{public}s) fail", #message); \ + GET_AND_THROW_NAPI_ERROR((env), (message)); \ + return false; \ + } \ + } while (0) + +#define CHKNRV(env, state, message) \ + do { \ + if ((state) != napi_ok) { \ + SEN_HILOGE("(%{public}s) fail", #message); \ + GET_AND_THROW_NAPI_ERROR((env), (message)); \ + return; \ + } \ + } while (0) + +#define CHKNRC(env, state, message) \ + { \ + if ((state) != napi_ok) { \ + SEN_HILOGW("(%{public}s) fail", #message); \ + GET_AND_THROW_NAPI_ERROR((env), (message)); \ + continue; \ + } \ + } +} // namespace Sensors +} // namespace OHOS #endif // SENSOR_NAPI_UTILS_H diff --git a/interfaces/plugin/include/sensor_system_js.h b/interfaces/plugin/include/sensor_system_js.h index 3b8dd9bd2530dfde679813c3a4d9df1324629dff..e8ba56345fd2d03a82a59f5ea362f063a3245cac 100644 --- a/interfaces/plugin/include/sensor_system_js.h +++ b/interfaces/plugin/include/sensor_system_js.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,8 @@ #define SENSOR_SYSTEM_JS_H #include "napi/native_api.h" #include "napi/native_node_api.h" - +namespace OHOS { +namespace Sensors { napi_value SubscribeAccelerometer(napi_env env, napi_callback_info info); napi_value UnsubscribeAccelerometer(napi_env env, napi_callback_info info); napi_value SubscribeCompass(napi_env env, napi_callback_info info); @@ -44,5 +45,6 @@ napi_value SubscribeMagnetic(napi_env env, napi_callback_info info); napi_value UnsubscribeMagnetic(napi_env env, napi_callback_info info); napi_value SubscribeHall(napi_env env, napi_callback_info info); napi_value UnsubscribeHall(napi_env env, napi_callback_info info); - +} // namespace Sensors +} // namespace OHOS #endif // SENSOR_SYSTEM_JS_H \ No newline at end of file diff --git a/interfaces/plugin/src/sensor_js.cpp b/interfaces/plugin/src/sensor_js.cpp index 64f6a848b7a10c021b29c4714163db8e7559e6ef..d98c24d32bfef706261a4b89b4445dd81a14916b 100644 --- a/interfaces/plugin/src/sensor_js.cpp +++ b/interfaces/plugin/src/sensor_js.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -14,6 +14,7 @@ */ #include "sensor_js.h" +#include #include #include #include @@ -25,160 +26,230 @@ #include #include "geomagnetic_field.h" - -#include "hilog/log.h" -#include "napi/native_api.h" -#include "napi/native_node_api.h" #include "refbase.h" #include "securec.h" -#include "sensor_agent.h" #include "sensor_algorithm.h" #include "sensor_napi_utils.h" #include "sensor_system_js.h" +namespace OHOS { +namespace Sensors { +namespace { +constexpr int32_t QUATERNION_LENGTH = 4; +constexpr int32_t ROTATION_VECTOR_LENGTH = 3; +constexpr int32_t REPORTING_INTERVAL = 200000000; +constexpr int32_t INVALID_SENSOR_ID = -1; +constexpr int32_t SENSOR_SUBSCRIBE_FAILURE = 1001; +constexpr int32_t INPUT_ERROR = 202; +constexpr float BODY_STATE_EXCEPT = 1.0f; +constexpr float THREESHOLD = 0.000001f; +} +static std::map g_samplingPeriod = { + {"normal", 200000000}, + {"ui", 60000000}, + {"game", 20000000}, +}; +static std::mutex mutex_; +static std::mutex bodyMutex_; +static float g_bodyState = -1.0f; +static std::map> g_subscribeCallbacks; +static std::mutex onMutex_; +static std::mutex onceMutex_; +static std::map>> g_onceCallbackInfos; +static std::map>> g_onCallbackInfos; -using namespace OHOS::HiviewDFX; -static constexpr HiLogLabel LABEL = {LOG_CORE, 0xD002708, "SensorJsAPI"}; - -static std::map g_onceCallbackInfos; -static std::map> g_onCallbackInfos; +static bool CheckSubscribe(int32_t sensorTypeId) +{ + std::lock_guard onCallbackLock(onMutex_); + auto iter = g_onCallbackInfos.find(sensorTypeId); + CHKCF((iter != g_onCallbackInfos.end()), "No client subscribe"); + return true; +} -static void DataCallbackImpl(SensorEvent *event) +static bool copySensorData(sptr callbackInfo, SensorEvent *event) { - HiLog::Info(LABEL, "%{public}s in", __func__); - if (event == nullptr) { - HiLog::Error(LABEL, "%{public}s event is null!", __func__); - return; + CHKPF(callbackInfo); + CHKPF(event); + int32_t sensorTypeId = event->sensorTypeId; + callbackInfo->data.sensorData.sensorTypeId = sensorTypeId; + callbackInfo->data.sensorData.dataLength = event->dataLen; + callbackInfo->data.sensorData.timestamp = event->timestamp; + auto data = reinterpret_cast(event->data); + if (sensorTypeId == SENSOR_TYPE_ID_WEAR_DETECTION && callbackInfo->type == SUBSCRIBE_CALLBACK) { + std::lock_guard onBodyLock(bodyMutex_); + g_bodyState = *data; + callbackInfo->data.sensorData.data[0] = + (fabs(g_bodyState - BODY_STATE_EXCEPT) < THREESHOLD) ? true : false; + return true; + } + CHKPF(data); + if (memcpy_s(callbackInfo->data.sensorData.data, event->dataLen, data, event->dataLen) != EOK) { + SEN_HILOGE("Copy data failed"); + return false; } + return true; +} + +static bool CheckSystemSubscribe(int32_t sensorTypeId) +{ + std::lock_guard subscribeLock(mutex_); + auto iter = g_subscribeCallbacks.find(sensorTypeId); + CHKCF((iter != g_subscribeCallbacks.end()), "No client subscribe"); + return true; +} + +static void EmitSubscribeCallback(SensorEvent *event) +{ + CHKPV(event); int32_t sensorTypeId = event->sensorTypeId; - float *data = (float *)(event->data); - if (g_onCallbackInfos.find(sensorTypeId) != g_onCallbackInfos.end()) { - for (uint32_t i = 0; i < g_onCallbackInfos[sensorTypeId].size(); ++i) { - g_onCallbackInfos[sensorTypeId][i]->data.sensorData.sensorTypeId = sensorTypeId; - g_onCallbackInfos[sensorTypeId][i]->data.sensorData.dataLength = event->dataLen; - g_onCallbackInfos[sensorTypeId][i]->data.sensorData.timestamp = event->timestamp; - errno_t ret = memcpy_s(g_onCallbackInfos[sensorTypeId][i]->data.sensorData.data, - event->dataLen, data, event->dataLen); - if (ret != EOK) { - HiLog::Error(LABEL, "%{public}s copy data failed", __func__); - return; - } - g_onCallbackInfos[sensorTypeId][i]->type = ON_CALLBACK; - EmitUvEventLoop(&g_onCallbackInfos[sensorTypeId][i]); + CHKCV(CheckSystemSubscribe(sensorTypeId), "No client subscribe"); + + std::lock_guard subscribeLock(mutex_); + auto callback = g_subscribeCallbacks[sensorTypeId]; + CHKCV(copySensorData(callback, event), "Copy sensor data failed"); + EmitUvEventLoop(callback); +} + +static void EmitOnCallback(SensorEvent *event) +{ + CHKPV(event); + int32_t sensorTypeId = event->sensorTypeId; + CHKCV(CheckSubscribe(sensorTypeId), "No client subscribe"); + + std::lock_guard onCallbackLock(onMutex_); + auto onCallbackInfos = g_onCallbackInfos[sensorTypeId]; + for (auto &onCallbackInfo : onCallbackInfos) { + if (!copySensorData(onCallbackInfo, event)) { + SEN_HILOGE("Copy sensor data failed"); + continue; } + EmitUvEventLoop(onCallbackInfo); } +} - if (g_onceCallbackInfos.find(sensorTypeId) == g_onceCallbackInfos.end()) { - HiLog::Debug(LABEL, "%{public}s no subscribe to the sensor data once", __func__); - return; - } - struct AsyncCallbackInfo *onceCallbackInfo = g_onceCallbackInfos[sensorTypeId]; - onceCallbackInfo->data.sensorData.sensorTypeId = sensorTypeId; - onceCallbackInfo->data.sensorData.dataLength = event->dataLen; - onceCallbackInfo->data.sensorData.timestamp = event->timestamp; - errno_t ret = memcpy_s(onceCallbackInfo->data.sensorData.data, event->dataLen, data, event->dataLen); - if (ret != EOK) { - HiLog::Error(LABEL, "%{public}s copy data failed", __func__); - return; - } - onceCallbackInfo->type = ONCE_CALLBACK; - EmitUvEventLoop(&g_onceCallbackInfos[sensorTypeId]); - if (g_onCallbackInfos.find(sensorTypeId) == g_onCallbackInfos.end()) { - HiLog::Debug(LABEL, "%{public}s no subscription to change sensor data, need to cancel registration", __func__); - UnsubscribeSensor(sensorTypeId); +static void EmitOnceCallback(SensorEvent *event) +{ + CHKPV(event); + int32_t sensorTypeId = event->sensorTypeId; + std::lock_guard onceCallbackLock(onceMutex_); + auto iter = g_onceCallbackInfos.find(sensorTypeId); + CHKCV((iter != g_onceCallbackInfos.end()), "No client subscribe once"); + + auto onceCallbackInfos = g_onceCallbackInfos[sensorTypeId]; + for (auto &onceCallbackInfo : onceCallbackInfos) { + if (!copySensorData(onceCallbackInfo, event)) { + SEN_HILOGE("Copy sensor data failed"); + continue; + } + EmitUvEventLoop(onceCallbackInfo); } + g_onceCallbackInfos[sensorTypeId].clear(); g_onceCallbackInfos.erase(sensorTypeId); - HiLog::Info(LABEL, "%{public}s end", __func__); + + CHKCV((!CheckSubscribe(sensorTypeId)), "Has client subscribe, not need cancel subscribe"); + CHKCV((!CheckSystemSubscribe(sensorTypeId)), "Has client subscribe system api, not need cancel subscribe"); + UnsubscribeSensor(sensorTypeId); } -static const SensorUser user = { +void DataCallbackImpl(SensorEvent *event) +{ + CHKPV(event); + EmitOnCallback(event); + EmitSubscribeCallback(event); + EmitOnceCallback(event); +} + +const SensorUser user = { .callback = DataCallbackImpl }; -static int32_t UnsubscribeSensor(int32_t sensorTypeId) +bool UnsubscribeSensor(int32_t sensorTypeId) { - HiLog::Info(LABEL, "%{public}s in", __func__); - int32_t ret = DeactivateSensor(sensorTypeId, &user); - if (ret < 0) { - HiLog::Error(LABEL, "%{public}s DeactivateSensor failed", __func__); - return ret; - } - ret = UnsubscribeSensor(sensorTypeId, &user); - if (ret < 0) { - HiLog::Error(LABEL, "%{public}s UnsubscribeSensor failed", __func__); - return ret; - } - HiLog::Info(LABEL, "%{public}s left", __func__); - return 0; + CALL_LOG_ENTER; + CHKCF((DeactivateSensor(sensorTypeId, &user) == SUCCESS), "DeactivateSensor failed"); + CHKCF((UnsubscribeSensor(sensorTypeId, &user) == SUCCESS), "UnsubscribeSensor failed"); + return true; } -static int32_t SubscribeSensor(int32_t sensorTypeId, int64_t interval, RecordSensorCallback callback) +bool SubscribeSensor(int32_t sensorTypeId, int64_t interval, RecordSensorCallback callback) { - HiLog::Info(LABEL, "%{public}s in, sensorTypeId: %{public}d", __func__, sensorTypeId); - int32_t ret = SubscribeSensor(sensorTypeId, &user); - if (ret < 0) { - HiLog::Error(LABEL, "%{public}s subscribeSensor failed", __func__); - return ret; - } - ret = SetBatch(sensorTypeId, &user, interval, 0); - if (ret < 0) { - HiLog::Error(LABEL, "%{public}s set batch failed", __func__); - return ret; + CALL_LOG_ENTER; + CHKCF((SubscribeSensor(sensorTypeId, &user) == ERR_OK), "SubscribeSensor failed"); + CHKCF((SetBatch(sensorTypeId, &user, interval, 0) == ERR_OK), "Set batch failed"); + CHKCF((ActivateSensor(sensorTypeId, &user) == ERR_OK), "ActivateSensor failed"); + return true; +} + +static bool IsOnceSubscribed(napi_env env, int32_t sensorTypeId, napi_value callback) +{ + CALL_LOG_ENTER; + if (auto iter = g_onceCallbackInfos.find(sensorTypeId); iter == g_onceCallbackInfos.end()) { + SEN_HILOGW("already subscribed, sensorTypeId: %{public}d", sensorTypeId); + return false; } - ret = ActivateSensor(sensorTypeId, &user); - if (ret < 0) { - HiLog::Error(LABEL, "%{public}s activateSensor failed", __func__); - return ret; + + std::vector> callbackInfos = g_onceCallbackInfos[sensorTypeId]; + for (auto callbackInfo : callbackInfos) { + CHKNCC(env, (callbackInfo != nullptr), "callbackInfo is null"); + napi_value sensorCallback = nullptr; + CHKNRF(env, napi_get_reference_value(env, callbackInfo->callback[0], &sensorCallback), + "napi_get_reference_value"); + if (IsSameValue(env, callback, sensorCallback)) { + return true; + } } - return 0; + return false; +} + +static void UpdateOnceCallback(napi_env env, int32_t sensorTypeId, napi_value callback) +{ + CALL_LOG_ENTER; + std::lock_guard onceCallbackLock(onceMutex_); + CHKNCV(env, !IsOnceSubscribed(env, sensorTypeId, callback), "The callback has been subscribed"); + + sptr asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo(env, ONCE_CALLBACK); + CHKPV(asyncCallbackInfo); + CHKNRV(env, napi_create_reference(env, callback, 1, &asyncCallbackInfo->callback[0]), + "napi_create_reference"); + std::vector> callbackInfos = g_onceCallbackInfos[sensorTypeId]; + callbackInfos.push_back(asyncCallbackInfo); + g_onceCallbackInfos[sensorTypeId] = callbackInfos; } static napi_value Once(napi_env env, napi_callback_info info) { - HiLog::Info(LABEL, "%{public}s in", __func__); + CALL_LOG_ENTER; size_t argc = 2; napi_value args[2] = { 0 }; napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, NULL)); + CHKNRP(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr), "napi_get_cb_info"); + CHKNCP(env, (argc == 2), "The number of parameters is not valid"); + CHKNCP(env, IsMatchType(env, args[0], napi_number), "Wrong argument type, should be number"); + CHKNCP(env, IsMatchType(env, args[1], napi_function), "Wrong argument type, should be function"); + int32_t sensorTypeId = INVALID_SENSOR_ID; + CHKNCP(env, GetCppInt32(env, args[0], sensorTypeId), "Wrong argument type, get number fail"); - if (argc != 2) { - HiLog::Error(LABEL, "%{public}s Invalid input, number of argument should be two", __func__); - 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"); } - if (!IsMatchType(env, args[0], napi_number) || !IsMatchType(env, args[1], napi_function)) { - HiLog::Error(LABEL, "%{public}s argument is invalid", __func__); - return nullptr; - } - int32_t sensorTypeId = GetCppInt32(args[0], env); - AsyncCallbackInfo *asyncCallbackInfo = new AsyncCallbackInfo { - .env = env, - .asyncWork = nullptr, - .deferred = nullptr, - }; - napi_create_reference(env, args[1], 1, &asyncCallbackInfo->callback[0]); - g_onceCallbackInfos[sensorTypeId] = asyncCallbackInfo; - if (g_onCallbackInfos.find(sensorTypeId) == g_onCallbackInfos.end()) { - HiLog::Debug(LABEL, "%{public}s no subscription to change sensor data, registration is required", __func__); - int32_t ret = SubscribeSensor(sensorTypeId, 200000000, DataCallbackImpl); - if (ret < 0) { - HiLog::Error(LABEL, "%{public}s subscribe Sensor failed", __func__); - g_onceCallbackInfos.erase(sensorTypeId); - return nullptr; - } - } - HiLog::Info(LABEL, "%{public}s left", __func__); + UpdateOnceCallback(env, sensorTypeId, args[1]); return nullptr; } static bool IsSubscribed(napi_env env, int32_t sensorTypeId, napi_value callback) { - if (g_onCallbackInfos.find(sensorTypeId) == g_onCallbackInfos.end()) { + CALL_LOG_ENTER; + if (auto iter = g_onCallbackInfos.find(sensorTypeId); iter == g_onCallbackInfos.end()) { + SEN_HILOGW("no client subscribe, sensorTypeId: %{public}d", sensorTypeId); return false; } - std::vector callbackInfos = g_onCallbackInfos[sensorTypeId]; + std::vector> callbackInfos = g_onCallbackInfos[sensorTypeId]; for (auto callbackInfo : callbackInfos) { + CHKNCC(env, (callbackInfo != nullptr), "callbackInfo is null"); napi_value sensorCallback = nullptr; - napi_get_reference_value(env, callbackInfo->callback[0], &sensorCallback); - if (IsNapiValueSame(env, callback, sensorCallback)) { + CHKNRF(env, napi_get_reference_value(env, callbackInfo->callback[0], &sensorCallback), + "napi_get_reference_value"); + if (IsSameValue(env, callback, sensorCallback)) { return true; } } @@ -187,90 +258,70 @@ static bool IsSubscribed(napi_env env, int32_t sensorTypeId, napi_value callback static void UpdateCallbackInfos(napi_env env, int32_t sensorTypeId, napi_value callback) { - if (IsSubscribed(env, sensorTypeId, callback)) { - HiLog::Debug(LABEL, "%{public}s the callback has been subscribed", __func__); - return; - } - AsyncCallbackInfo *asyncCallbackInfo = new AsyncCallbackInfo { - .env = env, - .asyncWork = nullptr, - .deferred = nullptr, - .type = ON_CALLBACK, - }; - napi_create_reference(env, callback, 1, &asyncCallbackInfo->callback[0]); - std::vector callbackInfos = g_onCallbackInfos[sensorTypeId]; + CALL_LOG_ENTER; + std::lock_guard onCallbackLock(onMutex_); + CHKNCV(env, !IsSubscribed(env, sensorTypeId, callback), "This callback has been subscribed"); + sptr asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo(env, ON_CALLBACK); + CHKPV(asyncCallbackInfo); + CHKNRV(env, napi_create_reference(env, callback, 1, &asyncCallbackInfo->callback[0]), + "napi_create_reference"); + std::vector> callbackInfos = g_onCallbackInfos[sensorTypeId]; callbackInfos.push_back(asyncCallbackInfo); g_onCallbackInfos[sensorTypeId] = callbackInfos; } static napi_value On(napi_env env, napi_callback_info info) { - HiLog::Debug(LABEL, "%{public}s in", __func__); + CALL_LOG_ENTER; size_t argc = 3; napi_value args[3] = { 0 }; napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, NULL)); - if (argc <= 1 || argc > 3) { - HiLog::Error(LABEL, "%{public}s the number of input parameters does not match", __func__); - return nullptr; - } - if (!IsMatchType(env, args[0], napi_number) || !IsMatchType(env, args[1], napi_function)) { - HiLog::Error(LABEL, "%{public}s the first parameter should be napi_number type", __func__); - return nullptr; - } - int32_t sensorTypeId = GetCppInt32(args[0], env); - int64_t interval = 200000000; + CHKNRP(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr), "napi_get_cb_info"); + CHKNCP(env, ((argc == 2) || (argc == 3)), "The number of parameters is not valid"); + CHKNCP(env, IsMatchType(env, args[0], napi_number), "Wrong argument type, should be number"); + CHKNCP(env, IsMatchType(env, args[1], napi_function), "Wrong argument type, should be function"); + + int32_t sensorTypeId = INVALID_SENSOR_ID; + CHKNCP(env, GetCppInt32(env, args[0], sensorTypeId), "Wrong argument type, get number fail"); + int64_t interval = REPORTING_INTERVAL; + if (argc == 3) { - napi_value value = NapiGetNamedProperty(args[2], "interval", env); - if (!IsMatchType(env, value, napi_number)) { - HiLog::Error(LABEL, "%{public}s argument should be napi_number type!", __func__); - return nullptr; - } - interval = GetCppInt64(value, env); - HiLog::Debug(LABEL, "%{public}s interval is %{public}lld", __func__, interval); - } - int32_t ret = SubscribeSensor(sensorTypeId, interval, DataCallbackImpl); - if (ret < 0) { - HiLog::Error(LABEL, "%{public}s subscribeSensor failed", __func__); - return nullptr; + napi_value value = GetNamedProperty(env, args[2], "interval"); + CHKNCP(env, IsMatchType(env, value, napi_number), "Wrong argument type, interval should be number"); + CHKNCP(env, GetCppInt64(env, value, interval), "Wrong argument type, get INT64 number fail"); + SEN_HILOGD("Interval is %{public}" PRId64, interval); } + CHKNCP(env, SubscribeSensor(sensorTypeId, interval, DataCallbackImpl), "SubscribeSensor failed"); UpdateCallbackInfos(env, sensorTypeId, args[1]); - HiLog::Debug(LABEL, "%{public}s end", __func__); return nullptr; } static void RemoveAllCallback(napi_env env, int32_t sensorTypeId) { - std::vector callbackInfos = g_onCallbackInfos[sensorTypeId]; - for (auto callbackInfo : callbackInfos) { - napi_delete_reference(env, callbackInfo->callback[0]); - callbackInfo->callback[0] = nullptr; - delete callbackInfo; - callbackInfo = nullptr; - } + CALL_LOG_ENTER; + std::lock_guard onCallbackLock(onMutex_); + g_onCallbackInfos[sensorTypeId].clear(); g_onCallbackInfos.erase(sensorTypeId); } static uint32_t RemoveCallback(napi_env env, int32_t sensorTypeId, napi_value callback) { - std::vector callbackInfos = g_onCallbackInfos[sensorTypeId]; - std::vector::iterator iter; - for (iter = callbackInfos.begin(); iter != callbackInfos.end(); iter++) { - if (*iter == nullptr || (*iter)->callback[0] == nullptr) { - continue; - } + CALL_LOG_ENTER; + std::lock_guard onCallbackLock(onMutex_); + std::vector> callbackInfos = g_onCallbackInfos[sensorTypeId]; + for (auto iter = callbackInfos.begin(); iter != callbackInfos.end(); ++iter) { + CHKPC(*iter); napi_value sensorCallback = nullptr; - napi_get_reference_value(env, (*iter)->callback[0], &sensorCallback); - if (IsNapiValueSame(env, callback, sensorCallback)) { - napi_delete_reference(env, (*iter)->callback[0]); - (*iter)->callback[0] = nullptr; - delete *iter; - *iter = nullptr; - callbackInfos.erase(iter); + CHKNRC(env, napi_get_reference_value(env, (*iter)->callback[0], &sensorCallback), + "napi_get_reference_value"); + if (IsSameValue(env, callback, sensorCallback)) { + callbackInfos.erase(iter++); + SEN_HILOGD("Remove callback success"); break; } } if (callbackInfos.empty()) { + SEN_HILOGD("No subscription to change sensor data"); g_onCallbackInfos.erase(sensorTypeId); return 0; } @@ -280,524 +331,484 @@ static uint32_t RemoveCallback(napi_env env, int32_t sensorTypeId, napi_value ca static napi_value Off(napi_env env, napi_callback_info info) { - HiLog::Info(LABEL, "%{public}s in", __func__); + CALL_LOG_ENTER; size_t argc = 2; napi_value args[2] = { 0 }; napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, NULL)); - if (argc < 1 || argc > 2 || !IsMatchType(env, args[0], napi_number)) { - HiLog::Error(LABEL, "%{public}s Invalid input.", __func__); - return nullptr; - } - int32_t sensorTypeId = GetCppInt32(args[0], env); - if (g_onCallbackInfos.find(sensorTypeId) == g_onCallbackInfos.end() - || (argc == 2 && !IsSubscribed(env, sensorTypeId, args[1]))) { - HiLog::Error(LABEL, "%{public}s should subscribe first", __func__); - return nullptr; - } - if (argc == 2 && RemoveCallback(env, sensorTypeId, args[1]) != 0) { - HiLog::Debug(LABEL, "%{public}s there are other client registrations as well", __func__); - return nullptr; - } + CHKNRP(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr), "napi_get_cb_info"); + CHKNCP(env, ((argc == 1) || (argc == 2)), "The number of parameters is not valid"); + CHKNCP(env, IsMatchType(env, args[0], napi_number), "Wrong argument type, should be number"); + int32_t sensorTypeId = INVALID_SENSOR_ID; + CHKNCP(env, GetCppInt32(env, args[0], sensorTypeId), "Wrong argument type, get number fail"); + CHKNCP(env, (CheckSubscribe(sensorTypeId)), "Should subscribe first"); + if (argc == 1) { RemoveAllCallback(env, sensorTypeId); + } else { + CHKNCP(env, IsMatchType(env, args[1], napi_function), "Wrong argument type, should be function"); + CHKNCP(env, (RemoveCallback(env, sensorTypeId, args[1]) == 0), + "There are other client subscribe as well, not need unsubscribe"); } - int32_t ret = UnsubscribeSensor(sensorTypeId); - if (ret < 0) { - HiLog::Error(LABEL, "%{public}s UnsubscribeSensor failed", __func__); + 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"); return nullptr; } static napi_value GetGeomagneticField(napi_env env, napi_callback_info info) { - HiLog::Info(LABEL, "%{public}s in", __func__); + CALL_LOG_ENTER; size_t argc = 3; napi_value args[3] = { 0 }; napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr)); - if (argc < 2 || argc > 3) { - HiLog::Error(LABEL, "%{public}s the number of input parameters does not match.", __func__); - return nullptr; - } - if (!IsMatchType(env, args[0], napi_object) || !IsMatchType(env, args[1], napi_number)) { - HiLog::Error(LABEL, "%{public}s argument is invalid.", __func__); - return nullptr; - } - napi_value napiLatitude = NapiGetNamedProperty(args[0], "latitude", env); + CHKNRP(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr), "napi_get_cb_info"); + CHKNCP(env, ((argc == 2) || (argc == 3)), "The number of parameters is not valid"); + CHKNCP(env, IsMatchType(env, args[0], napi_object), "Wrong argument type, should be object"); + CHKNCP(env, IsMatchType(env, args[1], napi_number), "Wrong argument type, should be number"); + + napi_value napiLatitude = GetNamedProperty(env, args[0], "latitude"); + CHKNCP(env, (napiLatitude != nullptr), "napiLatitude is null"); double latitude = 0; - napi_get_value_double(env, napiLatitude, &latitude); - napi_value napiLongitude = NapiGetNamedProperty(args[0], "longitude", env); + CHKNCP(env, GetCppDouble(env, napiLatitude, latitude), "Get latitude fail"); + napi_value napiLongitude = GetNamedProperty(env, args[0], "longitude"); + CHKNCP(env, (napiLongitude != nullptr), "napiLongitude is null"); double longitude = 0; - napi_get_value_double(env, napiLongitude, &longitude); - napi_value napiAltitude = NapiGetNamedProperty(args[0], "altitude", env); + CHKNCP(env, GetCppDouble(env, napiLongitude, longitude), "Get longitude fail"); + napi_value napiAltitude = GetNamedProperty(env, args[0], "altitude"); + CHKNCP(env, (napiAltitude != nullptr), "napiAltitude is null"); double altitude = 0; - napi_get_value_double(env, napiAltitude, &altitude); + CHKNCP(env, GetCppDouble(env, napiAltitude, altitude), "Get altitude fail"); int64_t timeMillis = 0; - timeMillis = GetCppInt64(args[1], env); + CHKNCP(env, GetCppInt64(env, args[1], timeMillis), "Get timeMillis fail"); GeomagneticField geomagneticField(latitude, longitude, altitude, timeMillis); - AsyncCallbackInfo *asyncCallbackInfo = new AsyncCallbackInfo { - .env = env, - .asyncWork = nullptr, - .deferred = nullptr, - .type = GET_GEOMAGNETIC_FIELD, - }; + sptr asyncCallbackInfo = + new (std::nothrow) AsyncCallbackInfo(env, GET_GEOMAGNETIC_FIELD); + CHKPP(asyncCallbackInfo); asyncCallbackInfo->data.geomagneticData = { - .x = geomagneticField.obtainX(), - .y = geomagneticField.obtainY(), - .z = geomagneticField.obtainZ(), - .geomagneticDip = geomagneticField.obtainGeomagneticDip(), - .deflectionAngle = geomagneticField.obtainDeflectionAngle(), - .levelIntensity = geomagneticField.obtainLevelIntensity(), - .totalIntensity = geomagneticField.obtainTotalIntensity(), + .x = geomagneticField.ObtainX(), + .y = geomagneticField.ObtainY(), + .z = geomagneticField.ObtainZ(), + .geomagneticDip = geomagneticField.ObtainGeomagneticDip(), + .deflectionAngle = geomagneticField.ObtainDeflectionAngle(), + .levelIntensity = geomagneticField.ObtainLevelIntensity(), + .totalIntensity = geomagneticField.ObtainTotalIntensity(), }; + if (argc == 2) { - napi_deferred deferred = nullptr; napi_value promise = nullptr; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - asyncCallbackInfo->deferred = deferred; + CHKNRP(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise), + "napi_create_promise"); EmitPromiseWork(asyncCallbackInfo); return promise; } - if (!IsMatchType(env, args[2], napi_function)) { - HiLog::Error(LABEL, "%{public}s argument should be function type", __func__); - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - return nullptr; - } - napi_create_reference(env, args[2], 1, &asyncCallbackInfo->callback[0]); + CHKNCP(env, IsMatchType(env, args[2], napi_function), "Wrong argument type, should be function"); + CHKNRP(env, napi_create_reference(env, args[2], 1, &asyncCallbackInfo->callback[0]), + "napi_create_reference"); EmitAsyncCallbackWork(asyncCallbackInfo); return nullptr; } static napi_value TransformCoordinateSystem(napi_env env, napi_callback_info info) { + CALL_LOG_ENTER; size_t argc = 3; napi_value args[3] = { 0 }; napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr)); - if (argc < 2 || argc > 3 || !IsMatchArrayType(env, args[0]) || !IsMatchType(env, args[1], napi_object)) { - HiLog::Error(LABEL, "%{public}s the number of input parameters does not match", __func__); - return nullptr; - } - std::vector inRotationVector = GetCppArrayFloat(env, args[0]); - napi_value napiAxisX = NapiGetNamedProperty(args[1], "axisX", env); - napi_value napiAxisY = NapiGetNamedProperty(args[1], "axisY", env); - if ((!IsMatchType(env, napiAxisX, napi_number)) || (!IsMatchType(env, napiAxisY, napi_number))) { - HiLog::Error(LABEL, "%{public}s argument should be napi_number type!", __func__); - return nullptr; - } - int32_t axisX = GetCppInt32(napiAxisX, env); - int32_t axisY = GetCppInt32(napiAxisY, env); - AsyncCallbackInfo *asyncCallbackInfo = new AsyncCallbackInfo { - .env = env, - .asyncWork = nullptr, - .deferred = nullptr, - .type = TRANSFORM_COORDINATE_SYSTEM, - }; - int32_t inRotationVectorLength = static_cast(inRotationVector.size()); - std::vector outRotationVector(inRotationVectorLength); - std::unique_ptr sensorAlgorithm = std::make_unique(); - int32_t ret = sensorAlgorithm->transformCoordinateSystem(inRotationVector, axisX, axisY, outRotationVector); - if (ret < 0) { - HiLog::Error(LABEL, "%{public}s EmitPromiseWork failed", __func__); + CHKNRP(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr), "napi_get_cb_info"); + CHKNCP(env, ((argc == 2) || (argc == 3)), "The number of parameters is not valid"); + CHKNCP(env, IsMatchArrayType(env, args[0]), "Wrong argument type, should be array"); + CHKNCP(env, IsMatchType(env, args[1], napi_object), "Wrong argument type, should be object"); + + std::vector inRotationVector; + CHKNCP(env, GetFloatArray(env, args[0], inRotationVector), "Wrong argument type, get inRotationVector fail"); + napi_value napiAxisX = GetNamedProperty(env, args[1], "axisX"); + CHKNCP(env, (napiAxisX != nullptr), "napiAxisX is null"); + int32_t axisX = 0; + CHKNCP(env, GetCppInt32(env, napiAxisX, axisX), "Get axisY fail"); + napi_value napiAxisY = GetNamedProperty(env, args[1], "axisY"); + CHKNCP(env, (napiAxisY != nullptr), "napiAxisY is null"); + int32_t axisY = 0; + CHKNCP(env, GetCppInt32(env, napiAxisY, axisY), "Get axisY fail"); + + sptr asyncCallbackInfo = + new (std::nothrow) AsyncCallbackInfo(env, TRANSFORM_COORDINATE_SYSTEM); + CHKPP(asyncCallbackInfo); + size_t length = inRotationVector.size(); + std::vector outRotationVector(length); + SensorAlgorithm sensorAlgorithm; + int32_t ret = sensorAlgorithm.transformCoordinateSystem(inRotationVector, axisX, axisY, outRotationVector); + if (ret != OHOS::ERR_OK) { + SEN_HILOGE("Transform coordinate system fail"); asyncCallbackInfo->type = FAIL; asyncCallbackInfo->error.code = ret; } else { - for (int32_t i = 0; i < inRotationVectorLength; i++) { + for (size_t i = 0; i < length; ++i) { asyncCallbackInfo->data.reserveData.reserve[i] = outRotationVector[i]; } - asyncCallbackInfo->data.reserveData.length = inRotationVectorLength; + asyncCallbackInfo->data.reserveData.length = static_cast(length); } if (argc == 2) { - napi_deferred deferred = nullptr; napi_value promise = nullptr; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - asyncCallbackInfo->deferred = deferred; + CHKNRP(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise), "napi_create_promise"); EmitPromiseWork(asyncCallbackInfo); return promise; } - if (!IsMatchType(env, args[2], napi_function)) { - HiLog::Error(LABEL, "%{public}s argument should be napi_function type!", __func__); - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - return nullptr; - } - napi_create_reference(env, args[2], 1, &asyncCallbackInfo->callback[0]); + CHKNCP(env, IsMatchType(env, args[2], napi_function), "Wrong argument type, should be function"); + CHKNRP(env, napi_create_reference(env, args[2], 1, &asyncCallbackInfo->callback[0]), + "napi_create_reference"); EmitAsyncCallbackWork(asyncCallbackInfo); return nullptr; } static napi_value GetAngleModify(napi_env env, napi_callback_info info) { + CALL_LOG_ENTER; size_t argc = 3; napi_value args[3] = { 0 }; napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr)); - if (argc < 2 || argc > 4 || !IsMatchArrayType(env, args[0]) || !IsMatchArrayType(env, args[1])) { - HiLog::Info(LABEL, "%{public}s argument error", __func__); - return nullptr; - } - AsyncCallbackInfo *asyncCallbackInfo = new AsyncCallbackInfo { - .env = env, - .asyncWork = nullptr, - .deferred = nullptr, - .type = GET_ANGLE_MODIFY, - }; - std::vector curRotationVector = GetCppArrayFloat(env, args[0]); - std::vector preRotationVector = GetCppArrayFloat(env, args[1]); + CHKNRP(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr), "napi_get_cb_info"); + CHKNCP(env, ((argc == 2) || (argc == 3)), "The number of parameters is not valid"); + CHKNCP(env, IsMatchArrayType(env, args[0]), "Wrong argument type, the first parameter should be array"); + CHKNCP(env, IsMatchArrayType(env, args[1]), "Wrong argument type, the second parameter should be array"); + + sptr asyncCallbackInfo = + new (std::nothrow) AsyncCallbackInfo(env, GET_ANGLE_MODIFY); + CHKPP(asyncCallbackInfo); + std::vector curRotationVector; + CHKNCP(env, GetFloatArray(env, args[0], curRotationVector), "Wrong argument type, get curRotationVector fail"); + std::vector preRotationVector; + CHKNCP(env, GetFloatArray(env, args[1], preRotationVector), "Wrong argument type, get preRotationVector fail"); + std::vector angleChange(ROTATION_VECTOR_LENGTH); - std::unique_ptr sensorAlgorithm = std::make_unique(); - int32_t ret = sensorAlgorithm->getAngleModify(curRotationVector, preRotationVector, angleChange); - if (ret < 0) { - HiLog::Error(LABEL, "%{public}s failed", __func__); + SensorAlgorithm sensorAlgorithm; + int32_t ret = sensorAlgorithm.getAngleModify(curRotationVector, preRotationVector, angleChange); + if (ret != OHOS::ERR_OK) { + SEN_HILOGE("Get angle modify fail"); asyncCallbackInfo->type = FAIL; asyncCallbackInfo->error.code = ret; } else { asyncCallbackInfo->data.reserveData.length = ROTATION_VECTOR_LENGTH; - for (int32_t i = 0; i < ROTATION_VECTOR_LENGTH; i++) { + for (int32_t i = 0; i < ROTATION_VECTOR_LENGTH; ++i) { asyncCallbackInfo->data.reserveData.reserve[i] = angleChange[i]; } } if (argc == 2) { - napi_deferred deferred = nullptr; napi_value promise = nullptr; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - asyncCallbackInfo->deferred = deferred; + CHKNRP(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise), + "napi_create_promise"); EmitPromiseWork(asyncCallbackInfo); return promise; } - if (!IsMatchType(env, args[2], napi_function)) { - HiLog::Error(LABEL, "%{public}s parameter should be napi_fouction type", __func__); - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - return nullptr; - } - napi_create_reference(env, args[2], 1, &asyncCallbackInfo->callback[0]); + CHKNCP(env, IsMatchType(env, args[2], napi_function), "Wrong argument type, should be function"); + CHKNRP(env, napi_create_reference(env, args[2], 1, &asyncCallbackInfo->callback[0]), + "napi_create_reference"); EmitAsyncCallbackWork(asyncCallbackInfo); return nullptr; } static napi_value GetDirection(napi_env env, napi_callback_info info) { + CALL_LOG_ENTER; size_t argc = 3; napi_value args[3] = { 0 }; napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, NULL)); - if (argc < 1 || argc > 2 || !IsMatchArrayType(env, args[0])) { - HiLog::Error(LABEL, "%{public}s the number of input parameters does not match", __func__); - return nullptr; - } - AsyncCallbackInfo *asyncCallbackInfo = new AsyncCallbackInfo { - .env = env, - .asyncWork = nullptr, - .deferred = nullptr, - .type = GET_DIRECTION, - }; - std::vector rotationMatrix = GetCppArrayFloat(env, args[0]); + CHKNRP(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr), "napi_get_cb_info fail"); + CHKNCP(env, ((argc == 1) || (argc == 2)), "The number of parameters is not valid"); + CHKNCP(env, IsMatchArrayType(env, args[0]), "Wrong argument type, should be array"); + + sptr asyncCallbackInfo = + new (std::nothrow) AsyncCallbackInfo(env, GET_DIRECTION); + CHKPP(asyncCallbackInfo); + std::vector rotationMatrix; + CHKNCP(env, GetFloatArray(env, args[0], rotationMatrix), "Wrong argument type, get rotationMatrix fail"); std::vector rotationAngle(ROTATION_VECTOR_LENGTH); - std::unique_ptr sensorAlgorithm = std::make_unique(); - int32_t ret = sensorAlgorithm->getDirection(rotationMatrix, rotationAngle); - if (ret < 0) { - HiLog::Error(LABEL, "%{public}s failed", __func__); + SensorAlgorithm sensorAlgorithm; + int32_t ret = sensorAlgorithm.getDirection(rotationMatrix, rotationAngle); + if (ret != OHOS::ERR_OK) { + SEN_HILOGE("Get direction fail"); asyncCallbackInfo->type = FAIL; asyncCallbackInfo->error.code = ret; } else { asyncCallbackInfo->data.reserveData.length = ROTATION_VECTOR_LENGTH; - for (int32_t i = 0; i < ROTATION_VECTOR_LENGTH; i++) { + for (int32_t i = 0; i < ROTATION_VECTOR_LENGTH; ++i) { asyncCallbackInfo->data.reserveData.reserve[i] = rotationAngle[i]; } } if (argc == 1) { - napi_deferred deferred = nullptr; napi_value promise = nullptr; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - asyncCallbackInfo->deferred = deferred; + CHKNRP(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise), + "napi_create_promise"); EmitPromiseWork(asyncCallbackInfo); return promise; } - if (!IsMatchType(env, args[1], napi_function)) { - HiLog::Error(LABEL, "%{public}s argument should be napi_function type!", __func__); - napi_value result; - napi_get_undefined(env, &result); - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - return result; - } - napi_create_reference(env, args[1], 1, &asyncCallbackInfo->callback[0]); + CHKNCP(env, IsMatchType(env, args[1], napi_function), "Wrong argument type, should be function"); + CHKNRP(env, napi_create_reference(env, args[1], 1, &asyncCallbackInfo->callback[0]), + "napi_create_reference"); EmitAsyncCallbackWork(asyncCallbackInfo); return nullptr; } static napi_value CreateQuaternion(napi_env env, napi_callback_info info) { + CALL_LOG_ENTER; size_t argc = 2; napi_value args[2] = { 0 }; napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr)); - if (argc < 1 || argc > 2 || !IsMatchArrayType(env, args[0])) { - HiLog::Error(LABEL, "%{public}s argument error!", __func__); - return nullptr; - } - AsyncCallbackInfo *asyncCallbackInfo = new AsyncCallbackInfo { - .env = env, - .asyncWork = nullptr, - .deferred = nullptr, - .type = CREATE_QUATERNION, - }; - std::vector rotationVector = GetCppArrayFloat(env, args[0]); + CHKNRP(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr), "napi_get_cb_info"); + CHKNCP(env, ((argc == 1) || (argc == 2)), "The number of parameters is not valid"); + CHKNCP(env, IsMatchArrayType(env, args[0]), "Wrong argument type, should be array"); + + sptr asyncCallbackInfo = + new (std::nothrow) AsyncCallbackInfo(env, CREATE_QUATERNION); + CHKPP(asyncCallbackInfo); + std::vector rotationVector; + CHKNCP(env, GetFloatArray(env, args[0], rotationVector), + "Wrong argument type, get rotationVector fail"); std::vector quaternion(QUATERNION_LENGTH); - std::unique_ptr sensorAlgorithm = std::make_unique(); - int32_t ret = sensorAlgorithm->createQuaternion(rotationVector, quaternion); - if (ret < 0) { - HiLog::Error(LABEL, "%{public}s failed", __func__); + SensorAlgorithm sensorAlgorithm; + int32_t ret = sensorAlgorithm.createQuaternion(rotationVector, quaternion); + if (ret != OHOS::ERR_OK) { + SEN_HILOGE("Create quaternin fail"); asyncCallbackInfo->type = FAIL; asyncCallbackInfo->error.code = ret; } else { asyncCallbackInfo->data.reserveData.length = QUATERNION_LENGTH; - for (int32_t i = 0; i < QUATERNION_LENGTH; i++) { + for (int32_t i = 0; i < QUATERNION_LENGTH; ++i) { asyncCallbackInfo->data.reserveData.reserve[i] = quaternion[i]; } } if (argc == 1) { - napi_deferred deferred = nullptr; napi_value promise = nullptr; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - asyncCallbackInfo->deferred = deferred; + CHKNRP(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise), + "napi_create_promise"); EmitPromiseWork(asyncCallbackInfo); return promise; } - if (!IsMatchType(env, args[1], napi_function)) { - HiLog::Error(LABEL, "%{public}s argument should be function!", __func__); - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - return nullptr; - } - napi_create_reference(env, args[1], 1, &asyncCallbackInfo->callback[0]); + CHKNCP(env, IsMatchType(env, args[1], napi_function), "Wrong argument type, should be function"); + CHKNRP(env, napi_create_reference(env, args[1], 1, &asyncCallbackInfo->callback[0]), + "napi_create_reference"); EmitAsyncCallbackWork(asyncCallbackInfo); return nullptr; } static napi_value GetAltitude(napi_env env, napi_callback_info info) { + CALL_LOG_ENTER; size_t argc = 3; napi_value args[3] = { 0 }; napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr)); - if (argc < 2 || argc > 3 || !IsMatchType(env, args[0], napi_number) - || !IsMatchType(env, args[1], napi_number)) { - HiLog::Error(LABEL, "%{public}s Invalid input.", __func__); - return nullptr; - } - AsyncCallbackInfo *asyncCallbackInfo = new AsyncCallbackInfo { - .env = env, - .asyncWork = nullptr, - .deferred = nullptr, - .type = GET_ALTITUDE, - }; - float seaPressure = GetCppFloat(env, args[0]); - float currentPressure = GetCppFloat(env, args[1]); + CHKNRP(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr), "napi_get_cb_info"); + CHKNCP(env, ((argc == 2) || (argc == 3)), "The number of parameters is not valid"); + CHKNCP(env, IsMatchType(env, args[0], napi_number), "Wrong argument type, should be number"); + CHKNCP(env, IsMatchType(env, args[1], napi_number), "Wrong argument type, should be number"); + + sptr asyncCallbackInfo = + new (std::nothrow) AsyncCallbackInfo(env, GET_ALTITUDE); + CHKPP(asyncCallbackInfo); + float seaPressure = 0; + CHKNCP(env, GetCppFloat(env, args[0], seaPressure), "Wrong argument type, get seaPressure fail"); + float currentPressure = 0; + CHKNCP(env, GetCppFloat(env, args[1], currentPressure), "Wrong argument type, get currentPressure fail"); float altitude = 0; - std::unique_ptr sensorAlgorithm = std::make_unique(); - int32_t ret = sensorAlgorithm->getAltitude(seaPressure, currentPressure, &altitude); - if (ret < 0) { - HiLog::Error(LABEL, "%{public}s failed", __func__); + SensorAlgorithm sensorAlgorithm; + int32_t ret = sensorAlgorithm.getAltitude(seaPressure, currentPressure, &altitude); + if (ret != OHOS::ERR_OK) { + SEN_HILOGE("Get altitude fail"); asyncCallbackInfo->type = FAIL; asyncCallbackInfo->error.code = ret; } else { asyncCallbackInfo->data.reserveData.reserve[0] = altitude; } if (argc == 2) { - napi_deferred deferred = nullptr; napi_value promise = nullptr; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - asyncCallbackInfo->deferred = deferred; + CHKNRP(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise), + "napi_create_promise"); EmitPromiseWork(asyncCallbackInfo); return promise; } - if (!IsMatchType(env, args[2], napi_function)) { - HiLog::Error(LABEL, "%{public}s parameter should be napi_fouction type", __func__); - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - return nullptr; - } - napi_create_reference(env, args[2], 1, &asyncCallbackInfo->callback[0]); + CHKNCP(env, IsMatchType(env, args[2], napi_function), "Wrong argument type, should be function"); + CHKNRP(env, napi_create_reference(env, args[2], 1, &asyncCallbackInfo->callback[0]), + "napi_create_reference"); EmitAsyncCallbackWork(asyncCallbackInfo); return nullptr; } static napi_value GetGeomagneticDip(napi_env env, napi_callback_info info) { + CALL_LOG_ENTER; size_t argc = 2; napi_value args[2] = { 0 }; napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr)); - if (argc < 1 || argc > 2 || !IsMatchArrayType(env, args[0])) { - HiLog::Error(LABEL, "%{public}s Invalid input.", __func__); - return nullptr; - } - AsyncCallbackInfo *asyncCallbackInfo = new AsyncCallbackInfo { - .env = env, - .asyncWork = nullptr, - .deferred = nullptr, - .type = GET_GEOMAGNITIC_DIP, - }; - std::vector inclinationMatrix = GetCppArrayFloat(env, args[0]); + CHKNRP(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr), "napi_get_cb_info"); + CHKNCP(env, ((argc == 1) || (argc == 2)), "The number of parameters is not valid"); + CHKNCP(env, IsMatchArrayType(env, args[0]), "Wrong argument type, should be array"); + + sptr asyncCallbackInfo = + new (std::nothrow) AsyncCallbackInfo(env, GET_GEOMAGNITIC_DIP); + CHKPP(asyncCallbackInfo); + std::vector inclinationMatrix; + CHKNCP(env, GetFloatArray(env, args[0], inclinationMatrix), + "Wrong argument type, get inclinationMatrix fail"); float geomagneticDip = 0; - std::unique_ptr sensorAlgorithm = std::make_unique(); - int32_t ret = sensorAlgorithm->getGeomagneticDip(inclinationMatrix, &geomagneticDip); - if (ret < 0) { - HiLog::Error(LABEL, "%{public}s failed", __func__); + SensorAlgorithm sensorAlgorithm; + int32_t ret = sensorAlgorithm.getGeomagneticDip(inclinationMatrix, &geomagneticDip); + if (ret != OHOS::ERR_OK) { + SEN_HILOGE("Get geomagnetic dip fail"); asyncCallbackInfo->type = FAIL; asyncCallbackInfo->error.code = ret; } else { asyncCallbackInfo->data.reserveData.reserve[0] = geomagneticDip; } if (argc == 1) { - napi_deferred deferred = nullptr; napi_value promise = nullptr; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - asyncCallbackInfo->deferred = deferred; + CHKNRP(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise), + "napi_create_promise"); EmitPromiseWork(asyncCallbackInfo); return promise; } - if (!IsMatchType(env, args[1], napi_function)) { - HiLog::Error(LABEL, "%{public}s argument should be function!", __func__); - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - return nullptr; - } - napi_create_reference(env, args[1], 1, &asyncCallbackInfo->callback[0]); + CHKNCP(env, IsMatchType(env, args[1], napi_function), "Wrong argument type, should be function"); + CHKNRP(env, napi_create_reference(env, args[1], 1, &asyncCallbackInfo->callback[0]), + "napi_create_reference"); EmitAsyncCallbackWork(asyncCallbackInfo); return nullptr; } -static napi_value CreateRotationMatrix(napi_env env, napi_callback_info info) +static napi_value createRotationAndInclination(const napi_env &env, napi_value args[], size_t argc) { - size_t argc = 3; - napi_value args[3] = { 0 }; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, NULL)); - if (argc < 1 || argc > 3 || !IsMatchArrayType(env, args[0])) { - HiLog::Info(LABEL, "%{public}s argument error", __func__); - return nullptr; - } - AsyncCallbackInfo *asyncCallbackInfo = new AsyncCallbackInfo { - .env = env, - .asyncWork = nullptr, - .deferred = nullptr, - .type = CREATE_ROTATION_MATRIX, - }; - std::unique_ptr sensorAlgorithm = std::make_unique(); - if (argc == 1 || (argc == 2 && IsMatchType(env, args[1], napi_function))) { - std::vector rotationVector = GetCppArrayFloat(env, args[0]); - std::vector rotationMatrix(THREE_DIMENSIONAL_MATRIX_LENGTH); - int32_t ret = sensorAlgorithm->createRotationMatrix(rotationVector, rotationMatrix); - if (ret < 0) { - HiLog::Error(LABEL, "%{public}s failed", __func__); - asyncCallbackInfo->type = FAIL; - asyncCallbackInfo->error.code = ret; - } else { - asyncCallbackInfo->data.reserveData.length = THREE_DIMENSIONAL_MATRIX_LENGTH; - for (int32_t i = 0; i < THREE_DIMENSIONAL_MATRIX_LENGTH; i++) { - asyncCallbackInfo->data.reserveData.reserve[i] = rotationMatrix[i]; - } - } - if (argc == 1) { - napi_deferred deferred = nullptr; - napi_value promise = nullptr; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - asyncCallbackInfo->deferred = deferred; - EmitPromiseWork(asyncCallbackInfo); - return promise; - } - napi_create_reference(env, args[1], 1, &asyncCallbackInfo->callback[0]); - EmitAsyncCallbackWork(asyncCallbackInfo); - return nullptr; - } - - if (!IsMatchArrayType(env, args[1]) || (argc == 3 && !IsMatchType(env, args[2], napi_function))) { - HiLog::Info(LABEL, "%{public}s argument error", __func__); - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - return nullptr; - } - asyncCallbackInfo->type = ROTATION_INCLINATION_MATRIX; - std::vector gravity = GetCppArrayFloat(env, args[0]); - std::vector geomagnetic = GetCppArrayFloat(env, args[1]); + CALL_LOG_ENTER; + CHKNCP(env, ((argc == 2) || (argc == 3)), "The number of parameters is not valid"); + std::vector gravity; + CHKNCP(env, GetFloatArray(env, args[0], gravity), "Wrong argument type, get gravity fail"); + std::vector geomagnetic; + CHKNCP(env, GetFloatArray(env, args[1], geomagnetic), "Wrong argument type, get geomagnetic fail"); std::vector rotation(THREE_DIMENSIONAL_MATRIX_LENGTH); std::vector inclination(THREE_DIMENSIONAL_MATRIX_LENGTH); - int32_t ret = sensorAlgorithm->createRotationAndInclination(gravity, geomagnetic, rotation, inclination); - if (ret < 0) { - HiLog::Error(LABEL, "%{public}s failed", __func__); + sptr asyncCallbackInfo = + new (std::nothrow) AsyncCallbackInfo(env, ROTATION_INCLINATION_MATRIX); + CHKPP(asyncCallbackInfo); + SensorAlgorithm sensorAlgorithm; + int32_t ret = sensorAlgorithm.createRotationAndInclination(gravity, geomagnetic, rotation, inclination); + if (ret != OHOS::ERR_OK) { + SEN_HILOGE("Create rotation and inclination matrix fail"); asyncCallbackInfo->type = FAIL; asyncCallbackInfo->error.code = ret; } else { - for (int32_t i = 0; i < THREE_DIMENSIONAL_MATRIX_LENGTH; i++) { + asyncCallbackInfo->data.reserveData.length = THREE_DIMENSIONAL_MATRIX_LENGTH; + for (int32_t i = 0; i < THREE_DIMENSIONAL_MATRIX_LENGTH; ++i) { asyncCallbackInfo->data.rationMatrixData.rotationMatrix[i] = rotation[i]; } - for (int32_t i = 0; i < THREE_DIMENSIONAL_MATRIX_LENGTH; i++) { + for (int32_t i = 0; i < THREE_DIMENSIONAL_MATRIX_LENGTH; ++i) { asyncCallbackInfo->data.rationMatrixData.inclinationMatrix[i] = inclination[i]; } } if (argc == 2) { - napi_deferred deferred = nullptr; napi_value promise = nullptr; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - asyncCallbackInfo->deferred = deferred; + CHKNRP(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise), + "napi_create_promise"); + EmitPromiseWork(asyncCallbackInfo); + return promise; + } + CHKNCP(env, IsMatchType(env, args[2], napi_function), "Wrong argument type, should be function"); + CHKNRP(env, napi_create_reference(env, args[2], 1, &asyncCallbackInfo->callback[0]), + "napi_create_reference"); + EmitAsyncCallbackWork(asyncCallbackInfo); + return nullptr; +} + +static napi_value GetRotationMatrix(const napi_env &env, napi_value args[], size_t argc) +{ + CALL_LOG_ENTER; + CHKNCP(env, ((argc == 1) || (argc == 2)), "The number of parameters is not valid"); + std::vector rotationVector; + CHKNCP(env, GetFloatArray(env, args[0], rotationVector), + "Wrong argument type, get rotationVector fail"); + + sptr asyncCallbackInfo = + new (std::nothrow) AsyncCallbackInfo(env, CREATE_ROTATION_MATRIX); + CHKPP(asyncCallbackInfo); + std::vector rotationMatrix(THREE_DIMENSIONAL_MATRIX_LENGTH); + SensorAlgorithm sensorAlgorithm; + int32_t ret = sensorAlgorithm.createRotationMatrix(rotationVector, rotationMatrix); + if (ret != OHOS::ERR_OK) { + SEN_HILOGE("Create rotation matrix fail"); + asyncCallbackInfo->type = FAIL; + asyncCallbackInfo->error.code = ret; + } else { + asyncCallbackInfo->data.reserveData.length = THREE_DIMENSIONAL_MATRIX_LENGTH; + for (int32_t i = 0; i < THREE_DIMENSIONAL_MATRIX_LENGTH; ++i) { + asyncCallbackInfo->data.reserveData.reserve[i] = rotationMatrix[i]; + } + } + + if (argc == 1) { + napi_value promise = nullptr; + CHKNRP(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise), + "napi_create_promise"); EmitPromiseWork(asyncCallbackInfo); return promise; } - napi_create_reference(env, args[2], 1, &asyncCallbackInfo->callback[0]); + CHKNCP(env, IsMatchType(env, args[1], napi_function), "Wrong argument type, should be function"); + CHKNRP(env, napi_create_reference(env, args[1], 1, &asyncCallbackInfo->callback[0]), + "napi_create_reference"); EmitAsyncCallbackWork(asyncCallbackInfo); return nullptr; } +static napi_value CreateRotationMatrix(napi_env env, napi_callback_info info) +{ + CALL_LOG_ENTER; + size_t argc = 3; + napi_value args[3] = { 0 }; + napi_value thisVar = nullptr; + CHKNRP(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr), "napi_get_cb_info"); + CHKNCP(env, ((argc >= 1) && (argc <= 3)), "The number of parameters is not valid"); + CHKNCP(env, IsMatchArrayType(env, args[0]), "Wrong argument type, should be array"); + + if (argc == 1 || (argc == 2 && IsMatchType(env, args[1], napi_function))) { + return GetRotationMatrix(env, args, argc); + } else if (IsMatchArrayType(env, args[1])) { + return createRotationAndInclination(env, args, argc); + } + return nullptr; +} + static napi_value GetSensorList(napi_env env, napi_callback_info info) { - HiLog::Info(LABEL, "%{public}s in", __func__); + CALL_LOG_ENTER; size_t argc = 1; napi_value args[1] = { 0 }; napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, NULL)); - if (argc < 0 || argc > 1) { - HiLog::Error(LABEL, "%{public}s the number of input parameters does not match", __func__); - return nullptr; - } + CHKNRP(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr), "napi_get_cb_info"); + CHKNCP(env, (argc <= 1), "The number of parameters is not valid"); + sptr asyncCallbackInfo = + new (std::nothrow) AsyncCallbackInfo(env, GET_SENSOR_LIST); + CHKPP(asyncCallbackInfo); + SensorInfo *sensorInfos = nullptr; int32_t count = 0; - AsyncCallbackInfo *asyncCallbackInfo = new AsyncCallbackInfo { - .env = env, - .asyncWork = nullptr, - .deferred = nullptr, - .type = GET_SENSOR_LIST, - }; int32_t ret = GetAllSensors(&sensorInfos, &count); - if (ret < 0) { - HiLog::Error(LABEL, "%{public}s get sensor list failed", __func__); + if (ret != OHOS::ERR_OK) { + SEN_HILOGE("Get sensor list fail"); asyncCallbackInfo->type = FAIL; asyncCallbackInfo->error.code = ret; } else { - for (int32_t i = 0; i < count; i++) { + for (int32_t i = 0; i < count; ++i) { asyncCallbackInfo->sensorInfos.push_back(*(sensorInfos + i)); } + free(sensorInfos); + sensorInfos = nullptr; } - if (argc == 0) { - napi_deferred deferred = nullptr; napi_value promise = nullptr; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - asyncCallbackInfo->deferred = deferred; + CHKNRP(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise), + "napi_create_promise"); EmitPromiseWork(asyncCallbackInfo); return promise; } - if (!IsMatchType(env, args[0], napi_function)) { - HiLog::Error(LABEL, "%{public}s argument should be napi_function type", __func__); - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - return nullptr; - } + CHKNCP(env, IsMatchType(env, args[0], napi_function), "Wrong argument type, should be function"); napi_create_reference(env, args[0], 1, &asyncCallbackInfo->callback[0]); EmitAsyncCallbackWork(asyncCallbackInfo); return nullptr; @@ -805,115 +816,187 @@ static napi_value GetSensorList(napi_env env, napi_callback_info info) static napi_value GetSingleSensor(napi_env env, napi_callback_info info) { - HiLog::Info(LABEL, "%{public}s in", __func__); + CALL_LOG_ENTER; size_t argc = 2; napi_value args[2] = { 0 }; napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, NULL)); - if (argc < 1 || argc > 2 || !IsMatchType(env, args[0], napi_number)) { - HiLog::Error(LABEL, "%{public}s the number of input parameters does not match", __func__); - return nullptr; - } - AsyncCallbackInfo *asyncCallbackInfo = new AsyncCallbackInfo { - .env = env, - .asyncWork = nullptr, - .deferred = nullptr, - .type = GET_SINGLE_SENSOR, - }; + CHKNRP(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr), "napi_get_cb_info"); + CHKNCP(env, ((argc == 1) || (argc == 2)), "The number of parameters is not valid"); + int32_t sensorTypeId = INVALID_SENSOR_ID; + CHKNCP(env, GetCppInt32(env, args[0], sensorTypeId), "Wrong argument type, get number fail"); + + sptr asyncCallbackInfo = + new (std::nothrow) AsyncCallbackInfo(env, GET_SINGLE_SENSOR); + CHKPP(asyncCallbackInfo); SensorInfo *sensorInfos = nullptr; int32_t count = 0; int32_t ret = GetAllSensors(&sensorInfos, &count); - if (ret < 0) { - HiLog::Error(LABEL, "%{public}s get sensorlist failed", __func__); + if (ret != OHOS::ERR_OK) { + SEN_HILOGE("Get sensor list fail"); asyncCallbackInfo->type = FAIL; asyncCallbackInfo->error.code = ret; } else { - int32_t sensorTypeId = GetCppInt32(args[0], env); - for (int32_t i = 0; i < count; i++) { + for (int32_t i = 0; i < count; ++i) { if (sensorInfos[i].sensorTypeId == sensorTypeId) { asyncCallbackInfo->sensorInfos.push_back(*(sensorInfos + i)); break; } } if (asyncCallbackInfo->sensorInfos.empty()) { - HiLog::Error(LABEL, "%{public}s not find sensorTypeId: %{public}d", __func__, sensorTypeId); + SEN_HILOGE("Not find sensorTypeId: %{public}d", sensorTypeId); asyncCallbackInfo->type = FAIL; } + free(sensorInfos); + sensorInfos = nullptr; } if (argc == 1) { - napi_deferred deferred = nullptr; napi_value promise = nullptr; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - asyncCallbackInfo->deferred = deferred; + CHKNRP(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise), "napi_create_promise"); EmitPromiseWork(asyncCallbackInfo); return promise; } - if (!IsMatchType(env, args[1], napi_function)) { - HiLog::Error(LABEL, "%{public}s argument should be napi_function type!", __func__); - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - return nullptr; - } + CHKNCP(env, IsMatchType(env, args[1], napi_function), "Wrong argument type, should be function"); napi_create_reference(env, args[1], 1, &asyncCallbackInfo->callback[0]); EmitAsyncCallbackWork(asyncCallbackInfo); return nullptr; } +napi_value Subscribe(napi_env env, napi_callback_info info, int32_t sensorTypeId, CallbackDataType type) +{ + CALL_LOG_ENTER; + 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"); + CHKNCP(env, 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"); + } + 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]), + "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]), + "register callback fail"); + } + if (auto iter = g_samplingPeriod.find(interval); iter == g_samplingPeriod.end()) { + CHKNCP(env, (napiFail != nullptr), "input error, interval is invalid"); + CreateFailMessage(SUBSCRIBE_FAIL, INPUT_ERROR, "input error", asyncCallbackInfo); + EmitAsyncCallbackWork(asyncCallbackInfo); + return nullptr; + } + std::lock_guard subscribeCallbackLock(mutex_); + bool ret = SubscribeSensor(sensorTypeId, g_samplingPeriod[interval], DataCallbackImpl); + if (!ret) { + CHKNCP(env, (napiFail != nullptr), "subscribe fail"); + CreateFailMessage(SUBSCRIBE_FAIL, SENSOR_SUBSCRIBE_FAILURE, "subscribe fail", asyncCallbackInfo); + EmitAsyncCallbackWork(asyncCallbackInfo); + return nullptr; + } + g_subscribeCallbacks[sensorTypeId] = asyncCallbackInfo; + return nullptr; +} + +napi_value Unsubscribe(napi_env env, napi_callback_info info, int32_t sensorTypeId) +{ + CALL_LOG_ENTER; + 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 == 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"); + return nullptr; +} + +napi_value GetBodyState(napi_env env, napi_callback_info info) +{ + CALL_LOG_ENTER; + 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"); + CHKNCP(env, 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]), + "register success callback fail"); + std::lock_guard onBodyLock(bodyMutex_); + asyncCallbackInfo->data.sensorData.data[0] = + (fabs(g_bodyState - BODY_STATE_EXCEPT) < THREESHOLD) ? true : false; + EmitUvEventLoop(asyncCallbackInfo); + return nullptr; +} + static napi_value EnumClassConstructor(napi_env env, napi_callback_info info) { size_t argc = 0; napi_value args[1] = {0}; - napi_value res = nullptr; + napi_value ret = nullptr; void *data = nullptr; - napi_status status = napi_get_cb_info(env, info, &argc, args, &res, &data); - if (status != napi_ok) { - return nullptr; - } - return res; + CHKNRP(env, napi_get_cb_info(env, info, &argc, args, &ret, &data), "napi_get_cb_info"); + return ret; } static napi_value CreateEnumSensorType(napi_env env, napi_value exports) { napi_property_descriptor desc[] = { - DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_ACCELEROMETER", GetNapiInt32(SENSOR_TYPE_ID_ACCELEROMETER, env)), - DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_GYROSCOPE", GetNapiInt32(SENSOR_TYPE_ID_GYROSCOPE, env)), - DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_AMBIENT_LIGHT", GetNapiInt32(SENSOR_TYPE_ID_AMBIENT_LIGHT, env)), - DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_MAGNETIC_FIELD", GetNapiInt32(SENSOR_TYPE_ID_MAGNETIC_FIELD, env)), - DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_BAROMETER", GetNapiInt32(SENSOR_TYPE_ID_BAROMETER, env)), - DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_HALL", GetNapiInt32(SENSOR_TYPE_ID_HALL, env)), - DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_PROXIMITY", GetNapiInt32(SENSOR_TYPE_ID_PROXIMITY, env)), - DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_HUMIDITY", GetNapiInt32(SENSOR_TYPE_ID_HUMIDITY, env)), - DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_ORIENTATION", GetNapiInt32(SENSOR_TYPE_ID_ORIENTATION, env)), - DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_GRAVITY", GetNapiInt32(SENSOR_TYPE_ID_GRAVITY, env)), + DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_ACCELEROMETER", GetNapiInt32(env, SENSOR_TYPE_ID_ACCELEROMETER)), + DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_GYROSCOPE", GetNapiInt32(env, SENSOR_TYPE_ID_GYROSCOPE)), + DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_AMBIENT_LIGHT", GetNapiInt32(env, SENSOR_TYPE_ID_AMBIENT_LIGHT)), + DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_MAGNETIC_FIELD", GetNapiInt32(env, SENSOR_TYPE_ID_MAGNETIC_FIELD)), + DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_BAROMETER", GetNapiInt32(env, SENSOR_TYPE_ID_BAROMETER)), + DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_HALL", GetNapiInt32(env, SENSOR_TYPE_ID_HALL)), + DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_PROXIMITY", GetNapiInt32(env, SENSOR_TYPE_ID_PROXIMITY)), + DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_HUMIDITY", GetNapiInt32(env, SENSOR_TYPE_ID_HUMIDITY)), + DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_ORIENTATION", GetNapiInt32(env, SENSOR_TYPE_ID_ORIENTATION)), + DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_GRAVITY", GetNapiInt32(env, SENSOR_TYPE_ID_GRAVITY)), DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_LINEAR_ACCELERATION", - GetNapiInt32(SENSOR_TYPE_ID_LINEAR_ACCELERATION, env)), + GetNapiInt32(env, SENSOR_TYPE_ID_LINEAR_ACCELERATION)), DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_ROTATION_VECTOR", - GetNapiInt32(SENSOR_TYPE_ID_ROTATION_VECTOR, env)), + GetNapiInt32(env, SENSOR_TYPE_ID_ROTATION_VECTOR)), DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_AMBIENT_TEMPERATURE", - GetNapiInt32(SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, env)), + GetNapiInt32(env, SENSOR_TYPE_ID_AMBIENT_TEMPERATURE)), DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED", - GetNapiInt32(SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, env)), + GetNapiInt32(env, SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED)), DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED", - GetNapiInt32(SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, env)), + GetNapiInt32(env, SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED)), DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_SIGNIFICANT_MOTION", - GetNapiInt32(SENSOR_TYPE_ID_SIGNIFICANT_MOTION, env)), + GetNapiInt32(env, SENSOR_TYPE_ID_SIGNIFICANT_MOTION)), DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_PEDOMETER_DETECTION", - GetNapiInt32(SENSOR_TYPE_ID_PEDOMETER_DETECTION, env)), - DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_PEDOMETER", GetNapiInt32(SENSOR_TYPE_ID_PEDOMETER, env)), - DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_HEART_RATE", GetNapiInt32(SENSOR_TYPE_ID_HEART_RATE, env)), - DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_WEAR_DETECTION", GetNapiInt32(SENSOR_TYPE_ID_WEAR_DETECTION, env)), + GetNapiInt32(env, SENSOR_TYPE_ID_PEDOMETER_DETECTION)), + DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_PEDOMETER", GetNapiInt32(env, SENSOR_TYPE_ID_PEDOMETER)), + DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_HEART_RATE", GetNapiInt32(env, SENSOR_TYPE_ID_HEART_RATE)), + DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_WEAR_DETECTION", GetNapiInt32(env, SENSOR_TYPE_ID_WEAR_DETECTION)), DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED", - GetNapiInt32(SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, env)), + GetNapiInt32(env, SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED)), }; napi_value result = nullptr; - napi_define_class(env, "SensorType", NAPI_AUTO_LENGTH, EnumClassConstructor, nullptr, - sizeof(desc) / sizeof(*desc), desc, &result); - napi_set_named_property(env, exports, "SensorType", result); + CHKNRP(env, napi_define_class(env, "SensorType", NAPI_AUTO_LENGTH, EnumClassConstructor, nullptr, + sizeof(desc) / sizeof(*desc), desc, &result), "napi_define_class"); + CHKNRP(env, napi_set_named_property(env, exports, "SensorType", result), "napi_set_named_property fail"); return exports; } -EXTERN_C_START - static napi_value Init(napi_env env, napi_value exports) { napi_property_descriptor desc[] = { @@ -958,16 +1041,16 @@ static napi_value Init(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("subscribeHall", SubscribeHall), DECLARE_NAPI_FUNCTION("unsubscribeHall", UnsubscribeHall), }; - NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(napi_property_descriptor), desc)); - CreateEnumSensorType(env, exports); + CHKNRP(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(napi_property_descriptor), desc), + "napi_define_properties"); + CHKNCP(env, CreateEnumSensorType(env, exports), "Create enum sensor type fail"); return exports; } -EXTERN_C_END static napi_module _module = { .nm_version = 1, .nm_flags = 0, - .nm_filename = NULL, + .nm_filename = nullptr, .nm_register_func = Init, .nm_modname = "sensor", .nm_priv = ((void *)0), @@ -978,3 +1061,5 @@ extern "C" __attribute__((constructor)) void RegisterModule(void) { napi_module_register(&_module); } +} // namespace Sensors +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/plugin/src/sensor_napi_utils.cpp b/interfaces/plugin/src/sensor_napi_utils.cpp index 30be30b7709f85b22ef38b72f9ceec085249382c..bbf2f46b231de93c9d10679ce86dc00e0ded8085 100644 --- a/interfaces/plugin/src/sensor_napi_utils.cpp +++ b/interfaces/plugin/src/sensor_napi_utils.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 20212 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -15,129 +15,143 @@ #include "sensor_napi_utils.h" -#include #include #include #include -#include "hilog/log.h" - -using namespace OHOS::HiviewDFX; -static constexpr HiLogLabel LABEL = {LOG_CORE, 0xD002708, "SensorJsAPI"}; - -bool IsNapiValueSame(napi_env env, napi_value lhs, napi_value rhs) +namespace OHOS { +namespace Sensors { +namespace { + constexpr int32_t STRING_LENGTH_MAX = 64; +} +bool IsSameValue(const napi_env &env, const napi_value &lhs, const napi_value &rhs) { + CALL_LOG_ENTER; bool result = false; - napi_strict_equals(env, lhs, rhs, &result); + CHKNRF(env, napi_strict_equals(env, lhs, rhs, &result), "napi_strict_equals"); return result; } -bool IsMatchType(napi_env env, napi_value value, napi_valuetype type) +bool IsMatchType(const napi_env &env, const napi_value &value, const napi_valuetype &type) { + CALL_LOG_ENTER; napi_valuetype paramType = napi_undefined; - napi_typeof(env, value, ¶mType); - if (paramType != type) { - HiLog::Error(LABEL, "%{public}s failed!", __func__); - return false; - } - return true; + CHKNRF(env, napi_typeof(env, value, ¶mType), "napi_typeof"); + return paramType == type; } -bool IsMatchArrayType(napi_env env, napi_value value) +bool IsMatchArrayType(const napi_env &env, const napi_value &value) { + CALL_LOG_ENTER; bool result = false; - napi_is_array(env, value, &result); + CHKNRF(env, napi_is_array(env, value, &result), "napi_is_array"); return result; } -vector GetCppArrayFloat(napi_env env, napi_value value) +bool GetFloatArray(const napi_env &env, const napi_value &value, vector &array) { + CALL_LOG_ENTER; uint32_t arrayLength = 0; - napi_get_array_length(env, value, &arrayLength); - if (arrayLength <= 0) { - HiLog::Error(LABEL, "%{public}s The array is empty.", __func__); - return vector(); - } - vector paramArrays; - for (size_t i = 0; i < arrayLength; i++) { - napi_value napiElement = nullptr; - napi_get_element(env, value, i, &napiElement); - - napi_valuetype valuetype0 = napi_undefined; - napi_typeof(env, napiElement, &valuetype0); - if (valuetype0 != napi_number) { - HiLog::Error(LABEL, "%{public}s Wrong argument type. Numbers expected.", __func__); - return vector(); - } - double value0 = 0; - napi_get_value_double(env, napiElement, &value0); - paramArrays.push_back(static_cast(value0)); + CHKNRF(env, napi_get_array_length(env, value, &arrayLength), "napi_get_array_length"); + for (size_t i = 0; i < arrayLength; ++i) { + napi_value element = nullptr; + CHKNRF(env, napi_get_element(env, value, i, &element), "napi_get_element"); + CHKNCF(env, IsMatchType(env, element, napi_number), "Wrong argument type. Number or function expected"); + double value = 0; + CHKNCF(env, GetCppDouble(env, element, value), "Wrong argument type. get double fail"); + array.push_back(static_cast(value)); } - return paramArrays; + return true; } -bool IsMatchArrayType(napi_env env, napi_value value, napi_typedarray_type type) +napi_value GetNamedProperty(const napi_env &env, const napi_value &object, string name) { - napi_typedarray_type paramType = napi_int8_array; - size_t length; - void *data = nullptr; - napi_value arraybuffer = nullptr; - size_t byteOffset; - napi_get_typedarray_info(env, value, ¶mType, &length, &data, &arraybuffer, &byteOffset); - if (paramType != type) { - HiLog::Error(LABEL, "%{public}s paramType:%{public}d type:%{public}d failed!", __func__, paramType, type); - return false; + CALL_LOG_ENTER; + bool status = false; + CHKNRP(env, napi_has_named_property(env, object, name.c_str(), &status), "napi_has_named_property"); + if (!status) { + SEN_HILOGW("%{public}s not exists on the object", name.c_str()); + return nullptr; } + napi_value value = nullptr; + CHKNRP(env, napi_get_named_property(env, object, name.c_str(), &value), + "napi_get_named_property"); + return value; +} + +bool GetCppDouble(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; } -napi_value GetNapiInt32(int32_t number, napi_env env) +bool GetCppFloat(const napi_env &env, const napi_value &value, float &number) { - napi_value value = nullptr; - napi_create_int32(env, number, &value); - return value; + CALL_LOG_ENTER; + double result = 0; + CHKNCF(env, GetCppDouble(env, value, result), "Get cpp double fail"); + number = static_cast(result); + return true; } -napi_value NapiGetNamedProperty(napi_value jsonObject, string name, napi_env env) +bool GetCppInt32(const napi_env &env, const napi_value &value, int32_t &number) { - napi_value value = nullptr; - napi_get_named_property(env, jsonObject, name.c_str(), &value); - return value; + CALL_LOG_ENTER; + CHKNRF(env, napi_get_value_int32(env, value, &number), "napi_get_value_int32"); + return true; } -float GetCppFloat(napi_env env, napi_value value) +bool GetCppInt64(const napi_env &env, const napi_value &value, int64_t &number) { - double number; - napi_get_value_double(env, value, &number); - return static_cast(number); + CALL_LOG_ENTER; + CHKNRF(env, napi_get_value_int64(env, value, &number), "napi_get_value_int64"); + return true; } -int32_t GetCppInt32(napi_value value, napi_env env) +bool GetCppBool(const napi_env &env, const napi_value &value) { - int32_t number; - napi_get_value_int32(env, value, &number); + CALL_LOG_ENTER; + bool number = false; + CHKNRF(env, napi_get_value_bool(env, value, &number), "napi_get_value_bool"); return number; } -int64_t GetCppInt64(napi_value value, napi_env env) +napi_value GetNapiInt32(const napi_env &env, int32_t number) { - int64_t number; - napi_get_value_int64(env, value, &number); - return number; + napi_value value = nullptr; + CHKNRP(env, napi_create_int32(env, number, &value), "napi_create_int32"); + return value; } -bool GetCppBool(napi_value value, napi_env env) +bool GetStringValue(const napi_env &env, const napi_value &value, string &result) { - bool number; - napi_get_value_bool(env, value, &number); - return number; + CALL_LOG_ENTER; + CHKNCF(env, IsMatchType(env, value, napi_string), "Wrong argument type. String or function expected"); + char buf[STRING_LENGTH_MAX] = { 0 }; + size_t copyLength = 0; + CHKNRF(env, napi_get_value_string_utf8(env, value, buf, STRING_LENGTH_MAX, ©Length), + "napi_get_value_string_utf8"); + result = std::string(buf); + return true; } -napi_value GetUndefined(napi_env env) +bool RegisterNapiCallback(const napi_env &env, const napi_value &value, + napi_ref &callback) { - napi_value value; - napi_get_undefined(env, &value); - return value; + CHKNCF(env, IsMatchType(env, value, napi_function), "Wrong argument type, should be function"); + CHKNRF(env, napi_create_reference(env, value, 1, &callback), "napi_create_reference"); + return true; +} + +bool CreateFailMessage(CallbackDataType type, int32_t code, string message, + sptr &asyncCallbackInfo) +{ + CHKPF(asyncCallbackInfo); + asyncCallbackInfo->type = type; + asyncCallbackInfo->error.code = code; + asyncCallbackInfo->error.message = message; + return true; } std::map> g_sensorAttributeList = { @@ -167,7 +181,6 @@ std::map> g_sensorAttributeList = { std::map g_convertfuncList = { {FAIL, ConvertToFailData}, - {OFF_CALLBACK, ConvertToNoData}, {ON_CALLBACK, ConvertToSensorData}, {ONCE_CALLBACK, ConvertToSensorData}, {GET_GEOMAGNETIC_FIELD, ConvertToGeomagneticData}, @@ -181,317 +194,405 @@ std::map g_convertfuncList = { {ROTATION_INCLINATION_MATRIX, ConvertToRotationMatrix}, {GET_SENSOR_LIST, ConvertToSensorInfos}, {GET_SINGLE_SENSOR, ConvertToSingleSensor}, + {GET_BODY_STATE, ConvertToBodyData}, + {SUBSCRIBE_CALLBACK, ConvertToSensorData}, + {SUBSCRIBE_COMPASS, ConvertToCompass}, }; -void getJsonObject(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result) +bool getJsonObject(const napi_env &env, sptr asyncCallbackInfo, napi_value &result) { - napi_value x = nullptr; - napi_create_double(env, asyncCallbackInfo->data.geomagneticData.x, &x); - napi_set_named_property(env, result, "x", x); - - napi_value y = nullptr; - napi_create_double(env, asyncCallbackInfo->data.geomagneticData.y, &y); - napi_set_named_property(env, result, "y", y); - - napi_value z = nullptr; - napi_create_double(env, asyncCallbackInfo->data.geomagneticData.z, &z); - napi_set_named_property(env, result, "z", z); - - napi_value geomagneticDip = nullptr; - napi_create_double(env, asyncCallbackInfo->data.geomagneticData.geomagneticDip, &geomagneticDip); - napi_set_named_property(env, result, "geomagneticDip", geomagneticDip); - - napi_value deflectionAngle = nullptr; - napi_create_double(env, asyncCallbackInfo->data.geomagneticData.deflectionAngle, &deflectionAngle); - napi_set_named_property(env, result, "deflectionAngle", deflectionAngle); - - napi_value levelIntensity = nullptr; - napi_create_double(env, asyncCallbackInfo->data.geomagneticData.levelIntensity, &levelIntensity); - napi_set_named_property(env, result, "levelIntensity", levelIntensity); - - napi_value totalIntensity = nullptr; - napi_create_double(env, asyncCallbackInfo->data.geomagneticData.totalIntensity, &totalIntensity); - napi_set_named_property(env, result, "totalIntensity", totalIntensity); + CHKPF(asyncCallbackInfo); + CHKNRF(env, napi_create_object(env, &result), "napi_create_object"); + napi_value value = nullptr; + CHKNRF(env, napi_create_double(env, asyncCallbackInfo->data.geomagneticData.x, &value), "napi_create_double"); + CHKNRF(env, napi_set_named_property(env, result, "x", value), "napi_set_named_property"); + + value = nullptr; + CHKNRF(env, napi_create_double(env, asyncCallbackInfo->data.geomagneticData.y, &value), "napi_create_double"); + CHKNRF(env, napi_set_named_property(env, result, "y", value), "napi_set_named_property"); + + value = nullptr; + CHKNRF(env, napi_create_double(env, asyncCallbackInfo->data.geomagneticData.z, &value), "napi_create_double"); + CHKNRF(env, napi_set_named_property(env, result, "z", value), "napi_set_named_property"); + + value = nullptr; + CHKNRF(env, napi_create_double(env, asyncCallbackInfo->data.geomagneticData.geomagneticDip, &value), + "napi_create_double"); + CHKNRF(env, napi_set_named_property(env, result, "geomagneticDip", value), "napi_set_named_property"); + + value = nullptr; + CHKNRF(env, napi_create_double(env, asyncCallbackInfo->data.geomagneticData.deflectionAngle, &value), + "napi_create_double"); + CHKNRF(env, napi_set_named_property(env, result, "deflectionAngle", value), "napi_set_named_property"); + + value = nullptr; + CHKNRF(env, napi_create_double(env, asyncCallbackInfo->data.geomagneticData.levelIntensity, &value), + "napi_create_double"); + CHKNRF(env, napi_set_named_property(env, result, "levelIntensity", value), "napi_set_named_property"); + + value = nullptr; + CHKNRF(env, napi_create_double(env, asyncCallbackInfo->data.geomagneticData.totalIntensity, &value), + "napi_create_double"); + CHKNRF(env, napi_set_named_property(env, result, "totalIntensity", value), "napi_set_named_property"); + return true; } -void ConvertToSensorInfo(napi_env env, SensorInfo sensorInfo, napi_value result) +bool ConvertToSensorInfo(const napi_env &env, SensorInfo sensorInfo, napi_value &result) { - napi_value sensorName = nullptr; - napi_create_string_latin1(env, sensorInfo.sensorName, NAPI_AUTO_LENGTH, &sensorName); - napi_set_named_property(env, result, "sensorName", sensorName); - - napi_value vendorName = nullptr; - napi_create_string_latin1(env, sensorInfo.vendorName, NAPI_AUTO_LENGTH, &vendorName); - napi_set_named_property(env, result, "vendorName", vendorName); - - napi_value firmwareVersion = nullptr; - napi_create_string_latin1(env, sensorInfo.firmwareVersion, NAPI_AUTO_LENGTH, &firmwareVersion); - napi_set_named_property(env, result, "firmwareVersion", firmwareVersion); - - napi_value hardwareVersion = nullptr; - napi_create_string_latin1(env, sensorInfo.hardwareVersion, NAPI_AUTO_LENGTH, &hardwareVersion); - napi_set_named_property(env, result, "hardwareVersion", hardwareVersion); - - napi_value sensorTypeId = nullptr; - napi_create_double(env, sensorInfo.sensorTypeId, &sensorTypeId); - napi_set_named_property(env, result, "sensorTypeId", sensorTypeId); - - napi_value maxRange = nullptr; - napi_create_double(env, sensorInfo.maxRange, &maxRange); - napi_set_named_property(env, result, "maxRange", maxRange); - - napi_value precision = nullptr; - napi_create_double(env, sensorInfo.precision, &precision); - napi_set_named_property(env, result, "precision", precision); - - napi_value power = nullptr; - napi_create_double(env, sensorInfo.power, &power); - napi_set_named_property(env, result, "power", power); + CALL_LOG_ENTER; + CHKNRF(env, napi_create_object(env, &result), "napi_create_object"); + napi_value value = nullptr; + CHKNRF(env, napi_create_string_latin1(env, sensorInfo.sensorName, NAPI_AUTO_LENGTH, &value), + "napi_create_string_latin1"); + CHKNRF(env, napi_set_named_property(env, result, "sensorName", value), "napi_set_named_property"); + + value = nullptr; + CHKNRF(env, napi_create_string_latin1(env, sensorInfo.vendorName, NAPI_AUTO_LENGTH, &value), + "napi_create_string_latin1"); + CHKNRF(env, napi_set_named_property(env, result, "vendorName", value), "napi_set_named_property"); + + value = nullptr; + CHKNRF(env, napi_create_string_latin1(env, sensorInfo.firmwareVersion, NAPI_AUTO_LENGTH, &value), + "napi_create_string_latin1"); + CHKNRF(env, napi_set_named_property(env, result, "firmwareVersion", value), "napi_set_named_property"); + + value = nullptr; + CHKNRF(env, napi_create_string_latin1(env, sensorInfo.hardwareVersion, NAPI_AUTO_LENGTH, &value), + "napi_create_string_latin1"); + CHKNRF(env, napi_set_named_property(env, result, "hardwareVersion", value), "napi_set_named_property"); + + value = nullptr; + CHKNRF(env, napi_create_double(env, sensorInfo.sensorTypeId, &value), "napi_create_double"); + CHKNRF(env, napi_set_named_property(env, result, "sensorTypeId", value), "napi_set_named_property"); + + value = nullptr; + CHKNRF(env, napi_create_double(env, sensorInfo.maxRange, &value), "napi_create_double"); + CHKNRF(env, napi_set_named_property(env, result, "maxRange", value), "napi_set_named_property"); + + value = nullptr; + CHKNRF(env, napi_create_double(env, sensorInfo.precision, &value), "napi_create_double"); + CHKNRF(env, napi_set_named_property(env, result, "precision", value), "napi_set_named_property"); + + value = nullptr; + CHKNRF(env, napi_create_double(env, sensorInfo.power, &value), "napi_create_double"); + CHKNRF(env, napi_set_named_property(env, result, "power", value), "napi_set_named_property"); + return true; } -void ConvertToSingleSensor(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]) +bool ConvertToSingleSensor(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]) { - napi_get_undefined(env, &result[0]); - napi_create_object(env, &result[1]); - ConvertToSensorInfo(env, asyncCallbackInfo->sensorInfos[0], result[1]); + CALL_LOG_ENTER; + CHKPF(asyncCallbackInfo); + return ConvertToSensorInfo(env, asyncCallbackInfo->sensorInfos[0], result[1]); } -void ConvertToSensorInfos(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]) +bool ConvertToSensorInfos(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]) { - napi_get_undefined(env, &result[0]); - napi_create_array(env, &result[1]); - for (size_t i = 0; i < asyncCallbackInfo->sensorInfos.size(); i++) { - napi_value sensorInfo = nullptr; - napi_create_object(env, &sensorInfo); - ConvertToSensorInfo(env, asyncCallbackInfo->sensorInfos[i], sensorInfo); - napi_set_element(env, result[1], i, sensorInfo); + CALL_LOG_ENTER; + CHKPF(asyncCallbackInfo); + CHKNRF(env, napi_create_array(env, &result[1]), "napi_create_array"); + auto sensorInfos = asyncCallbackInfo->sensorInfos; + for (uint32_t i = 0; i < sensorInfos.size(); ++i) { + napi_value value = nullptr; + CHKNCF(env, ConvertToSensorInfo(env, sensorInfos[i], value), "Convert sensor info fail"); + CHKNRF(env, napi_set_element(env, result[1], i, value), "napi_set_element"); } + return true; } -void ConvertToFailData(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]) +bool ConvertToFailData(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]) { + CALL_LOG_ENTER; + CHKPF(asyncCallbackInfo); result[0] = GreateBusinessError(env, asyncCallbackInfo->error.code, asyncCallbackInfo->error.message, asyncCallbackInfo->error.name, asyncCallbackInfo->error.stack); - napi_get_undefined(env, &result[1]); + CHKPF(result[0]); + return true; } -void ConvertToSensorData(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]) +bool ConvertToSensorData(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]) { - napi_get_undefined(env, &result[0]); + CHKPF(asyncCallbackInfo); int32_t sensorTypeId = asyncCallbackInfo->data.sensorData.sensorTypeId; - if ((g_sensorAttributeList.count(sensorTypeId)) == 0 - || g_sensorAttributeList[sensorTypeId].size() - > (asyncCallbackInfo->data.sensorData.dataLength / sizeof(float))) { - HiLog::Error(LABEL, "%{public}s count of sensorTypeId is zero", __func__); - return; + CHKNCF(env, (g_sensorAttributeList.find(sensorTypeId) != g_sensorAttributeList.end()), "Invalid sensor type"); + if (sensorTypeId == SENSOR_TYPE_ID_WEAR_DETECTION && asyncCallbackInfo->type == SUBSCRIBE_CALLBACK) { + return ConvertToBodyData(env, asyncCallbackInfo, result); } - std::vector sensorAttribute = g_sensorAttributeList[sensorTypeId]; - napi_create_object(env, &result[1]); + + size_t size = g_sensorAttributeList[sensorTypeId].size(); + uint32_t dataLenth = asyncCallbackInfo->data.sensorData.dataLength / sizeof(float); + CHKNCF(env, (size <= dataLenth), "Data length mismatch"); + + CHKNRF(env, napi_create_object(env, &result[1]), "napi_create_object"); napi_value message = nullptr; - for (size_t i = 0; i < sensorAttribute.size(); i++) { - napi_create_double(env, asyncCallbackInfo->data.sensorData.data[i], &message); - napi_set_named_property(env, result[1], sensorAttribute[i].c_str(), message); + auto sensorAttributes = g_sensorAttributeList[sensorTypeId]; + for (uint32_t i = 0; i < size; ++i) { + CHKNRF(env, napi_create_double(env, asyncCallbackInfo->data.sensorData.data[i], &message), + "napi_create_double"); + CHKNRF(env, napi_set_named_property(env, result[1], sensorAttributes[i].c_str(), message), + "napi_set_named_property"); message = nullptr; } - napi_create_int64(env, asyncCallbackInfo->data.sensorData.timestamp, &message); - napi_set_named_property(env, result[1], "timestamp", message); + + CHKNRF(env, napi_create_int64(env, asyncCallbackInfo->data.sensorData.timestamp, &message), + "napi_create_int64"); + CHKNRF(env, napi_set_named_property(env, result[1], "timestamp", message), "napi_set_named_property"); + return true; +} + +bool ConvertToGeomagneticData(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]) +{ + CALL_LOG_ENTER; + return getJsonObject(env, asyncCallbackInfo, result[1]); } -void ConvertToNoData(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]) +bool ConvertToBodyData(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]) { - napi_get_undefined(env, &result[1]); - napi_get_undefined(env, &result[0]); + CALL_LOG_ENTER; + CHKPF(asyncCallbackInfo); + CHKNRF(env, napi_create_object(env, &result[1]), "napi_create_object"); + napi_value status = nullptr; + CHKNRF(env, napi_get_boolean(env, asyncCallbackInfo->data.sensorData.data[0], &status), + "napi_get_boolean"); + CHKNRF(env, napi_set_named_property(env, result[1], "value", status), "napi_set_named_property"); + return true; } -void ConvertToGeomagneticData(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]) +bool ConvertToCompass(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]) { - napi_get_undefined(env, &result[0]); - napi_create_object(env, &result[1]); - getJsonObject(env, asyncCallbackInfo, result[1]); + CALL_LOG_ENTER; + CHKPF(asyncCallbackInfo); + CHKNRF(env, napi_create_object(env, &result[1]), "napi_create_object"); + napi_value message = nullptr; + CHKNRF(env, napi_create_double(env, asyncCallbackInfo->data.sensorData.data[0], &message), + "napi_create_double"); + CHKNRF(env, napi_set_named_property(env, result[1], "direction", message), "napi_set_named_property"); + return true; } -void ConvertToNumber(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]) +bool ConvertToNumber(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]) { - napi_get_undefined(env, &result[0]); - napi_create_double(env, static_cast(asyncCallbackInfo->data.reserveData.reserve[0]), &result[1]); + CALL_LOG_ENTER; + CHKPF(asyncCallbackInfo); + napi_status status = + napi_create_double(env, static_cast(asyncCallbackInfo->data.reserveData.reserve[0]), &result[1]); + CHKNRF(env, status, "napi_create_double"); + return true; } -void ConvertToArray(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]) +bool ConvertToArray(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]) { - napi_get_undefined(env, &result[0]); - napi_create_array(env, &result[1]); - CreateNapiArray(env, asyncCallbackInfo->data.reserveData.reserve, + CALL_LOG_ENTER; + CHKPF(asyncCallbackInfo); + bool ret = CreateNapiArray(env, asyncCallbackInfo->data.reserveData.reserve, asyncCallbackInfo->data.reserveData.length, result[1]); + CHKNCF(env, ret, "Create napi array fail"); + return true; } -void ConvertToRotationMatrix(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]) +bool ConvertToRotationMatrix(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]) { - napi_get_undefined(env, &result[0]); - napi_create_object(env, &result[1]); + CALL_LOG_ENTER; + CHKPF(asyncCallbackInfo); napi_value rotation = nullptr; - napi_create_array(env, &rotation); - CreateNapiArray(env, asyncCallbackInfo->data.rationMatrixData.rotationMatrix, + bool ret = CreateNapiArray(env, asyncCallbackInfo->data.rationMatrixData.rotationMatrix, THREE_DIMENSIONAL_MATRIX_LENGTH, rotation); + CHKNCF(env, ret, "Create napi array rotation fail"); + napi_value inclination = nullptr; - napi_create_array(env, &inclination); - CreateNapiArray(env, asyncCallbackInfo->data.rationMatrixData.inclinationMatrix, + ret = CreateNapiArray(env, asyncCallbackInfo->data.rationMatrixData.inclinationMatrix, THREE_DIMENSIONAL_MATRIX_LENGTH, inclination); - napi_set_named_property(env, result[1], "rotation", rotation); - napi_set_named_property(env, result[1], "inclination", inclination); + CHKNCF(env, ret, "Create napi array inclination fail"); + + CHKNRF(env, napi_create_object(env, &result[1]), "napi_create_object"); + CHKNRF(env, napi_set_named_property(env, result[1], "rotation", rotation), + "napi_set_named_property"); + CHKNRF(env, napi_set_named_property(env, result[1], "inclination", inclination), + "napi_set_named_property"); + return true; } -napi_value GreateBusinessError(napi_env env, int32_t errCode, string errMessage, string errName, string errStack) +napi_value GreateBusinessError(const napi_env &env, int32_t errCode, string errMessage, + string errName, string errStack) { + CALL_LOG_ENTER; napi_value result = nullptr; - napi_value code = nullptr; - napi_value message = nullptr; - napi_value name = nullptr; - napi_value stack = nullptr; - NAPI_CALL(env, napi_create_int32(env, errCode, &code)); - NAPI_CALL(env, napi_create_string_utf8(env, errMessage.data(), NAPI_AUTO_LENGTH, &message)); - NAPI_CALL(env, napi_create_string_utf8(env, errName.data(), NAPI_AUTO_LENGTH, &name)); - NAPI_CALL(env, napi_create_string_utf8(env, errStack.data(), NAPI_AUTO_LENGTH, &stack)); - NAPI_CALL(env, napi_create_object(env, &result)); - NAPI_CALL(env, napi_set_named_property(env, result, "code", code)); - NAPI_CALL(env, napi_set_named_property(env, result, "message", message)); - NAPI_CALL(env, napi_set_named_property(env, result, "name", name)); - NAPI_CALL(env, napi_set_named_property(env, result, "stack", stack)); + CHKNRP(env, napi_create_object(env, &result), "napi_create_object"); + napi_value value = nullptr; + CHKNRP(env, napi_create_int32(env, errCode, &value), "napi_create_int32"); + CHKNRP(env, napi_set_named_property(env, result, "code", value), "napi_set_named_property"); + + value = nullptr; + CHKNRP(env, napi_create_string_utf8(env, errMessage.data(), NAPI_AUTO_LENGTH, &value), + "napi_create_string_utf8"); + CHKNRP(env, napi_set_named_property(env, result, "message", value), "napi_set_named_property"); + + value = nullptr; + CHKNRP(env, napi_create_string_utf8(env, errName.data(), NAPI_AUTO_LENGTH, &value), + "napi_create_string_utf8"); + CHKNRP(env, napi_set_named_property(env, result, "name", value), "napi_set_named_property"); + + value = nullptr; + CHKNRP(env, napi_create_string_utf8(env, errStack.data(), NAPI_AUTO_LENGTH, &value), + "napi_create_string_utf8"); + CHKNRP(env, napi_set_named_property(env, result, "stack", value), "napi_set_named_property"); return result; } -void CreateNapiArray(napi_env env, float *data, int32_t dataLength, napi_value result) +bool CreateNapiArray(const napi_env &env, float data[], int32_t dataLength, napi_value &result) { - for (int32_t index = 0; index < dataLength; index++) { + CHKNRF(env, napi_create_array(env, &result), "napi_create_array"); + for (int32_t i = 0; i < dataLength; ++i) { napi_value message = nullptr; - napi_create_double(env, data[index], &message); - napi_set_element(env, result, index, message); + CHKNRF(env, napi_create_double(env, data[i], &message), "napi_create_double"); + CHKNRF(env, napi_set_element(env, result, i, message), "napi_set_element"); } + return true; } -void EmitAsyncCallbackWork(AsyncCallbackInfo *asyncCallbackInfo) +void EmitAsyncCallbackWork(sptr asyncCallbackInfo) { - HiLog::Debug(LABEL, "%{public}s begin", __func__); - if (asyncCallbackInfo == nullptr) { - HiLog::Error(LABEL, "%{public}s asyncCallbackInfo is null!", __func__); - return; - } + CALL_LOG_ENTER; + CHKPV(asyncCallbackInfo); napi_value resourceName = nullptr; - if (napi_create_string_utf8(asyncCallbackInfo->env, "AsyncCallback", NAPI_AUTO_LENGTH, &resourceName) != napi_ok) { - HiLog::Error(LABEL, "%{public}s create string utf8 failed", __func__); - return; - } - napi_create_async_work( - asyncCallbackInfo->env, nullptr, resourceName, + CHKNRV(asyncCallbackInfo->env, napi_create_string_utf8(asyncCallbackInfo->env, "AsyncCallback", + NAPI_AUTO_LENGTH, &resourceName), "napi_create_string_utf8"); + asyncCallbackInfo->IncStrongRef(nullptr); + napi_status status = napi_create_async_work(asyncCallbackInfo->env, nullptr, resourceName, [](napi_env env, void* data) {}, [](napi_env env, napi_status status, void* data) { - HiLog::Debug(LABEL, "%{public}s napi_create_async_work in", __func__); - AsyncCallbackInfo *asyncCallbackInfo = reinterpret_cast(data); - if (asyncCallbackInfo == nullptr) { - HiLog::Error(LABEL, "%{public}s asyncCallbackInfo is null", __func__); - return; - } - napi_value callback; - napi_get_reference_value(env, asyncCallbackInfo->callback[0], &callback); + CALL_LOG_ENTER; + sptr asyncCallbackInfo(static_cast(data)); + /** + * After the asynchronous task is created, the asyncCallbackInfo reference count is reduced + * to 0 destructions, so you need to add 1 to the asyncCallbackInfo reference count when the + * asynchronous task is created, and subtract 1 from the reference count after the naked + * pointer is converted to a pointer when the asynchronous task is executed, the reference + * count of the smart pointer is guaranteed to be 1. + */ + asyncCallbackInfo->DecStrongRef(nullptr); + napi_value callback = nullptr; napi_value callResult = nullptr; napi_value result[2] = {0}; - if (g_convertfuncList.count(asyncCallbackInfo->type) == 0) { - HiLog::Error(LABEL, "%{public}s type invalid", __func__); + 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"); return; } - g_convertfuncList[asyncCallbackInfo->type](env, asyncCallbackInfo, result); - napi_call_function(env, nullptr, callback, 2, result, &callResult); - napi_delete_reference(env, asyncCallbackInfo->callback[0]); - napi_delete_async_work(env, asyncCallbackInfo->asyncWork); - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - HiLog::Debug(LABEL, "%{public}s napi_create_async_work left", __func__); + 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()), + "Callback type invalid in async work"); + bool ret = g_convertfuncList[asyncCallbackInfo->type](env, asyncCallbackInfo, result); + CHKNCV(env, ret, "Create napi data fail in async work"); + CHKNRV(env, napi_call_function(env, nullptr, callback, 2, result, &callResult), + "napi_call_function"); }, - asyncCallbackInfo, &asyncCallbackInfo->asyncWork); + asyncCallbackInfo.GetRefPtr(), &asyncCallbackInfo->asyncWork); + if (status != napi_ok + || napi_queue_async_work(asyncCallbackInfo->env, asyncCallbackInfo->asyncWork) != napi_ok) { + SEN_HILOGE("Create async work fail"); + asyncCallbackInfo->DecStrongRef(nullptr); + } +} - napi_queue_async_work(asyncCallbackInfo->env, asyncCallbackInfo->asyncWork); - HiLog::Debug(LABEL, "%{public}s end", __func__); +void freeWork(uv_work_t *work) +{ + CALL_LOG_ENTER; + CHKPV(work); + delete work; + work = nullptr; } -void EmitUvEventLoop(AsyncCallbackInfo **asyncCallbackInfo) +void EmitUvEventLoop(sptr asyncCallbackInfo) { + CHKPV(asyncCallbackInfo); uv_loop_s *loop(nullptr); - if (asyncCallbackInfo == nullptr || *asyncCallbackInfo == nullptr - || (*asyncCallbackInfo)->env == nullptr) { - HiLog::Error(LABEL, "%{public}s asyncCallbackInfo is null", __func__); - return; - } - napi_get_uv_event_loop((*asyncCallbackInfo)->env, &loop); - if (loop == nullptr) { - HiLog::Error(LABEL, "%{public}s loop is null", __func__); - return; - } + CHKNRV(asyncCallbackInfo->env, napi_get_uv_event_loop(asyncCallbackInfo->env, &loop), + "napi_get_uv_event_loop"); + CHKPV(loop); uv_work_t *work = new(std::nothrow) uv_work_t; - if (work == nullptr) { - HiLog::Error(LABEL, "%{public}s work is null", __func__); - return; - } - work->data = reinterpret_cast(asyncCallbackInfo); - uv_queue_work(loop, work, [] (uv_work_t *work) { }, [] (uv_work_t *work, int status) { - AsyncCallbackInfo *asyncCallbackInfo = *reinterpret_cast(work->data); - if (asyncCallbackInfo == nullptr || asyncCallbackInfo->env == nullptr - || asyncCallbackInfo->callback[0] == nullptr) { - HiLog::Error(LABEL, "%{public}s asyncCallbackInfo is null", __func__); - return; - } + CHKPV(work); + asyncCallbackInfo->work = work; + asyncCallbackInfo->IncStrongRef(nullptr); + work->data = asyncCallbackInfo.GetRefPtr(); + int32_t ret = uv_queue_work(loop, work, [] (uv_work_t *work) { }, [] (uv_work_t *work, int status) { + CHKPV(work); + sptr asyncCallbackInfo(static_cast(work->data)); + /** + * After the asynchronous task is created, the asyncCallbackInfo reference count is reduced + * to 0 destructions, so you need to add 1 to the asyncCallbackInfo reference count when the + * asynchronous task is created, and subtract 1 from the reference count after the naked + * pointer is converted to a pointer when the asynchronous task is executed, the reference + * count of the smart pointer is guaranteed to be 1. + */ + asyncCallbackInfo->DecStrongRef(nullptr); napi_env env = asyncCallbackInfo->env; - napi_value undefined = nullptr; - napi_get_undefined(env, &undefined); napi_value callback = nullptr; - napi_get_reference_value(env, asyncCallbackInfo->callback[0], &callback); + CHKNRV(env, napi_get_reference_value(env, asyncCallbackInfo->callback[0], &callback), + "napi_get_reference_value"); napi_value callResult = nullptr; napi_value result[2] = {0}; - if (g_convertfuncList.count(asyncCallbackInfo->type) == 0) { - HiLog::Error(LABEL, "%{public}s type invalid", __func__); - return; - } + CHKNCV(env, (g_convertfuncList.find(asyncCallbackInfo->type) != g_convertfuncList.end()), + "Asynccallback Type invalid in uv work"); g_convertfuncList[asyncCallbackInfo->type](env, asyncCallbackInfo, result); - napi_call_function(env, undefined, callback, 1, &result[1], &callResult); - if (asyncCallbackInfo->type != ON_CALLBACK) { - napi_delete_reference(env, asyncCallbackInfo->callback[0]); - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - } - delete work; - work = nullptr; + CHKNRV(env, napi_call_function(env, nullptr, callback, 1, &result[1], &callResult), "napi_call_function"); + asyncCallbackInfo->work = nullptr; + freeWork(work); }); + if (ret != 0) { + SEN_HILOGE("uv_queue_work fail"); + asyncCallbackInfo->DecStrongRef(nullptr); + asyncCallbackInfo->work = nullptr; + freeWork(work); + } } -void EmitPromiseWork(AsyncCallbackInfo *asyncCallbackInfo) +void EmitPromiseWork(sptr asyncCallbackInfo) { - if (asyncCallbackInfo == nullptr) { - HiLog::Error(LABEL, "%s asyncCallbackInfo is nullptr!", __func__); - return; - } + CALL_LOG_ENTER; + CHKPV(asyncCallbackInfo); napi_value resourceName = nullptr; - napi_create_string_latin1(asyncCallbackInfo->env, "Promise", NAPI_AUTO_LENGTH, &resourceName); - napi_create_async_work( - asyncCallbackInfo->env, nullptr, resourceName, [](napi_env env, void* data) {}, + CHKNRV(asyncCallbackInfo->env, napi_create_string_latin1(asyncCallbackInfo->env, "Promise", + NAPI_AUTO_LENGTH, &resourceName), "napi_create_string_latin1"); + asyncCallbackInfo->IncStrongRef(nullptr); + napi_status status = napi_create_async_work(asyncCallbackInfo->env, nullptr, resourceName, + [](napi_env env, void* data) {}, [](napi_env env, napi_status status, void* data) { - AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; - if (asyncCallbackInfo == nullptr) { - HiLog::Error(LABEL, "%{public}s asyncCallbackInfo is null", __func__); - return; - } + CALL_LOG_ENTER; + sptr asyncCallbackInfo(static_cast(data)); + /** + * After the asynchronous task is created, the asyncCallbackInfo reference count is reduced + * to 0 destructions, so you need to add 1 to the asyncCallbackInfo reference count when the + * asynchronous task is created, and subtract 1 from the reference count after the naked + * pointer is converted to a pointer when the asynchronous task is executed, the reference + * count of the smart pointer is guaranteed to be 1. + */ + asyncCallbackInfo->DecStrongRef(nullptr); napi_value result[2] = {0}; - if (g_convertfuncList.count(asyncCallbackInfo->type) == 0) { - HiLog::Error(LABEL, "%{public}s type invalid", __func__); - return; - } - g_convertfuncList[asyncCallbackInfo->type](env, asyncCallbackInfo, result); + CHKNCV(env, (g_convertfuncList.find(asyncCallbackInfo->type) != g_convertfuncList.end()), + "Callback type invalid in promise"); + bool ret = g_convertfuncList[asyncCallbackInfo->type](env, asyncCallbackInfo, result); + CHKNCV(env, ret, "Create napi data fail in promise"); if (asyncCallbackInfo->type == FAIL) { - napi_reject_deferred(env, asyncCallbackInfo->deferred, result[0]); + CHKNRV(env, napi_reject_deferred(env, asyncCallbackInfo->deferred, result[0]), + "napi_reject_deferred"); } else { - napi_resolve_deferred(env, asyncCallbackInfo->deferred, result[1]); + CHKNRV(env, napi_resolve_deferred(env, asyncCallbackInfo->deferred, result[1]), + "napi_resolve_deferred"); } - napi_delete_async_work(env, asyncCallbackInfo->asyncWork); - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; }, - (void*)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); - napi_queue_async_work(asyncCallbackInfo->env, asyncCallbackInfo->asyncWork); -} \ No newline at end of file + asyncCallbackInfo.GetRefPtr(), &asyncCallbackInfo->asyncWork); + if (status != napi_ok + || napi_queue_async_work(asyncCallbackInfo->env, asyncCallbackInfo->asyncWork) != napi_ok) { + SEN_HILOGE("Create async work fail"); + asyncCallbackInfo->DecStrongRef(nullptr); + } +} +} // namespace Sensors +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/plugin/src/sensor_system_js.cpp b/interfaces/plugin/src/sensor_system_js.cpp index d17ada02c2545ddd404f2ddcc21eb9a54fe44542..0cb17ae156b1360f09aa8aa9734d6f9a6d0b02e2 100644 --- a/interfaces/plugin/src/sensor_system_js.cpp +++ b/interfaces/plugin/src/sensor_system_js.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,181 +13,171 @@ * limitations under the License. */ #include "sensor_system_js.h" +#include "sensor_js.h" +#include "sensor_napi_utils.h" -#include "hilog/log.h" -#include "sensor_agent_type.h" - -using namespace OHOS::HiviewDFX; -static constexpr HiLogLabel LABEL = {LOG_CORE, 0xD002708, "SensorSystemJs"}; - -static napi_value Subscribe(napi_env env, napi_callback_info info, int32_t sensorTypeId) -{ - return nullptr; -} - -static napi_value Unsubscribe(napi_env env, napi_callback_info info, int32_t sensorTypeId) -{ - return nullptr; -} - +namespace OHOS { +namespace Sensors { napi_value SubscribeAccelerometer(napi_env env, napi_callback_info info) { - HiLog::Debug(LABEL, "%{public}s in", __func__); - return Subscribe(env, info, SENSOR_TYPE_ID_ACCELEROMETER); + CALL_LOG_ENTER; + return Subscribe(env, info, SENSOR_TYPE_ID_ACCELEROMETER, SUBSCRIBE_CALLBACK); } napi_value UnsubscribeAccelerometer(napi_env env, napi_callback_info info) { - HiLog::Debug(LABEL, "%{public}s in", __func__); + CALL_LOG_ENTER; return Unsubscribe(env, info, SENSOR_TYPE_ID_ACCELEROMETER); } napi_value SubscribeCompass(napi_env env, napi_callback_info info) { - HiLog::Debug(LABEL, "%{public}s in", __func__); - return Subscribe(env, info, SENSOR_TYPE_ID_ORIENTATION); + CALL_LOG_ENTER; + return Subscribe(env, info, SENSOR_TYPE_ID_ORIENTATION, SUBSCRIBE_COMPASS); } napi_value UnsubscribeCompass(napi_env env, napi_callback_info info) { - HiLog::Debug(LABEL, "%{public}s in", __func__); + CALL_LOG_ENTER; return Unsubscribe(env, info, SENSOR_TYPE_ID_ORIENTATION); } napi_value SubscribeProximity(napi_env env, napi_callback_info info) { - HiLog::Debug(LABEL, "%{public}s in", __func__); - return Subscribe(env, info, SENSOR_TYPE_ID_PROXIMITY); + CALL_LOG_ENTER; + return Subscribe(env, info, SENSOR_TYPE_ID_PROXIMITY, SUBSCRIBE_CALLBACK); } napi_value UnsubscribeProximity(napi_env env, napi_callback_info info) { - HiLog::Debug(LABEL, "%{public}s in", __func__); + CALL_LOG_ENTER; return Unsubscribe(env, info, SENSOR_TYPE_ID_PROXIMITY); } napi_value SubscribeLight(napi_env env, napi_callback_info info) { - HiLog::Debug(LABEL, "%{public}s in", __func__); - return Subscribe(env, info, SENSOR_TYPE_ID_AMBIENT_LIGHT); + CALL_LOG_ENTER; + return Subscribe(env, info, SENSOR_TYPE_ID_AMBIENT_LIGHT, SUBSCRIBE_CALLBACK); } napi_value UnsubscribeLight(napi_env env, napi_callback_info info) { - HiLog::Debug(LABEL, "%{public}s in", __func__); + CALL_LOG_ENTER; return Unsubscribe(env, info, SENSOR_TYPE_ID_AMBIENT_LIGHT); } napi_value SubscribeStepCounter(napi_env env, napi_callback_info info) { - HiLog::Debug(LABEL, "%{public}s in", __func__); - return Subscribe(env, info, SENSOR_TYPE_ID_PEDOMETER); + CALL_LOG_ENTER; + return Subscribe(env, info, SENSOR_TYPE_ID_PEDOMETER, SUBSCRIBE_CALLBACK); } napi_value UnsubscribeStepCounter(napi_env env, napi_callback_info info) { - HiLog::Debug(LABEL, "%{public}s in", __func__); + CALL_LOG_ENTER; return Unsubscribe(env, info, SENSOR_TYPE_ID_PEDOMETER); } napi_value SubscribeBarometer(napi_env env, napi_callback_info info) { - HiLog::Debug(LABEL, "%{public}s in", __func__); - return Subscribe(env, info, SENSOR_TYPE_ID_BAROMETER); + CALL_LOG_ENTER; + return Subscribe(env, info, SENSOR_TYPE_ID_BAROMETER, SUBSCRIBE_CALLBACK); } napi_value UnsubscribeBarometer(napi_env env, napi_callback_info info) { - HiLog::Debug(LABEL, "%{public}s in", __func__); + CALL_LOG_ENTER; return Unsubscribe(env, info, SENSOR_TYPE_ID_BAROMETER); } napi_value SubscribeHeartRate(napi_env env, napi_callback_info info) { - HiLog::Debug(LABEL, "%{public}s in", __func__); - return Subscribe(env, info, SENSOR_TYPE_ID_HEART_RATE); + CALL_LOG_ENTER; + return Subscribe(env, info, SENSOR_TYPE_ID_HEART_RATE, SUBSCRIBE_CALLBACK); } napi_value UnsubscribeHeartRate(napi_env env, napi_callback_info info) { - HiLog::Debug(LABEL, "%{public}s in", __func__); + CALL_LOG_ENTER; return Unsubscribe(env, info, SENSOR_TYPE_ID_HEART_RATE); } napi_value SubscribeOnBodyState(napi_env env, napi_callback_info info) { - HiLog::Debug(LABEL, "%{public}s in", __func__); - return Subscribe(env, info, SENSOR_TYPE_ID_WEAR_DETECTION); + CALL_LOG_ENTER; + return Subscribe(env, info, SENSOR_TYPE_ID_WEAR_DETECTION, SUBSCRIBE_CALLBACK); } napi_value UnsubscribeOnBodyState(napi_env env, napi_callback_info info) { - HiLog::Debug(LABEL, "%{public}s in", __func__); + CALL_LOG_ENTER; return Unsubscribe(env, info, SENSOR_TYPE_ID_WEAR_DETECTION); } napi_value GetOnBodyState(napi_env env, napi_callback_info info) { - HiLog::Debug(LABEL, "%{public}s in", __func__); - return nullptr; + CALL_LOG_ENTER; + return GetBodyState(env, info); } napi_value SubscribeDeviceOrientation(napi_env env, napi_callback_info info) { - HiLog::Debug(LABEL, "%{public}s in", __func__); - return Subscribe(env, info, SENSOR_TYPE_ID_ORIENTATION); + CALL_LOG_ENTER; + return Subscribe(env, info, SENSOR_TYPE_ID_ORIENTATION, SUBSCRIBE_CALLBACK); } napi_value UnsubscribeDeviceOrientation(napi_env env, napi_callback_info info) { - HiLog::Debug(LABEL, "%{public}s in", __func__); + CALL_LOG_ENTER; return Unsubscribe(env, info, SENSOR_TYPE_ID_ORIENTATION); } napi_value SubscribeGyroscope(napi_env env, napi_callback_info info) { - HiLog::Debug(LABEL, "%{public}s in", __func__); - return Subscribe(env, info, SENSOR_TYPE_ID_GYROSCOPE); + CALL_LOG_ENTER; + return Subscribe(env, info, SENSOR_TYPE_ID_GYROSCOPE, SUBSCRIBE_CALLBACK); } napi_value UnsubscribeGyroscope(napi_env env, napi_callback_info info) { - HiLog::Debug(LABEL, "%{public}s in", __func__); + CALL_LOG_ENTER; return Unsubscribe(env, info, SENSOR_TYPE_ID_GYROSCOPE); } napi_value SubscribeGravity(napi_env env, napi_callback_info info) { - HiLog::Debug(LABEL, "%{public}s in", __func__); - return Subscribe(env, info, SENSOR_TYPE_ID_GRAVITY); + CALL_LOG_ENTER; + return Subscribe(env, info, SENSOR_TYPE_ID_GRAVITY, SUBSCRIBE_CALLBACK); } napi_value UnsubscribeGravity(napi_env env, napi_callback_info info) { - HiLog::Debug(LABEL, "%{public}s in", __func__); + CALL_LOG_ENTER; return Unsubscribe(env, info, SENSOR_TYPE_ID_GRAVITY); } napi_value SubscribeMagnetic(napi_env env, napi_callback_info info) { - HiLog::Debug(LABEL, "%{public}s in", __func__); - return Subscribe(env, info, SENSOR_TYPE_ID_MAGNETIC_FIELD); + CALL_LOG_ENTER; + return Subscribe(env, info, SENSOR_TYPE_ID_MAGNETIC_FIELD, SUBSCRIBE_CALLBACK); } napi_value UnsubscribeMagnetic(napi_env env, napi_callback_info info) { - HiLog::Debug(LABEL, "%{public}s in", __func__); + CALL_LOG_ENTER; return Unsubscribe(env, info, SENSOR_TYPE_ID_MAGNETIC_FIELD); } napi_value SubscribeHall(napi_env env, napi_callback_info info) { - HiLog::Debug(LABEL, "%{public}s in", __func__); - return Subscribe(env, info, SENSOR_TYPE_ID_HALL); + CALL_LOG_ENTER; + return Subscribe(env, info, SENSOR_TYPE_ID_HALL, SUBSCRIBE_CALLBACK); } napi_value UnsubscribeHall(napi_env env, napi_callback_info info) { - HiLog::Debug(LABEL, "%{public}s in", __func__); + CALL_LOG_ENTER; return Unsubscribe(env, info, SENSOR_TYPE_ID_HALL); } +} // namespace Sensors +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/plugin/test/ExampleJsunit.test_system.js b/interfaces/plugin/test/ExampleJsunit.test_system.js new file mode 100644 index 0000000000000000000000000000000000000000..a966ce2f51033e2b88ba26041cdbd69b219bcd7d --- /dev/null +++ b/interfaces/plugin/test/ExampleJsunit.test_system.js @@ -0,0 +1,506 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import sensor from '@system.sensor' + +import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' + +describe("SensorJsTest", function () { + beforeAll(function() { + /* + * @tc.setup: setup invoked before all testcases + */ + console.info('beforeAll caled') + }) + + afterAll(function() { + /* + * @tc.teardown: teardown invoked after all testcases + */ + console.info('afterAll caled') + }) + + beforeEach(function() { + /* + * @tc.setup: setup invoked before each testcases + */ + console.info('beforeEach caled') + }) + + afterEach(function() { + /* + * @tc.teardown: teardown invoked after each testcases + */ + console.info('afterEach caled') + }) + + /* + * @tc.name:SensorJsTest001 + * @tc.desc:verify app info is not null + * @tc.type: FUNC + * @tc.require: SR000H0ALK, AR000H0ALM + */ + it("SensorJsTest001", 0, async function (done) { + console.info('----------------------SensorJsTest001---------------------------'); + sensor.subscribeAccelerometer({ + interval: 'normal', + success: function(data) { + expect(typeof(data.x)).assertEqual("number"); + expect(typeof(data.y)).assertEqual("number"); + expect(typeof(data.z)).assertEqual("number"); + console.info("SensorJsTest001 success" + JSON.stringify(data)); + }, + fail: function(data, code) { + expect(false).assertTrue(); + console.error('Subscription failed. Code: ' + code + '; Data: ' + data); + }, + }); + setTimeout(()=>{ + try { + sensor.unsubscribeAccelerometer(); + } catch (error) { + console.info('SensorJsTest001 unsubscribe failed' + error); + expect(false).assertTrue(); + } + setTimeout(()=>{ + expect(true).assertTrue(); + done(); + }, 500); + }, 1000); + }) + + /* + * @tc.name:SensorJsTest002 + * @tc.desc:verify app info is not null + * @tc.type: FUNC + * @tc.require: SR000H0ALK, AR000H0ALM + */ + it("SensorJsTest002", 0, async function (done) { + console.info('----------------------SensorJsTest002---------------------------'); + sensor.subscribeAccelerometer({ + interval: 'xxx', + success: function(data) { + expect(false).assertTrue(); + console.info("SensorJsTest002 success" + JSON.stringify(data)); + done(); + }, + fail: function(data, code) { + expect(true).assertTrue(); + console.error('SensorJsTest002 Subscription failed. Code: ' + code + '; Data: ' + data); + done(); + }, + }); + }) + + /* + * @tc.name:SensorJsTest003 + * @tc.desc:verify app info is not null + * @tc.type: FUNC + * @tc.require: SR000H0ALK, AR000H0ALM + */ + it("SensorJsTest003", 0, async function (done) { + console.info('----------------------SensorJsTest003---------------------------'); + try { + sensor.subscribeAccelerometer({ + interval: 'xxx', + success: function(data) { + expect(false).assertTrue(); + console.info("SensorJsTest003 success" + JSON.stringify(data)); + done(); + } + }); + } catch (error) { + console.info('SensorJsTest003 Subscription failed' + error); + expect(true).assertTrue(); + done(); + } + }) + + /* + * @tc.name:SensorJsTest004 + * @tc.desc:verify app info is not null + * @tc.type: FUNC + * @tc.require: SR000H0ALK, AR000H0ALM + */ + it("SensorJsTest004", 0, async function (done) { + console.info('----------------------SensorJsTest004---------------------------'); + try { + sensor.subscribeAccelerometer({ + interval: 'normal', + }); + } catch (error) { + console.info('SensorJsTest004 Subscription failed' + error); + expect(true).assertTrue(); + done(); + } + }) + + /* + * @tc.name:SensorJsTest005 + * @tc.desc:verify app info is not null + * @tc.type: FUNC + * @tc.require: SR000H0ALK, AR000H0ALM + */ + it("SensorJsTest005", 0, async function (done) { + console.info('----------------------SensorJsTest005---------------------------'); + try { + sensor.unsubscribeAccelerometer(); + } catch (error) { + console.info(error); + expect(true).assertTrue(); + done(); + } + }) + + /* + * @tc.name:SensorJsTest006 + * @tc.desc:verify app info is not null + * @tc.type: FUNC + * @tc.require: SR000H0ALK, AR000H0ALM + */ + it("SensorJsTest006", 0, async function (done) { + console.info('----------------------SensorJsTest006---------------------------'); + try { + sensor.unsubscribeAccelerometer('xxx'); + } catch (error) { + console.info(error); + expect(true).assertTrue(); + done(); + } + }) + + /* + * @tc.name:SensorJsTest007 + * @tc.desc:verify app info is not null + * @tc.type: FUNC + * @tc.require: SR000H0ALK, AR000H0ALM + */ + it("SensorJsTest007", 0, async function (done) { + console.info('----------------------SensorJsTest007---------------------------'); + sensor.subscribeCompass({ + success: function(data) { + console.log('SensorJsTest007 get data direction:' + ret.direction); + expect(typeof(data.direction)).assertEqual("number"); + }, + fail: function(data, code) { + console.error('SensorJsTest007 Subscription failed. Code: ' + code + '; Data: ' + data); + expect(false).assertTrue(); + }, + }); + setTimeout(()=>{ + try { + sensor.unsubscribeCompass(); + } catch (error) { + console.info(error); + expect(false).assertTrue(); + } + setTimeout(()=>{ + expect(true).assertTrue(); + done(); + }, 500); + }, 1000); + }) + + /* + * @tc.name:SensorJsTest008 + * @tc.desc:verify app info is not null + * @tc.type: FUNC + * @tc.require: SR000H0ALK, AR000H0ALM + */ + it("SensorJsTest008", 0, async function (done) { + sensor.subscribeProximity({ + success: function(data) { + expect(typeof(data.distance)).assertEqual("number"); + console.info("SensorJsTest008 subscribeProximity" + JSON.stringify(data)); + }, + fail: function(data, code) { + console.error('SensorJsTest008 Subscription failed. Code: ' + code + '; Data: ' + data); + expect(true).assertTrue(); + }, + }); + setTimeout(()=>{ + try { + sensor.unsubscribeProximity(); + } catch (error) { + console.info(error); + } + setTimeout(()=>{ + expect(true).assertTrue(); + done(); + }, 500); + }, 1000); + }) + + /* + * @tc.name:SensorJsTest009 + * @tc.desc:verify app info is not null + * @tc.type: FUNC + * @tc.require: SR000H0ALK, AR000H0ALM + */ + it("SensorJsTest009", 0, function (done) { + sensor.subscribeLight({ + success: function(data) { + expect(typeof(data.intensity)).assertEqual("number"); + console.info("SensorJsTest009 subscribeLight" + JSON.stringify(data)); + }, + fail: function(data, code) { + console.error('SensorJsTest009 Subscription failed. Code: ' + code + '; Data: ' + data); + expect(false).assertTrue(); + }, + }); + setTimeout(()=>{ + try { + sensor.unsubscribeLight(); + } catch (error) { + console.info(error); + expect(false).assertTrue(); + } + setTimeout(()=>{ + expect(true).assertTrue(); + done(); + }, 500); + }, 1000); + }) + + /* + * @tc.name:SensorJsTest010 + * @tc.desc:verify app info is not null + * @tc.type: FUNC + * @tc.require: SR000H0ALK, AR000H0ALM + */ + it("SensorJsTest010", 0, async function (done) { + sensor.subscribeStepCounter({ + success: function(data) { + expect(typeof(data.steps)).assertEqual("number"); + console.info("SensorJsTest010 subscribeStepCounter" + JSON.stringify(data)); + }, + fail: function(data, code) { + console.error('SensorJsTest010 Subscription failed. Code: ' + code + '; Data: ' + data); + expect(true).assertTrue(); + }, + }); + setTimeout(()=>{ + try { + sensor.unsubscribeStepCounter(); + } catch (error) { + console.info(error); + } + setTimeout(()=>{ + expect(true).assertTrue(); + done(); + }, 500); + }, 1000); + }) + + /* + * @tc.name:SensorJsTest011 + * @tc.desc:verify app info is not null + * @tc.type: FUNC + * @tc.require: SR000H0ALK, AR000H0ALM + */ + it("SensorJsTest011", 0, async function (done) { + sensor.subscribeBarometer({ + success: function(data) { + expect(typeof(data.pressure)).assertEqual("number"); + console.info("subscribeBarometer" + JSON.stringify(data)); + }, + fail: function(data, code) { + console.error('SensorJsTest011 Subscription failed. Code: ' + code + '; Data: ' + data); + expect(true).assertTrue(); + }, + }); + setTimeout(()=>{ + try { + sensor.unsubscribeBarometer(); + } catch (error) { + console.info(error); + } + setTimeout(()=>{ + expect(true).assertTrue(); + done(); + }, 500); + }, 1000); + }) + + /* + * @tc.name:SensorJsTest012 + * @tc.desc:verify app info is not null + * @tc.type: FUNC + * @tc.require: SR000H0ALK, AR000H0ALM + */ + it("SensorJsTest012", 0, function (done) { + sensor.subscribeHeartRate({ + success: function(data) { + expect(typeof(data.heartRate)).assertEqual("number"); + console.info("SensorJsTest012 subscribeHeartRate" + JSON.stringify(data)); + }, + fail: function(data, code) { + console.error('SensorJsTest012 Subscription failed. Code: ' + code + '; Data: ' + data); + expect(true).assertTrue(); + }, + }); + setTimeout(()=>{ + try { + sensor.unsubscribeHeartRate(); + } catch (error) { + console.info(error); + } + setTimeout(()=>{ + expect(true).assertTrue(); + done(); + }, 500); + }, 1000); + }) + + /* + * @tc.name:SensorJsTest013 + * @tc.desc:verify app info is not null + * @tc.type: FUNC + * @tc.require: SR000H0ALK, AR000H0ALM + */ + it("SensorJsTest013", 0, async function (done) { + console.info('----------------------SensorJsTest013---------------------------'); + sensor.subscribeOnBodyState({ + success: function(data) { + expect(typeof(data.value)).assertEqual("number"); + console.info("SensorJsTest013 subscribeOnBodyState" + JSON.stringify(data)); + }, + fail: function(data, code) { + console.error('SensorJsTest013 Subscription failed. Code: ' + code + '; Data: ' + data); + expect(true).assertTrue(); + }, + }); + setTimeout(()=>{ + try { + sensor.unsubscribeOnBodyState(); + } catch (error) { + console.info(error); + } + setTimeout(()=>{ + expect(true).assertTrue(); + done(); + }, 500); + }, 1000); + }) + + /* + * @tc.name:SensorJsTest014 + * @tc.desc:verify app info is not null + * @tc.type: FUNC + * @tc.require: SR000H0ALK, AR000H0ALM + */ + it('SensorJsTest014', 0, async function (done) { + console.info("---------------------------SensorJsTest014----------------------------------"); + try { + sensor.getOnBodyState({ + success: function(data) { + expect(typeof(data.value)).assertEqual("boolean"); + console.info("subscribeOnBodyState" + JSON.stringify(data)); + done(); + } + }); + } catch (error) { + console.info(error); + expect(false).assertTrue(); + done(); + } + }) + + /* + * @tc.name:SensorJsTest015 + * @tc.desc:verify app info is not null + * @tc.type: FUNC + * @tc.require: SR000H0ALK, AR000H0ALM + */ + it('SensorJsTest015', 0, async function (done) { + console.info("---------------------------SensorJsTest014----------------------------------"); + try { + sensor.getOnBodyState(); + } catch (error) { + console.info(error); + expect(true).assertTrue(); + done(); + } + }) + + /* + * @tc.name:SensorJsTest016 + * @tc.desc:verify app info is not null + * @tc.type: FUNC + * @tc.require: SR000H0ALK, AR000H0ALM + */ + it("SensorJsTest016", 0, async function (done) { + console.info('----------------------SensorJsTest016---------------------------'); + sensor.subscribeDeviceOrientation({ + interval: 'normal', + success: function(data) { + expect(typeof(data.alpha)).assertEqual("number"); + expect(typeof(data.beta)).assertEqual("number"); + expect(typeof(data.gamma)).assertEqual("number"); + console.info("SensorJsTest016 subscribeDeviceOrientation" + JSON.stringify(data)); + }, + fail: function(data, code) { + console.error('SensorJsTest015 Subscription failed. Code: ' + code + '; Data: ' + data); + expect(false).assertTrue(); + }, + }); + setTimeout(()=>{ + try { + sensor.unsubscribeDeviceOrientation(); + } catch (error) { + console.info(error); + expect(false).assertTrue(); + } + setTimeout(()=>{ + expect(true).assertTrue(); + done(); + }, 500); + }, 1000); + }) + + /* + * @tc.name:SensorJsTest017 + * @tc.desc:verify app info is not null + * @tc.type: FUNC + * @tc.require: SR000H0ALK, AR000H0ALM + */ + it("SensorJsTest017", 0, async function (done) { + console.info('----------------------SensorJsTest017---------------------------'); + sensor.subscribeGyroscope({ + interval: 'normal', + success: function(data) { + expect(typeof(data.x)).assertEqual("number"); + expect(typeof(data.y)).assertEqual("number"); + expect(typeof(data.z)).assertEqual("number"); + console.info("SensorJsTest017 subscribeGyroscope" + JSON.stringify(data)); + }, + fail: function(data, code) { + console.error('SensorJsTest017 Subscription failed. Code: ' + code + '; Data: ' + data); + expect(false).assertTrue(); + }, + }); + setTimeout(()=>{ + try { + sensor.unsubscribeGyroscope(); + } catch (error) { + console.info(error); + expect(false).assertTrue(); + } + setTimeout(()=>{ + expect(true).assertTrue(); + done(); + }, 500); + }, 1000); + }) +}) diff --git a/interfaces/plugin/test/unittest/ExampleJsunit.test.js b/interfaces/plugin/test/unittest/ExampleJsunit.test.js index 846955438d7e453f9c06417dfa17335b617869cd..6cd83f2859bb3beb5e347ad9c827fbb4a38b105a 100644 --- a/interfaces/plugin/test/unittest/ExampleJsunit.test.js +++ b/interfaces/plugin/test/unittest/ExampleJsunit.test.js @@ -63,9 +63,9 @@ describe("SensorJsTest", function () { */ it("SensorJsTest001", 0, async function (done) { console.info('----------------------SensorJsTest001---------------------------'); - sensor.on(0, callback); + sensor.on(1, callback); setTimeout(()=>{ - sensor.off(0); + sensor.off(1); done(); }, 500); }) @@ -83,11 +83,13 @@ describe("SensorJsTest", function () { expect(false).assertTrue(); done(); } - sensor.on(-1, onSensorCallback); - setTimeout(()=>{ + try { + sensor.on(-1, onSensorCallback); + } catch (error) { + console.info(error); expect(true).assertTrue(); done(); - }, 500); + } }) /* @@ -98,10 +100,10 @@ describe("SensorJsTest", function () { */ it("SensorJsTest003", 0, async function (done) { console.info('----------------------SensorJsTest003---------------------------'); - sensor.on(0, callback, {'interval': 100000000}); + sensor.on(1, callback, {'interval': 100000000}); setTimeout(()=>{ console.info('----------------------SensorJsTest003 off in---------------------------'); - sensor.off(0); + sensor.off(1); console.info('----------------------SensorJsTest003 off end---------------------------'); done(); }, 500); @@ -113,19 +115,20 @@ describe("SensorJsTest", function () { * @tc.type: FUNC * @tc.require: Issue Number */ - it("SensorJsTest004", 0, function () { + it("SensorJsTest004", 0, function (done) { console.info('----------------------SensorJsTest004---------------------------'); function onSensorCallback(data) { console.info('SensorJsTest004 on error'); expect(false).assertTrue(); done(); } - sensor.on(0, onSensorCallback, {'interval': 100000000}, 5); - setTimeout(()=>{ + try { + sensor.on(1, onSensorCallback, {'interval': 100000000}, 5); + } catch (error) { + console.info(error); expect(true).assertTrue(); done(); - }, 500); - console.info('----------------------SensorJsTest004--------------------------- end'); + } }) /* @@ -135,7 +138,7 @@ describe("SensorJsTest", function () { * @tc.require: Issue Number */ it("SensorJsTest005", 0, async function (done) { - sensor.once(0, callback); + sensor.once(1, callback); setTimeout(()=>{ expect(true).assertTrue(); done(); @@ -154,11 +157,13 @@ describe("SensorJsTest", function () { expect(false).assertTrue(); done(); } - sensor.once(-1, onceSensorCallback); - setTimeout(()=>{ + try { + sensor.once(-1, onceSensorCallback); + } catch (error) { + console.info(error); expect(true).assertTrue(); done(); - }, 500); + } }) /* @@ -167,17 +172,19 @@ describe("SensorJsTest", function () { * @tc.type: FUNC * @tc.require: Issue Number */ - it("SensorJsTest007", 0, function () { + it("SensorJsTest007", 0, function (done) { function onceSensorCallback(data) { console.info('SensorJsTest007 on error'); expect(false).assertTrue(); done(); } - sensor.once(0, onceSensorCallback, 5); - setTimeout(()=>{ + try{ + sensor.once(1, onceSensorCallback, 5); + } catch (error) { + console.info(error); expect(true).assertTrue(); done(); - }, 500); + } }) /* @@ -187,11 +194,13 @@ describe("SensorJsTest", function () { * @tc.require: Issue Number */ it("SensorJsTest008", 0, async function (done) { - sensor.off(-1, callback); - setTimeout(()=>{ + try { + sensor.off(-1, callback); + } catch (error) { + console.info(error); expect(true).assertTrue(); done(); - }, 500); + } }) /* @@ -206,8 +215,8 @@ describe("SensorJsTest", function () { expect(false).assertTrue(); done(); } - sensor.on(0, onSensorCallback); - sensor.off(0, onSensorCallback); + sensor.on(1, onSensorCallback); + sensor.off(1, onSensorCallback); setTimeout(()=>{ expect(true).assertTrue(); done(); @@ -226,11 +235,13 @@ describe("SensorJsTest", function () { expect(false).assertTrue(); done(); } - sensor.off(1000000, onSensorCallback); - setTimeout(()=>{ + try { + sensor.off(1000000, onSensorCallback); + } catch (error) { + console.info(error); expect(true).assertTrue(); done(); - }, 500); + } }) /* @@ -240,11 +251,11 @@ describe("SensorJsTest", function () { * @tc.require: Issue Number */ it("SensorJsTest011", 0, async function (done) { - sensor.on(0, callback); - sensor.on(0, callback2); + sensor.on(1, callback); + sensor.on(1, callback2); setTimeout(()=>{ console.info('----------------------SensorJsTest011 off in---------------------------'); - sensor.off(0); + sensor.off(1); console.info('----------------------SensorJsTest011 off end---------------------------'); done(); }, 1000); @@ -257,12 +268,16 @@ describe("SensorJsTest", function () { * @tc.require: Issue Number */ it("SensorJsTest012", 0, async function (done) { - sensor.on(0, callback); - sensor.on(0, callback2); + sensor.on(1, callback); + sensor.on(1, callback2); + setTimeout(()=>{ + console.info('----------------------SensorJsTest012 off in---------------------------'); + sensor.off(1, callback); + console.info('----------------------SensorJsTest012 off end---------------------------'); + }, 500); setTimeout(()=>{ console.info('----------------------SensorJsTest012 off in---------------------------'); - sensor.off(0, callback); - sensor.off(0, callback2); + sensor.off(1, callback2); console.info('----------------------SensorJsTest012 off end---------------------------'); done(); }, 1000); @@ -274,9 +289,14 @@ describe("SensorJsTest", function () { * @tc.type: FUNC * @tc.require: Issue Number */ - it("SensorJsTest013", 0, function () { - sensor.off(0, 5); - expect(true).assertTrue(); + it("SensorJsTest013", 0, function (done) { + try { + sensor.off(1, 5); + } catch (error) { + console.info(error); + expect(true).assertTrue(); + done(); + } }) /* @@ -287,12 +307,11 @@ describe("SensorJsTest", function () { */ it("SensorJsTest014", 0, async function (done) { console.info('----------------------SensorJsTest014---------------------------'); - sensor.on(0, callback, {'interval': 100000000}); - sensor.once(0, callback2); + sensor.on(1, callback, {'interval': 100000000}); + sensor.once(1, callback2); setTimeout(()=>{ console.info('----------------------SensorJsTest014 off in---------------------------'); - sensor.off(0, callback); - sensor.off(0, callback2); + sensor.off(1); console.info('----------------------SensorJsTest014 off end---------------------------'); done(); }, 1000); @@ -306,12 +325,16 @@ describe("SensorJsTest", function () { */ it("SensorJsTest015", 0, async function (done) { console.info('----------------------SensorJsTest015---------------------------'); - sensor.on(0, callback, {'interval': 100000000}); - sensor.on(0, callback2, {'interval': 100000000}); + sensor.on(1, callback, {'interval': 100000000}); + sensor.on(1, callback2, {'interval': 100000000}); + setTimeout(()=>{ + console.info('----------------------SensorJsTest015 off in---------------------------'); + sensor.off(1, callback); + console.info('----------------------SensorJsTest015 off end---------------------------'); + }, 500); setTimeout(()=>{ console.info('----------------------SensorJsTest015 off in---------------------------'); - sensor.off(0, callback); - sensor.off(0, callback2); + sensor.off(1, callback2); console.info('----------------------SensorJsTest015 off end---------------------------'); done(); }, 1000); @@ -325,11 +348,11 @@ describe("SensorJsTest", function () { */ it("SensorJsTest016", 0, async function (done) { console.info('----------------------SensorJsTest016---------------------------'); - sensor.on(0, callback, {'interval': 100000000}); - sensor.on(0, callback2, {'interval': 100000000}); + sensor.on(1, callback, {'interval': 100000000}); + sensor.on(1, callback2, {'interval': 100000000}); setTimeout(()=>{ console.info('----------------------SensorJsTest016 off in---------------------------'); - sensor.off(0); + sensor.off(1); console.info('----------------------SensorJsTest016 off end---------------------------'); done(); }, 1000); @@ -2581,7 +2604,7 @@ describe("SensorJsTest", function () { */ it("SensorJsTest_113", 0, async function (done) { console.info("---------------------------SensorJsTest_113----------------------------------"); - sensor.getSingleSensor(0, (error, data) => { + sensor.getSingleSensor(1, (error, data) => { if (error) { console.info('SensorJsTest_113 failed'); expect(false).assertTrue(); @@ -2623,7 +2646,7 @@ describe("SensorJsTest", function () { */ it("SensorJsTest_115", 0, async function (done) { console.info("---------------------------SensorJsTest_115----------------------------------"); - sensor.getSingleSensor(0).then((data) => { + sensor.getSingleSensor(1).then((data) => { console.info("SensorJsTest_115 " + JSON.stringify(data)); expect(true).assertTrue(); done() diff --git a/utils/include/sensor_log.h b/utils/include/sensor_log.h new file mode 100644 index 0000000000000000000000000000000000000000..b252ddc585a1eb8396580e8fa69dcc83bf5f9abc --- /dev/null +++ b/utils/include/sensor_log.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2021-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_LOG_H +#define SENSOR_LOG_H + +#include "hilog/log.h" + +namespace OHOS { +namespace Sensors { +namespace { +constexpr uint32_t SENSOR_LOG_DOMAIN = 0xD002800; +} // namespace +#ifndef SENSOR_FUNC_FMT +#define SENSOR_FUNC_FMT "in %{public}s, " +#endif + +#ifndef SENSOR_FUNC_INFO +#define SENSOR_FUNC_INFO __FUNCTION__ +#endif + +#define SEN_HILOGD(fmt, ...) do { \ + OHOS::HiviewDFX::HiLog::Debug(LABEL, SENSOR_FUNC_FMT fmt, SENSOR_FUNC_INFO, ##__VA_ARGS__); \ +} while (0) +#define SEN_HILOGI(fmt, ...) do { \ + OHOS::HiviewDFX::HiLog::Info(LABEL, SENSOR_FUNC_FMT fmt, SENSOR_FUNC_INFO, ##__VA_ARGS__); \ +} while (0) +#define SEN_HILOGW(fmt, ...) do { \ + OHOS::HiviewDFX::HiLog::Warn(LABEL, SENSOR_FUNC_FMT fmt, SENSOR_FUNC_INFO, ##__VA_ARGS__); \ +} while (0) +#define SEN_HILOGE(fmt, ...) do { \ + OHOS::HiviewDFX::HiLog::Error(LABEL, SENSOR_FUNC_FMT fmt, SENSOR_FUNC_INFO, ##__VA_ARGS__); \ +} while (0) +#define SENSOR_LOGF(fmt, ...) do { \ + OHOS::HiviewDFX::HiLog::Fatal(LABEL, SENSOR_FUNC_FMT fmt, SENSOR_FUNC_INFO, ##__VA_ARGS__); \ +} while (0) +} // namespace Sensors +} // namespace OHOS +#endif // SENSOR_LOG_H \ No newline at end of file diff --git a/utils/include/sensors_errors.h b/utils/include/sensors_errors.h index 38a2d16b83317df5138c3ecb6e4b5c337724ae8a..f7ced51e22c4903d60a2923a0e4c5f586f874b93 100644 --- a/utils/include/sensors_errors.h +++ b/utils/include/sensors_errors.h @@ -17,6 +17,9 @@ #define SENSORS_ERRORS_H #include +#include + +#include "hilog/log.h" namespace OHOS { namespace Sensors { @@ -105,6 +108,176 @@ enum { SENSOR_NATIVE_GET_SERVICE_ERR = SENSOR_NATIVE_SAM_ERR + 1, SENSOR_NATIVE_REGSITER_CB_ERR = SENSOR_NATIVE_GET_SERVICE_ERR + 1, }; + +class InnerFunctionTracer { +public: + InnerFunctionTracer(const OHOS::HiviewDFX::HiLogLabel& label, const char *func) + : label_ { label }, func_ { func } + { + OHOS::HiviewDFX::HiLog::Debug(label_, "in %{public}s, enter", func_); + } + ~InnerFunctionTracer() + { + OHOS::HiviewDFX::HiLog::Debug(label_, "in %{public}s, leave", func_); + } +private: + const OHOS::HiviewDFX::HiLogLabel& label_; + const char* func_ { nullptr }; +}; + +#define CALL_LOG_ENTER InnerFunctionTracer ___innerFuncTracer___ { LABEL, __FUNCTION__ } + +#ifdef DEBUG_CODE_TEST +#define CHKPL(cond, ...) \ + do { \ + if ((cond) == nullptr) { \ + SEN_HILOGW("%{public}s, (%{public}d), CHKPL(%{public}s) is null, do nothing", \ + __FILE__, __LINE__, #cond); \ + } \ + } while (0) + +#define CHKPV(cond) \ + do { \ + if ((cond) == nullptr) { \ + SEN_HILOGE("%{public}s, (%{public}d), CHKPV(%{public}s) is null", \ + __FILE__, __LINE__, #cond); \ + return; \ + } \ + } while (0) + +#define CHKPF(cond) \ + do { \ + if ((cond) == nullptr) { \ + SEN_HILOGE("%{public}s, (%{public}d), CHKPF(%{public}s) is null", \ + __FILE__, __LINE__, #cond); \ + return false; \ + } \ + } while (0) + +#define CHKPC(cond) \ + { \ + if ((cond) == nullptr) { \ + SEN_HILOGW("%{public}s, (%{public}d), CHKPC(%{public}s) is null, skip then continue", \ + __FILE__, __LINE__, #cond); \ + continue; \ + } \ + } + +#define CHKPB(cond) \ + { \ + if ((cond) == nullptr) { \ + SEN_HILOGW("%{public}s, (%{public}d), CHKPC(%{public}s) is null, skip then break", \ + __FILE__, __LINE__, #cond); \ + break; \ + } \ + } + +#define CHKPR(cond, r) \ + do { \ + if ((cond) == nullptr) { \ + SEN_HILOGE("%{public}s, (%{public}d), CHKPR(%{public}s) is null, return value is %{public}d", \ + __FILE__, __LINE__, #cond, r); \ + return r; \ + } \ + } while (0) + +#define CHKPP(cond) \ + do { \ + if ((cond) == nullptr) { \ + SEN_HILOGE("%{public}s, (%{public}d), CHKPP(%{public}s) is null, return value is null", \ + __FILE__, __LINE__, #cond); \ + return nullptr; \ + } \ + } while (0) + +#define CK(cond, ec) \ + do { \ + if (!(cond)) { \ + SEN_HILOGE("%{public}s, (%{public}d), CK(%{public}s), errCode:%{public}d", \ + __FILE__, __LINE__, #cond, ec); \ + } \ + } while (0) + +#else // DEBUG_CODE_TEST +#define CHKPL(cond) \ + do { \ + if ((cond) == nullptr) { \ + SEN_HILOGW("CHKPL(%{public}s) is null, do nothing", #cond); \ + } \ + } while (0) + +#define CHKPV(cond) \ + do { \ + if ((cond) == nullptr) { \ + SEN_HILOGE("CHKPV(%{public}s) is null", #cond); \ + return; \ + } \ + } while (0) + +#define CHKPF(cond) \ + do { \ + if ((cond) == nullptr) { \ + SEN_HILOGE("CHKPF(%{public}s) is null", #cond); \ + return false; \ + } \ + } while (0) + +#define CHKPC(cond) \ + { \ + if ((cond) == nullptr) { \ + SEN_HILOGW("CHKPC(%{public}s) is null, skip then continue", #cond); \ + continue; \ + } \ + } + +#define CHKPB(cond) \ + { \ + if ((cond) == nullptr) { \ + SEN_HILOGW("CHKPC(%{public}s) is null, skip then break", #cond); \ + break; \ + } \ + } + +#define CHKPR(cond, r) \ + do { \ + if ((cond) == nullptr) { \ + SEN_HILOGE("CHKPR(%{public}s) is null, return value is %{public}d", #cond, r); \ + return r; \ + } \ + } while (0) + +#define CHKCF(cond, message) \ + do { \ + if (!(cond)) { \ + SEN_HILOGE("CK(%{public}s), %{public}s", #cond, message); \ + return false; \ + } \ + } while (0) + +#define CHKCV(cond, message) \ + do { \ + if (!(cond)) { \ + SEN_HILOGE("CK(%{public}s), %{public}s", #cond, message); \ + return; \ + } \ + } while (0) + +#define CHKPP(cond) \ + do { \ + if ((cond) == nullptr) { \ + SEN_HILOGE("CHKPP(%{public}s) is null, return value is null", #cond); \ + return nullptr; \ + } \ + } while (0) + +#define CK(cond, ec) \ + do { \ + if (!(cond)) { \ + SEN_HILOGE("CK(%{public}s), errCode:%{public}d", #cond, ec); \ + } \ + } while (0) + +#endif } // namespace Sensors } // namespace OHOS #endif // SENSORS_ERRORS_H