鸿蒙OpenHarmony技术—消息机制实现

2024-01-08 12:38:41

用户态应用发送消息到驱动

用户态主要代码

struct HdfIoService *serv = HdfIoServiceBind(SAMPLE_SERVICE_NAME);


......


ret = serv->dispatcher->Dispatch(&serv->object, SAMPLE_WRITE_READ, data, reply);
if (ret != HDF_SUCCESS) {
    HDF_LOGE("fail to send service call");
    goto out;
}

重点就是通过HdfIoServiceBind绑定服务,调用服务的Dispatch接口

HdfIoServiceBind接口流程

HdfIoServiceBind接口的主要作用是open对应服务的字符设备节点/dev/hdf/serviceName,细节流程如下:

SHELL
HdfIoServiceBind(`drivers/hdf_core/framework/core/shared/src/hdf_io_service.c`)
    -> HdfIoServiceAdapterObtain
        -> open /dev/hdf/serviceName
        -> .Dispatch = HdfSyscallAdapterDispatch

HdfIoServiceAdapterObtain函数有两处实现:

  • 针对内核态,给内核用:drivers/hdf_core/framework/core/adapter/vnode/src/hdf_vnode_adapter.c
  • 针对用户态,给应用用:drivers/hdf_core/framework/core/adapter/syscall/src/hdf_syscall_adapter.c

这里主要看用户态的实现,即hdf_syscall_adapter.c

Dispatch接口流程

SHELL
serv->dispatcher->Dispatch()
dispatcher 
    -> Dispatch()
        -> HdfSyscallAdapterDispatch 
            -> ioctl - HDF_WRITE_READ

最底层就是通过系统调用ioctl来读写消息(HDF_WRITE_READ)。

用户态应用接收驱动上报事件

用户态代码

struct HdfIoService *serv = HdfIoServiceBind(SAMPLE_SERVICE_NAME);


......


static struct HdfDevEventlistener listener = {
    .callBack = OnDevEventReceived,
    .priv ="Service0"
};


if (HdfDeviceRegisterEventListener(serv, &listener) !=          HDF_SUCCESS) {
    HDF_LOGE("fail to register event listener");
    return HDF_FAILURE;
}

主要是通过HdfDeviceRegisterEventListener注册回调函数

HdfDeviceRegisterEventListener函数流程

drivers/hdf_core/framework/core/adapter/syscall/src/hdf_syscall_adapter.c

SHELL
HdfDeviceRegisterEventListener
    -> HdfDeviceRegisterEventListenerWithSchedPolicy
        -> HdfIoServiceStartListen
            -> HdfIoServiceThreadBindLocked
                -> HdfDevListenerThreadInit
                    -> HdfDevListenerThreadDoInit
                        -> OsalThreadCreate HdfDevEventListenTask
            -> HdfDevListenerThreadStart
                -> HdfAdapterStartListenIoctl  
                    -> ioctl  - HDF_LISTEN_EVENT_START
                -> OsalThreadStart HdfDevEventListenTask

调到最后,就是通过osal的接口OsalThreadCreate创建线程,OsalThreadStart开始线程,而对应的线程就是下面的HdfDevEventListenTask:

SHELL
HdfDevEventListenTask  - poll
    -> HdfDevEventReadAndDispatch  
        -> ioctl - HDF_READ_DEV_EVENT
        -> HdfDevEventDispatchLocked
            -> listener->callBack

以上的核心就是基于poll,通过ioctl来读取消息(HDF_READ_DEV_EVENT),然后再去调用上面传过来的回调函数。

有关进阶鸿蒙开发核心技术,可以前往主页查看更多。鸿蒙技术学习路线(略缩图)分布如下:

高清完整版获取可前往主页保存,另附鸿蒙文档

文章来源:https://blog.csdn.net/2301_76813281/article/details/135387057
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。