diff --git a/bundle.json b/bundle.json index 1f60658af12fe30ba5ec55111265e8d8825c517c..537f25166b50109031299c603f55eca1174923cf 100644 --- a/bundle.json +++ b/bundle.json @@ -46,10 +46,10 @@ "base_group": [], "fwk_group": [ "//base/sensors/sensor/frameworks/js/napi:sensor_js_target", - "//base/sensors/sensor/frameworks/js/ani:sensor_ani_target", "//base/sensors/sensor/frameworks/cj:cj_sensor_ffi", "//base/sensors/sensor/frameworks/native:sensor_target", "//base/sensors/sensor/frameworks/native:ohsensor", + "//base/sensors/sensor/frameworks/ets/taihe:sensor_taihe", "//base/sensors/sensor/utils:sensor_utils_target" ], "service_group": [ @@ -58,6 +58,9 @@ ] }, "inner_kits": [ + { + "name": "//base/sensors/sensor/frameworks/ets/taihe:copy_taihe" + }, { "name": "//base/sensors/sensor/frameworks/native:sensor_interface_native", "header": { diff --git a/frameworks/js/ani/BUILD.gn b/frameworks/ets/taihe/BUILD.gn similarity index 47% rename from frameworks/js/ani/BUILD.gn rename to frameworks/ets/taihe/BUILD.gn index c56092f3b88265d944156277f43425d535aa2682..e9149dee53a10fa70d4520f96d2e205ea0febc41 100644 --- a/frameworks/js/ani/BUILD.gn +++ b/frameworks/ets/taihe/BUILD.gn @@ -13,65 +13,88 @@ import("//build/config/components/ets_frontend/ets2abc_config.gni") import("//build/ohos.gni") +import("//build/ohos/taihe_idl/taihe.gni") import("./../../../sensor.gni") -ohos_shared_library("sensor_ani") { +subsystem_name = "sensors" +part_name = "sensor" +taihe_generated_file_path = "$taihe_file_path/out/$subsystem_name/$part_name" + +copy_taihe_idl("copy_taihe") { + sources = [ "idl/ohos.sensor.taihe" ] + + external_deps = [] +} + +ohos_taihe("run_taihe") { + taihe_generated_file_path = "$taihe_generated_file_path" + deps = [ ":copy_taihe" ] + outputs = [ + "$taihe_generated_file_path/src/ohos.sensor.abi.c", + "$taihe_generated_file_path/src/ohos.sensor.ani.cpp", + ] +} + +taihe_shared_library("sensor_taihe_native") { branch_protector_ret = "pac_ret" sanitize = { + boundary_sanitize = true cfi = true cfi_cross_dso = true debug = false + integer_overflow = true + ubsan = true } - - sources = [ "src/sensor_ani.cpp" ] + taihe_generated_file_path = "$taihe_generated_file_path" + subsystem_name = "$subsystem_name" + part_name = "$part_name" include_dirs = [ - "include", "$SUBSYSTEM_DIR/frameworks/native/include", + "$SUBSYSTEM_DIR/frameworks/js/napi/include", "$SUBSYSTEM_DIR/interfaces/inner_api", "$SUBSYSTEM_DIR/utils/common/include", ] + sources = get_target_outputs(":run_taihe") + sources += [ + "author/src/ani_constructor.cpp", + "author/src/ohos.sensor.impl.cpp", + ] deps = [ - "$SUBSYSTEM_DIR/frameworks/native:sensor_interface_native", - "$SUBSYSTEM_DIR/utils/common:libsensor_utils", + ":run_taihe", + "$SUBSYSTEM_DIR/frameworks/native:sensor_interface_native" ] - external_deps = [ "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "c_utils:utils", - "eventhandler:libeventhandler", "hilog:libhilog", "ipc:ipc_single", - "runtime_core:ani", - "safwk:system_ability_fwk", "samgr:samgr_proxy", ] - - subsystem_name = "sensors" - part_name = "sensor" - output_extension = "so" } generate_static_abc("sensor_abc") { - base_url = "./ets" - files = [ "./ets/@ohos.sensor.ets" ] - dst_file = "$target_out_dir/sensor.abc" - out_puts = [ "$target_out_dir/sensor.abc" ] + base_url = "$taihe_generated_file_path" + files = [ + "$taihe_generated_file_path/@ohos.base.ets", + "$taihe_generated_file_path/@ohos.sensor.ets", + ] is_boot_abc = "True" - device_dst_file = "/system/framework/sensor.abc" + device_dst_file = "/system/framework/sensor_abc.abc" + dependencies = [ ":run_taihe" ] } -ohos_prebuilt_etc("sensor_abc_etc") { - source = "$target_out_dir/sensor.abc" +ohos_prebuilt_etc("sensor_etc") { + source = "$target_out_dir/sensor_abc.abc" module_install_dir = "framework" - subsystem_name = "sensors" - part_name = "sensor" + part_name = "$part_name" + subsystem_name = "$subsystem_name" deps = [ ":sensor_abc" ] } -group("sensor_ani_target") { +group("sensor_taihe") { deps = [ - ":sensor_abc_etc", - ":sensor_ani", + ":sensor_etc", + ":sensor_taihe_native", ] } diff --git a/frameworks/js/ani/ets/@ohos.sensor.ets b/frameworks/ets/taihe/author/src/ani_constructor.cpp similarity index 33% rename from frameworks/js/ani/ets/@ohos.sensor.ets rename to frameworks/ets/taihe/author/src/ani_constructor.cpp index 31b4c5526f534d93dcd08d63432afffcc5167804..931fc92a1fc5f8ecd19d6edecae468fe4da7d2cd 100644 --- a/frameworks/js/ani/ets/@ohos.sensor.ets +++ b/frameworks/ets/taihe/author/src/ani_constructor.cpp @@ -4,7 +4,7 @@ * 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 + * 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, @@ -13,42 +13,19 @@ * limitations under the License. */ -import type { Callback } from '@ohos.base'; -import { BusinessError } from '@ohos.base'; +#include "ohos.sensor.ani.hpp" +#include "taihe/runtime.hpp" -export default namespace sensor { - loadLibrary("sensor_ani"); - - export native function on(type: 'ORIENTATION', callback: Callback, options?: Options): void; - export native function off(type: 'ORIENTATION', callback?: Callback): void; - export type SensorFrequency = 'game' | 'ui' | 'normal'; - export interface Options { - interval?: number | SensorFrequency; - } - - export enum SensorAccuracy { - ACCURACY_UNRELIABLE = 0, - ACCURACY_LOW = 1, - ACCURACY_MEDIUM = 2, - ACCURACY_HIGH = 3 - } - - export interface Response { - timestamp: number; - accuracy: SensorAccuracy; - } - - export interface OrientationResponse extends Response { - alpha: number; - beta: number; - gamma: number; +ANI_EXPORT ani_status ANI_Constructor(ani_vm *vm, uint32_t *result) +{ + ani_env *env; + if (ANI_OK != vm->GetEnv(ANI_VERSION_1, &env)) { + return ANI_ERROR; } - - class OrientationResponseImpl implements OrientationResponse { - timestamp: number; - accuracy: SensorAccuracy; - alpha: number; - beta: number; - gamma: number; + if (ANI_OK != ohos::sensor::ANIRegister(env)) { + std::cerr << "Error from ohos::sensor::ANIRegister" << std::endl; + return ANI_ERROR; } + *result = ANI_VERSION_1; + return ANI_OK; } \ No newline at end of file diff --git a/frameworks/ets/taihe/author/src/ohos.sensor.impl.cpp b/frameworks/ets/taihe/author/src/ohos.sensor.impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..13f7cdbf792b941bda0b81fc98eaea52a8444e0c --- /dev/null +++ b/frameworks/ets/taihe/author/src/ohos.sensor.impl.cpp @@ -0,0 +1,1554 @@ +/* + * Copyright (c) 2025 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 "ohos.sensor.impl.hpp" + +#include +#include +#include +#include +#include +#include + +#include "ohos.sensor.proj.hpp" +#include "refbase.h" +#include "securec.h" +#include "sensor_agent.h" +#include "sensor_agent_type.h" +#include "sensor_algorithm.h" +#include "sensor_errors.h" +#include "sensor_log.h" +#include "stdexcept" +#include "taihe/runtime.hpp" + +#undef LOG_TAG +#define LOG_TAG "OhosSensorImpl" + +using namespace taihe; +using namespace ohos::sensor; +using namespace OHOS::Sensors; +using namespace OHOS; + +using responseSensorData = std::variant; +using callbackType = std::variant, + taihe::callback, taihe::callback, + taihe::callback, taihe::callback, + taihe::callback, taihe::callback, + taihe::callback, + taihe::callback, taihe::callback, + taihe::callback, taihe::callback, + taihe::callback, taihe::callback, + taihe::callback, taihe::callback, + taihe::callback, taihe::callback, + taihe::callback, taihe::callback, + taihe::callback, taihe::callback, + taihe::callback>; + +struct CallbackObject : public RefBase { + CallbackObject(callbackType cb, ani_ref ref) : callback(cb), ref(ref) + { + } + ~CallbackObject() + { + } + callbackType callback; + ani_ref ref; +}; + +namespace { +constexpr int32_t ROTATION_VECTOR_LENGTH = 3; +constexpr int32_t REPORTING_INTERVAL = 200000000; +constexpr int32_t THREE_DIMENSIONAL_MATRIX_LENGTH = 9; +constexpr int32_t CALLBACK_MAX_DATA_LENGTH = 16; + +void CallBackAccelermeter(std::map data, sptr callbackObject); +void CallBackGyroscope(std::map data, sptr callbackObject); +void CallBackAmbientLight(std::map data, sptr callbackObject); +void CallBackMagneticField(std::map data, sptr callbackObject); +void CallBackBarometer(std::map data, sptr callbackObject); +void CallBackHall(std::map data, sptr callbackObject); +void CallBackProximity(std::map data, sptr callbackObject); +void CallBackHumidity(std::map data, sptr callbackObject); +void CallBackOrientation(std::map data, sptr callbackObject); +void CallBackGravity(std::map data, sptr callbackObject); +void CallBackLinearAcceleration(std::map data, sptr callbackObject); +void CallBackRotationVector(std::map data, sptr callbackObject); +void CallBackAmbientTemperature(std::map data, sptr callbackObject); +void CallBackMagneticFieldUncalibrated(std::map data, + sptr callbackObject); +void CallBackGyroscopeUncalibrated(std::map data, sptr callbackObject); +void CallBackSignificantMotion(std::map data, sptr callbackObject); +void CallBackPedometerDetection(std::map data, sptr callbackObject); +void CallBackPedometer(std::map data, sptr callbackObject); +void CallBackHeartRate(std::map data, sptr callbackObject); +void CallBackWearDetection(std::map data, sptr callbackObject); +void CallBackAccelerometerUncalibrated(std::map data, + sptr callbackObject); +void CallBackColor(std::map data, sptr callbackObject); +void CallBackSar(std::map data, sptr callbackObject); +void EmitOnceCallback(SensorEvent *event); + +std::map g_samplingPeriod = { + { "normal", 200000000 }, + { "ui", 60000000 }, + { "game", 20000000 }, +}; + +std::map> g_sensorAttributeList = { + { 0, { "x" } }, + { SENSOR_TYPE_ID_ACCELEROMETER, { "x", "y", "z" } }, + { SENSOR_TYPE_ID_GYROSCOPE, { "x", "y", "z" } }, + { SENSOR_TYPE_ID_AMBIENT_LIGHT, { "intensity", "colorTemperature", "infraredLuminance" } }, + { SENSOR_TYPE_ID_MAGNETIC_FIELD, { "x", "y", "z" } }, + { SENSOR_TYPE_ID_BAROMETER, { "pressure" } }, + { SENSOR_TYPE_ID_HALL, { "status" } }, + { SENSOR_TYPE_ID_TEMPERATURE, { "temperature" } }, + { SENSOR_TYPE_ID_PROXIMITY, { "distance" } }, + { SENSOR_TYPE_ID_HUMIDITY, { "humidity" } }, + { SENSOR_TYPE_ID_ORIENTATION, { "alpha", "beta", "gamma" } }, + { SENSOR_TYPE_ID_GRAVITY, { "x", "y", "z" } }, + { SENSOR_TYPE_ID_LINEAR_ACCELERATION, { "x", "y", "z" } }, + { SENSOR_TYPE_ID_ROTATION_VECTOR, { "x", "y", "z", "w" } }, + { SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, { "temperature" } }, + { SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, { "x", "y", "z", "biasX", "biasY", "biasZ" } }, + { SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, { "x", "y", "z", "biasX", "biasY", "biasZ" } }, + { SENSOR_TYPE_ID_SIGNIFICANT_MOTION, { "scalar" } }, + { SENSOR_TYPE_ID_PEDOMETER_DETECTION, { "scalar" } }, + { SENSOR_TYPE_ID_PEDOMETER, { "steps" } }, + { SENSOR_TYPE_ID_HEART_RATE, { "heartRate" } }, + { SENSOR_TYPE_ID_WEAR_DETECTION, { "value" } }, + { SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, { "x", "y", "z", "biasX", "biasY", "biasZ" } }, + { SENSOR_TYPE_ID_COLOR, { "lightIntensity", "colorTemperature" } }, + { SENSOR_TYPE_ID_SAR, { "absorptionRatio" } }, + { SENSOR_TYPE_ID_FUSION_PRESSURE, { "fusionPressure" } }, +}; + +std::map, sptr)>> + g_functionBySensorTypeIdMap = { + { SENSOR_TYPE_ID_ACCELEROMETER, CallBackAccelermeter }, + { SENSOR_TYPE_ID_GYROSCOPE, CallBackGyroscope }, + { SENSOR_TYPE_ID_AMBIENT_LIGHT, CallBackAmbientLight }, + { SENSOR_TYPE_ID_MAGNETIC_FIELD, CallBackMagneticField }, + { SENSOR_TYPE_ID_BAROMETER, CallBackBarometer }, + { SENSOR_TYPE_ID_HALL, CallBackHall }, + { SENSOR_TYPE_ID_PROXIMITY, CallBackProximity }, + { SENSOR_TYPE_ID_HUMIDITY, CallBackHumidity }, + { SENSOR_TYPE_ID_ORIENTATION, CallBackOrientation }, + { SENSOR_TYPE_ID_GRAVITY, CallBackGravity }, + { SENSOR_TYPE_ID_LINEAR_ACCELERATION, CallBackLinearAcceleration }, + { SENSOR_TYPE_ID_ROTATION_VECTOR, CallBackRotationVector }, + { SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, CallBackAmbientTemperature }, + { SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, CallBackMagneticFieldUncalibrated }, + { SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, CallBackGyroscopeUncalibrated }, + { SENSOR_TYPE_ID_SIGNIFICANT_MOTION, CallBackSignificantMotion }, + { SENSOR_TYPE_ID_PEDOMETER_DETECTION, CallBackPedometerDetection }, + { SENSOR_TYPE_ID_PEDOMETER, CallBackPedometer }, + { SENSOR_TYPE_ID_HEART_RATE, CallBackHeartRate }, + { SENSOR_TYPE_ID_WEAR_DETECTION, CallBackWearDetection }, + { SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, CallBackAccelerometerUncalibrated }, + { SENSOR_TYPE_ID_COLOR, CallBackColor }, + { SENSOR_TYPE_ID_SAR, CallBackSar }, + }; + +std::mutex g_mutex; +std::mutex g_bodyMutex; +std::map>> g_subscribeCallbacks; +std::mutex g_onMutex; +std::mutex g_onceMutex; +std::map>> g_onceCallbackInfos; +std::map>> g_onCallbackInfos; +std::mutex g_sensorTaiheAttrListMutex; + +RotationMatrixResponse getRotationMatrixSyncGrav(array_view gravity, array_view geomagnetic) +{ + std::vector rotation(THREE_DIMENSIONAL_MATRIX_LENGTH); + std::vector inclination(THREE_DIMENSIONAL_MATRIX_LENGTH); + SensorAlgorithm sensorAlgorithm; + std::vector gravityVector(gravity.begin(), gravity.end()); + std::vector geomagneticVector(geomagnetic.begin(), geomagnetic.end()); + int32_t ret = sensorAlgorithm.CreateRotationAndInclination(gravityVector, geomagneticVector, rotation, inclination); + ohos::sensor::RotationMatrixResponse rsp = { + .rotation = array::make(THREE_DIMENSIONAL_MATRIX_LENGTH), + .inclination = array::make(THREE_DIMENSIONAL_MATRIX_LENGTH), + }; + if (ret != OHOS::ERR_OK) { + taihe::set_business_error(ret, "Create rotation and inclination matrix fail"); + return rsp; + } + for (int32_t i = 0; i < THREE_DIMENSIONAL_MATRIX_LENGTH; ++i) { + rsp.rotation[i] = rotation[i]; + rsp.inclination[i] = inclination[i]; + } + return rsp; +} + +array getOrientationSync(array_view rotationMatrix) +{ + std::vector rotationAngle(ROTATION_VECTOR_LENGTH); + SensorAlgorithm sensorAlgorithm; + std::vector rotationMatrixVector(rotationMatrix.begin(), rotationMatrix.end()); + int32_t ret = sensorAlgorithm.GetDirection(rotationMatrixVector, rotationAngle); + if (ret != OHOS::ERR_OK) { + taihe::set_business_error(ret, "Get direction fail"); + return taihe::array(rotationAngle); + } + return taihe::array(rotationAngle); +} + +array getRotationMatrixSync(array_view rotation) +{ + std::vector rotationMatrix(THREE_DIMENSIONAL_MATRIX_LENGTH); + SensorAlgorithm sensorAlgorithm; + std::vector rotationVector(rotation.begin(), rotation.end()); + int32_t ret = sensorAlgorithm.CreateRotationMatrix(rotationVector, rotationMatrix); + if (ret != OHOS::ERR_OK) { + taihe::set_business_error(ret, "Create rotation matrix fail"); + return taihe::array(rotationMatrix); + } + return taihe::array(rotationMatrix); +} + +array getSensorListSync() +{ + SensorInfo *sensorInfos = nullptr; + int32_t count = 0; + int32_t ret = GetAllSensors(&sensorInfos, &count); + std::vector<::ohos::sensor::Sensor> result; + if (ret != OHOS::ERR_OK) { + taihe::set_business_error(ret, "Get sensor list fail"); + return taihe::array<::ohos::sensor::Sensor>(result); + } + for (int32_t i = 0; i < count; ++i) { + if ((sensorInfos[i].sensorTypeId == SENSOR_TYPE_ID_AMBIENT_LIGHT1) || + (sensorInfos[i].sensorTypeId == SENSOR_TYPE_ID_PROXIMITY1) || + (sensorInfos[i].sensorTypeId > GL_SENSOR_TYPE_PRIVATE_MIN_VALUE)) { + SEN_HILOGD("This sensor is secondary ambient light"); + continue; + } + ohos::sensor::Sensor sensorInfo = { + .sensorName = sensorInfos[i].sensorName, + .vendorName = sensorInfos[i].vendorName, + .firmwareVersion = sensorInfos[i].firmwareVersion, + .hardwareVersion = sensorInfos[i].hardwareVersion, + .sensorId = sensorInfos[i].sensorId, + .maxRange = sensorInfos[i].maxRange, + .minSamplePeriod = sensorInfos[i].minSamplePeriod, + .maxSamplePeriod = sensorInfos[i].maxSamplePeriod, + .precision = sensorInfos[i].precision, + .power = sensorInfos[i].power, + }; + result.push_back(sensorInfo); + } + return taihe::array<::ohos::sensor::Sensor>(result); +} + +bool GetInterval(const Options &options, int64_t &interval) +{ + if (options.interval.holds_interval_i64()) { + interval = *options.interval.get_interval_i64_ptr(); + } else if (options.interval.holds_interval_string()) { + taihe::string modeTemp = *options.interval.get_interval_string_ptr(); + auto iter = g_samplingPeriod.find(modeTemp); + if (iter == g_samplingPeriod.end()) { + SEN_HILOGE("Find interval mode failed"); + return false; + } + interval = static_cast(iter->second); + SEN_HILOGI("Get interval by mode, mode:%{public}s", modeTemp.c_str()); + } else { + SEN_HILOGE("Interval failed"); + return false; + } + return true; +} + +bool CheckSubscribe(int32_t sensorTypeId) +{ + std::lock_guard onCallbackLock(g_onMutex); + return g_onCallbackInfos.find(sensorTypeId) != g_onCallbackInfos.end(); +} + +void CallBackAccelermeter(std::map data, sptr callbackObject) +{ + if (callbackObject == nullptr) { + SEN_HILOGE("callbackObject is null"); + return; + } + if (!std::holds_alternative>(callbackObject->callback)) { + SEN_HILOGE("callbackObject is not of type callback accelerometerResponse function"); + return; + } + ohos::sensor::Response res = { + .timestamp = std::get(data["timestamp"]), + .accuracy = std::get(data["accuracy"]), + }; + AccelerometerResponse responseData = { + .base = res, + .x = std::get(data["x"]), + .y = std::get(data["y"]), + .z = std::get(data["z"]), + }; + auto &func = std::get>(callbackObject->callback); + func(responseData); +} + +void CallBackGyroscope(std::map data, sptr callbackObject) +{ + if (callbackObject == nullptr) { + SEN_HILOGE("callbackObject is null"); + return; + } + if (!std::holds_alternative>(callbackObject->callback)) { + SEN_HILOGE("callbackObject is not of type callback gyroscopeResponse function"); + return; + } + ohos::sensor::Response res = { + .timestamp = std::get(data["timestamp"]), + .accuracy = std::get(data["accuracy"]), + }; + GyroscopeResponse responseData = { + .base = res, + .x = std::get(data["x"]), + .y = std::get(data["y"]), + .z = std::get(data["z"]), + }; + auto &func = std::get>(callbackObject->callback); + func(responseData); +} + +void CallBackAmbientLight(std::map data, sptr callbackObject) +{ + if (callbackObject == nullptr) { + SEN_HILOGE("callbackObject is null"); + return; + } + if (!std::holds_alternative>(callbackObject->callback)) { + SEN_HILOGE("callbackObject is not of type callback lightResponse function"); + return; + } + ohos::sensor::Response res = { + .timestamp = std::get(data["timestamp"]), + .accuracy = std::get(data["accuracy"]), + }; + LightResponse responseData = { + .base = res, + .intensity = std::get(data["intensity"]), + .colorTemperature = taihe::optional(std::in_place_t{}, std::get(data["colorTemperature"])), + .infraredLuminance = taihe::optional(std::in_place_t{}, std::get(data["infraredLuminance"])), + }; + auto &func = std::get>(callbackObject->callback); + func(responseData); +} + +void CallBackMagneticField(std::map data, sptr callbackObject) +{ + if (callbackObject == nullptr) { + SEN_HILOGE("callbackObject is null"); + return; + } + if (!std::holds_alternative>(callbackObject->callback)) { + SEN_HILOGE("callbackObject is not of type callback magneticFieldResponse function"); + return; + } + ohos::sensor::Response res = { + .timestamp = std::get(data["timestamp"]), + .accuracy = std::get(data["accuracy"]), + }; + MagneticFieldResponse responseData = { + .base = res, + .x = std::get(data["x"]), + .y = std::get(data["y"]), + .z = std::get(data["z"]), + }; + auto &func = std::get>(callbackObject->callback); + func(responseData); +} + +void CallBackBarometer(std::map data, sptr callbackObject) +{ + if (callbackObject == nullptr) { + SEN_HILOGE("callbackObject is null"); + return; + } + if (!std::holds_alternative>(callbackObject->callback)) { + SEN_HILOGE("callbackObject is not of type callback barometerResponse function"); + return; + } + ohos::sensor::Response res = { + .timestamp = std::get(data["timestamp"]), + .accuracy = std::get(data["accuracy"]), + }; + BarometerResponse responseData = { + .base = res, + .pressure = std::get(data["pressure"]), + }; + auto &func = std::get>(callbackObject->callback); + func(responseData); +} + +void CallBackHall(std::map data, sptr callbackObject) +{ + if (callbackObject == nullptr) { + SEN_HILOGE("callbackObject is null"); + return; + } + if (!std::holds_alternative>(callbackObject->callback)) { + SEN_HILOGE("callbackObject is not of type callback hallResponse function"); + return; + } + ohos::sensor::Response res = { + .timestamp = std::get(data["timestamp"]), + .accuracy = std::get(data["accuracy"]), + }; + HallResponse responseData = { + .base = res, + .status = std::get(data["status"]), + }; + auto &func = std::get>(callbackObject->callback); + func(responseData); +} + +void CallBackProximity(std::map data, sptr callbackObject) +{ + if (callbackObject == nullptr) { + SEN_HILOGE("callbackObject is null"); + return; + } + if (!std::holds_alternative>(callbackObject->callback)) { + SEN_HILOGE("callbackObject is not of type callback proximityResponse function"); + return; + } + ohos::sensor::Response res = { + .timestamp = std::get(data["timestamp"]), + .accuracy = std::get(data["accuracy"]), + }; + ProximityResponse responseData = { + .base = res, + .distance = std::get(data["distance"]), + }; + auto &func = std::get>(callbackObject->callback); + func(responseData); +} + +void CallBackHumidity(std::map data, sptr callbackObject) +{ + if (callbackObject == nullptr) { + SEN_HILOGE("callbackObject is null"); + return; + } + if (!std::holds_alternative>(callbackObject->callback)) { + SEN_HILOGE("callbackObject is not of type callback humidityResponse function"); + return; + } + ohos::sensor::Response res = { + .timestamp = std::get(data["timestamp"]), + .accuracy = std::get(data["accuracy"]), + }; + HumidityResponse responseData = { + .base = res, + .humidity = std::get(data["humidity"]), + }; + auto &func = std::get>(callbackObject->callback); + func(responseData); +} + +void CallBackOrientation(std::map data, sptr callbackObject) +{ + if (callbackObject == nullptr) { + SEN_HILOGE("callbackObject is null"); + return; + } + if (!std::holds_alternative>(callbackObject->callback)) { + SEN_HILOGE("callbackObject is not of type callback orientationResponse function"); + return; + } + ohos::sensor::Response res = { + .timestamp = std::get(data["timestamp"]), + .accuracy = std::get(data["accuracy"]), + }; + OrientationResponse responseData = { + .base = res, + .alpha = std::get(data["alpha"]), + .beta = std::get(data["beta"]), + .gamma = std::get(data["gamma"]), + }; + auto &func = std::get>(callbackObject->callback); + func(responseData); +} + +void CallBackGravity(std::map data, sptr callbackObject) +{ + if (callbackObject == nullptr) { + SEN_HILOGE("callbackObject is null"); + return; + } + if (!std::holds_alternative>(callbackObject->callback)) { + SEN_HILOGE("callbackObject is not of type callback gravityResponse function"); + return; + } + ohos::sensor::Response res = { + .timestamp = std::get(data["timestamp"]), + .accuracy = std::get(data["accuracy"]), + }; + GravityResponse responseData = { + .base = res, + .x = std::get(data["x"]), + .y = std::get(data["y"]), + .z = std::get(data["z"]), + }; + auto &func = std::get>(callbackObject->callback); + func(responseData); +} + +void CallBackLinearAcceleration(std::map data, sptr callbackObject) +{ + if (callbackObject == nullptr) { + SEN_HILOGE("callbackObject is null"); + return; + } + if (!std::holds_alternative>(callbackObject->callback)) { + SEN_HILOGE("callbackObject is not of type callback linearAccelerometerResponse function"); + return; + } + ohos::sensor::Response res = { + .timestamp = std::get(data["timestamp"]), + .accuracy = std::get(data["accuracy"]), + }; + LinearAccelerometerResponse responseData = { + .base = res, + .x = std::get(data["x"]), + .y = std::get(data["y"]), + .z = std::get(data["z"]), + }; + auto &func = std::get>(callbackObject->callback); + func(responseData); +} + +void CallBackRotationVector(std::map data, sptr callbackObject) +{ + if (callbackObject == nullptr) { + SEN_HILOGE("callbackObject is null"); + return; + } + if (!std::holds_alternative>(callbackObject->callback)) { + SEN_HILOGE("callbackObject is not of type callback rotationVectorResponse function"); + return; + } + ohos::sensor::Response res = { + .timestamp = std::get(data["timestamp"]), + .accuracy = std::get(data["accuracy"]), + }; + RotationVectorResponse responseData = { + .base = res, + .x = std::get(data["x"]), + .y = std::get(data["y"]), + .z = std::get(data["z"]), + .w = std::get(data["w"]), + }; + auto &func = std::get>(callbackObject->callback); + func(responseData); +} + +void CallBackAmbientTemperature(std::map data, sptr callbackObject) +{ + if (callbackObject == nullptr) { + SEN_HILOGE("callbackObject is null"); + return; + } + if (!std::holds_alternative>(callbackObject->callback)) { + SEN_HILOGE("callbackObject is not of type callback ambientTemperatureResponse function"); + return; + } + ohos::sensor::Response res = { + .timestamp = std::get(data["timestamp"]), + .accuracy = std::get(data["accuracy"]), + }; + AmbientTemperatureResponse responseData = { + .base = res, + .temperature = std::get(data["temperature"]), + }; + auto &func = std::get>(callbackObject->callback); + func(responseData); +} + +void CallBackMagneticFieldUncalibrated(std::map data, + sptr callbackObject) +{ + if (callbackObject == nullptr) { + SEN_HILOGE("callbackObject is null"); + return; + } + if (!std::holds_alternative>( + callbackObject->callback)) { + SEN_HILOGE("callbackObject is not of type callback magneticFieldUncalibratedResponse function"); + return; + } + ohos::sensor::Response res = { + .timestamp = std::get(data["timestamp"]), + .accuracy = std::get(data["accuracy"]), + }; + MagneticFieldUncalibratedResponse responseData = { + .base = res, + .x = std::get(data["x"]), + .y = std::get(data["y"]), + .z = std::get(data["z"]), + .biasX = std::get(data["biasX"]), + .biasY = std::get(data["biasY"]), + .biasZ = std::get(data["biasZ"]), + }; + auto &func = std::get>(callbackObject->callback); + func(responseData); +} + +void CallBackGyroscopeUncalibrated(std::map data, sptr callbackObject) +{ + if (callbackObject == nullptr) { + SEN_HILOGE("callbackObject is null"); + return; + } + if (!std::holds_alternative>( + callbackObject->callback)) { + SEN_HILOGE("callbackObject is not of type callback gyroscopeUncalibratedResponse function"); + return; + } + ohos::sensor::Response res = { + .timestamp = std::get(data["timestamp"]), + .accuracy = std::get(data["accuracy"]), + }; + GyroscopeUncalibratedResponse responseData = { + .base = res, + .x = std::get(data["x"]), + .y = std::get(data["y"]), + .z = std::get(data["z"]), + .biasX = std::get(data["biasX"]), + .biasY = std::get(data["biasY"]), + .biasZ = std::get(data["biasZ"]), + }; + auto &func = std::get>(callbackObject->callback); + func(responseData); +} + +void CallBackSignificantMotion(std::map data, sptr callbackObject) +{ + if (callbackObject == nullptr) { + SEN_HILOGE("callbackObject is null"); + return; + } + if (!std::holds_alternative>(callbackObject->callback)) { + SEN_HILOGE("callbackObject is not of type callback significantMotionResponse function"); + return; + } + ohos::sensor::Response res = { + .timestamp = std::get(data["timestamp"]), + .accuracy = std::get(data["accuracy"]), + }; + SignificantMotionResponse responseData = { + .base = res, + .scalar = std::get(data["scalar"]), + }; + auto &func = std::get>(callbackObject->callback); + func(responseData); +} + +void CallBackPedometerDetection(std::map data, sptr callbackObject) +{ + if (callbackObject == nullptr) { + SEN_HILOGE("callbackObject is null"); + return; + } + if (!std::holds_alternative>(callbackObject->callback)) { + SEN_HILOGE("callbackObject is not of type callback pedometerDetectionResponse function"); + return; + } + ohos::sensor::Response res = { + .timestamp = std::get(data["timestamp"]), + .accuracy = std::get(data["accuracy"]), + }; + PedometerDetectionResponse responseData = { + .base = res, + .scalar = std::get(data["scalar"]), + }; + auto &func = std::get>(callbackObject->callback); + func(responseData); +} + +void CallBackPedometer(std::map data, sptr callbackObject) +{ + if (callbackObject == nullptr) { + SEN_HILOGE("callbackObject is null"); + return; + } + if (!std::holds_alternative>(callbackObject->callback)) { + SEN_HILOGE("callbackObject is not of type callback pedometerResponse function"); + return; + } + ohos::sensor::Response res = { + .timestamp = std::get(data["timestamp"]), + .accuracy = std::get(data["accuracy"]), + }; + PedometerResponse responseData = { + .base = res, + .steps = std::get(data["steps"]), + }; + auto &func = std::get>(callbackObject->callback); + func(responseData); +} + +void CallBackHeartRate(std::map data, sptr callbackObject) +{ + if (callbackObject == nullptr) { + SEN_HILOGE("callbackObject is null"); + return; + } + if (!std::holds_alternative>(callbackObject->callback)) { + SEN_HILOGE("callbackObject is not of type callback heartRateResponse function"); + return; + } + ohos::sensor::Response res = { + .timestamp = std::get(data["timestamp"]), + .accuracy = std::get(data["accuracy"]), + }; + HeartRateResponse responseData = { + .base = res, + .heartRate = std::get(data["heartRate"]), + }; + auto &func = std::get>(callbackObject->callback); + func(responseData); +} + +void CallBackWearDetection(std::map data, sptr callbackObject) +{ + if (callbackObject == nullptr) { + SEN_HILOGE("callbackObject is null"); + return; + } + if (!std::holds_alternative>(callbackObject->callback)) { + SEN_HILOGE("callbackObject is not of type callback wearDetectionResponse function"); + return; + } + ohos::sensor::Response res = { + .timestamp = std::get(data["timestamp"]), + .accuracy = std::get(data["accuracy"]), + }; + WearDetectionResponse responseData = { + .base = res, + .value = std::get(data["value"]), + }; + auto &func = std::get>(callbackObject->callback); + func(responseData); +} + +void CallBackAccelerometerUncalibrated(std::map data, + sptr callbackObject) +{ + if (callbackObject == nullptr) { + SEN_HILOGE("callbackObject is null"); + return; + } + if (!std::holds_alternative>( + callbackObject->callback)) { + SEN_HILOGE("callbackObject is not of type callback accelerometerUncalibratedResponse function"); + return; + } + ohos::sensor::Response res = { + .timestamp = std::get(data["timestamp"]), + .accuracy = std::get(data["accuracy"]), + }; + AccelerometerUncalibratedResponse responseData = { + .base = res, + .x = std::get(data["x"]), + .y = std::get(data["y"]), + .z = std::get(data["z"]), + .biasX = std::get(data["biasX"]), + .biasY = std::get(data["biasY"]), + .biasZ = std::get(data["biasZ"]), + }; + auto &func = std::get>(callbackObject->callback); + func(responseData); +} + +void CallBackColor(std::map data, sptr callbackObject) +{ + if (callbackObject == nullptr) { + SEN_HILOGE("callbackObject is null"); + return; + } + if (!std::holds_alternative>(callbackObject->callback)) { + SEN_HILOGE("callbackObject is not of type callback colorResponse function"); + return; + } + ohos::sensor::Response res = { + .timestamp = std::get(data["timestamp"]), + .accuracy = std::get(data["accuracy"]), + }; + ColorResponse responseData = { + .base = res, + .lightIntensity = std::get(data["lightIntensity"]), + .colorTemperature = std::get(data["colorTemperature"]), + }; + auto &func = std::get>(callbackObject->callback); + func(responseData); +} + +void CallBackSar(std::map data, sptr callbackObject) +{ + if (callbackObject == nullptr) { + SEN_HILOGE("callbackObject is null"); + return; + } + if (!std::holds_alternative>(callbackObject->callback)) { + SEN_HILOGE("callbackObject is not of type callback sarResponse function"); + return; + } + ohos::sensor::Response res = { + .timestamp = std::get(data["timestamp"]), + .accuracy = std::get(data["accuracy"]), + }; + SarResponse responseData = { + .base = res, + .absorptionRatio = std::get(data["absorptionRatio"]), + }; + auto &func = std::get>(callbackObject->callback); + func(responseData); +} + +void CallbackDataBySensorTypeId(int32_t sensorTypeId, std::map data, + sptr callbackObject) +{ + if (g_functionBySensorTypeIdMap.find(sensorTypeId) == g_functionBySensorTypeIdMap.end()) { + SEN_HILOGE("SensorTypeId not exist, id:%{public}d", sensorTypeId); + return; + } + g_functionBySensorTypeIdMap[sensorTypeId](data, callbackObject); +} + +void CallbackSensorData(sptr callbackObject, SensorEvent *event) +{ + if (event == nullptr) { + SEN_HILOGE("event is null"); + return; + } + int32_t sensorTypeId = event->sensorTypeId; + std::lock_guard sensorTaiheAttrListLock(g_sensorTaiheAttrListMutex); + size_t size = g_sensorAttributeList[sensorTypeId].size(); + uint32_t dataLength = event->dataLen / sizeof(float); + if (size > dataLength) { + SEN_HILOGE("Data length mismatch"); + return; + } + auto sensorAttributes = g_sensorAttributeList[sensorTypeId]; + auto dataOrigin = reinterpret_cast(event->data); + float dataNow[CALLBACK_MAX_DATA_LENGTH] = { 0 }; + if (memcpy_s(dataNow, sizeof(dataNow), dataOrigin, event->dataLen) != EOK) { + SEN_HILOGE("Copy data failed"); + return; + } + std::map dataMap; + for (size_t i = 0; i < size; ++i) { + dataMap.emplace(sensorAttributes[i].c_str(), static_cast(dataNow[i])); + } + dataMap.emplace("timestamp", event->timestamp); + ohos::sensor::SensorAccuracy sensorAccuracyTemp(static_cast(event->option)); + dataMap.emplace("accuracy", sensorAccuracyTemp); + CallbackDataBySensorTypeId(sensorTypeId, dataMap, callbackObject); +} + +void EmitOnCallback(SensorEvent *event) +{ + if (event == nullptr) { + SEN_HILOGE("event is null"); + return; + } + int32_t sensorTypeId = event->sensorTypeId; + if (!CheckSubscribe(sensorTypeId)) { + return; + } + std::lock_guard onCallbackLock(g_onMutex); + auto onCallbackInfos = g_onCallbackInfos[sensorTypeId]; + for (auto &onCallbackInfo : onCallbackInfos) { + CallbackSensorData(onCallbackInfo, event); + } +} + +bool CheckSystemSubscribe(int32_t sensorTypeId) +{ + std::lock_guard subscribeLock(g_mutex); + auto iter = g_subscribeCallbacks.find(sensorTypeId); + return iter != g_subscribeCallbacks.end(); +} + +void EmitSubscribeCallback(SensorEvent *event) +{ + if (event == nullptr) { + SEN_HILOGE("event is null"); + return; + } + int32_t sensorTypeId = event->sensorTypeId; + if (!CheckSystemSubscribe(sensorTypeId)) { + return; + } + std::lock_guard subscribeLock(g_mutex); + auto callbacks = g_subscribeCallbacks[sensorTypeId]; + for (auto &callback : callbacks) { + CallbackSensorData(callback, event); + } +} + +void DataCallbackImpl(SensorEvent *event) +{ + if (event == nullptr) { + SEN_HILOGE("event is null"); + return; + } + EmitOnCallback(event); + EmitSubscribeCallback(event); + EmitOnceCallback(event); +} + +const SensorUser user = { .callback = DataCallbackImpl }; + +int32_t UnsubscribeSensor(int32_t sensorTypeId) +{ + int32_t ret = DeactivateSensor(sensorTypeId, &user); + if (ret != ERR_OK) { + SEN_HILOGE("DeactivateSensor failed"); + return ret; + } + return UnsubscribeSensor(sensorTypeId, &user); +} + +void EmitOnceCallback(SensorEvent *event) +{ + if (event == nullptr) { + SEN_HILOGE("event is null"); + return; + } + int32_t sensorTypeId = event->sensorTypeId; + std::lock_guard onceCallbackLock(g_onceMutex); + auto iter = g_onceCallbackInfos.find(sensorTypeId); + if (iter == g_onceCallbackInfos.end()) { + return; + } + auto &onceCallbackInfos = iter->second; + while (!onceCallbackInfos.empty()) { + auto onceCallbackInfo = onceCallbackInfos.front(); + auto beginIter = onceCallbackInfos.begin(); + onceCallbackInfos.erase(beginIter); + CallbackSensorData(onceCallbackInfo, event); + } + g_onceCallbackInfos.erase(sensorTypeId); + + CHKCV((!CheckSubscribe(sensorTypeId)), "Has client subscribe, not need cancel subscribe"); + CHKCV((!CheckSystemSubscribe(sensorTypeId)), "Has client subscribe system api, not need cancel subscribe"); + UnsubscribeSensor(sensorTypeId); +} + +int32_t SubscribeSensor(int32_t sensorTypeId, int64_t interval, RecordSensorCallback callback) +{ + int32_t ret = SubscribeSensor(sensorTypeId, &user); + if (ret != ERR_OK) { + SEN_HILOGE("SubscribeSensor failed"); + return ret; + } + ret = SetBatch(sensorTypeId, &user, interval, 0); + if (ret != ERR_OK) { + SEN_HILOGE("SetBatch failed"); + return ret; + } + return ActivateSensor(sensorTypeId, &user); +} + +void UpdateCallbackInfos(int32_t sensorTypeId, callbackType callback, uintptr_t opq) +{ + std::lock_guard onCallbackLock(g_onMutex); + ani_object callbackObj = reinterpret_cast(opq); + ani_ref callbackRef; + ani_env *env = taihe::get_env(); + if (env == nullptr || env->GlobalReference_Create(callbackObj, &callbackRef) != ANI_OK) { + SEN_HILOGE("Failed to create callbackRef, sensorTypeId:%{public}d", sensorTypeId); + return; + } + std::vector> callbackInfos = g_onCallbackInfos[sensorTypeId]; + bool isSubscribedCallback = + std::any_of(callbackInfos.begin(), callbackInfos.end(), [env, callbackRef](const CallbackObject *obj) { + ani_boolean isEqual = false; + return (env->Reference_StrictEquals(callbackRef, obj->ref, &isEqual) == ANI_OK) && isEqual; + }); + if (isSubscribedCallback) { + env->GlobalReference_Delete(callbackRef); + SEN_HILOGE("Callback is already subscribed, sensorTypeId:%{public}d", sensorTypeId); + return; + } + sptr taiheCallbackInfo = new (std::nothrow) CallbackObject(callback, callbackRef); + if (taiheCallbackInfo == nullptr) { + SEN_HILOGE("taiheCallbackInfo is nullptr"); + return; + } + callbackInfos.push_back(taiheCallbackInfo); + g_onCallbackInfos[sensorTypeId] = callbackInfos; +} + +void OnCommon(int32_t sensorTypeId, callbackType cb, uintptr_t opq, optional_view options) +{ + int64_t interval = REPORTING_INTERVAL; + if (options.has_value() && !GetInterval(options.value(), interval)) { + SEN_HILOGW("Get interval failed"); + } + SEN_HILOGD("Interval is %{public}" PRId64, interval); + int32_t ret = SubscribeSensor(sensorTypeId, interval, DataCallbackImpl); + if (ret != ERR_OK) { + taihe::set_business_error(ret, "SubscribeSensor fail"); + return; + } + UpdateCallbackInfos(sensorTypeId, cb, opq); +} + +void OnWearDetection(callback_view f, uintptr_t opq, + optional_view options) +{ + OnCommon(SENSOR_TYPE_ID_WEAR_DETECTION, f, opq, options); +} + +void UpdateOnceCallback(int32_t sensorTypeId, callbackType cb, uintptr_t opq) +{ + std::lock_guard onceCallbackLock(g_onceMutex); + ani_object callbackObj = reinterpret_cast(opq); + ani_ref callbackRef; + ani_env *env = taihe::get_env(); + if (env == nullptr || env->GlobalReference_Create(callbackObj, &callbackRef) != ANI_OK) { + SEN_HILOGE("Failed to create callbackRef, sensorTypeId:%{public}d", sensorTypeId); + return; + } + std::vector> callbackInfos = g_onceCallbackInfos[sensorTypeId]; + bool isSubscribedCallback = + std::any_of(callbackInfos.begin(), callbackInfos.end(), [env, callbackRef](const CallbackObject *obj) { + ani_boolean isEqual = false; + return (env->Reference_StrictEquals(callbackRef, obj->ref, &isEqual) == ANI_OK) && isEqual; + }); + if (isSubscribedCallback) { + env->GlobalReference_Delete(callbackRef); + SEN_HILOGE("Callback is already subscribed, sensorTypeId:%{public}d", sensorTypeId); + return; + } + sptr taiheCallbackInfo = new (std::nothrow) CallbackObject(cb, callbackRef); + if (taiheCallbackInfo == nullptr) { + SEN_HILOGE("taiheCallbackInfo is nullptr"); + return; + } + callbackInfos.push_back(taiheCallbackInfo); + g_onceCallbackInfos[sensorTypeId] = callbackInfos; +} + +void OnceCommon(int32_t sensorTypeId, callbackType cb, uintptr_t opq) +{ + if (!CheckSubscribe(sensorTypeId)) { + SEN_HILOGD("No subscription to change sensor data, registration is required"); + int32_t ret = SubscribeSensor(sensorTypeId, REPORTING_INTERVAL, DataCallbackImpl); + if (ret != ERR_OK) { + taihe::set_business_error(ret, "SubscribeSensor fail"); + return; + } + } + UpdateOnceCallback(sensorTypeId, cb, opq); +} + +void OnceWearDetection(callback_view f, uintptr_t opq) +{ + OnceCommon(SENSOR_TYPE_ID_WEAR_DETECTION, f, opq); +} + +int32_t RemoveAllCallback(int32_t sensorTypeId) +{ + std::lock_guard onCallbackLock(g_onMutex); + std::vector> callbackInfos = g_onCallbackInfos[sensorTypeId]; + for (auto iter = callbackInfos.begin(); iter != callbackInfos.end();) { + CHKPC(*iter); + if (auto *env = taihe::get_env()) { + env->GlobalReference_Delete((*iter)->ref); + } + iter = callbackInfos.erase(iter); + } + if (callbackInfos.empty()) { + SEN_HILOGD("No subscription to change sensor data"); + g_onCallbackInfos.erase(sensorTypeId); + return 0; + } + g_onCallbackInfos[sensorTypeId] = callbackInfos; + return static_cast(callbackInfos.size()); +} + +int32_t RemoveCallback(int32_t sensorTypeId, uintptr_t opq) +{ + std::lock_guard onCallbackLock(g_onMutex); + ani_object callbackObj = reinterpret_cast(opq); + ani_ref callbackRef; + ani_env *env = taihe::get_env(); + if (env == nullptr || env->GlobalReference_Create(callbackObj, &callbackRef) != ANI_OK) { + SEN_HILOGE("Failed to create callbackRef, sensorTypeId:%{public}d", sensorTypeId); + return 0; + } + std::vector> callbackInfos = g_onCallbackInfos[sensorTypeId]; + for (auto iter = callbackInfos.begin(); iter != callbackInfos.end();) { + CHKPC(*iter); + ani_boolean isEqual = false; + if ((env->Reference_StrictEquals(callbackRef, (*iter)->ref, &isEqual) == ANI_OK) && isEqual) { + env->GlobalReference_Delete((*iter)->ref); + iter = callbackInfos.erase(iter); + SEN_HILOGD("Remove callback success"); + break; + } else { + ++iter; + } + } + env->GlobalReference_Delete(callbackRef); + if (callbackInfos.empty()) { + SEN_HILOGD("No subscription to change sensor data"); + g_onCallbackInfos.erase(sensorTypeId); + return 0; + } + g_onCallbackInfos[sensorTypeId] = callbackInfos; + return static_cast(callbackInfos.size()); +} + +void OffCommon(int32_t sensorTypeId, optional_view opq) +{ + int32_t subscribeSize = -1; + if (!opq.has_value()) { + subscribeSize = RemoveAllCallback(sensorTypeId); + } else { + subscribeSize = RemoveCallback(sensorTypeId, opq.value()); + } + if (CheckSystemSubscribe(sensorTypeId) || (subscribeSize > 0)) { + SEN_HILOGW("There are other client subscribe system js api as well, not need unsubscribe"); + return; + } + int32_t ret = UnsubscribeSensor(sensorTypeId); + if (ret != ERR_OK) { + SEN_HILOGE("UnsubscribeSensor fail, ret:%{public}d", ret); + taihe::set_business_error(ret, "UnsubscribeSensor fail"); + return; + } +} + +void OffWearDetection(optional_view opq) +{ + OffCommon(SENSOR_TYPE_ID_WEAR_DETECTION, opq); +} + +void OnSignificantMotion(callback_view f, uintptr_t opq, + optional_view options) +{ + OnCommon(SENSOR_TYPE_ID_SIGNIFICANT_MOTION, f, opq, options); +} + +void OnceSignificantMotion(callback_view f, uintptr_t opq) +{ + OnceCommon(SENSOR_TYPE_ID_SIGNIFICANT_MOTION, f, opq); +} + +void OffSignificantMotion(optional_view opq) +{ + OffCommon(SENSOR_TYPE_ID_SIGNIFICANT_MOTION, opq); +} + +void OnRotationVector(callback_view f, uintptr_t opq, + optional_view options) +{ + OnCommon(SENSOR_TYPE_ID_ROTATION_VECTOR, f, opq, options); +} + +void OnceRotationVector(callback_view f, uintptr_t opq) +{ + OnceCommon(SENSOR_TYPE_ID_ROTATION_VECTOR, f, opq); +} + +void OffRotationVector(optional_view opq) +{ + OffCommon(SENSOR_TYPE_ID_ROTATION_VECTOR, opq); +} + +void OnProximity(callback_view f, uintptr_t opq, optional_view options) +{ + OnCommon(SENSOR_TYPE_ID_PROXIMITY, f, opq, options); +} + +void OnceProximity(callback_view f, uintptr_t opq) +{ + OnceCommon(SENSOR_TYPE_ID_PROXIMITY, f, opq); +} + +void OffProximity(optional_view opq) +{ + OffCommon(SENSOR_TYPE_ID_PROXIMITY, opq); +} + +void OnPedometerDetection(callback_view f, uintptr_t opq, + optional_view options) +{ + OnCommon(SENSOR_TYPE_ID_PEDOMETER_DETECTION, f, opq, options); +} + +void OncePedometerDetection(callback_view f, uintptr_t opq) +{ + OnceCommon(SENSOR_TYPE_ID_PEDOMETER_DETECTION, f, opq); +} + +void OffPedometerDetection(optional_view opq) +{ + OffCommon(SENSOR_TYPE_ID_PEDOMETER_DETECTION, opq); +} + +void OnPedometer(callback_view f, uintptr_t opq, optional_view options) +{ + OnCommon(SENSOR_TYPE_ID_PEDOMETER, f, opq, options); +} + +void OncePedometer(callback_view f, uintptr_t opq) +{ + OnceCommon(SENSOR_TYPE_ID_PEDOMETER, f, opq); +} + +void OffPedometer(optional_view opq) +{ + OffCommon(SENSOR_TYPE_ID_PEDOMETER, opq); +} + +void OnOrientation(callback_view f, uintptr_t opq, optional_view options) +{ + OnCommon(SENSOR_TYPE_ID_ORIENTATION, f, opq, options); +} + +void OnceOrientation(callback_view f, uintptr_t opq) +{ + OnceCommon(SENSOR_TYPE_ID_ORIENTATION, f, opq); +} + +void OffOrientation(optional_view opq) +{ + OffCommon(SENSOR_TYPE_ID_ORIENTATION, opq); +} + +void OnMagneticFieldUncalibrated(callback_view f, uintptr_t opq, + optional_view options) +{ + OnCommon(SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, f, opq, options); +} + +void OnceMagneticFieldUncalibrated(callback_view f, uintptr_t opq) +{ + OnceCommon(SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, f, opq); +} + +void OffMagneticFieldUncalibrated(optional_view opq) +{ + OffCommon(SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, opq); +} + +void OnMagneticField(callback_view f, uintptr_t opq, + optional_view options) +{ + OnCommon(SENSOR_TYPE_ID_MAGNETIC_FIELD, f, opq, options); +} + +void OnceMagneticField(callback_view f, uintptr_t opq) +{ + OnceCommon(SENSOR_TYPE_ID_MAGNETIC_FIELD, f, opq); +} + +void OffMagneticField(optional_view opq) +{ + OffCommon(SENSOR_TYPE_ID_MAGNETIC_FIELD, opq); +} + +void OnLinearAccelerometer(callback_view f, uintptr_t opq, + optional_view options) +{ + OnCommon(SENSOR_TYPE_ID_LINEAR_ACCELERATION, f, opq, options); +} + +void OnceLinearAccelerometer(callback_view f, uintptr_t opq) +{ + OnceCommon(SENSOR_TYPE_ID_LINEAR_ACCELERATION, f, opq); +} + +void OffLinearAccelerometer(optional_view opq) +{ + OffCommon(SENSOR_TYPE_ID_LINEAR_ACCELERATION, opq); +} + +void OnHumidity(callback_view f, uintptr_t opq, optional_view options) +{ + OnCommon(SENSOR_TYPE_ID_HUMIDITY, f, opq, options); +} + +void OnceHumidity(callback_view f, uintptr_t opq) +{ + OnceCommon(SENSOR_TYPE_ID_HUMIDITY, f, opq); +} + +void OffHumidity(optional_view opq) +{ + OffCommon(SENSOR_TYPE_ID_HUMIDITY, opq); +} + +void OnHeartRate(callback_view f, uintptr_t opq, optional_view options) +{ + OnCommon(SENSOR_TYPE_ID_HEART_RATE, f, opq, options); +} + +void OnceHeartRate(callback_view f, uintptr_t opq) +{ + OnceCommon(SENSOR_TYPE_ID_HEART_RATE, f, opq); +} + +void OffHeartRate(optional_view opq) +{ + OffCommon(SENSOR_TYPE_ID_HEART_RATE, opq); +} + +void OnHall(callback_view f, uintptr_t opq, optional_view options) +{ + OnCommon(SENSOR_TYPE_ID_HALL, f, opq, options); +} + +void OnceHall(callback_view f, uintptr_t opq) +{ + OnceCommon(SENSOR_TYPE_ID_HALL, f, opq); +} + +void OffHall(optional_view opq) +{ + OffCommon(SENSOR_TYPE_ID_HALL, opq); +} + +void OnGyroscopeUncalibrated(callback_view f, uintptr_t opq, + optional_view options) +{ + OnCommon(SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, f, opq, options); +} + +void OnceGyroscopeUncalibrated(callback_view f, uintptr_t opq) +{ + OnceCommon(SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, f, opq); +} + +void OffGyroscopeUncalibrated(optional_view opq) +{ + OffCommon(SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, opq); +} + +void OnGyroscope(callback_view f, uintptr_t opq, optional_view options) +{ + OnCommon(SENSOR_TYPE_ID_GYROSCOPE, f, opq, options); +} + +void OnceGyroscope(callback_view f, uintptr_t opq) +{ + OnceCommon(SENSOR_TYPE_ID_GYROSCOPE, f, opq); +} + +void OffGyroscope(optional_view opq) +{ + OffCommon(SENSOR_TYPE_ID_GYROSCOPE, opq); +} + +void OnGravity(callback_view f, uintptr_t opq, optional_view options) +{ + OnCommon(SENSOR_TYPE_ID_GRAVITY, f, opq, options); +} + +void OnceGravity(callback_view f, uintptr_t opq) +{ + OnceCommon(SENSOR_TYPE_ID_GRAVITY, f, opq); +} + +void OffGravity(optional_view opq) +{ + OffCommon(SENSOR_TYPE_ID_GRAVITY, opq); +} + +void OnBarometer(callback_view f, uintptr_t opq, optional_view options) +{ + OnCommon(SENSOR_TYPE_ID_BAROMETER, f, opq, options); +} + +void OnceBarometer(callback_view f, uintptr_t opq) +{ + OnceCommon(SENSOR_TYPE_ID_BAROMETER, f, opq); +} + +void OffBarometer(optional_view opq) +{ + OffCommon(SENSOR_TYPE_ID_BAROMETER, opq); +} + +void OnAmbientTemperature(callback_view f, uintptr_t opq, + optional_view options) +{ + OnCommon(SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, f, opq, options); +} + +void OnceAmbientTemperature(callback_view f, uintptr_t opq) +{ + OnceCommon(SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, f, opq); +} + +void OffAmbientTemperature(optional_view opq) +{ + OffCommon(SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, opq); +} + +void OnAmbientLight(callback_view f, uintptr_t opq, optional_view options) +{ + OnCommon(SENSOR_TYPE_ID_AMBIENT_LIGHT, f, opq, options); +} + +void OnceAmbientLight(callback_view f, uintptr_t opq) +{ + OnceCommon(SENSOR_TYPE_ID_AMBIENT_LIGHT, f, opq); +} + +void OffAmbientLight(optional_view opq) +{ + OffCommon(SENSOR_TYPE_ID_AMBIENT_LIGHT, opq); +} + +void OnAccelerometerUncalibrated(callback_view f, uintptr_t opq, + optional_view options) +{ + OnCommon(SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, f, opq, options); +} + +void OnceAccelerometerUncalibrated(callback_view f, uintptr_t opq) +{ + OnceCommon(SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, f, opq); +} + +void OffAccelerometerUncalibrated(optional_view opq) +{ + OffCommon(SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, opq); +} + +void OnAccelerometer(callback_view f, uintptr_t opq, + optional_view options) +{ + OnCommon(SENSOR_TYPE_ID_ACCELEROMETER, f, opq, options); +} + +void OnceAccelerometer(callback_view f, uintptr_t opq) +{ + OnceCommon(SENSOR_TYPE_ID_ACCELEROMETER, f, opq); +} + +void OffAccelerometer(optional_view opq) +{ + OffCommon(SENSOR_TYPE_ID_ACCELEROMETER, opq); +} + +void OnSar(callback_view f, uintptr_t opq, optional_view options) +{ + OnCommon(SENSOR_TYPE_ID_SAR, f, opq, options); +} + +void OffSar(optional_view opq) +{ + OffCommon(SENSOR_TYPE_ID_SAR, opq); +} + +void OnColor(callback_view f, uintptr_t opq, optional_view options) +{ + OnCommon(SENSOR_TYPE_ID_COLOR, f, opq, options); +} + +void OffColor(optional_view opq) +{ + OffCommon(SENSOR_TYPE_ID_COLOR, opq); +} +} // namespace + +// Since there macros are auto-generate, lint will cause false positive. +// NOLINTBEGIN +TH_EXPORT_CPP_API_getRotationMatrixSyncGrav(getRotationMatrixSyncGrav); +TH_EXPORT_CPP_API_getOrientationSync(getOrientationSync); +TH_EXPORT_CPP_API_getRotationMatrixSync(getRotationMatrixSync); +TH_EXPORT_CPP_API_getSensorListSync(getSensorListSync); +TH_EXPORT_CPP_API_OnWearDetection(OnWearDetection); +TH_EXPORT_CPP_API_OnceWearDetection(OnceWearDetection); +TH_EXPORT_CPP_API_OffWearDetection(OffWearDetection); +TH_EXPORT_CPP_API_OnSignificantMotion(OnSignificantMotion); +TH_EXPORT_CPP_API_OnceSignificantMotion(OnceSignificantMotion); +TH_EXPORT_CPP_API_OffSignificantMotion(OffSignificantMotion); +TH_EXPORT_CPP_API_OnRotationVector(OnRotationVector); +TH_EXPORT_CPP_API_OnceRotationVector(OnceRotationVector); +TH_EXPORT_CPP_API_OffRotationVector(OffRotationVector); +TH_EXPORT_CPP_API_OnProximity(OnProximity); +TH_EXPORT_CPP_API_OnceProximity(OnceProximity); +TH_EXPORT_CPP_API_OffProximity(OffProximity); +TH_EXPORT_CPP_API_OnPedometerDetection(OnPedometerDetection); +TH_EXPORT_CPP_API_OncePedometerDetection(OncePedometerDetection); +TH_EXPORT_CPP_API_OffPedometerDetection(OffPedometerDetection); +TH_EXPORT_CPP_API_OnPedometer(OnPedometer); +TH_EXPORT_CPP_API_OncePedometer(OncePedometer); +TH_EXPORT_CPP_API_OffPedometer(OffPedometer); +TH_EXPORT_CPP_API_OnOrientation(OnOrientation); +TH_EXPORT_CPP_API_OnceOrientation(OnceOrientation); +TH_EXPORT_CPP_API_OffOrientation(OffOrientation); +TH_EXPORT_CPP_API_OnMagneticFieldUncalibrated(OnMagneticFieldUncalibrated); +TH_EXPORT_CPP_API_OnceMagneticFieldUncalibrated(OnceMagneticFieldUncalibrated); +TH_EXPORT_CPP_API_OffMagneticFieldUncalibrated(OffMagneticFieldUncalibrated); +TH_EXPORT_CPP_API_OnMagneticField(OnMagneticField); +TH_EXPORT_CPP_API_OnceMagneticField(OnceMagneticField); +TH_EXPORT_CPP_API_OffMagneticField(OffMagneticField); +TH_EXPORT_CPP_API_OnLinearAccelerometer(OnLinearAccelerometer); +TH_EXPORT_CPP_API_OnceLinearAccelerometer(OnceLinearAccelerometer); +TH_EXPORT_CPP_API_OffLinearAccelerometer(OffLinearAccelerometer); +TH_EXPORT_CPP_API_OnHumidity(OnHumidity); +TH_EXPORT_CPP_API_OnceHumidity(OnceHumidity); +TH_EXPORT_CPP_API_OffHumidity(OffHumidity); +TH_EXPORT_CPP_API_OnHeartRate(OnHeartRate); +TH_EXPORT_CPP_API_OnceHeartRate(OnceHeartRate); +TH_EXPORT_CPP_API_OffHeartRate(OffHeartRate); +TH_EXPORT_CPP_API_OnHall(OnHall); +TH_EXPORT_CPP_API_OnceHall(OnceHall); +TH_EXPORT_CPP_API_OffHall(OffHall); +TH_EXPORT_CPP_API_OnGyroscopeUncalibrated(OnGyroscopeUncalibrated); +TH_EXPORT_CPP_API_OnceGyroscopeUncalibrated(OnceGyroscopeUncalibrated); +TH_EXPORT_CPP_API_OffGyroscopeUncalibrated(OffGyroscopeUncalibrated); +TH_EXPORT_CPP_API_OnGyroscope(OnGyroscope); +TH_EXPORT_CPP_API_OnceGyroscope(OnceGyroscope); +TH_EXPORT_CPP_API_OffGyroscope(OffGyroscope); +TH_EXPORT_CPP_API_OnGravity(OnGravity); +TH_EXPORT_CPP_API_OnceGravity(OnceGravity); +TH_EXPORT_CPP_API_OffGravity(OffGravity); +TH_EXPORT_CPP_API_OnBarometer(OnBarometer); +TH_EXPORT_CPP_API_OnceBarometer(OnceBarometer); +TH_EXPORT_CPP_API_OffBarometer(OffBarometer); +TH_EXPORT_CPP_API_OnAmbientTemperature(OnAmbientTemperature); +TH_EXPORT_CPP_API_OnceAmbientTemperature(OnceAmbientTemperature); +TH_EXPORT_CPP_API_OffAmbientTemperature(OffAmbientTemperature); +TH_EXPORT_CPP_API_OnAmbientLight(OnAmbientLight); +TH_EXPORT_CPP_API_OnceAmbientLight(OnceAmbientLight); +TH_EXPORT_CPP_API_OffAmbientLight(OffAmbientLight); +TH_EXPORT_CPP_API_OnAccelerometerUncalibrated(OnAccelerometerUncalibrated); +TH_EXPORT_CPP_API_OnceAccelerometerUncalibrated(OnceAccelerometerUncalibrated); +TH_EXPORT_CPP_API_OffAccelerometerUncalibrated(OffAccelerometerUncalibrated); +TH_EXPORT_CPP_API_OnAccelerometer(OnAccelerometer); +TH_EXPORT_CPP_API_OnceAccelerometer(OnceAccelerometer); +TH_EXPORT_CPP_API_OffAccelerometer(OffAccelerometer); +TH_EXPORT_CPP_API_OnSar(OnSar); +TH_EXPORT_CPP_API_OffSar(OffSar); +TH_EXPORT_CPP_API_OnColor(OnColor); +TH_EXPORT_CPP_API_OffColor(OffColor); +// NOLINTEND \ No newline at end of file diff --git a/frameworks/ets/taihe/idl/ohos.sensor.taihe b/frameworks/ets/taihe/idl/ohos.sensor.taihe new file mode 100644 index 0000000000000000000000000000000000000000..7681850a1484b0917503d61c1a55c796ff572066 --- /dev/null +++ b/frameworks/ets/taihe/idl/ohos.sensor.taihe @@ -0,0 +1,1565 @@ +/* + * Copyright (c) 2025 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. + */ + +@!namespace("@ohos.sensor", "sensor") + +@!sts_inject(""" + static { loadLibrary("sensor_taihe_native.z") } +""") + +/** + * Enum for obtain the type of sensor. + * @enum { i32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 9 + */ +/** + * Enum for obtain the type of sensor. + * @enum { i32 } + * @syscap SystemCapability.Sensors.Sensor + * @atomicservice + * @since 11 + */ +enum SensorId: i32 { + /** + * Acceleration sensor. + * @syscap SystemCapability.Sensors.Sensor + * @since 9 + */ + /** + * Acceleration sensor. + * @syscap SystemCapability.Sensors.Sensor + * @atomicservice + * @since 11 + */ + ACCELEROMETER = 1, + + /** + * Gyroscope sensor. + * @syscap SystemCapability.Sensors.Sensor + * @since 9 + */ + /** + * Gyroscope sensor. + * @syscap SystemCapability.Sensors.Sensor + * @atomicservice + * @since 11 + */ + GYROSCOPE = 2, + + /** + * Ambient light sensor. + * @syscap SystemCapability.Sensors.Sensor + * @since 9 + */ + AMBIENT_LIGHT = 5, + + /** + * Magnetic field sensor. + * @syscap SystemCapability.Sensors.Sensor + * @since 9 + */ + MAGNETIC_FIELD = 6, + + /** + * Barometric pressure sensor. + * @syscap SystemCapability.Sensors.Sensor + * @since 9 + */ + BAROMETER = 8, + + /** + * Hall effect sensor. + * @syscap SystemCapability.Sensors.Sensor + * @since 9 + */ + HALL = 10, + + /** + * Proximity sensor. + * @syscap SystemCapability.Sensors.Sensor + * @since 9 + */ + PROXIMITY = 12, + + /** + * Humidity sensor. + * @syscap SystemCapability.Sensors.Sensor + * @since 9 + */ + HUMIDITY = 13, + + /** + * Color sensor. + * @syscap SystemCapability.Sensors.Sensor + * @systemapi + * @since 10 + */ + COLOR = 14, + + /** + * Sar sensor. + * @syscap SystemCapability.Sensors.Sensor + * @systemapi + * @since 10 + */ + SAR = 15, + + /** + * Orientation sensor. + * @syscap SystemCapability.Sensors.Sensor + * @since 9 + */ + /** + * Orientation sensor. + * @syscap SystemCapability.Sensors.Sensor + * @atomicservice + * @since 11 + */ + ORIENTATION = 256, + + /** + * Gravity sensor. + * @syscap SystemCapability.Sensors.Sensor + * @since 9 + */ + GRAVITY = 257, + + /** + * Linear acceleration sensor. + * @syscap SystemCapability.Sensors.Sensor + * @since 9 + */ + LINEAR_ACCELEROMETER = 258, + + /** + * Rotation vector sensor. + * @syscap SystemCapability.Sensors.Sensor + * @since 9 + */ + ROTATION_VECTOR = 259, + + /** + * Ambient temperature sensor. + * @syscap SystemCapability.Sensors.Sensor + * @since 9 + */ + AMBIENT_TEMPERATURE = 260, + + /** + * Uncalibrated magnetic field sensor. + * @syscap SystemCapability.Sensors.Sensor + * @since 9 + */ + MAGNETIC_FIELD_UNCALIBRATED = 261, + + /** + * Uncalibrated gyroscope sensor. + * @syscap SystemCapability.Sensors.Sensor + * @since 9 + */ + GYROSCOPE_UNCALIBRATED = 263, + + /** + * Significant motion sensor. + * @syscap SystemCapability.Sensors.Sensor + * @since 9 + */ + SIGNIFICANT_MOTION = 264, + + /** + * Pedometer detection sensor. + * @syscap SystemCapability.Sensors.Sensor + * @since 9 + */ + PEDOMETER_DETECTION = 265, + + /** + * Pedometer sensor. + * @syscap SystemCapability.Sensors.Sensor + * @since 9 + */ + PEDOMETER = 266, + + /** + * Heart rate sensor. + * @syscap SystemCapability.Sensors.Sensor + * @since 9 + */ + HEART_RATE = 278, + + /** + * Wear detection sensor. + * @syscap SystemCapability.Sensors.Sensor + * @since 9 + */ + WEAR_DETECTION = 280, + + /** + * Uncalibrated acceleration sensor. + * @syscap SystemCapability.Sensors.Sensor + * @since 9 + */ + ACCELEROMETER_UNCALIBRATED = 281 +} + +/** + * Enumerates the accuracy levels of data reported by a sensor. + * @enum { i32 } + * @syscap SystemCapability.Sensors.Sensor + * @atomicservice + * @since 11 + */ +enum SensorAccuracy: i32 { + /** + * The sensor data is unreliable. It is possible that the sensor does not contact with the device to measure. + * @syscap SystemCapability.Sensors.Sensor + * @atomicservice + * @since 11 + */ + ACCURACY_UNRELIABLE = 0, + + /** + * The sensor data is at a low accuracy level. The data must be calibrated based on the environment before being used. + * @syscap SystemCapability.Sensors.Sensor + * @atomicservice + * @since 11 + */ + ACCURACY_LOW = 1, + + /** + * The sensor data is at a medium accuracy level. You are advised to calibrate the data based on the environment before using it. + * @syscap SystemCapability.Sensors.Sensor + * @atomicservice + * @since 11 + */ + ACCURACY_MEDIUM = 2, + + /** + * The sensor data is at a high accuracy level. The data can be used directly. + * @syscap SystemCapability.Sensors.Sensor + * @atomicservice + * @since 11 + */ + ACCURACY_HIGH = 3 +} + +/** + * The basic data structure of the sensor event. + * @typedef Response + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ +/** + * The basic data structure of the sensor event. + * @typedef Response + * @syscap SystemCapability.Sensors.Sensor + * @atomicservice + * @since 11 + */ +struct Response { + /** + * The timestamp of the reported sensor data. + * @type { i64 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + /** + * The timestamp of the reported sensor data. + * @type { i64 } + * @syscap SystemCapability.Sensors.Sensor + * @atomicservice + * @since 11 + */ + timestamp: i64; + + /** + * The accuracy levels of data reported by a sensor. + * @type { SensorAccuracy } + * @syscap SystemCapability.Sensors.Sensor + * @atomicservice + * @since 11 + */ + accuracy: SensorAccuracy; +} + +/** + * Acceleration sensor event data. + * @typedef AccelerometerResponse + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ +/** + * Acceleration sensor event data. + * @typedef AccelerometerResponse + * @syscap SystemCapability.Sensors.Sensor + * @atomicservice + * @since 11 + */ +struct AccelerometerResponse { + + @extends base: Response; + + /** + * Acceleration x-axis component. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + /** + * Acceleration x-axis component. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @atomicservice + * @since 11 + */ + x: f32; + + /** + * Acceleration y-axis component. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + /** + * Acceleration y-axis component. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @atomicservice + * @since 11 + */ + y: f32; + + /** + * Acceleration z-axis component + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + /** + * Acceleration z-axis component + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @atomicservice + * @since 11 + */ + z: f32; +} + +/** + * Linear acceleration sensor event data. + * @typedef LinearAccelerometerResponse + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ +struct LinearAccelerometerResponse { + + @extends base: Response; + + /** + * Linear acceleration x-axis component. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + x: f32; + + /** + * Linear acceleration y-axis component. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + y: f32; + + /** + * Linear acceleration z-axis component. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + z: f32; +} + +/** + * Acceleration uncalibrated sensor event data. + * @typedef AccelerometerUncalibratedResponse + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ +struct AccelerometerUncalibratedResponse { + + @extends base: Response; + + /** + * Acceleration uncalibrated x-axis component. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + x: f32; + + /** + * Acceleration uncalibrated y-axis component. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + y: f32; + + /** + * Acceleration uncalibrated z-axis component. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + z: f32; + + /** + * Acceleration uncalibrated x-axis offset. + * + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + biasX: f32; + + /** + * Acceleration uncalibrated y-axis offset. + * + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + biasY: f32; + + /** + * Acceleration uncalibrated z-axis offset. + * + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + biasZ: f32; +} + +/** + * Gravity sensor event data. + * @typedef GravityResponse + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ +struct GravityResponse { + + @extends base: Response; + + /** + * Gravity x-axis component. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + x: f32; + + /** + * Gravity y-axis component. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + y: f32; + + /** + * Gravity z-axis component. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + z: f32; +} + +/** + * Orientation sensor event data. + * @typedef OrientationResponse + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ +/** + * Orientation sensor event data. + * @typedef OrientationResponse + * @syscap SystemCapability.Sensors.Sensor + * @atomicservice + * @since 11 + */ +struct OrientationResponse { + + @extends base: Response; + + /** + * The device rotates at an angle around the Z axis. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + /** + * The device rotates at an angle around the Z axis. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @atomicservice + * @since 11 + */ + alpha: f32; + + /** + * The device rotates at an angle around the X axis. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + /** + * The device rotates at an angle around the X axis. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @atomicservice + * @since 11 + */ + beta: f32; + + /** + * The device rotates at an angle around the Y axis. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + /** + * The device rotates at an angle around the Y axis. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @atomicservice + * @since 11 + */ + gamma: f32; +} + +/** + * Rotation vector sensor event data. + * @typedef RotationVectorResponse + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ +struct RotationVectorResponse { + + @extends base: Response; + + /** + * Rotation vector x-axis component. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + x: f32; + + /** + * Rotation vector y-axis component. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + y: f32; + + /** + * Rotation vector z-axis component. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + z: f32; + + /** + * Scalar quantity. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + w: f32; +} + +/** + * Gyroscope sensor event data. + * @typedef GyroscopeResponse + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ +/** + * Gyroscope sensor event data. + * @typedef GyroscopeResponse + * @syscap SystemCapability.Sensors.Sensor + * @atomicservice + * @since 11 + */ +struct GyroscopeResponse { + + @extends base: Response; + + /** + * Gyroscope x-axis component. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + /** + * Gyroscope x-axis component. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @atomicservice + * @since 11 + */ + x: f32; + + /** + * Gyroscope y-axis component. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + /** + * Gyroscope y-axis component. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @atomicservice + * @since 11 + */ + y: f32; + + /** + * Gyroscope z-axis component. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + /** + * Gyroscope z-axis component. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @atomicservice + * @since 11 + */ + z: f32; +} + +/** + * Gyroscope uncalibrated sensor event data. + * @typedef GyroscopeUncalibratedResponse + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ +struct GyroscopeUncalibratedResponse { + + @extends base: Response; + + /** + * Gyroscope uncalibrated x-axis component. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + x: f32; + + /** + * Gyroscope uncalibrated y-axis component. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + y: f32; + + /** + * Gyroscope uncalibrated z-axis component. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + z: f32; + + /** + * Gyroscope uncalibrated x-axis offset. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + biasX: f32; + + /** + * Gyroscope uncalibrated y-axis offset. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + biasY: f32; + + /** + * Gyroscope uncalibrated z-axis offset. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + biasZ: f32; +} + +/** + * Significant motion sensor event data. + * @typedef SignificantMotionResponse + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ +struct SignificantMotionResponse { + + @extends base: Response; + + /** + * The degree of significant motion. + * Whether the device has a significant motion. + * The value 1 means that the device has a significant motion, and 0 means the opposite. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + scalar: f32; +} + +/** + * Proximity sensor event data. + * @typedef ProximityResponse + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ +struct ProximityResponse { + + @extends base: Response; + + /** + * Indicates the degree of proximity, event 0 indicates proximity, and greater than 0 indicates distance. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + distance: f32; +} + +/** + * Light sensor event data. + * @typedef LightResponse + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ +struct LightResponse { + + @extends base: Response; + + /** + * Indicates light intensity, in lux. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + intensity: f32; + + /** + * Indicates color temperature, in kelvin. + * @type { ?f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 12 + */ + colorTemperature: Optional; + + /** + * Indicates infrared luminance, in cd/m2. + * @type { ?f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 12 + */ + infraredLuminance: Optional; +} + +/** + * Hall sensor event data. + * @typedef HallResponse + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ +struct HallResponse { + + @extends base: Response; + + /** + * Indicates hall status, 0 indicates open, and greater than 0 indicates suction. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + status: f32; +} + +/** + * Magnetic field sensor event data. + * @typedef MagneticFieldResponse + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ +struct MagneticFieldResponse { + + @extends base: Response; + + /** + * Magnetic field x-axis component. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + x: f32; + + /** + * Magnetic field y-axis component. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + y: f32; + + /** + * Magnetic field z-axis component. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + z: f32; +} + +/** + * Magnetic field uncalibrated sensor event data. + * @typedef MagneticFieldUncalibratedResponse + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ +struct MagneticFieldUncalibratedResponse { + + @extends base: Response; + + /** + * Magnetic field uncalibrated x-axis component. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + x: f32; + + /** + * Magnetic field uncalibrated y-axis component. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + y: f32; + + /** + * Magnetic field uncalibrated z-axis component. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + z: f32; + + /** + * Magnetic field uncalibrated x-axis offset. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + biasX: f32; + + /** + * Magnetic field uncalibrated y-axis offset. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + biasY: f32; + + /** + * Magnetic field uncalibrated z-axis offset. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + biasZ: f32; +} + +/** + * Pedometer sensor event data. + * @typedef PedometerResponse + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ +struct PedometerResponse { + + @extends base: Response; + + /** + * Indicates the number of steps. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + steps: f32; +} + +/** + * Pedometer detection sensor event data. + * @typedef PedometerDetectionResponse + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ +struct PedometerDetectionResponse { + + @extends base: Response; + + /** + * Indicates the pedometer detection status, 1 indicates that a walking action has occurred, + * and 0 indicates that no movement has occurred. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + scalar: f32; +} + +/** + * Heart rate sensor event data. + * @typedef HeartRateResponse + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ +struct HeartRateResponse { + + @extends base: Response; + + /** + * Indicates the number of heart rate. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + heartRate: f32; +} + +/** + * Barometer sensor event data. + * @typedef BarometerResponse + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ +struct BarometerResponse { + + @extends base: Response; + + /** + * Indicates the number of barometer, in hpa. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + pressure: f32; +} + +/** + * Wear detection sensor event data. + * @typedef WearDetectionResponse + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ +struct WearDetectionResponse { + + @extends base: Response; + + /** + * Indicates the status of wear detection, 1 for wearing, 0 for wearing not. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + value: f32; +} + +/** + * Humidity sensor event data. + * @typedef HumidityResponse + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ +struct HumidityResponse { + + @extends base: Response; + + /** + * Indicates the number of humidity. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + humidity: f32; +} + +/** + * Ambient temperature sensor event data. + * @typedef AmbientTemperatureResponse + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ +struct AmbientTemperatureResponse { + + @extends base: Response; + + /** + * Indicates ambient temperature, in celsius. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + temperature: f32; +} + +/** + * Sar sensor event data. + * @typedef SarResponse + * @syscap SystemCapability.Sensors.Sensor + * @systemapi + * @since 10 + */ +struct SarResponse { + + @extends base: Response; + + /** + * Indicates the specific absorption rate, in W/kg. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @systemapi + * @since 10 + */ + absorptionRatio: f32; +} + +/** + * Color sensor event data. + * @typedef ColorResponse + * @syscap SystemCapability.Sensors.Sensor + * @systemapi + * @since 10 + */ +struct ColorResponse { + + @extends base: Response; + + /** + * Indicates the intensity of light, in lux. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @systemapi + * @since 10 + */ + lightIntensity: f32; + /** + * Indicates the color temperature, in kelvin. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @systemapi + * @since 10 + */ + colorTemperature: f32; +} + +/** + * Indicates the response of rotation matrix. + * @typedef RotationMatrixResponse + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ +struct RotationMatrixResponse { + /** + * rotation matrix. + * @type { Array } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + rotation: Array; + + /** + * inclination matrix. + * @type { Array } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + inclination: Array; +} + +/** + * Indicates the axis of the new coordinate system that coincides with the XY axis of the original coordinate system. + * @typedef CoordinatesOptions + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ +struct CoordinatesOptions { + /** Indicates the axis of the new coordinate system that coincides with the X axis of the original coordinate system. + * @type { i32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + x: i32; + + /** Indicates the axis of the new coordinate system that coincides with the Y axis of the original coordinate system. + * @type { i32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + y: i32; +} + +/** + * Indicates geomagnetic field data. + * @typedef GeomagneticResponse + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ +struct GeomagneticResponse { + /** + * Geomagnetic x-axis component. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + x: f32; + + /** + * Geomagnetic y-axis component. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + y: f32; + + /** + * Geomagnetic z-axis component. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + z: f32; + + /** + * The Angle between the earth's magnetic field lines and the horizontal plane. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + geomagneticDip: f32; + + /** + * The Angle of magnetic north and true north on a horizontal plane. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + deflectionAngle: f32; + + /** + * The horizontal strength of the geomagnetic field. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + levelIntensity: f32; + + /** + * The total strength of the geomagnetic field. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + totalIntensity: f32; +} + +/** + * Indicates sensor information. + * @typedef Sensor + * @syscap SystemCapability.Sensors.Sensor + * @since 9 + */ +struct Sensor { + /** + * Sensor name. + * @type { String } + * @syscap SystemCapability.Sensors.Sensor + * @since 9 + */ + sensorName: String; + + /** + * Sensor vendor. + * @type { String } + * @syscap SystemCapability.Sensors.Sensor + * @since 9 + */ + vendorName: String; + + /** + * Sensor firmware version. + * @type { String } + * @syscap SystemCapability.Sensors.Sensor + * @since 9 + */ + firmwareVersion: String; + + /** + * Sensor hardware version. + * @type { String } + * @syscap SystemCapability.Sensors.Sensor + * @since 9 + */ + hardwareVersion: String; + + /** + * Sensor type ID, {@code SensorType}. + * @type { i32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 9 + */ + sensorId: i32; + + /** + * Maximum measurement range of the sensor. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 9 + */ + maxRange: f32; + + /** + * Minimum sample period allowed, in ns. + * @type { i64 } + * @syscap SystemCapability.Sensors.Sensor + * @since 9 + */ + minSamplePeriod: i64; + + /** + * Maximum sample period allowed, in ns. + * @type { i64 } + * @syscap SystemCapability.Sensors.Sensor + * @since 9 + */ + maxSamplePeriod: i64; + + /** + * Sensor accuracy. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 9 + */ + precision: f32; + + /** + * Sensor power. + * @type { f32 } + * @syscap SystemCapability.Sensors.Sensor + * @since 9 + */ + power: f32; +} + +/** + * The sensor reporting frequency is divided into three modes. + * @typedef {'game' | 'ui' | 'normal'} + * @syscap SystemCapability.Sensors.Sensor + * @atomicservice + * @since 11 + */ +@!sts_inject(""" + type SensorFrequency = 'game' | 'ui' | 'normal'; +""") + +union MapOption { + interval_i64: i64; + interval_string: String; +} + +/** + * Subscribe to the sensor's optional parameters. + * @typedef Options + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ +/** + * Subscribe to the sensor's optional parameters. + * @typedef Options + * @syscap SystemCapability.Sensors.Sensor + * @atomicservice + * @since 11 + */ +struct Options { + /** + * Sensor event reporting event interval. + * @type { i64 } + * @syscap SystemCapability.Sensors.Sensor + * @since 8 + */ + /** + * Sensor event reporting event interval. + * @type { MapOption } + * @syscap SystemCapability.Sensors.Sensor + * @atomicservice + * @since 11 + */ + interval: MapOption; +} + +/** + * Calculate rotation matrix based on gravity vector and geomagnetic vector. + * @param { Array } gravity - gravity Indicates the gravity vector. + * @param { Array } geomagnetic - geomagnetic Indicates the geomagnetic vector. + * @param { AsyncCallback } callback - callback rotation matrix and inclination matrix. + * @throws { BusinessError } 401 - Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; + *
2. Incorrect parameter types; 3. Parameter verification failed. + * @throws { BusinessError } 14500101 - Service exception. + * @syscap SystemCapability.Sensors.Sensor + * @since 9 + */ +@gen_async("getRotationMatrix") +@gen_promise("getRotationMatrix") +function getRotationMatrixSyncGrav(gravity: Array, geomagnetic: Array): RotationMatrixResponse; + +/** + * Computes the device's orientation based on the rotation matrix. + * @param { Array } rotationMatrix - rotationMatrix Indicates the rotation matrix. + * @param { AsyncCallback> } callback - callback the angle of rotation around the z, x, y axis. + * @throws { BusinessError } 401 - Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; + *
2. Incorrect parameter types; 3. Parameter verification failed. + * @throws { BusinessError } 14500101 - Service exception. + * @syscap SystemCapability.Sensors.Sensor + * @since 9 + */ +@gen_async("getOrientation") +@gen_promise("getOrientation") +function getOrientationSync(rotationMatrix: Array): Array; + +/** + * Convert rotation vector to rotation matrix. + * @param { Array } rotationVector - rotationVector Indicates the rotation vector. + * @param { AsyncCallback> } callback - callback rotation matrix. + * @throws { BusinessError } 401 - Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; + *
2. Incorrect parameter types; 3. Parameter verification failed. + * @throws { BusinessError } 14500101 - Service exception. + * @syscap SystemCapability.Sensors.Sensor + * @since 9 + */ +@gen_async("getRotationMatrix") +@gen_promise("getRotationMatrix") +function getRotationMatrixSync(rotationVector: Array): Array; + +/** + * Obtains all sensor information on the device. + * @param { AsyncCallback> } callback - callback sensor list. + * @throws { BusinessError } 401 - Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; + *
2. Incorrect parameter types; 3. Parameter verification failed. + * @throws { BusinessError } 14500101 - Service exception. + * @syscap SystemCapability.Sensors.Sensor + * @since 9 + */ +@gen_async("getSensorList") +@gen_promise("getSensorList") +function getSensorListSync(): Array; + +@!sts_inject(""" + function on(type: string, callback: (arg0 : Object) => void, options?: Options) { + switch(type) { + case "wearDetectionChange": return onWearDetection(callback as (info: WearDetectionResponse) => void, callback, options); + case "significantMotionChange": return onSignificantMotion(callback as (info: SignificantMotionResponse) => void, callback, options); + case "rotationVectorChange": return onRotationVector(callback as (info: RotationVectorResponse) => void, callback, options); + case "proximityChange": return onProximity(callback as (info: ProximityResponse) => void, callback, options); + case "pedometerDetectionChange": return onPedometerDetection(callback as (info: PedometerDetectionResponse) => void, callback, options); + case "pedometerChange": return onPedometer(callback as (info: PedometerResponse) => void, callback, options); + case "orientationChange": return onOrientation(callback as (info: OrientationResponse) => void, callback, options); + case "magneticFieldUncalibratedChange": return onMagneticFieldUncalibrated(callback as (info: MagneticFieldUncalibratedResponse) => void, callback, options); + case "magneticFieldChange": return onMagneticField(callback as (info: MagneticFieldResponse) => void, callback, options); + case "linearAccelerometerChange": return onLinearAccelerometer(callback as (info: LinearAccelerometerResponse) => void, callback, options); + case "humidityChange": return onHumidity(callback as (info: HumidityResponse) => void, callback, options); + case "heartRateChange": return onHeartRate(callback as (info: HeartRateResponse) => void, callback, options); + case "hallChange": return onHall(callback as (info: HallResponse) => void, callback, options); + case "gyroscopeUncalibratedChange": return onGyroscopeUncalibrated(callback as (info: GyroscopeUncalibratedResponse) => void, callback, options); + case "gyroscopeChange": return onGyroscope(callback as (info: GyroscopeResponse) => void, callback, options); + case "gravityChange": return onGravity(callback as (info: GravityResponse) => void, callback, options); + case "barometerChange": return onBarometer(callback as (info: BarometerResponse) => void, callback, options); + case "ambientTemperatureChange": return onAmbientTemperature(callback as (info: AmbientTemperatureResponse) => void, callback, options); + case "ambientLightChange": return onAmbientLight(callback as (info: LightResponse) => void, callback, options); + case "accelerometerUncalibratedChange": return onAccelerometerUncalibrated(callback as (info: AccelerometerUncalibratedResponse) => void, callback, options); + case "accelerometerChange": return onAccelerometer(callback as (info: AccelerometerResponse) => void, callback, options); + case "sarChange": return onSar(callback as (info: SarResponse) => void, callback, options); + case "colorChange": return onColor(callback as (info: ColorResponse) => void, callback, options); + default: throw new Error(`Unknown type: ${type}`); + } + } + function once(type: string, callback: (arg0 : Object) => void) { + switch(type) { + case "wearDetectionChange": return onceWearDetection(callback as (info: WearDetectionResponse) => void, callback); + case "significantMotionChange": return onceSignificantMotion(callback as (info: SignificantMotionResponse) => void, callback); + case "rotationVectorChange": return onceRotationVector(callback as (info: RotationVectorResponse) => void, callback); + case "proximityChange": return onceProximity(callback as (info: ProximityResponse) => void, callback); + case "pedometerDetectionChange": return oncePedometerDetection(callback as (info: PedometerDetectionResponse) => void, callback); + case "pedometerChange": return oncePedometer(callback as (info: PedometerResponse) => void, callback); + case "orientationChange": return onceOrientation(callback as (info: OrientationResponse) => void, callback); + case "magneticFieldUncalibratedChange": return onceMagneticFieldUncalibrated(callback as (info: MagneticFieldUncalibratedResponse) => void, callback); + case "magneticFieldChange": return onceMagneticField(callback as (info: MagneticFieldResponse) => void, callback); + case "linearAccelerometerChange": return onceLinearAccelerometer(callback as (info: LinearAccelerometerResponse) => void, callback); + case "humidityChange": return onceHumidity(callback as (info: HumidityResponse) => void, callback); + case "heartRateChange": return onceHeartRate(callback as (info: HeartRateResponse) => void, callback); + case "hallChange": return onceHall(callback as (info: HallResponse) => void, callback); + case "gyroscopeUncalibratedChange": return onceGyroscopeUncalibrated(callback as (info: GyroscopeUncalibratedResponse) => void, callback); + case "gyroscopeChange": return onceGyroscope(callback as (info: GyroscopeResponse) => void, callback); + case "gravityChange": return onceGravity(callback as (info: GravityResponse) => void, callback); + case "barometerChange": return onceBarometer(callback as (info: BarometerResponse) => void, callback); + case "ambientTemperatureChange": return onceAmbientTemperature(callback as (info: AmbientTemperatureResponse) => void, callback); + case "ambientLightChange": return onceAmbientLight(callback as (info: LightResponse) => void, callback); + case "accelerometerUncalibratedChange": return onceAccelerometerUncalibrated(callback as (info: AccelerometerUncalibratedResponse) => void, callback); + case "accelerometerChange": return onceAccelerometer(callback as (info: AccelerometerResponse) => void, callback); + default: throw new Error(`Unknown type: ${type}`); + } + } + function off(type: string, callback?: (arg0 : Object) => void) { + switch(type) { + case "wearDetectionChange": return offWearDetection(callback); + case "significantMotionChange": return offSignificantMotion(callback); + case "rotationVectorChange": return offRotationVector(callback); + case "proximityChange": return offProximity(callback); + case "pedometerDetectionChange": return offPedometerDetection(callback); + case "pedometerChange": return offPedometer(callback); + case "orientationChange": return offOrientation(callback); + case "magneticFieldUncalibratedChange": return offMagneticFieldUncalibrated(callback); + case "magneticFieldChange": return offMagneticField(callback); + case "linearAccelerometerChange": return offLinearAccelerometer(callback); + case "humidityChange": return offHumidity(callback); + case "heartRateChange": return offHeartRate(callback); + case "hallChange": return offHall(callback); + case "gyroscopeUncalibratedChange": return offGyroscopeUncalibrated(callback); + case "gyroscopeChange": return offGyroscope(callback); + case "gravityChange": return offGravity(callback); + case "barometerChange": return offBarometer(callback); + case "ambientTemperatureChange": return offAmbientTemperature(callback); + case "ambientLightChange": return offAmbientLight(callback); + case "accelerometerUncalibratedChange": return offAccelerometerUncalibrated(callback); + case "accelerometerChange": return offAccelerometer(callback); + case "sarChange": return offSar(callback); + case "colorChange": return offColor(callback); + default: throw new Error(`Unknown type: ${type}`); + } + } +""") +function OnWearDetection(f: (info: WearDetectionResponse) => void, opq: Opaque, options: Optional); +function OnceWearDetection(f: (info: WearDetectionResponse) => void, opq: Opaque); +function OffWearDetection(opq: Optional); + +function OnSignificantMotion(f: (info: SignificantMotionResponse) => void, opq: Opaque, options: Optional); +function OnceSignificantMotion(f: (info: SignificantMotionResponse) => void, opq: Opaque); +function OffSignificantMotion(opq: Optional); + +function OnRotationVector(f: (info: RotationVectorResponse) => void, opq: Opaque, options: Optional); +function OnceRotationVector(f: (info: RotationVectorResponse) => void, opq: Opaque); +function OffRotationVector(opq: Optional); + +function OnProximity(f: (info: ProximityResponse) => void, opq: Opaque, options: Optional); +function OnceProximity(f: (info: ProximityResponse) => void, opq: Opaque); +function OffProximity(opq: Optional); + +function OnPedometerDetection(f: (info: PedometerDetectionResponse) => void, opq: Opaque, options: Optional); +function OncePedometerDetection(f: (info: PedometerDetectionResponse) => void, opq: Opaque); +function OffPedometerDetection(opq: Optional); + +function OnPedometer(f: (info: PedometerResponse) => void, opq: Opaque, options: Optional); +function OncePedometer(f: (info: PedometerResponse) => void, opq: Opaque); +function OffPedometer(opq: Optional); + +function OnOrientation(f: (info: OrientationResponse) => void, opq: Opaque, options: Optional); +function OnceOrientation(f: (info: OrientationResponse) => void, opq: Opaque); +function OffOrientation(opq: Optional); + +function OnMagneticFieldUncalibrated(f: (info: MagneticFieldUncalibratedResponse) => void, opq: Opaque, options: Optional); +function OnceMagneticFieldUncalibrated(f: (info: MagneticFieldUncalibratedResponse) => void, opq: Opaque); +function OffMagneticFieldUncalibrated(opq: Optional); + +function OnMagneticField(f: (info: MagneticFieldResponse) => void, opq: Opaque, options: Optional); +function OnceMagneticField(f: (info: MagneticFieldResponse) => void, opq: Opaque); +function OffMagneticField(opq: Optional); + +function OnLinearAccelerometer(f: (info: LinearAccelerometerResponse) => void, opq: Opaque, options: Optional); +function OnceLinearAccelerometer(f: (info: LinearAccelerometerResponse) => void, opq: Opaque); +function OffLinearAccelerometer(opq: Optional); + +function OnHumidity(f: (info: HumidityResponse) => void, opq: Opaque, options: Optional); +function OnceHumidity(f: (info: HumidityResponse) => void, opq: Opaque); +function OffHumidity(opq: Optional); + +function OnHeartRate(f: (info: HeartRateResponse) => void, opq: Opaque, options: Optional); +function OnceHeartRate(f: (info: HeartRateResponse) => void, opq: Opaque); +function OffHeartRate(opq: Optional); + +function OnHall(f: (info: HallResponse) => void, opq: Opaque, options: Optional); +function OnceHall(f: (info: HallResponse) => void, opq: Opaque); +function OffHall(opq: Optional); + +function OnGyroscopeUncalibrated(f: (info: GyroscopeUncalibratedResponse) => void, opq: Opaque, options: Optional); +function OnceGyroscopeUncalibrated(f: (info: GyroscopeUncalibratedResponse) => void, opq: Opaque); +function OffGyroscopeUncalibrated(opq: Optional); + +function OnGyroscope(f: (info: GyroscopeResponse) => void, opq: Opaque, options: Optional); +function OnceGyroscope(f: (info: GyroscopeResponse) => void, opq: Opaque); +function OffGyroscope(opq: Optional); + +function OnGravity(f: (info: GravityResponse) => void, opq: Opaque, options: Optional); +function OnceGravity(f: (info: GravityResponse) => void, opq: Opaque); +function OffGravity(opq: Optional); + +function OnBarometer(f: (info: BarometerResponse) => void, opq: Opaque, options: Optional); +function OnceBarometer(f: (info: BarometerResponse) => void, opq: Opaque); +function OffBarometer(opq: Optional); + +function OnAmbientTemperature(f: (info: AmbientTemperatureResponse) => void, opq: Opaque, options: Optional); +function OnceAmbientTemperature(f: (info: AmbientTemperatureResponse) => void, opq: Opaque); +function OffAmbientTemperature(opq: Optional); + +function OnAmbientLight(f: (info: LightResponse) => void, opq: Opaque, options: Optional); +function OnceAmbientLight(f: (info: LightResponse) => void, opq: Opaque); +function OffAmbientLight(opq: Optional); + +function OnAccelerometerUncalibrated(f: (info: AccelerometerUncalibratedResponse) => void, opq: Opaque, options: Optional); +function OnceAccelerometerUncalibrated(f: (info: AccelerometerUncalibratedResponse) => void, opq: Opaque); +function OffAccelerometerUncalibrated(opq: Optional); + +function OnAccelerometer(f: (info: AccelerometerResponse) => void, opq: Opaque, options: Optional); +function OnceAccelerometer(f: (info: AccelerometerResponse) => void, opq: Opaque); +function OffAccelerometer(opq: Optional); + +function OnSar(f: (info: SarResponse) => void, opq: Opaque, options: Optional); +function OffSar(opq: Optional); + +function OnColor(f: (info: ColorResponse) => void, opq: Opaque, options: Optional); +function OffColor(opq: Optional); \ No newline at end of file diff --git a/frameworks/js/ani/include/ani_utils.h b/frameworks/js/ani/include/ani_utils.h deleted file mode 100644 index 8f2605f0e3f3ad9c2e8399e9d0f56efe06bbe684..0000000000000000000000000000000000000000 --- a/frameworks/js/ani/include/ani_utils.h +++ /dev/null @@ -1,413 +0,0 @@ -/* - * Copyright (c) 2025 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 ANI_UTILS_H -#define ANI_UTILS_H - -#include - -#include -#include -#include -#include -#include -#include -#include - -template -class NativeObjectWrapper { -public: - static ani_object Create([[maybe_unused]] ani_env *env, [[maybe_unused]] ani_class clazz) - { - T* nativePtr = new T; - return Wrap(env, clazz, nativePtr); - } - - static ani_object Wrap([[maybe_unused]] ani_env *env, [[maybe_unused]] ani_class clazz, T* nativePtr) - { - ani_method ctor; - if (ANI_OK != env->Class_FindMethod(clazz, "", "J:V", &ctor)) { - std::cerr << "Not found ''" << std::endl; - ani_object nullobj = nullptr; - return nullobj; - } - - ani_object obj; - if (ANI_OK != env->Object_New(clazz, ctor, &obj, reinterpret_cast(nativePtr))) { - std::cerr << "Object_New failed" << std::endl; - } - return obj; - } - - static T* Unwrap(ani_env *env, ani_object object, const char* propName = "nativePtr") - { - ani_long nativePtr; - if (ANI_OK != env->Object_GetFieldByName_Long(object, propName, &nativePtr)) { - return nullptr; - } - return reinterpret_cast(nativePtr); - } - - static ani_status Attach(ani_env *env, ani_object object, T* nativePtr, const char* propName = "nativePtr") - { - return env->Object_SetFieldByName_Long(object, propName, reinterpret_cast(nativePtr)); - } -}; - -class AniStringUtils { -public: - static std::string ToStd(ani_env *env, ani_string ani_str) - { - ani_size strSize; - env->String_GetUTF8Size(ani_str, &strSize); - - std::vector buffer(strSize + 1); // +1 for null terminator - char* utf8_buffer = buffer.data(); - - //String_GetUTF8 Supportted by https://gitee.com/openharmony/arkcompiler_runtime_core/pulls/3416 - ani_size bytes_written = 0; - env->String_GetUTF8(ani_str, utf8_buffer, strSize + 1, &bytes_written); - - utf8_buffer[bytes_written] = '\0'; - std::string content = std::string(utf8_buffer); - return content; - } - - static ani_string ToAni(ani_env* env, const std::string& str) - { - ani_string aniStr = nullptr; - if (ANI_OK != env->String_NewUTF8(str.data(), str.size(), &aniStr)) { - std::cerr << "[ANI] Unsupported ANI_VERSION_1" << std::endl; - return nullptr; - } - return aniStr; - } -}; - -class UnionAccessor { -public: - UnionAccessor(ani_env *env, ani_object &obj) : env_(env), obj_(obj) - { - } - - bool IsInstanceOf(const std::string& cls_name) - { - ani_class cls; - env_->FindClass(cls_name.c_str(), &cls); - - ani_boolean ret; - env_->Object_InstanceOf(obj_, cls, &ret); - return ret; - } - - template - bool IsInstanceOfType(); - - template - bool TryConvert(T &value); - - template - bool TryConvertArray(std::vector &value); - -private: - ani_env *env_; - ani_object obj_; -}; - -template<> -bool UnionAccessor::IsInstanceOfType() -{ - return IsInstanceOf("Lstd/core/Boolean;"); -} - -template<> -bool UnionAccessor::IsInstanceOfType() -{ - return IsInstanceOf("Lstd/core/Int;"); -} - -template<> -bool UnionAccessor::IsInstanceOfType() -{ - return IsInstanceOf("Lstd/core/Double;"); -} - -template<> -bool UnionAccessor::IsInstanceOfType() -{ - return IsInstanceOf("Lstd/core/String;"); -} - -template<> -bool UnionAccessor::TryConvert(bool &value) -{ - if (!IsInstanceOfType()) { - return false; - } - - ani_boolean aniValue; - auto ret = env_->Object_CallMethodByName_Boolean(obj_, "unboxed", nullptr, &aniValue); - if (ret != ANI_OK) { - return false; - } - value = static_cast(aniValue); - return true; -} - -template<> -bool UnionAccessor::TryConvert(int &value) -{ - if (!IsInstanceOfType()) { - return false; - } - - ani_int aniValue; - auto ret = env_->Object_CallMethodByName_Int(obj_, "unboxed", nullptr, &aniValue); - if (ret != ANI_OK) { - return false; - } - value = static_cast(aniValue); - return true; -} - -template<> -bool UnionAccessor::TryConvert(double &value) -{ - if (!IsInstanceOfType()) { - return false; - } - - ani_double aniValue; - auto ret = env_->Object_CallMethodByName_Double(obj_, "unboxed", nullptr, &aniValue); - if (ret != ANI_OK) { - return false; - } - value = static_cast(aniValue); - return true; -} - -template<> -bool UnionAccessor::TryConvert(std::string &value) -{ - if (!IsInstanceOfType()) { - return false; - } - - value = AniStringUtils::ToStd(env_, static_cast(obj_)); - return true; -} - -template<> -bool UnionAccessor::TryConvertArray(std::vector &value) -{ - ani_double length; - if (ANI_OK != env_->Object_GetPropertyByName_Double(obj_, "length", &length)) { - std::cerr << "Object_GetPropertyByName_Double length failed" << std::endl; - return false; - } - for (int i = 0; i < int(length); i++) { - ani_ref ref; - if (ANI_OK != env_->Object_CallMethodByName_Ref(obj_, "$_get", "I:Lstd/core/Object;", &ref, (ani_int)i)) { - std::cerr << "Object_GetPropertyByName_Ref failed" << std::endl; - return false; - } - ani_boolean val; - if (ANI_OK != env_->Object_CallMethodByName_Boolean(static_cast(ref), "unboxed", nullptr, &val)) { - std::cerr << "Object_CallMethodByName_Double unbox failed" << std::endl; - return false; - } - value.push_back(static_cast(val)); - } - return true; -} - -template<> -bool UnionAccessor::TryConvertArray(std::vector &value) -{ - ani_double length; - if (ANI_OK != env_->Object_GetPropertyByName_Double(obj_, "length", &length)) { - std::cerr << "Object_GetPropertyByName_Double length failed" << std::endl; - return false; - } - for (int i = 0; i < int(length); i++) { - ani_ref ref; - if (ANI_OK != env_->Object_CallMethodByName_Ref(obj_, "$_get", "I:Lstd/core/Object;", &ref, (ani_int)i)) { - std::cerr << "Object_GetPropertyByName_Ref failed" << std::endl; - return false; - } - ani_int intValue; - if (ANI_OK != env_->Object_CallMethodByName_Int(static_cast(ref), "unboxed", nullptr, &intValue)) { - std::cerr << "Object_CallMethodByName_Double unbox failed" << std::endl; - return false; - } - value.push_back(static_cast(intValue)); - } - return true; -} - -template<> -bool UnionAccessor::TryConvertArray(std::vector &value) -{ - ani_double length; - if (ANI_OK != env_->Object_GetPropertyByName_Double(obj_, "length", &length)) { - std::cerr << "Object_GetPropertyByName_Double length failed" << std::endl; - return false; - } - for (int i = 0; i < int(length); i++) { - ani_ref ref; - if (ANI_OK != env_->Object_CallMethodByName_Ref(obj_, "$_get", "I:Lstd/core/Object;", &ref, (ani_int)i)) { - std::cerr << "Object_GetPropertyByName_Ref failed" << std::endl; - return false; - } - ani_double val; - if (ANI_OK != env_->Object_CallMethodByName_Double(static_cast(ref), "unboxed", nullptr, &val)) { - std::cerr << "Object_CallMethodByName_Double unbox failed" << std::endl; - return false; - } - value.push_back(static_cast(val)); - } - return true; -} - -template<> -bool UnionAccessor::TryConvertArray(std::vector &value) -{ - std::cout << "TryConvertArray std::vector" << std::endl; - ani_ref buffer; - if (ANI_OK != env_->Object_GetFieldByName_Ref(obj_, "buffer", &buffer)) { - std::cout << "Object_GetFieldByName_Ref failed" << std::endl; - return false; - } - void* data; - size_t length; - if (ANI_OK != env_->ArrayBuffer_GetInfo(static_cast(buffer), &data, &length)) { - std::cerr << "ArrayBuffer_GetInfo failed" << std::endl; - return false; - } - std::cout << "Length of buffer is " << length << std::endl; - for (size_t i = 0; i < length; i++) { - value.push_back(static_cast(data)[i]); - } - return true; -} - -template<> -bool UnionAccessor::TryConvertArray(std::vector &value) -{ - ani_double length; - if (ANI_OK != env_->Object_GetPropertyByName_Double(obj_, "length", &length)) { - std::cerr << "Object_GetPropertyByName_Double length failed" << std::endl; - return false; - } - - for (int i = 0; i < int(length); i++) { - ani_ref ref; - if (ANI_OK != env_->Object_CallMethodByName_Ref(obj_, "$_get", "I:Lstd/core/Object;", &ref, (ani_int)i)) { - std::cerr << "Object_GetPropertyByName_Double length failed" << std::endl; - return false; - } - value.push_back(AniStringUtils::ToStd(env_, static_cast(ref))); - } - return true; -} - -class OptionalAccessor { -public: - OptionalAccessor(ani_env *env, ani_object &obj) : env_(env), obj_(obj) - { - } - - bool IsUndefined() - { - ani_boolean isUndefined; - env_->Reference_IsUndefined(obj_, &isUndefined); - return isUndefined; - } - - template - std::optional Convert(); - -private: - ani_env *env_; - ani_object obj_; -}; - -template<> -std::optional OptionalAccessor::Convert() -{ - if (IsUndefined()) { - return std::nullopt; - } - - ani_double aniValue; - auto ret = env_->Object_CallMethodByName_Double(obj_, "doubleValue", nullptr, &aniValue); - if (ret != ANI_OK) { - return std::nullopt; - } - auto value = static_cast(aniValue); - return value; -} - -template<> -std::optional OptionalAccessor::Convert() -{ - if (IsUndefined()) { - return std::nullopt; - } - - ani_size strSize; - env_->String_GetUTF8Size(static_cast(obj_), &strSize); - - std::vector buffer(strSize + 1); - char* utf8_buffer = buffer.data(); - - ani_size bytes_written = 0; - env_->String_GetUTF8(static_cast(obj_), utf8_buffer, strSize + 1, &bytes_written); - - utf8_buffer[bytes_written] = '\0'; - std::string content = std::string(utf8_buffer); - return content; -} - -class AniLocalScopeGuard { -public: - AniLocalScopeGuard(ani_env *env, size_t nrRefs) : env_(env) - { - status_ = env_->CreateLocalScope(nrRefs); - } - - ~AniLocalScopeGuard() - { - if (ANI_OK != status_) { - return; - } - env_->DestroyLocalScope(); - } - - bool IsStatusOK() - { - return ANI_OK == status_; - } - - ani_status GetStatus() - { - return status_; - } - -private: - ani_env *env_ = nullptr; - ani_status status_ = ANI_ERROR; -}; -#endif \ No newline at end of file diff --git a/frameworks/js/ani/include/sensor_ani.h b/frameworks/js/ani/include/sensor_ani.h deleted file mode 100644 index be11ac1711c37a0a90df2978ea5e93a182a7a27d..0000000000000000000000000000000000000000 --- a/frameworks/js/ani/include/sensor_ani.h +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright (c) 2025 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_ANI_H -#define SENSOR_ANI_H - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "refbase.h" -#include "sensor_agent_type.h" -#include "sensor_errors.h" -#include "sensor_log.h" - -#undef LOG_TAG -#define LOG_TAG "SensorAniAPI" - -namespace OHOS { -namespace Sensors { -using std::vector; -using std::string; -using namespace OHOS::HiviewDFX; -constexpr int32_t THREE_DIMENSIONAL_MATRIX_LENGTH = 9; -constexpr static int32_t DATA_LENGTH = 16; -constexpr int32_t CALLBACK_NUM = 3; -enum CallbackDataType { - SUBSCRIBE_FAIL = -2, - FAIL = -1, - OFF_CALLBACK = 0, - ON_CALLBACK = 1, - ONCE_CALLBACK = 2, - GET_GEOMAGNETIC_FIELD = 3, - GET_ALTITUDE = 4, - GET_GEOMAGNETIC_DIP = 5, - GET_ANGLE_MODIFY = 6, - CREATE_ROTATION_MATRIX = 7, - TRANSFORM_COORDINATE_SYSTEM = 8, - CREATE_QUATERNION = 9, - GET_DIRECTION = 10, - ROTATION_INCLINATION_MATRIX = 11, - GET_SENSOR_LIST = 12, - GET_SINGLE_SENSOR = 13, - SUBSCRIBE_CALLBACK = 14, - SUBSCRIBE_COMPASS = 15, - GET_BODY_STATE = 16, -}; - -struct GeomagneticData { - float x; - float y; - float z; - float geomagneticDip; - float deflectionAngle; - float levelIntensity; - float totalIntensity; -}; - -struct RationMatrixData { - float rotationMatrix[THREE_DIMENSIONAL_MATRIX_LENGTH]; - float inclinationMatrix[THREE_DIMENSIONAL_MATRIX_LENGTH]; -}; - -struct CallbackSensorData { - int32_t sensorTypeId; - uint32_t dataLength; - float data[DATA_LENGTH]; - int64_t timestamp; - int32_t sensorAccuracy; -}; - -struct ReserveData { - float reserve[DATA_LENGTH]; - int32_t length; -}; - -union CallbackData { - CallbackSensorData sensorData; - GeomagneticData geomagneticData; - RationMatrixData rationMatrixData; - ReserveData reserveData; -}; - -struct BusinessError { - int32_t code { 0 }; - string message; - string name; - string stack; -}; - -class AsyncCallbackInfo : public RefBase { -public: - ani_vm *vm = nullptr; - ani_env *env = nullptr; - ani_ref callback[CALLBACK_NUM] = { 0 }; - CallbackData data; - BusinessError error; - CallbackDataType type; - vector sensorInfos; - AsyncCallbackInfo(ani_vm *vm, ani_env *env, CallbackDataType type) : vm(vm), env(env), type(type) {} - ~AsyncCallbackInfo() - { - CALL_LOG_ENTER; - if (type != ONCE_CALLBACK) { - for (int32_t i = 0; i < CALLBACK_NUM; ++i) { - if (callback[i] != nullptr) { - SEN_HILOGD("Delete reference, i:%{public}d", i); - env->GlobalReference_Delete(callback[i]); - callback[i] = nullptr; - env = nullptr; - vm = nullptr; - } - } - } - } - -private: -}; -} // namespace Sensors -} // namespace OHOS -#endif // SENSOR_ANI_H \ No newline at end of file diff --git a/frameworks/js/ani/src/sensor_ani.cpp b/frameworks/js/ani/src/sensor_ani.cpp deleted file mode 100644 index 6871e423dcc2346b8e40d4058d3a7d0a90a8ebb5..0000000000000000000000000000000000000000 --- a/frameworks/js/ani/src/sensor_ani.cpp +++ /dev/null @@ -1,708 +0,0 @@ -/* - * Copyright (c) 2025 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_ani.h" -#include "securec.h" -#include "ani_utils.h" -#include "sensor_agent.h" -#include "event_handler.h" - -#undef LOG_TAG -#define LOG_TAG "SensorAniAPI" - -using namespace OHOS; -using namespace OHOS::Sensors; - -constexpr int32_t REPORTING_INTERVAL = 200000000; -constexpr int32_t INVALID_SENSOR_ID = -1; -constexpr float BODY_STATE_EXCEPT = 1.0f; -constexpr float THRESHOLD = 0.000001f; -constexpr int32_t ANI_SCOPE_SIZE = 16; - -static std::unordered_map g_sensorTypeToClassName = { - {256, "LOrientationResponseImpl;"}, -}; - -std::map> g_sensorAttributeList = { - { 0, { "x" } }, - { SENSOR_TYPE_ID_ACCELEROMETER, { "x", "y", "z" } }, - { SENSOR_TYPE_ID_GYROSCOPE, { "x", "y", "z" } }, - { SENSOR_TYPE_ID_AMBIENT_LIGHT, { "intensity", "colorTemperature", "infraredLuminance" } }, - { SENSOR_TYPE_ID_MAGNETIC_FIELD, { "x", "y", "z" } }, - { SENSOR_TYPE_ID_BAROMETER, { "pressure" } }, - { SENSOR_TYPE_ID_HALL, { "status" } }, - { SENSOR_TYPE_ID_TEMPERATURE, { "temperature" } }, - { SENSOR_TYPE_ID_PROXIMITY, { "distance" } }, - { SENSOR_TYPE_ID_HUMIDITY, { "humidity" } }, - { SENSOR_TYPE_ID_ORIENTATION, { "alpha", "beta", "gamma" } }, - { SENSOR_TYPE_ID_GRAVITY, { "x", "y", "z" } }, - { SENSOR_TYPE_ID_LINEAR_ACCELERATION, { "x", "y", "z" } }, - { SENSOR_TYPE_ID_ROTATION_VECTOR, { "x", "y", "z", "w" } }, - { SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, { "temperature" } }, - { SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, { "x", "y", "z", "biasX", "biasY", "biasZ" } }, - { SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, { "x", "y", "z", "biasX", "biasY", "biasZ" } }, - { SENSOR_TYPE_ID_SIGNIFICANT_MOTION, { "scalar" } }, - { SENSOR_TYPE_ID_PEDOMETER_DETECTION, { "scalar" } }, - { SENSOR_TYPE_ID_PEDOMETER, { "steps" } }, - { SENSOR_TYPE_ID_HEART_RATE, { "heartRate" } }, - { SENSOR_TYPE_ID_WEAR_DETECTION, { "value" } }, - { SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, { "x", "y", "z", "biasX", "biasY", "biasZ" } }, - { SENSOR_TYPE_ID_COLOR, { "lightIntensity", "colorTemperature" } }, - { SENSOR_TYPE_ID_SAR, { "absorptionRatio" } } -}; - -static std::unordered_map stringToNumberMap = { - {"ORIENTATION", 256}, -}; - -static std::map g_samplingPeriod = { - {"normal", 200000000}, - {"ui", 60000000}, - {"game", 20000000}, -}; - -using ConvertDataFunc = bool(*)(sptr asyncCallbackInfo, std::vector &data); -static bool ConvertToSensorData(sptr asyncCallbackInfo, std::vector &data); - -static std::map g_convertfuncList = { - {ON_CALLBACK, ConvertToSensorData}, -}; - -static std::mutex mutex_; -static std::mutex bodyMutex_; -static float g_bodyState = -1.0f; -static std::map>> g_subscribeCallbacks; -static std::mutex onMutex_; -static std::map>> g_onCallbackInfos; -static thread_local std::shared_ptr mainHandler = nullptr; - -static void ThrowBusinessError(ani_env *env, int errCode, std::string&& errMsg) -{ - SEN_HILOGD("Begin ThrowBusinessError."); - static const char *errorClsName = "L@ohos/base/BusinessError;"; - ani_class cls {}; - if (ANI_OK != env->FindClass(errorClsName, &cls)) { - SEN_HILOGE("find class BusinessError %{public}s failed", errorClsName); - return; - } - ani_method ctor; - if (ANI_OK != env->Class_FindMethod(cls, "", ":V", &ctor)) { - SEN_HILOGE("find method BusinessError.constructor failed"); - return; - } - ani_object errorObject; - if (ANI_OK != env->Object_New(cls, ctor, &errorObject)) { - SEN_HILOGE("create BusinessError object failed"); - return; - } - ani_double aniErrCode = static_cast(errCode); - ani_string errMsgStr; - if (ANI_OK != env->String_NewUTF8(errMsg.c_str(), errMsg.size(), &errMsgStr)) { - SEN_HILOGE("convert errMsg to ani_string failed"); - return; - } - if (ANI_OK != env->Object_SetFieldByName_Double(errorObject, "code", aniErrCode)) { - SEN_HILOGE("set error code failed"); - return; - } - if (ANI_OK != env->Object_SetPropertyByName_Ref(errorObject, "message", errMsgStr)) { - SEN_HILOGE("set error message failed"); - return; - } - env->ThrowError(static_cast(errorObject)); - return; -} - -static bool CheckSubscribe(int32_t sensorTypeId) -{ - std::lock_guard onCallbackLock(onMutex_); - auto iter = g_onCallbackInfos.find(sensorTypeId); - return iter != g_onCallbackInfos.end(); -} - -static bool CopySensorData(sptr callbackInfo, SensorEvent *event) -{ - CHKPF(callbackInfo); - CHKPF(event); - int32_t sensorTypeId = event->sensorTypeId; - callbackInfo->data.sensorData.sensorTypeId = sensorTypeId; - callbackInfo->data.sensorData.dataLength = event->dataLen; - callbackInfo->data.sensorData.timestamp = event->timestamp; - callbackInfo->data.sensorData.sensorAccuracy = event->option; - CHKPF(event->data); - if (event->dataLen < sizeof(float)) { - SEN_HILOGE("Event dataLen less than float size"); - return false; - } - auto data = reinterpret_cast(event->data); - if (sensorTypeId == SENSOR_TYPE_ID_WEAR_DETECTION && callbackInfo->type == SUBSCRIBE_CALLBACK) { - std::lock_guard onBodyLock(bodyMutex_); - g_bodyState = *data; - callbackInfo->data.sensorData.data[0] = - (fabs(g_bodyState - BODY_STATE_EXCEPT) < THRESHOLD) ? true : false; - return true; - } - if (memcpy_s(callbackInfo->data.sensorData.data, sizeof(callbackInfo->data.sensorData.data), - data, event->dataLen) != EOK) { - SEN_HILOGE("Copy data failed"); - return false; - } - return true; -} - -static bool CheckSystemSubscribe(int32_t sensorTypeId) -{ - std::lock_guard subscribeLock(mutex_); - auto iter = g_subscribeCallbacks.find(sensorTypeId); - if (iter == g_subscribeCallbacks.end()) { - return false; - } - return true; -} - -static ani_boolean IsInstanceOf(ani_env *env, const std::string &cls_name, ani_object obj) -{ - ani_class cls; - if (ANI_OK != env->FindClass(cls_name.c_str(), &cls)) { - SEN_HILOGE("FindClass failed"); - return ANI_FALSE; - } - - ani_boolean ret; - env->Object_InstanceOf(obj, cls, &ret); - return ret; -} - -static bool SendEventToMainThread(const std::function func) -{ - if (func == nullptr) { - SEN_HILOGE("func is nullptr!"); - return false; - } - - if (!mainHandler) { - auto runner = OHOS::AppExecFwk::EventRunner::GetMainEventRunner(); - if (!runner) { - SEN_HILOGE("get main event runner failed!"); - return false; - } - mainHandler = std::make_shared(runner); - } - mainHandler->PostTask(func, "", 0, OHOS::AppExecFwk::EventQueue::Priority::HIGH, {}); - return true; -} - -static bool ValidateAndInitialize(sptr asyncCallbackInfo, ani_object &obj) -{ - CHKPF(asyncCallbackInfo); - int32_t sensorTypeId = asyncCallbackInfo->data.sensorData.sensorTypeId; - if (g_sensorAttributeList.find(sensorTypeId) == g_sensorAttributeList.end()) { - SEN_HILOGE("Invalid sensor type"); - return false; - } - if (sensorTypeId == SENSOR_TYPE_ID_WEAR_DETECTION && asyncCallbackInfo->type == SUBSCRIBE_CALLBACK) { - return false; - } - size_t size = g_sensorAttributeList[sensorTypeId].size(); - uint32_t dataLength = asyncCallbackInfo->data.sensorData.dataLength / sizeof(float); - if (size > dataLength) { - SEN_HILOGE("Data length mismatch"); - return false; - } - - if (g_sensorTypeToClassName.find(sensorTypeId) == g_sensorTypeToClassName.end()) { - SEN_HILOGE("Find class by sensorType failed"); - return false; - } - - ani_namespace ns; - static const char *namespaceName = "L@ohos/sensor/sensor;"; - if (ANI_OK != asyncCallbackInfo->env->FindNamespace(namespaceName, &ns)) { - SEN_HILOGE("Not found '%{public}s'", namespaceName); - return false; - } - - ani_class cls; - const char *className = g_sensorTypeToClassName[sensorTypeId].c_str(); - if (ANI_OK != asyncCallbackInfo->env->Namespace_FindClass(ns, className, &cls)) { - SEN_HILOGE("FindClass %{public}s failed", className); - return false; - } - - ani_method ctor; - if (ANI_OK != asyncCallbackInfo->env->Class_FindMethod(cls, "", nullptr, &ctor)) { - SEN_HILOGE("Class_FindMethod 'constructor' failed"); - return false; - } - - if (ANI_OK != asyncCallbackInfo->env->Object_New(cls, ctor, &obj)) { - SEN_HILOGE("Object_New '%{public}s' failed", className); - return false; - } - return true; -} - -static ani_enum_item GetEnumItem(ani_env *env, int32_t accuracy) -{ - ani_namespace ns; - static const char *namespaceName = "L@ohos/sensor/sensor;"; - if (ANI_OK != env->FindNamespace(namespaceName, &ns)) { - SEN_HILOGE("Not found '%{public}s'", namespaceName); - return nullptr; - } - - ani_enum aniEnum{}; - const char *enumName = "LSensorAccuracy;"; - if (ANI_OK != env->Namespace_FindEnum(ns, enumName, &aniEnum)) { - SEN_HILOGE("Not found '%{public}s'", enumName); - return nullptr; - } - - constexpr int32_t loopMaxNum = 1000; - for (int32_t index = 0U; index < loopMaxNum; index++) { - ani_enum_item enumItem{}; - if (ANI_OK != env->Enum_GetEnumItemByIndex(aniEnum, index, &enumItem)) { - SEN_HILOGE("Enum_GetEnumItemByIndex failed"); - return nullptr; - } - ani_int intValue = -1; - if (ANI_OK != env->EnumItem_GetValue_Int(enumItem, &intValue)) { - SEN_HILOGE("EnumItem_GetValue_Int FAILD."); - return nullptr; - } - if (intValue == accuracy) { - return enumItem; - } - } - SEN_HILOGE("Get enumItem by %{public}d failed.", accuracy); - return nullptr; -} - -static bool SetSensorPropertiesAndPushData(sptr asyncCallbackInfo, ani_object obj, - std::vector &data) -{ - CALL_LOG_ENTER; - int32_t sensorTypeId = asyncCallbackInfo->data.sensorData.sensorTypeId; - size_t size = g_sensorAttributeList[sensorTypeId].size(); - auto sensorAttributes = g_sensorAttributeList[sensorTypeId]; - for (uint32_t i = 0; i < size; ++i) { - if (ANI_OK != asyncCallbackInfo->env->Object_SetPropertyByName_Double(obj, sensorAttributes[i].c_str(), - asyncCallbackInfo->data.sensorData.data[i])) { - SEN_HILOGE("Object_SetPropertyByName_Double failed"); - return false; - } - } - - if (ANI_OK != asyncCallbackInfo->env->Object_SetPropertyByName_Double(obj, "timestamp", - asyncCallbackInfo->data.sensorData.timestamp)) { - SEN_HILOGE("Object_SetPropertyByName_Double timestamp failed"); - return false; - } - - ani_enum_item accuracy = GetEnumItem(asyncCallbackInfo->env, asyncCallbackInfo->data.sensorData.sensorAccuracy); - if (accuracy == nullptr) { - SEN_HILOGE("GetEnumItem failed"); - return false; - } - if (ANI_OK != asyncCallbackInfo->env->Object_SetPropertyByName_Ref(obj, "accuracy", accuracy)) { - SEN_HILOGE("Object_SetPropertyByName_Ref accuracy failed"); - return false; - } - - data.push_back(obj); - return true; -} - -static bool ConvertToSensorData(sptr asyncCallbackInfo, std::vector &data) -{ - ani_object obj; - if (!ValidateAndInitialize(asyncCallbackInfo, obj)) { - return false; - } - - if (!SetSensorPropertiesAndPushData(asyncCallbackInfo, obj, data)) { - return false; - } - - return true; -} - -static void EmitUvEventLoop(sptr asyncCallbackInfo) -{ - CHKPV(asyncCallbackInfo); - auto task = [asyncCallbackInfo]() { - SEN_HILOGD("Begin to call task"); - ani_env *env = nullptr; - ani_options aniArgs {0, nullptr}; - if (ANI_ERROR == asyncCallbackInfo->vm->AttachCurrentThread(&aniArgs, ANI_VERSION_1, &env)) { - if (ANI_OK != asyncCallbackInfo->vm->GetEnv(ANI_VERSION_1, &env)) { - SEN_HILOGE("GetEnv failed"); - return; - } - } - asyncCallbackInfo->env = env; - - AniLocalScopeGuard aniLocalScopeGuard(asyncCallbackInfo->env, ANI_SCOPE_SIZE); - if (!aniLocalScopeGuard.IsStatusOK()) { - SEN_HILOGE("CreateLocalScope failed"); - return; - } - - if (!(g_convertfuncList.find(asyncCallbackInfo->type) != g_convertfuncList.end())) { - SEN_HILOGE("asyncCallbackInfo type is invalid"); - ThrowBusinessError(asyncCallbackInfo->env, EINVAL, "asyncCallbackInfo type is invalid"); - return; - } - std::vector args; - g_convertfuncList[asyncCallbackInfo->type](asyncCallbackInfo, args); - - auto fnObj = reinterpret_cast(asyncCallbackInfo->callback[0]); - SEN_HILOGD("Begin to call FunctionalObject_Call"); - if (fnObj == nullptr) { - SEN_HILOGE("fnObj == nullptr"); - ThrowBusinessError(asyncCallbackInfo->env, EINVAL, "fnObj == nullptr"); - return; - } - if (IsInstanceOf(asyncCallbackInfo->env, "Lstd/core/Function1;", fnObj) == 0) { - SEN_HILOGE("fnObj is not instance Of function"); - ThrowBusinessError(asyncCallbackInfo->env, EINVAL, "fnObj is not instance Of function"); - return; - } - - ani_ref result; - if (ANI_OK != asyncCallbackInfo->env->FunctionalObject_Call(fnObj, 1, args.data(), &result)) { - SEN_HILOGE("FunctionalObject_Call failed"); - ThrowBusinessError(asyncCallbackInfo->env, EINVAL, "FunctionalObject_Call failed"); - return; - } - SEN_HILOGD("FunctionalObject_Call success"); - }; - if (!SendEventToMainThread(task)) { - SEN_HILOGE("failed to send event"); - } -} -static void EmitOnCallback(SensorEvent *event) -{ - CHKPV(event); - int32_t sensorTypeId = event->sensorTypeId; - if (!CheckSubscribe(sensorTypeId)) { - return; - } - std::lock_guard onCallbackLock(onMutex_); - auto onCallbackInfos = g_onCallbackInfos[sensorTypeId]; - for (auto &onCallbackInfo : onCallbackInfos) { - if (!CopySensorData(onCallbackInfo, event)) { - SEN_HILOGE("Copy sensor data failed"); - continue; - } - EmitUvEventLoop(onCallbackInfo); - } -} - -static void DataCallbackImpl(SensorEvent *event) -{ - CHKPV(event); - EmitOnCallback(event); -} - -static const SensorUser user = { - .callback = DataCallbackImpl -}; - -static int32_t SubscribeSensor(int32_t sensorTypeId, int64_t interval, RecordSensorCallback callback) -{ - CALL_LOG_ENTER; - int32_t ret = SubscribeSensor(sensorTypeId, &user); - if (ret != ERR_OK) { - SEN_HILOGE("SubscribeSensor failed"); - return ret; - } - ret = SetBatch(sensorTypeId, &user, interval, 0); - if (ret != ERR_OK) { - SEN_HILOGE("SetBatch failed"); - return ret; - } - return ActivateSensor(sensorTypeId, &user); -} - -static bool IsSubscribed(ani_env *env, int32_t sensorTypeId, ani_object callback) -{ - CALL_LOG_ENTER; - if (auto iter = g_onCallbackInfos.find(sensorTypeId); iter == g_onCallbackInfos.end()) { - SEN_HILOGW("No client subscribe, sensorTypeId:%{public}d", sensorTypeId); - return false; - } - std::vector> callbackInfos = g_onCallbackInfos[sensorTypeId]; - for (auto callbackInfo : callbackInfos) { - CHKPC(callbackInfo); - if (callbackInfo->env != env) { - continue; - } - - ani_boolean isEquals = false; - if (ANI_OK != env->Reference_StrictEquals(callback, callbackInfo->callback[0], &isEquals)) { - SEN_HILOGE("StrictEquals failed"); - return false; - } - if (isEquals) { - return true; - } - } - return false; -} - -static void UpdateCallbackInfos(ani_env *env, int32_t sensorTypeId, ani_object callback) -{ - CALL_LOG_ENTER; - std::lock_guard onCallbackLock(onMutex_); - CHKCV((!IsSubscribed(env, sensorTypeId, callback)), "The callback has been subscribed"); - - ani_vm *vm = nullptr; - if (ANI_OK != env->GetVM(&vm)) { - SEN_HILOGE("GetVM failed."); - return; - } - sptr asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo(vm, env, ON_CALLBACK); - CHKPV(asyncCallbackInfo); - - if (ANI_OK != env->GlobalReference_Create(callback, &asyncCallbackInfo->callback[0])) { - SEN_HILOGE("GlobalReference_Create failed"); - return; - } - - std::vector> callbackInfos = g_onCallbackInfos[sensorTypeId]; - callbackInfos.push_back(asyncCallbackInfo); - g_onCallbackInfos[sensorTypeId] = callbackInfos; -} - -static bool GetIntervalValue(ani_env *env, ani_object options, int64_t& interval) -{ - ani_boolean isUndefined; - env->Reference_IsUndefined(options, &isUndefined); - if (isUndefined) { - return true; - } - - ani_ref intervalRef; - ani_boolean isIntervalUndefined; - if (ANI_OK != env->Object_GetPropertyByName_Ref(options, "interval", &intervalRef)) { - SEN_HILOGE("Failed to get property named interval"); - return false; - } - - env->Reference_IsUndefined(intervalRef, &isIntervalUndefined); - if (isIntervalUndefined) { - SEN_HILOGE("interval is undefined"); - return false; - } - - ani_class stringClass; - env->FindClass("Lstd/core/String;", &stringClass); - ani_class doubleClass; - env->FindClass("Lstd/core/Double;", &doubleClass); - - ani_boolean isDouble; - env->Object_InstanceOf(static_cast(intervalRef), doubleClass, &isDouble); - ani_boolean isString; - env->Object_InstanceOf(static_cast(intervalRef), stringClass, &isString); - if (isDouble) { - ani_double doubleValue; - auto ret = env->Object_CallMethodByName_Double(static_cast(intervalRef), "unboxed", - nullptr, &doubleValue); - if (ret != ANI_OK) { - SEN_HILOGE("Failed to get property named doubleValue"); - return false; - } - interval = static_cast(doubleValue); - return true; - } - - if (isString) { - auto mode = AniStringUtils::ToStd(env, static_cast(intervalRef)); - auto iter = g_samplingPeriod.find(mode); - if (iter == g_samplingPeriod.end()) { - SEN_HILOGE("Find interval mode failed"); - return false; - } - interval = iter->second; - SEN_HILOGI("GetIntervalValue mode: %{public}s", mode.c_str()); - return true; - } - - SEN_HILOGE("Invalid interval type"); - return false; -} - -static void On([[maybe_unused]] ani_env *env, ani_string typeId, ani_object callback, ani_object options) -{ - CALL_LOG_ENTER; - if (!IsInstanceOf(env, "Lstd/core/Function1;", callback)) { - SEN_HILOGE("Wrong argument type"); - return; - } - - int32_t sensorTypeId = INVALID_SENSOR_ID; - auto typeIdStr = AniStringUtils::ToStd(env, static_cast(typeId)); - if (stringToNumberMap.find(typeIdStr) == stringToNumberMap.end()) { - SEN_HILOGE("Invalid sensor typeId: %{public}s", typeIdStr.c_str()); - return; - } - sensorTypeId = stringToNumberMap[typeIdStr]; - - int64_t interval = REPORTING_INTERVAL; - if (!GetIntervalValue(env, options, interval)) { - SEN_HILOGW("Get interval failed"); - } - int32_t ret = SubscribeSensor(sensorTypeId, interval, DataCallbackImpl); - if (ret != ERR_OK) { - ThrowBusinessError(env, ret, "SubscribeSensor fail"); - return; - } - UpdateCallbackInfos(env, sensorTypeId, callback); -} - -static int32_t RemoveAllCallback(ani_env *env, int32_t sensorTypeId) -{ - CALL_LOG_ENTER; - std::lock_guard onCallbackLock(onMutex_); - std::vector> callbackInfos = g_onCallbackInfos[sensorTypeId]; - for (auto iter = callbackInfos.begin(); iter != callbackInfos.end();) { - CHKPC(*iter); - if ((*iter)->env != env) { - ++iter; - continue; - } - iter = callbackInfos.erase(iter); - } - if (callbackInfos.empty()) { - SEN_HILOGD("No subscription to change sensor data"); - g_onCallbackInfos.erase(sensorTypeId); - return 0; - } - g_onCallbackInfos[sensorTypeId] = callbackInfos; - return callbackInfos.size(); -} - -static int32_t RemoveCallback(ani_env *env, int32_t sensorTypeId, ani_object callback) -{ - CALL_LOG_ENTER; - std::lock_guard onCallbackLock(onMutex_); - std::vector> callbackInfos = g_onCallbackInfos[sensorTypeId]; - for (auto iter = callbackInfos.begin(); iter != callbackInfos.end();) { - CHKPC(*iter); - if ((*iter)->env != env) { - continue; - } - - ani_boolean isEquals = false; - if (ANI_OK != env->Reference_StrictEquals(callback, (*iter)->callback[0], &isEquals)) { - SEN_HILOGE("Reference_StrictEquals failed"); - return false; - } - if (isEquals) { - iter = callbackInfos.erase(iter); - SEN_HILOGD("Remove callback success"); - break; - } else { - ++iter; - } - } - if (callbackInfos.empty()) { - SEN_HILOGD("No subscription to change sensor data"); - g_onCallbackInfos.erase(sensorTypeId); - return 0; - } - g_onCallbackInfos[sensorTypeId] = callbackInfos; - return callbackInfos.size(); -} - -static int32_t UnsubscribeSensor(int32_t sensorTypeId) -{ - int32_t ret = DeactivateSensor(sensorTypeId, &user); - if (ret != ERR_OK) { - SEN_HILOGE("DeactivateSensor failed"); - return ret; - } - return UnsubscribeSensor(sensorTypeId, &user); -} - -static void Off([[maybe_unused]] ani_env *env, ani_string type, ani_object callback) -{ - CALL_LOG_ENTER; - int32_t sensorTypeId = INVALID_SENSOR_ID; - auto typeStr = AniStringUtils::ToStd(env, static_cast(type)); - if (stringToNumberMap.find(typeStr) == stringToNumberMap.end()) { - SEN_HILOGE("Invalid sensor type: %{public}s", typeStr.c_str()); - ThrowBusinessError(env, PARAMETER_ERROR, "Invalid sensor type"); - return; - } - sensorTypeId = stringToNumberMap[typeStr]; - - int32_t subscribeSize = -1; - ani_boolean isUndefined; - env->Reference_IsUndefined(callback, &isUndefined); - if (isUndefined) { - subscribeSize = RemoveAllCallback(env, sensorTypeId); - } else { - ani_boolean result; - if (env->Reference_IsNull(callback, &result) == ANI_OK && result) { - subscribeSize = RemoveAllCallback(env, sensorTypeId); - } else if (IsInstanceOf(env, "Lstd/core/Function1;", callback)) { - subscribeSize = RemoveCallback(env, sensorTypeId, callback); - } else { - ThrowBusinessError(env, PARAMETER_ERROR, "Invalid callback"); - return; - } - } - - if (CheckSystemSubscribe(sensorTypeId) || (subscribeSize > 0)) { - SEN_HILOGW("There are other client subscribe system js api as well, not need unsubscribe"); - return; - } - int32_t ret = UnsubscribeSensor(sensorTypeId); - if (ret == PARAMETER_ERROR || ret == PERMISSION_DENIED) { - ThrowBusinessError(env, ret, "UnsubscribeSensor fail"); - } - return; -} - -ANI_EXPORT ani_status ANI_Constructor(ani_vm *vm, uint32_t *result) -{ - ani_env *env; - if (ANI_OK != vm->GetEnv(ANI_VERSION_1, &env)) { - SEN_HILOGE("Unsupported ANI_VERSION_1"); - return ANI_ERROR; - } - - ani_namespace ns; - static const char *spaceName = "L@ohos/sensor/sensor;"; - if (ANI_OK != env->FindNamespace(spaceName, &ns)) { - SEN_HILOGE("Not found space name"); - return ANI_ERROR; - } - - std::array methods = { - ani_native_function {"on", nullptr, reinterpret_cast(On)}, - ani_native_function {"off", nullptr, reinterpret_cast(Off)}, - }; - - if (ANI_OK != env->Namespace_BindNativeFunctions(ns, methods.data(), methods.size())) { - SEN_HILOGE("Cannot bind native methods to %{public}s", spaceName); - return ANI_ERROR; - } - - *result = ANI_VERSION_1; - return ANI_OK; -} \ No newline at end of file