未验证 提交 67c79741 编写于 作者: O openharmony_ci 提交者: Gitee

!21908 翻译完成:21038+21114+21212+21053 【泛Sensor】修复文档描述、代码示例

Merge pull request !21908 from wusongqing/TR21038
......@@ -15,65 +15,64 @@ For details about the APIs, see [Sensor](../reference/apis/js-apis-sensor.md).
| ohos.sensor | sensor.on(sensorId, callback:AsyncCallback<Response>): void | Subscribes to data changes of a type of sensor.|
| ohos.sensor | sensor.once(sensorId, callback:AsyncCallback<Response>): void | Subscribes to only one data change of a type of sensor.|
| ohos.sensor | sensor.off(sensorId, callback?:AsyncCallback<void>): void | Unsubscribes from sensor data changes.|
| ohos.sensor | sensor.getSensorList(callback: AsyncCallback\<Array\<Sensor>>): void| Obtains information about all sensors on the device. This API uses an asynchronous callback to return the result.|
## How to Develop
1. Before obtaining data from a type of sensor, check whether the required permission has been configured.<br>
The system provides the following sensor-related permissions:
- ohos.permission.ACCELEROMETER
The acceleration sensor is used as an example.
- ohos.permission.GYROSCOPE
1. Import the module.
- ohos.permission.ACTIVITY_MOTION
- ohos.permission.READ_HEALTH_DATA
For details about how to configure a permission, see [Declaring Permissions](../security/accesstoken-guidelines.md).
2. Subscribe to data changes of a type of sensor. The following uses the acceleration sensor as an example.
```ts
import sensor from "@ohos.sensor";
sensor.on(sensor.SensorId.ACCELEROMETER, function (data) {
console.info("Succeeded in obtaining data. x: " + data.x + "y: " + data.y + "z: " + data.z); // Data is obtained.
});
```
![171e6f30-a8d9-414c-bafa-b430340305fb](figures/171e6f30-a8d9-414c-bafa-b430340305fb.png)
3. Unsubscribe from sensor data changes.
```ts
import sensor from "@ohos.sensor";
sensor.off(sensor.SensorId.ACCELEROMETER);
```
![65d69983-29f6-4381-80a3-f9ef2ec19e53](figures/65d69983-29f6-4381-80a3-f9ef2ec19e53.png)
2. Obtain information about all sensors on the device.
```ts
sensor.getSensorList(function (error, data) {
if (error) {
console.info('getSensorList failed');
} else {
console.info('getSensorList success');
for (let i = 0; i < data.length; i++) {
console.info(JSON.stringify(data[i]));
}
}
});
```
4. Subscribe to only one data change of a type of sensor.
```ts
import sensor from "@ohos.sensor";
![](figures/001.png)
sensor.once(sensor.SensorId.ACCELEROMETER, function (data) {
console.info("Succeeded in obtaining data. x: " + data.x + "y: " + data.y + "z: " + data.z); // Data is obtained.
});
```
![db5d017d-6c1c-4a71-a2dd-f74b7f23239e](figures/db5d017d-6c1c-4a71-a2dd-f74b7f23239e.png)
The minimum and the maximum sampling periods supported by the sensor are 5000000 ns and 200000000 ns, respectively. Therefore, the value of **interval** must be within this range.
3. Check whether the corresponding permission has been configured. For details, see [Applying for Permissions](../security/accesstoken-guidelines.md).
If the API fails to be called, you are advised to use the **try/catch** statement to capture error information that may occur in the code. Example:
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, function (data) {
console.info("Succeeded in obtaining data. x: " + data.x + " y: " + data.y + " z: " + data.z);
}, {'interval': 100000000});
```
![](figures/002.png)
- The **once()** API is used to listen for only one data change of the sensor.
```ts
import sensor from "@ohos.sensor";
sensor.once(sensor.SensorId.ACCELEROMETER, function (data) {
console.info("Succeeded in obtaining data. x: " + data.x + " y: " + data.y + " z: " + data.z);
});
```
![](figures/003.png)
try {
sensor.once(sensor.SensorId.ACCELEROMETER, function (data) {
console.info("Succeeded in obtaining data. x: " + data.x + "y: " + data.y + "z: " + data.z); // Data is obtained.
});
} catch (error) {
console.error(`Failed to get sensor data. Code: ${error.code}, message: ${error.message}`);
}
5. Cancel continuous listening.
```ts
sensor.off(sensor.SensorId.ACCELEROMETER);
```
......@@ -76,9 +76,9 @@ This JSON file contains two attributes: **MetaData** and **Channels**.
- **Create**: time when the file was created. This parameter is optional.
- **Description**: additional information such as the vibration effect and creation information. This parameter is optional.
- **Channels** provides information about the vibration channel. It is a JSON array that holds information about each channel. It contains two attributes: **Parameters** and **Pattern**.
- **Parameters** provides parameters related to the channel. Under it, **Index** indicates the channel ID. The value is fixed at **1** for a single channel. This parameter is mandatory.
- **Parameters** provides parameters related to the channel. Under it, **Index** indicates the channel ID. The value is fixed at **1** for a single channel. This parameter is mandatory.
- **Pattern** indicates the vibration sequence. It is a JSON array. Under it, **Event** indicates a vibration event, which can be either of the following types:
- **transient**: short vibration
- **transient**: short vibration
- **continuous**: long vibration
The table below describes the parameters under **Event**.
......@@ -89,7 +89,7 @@ The table below describes the parameters under **Event**.
| StartTime | Start time of the vibration. This parameter is mandatory.| [0, 1800 000], in ms, without overlapping|
| Duration | Duration of the vibration. This parameter is valid only when **Type** is **continuous**.| (10, 1600), in ms|
| Intensity | Intensity of the vibration. This parameter is mandatory.| [0, 100], a relative value that does not represent the actual vibration strength.|
| Frequency | Frequency of the vibration. This parameter is mandatory.| [0, 100], a relative value that does not represent the actual vibration frequency|
| Frequency | Frequency of the vibration. This parameter is mandatory.| [0, 100], a relative value that does not represent the actual vibration frequency.|
The following requirements must be met:
......@@ -221,45 +221,42 @@ The following requirements must be met:
```ts
import vibrator from '@ohos.vibrator';
const FILE_NAME = "xxx.json";
// Obtain the file descriptor of the vibration configuration file.
let fileDescriptor = undefined;
getContext().resourceManager.getRawFd(FILE_NAME).then(value => {
fileDescriptor = { fd: value.fd, offset: value.offset, length: value.length };
console.info('Succeed in getting resource file descriptor');
}).catch(error => {
console.error(`Failed to get resource file descriptor. Code: ${error.code}, message: ${error.message}`);
});
// To use startVibration and stopVibration, you must configure the ohos.permission.VIBRATE permission.
try {
// Start custom vibration.
vibrator.startVibration({
type: "file",
hapticFd: { fd: fileDescriptor.fd, offset: fileDescriptor.offset, length: fileDescriptor.length }
}, {
usage: "alarm"
}).then(() => {
console.info('Succeed in starting vibration');
}, (error) => {
console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`);
});
// Stop vibration in all modes.
vibrator.stopVibration(function (error) {
if (error) {
console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`);
return;
}
console.info('Succeed in stopping vibration');
})
} catch (error) {
console.error(`An unexpected error occurred. Code: ${error.code}, message: ${error.message}`);
async function getRawfileFd(fileName) {
let rawFd = await globalThis.getContext().resourceManager.getRawFd(fileName);
return rawFd;
}
// Close the file descriptor of the vibration configuration file.
async function closeRawfileFd(fileName) {
await globalThis.getContext().resourceManager.closeRawFd(fileName)
}
// Play the custom vibration. To use startVibration and stopVibration, you must configure the ohos.permission.VIBRATE permission.
async function playCustomHaptic(fileName) {
try {
let rawFd = await getRawfileFd(fileName);
vibrator.startVibration({
type: "file",
hapticFd: { fd: rawFd.fd, offset: rawFd.offset, length: rawFd.length }
}, {
usage: "alarm"
}).then(() => {
console.info('Succeed in starting vibration');
}, (error) => {
console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`);
});
vibrator.stopVibration(function (error) {
if (error) {
console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`);
return;
}
console.info('Succeed in stopping vibration');
})
await closeRawfileFd(fileName);
} catch (error) {
console.error(`An unexpected error occurred. Code: ${error.code}, message: ${error.message}`);
}
}
// Close the vibration file.
getContext().resourceManager.closeRawFd(FILE_NAME).then(() => {
console.info('Succeed in closing resource file descriptor');
}).catch(error => {
console.error(`Failed to close resource file descriptor. Code: ${error.code}, message: ${error.message}`);
});
```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册