diff --git a/en/application-dev/device/sensor/sensor-guidelines.md b/en/application-dev/device/sensor/sensor-guidelines.md index d5f7ef19b04d029ac76e0e096bc91e1c44419f2d..dd91c4900d14172fda8046345c5f5c346104445a 100644 --- a/en/application-dev/device/sensor/sensor-guidelines.md +++ b/en/application-dev/device/sensor/sensor-guidelines.md @@ -10,12 +10,15 @@ For details about the APIs, see [Sensor](../../reference/apis-sensor-service-kit ## Available APIs -| Name| Description| -| -------- | -------- | -| sensor.on(sensorId, callback:AsyncCallback<Response>): void | Subscribes to data changes of a type of sensor.| -| sensor.once(sensorId, callback:AsyncCallback<Response>): void | Subscribes to only one data change of a type of sensor.| -| sensor.off(sensorId, callback?:AsyncCallback<void>): void | Unsubscribes from sensor data changes.| -| sensor.getSensorList(callback: AsyncCallback\>): void| Obtains information about all sensors on the device. This API uses an asynchronous callback to return the result.| +| Name| Description | +| -------- |---------------------------------| +| sensor.on(sensorId, callback:AsyncCallback<Response>, options?: Options): void | Subscribes to data changes of a type of sensor. | +| sensor.on(type: 'sensorStatusChange', callback: Callback<SensorStatusEvent>): void | Enables listening for sensor status changes.| +| sensor.once(sensorId, callback:AsyncCallback<Response>): void | Subscribes to only one data change of a type of sensor. | +| sensor.off(sensorId, callback?:AsyncCallback<void>): void | Unsubscribes from sensor data changes. | +| sensor.off(sensorId, sensorInfoParam?: SensorInfoParam, callback?:AsyncCallback<void>): void | Disables listening for data changes of the specified type of sensor based on the given sensor parameters. | +| sensor.off(type: 'sensorStatusChange', callback?: Callback<SensorStatusEvent>): void | Disables listening for sensor status changes. | +| sensor.getSensorList(callback: AsyncCallback\>): void| Obtains information about all sensors on the device. This API uses an asynchronous callback to return the result. | ## How to Develop @@ -34,7 +37,7 @@ The acceleration sensor is used as an example. ```ts sensor.getSensorList((error: BusinessError, data: Array) => { if (error) { - console.info('getSensorList failed'); + console.error('getSensorList failed'); } else { console.info('getSensorList success'); for (let i = 0; i < data.length; i++) { @@ -48,16 +51,53 @@ The acceleration sensor is used as an example. The minimum and the maximum sampling periods supported by the sensor are 5000000 ns and 200000000 ns, respectively. The sampling interval may vary depending on the sensor type. The specified sampling interval must be within this range. If the configured value is smaller than the minimum sampling interval of the sensor, the minimum sampling interval is used. If the configured value is larger than the maximum sampling interval of the sensor, the maximum sampling interval is used. A smaller value means a higher reporting frequency and a higher power consumption. + You can query sensors based on the given device ID. + ```ts + try { + const deviceId = 1; + // The deviceId parameter is optional. The default value is the ID of the local device. + const sensorList: sensor.Sensor[] = sensor.getSensorListByDeviceSync(deviceId); + console.log(`sensorList length: ${sensorList.length}`); + console.log(`sensorList: ${JSON.stringify(sensorList)}`); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to get sensorList. Code: ${e.code}, message: ${e.message}`); + } + ``` + 3. Check whether the corresponding permission has been configured. For details, see [Declaring Permissions](../../security/AccessToken/declare-permissions.md). 4. Register a listener. You can call **on()** or **once()** to listen for sensor data changes. The **on()** API is used to continuously listen for data changes of the sensor. The sensor reporting interval is set to 100000000 ns. - ```ts - sensor.on(sensor.SensorId.ACCELEROMETER, (data: sensor.AccelerometerResponse) => { - console.info("Succeeded in obtaining data. x: " + data.x + " y: " + data.y + " z: " + data.z); - }, { interval: 100000000 }); + ```ts + import { sensor } from '@kit.SensorServiceKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + try { + sensor.on(sensor.SensorId.ACCELEROMETER, (data: sensor.AccelerometerResponse) => { + console.info("Succeeded in obtaining data. x: " + data.x + " y: " + data.y + " z: " + data.z); + }, { interval: 100000000 }); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to get sensorList. Code: ${e.code}, message: ${e.message}`); + } + ``` + + You can also specify SensorInfoParam, which is used to pass deviceId and sensorIndex. + ```ts + import { sensor } from '@kit.SensorServiceKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + try { + sensor.on(sensor.SensorId.ACCELEROMETER, (data: sensor.AccelerometerResponse) => { + console.info("Succeeded in obtaining data. x: " + data.x + " y: " + data.y + " z: " + data.z); + }, { interval: 100000000, sensorInfoParam: { deviceId: 1, sensorIndex: 3 } }); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to get sensorList. Code: ${e.code}, message: ${e.message}`); + } ``` ![](figures/002.png) @@ -74,6 +114,29 @@ The acceleration sensor is used as an example. 5. Cancel continuous listening. + Note that disabling listening without a prior subscription is an abnormal behavior and requires exception handling. ```ts sensor.off(sensor.SensorId.ACCELEROMETER); ``` + + Disables listening for sensor status changes based on the given sensor parameters. + ```ts + sensor.off(sensor.SensorId.ACCELEROMETER, { deviceId: 1, sensorIndex: 3 }); + ``` + +6. Enable listening for sensor status changes. When receiving a device offline event, you need to call **off** to close the sensor on the device. + + In **SensorStatusEvent**, the following information is included: event timestamp, sensor ID, sensor index, online/offline status, device ID, and device name. + ```ts + sensor.on('sensorStatusChange', (data: sensor.SensorStatusEvent) => { + console.log(`timestamp: ${data.timestamp}, + deviceId: ${data.deviceId} deviceName: ${data.deviceName} + sensorId: ${data.sensorId} sensorIndex:${data.sensorIndex} isSensorOnline: ${data.isSensorOnline}`) + }); + ``` + + Disable listening for sensor status changes. + ```ts + // Before performing this operation, ensure that listening for sensor status changes has been enabled. + sensor.off('sensorStatusChange'); + ``` diff --git a/en/application-dev/device/sensor/sensorservice-kit-intro.md b/en/application-dev/device/sensor/sensorservice-kit-intro.md index 6f10e0a7bab477b5364013ff119116d4df8e3382..946eee9d34923ebf9cec7580ffd122741a0c3292 100644 --- a/en/application-dev/device/sensor/sensorservice-kit-intro.md +++ b/en/application-dev/device/sensor/sensorservice-kit-intro.md @@ -5,8 +5,13 @@ Sensor Service Kit enables applications to obtain raw data from sensors and provides vibration control capabilities. - The sensor module provides APIs for applications to access the underlying sensor hardware. Using these APIs, you can query sensors on your device and subscribe to sensor data. Based on the sensor data obtained, you can customize algorithms and develop various sensor-based applications, such as compass, motion-controlled games, and fitness and health applications. + - Local sensors: sensors built into the device. Typical examples include accelerometers, gyroscopes, and temperature sensors. + - Dynamic sensors: external sensors. The sensor module supports refined control over dynamic sensors, and listening for status changes (such as connection and disconnection) of dynamic sensors can be enabled or disabled via the **on** or **off** API. - The vibrator module maximally unlocks the capabilities of the vibrator device. By expanding the vibrator services, it achieves an integrated design of vibration and interaction, creating a delicate and sophisticated vibration experience that takes user interaction efficiency and usability to the next level. + - Local vibrators: vibrators built into the device. Typical examples include rotor vibrators and linear vibrators. + - Dynamic vibrators: external vibrators, which support independent control and management based on information such as device connection status and vibrator status. Dynamic vibrators are widely used in peripherals, including game controllers and external vibrators. + ## Constraints @@ -18,8 +23,10 @@ Sensor Service Kit enables applications to obtain raw data from sensors and prov - The APIs for subscribing to and unsubscribing from sensor data work in pairs. If you do not need sensor data, call the unsubscription API to stop sensor data reporting. +- If a dynamic sensor is disconnected, the application needs to disable listening for sensor data changes. ### Vibrator - To use vibrator functions, ensure that the device where your application runs has the required misc components. - To use vibrators, you need to request the required permissions. +- If there are multiple devices and vibrators, the application must determine which vibrator to use. diff --git a/en/application-dev/device/sensor/vibrator-guidelines.md b/en/application-dev/device/sensor/vibrator-guidelines.md index b14c495f2c017225827409b7dad7f6aa0a29889d..7cc77c74ec5f0f0d3b3664f4b1793526ddf6e599 100644 --- a/en/application-dev/device/sensor/vibrator-guidelines.md +++ b/en/application-dev/device/sensor/vibrator-guidelines.md @@ -10,16 +10,21 @@ For details about the APIs, see [Vibrator](../../reference/apis-sensor-service-k ## Available APIs -| Name | Description | -| ------------------------------------------------------------ | ------------------------------------------------------------ | -| startVibration(effect: VibrateEffect, attribute: VibrateAttribute): Promise<void> | Starts vibration with the specified effect and attribute. This API uses a promise to return the result.| -| startVibration(effect: VibrateEffect, attribute: VibrateAttribute, callback: AsyncCallback<void>): void | Starts vibration with the specified effect and attribute. This API uses an asynchronous callback to return the result.| -| stopVibration(stopMode: VibratorStopMode): Promise<void> | Stops vibration in the specified mode. This API uses a promise to return the result. | -| stopVibration(stopMode: VibratorStopMode, callback: AsyncCallback<void>): void | Stops vibration in the specified mode. This API uses an asynchronous callback to return the result. | -| stopVibration(): Promise<void> | Stops vibration in all modes. This API uses a promise to return the result. | -| stopVibration(callback: AsyncCallback<void>): void | Stops vibration in all modes. This API uses an asynchronous callback to return the result. | -| isSupportEffect(effectId: string): Promise<boolean> | Checks whether an effect ID is supported. This API uses a promise to return the result. This API uses a promise to return the result. The return value **true** means that the effect ID is supported, and **false** means the opposite.| -| isSupportEffect(effectId: string, callback: AsyncCallback<boolean>): void | Checks whether an effect ID is supported. This API uses an asynchronous callback to return the result. This API uses an asynchronous callback to return the result. The return value **true** means that the effect ID is supported, and **false** means the opposite.| +| Name | Description | +| ------------------------------------------------------------ |-----------------------------------------------------------------------------| +| startVibration(effect: VibrateEffect, attribute: VibrateAttribute): Promise<void> | Starts vibration with the specified effect and attribute. This API uses a promise to return the result. | +| startVibration(effect: VibrateEffect, attribute: VibrateAttribute, callback: AsyncCallback<void>): void | Starts vibration with the specified effect and attribute. This API uses an asynchronous callback to return the result. | +| stopVibration(stopMode: VibratorStopMode): Promise<void> | Stops vibration in the specified mode. This API uses a promise to return the result. | +| stopVibration(stopMode: VibratorStopMode, callback: AsyncCallback<void>): void | Stops vibration in the specified mode. This API uses an asynchronous callback to return the result. | +| stopVibration(): Promise<void> | Stops vibration in all modes. This API uses a promise to return the result. | +| stopVibration(param?: VibratorInfoParam): Promise<void> | Stops vibration based on the specified vibrator parameters. This API uses a promise to return the result. | +| stopVibration(callback: AsyncCallback<void>): void | Stops vibration in all modes. This API uses an asynchronous callback to return the result. | +| isSupportEffect(effectId: string): Promise<boolean> | Checks whether an effect ID is supported. This API uses a promise to return the result. The return value **true** means that the effect ID is supported, and **false** means the opposite. | +| isSupportEffect(effectId: string, callback: AsyncCallback<boolean>): void | Checks whether an effect ID is supported. This API uses an asynchronous callback to return the result. The return value **true** means that the effect ID is supported, and **false** means the opposite. | +| getEffectInfoSync(effectId: string, param?: VibratorInfoParam): EffectInfo | Checks whether the effect specified by the input **effectId** is supported. The **param** parameter can be used to specify a specific vibrator. You can check the **isEffectSupported** field in the returned **EffectInfo** object to determine whether the effect is supported.| +| getVibratorInfoSync(param?: VibratorInfoParam): Array<VibratorInfo> | Queries the vibrator list of one or all devices. The returned **VibratorInfo** object includes the following information: device ID, vibrator ID, device name, support for HD vibration, and local device flag. | +| on(type: 'vibratorStateChange', callback: Callback<VibratorStatusEvent>): void | Enables listening for vibrator status changes. The **VibratorStatusEvent** parameter includes the following information: event timestamp, device ID, number of vibrators, and online/offline status. | +| off(type: 'vibratorStateChange', callback?: Callback<VibratorStatusEvent>): void | Disables listening for vibrator status changes. | ## Vibration Effect Description @@ -151,7 +156,42 @@ The following requirements must be met: 1. Before using the vibrator on a device, you must declare the **ohos.permission.VIBRATE** permission. For details, see [Declaring Permissions](../../security/AccessToken/declare-permissions.md). -2. Start vibration with the specified effect and attribute. +2. Query vibrator information. + + Scenario 1: Query information about all vibrators. + + ```ts + import { vibrator } from '@kit.SensorServiceKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + try { + const vibratorInfoList: vibrator.VibratorInfo[] = vibrator.getVibratorInfoSync(); + console.log(`vibratorInfoList: ${JSON.stringify(vibratorInfoList)}`); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); + } + ``` + + Scenario 2: Query information about one or more vibrators of the specified device. + + ```ts + import { vibrator } from '@kit.SensorServiceKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + try { + const vibratorParam: vibrator.VibratorInfoParam = { + deviceId: 1 // The device ID must be the one that actually exists. + } + const vibratorInfoList: vibrator.VibratorInfo[] = vibrator.getVibratorInfoSync(vibratorParam); + console.log(`vibratorInfoList: ${JSON.stringify(vibratorInfoList)}`); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); + } + ``` + +3. Start vibration with the specified effect and attribute. Scenario 1: Trigger vibration with the specified duration. @@ -276,7 +316,7 @@ The following requirements must be met: } ``` -3. Stop vibration. +4. Stop vibration. Method 1: Stop vibration in the specified mode. This method is invalid for custom vibration. @@ -343,11 +383,65 @@ The following requirements must be met: } ``` + Method 3: Stop vibration of the specified device. -## Samples + ```ts + import { vibrator } from '@kit.SensorServiceKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + const vibratorInfoParam: vibrator.VibratorInfoParam = { + deviceId: 1 // The device ID must be the one that actually exists. + } + try { + vibrator.stopVibration(vibratorInfoParam).then(() => { + console.info('Succeed in stopping vibration'); + }, (error: BusinessError) => { + console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); + }); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); + } + ``` -The following sample is provided to help you better understand how to develop vibrators: -- [Vibrator (ArkTS, API version 9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/DeviceManagement/Vibrator/BasicVibration) +5. Enable listening for vibrator status changes. -- [CustomHaptic (ArkTS, Full SDK, API version 10)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/DeviceManagement/Vibrator/CustomHaptic) + Enable listening. + ```ts + import { vibrator } from '@kit.SensorServiceKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + // Callback + const vibratorStateChangeCallback = (data: vibrator.VibratorStatusEvent) => { + console.log('vibrator state callback info:', JSON.stringify(data)); + } + + try { + // Subscribe to vibratorStateChange events. + vibrator.on('vibratorStateChange', vibratorStateChangeCallback); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); + } + ``` + + Disable listening. The specified callback must be the same as that passed to the **on** API. + ```ts + import { vibrator } from '@kit.SensorServiceKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + // Callback + const vibratorStateChangeCallback = (data: vibrator.VibratorStatusEvent) => { + console.log('vibrator state callback info:', JSON.stringify(data)); + } + try { + // Unsubscribe from specified vibratorStateChange events. + vibrator.off('vibratorStateChange', vibratorStateChangeCallback); + // Unsubscribe from all vibratorStateChange events. + // vibrator.off('vibratorStateChange'); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); + } + ``` diff --git a/en/application-dev/reference/apis-sensor-service-kit/_sensor.md b/en/application-dev/reference/apis-sensor-service-kit/_sensor.md index 6a965a19b1cd5a079e729a52a140f1e9376bdc35..74158a0b6eb8c262a9eea4620d99343fbdfbc345 100644 --- a/en/application-dev/reference/apis-sensor-service-kit/_sensor.md +++ b/en/application-dev/reference/apis-sensor-service-kit/_sensor.md @@ -298,6 +298,38 @@ Creates a [Sensor_Subscriber](#sensor_subscriber) instance. Returns the pointer to the [Sensor_Subscriber](#sensor_subscriber) instances if the operation is successful; returns **NULL** otherwise. +**Example** + +For details about the development procedure, see [Sensor Development](../../device/sensor/sensor-guidelines-capi.md). + + ```c + #include "sensors/oh_sensor.h" + #include "napi/native_api.h" + #include "hilog/log.h" + + const int SENSOR_LOG_DOMAIN = 0xD002700; + const char *TAG = "[Sensor]"; + + static napi_value CreateSubscriber(napi_env env, napi_callback_info info) { + Sensor_Result ret; + // Create a Sensor_Subscriber instance. + Sensor_Subscriber *subscriberTemp = OH_Sensor_CreateSubscriber(); + if (subscriberTemp == nullptr) { + OH_LOG_Print(LOG_APP, LOG_ERROR, SENSOR_LOG_DOMAIN, TAG, "OH_Sensor_CreateSubscriber failed"); + ret = SENSOR_SERVICE_EXCEPTION; + } else { + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "OH_Sensor_CreateSubscriber successful"); + ret = SENSOR_SUCCESS; + } + // Destroy the Sensor_Subscriber instance when it is no longer needed. + if (subscriberTemp != nullptr) { + OH_Sensor_DestroySubscriber(subscriberTemp); + } + napi_value result; + napi_create_int32(env, ret, &result); + return result; + } + ``` ### OH_Sensor_CreateSubscriptionAttribute() @@ -314,6 +346,38 @@ Creates a [Sensor_SubscriptionAttribute](#sensor_subscriptionattribute) instance Returns the pointer to the [Sensor_SubscriptionAttribute](#sensor_subscriptionattribute) instances if the operation is successful; returns **NULL** otherwise. +**Example** + +For details about the development procedure, see [Sensor Development](../../device/sensor/sensor-guidelines-capi.md). + + ```c + #include "sensors/oh_sensor.h" + #include "napi/native_api.h" + #include "hilog/log.h" + + const int SENSOR_LOG_DOMAIN = 0xD002700; + const char *TAG = "[Sensor]"; + + static napi_value CreateSubscriptionAttribute(napi_env env, napi_callback_info info) { + Sensor_Result ret; + // Create a Sensor_SubscriptionAttribute instance. + Sensor_SubscriptionAttribute *attr = OH_Sensor_CreateSubscriptionAttribute(); + if (attr == nullptr) { + OH_LOG_Print(LOG_APP, LOG_ERROR, SENSOR_LOG_DOMAIN, TAG, "OH_Sensor_CreateSubscriptionAttribute failed"); + ret = SENSOR_SERVICE_EXCEPTION; + } else { + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "OH_Sensor_CreateSubscriptionAttribute successful"); + ret = SENSOR_SUCCESS; + } + // Destroy the Sensor_SubscriptionAttribute instance when it is no longer needed. + if (attr != nullptr) { + OH_Sensor_DestroySubscriptionAttribute(attr); + } + napi_value result; + napi_create_int32(env, ret, &result); + return result; + } + ``` ### OH_Sensor_CreateSubscriptionId() @@ -330,6 +394,38 @@ Creates a [Sensor_SubscriptionId](#sensor_subscriptionid) instance. Returns the pointer to the [Sensor_SubscriptionId](#sensor_subscriptionid) instances if the operation is successful; returns **NULL** otherwise. +**Example** + +For details about the development procedure, see [Sensor Development](../../device/sensor/sensor-guidelines-capi.md). + + ```c + #include "sensors/oh_sensor.h" + #include "napi/native_api.h" + #include "hilog/log.h" + + const int SENSOR_LOG_DOMAIN = 0xD002700; + const char *TAG = "[Sensor]"; + + static napi_value CreateSubscriptionId(napi_env env, napi_callback_info info) { + Sensor_Result ret; + // Create a Sensor_SubscriptionId instance. + Sensor_SubscriptionId *id = OH_Sensor_CreateSubscriptionId(); + if (id == nullptr) { + OH_LOG_Print(LOG_APP, LOG_ERROR, SENSOR_LOG_DOMAIN, TAG, "OH_Sensor_CreateSubscriptionId failed"); + ret = SENSOR_SERVICE_EXCEPTION; + } else { + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "OH_Sensor_CreateSubscriptionId successful"); + ret = SENSOR_SUCCESS; + } + // Destroy the Sensor_SubscriptionId instance when it is no longer needed. + if (id != nullptr) { + OH_Sensor_DestroySubscriptionId(id); + } + napi_value result; + napi_create_int32(env, ret, &result); + return result; + } + ``` ### OH_Sensor_DestroyInfos() @@ -375,6 +471,33 @@ Destroys a [Sensor_Subscriber](#sensor_subscriber) instance and reclaims memory. Returns **SENSOR_SUCCESS** if the operation is successful; returns an error code defined in [Sensor_Result](#sensor_result) otherwise. +**Example** + +For details about the development procedure, see [Sensor Development](../../device/sensor/sensor-guidelines-capi.md). + + ```c + #include "sensors/oh_sensor.h" + #include "napi/native_api.h" + #include "hilog/log.h" + + const int SENSOR_LOG_DOMAIN = 0xD002700; + const char *TAG = "[Sensor]"; + + static napi_value DestroySubscriber(napi_env env, napi_callback_info info) { + // Create a Sensor_Subscriber instance. + Sensor_Subscriber *subscriberTemp = OH_Sensor_CreateSubscriber(); + // Destroy the Sensor_Subscriber instance when it is no longer needed. + int32_t ret = OH_Sensor_DestroySubscriber(subscriberTemp); + if (ret != SENSOR_SUCCESS) { + OH_LOG_Print(LOG_APP, LOG_ERROR, SENSOR_LOG_DOMAIN, TAG, "OH_Sensor_DestroySubscriber failed"); + } else { + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "OH_Sensor_DestroySubscriber successful"); + } + napi_value result; + napi_create_int32(env, ret, &result); + return result; + } + ``` ### OH_Sensor_DestroySubscriptionAttribute() @@ -397,6 +520,33 @@ Destroys a [Sensor_SubscriptionAttribute](#sensor_subscriptionattribute) instanc Returns **SENSOR_SUCCESS** if the operation is successful; returns an error code defined in [Sensor_Result](#sensor_result) otherwise. +**Example** + +For details about the development procedure, see [Sensor Development](../../device/sensor/sensor-guidelines-capi.md). + + ```c + #include "sensors/oh_sensor.h" + #include "napi/native_api.h" + #include "hilog/log.h" + + const int SENSOR_LOG_DOMAIN = 0xD002700; + const char *TAG = "[Sensor]"; + + static napi_value DestroySubscriptionAttribute(napi_env env, napi_callback_info info) { + // Create a **Sensor_SubscriptionAttribute** instance. + Sensor_SubscriptionAttribute *attr = OH_Sensor_CreateSubscriptionAttribute(); + // Destroy the Sensor_SubscriptionAttribute instance when it is no longer needed. + int32_t ret = OH_Sensor_DestroySubscriptionAttribute(attr); + if (ret != SENSOR_SUCCESS) { + OH_LOG_Print(LOG_APP, LOG_ERROR, SENSOR_LOG_DOMAIN, TAG, "OH_Sensor_DestroySubscriptionAttribute failed"); + } else { + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "OH_Sensor_DestroySubscriptionAttribute successful"); + } + napi_value result; + napi_create_int32(env, ret, &result); + return result; + } + ``` ### OH_Sensor_DestroySubscriptionId() @@ -419,6 +569,33 @@ Destroys a [Sensor_SubscriptionId](#sensor_subscriptionid) instance and reclaims Returns **SENSOR_SUCCESS** if the operation is successful; returns an error code defined in [Sensor_Result](#sensor_result) otherwise. +**Example** + +For details about the development procedure, see [Sensor Development](../../device/sensor/sensor-guidelines-capi.md). + + ```c + #include "sensors/oh_sensor.h" + #include "napi/native_api.h" + #include "hilog/log.h" + + const int SENSOR_LOG_DOMAIN = 0xD002700; + const char *TAG = "[Sensor]"; + + static napi_value DestroySubscriptionId(napi_env env, napi_callback_info info) { + // Create a Sensor_SubscriptionId instance. + Sensor_SubscriptionId *id = OH_Sensor_CreateSubscriptionId(); + // Destroy the Sensor_SubscriptionId instance when it is no longer needed. + int32_t ret = OH_Sensor_DestroySubscriptionId(id); + if (ret != SENSOR_SUCCESS) { + OH_LOG_Print(LOG_APP, LOG_ERROR, SENSOR_LOG_DOMAIN, TAG, "OH_Sensor_DestroySubscriptionId failed"); + } else { + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "OH_Sensor_DestroySubscriptionId successful"); + } + napi_value result; + napi_create_int32(env, ret, &result); + return result; + } + ``` ### OH_Sensor_GetInfos() @@ -466,10 +643,124 @@ Subscribe to sensor data. The system will report sensor data to the subscriber a Returns **SENSOR_SUCCESS** if the operation is successful; returns an error code defined in [Sensor_Result](#sensor_result) otherwise. -**Required Permissions** +**Permission**: ohos.permission.ACCELEROMETER, ohos.permission.GYROSCOPE, ohos.permission.ACTIVITY_MOTION, or ohos.permission.READ_HEALTH_DATA +**Example** + +For details about the development procedure, see [Sensor Development](../../device/sensor/sensor-guidelines-capi.md). + + ```c + #include "sensors/oh_sensor.h" + #include "napi/native_api.h" + #include "hilog/log.h" + #include + + const int SENSOR_LOG_DOMAIN = 0xD002700; + const char *TAG = "[Sensor]"; + constexpr Sensor_Type SENSOR_ID { SENSOR_TYPE_ACCELEROMETER }; + constexpr uint32_t SENSOR_NAME_LENGTH_MAX = 64; + constexpr int64_t SENSOR_SAMPLE_PERIOD = 200000000; + constexpr int32_t SLEEP_TIME_MS = 1000; + constexpr int64_t INVALID_VALUE = -1; + constexpr float INVALID_RESOLUTION = -1.0F; + Sensor_Subscriber *g_user = nullptr; + + // Define the callback. + void SensorDataCallbackImpl(Sensor_Event *event) { + if (event == nullptr) { + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "event is null"); + return; + } + int64_t timestamp = INVALID_VALUE; + // Obtain the timestamp of sensor data. + int32_t ret = OH_SensorEvent_GetTimestamp(event, ×tamp); + if (ret != SENSOR_SUCCESS) { + return; + } + Sensor_Type sensorType; + // Obtain the sensor type. + ret = OH_SensorEvent_GetType(event, &sensorType); + if (ret != SENSOR_SUCCESS) { + return; + } + Sensor_Accuracy accuracy = SENSOR_ACCURACY_UNRELIABLE; + // Obtain the accuracy of sensor data. + ret = OH_SensorEvent_GetAccuracy(event, &accuracy); + if (ret != SENSOR_SUCCESS) { + return; + } + float *data = nullptr; + uint32_t length = 0; + // Obtain sensor data. + ret = OH_SensorEvent_GetData(event, &data, &length); + if (ret != SENSOR_SUCCESS) { + return; + } + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "sensorType:%{public}d, dataLen:%{public}d, accuracy:%{public}d", sensorType, length, accuracy); + for (uint32_t i = 0; i < length; ++i) { + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "accData[%{public}d]:%{public}f", i, data[i]); + } + } + + static napi_value Subscribe(napi_env env, napi_callback_info info) { + // Create a Sensor_Subscriber instance. + g_user = OH_Sensor_CreateSubscriber(); + // Set the callback used to return sensor data. + int32_t ret = OH_SensorSubscriber_SetCallback(g_user, SensorDataCallbackImpl); + if (ret != SENSOR_SUCCESS) { + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "OH_SensorSubscriber_SetCallback failed"); + return nullptr; + } + // Create a Sensor_SubscriptionId instance. + Sensor_SubscriptionId *id = OH_Sensor_CreateSubscriptionId(); + // Set the sensor type. For example, if you use SENSOR_TYPE_ACCELEROMETER, you need to request the ohos.permission.ACCELEROMETER permission. + // Configure the required permission as instructed in step 2 in the Sensor Development. + ret = OH_SensorSubscriptionId_SetType(id, SENSOR_ID); + if (ret != SENSOR_SUCCESS) { + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "OH_SensorSubscriptionId_SetType failed"); + return nullptr; + } + // Create a Sensor_SubscriptionAttribute instance. + Sensor_SubscriptionAttribute *attr = OH_Sensor_CreateSubscriptionAttribute(); + // Set the sensor data reporting interval. + ret = OH_SensorSubscriptionAttribute_SetSamplingInterval(attr, SENSOR_SAMPLE_PERIOD); + if (ret != SENSOR_SUCCESS) { + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "OH_SensorSubscriptionAttribute_SetSamplingInterval failed"); + return nullptr; + } + // Subscribe to sensor data. + ret = OH_Sensor_Subscribe(id, attr, g_user); + if (ret != SENSOR_SUCCESS) { + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "OH_Sensor_Subscribe failed"); + return nullptr; + } + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "OH_Sensor_Subscribe successful"); + std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIME_MS)); + // Unsubscribe from sensor data. + ret = OH_Sensor_Unsubscribe(id, g_user); + if (ret != SENSOR_SUCCESS) { + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "OH_Sensor_Unsubscribe failed"); + return nullptr; + } + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "OH_Sensor_Unsubscribe successful"); + if (id != nullptr) { + // Destroy the Sensor_SubscriptionId instance. + OH_Sensor_DestroySubscriptionId(id); + } + if (attr != nullptr) { + // Destroy the Sensor_SubscriptionAttribute instance. + OH_Sensor_DestroySubscriptionAttribute(attr); + } + if (g_user != nullptr) { + // Destroy the Sensor_Subscriber instance and reclaim memory. + OH_Sensor_DestroySubscriber(g_user); + g_user = nullptr; + } + return nullptr; + } + ``` ### OH_Sensor_Unsubscribe() @@ -493,10 +784,124 @@ Unsubscribes from sensor data. To unsubscribe from data of acceleration sensors, Returns **SENSOR_SUCCESS** if the operation is successful; returns an error code defined in [Sensor_Result](#sensor_result) otherwise. -**Required Permissions** +**Permission**: ohos.permission.ACCELEROMETER, ohos.permission.GYROSCOPE, ohos.permission.ACTIVITY_MOTION, or ohos.permission.READ_HEALTH_DATA +**Example** + +For details about the development procedure, see [Sensor Development](../../device/sensor/sensor-guidelines-capi.md). + + ```c + #include "sensors/oh_sensor.h" + #include "napi/native_api.h" + #include "hilog/log.h" + #include + + const int SENSOR_LOG_DOMAIN = 0xD002700; + const char *TAG = "[Sensor]"; + constexpr Sensor_Type SENSOR_ID { SENSOR_TYPE_ACCELEROMETER }; + constexpr uint32_t SENSOR_NAME_LENGTH_MAX = 64; + constexpr int64_t SENSOR_SAMPLE_PERIOD = 200000000; + constexpr int32_t SLEEP_TIME_MS = 1000; + constexpr int64_t INVALID_VALUE = -1; + constexpr float INVALID_RESOLUTION = -1.0F; + Sensor_Subscriber *g_user = nullptr; + + // Define the callback. + void SensorDataCallbackImpl(Sensor_Event *event) { + if (event == nullptr) { + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "event is null"); + return; + } + int64_t timestamp = INVALID_VALUE; + // Obtain the timestamp of sensor data. + int32_t ret = OH_SensorEvent_GetTimestamp(event, ×tamp); + if (ret != SENSOR_SUCCESS) { + return; + } + Sensor_Type sensorType; + // Obtain the sensor type. + ret = OH_SensorEvent_GetType(event, &sensorType); + if (ret != SENSOR_SUCCESS) { + return; + } + Sensor_Accuracy accuracy = SENSOR_ACCURACY_UNRELIABLE; + // Obtain the accuracy of sensor data. + ret = OH_SensorEvent_GetAccuracy(event, &accuracy); + if (ret != SENSOR_SUCCESS) { + return; + } + float *data = nullptr; + uint32_t length = 0; + // Obtain sensor data. + ret = OH_SensorEvent_GetData(event, &data, &length); + if (ret != SENSOR_SUCCESS) { + return; + } + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "sensorType:%{public}d, dataLen:%{public}d, accuracy:%{public}d", sensorType, length, accuracy); + for (uint32_t i = 0; i < length; ++i) { + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "accData[%{public}d]:%{public}f", i, data[i]); + } + } + + static napi_value Unsubscribe(napi_env env, napi_callback_info info) { + // Create a Sensor_Subscriber instance. + g_user = OH_Sensor_CreateSubscriber(); + // Set the callback used to return sensor data. + int32_t ret = OH_SensorSubscriber_SetCallback(g_user, SensorDataCallbackImpl); + if (ret != SENSOR_SUCCESS) { + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "OH_SensorSubscriber_SetCallback failed"); + return nullptr; + } + // Create a Sensor_SubscriptionId instance. + Sensor_SubscriptionId *id = OH_Sensor_CreateSubscriptionId(); + // Set the sensor type. For example, if you use SENSOR_TYPE_ACCELEROMETER, you need to request the ohos.permission.ACCELEROMETER permission. + // Configure the required permission as instructed in step 2 in the Sensor Development. + ret = OH_SensorSubscriptionId_SetType(id, SENSOR_ID); + if (ret != SENSOR_SUCCESS) { + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "OH_SensorSubscriptionId_SetType failed"); + return nullptr; + } + // Create a **Sensor_SubscriptionAttribute** instance. + Sensor_SubscriptionAttribute *attr = OH_Sensor_CreateSubscriptionAttribute(); + // Set the sensor data reporting interval. + ret = OH_SensorSubscriptionAttribute_SetSamplingInterval(attr, SENSOR_SAMPLE_PERIOD); + if (ret != SENSOR_SUCCESS) { + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "OH_SensorSubscriptionAttribute_SetSamplingInterval failed"); + return nullptr; + } + // Subscribe to sensor data. + ret = OH_Sensor_Subscribe(id, attr, g_user); + if (ret != SENSOR_SUCCESS) { + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "OH_Sensor_Subscribe failed"); + return nullptr; + } + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "OH_Sensor_Subscribe successful"); + std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIME_MS)); + // Unsubscribe from sensor data. + ret = OH_Sensor_Unsubscribe(id, g_user); + if (ret != SENSOR_SUCCESS) { + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "OH_Sensor_Unsubscribe failed"); + return nullptr; + } + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "OH_Sensor_Unsubscribe successful"); + if (id != nullptr) { + // Destroy the Sensor_SubscriptionId instance. + OH_Sensor_DestroySubscriptionId(id); + } + if (attr != nullptr) { + // Destroy the Sensor_SubscriptionAttribute instance. + OH_Sensor_DestroySubscriptionAttribute(attr); + } + if (g_user != nullptr) { + // Destroy the Sensor_Subscriber instance and reclaim memory. + OH_Sensor_DestroySubscriber(g_user); + g_user = nullptr; + } + return nullptr; + } + ``` ### OH_SensorEvent_GetAccuracy() @@ -574,6 +979,121 @@ Obtains sensor data. The data length and content depend on the sensor type. The Returns **SENSOR_SUCCESS** if the operation is successful; returns an error code defined in [Sensor_Result](#sensor_result) otherwise. +**Example** + +For details about the development procedure, see [Sensor Development](../../device/sensor/sensor-guidelines-capi.md). + + ```c + #include "sensors/oh_sensor.h" + #include "napi/native_api.h" + #include "hilog/log.h" + #include + + const int SENSOR_LOG_DOMAIN = 0xD002700; + const char *TAG = "[Sensor]"; + constexpr Sensor_Type SENSOR_ID { SENSOR_TYPE_ACCELEROMETER }; + constexpr uint32_t SENSOR_NAME_LENGTH_MAX = 64; + constexpr int64_t SENSOR_SAMPLE_PERIOD = 200000000; + constexpr int32_t SLEEP_TIME_MS = 1000; + constexpr int64_t INVALID_VALUE = -1; + constexpr float INVALID_RESOLUTION = -1.0F; + Sensor_Subscriber *g_user = nullptr; + + // Define the callback. + void SensorDataCallbackImpl(Sensor_Event *event) { + if (event == nullptr) { + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "event is null"); + return; + } + int64_t timestamp = INVALID_VALUE; + // Obtain the timestamp of sensor data. + int32_t ret = OH_SensorEvent_GetTimestamp(event, ×tamp); + if (ret != SENSOR_SUCCESS) { + return; + } + Sensor_Type sensorType; + // Obtain the sensor type. + ret = OH_SensorEvent_GetType(event, &sensorType); + if (ret != SENSOR_SUCCESS) { + return; + } + Sensor_Accuracy accuracy = SENSOR_ACCURACY_UNRELIABLE; + // Obtain the accuracy of sensor data. + ret = OH_SensorEvent_GetAccuracy(event, &accuracy); + if (ret != SENSOR_SUCCESS) { + return; + } + float *data = nullptr; + uint32_t length = 0; + // Obtain sensor data. + ret = OH_SensorEvent_GetData(event, &data, &length); + if (ret != SENSOR_SUCCESS) { + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "OH_SensorEvent_GetData failed"); + return; + } + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "OH_SensorEvent_GetData successful"); + for (uint32_t i = 0; i < length; ++i) { + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "accData[%{public}d]:%{public}f", i, data[i]); + } + } + + static napi_value SensorEventGetData(napi_env env, napi_callback_info info) { + // Create a Sensor_Subscriber instance. + g_user = OH_Sensor_CreateSubscriber(); + // Set the callback used to return sensor data. + int32_t ret = OH_SensorSubscriber_SetCallback(g_user, SensorDataCallbackImpl); + if (ret != SENSOR_SUCCESS) { + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "OH_SensorSubscriber_SetCallback failed"); + return nullptr; + } + // Create a Sensor_SubscriptionId instance. + Sensor_SubscriptionId *id = OH_Sensor_CreateSubscriptionId(); + // Set the sensor type. For example, if you use SENSOR_TYPE_ACCELEROMETER, you need to request the ohos.permission.ACCELEROMETER permission. + // Configure the required permission as instructed in step 2 in the Sensor Development. + ret = OH_SensorSubscriptionId_SetType(id, SENSOR_ID); + if (ret != SENSOR_SUCCESS) { + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "OH_SensorSubscriptionId_SetType failed"); + return nullptr; + } + // Create a **Sensor_SubscriptionAttribute** instance. + Sensor_SubscriptionAttribute *attr = OH_Sensor_CreateSubscriptionAttribute(); + // Set the sensor data reporting interval. + ret = OH_SensorSubscriptionAttribute_SetSamplingInterval(attr, SENSOR_SAMPLE_PERIOD); + if (ret != SENSOR_SUCCESS) { + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "OH_SensorSubscriptionAttribute_SetSamplingInterval failed"); + return nullptr; + } + // Subscribe to sensor data. + ret = OH_Sensor_Subscribe(id, attr, g_user); + if (ret != SENSOR_SUCCESS) { + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "OH_Sensor_Subscribe failed"); + return nullptr; + } + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "OH_Sensor_Subscribe successful"); + std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIME_MS)); + // Unsubscribe from sensor data. + ret = OH_Sensor_Unsubscribe(id, g_user); + if (ret != SENSOR_SUCCESS) { + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "OH_Sensor_Unsubscribe failed"); + return nullptr; + } + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "OH_Sensor_Unsubscribe successful"); + if (id != nullptr) { + // Destroy the Sensor_SubscriptionId instance. + OH_Sensor_DestroySubscriptionId(id); + } + if (attr != nullptr) { + // Destroy the Sensor_SubscriptionAttribute instance. + OH_Sensor_DestroySubscriptionAttribute(attr); + } + if (g_user != nullptr) { + // Destroy the Sensor_Subscriber instance and reclaim memory. + OH_Sensor_DestroySubscriber(g_user); + g_user = nullptr; + } + return nullptr; + } + ``` ### OH_SensorEvent_GetTimestamp() @@ -806,6 +1326,73 @@ Sets a callback function to report sensor data. Returns **SENSOR_SUCCESS** if the operation is successful; returns an error code defined in [Sensor_Result](#sensor_result) otherwise. +**Example** + +For details about the development procedure, see [Sensor Development](../../device/sensor/sensor-guidelines-capi.md). + + ```c + #include "sensors/oh_sensor.h" + #include "napi/native_api.h" + #include "hilog/log.h" + + const int SENSOR_LOG_DOMAIN = 0xD002700; + const char *TAG = "[Sensor]"; + constexpr int64_t INVALID_VALUE = -1; + + void SensorDataCallbackImpl(Sensor_Event *event) { + if (event == nullptr) { + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "event is null"); + return; + } + int64_t timestamp = INVALID_VALUE; + // Obtain the timestamp of sensor data. + int32_t ret = OH_SensorEvent_GetTimestamp(event, ×tamp); + if (ret != SENSOR_SUCCESS) { + return; + } + Sensor_Type sensorType; + // Obtain the sensor type. + ret = OH_SensorEvent_GetType(event, &sensorType); + if (ret != SENSOR_SUCCESS) { + return; + } + Sensor_Accuracy accuracy = SENSOR_ACCURACY_UNRELIABLE; + // Obtain the accuracy of sensor data. + ret = OH_SensorEvent_GetAccuracy(event, &accuracy); + if (ret != SENSOR_SUCCESS) { + return; + } + float *data = nullptr; + uint32_t length = 0; + // Obtain sensor data. + ret = OH_SensorEvent_GetData(event, &data, &length); + if (ret != SENSOR_SUCCESS) { + return; + } + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "sensorType:%{public}d, dataLen:%{public}d, accuracy:%{public}d", sensorType, length, accuracy); + for (uint32_t i = 0; i < length; ++i) { + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "data[%{public}d]:%{public}f", i, data[i]); + } + } + + static napi_value SensorSubscriberSetCallback(napi_env env, napi_callback_info info) { + // Create a Sensor_Subscriber instance. + Sensor_Subscriber *subscriberTemp = OH_Sensor_CreateSubscriber(); + int32_t ret = OH_SensorSubscriber_SetCallback(subscriberTemp, SensorDataCallbackImpl); + if (ret != SENSOR_SUCCESS) { + OH_LOG_Print(LOG_APP, LOG_ERROR, SENSOR_LOG_DOMAIN, TAG, "OH_SensorSubscriber_SetCallback failed"); + } else { + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "OH_SensorSubscriber_SetCallback successful"); + } + // Destroy the Sensor_Subscriber instance when it is no longer needed. + if (subscriberTemp != nullptr) { + OH_Sensor_DestroySubscriber(subscriberTemp); + } + napi_value result; + napi_create_int32(env, ret, &result); + return result; + } + ``` ### OH_SensorSubscriptionAttribute_GetSamplingInterval() @@ -852,6 +1439,37 @@ Sets the interval for reporting sensor data. Returns **SENSOR_SUCCESS** if the operation is successful; returns an error code defined in [Sensor_Result](#sensor_result) otherwise. +**Example** + +For details about the development procedure, see [Sensor Development](../../device/sensor/sensor-guidelines-capi.md). + + ```c + #include "sensors/oh_sensor.h" + #include "napi/native_api.h" + #include "hilog/log.h" + + const int SENSOR_LOG_DOMAIN = 0xD002700; + const char *TAG = "[Sensor]"; + + static napi_value SensorSubscriptionAttributeSetSamplingInterval(napi_env env, napi_callback_info info) { + // Create a **Sensor_SubscriptionAttribute** instance. + Sensor_SubscriptionAttribute *attr = OH_Sensor_CreateSubscriptionAttribute(); + int64_t sensorSamplePeriod = 200000000; + int32_t ret = OH_SensorSubscriptionAttribute_SetSamplingInterval(attr, sensorSamplePeriod); + if (ret != SENSOR_SUCCESS) { + OH_LOG_Print(LOG_APP, LOG_ERROR, SENSOR_LOG_DOMAIN, TAG, "OH_SensorSubscriptionAttribute_SetSamplingInterval failed"); + } else { + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "OH_SensorSubscriptionAttribute_SetSamplingInterval successful"); + } + // Destroy the Sensor_SubscriptionAttribute instance when it is no longer needed. + if (attr != nullptr) { + OH_Sensor_DestroySubscriptionAttribute(attr); + } + napi_value result; + napi_create_int32(env, ret, &result); + return result; + } + ``` ### OH_SensorSubscriptionId_GetType() @@ -897,3 +1515,35 @@ Sets the sensor type. **Returns** Returns **SENSOR_SUCCESS** if the operation is successful; returns an error code defined in [Sensor_Result](#sensor_result) otherwise. + +**Example** + +For details about the development procedure, see [Sensor Development](../../device/sensor/sensor-guidelines-capi.md). + + ```c + #include "sensors/oh_sensor.h" + #include "napi/native_api.h" + #include "hilog/log.h" + + const int SENSOR_LOG_DOMAIN = 0xD002700; + const char *TAG = "[Sensor]"; + + static napi_value SensorSubscriptionIdSetType(napi_env env, napi_callback_info info) { + // Create a Sensor_SubscriptionId instance. + Sensor_SubscriptionId *id = OH_Sensor_CreateSubscriptionId(); + Sensor_Type sensorId { SENSOR_TYPE_ACCELEROMETER }; + int32_t ret = OH_SensorSubscriptionId_SetType(id, sensorId); + if (ret != SENSOR_SUCCESS) { + OH_LOG_Print(LOG_APP, LOG_ERROR, SENSOR_LOG_DOMAIN, TAG, "OH_SensorSubscriptionId_SetType failed"); + } else { + OH_LOG_Print(LOG_APP, LOG_INFO, SENSOR_LOG_DOMAIN, TAG, "OH_SensorSubscriptionId_SetType successful"); + } + // Destroy the Sensor_SubscriptionId instance when it is no longer needed. + if (id != nullptr) { + OH_Sensor_DestroySubscriptionId(id); + } + napi_value result; + napi_create_int32(env, ret, &result); + return result; + } + ``` diff --git a/en/application-dev/reference/apis-sensor-service-kit/errorcode-sensor.md b/en/application-dev/reference/apis-sensor-service-kit/errorcode-sensor.md index 4612ba8e5b4a790638c2775c02b603d0d7b5fa99..c047ed9d8930967c26bd8ff52ade76d854da2168 100644 --- a/en/application-dev/reference/apis-sensor-service-kit/errorcode-sensor.md +++ b/en/application-dev/reference/apis-sensor-service-kit/errorcode-sensor.md @@ -4,7 +4,7 @@ > > This topic describes only module-specific error codes. For details about universal error codes, see [Universal Error Codes](../errorcode-universal.md). -## 14500101 Service Exception +## 14500101 Service exception. **Error Message** @@ -12,7 +12,7 @@ Service exception. **Description** -This error code is reported if the HDI service is abnormal when the **on**, **once**, or **off** API of the sensor module is called. +This error code is reported if the HDI service is abnormal when the **on**, **once**, or **off** interface of the sensor module is called. **Possible Causes** @@ -21,7 +21,7 @@ The HDI service is abnormal. **Solution** 1. Retry the operation at a specified interval (for example, 1s) or at an exponential increase interval. -2. If the operation fails for three consecutive times, stop the retry. You can also attempt to obtain the sensor list to check for device availability. +2. If the operation fails for three consecutive times, stop the attempt. You can also attempt to obtain the sensor list to check for device availability. ## 14500102 Sensor Not Supported by the Device diff --git a/en/application-dev/reference/apis-sensor-service-kit/js-apis-sensor-sys.md b/en/application-dev/reference/apis-sensor-service-kit/js-apis-sensor-sys.md index df5a162b15f939c5b7d58a94415c748d84aec2cd..8f7c44cfdc7aefa8c72c1aeea4b1f9210782e8f8 100644 --- a/en/application-dev/reference/apis-sensor-service-kit/js-apis-sensor-sys.md +++ b/en/application-dev/reference/apis-sensor-service-kit/js-apis-sensor-sys.md @@ -126,10 +126,10 @@ Unsubscribes from data of the color sensor. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9).COLOR | Yes | Sensor type. The value is fixed at **SensorId.COLOR**. | -| callback | Callback<[ColorResponse](#colorresponse10)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| +| Name | Type | Mandatory| Description | +| -------- |--------------------------------------------------------| ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9).COLOR | Yes | Sensor type. The value is fixed at **SensorId.COLOR**. | +| callback | Callback<[ColorResponse](#colorresponse10)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| **Error codes** @@ -167,6 +167,84 @@ try { } ``` +### COLOR19+ + +off(type: SensorId.COLOR, sensorInfoParam?: SensorInfoParam, callback?: Callback<ColorResponse>): void + +Unsubscribes from data of the color sensor. + +**System capability**: SystemCapability.Sensors.Sensor + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- |--------------------------------------------------------| ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9).COLOR | Yes | Sensor type. The value is fixed at **SensorId.COLOR**. | +| sensorInfoParam | [SensorInfoParam](#sensorinfoparam19) | No| Sensor parameters, including **deviceId** and **sensorIndex**.| +| callback | Callback<[ColorResponse](#colorresponse10)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 202 | Permission check failed. A non-system application uses the system API. | +| 14500101 | Service exception.Possible causes:1. Sensor hdf service exception;2. Sensor service ipc exception;3.Sensor data channel exception. | + +**Example** + +```ts +import { sensor } from '@kit.SensorServiceKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +enum Ret { OK, Failed = -1 } + +// Sensor callback +const sensorCallback = (response: sensor.ColorResponse) => { + console.log(`callback response: ${JSON.stringify(response)}`); +} +// Sensor type +const sensorType = sensor.SensorId.COLOR; +const sensorInfoParam: sensor.SensorInfoParam = {}; + +function sensorSubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + // Query all sensors. + const sensorList: sensor.Sensor[] = sensor.getSensorListSync(); + if (!sensorList.length) { + return Ret.Failed; + } + // Obtain the target sensor based on the actual service logic. + const targetSensor: sensor.Sensor = sensorList[0]; + sensorInfoParam.deviceId = targetSensor.deviceId ?? -1; + sensorInfoParam.sensorIndex = targetSensor.sensorIndex ?? -1; + // Subscribe to sensor events. + sensor.on(sensorType, sensorCallback, { sensorInfoParam }); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.on. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} + +function sensorUnsubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + sensor.off(sensorType, sensorInfoParam, sensorCallback); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.off. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} +``` + ### SAR10+ off(type: SensorId.SAR, callback?: Callback<SarResponse>): void @@ -220,6 +298,84 @@ try { } ``` +### SAR19+ + +off(type: SensorId.SAR, sensorInfoParam?: SensorInfoParam, callback?: Callback<SarResponse>): void + +Unsubscribes from data of the SAR sensor. + +**System capability**: SystemCapability.Sensors.Sensor + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9).SAR | Yes | Sensor type. The value is fixed at **SensorId.SAR**. | +| sensorInfoParam | [SensorInfoParam](#sensorinfoparam19) | No| Sensor parameters, including **deviceId** and **sensorIndex**.| +| callback | Callback<[SarResponse](#sarresponse10)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message | +| -------- |-----------------------------------------------------------------------------------------------------------------------------------------| +| 202 | Permission check failed. A non-system application uses the system API. | +| 14500101 | Service exception.Possible causes:1. Sensor hdf service exception;2. Sensor service ipc exception;3.Sensor data channel exception. | + +**Example** + +```ts +import { sensor } from '@kit.SensorServiceKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +enum Ret { OK, Failed = -1 } + +// Sensor callback +const sensorCallback = (response: sensor.SarResponse) => { + console.log(`callback response: ${JSON.stringify(response)}`); +} +// Sensor type +const sensorType = sensor.SensorId.SAR; +const sensorInfoParam: sensor.SensorInfoParam = {}; + +function sensorSubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + // Query all sensors. + const sensorList: sensor.Sensor[] = sensor.getSensorListSync(); + if (!sensorList.length) { + return Ret.Failed; + } + // Obtain the target sensor based on the actual service logic. + const targetSensor: sensor.Sensor = sensorList[0]; + sensorInfoParam.deviceId = targetSensor.deviceId ?? -1; + sensorInfoParam.sensorIndex = targetSensor.sensorIndex ?? -1; + // Subscribe to sensor events. + sensor.on(sensorType, sensorCallback, { sensorInfoParam }); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.on. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} + +function sensorUnsubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + sensor.off(sensorType, sensorInfoParam, sensorCallback); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.off. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} +``` + ## SensorId9+ Enumerates the sensor types. @@ -229,7 +385,7 @@ Enumerates the sensor types. | Name | Value | Description | | ------------------- | ---- | ----------------------------------------------- | | COLOR10+ | 14 | Color sensor.
System API: This is a system API. | -| SAR10+ | 15 | Sodium Adsorption Ratio (SAR) sensor.
System API: This is a system API.| +| SAR10+ | 15 | SAR sensor.
System API: This is a system API.| ## ColorResponse10+ @@ -240,7 +396,7 @@ Describes the color sensor data. It extends from [Response](js-apis-sensor.md#re **System API**: This is a system API. -| Name | Type | Readable| Writable| Description | +| Name | Type | Read-Only| Optional| Description | | ---------------- | ------ | ---- | ---- | ----------------------------- | | lightIntensity | number | Yes | Yes | Intensity of light, in lux.| | colorTemperature | number | Yes | Yes | Color temperature, in Kelvin. | @@ -254,6 +410,19 @@ Describes the SAR sensor data. It extends from [Response](js-apis-sensor.md#resp **System API**: This is a system API. -| Name | Type | Readable| Writable| Description | +| Name | Type | Read-Only| Optional| Description | | --------------- | ------ | ---- | ---- | ------------------------------- | | absorptionRatio | number | Yes | Yes | Absorption ratio, in W/kg.| + + +## SensorInfoParam19+ + +Defines sensor parameters. + +**System capability**: SystemCapability.Sensors.Sensor + + +| Name| Type | Mandatory| Description | +| ------ | ---------------------- | ---- |-------------------------| +| deviceId | number | No | Device ID. The default value is **-1**, which indicates the local device. | +| sensorIndex | number | No | Sensor index. The default value is **0**, which indicates the default sensor on the device.| diff --git a/en/application-dev/reference/apis-sensor-service-kit/js-apis-sensor.md b/en/application-dev/reference/apis-sensor-service-kit/js-apis-sensor.md index 744ddaa14b7b927050f8e4a603869884f5c9717b..985d6ff58554e0868c62f75938ebf1fee7e6535d 100644 --- a/en/application-dev/reference/apis-sensor-service-kit/js-apis-sensor.md +++ b/en/application-dev/reference/apis-sensor-service-kit/js-apis-sensor.md @@ -686,6 +686,9 @@ try { on(type: SensorId.ORIENTATION, callback: Callback<OrientationResponse>, options?: Options): void Subscribes to data of the orientation sensor. +> **NOTE** +> +> Applications or services invoking this API can prompt users to use figure-8 calibration to improve the accuracy of the direction sensor. The sensor has a theoretical error of ±5 degrees, but the specific precision may vary depending on different driver implementations and algorithmic designs. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -1006,6 +1009,49 @@ try { } ``` +### sensorStatusChange19+ + +on(type: 'sensorStatusChange', callback: Callback<SensorStatusEvent>): void + +Enables listening for sensor status changes. This API asynchronously returns the result through a callback. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | +| sensorStatusChange | sensorStatusChange | Yes | Event type. The value **sensorStatusChange** indicates a sensor status change event. | +| callback | Callback<[SensorStatusEvent](#sensorstatusevent19)> | Yes | Callback used to return the sensor status change event.| + +**Error codes** + +For details about the error codes, see [Sensor Error Codes](errorcode-sensor.md) and [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 14500101 | Service exception.Possible causes:1. Sensor hdf service exception;2. Sensor service ipc exception;3.Sensor data channel exception. | + +**Example** + +```ts +import { sensor } from '@kit.SensorServiceKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +try { + sensor.on('sensorStatusChange', (data: sensor.SensorStatusEvent) => { + console.info('sensorStatusChange : ' + JSON.stringify(data)); + }); + setTimeout(() => { + sensor.off('sensorStatusChange'); + }, 5000); +} catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke on. Code: ${e.code}, message: ${e.message}`); +} +``` + + ## sensor.once9+ ### ACCELEROMETER9+ @@ -1918,10 +1964,10 @@ Unsubscribes from data of the acceleration sensor. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9).ACCELEROMETER | Yes | Sensor type. The value is fixed at **SensorId.ACCELEROMETER**. | -| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| +| Name | Type | Mandatory| Description | +|-------------------------------| ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9).ACCELEROMETER | Yes | Sensor type. The value is fixed at **SensorId.ACCELEROMETER**. | +| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| **Error codes** @@ -1959,6 +2005,86 @@ try { } ``` +### ACCELEROMETER19+ + +off(type: SensorId.ACCELEROMETER, sensorInfoParam?: SensorInfoParam, callback?: Callback<AccelerometerResponse>): void + +Unsubscribes from data of the acceleration sensor. + +**Required permissions**: ohos.permission.ACCELEROMETER + +**Atomic service API**: This API can be used in atomic services since API version 19. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +|-------------------------------| ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9).ACCELEROMETER | Yes | Sensor type. The value is fixed at **SensorId.ACCELEROMETER**. | +| sensorInfoParam | [SensorInfoParam](#sensorinfoparam19) | No| Sensor parameters, including **deviceId** and **sensorIndex**.| +| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 201 | Permission denied. | +| 14500101 | Service exception.Possible causes:1. Sensor hdf service exception;2. Sensor service ipc exception;3.Sensor data channel exception. | + +**Example** + +```ts +import { sensor } from '@kit.SensorServiceKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +enum Ret { OK, Failed = -1 } + +// Sensor callback +const sensorCallback = (response: sensor.AccelerometerResponse) => { + console.log(`callback response: ${JSON.stringify(response)}`); +} +// Sensor type +const sensorType = sensor.SensorId.ACCELEROMETER; +const sensorInfoParam: sensor.SensorInfoParam = {}; + +function sensorSubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + // Query all sensors. + const sensorList: sensor.Sensor[] = sensor.getSensorListSync(); + if (!sensorList.length) { + return Ret.Failed; + } + // Obtain the target sensor based on the actual service logic. + const targetSensor: sensor.Sensor = sensorList[0]; + sensorInfoParam.deviceId = targetSensor.deviceId ?? -1; + sensorInfoParam.sensorIndex = targetSensor.sensorIndex ?? -1; + // Subscribe to sensor events. + sensor.on(sensorType, sensorCallback, { sensorInfoParam }); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.on. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} + +function sensorUnsubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + sensor.off(sensorType, sensorInfoParam, sensorCallback); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.off. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} +``` + ### ACCELEROMETER_UNCALIBRATED9+ off(type: SensorId.ACCELEROMETER_UNCALIBRATED, callback?: Callback<AccelerometerUncalibratedResponse>): void @@ -2012,6 +2138,84 @@ try { } ``` +### ACCELEROMETER_UNCALIBRATED19+ + +off(type: SensorId.ACCELEROMETER_UNCALIBRATED, sensorInfoParam?: SensorInfoParam, callback?: Callback<AccelerometerUncalibratedResponse>): void + +Unsubscribes from data of the uncalibrated acceleration sensor. + +**Required permissions**: ohos.permission.ACCELEROMETER + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9).ACCELEROMETER_UNCALIBRATED | Yes | Sensor type. The value is fixed at **SensorId.ACCELEROMETER_UNCALIBRATED**. | +| sensorInfoParam | [SensorInfoParam](#sensorinfoparam19) | No| Sensor parameters, including **deviceId** and **sensorIndex**.| +| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 201 | Permission denied. | +| 14500101 | Service exception.Possible causes:1. Sensor hdf service exception;2. Sensor service ipc exception;3.Sensor data channel exception. | + +**Example** + +```ts +import { sensor } from '@kit.SensorServiceKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +enum Ret { OK, Failed = -1 } + +// Sensor callback +const sensorCallback = (response: sensor.AccelerometerUncalibratedResponse) => { + console.log(`callback response: ${JSON.stringify(response)}`); +} +// Sensor type +const sensorType = sensor.SensorId.ACCELEROMETER_UNCALIBRATED; +const sensorInfoParam: sensor.SensorInfoParam = {}; + +function sensorSubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + // Query all sensors. + const sensorList: sensor.Sensor[] = sensor.getSensorListSync(); + if (!sensorList.length) { + return Ret.Failed; + } + // Obtain the target sensor based on the actual service logic. + const targetSensor: sensor.Sensor = sensorList[0]; + sensorInfoParam.deviceId = targetSensor.deviceId ?? -1; + sensorInfoParam.sensorIndex = targetSensor.sensorIndex ?? -1; + // Subscribe to sensor events. + sensor.on(sensorType, sensorCallback, { sensorInfoParam }); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.on. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} + +function sensorUnsubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + sensor.off(sensorType, sensorInfoParam, sensorCallback); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.off. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} +``` + ### AMBIENT_LIGHT9+ off(type: SensorId.AMBIENT_LIGHT, callback?: Callback<LightResponse>): void @@ -2062,6 +2266,81 @@ try { } ``` +### AMBIENT_LIGHT19+ + +off(type: SensorId.AMBIENT_LIGHT, sensorInfoParam?: SensorInfoParam, callback?: Callback<LightResponse>): void + +Unsubscribes from data of the ambient light sensor. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9).AMBIENT_LIGHT | Yes | Sensor type. The value is fixed at **SensorId.AMBIENT_LIGHT**. | +| sensorInfoParam | [SensorInfoParam](#sensorinfoparam19) | No| Sensor parameters, including **deviceId** and **sensorIndex**.| +| callback | Callback<[LightResponse](#lightresponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 14500101 | Service exception.Possible causes:1. Sensor hdf service exception;2. Sensor service ipc exception;3.Sensor data channel exception. | + +**Example** + +```ts +import { sensor } from '@kit.SensorServiceKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +enum Ret { OK, Failed = -1 } + +// Sensor callback +const sensorCallback = (response: sensor.LightResponse) => { + console.log(`callback response: ${JSON.stringify(response)}`); +} +// Sensor type +const sensorType = sensor.SensorId.AMBIENT_LIGHT; +const sensorInfoParam: sensor.SensorInfoParam = {}; + +function sensorSubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + // Query all sensors. + const sensorList: sensor.Sensor[] = sensor.getSensorListSync(); + if (!sensorList.length) { + return Ret.Failed; + } + // Obtain the target sensor based on the actual service logic. + const targetSensor: sensor.Sensor = sensorList[0]; + sensorInfoParam.deviceId = targetSensor.deviceId ?? -1; + sensorInfoParam.sensorIndex = targetSensor.sensorIndex ?? -1; + // Subscribe to sensor events. + sensor.on(sensorType, sensorCallback, { sensorInfoParam }); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.on. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} + +function sensorUnsubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + sensor.off(sensorType, sensorInfoParam, sensorCallback); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.off. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} +``` + ### AMBIENT_TEMPERATURE9+ off(type: SensorId.AMBIENT_TEMPERATURE, callback?: Callback<AmbientTemperatureResponse>): void @@ -2112,6 +2391,82 @@ try { } ``` +### AMBIENT_TEMPERATURE19+ + +off(type: SensorId.AMBIENT_TEMPERATURE, sensorInfoParam?: SensorInfoParam, callback?: Callback<AmbientTemperatureResponse>): void + +Unsubscribes from data of the ambient temperature sensor. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9).AMBIENT_TEMPERATURE | Yes | Sensor type. The value is fixed at **SensorId.AMBIENT_TEMPERATURE**. | +| sensorInfoParam | [SensorInfoParam](#sensorinfoparam19) | No| Sensor parameters, including **deviceId** and **sensorIndex**.| +| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 14500101 | Service exception.Possible causes:1. Sensor hdf service exception;2. Sensor service ipc exception;3.Sensor data channel exception. | + +**Example** + +```ts +import { sensor } from '@kit.SensorServiceKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +enum Ret { OK, Failed = -1 } + +// Sensor callback +const sensorCallback = (response: sensor.AmbientTemperatureResponse) => { + console.log(`callback response: ${JSON.stringify(response)}`); +} +// Sensor type +const sensorType = sensor.SensorId.AMBIENT_TEMPERATURE; +const sensorInfoParam: sensor.SensorInfoParam = {}; + +function sensorSubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + // Query all sensors. + const sensorList: sensor.Sensor[] = sensor.getSensorListSync(); + if (!sensorList.length) { + return Ret.Failed; + } + // Obtain the target sensor based on the actual service logic. + const targetSensor: sensor.Sensor = sensorList[0]; + sensorInfoParam.deviceId = targetSensor.deviceId ?? -1; + sensorInfoParam.sensorIndex = targetSensor.sensorIndex ?? -1; + // Subscribe to sensor events. + sensor.on(sensorType, sensorCallback, { sensorInfoParam }); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.on. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} + +function sensorUnsubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + sensor.off(sensorType, sensorInfoParam, sensorCallback); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.off. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} +``` + + ### BAROMETER9+ off(type: SensorId.BAROMETER, callback?: Callback<BarometerResponse>): void @@ -2162,6 +2517,81 @@ try { } ``` +### BAROMETER19+ + +off(type: SensorId.BAROMETER, sensorInfoParam?: SensorInfoParam, callback?: Callback<BarometerResponse>): void + +Unsubscribes from data of the barometer sensor. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9).BAROMETER | Yes | Sensor type. The value is fixed at **SensorId.BAROMETER**. | +| sensorInfoParam | [SensorInfoParam](#sensorinfoparam19) | No| Sensor parameters, including **deviceId** and **sensorIndex**.| +| callback | Callback<[BarometerResponse](#barometerresponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 14500101 | Service exception.Possible causes:1. Sensor hdf service exception;2. Sensor service ipc exception;3.Sensor data channel exception. | + +**Example** + +```ts +import { sensor } from '@kit.SensorServiceKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +enum Ret { OK, Failed = -1 } + +// Sensor callback +const sensorCallback = (response: sensor.BarometerResponse) => { + console.log(`callback response: ${JSON.stringify(response)}`); +} +// Sensor type +const sensorType = sensor.SensorId.BAROMETER; +const sensorInfoParam: sensor.SensorInfoParam = {}; + +function sensorSubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + // Query all sensors. + const sensorList: sensor.Sensor[] = sensor.getSensorListSync(); + if (!sensorList.length) { + return Ret.Failed; + } + // Obtain the target sensor based on the actual service logic. + const targetSensor: sensor.Sensor = sensorList[0]; + sensorInfoParam.deviceId = targetSensor.deviceId ?? -1; + sensorInfoParam.sensorIndex = targetSensor.sensorIndex ?? -1; + // Subscribe to sensor events. + sensor.on(sensorType, sensorCallback, { sensorInfoParam }); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.on. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} + +function sensorUnsubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + sensor.off(sensorType, sensorInfoParam, sensorCallback); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.off. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} +``` + ### GRAVITY9+ off(type: SensorId.GRAVITY, callback?: Callback<GravityResponse>): void @@ -2213,24 +2643,21 @@ try { ``` -### GYROSCOPE9+ - -off(type: SensorId.GYROSCOPE, callback?: Callback<GyroscopeResponse>): void - -Unsubscribes from data of the gyroscope sensor. +### GRAVITY19+ -**Required permissions**: ohos.permission.GYROSCOPE +off(type: SensorId.GRAVITY, sensorInfoParam?: SensorInfoParam, callback?: Callback<GravityResponse>): void -**Atomic service API**: This API can be used in atomic services since API version 11. +Unsubscribes from data of the gravity sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9).GYROSCOPE | Yes | Sensor type. The value is fixed at **SensorId.GYROSCOPE**. | -| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9).GRAVITY | Yes | Sensor type. The value is fixed at **SensorId.GRAVITY**. | +| sensorInfoParam | [SensorInfoParam](#sensorinfoparam19) | No| Sensor parameters, including **deviceId** and **sensorIndex**.| +| callback | Callback<[GravityResponse](#gravityresponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| **Error codes** @@ -2238,8 +2665,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 201 | Permission denied. | -| 401 | Parameter error.Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | +| 14500101 | Service exception.Possible causes:1. Sensor hdf service exception;2. Sensor service ipc exception;3.Sensor data channel exception. | **Example** @@ -2247,8 +2673,87 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ import { sensor } from '@kit.SensorServiceKit'; import { BusinessError } from '@kit.BasicServicesKit'; -function callback1(data: object) { - console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); +enum Ret { OK, Failed = -1 } + +// Sensor callback +const sensorCallback = (response: sensor.GravityResponse) => { + console.log(`callback response: ${JSON.stringify(response)}`); +} +// Sensor type +const sensorType = sensor.SensorId.GRAVITY; +const sensorInfoParam: sensor.SensorInfoParam = {}; + +function sensorSubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + // Query all sensors. + const sensorList: sensor.Sensor[] = sensor.getSensorListSync(); + if (!sensorList.length) { + return Ret.Failed; + } + // Obtain the target sensor based on the actual service logic. + const targetSensor: sensor.Sensor = sensorList[0]; + sensorInfoParam.deviceId = targetSensor.deviceId ?? -1; + sensorInfoParam.sensorIndex = targetSensor.sensorIndex ?? -1; + // Subscribe to sensor events. + sensor.on(sensorType, sensorCallback, { sensorInfoParam }); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.on. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} + +function sensorUnsubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + sensor.off(sensorType, sensorInfoParam, sensorCallback); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.off. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} +``` + +### GYROSCOPE9+ + +off(type: SensorId.GYROSCOPE, callback?: Callback<GyroscopeResponse>): void + +Unsubscribes from data of the gyroscope sensor. + +**Required permissions**: ohos.permission.GYROSCOPE + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9).GYROSCOPE | Yes | Sensor type. The value is fixed at **SensorId.GYROSCOPE**. | +| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 201 | Permission denied. | +| 401 | Parameter error.Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | + +**Example** + +```ts +import { sensor } from '@kit.SensorServiceKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +function callback1(data: object) { + console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); } function callback2(data: object) { @@ -2268,6 +2773,86 @@ try { } ``` +### GYROSCOPE19+ + +off(type: SensorId.GYROSCOPE, sensorInfoParam?: SensorInfoParam, callback?: Callback<GyroscopeResponse>): void + +Unsubscribes from data of the gyroscope sensor. + +**Required permissions**: ohos.permission.GYROSCOPE + +**Atomic service API**: This API can be used in atomic services since API version 19. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9).GYROSCOPE | Yes | Sensor type. The value is fixed at **SensorId.GYROSCOPE**. | +| sensorInfoParam | [SensorInfoParam](#sensorinfoparam19) | No| Sensor parameters, including **deviceId** and **sensorIndex**.| +| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 201 | Permission denied. | +| 14500101 | Service exception.Possible causes:1. Sensor hdf service exception;2. Sensor service ipc exception;3.Sensor data channel exception. | + +**Example** + +```ts +import { sensor } from '@kit.SensorServiceKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +enum Ret { OK, Failed = -1 } + +// Sensor callback +const sensorCallback = (response: sensor.GyroscopeResponse) => { + console.log(`callback response: ${JSON.stringify(response)}`); +} +// Sensor type +const sensorType = sensor.SensorId.GYROSCOPE; +const sensorInfoParam: sensor.SensorInfoParam = {}; + +function sensorSubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + // Query all sensors. + const sensorList: sensor.Sensor[] = sensor.getSensorListSync(); + if (!sensorList.length) { + return Ret.Failed; + } + // Obtain the target sensor based on the actual service logic. + const targetSensor: sensor.Sensor = sensorList[0]; + sensorInfoParam.deviceId = targetSensor.deviceId ?? -1; + sensorInfoParam.sensorIndex = targetSensor.sensorIndex ?? -1; + // Subscribe to sensor events. + sensor.on(sensorType, sensorCallback, { sensorInfoParam }); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.on. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} + +function sensorUnsubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + sensor.off(sensorType, sensorInfoParam, sensorCallback); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.off. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} +``` + ### GYROSCOPE_UNCALIBRATED9+ off(type: SensorId.GYROSCOPE_UNCALIBRATED, callback?: Callback<GyroscopeUncalibratedResponse>): void @@ -2321,6 +2906,84 @@ try { } ``` +### GYROSCOPE_UNCALIBRATED19+ + +off(type: SensorId.GYROSCOPE_UNCALIBRATED, sensorInfoParam?: SensorInfoParam, callback?: Callback<GyroscopeUncalibratedResponse>): void + +Unsubscribes from data of the uncalibrated gyroscope sensor. + +**Required permissions**: ohos.permission.GYROSCOPE + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9).GYROSCOPE_UNCALIBRATED | Yes | Sensor type. The value is fixed at **SensorId.GYROSCOPE_UNCALIBRATED**. | +| sensorInfoParam | [SensorInfoParam](#sensorinfoparam19) | No| Sensor parameters, including **deviceId** and **sensorIndex**.| +| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 201 | Permission denied. | +| 14500101 | Service exception.Possible causes:1. Sensor hdf service exception;2. Sensor service ipc exception;3.Sensor data channel exception. | + +**Example** + +```ts +import { sensor } from '@kit.SensorServiceKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +enum Ret { OK, Failed = -1 } + +// Sensor callback +const sensorCallback = (response: sensor.GyroscopeUncalibratedResponse) => { + console.log(`callback response: ${JSON.stringify(response)}`); +} +// Sensor type +const sensorType = sensor.SensorId.GYROSCOPE_UNCALIBRATED; +const sensorInfoParam: sensor.SensorInfoParam = {}; + +function sensorSubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + // Query all sensors. + const sensorList: sensor.Sensor[] = sensor.getSensorListSync(); + if (!sensorList.length) { + return Ret.Failed; + } + // Obtain the target sensor based on the actual service logic. + const targetSensor: sensor.Sensor = sensorList[0]; + sensorInfoParam.deviceId = targetSensor.deviceId ?? -1; + sensorInfoParam.sensorIndex = targetSensor.sensorIndex ?? -1; + // Subscribe to sensor events. + sensor.on(sensorType, sensorCallback, { sensorInfoParam }); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.on. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} + +function sensorUnsubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + sensor.off(sensorType, sensorInfoParam, sensorCallback); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.off. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} +``` + ### HALL9+ off(type: SensorId.HALL, callback?: Callback<HallResponse>): void @@ -2371,6 +3034,81 @@ try { } ``` +### HALL19+ + +off(type: SensorId.HALL, sensorInfoParam?: SensorInfoParam, callback?: Callback<HallResponse>): void + +Unsubscribes from data of the Hall effect sensor. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9).HALL | Yes | Sensor type. The value is fixed at **SensorId.HALL**. | +| sensorInfoParam | [SensorInfoParam](#sensorinfoparam19) | No| Sensor parameters, including **deviceId** and **sensorIndex**.| +| callback | Callback<[HallResponse](#hallresponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 14500101 | Service exception.Possible causes:1. Sensor hdf service exception;2. Sensor service ipc exception;3.Sensor data channel exception. | + +**Example** + +```ts +import { sensor } from '@kit.SensorServiceKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +enum Ret { OK, Failed = -1 } + +// Sensor callback +const sensorCallback = (response: sensor.HallResponse) => { + console.log(`callback response: ${JSON.stringify(response)}`); +} +// Sensor type +const sensorType = sensor.SensorId.HALL; +const sensorInfoParam: sensor.SensorInfoParam = {}; + +function sensorSubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + // Query all sensors. + const sensorList: sensor.Sensor[] = sensor.getSensorListSync(); + if (!sensorList.length) { + return Ret.Failed; + } + // Obtain the target sensor based on the actual service logic. + const targetSensor: sensor.Sensor = sensorList[0]; + sensorInfoParam.deviceId = targetSensor.deviceId ?? -1; + sensorInfoParam.sensorIndex = targetSensor.sensorIndex ?? -1; + // Subscribe to sensor events. + sensor.on(sensorType, sensorCallback, { sensorInfoParam }); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.on. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} + +function sensorUnsubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + sensor.off(sensorType, sensorInfoParam, sensorCallback); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.off. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} +``` + ### HEART_RATE9+ off(type: SensorId.HEART_RATE, callback?: Callback<HeartRateResponse>): void @@ -2424,6 +3162,84 @@ try { } ``` +### HEART_RATE19+ + +off(type: SensorId.HEART_RATE, sensorInfoParam?: SensorInfoParam, callback?: Callback<HeartRateResponse>): void + +Unsubscribes from data of the heart rate sensor. + +**Required permissions**: ohos.permission.READ_HEALTH_DATA + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9).HEART_RATE | Yes | Sensor type. The value is fixed at **SensorId.HEART_RATE**. | +| sensorInfoParam | [SensorInfoParam](#sensorinfoparam19) | No| Sensor parameters, including **deviceId** and **sensorIndex**.| +| callback | Callback<[HeartRateResponse](#heartrateresponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 201 | Permission denied. | +| 14500101 | Service exception.Possible causes:1. Sensor hdf service exception;2. Sensor service ipc exception;3.Sensor data channel exception. | + +**Example** + +```ts +import { sensor } from '@kit.SensorServiceKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +enum Ret { OK, Failed = -1 } + +// Sensor callback +const sensorCallback = (response: sensor.HeartRateResponse) => { + console.log(`callback response: ${JSON.stringify(response)}`); +} +// Sensor type +const sensorType = sensor.SensorId.HEART_RATE; +const sensorInfoParam: sensor.SensorInfoParam = {}; + +function sensorSubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + // Query all sensors. + const sensorList: sensor.Sensor[] = sensor.getSensorListSync(); + if (!sensorList.length) { + return Ret.Failed; + } + // Obtain the target sensor based on the actual service logic. + const targetSensor: sensor.Sensor = sensorList[0]; + sensorInfoParam.deviceId = targetSensor.deviceId ?? -1; + sensorInfoParam.sensorIndex = targetSensor.sensorIndex ?? -1; + // Subscribe to sensor events. + sensor.on(sensorType, sensorCallback, { sensorInfoParam }); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.on. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} + +function sensorUnsubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + sensor.off(sensorType, sensorInfoParam, sensorCallback); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.off. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} +``` + ### HUMIDITY9+ off(type: SensorId.HUMIDITY, callback?: Callback<HumidityResponse>): void @@ -2474,6 +3290,81 @@ try { } ``` +### HUMIDITY19+ + +off(type: SensorId.HUMIDITY, sensorInfoParam?: SensorInfoParam, callback?: Callback<HumidityResponse>): void + +Unsubscribes from data of the humidity sensor. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9).HUMIDITY | Yes | Sensor type. The value is fixed at **SensorId.HUMIDITY**. | +| sensorInfoParam | [SensorInfoParam](#sensorinfoparam19) | No| Sensor parameters, including **deviceId** and **sensorIndex**.| +| callback | Callback<[HumidityResponse](#humidityresponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 14500101 | Service exception.Possible causes:1. Sensor hdf service exception;2. Sensor service ipc exception;3.Sensor data channel exception. | + +**Example** + +```ts +import { sensor } from '@kit.SensorServiceKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +enum Ret { OK, Failed = -1 } + +// Sensor callback +const sensorCallback = (response: sensor.HumidityResponse) => { + console.log(`callback response: ${JSON.stringify(response)}`); +} +// Sensor type +const sensorType = sensor.SensorId.HUMIDITY; +const sensorInfoParam: sensor.SensorInfoParam = {}; + +function sensorSubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + // Query all sensors. + const sensorList: sensor.Sensor[] = sensor.getSensorListSync(); + if (!sensorList.length) { + return Ret.Failed; + } + // Obtain the target sensor based on the actual service logic. + const targetSensor: sensor.Sensor = sensorList[0]; + sensorInfoParam.deviceId = targetSensor.deviceId ?? -1; + sensorInfoParam.sensorIndex = targetSensor.sensorIndex ?? -1; + // Subscribe to sensor events. + sensor.on(sensorType, sensorCallback, { sensorInfoParam }); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.on. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} + +function sensorUnsubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + sensor.off(sensorType, sensorInfoParam, sensorCallback); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.off. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} +``` + ### LINEAR_ACCELEROMETER9+ off(type: SensorId.LINEAR_ACCELEROMETER, callback?: Callback<LinearAccelerometerResponse>): void @@ -2527,11 +3418,89 @@ try { } ``` -### MAGNETIC_FIELD9+ +### LINEAR_ACCELEROMETER19+ -off(type: SensorId.MAGNETIC_FIELD, callback?: Callback<MagneticFieldResponse>): void +off(type: SensorId.LINEAR_ACCELEROMETER, sensorInfoParam?: SensorInfoParam, callback?: Callback<LinearAccelerometerResponse>): void -Unsubscribes from data of the magnetic field sensor. +Unsubscribes from data of the linear acceleration sensor. + +**Required permissions**: ohos.permission.ACCELEROMETER + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9).LINEAR_ACCELEROMETER | Yes | Sensor type. The value is fixed at **SensorId.LINEAR_ACCELERATION**. | +| sensorInfoParam | [SensorInfoParam](#sensorinfoparam19) | No| Sensor parameters, including **deviceId** and **sensorIndex**.| +| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 201 | Permission denied. | +| 14500101 | Service exception.Possible causes:1. Sensor hdf service exception;2. Sensor service ipc exception;3.Sensor data channel exception. | + +**Example** + +```ts +import { sensor } from '@kit.SensorServiceKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +enum Ret { OK, Failed = -1 } + +// Sensor callback +const sensorCallback = (response: sensor.LinearAccelerometerResponse) => { + console.log(`callback response: ${JSON.stringify(response)}`); +} +// Sensor type +const sensorType = sensor.SensorId.LINEAR_ACCELEROMETER; +const sensorInfoParam: sensor.SensorInfoParam = {}; + +function sensorSubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + // Query all sensors. + const sensorList: sensor.Sensor[] = sensor.getSensorListSync(); + if (!sensorList.length) { + return Ret.Failed; + } + // Obtain the target sensor based on the actual service logic. + const targetSensor: sensor.Sensor = sensorList[0]; + sensorInfoParam.deviceId = targetSensor.deviceId ?? -1; + sensorInfoParam.sensorIndex = targetSensor.sensorIndex ?? -1; + // Subscribe to sensor events. + sensor.on(sensorType, sensorCallback, { sensorInfoParam }); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.on. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} + +function sensorUnsubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + sensor.off(sensorType, sensorInfoParam, sensorCallback); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.off. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} +``` + +### MAGNETIC_FIELD9+ + +off(type: SensorId.MAGNETIC_FIELD, callback?: Callback<MagneticFieldResponse>): void + +Unsubscribes from data of the magnetic field sensor. **System capability**: SystemCapability.Sensors.Sensor @@ -2577,11 +3546,777 @@ try { } ``` +### MAGNETIC_FIELD19+ + +off(type: SensorId.MAGNETIC_FIELD, sensorInfoParam?: SensorInfoParam, callback?: Callback<MagneticFieldResponse>): void + +Unsubscribes from data of the magnetic field sensor. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9).MAGNETIC_FIELD | Yes | Sensor type. The value is fixed at **SensorId.MAGNETIC_FIELD**. | +| sensorInfoParam | [SensorInfoParam](#sensorinfoparam19) | No| Sensor parameters, including **deviceId** and **sensorIndex**.| +| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 14500101 | Service exception.Possible causes:1. Sensor hdf service exception;2. Sensor service ipc exception;3.Sensor data channel exception. | + +**Example** + +```ts +import { sensor } from '@kit.SensorServiceKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +enum Ret { OK, Failed = -1 } + +// Sensor callback +const sensorCallback = (response: sensor.MagneticFieldResponse) => { + console.log(`callback response: ${JSON.stringify(response)}`); +} +// Sensor type +const sensorType = sensor.SensorId.MAGNETIC_FIELD; +const sensorInfoParam: sensor.SensorInfoParam = {}; + +function sensorSubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + // Query all sensors. + const sensorList: sensor.Sensor[] = sensor.getSensorListSync(); + if (!sensorList.length) { + return Ret.Failed; + } + // Obtain the target sensor based on the actual service logic. + const targetSensor: sensor.Sensor = sensorList[0]; + sensorInfoParam.deviceId = targetSensor.deviceId ?? -1; + sensorInfoParam.sensorIndex = targetSensor.sensorIndex ?? -1; + // Subscribe to sensor events. + sensor.on(sensorType, sensorCallback, { sensorInfoParam }); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.on. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} + +function sensorUnsubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + sensor.off(sensorType, sensorInfoParam, sensorCallback); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.off. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} +``` + ### MAGNETIC_FIELD_UNCALIBRATED9+ off(type: SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback?: Callback<MagneticFieldUncalibratedResponse>): void -Unsubscribes from data of the uncalibrated magnetic field sensor. +Unsubscribes from data of the uncalibrated magnetic field sensor. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9).MAGNETIC_FIELD_UNCALIBRATED | Yes | Sensor type. The value is fixed at **SensorId.MAGNETIC_FIELD_UNCALIBRATED**.| +| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 401 | Parameter error.Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | + +**Example** + +```ts +import { sensor } from '@kit.SensorServiceKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +function callback1(data: object) { + console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); +} + +function callback2(data: object) { + console.info('Succeeded in getting callback2 data: ' + JSON.stringify(data)); +} + +try { + sensor.on(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback1); + sensor.on(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback2); + // Unsubscribe from callback1. + sensor.off(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback1); + // Unsubscribe from all callbacks of the SensorId.MAGNETIC_FIELD_UNCALIBRATED type. + sensor.off(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED); +} catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke off. Code: ${e.code}, message: ${e.message}`); +} +``` + +### MAGNETIC_FIELD_UNCALIBRATED19+ + +off(type: SensorId.MAGNETIC_FIELD_UNCALIBRATED, sensorInfoParam?: SensorInfoParam, callback?: Callback<MagneticFieldUncalibratedResponse>): void + +Unsubscribes from data of the uncalibrated magnetic field sensor. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9).MAGNETIC_FIELD_UNCALIBRATED | Yes | Sensor type. The value is fixed at **SensorId.MAGNETIC_FIELD_UNCALIBRATED**.| +| sensorInfoParam | [SensorInfoParam](#sensorinfoparam19) | No| Sensor parameters, including **deviceId** and **sensorIndex**.| +| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 14500101 | Service exception.Possible causes:1. Sensor hdf service exception;2. Sensor service ipc exception;3.Sensor data channel exception. | + +**Example** + +```ts +import { sensor } from '@kit.SensorServiceKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +enum Ret { OK, Failed = -1 } + +// Sensor callback +const sensorCallback = (response: sensor.MagneticFieldUncalibratedResponse) => { + console.log(`callback response: ${JSON.stringify(response)}`); +} +// Sensor type +const sensorType = sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED; +const sensorInfoParam: sensor.SensorInfoParam = {}; + +function sensorSubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + // Query all sensors. + const sensorList: sensor.Sensor[] = sensor.getSensorListSync(); + if (!sensorList.length) { + return Ret.Failed; + } + // Obtain the target sensor based on the actual service logic. + const targetSensor: sensor.Sensor = sensorList[0]; + sensorInfoParam.deviceId = targetSensor.deviceId ?? -1; + sensorInfoParam.sensorIndex = targetSensor.sensorIndex ?? -1; + // Subscribe to sensor events. + sensor.on(sensorType, sensorCallback, { sensorInfoParam }); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.on. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} + +function sensorUnsubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + sensor.off(sensorType, sensorInfoParam, sensorCallback); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.off. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} +``` + +### ORIENTATION9+ + +off(type: SensorId.ORIENTATION, callback?: Callback<OrientationResponse>): void + +Unsubscribes from data of the orientation sensor. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9).ORIENTATION | Yes | Sensor type. The value is fixed at **SensorId.ORIENTATION**. | +| callback | Callback<[OrientationResponse](#orientationresponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 401 | Parameter error.Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | + +**Example** + +```ts +import { sensor } from '@kit.SensorServiceKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +function callback1(data: object) { + console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); +} + +function callback2(data: object) { + console.info('Succeeded in getting callback2 data: ' + JSON.stringify(data)); +} + +try { + sensor.on(sensor.SensorId.ORIENTATION, callback1); + sensor.on(sensor.SensorId.ORIENTATION, callback2); + // Unsubscribe from callback1. + sensor.off(sensor.SensorId.ORIENTATION, callback1); + // Unsubscribe from all callbacks of the SensorId.ORIENTATION type. + sensor.off(sensor.SensorId.ORIENTATION); +} catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke off. Code: ${e.code}, message: ${e.message}`); +} +``` + +### ORIENTATION19+ + +off(type: SensorId.ORIENTATION, sensorInfoParam?: SensorInfoParam, callback?: Callback<OrientationResponse>): void + +Unsubscribes from data of the orientation sensor. + +**Atomic service API**: This API can be used in atomic services since API version 19. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9).ORIENTATION | Yes | Sensor type. The value is fixed at **SensorId.ORIENTATION**. | +| sensorInfoParam | [SensorInfoParam](#sensorinfoparam19) | No| Sensor parameters, including **deviceId** and **sensorIndex**.| +| callback | Callback<[OrientationResponse](#orientationresponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 14500101 | Service exception.Possible causes:1. Sensor hdf service exception;2. Sensor service ipc exception;3.Sensor data channel exception. | + +**Example** + +```ts +import { sensor } from '@kit.SensorServiceKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +enum Ret { OK, Failed = -1 } + +// Sensor callback +const sensorCallback = (response: sensor.OrientationResponse) => { + console.log(`callback response: ${JSON.stringify(response)}`); +} +// Sensor type +const sensorType = sensor.SensorId.ORIENTATION; +const sensorInfoParam: sensor.SensorInfoParam = {}; + +function sensorSubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + // Query all sensors. + const sensorList: sensor.Sensor[] = sensor.getSensorListSync(); + if (!sensorList.length) { + return Ret.Failed; + } + // Obtain the target sensor based on the actual service logic. + const targetSensor: sensor.Sensor = sensorList[0]; + sensorInfoParam.deviceId = targetSensor.deviceId ?? -1; + sensorInfoParam.sensorIndex = targetSensor.sensorIndex ?? -1; + // Subscribe to sensor events. + sensor.on(sensorType, sensorCallback, { sensorInfoParam }); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.on. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} + +function sensorUnsubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + sensor.off(sensorType, sensorInfoParam, sensorCallback); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.off. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} +``` + +### PEDOMETER9+ + +off(type: SensorId.PEDOMETER, callback?: Callback<PedometerResponse>): void + +Unsubscribes from data of the pedometer sensor. + +**Required permissions**: ohos.permission.ACTIVITY_MOTION + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9).PEDOMETER | Yes | Sensor type. The value is fixed at **SensorId.PEDOMETER**. | +| callback | Callback<[PedometerResponse](#pedometerresponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 201 | Permission denied. | +| 401 | Parameter error.Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | + +**Example** + +```ts +import { sensor } from '@kit.SensorServiceKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +function callback1(data: object) { + console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); +} + +function callback2(data: object) { + console.info('Succeeded in getting callback2 data: ' + JSON.stringify(data)); +} + +try { + sensor.on(sensor.SensorId.PEDOMETER, callback1); + sensor.on(sensor.SensorId.PEDOMETER, callback2); + // Unsubscribe from callback1. + sensor.off(sensor.SensorId.PEDOMETER, callback1); + // Unsubscribe from all callbacks of the SensorId.ORIENTATION type. + sensor.off(sensor.SensorId.PEDOMETER); +} catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke off. Code: ${e.code}, message: ${e.message}`); +} +``` + +### PEDOMETER19+ + +off(type: SensorId.PEDOMETER, sensorInfoParam?: SensorInfoParam, callback?: Callback<PedometerResponse>): void + +Unsubscribes from data of the pedometer sensor. + +**Required permissions**: ohos.permission.ACTIVITY_MOTION + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9).PEDOMETER | Yes | Sensor type. The value is fixed at **SensorId.PEDOMETER**. | +| sensorInfoParam | [SensorInfoParam](#sensorinfoparam19) | No| Sensor parameters, including **deviceId** and **sensorIndex**.| +| callback | Callback<[PedometerResponse](#pedometerresponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 201 | Permission denied. | +| 14500101 | Service exception.Possible causes:1. Sensor hdf service exception;2. Sensor service ipc exception;3.Sensor data channel exception. | + +**Example** + +```ts +import { sensor } from '@kit.SensorServiceKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +enum Ret { OK, Failed = -1 } + +// Sensor callback +const sensorCallback = (response: sensor.PedometerResponse) => { + console.log(`callback response: ${JSON.stringify(response)}`); +} +// Sensor type +const sensorType = sensor.SensorId.PEDOMETER; +const sensorInfoParam: sensor.SensorInfoParam = {}; + +function sensorSubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + // Query all sensors. + const sensorList: sensor.Sensor[] = sensor.getSensorListSync(); + if (!sensorList.length) { + return Ret.Failed; + } + // Obtain the target sensor based on the actual service logic. + const targetSensor: sensor.Sensor = sensorList[0]; + sensorInfoParam.deviceId = targetSensor.deviceId ?? -1; + sensorInfoParam.sensorIndex = targetSensor.sensorIndex ?? -1; + // Subscribe to sensor events. + sensor.on(sensorType, sensorCallback, { sensorInfoParam }); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.on. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} + +function sensorUnsubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + sensor.off(sensorType, sensorInfoParam, sensorCallback); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.off. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} +``` + +### PEDOMETER_DETECTION9+ + +off(type: SensorId.PEDOMETER_DETECTION, callback?: Callback<PedometerDetectionResponse>): void + +Unsubscribes from data of the pedometer detection sensor. + +**Required permissions**: ohos.permission.ACTIVITY_MOTION + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9).PEDOMETER_DETECTION | Yes | Sensor type. The value is fixed at **SensorId.PEDOMETER_DETECTION**. | +| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 201 | Permission denied. | +| 401 | Parameter error.Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | + +**Example** + +```ts +import { sensor } from '@kit.SensorServiceKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +function callback1(data: object) { + console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); +} + +function callback2(data: object) { + console.info('Succeeded in getting callback2 data: ' + JSON.stringify(data)); +} + +try { + sensor.on(sensor.SensorId.PEDOMETER_DETECTION, callback1); + sensor.on(sensor.SensorId.PEDOMETER_DETECTION, callback2); + // Unsubscribe from callback1. + sensor.off(sensor.SensorId.PEDOMETER_DETECTION, callback1); + // Unsubscribe from all callbacks of the SensorId.PEDOMETER_DETECTION type. + sensor.off(sensor.SensorId.PEDOMETER_DETECTION); +} catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke off. Code: ${e.code}, message: ${e.message}`); +} +``` + +### PEDOMETER_DETECTION19+ + +off(type: SensorId.PEDOMETER_DETECTION, sensorInfoParam?: SensorInfoParam, callback?: Callback<PedometerDetectionResponse>): void + +Unsubscribes from data of the pedometer detection sensor. + +**Required permissions**: ohos.permission.ACTIVITY_MOTION + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9).PEDOMETER_DETECTION | Yes | Sensor type. The value is fixed at **SensorId.PEDOMETER_DETECTION**. | +| sensorInfoParam | [SensorInfoParam](#sensorinfoparam19) | No| Sensor parameters, including **deviceId** and **sensorIndex**.| +| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 201 | Permission denied. | +| 14500101 | Service exception.Possible causes:1. Sensor hdf service exception;2. Sensor service ipc exception;3.Sensor data channel exception. | + +**Example** + +```ts +import { sensor } from '@kit.SensorServiceKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +enum Ret { OK, Failed = -1 } + +// Sensor callback +const sensorCallback = (response: sensor.PedometerDetectionResponse) => { + console.log(`callback response: ${JSON.stringify(response)}`); +} +// Sensor type +const sensorType = sensor.SensorId.PEDOMETER_DETECTION; +const sensorInfoParam: sensor.SensorInfoParam = {}; + +function sensorSubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + // Query all sensors. + const sensorList: sensor.Sensor[] = sensor.getSensorListSync(); + if (!sensorList.length) { + return Ret.Failed; + } + // Obtain the target sensor based on the actual service logic. + const targetSensor: sensor.Sensor = sensorList[0]; + sensorInfoParam.deviceId = targetSensor.deviceId ?? -1; + sensorInfoParam.sensorIndex = targetSensor.sensorIndex ?? -1; + // Subscribe to sensor events. + sensor.on(sensorType, sensorCallback, { sensorInfoParam }); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.on. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} + +function sensorUnsubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + sensor.off(sensorType, sensorInfoParam, sensorCallback); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.off. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} +``` + +### PROXIMITY9+ + +off(type: SensorId.PROXIMITY, callback?: Callback<ProximityResponse>): void + +Unsubscribes from data of the proximity sensor. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9).PROXIMITY | Yes | Sensor type. The value is fixed at **SensorId.PROXIMITY**. | +| callback | Callback<[ProximityResponse](#proximityresponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 401 | Parameter error.Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | + +**Example** + +```ts +import { sensor } from '@kit.SensorServiceKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +function callback1(data: object) { + console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); +} + +function callback2(data: object) { + console.info('Succeeded in getting callback2 data: ' + JSON.stringify(data)); +} + +try { + sensor.on(sensor.SensorId.PROXIMITY, callback1); + sensor.on(sensor.SensorId.PROXIMITY, callback2); + // Unsubscribe from callback1. + sensor.off(sensor.SensorId.PROXIMITY, callback1); + // Unsubscribe from all callbacks of the SensorId.PROXIMITY type. + sensor.off(sensor.SensorId.PROXIMITY); +} catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke off. Code: ${e.code}, message: ${e.message}`); +} +``` + +### PROXIMITY19+ + +off(type: SensorId.PROXIMITY, sensorInfoParam?: SensorInfoParam, callback?: Callback<ProximityResponse>): void + +Unsubscribes from data of the proximity sensor. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9).PROXIMITY | Yes | Sensor type. The value is fixed at **SensorId.PROXIMITY**. | +| sensorInfoParam | [SensorInfoParam](#sensorinfoparam19) | No| Sensor parameters, including **deviceId** and **sensorIndex**.| +| callback | Callback<[ProximityResponse](#proximityresponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 14500101 | Service exception.Possible causes:1. Sensor hdf service exception;2. Sensor service ipc exception;3.Sensor data channel exception. | + +**Example** + +```ts +import { sensor } from '@kit.SensorServiceKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +enum Ret { OK, Failed = -1 } + +// Sensor callback +const sensorCallback = (response: sensor.ProximityResponse) => { + console.log(`callback response: ${JSON.stringify(response)}`); +} +// Sensor type +const sensorType = sensor.SensorId.PROXIMITY; +const sensorInfoParam: sensor.SensorInfoParam = {}; + +function sensorSubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + // Query all sensors. + const sensorList: sensor.Sensor[] = sensor.getSensorListSync(); + if (!sensorList.length) { + return Ret.Failed; + } + // Obtain the target sensor based on the actual service logic. + const targetSensor: sensor.Sensor = sensorList[0]; + sensorInfoParam.deviceId = targetSensor.deviceId ?? -1; + sensorInfoParam.sensorIndex = targetSensor.sensorIndex ?? -1; + // Subscribe to sensor events. + sensor.on(sensorType, sensorCallback, { sensorInfoParam }); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.on. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} + +function sensorUnsubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + sensor.off(sensorType, sensorInfoParam, sensorCallback); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.off. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; +} +``` + +### ROTATION_VECTOR9+ + +off(type: SensorId.ROTATION_VECTOR, callback?: Callback<RotationVectorResponse>): void + +Unsubscribes from data of the rotation vector sensor. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9).ROTATION_VECTOR | Yes | Sensor type. The value is fixed at **SensorId.ROTATION_VECTOR**. | +| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 401 | Parameter error.Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | + +**Example** + +```ts +import { sensor } from '@kit.SensorServiceKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +function callback1(data: object) { + console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); +} + +function callback2(data: object) { + console.info('Succeeded in getting callback2 data: ' + JSON.stringify(data)); +} + +try { + sensor.on(sensor.SensorId.ROTATION_VECTOR, callback1); + sensor.on(sensor.SensorId.ROTATION_VECTOR, callback2); + // Unsubscribe from callback1. + sensor.off(sensor.SensorId.ROTATION_VECTOR, callback1); + // Unsubscribe from all callbacks of the SensorId.ROTATION_VECTOR type. + sensor.off(sensor.SensorId.ROTATION_VECTOR); +} catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke off. Code: ${e.code}, message: ${e.message}`); +} +``` + +### ROTATION_VECTOR19+ + +off(type: SensorId.ROTATION_VECTOR, sensorInfoParam?: SensorInfoParam, callback?: Callback<RotationVectorResponse>): void + +Unsubscribes from data of the rotation vector sensor. **System capability**: SystemCapability.Sensors.Sensor @@ -2589,8 +4324,9 @@ Unsubscribes from data of the uncalibrated magnetic field sensor. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9).MAGNETIC_FIELD_UNCALIBRATED | Yes | Sensor type. The value is fixed at **SensorId.MAGNETIC_FIELD_UNCALIBRATED**.| -| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| +| type | [SensorId](#sensorid9).ROTATION_VECTOR | Yes | Sensor type. The value is fixed at **SensorId.ROTATION_VECTOR**. | +| sensorInfoParam | [SensorInfoParam](#sensorinfoparam19) | No| Sensor parameters, including **deviceId** and **sensorIndex**.| +| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| **Error codes** @@ -2598,7 +4334,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error.Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | +| 14500101 | Service exception.Possible causes:1. Sensor hdf service exception;2. Sensor service ipc exception;3.Sensor data channel exception. | **Example** @@ -2606,43 +4342,65 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ import { sensor } from '@kit.SensorServiceKit'; import { BusinessError } from '@kit.BasicServicesKit'; -function callback1(data: object) { - console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); +enum Ret { OK, Failed = -1 } + +// Sensor callback +const sensorCallback = (response: sensor.RotationVectorResponse) => { + console.log(`callback response: ${JSON.stringify(response)}`); } +// Sensor type +const sensorType = sensor.SensorId.ROTATION_VECTOR; +const sensorInfoParam: sensor.SensorInfoParam = {}; -function callback2(data: object) { - console.info('Succeeded in getting callback2 data: ' + JSON.stringify(data)); +function sensorSubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + // Query all sensors. + const sensorList: sensor.Sensor[] = sensor.getSensorListSync(); + if (!sensorList.length) { + return Ret.Failed; + } + // Obtain the target sensor based on the actual service logic. + const targetSensor: sensor.Sensor = sensorList[0]; + sensorInfoParam.deviceId = targetSensor.deviceId ?? -1; + sensorInfoParam.sensorIndex = targetSensor.sensorIndex ?? -1; + // Subscribe to sensor events. + sensor.on(sensorType, sensorCallback, { sensorInfoParam }); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.on. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; } -try { - sensor.on(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback1); - sensor.on(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback2); - // Unsubscribe from callback1. - sensor.off(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback1); - // Unsubscribe from all callbacks of the SensorId.MAGNETIC_FIELD_UNCALIBRATED type. - sensor.off(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED); -} catch (error) { - let e: BusinessError = error as BusinessError; - console.error(`Failed to invoke off. Code: ${e.code}, message: ${e.message}`); +function sensorUnsubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + sensor.off(sensorType, sensorInfoParam, sensorCallback); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.off. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; } ``` -### ORIENTATION9+ - -off(type: SensorId.ORIENTATION, callback?: Callback<OrientationResponse>): void +### SIGNIFICANT_MOTION9+ -Unsubscribes from data of the orientation sensor. +off(type: SensorId.SIGNIFICANT_MOTION, callback?: Callback<SignificantMotionResponse>): void -**Atomic service API**: This API can be used in atomic services since API version 11. +Unsubscribes from valid motion sensor data. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9).ORIENTATION | Yes | Sensor type. The value is fixed at **SensorId.ORIENTATION**. | -| callback | Callback<[OrientationResponse](#orientationresponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9).SIGNIFICANT_MOTION | Yes | Sensor type. The value is fixed at **SensorId.SIGNIFICANT_MOTION**. | +| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| **Error codes** @@ -2667,34 +4425,33 @@ function callback2(data: object) { } try { - sensor.on(sensor.SensorId.ORIENTATION, callback1); - sensor.on(sensor.SensorId.ORIENTATION, callback2); + sensor.on(sensor.SensorId.SIGNIFICANT_MOTION, callback1); + sensor.on(sensor.SensorId.SIGNIFICANT_MOTION, callback2); // Unsubscribe from callback1. - sensor.off(sensor.SensorId.ORIENTATION, callback1); - // Unsubscribe from all callbacks of the SensorId.ORIENTATION type. - sensor.off(sensor.SensorId.ORIENTATION); + sensor.off(sensor.SensorId.SIGNIFICANT_MOTION, callback1); + // Unsubscribe from all callbacks of the SensorId.SIGNIFICANT_MOTION type. + sensor.off(sensor.SensorId.SIGNIFICANT_MOTION); } catch (error) { let e: BusinessError = error as BusinessError; console.error(`Failed to invoke off. Code: ${e.code}, message: ${e.message}`); } ``` -### PEDOMETER9+ - -off(type: SensorId.PEDOMETER, callback?: Callback<PedometerResponse>): void +### SIGNIFICANT_MOTION19+ -Unsubscribes from data of the pedometer sensor. +off(type: SensorId.SIGNIFICANT_MOTION, sensorInfoParam?: SensorInfoParam, callback?: Callback<SignificantMotionResponse>): void -**Required permissions**: ohos.permission.ACTIVITY_MOTION +Unsubscribes from valid motion sensor data. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9).PEDOMETER | Yes | Sensor type. The value is fixed at **SensorId.PEDOMETER**. | -| callback | Callback<[PedometerResponse](#pedometerresponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9).SIGNIFICANT_MOTION | Yes | Sensor type. The value is fixed at **SensorId.SIGNIFICANT_MOTION**. | +| sensorInfoParam | [SensorInfoParam](#sensorinfoparam19) | No| Sensor parameters, including **deviceId** and **sensorIndex**.| +| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| **Error codes** @@ -2702,8 +4459,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 201 | Permission denied. | -| 401 | Parameter error.Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | +| 14500101 | Service exception.Possible causes:1. Sensor hdf service exception;2. Sensor service ipc exception;3.Sensor data channel exception. | **Example** @@ -2711,34 +4467,56 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ import { sensor } from '@kit.SensorServiceKit'; import { BusinessError } from '@kit.BasicServicesKit'; -function callback1(data: object) { - console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); +enum Ret { OK, Failed = -1 } + +// Sensor callback +const sensorCallback = (response: sensor.SignificantMotionResponse) => { + console.log(`callback response: ${JSON.stringify(response)}`); } +// Sensor type +const sensorType = sensor.SensorId.SIGNIFICANT_MOTION; +const sensorInfoParam: sensor.SensorInfoParam = {}; -function callback2(data: object) { - console.info('Succeeded in getting callback2 data: ' + JSON.stringify(data)); +function sensorSubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + // Query all sensors. + const sensorList: sensor.Sensor[] = sensor.getSensorListSync(); + if (!sensorList.length) { + return Ret.Failed; + } + // Obtain the target sensor based on the actual service logic. + const targetSensor: sensor.Sensor = sensorList[0]; + sensorInfoParam.deviceId = targetSensor.deviceId ?? -1; + sensorInfoParam.sensorIndex = targetSensor.sensorIndex ?? -1; + // Subscribe to sensor events. + sensor.on(sensorType, sensorCallback, { sensorInfoParam }); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.on. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; } -try { - sensor.on(sensor.SensorId.PEDOMETER, callback1); - sensor.on(sensor.SensorId.PEDOMETER, callback2); - // Unsubscribe from callback1. - sensor.off(sensor.SensorId.PEDOMETER, callback1); - // Unsubscribe from all callbacks of the SensorId.ORIENTATION type. - sensor.off(sensor.SensorId.PEDOMETER); -} catch (error) { - let e: BusinessError = error as BusinessError; - console.error(`Failed to invoke off. Code: ${e.code}, message: ${e.message}`); +function sensorUnsubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + sensor.off(sensorType, sensorInfoParam, sensorCallback); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.off. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; } ``` -### PEDOMETER_DETECTION9+ - -off(type: SensorId.PEDOMETER_DETECTION, callback?: Callback<PedometerDetectionResponse>): void +### WEAR_DETECTION9+ -Unsubscribes from data of the pedometer detection sensor. +off(type: SensorId.WEAR_DETECTION, callback?: Callback<WearDetectionResponse>): void -**Required permissions**: ohos.permission.ACTIVITY_MOTION +Unsubscribes from data of the wear detection sensor. **System capability**: SystemCapability.Sensors.Sensor @@ -2746,8 +4524,8 @@ Unsubscribes from data of the pedometer detection sensor. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9).PEDOMETER_DETECTION | Yes | Sensor type. The value is fixed at **SensorId.PEDOMETER_DETECTION**. | -| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| +| type | [SensorId](#sensorid9).WEAR_DETECTION | Yes | Sensor type. The value is fixed at **SensorId.WEAR_DETECTION**. | +| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| **Error codes** @@ -2755,7 +4533,6 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 201 | Permission denied. | | 401 | Parameter error.Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | **Example** @@ -2773,32 +4550,33 @@ function callback2(data: object) { } try { - sensor.on(sensor.SensorId.PEDOMETER_DETECTION, callback1); - sensor.on(sensor.SensorId.PEDOMETER_DETECTION, callback2); + sensor.on(sensor.SensorId.WEAR_DETECTION, callback1); + sensor.on(sensor.SensorId.WEAR_DETECTION, callback2); // Unsubscribe from callback1. - sensor.off(sensor.SensorId.PEDOMETER_DETECTION, callback1); - // Unsubscribe from all callbacks of the SensorId.PEDOMETER_DETECTION type. - sensor.off(sensor.SensorId.PEDOMETER_DETECTION); + sensor.off(sensor.SensorId.WEAR_DETECTION, callback1); + // Unsubscribe from all callbacks of the SensorId.WEAR_DETECTION type. + sensor.off(sensor.SensorId.WEAR_DETECTION); } catch (error) { let e: BusinessError = error as BusinessError; console.error(`Failed to invoke off. Code: ${e.code}, message: ${e.message}`); } ``` -### PROXIMITY9+ +### WEAR_DETECTION19+ -off(type: SensorId.PROXIMITY, callback?: Callback<ProximityResponse>): void +off(type: SensorId.WEAR_DETECTION, sensorInfoParam?: SensorInfoParam, callback?: Callback<WearDetectionResponse>): void -Unsubscribes from data of the proximity sensor. +Unsubscribes from data of the wear detection sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9).PROXIMITY | Yes | Sensor type. The value is fixed at **SensorId.PROXIMITY**. | -| callback | Callback<[ProximityResponse](#proximityresponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9).WEAR_DETECTION | Yes | Sensor type. The value is fixed at **SensorId.WEAR_DETECTION**. | +| sensorInfoParam | [SensorInfoParam](#sensorinfoparam19) | No| Sensor parameters, including **deviceId** and **sensorIndex**.| +| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| **Error codes** @@ -2806,7 +4584,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error.Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | +| 14500101 | Service exception.Possible causes:1. Sensor hdf service exception;2. Sensor service ipc exception;3.Sensor data channel exception. | **Example** @@ -2814,49 +4592,73 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ import { sensor } from '@kit.SensorServiceKit'; import { BusinessError } from '@kit.BasicServicesKit'; -function callback1(data: object) { - console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); +enum Ret { OK, Failed = -1 } + +// Sensor callback +const sensorCallback = (response: sensor.WearDetectionResponse) => { + console.log(`callback response: ${JSON.stringify(response)}`); } +// Sensor type +const sensorType = sensor.SensorId.WEAR_DETECTION; +const sensorInfoParam: sensor.SensorInfoParam = {}; -function callback2(data: object) { - console.info('Succeeded in getting callback2 data: ' + JSON.stringify(data)); +function sensorSubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + // Query all sensors. + const sensorList: sensor.Sensor[] = sensor.getSensorListSync(); + if (!sensorList.length) { + return Ret.Failed; + } + // Obtain the target sensor based on the actual service logic. + const targetSensor: sensor.Sensor = sensorList[0]; + sensorInfoParam.deviceId = targetSensor.deviceId ?? -1; + sensorInfoParam.sensorIndex = targetSensor.sensorIndex ?? -1; + // Subscribe to sensor events. + sensor.on(sensorType, sensorCallback, { sensorInfoParam }); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.on. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; } -try { - sensor.on(sensor.SensorId.PROXIMITY, callback1); - sensor.on(sensor.SensorId.PROXIMITY, callback2); - // Unsubscribe from callback1. - sensor.off(sensor.SensorId.PROXIMITY, callback1); - // Unsubscribe from all callbacks of the SensorId.PROXIMITY type. - sensor.off(sensor.SensorId.PROXIMITY); -} catch (error) { - let e: BusinessError = error as BusinessError; - console.error(`Failed to invoke off. Code: ${e.code}, message: ${e.message}`); +function sensorUnsubscribe(): Ret { + let ret: Ret = Ret.OK; + try { + sensor.off(sensorType, sensorInfoParam, sensorCallback); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke sensor.off. Code: ${e.code}, message: ${e.message}`); + ret = Ret.Failed; + } + return ret; } ``` -### ROTATION_VECTOR9+ +### sensorStatusChange19+ -off(type: SensorId.ROTATION_VECTOR, callback?: Callback<RotationVectorResponse>): void +off(type: 'sensorStatusChange', callback?: Callback<SensorStatusEvent>): void -Unsubscribes from data of the rotation vector sensor. +Disables listening for sensor status changes. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9).ROTATION_VECTOR | Yes | Sensor type. The value is fixed at **SensorId.ROTATION_VECTOR**. | -| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | +| sensorStatusChange | sensorStatusChange | Yes | Event type. The value **sensorStatusChange** indicates a sensor status change event. | +| callback | Callback<[SensorStatusEvent](#sensorstatusevent19)> | No | Callback passed to **sensor.on**. If this parameter is left unspecified, listening will be disabled for all callbacks.| **Error codes** -For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). +For details about the error codes, see [Sensor Error Codes](errorcode-sensor.md) and [Universal Error Codes](../errorcode-universal.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error.Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | +| 14500101 | Service exception.Possible causes:1. Sensor hdf service exception;2. Sensor service ipc exception;3.Sensor data channel exception. | **Example** @@ -2864,49 +4666,53 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ import { sensor } from '@kit.SensorServiceKit'; import { BusinessError } from '@kit.BasicServicesKit'; -function callback1(data: object) { - console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); -} - -function callback2(data: object) { - console.info('Succeeded in getting callback2 data: ' + JSON.stringify(data)); -} - try { - sensor.on(sensor.SensorId.ROTATION_VECTOR, callback1); - sensor.on(sensor.SensorId.ROTATION_VECTOR, callback2); - // Unsubscribe from callback1. - sensor.off(sensor.SensorId.ROTATION_VECTOR, callback1); - // Unsubscribe from all callbacks of the SensorId.ROTATION_VECTOR type. - sensor.off(sensor.SensorId.ROTATION_VECTOR); + const statusChangeCallback = (data: sensor.SensorStatusEvent) => { + console.info('sensorStatusChange : ' + JSON.stringify(data)); + } + const statusChangeCallback2 = (data: sensor.SensorStatusEvent) => { + console.info('sensorStatusChange2 : ' + JSON.stringify(data)); + } + // Register two callback listeners for device online events. + sensor.on('sensorStatusChange', statusChangeCallback); + sensor.on('sensorStatusChange', statusChangeCallback2); + + // Unregister the first listener after 3 seconds. + setTimeout(() => { + sensor.off('sensorStatusChange', statusChangeCallback); + }, 3000); + // Unregister the other listener after 5 seconds. + setTimeout(() => { + sensor.off('sensorStatusChange'); + }, 5000); } catch (error) { let e: BusinessError = error as BusinessError; - console.error(`Failed to invoke off. Code: ${e.code}, message: ${e.message}`); + console.error(`Failed to invoke on. Code: ${e.code}, message: ${e.message}`); } ``` -### SIGNIFICANT_MOTION9+ -off(type: SensorId.SIGNIFICANT_MOTION, callback?: Callback<SignificantMotionResponse>): void +## sensor.getSensorListByDeviceSync19+ -Unsubscribes from the significant motion sensor data. +getSensorListByDeviceSync(deviceId?: number): Array<Sensor> + +Obtains the information about all sensors on the device. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9).SIGNIFICANT_MOTION | Yes | Sensor type. The value is fixed at **SensorId.SIGNIFICANT_MOTION**. | -| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| +| Name | Type | Mandatory| Description | +| --------------- | ------------------------------------------------------------ | ---- |--------| +| deviceId | number | No | Device ID. The default value is the ID of the local device.| -**Error codes** -For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). +**Return value** + +| Type | Description | +| ---------------------------------------------------------- | -------------- | +| Array<[Sensor](#sensor9)> | Sensor attribute list. | -| ID| Error Message | -| -------- | ------------------------------------------------------------ | -| 401 | Parameter error.Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | **Example** @@ -2914,49 +4720,41 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ import { sensor } from '@kit.SensorServiceKit'; import { BusinessError } from '@kit.BasicServicesKit'; -function callback1(data: object) { - console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); -} - -function callback2(data: object) { - console.info('Succeeded in getting callback2 data: ' + JSON.stringify(data)); -} - try { - sensor.on(sensor.SensorId.SIGNIFICANT_MOTION, callback1); - sensor.on(sensor.SensorId.SIGNIFICANT_MOTION, callback2); - // Unsubscribe from callback1. - sensor.off(sensor.SensorId.SIGNIFICANT_MOTION, callback1); - // Unsubscribe from all callbacks of the SensorId.SIGNIFICANT_MOTION type. - sensor.off(sensor.SensorId.SIGNIFICANT_MOTION); + const deviceId = 1; + // The first deviceId is optional. By default, it is set to the ID of the local device. + const sensorList: sensor.Sensor[] = sensor.getSensorListByDeviceSync(deviceId); + console.log(`sensorList length: ${sensorList.length}`); + console.log(`sensorList: ${JSON.stringify(sensorList)}`); } catch (error) { let e: BusinessError = error as BusinessError; - console.error(`Failed to invoke off. Code: ${e.code}, message: ${e.message}`); + console.error(`Failed to get sensorList. Code: ${e.code}, message: ${e.message}`); } ``` -### WEAR_DETECTION9+ -off(type: SensorId.WEAR_DETECTION, callback?: Callback<WearDetectionResponse>): void +## sensor.getSingleSensorByDeviceSync19+ -Unsubscribes from data of the wear detection sensor. +getSingleSensorByDeviceSync(type: SensorId, deviceId?: number): Array<Sensor> + +Obtains information about the sensor of a specific type. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9).WEAR_DETECTION | Yes | Sensor type. The value is fixed at **SensorId.WEAR_DETECTION**. | -| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | No | Callback used for unsubscription. If this parameter is not specified, all callbacks of the specified sensor type are unsubscribed from.| +| Name | Type | Mandatory| Description | +| --------------- | ------------------------------------------------------------ | ---- |----------| +| type | [SensorId](#sensorid9) | Yes | Sensor type.| +| deviceId | number | No | Device ID. The default value is the ID of the local device. | -**Error codes** -For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). +**Return value** + +| Type | Description | +| ---------------------------------------------------------- | -------------- | +| Array<[Sensor](#sensor9)> | Sensor attribute list. | -| ID| Error Message | -| -------- | ------------------------------------------------------------ | -| 401 | Parameter error.Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | **Example** @@ -2964,27 +4762,19 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ import { sensor } from '@kit.SensorServiceKit'; import { BusinessError } from '@kit.BasicServicesKit'; -function callback1(data: object) { - console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); -} - -function callback2(data: object) { - console.info('Succeeded in getting callback2 data: ' + JSON.stringify(data)); -} - try { - sensor.on(sensor.SensorId.WEAR_DETECTION, callback1); - sensor.on(sensor.SensorId.WEAR_DETECTION, callback2); - // Unsubscribe from callback1. - sensor.off(sensor.SensorId.WEAR_DETECTION, callback1); - // Unsubscribe from all callbacks of the SensorId.WEAR_DETECTION type. - sensor.off(sensor.SensorId.WEAR_DETECTION); + const deviceId = 1; + // The second deviceId is optional. + const sensorList: sensor.Sensor[] = sensor.getSingleSensorByDeviceSync(sensor.SensorId.ACCELEROMETER, deviceId); + console.log(`sensorList length: ${sensorList.length}`); + console.log(`sensorList Json: ${JSON.stringify(sensorList)}`); } catch (error) { let e: BusinessError = error as BusinessError; - console.error(`Failed to invoke off. Code: ${e.code}, message: ${e.message}`); + console.error(`Failed to get sensorList. Code: ${e.code}, message: ${e.message}`); } ``` + ## sensor.getGeomagneticInfo9+ getGeomagneticInfo(locationOptions: LocationOptions, timeMillis: number, callback: AsyncCallback<GeomagneticResponse>): void @@ -4041,7 +5831,7 @@ For details about the following error codes, see [Sensor Error Codes](errorcode- | ID| Error Message | | -------- | ------------------ | -| 14500101 | Service exception. | +| 14500101 | Service exception.Possible causes:1. Sensor hdf service exception;2. Sensor service ipc exception;3.Sensor data channel exception. | **Example** @@ -4228,6 +6018,36 @@ Enumerates the sensor types. | WEAR_DETECTION | 280 | Wear detection sensor. | | ACCELEROMETER_UNCALIBRATED | 281 | Uncalibrated acceleration sensor. | + +## SensorInfoParam19+ + +Defines sensor parameters, including **deviceId** and **sensorIndex**. + +**System capability**: SystemCapability.Sensors.Sensor + + +| Name| Type | Mandatory| Description | +| ------ | ---------------------- | ---- |-------------------------| +| deviceId | number | No | Device ID. The default value is **-1**, which indicates the local device. You can use [getSensorListByDeviceSync](#sensorgetsensorlistbydevicesync19) to query other device IDs. | +| sensorIndex | number | No | Sensor index. The default value is **0**, which indicates the default sensor on the device. You can use [getSensorListByDeviceSync](#sensorgetsensorlistbydevicesync19) to query other sensor IDs.| + + +## SensorStatusEvent19+ + +Defines a device status change event. + +**System capability**: SystemCapability.Sensors.Sensor + + +| Name| Type | Description | +| ------ | ---------------------- | ------------ | +| timestamp | number | Timestamp when an event occurs.| +| sensorId | number | Sensor ID.| +| sensorIndex | number | Sensor index.| +| isSensorOnline | boolean | Sensor status. The value **true** indicates that the sensor is online, and the value **false** indicates the opposite.| +| deviceId | number | Device ID.| +| deviceName | string | Device name.| + ## SensorType(deprecated) Enumerates the sensor types. @@ -4282,7 +6102,7 @@ Describes the timestamp of the sensor data. **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable| Writable| Description | +| Name | Type | Read-Only| Optional| Description | | --------- | ------ | ---- | ---- | ------------------------ | | timestamp | number | Yes | Yes | Timestamp when the sensor reports data.| | accuracy11+ | [SensorAccuracy](#sensoraccuracy11)11+ | Yes | No | Accuracy of the sensor data.| @@ -4293,18 +6113,22 @@ Describes the sensor information. **System capability**: SystemCapability.Sensors.Sensor -| Name | Type| Readable| Writable| Description | -| --------------- | -------- | ---------------------- | ---------------------- | ---------------------- | -| sensorName | string | Yes | No | Sensor name. | -| vendorName | string | Yes | No | Vendor of the sensor. | -| firmwareVersion | string | Yes | No | Firmware version of the sensor. | -| hardwareVersion | string | Yes | No | Hardware version of the sensor. | -| sensorId | number | Yes | No | Sensor type ID. | -| maxRange | number | Yes | No | Maximum measurement range of the sensor.| -| minSamplePeriod | number | Yes | No | Minimum sampling period. | -| maxSamplePeriod | number | Yes | No | Maximum sampling period. | -| precision | number | Yes | No | Precision of the sensor. | -| power | number | Yes | No | Estimated sensor power, in mA. | +| Name | Type | Read-Only| Optional| Description | +|-----------------------------|---------|----|----|------------------| +| sensorName | string | Yes | No | Sensor name. | +| vendorName | string | Yes | No | Vendor of the sensor. | +| firmwareVersion | string | Yes | No | Firmware version of the sensor. | +| hardwareVersion | string | Yes | No | Hardware version of the sensor. | +| sensorId | number | Yes | No | Sensor type ID. | +| maxRange | number | Yes | No | Maximum measurement range of the sensor. | +| minSamplePeriod | number | Yes | No | Minimum sampling period. | +| maxSamplePeriod | number | Yes | No | Maximum sampling period. | +| precision | number | Yes | No | Precision of the sensor. | +| power | number | Yes | No | Estimated sensor power, in mA.| +| sensorIndex19+ | number | Yes | Yes | Sensor index. | +| deviceId19+ | number | Yes | Yes | Device ID. | +| deviceName19+ | string | Yes | Yes | Device name. | +| isLocalSensor19+ | boolean | Yes | Yes | Whether the sensor is a local sensor. | ## AccelerometerResponse @@ -4315,7 +6139,7 @@ Describes the acceleration sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name| Type | Readable| Writable| Description | +| Name| Type | Read-Only| Optional| Description | | ---- | ------ | ---- | ---- | ---------------------------------------------------------- | | x | number | Yes | Yes | Acceleration along the x-axis of the device, in m/s². The value is equal to the reported physical quantity.| | y | number | Yes | Yes | Acceleration along the y-axis of the device, in m/s². The value is equal to the reported physical quantity.| @@ -4329,7 +6153,7 @@ Describes the linear acceleration sensor data. It extends from [Response](#respo **System capability**: SystemCapability.Sensors.Sensor -| Name| Type | Readable| Writable| Description | +| Name| Type | Read-Only| Optional| Description | | ---- | ------ | ---- | ---- | ---------------------------------------- | | x | number | Yes | Yes | Linear acceleration along the x-axis of the device, in m/s².| | y | number | Yes | Yes | Linear acceleration along the y-axis of the device, in m/s².| @@ -4343,7 +6167,7 @@ Describes the uncalibrated acceleration sensor data. It extends from [Response]( **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable| Writable| Description | +| Name | Type | Read-Only| Optional| Description | | ----- | ------ | ---- | ---- | ---------------------------------------------- | | x | number | Yes | Yes | Uncalibrated acceleration along the x-axis of the device, in m/s². | | y | number | Yes | Yes | Uncalibrated acceleration along the y-axis of the device, in m/s². | @@ -4360,7 +6184,7 @@ Describes the gravity sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name| Type | Readable| Writable| Description | +| Name| Type | Read-Only| Optional| Description | | ---- | ------ | ---- | ---- | ---------------------------------------- | | x | number | Yes | Yes | Gravitational acceleration along the x-axis of the device, in m/s².| | y | number | Yes | Yes | Gravitational acceleration along the y-axis of the device, in m/s².| @@ -4376,7 +6200,7 @@ Describes the orientation sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable| Writable| Description | +| Name | Type | Read-Only| Optional| Description | | ----- | ------ | ---- | ---- | ----------------------------------------------------- | | alpha | number | Yes | Yes | Rotation angle of the device around the z-axis, in degrees. The value ranges from 0 to 360. | | beta | number | Yes | Yes | Rotation angle of the device around the x-axis, in degrees. The value ranges from 0 to ±180.| @@ -4390,7 +6214,7 @@ Describes the rotation vector sensor data. It extends from [Response](#response) **System capability**: SystemCapability.Sensors.Sensor -| Name| Type | Readable| Writable| Description | +| Name| Type | Read-Only| Optional| Description | | ---- | ------ | ---- | ---- | ----------------- | | x | number | Yes | Yes | X-component of the rotation vector.| | y | number | Yes | Yes | Y-component of the rotation vector.| @@ -4407,7 +6231,7 @@ Describes the gyroscope sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name| Type | Readable| Writable| Description | +| Name| Type | Read-Only| Optional| Description | | ---- | ------ | ---- | ---- | ------------------------------------------------------ | | x | number | Yes | Yes | Angular velocity of rotation around the x-axis of the device, in rad/s. The value is equal to the reported physical quantity.| | y | number | Yes | Yes | Angular velocity of rotation around the y-axis of the device, in rad/s. The value is equal to the reported physical quantity.| @@ -4421,7 +6245,7 @@ Describes the uncalibrated gyroscope sensor data. It extends from [Response](#re **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable| Writable| Description | +| Name | Type | Read-Only| Optional| Description | | ----- | ------ | ---- | ---- | ------------------------------------------ | | x | number | Yes | Yes | Uncalibrated angular velocity of rotation around the x-axis of the device, in rad/s. | | y | number | Yes | Yes | Uncalibrated angular velocity of rotation around the y-axis of the device, in rad/s. | @@ -4438,7 +6262,7 @@ Describes the significant motion sensor data. It extends from [Response](#respon **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable| Writable| Description | +| Name | Type | Read-Only| Optional| Description | | ------ | ------ | ---- | ---- | ------------------------------------------------------------ | | scalar | number | Yes | Yes | Intensity of a motion. This parameter specifies whether a device has a significant motion on three physical axes (X, Y, and Z). The value **1** is reported when the device has a significant motion.| @@ -4450,7 +6274,7 @@ Describes the proximity sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable| Writable| Description | +| Name | Type | Read-Only| Optional| Description | | -------- | ------ | ---- | ---- | ---------------------------------------------------------- | | distance | number | Yes | Yes | Proximity between the visible object and the device monitor. The value **0** means the two are close to each other, and a value greater than 0 means that they are far away from each other.| @@ -4462,7 +6286,7 @@ Describes the ambient light sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable| Writable| Description | +| Name | Type | Read-Only| Optional| Description | | ------------------------------- | ------ | ---- | ---- | ------------------------------------------------------------ | | intensity | number | Yes | Yes | Illumination, in lux. | | colorTemperature12+ | number | Yes | Yes | Color temperature, in Kelvin. This parameter is optional. If this parameter is not supported, **undefined** is returned. If this parameter is supported, a normal value is returned.| @@ -4476,7 +6300,7 @@ Describes the Hall effect sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable| Writable| Description | +| Name | Type | Read-Only| Optional| Description | | ------ | ------ | ---- | ---- | ------------------------------------------------------------ | | status | number | Yes | Yes | Hall effect sensor status. This parameter specifies whether a magnetic field exists around a device. The value **0** means that a magnetic field does not exist, and a value greater than **0** means the opposite.| @@ -4488,7 +6312,7 @@ Describes the magnetic field sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name| Type | Readable| Writable| Description | +| Name| Type | Read-Only| Optional| Description | | ---- | ------ | ---- | ---- | ---------------------------- | | x | number | Yes | Yes | Magnetic field strength on the x-axis, in μT.| | y | number | Yes | Yes | Magnetic field strength on the y-axis, in μT.| @@ -4502,7 +6326,7 @@ Describes the uncalibrated magnetic field sensor data. It extends from [Response **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable| Writable| Description | +| Name | Type | Read-Only| Optional| Description | | ----- | ------ | ---- | ---- | -------------------------------------- | | x | number | Yes | Yes | Uncalibrated magnetic field strength on the x-axis, in μT. | | y | number | Yes | Yes | Uncalibrated magnetic field strength on the y-axis, in μT. | @@ -4519,7 +6343,7 @@ Describes the pedometer sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable| Writable| Description | +| Name | Type | Read-Only| Optional| Description | | ----- | ------ | ---- | ---- | ---------------- | | steps | number | Yes | Yes | Number of steps a user has walked.| @@ -4531,7 +6355,7 @@ Describes the humidity sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable| Writable| Description | +| Name | Type | Read-Only| Optional| Description | | -------- | ------ | ---- | ---- | --------------------------------------------------------- | | humidity | number | Yes | Yes | Ambient relative humidity, in a percentage (%).| @@ -4543,7 +6367,7 @@ Describes the pedometer detection sensor data. It extends from [Response](#respo **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable| Writable| Description | +| Name | Type | Read-Only| Optional| Description | | ------ | ------ | ---- | ---- | ------------------------------------------------------------ | | scalar | number | Yes | Yes | Pedometer detection. This parameter specifies whether a user takes a step. The value **0** means that the user does not take a step, and **1** means that the user takes a step.| @@ -4555,7 +6379,7 @@ Describes the ambient temperature sensor data. It extends from [Response](#respo **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable| Writable| Description | +| Name | Type | Read-Only| Optional| Description | | ----------- | ------ | ---- | ---- | -------------------------- | | temperature | number | Yes | Yes | Ambient temperature, in degree Celsius.| @@ -4567,7 +6391,7 @@ Describes the barometer sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable| Writable| Description | +| Name | Type | Read-Only| Optional| Description | | -------- | ------ | ---- | ---- | ---------------------- | | pressure | number | Yes | Yes | Atmospheric pressure, in units of hPa.| @@ -4579,7 +6403,7 @@ Describes the heart rate sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable| Writable| Description | +| Name | Type | Read-Only| Optional| Description | | --------- | ------ | ---- | ---- | --------------------------------------- | | heartRate | number | Yes | Yes | Heart rate, in beats per minute (bpm).| @@ -4591,7 +6415,7 @@ Describes the wear detection sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable| Writable| Description | +| Name | Type | Read-Only| Optional| Description | | ----- | ------ | ---- | ---- | ------------------------------------------------ | | value | number | Yes | Yes | Whether the device is being worn. The value **1** means that the device is being worn, and **0** means the opposite.| @@ -4604,9 +6428,10 @@ Describes the sensor data reporting frequency. **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable| Writable| Description | +| Name | Type | Read-Only| Optional| Description | | -------- | ----------------------------------------------------------- | ---- | ---- | ------------------------------------------------------------ | | interval | number\|[SensorFrequency](#sensorfrequency11)11+ | Yes | Yes | Frequency at which a sensor reports data. The default value is 200,000,000 ns. The maximum and minimum values of this parameter are determined by the reporting frequency supported by the hardware. If the configured frequency is greater than the maximum value, the maximum value is used for data reporting. If the configured frequency is less than the minimum value, the minimum value is used for data reporting.| +| sensorInfoParam19+ | [SensorInfoParam](#sensorinfoparam19) | Yes| Yes| Sensor parameters, including **deviceId** and **sensorIndex**.| ## SensorFrequency11+ @@ -4630,7 +6455,7 @@ Describes the response for setting the rotation matrix. **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable| Writable| Description | +| Name | Type | Read-Only| Optional| Description | | ----------- | ------------------- | ---- | ---- | ---------- | | rotation | Array<number> | Yes | Yes | Rotation matrix.| | inclination | Array<number> | Yes | Yes | Inclination matrix.| @@ -4642,7 +6467,7 @@ Describes the coordinate options. **System capability**: SystemCapability.Sensors.Sensor -| Name| Type | Readable| Writable| Description | +| Name| Type | Read-Only| Optional| Description | | ---- | ------ | ---- | ---- | ----------- | | x | number | Yes | Yes | X coordinate direction.| | y | number | Yes | Yes | Y coordinate direction.| @@ -4654,7 +6479,7 @@ Describes a geomagnetic response object. **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable| Writable| Description | +| Name | Type | Read-Only| Optional| Description | | --------------- | ------ | ---- | ---- | -------------------------------------------------- | | x | number | Yes | Yes | North component of the geomagnetic field. | | y | number | Yes | Yes | East component of the geomagnetic field. | @@ -4670,7 +6495,7 @@ Describes the geographical location. **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable| Writable| Description | +| Name | Type | Read-Only| Optional| Description | | --------- | ------ | ---- | ---- | ---------- | | latitude | number | Yes | Yes | Latitude. | | longitude | number | Yes | Yes | Longitude. | diff --git a/en/application-dev/reference/apis-sensor-service-kit/js-apis-vibrator.md b/en/application-dev/reference/apis-sensor-service-kit/js-apis-vibrator.md index dd38e7259a162f5ce57fe998cba5b0c29913a8ac..f05f229761d8b7e25ee047543c28368090c78e68 100644 --- a/en/application-dev/reference/apis-sensor-service-kit/js-apis-vibrator.md +++ b/en/application-dev/reference/apis-sensor-service-kit/js-apis-vibrator.md @@ -1,6 +1,6 @@ # @ohos.vibrator (Vibrator) -The **vibrator** module provides APIs for starting or stopping vibration. +The **vibrator** module allows precise control over the vibration of device vibrators. With the APIs provided by this module, you can start vibration in various modes such as specified duration, preset effect, and custom effect and stop any or all of them. > **NOTE** > @@ -29,9 +29,9 @@ Starts vibration with the specified effect and attribute. This API uses an async | Name | Type | Mandatory| Description | | --------- | -------------------------------------- | ---- | :----------------------------------------------------------- | -| effect | [VibrateEffect](#vibrateeffect9) | Yes | Vibration effect. The following options are supported:
- [VibrateTime](#vibratetime9): vibration with the specified duration.
- [VibratePreset](#vibratepreset9): vibration with a preset effect.
- [VibrateFromFile](#vibratefromfile10): vibration according to a custom vibration configuration file.
- [VibrateFromPattern18+](#vibratefrompattern18): vibration according to a custom vibration pattern.| +| effect | [VibrateEffect](#vibrateeffect9) | Yes | Vibration effect. The following options are supported:
- [VibratePreset](#vibratepreset9): triggers vibration according to preset vibration effects. This mode is suitable for short vibration scenarios in interactive feedback (such as tapping, long-pressing, sliding, dragging, etc.). This API is recommended to maintain consistency with the system's overall vibration feedback experience.
- [VibrateFromFile](#vibratefromfile10): triggers vibration according to custom vibration configuration file. This mode is suitable for interactive feedback in complex scenarios requiring precise vibration patterns (such as realistic effects triggered by emoji packs, or feedback for in-game actions/mechanics).
- [VibrateTime](#vibratetime9): triggers vibration of the specified duration, providing basic control over the start and stop of vibration. This mode does not support customization of vibration intensity, frequency, or other parameters. As a result, the vibration adjustment is relatively coarse and not suitable for delivering a refined experience.
- [VibrateFromPattern18+](#vibratefrompattern18): triggers vibration according to a custom vibration pattern. The usage scenario is the same as **VibrateFromFile**. **VibrateFromFile** utilizes predefined effects in a custom configuration file, passing specific vibration events to the API via file descriptors. By contrast, **VibrateFromPattern** enables more flexible vibration event combinations, delivering them to the API as a vibration event array.| | attribute | [VibrateAttribute](#vibrateattribute9) | Yes | Vibration attribute. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the vibration starts, **err** is **undefined**; otherwise, **err** is an error object. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object, which contains the error code and error information.| **Error codes** @@ -46,108 +46,123 @@ For details about the error codes, see [Vibrator Error Codes](errorcode-vibrator **Example** -Trigger vibration with the specified duration. - -```ts -import { vibrator } from '@kit.SensorServiceKit'; -import { BusinessError } from '@kit.BasicServicesKit'; - -try { - vibrator.startVibration({ - type: 'time', - duration: 1000, - }, { - id: 0, - usage: 'alarm' // The switch control is subject to the selected type. - }, (error: BusinessError) => { - if (error) { - console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); - return; - } - console.info('Succeed in starting vibration'); - }); -} catch (err) { - let e: BusinessError = err as BusinessError; - console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); -} -``` - -Trigger vibration with a preset effect. - -```ts -import { vibrator } from '@kit.SensorServiceKit'; -import { BusinessError } from '@kit.BasicServicesKit'; - -try { - vibrator.startVibration({ - type: 'preset', - effectId: 'haptic.clock.timer', - count: 1, - }, { - id: 0, - usage: 'alarm' // The switch control is subject to the selected type. - }, (error: BusinessError) => { - if (error) { - console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); - return; - } - console.info('Succeed in starting vibration'); - }); -} catch (err) { - let e: BusinessError = err as BusinessError; - console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); -} -``` - -Trigger vibration according to a custom vibration configuration file. - -```ts -import { vibrator } from '@kit.SensorServiceKit'; -import { resourceManager } from '@kit.LocalizationKit'; -import { BusinessError } from '@kit.BasicServicesKit'; - -const fileName: string = 'xxx.json'; - -@Entry -@Component -struct Index { - uiContext = this.getUIContext(); - - build() { - Row() { - Column() { - Button('alarm-file') - .onClick(() => { - let rawFd: resourceManager.RawFileDescriptor | undefined = this.uiContext.getHostContext()?.resourceManager.getRawFdSync(fileName); - if (rawFd != undefined) { - try { - vibrator.startVibration({ - type: "file", - hapticFd: { fd: rawFd.fd, offset: rawFd.offset, length: rawFd.length } - }, { - id: 0, - usage: 'alarm' // The switch control is subject to the selected type. - }, (error: BusinessError) => { - if (error) { - console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); - return; - } - console.info('Succeed in starting vibration'); - }); - } catch (err) { - let e: BusinessError = err as BusinessError; - console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); - } - } - this.uiContext.getHostContext()?.resourceManager.closeRawFdSync(fileName); - }) - } - .width('100%') - } - .height('100%') - } -} -``` +1. Start vibration based on the preset effect. + + ```ts + import { vibrator } from '@kit.SensorServiceKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + try { + // Check whether 'haptic.notice.success' is supported. + vibrator.isSupportEffect('haptic.notice.success', (err: BusinessError, state: boolean) => { + if (err) { + console.error(`Failed to query effect. Code: ${err.code}, message: ${err.message}`); + return; + } + console.info('Succeed in querying effect'); + if (state) { + try { + vibrator.startVibration({ + type: 'preset', + effectId: 'haptic.notice.success', + count: 1, + }, { + usage: 'notification' // The switch control is subject to the selected type. + }, (error: BusinessError) => { + if (error) { + console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); + return; + } + console.info('Succeed in starting vibration'); + + }); + } catch (err) { + let e: BusinessError = err as BusinessError; + console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); + } + } + }) + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); + } + ``` + +2. Start vibration according to the custom vibration configuration file. + + ```ts + import { vibrator } from '@kit.SensorServiceKit'; + import { resourceManager } from '@kit.LocalizationKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + const fileName: string = 'xxx.json'; + + @Entry + @Component + struct Index { + uiContext = this.getUIContext(); + + build() { + Row() { + Column() { + Button('alarm-file') + .onClick(() => { + let rawFd: resourceManager.RawFileDescriptor | undefined = this.uiContext.getHostContext()?.resourceManager.getRawFdSync(fileName); + if (rawFd != undefined) { + try { + vibrator.startVibration({ + type: "file", + hapticFd: { fd: rawFd.fd, offset: rawFd.offset, length: rawFd.length } + }, { + id: 0, + usage: 'alarm' // The switch control is subject to the selected type. + }, (error: BusinessError) => { + if (error) { + console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); + return; + } + console.info('Succeed in starting vibration'); + }); + } catch (err) { + let e: BusinessError = err as BusinessError; + console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); + } + } + this.uiContext.getHostContext()?.resourceManager.closeRawFdSync(fileName); + }) + } + .width('100%') + } + .height('100%') + } + } + ``` + +3. Start vibration of the specified duration. + + ```ts + import { vibrator } from '@kit.SensorServiceKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + try { + vibrator.startVibration({ + type: 'time', + duration: 1000, + }, { + id: 0, + usage: 'alarm' // The switch control is subject to the selected type. + }, (error: BusinessError) => { + if (error) { + console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); + return; + } + console.info('Succeed in starting vibration'); + }); + } catch (err) { + let e: BusinessError = err as BusinessError; + console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); + } + ``` ## vibrator.startVibration9+ @@ -165,13 +180,13 @@ Starts vibration with the specified effect and attribute. This API uses a promis | Name | Type | Mandatory| Description | | --------- | -------------------------------------- | ---- | ------------------------------------------------------------ | -| effect | [VibrateEffect](#vibrateeffect9) | Yes | Vibration effect. The following options are supported:
- [VibrateTime](#vibratetime9): vibration with the specified duration.
- [VibratePreset](#vibratepreset9): vibration with a preset effect.
- [VibrateFromFile](#vibratefromfile10): vibration according to a custom vibration configuration file.
- [VibrateFromPattern18+](#vibratefrompattern18): vibration according to a custom vibration pattern.| +| effect | [VibrateEffect](#vibrateeffect9) | Yes | Vibration effect. The following options are supported:
- [VibratePreset](#vibratepreset9): triggers vibration according to preset vibration effects. This mode is suitable for short vibration scenarios in interactive feedback (such as tapping, long-pressing, sliding, dragging, etc.). This API is recommended to maintain consistency with the system's overall vibration feedback experience.
- [VibrateFromFile](#vibratefromfile10): triggers vibration according to custom vibration configuration file. This mode is suitable for interactive feedback in complex scenarios requiring precise vibration patterns (such as realistic effects triggered by emoji packs, or feedback for in-game actions/mechanics).
- [VibrateTime](#vibratetime9): triggers vibration of the specified duration, providing basic control over the start and stop of vibration. This mode does not support customization of vibration intensity, frequency, or other parameters. As a result, the vibration adjustment is relatively coarse and not suitable for delivering a refined experience.
- [VibrateFromPattern18+](#vibratefrompattern18): triggers vibration according to a custom vibration pattern. The usage scenario is the same as **VibrateFromFile**. **VibrateFromFile** utilizes predefined effects in a custom configuration file, passing specific vibration events to the API via file descriptors. By contrast, **VibrateFromPattern** enables more flexible vibration event combinations, delivering them to the API as a vibration event array.| | attribute | [VibrateAttribute](#vibrateattribute9) | Yes | Vibration attribute. | **Return value** -| Type | Description | -| ------------------- | -------------------------------------- | +| Type | Description | +| ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| **Error codes** @@ -187,104 +202,121 @@ For details about the error codes, see [Vibrator Error Codes](errorcode-vibrator **Example** -Trigger vibration with the specified duration. - -```ts -import { vibrator } from '@kit.SensorServiceKit'; -import { BusinessError } from '@kit.BasicServicesKit'; - -try { - vibrator.startVibration({ - type: 'time', - duration: 1000 - }, { - id: 0, - usage: 'alarm' // The switch control is subject to the selected type. - }).then(() => { - console.info('Succeed in starting vibration'); - }, (error: BusinessError) => { - console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); - }); -} catch (err) { - let e: BusinessError = err as BusinessError; - console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); -} -``` - -Trigger vibration with a preset effect. - -```ts -import { vibrator } from '@kit.SensorServiceKit'; -import { BusinessError } from '@kit.BasicServicesKit'; - -try { - vibrator.startVibration({ - type: 'preset', - effectId: 'haptic.clock.timer', - count: 1, - }, { - id: 0, - usage: 'alarm' // The switch control is subject to the selected type. - }).then(() => { - console.info('Succeed in starting vibration'); - }, (error: BusinessError) => { - console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); - }); -} catch (err) { - let e: BusinessError = err as BusinessError; - console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); -} -``` - -Trigger vibration according to a custom vibration configuration file. - -```ts -import { vibrator } from '@kit.SensorServiceKit'; -import { resourceManager } from '@kit.LocalizationKit'; -import { BusinessError } from '@kit.BasicServicesKit'; - -const fileName: string = 'xxx.json'; - -@Entry -@Component -struct Index { - uiContext = this.getUIContext(); - - build() { - Row() { - Column() { - Button('alarm-file') - .onClick(() => { - let rawFd: resourceManager.RawFileDescriptor | undefined = this.uiContext.getHostContext()?.resourceManager.getRawFdSync(fileName); - if (rawFd != undefined) { - try { - vibrator.startVibration({ - type: "file", - hapticFd: { fd: rawFd.fd, offset: rawFd.offset, length: rawFd.length } - }, { - id: 0, - usage: 'alarm' // The switch control is subject to the selected type. - }, (error: BusinessError) => { - if (error) { - console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); - return; - } - console.info('Succeed in starting vibration'); - }); - } catch (err) { - let e: BusinessError = err as BusinessError; - console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); - } - } - this.uiContext.getHostContext()?.resourceManager.closeRawFdSync(fileName); - }) - } - .width('100%') - } - .height('100%') - } -} -``` +1. Start vibration based on the preset effect. + + ```ts + import { vibrator } from '@kit.SensorServiceKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + try { + // Check whether 'haptic.notice.success' is supported. + vibrator.isSupportEffect('haptic.notice.success', (err: BusinessError, state: boolean) => { + if (err) { + console.error(`Failed to query effect. Code: ${err.code}, message: ${err.message}`); + return; + } + console.info('Succeed in querying effect'); + if (state) { + try { + vibrator.startVibration({ + type: 'preset', + effectId: 'haptic.notice.success', + count: 1, + }, { + usage: 'notification' // The switch control is subject to the selected type. + }, (error: BusinessError) => { + if (error) { + console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); + return; + } + console.info('Succeed in starting vibration'); + + }); + } catch (err) { + let e: BusinessError = err as BusinessError; + console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); + } + } + }) + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); + } + ``` + +2. Start vibration according to the custom vibration configuration file. + + ```ts + import { vibrator } from '@kit.SensorServiceKit'; + import { resourceManager } from '@kit.LocalizationKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + const fileName: string = 'xxx.json'; + + @Entry + @Component + struct Index { + uiContext = this.getUIContext(); + + build() { + Row() { + Column() { + Button('alarm-file') + .onClick(() => { + let rawFd: resourceManager.RawFileDescriptor | undefined = this.uiContext.getHostContext()?.resourceManager.getRawFdSync(fileName); + if (rawFd != undefined) { + try { + vibrator.startVibration({ + type: "file", + hapticFd: { fd: rawFd.fd, offset: rawFd.offset, length: rawFd.length } + }, { + id: 0, + usage: 'alarm' // The switch control is subject to the selected type. + }, (error: BusinessError) => { + if (error) { + console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); + return; + } + console.info('Succeed in starting vibration'); + }); + } catch (err) { + let e: BusinessError = err as BusinessError; + console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); + } + } + this.uiContext.getHostContext()?.resourceManager.closeRawFdSync(fileName); + }) + } + .width('100%') + } + .height('100%') + } + } + ``` + +3. Start vibration of the specified duration. + + ```ts + import { vibrator } from '@kit.SensorServiceKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + try { + vibrator.startVibration({ + type: 'time', + duration: 1000 + }, { + id: 0, + usage: 'alarm' // The switch control is subject to the selected type. + }).then(() => { + console.info('Succeed in starting vibration'); + }, (error: BusinessError) => { + console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); + }); + } catch (err) { + let e: BusinessError = err as BusinessError; + console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); + } + ``` ## vibrator.stopVibration9+ @@ -314,88 +346,88 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** -Stop fixed-duration vibration. - -```ts -import { vibrator } from '@kit.SensorServiceKit'; -import { BusinessError } from '@kit.BasicServicesKit'; - -try { - // Start vibration at a fixed duration. - vibrator.startVibration({ - type: 'time', - duration: 1000, - }, { - id: 0, - usage: 'alarm' // The switch control is subject to the selected type. - }, (error: BusinessError) => { - if (error) { - console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); - return; - } - console.info('Succeed in starting vibration'); - }); -} catch (err) { - let e: BusinessError = err as BusinessError; - console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); -} - -try { - // Stop vibration in VIBRATOR_STOP_MODE_TIME mode. - vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_TIME, (error: BusinessError) => { - if (error) { - console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); - return; - } - console.info('Succeed in stopping vibration'); - }) -} catch (err) { - let e: BusinessError = err as BusinessError; - console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); -} -``` - -Stop preset vibration. - -```ts -import { vibrator } from '@kit.SensorServiceKit'; -import { BusinessError } from '@kit.BasicServicesKit'; - -try { - // Start vibration with a preset effect. - vibrator.startVibration({ - type: 'preset', - effectId: 'haptic.clock.timer', - count: 1, - }, { - id: 0, - usage: 'alarm' // The switch control is subject to the selected type. - }, (error: BusinessError) => { - if (error) { - console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); - return; - } - console.info('Succeed in starting vibration'); - }); -} catch (err) { - let e: BusinessError = err as BusinessError; - console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); -} - -try { - // Stop vibration in VIBRATOR_STOP_MODE_PRESET mode. - vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET, (error: BusinessError) => { - if (error) { - console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); - return; - } - console.info('Succeed in stopping vibration'); - }) -} catch (err) { - let e: BusinessError = err as BusinessError; - console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); -} -``` +1. Stop vibration of the specified duration. + + ```ts + import { vibrator } from '@kit.SensorServiceKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + try { + // Start vibration of the specified duration. + vibrator.startVibration({ + type: 'time', + duration: 1000, + }, { + id: 0, + usage: 'alarm' // The switch control is subject to the selected type. + }, (error: BusinessError) => { + if (error) { + console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); + return; + } + console.info('Succeed in starting vibration'); + }); + } catch (err) { + let e: BusinessError = err as BusinessError; + console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); + } + + try { + // Stop vibration in VIBRATOR_STOP_MODE_TIME mode. + vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_TIME, (error: BusinessError) => { + if (error) { + console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); + return; + } + console.info('Succeed in stopping vibration'); + }) + } catch (err) { + let e: BusinessError = err as BusinessError; + console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); + } + ``` + +2. Stop vibration with the preset effect. + + ```ts + import { vibrator } from '@kit.SensorServiceKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + try { + // Start vibration with a preset effect. + vibrator.startVibration({ + type: 'preset', + effectId: 'haptic.notice.success', + count: 1, + }, { + id: 0, + usage: 'notification' // The switch control is subject to the selected type. + }, (error: BusinessError) => { + if (error) { + console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); + return; + } + console.info('Succeed in starting vibration'); + }); + } catch (err) { + let e: BusinessError = err as BusinessError; + console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); + } + + try { + // Stop vibration in VIBRATOR_STOP_MODE_PRESET mode. + vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET, (error: BusinessError) => { + if (error) { + console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); + return; + } + console.info('Succeed in stopping vibration'); + }) + } catch (err) { + let e: BusinessError = err as BusinessError; + console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); + } + ``` ## vibrator.stopVibration9+ @@ -409,14 +441,14 @@ Stops vibration in the specified mode. This API uses a promise to return the res **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------- | ---- | ------------------------ | -| stopMode | [VibratorStopMode](#vibratorstopmode) | Yes | Mode to stop the vibration. The options are as follows:
- **VIBRATOR_STOP_MODE_TIME**: used to stop fixed-duration vibration.
- **VIBRATOR_STOP_MODE_PRESET**: used to stop preset vibration.
To stop custom vibration, use [vibrator.stopVibration10+](#vibratorstopvibration10-1).| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | +| stopMode | [VibratorStopMode](#vibratorstopmode) | Yes | Vibration stop mode:
- **VIBRATOR_STOP_MODE_TIME**: used to stop vibration of the specified duration.
- **VIBRATOR_STOP_MODE_PRESET**: used to stop preset vibration.
To stop custom vibration, use [vibrator.stopVibration10+](#vibratorstopvibration10-1).| **Return value** -| Type | Description | -| ------------------- | -------------------------------------- | +| Type | Description | +| ------------------- | ------------- | | Promise<void> | Promise that returns no value.| **Error codes** @@ -430,80 +462,80 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** -Stop fixed-duration vibration. - -```ts -import { vibrator } from '@kit.SensorServiceKit'; -import { BusinessError } from '@kit.BasicServicesKit'; - -try { - // Start vibration at a fixed duration. - vibrator.startVibration({ - type: 'time', - duration: 1000, - }, { - id: 0, - usage: 'alarm' // The switch control is subject to the selected type. - }).then(() => { - console.info('Succeed in starting vibration'); - }, (error: BusinessError) => { - console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); - }); -} catch (err) { - let e: BusinessError = err as BusinessError; - console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); -} - -try { - // Stop vibration in VIBRATOR_STOP_MODE_TIME mode. - vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_TIME).then(() => { - console.info('Succeed in stopping vibration'); - }, (error: BusinessError) => { - console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); - }); -} catch (err) { - let e: BusinessError = err as BusinessError; - console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); -} -``` - -Stop preset vibration. - -```ts -import { vibrator } from '@kit.SensorServiceKit'; -import { BusinessError } from '@kit.BasicServicesKit'; - -try { - // Start vibration with a preset effect. - vibrator.startVibration({ - type: 'preset', - effectId: 'haptic.clock.timer', - count: 1, - }, { - id: 0, - usage: 'alarm' // The switch control is subject to the selected type. - }).then(() => { - console.info('Succeed in starting vibration'); - }, (error: BusinessError) => { - console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); - }); -} catch (err) { - let e: BusinessError = err as BusinessError; - console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); -} - -try { - // Stop vibration in VIBRATOR_STOP_MODE_PRESET mode. - vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then(() => { - console.info('Succeed in stopping vibration'); - }, (error: BusinessError) => { - console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); - }); -} catch (err) { - let e: BusinessError = err as BusinessError; - console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); -} -``` +1. Stop vibration of the specified duration. + + ```ts + import { vibrator } from '@kit.SensorServiceKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + try { + // Start vibration of the specified duration. + vibrator.startVibration({ + type: 'time', + duration: 1000, + }, { + id: 0, + usage: 'alarm' // The switch control is subject to the selected type. + }).then(() => { + console.info('Succeed in starting vibration'); + }, (error: BusinessError) => { + console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); + }); + } catch (err) { + let e: BusinessError = err as BusinessError; + console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); + } + + try { + // Stop vibration in VIBRATOR_STOP_MODE_TIME mode. + vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_TIME).then(() => { + console.info('Succeed in stopping vibration'); + }, (error: BusinessError) => { + console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); + }); + } catch (err) { + let e: BusinessError = err as BusinessError; + console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); + } + ``` + +2. Stop vibration with the preset effect. + + ```ts + import { vibrator } from '@kit.SensorServiceKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + try { + // Start vibration with a preset effect. + vibrator.startVibration({ + type: 'preset', + effectId: 'haptic.notice.success', + count: 1, + }, { + id: 0, + usage: 'notification' // The switch control is subject to the selected type. + }).then(() => { + console.info('Succeed in starting vibration'); + }, (error: BusinessError) => { + console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); + }); + } catch (err) { + let e: BusinessError = err as BusinessError; + console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); + } + + try { + // Stop vibration in VIBRATOR_STOP_MODE_PRESET mode. + vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then(() => { + console.info('Succeed in stopping vibration'); + }, (error: BusinessError) => { + console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); + }); + } catch (err) { + let e: BusinessError = err as BusinessError; + console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); + } + ``` ## vibrator.stopVibration10+ @@ -533,24 +565,24 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** -```ts -import { vibrator } from '@kit.SensorServiceKit'; -import { BusinessError } from '@kit.BasicServicesKit'; - -try { - // Stop vibration in all modes. - vibrator.stopVibration((error: BusinessError) => { - if (error) { - console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); - return; - } - console.info('Succeed in stopping vibration'); - }) -} catch (error) { - let e: BusinessError = error as BusinessError; - console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); -} -``` + ```ts + import { vibrator } from '@kit.SensorServiceKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + try { + // Stop vibration in all modes. + vibrator.stopVibration((error: BusinessError) => { + if (error) { + console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); + return; + } + console.info('Succeed in stopping vibration'); + }) + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); + } + ``` ## vibrator.stopVibration10+ @@ -580,22 +612,71 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** -```ts -import { vibrator } from '@kit.SensorServiceKit'; -import { BusinessError } from '@kit.BasicServicesKit'; - -try { - // Stop vibration in all modes. - vibrator.stopVibration().then(() => { - console.info('Succeed in stopping vibration'); - }, (error: BusinessError) => { - console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); - }); -} catch (error) { - let e: BusinessError = error as BusinessError; - console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); -} -``` + ```ts + import { vibrator } from '@kit.SensorServiceKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + try { + // Stop vibration in all modes. + vibrator.stopVibration().then(() => { + console.info('Succeed in stopping vibration'); + }, (error: BusinessError) => { + console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); + }); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); + } + ``` + +## vibrator.stopVibration19+ + +stopVibration(param?: VibratorInfoParam): Promise<void> + +Stops vibration based on the specified vibrator parameters. If no parameters are passed, this API stops all vibrators of the local device by default. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.VIBRATE + +**System capability**: SystemCapability.Sensors.MiscDevice + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- |-----------------------------------| +| param | [VibratorInfoParam](#vibratorinfoparam19) | No | Vibrator parameters, such as the specified device and vibrator. If this parameter is left unspecified, this API applies to all vibrators of the local device by default.| + +**Return value** + +| Type | Description | +| ------------------- | ------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message | +| -------- | ------------------ | +| 201 | Permission denied. | +| 14600101 | Device operation failed. | + +**Example** + + ```ts + import { vibrator } from '@kit.SensorServiceKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + try { + vibrator.stopVibration({ deviceId: 1, vibratorId: 3 }).then(() => { + console.info('Succeed in stopping vibration'); + }, (error: BusinessError) => { + console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); + }); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); + } + ``` ## vibrator.stopVibrationSync12+ @@ -620,19 +701,19 @@ For details about the error codes, see [Vibrator Error Codes](errorcode-vibrator **Example** -```ts -import { vibrator } from '@kit.SensorServiceKit'; -import { BusinessError } from '@kit.BasicServicesKit'; - -try { - // Stop any form of motor vibration. - vibrator.stopVibrationSync() - console.info('Succeed in stopping vibration'); -} catch (error) { - let e: BusinessError = error as BusinessError; - console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); -} -``` + ```ts + import { vibrator } from '@kit.SensorServiceKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + try { + // Stop any form of motor vibration. + vibrator.stopVibrationSync() + console.info('Succeed in stopping vibration'); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); + } + ``` ## vibrator.isSupportEffect10+ @@ -644,10 +725,10 @@ Checks whether an effect ID is supported. This API uses an asynchronous callback **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------- | ---- | ------------------------------------------------------ | -| effectId | string | Yes | Vibration effect ID. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. The value **true** means that the effect ID is supported, and **false** means the opposite.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ----------------------------------------------------------- | +| effectId | string | Yes | ID of the preset vibration effect. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. The value **true** means that the effect ID is supported, and the value **false** means the opposite.| **Error codes** @@ -660,45 +741,45 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** -```ts -import { vibrator } from '@kit.SensorServiceKit'; -import { BusinessError } from '@kit.BasicServicesKit'; - -try { - // Check whether 'haptic.clock.timer' is supported. - vibrator.isSupportEffect('haptic.clock.timer', (err: BusinessError, state: boolean) => { - if (err) { - console.error(`Failed to query effect. Code: ${err.code}, message: ${err.message}`); - return; - } - console.info('Succeed in querying effect'); - if (state) { - try { - // To use startVibration, you must configure the ohos.permission.VIBRATE permission. - vibrator.startVibration({ - type: 'preset', - effectId: 'haptic.clock.timer', - count: 1, - }, { - usage: 'unknown' // The switch control is subject to the selected type. - }, (error: BusinessError) => { - if (error) { - console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); - } else { - console.info('Succeed in starting vibration'); - } - }); - } catch (error) { - let e: BusinessError = error as BusinessError; - console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); - } - } - }) -} catch (error) { - let e: BusinessError = error as BusinessError; - console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); -} -``` + ```ts + import { vibrator } from '@kit.SensorServiceKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + try { + // Check whether 'haptic.notice.success' is supported. + vibrator.isSupportEffect('haptic.notice.success', (err: BusinessError, state: boolean) => { + if (err) { + console.error(`Failed to query effect. Code: ${err.code}, message: ${err.message}`); + return; + } + console.info('Succeed in querying effect'); + if (state) { + try { + // To use startVibration, you must configure the ohos.permission.VIBRATE permission. + vibrator.startVibration({ + type: 'preset', + effectId: 'haptic.notice.success', + count: 1, + }, { + usage: 'unknown' // The switch control is subject to the selected type. + }, (error: BusinessError) => { + if (error) { + console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); + } else { + console.info('Succeed in starting vibration'); + } + }); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); + } + } + }) + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); + } + ``` ## vibrator.isSupportEffect10+ @@ -710,15 +791,15 @@ Checks whether an effect ID is supported. This API uses a promise to return the **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------ | ---- | ------------ | -| effectId | string | Yes | Vibration effect ID.| +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ---------------------- | +| effectId | string | Yes | ID of the preset vibration effect.| **Return value** -| Type | Description | -| ---------------------- | --------------------------------------------------------- | -| Promise<boolean> | Promise that returns the result. The value **true** means that the effect ID is supported, and **false** means the opposite.| +| Type | Description | +| ---------------------- | ------------------------------------------------------------ | +| Promise<boolean> | Promise that returns the result. The value **true** means that the effect ID is supported, and the value **false** means the opposite.| **Error codes** @@ -731,40 +812,40 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** -```ts -import { vibrator } from '@kit.SensorServiceKit'; -import { BusinessError } from '@kit.BasicServicesKit'; - -try { - // Check whether 'haptic.clock.timer' is supported. - vibrator.isSupportEffect('haptic.clock.timer').then((state: boolean) => { - console.info(`The query result is ${state}`); - if (state) { - try { - vibrator.startVibration({ - type: 'preset', - effectId: 'haptic.clock.timer', - count: 1, - }, { - usage: 'unknown' // The switch control is subject to the selected type. - }).then(() => { - console.info('Succeed in starting vibration'); - }).catch((error: BusinessError) => { - console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); - }); - } catch (error) { - let e: BusinessError = error as BusinessError; - console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); - } - } - }, (error: BusinessError) => { - console.error(`Failed to query effect. Code: ${error.code}, message: ${error.message}`); - }) -} catch (error) { - let e: BusinessError = error as BusinessError; - console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); -} -``` + ```ts + import { vibrator } from '@kit.SensorServiceKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + try { + // Check whether 'haptic.notice.success' is supported. + vibrator.isSupportEffect('haptic.notice.success').then((state: boolean) => { + console.info(`The query result is ${state}`); + if (state) { + try { + vibrator.startVibration({ + type: 'preset', + effectId: 'haptic.notice.success', + count: 1, + }, { + usage: 'unknown' // The switch control is subject to the selected type. + }).then(() => { + console.info('Succeed in starting vibration'); + }).catch((error: BusinessError) => { + console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); + }); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); + } + } + }, (error: BusinessError) => { + console.error(`Failed to query effect. Code: ${error.code}, message: ${error.message}`); + }) + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); + } + ``` ## vibrator.isSupportEffectSync12+ @@ -776,15 +857,15 @@ Checks whether the preset vibration effect is supported. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------ | ---- | -------------------- | +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ---------------------- | | effectId | string | Yes | ID of the preset vibration effect.| **Return value** -| Type | Description | -| ------- | ------------------------------------------------------ | -| boolean | Returned object. The value **true** means that the effect ID is supported, and **false** means the opposite.| +| Type | Description | +| ------- | ----------------------------------------------------------- | +| boolean | Returned object. The value **true** means that the effect ID is supported, and the value **false** means the opposite.| **Error codes** @@ -797,19 +878,247 @@ For details about the error codes, see [Vibrator Error Codes](errorcode-vibrator **Example** -```ts -import { vibrator } from '@kit.SensorServiceKit'; -import { BusinessError } from '@kit.BasicServicesKit'; - -try { - // Check whether the preset 'haptic.clock.timer' is supported. - let ret = vibrator.isSupportEffectSync('haptic.clock.timer'); - console.info(`The query result is ${ret}`); -} catch (error) { - let e: BusinessError = error as BusinessError; - console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); -} -``` + ```ts + import { vibrator } from '@kit.SensorServiceKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + try { + // Check whether the preset 'haptic.notice.success' is supported. + let ret = vibrator.isSupportEffectSync('haptic.notice.success'); + console.info(`The query result is ${ret}`); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); + } + ``` + +## vibrator.getEffectInfoSync19+ + +getEffectInfoSync(effectId: string, param?: VibratorInfoParam): EffectInfo; + +Obtains the preset vibration effect based on the device ID and vibrator ID to determine whether the preset vibration effect is supported. + +**System capability**: SystemCapability.Sensors.MiscDevice + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- |-----------------------------| +| effectId | string | Yes | ID of the preset vibration effect. | +| param | [VibratorInfoParam](#vibratorinfoparam19) | No | Device ID and vibrator ID. If this parameter is left unspecified, this API applies to the local device by default.| + +**Error codes** + +For details about the error codes, see [Vibrator Error Codes](errorcode-vibrator.md). + +| ID| Error Message | +| -------- | ------------------------ | +| 14600101 | Device operation failed. | + +**Return value** + +| Type | Description | +| ------- | --------------------------------------------------------- | +| [EffectInfo](#effectinfo19) | Whether the preset vibration effect is supported.| + + +**Example** + + ```ts + import { vibrator } from '@kit.SensorServiceKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + try { + const effectInfo: vibrator.EffectInfo = vibrator.getEffectInfoSync('haptic.clock.timer', { deviceId: 1, vibratorId: 3}); + console.log(`isEffectSupported: ${effectInfo.isEffectSupported}`); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); + } + ``` + + +## vibrator.getVibratorInfoSync19+ + +getVibratorInfoSync(param?: VibratorInfoParam): Array<VibratorInfo>; + +Queries the vibrator list of one or all devices. + +**System capability**: SystemCapability.Sensors.MiscDevice + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- |-----------------------------------------| ---- |-----------------------------------| +| param | [VibratorInfoParam](#vibratorinfoparam19) | No | Vibrator parameters, such as the specified device and vibrator. If this parameter is left unspecified, this API applies to all vibrators of the local device by default.| + +**Return value** + +| Type | Description | +|-------------------------------| --------------------------------------------------------- | +| [VibratorInfo](#vibratorinfo19) | Vibrator information.| + + +**Example** + + ```ts + import { vibrator } from '@kit.SensorServiceKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + try { + const vibratorInfoList: vibrator.VibratorInfo[] = vibrator.getVibratorInfoSync({ deviceId: 1, vibratorId: 3 }); + console.log(`vibratorInfoList: ${JSON.stringify(vibratorInfoList)}`); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); + } + ``` + + +## vibrator.on19+ + +on(type: 'vibratorStateChange', callback: Callback<VibratorStatusEvent>): void + +Enables listening for vibrator status changes. + +**System capability**: SystemCapability.Sensors.MiscDevice + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | +| type | 'vibratorStateChange' | Yes | Event type. The value **vibratorStateChange** indicates a vibrator online/offline event. | +| callback | Callback<[VibratorStatusEvent](#vibratorstatusevent19)> | Yes | Callback used to return the vibrator status change event.| + +**Error codes** + +For details about the error codes, see [Vibrator Error Codes](errorcode-vibrator.md). + +| ID| Error Message | +| -------- | ------------------------ | +| 14600101 | Device operation failed. | + + +**Example** + + ```ts + import { vibrator } from '@kit.SensorServiceKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + // Callback + const vibratorStateChangeCallback = (data: vibrator.VibratorStatusEvent) => { + console.log('vibrator state callback info:', JSON.stringify(data)); + } + + try { + // Subscribe to vibratorStateChange events. + vibrator.on('vibratorStateChange', vibratorStateChangeCallback); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); + } + ``` + + +## vibrator.off19+ + +off(type: 'vibratorStateChange', callback?: Callback<VibratorStatusEvent>): void + +Disables listening for vibrator status changes. + +**System capability**: SystemCapability.Sensors.MiscDevice + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | +| type | 'vibratorStateChange' | Yes | Event type. The value **vibratorStateChange** indicates a vibrator online/offline event. | +| callback | Callback<[VibratorStatusEvent](#vibratorstatusevent19)> | No | Callback used to return the vibrator status change event. If this parameter is not specified, all callbacks of vibrator status change events will be unregistered.| + +**Error codes** + +For details about the error codes, see [Vibrator Error Codes](errorcode-vibrator.md). + +| ID| Error Message | +| -------- | ------------------------ | +| 14600101 | Device operation failed. | + + +**Example** + + ```ts + import { vibrator } from '@kit.SensorServiceKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + // Callback + const vibratorStateChangeCallback = (data: vibrator.VibratorStatusEvent) => { + console.log('vibrator state callback info:', JSON.stringify(data)); + } + try { + // Unsubscribe from specified vibratorStateChange events. + vibrator.off('vibratorStateChange', vibratorStateChangeCallback); + // Unsubscribe from all vibratorStateChange events. + // vibrator.off('vibratorStateChange'); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); + } + ``` + + +## VibratorStatusEvent19+ + +Defines the vibrator status change event. + +**System capability**: SystemCapability.Sensors.MiscDevice + + +| Name| Type | Description | +| ---- | ------ |----------------------------------| +| timestamp | number | Event timestamp. | +| deviceId | number | Device ID. | +| vibratorCount | number | Number of vibrators on the device. | +| isVibratorOnline | boolean | Vibrator status. The value **true** indicates that the device is online, and the value **false** indicates the opposite.| + + +## VibratorInfoParam19+ + +Defines the vibrator parameters. If **VibratorInfoParam** is left unspecified, an API applies to all vibrators of the local device by default. + +**System capability**: SystemCapability.Sensors.MiscDevice + + +| Name| Type | Read-Only| Optional| Description | +| ---- | ------ | ---- | ---- |------------------------------------------------------------| +| deviceId | number | No | Yes | Device ID. The default value is **-1**, which indicates the local device. You can use [getEffectInfoSync](#vibratorgeteffectinfosync19) to query other device IDs.| +| vibratorId | number | No | Yes | Vibrator ID. The default value is **-1**, which indicates all vibrator of the local device. You can use [getEffectInfoSync](#vibratorgeteffectinfosync19) to query other vibrator IDs. | + + + +## EffectInfo19+ + +Defines the preset effect. + +**System capability**: SystemCapability.Sensors.MiscDevice + + +| Name| Type | Description | +| ---- | ------ |------------| +| isEffectSupported | boolean | Whether the preset effect is supported. The value **true** indicates that the preset effect is supported, and the value **false** indicates the opposite.| + + +## VibratorInfo19+ + +Defines the vibrator information. + +| Name| Type | Description | +| ---- | ------ |-----------| +| deviceId | number | Device ID. | +| vibratorId | number | Vibrator ID. | +| deviceName | string | Device name. | +| isHdHapticSupported | boolean | Whether HD vibration is supported.| +| isLocalVibrator | boolean | Whether the device is a local device. | + ## vibrator.isHdHapticSupported12+ @@ -821,8 +1130,8 @@ Checks whether HD vibration is supported. **Return value** -| Type | Description | -| ------- | -------------------------------------------------- | +| Type | Description | +| ------- | --------------------------------------------------------- | | boolean | Boolean value indicating whether HD vibration is supported. The value **true** indicates that HD vibration is supported, and the value **false** indicates the opposite.| **Error codes** @@ -835,19 +1144,19 @@ For details about the error codes, see [Vibrator Error Codes](errorcode-vibrator **Example** -```ts -import { vibrator } from '@kit.SensorServiceKit'; -import { BusinessError } from '@kit.BasicServicesKit'; - -try { - // Check whether HD vibration is supported. - let ret = vibrator.isHdHapticSupported(); - console.info(`The query result is ${ret}`); -} catch (error) { - let e: BusinessError = error as BusinessError; - console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); -} -``` + ```ts + import { vibrator } from '@kit.SensorServiceKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + try { + // Check whether HD vibration is supported. + let ret = vibrator.isHdHapticSupported(); + console.info(`The query result is ${ret}`); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); + } + ``` ## VibratorPatternBuilder18+ @@ -861,11 +1170,11 @@ Adds a long vibration event as a **VibratorPattern** object. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------- | ---- | ------------------------ | -| time | number | Yes | Start time of the long vibration. | -| duration | number | Yes | Duration of the long vibration. | -| options | [ContinuousParam](#continuousparam18) | No | Optional parameters.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | +| time | number | Yes | Start time of the long vibration, in ms. The value range is (0,1800000).| +| duration | number | Yes | Duration of the long vibration, in ms. The value range is (0,5000].| +| options | [ContinuousParam](#continuousparam18) | No | Optional parameters. | **Return value** @@ -879,42 +1188,42 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ---------------- | -| 401 | Parameter error. | +| 401 | Parameter error.Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | **Example** -```ts -import { vibrator } from '@kit.SensorServiceKit'; -import { BusinessError } from '@kit.BasicServicesKit'; - -let builder = new vibrator.VibratorPatternBuilder(); -try { - let pointsMe: vibrator.VibratorCurvePoint[] = [ - { time: 0, intensity: 0, frequency: -7 }, - { time: 42, intensity: 1, frequency: -6 }, - { time: 128, intensity: 0.94, frequency: -4 }, - { time: 217, intensity: 0.63, frequency: -14 }, - { time: 763, intensity: 0.48, frequency: -14 }, - { time: 1125, intensity: 0.53, frequency: -10 }, - { time: 1503, intensity: 0.42, frequency: -14 }, - { time: 1858, intensity: 0.39, frequency: -14 }, - { time: 2295, intensity: 0.34, frequency: -17 }, - { time: 2448, intensity: 0.21, frequency: -14 }, - { time: 2468, intensity: 0, frequency: -21 } - ] // No less than four VibratorCurvePoint objects must be set. The maximum value is 16. - let param: vibrator.ContinuousParam = { - intensity: 97, - frequency: 34, - points:pointsMe, - index: 0 - } - builder.addContinuousEvent(0, 2468, param); - console.info(`addContinuousEvent builder is ${builder.build()}`); -} catch(error) { - let e: BusinessError = error as BusinessError; - console.error(`Exception. Code ${e.code}`); -} -``` + ```ts + import { vibrator } from '@kit.SensorServiceKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + let builder = new vibrator.VibratorPatternBuilder(); + try { + let pointsMe: vibrator.VibratorCurvePoint[] = [ + { time: 0, intensity: 0, frequency: -7 }, + { time: 42, intensity: 1, frequency: -6 }, + { time: 128, intensity: 0.94, frequency: -4 }, + { time: 217, intensity: 0.63, frequency: -14 }, + { time: 763, intensity: 0.48, frequency: -14 }, + { time: 1125, intensity: 0.53, frequency: -10 }, + { time: 1503, intensity: 0.42, frequency: -14 }, + { time: 1858, intensity: 0.39, frequency: -14 }, + { time: 2295, intensity: 0.34, frequency: -17 }, + { time: 2448, intensity: 0.21, frequency: -14 }, + { time: 2468, intensity: 0, frequency: -21 } + ] // No less than four VibratorCurvePoint objects must be set. The maximum value is 16. + let param: vibrator.ContinuousParam = { + intensity: 97, + frequency: 34, + points:pointsMe, + index: 0 + } + builder.addContinuousEvent(0, 2468, param); + console.info(`addContinuousEvent builder is ${builder.build()}`); + } catch(error) { + let e: BusinessError = error as BusinessError; + console.error(`Exception. Code ${e.code}`); + } + ``` ### vibrator('addTransientEvent')18+ @@ -926,10 +1235,10 @@ Adds a short vibration event as a **VibratorPattern** object. **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ----------------------------------- | ---- | ------------------------ | -| time | number | Yes | Start time of long vibration. | -| options | [TransientParam](#transientparam18) | No | Optional parameters.| +| Name | Type | Mandatory| Description | +| ------- | ----------------------------------- | ---- | ------------------------------------------------------------ | +| time | number | Yes | Start time of the long vibration, in ms. The value range is (0,1800000).| +| options | [TransientParam](#transientparam18) | No | Optional parameters. | **Return value** @@ -943,28 +1252,28 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ---------------- | -| 401 | Parameter error. | +| 401 | Parameter error.Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | **Example** -```ts -import { vibrator } from '@kit.SensorServiceKit'; -import { BusinessError } from '@kit.BasicServicesKit'; - -let builder = new vibrator.VibratorPatternBuilder(); -try { - let param: vibrator.TransientParam = { - intensity: 80, - frequency: 70, - index: 0 - } - builder.addTransientEvent(0, param); - console.log(`addTransientEvent builder is ${builder.build()}`); -} catch(error) { - let e: BusinessError = error as BusinessError; - console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); -} -``` + ```ts + import { vibrator } from '@kit.SensorServiceKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + let builder = new vibrator.VibratorPatternBuilder(); + try { + let param: vibrator.TransientParam = { + intensity: 80, + frequency: 70, + index: 0 + } + builder.addTransientEvent(0, param); + console.log(`addTransientEvent builder is ${builder.build()}`); + } catch(error) { + let e: BusinessError = error as BusinessError; + console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); + } + ``` ### vibrator('build')18+ @@ -982,56 +1291,59 @@ Constructor used to create a **VibratorPattern** object, which determines the vi **Example** -```ts -import { vibrator } from '@kit.SensorServiceKit'; -import { BusinessError } from '@kit.BasicServicesKit'; - -let builder = new vibrator.VibratorPatternBuilder(); -try { - let param: vibrator.TransientParam = { - intensity: 80, - frequency: 70, - index: 0 - } - builder.addTransientEvent(0, param); - console.log(`addTransientEvent builder is ${builder.build()}`); -} catch(error) { - let e: BusinessError = error as BusinessError; - console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); -} -try { - vibrator.startVibration({ - type: "pattern", - pattern: builder.build() - }, { - usage: "alarm", // The switch control is subject to the selected type. - }, (error) => { - if (error) { - let e: BusinessError = error as BusinessError; - console.error(`Vibrate fail. Code: ${e.code}, message: ${e.message}`); - } else { - console.info(`vibrate success`); - } - }); -} catch(error) { - let e: BusinessError = error as BusinessError; - console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); -} -``` + ```ts + import { vibrator } from '@kit.SensorServiceKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + let builder = new vibrator.VibratorPatternBuilder(); + try { + let param: vibrator.TransientParam = { + intensity: 80, + frequency: 70, + index: 0 + } + builder.addTransientEvent(0, param); + console.log(`addTransientEvent builder is ${builder.build()}`); + } catch(error) { + let e: BusinessError = error as BusinessError; + console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); + } + try { + vibrator.startVibration({ + type: "pattern", + pattern: builder.build() + }, { + usage: "alarm", // The switch control is subject to the selected type. + }, (error) => { + if (error) { + let e: BusinessError = error as BusinessError; + console.error(`Vibrate fail. Code: ${e.code}, message: ${e.message}`); + } else { + console.info(`vibrate success`); + } + }); + } catch(error) { + let e: BusinessError = error as BusinessError; + console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); + } + ``` ## EffectId -Enumerates the preset vibration effect IDs. +Enumerates the preset vibration effect IDs. You can pass this parameter to [vibrator.startVibration9+](#vibratorstartvibration9) or [vibrator.stopVibration9+](#vibratorstopvibration9-1) to deliver the vibration effect specified by [VibratePreset](#vibratepreset9). This parameter supports a variety of values, such as **haptic.clock.timer**. [HapticFeedback12+](#hapticfeedback12) provides several frequently used **EffectId** values. +> **NOTE** +> +> Preset effects vary according to devices. You are advised to call [vibrator.isSupportEffect](#vibratorissupporteffect10-1)10+ to check whether the device supports the preset effect before use. **System capability**: SystemCapability.Sensors.MiscDevice -| Name | Value | Description | -| ------------------ | -------------------- | -------------------------------- | -| EFFECT_CLOCK_TIMER | 'haptic.clock.timer' | Vibration effect when a user adjusts the timer.| +| Name | Value | Description | +| ----------- | -------------------- | ---------------------------- | +| EFFECT_CLOCK_TIMER | 'haptic.clock.timer' | Vibration effect of the vibrator when a user adjusts the timer.| ## HapticFeedback12+ -Defines the vibration effect. +Defines the vibration effect. The frequency of the same vibration effect may vary depending on the vibrator, but the frequency trend remains consistent. These vibration effects correspond to the specific values of **EffectId**. For details, see the sample code that demonstrates how to use [vibrator.startVibration9+](#vibratorstartvibration9) or [vibrator.stopVibration9+](#vibratorstopvibration9-1) to deliver the vibration effect defined by [VibratePreset](#vibratepreset9). **System capability**: SystemCapability.Sensors.MiscDevice @@ -1040,82 +1352,82 @@ Defines the vibration effect. | EFFECT_SOFT | 'haptic.effect.soft' | Soft vibration, low frequency.| | EFFECT_HARD | 'haptic.effect.hard' | Hard vibration, medium frequency.| | EFFECT_SHARP | 'haptic.effect.sharp' | Sharp vibration, high frequency.| -| EFFECT_NOTICE_SUCCESS18+ | 'haptic.notice.success' | Vibration for a successful notification. | -| EFFECT_NOTICE_FAILURE18+ | 'haptic.notice.fail' | Vibration for a notification failure. | +| EFFECT_NOTICE_SUCCESS18+ | 'haptic.notice.success' | Vibration for a success notification. | +| EFFECT_NOTICE_FAILURE18+ | 'haptic.notice.fail' | Vibration for a failure notification. | | EFFECT_NOTICE_WARNING18+ | 'haptic.notice.warning' | Vibration for an alert. | ## VibratorStopMode -Enumerates the modes available to stop the vibration. +Enumerates the modes available to stop the vibration. This parameter is required for [vibrator.stopVibration9+](#vibratorstopvibration9) or [vibrator.stopVibration9+](#vibratorstopvibration9-1). The stop mode must match that delivered in [VibrateEffect9+](#vibrateeffect9). **System capability**: SystemCapability.Sensors.MiscDevice -| Name | Value | Description | -| ------------------------- | -------- | ------------------------------ | +| Name | Value | Description | +| ------------------------- | -------- | ------------------------ | | VIBRATOR_STOP_MODE_TIME | 'time' | The vibration to stop is in **duration** mode.| | VIBRATOR_STOP_MODE_PRESET | 'preset' | The vibration to stop is in **EffectId** mode.| ## VibrateEffect9+ -Describes the vibration effect. +Describes the vibration effect. This parameter is required for [vibrator.startVibration9+](#vibratorstartvibration9) or [vibrator.startVibration9+](#vibratorstartvibration9-1). **System capability**: SystemCapability.Sensors.MiscDevice -| Type | Description | -| -------------------------------- | ------------------------------ | -| [VibrateTime](#vibratetime9) | Vibration with the specified duration.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| [VibratePreset](#vibratepreset9) | Vibration with a preset effect.| -| [VibrateFromFile](#vibratefromfile10) | Vibration according to a custom vibration configuration file.| -| VibrateFromPattern18+ | Triggers vibration with the custom effect. This API uses an asynchronous callback to return the result.| +| Type | Description | +| ------------------------------------- | ------------------------------------------------------------ | +| [VibrateTime](#vibratetime9) | Start vibration of the specified duration.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| [VibratePreset](#vibratepreset9) | Vibration with a preset effect. | +| [VibrateFromFile](#vibratefromfile10) | Vibration according to a custom vibration configuration file. | +| VibrateFromPattern18+ | Triggers vibration with the custom effect. This API uses an asynchronous callback to return the result. | ## VibrateTime9+ -Describes the fixed-duration vibration. +Represents vibration of the specified duration. **Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.Sensors.MiscDevice -| Name | Type | Mandatory| Description | -| -------- | ------ | ----- | ------------------------------ | -| type | 'time' | Yes | The value **time** means vibration with the specified duration.| -| duration | number | Yes | Vibration duration, in ms. | +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ----------------------------------------------------------- | +| type | 'time' | Yes | The value is **time**, indicating vibration of the specified duration. | +| duration | number | Yes | Vibration duration, in ms. The value range is (0,1800000].| ## VibratePreset9+ -Describes the preset vibration. +Describes the preset vibration. You can pass this parameter to [VibrateEffect9+](#vibrateeffect9) to specify a preset vibration effect when calling [vibrator.startVibration9+](#vibratorstartvibration9) or [vibrator.startVibration9+](#vibratorstartvibration9-1). **System capability**: SystemCapability.Sensors.MiscDevice -| Name | Type | Mandatory| Description | -| -------- | -------- | ---- |------------------------------ | -| type | 'preset' | Yes | The value **preset** means vibration with the specified effect.| -| effectId | string | Yes | Preset vibration effect ID. | -| count | number | No | Number of repeated vibrations. This parameter is optional. The default value is **1**. | -| intensity12+ | number | No| Vibration intensity. This parameter is optional. The value range is [0, 100]. The default value is **100**. If vibration intensity adjustment is not supported, the default vibration intensity will be used.| +| Name | Type | Mandatory| Description | +| ----------------------- | -------- | ---- | ------------------------------------------------------------ | +| type | 'preset' | Yes | The value **preset** means vibration with the specified effect. | +| effectId | string | Yes | Preset vibration effect ID. | +| count | number | No | Number of repeated vibrations. This parameter is optional. The default value is **1**. | +| intensity12+ | number | No | Vibration intensity. This parameter is optional. The value range is [0, 100]. The default value is **100**. If vibration intensity adjustment is not supported, the default vibration intensity will be used.| ## VibrateFromFile10+ -Describes the custom vibration type, which is supported only by certain devices. If a device does not support this vibration type, [an error code indicating unsupported device](../errorcode-universal.md) is returned. +Represents a custom vibration pattern. It is supported only by certain devices. An error code will be returned if a device does not support this vibration mode. You can pass this parameter to [VibrateEffect9+](#vibrateeffect9) to specify a custom vibration pattern when calling [vibrator.startVibration9+](#vibratorstartvibration9) or [vibrator.startVibration9+](#vibratorstartvibration9-1). **System capability**: SystemCapability.Sensors.MiscDevice -| Name | Type | Mandatory| Description | -| -------- | -------- | ---- | ------------------------------ | -| type | 'file' | Yes | The value **file** means vibration according to a vibration configuration file.| -| hapticFd | [HapticFileDescriptor](#hapticfiledescriptor10)10+ | Yes| File descriptor (FD) of the vibration configuration file.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------ | +| type | 'file' | Yes | The value **file** means vibration according to a vibration configuration file.| +| hapticFd | [HapticFileDescriptor](#hapticfiledescriptor10)10+ | Yes | File descriptor (FD) of the vibration configuration file. | ## HapticFileDescriptor10+ -Describes the FD of a custom vibration configuration file. Ensure that the file is available, and the parameters in it can be obtained from the sandbox path through the [file management API](../apis-core-file-kit/js-apis-file-fs.md#fsopen) or from the HAP resource through the [resource management API](../apis-localization-kit/js-apis-resource-manager.md#getrawfd9). The use case is as follows: The system triggers vibration according to the sequence set in a configuration file, based on the specified offset and length. For details about the storage format of the vibration sequence, see Custom Vibration. +Describes the FD of a custom vibration configuration file. Ensure that the file is available, and the parameters in it can be obtained from the sandbox path through the [file management API](../apis-core-file-kit/js-apis-file-fs.md#fsopen) or from the HAP resource through the [resource management API](../apis-localization-kit/js-apis-resource-manager.md#getrawfd9). The use case is as follows: The system triggers vibration according to the sequence set in a configuration file, based on the specified offset and length. For details about the storage format of the vibration sequence, see [Custom Vibration](../../device/sensor/vibrator-guidelines.md). **System capability**: SystemCapability.Sensors.MiscDevice -| Name | Type | Mandatory | Description | -| -------- | -------- |--------| ------------------------------| -| fd | number | Yes | FD of the custom vibration configuration file. | -| offset | number | No | Offset from the start position of the file, in bytes. The default value is the start position of the file, and the value cannot exceed the valid range of the file.| -| length | number | No | Resource length, in bytes. The default value is the length from the offset position to the end of the file, and the value cannot exceed the valid range of the file.| +| Name | Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| fd | number | Yes | FD of the custom vibration configuration file. | +| offset | number | No | Offset from the start position of the file, in bytes. The default value is the start position of the file, and the value cannot exceed the valid range of the file.| +| length | number | No | Resource length, in bytes. The default value is the length from the offset position to the end of the file, and the value cannot exceed the valid range of the file.| ## VibratorEventType18+ @@ -1137,8 +1449,8 @@ Defines the gain relative to the vibration intensity. | Name | Type | Mandatory| Description | | --------- | ------ | ---- | ------------------------------------------------------------ | | time | number | Yes | Start time offset. | -| intensity | number | No | Gain relative to the vibration intensity. This parameter is optional. The value range is [0, 1]. If this parameter is left empty, the default value is **1**.| -| frequency | number | No | Change relative to the vibration frequency. This parameter is optional. The value range is [-100, 100]. If this parameter is left empty, the default value is 0.| +| intensity | number | No | Gain relative to the vibration intensity. This parameter is optional. The value range is [0,100%]. If this parameter is left empty, the default value is **1**.| +| frequency | number | No | Change relative to the vibration frequency. This parameter is optional. The value range is [-100,100]. If this parameter is left empty, the default value is **0**.| ## VibratorEvent18+ @@ -1146,15 +1458,15 @@ Vibration event. **System capability**: SystemCapability.Sensors.MiscDevice -| Name | Type | Mandatory| Description | -| --------- | ------------------------------- | ---- | ------------------------------------------------------------ | -| eventType | VibratorEventType | Yes | Vibration event type. | -| time | number | Yes | Vibration start time. | -| duration | number | No | Vibration duration. This parameter is optional. The value range is [0, 5000]. The default value is **48** for short vibration and **1000** for long vibration.| -| intensity | number | No | Vibration intensity. This parameter is optional. The value range is [0, 100]. If this parameter is left empty, the default value is **100**.| -| frequency | number | No | Vibration frequency. This parameter is optional.The value range is [0, 100]. If this parameter is left empty, the default value is **50**. | -| index | number | No | Channel number. This parameter is optional. If this parameter is left empty, the default value is **0**. | -| points | Array<VibratorCurvePoint> | No | Adjustment points of the vibration curve. | +| Name | Type | Mandatory| Description | +| --------- | -------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| eventType | VibratorEventType | Yes | Vibration event type. | +| time | number | Yes | Vibration start time, in ms. The value range is [0,1800000]. | +| duration | number | No | Vibration duration. This parameter is optional. The value range is (0,5000]. The default value is **48** for short vibration and **1000** for long vibration.| +| intensity | number | No | Vibration intensity. This parameter is optional. The value range is [0,100]. If this parameter is left empty, the default value is **100**.| +| frequency | number | No | Vibration frequency. This parameter is optional. The value range is [0,100]. If this parameter is left empty, the default value is **50**.| +| index | number | No | Channel number. This parameter is optional. The value range is [0,2]. If this parameter is left empty, the default value is **0**. | +| points | Array<[VibratorCurvePoint](#vibratorcurvepoint18)> | No | Adjustment points of the vibration curve. | ## VibratorPattern18+ @@ -1162,10 +1474,10 @@ Defines the vibration sequence. **System capability**: SystemCapability.Sensors.MiscDevice -| Name | Type | Mandatory| Description | -| ------ | -------------------------- | ---- | ---------------------------------------------------- | -| time | number | Yes | Absolute vibration start time. | -| events | Array<VibratorEvent> | Yes | Vibration event array, which is the **VibratorPattern** object returned by **build() **.| +| Name | Type | Mandatory| Description | +| ------ | ---------------------------------------------- | ---- | ---------------------------------------------------- | +| time | number | Yes | Absolute vibration start time. | +| events | Array<[VibratorEvent](#vibratorevent18)> | Yes | Vibration event array, which is the **VibratorPattern** object returned by **build() **.| ## ContinuousParam18+ @@ -1173,12 +1485,12 @@ Defines the parameters for continuous vibration. **System capability**: SystemCapability.Sensors.MiscDevice -| Name | Type | Mandatory| Description | -| --------- | -------------------- | ---- | ------------------------------------------------------------ | -| intensity | number | No | Vibration intensity. This parameter is optional. The value range is [0, 100]. If this parameter is left empty, the default value is **100**.| -| frequency | number | No | Vibration frequency. This parameter is optional.The value range is [0, 100]. If this parameter is left empty, the default value is **50**. | -| points | VibratorCurvePoint[] | No | Adjustment points of the vibration curve. | -| index | number | No | Channel number. This parameter is optional. If this parameter is left empty, the default value is **0**. | +| Name | Type | Mandatory| Description | +| --------- | -------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| intensity | number | No | Vibration intensity. This parameter is optional. The value range is [0,100]. If this parameter is left empty, the default value is **100**.| +| frequency | number | No | Vibration frequency. This parameter is optional. The value range is [0,100]. If this parameter is left empty, the default value is **50**.| +| points | [VibratorCurvePoint](#vibratorcurvepoint18)[] | No | Adjustment points of the vibration curve. | +| index | number | No | Channel number. This parameter is optional. The value range is [0,2]. If this parameter is left empty, the default value is **0**. | ## TransientParam18+ @@ -1186,11 +1498,11 @@ Defines the parameters for transient vibration. **System capability**: SystemCapability.Sensors.MiscDevice -| Name | Type | Mandatory| Description | -| --------- | ------ | ---- | ------------------------------------------- | -| intensity | number | No | Vibration intensity. This parameter is optional. If this parameter is left empty, the default value is **100**.| -| frequency | number | No | Vibration frequency. This parameter is optional. If this parameter is left empty, the default value is **50**. | -| index | number | No | Channel number. This parameter is optional. If this parameter is left empty, the default value is **0**. | +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | ------------------------------------------------------------ | +| intensity | number | No | Vibration intensity. This parameter is optional. The value range is [0,100]. If this parameter is left empty, the default value is **100**.| +| frequency | number | No | Vibration frequency. This parameter is optional. The value range is [0,100]. If this parameter is left empty, the default value is **50**.| +| index | number | No | Channel number. This parameter is optional. The value range is [0,2]. If this parameter is left empty, the default value is **0**. | ## VibrateFromPattern18+ @@ -1211,10 +1523,11 @@ Describes the vibration attribute. **System capability**: SystemCapability.Sensors.MiscDevice -| Name | Type| Mandatory| Description | -| ----- | ------ | ---- | -------------- | -| id | number | No| Vibrator ID. The default value is **0**. | -| usage | [Usage](#usage9) | Yes| Vibration scenario.| +| Name | Type | Mandatory| Description | +|------------------------| ---------------- | ---- | ------------------------------------------------------------ | +| id | number | No | Vibrator ID. The default value is **0**. | +| deviceId19+ | number | No | Device ID. | +| usage | [Usage](#usage9) | Yes | Vibration scenario. The default value is **unknown**. The value must be an enum defined in [Usage](#usage9).| ## Usage9+ @@ -1227,24 +1540,25 @@ Enumerates the vibration scenarios. **System capability**: SystemCapability.Sensors.MiscDevice -| Type | Description | -| ---------------- | ------------------------------ | -| 'unknown' | Unknown scenario, with the lowest priority. This parameter has a fixed value of **unknown**.| -| 'alarm' | Vibration for alarms. This parameter has a fixed value of **alarm**.| -| 'ring' | Vibration for ringing. This parameter has a fixed value of **ring**.| -| 'notification' | Vibration for notification. This parameter has a fixed value of **notification**.| -| 'communication' | Vibration for communication. This parameter has a fixed value of **communication**.| -| 'touch' | Vibration for touch. This parameter has a fixed value of **touch**.| -| 'media' | Vibration for media. This parameter has a fixed value of **media**.| -| 'physicalFeedback' | Vibration for physical feedback. This parameter has a fixed value of **physicalFeedback**.| -| 'simulateReality' | Vibration for simulated reality. This parameter has a fixed value of **simulateReality**.| +| Type | Description | +| ------------------ | ------------------------------------------------------- | +| 'unknown' | Unknown scenario, with the lowest priority. This parameter has a fixed value of **unknown**.| +| 'alarm' | Vibration for alarms. This parameter has a fixed value of **alarm**. | +| 'ring' | Vibration for ringing. This parameter has a fixed value of **ring**. | +| 'notification' | Vibration for notification. This parameter has a fixed value of **notification**. | +| 'communication' | Vibration for communication. This parameter has a fixed value of **communication**. | +| 'touch' | Vibration for touch. This parameter has a fixed value of **touch**. | +| 'media' | Vibration for media. This parameter has a fixed value of **media**. | +| 'physicalFeedback' | Vibration for physical feedback. This parameter has a fixed value of **physicalFeedback**. | +| 'simulateReality' | Vibration for simulated reality. This parameter has a fixed value of **simulateReality**. | + ## vibrator.vibrate(deprecated) vibrate(duration: number): Promise<void> -Triggers vibration with the specified duration. This API uses a promise to return the result. +Triggers vibration of the specified duration. This API uses a promise to return the result. This API is deprecated since API version 9. You are advised to use [vibrator.startVibration](#vibratorstartvibration9-1)9+ instead. @@ -1254,34 +1568,34 @@ This API is deprecated since API version 9. You are advised to use [vibrator.sta **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------ | ---- | ---------------------- | -| duration | number | Yes | Vibration duration, in ms.| +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------------------------------------------------------ | +| duration | number | Yes | Vibration duration, in ms. The value range is (0,1800000].| **Return value** -| Type | Description | -| ------------------- | -------------------------------------- | +| Type | Description | +| ------------------- | ------------- | | Promise<void> | Promise that returns no value.| **Example** -```ts -import { vibrator } from '@kit.SensorServiceKit'; -import { BusinessError } from '@kit.BasicServicesKit'; + ```ts + import { vibrator } from '@kit.SensorServiceKit'; + import { BusinessError } from '@kit.BasicServicesKit'; -vibrator.vibrate(1000).then(() => { - console.info('Succeed in vibrating'); -}, (error: BusinessError) => { - console.error(`Failed to vibrate. Code: ${error.code}, message: ${error.message}`); -}); -``` + vibrator.vibrate(1000).then(() => { + console.info('Succeed in vibrating'); + }, (error: BusinessError) => { + console.error(`Failed to vibrate. Code: ${error.code}, message: ${error.message}`); + }); + ``` ## vibrator.vibrate(deprecated) vibrate(duration: number, callback?: AsyncCallback<void>): void -Triggers vibration with the specified duration. This API uses an asynchronous callback to return the result. +Triggers vibration of the specified duration. This API uses an asynchronous callback to return the result. This API is deprecated since API version 9. You are advised to use [vibrator.startVibration](#vibratorstartvibration9)9+ instead. @@ -1291,25 +1605,25 @@ This API is deprecated since API version 9. You are advised to use [vibrator.sta **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ---------------------------------------------------------- | -| duration | number | Yes | Vibration duration, in ms. | -| callback | AsyncCallback<void> | No | Callback used to return the result. If the vibration starts, **err** is **undefined**; otherwise, **err** is an error object.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| duration | number | Yes | Vibration duration, in ms. The value range is (0,1800000].| +| callback | AsyncCallback<void> | No | Callback used to return the result. If the vibration starts, **err** is **undefined**; otherwise, **err** is an error object. | **Example** -```ts -import { vibrator } from '@kit.SensorServiceKit'; -import { BusinessError } from '@kit.BasicServicesKit'; - -vibrator.vibrate(1000, (error: BusinessError) => { - if (error) { - console.error(`Failed to vibrate. Code: ${error.code}, message: ${error.message}`); - } else { - console.info('Succeed in vibrating'); - } -}) -``` + ```ts + import { vibrator } from '@kit.SensorServiceKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + vibrator.vibrate(1000, (error: BusinessError) => { + if (error) { + console.error(`Failed to vibrate. Code: ${error.code}, message: ${error.message}`); + } else { + console.info('Succeed in vibrating'); + } + }) + ``` ## vibrator.vibrate(deprecated) @@ -1332,22 +1646,22 @@ This API is deprecated since API version 9. You are advised to use [vibrator.sta **Return value** -| Type | Description | -| ------------------- | -------------------------------------- | +| Type | Description | +| ------------------- | ------------- | | Promise<void> | Promise that returns no value.| **Example** -```ts -import { vibrator } from '@kit.SensorServiceKit'; -import { BusinessError } from '@kit.BasicServicesKit'; + ```ts + import { vibrator } from '@kit.SensorServiceKit'; + import { BusinessError } from '@kit.BasicServicesKit'; -vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER).then(() => { - console.info('Succeed in vibrating'); -}, (error: BusinessError) => { - console.error(`Failed to vibrate. Code: ${error.code}, message: ${error.message}`); -}); -``` + vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER).then(() => { + console.info('Succeed in vibrating'); + }, (error: BusinessError) => { + console.error(`Failed to vibrate. Code: ${error.code}, message: ${error.message}`); + }); + ``` ## vibrator.vibrate(deprecated) @@ -1371,18 +1685,18 @@ This API is deprecated since API version 9. You are advised to use [vibrator.sta **Example** -```ts -import { vibrator } from '@kit.SensorServiceKit'; -import { BusinessError } from '@kit.BasicServicesKit'; - -vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER, (error: BusinessError) => { - if (error) { - console.error(`Failed to vibrate. Code: ${error.code}, message: ${error.message}`); - } else { - console.info('Succeed in vibrating'); - } -}) -``` + ```ts + import { vibrator } from '@kit.SensorServiceKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER, (error: BusinessError) => { + if (error) { + console.error(`Failed to vibrate. Code: ${error.code}, message: ${error.message}`); + } else { + console.info('Succeed in vibrating'); + } + }) + ``` ## vibrator.stop(deprecated) @@ -1404,31 +1718,31 @@ This API is deprecated since API version 9. You are advised to use [vibrator.sto **Return value** -| Type | Description | -| ------------------- | -------------------------------------- | +| Type | Description | +| ------------------- | ------------- | | Promise<void> | Promise that returns no value.| **Example** -```ts -import { vibrator } from '@kit.SensorServiceKit'; -import { BusinessError } from '@kit.BasicServicesKit'; - -// Start vibration based on the specified effect ID. -vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER, (error: BusinessError) => { - if (error) { - console.error(`Failed to vibrate. Code: ${error.code}, message: ${error.message}`); - } else { - console.info('Succeed in vibrating'); - } -}) -// Stop vibration in VIBRATOR_STOP_MODE_PRESET mode. -vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then(() => { - console.info('Succeed in stopping'); -}, (error: BusinessError) => { - console.error(`Failed to stop. Code: ${error.code}, message: ${error.message}`); -}); -``` + ```ts + import { vibrator } from '@kit.SensorServiceKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + // Start vibration based on the specified effect ID. + vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER, (error: BusinessError) => { + if (error) { + console.error(`Failed to vibrate. Code: ${error.code}, message: ${error.message}`); + } else { + console.info('Succeed in vibrating'); + } + }) + // Stop vibration in VIBRATOR_STOP_MODE_PRESET mode. + vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then(() => { + console.info('Succeed in stopping'); + }, (error: BusinessError) => { + console.error(`Failed to stop. Code: ${error.code}, message: ${error.message}`); + }); + ``` ## vibrator.stop(deprecated) @@ -1452,24 +1766,24 @@ This API is deprecated since API version 9. You are advised to use [vibrator.sto **Example** -```ts -import { vibrator } from '@kit.SensorServiceKit'; -import { BusinessError } from '@kit.BasicServicesKit'; - -// Start vibration based on the specified effect ID. -vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER, (error: BusinessError) => { - if (error) { - console.error(`Failed to vibrate. Code: ${error.code}, message: ${error.message}`); - } else { - console.info('Succeed in vibrating'); - } -}) -// Stop vibration in VIBRATOR_STOP_MODE_PRESET mode. -vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET, (error: BusinessError) => { - if (error) { - console.error(`Failed to stop. Code: ${error.code}, message: ${error.message}`); - } else { - console.info('Succeed in stopping'); - } -}) -``` + ```ts + import { vibrator } from '@kit.SensorServiceKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + // Start vibration based on the specified effect ID. + vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER, (error: BusinessError) => { + if (error) { + console.error(`Failed to vibrate. Code: ${error.code}, message: ${error.message}`); + } else { + console.info('Succeed in vibrating'); + } + }) + // Stop vibration in VIBRATOR_STOP_MODE_PRESET mode. + vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET, (error: BusinessError) => { + if (error) { + console.error(`Failed to stop. Code: ${error.code}, message: ${error.message}`); + } else { + console.info('Succeed in stopping'); + } + }) + ```