• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Sensor Development (ArkTS)
2
3
4## When to Use
5
6With the sensor module, a device can obtain sensor data. For example, the device can subscribe to data of the orientation sensor to detect its own orientation, and data of the pedometer sensor to learn the number of steps the user walks every day.
7
8For details about the APIs, see [Sensor](../../reference/apis-sensor-service-kit/js-apis-sensor.md).
9
10
11## Available APIs
12
13| Name| Description                             |
14| -------- |---------------------------------|
15| sensor.on(sensorId, callback:AsyncCallback<Response>, options?: Options): void | Enables listening for data changes of the specified type of sensor.                   |
16| sensor.on(type: 'sensorStatusChange', callback: Callback<SensorStatusEvent>): void | Enables listening for sensor status changes.|
17| sensor.once(sensorId, callback:AsyncCallback<Response>): void | Enables one-time listening for sensor data changes.                   |
18| sensor.off(sensorId, callback?:AsyncCallback<void>): void | Disables listening for data changes of the specified type of sensor.                    |
19| 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.            |
20| sensor.off(type: 'sensorStatusChange', callback?: Callback<SensorStatusEvent>): void | Disables listening for sensor status changes.             |
21| sensor.getSensorList(callback: AsyncCallback\<Array\<Sensor>>): void| Obtains information about all sensors on the device.                 |
22
23
24## How to Develop
25
26The acceleration sensor is used as an example.
27
281. Import the module.
29
30   ```ts
31   import { sensor } from '@kit.SensorServiceKit';
32   import { BusinessError } from '@kit.BasicServicesKit';
33   ```
34
352. Obtain information about all sensors on the device.
36
37    ```ts
38    sensor.getSensorList((error: BusinessError, data: Array<sensor.Sensor>) => {
39        if (error) {
40            console.error('getSensorList failed');
41        } else {
42            console.info('getSensorList success');
43            for (let i = 0; i < data.length; i++) {
44                console.info(JSON.stringify(data[i]));
45            }
46        }
47    });
48    ```
49
50    ![](figures/001.png)
51
52    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.
53
54    You can query sensors based on the given device ID.
55    ```ts
56    try {
57      const deviceId = 1;
58      // The deviceId parameter is optional. By default, it is set to the ID of the local device.
59      const sensorList: sensor.Sensor[] = sensor.getSensorListByDeviceSync(deviceId);
60      console.log(`sensorList length: ${sensorList.length}`);
61      console.log(`sensorList: ${JSON.stringify(sensorList)}`);
62    } catch (error) {
63      let e: BusinessError = error as BusinessError;
64      console.error(`Failed to get sensorList. Code: ${e.code}, message: ${e.message}`);
65    }
66    ```
67
683. Check whether the corresponding permission has been configured. For details, see [Declaring Permissions](../../security/AccessToken/declare-permissions.md).
69
704. Enable listening for sensor status changes. You can call **on()** or **once()** to listen for sensor data changes.
71
72   The **on()** API is used to continuously listen for data changes of the sensor. The sensor reporting interval is set to 100000000 ns.
73
74   ```ts
75   import { sensor } from '@kit.SensorServiceKit';
76   import { BusinessError } from '@kit.BasicServicesKit';
77
78   try {
79     sensor.on(sensor.SensorId.ACCELEROMETER, (data: sensor.AccelerometerResponse) => {
80          console.info("Succeeded in obtaining data. x: " + data.x + " y: " + data.y + " z: " + data.z);
81     }, { interval: 100000000 });
82   } catch (error) {
83      let e: BusinessError = error as BusinessError;
84      console.error(`Failed to get sensorList. Code: ${e.code}, message: ${e.message}`);
85   }
86   ```
87
88   You can also specify SensorInfoParam, which is used to pass deviceId and sensorIndex.
89   ```ts
90   import { sensor } from '@kit.SensorServiceKit';
91   import { BusinessError } from '@kit.BasicServicesKit';
92
93   try {
94     sensor.on(sensor.SensorId.ACCELEROMETER, (data: sensor.AccelerometerResponse) => {
95          console.info("Succeeded in obtaining data. x: " + data.x + " y: " + data.y + " z: " + data.z);
96     }, { interval: 100000000, sensorInfoParam: { deviceId: 1, sensorIndex: 3 } });
97   } catch (error) {
98      let e: BusinessError = error as BusinessError;
99      console.error(`Failed to get sensorList. Code: ${e.code}, message: ${e.message}`);
100   }
101   ```
102
103    ![](figures/002.png)
104
105   The **once()** API is used to perform one-time listening for sensor data changes.
106
107   ```ts
108   sensor.once(sensor.SensorId.ACCELEROMETER, (data: sensor.AccelerometerResponse) => {
109       console.info("Succeeded in obtaining data. x: " + data.x + " y: " + data.y + " z: " + data.z);
110   });
111   ```
112
113   ![](figures/003.png)
114
1155. Disable listening for sensor status changes.
116
117    Note that disabling listening without a prior subscription is an abnormal behavior and requires exception handling.
118    ```ts
119    sensor.off(sensor.SensorId.ACCELEROMETER);
120    ```
121
122    Disables listening for sensor status changes based on the given sensor parameters.
123    ```ts
124    sensor.off(sensor.SensorId.ACCELEROMETER, { deviceId: 1, sensorIndex: 3 });
125    ```
126
1276. Enable listening for sensor status changes. When receiving a device offline event, you need to call **off** to close the sensor on the device.
128
129    In **SensorStatusEvent**, the following information is included: event timestamp, sensor ID, sensor index, online/offline status, device ID, and device name.
130    ```ts
131    sensor.on('sensorStatusChange', (data: sensor.SensorStatusEvent) => {
132          console.log(`timestamp: ${data.timestamp},
133            deviceId: ${data.deviceId} deviceName: ${data.deviceName}
134            sensorId: ${data.sensorId} sensorIndex:${data.sensorIndex} isSensorOnline: ${data.isSensorOnline}`)
135    });
136    ```
137
138    Disable listening for sensor status changes.
139    ```ts
140    // Before performing this operation, ensure that listening for sensor status changes has been enabled.
141    sensor.off('sensorStatusChange');
142    ```
143