diff --git a/.github/workflows/usb_device_tests.yml b/.github/workflows/usb_device_tests.yml new file mode 100644 index 0000000000..5229096140 --- /dev/null +++ b/.github/workflows/usb_device_tests.yml @@ -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 diff --git a/components/usb_device/README.md b/components/usb_device/README.md index 18e92e37af..dd08558bea 100644 --- a/components/usb_device/README.md +++ b/components/usb_device/README.md @@ -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 @@ -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) diff --git a/components/usb_device/include/ms_os_20.hpp b/components/usb_device/include/ms_os_20.hpp new file mode 100644 index 0000000000..9d74d49bcb --- /dev/null +++ b/components/usb_device/include/ms_os_20.hpp @@ -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 +#include +#include +#include +#include +#include +#include +#include + +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 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 descriptor_set(std::span functions) { + std::vector out; + const size_t total = descriptor_set_length(functions); + if (total > kMaxSetLength) + return out; + out.reserve(total); + auto u16 = [&](uint16_t v) { + out.push_back(static_cast(v & 0xFF)); + out.push_back(static_cast(v >> 8)); + }; + auto u32 = [&](uint32_t v) { + u16(static_cast(v & 0xFFFF)); + u16(static_cast(v >> 16)); + }; + auto utf16 = [&](std::string_view s) { + for (char c : s) { + out.push_back(static_cast(c)); + out.push_back(0x00); + } + }; + + // set header + u16(static_cast(kSetHeaderLen)); + u16(kSetHeaderDescriptor); + u32(kWindowsVersion); + u16(static_cast(total)); + // configuration subset header: configuration 0, reserved, subset length + u16(static_cast(kConfigurationSubsetHeaderLen)); + u16(kSubsetHeaderConfiguration); + out.push_back(0x00); + out.push_back(0x00); + u16(static_cast(total - kSetHeaderLen)); + + 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(kFunctionSubsetHeaderLen)); + u16(kSubsetHeaderFunction); + out.push_back(f.first_interface); + out.push_back(0x00); + u16(static_cast(subset_len)); + // compatible ID feature: 8-byte compatible ID + 8-byte sub-compatible ID, + // both NUL padded + u16(static_cast(kCompatibleIdFeatureLen)); + u16(kFeatureCompatibleId); + std::array 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(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 diff --git a/components/usb_device/include/usb_device.hpp b/components/usb_device/include/usb_device.hpp index 77d8dc0e14..1c064fa51e 100644 --- a/components/usb_device/include/usb_device.hpp +++ b/components/usb_device/include/usb_device.hpp @@ -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. */ diff --git a/components/usb_device/src/usb_device.cpp b/components/usb_device/src/usb_device.cpp index 2c99d8ebea..729e5010ae 100644 --- a/components/usb_device/src/usb_device.cpp +++ b/components/usb_device/src/usb_device.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include "sdkconfig.h" // CONFIG_ESP_CONSOLE_UART_NUM for the console-tee path @@ -50,6 +51,7 @@ #include "wear_levelling.h" #endif +#include "ms_os_20.hpp" #include "xinput.hpp" namespace espp { @@ -210,10 +212,6 @@ constexpr uint8_t kMaxOutEndpoints = 5; // each type (its SD card and wear-levelling media are singletons). constexpr size_t kMaxMscLuns = 2; -// The MS OS 2.0 descriptor set length used below (fixed by the registry-property -// payload; identical to TinyUSB's webusb_serial example). -constexpr uint16_t kMsOs20DescLen = 0xB2; - // Handle of the task that runs tud_task() (created inside esp_tinyusb's // tinyusb_driver_install(); esp_tinyusb does not expose it). Every TinyUSB // class/descriptor callback below runs on that task, so each one records the @@ -1315,177 +1313,35 @@ bool UsbDevice::initialize(std::error_code &ec) { impl_->webusb_url_desc.insert(impl_->webusb_url_desc.end(), v.landing_page_url.begin(), v.landing_page_url.end()); - // MS OS 2.0 descriptor set (identical layout to TinyUSB's webusb example, with - // the function-subset "first interface" byte set to our vendor interface). - const uint8_t ms_os_20[] = { - // Set header: length, type, windows version, total length - U16_TO_U8S_LE(0x000A), - U16_TO_U8S_LE(MS_OS_20_SET_HEADER_DESCRIPTOR), - U32_TO_U8S_LE(0x06030000), - U16_TO_U8S_LE(kMsOs20DescLen), - // Configuration subset header: length, type, config index, reserved, total length - U16_TO_U8S_LE(0x0008), - U16_TO_U8S_LE(MS_OS_20_SUBSET_HEADER_CONFIGURATION), - 0, - 0, - U16_TO_U8S_LE(kMsOs20DescLen - 0x0A), - // Function subset header: length, type, first interface, reserved, subset length - U16_TO_U8S_LE(0x0008), - U16_TO_U8S_LE(MS_OS_20_SUBSET_HEADER_FUNCTION), - vendor_itf, - 0, - U16_TO_U8S_LE(kMsOs20DescLen - 0x0A - 0x08), - // MS OS 2.0 compatible ID: length, type, compatible ID, sub compatible ID - U16_TO_U8S_LE(0x0014), - U16_TO_U8S_LE(MS_OS_20_FEATURE_COMPATBLE_ID), - 'W', - 'I', - 'N', - 'U', - 'S', - 'B', - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - // MS OS 2.0 registry property: length, type - U16_TO_U8S_LE(kMsOs20DescLen - 0x0A - 0x08 - 0x08 - 0x14), - U16_TO_U8S_LE(MS_OS_20_FEATURE_REG_PROPERTY), - U16_TO_U8S_LE(0x0007), - U16_TO_U8S_LE(0x002A), - 'D', - 0x00, - 'e', - 0x00, - 'v', - 0x00, - 'i', - 0x00, - 'c', - 0x00, - 'e', - 0x00, - 'I', - 0x00, - 'n', - 0x00, - 't', - 0x00, - 'e', - 0x00, - 'r', - 0x00, - 'f', - 0x00, - 'a', - 0x00, - 'c', - 0x00, - 'e', - 0x00, - 'G', - 0x00, - 'U', - 0x00, - 'I', - 0x00, - 'D', - 0x00, - 's', - 0x00, - 0x00, - 0x00, - U16_TO_U8S_LE(0x0050), - // bPropertyData: "{975F44D9-0D08-43FD-8B3E-127CA8AFFF9D}" - '{', - 0x00, - '9', - 0x00, - '7', - 0x00, - '5', - 0x00, - 'F', - 0x00, - '4', - 0x00, - '4', - 0x00, - 'D', - 0x00, - '9', - 0x00, - '-', - 0x00, - '0', - 0x00, - 'D', - 0x00, - '0', - 0x00, - '8', - 0x00, - '-', - 0x00, - '4', - 0x00, - '3', - 0x00, - 'F', - 0x00, - 'D', - 0x00, - '-', - 0x00, - '8', - 0x00, - 'B', - 0x00, - '3', - 0x00, - 'E', - 0x00, - '-', - 0x00, - '1', - 0x00, - '2', - 0x00, - '7', - 0x00, - 'C', - 0x00, - 'A', - 0x00, - '8', - 0x00, - 'A', - 0x00, - 'F', - 0x00, - 'F', - 0x00, - 'F', - 0x00, - '9', - 0x00, - 'D', - 0x00, - '}', - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - }; - static_assert(sizeof(ms_os_20) == kMsOs20DescLen, "MS OS 2.0 descriptor size mismatch"); - impl_->ms_os_20_desc.assign(ms_os_20, ms_os_20 + sizeof(ms_os_20)); + // MS OS 2.0 descriptor set: one function subset per interface Windows must + // bind a driver to without an INF. The vendor interface gets WinUSB (plus + // the DeviceInterfaceGUIDs property), which is what WebUSB needs; an X-Input + // interface gets "XUSB10", the compatible ID Windows' own Xbox 360 driver + // matches, so a composite device (X-Input beside this vendor interface) is + // recognized as a controller too - the retail controller's VID/PID match + // would claim the whole device and hide the vendor interface. + std::vector ms_functions; + ms_functions.push_back({.first_interface = vendor_itf, + .compatible_id = espp::ms_os_20::kCompatibleIdWinUsb, + .device_interface_guid = true}); + if (config_.xinput) { + ms_functions.push_back( + {.first_interface = xinput_itf, .compatible_id = espp::ms_os_20::kCompatibleIdXusb10}); + } + impl_->ms_os_20_desc = espp::ms_os_20::descriptor_set( + std::span(ms_functions.data(), ms_functions.size())); + // The builder returns nothing if the set would not fit the format's 16-bit + // length fields (the BOS capability carries the same length); a few hundred + // bytes here, so this is a guard, not an expected path. + if (impl_->ms_os_20_desc.empty()) { + logger_.error("MS OS 2.0 descriptor set too long ({} bytes); max {}", + espp::ms_os_20::descriptor_set_length(std::span( + ms_functions.data(), ms_functions.size())), + espp::ms_os_20::kMaxSetLength); + ec = std::make_error_code(std::errc::invalid_argument); + return false; + } + const auto ms_os_20_len = static_cast(impl_->ms_os_20_desc.size()); // BOS descriptor: WebUSB + MS OS 2.0 platform capabilities. const uint16_t bos_total = @@ -1493,7 +1349,7 @@ bool UsbDevice::initialize(std::error_code &ec) { const uint8_t bos[] = { TUD_BOS_DESCRIPTOR(bos_total, 2), TUD_BOS_WEBUSB_DESCRIPTOR(v.webusb_vendor_code, 1), - TUD_BOS_MS_OS_20_DESCRIPTOR(kMsOs20DescLen, v.ms_os_vendor_code), + TUD_BOS_MS_OS_20_DESCRIPTOR(ms_os_20_len, v.ms_os_vendor_code), }; impl_->bos_desc.assign(bos, bos + sizeof(bos)); } @@ -2223,7 +2079,10 @@ bool UsbDevice::is_xinput_ready() const { if (!initialized_ || !config_.xinput) return false; // Fixed at initialize(), immutable after; tud_mounted() implies the class - // driver has opened this interface's endpoints (it is the only function). + // driver has opened this interface's endpoints (alone or in a composite + // device). A busy IN endpoint means the host has not taken the last report: + // no X-Input driver is polling it (macOS has none), so the state is "not + // ready" until one does. const uint8_t ep_in = impl_->xinput_ep_in; return tud_mounted() && ep_in != 0 && !usbd_edpt_busy(0, ep_in); } diff --git a/components/usb_device/test/ms_os_20_host_test.cpp b/components/usb_device/test/ms_os_20_host_test.cpp new file mode 100644 index 0000000000..58afa80377 --- /dev/null +++ b/components/usb_device/test/ms_os_20_host_test.cpp @@ -0,0 +1,192 @@ +// Host-buildable unit test for the Microsoft OS 2.0 descriptor set builder in +// include/ms_os_20.hpp. No ESP-IDF / TinyUSB headers required. +// +/* Build & run (a block comment so the line-continuation doesn't trip -Wcomment): + c++ -std=c++23 -Wall -Wextra -Werror -I components/usb_device/include \ + components/usb_device/test/ms_os_20_host_test.cpp -o test && ./test */ + +#include +#include +#include +#include +#include + +#include "ms_os_20.hpp" + +using namespace espp::ms_os_20; + +static int g_failures = 0; +#define CHECK(cond) \ + do { \ + if (!(cond)) { \ + std::printf("FAIL (%s:%d): %s\n", __FILE__, __LINE__, #cond); \ + ++g_failures; \ + } \ + } while (0) + +static uint16_t rd16(const std::vector &d, size_t i) { + return static_cast(d[i] | (d[i + 1] << 8)); +} +static uint32_t rd32(const std::vector &d, size_t i) { + return static_cast(rd16(d, i) | (static_cast(rd16(d, i + 2)) << 16)); +} +static std::string ascii(const std::vector &d, size_t i, size_t n) { + std::string s; + for (size_t k = 0; k < n && d[i + k] != 0; ++k) + s.push_back(static_cast(d[i + k])); + return s; +} +static std::string utf16(const std::vector &d, size_t i, size_t units) { + std::string s; + for (size_t k = 0; k < units; ++k) { + const uint16_t c = rd16(d, i + 2 * k); + if (c == 0) + break; + s.push_back(static_cast(c)); + } + return s; +} + +// Walk a built set and check every length field against the bytes. +static void check_structure(const std::vector &d, size_t expected_functions) { + CHECK(rd16(d, 0) == kSetHeaderLen); + CHECK(rd16(d, 2) == kSetHeaderDescriptor); + CHECK(rd32(d, 4) == kWindowsVersion); + CHECK(rd16(d, 8) == d.size()); + size_t i = kSetHeaderLen; + CHECK(rd16(d, i) == kConfigurationSubsetHeaderLen); + CHECK(rd16(d, i + 2) == kSubsetHeaderConfiguration); + CHECK(d[i + 4] == 0 && d[i + 5] == 0); + CHECK(rd16(d, i + 6) == d.size() - kSetHeaderLen); + i += kConfigurationSubsetHeaderLen; + size_t functions = 0; + while (i < d.size()) { + CHECK(rd16(d, i) == kFunctionSubsetHeaderLen); + CHECK(rd16(d, i + 2) == kSubsetHeaderFunction); + const size_t subset_len = rd16(d, i + 6); + const size_t subset_end = i + subset_len; + CHECK(subset_end <= d.size()); + if (subset_len < kFunctionSubsetHeaderLen || subset_end > d.size()) + break; // a short or runaway subset would never advance + size_t j = i + kFunctionSubsetHeaderLen; + bool saw_compat = false; + while (j < subset_end) { + const size_t len = rd16(d, j); + const uint16_t type = rd16(d, j + 2); + CHECK(len > 0 && j + len <= subset_end); + if (len == 0) + break; // a zero length would never advance + if (type == kFeatureCompatibleId) { + CHECK(len == kCompatibleIdFeatureLen); + saw_compat = true; + } else { + CHECK(type == kFeatureRegProperty && len == kRegPropertyFeatureLen); + } + j += len; + } + CHECK(j == subset_end); + CHECK(saw_compat); + i = subset_end; + ++functions; + } + CHECK(i == d.size()); + CHECK(functions == expected_functions); +} + +int main() { + // --- WinUSB only: the set TinyUSB's webusb_serial example ships (0xB2 bytes) --- + { + const Function fns[] = {{.first_interface = 2, + .compatible_id = kCompatibleIdWinUsb, + .device_interface_guid = true}}; + const auto d = descriptor_set(fns); + CHECK(d.size() == 0xB2); + CHECK(descriptor_set_length(fns) == 0xB2); + check_structure(d, 1); + const size_t fn = kSetHeaderLen + kConfigurationSubsetHeaderLen; + CHECK(d[fn + 4] == 2); // bFirstInterface + CHECK(rd16(d, fn + 6) == 0xB2 - 0x0A - 0x08); + const size_t compat = fn + kFunctionSubsetHeaderLen; + CHECK(ascii(d, compat + 4, 8) == "WINUSB"); + CHECK(ascii(d, compat + 12, 8).empty()); // sub-compatible ID blank + const size_t prop = compat + kCompatibleIdFeatureLen; + CHECK(rd16(d, prop) == kRegPropertyFeatureLen); + CHECK(rd16(d, prop + 2) == kFeatureRegProperty); + CHECK(rd16(d, prop + 4) == 7); // REG_MULTI_SZ + CHECK(rd16(d, prop + 6) == 0x2A); // name length + CHECK(utf16(d, prop + 8, 21) == "DeviceInterfaceGUIDs"); + CHECK(rd16(d, prop + 8 + 0x2A) == 0x50); // data length + CHECK(utf16(d, prop + 8 + 0x2A + 2, 40) == std::string(kDeviceInterfaceGuid)); + // the REG_MULTI_SZ ends with two UTF-16 NULs + CHECK(rd16(d, d.size() - 4) == 0 && rd16(d, d.size() - 2) == 0); + } + + // --- WinUSB (interface 0) + X-Input (interface 1): a composite controller --- + { + const Function fns[] = { + {.first_interface = 0, .compatible_id = kCompatibleIdWinUsb, .device_interface_guid = true}, + {.first_interface = 1, .compatible_id = kCompatibleIdXusb10}, + }; + const auto d = descriptor_set(fns); + CHECK(d.size() == 0xB2 + kFunctionSubsetHeaderLen + kCompatibleIdFeatureLen); + check_structure(d, 2); + const size_t fn2 = 0xB2; + CHECK(d[fn2 + 4] == 1); + CHECK(rd16(d, fn2 + 6) == kFunctionSubsetHeaderLen + kCompatibleIdFeatureLen); + CHECK(ascii(d, fn2 + kFunctionSubsetHeaderLen + 4, 8) == "XUSB10"); + } + + // --- too long for the 16-bit length fields: refused, not truncated --- + { + std::vector many( + kMaxSetLength / (kFunctionSubsetHeaderLen + kCompatibleIdFeatureLen) + 1, + Function{.first_interface = 0, .compatible_id = kCompatibleIdXusb10}); + CHECK(descriptor_set_length(many) > kMaxSetLength); + CHECK(descriptor_set(many).empty()); + many.pop_back(); + many.pop_back(); + CHECK(descriptor_set_length(many) <= kMaxSetLength); + const auto d = descriptor_set(many); + CHECK(d.size() == descriptor_set_length(many)); + CHECK(rd16(d, 8) == d.size()); + } + + // --- the other order, and an X-Input function alone --- + { + const Function fns[] = { + {.first_interface = 0, .compatible_id = kCompatibleIdXusb10}, + {.first_interface = 1, .compatible_id = kCompatibleIdWinUsb, .device_interface_guid = true}, + }; + const auto d = descriptor_set(fns); + check_structure(d, 2); + CHECK(d[kSetHeaderLen + kConfigurationSubsetHeaderLen + 4] == 0); + const Function alone[] = {{.first_interface = 0, .compatible_id = kCompatibleIdXusb10}}; + const auto a = descriptor_set(alone); + CHECK(a.size() == kSetHeaderLen + kConfigurationSubsetHeaderLen + kFunctionSubsetHeaderLen + + kCompatibleIdFeatureLen); + check_structure(a, 1); + } + + // --- a compatible ID longer than 8 bytes is truncated, never overruns --- + { + const Function fns[] = {{.first_interface = 0, .compatible_id = "TOOLONGCOMPATID"}}; + const auto d = descriptor_set(fns); + check_structure(d, 1); + const size_t compat = kSetHeaderLen + kConfigurationSubsetHeaderLen + kFunctionSubsetHeaderLen; + CHECK(ascii(d, compat + 4, 8) == "TOOLONGC"); + } + + // --- no functions: just the two headers --- + { + const auto d = descriptor_set(std::span{}); + CHECK(d.size() == kSetHeaderLen + kConfigurationSubsetHeaderLen); + check_structure(d, 0); + } + + if (g_failures) { + std::printf("%d failure(s)\n", g_failures); + return 1; + } + std::printf("PASS\n"); + return 0; +} diff --git a/components/usb_device/xinput_example/README.md b/components/usb_device/xinput_example/README.md index 6388867bec..7bf7422cc9 100644 --- a/components/usb_device/xinput_example/README.md +++ b/components/usb_device/xinput_example/README.md @@ -50,5 +50,32 @@ usb.update_xinput_state(state); // send a 20-byte input repor See `components/usb_device/include/xinput.hpp` for the `GamepadState` / `Button` API and the report layout, and the component -[README](../README.md#enabling-x-input-xbox-360) for the constraints (X-Input must -be the only enabled function). +[README](../README.md#enabling-x-input-xbox-360) for how a PC recognizes the +controller in each configuration. + +## Composite variant: a WebUSB console beside the controller + +A device that is also something else, a controller with a browser-based +configuration console on a WebUSB vendor interface for instance, cannot present +the retail controller's identity: that identity (and a 0xFF device class) makes +Windows' Xbox driver take the whole device, hiding the other interface. The +`sdkconfig.composite` variant builds that case: + +```sh +idf.py -DSDKCONFIG_DEFAULTS="sdkconfig.defaults;sdkconfig.composite" -p flash monitor +``` + +It enables TinyUSB's built-in vendor class driver (the X-Input driver only +claims its own interface, so the two coexist) and `XINPUT_EXAMPLE_COMPOSITE`, +which adds a WebUSB vendor interface and gives the device Microsoft's vendor ID +with a product ID of its own (`XINPUT_EXAMPLE_COMPOSITE_PID`, 0x0E60 by default). +The device keeps the composite identity (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`). Linux's xpad matches the interface class under the +Microsoft vendor ID. + +The product ID must be one Windows' Xbox driver INF does **not** list by hardware +ID (the retail controllers' 0x028E, 0x0719, ... are), or that hardware-ID match +again takes the whole device. Still Microsoft's vendor ID: emulation / testing +of your own device only. diff --git a/components/usb_device/xinput_example/main/Kconfig.projbuild b/components/usb_device/xinput_example/main/Kconfig.projbuild new file mode 100644 index 0000000000..f13e15a674 --- /dev/null +++ b/components/usb_device/xinput_example/main/Kconfig.projbuild @@ -0,0 +1,31 @@ +menu "X-Input Example Configuration" + + config XINPUT_EXAMPLE_COMPOSITE + bool "Composite: add a WebUSB vendor interface beside the X-Input one" + default n + help + Off: X-Input is the only function, the device carries the Xbox 360 + controller's own identity (0x045E:0x028E, a 0xFF device class) and a + PC binds it as that controller. + + On: a WebUSB vendor interface is added (as a configuration console + would be), so the device is a composite one (0x00 device class). It + then advertises the "XUSB10" compatible ID for the X-Input interface + through the Microsoft OS 2.0 descriptor, which Windows' Xbox 360 + driver matches, and Linux's xpad matches the interface class under + the Microsoft vendor ID. Needs the built-in vendor class driver: + build with `-DSDKCONFIG_DEFAULTS="sdkconfig.defaults;sdkconfig.composite"`. + + config XINPUT_EXAMPLE_COMPOSITE_PID + hex "Composite product ID (under vendor ID 0x045E)" + depends on XINPUT_EXAMPLE_COMPOSITE + default 0x0E60 + help + Windows binds its Xbox 360 driver to the WHOLE device when the + device's VID:PID is one its driver INF lists by hardware ID (the + retail controllers: 0x028E, 0x0719, ...), which would hide the vendor + interface. A composite device therefore needs a product ID that INF + does not list; the vendor ID stays Microsoft's so Linux's xpad + recognizes the interface. Emulation / testing of your own device only. + +endmenu diff --git a/components/usb_device/xinput_example/main/xinput_example.cpp b/components/usb_device/xinput_example/main/xinput_example.cpp index bbaa6290a1..d9946bd92f 100644 --- a/components/usb_device/xinput_example/main/xinput_example.cpp +++ b/components/usb_device/xinput_example/main/xinput_example.cpp @@ -12,6 +12,8 @@ #include #include +#include "sdkconfig.h" + #include "logger.hpp" #include "usb_device.hpp" @@ -35,7 +37,26 @@ extern "C" void app_main(void) { else if (!data.empty() && data[0] == 0x01) // 0x01 = LED report logger.info("led pattern: {}", data.size() >= 3 ? data[2] : 0); }; +#if CONFIG_XINPUT_EXAMPLE_COMPOSITE + // Composite: the WebUSB vendor interface beside X-Input. The device then has + // the normal composite identity, so give it Microsoft's vendor ID (Linux's + // xpad binds on it) and a product ID Windows' Xbox driver INF does not list + // (else that driver takes the whole device); Windows binds X-Input through + // the "XUSB10" compatible ID usb_device puts in the MS OS 2.0 descriptor. + cfg.vid = espp::xinput::kDefaultVid; + cfg.pid = CONFIG_XINPUT_EXAMPLE_COMPOSITE_PID; + espp::UsbDevice::VendorFunction vendor; + vendor.interface_name = "espp XInput Console"; + vendor.webusb = true; + vendor.landing_page_url = "esp-cpp.github.io/espp/apps/"; + vendor.on_receive = [&](std::span data) { + logger.info("vendor rx: {} bytes", data.size()); + }; + cfg.vendor = vendor; + cfg.xinput = xinput; // X-Input + vendor: a composite controller with a console +#else cfg.xinput = xinput; // XInput is the ONLY function -> Xbox identity + XUSB bind +#endif espp::UsbDevice usb(cfg); std::error_code ec; @@ -44,7 +65,12 @@ extern "C" void app_main(void) { return; } +#if CONFIG_XINPUT_EXAMPLE_COMPOSITE + logger.info("Ready (composite). Connect to a PC; it should enumerate as an Xbox 360 " + "controller plus a WebUSB interface."); +#else logger.info("Ready. Connect to a PC; it should enumerate as an Xbox 360 controller."); +#endif // Demo input generator: sweep the sticks/triggers in a circle and step the // face buttons A/B/X/Y one at a time each second. diff --git a/components/usb_device/xinput_example/sdkconfig.composite b/components/usb_device/xinput_example/sdkconfig.composite new file mode 100644 index 0000000000..9cd04ae69e --- /dev/null +++ b/components/usb_device/xinput_example/sdkconfig.composite @@ -0,0 +1,7 @@ +# Composite variant: X-Input + a WebUSB vendor interface (see +# main/Kconfig.projbuild, XINPUT_EXAMPLE_COMPOSITE). The vendor interface needs +# TinyUSB's built-in vendor class driver, which the X-Input-only defaults leave +# out. Build with: +# idf.py -DSDKCONFIG_DEFAULTS="sdkconfig.defaults;sdkconfig.composite" build +CONFIG_XINPUT_EXAMPLE_COMPOSITE=y +CONFIG_TINYUSB_VENDOR_COUNT=1