driver-peripherals-sensor-des.md 28.6 KB
Newer Older
W
wusongqing 已提交
1
# Sensor
D
duangavin123 已提交
2 3
  

W
wusongqing 已提交
4
## Overview
D
duangavin123 已提交
5

W
wusongqing 已提交
6
### Introduction
D
duangavin123 已提交
7

W
wusongqing 已提交
8
The sensor driver model masks the sensor hardware differences and provides interfaces for the upper-layer sensor service to implement basic sensor capabilities, including querying the sensor list, enabling or disabling a sensor, subscribing to or unsubscribing from sensor data changes, and setting sensor options. The model is developed on the Hardware Driver Foundation (HDF), Operating System Abstraction Layer (OSAL), and platform driver interfaces (such as the I2C, SPI, and UART buses). It provides functionalities such as cross-OS migration and differentiated device configurations. The figure below shows the architecture of the sensor driver model.
D
duangavin123 已提交
9

W
wusongqing 已提交
10 11
**Figure 1** Sensor driver model 
![Sensor driver model](figures/sensor_driver_model.png)
D
duangavin123 已提交
12

W
wusongqing 已提交
13
### Basic Concepts
D
duangavin123 已提交
14

W
wusongqing 已提交
15
Currently, sensors are classified into medical sensors and traditional sensors by sensor ID.
D
duangavin123 已提交
16

W
wusongqing 已提交
17
- The IDs of medical sensors range from 128 to 160.
D
duangavin123 已提交
18

W
wusongqing 已提交
19
- The IDs of traditional sensors are out of the range of 128 to 160.
D
duangavin123 已提交
20

W
wusongqing 已提交
21
### Working Principles
D
duangavin123 已提交
22

W
wusongqing 已提交
23
Based on the loading and running process (shown below) of the sensor driver model, the relationships between key modules in the model and associated modules are clearly defined.
D
duangavin123 已提交
24

W
wusongqing 已提交
25
**Figure 2** How sensor driver works
D
duangavin123 已提交
26

W
wusongqing 已提交
27
![How sensor driver works](figures/sensor_working.png)
D
duangavin123 已提交
28

W
wusongqing 已提交
29
The following uses the acceleration sensor driver on the Hi3516D V300 development board of the standard system as an example to describe the driver loading and running process.
D
duangavin123 已提交
30

W
wusongqing 已提交
31 32 33 34 35 36 37 38 39 40
1. The sensor host reads the sensor management configuration from the Sensor Host node of the device_info HCS (sensor device information HCS).
2. The sensor host parses the sensor management configuration from the HCB database and associates the corresponding sensor driver.
3. The sensor host loads and initializes the sensor manager driver.
4. The sensor manager driver publishes the sensor hardware driver interfaces (HDIs).
5. The sensor host reads the acceleration sensor driver configuration from the Sensor Host node of the device_info HCS.
6. The sensor host loads the acceleration sensor abstract driver and calls the initialization interface to allocate the sensor driver resources and create the data processing queue.
7. The sensor host reads the chipset driver configuration and private configuration of the acceleration sensor from the accel_xxx_config HCS (sensor private configuration HCS).
8. The acceleration sensor chipset driver calls the common configuration parsing interface to parse the sensor attributes and registers.
9. The chipset driver detects sensors, allocates configuration resources to the acceleration sensor, and registers the acceleration sensor chipset interfaces.
10. Upon successful sensor detection, the chipset driver instructs the abstract driver to register the acceleration sensor to the sensor manager driver.
D
duangavin123 已提交
41

W
wusongqing 已提交
42
## Development Guidelines
D
duangavin123 已提交
43

W
wusongqing 已提交
44
### When to Use
D
duangavin123 已提交
45

W
wusongqing 已提交
46 47 48 49 50
- Data provided by the gravity and gyroscope sensors denotes the tilt and rotation of the device, which helps your application improve user experience in games.
- Data provided by the proximity sensor denotes the distance between the device and a visible object, which enables the device to automatically turn on or off its screen accordingly to prevent accidental touch on the screen. For example, when the proximity sensor detects the user face approaches the earpiece during a call, it triggers backlight of the screen to be turned off. This can further reduce power consumption.
- Data provided by the barometric pressure sensor helps your application accurately determine the altitude of the device.
- Data provided by the ambient light sensor helps your device automatically adjust its backlight.
- Data provided by the Hall effect sensor implements the smart cover mode of your device. When the smart cover is closed, a small window is opened on the phone to reduce power consumption. 
D
duangavin123 已提交
51

W
wusongqing 已提交
52
### Available APIs<a name="section188213414114"></a>
D
duangavin123 已提交
53

W
wusongqing 已提交
54
The sensor driver model offers the following APIs:
D
duangavin123 已提交
55

W
wusongqing 已提交
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
- Sensor HDIs, for easier sensor service development
- Sensor driver model capability interfaces
  - Interfaces for registering, loading, and deregistering sensor drivers, and detecting sensors
  - Driver normalization interface, register configuration parsing interface, bus access abstract interface, and platform abstract interface for the same type of sensors
- Interfaces to be implemented by developers: Based on the HDF Configuration Source (HCS) and differentiated configuration for sensors of the same type, developers need to implement serialized configuration of sensor device parameters and some sensor device operation interfaces to simplify sensor driver development.

The sensor driver model provides APIs for the hardware service to make sensor service development easier. See the table below.

**Table 1** APIs for the members in the PinCntlrMethod structure

| API| Description| 
| ----- | -------- |
| int32_t GetAllSensors(struct SensorInformation **sensorInfo, int32_t *count) | Obtains information about all registered sensors in the system. The sensor information includes the sensor name, sensor vendor, firmware version, hardware version, sensor type ID, sensor ID, maximum range, accuracy, and power consumption.|
| int32_t Enable(int32_t sensorId) | Enables a sensor. The subscriber can obtain sensor data only after the sensor is enabled.| 
| int32_t Disable(int32_t sensorId) | Disables a sensor.| 
| int32_t SetBatch(iint32_t sensorId, int64_t samplingInterval, int64_t reportInterval) | Sets the sampling interval and data reporting interval for a sensor.| 
| int32_t SetMode(int32_t sensorId, int32_t mode) | Sets the data reporting mode for a sensor.| 
| int32_t SetOption(int32_t sensorId, uint32_t option) | Sets options for a sensor, including its range and accuracy.| 
| int32_t Register(int32_t groupId, RecordDataCallback cb) | Registers a sensor data callback based on the group ID.| 
| int32_t Unregister(int32_t groupId, RecordDataCallback cb) | Deregisters a sensor data callback based on the group ID.| 



The sensor driver model provides driver development APIs that do not require further implementation. See the table below.

 **Table 2** Sensor driver development APIs that do not need to be implemented by driver developers

| API| Description| 
| ----- | -------- |
| int32_t AddSensorDevice(const struct SensorDeviceInfo *deviceInfo) | Adds a sensor of the current type to the sensor management module.|
| int32_t DeleteSensorDevice(const struct SensorBasicInfo *sensorBaseInfo) | Deletes a sensor from the sensor management module.|
| int32_t ReportSensorEvent(const struct SensorReportEvent *events) | Reports data of a specified sensor type.|
| int32_t ReadSensor(struct SensorBusCfg *busCfg, uint16_t regAddr, uint8_t *data, uint16_t dataLen) | Reads sensor configuration data from the sensor register based on the bus configuration.|
| int32_t WriteSensor(struct SensorBusCfg *busCfg, uint8_t *writeData, uint16_t len) | Writes sensor configuration data to the sensor register based on the bus configuration.|
| int32_t SetSensorRegCfgArray(struct SensorBusCfg *busCfg, const struct SensorRegCfgGroupNode *group); | Sets the sensor register group configuration based on the sensor bus type.|
| int32_t GetSensorBaseConfigData(const struct DeviceResourceNode *node, struct SensorCfgData *config) | Obtains basic configuration information such as sensor, bus, and attribute configurations based on the device information HCS configuration, and initializes the basic configuration data structure.|
| int32_t ParseSensorRegConfig(struct SensorCfgData *config) | Parses the register group information based on the device information HCS configuration and initializes the configuration data structure.|
| void ReleaseSensorAllRegConfig(struct SensorCfgData *config) | Releases the resources allocated to the sensor configuration data structure.|
| int32_t GetSensorBusHandle(struct SensorBusCfg *busCfg) | Obtains the sensor bus handle information.|
| int32_t ReleaseSensorBusHandle(struct SensorBusCfg *busCfg) | Releases the sensor bus handle information.|



The sensor driver model also provides certain driver development APIs that need to be implemented by driver developers. See the table below.

**Table 3** Driver development APIs that need to be implemented by driver developers

| API| Description| 
| ----- | -------- |
| int32_t init(void) | Initializes the sensor device configuration after a sensor is detected.|
| int32_t Enable(void) | Enables the current sensor by delivering the register configuration in the enabling operation group based on the device information HCS configuration.|
| int32_t Disable(void) | Disables the current sensor by delivering the register configuration in the disabling operation group based on the device information HCS configuration.|
| int32_t SetBatch(int64_t samplingInterval, int64_t reportInterval) | Sets the processing time of the data reporting thread for the current sensor based on the sampling interval and data reporting interval.|
| int32_t SetMode(int32_t mode) | Sets the data reporting mode of the current sensor device.|
| int32_t SetOption(uint32_t option) | Sets the register configuration such as the range and accuracy based on sensor options.|
| void ReadSensorData(void) | Reads sensor data.|


For details about the interface implementation, see [How to Develop](#section7893102915819).

### How to Develop<a name="section7893102915819"></a>
1. Develop the acceleration sensor abstract driver. Specifically, implement the **Bind**, **Init**, **Release**, and **Dispatch** functions.

   - Implement the entry function for the acceleration sensor.

     ```c
     /* Register the entry structure object of the acceleration sensor. */
     struct HdfDriverEntry g_sensorAccelDevEntry = {
         .moduleVersion = 1, // Version of the acceleration sensor module.
         .moduleName = "HDF_SENSOR_ACCEL", // Name of the acceleration sensor module. The value must be the same as that of moduleName in the device_info.hcs file.
         .Bind = BindAccelDriver, // Function for binding an acceleration sensor.
         .Init = InitAccelDriver, // Function for initializing an acceleration sensor.
         .Release = ReleaseAccelDriver, // Function for releasing acceleration sensor resources.
     };
     
     /* Call HDF_INIT to register the driver entry with the HDF. When loading the driver, the HDF calls the Bind function first and then the Init function. If the Init function fails to be called, the HDF will call Release to release the driver resource and exit the sensor driver model. */
     HDF_INIT(g_sensorAccelDevEntry);
     ```

   - Implement interfaces for acceleration sensor driver operations.

     ```c
     /* Bind the service provided by the acceleration sensor driver to the HDF. */
     int32_t AccelBindDriver(struct HdfDeviceObject *device)
     {
         CHECK_NULL_PTR_RETURN_VALUE(device, HDF_ERR_INVALID_PARAM);
     
         struct AccelDrvData *drvData = (struct AccelDrvData *)OsalMemCalloc(sizeof(*drvData));
         if (drvData == NULL) {
             HDF_LOGE("%s: Malloc accel drv data fail!", __func__);
             return HDF_ERR_MALLOC_FAIL;
         }
     
         drvData->ioService.Dispatch = DispatchAccel;
         drvData->device = device;
         device->service = &drvData->ioService;
         g_accelDrvData = drvData;
         return HDF_SUCCESS;
     }
     
     /* Register the normalization functions of the acceleration sensor driver. */
     static int32_t InitAccelOps(struct SensorCfgData *config, struct SensorDeviceInfo *deviceInfo)
     {
         CHECK_NULL_PTR_RETURN_VALUE(config, HDF_ERR_INVALID_PARAM);
     
         deviceInfo->ops.Enable = SetAccelEnable;
         deviceInfo->ops.Disable = SetAccelDisable;
         deviceInfo->ops.SetBatch = SetAccelBatch;
         deviceInfo->ops.SetMode = SetAccelMode;
         deviceInfo->ops.SetOption = SetAccelOption;
     
         if (memcpy_s(&deviceInfo->sensorInfo, sizeof(deviceInfo->sensorInfo),
             &config->sensorInfo, sizeof(config->sensorInfo)) != EOK) {
             HDF_LOGE("%s: Copy sensor info failed", __func__);
             return HDF_FAILURE;
         }
     
         return HDF_SUCCESS;
     }
     /* Provide the initialization interface for the chipset driver to parse the basic acceleration sensor configuration (acceleration information, bus configuration, and sensor detection register configuration), detect sensors, and parse sensor registers. */
     static int32_t InitAccelAfterDetected(struct SensorCfgData *config)
     {
         struct SensorDeviceInfo deviceInfo;
         CHECK_NULL_PTR_RETURN_VALUE(config, HDF_ERR_INVALID_PARAM);
         /* Initialize the acceleration sensor function. */
         if (InitAccelOps(config, &deviceInfo) != HDF_SUCCESS) {
             HDF_LOGE("%s: Init accel ops failed", __func__);
             return HDF_FAILURE;
         }
         /* Register the acceleration sensor with the sensor management module. */
         if (AddSensorDevice(&deviceInfo) != HDF_SUCCESS) {
             HDF_LOGE("%s: Add accel device failed", __func__);
             return HDF_FAILURE;
         }
         /* Parse the sensor register. */
         if (ParseSensorRegConfig(config) != HDF_SUCCESS) {
             HDF_LOGE("%s: Parse sensor register failed", __func__);
             (void)DeleteSensorDevice(&config->sensorInfo);
             ReleaseSensorAllRegConfig(config);
             return HDF_FAILURE;
         }
         return HDF_SUCCESS;
     }
     struct SensorCfgData *AccelCreateCfgData(const struct DeviceResourceNode *node)
     {
         ......
         /* Continue the next detection if the sensor is not detected. */
         if (drvData->detectFlag) {
             HDF_LOGE("%s: Accel sensor have detected", __func__);
             return NULL;
         }
         if (drvData->accelCfg == NULL) {
             HDF_LOGE("%s: Accel accelCfg pointer NULL", __func__);
             return NULL;
         }
         /* Parse the basic sensor configuration. */
         if (GetSensorBaseConfigData(node, drvData->accelCfg) != HDF_SUCCESS) {
             HDF_LOGE("%s: Get sensor base config failed", __func__);
             goto BASE_CONFIG_EXIT;
         }
         /* Continue the next detection if the sensor is not detected. */
         if (DetectSensorDevice(drvData->accelCfg) != HDF_SUCCESS) {
             HDF_LOGI("%s: Accel sensor detect device no exist", __func__);
             drvData->detectFlag = false;
             goto BASE_CONFIG_EXIT;
         }
         drvData->detectFlag = true;
         /* Parse the sensor register. */
         if (InitAccelAfterDetected(drvData->accelCfg) != HDF_SUCCESS) {
             HDF_LOGE("%s: Accel sensor detect device no exist", __func__);
             goto INIT_EXIT;
         }
         return drvData->accelCfg;
         ......
     }
     /* The entry function of the acceleration sensor driver is used to initialize the sensor private data structure object, allocate space for the sensor HCS data configuration object, call the entry function for initializing the sensor HCS data configuration, detect whether the sensor device is in position, create a sensor data reporting timer, register the sensor normalization APIs, and register the sensor device. */
     int32_t AccelInitDriver(struct HdfDeviceObject *device)
     {
         ......
         /* Initialize work queue resources. */
         if (InitAccelData(drvData) != HDF_SUCCESS) {
             HDF_LOGE("%s: Init accel config failed", __func__);
             return HDF_FAILURE;
         }
         /* Allocate acceleration configuration resources. */
         drvData->accelCfg = (struct SensorCfgData *)OsalMemCalloc(sizeof(*drvData->accelCfg));
         if (drvData->accelCfg == NULL) {
             HDF_LOGE("%s: Malloc accel config data failed", __func__);
             return HDF_FAILURE;
         }
         /* Register the register group information. */
         drvData->accelCfg->regCfgGroup = &g_regCfgGroup[0];
         ......
         return HDF_SUCCESS;
     }
     /* Release the resources allocated during driver initialization. */
     void AccelReleaseDriver(struct HdfDeviceObject *device)
     {
         CHECK_NULL_PTR_RETURN(device);
         struct AccelDrvData *drvData = (struct AccelDrvData *)device->service;
         CHECK_NULL_PTR_RETURN(drvData);
         /* Release the resources if the sensor is in position. */
         if (drvData->detectFlag) {
             AccelReleaseCfgData(drvData->accelCfg);
         }
         OsalMemFree(drvData->accelCfg);
         drvData->accelCfg = NULL;
         /* Destroy the work queue resource if the sensor is in position. */
         HdfWorkDestroy(&drvData->accelWork);
         HdfWorkQueueDestroy(&drvData->accelWorkQueue);
         OsalMemFree(drvData);
     }
     ```

2. Configure the device information about the acceleration sensor driver.

   The acceleration sensor model uses the HCS as the configuration source code. For details about the HCS configuration fields, see [Driver Configuration Management](driver-hdf-manage.md).

   ```
   /* Device information HCS configuration of the acceleration sensor. */
   device_sensor_accel :: device {
       device0 :: deviceNode {
           policy = 1; // Policy for publishing the driver service.
           priority = 110; // Driver startup priority (0–200). A larger value indicates a lower priority. The default value 100 is recommended. The sequence for loading devices with the same priority is random.
           preload = 0; // Field for specifying whether to load the driver. The value 0 means to load the driver, and 2 means the opposite.
           permission = 0664; // Permission for the driver to create a device node.
           moduleName = "HDF_SENSOR_ACCEL"; // Driver name. The value must be the same as that of moduleName in the driver entry structure.
           serviceName = "sensor_accel"; // Name of the service provided by the driver. The name must be unique.
           deviceMatchAttr = "hdf_sensor_accel_driver"; // Keyword matching the private data of the driver. The value must be the same as that of match_attr in the private data configuration table of the driver.
       }
   } 
   ```

3. Develop the internal interfaces of the acceleration sensor abstract driver. Specifically, implement the **Enable**, **Disable**, **SetBatch**, **SetMode**, **SetOption**, **AccelCreateCfgData**, **AccelReleaseCfgData**, and **AccelRegisterChipOps** functions.

   ```c
   /* Leave a function empty if it is not used. */
   static int32_t SetAccelInfo(struct SensorBasicInfo *info)
   {
       (void)info;
   
       return HDF_ERR_NOT_SUPPORT;
   }
   /* Deliver the configuration of enabling the register groups. */
   static int32_t SetAccelEnable(void)
   {
       int32_t ret;
       struct AccelDrvData *drvData = AccelGetDrvData();
   
       CHECK_NULL_PTR_RETURN_VALUE(drvData, HDF_ERR_INVALID_PARAM);
       CHECK_NULL_PTR_RETURN_VALUE(drvData->accelCfg, HDF_ERR_INVALID_PARAM);
   
       if (drvData->enable) {
           HDF_LOGE("%s: Accel sensor is enabled", __func__);
           return HDF_SUCCESS;
       }
   
       ret = SetSensorRegCfgArray(&drvData->accelCfg->busCfg, drvData->accelCfg->regCfgGroup[SENSOR_ENABLE_GROUP]);
       if (ret != HDF_SUCCESS) {
           HDF_LOGE("%s: Accel sensor enable config failed", __func__);
           return ret;
       }
   
       ret = OsalTimerCreate(&drvData->accelTimer, SENSOR_TIMER_MIN_TIME, AccelTimerEntry, (uintptr_t)drvData);
       if (ret != HDF_SUCCESS) {
           HDF_LOGE("%s: Accel create timer failed[%d]", __func__, ret);
           return ret;
       }
   
       ret = OsalTimerStartLoop(&drvData->accelTimer);
       if (ret != HDF_SUCCESS) {
           HDF_LOGE("%s: Accel start timer failed[%d]", __func__, ret);
           return ret;
       }
       drvData->enable = true;
   
       return HDF_SUCCESS;
   }
   /* Deliver the configuration of disabling the register groups. */
   static int32_t SetAccelDisable(void)
   {
       int32_t ret;
       struct AccelDrvData *drvData = AccelGetDrvData();
   
       CHECK_NULL_PTR_RETURN_VALUE(drvData, HDF_ERR_INVALID_PARAM);
       CHECK_NULL_PTR_RETURN_VALUE(drvData->accelCfg, HDF_ERR_INVALID_PARAM);
   
       if (!drvData->enable) {
           HDF_LOGE("%s: Accel sensor had disable", __func__);
           return HDF_SUCCESS;
       }
   
       ret = SetSensorRegCfgArray(&drvData->accelCfg->busCfg, drvData->accelCfg->regCfgGroup[SENSOR_DISABLE_GROUP]);
       if (ret != HDF_SUCCESS) {
           HDF_LOGE("%s: Accel sensor disable config failed", __func__);
           return ret;
       }
   
       ret = OsalTimerDelete(&drvData->accelTimer);
       if (ret != HDF_SUCCESS) {
           HDF_LOGE("%s: Accel delete timer failed", __func__);
           return ret;
       }
       drvData->enable = false;
   
       return HDF_SUCCESS;
   }
   /* Set the sampling interval and data reporting interval of the sensor. */
   static int32_t SetAccelBatch(int64_t samplingInterval, int64_t interval)
   {
       (void)interval;
   
       struct AccelDrvData *drvData = NULL;
   
       drvData = AccelGetDrvData();
       CHECK_NULL_PTR_RETURN_VALUE(drvData, HDF_ERR_INVALID_PARAM);
   
       drvData->interval = samplingInterval;
   
       return HDF_SUCCESS;
   }
   /* Set the data reporting mode of the sensor. Currently, the real-time mode is supported. */
   static int32_t SetAccelMode(int32_t mode)
   {
       return (mode == SENSOR_WORK_MODE_REALTIME) ? HDF_SUCCESS : HDF_FAILURE;
   }
   
   static int32_t SetAccelOption(uint32_t option)
   {
       (void)option;
       return HDF_SUCCESS;
   }
   /* Set the sensor options. */
   static int32_t SetAccelOption(uint32_t option)
   {
       (void)option;
       return HDF_ERR_NOT_SUPPORT;
   }
   ```

4. Develop the acceleration sensor chipset driver. Specifically, implement the **Bind**, **Init**, **Release**, and **Dispatch** functions.

   ```c
   /* Message interaction of the acceleration sensor chipset driver */
   static int32_t DispatchBMI160(struct HdfDeviceIoClient *client,
       int cmd, struct HdfSBuf *data, struct HdfSBuf *reply)
   {
       (void)client;
       (void)cmd;
       (void)data;
       (void)reply;
   
       return HDF_SUCCESS;
   }
   /* Bind the service provided by the acceleration sensor chipset driver to the HDF. */
   int32_t Bmi160BindDriver(struct HdfDeviceObject *device)
   {
       CHECK_NULL_PTR_RETURN_VALUE(device, HDF_ERR_INVALID_PARAM);
   
       struct Bmi160DrvData *drvData = (struct Bmi160DrvData *)OsalMemCalloc(sizeof(*drvData));
       if (drvData == NULL) {
           HDF_LOGE("%s: Malloc Bmi160 drv data fail", __func__);
           return HDF_ERR_MALLOC_FAIL;
       }
   
       drvData->ioService.Dispatch = DispatchBMI160;
       drvData->device = device;
       device->service = &drvData->ioService;
       g_bmi160DrvData = drvData;
   
       return HDF_SUCCESS;
   }
   /* Initialize the acceleration sensor chipset driver. */
   int32_t Bmi160InitDriver(struct HdfDeviceObject *device)
   {
       int32_t ret;
       struct AccelOpsCall ops;
   
       CHECK_NULL_PTR_RETURN_VALUE(device, HDF_ERR_INVALID_PARAM);
       struct Bmi160DrvData *drvData = (struct Bmi160DrvData *)device->service;
       CHECK_NULL_PTR_RETURN_VALUE(drvData, HDF_ERR_INVALID_PARAM);
   
       ret = InitAccelPreConfig();
       if (ret != HDF_SUCCESS) {
           HDF_LOGE("%s: Init  BMI160 bus mux config", __func__);
           return HDF_FAILURE;
       }
   
       drvData->sensorCfg = AccelCreateCfgData(device->property);
       if (drvData->sensorCfg == NULL || drvData->sensorCfg->root == NULL) {
           HDF_LOGD("%s: Creating accelcfg failed because detection failed", __func__);
           return HDF_ERR_NOT_SUPPORT;
       }
   
       ops.Init = NULL;
       ops.ReadData = ReadBmi160Data;
       ret = AccelRegisterChipOps(&ops);
       if (ret != HDF_SUCCESS) {
           HDF_LOGE("%s: Register BMI160 accel failed", __func__);
           return HDF_FAILURE;
       }
   
       ret = InitBmi160(drvData->sensorCfg);
       if (ret != HDF_SUCCESS) {
           HDF_LOGE("%s: Init BMI160 accel failed", __func__);
           return HDF_FAILURE;
       }
   
       return HDF_SUCCESS;
   }
   /* Release the resources allocated during driver initialization. */
   void Bmi160ReleaseDriver(struct HdfDeviceObject *device)
   {
   	......
       if (drvData->sensorCfg != NULL) {
           AccelReleaseCfgData(drvData->sensorCfg);
           drvData->sensorCfg = NULL;
       }
       OsalMemFree(drvData);
   }
   /*HdfDriverEntry object corresponding to the acceleration sensor chipset driver */
   struct HdfDriverEntry g_accelBmi160DevEntry = {
       .moduleVersion = 1,
       .moduleName = "HDF_SENSOR_ACCEL_BMI160",
       .Bind = Bmi160BindDriver,
       .Init = Bmi160InitDriver,
       .Release = Bmi160ReleaseDriver,
   };
   HDF_INIT(g_accelBmi160DevEntry);
   ```

5. Implement the **ReadData** function of the acceleration sensor chipset driver.

   ```c
   int32_t ReadBmi160Data(struct SensorCfgData *data)
   {
       int32_t ret;
       struct AccelData rawData = { 0, 0, 0 };
       int32_t tmp[ACCEL_AXIS_NUM];
       struct SensorReportEvent event;
       (void)memset_s(&event, sizeof(event), 0, sizeof(event));
       ret = ReadBmi160RawData(data, &rawData, &event.timestamp);
       if (ret != HDF_SUCCESS) {
           HDF_LOGE("%s: BMI160 read raw data failed", __func__);
           return HDF_FAILURE;
       }
       event.sensorId = SENSOR_TAG_ACCELEROMETER;
       event.option = 0;
       event.mode = SENSOR_WORK_MODE_REALTIME;
       ......
       ret = ReportSensorEvent(&event);
       if (ret != HDF_SUCCESS) {
           HDF_LOGE("%s: BMI160 report data failed", __func__);
       }
       return ret;
   }
   ```

>![](../public_sys-resources/icon-note.gif) **NOTE**
>
>- The sensor driver model provides certain APIs to implement sensor driver capabilities, including the driver device management, abstract bus and platform operation, common configuration, and configuration parsing capabilities. For details about them, see [Table 2](#table1156812588320).
>
>- You need to implement the following functions: certain sensor operation interfaces (listed in [Table 3](#table1083014911336)) and sensor chipset HCS configuration.
> - You also need to verify basic driver functions.

### Commissioning and Verifying<a name="section106021256121219"></a>

After the driver is developed, you can develop self-test cases in the sensor unit test to verify the basic functions of the driver. Use the developer self-test platform as the test environment.
D
duangavin123 已提交
524 525

```
W
wusongqing 已提交
526 527
static int32_t g_sensorDataFlag = 0; // Indicates whether to report sensor data.
static const struct SensorInterface *g_sensorDev = nullptr; // Retain the obtained sensor interface instance address.
D
duangavin123 已提交
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561

/* Register the data reporting function. */
static int SensorTestDataCallback(struct SensorEvents *event)
{
    if (event == nullptr) {
        return -1;
    }
    float *data = (float*)event->data;
    printf("time [%lld] sensor id [%d] x-[%f] y-[%f] z-[%f]\n\r", event->timestamp,
        event->sensorId, (*data), *(data + 1), *(data + g_axisZ));
    if (*data > 1e-5) {
        g_sensorDataFlag = 1;
    }
    return 0;
}
/* Initialize the sensor interface instance before executing the test cases. */
void HdfSensorTest::SetUpTestCase()
{
    g_sensorDev = NewSensorInterfaceInstance();
    if (g_sensorDev == nullptr) {
        printf("test sensorHdi get Module instace failed\n\r");
    }
}
/* Release case resources. */
void HdfSensorTest::TearDownTestCase()
{
    if (g_sensorDev != nullptr) {
        FreeSensorInterfaceInstance();
        g_sensorDev = nullptr;
    }
}
/* Verify the sensor driver. */
HWTEST_F(HdfSensorTest,TestAccelDriver_001, TestSize.Level0)
{
W
wusongqing 已提交
562 563 564
    int32_t sensorInterval = 1000000000; // Data sampling interval, in nanoseconds.
    int32_t pollTime = 5; // Data sampling duration, in seconds.
    int32_t accelSensorId = 1; // Acceleration sensor ID, which is 1.
D
duangavin123 已提交
565 566 567 568
    int32_t count = 0;
    int ret;
    struct SensorInformation *sensorInfo = nullptr;

W
wusongqing 已提交
569
    ret = g_sensorDev->Register(0, TraditionSensorTestDataCallback)
D
duangavin123 已提交
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
    EXPECT_EQ(SENSOR_NULL_PTR, ret);

    ret = g_sensorDev->GetAllSensors(&sensorInfo, &count);
    EXPECT_EQ(0, ret);
    if (sensorInfo == nullptr) {
        EXPECT_NE(nullptr, sensorInfo);
        return;
    }
    /* Print the obtained sensor list. */
    for (int i = 0; i < count; i++) {
        printf("get sensoriId[%d], info name[%s]\n\r", sensorInfo[i]->sensorId, sensorInfo[i]->sensorName);
    }
    ret = g_sensorDev->Enable(accelSensorId);
    EXPECT_EQ(0, ret);
    g_sensorDataFlag = 0;

    ret = g_sensorDev->SetBatch(accelSensorId, sensorInterval, pollTime);
    EXPECT_EQ(0, ret);
    /* Observe the printed data within the period specified by pollTime. */
    OsalSleep(pollTime);
    EXPECT_EQ(1, g_sensorDataFlag);

    ret = g_sensorDev->Disable(accelSensorId);
    g_sensorDataFlag = 0;
    EXPECT_EQ(0, ret);

W
wusongqing 已提交
596
    ret = g_sensorDev->Unregister(0, TraditionSensorTestDataCallback);
D
duangavin123 已提交
597 598 599
    EXPECT_EQ(0, ret);
}
```