Что значит составное usb устройство
Композитное USB-устройство не может должным образом работать с USB 3.0 [решено]
Что вас может беспокоить…
Попробуйте эти исправления:
Решение 1. Обновите драйвер USB-контроллера
Если ваш драйвер USB-контроллера поврежден, устарел или отсутствует, вероятно, возникает ошибка.
Вы можете обновить драйвер контроллера USB вручную или автоматически.
Вариант 1 — Вы можете перейти на веб-сайт производителя своего фирменного компьютера или USB-контроллера, а затем выполнить поиск последней версии USB-контроллера, соответствующей вашей конкретной версии Windows (например, Windows 64 bit) и загрузите драйвер вручную.
После того, как вы загрузили правильные драйверы для вашей системы, дважды щелкните загруженный файл и следуйте инструкциям на экране, чтобы установить d river.
Driver Easy автоматически распознает вашу систему и найдет для нее правильные драйверы. Вам не нужно точно знать, в какой системе работает ваш компьютер, вам не нужно рисковать загрузкой и установкой неправильного драйвера, и вам не нужно беспокоиться об ошибке при установке.
Загрузить и установите Driver Easy.
После обновления драйвера USB-контроллера до последней версии перезагрузите компьютер, чтобы проверить, успешно ли подключен принтер.
Решение 2: Обновите драйвер принтера
Решение 3. Отрегулируйте настройки BIOS
Для включения поддержки устаревших USB выполните следующие действия:
Вот и все. Возможно, теперь вы сможете использовать свой принтер с компьютером под управлением Windows. Не стесняйтесь комментировать ниже, если у вас есть какие-либо вопросы.
Два в одном: USB хост и составное USB устройство
Не так давно, была опубликована статья «Пастильда — открытый аппаратный менеджер паролей». Так как данный проект является открытым, то мы решили, что будет интересно, если мы будем писать небольшие заметки о процессе проектирования, о задачах, которые перед нами стоят и о трудностях, с которыми мы сталкиваемся.
Реализация USB хоста
Итак, во-первых мне нужно было реализовать на устройстве USB хост, чтобы оно могло распознавать и общаться с подключенной к нему клавиатурой. Так как в работе я использую связку Eclipse + GNU ARM Eclipse + libopencm3, то очень хотелось найти уже что-то готовое и желательно написанное с использованием библиотеки libopencm3. Желание мое было очень жирным, до последнего момента не верила, что мои поиски увенчаются успехом. Однако под конец рабочего дня, проскролив интернет до самого дна, я вдруг наткнулась вот на это. libusbhost? Серьезно? И это был не просто написанный на основе libopencm3 usb хост, он еще и был написан под STM32F4, под тот самый, который мы решили использовать в проекте. В общем, звезды сошлись и радости моей не было предела. Кстати, оказалось, что этот проект создавался как часть libopencm3, однако его так и не добавили в библиотеку.
Как библиотеку, libusbhost я не собирала, просто взяла необходимые мне исходники, написала драйвер для клавиатуры и, в общем-то все, погнали! Но обо всем по-порядку.
По аналогии с usbh_driver_hid_mouse.[ch], я написала драйвер для клавиатуры (usbh_driver_hid_kbd.[ch]).
Далее был реализован простенький класс, для работы с хостом:
Реализация составного USB устройства
Далее мне нужно было сделать так, чтобы наше устройство отображалось в диспетчере устройств и как клавиатура, и как дисковый накопитель. Тут вся магия в дескрипторах=) В этом документе, в главе 9, подробно описан USB Device Framework. Эту главу нужно очень внимательно прочитать и в соответствии с ней описать дескрипторы устройства. В моем случае получилось следующее:
Для работы с составным устройством был написан класс USB_composite, представленный ниже.
Как правило, функции control_request и set_config должны быть явно описаны для каждого устройства. Однако из этого правила есть исключение: Mass Storage Device. Итак, разберемся с конструктором класса USB_Composite.
Во-первых, мы инициализируем ноги USB OTG FS:
Во-вторых, нам нужно проинициализировать наше составное устройство, зарегистрировать USB_set_config_callback, о котором шла речь выше, и разрешить прерывание:
Так вот. Теперь, когда конструктор класса USB_Composite дописан, можно собрать проект, прошить устройство и увидеть, что «Запоминающее устройство для USB» больше не помечено предупреждением, а во вкладке «Дисковые устройства» можно обнаружить «ThirdPin Pastilda USB Device». И, казалось бы, все хорошо. Но нет=) Проблем стало больше:
1. Зайти на диск невозможно. При попытке сделать это все виснет, умирает, компьютеру очень плохо.
2. Распознавание устройства как дискового занимает более 2-х минут.
Об этих проблемах и о том, как их решить без вреда для здоровья написано здесь: USB mass storage device и libopencm3.
И, о, чудо! Никаких пятен=) Теперь все работает. У нас есть USB хост и составное USB устройство. Осталось только объединить их работу.
Объединение хоста и составного устройства
, Пастильда должна перехватить управление и отправить сообщение в ПК как клавиатура, после чего мы возвращаемся в режим трансляции и снова ожидаем комбинацию.
Код, реализующий все это, простой как палка:
, мы будем попадать в однострочное меню, а во флеше будет храниться наша зашифрованная база данных паролей.
Буду рада любым комментариям и пожеланиям.
И, конечно же, ссылка на github.
Составное устройство USB на STM32. Часть 1: Предпосылки
История эта началась три года назад, когда я осознал, что мне скоро исполнится 50 лет, что я погряз в бумажной работе, и что мне хочется чего-то нового. Работу поменять в моём возрасте уже проблематично, поэтому я решил начать pet-проект.
Первое, что приходит в таких случаях на ум старому радиолюбителю: новая радиостанция. Стопроцентно аппаратные решения остались в далёком прошлом. Сейчас гораздо более актуальны SDR-трансиверы: решение это программно-аппаратное, есть опубликованные примеры реализации, к некоторым из них даже выложены исходные коды прошивок.
Основная проблема в разработке заключалась в том, что несложные SDR-радиостанции, работающие в связке со звуковой картой, требуют наличия у компьютера, к которому они подключены, двухканальных линейных входа и выхода для работы приёмо-передающего тракта, а также COM-порта для работы CAT-интерфейса. В современных же ноутбуках аудиовход обычно предназначен для подключения микрофона гарнитуры и бывает только монофоническим.
Решением проблемы стала реализация составного устройства USB, состоящего из виртуального COM-порта и дуплексной звуковой карты. Кому интересно, как я с этим справился, не имея опыта программирования, милости прошу под cut.
TL/DR: Как я с этим справился, не имея опыта программирования? Просто начал программировать на C, а остальное приложилось само: MVP проекта реализован, а исходные коды публикуемой реализации составного устройства USB, состоящего из виртуального COM-порта и дуплексной звуковой карты находятся здесь: http://github.com/dmitrii-rudnev/selenite-habr
… и опыт, сын ошибок трудных.
И опыт и навыки формируются практикой. Для их формирования необходимо:
Язык C разрабатывался инженерами и для инженеров. Использование языка программирования C дало мне возможность абстрагироваться от ассемблера и машинных кодов с одной стороны, но в тоже время обращаться напрямую к регистрам или к памяти.
Нелюбимый многими STM32CubeMX с библиотекой HAL значительно облегчил мне процесс разработки хотя бы тем, что не надо было за каждой мелочью заглядывать в Reference Manual.
Кроме того, я очень многому научился, разбирая сгенерированный STM32CubeMX код:
В силу того, что я не мог гарантировать результат своей программистской деятельности, пришлось вводить градации по функционалу MVP проекта от простого к сложному.
Минимальный функционал MVP подразумевал подключение приёмной части радиостанции к линейному входу звуковой карты компьютера и приём на фиксированной частоте.
Следующим шагом планировалась реализация перестройки частоты через CAT-интерфейс, подключение приёмного и передающего трактов радиостанции к линейным входу и выходу звуковой карты и приём-передача на любительских диапазонах.
И только после этого планировалось подключение SDR-трансивера к компьютеру как звукового устройства USB с управлением по CAT-интерфейсу.
Такой подход сразу дал плоды: уже к началу 2019 года, всего через шесть месяцев после установки на мой компьютер STM32CubeMX, был реализован минимальный MVP проекта: функциональный аналог SDR-приёмника Softrock Lite II RX уверенно принимал сигналы точного времени на частоте 9996 кГц.
В настоящее время MVP проекта является функциональным аналогом SDR-трансивера Peaberry SDR V2 и работает как на приём, так и на передачу.
Структура приёмопередающего тракта SDR-трансивера
Описываемое в публикации составное устройство USB работает в составе SDR-трансивера. Структура приёмопередающего тракта разрабатываемого SDR-трансивера включает в себя пока только самый необходимый минимум и представлена на рисунке ниже:
При приёме радиосигнал поступает из антенны через полосовой фильтр (BPF) в квадратурный детектор (QSD). Полученный в результате квадратурный сигнал (IQ) через двухканальный вход дуплексного звукового устройства USB поступает в компьютер для дальнейшей обработки.
При передаче сформированный в компьютере квадратурный сигнал (IQ) через двухканальный выход дуплексного звукового устройства USB поступает в квадратурный возбудитель (QSE).
Полученный в результате радиосигнал подаётся через полосовой фильтр (BPF) в антенну.
Обработка сигналов на стороне компьютера осуществляется программой HDSDR.
Частота приёма и передачи задаётся настройками генератора плавного диапазона (VFO). Управление VFO и режимом работы (приём-передача) осуществляется из программы HDSDR через CAT-интерфейс, подключенный к виртуальному COM-порту.
Связь HDSDR с виртуальным COM-портом осуществляется посредством программы OmniRig, созданной канадским радиолюбителем Alex Shovkoplyas (VE3NEA).
CAT-интерфейс трансивера использует ограниченный набор команд популярного во всём мире трансивера Yaesu FT-817.
Виртуальный COM-порт и дуплексное звуковое устройство объединены в составное устройство USB, работа которого и будет разобрана в данной публикации. Для облегчения проверки работоспособности публикуемого решения на входные и выходные потоки устройств установлены шлейфы.
Вся необходимая для разработки описанного в публикации составного устройства USB документация была найдена поиском по сайту usb.org.
Техническое решение разрабатывалось на основе анализа созданной немецким радиолюбителем Andreas Richter (DF8OE) open source прошивки для трансивера mcHF M0NKA и его клонов. Ряд нюансов был проработан при попытках разобраться в кодах дуплексного звукового устройства USB на базе расширения X-CUBE-AUDIO для STM32CubeMХ.
Структура составного устройства USB
Описываемое в публикации составное устройство USB состоит из виртуального COM-порта и дуплексного звукового устройства USB 16 бит 48 кГц. Публикуемое решение реализовано на микроконтроллере STM32F446ZET6 из состава платы NUCLEO-F446ZE.
Упрощенная структура дескриптора представлена на рисунке ниже:
Дескриптор составного устройства USB создан по рекомендациям, содержащимся в документе:
Хотел бы заострить внимание на том, что в структуре дескриптора составного устройства USB важен порядок описания интерфейсов: сначала идёт описание интерфейса 0, затем интерфейса 1 и т.д. Номера используемых интерфейсами конечных точек (EP) могут идти не по порядку.
При генерации кода STM32CubeMX размещает дескриптор устройства (Device Descriptor) в файле usbd_desc.c. Нужно отметить, что STM32CubeMX при последующей генерации кода не сохранит изменения, вручную внесённые в дескриптор, т.к. они не находятся в области, помеченной как USER CODE.
Дескрипторы конфигурации и классов устройств размещаются в файлах usbd_cdc.c и usbd_audio.c, размещённых в папках директории Middlewares/ST/Class. Важно помнить, что STM32CubeMX даёт выбрать за раз только один класс устройств. Если ранее был выбран другой класс, при генерации кода файлы с драйверами этого класса из проекта будут удалены.
От автора
В следующей части публикации будет разобрана:
Русские Блоги
Дескриптор ассоциации интерфейса комбинированного устройства USB (IAD)
Класс коммуникационного устройства, сокращенно CDC
Составное USB-устройство , Составное USB-устройство
Составное USB-устройство , Составное USB-устройство
Резюме
Составное USB-устройство В составное устройство встроен концентратор и множество функций.Каждая функция эквивалентна независимому периферийному USB-устройству со своим собственным PID / VID.
Составное устройство USB имеет только одну функцию и только один набор PID / VID.Комбинация нескольких функций реализуется путем определения разных интерфейсов как разных классов.
Составное устройство включает концентратор и несколько функций, и каждая функция эквивалентна независимому периферийному устройству USB со своим собственным PID / VID.
В составном устройстве есть только одна функция и только один набор PID / VID.Комбинация нескольких функций реализуется путем определения разных интерфейсов как разных классов.
Многие думают, что реализация нескольких устройств на одном интерфейсе USB относится к составным устройствам, но на самом деле это не совсем так.
Хотя и составное USB-устройство, и составное USB-устройство будут переведены Baidu в составные USB-устройства.
В стандартном протоколе USB2.0 это определяется следующим образом:
When multiple functions are combined with a hub in a single package, they are referred to as a compound device.
A device that has multiple interfaces controlled independently of each other is referred to as a composite device.
ВидетьUSB Descriptors
Составные USB-устройства обычно реализуются с помощью дескриптора ассоциации интерфейса (IAD), который должен добавить дескриптор IAD перед объединяемым интерфейсом.
The bFirstInterface field of the IAD indicates the number of the first interface in the function.
The bInterfaceCount field of the IAD indicates how many interfaces are in the interface collection.
Interfaces in an IAD interface collection must be contiguous (there can be no gaps in the list of interface numbers),
and so a count with a first interface number is sufficient to specify all of the interfaces in the collection.
USB Interface Association Descriptor Device Class code ans Use Model
USB Interface Association Descriptor Example
The following illustrates a descriptor layout for a composite USB device.
The example device has two functions:
Function 1: Video Class
This function is defined by an interface association descriptor (IAD)
and contains two interfaces: interface zero (0) and interface one (1).
The system generates hardware and compatible identifiers (IDs) for the function,
as described in Enumeration of Interface Collections on USB Devices with IADs.
After matching the appropriate INF file, the system loads the Video Class driver stack.
Function 2: Human Input Device
This function contains only one interface : interface two (2).
The system generates hardware and compatible IDs for the function,
as described in Enumeration of Interfaces on USB Composite Devices.
After matching the appropriate INF file, the system loads the Human Input Device (HID) class driver.
However, the USB Device Working Group (DWG) created USB device classes that allow for functions with multiple interfaces,
and the USB Implementor’s Forum issued an Engineering Change Notification (ECN) that defines a mechanism for grouping interfaces.
The ECN specifies a USB descriptor, called the Interface Association Descriptor (IAD), that allows hardware manufacturers to define groupings of interfaces.
The device classes that are most likely to use IADs include:
Windows 7, Windows Server 2008, Windows Vista, Microsoft Windows Server 2003 Service Pack 1 (SP1), and Microsoft Windows XP Service Pack 2 (SP2) support IADs.
Manufacturers of composite devices typically assign a value of zero ( 0x00 ) in the device descriptor, as specified by the Universal Serial Bus Specification.
This allows the manufacturer to associate each individual interface with a different device class and protocol.
The USB-IF core team has devised a special class and protocol code set that notifies the operating system that one or more IADs are present in device firmware.
A device’s device descriptor must have the values that appear in the following table
or else the operating system will not detect the device’s IADs or group the device’s interfaces properly.
These code values also alert versions of Windows that do not support IADs to install a special-purpose bus driver that correctly enumerates the device.
Without these codes in the device descriptor, the system might fail to enumerate the device, or the device might not work properly.
Больше говорить бесполезно, убедитесь самиhttp://www.microsoft.com/whdc/archive/IAD.mspx. Очень просто использовать.
В Windows нет разницы между IAD и составными устройствами в диспетчере устройств, и даже все используемые драйверы являются составными.
Под Linux это устройство действительно можно найти, но CDC, который я реализовал с IAD, не загружается автоматически в ttyACM0. Я изучу это позже.
【Решение】
Я обнаружил, что в диспетчере устройств Windows, если отключить или удалить последовательный порт CDC, все в порядке.
Вроде двух тигров места нет.При использовании libusb последовательный порт CDC отключен. При использовании последовательного порта CDC включите его снова.
Это связано с тем, что устройство CDC под Windows не может работать с libusb, если не используется драйвер usbser, а используется драйвер libusb.
USB-описание JTAGICE mkII и USB-CDC вместе:
Дескриптор составного устройства Mass Storage и CDC:
USB CDC + HID + IAD interface
Connection Status | Device connected |
Current Configuration | 1 |
Speed | Full |
Device Address | 1 |
Number Of Open Pipes | 5 |
bLength | 1 | 12h | ||
1 | bDescriptorType | 1 | 01h | Device |
2 | bcdUSB | 2 | 0200h | USB Spec 2.0 |
4 | bDeviceClass | 1 | EFh | Miscellaneous |
5 | bDeviceSubClass | 1 | 02h | Common Class |
6 | bDeviceProtocol | 1 | 01h | Interface Association Descriptor |
7 | bMaxPacketSize0 | 1 | 08h | 8 bytes |
8 | idVendor | 2 | 04D8h | Microchip Technology, Inc. |
10 | idProduct | 2 | 00DFh | |
12 | bcdDevice | 2 | 0101h | 1.01 |
14 | iManufacturer | 1 | 01h | «Microchip Technology Inc.» |
15 | iProduct | 1 | 02h | «MCP2200 USB Serial Port Emulator» |
16 | iSerialNumber | 1 | 03h | «0000133170» |
17 | bNumConfigurations | 1 | 01h |
bLength | 1 | 09h | ||
1 | bDescriptorType | 1 | 02h | Configuration |
2 | wTotalLength | 2 | 006Bh | |
4 | bNumInterfaces | 1 | 03h | |
5 | bConfigurationValue | 1 | 01h | |
6 | iConfiguration | 1 | 00h | |
7 | bmAttributes | 1 | 80h | Bus Powered |
4..0: Reserved | . 00000 | |||
5: Remote Wakeup | ..0. | No | ||
6: Self Powered | .0. | No, Bus Powered | ||
7: Reserved (set to one) (bus-powered for 1.0) | 1. | |||
8 | bMaxPower | 1 | 32h | 100 mA |
bLength | 1 | 08h | ||
1 | bDescriptorType | 1 | 0Bh | Interface Association |
2 | bFirstInterface | 1 | 00h | |
3 | bInterfaceCount | 1 | 02h | |
4 | bFunctionClass | 1 | 02h | CDC Control |
5 | bFunctionSubClass | 1 | 02h | Abstract Control Model |
6 | bFunctionProtocol | 1 | 01h | AT Commands: V.250 etc |
7 | iFunction | 1 | 00h |
bLength | 1 | 09h | ||
1 | bDescriptorType | 1 | 04h | Interface |
2 | bInterfaceNumber | 1 | 00h | |
3 | bAlternateSetting | 1 | 00h | |
4 | bNumEndpoints | 1 | 01h | |
5 | bInterfaceClass | 1 | 02h | CDC Control |
6 | bInterfaceSubClass | 1 | 02h | Abstract Control Model |
7 | bInterfaceProtocol | 1 | 01h | AT Commands: V.250 etc |
8 | iInterface | 1 | 00h |
bFunctionLength | 1 | 05h | ||
1 | bDescriptorType | 1 | 24h | CS Interface |
2 | bDescriptorSubtype | 1 | 00h | Header |
3 | bcdCDC | 2 | 0110h | 1.10 |
bFunctionLength | 1 | 04h | ||
1 | bDescriptorType | 1 | 24h | CS Interface |
2 | bDescriptorSubtype | 1 | 02h | Abstract Control Management |
3 | bmCapabilities | 1 | 06h | |
7..4: Reserved | 0000. | |||
3: Connection | . 0. | |||
2: Send Break | . 1.. | Send Break request supported | ||
1: Line Coding | . 1. | Line Coding requests and Serial State notification supported | ||
0: Comm Features | . 0 |
bFunctionLength | 1 | 05h | ||
1 | bDescriptorType | 1 | 24h | CS Interface |
2 | bDescriptorSubtype | 1 | 06h | Union |
3 | bControlInterface | 1 | 00h | |
4 | bSubordinateInterface0 | 1 | 01h | CDC Data |
bFunctionLength | 1 | 05h | ||
1 | bDescriptorType | 1 | 24h | CS Interface |
2 | bDescriptorSubtype | 1 | 01h | Call Management |
3 | bmCapabilities | 1 | 00h | |
7..2: Reserved | 000000.. | |||
1: Data Ifc Usage | . 0. | Call management only over Comm Ifc | ||
0: Call Management | . 0 | Does not handle call management itself | ||
4 | bDataInterface | 1 | 01h |
bLength | 1 | 07h | ||
1 | bDescriptorType | 1 | 05h | Endpoint |
2 | bEndpointAddress | 1 | 82h | 2 In |
3 | bmAttributes | 1 | 03h | Interrupt |
1..0: Transfer Type | . 11 | Interrupt | ||
7..2: Reserved | 000000.. | |||
4 | wMaxPacketSize | 2 | 0008h | 8 bytes |
6 | bInterval | 1 | 02h | 2 ms |
bLength | 1 | 09h | ||
1 | bDescriptorType | 1 | 04h | Interface |
2 | bInterfaceNumber | 1 | 01h | |
3 | bAlternateSetting | 1 | 00h | |
4 | bNumEndpoints | 1 | 02h | |
5 | bInterfaceClass | 1 | 0Ah | CDC Data |
6 | bInterfaceSubClass | 1 | 00h | |
7 | bInterfaceProtocol | 1 | 00h | |
8 | iInterface | 1 | 00h |
bLength | 1 | 07h | ||
1 | bDescriptorType | 1 | 05h | Endpoint |
2 | bEndpointAddress | 1 | 03h | 3 Out |
3 | bmAttributes | 1 | 02h | Bulk |
1..0: Transfer Type | . 10 | Bulk | ||
7..2: Reserved | 000000.. | |||
4 | wMaxPacketSize | 2 | 0020h | 32 bytes |
6 | bInterval | 1 | 00h |
bLength | 1 | 07h | ||
1 | bDescriptorType | 1 | 05h | Endpoint |
2 | bEndpointAddress | 1 | 83h | 3 In |
3 | bmAttributes | 1 | 02h | Bulk |
1..0: Transfer Type | . 10 | Bulk | ||
7..2: Reserved | 000000.. | |||
4 | wMaxPacketSize | 2 | 0040h | 64 bytes |
6 | bInterval | 1 | 00h |
bLength | 1 | 09h | ||
1 | bDescriptorType | 1 | 04h | Interface |
2 | bInterfaceNumber | 1 | 02h | |
3 | bAlternateSetting | 1 | 00h | |
4 | bNumEndpoints | 1 | 02h | |
5 | bInterfaceClass | 1 | 03h | HID |
6 | bInterfaceSubClass | 1 | 00h | |
7 | bInterfaceProtocol | 1 | 00h | |
8 | iInterface | 1 | 00h |
bLength | 1 | 09h | ||
1 | bDescriptorType | 1 | 21h | HID |
2 | bcdHID | 2 | 0111h | 1.11 |
4 | bCountryCode | 1 | 00h | |
5 | bNumDescriptors | 1 | 01h | |
6 | bDescriptorType | 1 | 22h | Report |
7 | wDescriptorLength | 2 | 001Dh | 29 bytes |
bLength | 1 | 07h | ||
1 | bDescriptorType | 1 | 05h | Endpoint |
2 | bEndpointAddress | 1 | 81h | 1 In |
3 | bmAttributes | 1 | 03h | Interrupt |
1..0: Transfer Type | . 11 | Interrupt | ||
7..2: Reserved | 000000.. | |||
4 | wMaxPacketSize | 2 | 0010h | 16 bytes |
6 | bInterval | 1 | 01h | 1 ms |
bLength | 1 | 07h | ||
1 | bDescriptorType | 1 | 05h | Endpoint |
2 | bEndpointAddress | 1 | 01h | 1 Out |
3 | bmAttributes | 1 | 03h | Interrupt |
1..0: Transfer Type | . 11 | Interrupt | ||
7..2: Reserved | 000000.. | |||
4 | wMaxPacketSize | 2 | 0010h | 16 bytes |
6 | bInterval | 1 | 01h | 1 ms |
Usage Page (Vendor-Defined 1) | 06 00 FF |
Usage (Vendor-Defined 1) | 09 01 |
Collection (Application) | A1 01 |
Usage Minimum (Vendor-Defined 1) | 19 01 |
Usage Maximum (Vendor-Defined 16) | 29 10 |
Logical Minimum (0) | 15 00 |
Logical Maximum (255) | 26 FF 00 |
Report Size (8) | 75 08 |
Report Count (16) | 95 10 |
Input (Data,Ary,Abs) | 81 00 |
Usage Minimum (Vendor-Defined 1) | 19 01 |
Usage Maximum (Vendor-Defined 16) | 29 10 |
Output (Data,Ary,Abs,NWrp,Lin,Pref,NNul,NVol,Bit) | 91 00 |
End Collection | C0 |
As I understood from all googling about composite devices, two interfaces usually mean that in Windows device manager
we will see composite device and two other devices that corespond to each interface.
If you need one device, then most likely you will need to use device class 0xEF and USB Interface Association Descriptor,
but I’m not sure if it will do what you need.
usbccgp.sys hangs Windows to death when a descriptor is malformed?
Yes, it’s true. Even for full-speed and low-speed devices. So double-check your descriptors:
Problems arise when you change your single-interface USB device into a multi-interface (multi-function) while keeping your USB VID+PID pair!
Even when your change or add some more USB interface with the same VID+PID pair, problems occur.
The Windows behaviour of assigning a driver is as follows:
So you may conclude:
This INF file snippet is wrong because you have no control whether your driver is bound to the Interface #0
or the entire USB device (except your driver is very smart and can handle this):
(Windows will work as expected most of the time, but users are able to bind multi-function devices to entire devices,
and produce overwhelming trouble with your support.)
If you change your single-interface USB device to multi-interface and vice versa keeping VID+PID,
make sure that you cleaned your Device Manager entries beforehand.
Or at least before you plug your changed device.
Google for devmgr_show_nonpresent_devices and devmgr_show_details to get a clue.
Better you change VID+PID too, providing you have a free pair available.
If you are in doubt offering a single-interface or multi-interface USB device,
simply decide to multi-interface at the first step,
and implement an extra HID or CDC interface to make usbccgp.sys happy.
It’s useful for debugging purposes later. At least two childs are needed.
Note that CDC interface (which is itself a composite USB device by design and handled in a special way by usbccgp.sys)
will not run properly in elsewhere-multifunction devices on Windows 2000 and earlier.
USB Composite Device
USB composite device
This example implements a composite device of CDC (with IAD) and HID
The CDC interface is based on the code of USB CDC implementation for ‘F32x and ‘F34x In either interface, CDC and HID, the device loops back the OUT transfer to IN.
Passed USBCV R1.3.1, the ch9 and HID test
Tested on these Windows version,
— Windows Vista SP1
— WinXP SP3 (usbser.sys: 5.1.2600.5508, usbccgp.sys: 5.1.2600.5512)
On the original WinXP SP2 (usbser.sys, usbccgp.sys: 5.1.2600.2180),
the HID interface of the device works well, but CDC causes BSOD when a test app opens the VCP.
This example implements three HID interfaces to SiLabs ‘F320/’F340 DK.
Each interface has an interrupt IN EP and an interrupt OUT EP.
The firmware loops back the data sent to the OUT EP to the IN EP, on each interface.
Passed the USB compliance test, USBCV 1.3, ch9 and HID test.
Tested on HClient host app example on WinDDK.
This is a demonstration which shows a composite device combined SiLabs USB_HID\MouseExample and USB_Interrupt (USB_INT)
1. What is composite device
Composite device is defined in the USB spec as follows (usb_20.pdf 5.2.3),
A device that has multiple interfaces controlled independently of each other is referred to as a composite device.
Using composite device, multiple functions are combined into a single device.
Ex.
— Keyboard + Mouse
— Video + USB Hard disk
— I/O device (HID + USB_bulk)
Another advantage of composite device is that it eases the device driver development.
OS assigns a separate device driver to each Interface of the composite device as follows.
Therefore, a dedicated monolithic driver is not required for newly designed device;
you can realize it using existing drivers.
When OS has some required drivers as built-in, they are available for the composite device.
These OS built-in device drivers are called as USB class driver.
Approved Class Specification Documents from USB.org
http://www.usb.org/developers/devclass_docs#approved
Please note, available drivers for a composite device are not limited only to class drivers.
Any driver can be applied, as long as it doesn’t require a device class (class defined in device descriptor).
For example, SiLabs USB_INT and USB_bulk drivers are also applicable for composite devices.
2. How Windows handles a composite device
When a device satisfies these three requirement, Windows system recognizes the device as a composite device.
[Note]
WinXP SP2, Win2k3 SP1 and Vista supports this alternative requirement.
1′. The class, subclass and protocol fields of the device are that of Interface Association Descriptor:
(bDeviceClass, bDeviceSubClass, bDeviceProtocol) = (0xEF, 0x02, 0x01)
When an USB device is plugged in to a PC, the system reads out the device descriptor of the device and makes these Device ID.
USB\VID_vvvv&PID_pppp
USB\VID_vvvv&PID_pppp&REV_rrrr
(vvvv, pppp, rrrr: four digit hex number for the VID, PID, device release number.
Matches to idVendor/ idProduct/ bcdDevice, defined in the device descriptor)
The system searches device database on the registry, installed by INF files.
When the system finds the Device ID in a device record, it assigns the device driver specified by the record.
However, when it cannot find any matched record, and the device Configuration satisfies above criteria,
the generic composite parent driver is loaded.
This parent driver parses the Configuration of the device, and assigns this Device ID to each Interfaces.
USB\VID_vvvv&PID_pppp&MI_mm
USB\VID_vvvv&PID_pppp&REV_rrrr&MI_mm
(mm: Interface number of the corresponding function, two digit hex number)
As of the Interface which specifies a class, the system also assigns this Compatible ID.
USB\CLASS_cc
USB\CLASS_cc&SUBCLASS_ss
USB\CLASS_cc&SUBCLASS_ss&PROT_pp
(cc/ ss / pp: two digits hex number. bInterfaceClass/ bInterfaceSubClass/ bInterfaceProtocol, from the Interface descriptor)
The system searches these Device ID and Compatible ID in the device database again.
When it finds a matched record, it assigns the specified device driver to the Interface.
However, when it cannot find any matched record, it shows ‘New Hardware Wizard’ to users and asks them to install the device driver.
3. Implementation
On USB application, firmware, device driver and host application are closely related.
It is desirable to make separate prototypes of firmwares and host applications for each Interface first.
After confirming them to work properly, combine them together.
3.1 Device firmware
When the source code is well organized, modification of the firmware is easy.
Based on one of the prototypes, copy a part of code from other prototypes and insert it to corresponding part of the base source code.
In other word, the source codes should be organized considering to make it a composite device.
When these parameters are defined by #define macro or enum instead of direct number in each prototype,
the combination of prototypes is done smoothly.
HID report descriptor and String descriptors are not included in the Configuration set.
3.1.2 Standard requests
3.1.3 Class-specific requests
wIndex field of the Setup data of the request indicates the Interface to which this request is issued.
Therefore, dispatch the request by wIndex first, and copy the each handler for class-specific requests from the prototypes under each case.
3.1.4 Endpoint handling
When the Endpoint address and Endpoint status are defined by macro,
modification on this part finishes by copying the Endpoint handler of each prototype to the base one.
3.2 Device driver and host application
OS built-in class drivers are designed to work with composite devices.
In most case, these drivers are applicable to composite devices without any change of default INF file.
However, device drivers provided by vendors are not always designed to work with composite devices.
INF file and host application code should be modified for these drivers.
The device driver itself should work without any change.
Of course, rare exception may exist.
3.2.1 INF file
When the device driver requires an INF file even for single use, the INF file is required as a part of composite device.
The INF file defines the Device ID as follows.
USB\VID_vvvv&PID_pppp &MI_mm
USB\VID_vvvv&PID_pppp&REV_rrrr &MI_mm
USB\VID_vvvv&PID_pppp&MI_01
(vvvv, pppp: VID/PID must be unique)
3.2.2 Endpoint address and pipe name / device path name
When two or more devices are combined into a single composite device,
the Endpoint addresses must be often changed to fit to the newly designed device.
Usually, the pipe name and device path name from device drivers are designed to hide the Endpoint address.
Therefore, in most case, Endpoint address reassignment doesn’t affect to the host application.
Enumeration of USB Composite Devices
for the device and generates a PnP event to report the new PDO.
The operating system then queries the bus driver for the hardware IDs associated with the PDO.
For all USB devices, the USB bus driver reports a device ID with the following format:
The device must have multiple interfaces.
The device must have a single configuration.
The bus driver also checks the device class (bDeviceClass), subclass (bDeviceSubClass), and protocol (bDeviceProtocol) fields of the device descriptor.
If these fields are zero, the device is a composite device, and the bus driver reports an extra compatible identifier (ID) of USB\COMPOSITE for the PDO.
After retrieving the hardware and compatible IDs for the new PDO, the operating system searches the INF files.
If one of the INF files contains a match for the device ID, Windows loads the driver that is indicated by that INF file
and the generic parent driver does not come into play.
If no INF file contains the device ID, and the PDO has a compatible ID, Windows searches for the compatible ID.
This produces a match in Usb.inf and causes the operating system to load the USB Generic Parent Driver (Usbccgp.sys).
If you want the generic parent driver to manage your device, but your device does not have the characteristics necessary
to ensure that the system will generate a compatible ID of USB\COMPOSITE,
you will have to provide an INF file that loads the generic parent driver.
The INF file should contain a needs/includes section that references Usb.inf.
If your composite device has multiple configurations, the INF file you provide must specify which configuration the generic parent should use in the registry.
USB Generic Parent Driver (Usbccgp.sys)
Many USB devices expose multiple USB interfaces.
In USB terminology, these devices are called composite devices.
Microsoft Windows 2000 and Windows 98 operating systems include a generic parent facility in the USB bus driver
(Usbhub.sys) that exposes each interface of the composite device as a separate device.
In Microsoft Windows XP and Windows Me, this facility is streamlined and improved by transferring it
to an independent driver called the USB generic parent driver(Usbccgp.sys).
Using the features of the generic parent driver, device vendors can make selective use of Microsoft-supplied driver support for some interfaces.
The interfaces of some composite device operate independently.
For example, a composite USB keyboard with power buttons might have one interface for the keyboard
and another interface for the power buttons.
The USB generic parent driver enumerates each of these interfaces as a separate device.
The operating system loads the Microsoft-supplied keyboard driver to manage the keyboard interface, a
nd the Microsoft-supplied power keys driver to manage the power keys interface.
If the composite device has an interface that is not supported by native Windows drivers,
the vendor of the device should provide a driver for the interfaces and an INF file.
The INF file should have an INF DDInstall section that matches the device ID of interface. T
he INF file must not match the device ID for the composite device itself, because this prevents the generic parent driver from loading.
For an explanation of how the operating system loads the USB generic parent driver, see
Some devices group interfaces into interface collections that work together to perform a particular function.
When interfaces are grouped in interface collections, the generic parent driver treats each collection,
rather than each individual interfaces, as a device.
For more information on how the generic parent driver manages interface collections,
After the operating system loads the client drivers for the interfaces of a composite device,
the generic parent driver multiplexes the data flow from the client drivers,
combining these separate interactions into a single data stream for the composite device.
The generic parent is power policy owner for the entire composite device and all of its interfaces.
It also manages synchronization and PnP requests.
The generic parent driver can simplify the task for vendors of composite hardware,
if Microsoft-supplied drivers support some interfaces but not others.
Vendors of such devices need only supply drivers for the unsupported interfaces,
because the generic parent driver facilitates the use of Microsoft-supplied drivers for the supported interfaces.
The following sections describe the features and functions of the generic parent driver: