赞
踩
hidl_interface 是 Android 系统中 HAL(Hardware Abstraction Layer)层中重要的一个概念。HAL 的作用是为系统上层提供硬件抽象层接口,使不同的硬件设备可以在 Android 中得到统一的访问和使用。hidl_interface 则是定义了 HAL 接口中所需要实现的方法和数据结构。
hidl_interface 实际上是由 Android 框架层(Framework Layer)自动生成的 C++ 接口类,在此类中定义了客户端和服务端共通的纯虚函数,这些函数描述了 HAL 层与其他层交流所需的操作。当客户端需要访问某个 HAL 服务时,需要向该服务发出请求并传递相关参数,通过调用 hidl_interface 中定义的函数,来与 HAL 服务进行交互。
同时,hidl_interface 还隐式地定义了一些常量、类型以及其它辅助性结构等,这些都为 HAL 层与其他层之间的交互提供支持。因此,hidl_interface 可以说是 HAL 层接口的基础和核心。
总之,hidl_interface 的作用是规范化 HAL 层的接口规格并提供给上层进行访问,使得 HAL 层可以在不同的硬件设备和不同的 Android 平台上提供相同的抽象层级的接口,并达到更好的可驱动性和可维护性。
这里给出一个简单的 HIDL 接口示例,该接口用于获取 Android 设备中的 CPU 温度。
首先在/hardware/interfaces/thermal/目录下创建 thermal.hal 文件,并在文件中定义 HIDL 接口:
// thermal.hal
package android.hardware.thermal;
interface IThermal {
// 获取 CPU 温度
int32_t get_cpu_temperature() generates(ERR_OTHERWISE, "", "温度读取失败");
};
如何自动生成c++的实现类?看这里。
c++ // Thermal.cpp #include <android/hardware/thermal/1.0/IThermal.h> using android::hardware::thermal::V1_0::IThermal; class Thermal : public IThermal { public: Thermal() {} Return<int32_t> get_cpu_temperature() override { int temperature = 0; // 假设已经获取到了 CPU 温度数据 return temperature; // 将 CPU 温度直接返回给上层调用者 } };
int main() {
sp<IThermal> thermal_svc = new Thermal();
// 将服务发布到 HIDL transport 中
if (thermal_svc->registerAsService("thermal") != android::OK) {
perror("Registering service failed!");
abort();
}
// 执行 I/O 任务循环,等待客户端请求
android::hardware::joinRpcThreadpool();
}
在上面的代码中,我们实现了自定义 IThermal 类并继承了它,并且根据接口定义实现了对 get_cpu_temperature 函数的具体实现。在这个示例中,我们假设已经获取到了 CPU 温度数据,并将其送回给客户端。
因为 HIDL 服务是被托管到一个单独的进程中运行的,所以我们还需要在 main 函数中执行 registerAsService 方法来将服务发布到 HIDL transport 中,以便客户端可以访问它。最后,我们通过 RPC thread pool 循环执行 I/O 任务,以等待客户端请求。
在这个示例中,并不包含完整的 Android 代码,仅展示了如何创建并实现一个基本的 HIDL 接口。对于真实的 Android HAL 层开发需要使用更全面和复杂的框架和工具。
在客户端访问上面创建并发布的 HAL 服务,首先需要调用 HIDL 中提供的 getService 方法获取到该服务的代理对象,然后可以使用该对象来调用服务中定义的方法。下面是一个示例代码:
// ThermalClient.cpp #include <android/hardware/thermal/1.0/IThermal.h> #include <hidl/HidlTransportSupport.h> using android::hardware::thermal::V1_0::IThermal; int main() { // 获取 IThermal 类实例对象 sp<IThermal> thermal_svc = IThermal::getService(); if (thermal_svc == nullptr) { printf("Failed to get IThermal instance!\n"); return -1; } // 调用 IThermal 类对象方法:get_cpu_temperature int temperature = thermal_svc->get_cpu_temperature(); // 检查结果 if (temperature < 0) { printf("Error reading CPU temperature!"); return -1; } printf("CPU temperature is: %d \n", temperature); return 0; }
在上面的代码中,我们通过 IThermal::getService() 方法获取到了 IThermal 类实例化的代理对象,然后调用 get_cpu_temperature() 方法,并传入一个回调函数,以便在获取到 CPU 温度之后进行处理。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。