- USB Host
- In this document
- Related Samples
- API Overview
- Android Manifest Requirements
- Manifest and resource file examples
- Working with Devices
- Discovering a device
- Using an intent filter
- Enumerating devices
- Obtaining permission to communicate with a device
- Communicating with a device
- Terminating communication with a device
- Работаем с USB Custom HID на Android
- Теория. Максимально коротко
- Подальше от железа, поближе к Android
- Заключение
USB Host
In this document
Related Samples
When your Android-powered device is in USB host mode, it acts as the USB host, powers the bus, and enumerates connected USB devices. USB host mode is supported in Android 3.1 and higher.
API Overview
Before you begin, it is important to understand the classes that you need to work with. The following table describes the USB host APIs in the android.hardware.usb package.
Table 1. USB Host APIs
Class | Description |
---|---|
UsbManager | Allows you to enumerate and communicate with connected USB devices. |
UsbDevice | Represents a connected USB device and contains methods to access its identifying information, interfaces, and endpoints. |
UsbInterface | Represents an interface of a USB device, which defines a set of functionality for the device. A device can have one or more interfaces on which to communicate on. |
UsbEndpoint | Represents an interface endpoint, which is a communication channel for this interface. An interface can have one or more endpoints, and usually has input and output endpoints for two-way communication with the device. |
UsbDeviceConnection | Represents a connection to the device, which transfers data on endpoints. This class allows you to send data back and forth sychronously or asynchronously. |
UsbRequest | Represents an asynchronous request to communicate with a device through a UsbDeviceConnection . |
UsbConstants | Defines USB constants that correspond to definitions in linux/usb/ch9.h of the Linux kernel. |
In most situations, you need to use all of these classes ( UsbRequest is only required if you are doing asynchronous communication) when communicating with a USB device. In general, you obtain a UsbManager to retrieve the desired UsbDevice . When you have the device, you need to find the appropriate UsbInterface and the UsbEndpoint of that interface to communicate on. Once you obtain the correct endpoint, open a UsbDeviceConnection to communicate with the USB device.
Android Manifest Requirements
The following list describes what you need to add to your application’s manifest file before working with the USB host APIs:
- Because not all Android-powered devices are guaranteed to support the USB host APIs, include a element that declares that your application uses the android.hardware.usb.host feature.
- Set the minimum SDK of the application to API Level 12 or higher. The USB host APIs are not present on earlier API levels.
- If you want your application to be notified of an attached USB device, specify an and element pair for the android.hardware.usb.action.USB_DEVICE_ATTACHED intent in your main activity. The element points to an external XML resource file that declares identifying information about the device that you want to detect.
In the XML resource file, declare elements for the USB devices that you want to filter. The following list describes the attributes of . In general, use vendor and product ID if you want to filter for a specific device and use class, subclass, and protocol if you want to filter for a group of USB devices, such as mass storage devices or digital cameras. You can specify none or all of these attributes. Specifying no attributes matches every USB device, so only do this if your application requires it:
- vendor-id
- product-id
- class
- subclass
- protocol (device or interface)
Save the resource file in the res/xml/ directory. The resource file name (without the .xml extension) must be the same as the one you specified in the element. The format for the XML resource file is in the example below.
Manifest and resource file examples
The following example shows a sample manifest and its corresponding resource file:
In this case, the following resource file should be saved in res/xml/device_filter.xml and specifies that any USB device with the specified attributes should be filtered:
Working with Devices
When users connect USB devices to an Android-powered device, the Android system can determine whether your application is interested in the connected device. If so, you can set up communication with the device if desired. To do this, your application has to:
- Discover connected USB devices by using an intent filter to be notified when the user connects a USB device or by enumerating USB devices that are already connected.
- Ask the user for permission to connect to the USB device, if not already obtained.
- Communicate with the USB device by reading and writing data on the appropriate interface endpoints.
Discovering a device
Your application can discover USB devices by either using an intent filter to be notified when the user connects a device or by enumerating USB devices that are already connected. Using an intent filter is useful if you want to be able to have your application automatically detect a desired device. Enumerating connected USB devices is useful if you want to get a list of all connected devices or if your application did not filter for an intent.
Using an intent filter
To have your application discover a particular USB device, you can specify an intent filter to filter for the android.hardware.usb.action.USB_DEVICE_ATTACHED intent. Along with this intent filter, you need to specify a resource file that specifies properties of the USB device, such as product and vendor ID. When users connect a device that matches your device filter, the system presents them with a dialog that asks if they want to start your application. If users accept, your application automatically has permission to access the device until the device is disconnected.
The following example shows how to declare the intent filter:
The following example shows how to declare the corresponding resource file that specifies the USB devices that you’re interested in:
In your activity, you can obtain the UsbDevice that represents the attached device from the intent like this:
Enumerating devices
If your application is interested in inspecting all of the USB devices currently connected while your application is running, it can enumerate devices on the bus. Use the getDeviceList() method to get a hash map of all the USB devices that are connected. The hash map is keyed by the USB device’s name if you want to obtain a device from the map.
If desired, you can also just obtain an iterator from the hash map and process each device one by one:
Obtaining permission to communicate with a device
Before communicating with the USB device, your application must have permission from your users.
Note: If your application uses an intent filter to discover USB devices as they’re connected, it automatically receives permission if the user allows your application to handle the intent. If not, you must request permission explicitly in your application before connecting to the device.
Explicitly asking for permission might be neccessary in some situations such as when your application enumerates USB devices that are already connected and then wants to communicate with one. You must check for permission to access a device before trying to communicate with it. If not, you will receive a runtime error if the user denied permission to access the device.
To explicitly obtain permission, first create a broadcast receiver. This receiver listens for the intent that gets broadcast when you call requestPermission() . The call to requestPermission() displays a dialog to the user asking for permission to connect to the device. The following sample code shows how to create the broadcast receiver:
To register the broadcast receiver, add this in your onCreate() method in your activity:
To display the dialog that asks users for permission to connect to the device, call the requestPermission() method:
When users reply to the dialog, your broadcast receiver receives the intent that contains the EXTRA_PERMISSION_GRANTED extra, which is a boolean representing the answer. Check this extra for a value of true before connecting to the device.
Communicating with a device
Communication with a USB device can be either synchronous or asynchronous. In either case, you should create a new thread on which to carry out all data transmissions, so you don’t block the UI thread. To properly set up communication with a device, you need to obtain the appropriate UsbInterface and UsbEndpoint of the device that you want to communicate on and send requests on this endpoint with a UsbDeviceConnection . In general, your code should:
- Check a UsbDevice object’s attributes, such as product ID, vendor ID, or device class to figure out whether or not you want to communicate with the device.
- When you are certain that you want to communicate with the device, find the appropriate UsbInterface that you want to use to communicate along with the appropriate UsbEndpoint of that interface. Interfaces can have one or more endpoints, and commonly will have an input and output endpoint for two-way communication.
- When you find the correct endpoint, open a UsbDeviceConnection on that endpoint.
- Supply the data that you want to transmit on the endpoint with the bulkTransfer() or controlTransfer() method. You should carry out this step in another thread to prevent blocking the main UI thread. For more information about using threads in Android, see Processes and Threads.
The following code snippet is a trivial way to do a synchronous data transfer. Your code should have more logic to correctly find the correct interface and endpoints to communicate on and also should do any transferring of data in a different thread than the main UI thread:
To send data asynchronously, use the UsbRequest class to initialize and queue an asynchronous request, then wait for the result with requestWait() .
For more information, see the AdbTest sample, which shows how to do asynchronous bulk transfers, and the MissileLauncher sample, which shows how to listen on an interrupt endpoint asynchronously.
Terminating communication with a device
When you are done communicating with a device or if the device was detached, close the UsbInterface and UsbDeviceConnection by calling releaseInterface() and close() . To listen for detached events, create a broadcast receiver like below:
Creating the broadcast receiver within the application, and not the manifest, allows your application to only handle detached events while it is running. This way, detached events are only sent to the application that is currently running and not broadcast to all applications.
Источник
Работаем с USB Custom HID на Android
В современных Android — приложениях для взаимодействия с другими устройствами чаще всего используются беспроводные протоколы передачи данных, как например Bluetooth. В годы, когда часть устройств имеют беспроводную зарядку, сложно представить себе связку Android устройства и периферийного модуля, в которой необходимо использование проводных интерфейсов. Однако когда такая необходимость возникает, на ум сразу же приходит USB.
Давайте разберем с вами гипотетический кейс. Представьте, что к вам приходит заказчик и говорит: “Мне нужно Android приложение для управления устройством сбора данных и вывода этих самых данных на экран. Есть одно НО — приложение надо написать на одноплатный компьютер с операционной системой Android, а периферийное устройство подключено по USB”
Звучит фантастически, но и такое иногда случается. И тут как нельзя кстати пригодится глубокое знание USB стека и его протоколов, но данная статья не об этом. В данной статье мы рассмотрим, как управлять периферийным устройством по протоколу USB Custom HID с Android устройства. Для простоты напишем Android-приложение (HOST), которое будет управлять светодиодом на периферийным устройством (DEVICE) и получать состояние кнопки (нажатия). Код для периферийной платы приводить не буду, кому интересно — пишите в комментариях.
Итак, приступим.
Теория. Максимально коротко
Для начала немного теории, максимально коротко. Это упрощенный минимум, достаточный для понимания кода, но для большего понимания советую ознакомиться с этим ресурсом.
Для общения по USB на периферийном устройстве необходимо реализовать интерфейс взаимодействия. Разные функции (например, USB HID, USB Mass Strorage или USB CDC) будут реализовывать свои интерфейсы, а некоторые будут иметь несколько интерфейсов. Каждый интерфейс содержит в себе конечные точки — специальные каналы связи, своего рода буферы обмена.
На моем периферийном устройстве реализован Custom HID с одним интерфейсом и с двумя конечными точками, одной для приёма, другой для передачи. Обычно информация с существующими на устройстве интерфейсами и конечными точками написана в спецификации на устройство, в противном случае определить их можно через специальные программы, к примеру USBlyzer.
Устройства в USB HID общаются через репорты. Что такое репорты? Так как данные передаются через конечные точки, то нам надо как-то идентифицировать, а также распарсить в соответствие с протоколом. Устройства не просто кидают друг другу байты данных, а обмениваются пакетами, имеющими четко определенную структуру, которая описывается на устройстве в специальном дескрипторе репорта. Таким образом, по дескриптору репорта, мы можем точно определить, какой идентификатор, структуру, размер и частоту передачи имеют те или иные данные. Идентификация пакета происходит по первому байту, который представляет из себя ID репорта. Например данные о состоянии кнопки, идут в репорта с а светодиодом мы управляем через репорт с >
Подальше от железа, поближе к Android
В Android поддержка USB устройств появилась начиная с API версии 12 (Android 3.1) Для работы с периферийным устройством нам необходимо реализовать режим USB host. Работа с USB достаточно неплохо описана в документации.
Для начала необходимо идентифицировать ваше подключаемое устройство, среди всего разнообразия USB девайсов. USB девайсы идентифицируются по сочетанию vid (vendor id) и pid (product id). Создадим в папке xml файл device_filter.xml со следующим содержимым:
Теперь необходимо внести соответствующие разрешения и action (если вам они необходимы) в манифест приложения:
В android:resource мы указываем файл с необходимыми фильтрами для устройств. Также, как я уже говорил ранее, можно назначить intent фильтры, для запуска приложения, к примеру, в результате подключения вашего устройства.
Для начала необходимо получить UsbManager, найти устройство, интерфейс и конечные точки устройства. Это необходимо делать при каждом подключении устройства.
Здесь мы видим те самые интерфейсы и конечные точки, речь о которых шла в прошлом разделе. Зная номер интерфейса, мы находим обе конечные точки, на прием и передачу, и инициируем usb соединение. На этом все, теперь можно читать данные.
Как я уже говорил ранее, устройства общаются через репорты.
В метод sendReport мы передаем массив байт, в котором нулевым байтом является репорт ID, берем текущее USB подключение к устройству и выполняем передачу. В качестве параметров в метод BulkTransfer передаем номер конечной точки, данные, их размер и таймаут передачи. Стоит отметить, что класс UsbDeviceConnection имеет методы для реализации обмена данными с устройством USB — методы bulkTransfer и controlTransfer. Их использование зависит от типа передачи, который поддерживает та или иная конечная точка. В данном случае используем bulkTransfer, хотя для HID чаще всего характерно использование конечных точек с типом control. Но у нас Custom HID, так что делаем что хотим. Про тип передачи советую почитать отдельно, так как от него зависит объем и частота передаваемых данных.
Для получения данных необходимо знать размер получаемых данных, который можно, как знать заранее, так и получить из конечной точки.
Метод получения данных по USB HID является синхронным и блокирующим и выполнять его необходимо в другом потоке, кроме того, репорты от устройства могут приходить постоянно, либо в любое время, поэтому необходимо реализовать постоянный опрос репорта, чтобы не пропустить данные. Сделаем это при помощи RxJava:
Получив массив байт, мы должны проверить нулевой байт, так как он является report ID и в соответствии с ним парсить полученные данные.
По завершении всех действий с USB нужно закрыть соединение. Можно выполнять это в onDestroy activity или в onCleared во ViewModel.
Заключение
В статье рассмотрен очень небольшой и примитивный, исключительно демонстративный код с реализацией для конкретного устройства. Конечно, классов USB существует много, не только HID и для них естественно реализация будет иная. Однако все методы достаточно неплохо документированы и имея хорошее представление о USB стеке можно легко разобраться в том, как их применять.
Источник