USB Interface(接口) 并不是 Class 层 的内容,而是属于 USB 协议栈的配置层。它是 USB 设备描述符的一部分,用于描述设备的功能和通信方式。以下是详细的解释:
1. USB Interface 的位置
USB Interface 位于 USB 描述符 中,是 USB 设备配置的一部分。USB 描述符的层次结构如下:
-
设备描述符(Device Descriptor):
-
描述设备的全局信息,如厂商 ID(VID)、产品 ID(PID)、设备类(bDeviceClass)等。
-
-
配置描述符(Configuration Descriptor):
-
描述设备的配置信息,如供电模式、接口数量等。
-
-
接口描述符(Interface Descriptor):
-
描述设备的功能接口,如接口编号、端点数量、接口类(bInterfaceClass)等。
-
-
端点描述符(Endpoint Descriptor):
-
描述端点的传输类型、方向、最大包大小等。
-
-
类特定描述符(Class-Specific Descriptor):
-
描述特定类的额外信息,如 HID 报告描述符、CDC 功能描述符等。
-
2. USB Interface 的作用
-
功能划分:一个 USB 设备可以包含多个 Interface,每个 Interface 代表一种独立的功能。例如,一个复合设备可以有一个 Interface 用于键盘功能,另一个 Interface 用于鼠标功能。
-
通信方式:每个 Interface 定义了设备与主机之间的通信方式,包括使用的端点、传输类型(控制、中断、批量、等时)等。
-
驱动程序绑定:主机操作系统根据 Interface 的 Class 和 Protocol 来加载相应的驱动程序。例如,HID Class 的 Interface 会绑定 HID 驱动程序。
3. USB Interface 与 Class 的关系
-
Interface 描述符中的 Class 字段:
-
每个 Interface 描述符包含一个
bInterfaceClass
字段,用于指定该 Interface 的类(如 HID、CDC、MSC 等)。 -
例如,
bInterfaceClass = 0x03
表示 HID 类,bInterfaceClass = 0x02
表示 CDC 类。
-
-
Class 层的作用:
-
Class 层是基于 Interface 描述符的更高层次抽象,用于实现特定类的功能。
-
例如,HID 类驱动会根据 HID Interface 的描述符初始化 HID 设备,并提供 HID 报告描述符。
-
4. 示例:HID Interface 描述符
以下是一个 HID Interface 描述符的示例:
// HID Interface 描述符 0x09, // bLength: 描述符长度(9 字节) 0x04, // bDescriptorType: 接口描述符类型 0x00, // bInterfaceNumber: 接口编号(0) 0x00, // bAlternateSetting: 备用设置编号 0x01, // bNumEndpoints: 使用的端点数量(1 个中断端点) 0x03, // bInterfaceClass: 接口类代码(HID Class) 0x01, // bInterfaceSubClass: 接口子类代码(1:Boot Interface Subclass) 0x01, // bInterfaceProtocol: 接口协议代码(1:Keyboard) 0x00 // iInterface: 描述接口的字符串索引(无)
-
bInterfaceClass = 0x03
表示这是一个 HID 类接口。 -
bInterfaceProtocol = 0x01
表示这是一个键盘设备。
5. Zephyr 中的 USB Interface
在 Zephyr 中,USB Interface 的描述符通常通过 USB 配置 来定义。例如,定义一个 HID 设备的 Interface:
static const struct usb_if_descriptor if_descriptor = { .bLength = USB_IF_DESC_SIZE, .bDescriptorType = USB_DESC_INTERFACE, .bInterfaceNumber = 0, .bAlternateSetting = 0, .bNumEndpoints = 1, .bInterfaceClass = USB_CLASS_HID, .bInterfaceSubClass = USB_HID_SUBCLASS_BOOT, .bInterfaceProtocol = USB_HID_PROTOCOL_KEYBOARD, .iInterface = 0, .extra = &hid_descriptor, .extra_size = sizeof(hid_descriptor), };
6. 总结
-
USB Interface 是 USB 描述符的一部分,用于描述设备的功能和通信方式。
-
Class 层 是基于 Interface 描述符的更高层次抽象,用于实现特定类的功能。
-
在 Zephyr 中,USB Interface 的描述符通过 USB 配置来定义,并与 Class 驱动结合使用。
通过理解 USB Interface 的作用和与 Class 层的关系,可以更好地设计和实现 USB 设备。如果仍有疑问,可以参考 USB 协议规范或 Zephyr 官方文档。