diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 7b91445394..112a8a5345 100755 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -355,6 +355,8 @@ jobs: target: esp32c6 - path: 'components/switch_pro/example' target: esp32s3 + - path: 'components/switch_pro/host_example' + target: esp32s3 - path: 'components/sx126x/example' target: esp32s3 - path: 'components/system/example' @@ -428,6 +430,8 @@ jobs: target: esp32s3 - path: 'components/ws-s3-touch/example' target: esp32s3 + - path: 'components/xbox_host/example' + target: esp32s3 - path: 'components/xiao-esp32s3-sense/example' target: esp32s3 diff --git a/.github/workflows/upload_components.yml b/.github/workflows/upload_components.yml index 1338ad8897..74326433d0 100755 --- a/.github/workflows/upload_components.yml +++ b/.github/workflows/upload_components.yml @@ -213,7 +213,9 @@ jobs: components/ws-s3-geek components/ws-s3-lcd-1-47 components/ws-s3-touch + components/xbox_host components/xiao-esp32s3-sense + components/xinput namespace: "espp" # use old version if this isn't a release for testing version: ${{ github.event.release && github.event.release.tag_name || 'v0.20.2' }} diff --git a/components/bldc_haptics/example/CMakeLists.txt b/components/bldc_haptics/example/CMakeLists.txt index f958b4fd7a..0dd6a4411e 100644 --- a/components/bldc_haptics/example/CMakeLists.txt +++ b/components/bldc_haptics/example/CMakeLists.txt @@ -51,6 +51,7 @@ set(EXTRA_COMPONENT_DIRS "../../../components/task" "../../../components/timer" "../../../components/usb_device" + "../../../components/xinput" ) # With the component manager disabled (IDF_COMPONENT_MANAGER=0, e.g. in CI so the diff --git a/components/canopen/can_bridge_example/CMakeLists.txt b/components/canopen/can_bridge_example/CMakeLists.txt index 01887e2e66..c6eafc6278 100644 --- a/components/canopen/can_bridge_example/CMakeLists.txt +++ b/components/canopen/can_bridge_example/CMakeLists.txt @@ -33,6 +33,7 @@ set(EXTRA_COMPONENT_DIRS "../../../components/task" "../../../components/twai" "../../../components/usb_device" + "../../../components/xinput" ) # With the component manager disabled (IDF_COMPONENT_MANAGER=0, e.g. in CI so the diff --git a/components/canopen/can_bridge_example/main/idf_component.yml b/components/canopen/can_bridge_example/main/idf_component.yml new file mode 100644 index 0000000000..455628219d --- /dev/null +++ b/components/canopen/can_bridge_example/main/idf_component.yml @@ -0,0 +1,13 @@ +## IDF Component Manager Manifest File - example project overrides. +## +## This file only affects THIS example build, not any published component. +dependencies: + # espp/xinput (the X-Input wire format, which usb_device and xbox_host use) is + # published with the next espp release (it is in + # .github/workflows/upload_components.yml now); until then this example, which + # runs the component manager, would fail to resolve it from the registry. + # Point at the in-repo source, and delete this file once it is on the + # registry. + espp/xinput: + version: "*" + override_path: "../../../xinput" diff --git a/components/coredump/example/CMakeLists.txt b/components/coredump/example/CMakeLists.txt index 23a3ca9c0a..3bd1b3790f 100644 --- a/components/coredump/example/CMakeLists.txt +++ b/components/coredump/example/CMakeLists.txt @@ -29,6 +29,7 @@ set(EXTRA_COMPONENT_DIRS "../../../components/system" "../../../components/task" "../../../components/usb_device" + "../../../components/xinput" ) # With the component manager disabled (IDF_COMPONENT_MANAGER=0, e.g. in CI so the diff --git a/components/desktop/example/CMakeLists.txt b/components/desktop/example/CMakeLists.txt index ff7271d5ff..749af7db36 100644 --- a/components/desktop/example/CMakeLists.txt +++ b/components/desktop/example/CMakeLists.txt @@ -68,6 +68,7 @@ set(EXTRA_COMPONENT_DIRS "../../../components/system" "../../../components/task" "../../../components/usb_device" + "../../../components/xinput" "../../../components/wifi" ) diff --git a/components/gamepad_map/webapp_example/CMakeLists.txt b/components/gamepad_map/webapp_example/CMakeLists.txt index 47dc23aaa9..8a45b3489a 100644 --- a/components/gamepad_map/webapp_example/CMakeLists.txt +++ b/components/gamepad_map/webapp_example/CMakeLists.txt @@ -38,6 +38,7 @@ set(EXTRA_COMPONENT_DIRS "../../../components/system" "../../../components/task" "../../../components/usb_device" + "../../../components/xinput" ) # With the component manager disabled (IDF_COMPONENT_MANAGER=0, e.g. in CI so the diff --git a/components/hid-rp/include/hid-rp-rumble.hpp b/components/hid-rp/include/hid-rp-rumble.hpp index 93649305cf..0d4dfcac81 100644 --- a/components/hid-rp/include/hid-rp-rumble.hpp +++ b/components/hid-rp/include/hid-rp-rumble.hpp @@ -273,6 +273,35 @@ inline uint8_t switch_rumble_motor(std::span m) { } } // namespace detail +namespace detail { +// One motor's 4 bytes for a level (0..255): the amplitude code whose +// amplitude (switch_rumble_amplitude) is closest, in both bands, at the +// frequencies of the neutral packet (high band 320 Hz, low band 160 Hz). Level +// 0 is the neutral 00 01 40 40. +inline std::array switch_rumble_motor_bytes(uint8_t level) { + const float target = level / 255.0f; + int code = 0; + float best = target; // code 0: amplitude 0 + for (int c = 1; c <= 100; c++) { + const float err = std::fabs(switch_rumble_amplitude(c) - target); + if (err < best) { + best = err; + code = c; + } + } + return {0x00, static_cast((code << 1) | 0x01), + static_cast(0x40 | ((code & 1) << 7)), static_cast(0x40 + (code >> 1))}; +} +} // namespace detail + +/// The 8-byte rumble packet a host sends a Switch controller for two motor +/// levels (the inverse of decode_switch_rumble(), to within a level's rounding). +inline std::array encode_switch_rumble(const SwitchRumble &rumble) { + const auto l = detail::switch_rumble_motor_bytes(rumble.left); + const auto r = detail::switch_rumble_motor_bytes(rumble.right); + return {l[0], l[1], l[2], l[3], r[0], r[1], r[2], r[3]}; +} + /// The motor levels in an 8-byte Switch rumble packet (left motor's 4 bytes, /// then the right's). The neutral packet (00 01 40 40 per motor) is 0 / 0. inline SwitchRumble decode_switch_rumble(std::span data) { diff --git a/components/hid-rp/test/hid_rp_rumble_host_test.cpp b/components/hid-rp/test/hid_rp_rumble_host_test.cpp index f7cac4bf5b..c1b04d4a05 100644 --- a/components/hid-rp/test/hid_rp_rumble_host_test.cpp +++ b/components/hid-rp/test/hid_rp_rumble_host_test.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include @@ -204,3 +205,22 @@ TEST_CASE("switch rumble") { const uint8_t short_report[9] = {0x10, 0x00, 0x00, 0x01, 0x40, 0x40, 0x00, 0x01, 0x40}; CHECK(!decode_switch_rumble_report(short_report).has_value()); } + +TEST_CASE("a host's Switch rumble packets decode back to their levels") { + using espp::hid_rp::SwitchRumble; + // off is the neutral packet + CHECK(espp::hid_rp::encode_switch_rumble(SwitchRumble{}) == + std::array{0x00, 0x01, 0x40, 0x40, 0x00, 0x01, 0x40, 0x40}); + // every level comes back within the encoding's step + for (int left = 0; left <= 255; left += 5) { + const SwitchRumble r{static_cast(left), static_cast(255 - left)}; + const auto packet = espp::hid_rp::encode_switch_rumble(r); + const auto back = espp::hid_rp::decode_switch_rumble(packet); + CHECK(std::abs(back.left - r.left) <= 12); + CHECK(std::abs(back.right - r.right) <= 12); + } + // full strength stays at (not beyond) the table's top code, 100 + const auto full = espp::hid_rp::encode_switch_rumble(SwitchRumble{255, 255}); + CHECK((full[1] >> 1) <= 100); + CHECK(espp::hid_rp::decode_switch_rumble(full) == SwitchRumble{255, 255}); +} diff --git a/components/mcp266/webapp_example/CMakeLists.txt b/components/mcp266/webapp_example/CMakeLists.txt index 3c867c9c0e..e2f5915ece 100644 --- a/components/mcp266/webapp_example/CMakeLists.txt +++ b/components/mcp266/webapp_example/CMakeLists.txt @@ -35,6 +35,7 @@ set(EXTRA_COMPONENT_DIRS "../../../components/task" "../../../components/twai" "../../../components/usb_device" + "../../../components/xinput" ) # With the component manager disabled (IDF_COMPONENT_MANAGER=0, e.g. in CI so the diff --git a/components/odrive_native/usb_example/CMakeLists.txt b/components/odrive_native/usb_example/CMakeLists.txt index 4f3120ee11..a2c32cf611 100644 --- a/components/odrive_native/usb_example/CMakeLists.txt +++ b/components/odrive_native/usb_example/CMakeLists.txt @@ -21,6 +21,7 @@ set(EXTRA_COMPONENT_DIRS "../../../components/odrive_ascii" "../../../components/odrive_native" "../../../components/usb_device" + "../../../components/xinput" ) set( diff --git a/components/odrive_native/usb_example/main/idf_component.yml b/components/odrive_native/usb_example/main/idf_component.yml new file mode 100644 index 0000000000..455628219d --- /dev/null +++ b/components/odrive_native/usb_example/main/idf_component.yml @@ -0,0 +1,13 @@ +## IDF Component Manager Manifest File - example project overrides. +## +## This file only affects THIS example build, not any published component. +dependencies: + # espp/xinput (the X-Input wire format, which usb_device and xbox_host use) is + # published with the next espp release (it is in + # .github/workflows/upload_components.yml now); until then this example, which + # runs the component manager, would fail to resolve it from the registry. + # Point at the in-repo source, and delete this file once it is on the + # registry. + espp/xinput: + version: "*" + override_path: "../../../xinput" diff --git a/components/ota/example/CMakeLists.txt b/components/ota/example/CMakeLists.txt index ac6a814e98..85a87dd55e 100644 --- a/components/ota/example/CMakeLists.txt +++ b/components/ota/example/CMakeLists.txt @@ -27,6 +27,7 @@ set(EXTRA_COMPONENT_DIRS "../../../components/system" "../../../components/task" "../../../components/usb_device" + "../../../components/xinput" "../../../components/wifi" ) diff --git a/components/switch_pro/CMakeLists.txt b/components/switch_pro/CMakeLists.txt index a239638a3c..5af06d0042 100644 --- a/components/switch_pro/CMakeLists.txt +++ b/components/switch_pro/CMakeLists.txt @@ -4,4 +4,5 @@ idf_component_register( # esp_hw_support (esp_mac.h / esp_random.h) and esp_timer (esp_timer.h) are # included by the PUBLIC switch_pro.hpp, so downstream consumers of that header # need their include paths -> public REQUIRES, not PRIV_REQUIRES. - REQUIRES base_component hid-rp timer esp_hw_support esp_timer) + # gamepad_map: GamepadState / RumbleState (switch_pro_host.hpp) + REQUIRES base_component gamepad_map hid-rp timer esp_hw_support esp_timer) diff --git a/components/switch_pro/README.md b/components/switch_pro/README.md index 05b8c94e2f..dfbea4245b 100644 --- a/components/switch_pro/README.md +++ b/components/switch_pro/README.md @@ -98,7 +98,56 @@ The example's `sdkconfig.defaults` enables the TinyUSB HID class keeps the console on UART0 (the native USB port is taken by the HID interface; see the `usb_device` docs on the shared ESP32-S3 USB PHY). +## Host side: `espp::SwitchProHost` + +`espp::SwitchProHost` (`switch_pro_host.hpp`) is the other end of the cable: it +reads a real Pro controller plugged into a USB **host** port. Over USB the Pro +controller is a HID device, but a generic HID gamepad decoder cannot read it: it +reports nothing useful until a host runs its handshake, and its full input +report (`0x30`) is vendor-defined. `SwitchProHost` runs that handshake and +decodes the reports into gamepad_map's `espp::GamepadState`: + +1. init commands (OUTPUT report `0x80`): device info, handshake, baud rate, + handshake, USB only (no Bluetooth timeout); +2. subcommands (OUTPUT report `0x01`): the full input report mode (`0x30`), the + stick calibration from the controller's SPI flash (factory at `0x603D`, then + the user calibration at `0x8010` when it has one), vibration on, and the + player lights; +3. then every `0x30` report is decoded with that calibration, and + `set_rumble()` (gamepad_map's `espp::RumbleState`) / `set_player()` drive the + motors and the lights. + +It is transport-light too: give it a function that sends an OUTPUT report +(`espp::UsbHost::HidDevice::send_output_report()` takes the same arguments), +feed it every INPUT report (`on_input_report()`, byte 0 the report ID), and call +`update()` every 10..50 ms while it starts: it resends a step whose reply is late +and skips one that is never answered (with typical values for a calibration it +could not read), so a controller that only partly follows the protocol still +ends up streaming input. A calibration that covers the whole 12-bit range, as +some third-party controllers that present themselves as a Pro controller store, +is also replaced by typical values, so their sticks still reach full deflection. + +```cpp +std::shared_ptr device = ...; // VID/PID 057E:2009 +espp::SwitchProHost pro({ + .send_report = [device](uint8_t id, std::span payload) { + std::error_code ec; + return device->send_output_report(id, payload, ec); + }, + .on_state = [](const espp::GamepadState &state) { /* ... */ }, + .player = 1, +}); +device->set_input_callback([&](std::span report) { pro.on_input_report(report); }); +pro.start(); +// ... and pro.update() from a timer every ~20 ms +``` + +The [host example](./host_example) does this with `espp::UsbHost` on an +ESP32-S3: it logs the controller's state and rumbles it with ZL / ZR. + ## Requirements - An ESP with the native USB-OTG peripheral (ESP32-S3 / S2 / P4). - espp `usb_device` (or another USB HID transport), `hid-rp`, `timer`. +- For the host side: espp `usb_host` (or another HID host transport) and + `gamepad_map` (`GamepadState` / `RumbleState`). diff --git a/components/switch_pro/example/CMakeLists.txt b/components/switch_pro/example/CMakeLists.txt index 7a1836b38f..6060163dfe 100644 --- a/components/switch_pro/example/CMakeLists.txt +++ b/components/switch_pro/example/CMakeLists.txt @@ -7,12 +7,18 @@ include($ENV{IDF_PATH}/tools/cmake/project.cmake) # add only the component directories that we want to use set(EXTRA_COMPONENT_DIRS "../../../components/base_component" + "../../../components/dispatcher" "../../../components/format" + "../../../components/gamepad_map" + "../../../components/persistent_data" + "../../../components/serialization" + "../../../components/stream_frame" "../../../components/logger" "../../../components/task" "../../../components/timer" "../../../components/hid-rp" "../../../components/usb_device" + "../../../components/xinput" "../../../components/switch_pro" ) diff --git a/components/switch_pro/example/main/idf_component.yml b/components/switch_pro/example/main/idf_component.yml new file mode 100644 index 0000000000..455628219d --- /dev/null +++ b/components/switch_pro/example/main/idf_component.yml @@ -0,0 +1,13 @@ +## IDF Component Manager Manifest File - example project overrides. +## +## This file only affects THIS example build, not any published component. +dependencies: + # espp/xinput (the X-Input wire format, which usb_device and xbox_host use) is + # published with the next espp release (it is in + # .github/workflows/upload_components.yml now); until then this example, which + # runs the component manager, would fail to resolve it from the registry. + # Point at the in-repo source, and delete this file once it is on the + # registry. + espp/xinput: + version: "*" + override_path: "../../../xinput" diff --git a/components/switch_pro/host_example/CMakeLists.txt b/components/switch_pro/host_example/CMakeLists.txt new file mode 100644 index 0000000000..097cda859f --- /dev/null +++ b/components/switch_pro/host_example/CMakeLists.txt @@ -0,0 +1,34 @@ +# The following lines of boilerplate have to be in your project's CMakeLists +# in this exact order for cmake to work correctly +cmake_minimum_required(VERSION 3.20) + +include($ENV{IDF_PATH}/tools/cmake/project.cmake) + +# espp's components, from this repository; the USB Host Library (`usb`) and +# the HID class driver espp::UsbHost uses come from the ESP Component Registry +set(EXTRA_COMPONENT_DIRS + "../../../components/base_component" + "../../../components/dispatcher" + "../../../components/format" + "../../../components/gamepad_map" + "../../../components/hid-rp" + "../../../components/logger" + "../../../components/persistent_data" + "../../../components/serialization" + "../../../components/stream_frame" + "../../../components/switch_pro" + "../../../components/task" + "../../../components/timer" + "../../../components/usb_host" +) + +set( + COMPONENTS + "main esptool_py switch_pro usb_host" + CACHE STRING + "List of components to include" + ) + +project(switch_pro_host_example) + +set(CMAKE_CXX_STANDARD 23) diff --git a/components/switch_pro/host_example/README.md b/components/switch_pro/host_example/README.md new file mode 100644 index 0000000000..20ed6d889d --- /dev/null +++ b/components/switch_pro/host_example/README.md @@ -0,0 +1,35 @@ +# Switch Pro Controller Host Example + +This example reads a Nintendo Switch Pro controller (NS1) plugged into the +ESP32-S3's native USB port in host mode. `espp::UsbHost` opens it as a HID +device, and `espp::SwitchProHost` runs the USB handshake that starts it, reads +its stick calibration, lights the player 1 LED, and decodes its input reports +into `espp::GamepadState`, which the example logs. The triggers rumble the +controller (ZL: the left grip, ZR: the right). + +## How to use the example + +### Hardware Required + +An ESP32-S3 (or -S2 / -P4) board whose native USB port can **source VBUS** to +the controller (a USB-A host port, or an OTG adapter with power), and a +Nintendo Switch Pro controller with a USB-C cable. On the ESP32-S3 the console +runs on UART0 (the native USB port is the host), so monitor it with a UART +adapter. + +### Build and Flash + +``` +idf.py -p PORT flash monitor +``` + +(To exit the serial monitor, type ``Ctrl-]``.) + +## Example Output + +``` +I (1234) Switch Pro Host: Starting the Switch Pro controller host example +I (2345) Switch Pro Host: Pro controller connected: 'Pro Controller' +I (2600) Switch Pro Host: Pro controller running +I (2700) Switch Pro Host: GamepadState{buttons: [east], left_x: 0, ...} +``` diff --git a/components/switch_pro/host_example/main/CMakeLists.txt b/components/switch_pro/host_example/main/CMakeLists.txt new file mode 100644 index 0000000000..3f3c8a8e80 --- /dev/null +++ b/components/switch_pro/host_example/main/CMakeLists.txt @@ -0,0 +1,5 @@ +idf_component_register( + SRC_DIRS "." + INCLUDE_DIRS "." + REQUIRES gamepad_map switch_pro timer usb_host +) diff --git a/components/switch_pro/host_example/main/switch_pro_host_example.cpp b/components/switch_pro/host_example/main/switch_pro_host_example.cpp new file mode 100644 index 0000000000..3cce48bb6a --- /dev/null +++ b/components/switch_pro/host_example/main/switch_pro_host_example.cpp @@ -0,0 +1,90 @@ +#include +#include +#include + +#include "gamepad_state_formatters.hpp" +#include "logger.hpp" +#include "switch_pro_host.hpp" +#include "timer.hpp" +#include "usb_host.hpp" + +using namespace std::chrono_literals; + +extern "C" void app_main(void) { + espp::Logger logger({.tag = "Switch Pro Host", .level = espp::Logger::Verbosity::INFO}); + logger.info("Starting the Switch Pro controller host example"); + + //! [switch_pro_host example] + // the Pro controller is a HID device: espp::UsbHost opens it and hands over + // its INPUT reports; SwitchProHost runs the handshake and decodes them + std::shared_ptr pad; + std::unique_ptr switch_pro; + std::mutex m; + + espp::UsbHost usb_host({ + .on_device_connected = + [&](const std::shared_ptr &device) { + const auto info = device->info(); + if (info.vid != espp::SwitchProHost::vid || info.pid != espp::SwitchProHost::pid) + return; + logger.info("Pro controller connected: '{}'", info.product); + std::lock_guard lk(m); + pad = device; + switch_pro = std::make_unique(espp::SwitchProHost::Config{ + .send_report = + [device](uint8_t report_id, std::span payload) { + std::error_code ec; + return device->send_output_report(report_id, payload, ec); + }, + .on_state = + [&](const espp::GamepadState &state) { + logger.info("{}", state); + // rumble with the triggers (ZL: the left grip, ZR: the right) + using A = espp::GamepadState::Axis; + using M = espp::RumbleState::Motor; + espp::RumbleState rumble; + rumble.set(M::Strong, state.axis(A::LeftTrigger) ? 160 : 0); + rumble.set(M::Weak, state.axis(A::RightTrigger) ? 160 : 0); + switch_pro->set_rumble(rumble); + }, + .on_ready = [&] { logger.info("Pro controller running"); }, + .player = 1, + .log_level = espp::Logger::Verbosity::INFO, + }); + device->set_input_callback([&](std::span report) { + std::lock_guard lk(m); + if (switch_pro) + switch_pro->on_input_report(report); + }); + switch_pro->start(); + }, + .on_device_disconnected = + [&](const std::shared_ptr &device) { + std::lock_guard lk(m); + if (device == pad) { + logger.info("Pro controller disconnected"); + switch_pro.reset(); + pad.reset(); + } + }, + .log_level = espp::Logger::Verbosity::WARN, + }); + std::error_code ec; + if (!usb_host.initialize(ec)) { + logger.error("Failed to initialize the USB host: {}", ec.message()); + return; + } + + // SwitchProHost resends a handshake step whose reply is late: tick it + espp::Timer ticker({.name = "switch_pro_host", .period = 20ms, .callback = [&]() { + std::lock_guard lk(m); + if (switch_pro) + switch_pro->update(); + return false; // keep running + }}); + //! [switch_pro_host example] + + while (true) { + std::this_thread::sleep_for(1s); + } +} diff --git a/components/switch_pro/host_example/sdkconfig.defaults b/components/switch_pro/host_example/sdkconfig.defaults new file mode 100644 index 0000000000..46c8c82593 --- /dev/null +++ b/components/switch_pro/host_example/sdkconfig.defaults @@ -0,0 +1,7 @@ +CONFIG_IDF_TARGET="esp32s3" +CONFIG_ESP_MAIN_TASK_STACK_SIZE=8192 +# The native USB-OTG port is used for the USB **host** role. On the ESP32-S3 the +# USB-Serial-JTAG shares that PHY, so the console runs on UART0 (with +# USB-Serial-JTAG as an early-boot secondary). Use a UART adapter to monitor. +CONFIG_ESP_CONSOLE_UART_DEFAULT=y +CONFIG_ESP_CONSOLE_SECONDARY_USB_SERIAL_JTAG=y diff --git a/components/switch_pro/idf_component.yml b/components/switch_pro/idf_component.yml index 1506079c03..668a9dd544 100644 --- a/components/switch_pro/idf_component.yml +++ b/components/switch_pro/idf_component.yml @@ -1,6 +1,6 @@ ## IDF Component Manager Manifest File license: "MIT" -description: "Nintendo Switch Pro (NS1) controller USB emulation protocol engine for ESP-IDF" +description: "Nintendo Switch Pro (NS1) controller over USB, both ends: a protocol engine that emulates the controller to a Switch, and one that reads a real controller on a USB host port (handshake, calibration, GamepadState, rumble)" url: "https://github.com/esp-cpp/espp/tree/main/components/switch_pro" repository: "git://github.com/esp-cpp/espp.git" maintainers: @@ -8,10 +8,12 @@ maintainers: documentation: "https://esp-cpp.github.io/espp/hid/switch_pro.html" examples: - path: example + - path: host_example tags: - cpp - Component - USB + - USB-Host - HID - Gamepad - Nintendo @@ -20,5 +22,7 @@ dependencies: idf: version: '>=5.0' espp/base_component: '>=1.0' + # GamepadState / RumbleState (SwitchProHost) + espp/gamepad_map: '>=1.4.6' espp/hid-rp: '>=1.0' espp/timer: '>=1.0' diff --git a/components/switch_pro/include/switch_pro_host.hpp b/components/switch_pro/include/switch_pro_host.hpp new file mode 100644 index 0000000000..f8b5632897 --- /dev/null +++ b/components/switch_pro/include/switch_pro_host.hpp @@ -0,0 +1,175 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "base_component.hpp" +#include "gamepad_state.hpp" +#include "rumble_state.hpp" + +namespace espp { +/** + * @brief The host side of a Nintendo Switch Pro controller (NS1) on USB: the + * handshake that starts it, its input decoded into gamepad_map's + * GamepadState, rumble and the player lights. + * + * @details The counterpart of espp::SwitchPro (which emulates a Pro controller + * to a Switch). Over USB the Pro controller is a HID device, but a + * generic HID gamepad decoder cannot read it: until a host sends the + * handshake it reports nothing useful, and its full input report + * (0x30) is vendor-defined. SwitchProHost runs that handshake: + * - init commands (OUTPUT report 0x80): device info, handshake, baud + * rate, handshake, USB only (no Bluetooth timeout); + * - subcommands (OUTPUT report 0x01): the full input report mode + * (0x30), the stick calibration from the controller's SPI flash + * (factory, then the user calibration when present), vibration on, + * and the player lights; + * and then decodes every 0x30 report with that calibration. + * + * Like SwitchPro it is transport-light: it does no USB I/O itself. + * Hand it a function that sends an OUTPUT report (e.g. via + * espp::UsbHost::HidDevice::send_output_report(), whose arguments it + * matches), feed it every INPUT report (on_input_report()), and call + * update() every 10..50 ms or so (it resends a step whose reply has not + * come). A step that never gets its reply is skipped after a few tries + * (the calibration falls back to typical values), so a controller that + * only partly follows the protocol still ends up streaming input. + * + * Thread safety: on_input_report(), update(), set_rumble() and + * set_player() may be called from different tasks; the callbacks run + * on the task that called on_input_report() or update(). + * + * \section switch_pro_host_ex1 Example + * \snippet switch_pro_host_example.cpp switch_pro_host example + */ +class SwitchProHost : public BaseComponent { +public: + /// Nintendo's USB VID / PID of the Pro controller (pick it out with these). + static constexpr uint16_t vid = 0x057E; + static constexpr uint16_t pid = 0x2009; + + /// Payload bytes of the controller's OUTPUT reports (after the report ID). + static constexpr size_t output_report_size = 63; + + /// Sends one OUTPUT report: @p report_id and the bytes after it. + using send_fn = std::function payload)>; + using state_fn = std::function; + + /// Where the handshake is. + enum class Stage : uint8_t { + Idle, ///< start() not called yet + DeviceInfo, ///< 0x80 0x01 + Handshake, ///< 0x80 0x02 + BaudRate, ///< 0x80 0x03 + Handshake2, ///< 0x80 0x02 again + UsbOnly, ///< 0x80 0x04 (moves on after reply_timeout if not answered) + InputMode, ///< subcommand 0x03 0x30 + FactoryCalibration, ///< subcommand 0x10: SPI 0x603D, 18 bytes + UserCalibration, ///< subcommand 0x10: SPI 0x8010, 22 bytes + Vibration, ///< subcommand 0x48 0x01 + PlayerLights, ///< subcommand 0x30 + Running, ///< streaming input + }; + + /// One stick's calibration, per axis, in the controller's 12-bit units. + struct StickCalibration { + struct Axis { + uint16_t center{2048}; + uint16_t above{1500}; ///< travel from the center to the top / right + uint16_t below{1500}; ///< travel from the center to the bottom / left + }; + Axis x{}; + Axis y{}; + }; + + /// Configuration. + struct Config { + send_fn send_report{nullptr}; ///< sends an OUTPUT report (required) + state_fn on_state{nullptr}; ///< the controller's state changed + std::function on_ready{nullptr}; ///< the handshake finished (Stage::Running) + int player{1}; ///< 1..4: which player lights to show (0 = none) + bool only_on_change{true}; ///< call on_state only when the state changes + std::chrono::milliseconds reply_timeout{std::chrono::milliseconds(150)}; + int max_tries{4}; ///< sends of a step before it is skipped + Logger::Verbosity log_level{Logger::Verbosity::WARN}; + }; + + /// @brief Construct it. Call start() once the controller is open. + explicit SwitchProHost(const Config &config); + + /// @brief Begin (or restart) the handshake. + void start(); + /// @brief Feed every INPUT report the controller sends (byte 0: the report ID). + void on_input_report(std::span report); + /// @brief Resend a step whose reply is late; call it every 10..50 ms. + void update(); + + /// @brief Where the handshake is. + Stage stage() const; + /// @brief Whether the handshake is done (input is streaming). + bool running() const { return stage() == Stage::Running; } + /// @brief The latest state. + GamepadState state() const; + /// @brief The stick calibration in use (factory, or the user's if it has one). + std::pair calibration() const; + + /// @brief Drive the rumble motors (strong: the left grip, weak: the right). + /// @return false if the report could not be sent. + bool set_rumble(const RumbleState &rumble); + /// @brief Show a player number on the lights (1..4, 0 = off). + /// @return false if the report could not be sent. + bool set_player(int player); + + // ---- the wire format (static, for tests and other transports) ----------- + + /// @brief A stick calibration from the controller's SPI flash: the left + /// stick's 9 bytes (max above center, center, min below center) or + /// the right stick's (center, min below center, max above center). + /// nullopt for an unprogrammed (all 0xFF) block. + static std::optional parse_calibration(std::span data, + bool left); + /// @brief One stick axis reading (12 bits) with its calibration, in + /// -GamepadState::AXIS_MAX..AXIS_MAX (right / up positive, as on the + /// wire); a reading past the calibrated travel is full deflection. + static int32_t normalize_axis(uint16_t raw, const StickCalibration::Axis &axis); + /// @brief The state in a full input report (0x30, byte 0 the report ID), or + /// nullopt for any other report. + static std::optional decode_input(std::span report, + const StickCalibration &left, + const StickCalibration &right); + +protected: + using clock = std::chrono::steady_clock; + void begin_stage(Stage stage); // sends its packet (with mutex_ held) + void next_stage(Stage after); // (with mutex_ held) + void send_stage_packet(); // (with mutex_ held) + bool send_init(uint8_t command); + bool send_subcommand(uint8_t id, std::span args); + bool send_spi_read(uint32_t address, uint8_t length); + void handle_reply(std::span report); // 0x81 / 0x21 + void finish(); // -> Running (with mutex_ held) + static uint8_t player_bits(int player); + + Config config_; + mutable std::mutex mutex_; + Stage stage_{Stage::Idle}; + clock::time_point sent_at_{}; + int tries_{0}; + uint8_t counter_{0}; // the packet number in reports 0x01 / 0x10 (0..15) + std::array rumble_{0x00, 0x01, 0x40, 0x40, 0x00, 0x01, 0x40, 0x40}; + StickCalibration left_cal_{}; + StickCalibration right_cal_{}; + const char *left_cal_source_{"typical"}; // "typical", "factory" or "user" + const char *right_cal_source_{"typical"}; + GamepadState state_{}; + bool have_state_{false}; + bool ready_pending_{false}; +}; +} // namespace espp diff --git a/components/switch_pro/src/switch_pro_host.cpp b/components/switch_pro/src/switch_pro_host.cpp new file mode 100644 index 0000000000..7a75d94ecd --- /dev/null +++ b/components/switch_pro/src/switch_pro_host.cpp @@ -0,0 +1,464 @@ +#include "switch_pro_host.hpp" + +#include +#include +#include + +#include "format.hpp" +#include "hid-rp-rumble.hpp" + +using namespace espp; + +namespace { +using Stage = SwitchProHost::Stage; + +constexpr uint8_t kInitReport = 0x80; // host -> controller: init commands +constexpr uint8_t kInitReplyReport = 0x81; // controller -> host: their replies +constexpr uint8_t kSubcommandReport = 0x01; // host -> controller: rumble + subcommand +constexpr uint8_t kRumbleReport = 0x10; // host -> controller: rumble only +constexpr uint8_t kReplyReport = 0x21; // controller -> host: input + subcommand reply +constexpr uint8_t kInputReport = 0x30; // controller -> host: full input + +constexpr uint32_t kFactoryStickCalibration = 0x603D; // left 9 bytes, right 9 bytes +constexpr uint32_t kUserStickCalibration = 0x8010; // magic B2 A1 + left 9, magic + right 9 + +const char *stage_name(Stage s) { + switch (s) { + case Stage::Idle: + return "idle"; + case Stage::DeviceInfo: + return "device info"; + case Stage::Handshake: + case Stage::Handshake2: + return "handshake"; + case Stage::BaudRate: + return "baud rate"; + case Stage::UsbOnly: + return "USB only"; + case Stage::InputMode: + return "input mode"; + case Stage::FactoryCalibration: + return "factory calibration"; + case Stage::UserCalibration: + return "user calibration"; + case Stage::Vibration: + return "vibration"; + case Stage::PlayerLights: + return "player lights"; + case Stage::Running: + return "running"; + } + return "?"; +} + +Stage stage_after(Stage s) { + switch (s) { + case Stage::DeviceInfo: + return Stage::Handshake; + case Stage::Handshake: + return Stage::BaudRate; + case Stage::BaudRate: + return Stage::Handshake2; + case Stage::Handshake2: + return Stage::UsbOnly; + case Stage::UsbOnly: + return Stage::InputMode; + case Stage::InputMode: + return Stage::FactoryCalibration; + case Stage::FactoryCalibration: + return Stage::UserCalibration; + case Stage::UserCalibration: + return Stage::Vibration; + case Stage::Vibration: + return Stage::PlayerLights; + default: + return Stage::Running; + } +} + +// Whether a calibration describes a real stick: its center near the middle +// and its travel well inside the 12-bit range. Some third-party controllers +// that present themselves as a Pro controller store the whole range (center +// 2048, travel 2047 / 2048), which would keep their sticks from ever reaching +// full deflection; they get the typical values instead. +bool plausible(const SwitchProHost::StickCalibration &c) { + auto ok = [](const SwitchProHost::StickCalibration::Axis &a) { + return a.center >= 1000 && a.center <= 3100 && a.above >= 500 && a.above <= 1900 && + a.below >= 500 && a.below <= 1900; + }; + return ok(c.x) && ok(c.y); +} + +bool same_state(const GamepadState &a, const GamepadState &b) { + return a.buttons == b.buttons && a.axes == b.axes; +} + +} // namespace + +int32_t SwitchProHost::normalize_axis(uint16_t raw, const StickCalibration::Axis &axis) { + const int32_t v = static_cast(raw) - axis.center; + const int32_t range = v >= 0 ? axis.above : axis.below; + if (range <= 0) + return 0; + // a reading past the calibrated travel (a worn stick, a calibration that + // does not quite reach the edge) is full deflection, not more + return std::clamp(v * GamepadState::AXIS_MAX / range, -GamepadState::AXIS_MAX, + GamepadState::AXIS_MAX); +} + +SwitchProHost::SwitchProHost(const Config &config) + : BaseComponent("SwitchProHost", config.log_level) + , config_(config) {} + +void SwitchProHost::start() { + std::lock_guard lk(mutex_); + have_state_ = false; + left_cal_ = right_cal_ = StickCalibration{}; + left_cal_source_ = right_cal_source_ = "typical"; + ready_pending_ = false; + begin_stage(Stage::DeviceInfo); +} + +SwitchProHost::Stage SwitchProHost::stage() const { + std::lock_guard lk(mutex_); + return stage_; +} + +GamepadState SwitchProHost::state() const { + std::lock_guard lk(mutex_); + return state_; +} + +std::pair +SwitchProHost::calibration() const { + std::lock_guard lk(mutex_); + return {left_cal_, right_cal_}; +} + +void SwitchProHost::begin_stage(Stage stage) { + logger_.debug("-> {}", stage_name(stage)); + stage_ = stage; + tries_ = 0; + if (stage == Stage::Running) { + finish(); + return; + } + send_stage_packet(); +} + +void SwitchProHost::next_stage(Stage after) { begin_stage(stage_after(after)); } + +void SwitchProHost::finish() { + stage_ = Stage::Running; + ready_pending_ = true; + logger_.info("running: stick calibration {} / {}, centers L ({}, {}) R ({}, {})", + left_cal_source_, right_cal_source_, left_cal_.x.center, left_cal_.y.center, + right_cal_.x.center, right_cal_.y.center); +} + +void SwitchProHost::send_stage_packet() { + tries_++; + sent_at_ = clock::now(); + switch (stage_) { + case Stage::DeviceInfo: + send_init(0x01); + break; + case Stage::Handshake: + case Stage::Handshake2: + send_init(0x02); + break; + case Stage::BaudRate: + send_init(0x03); + break; + case Stage::UsbOnly: + send_init(0x04); + break; + case Stage::InputMode: { + const uint8_t args[] = {kInputReport}; // the full input report + send_subcommand(0x03, args); + break; + } + case Stage::FactoryCalibration: + send_spi_read(kFactoryStickCalibration, 18); + break; + case Stage::UserCalibration: + send_spi_read(kUserStickCalibration, 22); + break; + case Stage::Vibration: { + const uint8_t args[] = {0x01}; + send_subcommand(0x48, args); + break; + } + case Stage::PlayerLights: { + const uint8_t args[] = {player_bits(config_.player)}; + send_subcommand(0x30, args); + break; + } + default: + break; + } +} + +bool SwitchProHost::send_init(uint8_t command) { + if (!config_.send_report) + return false; + std::array payload{}; + payload[0] = command; + return config_.send_report(kInitReport, payload); +} + +bool SwitchProHost::send_subcommand(uint8_t id, std::span args) { + if (!config_.send_report) + return false; + // [packet number][rumble (8)][subcommand][arguments...] + std::array payload{}; + payload[0] = counter_; + counter_ = static_cast((counter_ + 1) & 0x0F); + std::memcpy(&payload[1], rumble_.data(), rumble_.size()); + payload[9] = id; + const size_t n = std::min(args.size(), payload.size() - 10); + std::memcpy(&payload[10], args.data(), n); + return config_.send_report(kSubcommandReport, payload); +} + +bool SwitchProHost::send_spi_read(uint32_t address, uint8_t length) { + const uint8_t args[] = { + static_cast(address & 0xFF), static_cast((address >> 8) & 0xFF), + static_cast((address >> 16) & 0xFF), static_cast(address >> 24), length}; + return send_subcommand(0x10, args); +} + +uint8_t SwitchProHost::player_bits(int player) { + return player >= 1 && player <= 4 ? static_cast(1u << (player - 1)) : 0; +} + +void SwitchProHost::update() { + bool ready = false; + { + std::lock_guard lk(mutex_); + if (stage_ != Stage::Idle && stage_ != Stage::Running) { + // (USB only may have no reply: after its timeout it simply moves on) + if (clock::now() - sent_at_ >= config_.reply_timeout) { + if (stage_ == Stage::UsbOnly) { + next_stage(Stage::UsbOnly); + } else if (tries_ < config_.max_tries) { + send_stage_packet(); + } else { + logger_.warn("no reply to '{}' after {} tries: skipping it", stage_name(stage_), tries_); + next_stage(stage_); + } + } + } + ready = std::exchange(ready_pending_, false); + } + // (finish() sets ready_pending_ under the lock, which cppcheck does not follow) + // cppcheck-suppress knownConditionTrueFalse + if (ready && config_.on_ready) + config_.on_ready(); +} + +void SwitchProHost::on_input_report(std::span report) { + if (report.empty()) + return; + const uint8_t id = report[0]; + std::optional decoded; + bool publish = false; + bool ready = false; + { + std::lock_guard lk(mutex_); + if (id == kInitReplyReport || id == kReplyReport) + handle_reply(report); + if (id == kInputReport || id == kReplyReport) { + decoded = decode_input(report, left_cal_, right_cal_); + if (decoded) { + publish = !config_.only_on_change || !have_state_ || !same_state(*decoded, state_); + state_ = *decoded; + have_state_ = true; + } + } + ready = std::exchange(ready_pending_, false); + } + if (ready && config_.on_ready) + config_.on_ready(); + if (publish && config_.on_state) + config_.on_state(*decoded); +} + +void SwitchProHost::handle_reply(std::span report) { + if (report[0] == kInitReplyReport) { + if (report.size() < 2) + return; + const uint8_t command = report[1]; + const bool matches = + (stage_ == Stage::DeviceInfo && command == 0x01) || + ((stage_ == Stage::Handshake || stage_ == Stage::Handshake2) && command == 0x02) || + (stage_ == Stage::BaudRate && command == 0x03) || + (stage_ == Stage::UsbOnly && command == 0x04); + if (matches) + next_stage(stage_); + return; + } + // 0x21: [id][timer][battery][buttons (3)][sticks (6)][vibrator][ack][subcommand][data...] + if (report.size() < 15) + return; + const uint8_t subcommand = report[14]; + const auto data = report.subspan(15); + switch (stage_) { + case Stage::InputMode: + if (subcommand == 0x03) + next_stage(stage_); + break; + case Stage::FactoryCalibration: + case Stage::UserCalibration: { + // SPI read reply: [address (4, LE)][length][bytes...] + if (subcommand != 0x10 || data.size() < 5) + break; + const uint32_t address = + data[0] | (data[1] << 8) | (data[2] << 16) | (static_cast(data[3]) << 24); + const auto bytes = data.subspan(5); + { + // the bytes as hex, by hand: fmt's range formatter trips MSVC's + // unreachable-code warning (C4702) in fmt/ranges.h + static constexpr char kDigits[] = "0123456789abcdef"; + char hex[3 * 32 + 1] = {}; + size_t n = 0; + for (uint8_t b : bytes.first(std::min({bytes.size(), data[4], 32}))) { + hex[n++] = kDigits[b >> 4]; + hex[n++] = kDigits[b & 0x0F]; + hex[n++] = ' '; + } + logger_.debug("SPI {:#06x} ({} bytes, ack {:#04x}): {}", address, data[4], report[13], + std::string_view(hex, n)); + } + if (stage_ == Stage::FactoryCalibration && address == kFactoryStickCalibration && + bytes.size() >= 18) { + if (auto l = parse_calibration(bytes.subspan<0, 9>(), true); l && plausible(*l)) { + left_cal_ = *l; + left_cal_source_ = "factory"; + } + if (auto r = parse_calibration(bytes.subspan<9, 9>(), false); r && plausible(*r)) { + right_cal_ = *r; + right_cal_source_ = "factory"; + } + next_stage(stage_); + } else if (stage_ == Stage::UserCalibration && address == kUserStickCalibration && + bytes.size() >= 22) { + // each stick's user calibration is there only after its magic B2 A1 + if (bytes[0] == 0xB2 && bytes[1] == 0xA1) { + if (auto l = parse_calibration(bytes.subspan<2, 9>(), true); l && plausible(*l)) { + left_cal_ = *l; + left_cal_source_ = "user"; + } + } + if (bytes[11] == 0xB2 && bytes[12] == 0xA1) { + if (auto r = parse_calibration(bytes.subspan<13, 9>(), false); r && plausible(*r)) { + right_cal_ = *r; + right_cal_source_ = "user"; + } + } + next_stage(stage_); + } + break; + } + case Stage::Vibration: + if (subcommand == 0x48) + next_stage(stage_); + break; + case Stage::PlayerLights: + if (subcommand == 0x30) + next_stage(stage_); + break; + default: + break; + } +} + +bool SwitchProHost::set_rumble(const RumbleState &rumble) { + using M = RumbleState::Motor; + std::lock_guard lk(mutex_); + rumble_ = hid_rp::encode_switch_rumble({rumble.level(M::Strong), rumble.level(M::Weak)}); + if (!config_.send_report || stage_ != Stage::Running) + return false; + // [packet number][rumble (8)] + std::array payload{}; + payload[0] = counter_; + counter_ = static_cast((counter_ + 1) & 0x0F); + std::memcpy(&payload[1], rumble_.data(), rumble_.size()); + return config_.send_report(kRumbleReport, payload); +} + +bool SwitchProHost::set_player(int player) { + std::lock_guard lk(mutex_); + config_.player = player; + if (stage_ != Stage::Running) + return stage_ != Stage::Idle; // it is set as part of the handshake + const uint8_t args[] = {player_bits(player)}; + return send_subcommand(0x30, args); +} + +std::optional +SwitchProHost::parse_calibration(std::span d, bool left) { + if (std::all_of(d.begin(), d.end(), [](uint8_t b) { return b == 0xFF; })) + return std::nullopt; // not programmed + // three 12-bit (x, y) pairs + auto pair_at = [&](size_t i) { + const uint16_t x = static_cast(d[i] | ((d[i + 1] & 0x0F) << 8)); + const uint16_t y = static_cast((d[i + 1] >> 4) | (d[i + 2] << 4)); + return std::pair{x, y}; + }; + // left: above, center, below; right: center, below, above + const auto above = left ? pair_at(0) : pair_at(6); + const auto center = left ? pair_at(3) : pair_at(0); + const auto below = left ? pair_at(6) : pair_at(3); + StickCalibration c; + c.x = {center.first, above.first, below.first}; + c.y = {center.second, above.second, below.second}; + if (c.x.above == 0 || c.x.below == 0 || c.y.above == 0 || c.y.below == 0) + return std::nullopt; + return c; +} + +std::optional SwitchProHost::decode_input(std::span report, + const StickCalibration &left, + const StickCalibration &right) { + // [id][timer][battery][right buttons][shared buttons][left buttons][L stick (3)][R stick (3)] + if (report.size() < 12 || (report[0] != kInputReport && report[0] != kReplyReport)) + return std::nullopt; + using B = GamepadState::Button; + using A = GamepadState::Axis; + const uint8_t r = report[3]; + const uint8_t s = report[4]; + const uint8_t l = report[5]; + GamepadState g; + // Nintendo's labels, by position: B south, A east, Y west, X north + g.set(B::West, r & 0x01); // Y + g.set(B::North, r & 0x02); // X + g.set(B::South, r & 0x04); // B + g.set(B::East, r & 0x08); // A + g.set(B::R1, r & 0x40); // R + g.set(B::R2, r & 0x80); // ZR + g.set(B::Select, s & 0x01); // - + g.set(B::Start, s & 0x02); // + + g.set(B::R3, s & 0x04); + g.set(B::L3, s & 0x08); + g.set(B::Home, s & 0x10); + g.set(B::Capture, s & 0x20); + g.set(B::Down, l & 0x01); + g.set(B::Up, l & 0x02); + g.set(B::Right, l & 0x04); + g.set(B::Left, l & 0x08); + g.set(B::L1, l & 0x40); // L + g.set(B::L2, l & 0x80); // ZL + // the triggers are digital + g.set(A::LeftTrigger, (l & 0x80) ? GamepadState::AXIS_MAX : 0); + g.set(A::RightTrigger, (r & 0x80) ? GamepadState::AXIS_MAX : 0); + const uint16_t lx = static_cast(report[6] | ((report[7] & 0x0F) << 8)); + const uint16_t ly = static_cast((report[7] >> 4) | (report[8] << 4)); + const uint16_t rx = static_cast(report[9] | ((report[10] & 0x0F) << 8)); + const uint16_t ry = static_cast((report[10] >> 4) | (report[11] << 4)); + g.set(A::LeftX, normalize_axis(lx, left.x)); + g.set(A::LeftY, -normalize_axis(ly, left.y)); // up positive on the wire, down in GamepadState + g.set(A::RightX, normalize_axis(rx, right.x)); + g.set(A::RightY, -normalize_axis(ry, right.y)); + return g; +} diff --git a/components/switch_pro/test/CMakeLists.txt b/components/switch_pro/test/CMakeLists.txt new file mode 100644 index 0000000000..92a765f493 --- /dev/null +++ b/components/switch_pro/test/CMakeLists.txt @@ -0,0 +1,3 @@ +# Host tests of switch_pro (see test/EsppTest.cmake and test/README.md). +espp_add_component_test(switch_pro_host_test DOCTEST + SOURCES switch_pro_host_test.cpp ${ESPP_ROOT}/components/switch_pro/src/switch_pro_host.cpp) diff --git a/components/switch_pro/test/switch_pro_host_test.cpp b/components/switch_pro/test/switch_pro_host_test.cpp new file mode 100644 index 0000000000..dbb09b4bff --- /dev/null +++ b/components/switch_pro/test/switch_pro_host_test.cpp @@ -0,0 +1,283 @@ +// Host-buildable unit tests for espp::SwitchProHost: the USB handshake against +// a fake Pro controller, the stick calibration read from its SPI flash, input +// decoding, rumble and the player lights. No ESP-IDF headers required. +// +// From the repository root: +// ./run_host_tests.sh switch_pro_host_test + +#include +#include +#include +#include +#include + +#include + +#include "hid-rp-rumble.hpp" +#include "switch_pro_host.hpp" + +using espp::GamepadState; +using espp::SwitchProHost; +using B = GamepadState::Button; +using A = GamepadState::Axis; +using Stage = SwitchProHost::Stage; + +namespace { +// three 12-bit (x, y) pairs, as the SPI flash stores a calibration +std::array pack(uint16_t x, uint16_t y) { + return {static_cast(x & 0xFF), + static_cast(((x >> 8) & 0x0F) | ((y & 0x0F) << 4)), + static_cast(y >> 4)}; +} +void put(std::vector &v, std::array p) { + v.insert(v.end(), p.begin(), p.end()); +} + +// A fake controller: answers the init commands and subcommands it is sent. +struct FakeController { + std::vector> sent; // [report id, payload...] + std::vector> replies; + std::map> flash; + bool answer = true; + bool answer_device_info = true; + bool answer_usb_only = true; + + FakeController() { + // factory calibration at 0x603D: left (above, center, below), right (center, below, above) + std::vector factory; + put(factory, pack(1400, 1300)); // left: travel above the center + put(factory, pack(2000, 2100)); // left: center + put(factory, pack(1200, 1100)); // left: travel below + put(factory, pack(1900, 1950)); // right: center + put(factory, pack(1000, 1000)); // right: below + put(factory, pack(1500, 1500)); // right: above + flash[0x603D] = factory; + flash[0x8010] = std::vector(22, 0xFF); // no user calibration + } + + bool send(uint8_t id, std::span payload) { + std::vector report{id}; + report.insert(report.end(), payload.begin(), payload.end()); + sent.push_back(report); + if (!answer) + return true; + if (id == 0x80) { + const uint8_t cmd = payload[0]; + if ((cmd == 0x04 && !answer_usb_only) || (cmd == 0x01 && !answer_device_info)) + return true; // no reply + std::vector r{0x81, cmd}; + if (cmd == 0x01) // device type 3 (Pro controller) + MAC + r.insert(r.end(), {0x00, 0x03, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66}); + replies.push_back(r); + } else if (id == 0x01) { + const uint8_t sub = payload[9]; + std::vector r(15, 0); + r[0] = 0x21; + r[13] = 0x80; // ack + r[14] = sub; + if (sub == 0x10) { + const uint32_t addr = + payload[10] | (payload[11] << 8) | (payload[12] << 16) | (payload[13] << 24); + const uint8_t len = payload[14]; + r[13] = 0x90; + r.insert(r.end(), payload.begin() + 10, payload.begin() + 15); // address + length + auto bytes = flash.count(addr) ? flash[addr] : std::vector(len, 0xFF); + bytes.resize(len, 0xFF); + r.insert(r.end(), bytes.begin(), bytes.end()); + } + replies.push_back(r); + } + return true; + } + void deliver(SwitchProHost &host) { + std::vector> pending; + pending.swap(replies); + for (auto &r : pending) + host.on_input_report(r); + } +}; + +// a full input report: buttons (right, shared, left) and raw 12-bit sticks +std::vector input_report(uint8_t right, uint8_t shared, uint8_t left, uint16_t lx, + uint16_t ly, uint16_t rx, uint16_t ry) { + std::vector r{0x30, 0x00, 0x8E, right, shared, left}; + put(r, pack(lx, ly)); + put(r, pack(rx, ry)); + r.push_back(0x00); // vibrator + r.resize(49, 0); // + IMU + return r; +} +} // namespace + +TEST_CASE("the USB handshake runs to the end against a controller that answers") { + FakeController pad; + int ready = 0; + SwitchProHost host( + {.send_report = [&](uint8_t id, std::span p) { return pad.send(id, p); }, + .on_ready = [&] { ready++; }, + .player = 2, + .reply_timeout = std::chrono::seconds(10)}); + CHECK(host.stage() == Stage::Idle); + host.start(); + for (int i = 0; i < 40 && !host.running(); i++) { + pad.deliver(host); + host.update(); + } + REQUIRE(host.running()); + CHECK(ready == 1); + + // what was sent, in order: the init commands, then the subcommands + std::vector> steps; // (report id, command / subcommand) + std::transform(pad.sent.begin(), pad.sent.end(), std::back_inserter(steps), [](const auto &r) { + return std::pair(r[0], r[0] == 0x80 ? r[1] : r[10]); + }); + const std::vector> expected = { + {0x80, 0x01}, {0x80, 0x02}, {0x80, 0x03}, {0x80, 0x02}, {0x80, 0x04}, + {0x01, 0x03}, {0x01, 0x10}, {0x01, 0x10}, {0x01, 0x48}, {0x01, 0x30}}; + CHECK(steps == expected); + CHECK(pad.sent[5][11] == 0x30); // input mode: the full report + CHECK(pad.sent.back()[11] == 0x02); // player 2's light + for (const auto &r : pad.sent) + CHECK(r.size() == 1 + SwitchProHost::output_report_size); + + // the factory calibration, read from the SPI flash + const auto [left, right] = host.calibration(); + CHECK((left.x.center == 2000 && left.x.above == 1400 && left.x.below == 1200)); + CHECK((left.y.center == 2100 && left.y.above == 1300 && left.y.below == 1100)); + CHECK((right.x.center == 1900 && right.x.below == 1000 && right.x.above == 1500)); +} + +TEST_CASE("a step that is never answered is skipped after its tries") { + FakeController pad; + pad.answer_device_info = false; // e.g. a third-party controller + pad.answer_usb_only = false; + SwitchProHost host( + {.send_report = [&](uint8_t id, std::span p) { return pad.send(id, p); }, + .reply_timeout = std::chrono::milliseconds(0), + .max_tries = 3}); + host.start(); + for (int i = 0; i < 40 && !host.running(); i++) { + pad.deliver(host); + host.update(); + } + CHECK(host.running()); + const auto device_info_sends = std::count_if( + pad.sent.begin(), pad.sent.end(), [](const auto &r) { return r[0] == 0x80 && r[1] == 0x01; }); + CHECK(device_info_sends == 3); +} + +TEST_CASE("input reports decode with the calibration") { + SwitchProHost::StickCalibration left, right; // center 2048, travel 1500 + left.x = {2000, 1400, 1200}; + left.y = {2100, 1300, 1100}; + // B (south) + ZR, Home + Minus, d-pad up + ZL; left stick full right / full up + const auto r = input_report(0x04 | 0x80, 0x10 | 0x01, 0x02 | 0x80, 2000 + 1400, 2100 + 1300, 2048, + 2048 - 1500); + const auto s = SwitchProHost::decode_input(r, left, right); + REQUIRE(s.has_value()); + CHECK( + (s->pressed(B::South) && s->pressed(B::R2) && s->pressed(B::Home) && s->pressed(B::Select))); + CHECK((s->pressed(B::Up) && s->pressed(B::L2) && !s->pressed(B::East) && !s->pressed(B::L1))); + CHECK((s->axis(A::LeftTrigger) == GamepadState::AXIS_MAX && + s->axis(A::RightTrigger) == GamepadState::AXIS_MAX)); + CHECK(s->axis(A::LeftX) == GamepadState::AXIS_MAX); + CHECK(s->axis(A::LeftY) == -GamepadState::AXIS_MAX); // up: negative + CHECK(s->axis(A::RightX) == 0); + CHECK(s->axis(A::RightY) == GamepadState::AXIS_MAX); // down: positive + + // A (east), X (north), Y (west) and the shoulders + const auto r2 = + input_report(0x08 | 0x02 | 0x01 | 0x40, 0x02 | 0x20, 0x40, 2000, 2100, 2048, 2048); + const auto s2 = SwitchProHost::decode_input(r2, left, right); + CHECK((s2->pressed(B::East) && s2->pressed(B::North) && s2->pressed(B::West))); + CHECK((s2->pressed(B::R1) && s2->pressed(B::L1) && s2->pressed(B::Start) && + s2->pressed(B::Capture))); + CHECK((s2->axis(A::LeftX) == 0 && s2->axis(A::LeftY) == 0)); + + // not an input report + const uint8_t reply[2] = {0x81, 0x02}; + CHECK(!SwitchProHost::decode_input(reply, left, right).has_value()); +} + +TEST_CASE("a stick reading past its calibrated travel is full deflection") { + const SwitchProHost::StickCalibration::Axis a{2000, 1400, 1200}; // center, above, below + CHECK(SwitchProHost::normalize_axis(2000, a) == 0); + CHECK(SwitchProHost::normalize_axis(2000 + 700, a) == GamepadState::AXIS_MAX / 2); + CHECK(SwitchProHost::normalize_axis(2000 + 1400, a) == GamepadState::AXIS_MAX); + CHECK(SwitchProHost::normalize_axis(4095, a) == GamepadState::AXIS_MAX); // past the travel + CHECK(SwitchProHost::normalize_axis(2000 - 1200, a) == -GamepadState::AXIS_MAX); + CHECK(SwitchProHost::normalize_axis(0, a) == -GamepadState::AXIS_MAX); // past the travel + const SwitchProHost::StickCalibration::Axis none{2048, 0, 0}; + CHECK(SwitchProHost::normalize_axis(4095, none) == 0); // no travel: no deflection +} + +TEST_CASE("an unprogrammed calibration block is ignored") { + std::array blank; + blank.fill(0xFF); + CHECK(!SwitchProHost::parse_calibration(blank, true).has_value()); +} + +TEST_CASE("state, rumble and player lights once it runs") { + FakeController pad; + std::vector states; + SwitchProHost host( + {.send_report = [&](uint8_t id, std::span p) { return pad.send(id, p); }, + .on_state = [&](const GamepadState &s) { states.push_back(s); }, + .reply_timeout = std::chrono::seconds(10)}); + espp::RumbleState rumble; + rumble.set(espp::RumbleState::Motor::Strong, 200); + CHECK(!host.set_rumble(rumble)); // not before the handshake + host.start(); + for (int i = 0; i < 40 && !host.running(); i++) { + pad.deliver(host); + host.update(); + } + REQUIRE(host.running()); + states.clear(); + + const auto r = input_report(0x08, 0, 0, 2000, 2100, 1900, 1950); + host.on_input_report(r); + host.on_input_report(r); // the same state again: not published twice + REQUIRE(states.size() == 1); + CHECK(states[0].pressed(B::East)); + CHECK(host.state().pressed(B::East)); + + pad.sent.clear(); + CHECK(host.set_rumble(rumble)); + REQUIRE(pad.sent.size() == 1); + CHECK(pad.sent[0][0] == 0x10); + const auto levels = + espp::hid_rp::decode_switch_rumble(std::span(&pad.sent[0][2], 8)); + CHECK(std::abs(levels.left - 200) <= 12); + CHECK(levels.right == 0); + + pad.sent.clear(); + CHECK(host.set_player(3)); + REQUIRE(pad.sent.size() == 1); + CHECK((pad.sent[0][0] == 0x01 && pad.sent[0][10] == 0x30 && pad.sent[0][11] == 0x04)); +} + +TEST_CASE("a full-range calibration (some third-party controllers) is not used") { + FakeController pad; + // exactly what a third-party "Pro Controller" returned for 0x603D + pad.flash[0x603D] = {0xff, 0xf7, 0x7f, 0x00, 0x08, 0x80, 0x00, 0x08, 0x80, + 0x00, 0x08, 0x80, 0x00, 0x08, 0x80, 0xff, 0xf7, 0x7f}; + SwitchProHost host( + {.send_report = [&](uint8_t id, std::span p) { return pad.send(id, p); }, + .reply_timeout = std::chrono::seconds(10)}); + host.start(); + for (int i = 0; i < 40 && !host.running(); i++) { + pad.deliver(host); + host.update(); + } + REQUIRE(host.running()); + const auto [left, right] = host.calibration(); + const SwitchProHost::StickCalibration typical{}; + CHECK((left.x.above == typical.x.above && left.x.center == typical.x.center)); + CHECK((right.y.below == typical.y.below)); + // (parse_calibration itself still reads it as stored) + const auto parsed = SwitchProHost::parse_calibration( + std::span(pad.flash[0x603D].data(), 9), true); + REQUIRE(parsed.has_value()); + CHECK(parsed->x.above == 2047); +} diff --git a/components/system/example/CMakeLists.txt b/components/system/example/CMakeLists.txt index 7d359abd9f..f7556565c1 100644 --- a/components/system/example/CMakeLists.txt +++ b/components/system/example/CMakeLists.txt @@ -29,6 +29,7 @@ set(EXTRA_COMPONENT_DIRS "../../../components/system" "../../../components/task" "../../../components/usb_device" + "../../../components/xinput" ) if(DEFINED ENV{IDF_COMPONENT_MANAGER} AND "$ENV{IDF_COMPONENT_MANAGER}" STREQUAL "0") diff --git a/components/telemetry/example/CMakeLists.txt b/components/telemetry/example/CMakeLists.txt index c2b85a2d6e..1616018559 100644 --- a/components/telemetry/example/CMakeLists.txt +++ b/components/telemetry/example/CMakeLists.txt @@ -31,6 +31,7 @@ set(EXTRA_COMPONENT_DIRS "../../../components/task" "../../../components/timer" "../../../components/usb_device" + "../../../components/xinput" ) # With the component manager disabled (IDF_COMPONENT_MANAGER=0, e.g. in CI so the diff --git a/components/usb_device/CMakeLists.txt b/components/usb_device/CMakeLists.txt index 69f51b6bf6..719899c442 100644 --- a/components/usb_device/CMakeLists.txt +++ b/components/usb_device/CMakeLists.txt @@ -15,7 +15,8 @@ idf_component_register( # vfs: route_console_to_cdc() registers a VFS device (esp_vfs_register / # esp_vfs_t) to redirect stdout to the CDC interface. # sdmmc: the public header names sdmmc_card_t (MscMedium::sd_card). - REQUIRES base_component esp_tinyusb sdmmc vfs + # xinput: the X-Input wire format (xinput.hpp), used by the public header + REQUIRES base_component esp_tinyusb sdmmc vfs xinput PRIV_REQUIRES ${usb_device_priv_requires} ) diff --git a/components/usb_device/README.md b/components/usb_device/README.md index 56825a9fd7..8d4c764bfa 100644 --- a/components/usb_device/README.md +++ b/components/usb_device/README.md @@ -27,7 +27,7 @@ Today it can enable, in any combination (subject to the endpoint budget): - An **X-Input** function that presents the device as a wired **Xbox 360 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 + `update_xinput_state()` (`xinput.hpp`, from the [`xinput`](../xinput) component), and rumble/LED reports arrive via an `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 @@ -241,7 +241,7 @@ skips LED reports). 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. +`xinput.hpp` ([`xinput`](../xinput) component, shared with the host side) for the report/`GamepadState` API and the button/axis layout. How a PC recognizes the controller depends on what else the device carries: diff --git a/components/usb_device/example/CMakeLists.txt b/components/usb_device/example/CMakeLists.txt index dabc300f51..1e43d9f271 100644 --- a/components/usb_device/example/CMakeLists.txt +++ b/components/usb_device/example/CMakeLists.txt @@ -30,6 +30,7 @@ set(EXTRA_COMPONENT_DIRS "../../../components/system" "../../../components/task" "../../../components/usb_device" + "../../../components/xinput" ) if(DEFINED ENV{IDF_COMPONENT_MANAGER} AND "$ENV{IDF_COMPONENT_MANAGER}" STREQUAL "0") diff --git a/components/usb_device/idf_component.yml b/components/usb_device/idf_component.yml index 1693fb1df0..1b0be01b96 100644 --- a/components/usb_device/idf_component.yml +++ b/components/usb_device/idf_component.yml @@ -30,6 +30,8 @@ dependencies: idf: version: '>=5.3' espp/base_component: '>=1.0' + # the X-Input wire format (xinput.hpp), shared with the host side (xbox_host) + espp/xinput: '>=1.0' # >= 3.0.0: esp_tinyusb ships TinyUSB (0.21.0~2 in 3.0.0) as its own # submodule and no longer depends on the registry `tinyusb` component. Do not # add a `tinyusb` dependency here: with esp_tinyusb 3.x it pulls a second copy diff --git a/components/usb_device/msc_example/CMakeLists.txt b/components/usb_device/msc_example/CMakeLists.txt index 0b1906755c..e38823929b 100644 --- a/components/usb_device/msc_example/CMakeLists.txt +++ b/components/usb_device/msc_example/CMakeLists.txt @@ -11,6 +11,7 @@ set(EXTRA_COMPONENT_DIRS "../../../components/logger" "../../../components/sdcard" "../../../components/usb_device" + "../../../components/xinput" # The T-Dongle-S3 BSP (menuconfig: MSC_EXAMPLE_MEDIUM_BSP_T_DONGLE_S3) and the # components it requires. The BSP is always compiled so the medium can be # picked in menuconfig; it is only instantiated when selected. diff --git a/components/usb_device/test/CMakeLists.txt b/components/usb_device/test/CMakeLists.txt index 993e98ab86..ff7360f32c 100644 --- a/components/usb_device/test/CMakeLists.txt +++ b/components/usb_device/test/CMakeLists.txt @@ -1,3 +1,2 @@ # Host tests of usb_device (see test/EsppTest.cmake and test/README.md). espp_add_component_test(ms_os_20_host_test DOCTEST SOURCES ms_os_20_host_test.cpp) -espp_add_component_test(xinput_host_test DOCTEST SOURCES xinput_host_test.cpp) diff --git a/components/usb_device/xinput_example/CMakeLists.txt b/components/usb_device/xinput_example/CMakeLists.txt index b671245f27..4adce2501d 100644 --- a/components/usb_device/xinput_example/CMakeLists.txt +++ b/components/usb_device/xinput_example/CMakeLists.txt @@ -10,6 +10,7 @@ set(EXTRA_COMPONENT_DIRS "../../../components/format" "../../../components/logger" "../../../components/usb_device" + "../../../components/xinput" ) # With the component manager disabled (IDF_COMPONENT_MANAGER=0, e.g. in CI so the diff --git a/components/vl53l/vl53l5cx_webapp_example/CMakeLists.txt b/components/vl53l/vl53l5cx_webapp_example/CMakeLists.txt index 39aefd5730..aa2d9afbe5 100644 --- a/components/vl53l/vl53l5cx_webapp_example/CMakeLists.txt +++ b/components/vl53l/vl53l5cx_webapp_example/CMakeLists.txt @@ -34,6 +34,7 @@ set(EXTRA_COMPONENT_DIRS "../../../components/system" "../../../components/task" "../../../components/usb_device" + "../../../components/xinput" "../../../components/vl53l" ) diff --git a/components/wdi/usb_example/CMakeLists.txt b/components/wdi/usb_example/CMakeLists.txt index fe1e6df965..893e779718 100644 --- a/components/wdi/usb_example/CMakeLists.txt +++ b/components/wdi/usb_example/CMakeLists.txt @@ -13,6 +13,7 @@ set(EXTRA_COMPONENT_DIRS "../../../components/timer" "../../../components/hid-rp" "../../../components/usb_device" + "../../../components/xinput" "../../../components/wdi" ) diff --git a/components/xbox_host/CMakeLists.txt b/components/xbox_host/CMakeLists.txt new file mode 100644 index 0000000000..d74745859c --- /dev/null +++ b/components/xbox_host/CMakeLists.txt @@ -0,0 +1,8 @@ +idf_component_register( + INCLUDE_DIRS "include" + SRC_DIRS "src" + # usb: the USB Host Library (the built-in one before ESP-IDF 6, the esp-usb + # registry component from 6.0); gamepad_map: GamepadState / RumbleState; + # xinput: the X-Input wire format + REQUIRES base_component gamepad_map task usb xinput +) diff --git a/components/xbox_host/README.md b/components/xbox_host/README.md new file mode 100644 index 0000000000..5125d75541 --- /dev/null +++ b/components/xbox_host/README.md @@ -0,0 +1,71 @@ +# Xbox Host Component + +[![Badge](https://components.espressif.com/components/espp/xbox_host/badge.svg)](https://components.espressif.com/components/espp/xbox_host) + +`espp::XboxHost` reads **wired Xbox controllers** plugged into an ESP32-S2 / +-S3 / -P4 USB host port: + +- **X-Input**: Xbox 360 controllers, and the third-party controllers that speak + their protocol (most controllers' "X-input" mode, e.g. 8BitDo's); +- **GIP**: Xbox One and Xbox Series controllers. + +It decodes their input into gamepad_map's `espp::GamepadState`, drives their +rumble (`espp::RumbleState`: the two grips, and on GIP controllers the two +impulse triggers too) and, for X-Input, the player LED. + +## Why a separate component + +Neither family is a USB HID device: both present a vendor-specific interface +(X-Input: class `0xFF` / subclass `0x5D` / protocol `0x01`; GIP: `0xFF` / +`0x47` / `0xD0`) with an interrupt IN and an interrupt OUT endpoint, so a HID +host driver such as [`usb_host`](../usb_host)'s never sees them. `XboxHost` is +a second client of the ESP-IDF USB Host Library that claims those interfaces, +starts each controller (a GIP controller stays silent until the host powers it +on, and asks for its Xbox button presses to be acknowledged), decodes its +packets and sends it rumble. + +`XboxHost` does **not** install the USB Host Library: `espp::UsbHost` (or your +own `usb_host_install()`) does, and `XboxHost` registers its client alongside, +so HID devices and Xbox controllers share the port. Controllers already +attached when `XboxHost` initializes are picked up too. + +## Usage + +```cpp +espp::UsbHost usb_host({}); // installs the USB Host Library +std::error_code ec; +usb_host.initialize(ec); + +espp::XboxHost xbox({ + .on_connected = [](const auto &c) { /* c->info(): vid, pid, protocol, product */ }, + .on_disconnected = [](const auto &c) { /* ... */ }, + .on_state = [](const auto &c, const espp::GamepadState &state) { + // buttons by position (south = A), sticks -32767..32767 (Y down), + // triggers 0..32767 + }, +}); +xbox.initialize(ec); +// later, from any task: controller->set_rumble(rumble); controller->set_player(2); +``` + +The callbacks run on XboxHost's task (the one that handles the USB events), so +keep them short. See the [example](./example). + +## Wire formats + +Header-only and host-tested (`test/`): + +- `xinput.hpp`, from the [`xinput`](../xinput) component (shared with + `espp::UsbDevice`'s X-Input function): the 20-byte input report, rumble and + LED-ring reports; +- `gip.hpp`: GIP packet headers, input / Xbox button packets, the power-on, + acknowledgement, rumble and LED packets; +- `xbox_gamepad_state.hpp`: both families to `GamepadState`, `RumbleState` to + both families' rumble levels. + +## Requirements + +- An ESP32-S2 / -S3 / -P4 (USB-OTG host) whose port can source VBUS to the + controller. +- The USB Host Library installed by something else (`espp::UsbHost` or + `usb_host_install()`) before `XboxHost::initialize()`. diff --git a/components/xbox_host/example/CMakeLists.txt b/components/xbox_host/example/CMakeLists.txt new file mode 100644 index 0000000000..3a88887ce3 --- /dev/null +++ b/components/xbox_host/example/CMakeLists.txt @@ -0,0 +1,34 @@ +# The following lines of boilerplate have to be in your project's CMakeLists +# in this exact order for cmake to work correctly +cmake_minimum_required(VERSION 3.20) + +include($ENV{IDF_PATH}/tools/cmake/project.cmake) + +# espp's components, from this repository; the USB Host Library (`usb`) and +# the HID class driver espp::UsbHost uses come from the ESP Component Registry +set(EXTRA_COMPONENT_DIRS + "../../../components/base_component" + "../../../components/dispatcher" + "../../../components/format" + "../../../components/gamepad_map" + "../../../components/hid-rp" + "../../../components/logger" + "../../../components/persistent_data" + "../../../components/serialization" + "../../../components/stream_frame" + "../../../components/task" + "../../../components/usb_host" + "../../../components/xbox_host" + "../../../components/xinput" +) + +set( + COMPONENTS + "main esptool_py xbox_host usb_host" + CACHE STRING + "List of components to include" + ) + +project(xbox_host_example) + +set(CMAKE_CXX_STANDARD 23) diff --git a/components/xbox_host/example/README.md b/components/xbox_host/example/README.md new file mode 100644 index 0000000000..8330063db6 --- /dev/null +++ b/components/xbox_host/example/README.md @@ -0,0 +1,35 @@ +# Xbox Host Example + +This example reads wired Xbox controllers plugged into the ESP32-S3's native +USB port in host mode: an Xbox 360 controller (or a third-party controller in +its X-input mode) and an Xbox One / Xbox Series controller. It logs each +controller's state as it changes, and rumbles it with its triggers (left +trigger: the strong motor, right trigger: the weak one). + +`espp::UsbHost` installs the USB Host Library and `espp::XboxHost` registers +its client alongside it. + +## How to use the example + +### Hardware Required + +An ESP32-S3 (or -S2 / -P4) board whose native USB port can **source VBUS** to +the controller (a USB-A host port, or an OTG adapter with power), and a wired +Xbox 360, Xbox One or Xbox Series controller. On the ESP32-S3 the console runs +on UART0 (the native USB port is the host), so monitor it with a UART adapter. + +### Build and Flash + +``` +idf.py -p PORT flash monitor +``` + +(To exit the serial monitor, type ``Ctrl-]``.) + +## Example Output + +``` +I (1234) Xbox Host: Starting the Xbox controller host example +I (2345) Xbox Host: GIP controller connected: 'Microsoft' 'Controller' 045e:0b12, player 1 +I (2400) Xbox Host: player 1: GamepadState{buttons: [south], left_x: 0, ...} +``` diff --git a/components/xbox_host/example/main/CMakeLists.txt b/components/xbox_host/example/main/CMakeLists.txt new file mode 100644 index 0000000000..6dbb6ab71c --- /dev/null +++ b/components/xbox_host/example/main/CMakeLists.txt @@ -0,0 +1,5 @@ +idf_component_register( + SRC_DIRS "." + INCLUDE_DIRS "." + REQUIRES gamepad_map usb_host xbox_host +) diff --git a/components/xbox_host/example/main/idf_component.yml b/components/xbox_host/example/main/idf_component.yml new file mode 100644 index 0000000000..455628219d --- /dev/null +++ b/components/xbox_host/example/main/idf_component.yml @@ -0,0 +1,13 @@ +## IDF Component Manager Manifest File - example project overrides. +## +## This file only affects THIS example build, not any published component. +dependencies: + # espp/xinput (the X-Input wire format, which usb_device and xbox_host use) is + # published with the next espp release (it is in + # .github/workflows/upload_components.yml now); until then this example, which + # runs the component manager, would fail to resolve it from the registry. + # Point at the in-repo source, and delete this file once it is on the + # registry. + espp/xinput: + version: "*" + override_path: "../../../xinput" diff --git a/components/xbox_host/example/main/xbox_host_example.cpp b/components/xbox_host/example/main/xbox_host_example.cpp new file mode 100644 index 0000000000..ac316a26a8 --- /dev/null +++ b/components/xbox_host/example/main/xbox_host_example.cpp @@ -0,0 +1,62 @@ +#include +#include + +#include "gamepad_state_formatters.hpp" +#include "logger.hpp" +#include "usb_host.hpp" +#include "xbox_host.hpp" + +using namespace std::chrono_literals; + +extern "C" void app_main(void) { + espp::Logger logger({.tag = "Xbox Host", .level = espp::Logger::Verbosity::INFO}); + logger.info("Starting the Xbox controller host example"); + + //! [xbox_host example] + // espp::UsbHost installs the USB Host Library (and runs its event task); + // XboxHost registers its own client alongside it, so HID devices and Xbox + // controllers can share the port + espp::UsbHost usb_host({.log_level = espp::Logger::Verbosity::WARN}); + std::error_code ec; + if (!usb_host.initialize(ec)) { + logger.error("Failed to initialize the USB host: {}", ec.message()); + return; + } + + using Controller = espp::XboxHost::Controller; + espp::XboxHost xbox({ + .on_connected = + [&](const std::shared_ptr &c) { + const auto &info = c->info(); + logger.info("{} controller connected: '{}' '{}' {:04x}:{:04x}, player {}", + espp::XboxHost::name(info.protocol), info.manufacturer, info.product, + info.vid, info.pid, c->player()); + }, + .on_disconnected = + [&](const std::shared_ptr &c) { + logger.info("controller {:04x}:{:04x} disconnected", c->info().vid, c->info().pid); + }, + .on_state = + [&](const std::shared_ptr &c, const espp::GamepadState &state) { + logger.info("player {}: {}", c->player(), state); + // rumble with the triggers: the left one drives the strong motor, + // the right one the weak motor + using A = espp::GamepadState::Axis; + using M = espp::RumbleState::Motor; + espp::RumbleState rumble; + rumble.set(M::Strong, static_cast(state.axis(A::LeftTrigger) >> 7)); + rumble.set(M::Weak, static_cast(state.axis(A::RightTrigger) >> 7)); + c->set_rumble(rumble); + }, + .log_level = espp::Logger::Verbosity::INFO, + }); + if (!xbox.initialize(ec)) { + logger.error("Failed to initialize the Xbox host: {}", ec.message()); + return; + } + //! [xbox_host example] + + while (true) { + std::this_thread::sleep_for(1s); + } +} diff --git a/components/xbox_host/example/sdkconfig.defaults b/components/xbox_host/example/sdkconfig.defaults new file mode 100644 index 0000000000..46c8c82593 --- /dev/null +++ b/components/xbox_host/example/sdkconfig.defaults @@ -0,0 +1,7 @@ +CONFIG_IDF_TARGET="esp32s3" +CONFIG_ESP_MAIN_TASK_STACK_SIZE=8192 +# The native USB-OTG port is used for the USB **host** role. On the ESP32-S3 the +# USB-Serial-JTAG shares that PHY, so the console runs on UART0 (with +# USB-Serial-JTAG as an early-boot secondary). Use a UART adapter to monitor. +CONFIG_ESP_CONSOLE_UART_DEFAULT=y +CONFIG_ESP_CONSOLE_SECONDARY_USB_SERIAL_JTAG=y diff --git a/components/xbox_host/idf_component.yml b/components/xbox_host/idf_component.yml new file mode 100644 index 0000000000..8e70ab4961 --- /dev/null +++ b/components/xbox_host/idf_component.yml @@ -0,0 +1,35 @@ +## IDF Component Manager Manifest File +license: "MIT" +description: "Wired Xbox controllers on an ESP32-S2/-S3/-P4 USB host port: Xbox 360 / X-Input and Xbox One / Series (GIP), decoded into gamepad_map's GamepadState, with rumble and the player LED" +url: "https://github.com/esp-cpp/espp/tree/main/components/xbox_host" +repository: "git://github.com/esp-cpp/espp.git" +maintainers: + - William Emfinger +documentation: "https://esp-cpp.github.io/espp/buses/xbox_host.html" +examples: + - path: example +tags: + - cpp + - Component + - USB + - USB-Host + - Xbox + - XInput + - GIP + - Gamepad + - Controller +dependencies: + # like espp/usb_host: the USB Host Library is built into ESP-IDF before 6.0 + # and is the esp-usb `usb` registry component from 6.0 + idf: + version: '>=5.4' + espp/base_component: '>=1.0' + # GamepadState / RumbleState + espp/gamepad_map: '>=1.4.6' + espp/task: '>=1.0' + espp/xinput: '>=1.0' + espressif/usb: + version: '>=1.3.0' + public: true + rules: + - if: "idf_version >=6.0" diff --git a/components/xbox_host/include/gip.hpp b/components/xbox_host/include/gip.hpp new file mode 100644 index 0000000000..4724b3dee0 --- /dev/null +++ b/components/xbox_host/include/gip.hpp @@ -0,0 +1,211 @@ +#pragma once + +// Xbox One / Series controller (GIP, "Gaming Input Protocol") wire format, as a +// USB host sees it. +// +// This header is dependency-free and host-testable (no ESP-IDF headers): it +// parses the packets a wired Xbox One / Xbox Series controller sends on its +// interrupt IN endpoint and builds the ones a host sends on the OUT endpoint. +// `espp::XboxHost` (xbox_host.hpp) drives a controller with it. +// +// A GIP controller presents a vendor-specific interface (bInterfaceClass 0xFF / +// bInterfaceSubClass 0x47 / bInterfaceProtocol 0xD0) with an interrupt IN and +// an interrupt OUT endpoint. Every packet starts with a 4-byte header: +// [0] command, [1] options (GIP_OPT_*), [2] sequence, [3] payload length +// The controller sends nothing but its announcement until the host powers it on +// (power_on()); then it streams input packets (command 0x20) and reports the +// Xbox button on its own (command 0x07), asking the host to acknowledge that. + +#include +#include +#include +#include +#include + +namespace espp { +namespace gip { + +/// Vendor-specific interface class triple that identifies GIP. +inline constexpr uint8_t kInterfaceClass = 0xFF; +inline constexpr uint8_t kInterfaceSubClass = 0x47; +inline constexpr uint8_t kInterfaceProtocol = 0xD0; + +/// Packet commands (header byte 0). +enum class Command : uint8_t { + Acknowledge = 0x01, + Announce = 0x02, ///< controller -> host when it connects + Status = 0x03, ///< controller -> host (battery / keep-alive) + Identify = 0x04, + Power = 0x05, ///< host -> controller: power on / off + Authenticate = 0x06, + VirtualKey = 0x07, ///< controller -> host: the Xbox (guide) button + Rumble = 0x09, ///< host -> controller + Led = 0x0A, ///< host -> controller: the Xbox button's light + Input = 0x20, ///< controller -> host: buttons, triggers, sticks +}; + +/// Header option bits (header byte 1). +inline constexpr uint8_t kOptionAcknowledge = 0x10; ///< the sender wants an acknowledgement +inline constexpr uint8_t kOptionInternal = 0x20; ///< a system message (not device-specific) + +inline constexpr std::size_t kHeaderSize = 4; + +/// A packet's header. +struct Header { + uint8_t command{0}; + uint8_t options{0}; + uint8_t sequence{0}; + uint8_t length{0}; ///< payload bytes after the header + constexpr bool wants_ack() const { return (options & kOptionAcknowledge) != 0; } +}; + +/// The header of a packet, or nullopt if it is shorter than a header. +inline std::optional
parse_header(std::span p) { + if (p.size() < kHeaderSize) + return std::nullopt; + return Header{p[0], p[1], p[2], p[3]}; +} + +/// Button bits of an input packet (payload bytes 0 (low) and 1 (high)). +enum class Button : uint16_t { + Sync = 1u << 0, ///< the pairing button (wired: rarely reported) + Menu = 1u << 2, ///< ≡ (Start) + View = 1u << 3, ///< ⧉ (Back / Select) + A = 1u << 4, + B = 1u << 5, + X = 1u << 6, + Y = 1u << 7, + DpadUp = 1u << 8, + DpadDown = 1u << 9, + DpadLeft = 1u << 10, + DpadRight = 1u << 11, + LeftBumper = 1u << 12, + RightBumper = 1u << 13, + LeftStick = 1u << 14, ///< L3 + RightStick = 1u << 15, ///< R3 +}; + +inline constexpr uint16_t kTriggerMax = 1023; ///< a trigger's full press + +/// The controls in an input packet. +struct InputState { + uint16_t buttons{0}; ///< OR of Button values + uint16_t left_trigger{0}; ///< 0..1023 + uint16_t right_trigger{0}; ///< 0..1023 + int16_t lx{0}; ///< left stick X, -32768..32767 (right positive) + int16_t ly{0}; ///< left stick Y, -32768..32767 (up positive) + int16_t rx{0}; ///< right stick X + int16_t ry{0}; ///< right stick Y + bool share{false}; ///< the Share button (Xbox Series controllers) + bool get(Button b) const { return (buttons & static_cast(b)) != 0; } +}; + +/// Where an Xbox Series controller reports its Share button: bit 0 of this +/// packet byte (the payload of a Series controller's input packet runs past it; +/// an Xbox One controller's ends before it). +inline constexpr std::size_t kShareByte = 18; + +/// The controls in an input packet (command 0x20), or nullopt for any other +/// packet. @p has_share: read the Share button (only Xbox Series controllers +/// have one; other controllers may put something else at that byte). +inline std::optional parse_input(std::span p, bool has_share = false) { + // header + buttons (2) + triggers (2 x 2) + sticks (4 x 2) = 4 + 14 + if (p.size() < kHeaderSize + 14 || p[0] != static_cast(Command::Input)) + return std::nullopt; + auto get16 = [&](std::size_t i) { return static_cast(p[i] | (p[i + 1] << 8)); }; + InputState s; + s.buttons = get16(4); + s.left_trigger = get16(6); + s.right_trigger = get16(8); + s.lx = static_cast(get16(10)); + s.ly = static_cast(get16(12)); + s.rx = static_cast(get16(14)); + s.ry = static_cast(get16(16)); + if (has_share && p.size() > kShareByte) + s.share = (p[kShareByte] & 0x01) != 0; + return s; +} + +/// Whether the Xbox (guide) button is down in a virtual-key packet (command +/// 0x07), or nullopt for any other packet. +inline std::optional parse_guide(std::span p) { + if (p.size() < kHeaderSize + 1 || p[0] != static_cast(Command::VirtualKey)) + return std::nullopt; + return (p[4] & 0x01) != 0; +} + +/// Power the controller on, so it starts sending input: `05 20 01 00`. +inline std::array power_on(uint8_t sequence) { + return {static_cast(Command::Power), kOptionInternal, sequence, 0x01, 0x00}; +} + +/// The extra power packet some controllers need to start (the Xbox One S and +/// Elite Series 2 after they were last used over Bluetooth): `05 20 0f 06`. +inline std::array power_on_extra(uint8_t sequence) { + return {static_cast(Command::Power), kOptionInternal, sequence, 0x0F, 0x06}; +} + +/// The acknowledgement of a packet whose header asked for one (wants_ack()): +/// it names the packet's command, options and sequence. A controller repeats a +/// guide-button packet until it is acknowledged. +inline std::array acknowledge(const Header &packet) { + return {static_cast(Command::Acknowledge), + kOptionInternal, + packet.sequence, + 0x09, + 0x00, + packet.command, + static_cast(packet.options & ~kOptionAcknowledge), + packet.length, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00}; +} + +inline constexpr uint8_t kRumbleMax = 100; ///< a motor's full strength in a rumble packet + +/// A rumble packet: the four motors (the two grips and the two impulse +/// triggers), each 0..100, played until the next rumble packet: +/// `09 00 09 00 0f ff 00 eb`. +inline std::array rumble(uint8_t sequence, uint8_t left_trigger, uint8_t right_trigger, + uint8_t strong, uint8_t weak) { + auto lim = [](uint8_t v) { return v > kRumbleMax ? kRumbleMax : v; }; + return {static_cast(Command::Rumble), + 0x00, + sequence, + 0x09, + 0x00, + 0x0F, // all four motors + lim(left_trigger), + lim(right_trigger), + lim(strong), + lim(weak), + 0xFF, // duration (with the repeat below: until replaced) + 0x00, // delay + 0xEB}; // repeat +} + +/// The Xbox button's light: `0a 20 03 00 ` (mode 1 = +/// on; brightness 0..47ish, 0x14 is the default). +inline std::array led(uint8_t sequence, uint8_t mode = 0x01, + uint8_t brightness = 0x14) { + return { + static_cast(Command::Led), kOptionInternal, sequence, 0x03, 0x00, mode, brightness}; +} + +/// The host's packet sequence numbers: 1..255, then around again (0 is not used). +class Sequence { +public: + uint8_t next() { + value_ = static_cast(value_ % 255 + 1); // 1, 2, ... 255, 1, ... + return value_; + } + +private: + uint8_t value_{0}; +}; + +} // namespace gip +} // namespace espp diff --git a/components/xbox_host/include/xbox_gamepad_state.hpp b/components/xbox_host/include/xbox_gamepad_state.hpp new file mode 100644 index 0000000000..f28858d3f6 --- /dev/null +++ b/components/xbox_host/include/xbox_gamepad_state.hpp @@ -0,0 +1,131 @@ +#pragma once + +// Between the Xbox controllers' wire formats (xinput.hpp, gip.hpp) and the +// gamepad_map component's GamepadState / RumbleState. Dependency-free and +// host-testable, like the formats themselves. + +#include + +#include "gamepad_state.hpp" +#include "gip.hpp" +#include "rumble_state.hpp" +#include "xinput.hpp" + +namespace espp { +namespace xbox { + +/// How far a trigger goes down before it also counts as the L2 / R2 button: +/// XInput's own threshold, 30 of 255. +inline constexpr int32_t kTriggerButtonThreshold = 30 * GamepadState::AXIS_MAX / 255; + +namespace detail { +/// A stick axis in -AXIS_MAX..AXIS_MAX (the controllers' int16 reaches -32768). +constexpr int32_t stick(int32_t v) { + return v < -GamepadState::AXIS_MAX ? -GamepadState::AXIS_MAX + : v > GamepadState::AXIS_MAX ? GamepadState::AXIS_MAX + : v; +} +/// A stick's Y with up positive (the controllers) to down positive (GamepadState). +constexpr int32_t flip_y(int16_t y) { return stick(-static_cast(y)); } +/// A trigger reading of 0..@p full in 0..AXIS_MAX (a reading past full, which +/// a GIP packet's 16-bit field allows, is a full press). +constexpr int32_t trigger(uint32_t v, uint32_t full) { + return v >= full ? GamepadState::AXIS_MAX + : static_cast(v * static_cast(GamepadState::AXIS_MAX) / full); +} +} // namespace detail + +/// The GamepadState of an X-Input (Xbox 360) controller's input report. +inline GamepadState to_gamepad_state(const xinput::GamepadState &in) { + using B = GamepadState::Button; + using A = GamepadState::Axis; + using X = xinput::Button; + GamepadState s; + s.set(B::South, in.get(X::A)); + s.set(B::East, in.get(X::B)); + s.set(B::West, in.get(X::X)); + s.set(B::North, in.get(X::Y)); + s.set(B::L1, in.get(X::LeftBumper)); + s.set(B::R1, in.get(X::RightBumper)); + s.set(B::L3, in.get(X::LeftStick)); + s.set(B::R3, in.get(X::RightStick)); + s.set(B::Select, in.get(X::Back)); + s.set(B::Start, in.get(X::Start)); + s.set(B::Home, in.get(X::Guide)); + s.set(B::Up, in.get(X::DpadUp)); + s.set(B::Down, in.get(X::DpadDown)); + s.set(B::Left, in.get(X::DpadLeft)); + s.set(B::Right, in.get(X::DpadRight)); + s.set(A::LeftX, detail::stick(in.lx)); + s.set(A::LeftY, detail::flip_y(in.ly)); + s.set(A::RightX, detail::stick(in.rx)); + s.set(A::RightY, detail::flip_y(in.ry)); + s.set(A::LeftTrigger, detail::trigger(in.left_trigger, 255)); + s.set(A::RightTrigger, detail::trigger(in.right_trigger, 255)); + s.set(B::L2, s.axis(A::LeftTrigger) > kTriggerButtonThreshold); + s.set(B::R2, s.axis(A::RightTrigger) > kTriggerButtonThreshold); + return s; +} + +/// The GamepadState of a GIP (Xbox One / Series) controller's input packet, +/// with the Xbox button (reported in packets of its own) as @p guide. +inline GamepadState to_gamepad_state(const gip::InputState &in, bool guide) { + using B = GamepadState::Button; + using A = GamepadState::Axis; + using G = gip::Button; + GamepadState s; + s.set(B::South, in.get(G::A)); + s.set(B::East, in.get(G::B)); + s.set(B::West, in.get(G::X)); + s.set(B::North, in.get(G::Y)); + s.set(B::L1, in.get(G::LeftBumper)); + s.set(B::R1, in.get(G::RightBumper)); + s.set(B::L3, in.get(G::LeftStick)); + s.set(B::R3, in.get(G::RightStick)); + s.set(B::Select, in.get(G::View)); + s.set(B::Start, in.get(G::Menu)); + s.set(B::Home, guide); + s.set(B::Capture, in.share); + s.set(B::Up, in.get(G::DpadUp)); + s.set(B::Down, in.get(G::DpadDown)); + s.set(B::Left, in.get(G::DpadLeft)); + s.set(B::Right, in.get(G::DpadRight)); + s.set(A::LeftX, detail::stick(in.lx)); + s.set(A::LeftY, detail::flip_y(in.ly)); + s.set(A::RightX, detail::stick(in.rx)); + s.set(A::RightY, detail::flip_y(in.ry)); + s.set(A::LeftTrigger, detail::trigger(in.left_trigger, gip::kTriggerMax)); + s.set(A::RightTrigger, detail::trigger(in.right_trigger, gip::kTriggerMax)); + s.set(B::L2, s.axis(A::LeftTrigger) > kTriggerButtonThreshold); + s.set(B::R2, s.axis(A::RightTrigger) > kTriggerButtonThreshold); + return s; +} + +/// The X-Input rumble report levels for a RumbleState: the strong (left) and +/// weak (right) motors (an Xbox 360 controller has no trigger motors). +inline xinput::Rumble to_xinput_rumble(const RumbleState &r) { + using M = RumbleState::Motor; + return {r.level(M::Strong), r.level(M::Weak)}; +} + +/// A GIP rumble packet's four motor levels (0..100). +struct GipRumble { + uint8_t left_trigger{0}; + uint8_t right_trigger{0}; + uint8_t strong{0}; + uint8_t weak{0}; + constexpr bool operator==(const GipRumble &) const = default; +}; + +/// The GIP rumble levels for a RumbleState (0..255 -> 0..100, rounded). +inline GipRumble to_gip_rumble(const RumbleState &r) { + using M = RumbleState::Motor; + auto lvl = [&](M m) { + return static_cast((r.level(m) * gip::kRumbleMax + RumbleState::LEVEL_MAX / 2) / + RumbleState::LEVEL_MAX); + }; + return {lvl(M::LeftTrigger), lvl(M::RightTrigger), lvl(M::Strong), lvl(M::Weak)}; +} + +} // namespace xbox +} // namespace espp diff --git a/components/xbox_host/include/xbox_host.hpp b/components/xbox_host/include/xbox_host.hpp new file mode 100644 index 0000000000..9004869cce --- /dev/null +++ b/components/xbox_host/include/xbox_host.hpp @@ -0,0 +1,201 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "base_component.hpp" +#include "gamepad_state.hpp" +#include "gip.hpp" +#include "rumble_state.hpp" +#include "task.hpp" +#include "xbox_gamepad_state.hpp" +#include "xinput.hpp" + +#include "usb/usb_host.h" + +namespace espp { +/** + * @brief Wired Xbox controllers on a USB host port: Xbox 360 (X-Input, and most + * third-party controllers in their X-input mode) and Xbox One / Series + * (GIP). + * + * @details Neither family is a USB HID device: both present a vendor-specific + * interface (X-Input: class 0xFF / subclass 0x5D / protocol 0x01; GIP: + * 0xFF / 0x47 / 0xD0) with an interrupt IN and an interrupt OUT + * endpoint, so a HID host driver never sees them. XboxHost is a client + * of the ESP-IDF USB Host Library that claims those interfaces: it + * starts each controller (GIP controllers stay silent until the host + * powers them on), decodes its input into gamepad_map's GamepadState, + * and sends it rumble (gamepad_map's RumbleState) and, for X-Input, the + * player LED. + * + * XboxHost does not install the USB Host Library: something else on + * the port does (espp::UsbHost, which also runs the library's event + * task, or your own usb_host_install()), and XboxHost registers its + * client alongside, so HID devices (via UsbHost) and Xbox controllers + * work on the same port. Controllers already attached when XboxHost + * initializes are picked up too. + * + * The callbacks run on XboxHost's own task, the one that handles the + * USB events, so keep them short (copy the state somewhere and return); + * Controller::set_rumble() / set_player() may be called from any task. + * + * \section xbox_host_ex1 Example + * \snippet xbox_host_example.cpp xbox_host example + */ +class XboxHost : public BaseComponent { +public: + /// The protocol a controller speaks. + enum class Protocol : uint8_t { + XInput, ///< Xbox 360 (and X-input mode third-party controllers) + Gip, ///< Xbox One / Xbox Series + }; + + /// @brief The name of a protocol ("X-Input", "GIP"). + static constexpr const char *name(Protocol p) { return p == Protocol::Gip ? "GIP" : "X-Input"; } + + /// One connected controller. + class Controller { + public: + /// What the controller is. + struct Info { + uint16_t vid{0}; + uint16_t pid{0}; + Protocol protocol{Protocol::XInput}; + std::string manufacturer; ///< from the string descriptor (ASCII), may be empty + std::string product; ///< from the string descriptor (ASCII), may be empty + uint8_t address{0}; ///< USB device address + uint8_t interface_number{0}; + }; + + /// @brief What the controller is. + const Info &info() const { return info_; } + /// @brief Whether it is still attached. + bool connected() const { return !gone_.load(); } + /// @brief Its player number (1..4; XboxHost hands them out in order). + int player() const { return player_.load(); } + /// @brief Its latest state. + GamepadState state() const; + /// @brief Drive its rumble motors (X-Input: the two grips; GIP: the grips + /// and the two impulse triggers) until the next call. Any task. + /// @return false if it is gone or the report could not be queued. + bool set_rumble(const RumbleState &rumble); + /// @brief Change its player number (X-Input: the LED ring shows it). Any task. + bool set_player(int player); + + private: + friend class XboxHost; + explicit Controller(XboxHost &host) + : host_(host) {} + bool queue_output(std::vector data, bool is_rumble); + void submit_next_output_locked(); // with mutex_ held + + XboxHost &host_; + Info info_; + std::atomic gone_{false}; + std::atomic player_{0}; + mutable std::mutex mutex_; // state_, the output queue, the transfer flags + GamepadState state_{}; + bool guide_{false}; // GIP: the Xbox button, reported on its own + bool has_share_{false}; // GIP: an Xbox Series controller (a Share button) + gip::Sequence sequence_; + usb_device_handle_t device_{nullptr}; + uint8_t ep_in_{0}; + uint8_t ep_out_{0}; + uint16_t ep_in_mps_{0}; + usb_transfer_t *in_transfer_{nullptr}; + usb_transfer_t *out_transfer_{nullptr}; + bool in_busy_{false}; + bool out_busy_{false}; + std::deque> out_queue_; + std::optional> pending_rumble_; // the latest one only + bool closing_{false}; + }; + + using controller_fn = std::function &controller)>; + using state_fn = + std::function &controller, const GamepadState &state)>; + + /// Configuration. + struct Config { + controller_fn on_connected{nullptr}; ///< a controller attached and started + controller_fn on_disconnected{nullptr}; ///< a controller detached + /// @brief A controller's state changed (every input report, if + /// only_on_change is false). + state_fn on_state{nullptr}; + bool only_on_change{true}; ///< call on_state only when the state changes + size_t task_stack_size{4096}; + size_t task_priority{5}; + int task_core_id{-1}; ///< -1 = no affinity + /// @brief ESP only: heap capabilities for the task's stack (see + /// espp::Task::BaseConfig::stack_alloc_caps); 0 = internal RAM. + /// MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT puts it in PSRAM, as + /// espp::UsbHost::Config::task_stack_alloc_caps does for its tasks. + uint32_t task_stack_alloc_caps{0}; + Logger::Verbosity log_level{Logger::Verbosity::WARN}; + }; + + /// @brief Construct an XboxHost. Call initialize() to register it. + explicit XboxHost(const Config &config); + /// @brief Releases every controller and the client (deinitialize()). + ~XboxHost(); + + XboxHost(const XboxHost &) = delete; + XboxHost &operator=(const XboxHost &) = delete; + + /// @brief Register the USB Host Library client and start the event task. The + /// library must be installed already (espp::UsbHost::initialize() or + /// usb_host_install()). + /// @param ec Set on failure (the library not installed: invalid state). + /// @return true on success (or if already initialized). + bool initialize(std::error_code &ec); + + /// @brief Release every controller, deregister the client and stop the task. + /// Call it before the USB Host Library is uninstalled. + /// @param ec Set on failure. + /// @return true on success (or if not initialized). + bool deinitialize(std::error_code &ec); + + /// @brief Whether initialize() succeeded (and deinitialize() has not run). + bool is_initialized() const { return initialized_.load(); } + + /// @brief The connected controllers. + std::vector> controllers() const; + +private: + static void client_event_cb(const usb_host_client_event_msg_t *msg, void *arg); + static void in_transfer_cb(usb_transfer_t *transfer); + static void out_transfer_cb(usb_transfer_t *transfer); + bool task_fn(); + void scan_existing(); + void open_device(uint8_t address); + void on_device_gone(usb_device_handle_t device); + void begin_close(const std::shared_ptr &c); + bool try_finish_close(const std::shared_ptr &c); // true once released + void on_in_done(Controller *c, usb_transfer_t *transfer); + void on_out_done(Controller *c, usb_transfer_t *transfer); + void handle_packet(Controller *c, std::span data); + void publish(Controller *c, const GamepadState &state); + std::shared_ptr find(const Controller *c) const; + int next_free_player() const; + + Config config_; + std::atomic initialized_{false}; + std::atomic stopping_{false}; + std::atomic scan_pending_{false}; + std::atomic stopped_{false}; + usb_host_client_handle_t client_{nullptr}; + std::unique_ptr task_; + mutable std::mutex mutex_; // controllers_ + std::vector> controllers_; +}; +} // namespace espp diff --git a/components/xbox_host/src/xbox_host.cpp b/components/xbox_host/src/xbox_host.cpp new file mode 100644 index 0000000000..ef27b987eb --- /dev/null +++ b/components/xbox_host/src/xbox_host.cpp @@ -0,0 +1,633 @@ +#include "xbox_host.hpp" + +#include +#include +#include +#include +#include + +#include + +#include "usb/usb_helpers.h" + +using namespace espp; + +namespace { +// An ASCII rendering of a USB string descriptor (UTF-16LE); empty for none. +std::string to_ascii(const usb_str_desc_t *d) { + std::string s; + if (d == nullptr || d->bLength < 2) + return s; + const int n = (d->bLength - 2) / 2; + for (int i = 0; i < n; i++) { + const uint16_t c = d->wData[i]; + s += c >= 0x20 && c < 0x7F ? static_cast(c) : '?'; + } + return s; +} + +std::error_code make_ec(esp_err_t err) { + switch (err) { + case ESP_OK: + return {}; + case ESP_ERR_INVALID_STATE: + return std::make_error_code(std::errc::operation_not_permitted); + case ESP_ERR_NO_MEM: + return std::make_error_code(std::errc::not_enough_memory); + case ESP_ERR_INVALID_ARG: + return std::make_error_code(std::errc::invalid_argument); + case ESP_ERR_TIMEOUT: + return std::make_error_code(std::errc::timed_out); + default: + return std::make_error_code(std::errc::io_error); + } +} + +bool same_state(const GamepadState &a, const GamepadState &b) { + return a.buttons == b.buttons && a.axes == b.axes; +} + +// Xbox Series controllers (they have a Share button): Microsoft's wired PIDs +bool is_series_controller(uint16_t vid, uint16_t pid) { + return vid == 0x045E && (pid == 0x0B12 || pid == 0x0B13); +} +// controllers that need the extra power packet to start after they were last +// used over Bluetooth: the Xbox One S and the Elite Series 2 +bool needs_extra_power_on(uint16_t vid, uint16_t pid) { + return vid == 0x045E && (pid == 0x02EA || pid == 0x0B00 || pid == 0x0B05 || pid == 0x0B12); +} +} // namespace + +// ---- Controller -------------------------------------------------------------- + +GamepadState XboxHost::Controller::state() const { + std::lock_guard lk(mutex_); + return state_; +} + +bool XboxHost::Controller::set_rumble(const RumbleState &rumble) { + if (info_.protocol == Protocol::XInput) { + const auto r = xinput::rumble_report(xbox::to_xinput_rumble(rumble)); + return queue_output({r.begin(), r.end()}, /*is_rumble=*/true); + } + const auto levels = xbox::to_gip_rumble(rumble); + uint8_t seq = 0; + { + std::lock_guard lk(mutex_); + seq = sequence_.next(); + } + const auto r = + gip::rumble(seq, levels.left_trigger, levels.right_trigger, levels.strong, levels.weak); + return queue_output({r.begin(), r.end()}, /*is_rumble=*/true); +} + +bool XboxHost::Controller::set_player(int player) { + if (gone_.load()) + return false; + player_ = player; + if (info_.protocol != Protocol::XInput) + return true; // GIP has no player LEDs + const auto r = xinput::led_report(xinput::player_led(player)); + return queue_output({r.begin(), r.end()}, /*is_rumble=*/false); +} + +bool XboxHost::Controller::queue_output(std::vector data, bool is_rumble) { + std::lock_guard lk(mutex_); + if (gone_.load() || closing_ || out_transfer_ == nullptr) + return false; + if (data.size() > out_transfer_->data_buffer_size) + return false; + if (is_rumble) + pending_rumble_ = std::move(data); // only the latest rumble matters + else + out_queue_.push_back(std::move(data)); + if (!out_busy_) + submit_next_output_locked(); + return true; +} + +void XboxHost::Controller::submit_next_output_locked() { + std::vector data; + if (!out_queue_.empty()) { + data = std::move(out_queue_.front()); + out_queue_.pop_front(); + } else if (pending_rumble_) { + data = std::move(*pending_rumble_); + pending_rumble_.reset(); + } else { + return; + } + std::memcpy(out_transfer_->data_buffer, data.data(), data.size()); + out_transfer_->num_bytes = static_cast(data.size()); + const esp_err_t err = usb_host_transfer_submit(out_transfer_); + if (err == ESP_OK) + out_busy_ = true; + else + host_.logger_.warn("{:04x}:{:04x}: output submit failed: {}", info_.vid, info_.pid, + esp_err_to_name(err)); +} + +// ---- XboxHost ---------------------------------------------------------------- + +XboxHost::XboxHost(const Config &config) + : BaseComponent("XboxHost", config.log_level) + , config_(config) {} + +XboxHost::~XboxHost() { + std::error_code ec; + deinitialize(ec); +} + +bool XboxHost::initialize(std::error_code &ec) { + if (initialized_.load()) { + ec.clear(); + return true; + } + usb_host_client_config_t client_config = {}; + client_config.is_synchronous = false; + client_config.max_num_event_msg = 8; + client_config.async.client_event_callback = &XboxHost::client_event_cb; + client_config.async.callback_arg = this; + const esp_err_t err = usb_host_client_register(&client_config, &client_); + if (err != ESP_OK) { + logger_.error("usb_host_client_register failed: {} (is the USB Host Library installed?)", + esp_err_to_name(err)); + ec = make_ec(err); + client_ = nullptr; + return false; + } + stopping_ = false; + stopped_ = false; + scan_pending_ = true; // controllers attached before the client registered + task_ = Task::make_unique({ + .callback = [this](std::mutex &, std::condition_variable &) { return task_fn(); }, + .task_config = + { + .name = "xbox_host", + .stack_size_bytes = config_.task_stack_size, + .priority = config_.task_priority, + .core_id = config_.task_core_id, + .stack_alloc_caps = config_.task_stack_alloc_caps, + }, + .log_level = Logger::Verbosity::WARN, + }); + if (!task_->start()) { + logger_.error("could not start the task"); + usb_host_client_deregister(client_); + client_ = nullptr; + task_.reset(); + ec = std::make_error_code(std::errc::resource_unavailable_try_again); + return false; + } + initialized_ = true; + ec.clear(); + return true; +} + +bool XboxHost::deinitialize(std::error_code &ec) { + if (!initialized_.load()) { + ec.clear(); + return true; + } + stopping_ = true; + usb_host_client_unblock(client_); + // the task releases every controller and deregisters the client + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(2); + while (!stopped_.load() && std::chrono::steady_clock::now() < deadline) { + usb_host_client_unblock(client_); + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + const bool ok = stopped_.load(); + if (task_) + task_->stop(); + task_.reset(); + initialized_ = false; + if (!ok) { + logger_.error("timed out releasing the controllers"); + ec = std::make_error_code(std::errc::timed_out); + return false; + } + ec.clear(); + return true; +} + +std::vector> XboxHost::controllers() const { + std::lock_guard lk(mutex_); + std::vector> out; + std::copy_if(controllers_.begin(), controllers_.end(), std::back_inserter(out), + [](const auto &c) { return c->connected(); }); + return out; +} + +bool XboxHost::task_fn() { + if (scan_pending_.exchange(false)) + scan_existing(); + if (stopping_.load()) { + std::vector> all; + { + std::lock_guard lk(mutex_); + all = controllers_; + } + for (const auto &c : all) { + bool closing = false; + { + std::lock_guard lk(c->mutex_); + closing = c->closing_; + } + if (!closing) + begin_close(c); + try_finish_close(c); + } + bool empty = false; + { + std::lock_guard lk(mutex_); + empty = controllers_.empty(); + } + if (empty) { + usb_host_client_deregister(client_); + client_ = nullptr; + stopped_ = true; + return true; // stop the task + } + } + // the transfer callbacks and device events all run in here + usb_host_client_handle_events(client_, stopping_.load() ? pdMS_TO_TICKS(10) : portMAX_DELAY); + return false; +} + +void XboxHost::client_event_cb(const usb_host_client_event_msg_t *msg, void *arg) { + auto *self = static_cast(arg); + switch (msg->event) { + case USB_HOST_CLIENT_EVENT_NEW_DEV: + if (!self->stopping_.load()) + self->open_device(msg->new_dev.address); + break; + case USB_HOST_CLIENT_EVENT_DEV_GONE: + self->on_device_gone(msg->dev_gone.dev_hdl); + break; + default: + break; + } +} + +void XboxHost::scan_existing() { + uint8_t addresses[16] = {}; + int count = 0; + if (usb_host_device_addr_list_fill(sizeof(addresses), addresses, &count) != ESP_OK) + return; + for (int i = 0; i < count; i++) + open_device(addresses[i]); +} + +int XboxHost::next_free_player() const { + // (with mutex_ held) + for (int p = 1; p <= 4; p++) { + const bool used = std::any_of(controllers_.begin(), controllers_.end(), [p](const auto &c) { + return c->connected() && c->player() == p; + }); + if (!used) + return p; + } + return 0; +} + +void XboxHost::open_device(uint8_t address) { + { + std::lock_guard lk(mutex_); + if (std::any_of(controllers_.begin(), controllers_.end(), + [&](const auto &c) { return c->info_.address == address && c->connected(); })) + return; // already ours (scanned and announced) + } + usb_device_handle_t dev = nullptr; + if (usb_host_device_open(client_, address, &dev) != ESP_OK) + return; + const usb_device_desc_t *dev_desc = nullptr; + const usb_config_desc_t *cfg = nullptr; + if (usb_host_get_device_descriptor(dev, &dev_desc) != ESP_OK || + usb_host_get_active_config_descriptor(dev, &cfg) != ESP_OK || dev_desc == nullptr || + cfg == nullptr) { + usb_host_device_close(client_, dev); + return; + } + + // the first X-Input / GIP interface, and its interrupt endpoints + for (int n = 0; n < cfg->bNumInterfaces; n++) { + int offset = 0; + const usb_intf_desc_t *intf = usb_parse_interface_descriptor(cfg, n, 0, &offset); + if (intf == nullptr || intf->bInterfaceClass != 0xFF) + continue; + Protocol protocol; + if (intf->bInterfaceSubClass == xinput::kInterfaceSubClass && + intf->bInterfaceProtocol == xinput::kInterfaceProtocol) + protocol = Protocol::XInput; + else if (intf->bInterfaceSubClass == gip::kInterfaceSubClass && + intf->bInterfaceProtocol == gip::kInterfaceProtocol) + protocol = Protocol::Gip; + else + continue; + uint8_t ep_in = 0, ep_out = 0; + uint16_t mps_in = 0, mps_out = 0; + for (int i = 0; i < intf->bNumEndpoints; i++) { + int ep_offset = offset; + const usb_ep_desc_t *ep = + usb_parse_endpoint_descriptor_by_index(intf, i, cfg->wTotalLength, &ep_offset); + if (ep == nullptr || + (ep->bmAttributes & USB_BM_ATTRIBUTES_XFERTYPE_MASK) != USB_BM_ATTRIBUTES_XFER_INT) + continue; + const uint16_t mps = ep->wMaxPacketSize & 0x7FF; + if (ep->bEndpointAddress & USB_B_ENDPOINT_ADDRESS_EP_DIR_MASK) { + if (!ep_in) { + ep_in = ep->bEndpointAddress; + mps_in = mps; + } + } else if (!ep_out) { + ep_out = ep->bEndpointAddress; + mps_out = mps; + } + } + if (!ep_in || !ep_out || mps_in == 0) { + logger_.warn("{:04x}:{:04x}: {} interface {} without interrupt IN + OUT endpoints", + dev_desc->idVendor, dev_desc->idProduct, name(protocol), n); + continue; + } + esp_err_t err = usb_host_interface_claim(client_, dev, static_cast(n), 0); + if (err != ESP_OK) { + logger_.warn("{:04x}:{:04x}: could not claim interface {}: {}", dev_desc->idVendor, + dev_desc->idProduct, n, esp_err_to_name(err)); + continue; + } + + auto c = std::shared_ptr(new Controller(*this)); + c->info_.vid = dev_desc->idVendor; + c->info_.pid = dev_desc->idProduct; + c->info_.protocol = protocol; + c->info_.address = address; + c->info_.interface_number = static_cast(n); + usb_device_info_t dev_info = {}; + if (usb_host_device_info(dev, &dev_info) == ESP_OK) { + c->info_.manufacturer = to_ascii(dev_info.str_desc_manufacturer); + c->info_.product = to_ascii(dev_info.str_desc_product); + } + c->device_ = dev; + c->ep_in_ = ep_in; + c->ep_out_ = ep_out; + c->ep_in_mps_ = mps_in; + c->has_share_ = protocol == Protocol::Gip && is_series_controller(c->info_.vid, c->info_.pid); + // an IN transfer is a whole number of max-size packets + const size_t out_size = std::max(64, mps_out); + if (usb_host_transfer_alloc(mps_in, 0, &c->in_transfer_) != ESP_OK || + usb_host_transfer_alloc(out_size, 0, &c->out_transfer_) != ESP_OK) { + logger_.error("{:04x}:{:04x}: no memory for the transfers", c->info_.vid, c->info_.pid); + if (c->in_transfer_) + usb_host_transfer_free(c->in_transfer_); + c->in_transfer_ = nullptr; + usb_host_interface_release(client_, dev, static_cast(n)); + usb_host_device_close(client_, dev); + return; + } + for (auto *t : {c->in_transfer_, c->out_transfer_}) { + t->device_handle = dev; + t->context = c.get(); + t->timeout_ms = 0; + } + c->in_transfer_->bEndpointAddress = ep_in; + c->in_transfer_->callback = &XboxHost::in_transfer_cb; + c->in_transfer_->num_bytes = mps_in; + c->out_transfer_->bEndpointAddress = ep_out; + c->out_transfer_->callback = &XboxHost::out_transfer_cb; + { + std::lock_guard lk(mutex_); + c->player_ = next_free_player(); + controllers_.push_back(c); + } + { + std::lock_guard lk(c->mutex_); + err = usb_host_transfer_submit(c->in_transfer_); + c->in_busy_ = err == ESP_OK; + } + if (err != ESP_OK) + logger_.error("{:04x}:{:04x}: input submit failed: {}", c->info_.vid, c->info_.pid, + esp_err_to_name(err)); + + // start it: a GIP controller is silent until powered on + if (protocol == Protocol::Gip) { + std::vector> start; + { + std::lock_guard lk(c->mutex_); + const auto on = gip::power_on(c->sequence_.next()); + start.emplace_back(on.begin(), on.end()); + if (needs_extra_power_on(c->info_.vid, c->info_.pid)) { + const auto extra = gip::power_on_extra(c->sequence_.next()); + start.emplace_back(extra.begin(), extra.end()); + } + const auto light = gip::led(c->sequence_.next()); + start.emplace_back(light.begin(), light.end()); + } + for (auto &p : start) + c->queue_output(std::move(p), false); + } else { + c->set_player(c->player()); + } + logger_.info("{} controller {:04x}:{:04x} '{}' (address {}, interface {}, IN {:#04x} / OUT " + "{:#04x}), player {}", + name(protocol), c->info_.vid, c->info_.pid, c->info_.product, address, n, ep_in, + ep_out, c->player()); + if (config_.on_connected) + config_.on_connected(c); + return; + } + usb_host_device_close(client_, dev); // not a controller +} + +void XboxHost::on_device_gone(usb_device_handle_t device) { + std::shared_ptr c; + { + std::lock_guard lk(mutex_); + auto it = std::find_if(controllers_.begin(), controllers_.end(), + [&](const auto &x) { return x->device_ == device; }); + if (it != controllers_.end()) + c = *it; + } + if (c) + begin_close(c); +} + +void XboxHost::begin_close(const std::shared_ptr &c) { + const bool was_connected = !c->gone_.exchange(true); + { + std::lock_guard lk(c->mutex_); + c->closing_ = true; + c->out_queue_.clear(); + c->pending_rumble_.reset(); + } + if (was_connected) { + logger_.info("{} controller {:04x}:{:04x} detached", name(c->info_.protocol), c->info_.vid, + c->info_.pid); + if (config_.on_disconnected) + config_.on_disconnected(c); + } + // retire the transfers in flight: they come back cancelled (or, for an + // unplugged device, "no device"). For an unplugged device the halt fails + // and the USB Host Library logs "EP command error: ESP_ERR_INVALID_STATE" + // (as it does for ESP-IDF's own class drivers); the flush still retires them. + for (uint8_t ep : {c->ep_in_, c->ep_out_}) { + usb_host_endpoint_halt(c->device_, ep); + usb_host_endpoint_flush(c->device_, ep); + } + try_finish_close(c); +} + +bool XboxHost::try_finish_close(const std::shared_ptr &c) { + { + std::lock_guard lk(c->mutex_); + if (c->in_busy_ || c->out_busy_ || c->device_ == nullptr) + return c->device_ == nullptr; + } + for (uint8_t ep : {c->ep_in_, c->ep_out_}) + usb_host_endpoint_clear(c->device_, ep); + usb_host_interface_release(client_, c->device_, c->info_.interface_number); + usb_host_transfer_free(c->in_transfer_); + usb_host_transfer_free(c->out_transfer_); + c->in_transfer_ = nullptr; + c->out_transfer_ = nullptr; + usb_host_device_close(client_, c->device_); + c->device_ = nullptr; + logger_.debug("{} controller {:04x}:{:04x} released", name(c->info_.protocol), c->info_.vid, + c->info_.pid); + std::lock_guard lk(mutex_); + controllers_.erase(std::remove(controllers_.begin(), controllers_.end(), c), controllers_.end()); + return true; +} + +std::shared_ptr XboxHost::find(const Controller *c) const { + std::lock_guard lk(mutex_); + auto it = std::find_if(controllers_.begin(), controllers_.end(), + [&](const auto &x) { return x.get() == c; }); + return it != controllers_.end() ? *it : nullptr; +} + +void XboxHost::in_transfer_cb(usb_transfer_t *transfer) { + auto *c = static_cast(transfer->context); + c->host_.on_in_done(c, transfer); +} + +void XboxHost::out_transfer_cb(usb_transfer_t *transfer) { + auto *c = static_cast(transfer->context); + c->host_.on_out_done(c, transfer); +} + +void XboxHost::on_in_done(Controller *c, usb_transfer_t *transfer) { + { + std::lock_guard lk(c->mutex_); + c->in_busy_ = false; + } + if (transfer->status == USB_TRANSFER_STATUS_COMPLETED) { + handle_packet(c, std::span(transfer->data_buffer, transfer->actual_num_bytes)); + } else if (transfer->status != USB_TRANSFER_STATUS_NO_DEVICE && + transfer->status != USB_TRANSFER_STATUS_CANCELED) { + logger_.debug("{:04x}:{:04x}: input transfer status {}", c->info_.vid, c->info_.pid, + static_cast(transfer->status)); + } + // (a transfer back with "no device" precedes the device-gone event: do not + // resubmit it, the endpoint is going away) + const bool device_left = transfer->status == USB_TRANSFER_STATUS_NO_DEVICE || + transfer->status == USB_TRANSFER_STATUS_CANCELED; + bool closing = false; + { + std::lock_guard lk(c->mutex_); + closing = c->closing_; + if (!closing && !device_left && !c->gone_.load() && !stopping_.load()) { + transfer->num_bytes = c->ep_in_mps_; + c->in_busy_ = usb_host_transfer_submit(transfer) == ESP_OK; + } + } + if (closing) { + if (auto sp = find(c)) + try_finish_close(sp); + } +} + +void XboxHost::on_out_done(Controller *c, usb_transfer_t *transfer) { + if (transfer->status != USB_TRANSFER_STATUS_COMPLETED && + transfer->status != USB_TRANSFER_STATUS_NO_DEVICE && + transfer->status != USB_TRANSFER_STATUS_CANCELED) + logger_.debug("{:04x}:{:04x}: output transfer status {}", c->info_.vid, c->info_.pid, + static_cast(transfer->status)); + bool closing = false; + { + std::lock_guard lk(c->mutex_); + c->out_busy_ = false; + closing = c->closing_; + if (!closing && !c->gone_.load()) + c->submit_next_output_locked(); + } + if (closing) { + if (auto sp = find(c)) + try_finish_close(sp); + } +} + +void XboxHost::handle_packet(Controller *c, std::span data) { + if (c->info_.protocol == Protocol::XInput) { + if (auto in = xinput::parse_report(data)) + publish(c, xbox::to_gamepad_state(*in)); + return; + } + const auto header = gip::parse_header(data); + if (!header) + return; + if (header->wants_ack()) { + const auto ack = gip::acknowledge(*header); + c->queue_output({ack.begin(), ack.end()}, false); + } + switch (static_cast(header->command)) { + case gip::Command::Input: + if (auto in = gip::parse_input(data, c->has_share_)) { + bool guide = false; + { + std::lock_guard lk(c->mutex_); + guide = c->guide_; + } + publish(c, xbox::to_gamepad_state(*in, guide)); + } + break; + case gip::Command::VirtualKey: + if (auto down = gip::parse_guide(data)) { + GamepadState s; + { + std::lock_guard lk(c->mutex_); + c->guide_ = *down; + s = c->state_; + } + s.set(GamepadState::Button::Home, *down); + publish(c, s); + } + break; + case gip::Command::Announce: { + // (re)announced: power it on (again) + uint8_t seq = 0; + { + std::lock_guard lk(c->mutex_); + seq = c->sequence_.next(); + } + const auto on = gip::power_on(seq); + c->queue_output({on.begin(), on.end()}, false); + break; + } + default: + break; // status, identify, ... : nothing to do + } +} + +void XboxHost::publish(Controller *c, const GamepadState &state) { + bool changed = false; + { + std::lock_guard lk(c->mutex_); + changed = !same_state(c->state_, state); + c->state_ = state; + } + if (!config_.on_state || (config_.only_on_change && !changed)) + return; + if (auto sp = find(c)) + config_.on_state(sp, state); +} diff --git a/components/xbox_host/test/CMakeLists.txt b/components/xbox_host/test/CMakeLists.txt new file mode 100644 index 0000000000..a04ed68d8e --- /dev/null +++ b/components/xbox_host/test/CMakeLists.txt @@ -0,0 +1,2 @@ +# Host tests of xbox_host (see test/EsppTest.cmake and test/README.md). +espp_add_component_test(xbox_host_test DOCTEST SOURCES xbox_host_test.cpp) diff --git a/components/xbox_host/test/xbox_host_test.cpp b/components/xbox_host/test/xbox_host_test.cpp new file mode 100644 index 0000000000..587930633e --- /dev/null +++ b/components/xbox_host/test/xbox_host_test.cpp @@ -0,0 +1,175 @@ +// Host-buildable unit tests for xbox_host's wire formats: the GIP (Xbox One / +// Series) packets a host parses and sends (gip.hpp), and the conversions of +// both controller families to and from gamepad_map's GamepadState / +// RumbleState (xbox_gamepad_state.hpp). No ESP-IDF headers required. +// +// From the repository root: +// ./run_host_tests.sh xbox_host_test + +#include + +#include + +#include "gip.hpp" +#include "xbox_gamepad_state.hpp" + +using namespace espp; +using B = GamepadState::Button; +using A = GamepadState::Axis; + +namespace { +// An Xbox One input packet: header + 14 payload bytes (+ @p extra). +std::vector input_packet(uint16_t buttons, uint16_t lt, uint16_t rt, int16_t lx, + int16_t ly, int16_t rx, int16_t ry, size_t extra = 0) { + std::vector p = {0x20, 0x00, 0x07, static_cast(14 + extra)}; + auto put16 = [&](uint16_t v) { + p.push_back(static_cast(v & 0xFF)); + p.push_back(static_cast(v >> 8)); + }; + put16(buttons); + put16(lt); + put16(rt); + put16(static_cast(lx)); + put16(static_cast(ly)); + put16(static_cast(rx)); + put16(static_cast(ry)); + p.resize(p.size() + extra, 0); + return p; +} +} // namespace + +TEST_CASE("GIP: an input packet's controls") { + using G = gip::Button; + const uint16_t buttons = static_cast(G::A) | static_cast(G::Menu) | + static_cast(G::DpadRight) | + static_cast(G::RightStick); + const auto p = input_packet(buttons, 1023, 512, -32768, 32767, 100, -100); + const auto in = gip::parse_input(p); + REQUIRE(in.has_value()); + CHECK((in->get(G::A) && in->get(G::Menu) && in->get(G::DpadRight) && in->get(G::RightStick))); + CHECK((!in->get(G::B) && !in->get(G::View))); + CHECK((in->left_trigger == 1023 && in->right_trigger == 512)); + CHECK((in->lx == -32768 && in->ly == 32767 && in->rx == 100 && in->ry == -100)); + CHECK(!in->share); + + // other packets, and a short one, are not input packets + const uint8_t announce[8] = {0x02, 0x20, 0x01, 0x1c, 0, 0, 0, 0}; + CHECK(!gip::parse_input(announce).has_value()); + CHECK(!gip::parse_input(std::span(p).first(10)).has_value()); +} + +TEST_CASE("GIP: the Share button of a Series controller") { + auto p = input_packet(0, 0, 0, 0, 0, 0, 0, /*extra=*/16); + p[gip::kShareByte] = 0x01; + CHECK(gip::parse_input(p, /*has_share=*/true)->share); + CHECK(!gip::parse_input(p, /*has_share=*/false)->share); // an Xbox One: not read + // an Xbox One's shorter packet has no Share byte at all + CHECK(!gip::parse_input(input_packet(0, 0, 0, 0, 0, 0, 0), true)->share); +} + +TEST_CASE("GIP: the Xbox button and its acknowledgement") { + const uint8_t down[6] = {0x07, 0x30, 0x2a, 0x02, 0x01, 0x5b}; // internal + wants an ack + const uint8_t up[6] = {0x07, 0x20, 0x2b, 0x02, 0x00, 0x5b}; + CHECK(gip::parse_guide(down) == true); + CHECK(gip::parse_guide(up) == false); + CHECK(!gip::parse_guide(input_packet(0, 0, 0, 0, 0, 0, 0)).has_value()); + + const auto h = gip::parse_header(down); + REQUIRE(h.has_value()); + CHECK(h->wants_ack()); + CHECK(!gip::parse_header(up)->wants_ack()); + const auto ack = gip::acknowledge(*h); + // ack command, internal, the packet's sequence, 9 bytes: names the packet + CHECK((ack[0] == 0x01 && ack[1] == 0x20 && ack[2] == 0x2a && ack[3] == 0x09)); + CHECK((ack[5] == 0x07 && ack[6] == 0x20 && ack[7] == 0x02)); +} + +TEST_CASE("GIP: the packets a host sends") { + CHECK(gip::power_on(1) == std::array{0x05, 0x20, 0x01, 0x01, 0x00}); + CHECK(gip::power_on_extra(2) == std::array{0x05, 0x20, 0x02, 0x0f, 0x06}); + CHECK(gip::led(3) == std::array{0x0a, 0x20, 0x03, 0x03, 0x00, 0x01, 0x14}); + const auto r = gip::rumble(4, 10, 20, 100, 250 /* clamped to 100 */); + CHECK(r == std::array{0x09, 0x00, 0x04, 0x09, 0x00, 0x0f, 10, 20, 100, 100, 0xff, + 0x00, 0xeb}); + + gip::Sequence seq; + CHECK(seq.next() == 1); + for (int i = 0; i < 253; i++) + seq.next(); + CHECK(seq.next() == 255); + CHECK(seq.next() == 1); // 0 is skipped +} + +TEST_CASE("X-Input report -> GamepadState") { + xinput::GamepadState in; + in.set(xinput::Button::A, true); // south + in.set(xinput::Button::Y, true); // north + in.set(xinput::Button::Back, true); + in.set(xinput::Button::Guide, true); + in.set(xinput::Button::DpadDown, true); + in.left_trigger = 255; + in.right_trigger = 20; // under the button threshold + in.lx = 32767; + in.ly = 32767; // up + in.rx = -32768; + in.ry = -32768; // down + const auto s = xbox::to_gamepad_state(in); + CHECK((s.pressed(B::South) && s.pressed(B::North) && !s.pressed(B::East) && !s.pressed(B::West))); + CHECK((s.pressed(B::Select) && s.pressed(B::Home) && s.pressed(B::Down))); + CHECK(s.axis(A::LeftTrigger) == GamepadState::AXIS_MAX); + CHECK(s.pressed(B::L2)); + CHECK((s.axis(A::RightTrigger) > 0 && !s.pressed(B::R2))); + CHECK(s.axis(A::LeftX) == 32767); + CHECK(s.axis(A::LeftY) == -32767); // up: negative in GamepadState + CHECK(s.axis(A::RightX) == -32767); // clamped to the axis range + CHECK(s.axis(A::RightY) == 32767); // down: positive +} + +TEST_CASE("GIP input -> GamepadState") { + using G = gip::Button; + gip::InputState in; + in.buttons = static_cast(G::B) | static_cast(G::View) | + static_cast(G::LeftBumper); + in.left_trigger = 0; + in.right_trigger = 1023; + in.ly = -32768; + in.share = true; + const auto s = xbox::to_gamepad_state(in, /*guide=*/true); + CHECK((s.pressed(B::East) && s.pressed(B::Select) && s.pressed(B::L1))); + CHECK((s.pressed(B::Home) && s.pressed(B::Capture))); + CHECK((s.axis(A::RightTrigger) == GamepadState::AXIS_MAX && s.pressed(B::R2))); + CHECK((s.axis(A::LeftTrigger) == 0 && !s.pressed(B::L2))); + CHECK(s.axis(A::LeftY) == 32767); // stick down + CHECK(!xbox::to_gamepad_state(in, false).pressed(B::Home)); +} + +TEST_CASE("the conversions stay in the axis range at the extremes") { + using xbox::detail::flip_y; + using xbox::detail::stick; + using xbox::detail::trigger; + CHECK(stick(-32768) == -GamepadState::AXIS_MAX); + CHECK(stick(32767) == GamepadState::AXIS_MAX); + CHECK(flip_y(-32768) == GamepadState::AXIS_MAX); // -(-32768) would be 32768 + CHECK(flip_y(32767) == -GamepadState::AXIS_MAX); + CHECK(trigger(0, gip::kTriggerMax) == 0); + CHECK(trigger(gip::kTriggerMax, gip::kTriggerMax) == GamepadState::AXIS_MAX); + CHECK(trigger(0xFFFF, gip::kTriggerMax) == GamepadState::AXIS_MAX); // past a full press + CHECK(trigger(255, 255) == GamepadState::AXIS_MAX); + // a GIP packet whose trigger field is past 1023 is a full press, not more + gip::InputState in; + in.left_trigger = 0xFFFF; + const auto s = xbox::to_gamepad_state(in, false); + CHECK((s.axis(A::LeftTrigger) == GamepadState::AXIS_MAX && s.pressed(B::L2))); +} + +TEST_CASE("RumbleState -> the controllers' rumble levels") { + using M = RumbleState::Motor; + RumbleState r; + r.set(M::Strong, 255); + r.set(M::Weak, 128); + r.set(M::LeftTrigger, 51); + const auto x = xbox::to_xinput_rumble(r); + CHECK((x.left == 255 && x.right == 128)); + CHECK(xbox::to_gip_rumble(r) == xbox::GipRumble{20, 0, 100, 50}); + CHECK(xbox::to_gip_rumble(RumbleState{}) == xbox::GipRumble{}); +} diff --git a/components/xinput/CMakeLists.txt b/components/xinput/CMakeLists.txt new file mode 100644 index 0000000000..28b98b8c9a --- /dev/null +++ b/components/xinput/CMakeLists.txt @@ -0,0 +1,3 @@ +# Header-only: the X-Input (Xbox 360 controller) wire format, shared by the +# device side (usb_device) and the host side (xbox_host) +idf_component_register(INCLUDE_DIRS "include") diff --git a/components/xinput/README.md b/components/xinput/README.md new file mode 100644 index 0000000000..fa714007cc --- /dev/null +++ b/components/xinput/README.md @@ -0,0 +1,31 @@ +# X-Input Component + +[![Badge](https://components.espressif.com/components/espp/xinput/badge.svg)](https://components.espressif.com/components/espp/xinput) + +`xinput.hpp` is the wire format of X-Input, the protocol of the wired Xbox 360 +controller (and of most third-party controllers in their "X-input" mode). It is +header-only and dependency-free (no ESP-IDF or TinyUSB headers), so it builds +and is tested on a computer too, and it serves both ends of the cable: + +- [`usb_device`](../usb_device) presents an X-Input controller to a PC or + console: it packs `xinput::GamepadState::report()` and reads the host's + rumble with `xinput::decode_rumble()`; +- [`xbox_host`](../xbox_host) reads an X-Input controller plugged into a USB + host port: it parses `xinput::parse_report()` and sends + `xinput::rumble_report()` / `xinput::led_report()`. + +## Wire format + +An X-Input controller presents a vendor-specific interface (class `0xFF`, +subclass `0x5D`, protocol `0x01`) with one interrupt IN and one interrupt OUT +endpoint. + +| Direction | Message | Bytes | +|-----------|---------|-------| +| IN | input report | `00 14 ` + 6 reserved (sticks int16 little-endian, Y up positive) | +| IN | LED status | `01 03 ` | +| OUT | rumble | `00 08 00 00 00 00` | +| OUT | LED ring | `01 03 ` (`xinput::Led`, `xinput::player_led(n)`) | + +See `include/xinput.hpp` for the button bits (`xinput::Button`) and the +interface + XID descriptor builder. diff --git a/components/xinput/idf_component.yml b/components/xinput/idf_component.yml new file mode 100644 index 0000000000..52a4d1feba --- /dev/null +++ b/components/xinput/idf_component.yml @@ -0,0 +1,18 @@ +## IDF Component Manager Manifest File +license: "MIT" +description: "Header-only X-Input (Xbox 360 controller) wire format: the 20-byte input report, rumble and LED-ring reports and the interface / XID descriptor, for USB devices and hosts" +url: "https://github.com/esp-cpp/espp/tree/main/components/xinput" +repository: "git://github.com/esp-cpp/espp.git" +maintainers: + - William Emfinger +documentation: "https://esp-cpp.github.io/espp/buses/usb_cdc.html" +tags: + - cpp + - Component + - USB + - XInput + - Xbox + - Gamepad +dependencies: + idf: + version: '>=5.0' diff --git a/components/usb_device/include/xinput.hpp b/components/xinput/include/xinput.hpp similarity index 77% rename from components/usb_device/include/xinput.hpp rename to components/xinput/include/xinput.hpp index 0b76956eca..bc77cc307c 100644 --- a/components/usb_device/include/xinput.hpp +++ b/components/xinput/include/xinput.hpp @@ -4,9 +4,11 @@ // // This header is dependency-free and host-testable (no ESP-IDF / TinyUSB // headers): it defines the X-Input wire constants, a gamepad-state model that -// packs the 20-byte input report, and a builder for the USB interface + XID + -// interrupt-endpoint descriptor bytes. `espp::UsbDevice`'s XInput function -// (usb_device.hpp) consumes these on-device; a host test exercises `report()`. +// packs (device) and parses (host) the 20-byte input report, the rumble and +// LED-ring reports (host -> device), and a builder for the USB interface + XID +// + interrupt-endpoint descriptor bytes. Both ends use it: `espp::UsbDevice`'s +// XInput function (usb_device) presents an X-Input controller, and +// `espp::XboxHost` (xbox_host) reads one plugged into a USB host port. // // X-Input is Microsoft's proprietary protocol for the Xbox 360 controller. The // device presents a vendor-specific interface (bInterfaceClass 0xFF / @@ -114,6 +116,25 @@ struct GamepadState { } }; +/// The gamepad state in a 20-byte input report from a controller (the inverse +/// of GamepadState::report()), or nullopt for a report that is not an input +/// report. Controllers send other messages on the IN endpoint too (LED status +/// `01 03 ..`, headset / chatpad `02 ..` / `03 ..`), which are skipped here. +inline std::optional parse_report(std::span r) { + if (r.size() < 14 || r[0] != 0x00 || r[1] < 14) + return std::nullopt; + auto get16 = [&](std::size_t i) { return static_cast(r[i] | (r[i + 1] << 8)); }; + GamepadState s; + s.buttons = static_cast(r[2] | (r[3] << 8)); + s.left_trigger = r[4]; + s.right_trigger = r[5]; + s.lx = get16(6); + s.ly = get16(8); + s.rx = get16(10); + s.ry = get16(12); + return s; +} + /// The two motor levels of an X-Input rumble report. struct Rumble { uint8_t left{0}; ///< the large, low-frequency motor (left grip), 0..255 @@ -132,6 +153,36 @@ inline std::optional decode_rumble(std::span report) { return Rumble{report[3], report[4]}; } +/// The rumble report a host sends on the OUT endpoint: `00 08 00 +/// 00 00 00` (the inverse of decode_rumble()). +inline std::array rumble_report(const Rumble &rumble) { + return {0x00, 0x08, 0x00, rumble.left, rumble.right, 0x00, 0x00, 0x00}; +} + +/// The animations of the LED ring around the Guide button (the pattern byte of +/// an LED report; the "player" ones light that quadrant after a short flash). +enum class Led : uint8_t { + Off = 0x00, + BlinkAll = 0x01, + Player1 = 0x06, ///< flash, then quadrant 1 on + Player2 = 0x07, + Player3 = 0x08, + Player4 = 0x09, + Rotate = 0x0A, + SlowBlinkAll = 0x0D, + Alternate = 0x0E, +}; + +/// The LED ring for a player number (1..4; anything else: all off). +constexpr Led player_led(int player) { + return player >= 1 && player <= 4 ? static_cast(0x05 + player) : Led::Off; +} + +/// The LED report a host sends on the OUT endpoint: `01 03 `. +inline std::array led_report(Led pattern) { + return {0x01, 0x03, static_cast(pattern)}; +} + /// Build the interface + XID + two interrupt-endpoint descriptor bytes for an /// X-Input interface. @p ep_in and @p ep_out are the full endpoint ADDRESSES /// (e.g. 0x81 IN, 0x02 OUT). The retail controller shares endpoint number 1 for diff --git a/components/xinput/test/CMakeLists.txt b/components/xinput/test/CMakeLists.txt new file mode 100644 index 0000000000..cf66197ea5 --- /dev/null +++ b/components/xinput/test/CMakeLists.txt @@ -0,0 +1,2 @@ +# Host tests of xinput (see test/EsppTest.cmake and test/README.md). +espp_add_component_test(xinput_host_test DOCTEST SOURCES xinput_host_test.cpp) diff --git a/components/usb_device/test/xinput_host_test.cpp b/components/xinput/test/xinput_host_test.cpp similarity index 61% rename from components/usb_device/test/xinput_host_test.cpp rename to components/xinput/test/xinput_host_test.cpp index f8913abb08..7a35832cb0 100644 --- a/components/usb_device/test/xinput_host_test.cpp +++ b/components/xinput/test/xinput_host_test.cpp @@ -1,6 +1,7 @@ // Host-buildable unit tests for the espp X-Input (Xbox 360) helpers in -// include/xinput.hpp: the 20-byte input-report packing and the interface + XID + -// endpoint descriptor builder. No ESP-IDF / TinyUSB headers required. +// include/xinput.hpp: the 20-byte input report (packed by a device, parsed by a +// host), the rumble / LED reports and the interface + XID + endpoint descriptor +// builder. No ESP-IDF / TinyUSB headers required. // // From the repository root: // ./run_host_tests.sh xinput_host_test @@ -73,3 +74,42 @@ TEST_CASE("rumble reports from the host") { CHECK(!decode_rumble(short_report).has_value()); } } + +TEST_CASE("a host parses a controller's input report") { + GamepadState s; + s.set(Button::B, true); + s.set(Button::Guide, true); + s.set(Button::DpadLeft, true); + s.left_trigger = 17; + s.right_trigger = 255; + s.lx = -32768; + s.ly = 12345; + s.rx = 1; + s.ry = -1; + const auto r = s.report(); + const auto parsed = parse_report(r); + REQUIRE(parsed.has_value()); + CHECK(parsed->buttons == s.buttons); + CHECK((parsed->left_trigger == 17 && parsed->right_trigger == 255)); + CHECK((parsed->lx == -32768 && parsed->ly == 12345 && parsed->rx == 1 && parsed->ry == -1)); + CHECK((parsed->get(Button::B) && parsed->get(Button::Guide) && parsed->get(Button::DpadLeft))); + + // other messages on the IN endpoint are not input reports + const uint8_t led_status[3] = {0x01, 0x03, 0x06}; + CHECK(!parse_report(led_status).has_value()); + const uint8_t too_short[8] = {0x00, 0x14, 0, 0, 0, 0, 0, 0}; + CHECK(!parse_report(too_short).has_value()); +} + +TEST_CASE("a host builds rumble and LED reports") { + const auto rumble = rumble_report(Rumble{0xC8, 0x40}); + CHECK(rumble == std::array{0x00, 0x08, 0x00, 0xC8, 0x40, 0x00, 0x00, 0x00}); + // what the device side decodes + CHECK(decode_rumble(rumble) == Rumble{0xC8, 0x40}); + + CHECK(led_report(Led::Player2) == std::array{0x01, 0x03, 0x07}); + CHECK(player_led(1) == Led::Player1); + CHECK(player_led(4) == Led::Player4); + CHECK(player_led(0) == Led::Off); + CHECK(player_led(5) == Led::Off); +} diff --git a/doc/Doxyfile b/doc/Doxyfile index 23ec6deff9..0d302e8f12 100755 --- a/doc/Doxyfile +++ b/doc/Doxyfile @@ -198,6 +198,7 @@ EXAMPLE_PATH = \ $(PROJECT_PATH)/components/stream_frame/example/main/stream_frame_example.cpp \ $(PROJECT_PATH)/components/switch2_pro/example/main/switch2_pro_example.cpp \ $(PROJECT_PATH)/components/switch_pro/example/main/switch_pro_example.cpp \ + $(PROJECT_PATH)/components/switch_pro/host_example/main/switch_pro_host_example.cpp \ $(PROJECT_PATH)/components/sx126x/example/main/sx126x_example.cpp \ $(PROJECT_PATH)/components/system/example/main/system_example.cpp \ $(PROJECT_PATH)/components/tabulate/example/main/tabulate_example.cpp \ @@ -217,6 +218,7 @@ EXAMPLE_PATH = \ $(PROJECT_PATH)/components/usb_device/example/main/usb_device_example.cpp \ $(PROJECT_PATH)/components/usb_device/msc_example/main/msc_example.cpp \ $(PROJECT_PATH)/components/usb_device/xinput_example/main/xinput_example.cpp \ + $(PROJECT_PATH)/components/xbox_host/example/main/xbox_host_example.cpp \ $(PROJECT_PATH)/components/usb_host/example/main/usb_host_example.cpp \ $(PROJECT_PATH)/components/usb_host/tab5_example/main/usb_host_tab5_example.cpp \ $(PROJECT_PATH)/components/wdi/ble_example/main/wdi_ble_example.cpp \ @@ -506,6 +508,7 @@ INPUT = \ $(PROJECT_PATH)/components/switch2_pro/include/switch2_pro_protocol.hpp \ $(PROJECT_PATH)/components/switch2_pro/include/switch2_pro_report.hpp \ $(PROJECT_PATH)/components/switch_pro/include/switch_pro.hpp \ + $(PROJECT_PATH)/components/switch_pro/include/switch_pro_host.hpp \ $(PROJECT_PATH)/components/sx126x/include/sx126x.hpp \ $(PROJECT_PATH)/components/system/include/system_control.hpp \ $(PROJECT_PATH)/components/system/include/system_info.hpp \ @@ -529,8 +532,11 @@ INPUT = \ $(PROJECT_PATH)/components/tt21100/include/tt21100.hpp \ $(PROJECT_PATH)/components/usb_device/include/usb_device.hpp \ $(PROJECT_PATH)/components/usb_device/include/usb_cdc.hpp \ - $(PROJECT_PATH)/components/usb_device/include/xinput.hpp \ + $(PROJECT_PATH)/components/xinput/include/xinput.hpp \ $(PROJECT_PATH)/components/usb_host/include/usb_host.hpp \ + $(PROJECT_PATH)/components/xbox_host/include/xbox_host.hpp \ + $(PROJECT_PATH)/components/xbox_host/include/gip.hpp \ + $(PROJECT_PATH)/components/xbox_host/include/xbox_gamepad_state.hpp \ $(PROJECT_PATH)/components/wdi/include/detail/wdi_protocol.hpp \ $(PROJECT_PATH)/components/wdi/include/wdi.hpp \ $(PROJECT_PATH)/components/wdi/include/wdi_hid.hpp \ diff --git a/doc/en/buses/index.rst b/doc/en/buses/index.rst index 1ad45919f1..d90eac663c 100644 --- a/doc/en/buses/index.rst +++ b/doc/en/buses/index.rst @@ -14,3 +14,4 @@ external chips. canopen usb_cdc usb_host + xbox_host diff --git a/doc/en/buses/xbox_host.rst b/doc/en/buses/xbox_host.rst new file mode 100644 index 0000000000..4941d46ce5 --- /dev/null +++ b/doc/en/buses/xbox_host.rst @@ -0,0 +1,46 @@ +Xbox Controller Host +******************** + +Overview +-------- + +``espp::XboxHost`` reads **wired Xbox controllers** plugged into an ESP32-S2 / +-S3 / -P4 USB host port: Xbox 360 controllers and the third-party controllers +that speak their protocol (X-Input, as most controllers' "X-input" mode does), +and Xbox One / Xbox Series controllers (GIP). It decodes their input into +gamepad_map's ``espp::GamepadState`` and drives their rumble (``espp::RumbleState``) +and, for X-Input, the player LED. + +Neither family is a USB HID device: both present a vendor-specific interface +(X-Input: class ``0xFF`` / subclass ``0x5D`` / protocol ``0x01``; GIP: ``0xFF`` / +``0x47`` / ``0xD0``) with an interrupt IN and an interrupt OUT endpoint, so a HID +host driver such as ``espp::UsbHost``'s never sees them. ``XboxHost`` is a second +client of the ESP-IDF USB Host Library that claims those interfaces: it starts +each controller (a GIP controller stays silent until the host powers it on, and +asks for its Xbox button presses to be acknowledged), decodes its packets and +sends it rumble. + +``XboxHost`` does not install the USB Host Library: ``espp::UsbHost`` (or your +own ``usb_host_install()``) does, and ``XboxHost`` registers its client alongside, +so HID devices and Xbox controllers share the port. Controllers already attached +when ``XboxHost`` initializes are picked up too. + +The wire formats are header-only and host-tested: ``xinput.hpp`` (the ``xinput`` +component, shared with ``espp::UsbDevice``'s X-Input function), ``gip.hpp`` and +``xbox_gamepad_state.hpp`` (the conversions to and from ``GamepadState`` / +``RumbleState``). + +.. ------------------------------- Example ------------------------------------- + +.. toctree:: + + xbox_host_example.md + +.. ---------------------------- API Reference ---------------------------------- + +API Reference +------------- + +.. include-build-file:: inc/xbox_host.inc +.. include-build-file:: inc/gip.inc +.. include-build-file:: inc/xbox_gamepad_state.inc diff --git a/doc/en/buses/xbox_host_example.md b/doc/en/buses/xbox_host_example.md new file mode 100644 index 0000000000..7c9614228b --- /dev/null +++ b/doc/en/buses/xbox_host_example.md @@ -0,0 +1,2 @@ +```{include} ../../../components/xbox_host/example/README.md +``` diff --git a/doc/en/hid/switch_pro.rst b/doc/en/hid/switch_pro.rst index 61bc2972bd..8061c1aa3b 100644 --- a/doc/en/hid/switch_pro.rst +++ b/doc/en/hid/switch_pro.rst @@ -31,11 +31,33 @@ Switch compares against the original -- ``bcd_device`` (device release 2.10), ``espp::UsbDevice::Config`` (``vid`` / ``pid`` / ``manufacturer`` / ``product`` / ``bcd_device`` / ``max_power_ma`` / ``remote_wakeup``), as the example does. +Host side: ``espp::SwitchProHost`` +---------------------------------- + +The other end of the cable: ``espp::SwitchProHost`` reads a real Pro controller +plugged into a USB host port. Over USB the Pro controller is a HID device, but a +generic HID gamepad decoder cannot read it: it reports nothing useful until a host +runs its handshake, and its full input report (``0x30``) is vendor-defined. +``SwitchProHost`` runs that handshake (the ``0x80`` init commands, then the full +input report mode, the stick calibration from the controller's SPI flash, +vibration and the player lights) and decodes every input report into +gamepad_map's ``espp::GamepadState``; it also drives the rumble +(``espp::RumbleState``) and the player lights. + +Like ``SwitchPro`` it is transport-light: give it a function that sends an OUTPUT +report (``espp::UsbHost::HidDevice::send_output_report()`` matches it), feed it +the controller's INPUT reports, and call ``update()`` every 10..50 ms while it +starts (it resends a step whose reply is late, and skips one that is never +answered). A calibration that covers the whole 12-bit range, as some third-party +controllers that present themselves as a Pro controller store, is replaced by +typical values so their sticks still reach full deflection. + .. ------------------------------- Example ------------------------------------- .. toctree:: switch_pro_example + switch_pro_host_example .. ---------------------------- API Reference ---------------------------------- @@ -43,3 +65,4 @@ API Reference ------------- .. include-build-file:: inc/switch_pro.inc +.. include-build-file:: inc/switch_pro_host.inc diff --git a/doc/en/hid/switch_pro_host_example.md b/doc/en/hid/switch_pro_host_example.md new file mode 100644 index 0000000000..a236722ca6 --- /dev/null +++ b/doc/en/hid/switch_pro_host_example.md @@ -0,0 +1,2 @@ +```{include} ../../../components/switch_pro/host_example/README.md +``` diff --git a/suppressions.txt b/suppressions.txt index fc88f170a8..c9c122070e 100644 --- a/suppressions.txt +++ b/suppressions.txt @@ -20,3 +20,10 @@ unreadVariable:components/wdi/test/wdi_device_host_test.cpp redundantAssignment:components/wdi/test/wdi_device_host_test.cpp unreadVariable:components/wdi/test/wdi_host_host_test.cpp redundantAssignment:components/wdi/test/wdi_host_host_test.cpp + +// The SwitchProHost host test drives the handshake through a fake controller +// whose send / state callbacks (std::function) fill vectors; cppcheck can't +// trace those writes through the lambdas, so it reports the vectors as always +// empty (and the fake's send as always succeeding). +knownConditionTrueFalse:components/switch_pro/test/switch_pro_host_test.cpp +containerOutOfBounds:components/switch_pro/test/switch_pro_host_test.cpp