By: fulinux
E-mail: [email protected]
Blog: https://blog.csdn.net/fulinus
喜欢的盆友欢迎点赞和订阅!
你的喜欢就是我写作的动力!
最近在学习鸿蒙系统,首当其冲是学习HDF,这里有很多文章可以阅读:
https://docs.openharmony.cn/pages/v4.0/zh-cn/device-dev/driver/driver-overview-foundation.md/
但是千言万语,不如一个好示例。下面就是一个示例,不过适配的是3.1,在我的3.2上有比较多的问题,于是将修改后的内容提出来供大家一起学习。
https://blog.csdn.net/procedurecode/article/details/128906246
本例中基于Openharmony的V3.2版本,创建KHDF驱动程序。
创建KHDF驱动程序步骤如下:
通过HDF_INIT将驱动入口注册到HDF框架中,在加载驱动时HDF框架会先调用Bind函数,再调用Init函数加载该驱动,当Init调用异常时,HDF框架会调用Release释放驱动资源并退出:
//myhdfsample.c
#include
#include "device_resource_if.h"
#include "hdf_device_desc.h"
#include "hdf_log.h"
......
struct HdfDriverEntry g_MyHDFSampleEntry = {
.moduleVersion = 1,
.Bind = MyHDFSampleBind,
.Init = MyHDFSampleInit,
.Release = MyHDFSampleRelease,
.moduleName = "myhdfsample",
};
HDF_INIT(g_MyHDFSampleEntry);
通过指定Bind,MyHDFSampleBind将相关的服务接口绑定到HDF框架,通过Dispatch对用户态应用的消息进行处理:
//myhdfsample.c
......
#define TEST_WRITE_DATA 1234
static int32_t MyHDFSampleIoServiceDispatch(struct HdfDeviceIoClient *client, int cmdId, struct HdfSBuf *data, struct HdfSBuf *reply)
{
......
}
static struct IDeviceIoService MyHDFSampleService = {
.Open = NULL,
.Dispatch = MyHDFSampleIoServiceDispatch,
.Release = NULL,
};
static int32_t MyHDFSampleBind(struct HdfDeviceObject *deviceObject)
{
HDF_LOGD("enter %s", __func__);
deviceObject->service = &MyHDFSampleService;
return HDF_SUCCESS;
}
......
定义TEST_WRITE_DATA的cmdId号,对写入的数据进行打印,并返回应答数据。HdfDeviceSendEvent对应用端通过HdfDeviceRegisterEventListener方法注册的监听器HdfDevEventlistener对象均可以接受到cmdId消息。HdfDevEventlistener将会应用端进行说明:
#define TEST_WRITE_DATA 1234
static int32_t MyHDFSampleIoServiceDispatch(struct HdfDeviceIoClient *client, int cmdId, struct HdfSBuf *data, struct HdfSBuf *reply)
{
HDF_LOGD("enter %s: received cmd %d", __func__, cmdId);
if (cmdId == TEST_WRITE_DATA) {
const char *readData = HdfSbufReadString(data);
if (readData != NULL) {
HDF_LOGD("%s: read data is:%s", __func__, readData);
}
if (HdfSbufWriteString(reply, "I am driver's reply string!")) {
return HdfDeviceSendEvent(client->device, cmdId, data);
}
}
HDF_LOGE("%s: return fail", __func__);
return HDF_FAILURE;
}
HdfNewdeviceInit实现驱动自身业务初始的接口,HdfNewdeviceRelease实现驱动资源释放的接口:
static int32_t MyHDFSampleInit(struct HdfDeviceObject *device)
{
HDF_LOGD("%s: Hdf dev service:%s init success", __func__, HdfDeviceGetServiceName(device));
return HDF_SUCCESS;
}
static void MyHDFSampleRelease(struct HdfDeviceObject *device)
{
HDF_LOGD("%s: Hdf dev service:%s release success", __func__, HdfDeviceGetServiceName(device));
}
下面完整展示drivers/hdf_core/adapter/khdf/linux/myhdfsam