Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions .github/workflows/usb_device_tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
name: USB device host tests

# Builds and runs the dependency-free unit tests of components/usb_device on the
# host with g++ -std=c++23: the X-Input report / descriptor helpers
# (test/xinput_host_test.cpp) and the Microsoft OS 2.0 descriptor set builder
# (test/ms_os_20_host_test.cpp). Runs whenever the component changes.

# Minimal token scope: build + run tests, never writes.
permissions:
contents: read

on:
pull_request:
paths:
- "components/usb_device/**"
- ".github/workflows/usb_device_tests.yml"
push:
branches:
- main
paths:
- "components/usb_device/**"
- ".github/workflows/usb_device_tests.yml"
workflow_dispatch:

concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true

jobs:
host-test:
name: C++ host tests (X-Input helpers, MS OS 2.0 descriptor set)
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v7
- name: Build and run the usb_device host tests
run: |
g++ --version | head -1
for t in xinput_host_test ms_os_20_host_test; do
g++ -std=c++23 -Wall -Wextra -Werror -I components/usb_device/include \
components/usb_device/test/$t.cpp -o $t
./$t
done
68 changes: 46 additions & 22 deletions components/usb_device/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,11 @@ Today it can enable, in any combination (subject to the endpoint budget):
controller** (served by a small custom TinyUSB application class driver built
into this component — no `CFG_TUD_*` count required). Gamepad state is sent with
`update_xinput_state()` (`include/xinput.hpp`), and rumble/LED reports arrive via an
`on_rumble` callback. Because a PC's XUSB driver only binds a recognized Xbox
360 VID/PID, and because the built-in vendor class also claims interface class
0xFF, **use X-Input as the only enabled function** (it then advertises the Xbox
identity + 0xFF/0xFF/0xFF device class so the host recognizes it). See the
`on_rumble` callback. On its own it advertises the Xbox 360 controller's
identity (0xFF/0xFF/0xFF device class) so a PC recognizes it; beside a WebUSB
vendor function it stays a composite device and is recognized through the
`XUSB10` compatible ID in the MS OS 2.0 descriptor (see
[Enabling X-Input](#enabling-x-input-xbox-360)). See the
[`xinput_example`](xinput_example/). *These are Microsoft's IDs, for emulation /
testing of your own device only.*
- An **MSC** (mass storage) function exposing an SD card and/or a FAT partition
Expand Down Expand Up @@ -226,24 +227,47 @@ the HID function is requested but `CFG_TUD_HID == 0`, `initialize()` fails with

X-Input needs **no** `CFG_TUD_*` count — it is served by a custom TinyUSB
application class driver built into this component (registered via the weak
`usbd_app_driver_get_cb`, forced into the link with `-u`). So an X-Input-only
project needs no CDC/vendor/HID class enabled at all; the
[`xinput_example`](xinput_example/) sdkconfig disables them:

```
CONFIG_TINYUSB_CDC_ENABLED=n
CONFIG_TINYUSB_CDC_COUNT=0
# vendor/HID counts default to 0 — importantly, keep CFG_TUD_VENDOR at 0 so the
# built-in bulk vendor driver does not claim the X-Input 0xFF interface.
```

Set `Config::xinput` (only — see the "only enabled function" note above), send
gamepad state with `update_xinput_state(GamepadState)`, and receive rumble/LED reports
via `XInputFunction::on_rumble`. The interface uses one interrupt-IN endpoint
(0x81, 20-byte input reports) and one interrupt-OUT endpoint (rumble/LED); the two
use **separate endpoint numbers**, and the DMA report buffers are word-aligned, as
the ESP32-S3 DWC2 requires. See `include/xinput.hpp` for the report/`GamepadState`
API and the button/axis layout.
`usbd_app_driver_get_cb`, forced into the link with `-u`). It only claims the
X-Input interface (class 0xFF / subclass 0x5D / protocol 0x01), so it coexists
with the built-in CDC, HID and vendor drivers when those are enabled.

Set `Config::xinput`, send gamepad state with `update_xinput_state(GamepadState)`,
and receive rumble/LED reports via `XInputFunction::on_rumble`. The interface uses
one interrupt-IN endpoint (0x81, 20-byte input reports) and one interrupt-OUT
endpoint (rumble/LED); the two use **separate endpoint numbers**, and the DMA
report buffers are word-aligned, as the ESP32-S3 DWC2 requires. See
`include/xinput.hpp` for the report/`GamepadState` API and the button/axis layout.

How a PC recognizes the controller depends on what else the device carries:

- **X-Input only** (the [`xinput_example`](xinput_example/) default): the device
takes the Xbox 360 controller's own identity (`XInputFunction::vid` / `pid`,
Microsoft's `0x045E:0x028E` by default, and a 0xFF/0xFF/0xFF device class).
Windows' Xbox driver and Linux's xpad match it directly. No other class driver
is needed, and the example's sdkconfig leaves CDC off:

```
CONFIG_TINYUSB_CDC_ENABLED=n
CONFIG_TINYUSB_CDC_COUNT=0
```

- **X-Input beside a WebUSB vendor function** (a controller with a configuration
console, say; the example's `sdkconfig.composite` variant): the device keeps the
normal composite identity (`Config::vid` / `pid`, 0x00 device class), and the
Microsoft OS 2.0 descriptor that gives the vendor interface WinUSB also carries
the `XUSB10` compatible ID for the X-Input interface, which Windows' Xbox 360
driver matches (`USB\MS_COMP_XUSB10`, the same route the virtual-controller
drivers use). Set `Config::vid` to Microsoft's `0x045E` so Linux's xpad binds the
interface, and `Config::pid` to a product ID Windows' Xbox driver INF does **not**
list by hardware ID (the retail controllers' `0x028E`, `0x0719`, ... are): a
hardware-ID match takes the whole device and hides the vendor interface. The
descriptor set is built by `include/ms_os_20.hpp` (host-tested in
`test/ms_os_20_host_test.cpp`).

- X-Input beside other functions **without** the WebUSB vendor one: no MS OS 2.0
descriptor is served, so Windows does not bind it (Linux still does).

These identifiers are Microsoft's: emulation / testing of your own device only.

## Enabling mass storage (MSC)

Expand Down
166 changes: 166 additions & 0 deletions components/usb_device/include/ms_os_20.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
#pragma once

// Microsoft OS 2.0 descriptor set builder.
//
// Dependency-free and host-testable (no ESP-IDF / TinyUSB headers). Windows
// reads this descriptor set through a vendor request advertised in the BOS
// descriptor and uses it to bind drivers to interfaces without an INF: a
// function subset with the compatible ID "WINUSB" (plus a DeviceInterfaceGUIDs
// registry property) gives an interface WinUSB, which is what WebUSB needs; one
// with "XUSB10" gives an interface Windows' own Xbox 360 controller driver
// (xusb22.sys matches the compatible ID USB\MS_COMP_XUSB10), which is how an
// X-Input interface inside a COMPOSITE device gets recognized - the retail
// controller is matched by VID/PID instead, but that match claims the whole
// device and would hide the other interfaces.
//
// Layout (Microsoft OS 2.0 Descriptors Specification):
// set header (10)
// configuration subset header (8)
// function subset header (8) one per Function
// compatible ID feature (20)
// [registry property (132)] when the function wants the WinUSB GUID
//
// `espp::UsbDevice` builds the set from its enabled functions (see
// usb_device.cpp); `descriptor_set()` is the pure byte builder.

#include <array>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <span>
#include <string_view>
#include <vector>

namespace espp {
namespace ms_os_20 {

/// Descriptor types (wDescriptorType) of the MS OS 2.0 specification.
inline constexpr uint16_t kSetHeaderDescriptor = 0x00;
inline constexpr uint16_t kSubsetHeaderConfiguration = 0x01;
inline constexpr uint16_t kSubsetHeaderFunction = 0x02;
inline constexpr uint16_t kFeatureCompatibleId = 0x03;
inline constexpr uint16_t kFeatureRegProperty = 0x04;

/// dwWindowsVersion of the set header: Windows 8.1 (NTDDI_WINBLUE), the first
/// Windows that reads MS OS 2.0 descriptors.
inline constexpr uint32_t kWindowsVersion = 0x06030000;

/// Compatible IDs (8 bytes, NUL padded on the wire).
inline constexpr std::string_view kCompatibleIdWinUsb = "WINUSB";
inline constexpr std::string_view kCompatibleIdXusb10 =
"XUSB10"; ///< Xbox 360 controller (xusb22.sys)

/// The DeviceInterfaceGUIDs registry property the WinUSB function carries, the
/// GUID TinyUSB's webusb_serial example uses (WebUSB in Chromium does not care
/// which GUID it is, only that WinUSB is bound).
inline constexpr std::string_view kDeviceInterfaceGuid = "{975F44D9-0D08-43FD-8B3E-127CA8AFFF9D}";

inline constexpr size_t kSetHeaderLen = 10;
inline constexpr size_t kConfigurationSubsetHeaderLen = 8;
inline constexpr size_t kFunctionSubsetHeaderLen = 8;
inline constexpr size_t kCompatibleIdFeatureLen = 20;
/// Registry property feature: header (8: length, type, data type, name length)
/// + name "DeviceInterfaceGUIDs\0" as UTF-16 (42) + data length (2) + the GUID
/// + "\0\0" as a REG_MULTI_SZ in UTF-16 (80).
inline constexpr size_t kRegPropertyFeatureLen = 8 + 42 + 2 + 80; // 132

/// One function (interface) of the descriptor set.
struct Function {
uint8_t first_interface{0}; ///< bFirstInterface of the function subset
std::string_view compatible_id{}; ///< "WINUSB", "XUSB10", ... (at most 8 bytes)
bool device_interface_guid{false}; ///< add the DeviceInterfaceGUIDs registry property
};

/// Longest set the format can describe: every length field (the set's, the
/// configuration subset's, each function subset's) is 16 bits.
inline constexpr size_t kMaxSetLength = 0xFFFF;

/// Byte length descriptor_set() produces for these functions (not capped: compare
/// with kMaxSetLength to know whether descriptor_set() can build it).
inline constexpr size_t descriptor_set_length(std::span<const Function> functions) {
size_t n = kSetHeaderLen + kConfigurationSubsetHeaderLen;
for (const auto &f : functions) {
n += kFunctionSubsetHeaderLen + kCompatibleIdFeatureLen;
if (f.device_interface_guid)
n += kRegPropertyFeatureLen;
}
return n;
}

/// Build the MS OS 2.0 descriptor set for the given functions (in interface
/// order). An empty list yields a set with no function subsets, which Windows
/// accepts but which binds nothing. Returns an empty vector if the set would
/// not fit the format's 16-bit length fields (kMaxSetLength; thousands of
/// functions, so a caller error rather than a real device).
inline std::vector<uint8_t> descriptor_set(std::span<const Function> functions) {
std::vector<uint8_t> out;
const size_t total = descriptor_set_length(functions);
if (total > kMaxSetLength)
return out;
out.reserve(total);
Comment on lines +97 to +101

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added: descriptor_set() asserts that out.size() == descriptor_set_length(functions) before returning.

🤖 Generated with Claude Code

https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU

auto u16 = [&](uint16_t v) {
out.push_back(static_cast<uint8_t>(v & 0xFF));
out.push_back(static_cast<uint8_t>(v >> 8));
};
auto u32 = [&](uint32_t v) {
u16(static_cast<uint16_t>(v & 0xFFFF));
u16(static_cast<uint16_t>(v >> 16));
};
auto utf16 = [&](std::string_view s) {
for (char c : s) {
out.push_back(static_cast<uint8_t>(c));
out.push_back(0x00);
}
};

// set header
u16(static_cast<uint16_t>(kSetHeaderLen));
u16(kSetHeaderDescriptor);
u32(kWindowsVersion);
u16(static_cast<uint16_t>(total));
// configuration subset header: configuration 0, reserved, subset length
u16(static_cast<uint16_t>(kConfigurationSubsetHeaderLen));
u16(kSubsetHeaderConfiguration);
out.push_back(0x00);
out.push_back(0x00);
u16(static_cast<uint16_t>(total - kSetHeaderLen));
Comment on lines +117 to +127

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

descriptor_set() now refuses a set longer than kMaxSetLength (0xFFFF, the format's 16-bit length fields) and returns an empty vector; the per-subset lengths are at most 160 bytes by construction. The device treats an empty set as an initialization error with the computed size in the log. Host test added: an over-long list is refused, one just under the limit builds with consistent lengths.

🤖 Generated with Claude Code

https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU


for (const auto &f : functions) {
size_t subset_len = kFunctionSubsetHeaderLen + kCompatibleIdFeatureLen;
if (f.device_interface_guid)
subset_len += kRegPropertyFeatureLen;
// function subset header: first interface, reserved, subset length
u16(static_cast<uint16_t>(kFunctionSubsetHeaderLen));
u16(kSubsetHeaderFunction);
out.push_back(f.first_interface);
out.push_back(0x00);
u16(static_cast<uint16_t>(subset_len));
// compatible ID feature: 8-byte compatible ID + 8-byte sub-compatible ID,
// both NUL padded
u16(static_cast<uint16_t>(kCompatibleIdFeatureLen));
u16(kFeatureCompatibleId);
std::array<uint8_t, 16> ids{};
const size_t n = f.compatible_id.size() < 8 ? f.compatible_id.size() : 8;
std::memcpy(ids.data(), f.compatible_id.data(), n);
out.insert(out.end(), ids.begin(), ids.end());
if (f.device_interface_guid) {
// registry property feature: REG_MULTI_SZ (7) "DeviceInterfaceGUIDs"
u16(static_cast<uint16_t>(kRegPropertyFeatureLen));
u16(kFeatureRegProperty);
u16(0x0007); // wPropertyDataType: REG_MULTI_SZ
u16(0x002A); // wPropertyNameLength: 21 UTF-16 code units
utf16("DeviceInterfaceGUIDs");
u16(0x0000); // NUL terminator of the name
u16(0x0050); // wPropertyDataLength: 40 code units
utf16(kDeviceInterfaceGuid);
u16(0x0000); // string terminator
u16(0x0000); // multi-string terminator
}
}
assert(out.size() == total); // the length computation and the bytes agree
return out;
}

} // namespace ms_os_20
} // namespace espp
27 changes: 20 additions & 7 deletions components/usb_device/include/usb_device.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -194,13 +194,26 @@ class UsbDevice : public BaseComponent {
* small custom TinyUSB application class driver built into this component (no
* `CFG_TUD_*` count is required).
*
* A PC's XUSB driver only binds a device whose VID/PID is a recognized Xbox 360
* controller, so `vid` / `pid` default to Microsoft's identifiers
* (`0x045E:0x028E`) -- for emulation / testing of your own device only. When
* the XInput function is the ONLY enabled function these identifiers (and a
* 0xFF/0xFF/0xFF device class) override the top-level Config vid/pid so the
* host recognizes it; combine XInput with other functions only if you do not
* need XUSB to bind (the built-in vendor/WebUSB class also claims class 0xFF).
* How a PC recognizes it depends on what else the device carries:
*
* - X-Input as the ONLY function: the device takes the Xbox 360 controller's
* own identity (`vid` / `pid` below, Microsoft's `0x045E:0x028E` by default,
* and a 0xFF/0xFF/0xFF device class), which Windows' Xbox driver and Linux's
* xpad match directly. The top-level Config vid/pid are overridden.
* - X-Input BESIDE a WebUSB vendor function (a composite device with a
* console, say): the device keeps the composite identity (top-level Config
* vid/pid, 0x00 device class) and the MS OS 2.0 descriptor that gives the
* vendor interface WinUSB also carries the "XUSB10" compatible ID for the
* X-Input interface, which Windows' Xbox 360 driver matches
* (`USB\MS_COMP_XUSB10`). Set Config::vid to Microsoft's 0x045E so Linux's
* xpad binds the interface, and Config::pid to a product ID Windows' Xbox
* driver INF does NOT list by hardware ID (the retail controllers' 0x028E,
* 0x0719 ... are), else that driver takes the whole device and hides the
* vendor interface. `vid` / `pid` below are not used in this case.
* - X-Input beside other functions without the WebUSB vendor one: no MS OS
* 2.0 descriptor is served, so Windows does not bind it (Linux still does).
*
* These identifiers are Microsoft's: emulation / testing of your own device only.
*
* Consumes 1 interrupt IN + 1 interrupt OUT endpoint.
*/
Expand Down
Loading
Loading