The sensor driver module provides APIs for upper-layer sensor services to implement basic sensor capabilities, including querying the sensor list, enabling or disabling a sensor, subscribing to or unsubscribing from sensor data, and setting sensor options. The sensor driver model is developed based on the Hardware Driver Foundation \(HDF\) and supports functions such as cross-OS migration and differentiated device configuration. The following figure shows the architecture of the sensor driver model.
**Figure 1** Architecture of the sensor driver model<aname="fig10451455446"></a>
The sensor driver model offers the following APIs:
- Hardware Driver Interfaces \(HDIs\) for sensors: These HDIs facilitate service development.
- APIs for implementing sensor driver model capabilities: These APIs implement the capabilities of registering, loading, and unregistering sensor drivers as well as detecting sensor devices depending on the HDF. The APIs include normalized APIs for sensor devices of the same type, APIs for parsing register configurations, abstract APIs for bus access, and abstract platform APIs.
- APIs to be implemented by developers: Based on the HDF Configuration Source \(HCS\), developers can implement differentiated configuration for sensors of the same type and serialized configuration of sensor device parameters. Some sensor device operations can be abstracted as APIs to simplify sensor driver development.
## Available APIs<a name="section20930112117478"></a>
The following table lists the APIs provided by the sensor driver model.
**Table 1** External APIs provided by the sensor driver model
<tdclass="cellrowborder"valign="top"width="46.339999999999996%"headers="mcps1.2.4.1.3 "><pid="p199227318499"><aname="p199227318499"></a><aname="p199227318499"></a>Obtains information about all sensors in the system. The information about a sensor generally includes the sensor name, sensor vendor, firmware version, hardware version, sensor type ID, sensor ID, maximum measurement range, accuracy, and power.</p>
<tdclass="cellrowborder"valign="top"width="46.339999999999996%"headers="mcps1.2.4.1.3 "><pid="p5922331114916"><aname="p5922331114916"></a><aname="p5922331114916"></a>Enables the sensor that has been subscribed to. The subscriber can obtain the sensor data only after the sensor is enabled.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p139231531184912"><aname="p139231531184912"></a><aname="p139231531184912"></a>Disables a sensor.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p14924203134910"><aname="p14924203134910"></a><aname="p14924203134910"></a>Sets the data sampling interval and data reporting interval for the specified sensor.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p107051159281"><aname="p107051159281"></a><aname="p107051159281"></a>Sets the data reporting mode for the specified sensor.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p5926031124914"><aname="p5926031124914"></a><aname="p5926031124914"></a>Sets options for the specified sensor, including its measurement range and accuracy.</p>
</td>
</tr>
<trid="row939914814478"><tdclass="cellrowborder"rowspan="2"valign="top"width="8.260000000000002%"headers="mcps1.2.4.1.1 "><pid="p1039815743211"><aname="p1039815743211"></a><aname="p1039815743211"></a>Data subscription and unsubscription</p>
<tdclass="cellrowborder"valign="top"width="46.339999999999996%"headers="mcps1.2.4.1.3 "><pid="p892633118493"><aname="p892633118493"></a><aname="p892633118493"></a>Registers the callback for reporting sensor data to the subscriber.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p5817133119"><aname="p5817133119"></a><aname="p5817133119"></a>Unregisters the callback for reporting sensor data.</p>
<tdclass="cellrowborder"valign="top"width="46.339999999999996%"headers="mcps1.2.4.1.3 "><pid="p19679181612563"><aname="p19679181612563"></a><aname="p19679181612563"></a>Creates a <strongid="b10138658185717"><aname="b10138658185717"></a><aname="b10138658185717"></a>SensorInterface</strong> instance.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p18680916165620"><aname="p18680916165620"></a><aname="p18680916165620"></a>Releases the <strongid="b4150124205810"><aname="b4150124205810"></a><aname="b4150124205810"></a>SensorInterface</strong> instance.</p>
</td>
</tr>
</tbody>
</table>
The following table lists the APIs provided by the sensor driver model for driver developers. You can directly call these APIs without any implementations.
**Table 2** APIs provided by the sensor driver model for driver developers
<tdclass="cellrowborder"valign="top"width="45.91459145914592%"headers="mcps1.2.4.1.3 "><pid="p356935816328"><aname="p356935816328"></a><aname="p356935816328"></a>Adds a sensor of the current type to the sensor management module.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p2569145833214"><aname="p2569145833214"></a><aname="p2569145833214"></a>Deletes a specified sensor from the sensor management module.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p15691858193220"><aname="p15691858193220"></a><aname="p15691858193220"></a>Reports data of a specified sensor type.</p>
</td>
</tr>
<trid="row17569145814329"><tdclass="cellrowborder"rowspan="4"valign="top"width="8.550855085508552%"headers="mcps1.2.4.1.1 "><pid="p10589113932619"><aname="p10589113932619"></a><aname="p10589113932619"></a>Abstract bus and platform operations</p>
<tdclass="cellrowborder"valign="top"width="45.91459145914592%"headers="mcps1.2.4.1.3 "><pid="p1657018586322"><aname="p1657018586322"></a><aname="p1657018586322"></a>Reads sensor configuration data from the sensor register based on the bus configuration.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p6872112112201"><aname="p6872112112201"></a><aname="p6872112112201"></a>Writes sensor configuration data to the sensor register based on the bus configuration.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p10676112612013"><aname="p10676112612013"></a><aname="p10676112612013"></a>Creates a scheduled thread for a specified sensor to process sensor data reporting.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p69406415243"><aname="p69406415243"></a><aname="p69406415243"></a>Destroys the scheduled thread created for the sensor.</p>
<tdclass="cellrowborder"valign="top"width="45.91459145914592%"headers="mcps1.2.4.1.3 "><pid="p49409417249"><aname="p49409417249"></a><aname="p49409417249"></a>Sets the sensor register group configuration based on the sensor bus type.</p>
<tdclass="cellrowborder"valign="top"width="45.91459145914592%"headers="mcps1.2.4.1.3 "><pid="p79411640248"><aname="p79411640248"></a><aname="p79411640248"></a>Obtains basic configuration information such as sensor, bus, and attribute configurations based on the HCS resource configuration of the sensor device, and initializes the basic configuration data structure.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p171885685120"><aname="p171885685120"></a><aname="p171885685120"></a>Parses the register group information based on the HCS resource configuration of the sensor device and initializes the configuration data structure.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p17941154152419"><aname="p17941154152419"></a><aname="p17941154152419"></a>Releases the resources allocated to the sensor configuration data structure.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p953821245219"><aname="p953821245219"></a><aname="p953821245219"></a>Obtains the sensor bus handle information.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p1878422485212"><aname="p1878422485212"></a><aname="p1878422485212"></a>Releases the sensor bus handle information.</p>
</td>
</tr>
</tbody>
</table>
The following table lists the APIs that need to be implemented by driver developers.
**Table 3** APIs that need to be implemented by driver developers
<tdclass="cellrowborder"valign="top"width="45.81458145814582%"headers="mcps1.2.4.1.3 "><pid="p1480465165710"><aname="p1480465165710"></a><aname="p1480465165710"></a>Initializes the configuration of a sensor device after it is detected.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p4831139153316"><aname="p4831139153316"></a><aname="p4831139153316"></a>Obtains the basic information about the current sensor device from the HCS of sensor devices.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p68310953312"><aname="p68310953312"></a><aname="p68310953312"></a>Enables the current sensor device by delivering the register configuration in the operation group based on the HCS of the current sensor device.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p138314912336"><aname="p138314912336"></a><aname="p138314912336"></a>Disables the current sensor device by delivering the register configuration in the operation group based on the HCS of the current sensor device.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p08311903315"><aname="p08311903315"></a><aname="p08311903315"></a>Sets the processing time of the data reporting thread for the current sensor device based on the data sampling interval and data reporting interval.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p356524224213"><aname="p356524224213"></a><aname="p356524224213"></a>Sets the data reporting mode of the current sensor device.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p4565104214213"><aname="p4565104214213"></a><aname="p4565104214213"></a>Sets the register configuration such as the measurement range and accuracy based on sensor options.</p>
For details about the API implementation, see [Development Example](#section257750691).
## How to Develop<a name="section1140943382"></a>
Regardless of the OS and system on a chip \(SoC\), the sensor driver is developed based on the HDF, platform, and OSAL APIs to provide a unified driver model for sensor devices. This section uses the acceleration sensor as an example to describe how to develop a sensor driver.
1. Register the acceleration sensor driver. The HDF provides a unified driver management model. The HDF identifies and loads the target module driver based on the configuration of the acceleration sensor module.
2. Initialize and deinitialize the acceleration sensor driver. Using the **init** function, the HDF starts loading the sensor device driver and allocating configuration resources for sensor device data, respectively. Using the **release** function, the HDF releases the resources and configurations loaded by the driver.
3. Parse the configurations of the acceleration sensor register group. For different types of sensors, you must configure their respective HCS configuration files in the HCS, check whether the sensor device is in position during the device driver startup, and then load the corresponding configuration file to generate the configuration structure object.
4. Implement APIs for acceleration sensor driver operations. The driver APIs for various types of sensors, such as **init**, **GetInfo**, **Enable**, **Disable**, **SetBatch**, **SetMode**, **SetOption**, and **ReadSensorData**, are normalized to deliver sensor driver configurations and report sensor data.
>The sensor driver model provides a collection of APIs to implement sensor driver capabilities, including the driver device management, abstract bus and platform operation, general configuration, and configuration parsing capabilities. For details about the APIs, see [Table 2](#table1156812588320). You need to implement the following APIs: some operations to perform on sensors \([Table 3](#table1083014911336)\), differentiated data configuration of the sensor HCS, and verification of basic driver functions.
## Development Example<a name="section257750691"></a>
This section uses a code example to demonstrate how to load and start the acceleration sensor driver based on the HDF driver model. For details about the mechanism, see [Driver Development](driver-hdf-development.md). This example uses the Bosch BMI160 acceleration sensor that communicates over I2C.
1. Register the driver entry of the acceleration sensor.
- Implementation of the entry function
```
/* 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, /* Binding function of the acceleration sensor */
.Init = InitAccelDriver, /* Initialization function of the acceleration sensor */
.Release = ReleaseAccelDriver, /* Resource release function of the acceleration sensor */
};
/* 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.
HDF_INIT(g_sensorAccelDevEntry);
```
- Acceleration sensor configuration
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).
```
/* HCS configuration of the acceleration sensor device */
device_sensor_accel :: device {
device0 :: deviceNode {
policy = 1; /* Policy for providing the driver service */
priority = 105; /* 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 = 2; /* 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 device nodes */
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. */
}
}
```
1. Initialize and deinitialize the acceleration sensor driver.
- Initialization entry function **init**
```
/* Bind the service provided by the acceleration sensor driver to the HDF. */
/* The entry function of the acceleration sensor driver is used to initialize the structure object of the sensor private data, allocate space for the HCS data configuration object of the sensor, invoke the entry function for initializing the sensor HCS data configuration, detect whether the sensor device is in position, create the sensor data reporting timer, implement the sensor normalization API, and register the sensor device. */
/* Obtain the private data structure object of the sensor. */
struct AccelDrvData *drvData = AccelGetDrvData();
/* When detecting sensors of the same type from different vendors, the function checks whether this type of sensors is in position. If yes, it no longer detects the other sensors of this type and directly returns the result. */
if (drvData->detectFlag) {
HDF_LOGE("%s: accel sensor have detected", __func__);
/* Allocate space for the private data structure objects for storing sensor data configurations. The allocated space needs to be released when the driver is released. */
/* Initializing the sensor configuration data aims to parse the configuration information of the sensor communication bus, basic sensor information, sensor attributes, whether the sensor is in position, and register group information. */
if (GetSensorBaseConfigData(device->property, drvData->accelCfg) != HDF_SUCCESS) {
HDF_LOGE("%s: get sensor base config failed", __func__);
goto Base_CONFIG_EXIT;
}
if (DetectAccelChip() != HDF_SUCCESS) {
HDF_LOGE("%s: accel sensor detect device no exist", __func__);
goto DETECT_CHIP_EXIT;
}
drvData->detectFlag = true;
if (ParseSensorRegConfig(drvData->accelCfg) != HDF_SUCCESS) {
1. Configure the acceleration sensor register group.
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.
You only need to configure the acceleration sensor data according to the template. Template configuration parsing has been implemented via the **InitSensorConfigData** function and only needs to be called during initialization. If new configuration items are added, you need to modify this function accordingly.
Acceleration sensor data configuration template (accel_config.hcs)
root {
sensorAccelConfig {
accelChipConfig {
/* Sensor information template */
template sensorInfo {
sensorName = "accelerometer"; /* Acceleration sensor name. The value contains a maximum of 16 bytes. */
vendorName = "borsh_bmi160"; /* Sensor vendor name. The value contains a maximum of 16 bytes. */
firmwareVersion = "1.0"; /* Sensor firmware version. The default value is 1.0. The value contains a maximum of 16 bytes. */
hardwareVersion = "1.0"; /* Sensor hardware version. The default value is 1.0. The value contains a maximum of 16 bytes. */
sensorTypeId = 1; /* Sensor type ID. For details, see SensorTypeTag. */
sensorId = 1; /* Sensor ID, which is defined by the sensor driver developer. The SensorTypeTag enums are recommended. */
maxRange = 8; /* Maximum measurement range of the sensor. Set this parameter based on your business requirements. */
precision = 0; /* Sensor accuracy, which is used together with sensor data reporting. For details, see SensorEvents. */
power = 230; /* Power consumption of the sensor */
}
/* Template of the bus type and configuration information used by the sensor */
template sensorBusConfig {
busType = 0; /* 0:i2c 1:spi */
busNum = 6; /* Device ID allocated to the sensor on the chip */
busAddr = 0; /* Address allocated to the sensor on the chip */
regWidth = 1; /* Width of the sensor register address */
regBigEndian = 0; /* Endian mode of the sensor register */
}
/* Sensor attribute template */
template sensorAttr {
chipName = ""; /* Sensor chip name */
chipIdRegister = 0xf; /* Address of the register detecting whether the sensor is in position */
chipIdValue = 0xd1; /* Value of the register detecting whether the sensor is in position */
}
}
}
}
### Basic Concepts
/* You can modify the template configuration based on the differences of sensor devices. If no modification is made, the default template configuration is used. */
root {
sensorAccelConfig {
accel_bmi160_chip_config : accelChipConfig {
match_attr = "hdf_sensor_accel_driver"; /* The value must be the same as the match_attr field configured for the acceleration sensor. */
accelInfo :: sensorInfo {
vendorName = "borsh_bmi160";
sensorTypeId = 1;
sensorId = 1;
}
accelBusConfig :: sensorBusConfig {
busType = 0; /* I2C communication mode */
busNum = 6;
busAddr = 0x68;
regWidth = 1; /* 1-byte bit width */
}
accelAttr :: sensorAttr {
chipName = "bmi160";
chipIdRegister = 0x00;
chipIdValue = 0xd1;
}
accelRegConfig {
/* regAddr: Register address
value: Register value
mask: Mask of the register value
len: Length (in bytes) of the register value
delay: Register delay (in milliseconds)
opsType: Operation type. The options can be 0 (no operation), 1 (read), 2 (write), 3 (read and check), and 4 (bit update).
calType: Calculation type. The options can be 0 (none), 1 (write), 2 (negate), 3 (XOR) 4, (left shift), and 5 (right shift).
shiftNum: Number of shifts
debug: Debugging switch. The value can be 0 (disabled) or 1 (enabled).
save: Data saving switch. The value can be 0 (not save data) or 1 (save data).
*/
/* Groups of sensor register operations. Registers can be configured in sequence based on the groups. */
/* Register address, register value, mask of the register value, data length of the register value, register delay, operation type, calculation type, number of shifts, debugging switch, data saving switch */
/* Initialize the register groups. */
initSeqConfig = [
0x7e, 0xb6, 0xff, 1, 5, 2, 0, 0, 0, 0,
0x7e, 0x10, 0xff, 1, 5, 2, 0, 0, 0, 0
];
/* Enable the register groups. */
enableSeqConfig = [
0x7e, 0x11, 0xff, 1, 5, 2, 0, 0, 0, 0,
0x41, 0x03, 0xff, 1, 0, 2, 0, 0, 0, 0,
0x40, 0x08, 0xff, 1, 0, 2, 0, 0, 0, 0
];
/* Disable the register groups. */
disableSeqConfig = [
0x7e, 0x10, 0xff, 1, 5, 2, 0, 0, 0, 0
];
}
}
}
}
```
Currently, sensors are classified into medical sensors and traditional sensors by sensor ID.
1. Implement APIs for acceleration sensor driver operations.
- The IDs of medical sensors range from 128 to 160.
You need to implement normalized APIs based on sensor types.
- The IDs of traditional sensors are out of the range of 128 to 160.
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.
drvData->threadStatus = SENSOR_THREAD_RUNNING;
**Figure 2** How sensor driver works
return HDF_SUCCESS;
}
/* Deliver the configuration of disabling the register groups. */
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.
ret = SetSensorRegCfgArray(&drvData->accelCfg->busCfg, drvData->accelCfg->regCfgGroup[SENSOR_DISABLE_GROUP]);
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.
drvData->threadStatus = SENSOR_THREAD_STOPPED;
## Development Guidelines
return HDF_SUCCESS;
}
/* Set the sampling interval and data reporting interval of the sensor. */
- 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.
return HDF_SUCCESS;
}
/* Set the data reporting mode of the sensor. Currently, the real-time mode is supported. */
/* Sensitivity conversion value of the sensor with a 2g measurement range */
#define BMI160_ACC_SENSITIVITY_2G 61
/* Address of the sensor data sampling register */
#define BMI160_ACCEL_X_LSB_ADDR 0X12
#define BMI160_ACCEL_X_MSB_ADDR 0X13
#define BMI160_ACCEL_Y_LSB_ADDR 0X14
#define BMI160_ACCEL_Y_MSB_ADDR 0X15
#define BMI160_ACCEL_Z_LSB_ADDR 0X16
#define BMI160_ACCEL_Z_MSB_ADDR 0X17
/* Data dimension of the sensor */
enum AccelAxisNum {
ACCEL_X_AXIS = 0,
ACCEL_Y_AXIS = 1,
ACCEL_Z_AXIS = 2,
ACCEL_AXIS_NUM = 3,
};
/* Each dimension of the sensor */
struct AccelData {
int32_t x;
int32_t y;
int32_t z;
};
/* Private data structure of the sensor */
struct AccelDrvData {
bool detectFlag;
uint8_t threadStatus;
uint8_t initStatus;
int64_t interval;
struct SensorCfgData *accelCfg;
struct OsalThread thread;
struct AccelOpsCall ops;
};
/* Differentiation adaptation function */
struct AccelOpsCall {
int32_t (*Init)(struct SensorCfgData *data);
int32_t (*ReadData)(struct SensorCfgData *data);
};
```
## Test Guidelines<a name="section106021256121219"></a>
The sensor driver model offers the following APIs:
After the driver is developed, you can develop self-test cases in the sensor unit test to verify the basic functions of the driver. The developer self-test platform is used as the test environment.
- 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. */
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. */
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. */
/* 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.
>- 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.
```
/* Specify whether to report sensor data. */
static int32_t g_sensorDataFlag = 0;
/* Retain the address of the sensor interface instance. */
Developed on the Hardware Driver Foundation (HDF), the vibrator driver model makes vibrator driver development easier. This model masks the interaction between the device driver and system, provides unified and stable driver interfaces for the hardware service layer, and offers open interfaces and interface parsing capabilities for driver developers. This document provides guidance for developing vibrator drivers and deploying vibrators in different OSs. The figure below shows the vibrator driver model.
The system controls device vibration by invoking the vibrator. There are two vibration modes:
- One-shot vibration
The vibrator vibrates for a specified duration.
- Periodic vibration
The vibrator vibrates with a preset effect. For example, if the preset effect is "haptic.clock.timer" = [600, 600, 200, 600], the vibrator waits for 600 ms, vibrates for 600 ms, waits for 200 ms, and vibrates for 600 ms.
### Working Principles
Based on the loading and running process (shown below) of the vibrator driver model, the relationships between key modules in the model and associated modules are clearly defined.
The following uses the vibrator driver on the Hi3516D V300 development board of the standard system as an example to describe the driver loading and running process.
1. The vibrator host reads the vibrator management configuration from the Vibrator Host node of the device_info HCS (vibrator device information HCS).
2. The vibrator host parses the vibrator management configuration and associates it with the corresponding vibrator abstract driver.
3. The vibrator host reads the vibrator data configuration from the linear_vibrator_config HCS (vibrator private configuration HCS).
4. The vibrator host parses the vibrator data configuration and associates it with the corresponding vibrator haptic driver.
5. The vibrator proxy delivers an instruction to the vibrator stub.
6. The vibrator stub calls the vibrator controller.
7. The vibrator host initializes the vibrator abstract driver interfaces.
8. The vibrator haptic driver starts a thread to parse the vibrator haptic module.
9. The vibrator haptic driver calls the **Start** interface in the vibrator abstract driver.
10. The vibrator abstract driver calls the **Start** interface in the vibrator chipset driver.
## Development Guidelines
### When to Use
You can set different vibration effects as needed, for example, customizing vibration effects with different intensities and durations for buttons on the device, and customizing one-shot or periodic vibration effects with different intensities and durations for alarm clocks and incoming calls.
### Available APIs
The vibrator driver model supports static HDF Configuration Source (HCS) configurations and dynamic parameter configurations. The vibrator hardware service calls the **StartOnce** interface to trigger continuous vibration and calls the **Start** interface to trigger vibration with a specified effect. The table below lists the APIs provided by the vibrator driver model for the hardware service layer.
**Table 1** External APIs of the vibrator driver model
The vibrator driver model provides stable interfaces for the upper-layer hardware service to trigger a one-shot vibration with a given duration, trigger vibration with a given effect, and stop vibration. The model implements functionalities such as cross-OS migration and differentiated configurations. To develop a vibrator, perform the following steps:
1. Develop the vibrator abstract driver based on the driver entry. Specifically, implement the **Bind**, **Init**, **Release**, and **Dispatch** functions, configure resources, and parse HCS configurations.
- Call **HDF_INIT** to register the driver entry with the HDF. During driver loading, the HDF calls the **Bind** function and then the **Init** function to load the driver. If the **Init** function fails to be called, the HDF calls **Release** to release the driver resources and exit the vibrator driver model. The vibrator driver model uses the HCS as the configuration source code. For details about HCS fields, see [Driver Configuration Management](https://gitee.com/openharmony/docs/blob/master/en/device-dev/driver/driver-hdf-manage.md). The driver entry function is defined as follows:
```c
/* Register the entry structure object of the vibrator abstract driver. */
struct HdfDriverEntry g_vibratorDriverEntry = {
.moduleVersion = 1, // Version of the vibrator module.
.moduleName = "HDF_VIBRATOR", // Vibrator module name. The value must be the same as the value of moduleName in the device_info.hcs file.
.Bind = BindVibratorDriver, // Function for binding a vibrator.
.Init = InitVibratorDriver, // Function for initializing a vibrator.
.Release = ReleaseVibratorDriver, // Function for releasing vibrator resources.
};
HDF_INIT(g_vibratorDriverEntry);
```
- Develop the vibrator abstract driver. Specifically, implement the **Bind**, **Init**, **Release**, and **Dispatch** functions.
```c
/* External service published by the vibrator driver. */
- During system startup, the HDF configuration management loads the vibrator abstract driver based on the device information HCS and publishes the vibrator driver interfaces.
```c
/* Device information HCS. */
vibrator :: host {
hostName = "vibrator_host";
device_vibrator :: device {
device0 :: deviceNode {
policy = 2; // Policy for publishing the driver service.
priority = 100; // 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_VIBRATOR"; // Driver name. The value must be the same as that of moduleName in the driver entry structure.
serviceName = "hdf_misc_vibrator"; // Name of the service provided by the driver. The name must be unique.
deviceMatchAttr = "hdf_vibrator_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.
}
}
```
2. Create a vibrator haptic model and parse the haptic HCS configuration.
- Create a vibrator haptic model.
```hcs
/* Create a vibrator haptic model, allocate resources, and parse the haptic HCS configuration. */
- The vibrator effect model uses the HCS. For details about HCS fields, see [Driver Configuration Management](https://gitee.com/openharmony/docs/blob/master/en/device-dev/driver/driver-hdf-manage.md).
```
/* Vibrator data configuration template (vibrator_config.hcs). */
root {
vibratorConfig {
boardConfig {
match_attr = "hdf_vibrator_driver"; // The value must be the same as that of the match_attr field configured for the vibrator.
vibratorAttr {
/* The value 0 means a rotor vibrator, and 1 means a linear vibrator. */
deviceType = 1; // Device type.
supportPreset = 1; // Supported preset type.
}
vibratorHapticConfig {
haptic_clock_timer {
effectName = "haptic.clock.timer";
type = 1; // The value 0 means the built-in mode, and 1 means the time sequence.
seq = [600, 600, 200, 600]; // Time sequence.
}
haptic_default_effect {
effectName = "haptic.default.effect";
type = 0;
seq = [0, 3, 800, 1];
}
}
}
}
}
```
3. Develop the interfaces for starting and stopping vibration. A timer will be created and destroyed based on the vibration effect.
The vibrator hardware service calls **StartOnce** to start one-shot vibration with a given duration and calls **StartEffect** to start vibration with a specified effect.