1# @ohos.sensor (Sensor) (System API) 2 3The **Sensor** module provides APIs for obtaining the sensor list and subscribing to sensor data. It also provides some common sensor algorithms. 4 5> **NOTE** 6> 7> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. 8> 9> The APIs provided by this module are system APIs. 10 11 12## Modules to Import 13 14```ts 15import { sensor } from '@kit.SensorServiceKit'; 16``` 17 18## sensor.on 19 20### COLOR<sup>10+</sup> 21 22on(type: SensorId.COLOR, callback: Callback<ColorResponse>, options?: Options): void 23 24Subscribes to data of the color sensor. 25 26**System capability**: SystemCapability.Sensors.Sensor 27 28**System API**: This is a system API. 29 30**Parameters** 31 32| Name | Type | Mandatory| Description | 33| -------- | ------------------------------------------------- | ---- | ----------------------------------------------------------- | 34| type | [SensorId](#sensorid9).COLOR | Yes | Sensor type. The value is fixed at **SensorId.COLOR**. | 35| callback | Callback<[ColorResponse](#colorresponse10)> | Yes | Callback used to report the sensor data, which is a **ColorResponse** object. | 36| options | [Options](js-apis-sensor.md#options) | No | List of optional parameters. This parameter is used to set the data reporting frequency. The default value is 200,000,000 ns.| 37 38**Error codes** 39 40For details about the error codes, see [Sensor Error Codes](errorcode-sensor.md) and [Universal Error Codes](../errorcode-universal.md). 41 42| ID| Error Message | 43| -------- | ------------------------------------------------------------ | 44| 202 | Permission check failed. A non-system application uses the system API. | 45| 401 | Parameter error.Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | 46| 14500101 | Service exception.Possible causes:1. Sensor hdf service exception;2. Sensor service ipc exception;3.Sensor data channel exception. | 47 48**Example** 49 50```ts 51import { sensor } from '@kit.SensorServiceKit'; 52import { BusinessError } from '@kit.BasicServicesKit'; 53 54try{ 55 sensor.on(sensor.SensorId.COLOR, (data: sensor.ColorResponse) => { 56 console.log('Succeeded in getting the intensity of light: ' + data.lightIntensity); 57 console.log('Succeeded in getting the color temperature: ' + data.colorTemperature); 58 }, { interval: 100000000 }); 59 setTimeout(() => { 60 sensor.off(sensor.SensorId.COLOR); 61 }, 500); 62} catch (error) { 63 let e: BusinessError = error as BusinessError; 64 console.error(`Failed to invoke on. Code: ${e.code}, message: ${e.message}`); 65} 66``` 67 68### SAR<sup>10+</sup> 69 70on(type: SensorId.SAR, callback: Callback<SarResponse>, options?: Options): void 71 72Subscribes to data of the Sodium Adsorption Ratio (SAR) sensor. 73 74**System capability**: SystemCapability.Sensors.Sensor 75 76**System API**: This is a system API. 77 78**Parameters** 79 80| Name | Type | Mandatory| Description | 81| -------- | --------------------------------------------- | ---- | ----------------------------------------------------------- | 82| type | [SensorId](#sensorid9).SAR | Yes | Sensor type. The value is fixed at **SensorId.SAR**. | 83| callback | Callback<[SarResponse](#sarresponse10)> | Yes | Callback used to report the sensor data, which is a **SarResponse** object. | 84| options | [Options](js-apis-sensor.md#options) | No | List of optional parameters. This parameter is used to set the data reporting frequency. The default value is 200,000,000 ns.| 85 86**Error codes** 87 88For details about the error codes, see [Sensor Error Codes](errorcode-sensor.md) and [Universal Error Codes](../errorcode-universal.md). 89 90| ID| Error Message | 91| -------- | ------------------------------------------------------------ | 92| 202 | Permission check failed. A non-system application uses the system API. | 93| 401 | Parameter error.Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | 94| 14500101 | Service exception.Possible causes:1. Sensor hdf service exception;2. Sensor service ipc exception;3.Sensor data channel exception. | 95 96**Example** 97 98```ts 99import { sensor } from '@kit.SensorServiceKit'; 100import { BusinessError } from '@kit.BasicServicesKit'; 101 102try { 103 sensor.on(sensor.SensorId.SAR, (data: sensor.SarResponse) => { 104 console.info('Succeeded in getting specific absorption rate : ' + data.absorptionRatio); 105 }, { interval: 100000000 }); 106 setTimeout(() => { 107 sensor.off(sensor.SensorId.SAR); 108 }, 500); 109} catch (error) { 110 let e: BusinessError = error as BusinessError; 111 console.error(`Failed to invoke on. Code: ${e.code}, message: ${e.message}`); 112} 113``` 114 115## sensor.off 116 117### COLOR<sup>10+</sup> 118 119off(type: SensorId.COLOR, callback?: Callback<ColorResponse>): void 120 121Unsubscribes from data of the color sensor. 122 123**System capability**: SystemCapability.Sensors.Sensor 124 125**System API**: This is a system API. 126 127**Parameters** 128 129| Name | Type | Mandatory| Description | 130| -------- |--------------------------------------------------------| ---- | ------------------------------------------------------------ | 131| type | [SensorId](#sensorid9).COLOR | Yes | Sensor type. The value is fixed at **SensorId.COLOR**. | 132| 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.| 133 134**Error codes** 135 136For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 137 138| ID| Error Message | 139| -------- | ------------------------------------------------------------ | 140| 202 | Permission check failed. A non-system application uses the system API. | 141| 401 | Parameter error.Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | 142 143**Example** 144 145```ts 146import { sensor } from '@kit.SensorServiceKit'; 147import { BusinessError } from '@kit.BasicServicesKit'; 148 149function callback1(data: object) { 150 console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); 151} 152 153function callback2(data: object) { 154 console.info('Succeeded in getting callback2 data: ' + JSON.stringify(data)); 155} 156 157try { 158 sensor.on(sensor.SensorId.COLOR, callback1); 159 sensor.on(sensor.SensorId.COLOR, callback2); 160 // Unsubscribe from callback1. 161 sensor.off(sensor.SensorId.COLOR, callback1); 162 // Unsubscribe from all callbacks of the SensorId.COLOR type. 163 sensor.off(sensor.SensorId.COLOR); 164} catch (error) { 165 let e: BusinessError = error as BusinessError; 166 console.error(`Failed to invoke off. Code: ${e.code}, message: ${e.message}`); 167} 168``` 169 170### COLOR<sup>19+</sup> 171 172off(type: SensorId.COLOR, sensorInfoParam?: SensorInfoParam, callback?: Callback<ColorResponse>): void 173 174Unsubscribes from data of the color sensor. 175 176**System capability**: SystemCapability.Sensors.Sensor 177 178**System API**: This is a system API. 179 180**Parameters** 181 182| Name | Type | Mandatory| Description | 183| -------- |--------------------------------------------------------| ---- | ------------------------------------------------------------ | 184| type | [SensorId](#sensorid9).COLOR | Yes | Sensor type. The value is fixed at **SensorId.COLOR**. | 185| sensorInfoParam | [SensorInfoParam](#sensorinfoparam19) | No| Sensor parameters, including **deviceId** and **sensorIndex**.| 186| 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.| 187 188**Error codes** 189 190For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 191 192| ID| Error Message | 193| -------- | ------------------------------------------------------------ | 194| 202 | Permission check failed. A non-system application uses the system API. | 195| 14500101 | Service exception.Possible causes:1. Sensor hdf service exception;2. Sensor service ipc exception;3.Sensor data channel exception. | 196 197**Example** 198 199```ts 200import { sensor } from '@kit.SensorServiceKit'; 201import { BusinessError } from '@kit.BasicServicesKit'; 202 203enum Ret { OK, Failed = -1 } 204 205// Sensor callback 206const sensorCallback = (response: sensor.ColorResponse) => { 207 console.log(`callback response: ${JSON.stringify(response)}`); 208} 209// Sensor type 210const sensorType = sensor.SensorId.COLOR; 211const sensorInfoParam: sensor.SensorInfoParam = {}; 212 213function sensorSubscribe(): Ret { 214 let ret: Ret = Ret.OK; 215 try { 216 // Query all sensors. 217 const sensorList: sensor.Sensor[] = sensor.getSensorListSync(); 218 if (!sensorList.length) { 219 return Ret.Failed; 220 } 221 // Obtain the target sensor based on the actual service logic. 222 const targetSensor: sensor.Sensor = sensorList[0]; 223 sensorInfoParam.deviceId = targetSensor.deviceId ?? -1; 224 sensorInfoParam.sensorIndex = targetSensor.sensorIndex ?? -1; 225 // Subscribe to sensor events. 226 sensor.on(sensorType, sensorCallback, { sensorInfoParam }); 227 } catch (error) { 228 let e: BusinessError = error as BusinessError; 229 console.error(`Failed to invoke sensor.on. Code: ${e.code}, message: ${e.message}`); 230 ret = Ret.Failed; 231 } 232 return ret; 233} 234 235function sensorUnsubscribe(): Ret { 236 let ret: Ret = Ret.OK; 237 try { 238 sensor.off(sensorType, sensorInfoParam, sensorCallback); 239 } catch (error) { 240 let e: BusinessError = error as BusinessError; 241 console.error(`Failed to invoke sensor.off. Code: ${e.code}, message: ${e.message}`); 242 ret = Ret.Failed; 243 } 244 return ret; 245} 246``` 247 248### SAR<sup>10+</sup> 249 250off(type: SensorId.SAR, callback?: Callback<SarResponse>): void 251 252Unsubscribes from data of the SAR sensor. 253 254**System capability**: SystemCapability.Sensors.Sensor 255 256**System API**: This is a system API. 257 258**Parameters** 259 260| Name | Type | Mandatory| Description | 261| -------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | 262| type | [SensorId](#sensorid9).SAR | Yes | Sensor type. The value is fixed at **SensorId.SAR**. | 263| 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.| 264 265**Error codes** 266 267For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 268 269| ID| Error Message | 270| -------- | ------------------------------------------------------------ | 271| 202 | Permission check failed. A non-system application uses the system API. | 272| 401 | Parameter error.Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | 273 274**Example** 275 276```ts 277import { sensor } from '@kit.SensorServiceKit'; 278import { BusinessError } from '@kit.BasicServicesKit'; 279 280function callback1(data: object) { 281 console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); 282} 283 284function callback2(data: object) { 285 console.info('Succeeded in getting callback2 data: ' + JSON.stringify(data)); 286} 287 288try { 289 sensor.on(sensor.SensorId.SAR, callback1); 290 sensor.on(sensor.SensorId.SAR, callback2); 291 // Unsubscribe from callback1. 292 sensor.off(sensor.SensorId.SAR, callback1); 293 // Unsubscribe from all callbacks of the SensorId.SAR type. 294 sensor.off(sensor.SensorId.SAR); 295} catch (error) { 296 let e: BusinessError = error as BusinessError; 297 console.error(`Failed to invoke off. Code: ${e.code}, message: ${e.message}`); 298} 299``` 300 301### SAR<sup>19+</sup> 302 303off(type: SensorId.SAR, sensorInfoParam?: SensorInfoParam, callback?: Callback<SarResponse>): void 304 305Unsubscribes from data of the SAR sensor. 306 307**System capability**: SystemCapability.Sensors.Sensor 308 309**System API**: This is a system API. 310 311**Parameters** 312 313| Name | Type | Mandatory| Description | 314| -------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | 315| type | [SensorId](#sensorid9).SAR | Yes | Sensor type. The value is fixed at **SensorId.SAR**. | 316| sensorInfoParam | [SensorInfoParam](#sensorinfoparam19) | No| Sensor parameters, including **deviceId** and **sensorIndex**.| 317| 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.| 318 319**Error codes** 320 321For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 322 323| ID| Error Message | 324| -------- |-----------------------------------------------------------------------------------------------------------------------------------------| 325| 202 | Permission check failed. A non-system application uses the system API. | 326| 14500101 | Service exception.Possible causes:1. Sensor hdf service exception;2. Sensor service ipc exception;3.Sensor data channel exception. | 327 328**Example** 329 330```ts 331import { sensor } from '@kit.SensorServiceKit'; 332import { BusinessError } from '@kit.BasicServicesKit'; 333 334enum Ret { OK, Failed = -1 } 335 336// Sensor callback 337const sensorCallback = (response: sensor.SarResponse) => { 338 console.log(`callback response: ${JSON.stringify(response)}`); 339} 340// Sensor type 341const sensorType = sensor.SensorId.SAR; 342const sensorInfoParam: sensor.SensorInfoParam = {}; 343 344function sensorSubscribe(): Ret { 345 let ret: Ret = Ret.OK; 346 try { 347 // Query all sensors. 348 const sensorList: sensor.Sensor[] = sensor.getSensorListSync(); 349 if (!sensorList.length) { 350 return Ret.Failed; 351 } 352 // Obtain the target sensor based on the actual service logic. 353 const targetSensor: sensor.Sensor = sensorList[0]; 354 sensorInfoParam.deviceId = targetSensor.deviceId ?? -1; 355 sensorInfoParam.sensorIndex = targetSensor.sensorIndex ?? -1; 356 // Subscribe to sensor events. 357 sensor.on(sensorType, sensorCallback, { sensorInfoParam }); 358 } catch (error) { 359 let e: BusinessError = error as BusinessError; 360 console.error(`Failed to invoke sensor.on. Code: ${e.code}, message: ${e.message}`); 361 ret = Ret.Failed; 362 } 363 return ret; 364} 365 366function sensorUnsubscribe(): Ret { 367 let ret: Ret = Ret.OK; 368 try { 369 sensor.off(sensorType, sensorInfoParam, sensorCallback); 370 } catch (error) { 371 let e: BusinessError = error as BusinessError; 372 console.error(`Failed to invoke sensor.off. Code: ${e.code}, message: ${e.message}`); 373 ret = Ret.Failed; 374 } 375 return ret; 376} 377``` 378 379## SensorId<sup>9+</sup> 380 381Enumerates the sensor types. 382 383**System capability**: SystemCapability.Sensors.Sensor 384 385| Name | Value | Description | 386| ------------------- | ---- | ----------------------------------------------- | 387| COLOR<sup>10+</sup> | 14 | Color sensor.<br>System API: This is a system API. | 388| SAR<sup>10+</sup> | 15 | Sodium Adsorption Ratio (SAR) sensor.<br>System API: This is a system API.| 389 390## ColorResponse<sup>10+</sup> 391 392Describes the color sensor data. It extends from [Response](js-apis-sensor.md#response). 393 394**System capability**: SystemCapability.Sensors.Sensor 395 396**System API**: This is a system API. 397 398 399| Name | Type | Read-Only| Optional| Description | 400| ---------------- | ------ | ---- | ---- | ----------------------------- | 401| lightIntensity | number | Yes | Yes | Intensity of light, in lux.| 402| colorTemperature | number | Yes | Yes | Color temperature, in Kelvin. | 403 404## SarResponse<sup>10+ </sup> 405 406Describes the SAR sensor data. It extends from [Response](js-apis-sensor.md#response). 407 408**System capability**: SystemCapability.Sensors.Sensor 409 410**System API**: This is a system API. 411 412 413| Name | Type | Read-Only| Optional| Description | 414| --------------- | ------ | ---- | ---- | ------------------------------- | 415| absorptionRatio | number | Yes | Yes | Absorption ratio, in W/kg.| 416 417 418## SensorInfoParam<sup>19+</sup> 419 420Defines sensor parameters. 421 422**System capability**: SystemCapability.Sensors.Sensor 423 424 425| Name| Type | Mandatory| Description | 426| ------ | ---------------------- | ---- |-------------------------| 427| deviceId | number | No | Device ID. The default value is **-1**, which indicates the local device. | 428| sensorIndex | number | No | Sensor index. The default value is **0**, which indicates the default sensor on the device.| 429