diff --git a/frameworks/native/sensor/BUILD.gn b/frameworks/native/sensor/BUILD.gn index 6c5824e7a1d592df50495223f6ee9c47e0ed8dce..35fa0fe1b97def4c0ccb9f8217c185c495f8e3f7 100755 --- a/frameworks/native/sensor/BUILD.gn +++ b/frameworks/native/sensor/BUILD.gn @@ -39,7 +39,6 @@ ohos_shared_library("libsensor_native") { "//drivers/peripheral/sensor/interfaces/include", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", "//foundation/appexecfwk/standard/libs/test/moduletest/common/event_handler", - "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", ] deps = [ "$SUBSYSTEM_DIR/sensor/services/sensor:libsensor_service", diff --git a/frameworks/native/sensor/include/my_file_descriptor_listener.h b/frameworks/native/sensor/include/my_file_descriptor_listener.h index 25cc58fd879470b689c5fb0c780e96bf326e5b35..a2a5ff7a608e3a864b71e4042570fdc5fac27f1a 100755 --- a/frameworks/native/sensor/include/my_file_descriptor_listener.h +++ b/frameworks/native/sensor/include/my_file_descriptor_listener.h @@ -32,7 +32,7 @@ class MyFileDescriptorListener : public AppExecFwk::FileDescriptorListener { public: explicit MyFileDescriptorListener(); - ~MyFileDescriptorListener() = default; + ~MyFileDescriptorListener(); void OnReadable(int32_t fileDescriptor) override; @@ -41,7 +41,7 @@ public: void OnShutdown(int32_t fileDescriptor) override; void OnException(int32_t fileDescriptor) override; - + void SetChannel(SensorDataChannel* channel); private: diff --git a/frameworks/native/sensor/src/my_file_descriptor_listener.cpp b/frameworks/native/sensor/src/my_file_descriptor_listener.cpp index f7db8c869ce79fbebd4fa939aa67fd4bed7f097e..a16f79d0bbf59e1510c183c76b19915ebdc00195 100755 --- a/frameworks/native/sensor/src/my_file_descriptor_listener.cpp +++ b/frameworks/native/sensor/src/my_file_descriptor_listener.cpp @@ -32,6 +32,15 @@ MyFileDescriptorListener::MyFileDescriptorListener() new (std::nothrow) TransferSensorEvents[sizeof(struct TransferSensorEvents) * RECEIVE_DATA_SIZE]) {} +MyFileDescriptorListener::~MyFileDescriptorListener() +{ + HiLog::Debug(LABEL, "%{public}s begin", __func__); + if (receiveDataBuff_ != nullptr) { + delete[] receiveDataBuff_; + receiveDataBuff_ = nullptr; + } +} + void MyFileDescriptorListener::OnReadable(int32_t fileDescriptor) { HiLog::Debug(LABEL, "%{public}s begin", __func__); @@ -83,6 +92,7 @@ void MyFileDescriptorListener::OnShutdown(int32_t fileDescriptor) FileDescriptorListener::OnShutdown(fileDescriptor); if (receiveDataBuff_ != nullptr) { delete[] receiveDataBuff_; + receiveDataBuff_ = nullptr; } } @@ -96,6 +106,7 @@ void MyFileDescriptorListener::OnException(int32_t fileDescriptor) FileDescriptorListener::OnException(fileDescriptor); if (receiveDataBuff_ != nullptr) { delete[] receiveDataBuff_; + receiveDataBuff_ = nullptr; } } } // namespace Sensors diff --git a/frameworks/native/sensor/src/sensor_agent_proxy.cpp b/frameworks/native/sensor/src/sensor_agent_proxy.cpp index b00e7e3d9839b3202f6fe33a92ea715efda6b81c..ce29e2f1354607ca81848b8d6f485878851fab54 100755 --- a/frameworks/native/sensor/src/sensor_agent_proxy.cpp +++ b/frameworks/native/sensor/src/sensor_agent_proxy.cpp @@ -344,7 +344,7 @@ int32_t SensorAgentProxy::GetAllSensors(SensorInfo **sensorInfo, int32_t *count) return OHOS::Sensors::ERROR; } const char *version = std::to_string(sensorList_[index].GetVersion()).c_str(); - ret = strcpy_s((*sensorInfo + index)->hardwareVersion, SENSOR_NAME_MAX_LEN2, version); + ret = strcpy_s((*sensorInfo + index)->hardwareVersion, VERSION_MAX_LEN, version); if (ret != EOK) { HiLog::Error(LABEL, "%{public}s strcpy hardwareVersion failed", __func__); return OHOS::Sensors::ERROR; diff --git a/interfaces/native/BUILD.gn b/interfaces/native/BUILD.gn index d9c5afb0156aa26db7cde9e97b2eecd15dfe3c84..91a938c4410a8e326a1944fc43ec3a5f84cbdf55 100755 --- a/interfaces/native/BUILD.gn +++ b/interfaces/native/BUILD.gn @@ -24,7 +24,11 @@ ohos_ndk_library("libsensor_ndk") { ohos_shared_library("sensor_interface_native") { output_name = "sensor_agent" - sources = [ "src/sensor_agent.cpp" ] + sources = [ + "src/geomagnetic_field.cpp", + "src/sensor_agent.cpp", + "src/sensor_algorithm.cpp", + ] include_dirs = [ "include", @@ -37,7 +41,6 @@ ohos_shared_library("sensor_interface_native") { "$SUBSYSTEM_DIR/interfaces/native/include", "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", - "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", ] deps = [ "$SUBSYSTEM_DIR/frameworks/native/sensor:libsensor_native", @@ -46,10 +49,7 @@ ohos_shared_library("sensor_interface_native") { "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", "//utils/native/base:utils", ] - external_deps = [ - "hiviewdfx_hilog_native:libhilog", - "ipc:ipc_core", - ] + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] part_name = "sensor" subsystem_name = "sensors" } diff --git a/interfaces/native/include/geomagnetic_field.h b/interfaces/native/include/geomagnetic_field.h new file mode 100755 index 0000000000000000000000000000000000000000..d58584bd99ba6fa633f575fe3e901b820ee5ba12 --- /dev/null +++ b/interfaces/native/include/geomagnetic_field.h @@ -0,0 +1,88 @@ +/* + * 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. + */ + +#ifndef GEOMAGNETIC_FIELD_H +#define GEOMAGNETIC_FIELD_H + +#include +#include +#include +#include +#include +#include +#include +#include "iostream" + +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(); + +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); +}; +#endif // GEOMAGNETIC_FIELD_H \ No newline at end of file diff --git a/interfaces/native/include/sensor_algorithm.h b/interfaces/native/include/sensor_algorithm.h new file mode 100755 index 0000000000000000000000000000000000000000..7f6154cc77f4fa34388595b620db067dea848798 --- /dev/null +++ b/interfaces/native/include/sensor_algorithm.h @@ -0,0 +1,56 @@ +/* + * 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. + */ + +#ifndef SENSOR_ALGORITHM_H +#define SENSOR_ALGORITHM_H + +#include +#include + +class SensorAlgorithm { +public: + SensorAlgorithm() = default; + ~SensorAlgorithm() = default; + static constexpr int32_t QUATERNION_LENGTH = 4; + static constexpr int32_t ROTATION_VECTOR_LENGTH = 3; + static constexpr int32_t THREE_DIMENSIONAL_MATRIX_LENGTH = 9; + static constexpr int32_t FOUR_DIMENSIONAL_MATRIX_LENGTH = 16; + + int32_t createQuaternion(std::vector rotationVector, std::vector &quaternion); + + int32_t transformCoordinateSystem(std::vector inRotationMatrix, int32_t axisX, + int32_t axisY, std::vector &outRotationMatrix); + + int32_t getAltitude(float seaPressure, float currentPressure, float *altitude); + + int32_t getGeomagneticDip(std::vector inclinationMatrix, float *geomagneticDip); + + int32_t getAngleModify(std::vector currotationMatrix, std::vector prerotationMatrix, + std::vector &angleChange); + + int32_t getDirection(std::vector rotationMatrix, std::vector &rotationAngle); + + int32_t createRotationMatrix(std::vector rotationVector, std::vector &rotationMatrix); + + int32_t createRotationAndInclination(std::vector gravity, std::vector geomagnetic, + std::vector &rotationMatrix, std::vector &inclinationMatrix); +private: + int32_t transformCoordinateSystemImpl(std::vector inRotationMatrix, int32_t axisX, + int32_t axisY, std::vector &outRotationMatrix); + static constexpr float GRAVITATIONAL_ACCELERATION = 9.81f; + static constexpr float RECIPROCAL_COEFFICIENT = 5.255f; + static constexpr float ZERO_PRESSURE_ALTITUDE = 44330.0f; +}; +#endif // SENSOR_ALGORITHM_H diff --git a/interfaces/native/src/geomagnetic_field.cpp b/interfaces/native/src/geomagnetic_field.cpp new file mode 100755 index 0000000000000000000000000000000000000000..3de603309da6718ec956fb31caf6625967069191 --- /dev/null +++ b/interfaces/native/src/geomagnetic_field.cpp @@ -0,0 +1,312 @@ +/* + * 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. + */ + +#include "geomagnetic_field.h" +#include "sensors_log_domain.h" + +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; +// 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] = { + {0.0f}, + {-29404.5f, -1450.7f}, + {-2500.0f, 2982.0f, 1676.8f}, + {1363.9f, -2381.0f, 1236.2f, 525.7f}, + {903.1f, 809.4f, 86.2f, -309.4f, 47.9f}, + {-234.4f, 363.1f, 187.8f, -140.7f, -151.2f, 13.7f}, + {65.9f, 65.6f, 73.0f, -121.5f, -36.2f, 13.5f, -64.7f}, + {80.6f, -76.8f, -8.3f, 56.5f, 15.8f, 6.4f, -7.2f, 9.8f}, + {23.6f, 9.8f, -17.5f, -0.4f, -21.1f, 15.3f, 13.7f, -16.5f, -0.3f}, + {5.0f, 8.2f, 2.9f, -1.4f, -1.1f, -13.3f, 1.1f, 8.9f, -9.3f, -11.9f}, + {-1.9f, -6.2f, -0.1f, 1.7f, -0.9f, 0.6f, -0.9f, 1.9f, 1.4f, -2.4f, -3.9f}, + {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] = { + {0.0f}, + {0.0f, 4652.9f}, + {0.0f, -2991.6f, -734.8f}, + {0.0f, -82.2f, 241.8f, -542.9f}, + {0.0f, 282.0f, -158.4f, 199.8f, -350.1f}, + {0.0f, 47.7f, 208.4f, -121.3f, 32.2f, 99.1f}, + {0.0f, -19.1f, 25.0f, 52.7f, -64.4f, 9.0f, 68.1f}, + {0.0f, -51.4f, -16.8f, 2.3f, 23.5f, -2.2f, -27.2f, -1.9f}, + {0.0f, 8.4f, -15.3f, 12.8f, -11.8f, 14.9f, 3.6f, -6.9f, 2.8f}, + {0.0f, -23.3f, 11.1f, 9.8f, -5.1f, -6.2f, 7.8f, 0.4f, -1.5f, 9.7f}, + {0.0f, 3.4f, -0.2f, 3.5f, 4.8f, -8.6f, -0.1f, -4.2f, -3.4f, -0.1f, -8.8f}, + {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] = { + {0.0f}, + {6.7f, 7.7f}, + {-11.5f, -7.1f, -2.2f}, + {2.8f, -6.2f, 3.4f, -12.2f}, + {-1.1f, -1.6f, -6.0f, 5.4f, -5.5f}, + {-0.3f, 0.6f, -0.7f, 0.1f, 1.2f, 1.0f}, + {-0.6f, -0.4f, 0.5f, 1.4f, -1.4f, 0.0f, 0.8f}, + {-0.1f, -0.3f, -0.1f, 0.7f, 0.2f, -0.5f, -0.8f, 1.0f}, + {-0.1f, 0.1f, -0.1f, 0.5f, -0.1f, 0.4f, 0.5f, 0.0f, 0.4f}, + {-0.1f, -0.2f, 0.0f, 0.4f, -0.3f, 0.0f, 0.3f, 0.0f, 0.0f, -0.4f}, + {0.0f, 0.0f, 0.0f, 0.2f, -0.1f, -0.2f, 0.0f, -0.1f, -0.2f, -0.1f, 0.0f}, + {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] = { + {0.0f}, + {0.0f, -25.1f}, + {0.0f, -30.2f, -23.9f}, + {0.0f, 5.7f, -1.0f, 1.1f}, + {0.0f, 0.2f, 6.9f, 3.7f, -5.6f}, + {0.0f, 0.1f, 2.5f, -0.9f, 3.0f, 0.5f}, + {0.0f, 0.1f, -1.8f, -1.4f, 0.9f, 0.1f, 1.0f}, + {0.0f, 0.5f, 0.6f, -0.7f, -0.2f, -1.2f, 0.2f, 0.3f}, + {0.0f, -0.3f, 0.7f, -0.2f, 0.5f, -0.3f, -0.5f, 0.4f, 0.1f}, + {0.0f, -0.3f, 0.2f, -0.4f, 0.4f, 0.1f, 0.0f, -0.2f, 0.5f, 0.2f}, + {0.0f, 0.0f, 0.1f, -0.3f, 0.1f, -0.2f, 0.1f, 0.0f, -0.1f, 0.2f, 0.0f}, + {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} +}; + +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; + +GeomagneticField::GeomagneticField(float latitude, float longitude, float altitude, int64_t timeMillis) +{ + 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); +} + +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))); + } + } + return schmidtQuasiNormFactors; +} + +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(); + 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] + * inverseCosLatitude; + gcZ -= (rowIndex + 1) * relativeRadiusPower[rowIndex + 2] + * (g * cosMLongitude[columnIndex] + h * sinMLongitude[columnIndex]) + * polynomials[rowIndex][columnIndex] + * schmidtQuasiNormalFactors[rowIndex][columnIndex]; + } + northComponent = static_cast(gcX * cos(latDiffRad) + gcZ * sin(latDiffRad)); + eastComponent = gcY; + downComponent = static_cast(-gcX * sin(latDiffRad) + gcZ * cos(latDiffRad)); + } +} + +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 (uint32_t index = 2; index < GAUSSIAN_COEFFICIENT_DIMENSION; ++index) { + int32_t x = index >> 1; + sinMLongitude[index] = (sinMLongitude[index - x] * cosMLongitude[x] + + cosMLongitude[index - x] * sinMLongitude[x]); + cosMLongitude[index] = (cosMLongitude[index - x] * cosMLongitude[x] + - sinMLongitude[index - x] * sinMLongitude[x]); + } +} + +void GeomagneticField::getRelativeRadiusPower() +{ + HiLog::Info(LABEL, "%{public}s begin", __func__); + relativeRadiusPower[0] = 1.0f; + relativeRadiusPower[1] = EARTH_REFERENCE_RADIUS / geocentricRadius; + for (int32_t index = 2; index < relativeRadiusPower.size(); ++index) { + relativeRadiusPower[index] = relativeRadiusPower[index - 1] * relativeRadiusPower[1]; + } +} + +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); + 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)); + + float radSq = altitudeKm * altitudeKm + 2 * altitudeKm + * latRad + (a2 * a2 * clat * clat + b2 * b2 * slat * slat) + / (a2 * clat * clat + b2 * slat * slat); + geocentricRadius = static_cast(sqrt(radSq)); +} + +void GeomagneticField::initLegendreTable(int32_t expansionDegree, float thetaRad) +{ + HiLog::Info(LABEL, "%{public}s begin", __func__); + polynomials[0].resize(1); + polynomials[0][0] = 1.0f; + polynomialsDerivative[0].resize(1); + 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]; + } 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 GeomagneticField::obtainX() +{ + HiLog::Info(LABEL, "%{public}s begin", __func__); + return northComponent; +} + +float GeomagneticField::obtainY() +{ + HiLog::Info(LABEL, "%{public}s begin", __func__); + return eastComponent; +} + +float GeomagneticField::obtainZ() +{ + HiLog::Info(LABEL, "%{public}s begin", __func__); + return downComponent; +} + +float GeomagneticField::obtainGeomagneticDip() +{ + return static_cast(toDegrees(atan2(downComponent, obtainLevelIntensity()))); +} + +double GeomagneticField::toDegrees(double angrad) +{ + return angrad * 180.0 / M_PI; +} + +double GeomagneticField::toRadians(double angdeg) +{ + return angdeg / 180.0 * M_PI; +} + +float GeomagneticField::obtainDeflectionAngle() +{ + HiLog::Info(LABEL, "%{public}s begin", __func__); + return static_cast(toDegrees(atan2(eastComponent, northComponent))); +} + +float GeomagneticField::obtainLevelIntensity() +{ + HiLog::Info(LABEL, "%{public}s begin", __func__); + float horizontalIntensity = hypot(northComponent, eastComponent); + return horizontalIntensity; +} + +float GeomagneticField::obtainTotalIntensity() +{ + HiLog::Info(LABEL, "%{public}s begin", __func__); + float sumOfSquares = northComponent * northComponent + eastComponent * eastComponent + + downComponent * downComponent; + float totalIntensity = static_cast(sqrt(sumOfSquares)); + return totalIntensity; +} + diff --git a/interfaces/native/src/sensor_algorithm.cpp b/interfaces/native/src/sensor_algorithm.cpp new file mode 100755 index 0000000000000000000000000000000000000000..ebbca9f5ca5abee180c1df53fa387eeebb899ff8 --- /dev/null +++ b/interfaces/native/src/sensor_algorithm.cpp @@ -0,0 +1,351 @@ +/* + * 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. + */ +#include "sensor_algorithm.h" + +#include +#include +#include "sensors_errors.h" +#include "sensors_log_domain.h" + +using OHOS::HiviewDFX::HiLog; +using OHOS::HiviewDFX::HiLogLabel; + +static constexpr HiLogLabel LABEL = {LOG_CORE, OHOS::SensorsLogDomain::SENSORS_INTERFACE, "SensorAlgorithmAPI"}; + +int32_t SensorAlgorithm::createQuaternion(std::vector rotationVector, std::vector &quaternion) +{ + if (rotationVector.size() < ROTATION_VECTOR_LENGTH) { + HiLog::Error(LABEL, "%{public}s Invalid input rotationVector parameter", __func__); + return OHOS::Sensors::ERROR; + } + if (quaternion.size() < 4) { + HiLog::Error(LABEL, "%{public}s Invalid input quaternion parameter", __func__); + return OHOS::Sensors::ERROR; + } + if (rotationVector.size() == ROTATION_VECTOR_LENGTH) { + quaternion[0] = 1 - static_cast((pow(rotationVector[0], 2) + pow(rotationVector[1], 2) + + pow(rotationVector[2], 2))); + quaternion[0] = (quaternion[0] > 0) ? static_cast(std::sqrt(quaternion[0])) : 0; + } else { + quaternion[0] = rotationVector[3]; + } + quaternion[1] = rotationVector[0]; + quaternion[2] = rotationVector[1]; + quaternion[3] = rotationVector[2]; + return OHOS::Sensors::SUCCESS; +} + +int32_t SensorAlgorithm::transformCoordinateSystemImpl(std::vector inRotationMatrix, int32_t axisX, + int32_t axisY, std::vector &outRotationMatrix) +{ + if ((axisX & 0x7C) != 0 || (axisX & 0x3) == 0) { + HiLog::Error(LABEL, "%{public}s axisX is invalid parameter", __func__); + return OHOS::Sensors::ERROR; + } + if ((axisY & 0x7C) != 0 || (axisY & 0x3) == 0 || (axisX & 0x3) == (axisY & 0x3)) { + HiLog::Error(LABEL, "%{public}s axisY is invalid parameter", __func__); + return OHOS::Sensors::ERROR; + } + int32_t axisZ = axisX ^ axisY; + + int32_t x = (axisX & 0x3) - 1; + int32_t y = (axisY & 0x3) - 1; + int32_t z = (axisZ & 0x3) - 1; + if (((x ^ ((z + 1) % 3)) | ( y ^ ((z + 2) % 3))) != 0) { + axisZ ^= 0x80; + } + int32_t inRotationMatrixLength = inRotationMatrix.size(); + int32_t matrixDimension = ((inRotationMatrixLength == FOUR_DIMENSIONAL_MATRIX_LENGTH) + ? QUATERNION_LENGTH : ROTATION_VECTOR_LENGTH); + for (int32_t j = 0; j < ROTATION_VECTOR_LENGTH; j++) { + int32_t offset = j * matrixDimension; + for (int32_t i = 0; i < 3; i++) { + if (x == i) { + outRotationMatrix[offset + i] = (axisX >= 0x80) ? -inRotationMatrix[offset + 0] : inRotationMatrix[offset + 0]; + } + if (y == i) { + outRotationMatrix[offset + i] = (axisY >= 0x80) ? -inRotationMatrix[offset + 1] : inRotationMatrix[offset + 1]; + } + if (z == i) { + outRotationMatrix[offset + i] = (axisZ >= 0x80) ? -inRotationMatrix[offset + 2] : inRotationMatrix[offset + 2]; + } + } + } + + if (inRotationMatrixLength == FOUR_DIMENSIONAL_MATRIX_LENGTH) { + outRotationMatrix[3] = outRotationMatrix[7] = outRotationMatrix[11] = + outRotationMatrix[12] = outRotationMatrix[13] = outRotationMatrix[14] = 0; + outRotationMatrix[15] = 1; + } + return OHOS::Sensors::SUCCESS; +} + +int32_t SensorAlgorithm::transformCoordinateSystem(std::vector inRotationMatrix, int32_t axisX, int32_t axisY, + std::vector &outRotationMatrix) +{ + HiLog::Info(LABEL, "%{public}s inRotationMatrix start", __func__); + int32_t inRotationMatrixLength = inRotationMatrix.size(); + if (((inRotationMatrixLength != THREE_DIMENSIONAL_MATRIX_LENGTH) && (inRotationMatrixLength != FOUR_DIMENSIONAL_MATRIX_LENGTH)) + || (inRotationMatrixLength != outRotationMatrix.size())) { + HiLog::Error(LABEL, "%{public}s Invalid input parameter", __func__); + return OHOS::Sensors::ERROR; + } + if (inRotationMatrix == outRotationMatrix) { + std::vector tempRotationMatrix(inRotationMatrixLength); + if (transformCoordinateSystemImpl(inRotationMatrix, axisX, axisY, tempRotationMatrix) != OHOS::Sensors::SUCCESS) { + HiLog::Error(LABEL, "%{public}s transformCoordinateSystemImpl failed", __func__); + return OHOS::Sensors::ERROR; + } + for (int32_t i = 0; i < inRotationMatrixLength; i++) { + outRotationMatrix[i] = tempRotationMatrix[i]; + } + return OHOS::Sensors::SUCCESS; + } + return transformCoordinateSystemImpl(inRotationMatrix, axisX, axisY, outRotationMatrix); +} + +int32_t SensorAlgorithm::getAltitude(float seaPressure, float currentPressure, float *altitude) +{ + if (altitude == nullptr) { + HiLog::Error(LABEL, "%{public}s invalid parameter", __func__); + return OHOS::Sensors::ERROR; + } + float coef = 1.0f / RECIPROCAL_COEFFICIENT; + float rationOfStandardPressure = currentPressure / seaPressure; + float difference = pow(rationOfStandardPressure, coef); + *altitude = ZERO_PRESSURE_ALTITUDE * (1.0f - difference); + return OHOS::Sensors::SUCCESS; +} + +int32_t SensorAlgorithm::getGeomagneticDip(std::vector inclinationMatrix, float *geomagneticDip) +{ + if (geomagneticDip == nullptr) { + HiLog::Error(LABEL, "%{public}s invalid parameter", __func__); + return OHOS::Sensors::ERROR; + } + int32_t matrixLength = inclinationMatrix.size(); + if (matrixLength != THREE_DIMENSIONAL_MATRIX_LENGTH && matrixLength != FOUR_DIMENSIONAL_MATRIX_LENGTH) { + HiLog::Error(LABEL, "%{public}s Invalid input parameter", __func__); + return OHOS::Sensors::ERROR; + } + if (matrixLength == THREE_DIMENSIONAL_MATRIX_LENGTH) { + *geomagneticDip = std::atan2(inclinationMatrix[5], inclinationMatrix[4]); + } else { + *geomagneticDip = std::atan2(inclinationMatrix[6], inclinationMatrix[5]); + } + return OHOS::Sensors::SUCCESS; +} + +int32_t SensorAlgorithm::getAngleModify(std::vector curRotationMatrix, std::vector preRotationMatrix, + std::vector &angleChange) +{ + if (angleChange.size() < ROTATION_VECTOR_LENGTH) { + HiLog::Error(LABEL, "%{public}s invalid parameter", __func__); + return OHOS::Sensors::ERROR; + } + int32_t curRotationMatrixLength = curRotationMatrix.size(); + int32_t preRotationMatrixLength = preRotationMatrix.size(); + if ((curRotationMatrixLength != FOUR_DIMENSIONAL_MATRIX_LENGTH) + && (curRotationMatrixLength != THREE_DIMENSIONAL_MATRIX_LENGTH)) { + HiLog::Error(LABEL, "%{public}s Invalid input curRotationMatrix parameter", __func__); + return OHOS::Sensors::ERROR; + } + if ((preRotationMatrixLength != FOUR_DIMENSIONAL_MATRIX_LENGTH) + && (preRotationMatrixLength != THREE_DIMENSIONAL_MATRIX_LENGTH)) { + HiLog::Error(LABEL, "%{public}s Invalid input currotationMatrix parameter", __func__); + return OHOS::Sensors::ERROR; + } + + float curMatrix[THREE_DIMENSIONAL_MATRIX_LENGTH] = {0}; + float preMatrix[THREE_DIMENSIONAL_MATRIX_LENGTH] = {0}; + int32_t curmatrixDimension = ((curRotationMatrixLength == FOUR_DIMENSIONAL_MATRIX_LENGTH) + ? QUATERNION_LENGTH : ROTATION_VECTOR_LENGTH); + int32_t prematrixDimension = ((preRotationMatrixLength == FOUR_DIMENSIONAL_MATRIX_LENGTH) + ? QUATERNION_LENGTH : ROTATION_VECTOR_LENGTH); + for (int32_t i = 0; i < THREE_DIMENSIONAL_MATRIX_LENGTH; i++) { + int32_t curMatrixIndex = i % ROTATION_VECTOR_LENGTH + (i / ROTATION_VECTOR_LENGTH) * curmatrixDimension; + curMatrix[i] = curRotationMatrix[curMatrixIndex]; + int32_t preMatrixIndex = i % ROTATION_VECTOR_LENGTH + (i / ROTATION_VECTOR_LENGTH) * prematrixDimension; + preMatrix[i] = preRotationMatrix[preMatrixIndex]; + } + + float radian[THREE_DIMENSIONAL_MATRIX_LENGTH] = {0}; + radian[1] = preMatrix[0] * curMatrix[1] + preMatrix[3] * curMatrix[4] + preMatrix[6] * curMatrix[7]; + radian[4] = preMatrix[1] * curMatrix[1] + preMatrix[4] * curMatrix[4] + preMatrix[7] * curMatrix[7]; + radian[6] = preMatrix[2] * curMatrix[0] + preMatrix[5] * curMatrix[3] + preMatrix[8] * curMatrix[6]; + radian[7] = preMatrix[2] * curMatrix[1] + preMatrix[5] * curMatrix[4] + preMatrix[8] * curMatrix[7]; + radian[8] = preMatrix[2] * curMatrix[2] + preMatrix[5] * curMatrix[5] + preMatrix[8] * curMatrix[8]; + angleChange[0] = static_cast(std::atan2(radian[1], radian[4])); + angleChange[1] = static_cast(std::asin(-radian[7])); + angleChange[2] = static_cast(std::atan2(-radian[6], radian[8])); + return OHOS::Sensors::SUCCESS; +} + +int32_t SensorAlgorithm::getDirection(std::vector rotationMatrix, std::vector &rotationAngle) +{ + if (rotationAngle.size() < ROTATION_VECTOR_LENGTH) { + HiLog::Error(LABEL, "%{public}s invalid parameter", __func__); + return OHOS::Sensors::ERROR; + } + int32_t rotationMatrixLength = rotationMatrix.size(); + if ((rotationMatrixLength != FOUR_DIMENSIONAL_MATRIX_LENGTH) + && (rotationMatrixLength != THREE_DIMENSIONAL_MATRIX_LENGTH)) { + HiLog::Error(LABEL, "%{public}s Invalid input rotationMatrix parameter", __func__); + return OHOS::Sensors::ERROR; + } + int32_t dimension = ((rotationMatrixLength == FOUR_DIMENSIONAL_MATRIX_LENGTH) + ? QUATERNION_LENGTH : ROTATION_VECTOR_LENGTH); + rotationAngle[0] = static_cast(std::atan2(rotationMatrix[1], + rotationMatrix[dimension * 1 + 1])); + rotationAngle[1] = static_cast(std::atan2(-rotationMatrix[2 * dimension + 1], + std::sqrt(pow(rotationMatrix[1], 2) + pow(rotationMatrix[dimension + 1], 2)))); + rotationAngle[2] = static_cast(std::atan2(-rotationMatrix[2 * dimension], + rotationMatrix[2 * dimension + 2])); + return OHOS::Sensors::SUCCESS; +} + +int32_t SensorAlgorithm::createRotationMatrix(std::vector rotationVector, std::vector &rotationMatrix) +{ + int32_t rotationMatrixLength = rotationMatrix.size(); + if ((rotationVector.size() < ROTATION_VECTOR_LENGTH) || ((rotationMatrixLength != FOUR_DIMENSIONAL_MATRIX_LENGTH) + && (rotationMatrixLength != THREE_DIMENSIONAL_MATRIX_LENGTH))) { + HiLog::Error(LABEL, "%{public}s Invalid input rotationMatrix parameter", __func__); + return OHOS::Sensors::ERROR; + } + std::vector quaternion(4); + int32_t ret = createQuaternion(rotationVector, quaternion); + if (ret != OHOS::Sensors::SUCCESS) { + HiLog::Error(LABEL, "%{public}s create quaternion failed", __func__); + return OHOS::Sensors::ERROR; + } + float squareOfX = 2 * static_cast(pow(quaternion[1], 2)); + float squareOfY = 2 * static_cast(pow(quaternion[2], 2)); + float squareOfZ = 2 * static_cast(pow(quaternion[3], 2)); + float productOfWZ = 2 * quaternion[0] * quaternion[3]; + float productOfXY = 2 * quaternion[1] * quaternion[2]; + float productOfWY = 2 * quaternion[0] * quaternion[2]; + float productOfXZ = 2 * quaternion[1] * quaternion[3]; + float productOfWX = 2 * quaternion[0] * quaternion[1]; + float productOfYZ = 2 * quaternion[2] * quaternion[3]; + int32_t rotationMatrixDimension = ((rotationMatrixLength == FOUR_DIMENSIONAL_MATRIX_LENGTH) + ? QUATERNION_LENGTH : ROTATION_VECTOR_LENGTH); + rotationMatrix[0] = 1 - squareOfY - squareOfZ; + rotationMatrix[1] = productOfXY - productOfWZ; + rotationMatrix[2] = productOfXZ + productOfWY; + rotationMatrix[3 % ROTATION_VECTOR_LENGTH + (3 / ROTATION_VECTOR_LENGTH) * rotationMatrixDimension] + = productOfXY + productOfWZ; + rotationMatrix[4 % ROTATION_VECTOR_LENGTH + (4 / ROTATION_VECTOR_LENGTH) * rotationMatrixDimension] + = 1 - squareOfX - squareOfZ; + rotationMatrix[5 % ROTATION_VECTOR_LENGTH + (5 / ROTATION_VECTOR_LENGTH) * rotationMatrixDimension] + = productOfYZ - productOfWX; + rotationMatrix[6 % ROTATION_VECTOR_LENGTH + (6 / ROTATION_VECTOR_LENGTH) * rotationMatrixDimension] + = productOfXZ - productOfWY; + rotationMatrix[7 % ROTATION_VECTOR_LENGTH + (7 / ROTATION_VECTOR_LENGTH) * rotationMatrixDimension] + = productOfYZ + productOfWX; + rotationMatrix[8 % ROTATION_VECTOR_LENGTH + (8 / ROTATION_VECTOR_LENGTH) * rotationMatrixDimension] + = 1 - squareOfX - squareOfY; + if (rotationMatrixLength == FOUR_DIMENSIONAL_MATRIX_LENGTH) { + rotationMatrix[3] = rotationMatrix[7] = rotationMatrix[11] = rotationMatrix[12] = rotationMatrix[13] + = rotationMatrix[14] = 0.0f; + rotationMatrix[15] = 1.0f; + } + return OHOS::Sensors::SUCCESS; +} + +int32_t SensorAlgorithm::createRotationAndInclination(std::vector gravity, std::vector geomagnetic, + std::vector &rotationMatrix, std::vector &inclinationMatrix) +{ + if (gravity.size() < ROTATION_VECTOR_LENGTH || geomagnetic.size() < ROTATION_VECTOR_LENGTH) { + HiLog::Error(LABEL, "%{public}s Invalid input parameter", __func__); + return OHOS::Sensors::ERROR; + } + float totalGravity = pow(gravity[0], 2) + pow(gravity[1], 2) + pow(gravity[2], 2); + if (totalGravity < (0.01f * pow(GRAVITATIONAL_ACCELERATION, 2))) { + HiLog::Error(LABEL, "%{public}s Invalid input gravity parameter", __func__); + return OHOS::Sensors::ERROR; + } + + std::vector componentH(3); + componentH[0] = geomagnetic[1] * gravity[2] - geomagnetic[2] * gravity[1]; + componentH[1] = geomagnetic[2] * gravity[0] - geomagnetic[0] * gravity[2]; + componentH[2] = geomagnetic[0] * gravity[1] - geomagnetic[1] * gravity[0]; + + float totalH = static_cast(std::sqrt(pow(componentH[0], 2) + pow(componentH[1], 2) + + pow(componentH[2], 2))); + if (totalH < 0.1f) { + HiLog::Error(LABEL, "%{public}s The total strength of H is less than 0.1", __func__); + return OHOS::Sensors::ERROR; + } + float reciprocalH = 1.0f / totalH; + componentH[0] *= reciprocalH; + componentH[1] *= reciprocalH; + componentH[2] *= reciprocalH; + float reciprocalA = 1.0f / static_cast(std::sqrt(totalGravity)); + gravity[0] *= reciprocalA; + gravity[1] *= reciprocalA; + gravity[2] *= reciprocalA; + + std::vector measuredValue(3); + measuredValue[0] = gravity[1] * componentH[2] - gravity[2] * componentH[1]; + measuredValue[1] = gravity[2] * componentH[0] - gravity[0] * componentH[2]; + measuredValue[2] = gravity[0] * componentH[1] - gravity[1] * componentH[0]; + + int32_t rotationMatrixLength = rotationMatrix.size(); + int32_t inclinationMatrixLength = inclinationMatrix.size(); + if ((rotationMatrixLength != 9 && rotationMatrixLength != 16) || (inclinationMatrixLength != 9 + && inclinationMatrixLength != 16)) { + HiLog::Error(LABEL, "%{public}s Invalid input parameter", __func__); + return OHOS::Sensors::ERROR; + } + float reciprocalE = 1.0f / static_cast(std::sqrt(pow(geomagnetic[0], 2) + pow(geomagnetic[1], 2) + + pow(geomagnetic[2], 2))); + float c = (geomagnetic[0] * measuredValue[0] + geomagnetic[1] * measuredValue[1] + + geomagnetic[2] * measuredValue[2]) * reciprocalE; + float s = (geomagnetic[0] * gravity[0] + geomagnetic[1] * gravity[1] + geomagnetic[2] * gravity[2]) * reciprocalE; + + int32_t rotationMatrixDimension = ((rotationMatrixLength == FOUR_DIMENSIONAL_MATRIX_LENGTH) + ? QUATERNION_LENGTH : ROTATION_VECTOR_LENGTH); + int32_t inclinationMatrixDimension = ((inclinationMatrixLength == FOUR_DIMENSIONAL_MATRIX_LENGTH) + ? QUATERNION_LENGTH : ROTATION_VECTOR_LENGTH); + rotationMatrix[0] = componentH[0]; + rotationMatrix[1] = componentH[1]; + rotationMatrix[2] = componentH[2]; + rotationMatrix[3 % ROTATION_VECTOR_LENGTH + (3 / ROTATION_VECTOR_LENGTH) * rotationMatrixDimension] = measuredValue[0]; + rotationMatrix[4 % ROTATION_VECTOR_LENGTH + (4 / ROTATION_VECTOR_LENGTH) * rotationMatrixDimension] = measuredValue[1]; + rotationMatrix[5 % ROTATION_VECTOR_LENGTH + (5 / ROTATION_VECTOR_LENGTH) * rotationMatrixDimension] = measuredValue[2]; + rotationMatrix[6 % ROTATION_VECTOR_LENGTH + (6 / ROTATION_VECTOR_LENGTH) * rotationMatrixDimension] = gravity[0]; + rotationMatrix[7 % ROTATION_VECTOR_LENGTH + (7 / ROTATION_VECTOR_LENGTH) * rotationMatrixDimension] = gravity[1]; + rotationMatrix[8 % ROTATION_VECTOR_LENGTH + (8 / ROTATION_VECTOR_LENGTH) * rotationMatrixDimension] = gravity[2]; + if (rotationMatrixLength == FOUR_DIMENSIONAL_MATRIX_LENGTH) { + rotationMatrix[3] = rotationMatrix[7] = rotationMatrix[11] = rotationMatrix[12] + = rotationMatrix[13] = rotationMatrix[14] = 0.0f; + rotationMatrix[15] = 1.0f; + } + inclinationMatrix[0] = 1; + inclinationMatrix[1] = 0; + inclinationMatrix[2] = 0; + inclinationMatrix[3 % ROTATION_VECTOR_LENGTH + (3 / ROTATION_VECTOR_LENGTH) * inclinationMatrixDimension] = 0; + inclinationMatrix[4 % ROTATION_VECTOR_LENGTH + (4 / ROTATION_VECTOR_LENGTH) * inclinationMatrixDimension] = c; + inclinationMatrix[5 % ROTATION_VECTOR_LENGTH + (5 / ROTATION_VECTOR_LENGTH) * inclinationMatrixDimension] = s; + inclinationMatrix[6 % ROTATION_VECTOR_LENGTH + (6 / ROTATION_VECTOR_LENGTH) * inclinationMatrixDimension] = 0; + inclinationMatrix[7 % ROTATION_VECTOR_LENGTH + (7 / ROTATION_VECTOR_LENGTH) * inclinationMatrixDimension] = -s; + inclinationMatrix[8 % ROTATION_VECTOR_LENGTH + (8 / ROTATION_VECTOR_LENGTH) * inclinationMatrixDimension] = c; + if (rotationMatrixLength == FOUR_DIMENSIONAL_MATRIX_LENGTH) { + inclinationMatrix[3] = inclinationMatrix[7] = inclinationMatrix[11] = inclinationMatrix[12] + = inclinationMatrix[13] = inclinationMatrix[14] = 0.0f; + inclinationMatrix[15] = 1.0f; + } + return OHOS::Sensors::SUCCESS; +} \ No newline at end of file diff --git a/interfaces/plugin/include/sensor_js.h b/interfaces/plugin/include/sensor_js.h index a361705c6864d275e6855231f99a6802a56d533a..bb38db195807fbbdbf7550c08865ca4246a0fc5f 100755 --- a/interfaces/plugin/include/sensor_js.h +++ b/interfaces/plugin/include/sensor_js.h @@ -12,8 +12,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#ifndef SENSOR_JS_H +#define SENSOR_JS_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); +#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 b7a377d5c0e4817cc625051a178204315dd8350a..e078b8d0461e43a67388580abebeabc20babd864 100755 --- a/interfaces/plugin/include/sensor_napi_utils.h +++ b/interfaces/plugin/include/sensor_napi_utils.h @@ -12,6 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#ifndef SENSOR_NAPI_UTILS_H +#define SENSOR_NAPI_UTILS_H #include "napi/native_api.h" #include "napi/native_node_api.h" @@ -19,8 +21,26 @@ #include "sensor_agent.h" #include -#define EVENT_INVALID_PARAMETER (-1); -#define EVENT_OK 0; +using std::vector; +using std::string; + +const int32_t THREE_DIMENSIONAL_MATRIX_LENGTH = 9; +const int32_t FOUR_DIMENSIONAL_MATRIX_LENGTH = 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; @@ -29,21 +49,93 @@ struct SensorData { int64_t timestamp; }; +union CallbackData { + SensorData sensorData; + GeomagneticData geomagneticData; + RationMatrixData rationMatrixData; + float reserve[16]; + int32_t dataLength; +}; + +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, +} CallbackDataType; + struct AsyncCallbackInfo { napi_env env; napi_async_work asyncWork; napi_deferred deferred; napi_ref callback[1] = { 0 }; - SensorData sensorData; - int32_t status; + CallbackData data; + BusinessError error; + CallbackDataType type; }; -bool IsMatchType(napi_value value, napi_valuetype type, napi_env env); +using ConvertDataFunc = void(*)(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]); + +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, std::string name, napi_env env); -napi_value GetUndefined(napi_env env); \ No newline at end of file + +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, + 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); +#endif // SENSOR_NAPI_UTILS_H diff --git a/interfaces/plugin/src/sensor_js.cpp b/interfaces/plugin/src/sensor_js.cpp index a3537a8b411770d500e36708731c6d289e031d78..52a95b3603917578533d5d22bef2530602f9df9e 100755 --- a/interfaces/plugin/src/sensor_js.cpp +++ b/interfaces/plugin/src/sensor_js.cpp @@ -18,19 +18,22 @@ #include #include #include +#include #include #include #include #include +#include "geomagnetic_field.h" + #include "hilog/log.h" #include "napi/native_api.h" #include "napi/native_node_api.h" -#include "sensor_agent.h" -#include "sensor_napi_utils.h" - #include "refbase.h" #include "securec.h" +#include "sensor_agent.h" +#include "sensor_algorithm.h" +#include "sensor_napi_utils.h" using namespace OHOS::HiviewDFX; static constexpr HiLogLabel LABEL = {LOG_CORE, 0xD002708, "SensorJsAPI"}; @@ -47,32 +50,34 @@ static void DataCallbackImpl(SensorEvent *event) } int32_t sensorTypeId = event->sensorTypeId; float *data = (float *)(event->data); - for (auto &onCallbackInfo: g_onCallbackInfos) { - if ((int32_t)onCallbackInfo.first == sensorTypeId) { - onCallbackInfo.second->sensorData.sensorTypeId = sensorTypeId; - onCallbackInfo.second->sensorData.dataLength = event->dataLen; - onCallbackInfo.second->sensorData.timestamp = event->timestamp; - if (memcpy_s(onCallbackInfo.second->sensorData.data, event->dataLen, data, event->dataLen) != EOK) { - HiLog::Error(LABEL, "%{public}s copy data failed", __func__); - return; - } - onCallbackInfo.second->status = 1; - EmitUvEventLoop((struct AsyncCallbackInfo *)(onCallbackInfo.second)); - } + if (g_onCallbackInfos.find(sensorTypeId) == g_onCallbackInfos.end()) { + HiLog::Debug(LABEL, "%{public}s no subscribe to the sensor data", __func__); + return; + } + struct AsyncCallbackInfo *onCallbackInfo = g_onCallbackInfos[sensorTypeId]; + onCallbackInfo->data.sensorData.sensorTypeId = sensorTypeId; + onCallbackInfo->data.sensorData.dataLength = event->dataLen; + onCallbackInfo->data.sensorData.timestamp = event->timestamp; + if (memcpy_s(onCallbackInfo->data.sensorData.data, event->dataLen, data, event->dataLen) != EOK) { + HiLog::Error(LABEL, "%{public}s copy data failed", __func__); + return; } + onCallbackInfo->type = ON_CALLBACK; + EmitUvEventLoop((struct AsyncCallbackInfo *)(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->sensorData.sensorTypeId = sensorTypeId; - onceCallbackInfo->sensorData.dataLength = event->dataLen; - onceCallbackInfo->sensorData.timestamp = event->timestamp; - if (memcpy_s(onceCallbackInfo->sensorData.data, event->dataLen, data, event->dataLen) != EOK) { + onceCallbackInfo->data.sensorData.sensorTypeId = sensorTypeId; + onceCallbackInfo->data.sensorData.dataLength = event->dataLen; + onceCallbackInfo->data.sensorData.timestamp = event->timestamp; + if (memcpy_s(onceCallbackInfo->data.sensorData.data, event->dataLen, data, event->dataLen) != EOK) { HiLog::Error(LABEL, "%{public}s copy data failed", __func__); return; } - onceCallbackInfo->status = 2; + onceCallbackInfo->type = ONCE_CALLBACK; EmitUvEventLoop((struct AsyncCallbackInfo *)(onceCallbackInfo)); if (g_onCallbackInfos.find(sensorTypeId) == g_onCallbackInfos.end()) { HiLog::Debug(LABEL, "%{public}s no subscription to change sensor data, need to cancel registration", __func__); @@ -128,23 +133,19 @@ static napi_value Once(napi_env env, napi_callback_info info) { HiLog::Info(LABEL, "%{public}s in", __func__); size_t argc = 2; - napi_value args[2]; - napi_value thisVar; + napi_value args[2] = { 0 }; + napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, NULL)); if (argc != 2) { HiLog::Error(LABEL, "%{public}s Invalid input, number of argument should be two", __func__); return nullptr; } - if (!IsMatchType(args[0], napi_number, env)) { - HiLog::Error(LABEL, "%{public}s argument should be number type", __func__); + 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); - if (!IsMatchType(args[1], napi_function, env)) { - HiLog::Error(LABEL, "%{public}s argument should be function type", __func__); - return nullptr; - } AsyncCallbackInfo *asyncCallbackInfo = new AsyncCallbackInfo { .env = env, .asyncWork = nullptr, @@ -157,7 +158,8 @@ static napi_value Once(napi_env env, napi_callback_info info) int32_t ret = SubscribeSensor(sensorTypeId, 200000000, DataCallbackImpl); if (ret < 0) { HiLog::Error(LABEL, "%{public}s subscribe Sensor failed", __func__); - asyncCallbackInfo->status = -1; + asyncCallbackInfo->type = FAIL; + asyncCallbackInfo->error.code = ret; EmitAsyncCallbackWork(asyncCallbackInfo); g_onceCallbackInfos.erase(sensorTypeId); return nullptr; @@ -171,27 +173,23 @@ static napi_value On(napi_env env, napi_callback_info info) { HiLog::Info(LABEL, "%{public}s in", __func__); size_t argc = 3; - napi_value args[3]; - napi_value thisVar; + 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(args[0], napi_number, env)) { + 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); - if (!IsMatchType(args[1], napi_function, env)) { - HiLog::Error(LABEL, "%{public}s the second parameter should be napi_function type!", __func__); - return nullptr; - } int64_t interval = 200000000; if (argc == 3) { HiLog::Info(LABEL, "%{public}s argc = 3!", __func__); napi_value value = NapiGetNamedProperty(args[2], "interval", env); - if (!IsMatchType(value, napi_number, env)) { + if (!IsMatchType(env, value, napi_number)) { HiLog::Error(LABEL, "%{public}s argument should be napi_number type!", __func__); return nullptr; } @@ -207,10 +205,10 @@ static napi_value On(napi_env env, napi_callback_info info) int32_t ret = SubscribeSensor(sensorTypeId, interval, DataCallbackImpl); if (ret < 0) { HiLog::Error(LABEL, "%{public}s subscribeSensor failed", __func__); - asyncCallbackInfo->status = -1; + asyncCallbackInfo->type = FAIL; + asyncCallbackInfo->error.code = ret; EmitAsyncCallbackWork(asyncCallbackInfo); g_onCallbackInfos.erase(sensorTypeId); - return nullptr; } HiLog::Info(LABEL, "%{public}s out", __func__); return nullptr; @@ -220,23 +218,19 @@ static napi_value Off(napi_env env, napi_callback_info info) { HiLog::Info(LABEL, "%{public}s in", __func__); size_t argc = 2; - napi_value args[2]; - napi_value thisVar; + 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) { HiLog::Error(LABEL, "%{public}s Invalid input.", __func__); return nullptr; } - if (!IsMatchType(args[0], napi_number, env)) { - HiLog::Error(LABEL, "%{public}s argument should be number type!", __func__); + 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); - if (!IsMatchType(args[1], napi_function, env)) { - HiLog::Error(LABEL, "%{public}s argument should be function type!", __func__); - return nullptr; - } AsyncCallbackInfo *asyncCallbackInfo = new AsyncCallbackInfo { .env = env, .asyncWork = nullptr, @@ -245,11 +239,12 @@ static napi_value Off(napi_env env, napi_callback_info info) napi_create_reference(env, args[1], 1, &asyncCallbackInfo->callback[0]); int32_t ret = UnsubscribeSensor(sensorTypeId); if (ret < 0) { - asyncCallbackInfo->status = -1; + asyncCallbackInfo->type = FAIL; + asyncCallbackInfo->error.code = ret; HiLog::Error(LABEL, "%{public}s UnsubscribeSensor failed", __func__); } else { HiLog::Error(LABEL, "%{public}s UnsubscribeSensor success", __func__); - asyncCallbackInfo->status = 0; + asyncCallbackInfo->type = OFF_CALLBACK; if (g_onCallbackInfos.find(sensorTypeId) != g_onCallbackInfos.end()) { napi_delete_reference(env, g_onCallbackInfos[sensorTypeId]->callback[0]); delete g_onCallbackInfos[sensorTypeId]; @@ -258,7 +253,453 @@ static napi_value Off(napi_env env, napi_callback_info info) } } EmitAsyncCallbackWork(asyncCallbackInfo); - HiLog::Info(LABEL, "%{public}s left", __func__); + return nullptr; +} + +static napi_value GetGeomagneticField(napi_env env, napi_callback_info info) +{ + HiLog::Info(LABEL, "%{public}s in", __func__); + 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); + double latitude = 0; + napi_get_value_double(env, napiLatitude, &latitude); + napi_value napiLongitude = NapiGetNamedProperty(args[0], "longitude", env); + double longitude = 0; + napi_get_value_double(env, napiLongitude, &longitude); + napi_value napiAltitude = NapiGetNamedProperty(args[0], "altitude", env); + double altitude = 0; + napi_get_value_double(env, napiAltitude, &altitude); + int64_t timeMillis = 0; + timeMillis = GetCppInt64(args[1], env); + + GeomagneticField geomagneticField(latitude, longitude, altitude, timeMillis); + AsyncCallbackInfo *asyncCallbackInfo = new AsyncCallbackInfo { + .env = env, + .asyncWork = nullptr, + .deferred = nullptr, + .type = GET_GEOMAGNETIC_FIELD, + }; + asyncCallbackInfo->data.geomagneticData = { + .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; + 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]); + EmitAsyncCallbackWork(asyncCallbackInfo); + return nullptr; +} + +static napi_value TransformCoordinateSystem(napi_env env, napi_callback_info info) +{ + 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 = 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__); + asyncCallbackInfo->type = FAIL; + asyncCallbackInfo->error.code = ret; + } else { + for (int32_t i = 0; i < inRotationVectorLength; i++) { + asyncCallbackInfo->data.reserve[i] = outRotationVector[i]; + } + asyncCallbackInfo->data.dataLength = inRotationVectorLength; + } + if (argc == 2) { + napi_deferred deferred = nullptr; + napi_value promise = nullptr; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + asyncCallbackInfo->deferred = deferred; + 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]); + EmitAsyncCallbackWork(asyncCallbackInfo); + return nullptr; +} + +static napi_value GetAngleModify(napi_env env, napi_callback_info info) +{ + 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]); + std::vector angleChange(3); + 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__); + asyncCallbackInfo->type = FAIL; + asyncCallbackInfo->error.code = ret; + } else { + asyncCallbackInfo->data.dataLength = angleChange.size(); + for (int32_t i = 0; i < asyncCallbackInfo->data.dataLength; i++) { + asyncCallbackInfo->data.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; + 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]); + EmitAsyncCallbackWork(asyncCallbackInfo); + return nullptr; +} + +static napi_value GetDirection(napi_env env, napi_callback_info info) +{ + size_t argc; + 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]); + std::vector rotationAngle(3); + std::unique_ptr sensorAlgorithm = std::make_unique(); + int32_t ret = sensorAlgorithm->getDirection(rotationMatrix, rotationAngle); + if (ret < 0) { + HiLog::Error(LABEL, "%{public}s failed", __func__); + asyncCallbackInfo->type = FAIL; + asyncCallbackInfo->error.code = ret; + } else { + asyncCallbackInfo->data.dataLength = rotationAngle.size(); + for (int32_t i = 0; i < asyncCallbackInfo->data.dataLength; i++) { + asyncCallbackInfo->data.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; + 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); + return result; + } + napi_create_reference(env, args[1], 1, &asyncCallbackInfo->callback[0]); + EmitAsyncCallbackWork(asyncCallbackInfo); + return nullptr; +} + +static napi_value CreateQuaternion(napi_env env, napi_callback_info info) +{ + 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]); + std::vector quaternion(4); + std::unique_ptr sensorAlgorithm = std::make_unique(); + int32_t ret = sensorAlgorithm->createQuaternion(rotationVector, quaternion); + if (ret < 0) { + HiLog::Error(LABEL, "%{public}s failed", __func__); + asyncCallbackInfo->type = FAIL; + asyncCallbackInfo->error.code = ret; + } else { + asyncCallbackInfo->data.dataLength = quaternion.size(); + for (int32_t i = 0; i < asyncCallbackInfo->data.dataLength; i++) { + asyncCallbackInfo->data.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; + 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]); + EmitAsyncCallbackWork(asyncCallbackInfo); + return nullptr; +} + +static napi_value GetAltitude(napi_env env, napi_callback_info info) +{ + 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]); + 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__); + asyncCallbackInfo->type = FAIL; + asyncCallbackInfo->error.code = ret; + } else { + asyncCallbackInfo->data.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; + 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]); + EmitAsyncCallbackWork(asyncCallbackInfo); + return nullptr; +} + +static napi_value GetGeomagneticDip(napi_env env, napi_callback_info info) +{ + 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]); + 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__); + asyncCallbackInfo->type = FAIL; + asyncCallbackInfo->error.code = ret; + } else { + asyncCallbackInfo->data.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; + 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]); + EmitAsyncCallbackWork(asyncCallbackInfo); + return nullptr; +} + +static napi_value CreateRotationMatrix(napi_env env, napi_callback_info info) +{ + 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.dataLength = rotationMatrix.size(); + for (int32_t i = 0; i < asyncCallbackInfo->data.dataLength; i++) { + asyncCallbackInfo->data.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[1], napi_function))) { + HiLog::Info(LABEL, "%{public}s argument error", __func__); + return nullptr; + } + asyncCallbackInfo->type = ROTATION_INCLINATION_MATRIX; + std::vector gravity = GetCppArrayFloat(env, args[0]); + std::vector geomagnetic = GetCppArrayFloat(env, args[1]); + 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__); + asyncCallbackInfo->type = FAIL; + asyncCallbackInfo->error.code = ret; + } else { + 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++) { + 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; + 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]); + EmitAsyncCallbackWork(asyncCallbackInfo); return nullptr; } @@ -269,7 +710,15 @@ static napi_value Init(napi_env env, napi_value exports) napi_property_descriptor desc[] = { DECLARE_NAPI_FUNCTION("on", On), DECLARE_NAPI_FUNCTION("once", Once), - DECLARE_NAPI_FUNCTION("off", Off) + DECLARE_NAPI_FUNCTION("off", Off), + DECLARE_NAPI_FUNCTION("getGeomagneticField", GetGeomagneticField), + DECLARE_NAPI_FUNCTION("transformCoordinateSystem", TransformCoordinateSystem), + DECLARE_NAPI_FUNCTION("getAngleModify", GetAngleModify), + DECLARE_NAPI_FUNCTION("getDirection", GetDirection), + DECLARE_NAPI_FUNCTION("createQuaternion", CreateQuaternion), + DECLARE_NAPI_FUNCTION("getAltitude", GetAltitude), + DECLARE_NAPI_FUNCTION("getGeomagneticDip", GetGeomagneticDip), + DECLARE_NAPI_FUNCTION("createRotationMatrix", CreateRotationMatrix) }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(napi_property_descriptor), desc)); return exports; diff --git a/interfaces/plugin/src/sensor_napi_utils.cpp b/interfaces/plugin/src/sensor_napi_utils.cpp index 2d66a145fd1167a8938edab655d5c0cabb992465..383426aac10eab6207cbba614ffd3bd5c72c7af2 100755 --- a/interfaces/plugin/src/sensor_napi_utils.cpp +++ b/interfaces/plugin/src/sensor_napi_utils.cpp @@ -24,9 +24,10 @@ using namespace OHOS::HiviewDFX; static constexpr HiLogLabel LABEL = {LOG_CORE, 0xD002708, "SensorJsAPI"}; -bool IsMatchType(napi_value value, napi_valuetype type, napi_env env) + +bool IsMatchType(napi_env env, napi_value value, napi_valuetype type) { - napi_valuetype paramType; + napi_valuetype paramType = napi_undefined; napi_typeof(env, value, ¶mType); if (paramType != type) { HiLog::Error(LABEL, "%{public}s failed!", __func__); @@ -35,20 +36,75 @@ bool IsMatchType(napi_value value, napi_valuetype type, napi_env env) return true; } +bool IsMatchArrayType(napi_env env, napi_value value) +{ + bool result = false; + napi_is_array(env, value, &result); + return result; +} + +vector GetCppArrayFloat(napi_env env, napi_value value) +{ + uint32_t arrayLength = 0; + napi_get_array_length(env, value, &arrayLength); + if (arrayLength <= 0) { + HiLog::Error(LABEL, "%{public}s The array is empty.", __func__); + return vector(); + } + vector paramArrays; + for (size_t i = 0; i < arrayLength; i++) { + napi_value napiElement = nullptr; + napi_get_element(env, value, i, &napiElement); + + napi_valuetype valuetype0 = napi_undefined; + napi_typeof(env, napiElement, &valuetype0); + if (valuetype0 != napi_number) { + HiLog::Error(LABEL, "%{public}s Wrong argument type. Numbers expected.", __func__); + return vector(); + } + double value0 = 0; + napi_get_value_double(env, napiElement, &value0); + paramArrays.push_back(static_cast(value0)); + } + return paramArrays; +} + +bool IsMatchArrayType(napi_env env, napi_value value, napi_typedarray_type type) +{ + napi_typedarray_type paramType = napi_int8_array; + size_t length; + void *data = nullptr; + napi_value arraybuffer = nullptr; + size_t byteOffset; + napi_get_typedarray_info(env, value, ¶mType, &length, &data, &arraybuffer, &byteOffset); + if (paramType != type) { + HiLog::Error(LABEL, "%{public}s paramType:%{public}d type:%{public}d failed!", __func__, paramType, type); + return false; + } + return true; +} + napi_value GetNapiInt32(int32_t number, napi_env env) { - napi_value value; + napi_value value = nullptr; napi_create_int32(env, number, &value); return value; } -napi_value NapiGetNamedProperty(napi_value jsonObject, std::string name, napi_env env) +napi_value NapiGetNamedProperty(napi_value jsonObject, string name, napi_env env) { - napi_value value; + napi_value value = nullptr; napi_get_named_property(env, jsonObject, name.c_str(), &value); return value; } +float GetCppFloat(napi_env env, napi_value value) +{ + double number; + napi_get_value_double(env, value, &number); + return static_cast(number); +} + int32_t GetCppInt32(napi_value value, napi_env env) { int32_t number; @@ -77,7 +133,7 @@ napi_value GetUndefined(napi_env env) return value; } -std::map> g_sensorAttributeList = { +std::map> g_sensorAttributeList = { { 0, { "x" } }, { SENSOR_TYPE_ID_ACCELEROMETER, { "x", "y", "z" } }, { SENSOR_TYPE_ID_GYROSCOPE, { "x", "y", "z" } }, @@ -102,6 +158,147 @@ std::map> g_sensorAttributeList = { { SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, { "x", "y", "z", "biasX", "biasY", "biasZ" } } }; +std::map g_convertfuncList = { + {FAIL, ConvertToFailData}, + {OFF_CALLBACK, ConvertToNoData}, + {ON_CALLBACK, ConvertToSensorData}, + {ONCE_CALLBACK, ConvertToSensorData}, + {GET_GEOMAGNETIC_FIELD, ConvertToGeomagneticData}, + {GET_ALTITUDE, ConvertToNumber}, + {GET_GEOMAGNITIC_DIP, ConvertToNumber}, + {GET_ANGLE_MODIFY, ConvertToArray}, + {CREATE_ROTATION_MATRIX, ConvertToArray}, + {TRANSFORM_COORDINATE_SYSTEM, ConvertToArray}, + {CREATE_QUATERNION, ConvertToArray}, + {GET_DIRECTION, ConvertToArray}, + {ROTATION_INCLINATION_MATRIX, ConvertToRotationMatrix} +}; + +void getJsonObject(napi_env env, AsyncCallbackInfo *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); +} + +void ConvertToFailData(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]) +{ + result[0] = GreateBusinessError(env, asyncCallbackInfo->error.code, asyncCallbackInfo->error.message, + asyncCallbackInfo->error.name, asyncCallbackInfo->error.stack); + napi_get_undefined(env, &result[1]); +} + +void ConvertToSensorData(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]) +{ + napi_get_undefined(env, &result[0]); + 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; + } + std::vector sensorAttribute = g_sensorAttributeList[sensorTypeId]; + napi_create_object(env, &result[1]); + 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); + message = nullptr; + } + napi_create_int64(env, asyncCallbackInfo->data.sensorData.timestamp, &message); + napi_set_named_property(env, result[1], "timestamp", message); +} + +void ConvertToNoData(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]) +{ + napi_get_undefined(env, &result[1]); + napi_get_undefined(env, &result[0]); +} + +void ConvertToGeomagneticData(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]) +{ + napi_get_undefined(env, &result[0]); + napi_create_object(env, &result[1]); + getJsonObject(env, asyncCallbackInfo, result[1]); +} + +void ConvertToNumber(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]) +{ + napi_get_undefined(env, &result[0]); + napi_create_double(env, static_cast(asyncCallbackInfo->data.reserve[0]), &result[1]); +} + +void ConvertToArray(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]) +{ + napi_get_undefined(env, &result[0]); + CreateNapiArray(env, asyncCallbackInfo->data.reserve, asyncCallbackInfo->data.dataLength, result[1]); +} + +void ConvertToRotationMatrix(napi_env env, AsyncCallbackInfo *asyncCallbackInfo, napi_value result[2]) +{ + napi_get_undefined(env, &result[0]); + napi_create_object(env, &result[1]); + napi_value rotation = nullptr; + CreateNapiArray(env, asyncCallbackInfo->data.rationMatrixData.rotationMatrix, THREE_DIMENSIONAL_MATRIX_LENGTH, rotation); + napi_value inclination = nullptr; + 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); +} + +napi_value GreateBusinessError(napi_env env, int32_t errCode, string errMessage, string errName, string errStack) +{ + 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)); + return result; +} + +void CreateNapiArray(napi_env env, float *data, int32_t dataLength, napi_value result) +{ + napi_create_array(env, &result); + for (int32_t index = 0; index < dataLength; index++) { + napi_value message = nullptr; + napi_create_double(env, data[index], &message); + napi_set_element(env, result, index, message); + } +} + void EmitAsyncCallbackWork(AsyncCallbackInfo *asyncCallbackInfo) { HiLog::Debug(LABEL, "%{public}s begin", __func__); @@ -109,7 +306,7 @@ void EmitAsyncCallbackWork(AsyncCallbackInfo *asyncCallbackInfo) HiLog::Error(LABEL, "%{public}s asyncCallbackInfo is null!", __func__); return; } - napi_value resourceName; + 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; @@ -120,22 +317,19 @@ void EmitAsyncCallbackWork(AsyncCallbackInfo *asyncCallbackInfo) [](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); napi_value callResult = nullptr; napi_value result[2] = {0}; - if (asyncCallbackInfo->status < 0) { - HiLog::Debug(LABEL, "%{public}s napi_create_async_work < 0 in", __func__); - napi_value code = nullptr; - napi_value message = nullptr; - napi_create_string_utf8(env, "-1", NAPI_AUTO_LENGTH, &code); - napi_create_string_utf8(env, "failed", NAPI_AUTO_LENGTH, &message); - napi_create_error(env, code, message, &result[0]); - napi_get_undefined(env, &result[1]); - } else if (asyncCallbackInfo->status == 0) { - napi_get_undefined(env, &result[1]); - napi_get_undefined(env, &result[0]); + if (g_convertfuncList.count(asyncCallbackInfo->type) == 0) { + HiLog::Error(LABEL, "%{public}s type invalid", __func__); + return; } + g_convertfuncList[asyncCallbackInfo->type](env, asyncCallbackInfo, result); napi_call_function(env, nullptr, callback, 2, result, &callResult); napi_delete_reference(env, asyncCallbackInfo->callback[0]); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); @@ -144,6 +338,7 @@ void EmitAsyncCallbackWork(AsyncCallbackInfo *asyncCallbackInfo) HiLog::Debug(LABEL, "%{public}s napi_create_async_work left", __func__); }, asyncCallbackInfo, &asyncCallbackInfo->asyncWork); + napi_queue_async_work(asyncCallbackInfo->env, asyncCallbackInfo->asyncWork); HiLog::Debug(LABEL, "%{public}s end", __func__); } @@ -157,15 +352,13 @@ void EmitUvEventLoop(AsyncCallbackInfo *asyncCallbackInfo) HiLog::Error(LABEL, "%{public}s loop is null", __func__); return; } - 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) { + uv_queue_work(loop, work, [] (uv_work_t *work) { }, [] (uv_work_t *work, int status) { AsyncCallbackInfo *asyncCallbackInfo = reinterpret_cast(work->data); if (asyncCallbackInfo == nullptr) { HiLog::Error(LABEL, "%{public}s asyncCallbackInfo is null", __func__); @@ -182,35 +375,13 @@ void EmitUvEventLoop(AsyncCallbackInfo *asyncCallbackInfo) napi_get_reference_value(env, asyncCallbackInfo->callback[0], &callback); napi_value callResult = nullptr; napi_value result[2] = {0}; - if (asyncCallbackInfo->status < 0) { - HiLog::Debug(LABEL, "%{public}s status < 0 in", __func__); - napi_value code = nullptr; - napi_value message = nullptr; - napi_create_string_utf8(env, "-1", NAPI_AUTO_LENGTH, &code); - napi_create_string_utf8(env, "failed", NAPI_AUTO_LENGTH, &message); - napi_create_error(env, code, message, &result[0]); - napi_get_undefined(env, &result[1]); - } else { - int32_t sensorTypeId = asyncCallbackInfo->sensorData.sensorTypeId; - if ((g_sensorAttributeList.count(sensorTypeId)) == 0 || (g_sensorAttributeList[sensorTypeId].size() - != (asyncCallbackInfo->sensorData.dataLength / sizeof(float)))) { - HiLog::Error(LABEL, "%{public}s count of sensorTypeId is zero", __func__); - return; - } - std::vector sensorAttribute = g_sensorAttributeList[sensorTypeId]; - napi_create_object(env, &result[1]); - napi_value message = nullptr; - for (size_t i = 0; i < sensorAttribute.size(); i++) { - napi_create_double(env, asyncCallbackInfo->sensorData.data[i], &message); - napi_set_named_property(env, result[1], sensorAttribute[i].c_str(), message); - message = nullptr; - } - napi_create_int64(env, asyncCallbackInfo->sensorData.timestamp, &message); - napi_set_named_property(env, result[1], "timestamp", message); - napi_get_undefined(env, &result[0]); + if (g_convertfuncList.count(asyncCallbackInfo->type) == 0) { + HiLog::Error(LABEL, "%{public}s type invalid", __func__); + return; } + g_convertfuncList[asyncCallbackInfo->type](env, asyncCallbackInfo, result); napi_call_function(env, undefined, callback, 2, result, &callResult); - if (asyncCallbackInfo->status != 1) { + if (asyncCallbackInfo->type != ON_CALLBACK) { napi_delete_reference(env, asyncCallbackInfo->callback[0]); delete asyncCallbackInfo; asyncCallbackInfo = nullptr; @@ -219,3 +390,38 @@ void EmitUvEventLoop(AsyncCallbackInfo *asyncCallbackInfo) work = nullptr; }); } + +void EmitPromiseWork(AsyncCallbackInfo *asyncCallbackInfo) +{ + if (asyncCallbackInfo == nullptr) { + HiLog::Error(LABEL, "%s asyncCallbackInfo is nullptr!", __func__); + return; + } + 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) {}, + [](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; + } + 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); + if (asyncCallbackInfo->type == FAIL) { + napi_reject_deferred(env, asyncCallbackInfo->deferred, result[0]); + } else { + napi_resolve_deferred(env, asyncCallbackInfo->deferred, result[1]); + } + 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 diff --git a/services/sensor/include/sensor_convert.h b/services/sensor/include/sensor_convert.h deleted file mode 100755 index b470b1fad53583d92d5adac847afb00deeb742ed..0000000000000000000000000000000000000000 --- a/services/sensor/include/sensor_convert.h +++ /dev/null @@ -1,57 +0,0 @@ -/* - * 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. - */ - -#ifndef SENSOR_DATA_CALLBACK_H -#define SENSOR_DATA_CALLBACK_H - -#include -#include -#include -#include "sensor_agent_type.h" -#include "refbase.h" -#include "sensor_device.h" - -namespace OHOS { -namespace Sensors { -using ConvertFun = int32_t (*)(const SensorEvent &event, struct SensorEvent &zEvent); - -class SensorConvert { -public: - int32_t ConvertToSensorEvent(const SensorEvent &event, struct SensorEvent &zEvent); - static int32_t ConvertToHeartRate(const SensorEvent &event, struct SensorEvent &zEvent); - static int32_t ConvertToOffbodyDetect(const SensorEvent &event, struct SensorEvent &zEvent); - static int32_t ConvertToStepDetector(const SensorEvent &event, struct SensorEvent &zEvent); - static int32_t ConvertToStepCounter(const SensorEvent &event, struct SensorEvent &zEvent); - static int32_t ConvertToMetaData(const SensorEvent &event, struct SensorEvent &zEvent); - static int32_t ConvertToMotionCali(const SensorEvent &event, struct SensorEvent &zEvent); - static int32_t ConvertToMotionUncali(const SensorEvent &event, struct SensorEvent &zEvent); - static int32_t ConvertToSignMotion(const SensorEvent &event, struct SensorEvent &zEvent); - static int32_t ConvertToEnvironmentCali(const SensorEvent &event, struct SensorEvent &zEvent); - static int32_t ConvertToEnvironmentUnCali(const SensorEvent &event, struct SensorEvent &zEvent); - static int32_t ConvertToEnvironmentOther(const SensorEvent &event, struct SensorEvent &zEvent); - static int32_t ConvertToOrientationPose(const SensorEvent &event, struct SensorEvent &zEvent); - static int32_t ConvertToOrientationDevice(const SensorEvent &event, struct SensorEvent &zEvent); - static int32_t ConvertToOrientation(const SensorEvent &event, struct SensorEvent &zEvent); - static int32_t ConvertToOrientationVec(const SensorEvent &event, struct SensorEvent &zEvent); - static int32_t ConvertToPressuePsAls(const SensorEvent &event, struct SensorEvent &zEvent); - static int32_t ConvertToUnsupport(const SensorEvent &event, struct SensorEvent &zEvent); - static int32_t ConvertToDefaultEvent(const SensorEvent &event, struct SensorEvent &zEvent); - -private: - static SensorDevice &sensorDevice_; -}; -} // namespace Sensors -} // namespace OHOS -#endif // SENSOR_DATA_CALLBACK_H diff --git a/services/sensor/src/client_info.cpp b/services/sensor/src/client_info.cpp index 7c504dbc994f2a12763dccfa2e8083ac61f10645..9ebb3c0356cf785f7e7fe37330b07327e04ecbc3 100755 --- a/services/sensor/src/client_info.cpp +++ b/services/sensor/src/client_info.cpp @@ -614,7 +614,6 @@ void ClientInfo::GetSensorChannelInfo(std::vector &channelInf continue; } channel.SetUid(uid); - // BundleManager bundleManager_; std::string packageName(""); channel.SetSensorId(sensorIt.first); channel.SetPackageName(packageName); diff --git a/services/sensor/src/sensor_convert.cpp b/services/sensor/src/sensor_convert.cpp deleted file mode 100755 index 2373128c4b4b3314e20bb3ce114f02044b102a43..0000000000000000000000000000000000000000 --- a/services/sensor/src/sensor_convert.cpp +++ /dev/null @@ -1,259 +0,0 @@ -/* - * 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. - */ - -#include "sensor_convert.h" - -#include "report_data_callback.h" -#include "securec.h" -#include "sensor_mapping.h" -#include "sensors_errors.h" -#include "sensors_log_domain.h" - -namespace OHOS { -namespace Sensors { -using namespace OHOS::HiviewDFX; -namespace { -constexpr HiLogLabel LABEL = { LOG_CORE, SensorsLogDomain::SENSOR_ADAPTER, "SensorDataCallback" }; -constexpr uint32_t INVALID_SENSOR_ID = -1; - -enum { - RET_OK = 0, - COPY_FAIL = -1, - DATA_TYPE_UNSUPPORT = -2, -}; - -enum { - X_VALUE = 0, - Y_VALUE = 1, - Z_VALUE = 2, - X_BIAS_VALUE = 3, - Y_BIAS_VALUE = 4, - Z_BIAS_VALUE = 5, - W_VALUE = 3, -}; - -enum { - LIGHT_DIMENSION = 3, - POSE_6DOF_DIMENSION = 15, - DEFAULT_DIMENSION = 16, -}; -} // namespace - -static std::map g_convertMap { - { SENSOR_TYPE_ACCELEROMETER, SensorDataCallback::ConvertToMotionCali }, - { SENSOR_TYPE_LINEAR_ACCELERATION, SensorDataCallback::ConvertToMotionCali }, - { SENSOR_TYPE_GRAVITY, SensorDataCallback::ConvertToMotionCali }, - { SENSOR_TYPE_GYROSCOPE, SensorDataCallback::ConvertToMotionCali }, - { SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED, SensorDataCallback::ConvertToMotionUncali }, - { SENSOR_TYPE_GYROSCOPE_UNCALIBRATED, SensorDataCallback::ConvertToMotionUncali }, - { SENSOR_TYPE_SIGNIFICANT_MOTION, SensorDataCallback::ConvertToSignMotion }, - { SensorType::STEP_DETECTOR, SensorDataCallback::ConvertToStepDetector }, - { SensorType::STEP_COUNTER, SensorDataCallback::ConvertToStepCounter }, - - { SENSOR_TYPE_AMBIENT_TEMPERATURE, SensorDataCallback::ConvertToEnvironmentOther }, - { SENSOR_TYPE_HUMIDITY, SensorDataCallback::ConvertToEnvironmentOther }, - { SENSOR_TYPE_MAGNETIC_FIELD, SensorDataCallback::ConvertToEnvironmentCali }, - { SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED, SensorDataCallback::ConvertToEnvironmentUnCali }, - { SensorType::PRESSURE, SensorDataCallback::ConvertToPressuePsAls }, - - { SensorType::POSE_6DOF, SensorDataCallback::ConvertToOrientationPose }, - { SENSOR_TYPE_DEVICE_ORIENTATION, SensorDataCallback::ConvertToOrientationDevice }, - { SENSOR_TYPE_ORIENTATION, SensorDataCallback::ConvertToOrientation }, - { SENSOR_TYPE_ROTATION_VECTOR, SensorDataCallback::ConvertToOrientationVec }, - { SENSOR_TYPE_GAME_ROTATION_VECTOR, SensorDataCallback::ConvertToOrientationVec }, - { SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR, SensorDataCallback::ConvertToOrientationVec }, - - { SENSOR_TYPE_PROXIMITY, SensorDataCallback::ConvertToPressuePsAls }, - { SENSOR_TYPE_AMBIENT_LIGHT, SensorDataCallback::ConvertToPressuePsAls }, - - { SensorType::META_DATA, SensorDataCallback::ConvertToMetaData }, - { SensorType::DYNAMIC_SENSOR_META, SensorDataCallback::ConvertToUnsupport }, - { SensorType::ADDITIONAL_INFO, SensorDataCallback::ConvertToUnsupport }, - - { SENSOR_TYPE_HEART_RATE, SensorDataCallback::ConvertToHeartRate }, - { SensorType::LOW_LATENCY_OFFBODY_DETECT, SensorDataCallback::ConvertToOffbodyDetect }, -}; - -int32_t SensorDataCallback::ConvertToHeartRate(const SensorEvent &event, struct SensorEvent &zEvent) -{ - zEvent.body.data[0] = aEvent.u.heartRate.bpm; - zEvent.body.data[1] = static_cast(aEvent.u.heartRate.status); - return ERR_OK; -} - -int32_t SensorDataCallback::ConvertToOffbodyDetect(const SensorEvent &event, struct SensorEvent &zEvent) -{ - zEvent.body.data[0] = aEvent.u.scalar; - return ERR_OK; -} - -int32_t SensorDataCallback::ConvertToStepCounter(const SensorEvent &event, struct SensorEvent &zEvent) -{ - zEvent.motion.data[0] = aEvent.u.stepCount; - return ERR_OK; -} - -int32_t SensorDataCallback::ConvertToStepDetector(const SensorEvent &event, struct SensorEvent &zEvent) -{ - zEvent.motion.data[0] = aEvent.u.scalar; - return ERR_OK; -} - -int32_t SensorDataCallback::ConvertToMotionCali(const SensorEvent &event, struct SensorEvent &zEvent) -{ - zEvent.motion.data[X_VALUE] = aEvent.u.vec3.x; - zEvent.motion.data[Y_VALUE] = aEvent.u.vec3.y; - zEvent.motion.data[Z_VALUE] = aEvent.u.vec3.z; - zEvent.accuracy = static_cast(aEvent.u.vec3.status); - return ERR_OK; -} - -int32_t SensorDataCallback::ConvertToMotionUncali(const SensorEvent &event, struct SensorEvent &zEvent) -{ - zEvent.motion.data[X_VALUE] = aEvent.u.uncal.x; - zEvent.motion.data[Y_VALUE] = aEvent.u.uncal.y; - zEvent.motion.data[Z_VALUE] = aEvent.u.uncal.z; - zEvent.motion.data[X_BIAS_VALUE] = aEvent.u.uncal.x_bias; - zEvent.motion.data[Y_BIAS_VALUE] = aEvent.u.uncal.y_bias; - zEvent.motion.data[Z_BIAS_VALUE] = aEvent.u.uncal.z_bias; - return ERR_OK; -} - -int32_t SensorDataCallback::ConvertToSignMotion(const SensorEvent &event, struct SensorEvent &zEvent) -{ - zEvent.motion.data[0] = aEvent.u.scalar; - return ERR_OK; -} - -int32_t SensorDataCallback::ConvertToEnvironmentCali(const SensorEvent &event, struct SensorEvent &zEvent) -{ - zEvent.environment.data[X_VALUE] = aEvent.u.vec3.x; - zEvent.environment.data[Y_VALUE] = aEvent.u.vec3.y; - zEvent.environment.data[Z_VALUE] = aEvent.u.vec3.z; - zEvent.accuracy = static_cast(aEvent.u.vec3.status); - return ERR_OK; -} - -int32_t SensorDataCallback::ConvertToEnvironmentUnCali(const SensorEvent &event, struct SensorEvent &zEvent) -{ - zEvent.environment.data[X_VALUE] = aEvent.u.uncal.x; - zEvent.environment.data[Y_VALUE] = aEvent.u.uncal.y; - zEvent.environment.data[Z_VALUE] = aEvent.u.uncal.z; - zEvent.environment.data[X_BIAS_VALUE] = aEvent.u.uncal.x_bias; - zEvent.environment.data[Y_BIAS_VALUE] = aEvent.u.uncal.y_bias; - zEvent.environment.data[Z_BIAS_VALUE] = aEvent.u.uncal.z_bias; - return ERR_OK; -} - -int32_t SensorDataCallback::ConvertToEnvironmentOther(const SensorEvent &event, struct SensorEvent &zEvent) -{ - zEvent.environment.data[0] = aEvent.u.scalar; - return ERR_OK; -} - -int32_t SensorDataCallback::ConvertToOrientationPose(const SensorEvent &event, struct SensorEvent &zEvent) -{ - for (int32_t i = 0; i < POSE_6DOF_DIMENSION; ++i) { - zEvent.orientation.data[i] = aEvent.u.pose6DOF[i]; - } - return ERR_OK; -} - -int32_t SensorDataCallback::ConvertToOrientationDevice(const SensorEvent &event, struct SensorEvent &zEvent) -{ - zEvent.orientation.data[0] = aEvent.u.scalar; - return ERR_OK; -} - -int32_t SensorDataCallback::ConvertToOrientation(const SensorEvent &event, struct SensorEvent &zEvent) -{ - zEvent.orientation.data[X_VALUE] = aEvent.u.vec3.x; - zEvent.orientation.data[Y_VALUE] = aEvent.u.vec3.y; - zEvent.orientation.data[Z_VALUE] = aEvent.u.vec3.z; - zEvent.accuracy = static_cast(aEvent.u.vec3.status); - return ERR_OK; -} - -int32_t SensorDataCallback::ConvertToOrientationVec(const SensorEvent &event, struct SensorEvent &zEvent) -{ - zEvent.orientation.data[X_VALUE] = aEvent.u.vec4.x; - zEvent.orientation.data[Y_VALUE] = aEvent.u.vec4.y; - zEvent.orientation.data[Z_VALUE] = aEvent.u.vec4.z; - zEvent.orientation.data[W_VALUE] = aEvent.u.vec4.w; - return ERR_OK; -} - -int32_t SensorDataCallback::ConvertToPressuePsAls(const SensorEvent &event, struct SensorEvent &zEvent) -{ - for (int32_t i = 0; i < LIGHT_DIMENSION; i++) { - zEvent.light.data[i] = aEvent.u.data[i]; - } - return ERR_OK; -} - -int32_t SensorDataCallback::ConvertToMetaData(const SensorEvent &event, struct SensorEvent &zEvent) -{ - SensorMapping sensorMapping; - zEvent.other.data[0] = static_cast(aEvent.u.meta.what); - // for Meta data, meta sensorId is stored in the 'sensorId' of zEvent header, - // real sensorid store in zEvent.other.reserved[0] - uint32_t realType = sensorDevice_.GetSensorTypeFromHandle(aEvent.sensorHandle); - zEvent.other.reserved[0] = sensorMapping.GetSensorIdByAType(static_cast(realType)); - return ERR_OK; -} - -int32_t SensorDataCallback::ConvertToUnsupport(const SensorEvent &event, struct SensorEvent &zEvent) -{ - return DATA_TYPE_UNSUPPORT; -} - -std::mutex SensorDataCallback::dataMutex_; -std::condition_variable SensorDataCallback::dataCondition_; - -int32_t SensorDataCallback::ConvertToDefaultEvent(const SensorEvent &event, struct SensorEvent &zEvent) -{ - if (aEvent.sensorType >= SensorType::DEVICE_PRIVATE_BASE) { - // data is defined with 16 float array - if (memcpy_s(zEvent.other.data, DEFAULT_DIMENSION * sizeof(float), aEvent.u.data.data(), - DEFAULT_DIMENSION * sizeof(float)) != EOK) { - HiLog::Error(LABEL, "%{public}s : memcpy_s is failed", __func__); - return COPY_FAIL; - } - } - return ERR_OK; -} - -int32_t SensorDataCallback::ConvertToSensorEvent(const SensorEvent &event, struct SensorEvent &zEvent) -{ - int32_t sensorTypeId = event.sensorTypeId; - if (sensorId == INVALID_SENSOR_ID) { - HiLog::Error(LABEL, "%{public}s failed", __func__); - return ERR_INVALID_VALUE; - } - - zEvent = { .version = sensorDevice_.GetHalDeviceVersion(), - .sensorId = sensorId, - .flags = 0, - .timestamp = aEvent.timestamp, - .accuracy = 0 }; - - auto it = g_convertMap.find(aEvent.sensorType); - if (it != g_convertMap.end()) { - return it->second(aEvent, zEvent); - } - return ConvertToDefaultEvent(aEvent, zEvent); -} -} // namespace Sensors -} // namespace OHOS diff --git a/services/sensor/src/sensor_manager.cpp b/services/sensor/src/sensor_manager.cpp index 872653ee657088b9cc426d244ec30fdf587b6a3b..2413a6b92794ba7e4d151185ba5ba2de477488b2 100755 --- a/services/sensor/src/sensor_manager.cpp +++ b/services/sensor/src/sensor_manager.cpp @@ -179,7 +179,6 @@ ErrCode SensorManager::AfterDisableSensor(uint32_t sensorId) auto ret = clientInfo_.GetStoreEvent(sensorId, event); if (ret == ERR_OK) { HiLog::Debug(LABEL, "%{public}s change the default state is far", __func__); - // event.light.data[0] = PROXIMITY_FAR; event.data[0] = PROXIMITY_FAR; clientInfo_.StoreEvent(event); } diff --git a/utils/include/dmd_report.h b/utils/include/dmd_report.h index a47975c489bceb684aa9a9fa6f335dd08c89340d..4955661f775f7255dcd4a334e44fbf65d939da38 100755 --- a/utils/include/dmd_report.h +++ b/utils/include/dmd_report.h @@ -31,9 +31,7 @@ enum SensorEventId { MISC_SERVICE_EXCEPTION = 951000111, SENSOR_SERVICE_IPC_EXCEPTION = 951000112, MISC_SERVICE_IPC_EXCEPTION = 951000113, - SENSOR_HIDL_SERVICE_EXCEPTION = 951000114, - LIGHT_HIDL_SERVICE_EXCEPTION = 951000115, - VIBRATOR_HIDL_SERVICE_EXCEPTION = 951000116, + SENSOR_HDF_SERVICE_EXCEPTION = 951000114, SENSOR_DATA_CHANNEL_EXCEPTION = 951000117, }; diff --git a/utils/include/sensors_errors.h b/utils/include/sensors_errors.h index a05258d222f0564c75f9db7789f6d3be786dc873..114e1ec63154bffd7ee5eca56b412d28e8778660 100755 --- a/utils/include/sensors_errors.h +++ b/utils/include/sensors_errors.h @@ -22,11 +22,10 @@ namespace OHOS { namespace Sensors { enum { MODULE_COMMON = 0x00, - MODULE_SENSORS_ADAPTER = 0x01, + MODULE_SENSORS_DEVICE = 0x01, MODULE_SENSOR_SERVICE = 0x02, MODULE_SENSORS_UTILS = 0x03, - MODULE_MISCDEVICE_SERVICE = 0x04, - MODULE_SENSORS_NATIVE = 0X05, + MODULE_SENSORS_NATIVE = 0X04, }; // Error code for common @@ -38,16 +37,16 @@ enum { COMMON_ERR = COMMON_ERR_OFFSET, }; -// Error code for adapter -constexpr ErrCode ADAPTER_ERR_OFFSET = ErrCodeOffset(SUBSYS_SENSORS, MODULE_SENSORS_ADAPTER); +// Error code for device +constexpr ErrCode DEVICE_ERR_OFFSET = ErrCodeOffset(SUBSYS_SENSORS, MODULE_SENSORS_DEVICE); enum { - ADAPTER_ERR = ADAPTER_ERR_OFFSET, - ADAPTER_ENABLE_SENSOR_ERR = ADAPTER_ERR_OFFSET + 1, - ADAPTER_DISABLE_SENSOR_ERR = ADAPTER_ENABLE_SENSOR_ERR + 1, - ADAPTER_RUN_COMMAND_ERR = ADAPTER_DISABLE_SENSOR_ERR + 1, - ADAPTER_SET_SENSOR_CONFIG_ERR = ADAPTER_RUN_COMMAND_ERR + 1, - ADAPTER_NOT_SUPPORT_CMD_ERR = ADAPTER_SET_SENSOR_CONFIG_ERR + 1, + DEVICE_ERR = DEVICE_ERR_OFFSET, + DEVICE_ENABLE_SENSOR_ERR = DEVICE_ERR_OFFSET + 1, + DEVICE_DISABLE_SENSOR_ERR = DEVICE_ENABLE_SENSOR_ERR + 1, + DEVICE_RUN_COMMAND_ERR = DEVICE_DISABLE_SENSOR_ERR + 1, + DEVICE_SET_SENSOR_CONFIG_ERR = DEVICE_RUN_COMMAND_ERR + 1, + DEVICE_NOT_SUPPORT_CMD_ERR = DEVICE_SET_SENSOR_CONFIG_ERR + 1, }; // Error code for sensor service @@ -57,8 +56,8 @@ enum { SENSOR_SERVICE_ERR = SENSOR_SERVICE_ERR_OFFSET, CMD_TYPE_ERR = SENSOR_SERVICE_ERR + 1, SENSOR_DEVICE_INIT_ERR = CMD_TYPE_ERR + 1, - CONNECT_SENSOR_HIDL_ERR = SENSOR_DEVICE_INIT_ERR + 1, - SET_SENSOR_CONFIG_ERR = CONNECT_SENSOR_HIDL_ERR + 1, + CONNECT_SENSOR_HDF_ERR = SENSOR_DEVICE_INIT_ERR + 1, + SET_SENSOR_CONFIG_ERR = CONNECT_SENSOR_HDF_ERR + 1, ENABLE_SENSOR_ERR = SET_SENSOR_CONFIG_ERR + 1, DISABLE_SENSOR_ERR = ENABLE_SENSOR_ERR + 1, RUN_COMMAND_ERR = DISABLE_SENSOR_ERR + 1, @@ -79,23 +78,6 @@ enum { WRITE_MSG_ERR = DUMP_PARAM_ERR + 1, }; -// Error code for miscdevice service -constexpr ErrCode MISCDEVICE_SERVICE_ERR_OFFSET = ErrCodeOffset(SUBSYS_SENSORS, MODULE_MISCDEVICE_SERVICE); - -enum { - LIGHT_HIDL_CONNECT_ERR = MISCDEVICE_SERVICE_ERR_OFFSET, - LIGHT_ID_NOT_SUPPORT = LIGHT_HIDL_CONNECT_ERR + 1, - LIGHT_ERR = LIGHT_ID_NOT_SUPPORT + 1, - LIGHT_PLAY_EFFECT_ERROR = LIGHT_ERR + 1, - LIGHT_STOP_EFFECT_ERROR = LIGHT_PLAY_EFFECT_ERROR + 1, - LIGHT_END_ERROR = LIGHT_STOP_EFFECT_ERROR, - VIBRATOR_HIDL_CONNECT_ERR = LIGHT_END_ERROR + 1, - VIBRATOR_ON_ERR = VIBRATOR_HIDL_CONNECT_ERR + 1, - VIBRATOR_OFF_ERR = VIBRATOR_ON_ERR + 1, - VIBRATOR_PLAY_EFFECT_ERR = VIBRATOR_OFF_ERR + 1, - VIBRATOR_STOP_EFFECT_ERR = VIBRATOR_PLAY_EFFECT_ERR + 1, - VIBRATOR_SET_PARA_ERR = VIBRATOR_STOP_EFFECT_ERR + 1, -}; // Error code for Sensor uitls constexpr ErrCode SENSOR_UTILS_ERR_OFFSET = ErrCodeOffset(SUBSYS_SENSORS, MODULE_SENSORS_UTILS); enum { @@ -119,8 +101,6 @@ enum { SENSOR_NATIVE_SAM_ERR = SENSOR_NATIVE_ERR_OFFSET, SENSOR_NATIVE_GET_SERVICE_ERR = SENSOR_NATIVE_SAM_ERR + 1, SENSOR_NATIVE_REGSITER_CB_ERR = SENSOR_NATIVE_GET_SERVICE_ERR + 1, - MISC_NATIVE_GET_SERVICE_ERR = SENSOR_NATIVE_REGSITER_CB_ERR + 1, - MISC_NATIVE_SAM_ERR = MISC_NATIVE_GET_SERVICE_ERR + 1, }; } // namespace Sensors } // namespace OHOS diff --git a/utils/src/dmd_report.cpp b/utils/src/dmd_report.cpp index c30ca7e40c47dcc6e935a49d8f00ababe4306d3b..25b90c3f90f1addef21493a346628cba5ad2f8b6 100755 --- a/utils/src/dmd_report.cpp +++ b/utils/src/dmd_report.cpp @@ -39,9 +39,7 @@ std::map DmdReport::eventMap_ = { { MISC_SERVICE_EXCEPTION, 0 }, { SENSOR_SERVICE_IPC_EXCEPTION, 0 }, { MISC_SERVICE_IPC_EXCEPTION, 0 }, - { SENSOR_HIDL_SERVICE_EXCEPTION, 0 }, - { LIGHT_HIDL_SERVICE_EXCEPTION, 0 }, - { VIBRATOR_HIDL_SERVICE_EXCEPTION, 0 }, + { SENSOR_HDF_SERVICE_EXCEPTION, 0 }, { SENSOR_DATA_CHANNEL_EXCEPTION, 0 }, }; @@ -66,12 +64,8 @@ static std::string GetEventName(int32_t eventId) return "SensorServiceIpcException"; case MISC_SERVICE_IPC_EXCEPTION: return "MiscServiceIpcException"; - case SENSOR_HIDL_SERVICE_EXCEPTION: - return "SensorHidlServiceException"; - case LIGHT_HIDL_SERVICE_EXCEPTION: - return "LightHidlServiceException"; - case VIBRATOR_HIDL_SERVICE_EXCEPTION: - return "VibratorHidlServiceException"; + case SENSOR_HDF_SERVICE_EXCEPTION: + return "SensorHdfServiceException"; case SENSOR_DATA_CHANNEL_EXCEPTION: return "SensorDataChannelException"; default: