diff --git a/en/device-dev/driver/driver-peripherals-sensor-des.md b/en/device-dev/driver/driver-peripherals-sensor-des.md index 4b54238b70d642fbc49825ef2324d9bc31644def..4f7eef84c1b304ae3208ff8e752b88f84256f3ab 100644 --- a/en/device-dev/driver/driver-peripherals-sensor-des.md +++ b/en/device-dev/driver/driver-peripherals-sensor-des.md @@ -1,848 +1,530 @@ -# Sensor - -## Overview - -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 -![](figures/architecture-of-the-sensor-driver-model.png "architecture-of-the-sensor-driver-model") - -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 - -The following table lists the APIs provided by the sensor driver model. - -**Table 1** External APIs provided by the sensor driver model - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Category

-

API

-

Description

-

Query

-

int32_t GetAllSensors(struct SensorInformation **sensorInfo, int32_t *count)

-

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.

-

Setting

-

int32_t Enable(int32_t sensorId)

-

Enables the sensor that has been subscribed to. The subscriber can obtain the 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 data sampling interval and data reporting interval for the specified sensor.

-

int32_t SetMode(int32_t sensorTypeId, SensorUser *user, int32_t mode)

-

Sets the data reporting mode for the specified sensor.

-

int32_t SetOption(int32_t sensorId, uint32_t option)

-

Sets options for the specified sensor, including its measurement range and accuracy.

-

Data subscription and unsubscription

-

int32_t Register(RecordDataCallback cb)

-

Registers the callback for reporting sensor data to the subscriber.

-

int32_t Unregister(void)

-

Unregisters the callback for reporting sensor data.

-

Instance creation

-

const struct SensorInterface *NewSensorInterfaceInstance(void)

-

Creates a SensorInterface instance.

-

int32_t FreeSensorInterfaceInstance(void)

-

Releases the SensorInterface instance.

-
- -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 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Category

-

API

-

Description

-

Device management

-

int32_t AddSensorDevice(const struct SensorDeviceInfo *deviceInfo)

-

Adds a sensor of the current type to the sensor management module.

-

int32_t DeleteSensorDevice(int32_t sensorId)

-

Deletes a specified sensor from the sensor management module.

-

int32_t ReportSensorEvent(const struct SensorReportEvent *events)

-

Reports data of a specified sensor type.

-

Abstract bus and platform operations

-

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 CreateSensorThread(struct OsalThread *thread, OsalThreadEntry threadEntry, char *name, void *entryPara)

-

Creates a scheduled thread for a specified sensor to process sensor data reporting.

-

void DestroySensorThread(struct OsalThread *thread, uint8_t *status);

-

Destroys the scheduled thread created for the sensor.

-

Common configuration

-

int32_t SetSensorRegCfgArray(struct SensorBusCfg *busCfg, const struct SensorRegCfgGroupNode *group);

-

Sets the sensor register group configuration based on the sensor bus type.

-

Configuration parsing

-

-

int32_t GetSensorBaseConfigData(const struct DeviceResourceNode *node, struct SensorCfgData *config)

-

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.

-

int32_t ParseSensorRegConfig(struct SensorCfgData *config)

-

Parses the register group information based on the HCS resource configuration of the sensor device 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 following table lists the APIs that need to be implemented by driver developers. - -**Table 3** APIs that need to be implemented by driver developers - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Category

-

API

-

Description

-

Basic functions

-

int32_t init(void)

-

Initializes the configuration of a sensor device after it is detected.

-

int32_t GetInfo(struct SensorBasicInfo *info)

-

Obtains the basic information about the current sensor device from the HCS of sensor devices.

-

int32_t Enable(void)

-

Enables the current sensor device by delivering the register configuration in the operation group based on the HCS of the current sensor device.

-

int32_t Disable(void)

-

Disables the current sensor device by delivering the register configuration in the operation group based on the HCS of the current sensor device.

-

int32_t SetBatch(int64_t samplingInterval, int64_t reportInterval)

-

Sets the processing time of the data reporting thread for the current sensor device based on the data 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 measurement range and accuracy based on sensor options.

-

void ReadSensorData(void)

-

Reads sensor data.

-
- -For details about the API implementation, see [Development Example](#section257750691). - -## How to Develop - -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. - ->![](../public_sys-resources/icon-note.gif) **NOTE:** ->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 - -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. */ -int32_t BindAccelDriver(struct HdfDeviceObject *device) -{ - CHECK_NULL_PTR_RETURN_VALUE(device, HDF_ERR_INVALID_PARAM); - - static struct IDeviceIoService service = { - .object = {0}, - .Dispatch = DispatchAccel, - }; - device->service = &service; - - return HDF_SUCCESS; -} -/* After detecting that the device is in position, call RegisterAccelChipOps to register the differentiation adaptation function. */ -int32_t RegisterAccelChipOps(struct AccelOpsCall *ops) -{ - struct AccelDrvData *drvData = NULL; - - CHECK_NULL_PTR_RETURN_VALUE(ops, HDF_ERR_INVALID_PARAM); - - drvData = AccelGetDrvData(); - drvData->ops.Init = ops->Init; - drvData->ops.ReadData = ops->ReadData; - return HDF_SUCCESS; -} -/* Hook the acceleration sensor driver normalization function. */ -static int32_t InitAccelOps(struct SensorDeviceInfo *deviceInfo) -{ - struct AccelDrvData *drvData = AccelGetDrvData(); - - (void)memset_s((void *)deviceInfo, sizeof(*deviceInfo), 0, sizeof(*deviceInfo)); - deviceInfo->ops.GetInfo = SetAccelInfo; - 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), - &drvData->accelCfg->sensorInfo, sizeof(drvData->accelCfg->sensorInfo)) != EOK) { - HDF_LOGE("%s: copy sensor info failed", __func__); - return HDF_FAILURE; - } - /* The sensor type ID can be configured in the HCS configuration file or here. */ - drvData->accelCfg->sensorInfo.sensorTypeId = SENSOR_TAG_ACCELEROMETER; - drvData->accelCfg->sensorInfo.sensorId = SENSOR_TAG_ACCELEROMETER; - - return HDF_SUCCESS; -} -/* Initialize the sensor register. */ -static int32_t InitAccelAfterConfig(void) -{ - struct SensorDeviceInfo deviceInfo; - - if (InitAccelConfig() != HDF_SUCCESS) { - HDF_LOGE("%s: init accel config failed", __func__); - return HDF_FAILURE; - } - - if (InitAccelOps(&deviceInfo) != HDF_SUCCESS) { - HDF_LOGE("%s: init accel ops failed", __func__); - return HDF_FAILURE; - } - - if (AddSensorDevice(&deviceInfo) != HDF_SUCCESS) { - HDF_LOGE("%s: add accel device failed", __func__); - return HDF_FAILURE; - } - - return HDF_SUCCESS; -} -/* Call the device detection function to hook the differentiated device function. */ -static int32_t DetectAccelChip(void) -{ - int32_t num; - int32_t ret; - int32_t loop; - struct AccelDrvData *drvData = AccelGetDrvData(); - CHECK_NULL_PTR_RETURN_VALUE(drvData->accelCfg, HDF_ERR_INVALID_PARAM); - - num = sizeof(g_accelDetectIfList) / sizeof(g_accelDetectIfList[0]); - for (loop = 0; loop < num; ++loop) { - if (g_accelDetectIfList[loop].DetectChip != NULL) { - ret = g_accelDetectIfList[loop].DetectChip(drvData->accelCfg); - if (ret == HDF_SUCCESS) { - drvData->detectFlag = true; - break; - } - } - } - - if (loop == num) { - HDF_LOGE("%s: detect accel device failed", __func__); - drvData->detectFlag = false; - return HDF_FAILURE; - } - return HDF_SUCCESS; -} -/* 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. */ -int32_t InitAccelDriver(struct HdfDeviceObject *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__); - return HDF_SUCCESS; - } - - CHECK_NULL_PTR_RETURN_VALUE(device, HDF_ERR_INVALID_PARAM); - /* 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. */ - drvData->accelCfg = (struct SensorCfgData *)OsalMemCalloc(sizeof(*cfg)); - if (drvData->accelCfg == NULL) { - HDF_LOGE("%s: malloc sensor config data failed", __func__); - return HDF_FAILURE; - } +# Sensor - drvData->accelCfg->regCfgGroup = &g_regCfgGroup[0]; - /* 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) { - HDF_LOGE("%s: detect sensor device failed", __func__); - goto REG_CONFIG_EXIT; - } - - if (InitAccelAfterConfig() != HDF_SUCCESS) { - HDF_LOGE("%s: init accel after config failed", __func__); - goto INIT_EXIT; - } - HDF_LOGI("%s: init accel driver success", __func__); - return HDF_SUCCESS; - -INIT_EXIT: - DestroySensorThread(&drvData->thread, &drvData->threadStatus); - (void)DeleteSensorDevice(SENSOR_TAG_ACCELEROMETER); -REG_CONFIG_EXIT: - ReleaseSensorAllRegConfig(drvData->accelCfg); - (void)ReleaseSensorBusHandle(&drvData->accelCfg->busCfg); -DETECT_CHIP_EXIT: - drvData->detectFlag = false; -BASE_CONFIG_EXIT: - drvData->accelCfg->root = NULL; - drvData->accelCfg->regCfgGroup = NULL; - OsalMemFree(drvData->accelCfg); - drvData->accelCfg = NULL; - return HDF_FAILURE; -} +## Overview -/* Release the resources allocated during driver initialization. */ -void ReleaseAccelDriver(struct HdfDeviceObject *device) -{ - (void)device; - struct AccelDrvData *drvData = NULL; - - drvData = AccelGetDrvData(); - (void)DestroySensorThread(&drvData->thread, &drvData->threadStatus); - (void)DeleteSensorDevice(SENSOR_TAG_ACCELEROMETER); - drvData->detectFlag = false; - - if (drvData->accelCfg != NULL) { - drvData->accelCfg->root = NULL; - drvData->accelCfg->regCfgGroup = NULL; - ReleaseSensorAllRegConfig(drvData->accelCfg); - (void)ReleaseSensorBusHandle(&drvData->accelCfg->busCfg); - OsalMemFree(drvData->accelCfg); - drvData->accelCfg = NULL; - } +### Introduction - drvData->initStatus = false; -} -``` - -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. +**Figure 1** Sensor driver model +![Sensor driver model](figures/sensor_driver_model.png) -``` -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. -``` -/* Leave a function empty if it is not used. */ -static int32_t SetAccelInfo(struct SensorBasicInfo *info) -{ - (void)info; +### Working Principles - 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->accelCfg, HDF_ERR_INVALID_PARAM); - ret = SetSensorRegCfgArray(&drvData->accelCfg->busCfg, drvData->accelCfg->regCfgGroup[SENSOR_ENABLE_GROUP]); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: accel sensor disable config failed", __func__); - return HDF_FAILURE; - } +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. */ -static int32_t SetAccelDisable(void) -{ - int32_t ret; - struct AccelDrvData *drvData = AccelGetDrvData(); +![How sensor driver works](figures/sensor_working.png) - CHECK_NULL_PTR_RETURN_VALUE(drvData->accelCfg, HDF_ERR_INVALID_PARAM); +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]); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: accel sensor disable config failed", __func__); - return HDF_FAILURE; - } +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. */ -static int32_t SetAccelBatch(int64_t samplingInterval, int64_t interval) -{ - (void)interval; +### When to Use - struct AccelDrvData *drvData = AccelGetDrvData(); - drvData->interval = samplingInterval; +- 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. */ -static int32_t SetAccelMode(int32_t mode) -{ - return (mode == SENSOR_WORK_MODE_REALTIME) ? HDF_SUCCESS : HDF_FAILURE; -} -/* Set the sensor options. */ -static int32_t SetAccelOption(uint32_t option) -{ - (void)option; - return HDF_ERR_NOT_SUPPORT; -} -``` +### Available APIs -- Differentiated processing APIs - - ``` - /* If a device is detected, register the differentiated processing function to the accel driver model. */ - int32_t DetectAccelBim160Chip(struct SensorCfgData *data) - { - int32_t ret; - struct AccelOpsCall ops; - CHECK_NULL_PTR_RETURN_VALUE(data, HDF_ERR_INVALID_PARAM); - - if (strcmp(ACCEL_CHIP_NAME_BMI160, data->sensorAttr.chipName) != 0) { - return HDF_SUCCESS; - } - ret = InitAccelPreConfig(); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: init BMI160 bus mux config", __func__); - return HDF_FAILURE; - } - if (DetectSensorDevice(data) != HDF_SUCCESS) { - return HDF_FAILURE; - } - - /* Differentiated processing function */ - ops.Init = InitBmi160; - ops.ReadData = ReadBmi160Data; - ret = RegisterAccelChipOps(&ops); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: register BMI160 accel failed", __func__); - (void)ReleaseSensorBusHandle(&data->busCfg); - return HDF_FAILURE; - } - return HDF_SUCCESS; - } - /* Initialization processing function */ - static int32_t InitBmi160(struct SensorCfgData *data) - { - int32_t ret; - - CHECK_NULL_PTR_RETURN_VALUE(data, HDF_ERR_INVALID_PARAM); - ret = SetSensorRegCfgArray(&data->busCfg, data->regCfgGroup[SENSOR_INIT_GROUP]); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: bmi160 sensor init config failed", __func__); - return HDF_FAILURE; - } - return HDF_SUCCESS; - } - /* Data processing function */ - 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) { - return HDF_FAILURE; - } - - event.sensorId = SENSOR_TAG_ACCELEROMETER; - event.option = 0; - event.mode = SENSOR_WORK_MODE_REALTIME; - - rawData.x = rawData.x * BMI160_ACC_SENSITIVITY_2G; - rawData.y = rawData.y * BMI160_ACC_SENSITIVITY_2G; - rawData.z = rawData.z * BMI160_ACC_SENSITIVITY_2G; - - tmp[ACCEL_X_AXIS] = (rawData.x * SENSOR_1K_UNIT) / SENSOR_CONVERT_UNIT; - tmp[ACCEL_Y_AXIS] = (rawData.y * SENSOR_1K_UNIT) / SENSOR_CONVERT_UNIT; - tmp[ACCEL_Z_AXIS] = (rawData.z * SENSOR_1K_UNIT) / SENSOR_CONVERT_UNIT; - - event.dataLen = sizeof(tmp); - event.data = (uint8_t *)&tmp; - ret = ReportSensorEvent(&event); - return ret; - } - ``` - -- Data processing function - -Create a sensor timer to periodically sample data based on the configured sampling interval and report the data to the data subscriber. - -``` -/* Scheduled working thread of the sensor */ -static int32_t ReadAccelDataThreadWorker(void *arg) -{ - (void)arg; - int64_t interval; - struct AccelDrvData *drvData = AccelGetDrvData(); - - drvData->threadStatus = SENSOR_THREAD_START; - while (true) { - if (drvData->threadStatus == SENSOR_THREAD_RUNNING) { - if (drvData->ops.ReadData != NULL) { - (void)drvData->ops.ReadData(drvData->accelCfg); - } - interval = OsalDivS64(drvData->interval, (SENSOR_CONVERT_UNIT * SENSOR_CONVERT_UNIT)); - OsalMSleep(interval); - } else if (drvData->threadStatus == SENSOR_THREAD_DESTROY) { - break; - } else { - OsalMSleep(ACC_DEFAULT_SAMPLING_200_MS / SENSOR_CONVERT_UNIT / SENSOR_CONVERT_UNIT); - } - - if ((!drvData->initStatus) || (drvData->interval < 0) || drvData->threadStatus != SENSOR_THREAD_RUNNING) { - continue; - } - } - - return HDF_SUCCESS; -} -/* Create a sensor timer and initialize the sensor device. */ -static int32_t InitAccelConfig(void) -{ - int32_t ret; - struct AccelDrvData *drvData = AccelGetDrvData(); - - if (drvData->threadStatus != SENSOR_THREAD_NONE && drvData->threadStatus != SENSOR_THREAD_DESTROY) { - HDF_LOGE("%s: accel thread have created", __func__); - return HDF_SUCCESS; - } - - ret = CreateSensorThread(&drvData->thread, ReadAccelDataThreadWorker, "hdf_sensor_accel", drvData); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: accel create thread failed", __func__); - drvData->threadStatus = SENSOR_THREAD_NONE; - return HDF_FAILURE; - } - - CHECK_NULL_PTR_RETURN_VALUE(drvData->ops.Init, HDF_ERR_INVALID_PARAM); - - ret = drvData->ops.Init(drvData->accelCfg); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: accel create thread failed", __func__); - drvData->threadStatus = SENSOR_THREAD_NONE; - return HDF_FAILURE; - } - drvData->initStatus = true; - return HDF_SUCCESS; -} -``` - -- Major data structures - -``` -/* Sensor conversion units */ -#define SENSOR_CONVERT_UNIT 1000 -#define SENSOR_1K_UNIT 1024 -/* 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 +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 +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 + +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. */ -static const struct SensorInterface *g_sensorDev = nullptr; +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. /* Register the data reporting function. */ static int SensorTestDataCallback(struct SensorEvents *event) @@ -877,14 +559,14 @@ void HdfSensorTest::TearDownTestCase() /* Verify the sensor driver. */ HWTEST_F(HdfSensorTest,TestAccelDriver_001, TestSize.Level0) { - int32_t sensorInterval = 1000000000; /* Data sampling interval, in nanoseconds */ - int32_t pollTime = 5; /* Data sampling duration, in seconds */ - int32_t accelSensorId = 1; /* Acceleration sensor type ID, which is 1 */ + 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. int32_t count = 0; int ret; struct SensorInformation *sensorInfo = nullptr; - ret = g_sensorDev->Register(SensorTestDataCallback) + ret = g_sensorDev->Register(0, TraditionSensorTestDataCallback) EXPECT_EQ(SENSOR_NULL_PTR, ret); ret = g_sensorDev->GetAllSensors(&sensorInfo, &count); @@ -911,8 +593,7 @@ HWTEST_F(HdfSensorTest,TestAccelDriver_001, TestSize.Level0) g_sensorDataFlag = 0; EXPECT_EQ(0, ret); - ret = g_sensorDev->Unregister(); + ret = g_sensorDev->Unregister(0, TraditionSensorTestDataCallback); EXPECT_EQ(0, ret); } ``` - diff --git a/en/device-dev/driver/driver-peripherals-vibrator-des.md b/en/device-dev/driver/driver-peripherals-vibrator-des.md new file mode 100644 index 0000000000000000000000000000000000000000..9b38fe6b46925333724714a092d9ea9d5109cd70 --- /dev/null +++ b/en/device-dev/driver/driver-peripherals-vibrator-des.md @@ -0,0 +1,368 @@ +# Vibrator + +## Overview + +### Introduction + +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. + +**Figure 1** Vibrator driver model + +![Vibrator driver model](figures/vibrator_driver_model.png) + +### Basic Concepts + +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. + +**Figure 2** How vibrator driver works + +![How vibrator driver works](figures/vibrator_working.png) + +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 + +| API | Description | +| -------------------------------------- | -------------------------------------------------------- | +| int32_t StartOnce(uint32_t duration) | Triggers vibration with a given **duration**. | +| int32_t Start(const char *effectType) | Triggers vibration with a given effect, which is specified by **effectType**.| +| int32_t Stop(enum VibratorMode mode) | Stops vibration. | + +### How to Develop + +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. */ + static int32_t DispatchVibrator(struct HdfDeviceIoClient *client, + int32_t cmd, struct HdfSBuf *data, struct HdfSBuf *reply) + { + int32_t loop; + + for (loop = 0; loop < sizeof(g_vibratorCmdHandle) / sizeof(g_vibratorCmdHandle[0]); ++loop) { + if ((cmd == g_vibratorCmdHandle[loop].cmd) && (g_vibratorCmdHandle[loop].func != NULL)) { + return g_vibratorCmdHandle[loop].func(data, reply); + } + } + + return HDF_SUCCESS; + } + + /* Bind the external service provided by the vibrator driver to the HDF. */ + int32_t BindVibratorDriver(struct HdfDeviceObject *device) + { + struct VibratorDriverData *drvData = NULL; + CHECK_VIBRATOR_NULL_PTR_RETURN_VALUE(device, HDF_FAILURE); + + drvData = (struct VibratorDriverData *)OsalMemCalloc(sizeof(*drvData)); + CHECK_VIBRATOR_NULL_PTR_RETURN_VALUE(drvData, HDF_ERR_MALLOC_FAIL); + + drvData->ioService.Dispatch = DispatchVibrator; + drvData->device = device; + device->service = &drvData->ioService; + g_vibratorDrvData = drvData; + + return HDF_SUCCESS; + } + + /* Entry function for vibrator driver initialization. */ + int32_t InitVibratorDriver(struct HdfDeviceObject *device) + { + struct VibratorDriverData *drvData = NULL; + + drvData->mode = VIBRATOR_MODE_BUTT; + drvData->state = VIBRATOR_STATE_IDLE; + ...... + if (CreateVibratorHaptic(device) != HDF_SUCCESS) { + HDF_LOGE("%s: init workQueue fail!", __func__); + return HDF_FAILURE; + } + + return HDF_SUCCESS; + } + + /* Release the resources allocated during vibrator driver initialization. */ + void ReleaseVibratorDriver(struct HdfDeviceObject *device) + { + struct VibratorDriverData *drvData = NULL; + ...... + (void)DestroyVibratorHaptic(); + (void)OsalMutexDestroy(&drvData->mutex); + (void)OsalMemFree(drvData); + g_vibratorDrvData = NULL; + } + ``` + + - 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. */ + int32_t CreateVibratorHaptic(struct HdfDeviceObject *device) + { + struct VibratorHapticData *hapticData = NULL; + CHECK_VIBRATOR_NULL_PTR_RETURN_VALUE(device, HDF_FAILURE); + + hapticData = (struct VibratorHapticData *)OsalMemCalloc(sizeof(*hapticData)); + CHECK_VIBRATOR_NULL_PTR_RETURN_VALUE(hapticData, HDF_ERR_MALLOC_FAIL); + g_vibratorHapticData = hapticData; + hapticData->supportHaptic = false; + + if (OsalMutexInit(&hapticData->mutex) != HDF_SUCCESS) { + HDF_LOGE("%s: fail to init mutex", __func__); + goto EXIT; + } + + DListHeadInit(&hapticData->effectSeqHead); + + /* Parse the haptic HCS configuration. */ + if (ParserVibratorHapticConfig(device->property) != HDF_SUCCESS) { + HDF_LOGE("%s: parser haptic config fail!", __func__); + goto EXIT; + } + + return HDF_SUCCESS; + EXIT: + OsalMemFree(hapticData); + return HDF_FAILURE; + } + ``` + + - 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. + + ```c + /* Trigger vibration with a given duration. */ + static int32_t StartOnce(struct HdfSBuf *data, struct HdfSBuf *reply) + { + uint32_t duration; + int32_t ret; + struct VibratorEffectCfg config; + struct VibratorDriverData *drvData = GetVibratorDrvData(); + (void)reply; + ...... + config.cfgMode = VIBRATOR_MODE_ONCE; + config.duration = duration; + config.effect = NULL; + /* Create a timer based on the vibration effect. */ + ret = StartHaptic(&config); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: start haptic fail!", __func__); + return ret; + } + + return HDF_SUCCESS; + } + + /* Trigger vibration with a given effect. */ + static int32_t StartEffect(struct HdfSBuf *data, struct HdfSBuf *reply) + { + int32_t ret; + const char *effect = NULL; + struct VibratorEffectCfg config; + struct VibratorDriverData *drvData = GetVibratorDrvData(); + (void)reply; + ...... + config.cfgMode = VIBRATOR_MODE_PRESET; + config.duration = 0; + config.effect = effect; + + ret = StartHaptic(&config); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: start haptic fail!", __func__); + return ret; + } + + return HDF_SUCCESS; + } + + /* Stop vibration based on the specified vibration mode. */ + static int32_t Stop(struct HdfSBuf *data, struct HdfSBuf *reply) + { + int32_t ret; + int32_t mode; + struct VibratorDriverData *drvData = GetVibratorDrvData(); + (void)reply; + ...... + /* Stop vibration and destroy the timer. */ + ret = StopHaptic(); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: stop haptic fail!", __func__); + return ret; + } + + (void)OsalMutexLock(&drvData->mutex); + drvData->mode = VIBRATOR_MODE_BUTT; + (void)OsalMutexUnlock(&drvData->mutex); + + return HDF_SUCCESS; + } + ``` + +4. Implement the interfaces for the vibrator chipset driver. + + - Register the vibrator chipset driver interfaces when the vibrator chipset driver is initialized successfully. + + ```c + /* Register the vibrator chipset driver interfaces. */ + int32_t RegisterVibrator(struct VibratorOps *ops) + { + struct VibratorDriverData *drvData = GetVibratorDrvData(); + + CHECK_VIBRATOR_NULL_PTR_RETURN_VALUE(ops, HDF_FAILURE); + CHECK_VIBRATOR_NULL_PTR_RETURN_VALUE(drvData, HDF_FAILURE); + + (void)OsalMutexLock(&drvData->mutex); + drvData->ops.Start = ops->Start; + drvData->ops.StartEffect = ops->StartEffect; + drvData->ops.Stop = ops->Stop; + (void)OsalMutexUnlock(&drvData->mutex); + + return HDF_SUCCESS; + } + ``` + + - The vibrator driver model provides vibrator chipset driver interfaces. Implement these interfaces as follows: + + ```c + /* Start a linear vibrator to vibrate with a given duration. */ + static int32_t StartLinearVibrator() + { + int32_t ret; + struct VibratorLinearDriverData *drvData = GetLinearVibratorData(); + CHECK_VIBRATOR_NULL_PTR_RETURN_VALUE(drvData, HDF_FAILURE); + ...... + ret = GpioWrite(drvData->gpioNum, GPIO_VAL_LOW); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: pull gpio%d to %d level failed", __func__, drvData->gpioNum, GPIO_VAL_LOW); + return ret; + } + return HDF_SUCCESS; + } + + /* Start a linear vibration to vibrate with a given effect. */ + static int32_t StartEffectLinearVibrator(uint32_t effectType) + { + (void)effectType; + HDF_LOGE("%s: vibrator set build-in effect no support!", __func__); + return HDF_SUCCESS; + } + + /* Stop a linear vibration based on the specified vibration mode. */ + static int32_t StopLinearVibrator() + { + int32_t ret; + struct VibratorLinearDriverData *drvData = GetLinearVibratorData(); + CHECK_VIBRATOR_NULL_PTR_RETURN_VALUE(drvData, HDF_FAILURE); + ...... + ret = GpioWrite(drvData->gpioNum, GPIO_VAL_HIGH); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: pull gpio%d to %d level failed", __func__, drvData->gpioNum, GPIO_VAL_HIGH); + return ret; + } + return HDF_SUCCESS; + } + ``` diff --git a/en/device-dev/driver/figures/sensor_driver_model.png b/en/device-dev/driver/figures/sensor_driver_model.png new file mode 100644 index 0000000000000000000000000000000000000000..ddb564e5a4d4d12f815fd81d526e4992e340a20e Binary files /dev/null and b/en/device-dev/driver/figures/sensor_driver_model.png differ diff --git a/en/device-dev/driver/figures/sensor_working.png b/en/device-dev/driver/figures/sensor_working.png new file mode 100644 index 0000000000000000000000000000000000000000..b2a8468d152ba9ddd0c36764c329c59c6725cced Binary files /dev/null and b/en/device-dev/driver/figures/sensor_working.png differ diff --git a/en/device-dev/driver/figures/vibrator_driver_model.png b/en/device-dev/driver/figures/vibrator_driver_model.png new file mode 100644 index 0000000000000000000000000000000000000000..9d377d21c044927727cab59f76fc0f0486423f1f Binary files /dev/null and b/en/device-dev/driver/figures/vibrator_driver_model.png differ diff --git a/en/device-dev/driver/figures/vibrator_working.png b/en/device-dev/driver/figures/vibrator_working.png new file mode 100644 index 0000000000000000000000000000000000000000..edf0dce07514add0db9394a200ebb2f0bc1f572e Binary files /dev/null and b/en/device-dev/driver/figures/vibrator_working.png differ