• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Sensor
2
3
4## Overview
5
6### Introduction
7
8The 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.
9
10**Figure 1** Sensor driver model
11
12![Sensor driver model](figures/sensor_driver_model.png)
13
14### Basic Concepts
15
16Currently, sensors are classified into medical sensors and traditional sensors by sensor ID.
17
18- The IDs of medical sensors range from 128 to 160.
19
20- The IDs of traditional sensors are out of the range of 128 to 160.
21
22### Working Principles
23
24Based 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.
25
26**Figure 2** How sensor driver works
27
28![How sensor driver works](figures/sensor_working.png)
29
30The 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.
31
321. The sensor host reads the sensor management configuration from the Sensor Host node of the device_info HCS (sensor device information HCS).
332. The sensor host parses the sensor management configuration from the HCB database and associates the corresponding sensor driver.
343. The sensor host loads and initializes the sensor manager driver.
354. The sensor manager driver publishes the sensor hardware driver interfaces (HDIs).
365. The sensor host reads the acceleration sensor driver configuration from the Sensor Host node of the device_info HCS.
376. 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.
387. 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).
398. The acceleration sensor chipset driver calls the common configuration parsing interface to parse the sensor attributes and registers.
409. The chipset driver detects sensors, allocates configuration resources to the acceleration sensor, and registers the acceleration sensor chipset interfaces.
4110. Upon successful sensor detection, the chipset driver instructs the abstract driver to register the acceleration sensor to the sensor manager driver.
42
43## Development Guidelines
44
45### When to Use
46
47- 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.
48- 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 prevents the screen from being accidentally touched and further reduces power consumption.
49- Data provided by the barometric pressure sensor helps your application accurately determine the altitude of the device.
50- Data provided by the ambient light sensor helps your device automatically adjust its backlight.
51- 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.
52
53### Available APIs
54
55The sensor driver model offers the following APIs:
56
57- Sensor HDIs, for easier sensor service development
58- Sensor driver model capability interfaces
59  - Interfaces for registering, loading, and deregistering sensor drivers, and detecting sensors
60  - Driver normalization interface, register configuration parsing interface, bus access abstract interface, and platform abstract interface for the same type of sensors
61- 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.
62
63The sensor driver model provides APIs for the hardware service to make sensor service development easier. See the table below.
64
65**Table 1** APIs of the sensor driver model
66
67| API| Description|
68| ----- | -------- |
69| 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.|
70| int32_t Enable(int32_t sensorId) | Enables a sensor. The subscriber can obtain sensor data only after the sensor is enabled.|
71| int32_t Disable(int32_t sensorId) | Disables a sensor.|
72| int32_t SetBatch(iint32_t sensorId, int64_t samplingInterval, int64_t reportInterval) | Sets the sampling interval and data reporting interval for a sensor.|
73| int32_t SetMode(int32_t sensorId, int32_t mode) | Sets the data reporting mode for a sensor.|
74| int32_t SetOption(int32_t sensorId, uint32_t option) | Sets options for a sensor, including its range and accuracy.|
75| int32_t Register(int32_t groupId, RecordDataCallback cb) | Registers a sensor data callback based on the group ID.|
76| int32_t Unregister(int32_t groupId, RecordDataCallback cb) | Deregisters a sensor data callback based on the group ID.|
77
78
79
80The sensor driver model provides driver development APIs that do not require further implementation. See the table below.
81
82 **Table 2** Sensor driver development APIs that do not need to be implemented by driver developers
83
84| API| Description|
85| ----- | -------- |
86| int32_t AddSensorDevice(const struct SensorDeviceInfo *deviceInfo) | Adds a sensor of the current type to the sensor management module.|
87| int32_t DeleteSensorDevice(const struct SensorBasicInfo *sensorBaseInfo) | Deletes a sensor from the sensor management module.|
88| int32_t ReportSensorEvent(const struct SensorReportEvent *events) | Reports data of a specified sensor type.|
89| 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.|
90| 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.|
91| int32_t SetSensorRegCfgArray(struct SensorBusCfg *busCfg, const struct SensorRegCfgGroupNode *group); | Sets the sensor register group configuration based on the sensor bus type.|
92| 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.|
93| int32_t ParseSensorRegConfig(struct SensorCfgData *config) | Parses the register group information based on the device information HCS configuration and initializes the configuration data structure.|
94| void ReleaseSensorAllRegConfig(struct SensorCfgData *config) | Releases the resources allocated to the sensor configuration data structure.|
95| int32_t GetSensorBusHandle(struct SensorBusCfg *busCfg) | Obtains the sensor bus handle information.|
96| int32_t ReleaseSensorBusHandle(struct SensorBusCfg *busCfg) | Releases the sensor bus handle information.|
97
98
99
100The sensor driver model also provides certain driver development APIs that need to be implemented by driver developers. See the table below.
101
102**Table 3** Driver development APIs that need to be implemented by driver developers
103
104| API| Description|
105| ----- | -------- |
106| int32_t init(void) | Initializes the sensor device configuration after a sensor is detected.|
107| 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.|
108| 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.|
109| 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.|
110| int32_t SetMode(int32_t mode) | Sets the data reporting mode of the current sensor device.|
111| int32_t SetOption(uint32_t option) | Sets the register configuration such as the range and accuracy based on sensor options.|
112| void ReadSensorData(void) | Reads sensor data.|
113
114
115For details about the interface implementation, see "How to Develop" below.
116
117### How to Develop
1181. Develop the acceleration sensor abstract driver. Specifically, implement the **Bind**, **Init**, **Release**, and **Dispatch** functions.
119
120   - Implement the entry function for the acceleration sensor.
121
122     ```c
123     /* Register the entry structure object of the acceleration sensor. */
124     struct HdfDriverEntry g_sensorAccelDevEntry = {
125         .moduleVersion = 1, // Version of the acceleration sensor module.
126         .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.
127         .Bind = BindAccelDriver, // Function for binding an acceleration sensor.
128         .Init = InitAccelDriver, // Function for initializing an acceleration sensor.
129         .Release = ReleaseAccelDriver, // Function for releasing acceleration sensor resources.
130     };
131
132     /* 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. */
133     HDF_INIT(g_sensorAccelDevEntry);
134     ```
135
136   - Implement interfaces for acceleration sensor driver operations.
137
138     ```c
139     /* Bind the service provided by the acceleration sensor driver to the HDF. */
140     int32_t AccelBindDriver(struct HdfDeviceObject *device)
141     {
142         CHECK_NULL_PTR_RETURN_VALUE(device, HDF_ERR_INVALID_PARAM);
143
144         struct AccelDrvData *drvData = (struct AccelDrvData *)OsalMemCalloc(sizeof(*drvData));
145         if (drvData == NULL) {
146             HDF_LOGE("%s: Malloc accel drv data fail!", __func__);
147             return HDF_ERR_MALLOC_FAIL;
148         }
149
150         drvData->ioService.Dispatch = DispatchAccel;
151         drvData->device = device;
152         device->service = &drvData->ioService;
153         g_accelDrvData = drvData;
154         return HDF_SUCCESS;
155     }
156
157     /* Register the normalization functions of the acceleration sensor driver. */
158     static int32_t InitAccelOps(struct SensorCfgData *config, struct SensorDeviceInfo *deviceInfo)
159     {
160         CHECK_NULL_PTR_RETURN_VALUE(config, HDF_ERR_INVALID_PARAM);
161
162         deviceInfo->ops.Enable = SetAccelEnable;
163         deviceInfo->ops.Disable = SetAccelDisable;
164         deviceInfo->ops.SetBatch = SetAccelBatch;
165         deviceInfo->ops.SetMode = SetAccelMode;
166         deviceInfo->ops.SetOption = SetAccelOption;
167
168         if (memcpy_s(&deviceInfo->sensorInfo, sizeof(deviceInfo->sensorInfo),
169             &config->sensorInfo, sizeof(config->sensorInfo)) != EOK) {
170             HDF_LOGE("%s: Copy sensor info failed", __func__);
171             return HDF_FAILURE;
172         }
173
174         return HDF_SUCCESS;
175     }
176     /* 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. */
177     static int32_t InitAccelAfterDetected(struct SensorCfgData *config)
178     {
179         struct SensorDeviceInfo deviceInfo;
180         CHECK_NULL_PTR_RETURN_VALUE(config, HDF_ERR_INVALID_PARAM);
181         /* Initialize the acceleration sensor function. */
182         if (InitAccelOps(config, &deviceInfo) != HDF_SUCCESS) {
183             HDF_LOGE("%s: Init accel ops failed", __func__);
184             return HDF_FAILURE;
185         }
186         /* Register the acceleration sensor with the sensor management module. */
187         if (AddSensorDevice(&deviceInfo) != HDF_SUCCESS) {
188             HDF_LOGE("%s: Add accel device failed", __func__);
189             return HDF_FAILURE;
190         }
191         /* Parse the sensor register. */
192         if (ParseSensorRegConfig(config) != HDF_SUCCESS) {
193             HDF_LOGE("%s: Parse sensor register failed", __func__);
194             (void)DeleteSensorDevice(&config->sensorInfo);
195             ReleaseSensorAllRegConfig(config);
196             return HDF_FAILURE;
197         }
198         return HDF_SUCCESS;
199     }
200     struct SensorCfgData *AccelCreateCfgData(const struct DeviceResourceNode *node)
201     {
202         ......
203         /* Continue the next detection if the sensor is not detected. */
204         if (drvData->detectFlag) {
205             HDF_LOGE("%s: Accel sensor have detected", __func__);
206             return NULL;
207         }
208         if (drvData->accelCfg == NULL) {
209             HDF_LOGE("%s: Accel accelCfg pointer NULL", __func__);
210             return NULL;
211         }
212         /* Parse the basic sensor configuration. */
213         if (GetSensorBaseConfigData(node, drvData->accelCfg) != HDF_SUCCESS) {
214             HDF_LOGE("%s: Get sensor base config failed", __func__);
215             goto BASE_CONFIG_EXIT;
216         }
217         /* Continue the next detection if the sensor is not detected. */
218         if (DetectSensorDevice(drvData->accelCfg) != HDF_SUCCESS) {
219             HDF_LOGI("%s: Accel sensor detect device no exist", __func__);
220             drvData->detectFlag = false;
221             goto BASE_CONFIG_EXIT;
222         }
223         drvData->detectFlag = true;
224         /* Parse the sensor register. */
225         if (InitAccelAfterDetected(drvData->accelCfg) != HDF_SUCCESS) {
226             HDF_LOGE("%s: Accel sensor detect device no exist", __func__);
227             goto INIT_EXIT;
228         }
229         return drvData->accelCfg;
230         ......
231     }
232     /* 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. */
233     int32_t AccelInitDriver(struct HdfDeviceObject *device)
234     {
235         ......
236         /* Initialize work queue resources. */
237         if (InitAccelData(drvData) != HDF_SUCCESS) {
238             HDF_LOGE("%s: Init accel config failed", __func__);
239             return HDF_FAILURE;
240         }
241         /* Allocate acceleration configuration resources. */
242         drvData->accelCfg = (struct SensorCfgData *)OsalMemCalloc(sizeof(*drvData->accelCfg));
243         if (drvData->accelCfg == NULL) {
244             HDF_LOGE("%s: Malloc accel config data failed", __func__);
245             return HDF_FAILURE;
246         }
247         /* Register the register group information. */
248         drvData->accelCfg->regCfgGroup = &g_regCfgGroup[0];
249         ......
250         return HDF_SUCCESS;
251     }
252     /* Release the resources allocated during driver initialization. */
253     void AccelReleaseDriver(struct HdfDeviceObject *device)
254     {
255         CHECK_NULL_PTR_RETURN(device);
256         struct AccelDrvData *drvData = (struct AccelDrvData *)device->service;
257         CHECK_NULL_PTR_RETURN(drvData);
258         /* Release the resources if the sensor is in position. */
259         if (drvData->detectFlag) {
260             AccelReleaseCfgData(drvData->accelCfg);
261         }
262         OsalMemFree(drvData->accelCfg);
263         drvData->accelCfg = NULL;
264         /* Destroy the work queue resource if the sensor is in position. */
265         HdfWorkDestroy(&drvData->accelWork);
266         HdfWorkQueueDestroy(&drvData->accelWorkQueue);
267         OsalMemFree(drvData);
268     }
269     ```
270
2712. Configure the device information about the acceleration sensor driver.
272
273   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).
274
275   ```
276   /* Device information HCS configuration of the acceleration sensor. */
277   device_sensor_accel :: device {
278       device0 :: deviceNode {
279           policy = 1; // Policy for publishing the driver service.
280           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.
281           preload = 0; // Field for specifying whether to load the driver. The value 0 means to load the driver, and 2 means the opposite.
282           permission = 0664; // Permission for the driver to create a device node.
283           moduleName = "HDF_SENSOR_ACCEL"; // Driver name. The value must be the same as that of moduleName in the driver entry structure.
284           serviceName = "sensor_accel"; // Name of the service provided by the driver. The name must be unique.
285           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.
286       }
287   }
288   ```
289
2903. Develop the internal interfaces of the acceleration sensor abstract driver. Specifically, implement the **Enable**, **Disable**, **SetBatch**, **SetMode**, **SetOption**, **AccelCreateCfgData**, **AccelReleaseCfgData**, and **AccelRegisterChipOps** functions.
291
292   ```c
293   /* Leave a function empty if it is not used. */
294   static int32_t SetAccelInfo(struct SensorBasicInfo *info)
295   {
296       (void)info;
297
298       return HDF_ERR_NOT_SUPPORT;
299   }
300   /* Deliver the configuration of enabling the register groups. */
301   static int32_t SetAccelEnable(void)
302   {
303       int32_t ret;
304       struct AccelDrvData *drvData = AccelGetDrvData();
305
306       CHECK_NULL_PTR_RETURN_VALUE(drvData, HDF_ERR_INVALID_PARAM);
307       CHECK_NULL_PTR_RETURN_VALUE(drvData->accelCfg, HDF_ERR_INVALID_PARAM);
308
309       if (drvData->enable) {
310           HDF_LOGE("%s: Accel sensor is enabled", __func__);
311           return HDF_SUCCESS;
312       }
313
314       ret = SetSensorRegCfgArray(&drvData->accelCfg->busCfg, drvData->accelCfg->regCfgGroup[SENSOR_ENABLE_GROUP]);
315       if (ret != HDF_SUCCESS) {
316           HDF_LOGE("%s: Accel sensor enable config failed", __func__);
317           return ret;
318       }
319
320       ret = OsalTimerCreate(&drvData->accelTimer, SENSOR_TIMER_MIN_TIME, AccelTimerEntry, (uintptr_t)drvData);
321       if (ret != HDF_SUCCESS) {
322           HDF_LOGE("%s: Accel create timer failed[%d]", __func__, ret);
323           return ret;
324       }
325
326       ret = OsalTimerStartLoop(&drvData->accelTimer);
327       if (ret != HDF_SUCCESS) {
328           HDF_LOGE("%s: Accel start timer failed[%d]", __func__, ret);
329           return ret;
330       }
331       drvData->enable = true;
332
333       return HDF_SUCCESS;
334   }
335   /* Deliver the configuration of disabling the register groups. */
336   static int32_t SetAccelDisable(void)
337   {
338       int32_t ret;
339       struct AccelDrvData *drvData = AccelGetDrvData();
340
341       CHECK_NULL_PTR_RETURN_VALUE(drvData, HDF_ERR_INVALID_PARAM);
342       CHECK_NULL_PTR_RETURN_VALUE(drvData->accelCfg, HDF_ERR_INVALID_PARAM);
343
344       if (!drvData->enable) {
345           HDF_LOGE("%s: Accel sensor had disable", __func__);
346           return HDF_SUCCESS;
347       }
348
349       ret = SetSensorRegCfgArray(&drvData->accelCfg->busCfg, drvData->accelCfg->regCfgGroup[SENSOR_DISABLE_GROUP]);
350       if (ret != HDF_SUCCESS) {
351           HDF_LOGE("%s: Accel sensor disable config failed", __func__);
352           return ret;
353       }
354
355       ret = OsalTimerDelete(&drvData->accelTimer);
356       if (ret != HDF_SUCCESS) {
357           HDF_LOGE("%s: Accel delete timer failed", __func__);
358           return ret;
359       }
360       drvData->enable = false;
361
362       return HDF_SUCCESS;
363   }
364   /* Set the sampling interval and data reporting interval of the sensor. */
365   static int32_t SetAccelBatch(int64_t samplingInterval, int64_t interval)
366   {
367       (void)interval;
368
369       struct AccelDrvData *drvData = NULL;
370
371       drvData = AccelGetDrvData();
372       CHECK_NULL_PTR_RETURN_VALUE(drvData, HDF_ERR_INVALID_PARAM);
373
374       drvData->interval = samplingInterval;
375
376       return HDF_SUCCESS;
377   }
378   /* Set the data reporting mode of the sensor. Currently, the real-time mode is supported. */
379   static int32_t SetAccelMode(int32_t mode)
380   {
381       return (mode == SENSOR_WORK_MODE_REALTIME) ? HDF_SUCCESS : HDF_FAILURE;
382   }
383
384   static int32_t SetAccelOption(uint32_t option)
385   {
386       (void)option;
387       return HDF_SUCCESS;
388   }
389   /* Set the sensor options. */
390   static int32_t SetAccelOption(uint32_t option)
391   {
392       (void)option;
393       return HDF_ERR_NOT_SUPPORT;
394   }
395   ```
396
3974. Develop the acceleration sensor chipset driver. Specifically, implement the **Bind**, **Init**, **Release**, and **Dispatch** functions.
398
399   ```c
400   /* Message interaction of the acceleration sensor chipset driver */
401   static int32_t DispatchBMI160(struct HdfDeviceIoClient *client,
402       int cmd, struct HdfSBuf *data, struct HdfSBuf *reply)
403   {
404       (void)client;
405       (void)cmd;
406       (void)data;
407       (void)reply;
408
409       return HDF_SUCCESS;
410   }
411   /* Bind the service provided by the acceleration sensor chipset driver to the HDF. */
412   int32_t Bmi160BindDriver(struct HdfDeviceObject *device)
413   {
414       CHECK_NULL_PTR_RETURN_VALUE(device, HDF_ERR_INVALID_PARAM);
415
416       struct Bmi160DrvData *drvData = (struct Bmi160DrvData *)OsalMemCalloc(sizeof(*drvData));
417       if (drvData == NULL) {
418           HDF_LOGE("%s: Malloc Bmi160 drv data fail", __func__);
419           return HDF_ERR_MALLOC_FAIL;
420       }
421
422       drvData->ioService.Dispatch = DispatchBMI160;
423       drvData->device = device;
424       device->service = &drvData->ioService;
425       g_bmi160DrvData = drvData;
426
427       return HDF_SUCCESS;
428   }
429   /* Initialize the acceleration sensor chipset driver. */
430   int32_t Bmi160InitDriver(struct HdfDeviceObject *device)
431   {
432       int32_t ret;
433       struct AccelOpsCall ops;
434
435       CHECK_NULL_PTR_RETURN_VALUE(device, HDF_ERR_INVALID_PARAM);
436       struct Bmi160DrvData *drvData = (struct Bmi160DrvData *)device->service;
437       CHECK_NULL_PTR_RETURN_VALUE(drvData, HDF_ERR_INVALID_PARAM);
438
439       ret = InitAccelPreConfig();
440       if (ret != HDF_SUCCESS) {
441           HDF_LOGE("%s: Init  BMI160 bus mux config", __func__);
442           return HDF_FAILURE;
443       }
444
445       drvData->sensorCfg = AccelCreateCfgData(device->property);
446       if (drvData->sensorCfg == NULL || drvData->sensorCfg->root == NULL) {
447           HDF_LOGD("%s: Creating accelcfg failed because detection failed", __func__);
448           return HDF_ERR_NOT_SUPPORT;
449       }
450
451       ops.Init = NULL;
452       ops.ReadData = ReadBmi160Data;
453       ret = AccelRegisterChipOps(&ops);
454       if (ret != HDF_SUCCESS) {
455           HDF_LOGE("%s: Register BMI160 accel failed", __func__);
456           return HDF_FAILURE;
457       }
458
459       ret = InitBmi160(drvData->sensorCfg);
460       if (ret != HDF_SUCCESS) {
461           HDF_LOGE("%s: Init BMI160 accel failed", __func__);
462           return HDF_FAILURE;
463       }
464
465       return HDF_SUCCESS;
466   }
467   /* Release the resources allocated during driver initialization. */
468   void Bmi160ReleaseDriver(struct HdfDeviceObject *device)
469   {
470   	......
471       if (drvData->sensorCfg != NULL) {
472           AccelReleaseCfgData(drvData->sensorCfg);
473           drvData->sensorCfg = NULL;
474       }
475       OsalMemFree(drvData);
476   }
477   /*HdfDriverEntry object corresponding to the acceleration sensor chipset driver */
478   struct HdfDriverEntry g_accelBmi160DevEntry = {
479       .moduleVersion = 1,
480       .moduleName = "HDF_SENSOR_ACCEL_BMI160",
481       .Bind = Bmi160BindDriver,
482       .Init = Bmi160InitDriver,
483       .Release = Bmi160ReleaseDriver,
484   };
485   HDF_INIT(g_accelBmi160DevEntry);
486   ```
487
4885. Implement the **ReadData** function of the acceleration sensor chipset driver.
489
490   ```c
491   int32_t ReadBmi160Data(struct SensorCfgData *data)
492   {
493       int32_t ret;
494       struct AccelData rawData = { 0, 0, 0 };
495       int32_t tmp[ACCEL_AXIS_NUM];
496       struct SensorReportEvent event;
497       (void)memset_s(&event, sizeof(event), 0, sizeof(event));
498       ret = ReadBmi160RawData(data, &rawData, &event.timestamp);
499       if (ret != HDF_SUCCESS) {
500           HDF_LOGE("%s: BMI160 read raw data failed", __func__);
501           return HDF_FAILURE;
502       }
503       event.sensorId = SENSOR_TAG_ACCELEROMETER;
504       event.option = 0;
505       event.mode = SENSOR_WORK_MODE_REALTIME;
506       ......
507       ret = ReportSensorEvent(&event);
508       if (ret != HDF_SUCCESS) {
509           HDF_LOGE("%s: BMI160 report data failed", __func__);
510       }
511       return ret;
512   }
513   ```
514
515>![](../public_sys-resources/icon-note.gif) **NOTE**
516>
517>- 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.
518>- You need to implement the following functions: certain sensor operation interfaces (listed in Table 3) and sensor chipset HCS configuration.
519>- You also need to verify basic driver functions.
520
521### How to Verify
522
523After 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.
524
525```
526static int32_t g_sensorDataFlag = 0; // Indicates whether to report sensor data.
527static const struct SensorInterface *g_sensorDev = nullptr; // Retain the obtained sensor interface instance address.
528
529/* Register the data reporting function. */
530static int SensorTestDataCallback(struct SensorEvents *event)
531{
532    if (event == nullptr) {
533        return -1;
534    }
535    float *data = (float*)event->data;
536    printf("time [%lld] sensor id [%d] x-[%f] y-[%f] z-[%f]\n\r", event->timestamp,
537        event->sensorId, (*data), *(data + 1), *(data + g_axisZ));
538    if (*data > 1e-5) {
539        g_sensorDataFlag = 1;
540    }
541    return 0;
542}
543/* Initialize the sensor interface instance before executing the test cases. */
544void HdfSensorTest::SetUpTestCase()
545{
546    g_sensorDev = NewSensorInterfaceInstance();
547    if (g_sensorDev == nullptr) {
548        printf("test sensorHdi get Module instance failed\n\r");
549    }
550}
551/* Release case resources. */
552void HdfSensorTest::TearDownTestCase()
553{
554    if (g_sensorDev != nullptr) {
555        FreeSensorInterfaceInstance();
556        g_sensorDev = nullptr;
557    }
558}
559/* Verify the sensor driver. */
560HWTEST_F(HdfSensorTest,TestAccelDriver_001, TestSize.Level0)
561{
562    int32_t sensorInterval = 1000000000; // Data sampling interval, in nanoseconds.
563    int32_t pollTime = 5; // Data sampling duration, in seconds.
564    int32_t accelSensorId = 1; // Acceleration sensor ID, which is 1.
565    int32_t count = 0;
566    int ret;
567    struct SensorInformation *sensorInfo = nullptr;
568
569    ret = g_sensorDev->Register(0, TraditionSensorTestDataCallback)
570    EXPECT_EQ(SENSOR_NULL_PTR, ret);
571
572    ret = g_sensorDev->GetAllSensors(&sensorInfo, &count);
573    EXPECT_EQ(0, ret);
574    if (sensorInfo == nullptr) {
575        EXPECT_NE(nullptr, sensorInfo);
576        return;
577    }
578    /* Print the obtained sensor list. */
579    for (int i = 0; i < count; i++) {
580        printf("get sensoriId[%d], info name[%s]\n\r", sensorInfo[i]->sensorId, sensorInfo[i]->sensorName);
581    }
582    ret = g_sensorDev->Enable(accelSensorId);
583    EXPECT_EQ(0, ret);
584    g_sensorDataFlag = 0;
585
586    ret = g_sensorDev->SetBatch(accelSensorId, sensorInterval, pollTime);
587    EXPECT_EQ(0, ret);
588    /* Observe the printed data within the period specified by pollTime. */
589    OsalSleep(pollTime);
590    EXPECT_EQ(1, g_sensorDataFlag);
591
592    ret = g_sensorDev->Disable(accelSensorId);
593    g_sensorDataFlag = 0;
594    EXPECT_EQ(0, ret);
595
596    ret = g_sensorDev->Unregister(0, TraditionSensorTestDataCallback);
597    EXPECT_EQ(0, ret);
598}
599```
600