From 7aaa7a09be43bf91eddb6c474cd7aeaa0dd8c933 Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Mon, 23 Nov 2026 15:15:16 -0700 Subject: [PATCH 1/3] feat(hid-rp, gamepad_map, switch_pro, usb_device): descriptor-driven rumble building blocks The first step of generic rumble for controller bridges: decode a host's rumble request into one normalised state, and drive a controller's motors from its own report descriptor rather than a known VID/PID. - hid-rp ReportMap maps Output fields too (output_fields(), output_report_bytes()), each with its unit and unit exponent. Inputs are unchanged: their own field list and bit cursors, and only input report IDs set uses_report_ids(). - hid-rp-rumble.hpp (new): - RumbleEncoder::from_report_map() finds a Physical Interface Device style output report (DC Enable Actuators, a Magnitude per actuator, Duration, Start Delay, Loop Count), as the Xbox Wireless controller declares over BLE. The descriptor gives the layout. Which Magnitude drives which motor follows the Xbox convention (Linux hid-microsoft: LT, RT, strong, weak; enable bit i = actuator n-1-i), with set_motor() to override. An effect plays once for its duration (clamped to the field), so callers re-send while the rumble lasts and a lost stop is bounded. - decode_switch_rumble[_report]() reads a Switch host's HD rumble (both bands, the amplitude code inverted per dekuNukem's table) from output reports 0x01 and 0x10, both [id][packet number][8 rumble bytes]. - gamepad_map: RumbleState (rumble_state.hpp), the output counterpart of GamepadState (strong / weak / two trigger motors, 0..255), plus the to_rumble_levels() / to_rumble_state() bridges in gamepad_state_hid_rp.hpp. It is also in the desktop umbrella header. - switch_pro: Config::on_rumble, called from on_hid_report() for every 0x01 / 0x10 report (replaces the 0x10 TODO). - usb_device: xinput::decode_rumble() for the X-Input OUT endpoint (rumble reports; LED reports are not rumble). Tests (host, -Werror, g++ and clang): - hid_rp_rumble_host_test: the Xbox descriptor's output fields at their offsets, its encoder byte for byte against espp's hand-written XboxRumbleOutputReport, a synthetic 2-motor layout (16-bit magnitudes, a 1-bit enable flag, ms durations), no encoder for the Switch Pro descriptor (constant vendor outputs), Switch decoding (neutral, full, monotonic, the packet-number offset); - gamepad_map and xinput tests extended. The existing hid-rp tests still pass. The switch_pro, xinput, gamepad_map and hid-rp examples build for ESP32-S3 (IDF 6.1). Docs: READMEs, docs pages and the Doxyfile entries for the new headers. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU --- components/gamepad_map/README.md | 15 + .../include/gamepad_state_hid_rp.hpp | 31 ++ .../gamepad_map/include/rumble_state.hpp | 58 ++++ .../test/gamepad_map_host_test.cpp | 22 ++ components/hid-rp/README.md | 38 +++ .../hid-rp/include/hid-rp-report-map.hpp | 57 +++- components/hid-rp/include/hid-rp-rumble.hpp | 294 ++++++++++++++++++ .../hid-rp/test/hid_rp_rumble_host_test.cpp | 232 ++++++++++++++ components/switch_pro/README.md | 4 + components/switch_pro/include/switch_pro.hpp | 9 + components/switch_pro/src/switch_pro.cpp | 13 +- components/usb_device/README.md | 4 +- components/usb_device/include/xinput.hpp | 20 ++ .../usb_device/test/xinput_host_test.cpp | 13 + doc/Doxyfile | 2 + doc/en/hid/hid-rp.rst | 8 + doc/en/input/gamepad_map.rst | 1 + lib/include/espp.hpp | 1 + 18 files changed, 809 insertions(+), 13 deletions(-) create mode 100644 components/gamepad_map/include/rumble_state.hpp create mode 100644 components/hid-rp/include/hid-rp-rumble.hpp create mode 100644 components/hid-rp/test/hid_rp_rumble_host_test.cpp diff --git a/components/gamepad_map/README.md b/components/gamepad_map/README.md index aa0b9f1366..0075a821b7 100644 --- a/components/gamepad_map/README.md +++ b/components/gamepad_map/README.md @@ -124,6 +124,21 @@ if (decoder.update(report_id, payload, report)) // BLE: the ID comes out of ba send(map.apply(espp::to_gamepad_state(report))); ``` +## Rumble + +`RumbleState` (`rumble_state.hpp`) is the output-direction counterpart of +`GamepadState`: how strongly to drive each motor (strong / weak, plus the two +impulse-trigger motors), 0..255. A host's rumble request is decoded into it, and +it is encoded into whatever drives the motors. `gamepad_state_hid_rp.hpp` bridges +it to `hid-rp`: + +```cpp +// a Switch host's rumble (espp::SwitchPro::Config::on_rumble) to a BLE +// controller's rumble report (hid_rp::RumbleEncoder from its report map) +auto state = espp::to_rumble_state(switch_rumble); +auto payload = encoder.encode(espp::to_rumble_levels(state), 200); +``` + ## Web console `espp::GamepadMapService` serves a `GamepadProfiles` store over any framed byte diff --git a/components/gamepad_map/include/gamepad_state_hid_rp.hpp b/components/gamepad_map/include/gamepad_state_hid_rp.hpp index 1433829698..172a7247f7 100644 --- a/components/gamepad_map/include/gamepad_state_hid_rp.hpp +++ b/components/gamepad_map/include/gamepad_state_hid_rp.hpp @@ -2,6 +2,8 @@ #include "gamepad_state.hpp" #include "hid-rp-report-map.hpp" +#include "hid-rp-rumble.hpp" +#include "rumble_state.hpp" namespace espp { @@ -49,4 +51,33 @@ inline GamepadState to_gamepad_state(const hid_rp::GamepadReport &r) { return s; } +/** + * @brief The levels to hand a hid_rp::RumbleEncoder for a RumbleState. + * @param r The rumble state. + * @return The same levels, motor by motor. + */ +inline hid_rp::RumbleLevels to_rumble_levels(const RumbleState &r) { + using M = RumbleState::Motor; + return {.strong = r.level(M::Strong), + .weak = r.level(M::Weak), + .left_trigger = r.level(M::LeftTrigger), + .right_trigger = r.level(M::RightTrigger)}; +} + +/** + * @brief A RumbleState from the motor levels of a Switch host's rumble packet + * (hid_rp::decode_switch_rumble()). + * + * @details The left Joy-Con / grip motor drives Strong and the right one + * Weak, as a hand-held controller places them. + * @param r The decoded packet. + * @return The state. + */ +inline RumbleState to_rumble_state(const hid_rp::SwitchRumble &r) { + RumbleState s; + s.set(RumbleState::Motor::Strong, r.left); + s.set(RumbleState::Motor::Weak, r.right); + return s; +} + } // namespace espp diff --git a/components/gamepad_map/include/rumble_state.hpp b/components/gamepad_map/include/rumble_state.hpp new file mode 100644 index 0000000000..2624bfce45 --- /dev/null +++ b/components/gamepad_map/include/rumble_state.hpp @@ -0,0 +1,58 @@ +#pragma once + +#include +#include +#include +#include + +namespace espp { + +/** + * @brief How strongly to drive a gamepad's rumble motors. + * + * @details The output-direction counterpart of GamepadState: a host's rumble + * request is decoded into it (a Switch's HD rumble, an X-Input + * rumble packet, an emulator's rumble pak...), and it is encoded into + * whatever drives the motors (a controller's rumble output report, a + * haptic driver). Levels are 0 (off) .. 255 (full). + * + * Strong is the large, low-frequency motor (in the left grip of a + * hand-held controller), Weak the small, high-frequency one (right + * grip). Controllers with impulse triggers (the Xbox Wireless + * controller) also have a motor behind each trigger. + */ +struct RumbleState { + /// A rumble motor. + enum class Motor : uint8_t { + Strong, ///< large, low-frequency motor (left grip) + Weak, ///< small, high-frequency motor (right grip) + LeftTrigger, ///< impulse-trigger motor behind the left trigger + RightTrigger, ///< impulse-trigger motor behind the right trigger + Count ///< number of motors (not a motor) + }; + + static constexpr size_t MOTOR_COUNT = static_cast(Motor::Count); + static constexpr uint8_t LEVEL_MAX = 255; ///< full strength + + std::array levels{}; ///< indexed by Motor + + /// @brief The level of a motor (0 for an invalid motor). + constexpr uint8_t level(Motor m) const { + return m < Motor::Count ? levels[static_cast(m)] : 0; + } + /// @brief Set a motor's level (ignored for an invalid motor). + constexpr void set(Motor m, uint8_t value) { + if (m < Motor::Count) + levels[static_cast(m)] = value; + } + /// @brief Whether any motor is on. + constexpr bool any() const { + return std::any_of(levels.begin(), levels.end(), [](uint8_t l) { return l != 0; }); + } + /// @brief All motors off. + constexpr void clear() { levels.fill(0); } + + constexpr bool operator==(const RumbleState &) const = default; +}; + +} // namespace espp diff --git a/components/gamepad_map/test/gamepad_map_host_test.cpp b/components/gamepad_map/test/gamepad_map_host_test.cpp index 8c4785ebf6..d5a8ce48bf 100644 --- a/components/gamepad_map/test/gamepad_map_host_test.cpp +++ b/components/gamepad_map/test/gamepad_map_host_test.cpp @@ -27,6 +27,7 @@ #include "gamepad_profiles.hpp" #include "gamepad_state_formatters.hpp" #include "gamepad_state_hid_rp.hpp" +#include "rumble_state.hpp" static int failures = 0; #define CHECK(cond) \ @@ -360,6 +361,26 @@ static void test_profiles() { fs::remove_all(dir); } +static void test_rumble_state() { + using espp::RumbleState; + using M = RumbleState::Motor; + RumbleState r; + CHECK(!r.any()); + r.set(M::Strong, 200); + r.set(M::RightTrigger, 10); + r.set(M::Count, 99); // ignored + CHECK(r.any() && r.level(M::Strong) == 200 && r.level(M::Weak) == 0 && + r.level(M::RightTrigger) == 10 && r.level(M::Count) == 0); + // to the encoder's levels, motor by motor + const auto l = espp::to_rumble_levels(r); + CHECK(l.strong == 200 && l.weak == 0 && l.left_trigger == 0 && l.right_trigger == 10); + // a Switch host's left / right motors are strong / weak + const auto s = espp::to_rumble_state(espp::hid_rp::SwitchRumble{.left = 117, .right = 40}); + CHECK(s.level(M::Strong) == 117 && s.level(M::Weak) == 40 && s.level(M::LeftTrigger) == 0); + r.clear(); + CHECK(!r.any() && r == RumbleState{}); +} + int main() { test_state(); test_identity(); @@ -372,6 +393,7 @@ int main() { test_validation(); test_aliasing(); test_hid_rp_bridge(); + test_rumble_state(); test_profiles(); if (failures == 0) { std::printf("gamepad_map_host_test: all checks passed\n"); diff --git a/components/hid-rp/README.md b/components/hid-rp/README.md index 9e4b11cc75..55a6477658 100644 --- a/components/hid-rp/README.md +++ b/components/hid-rp/README.md @@ -8,6 +8,44 @@ implementation of a configurable HID Gamepad using hid-rp. It also implements Switch Pro, Xbox gamepad, and 3Dconnexion SpaceMouse reports. +## Runtime report maps + +`hid-rp-report-map.hpp` goes the other way: given the report descriptor of a +device found at runtime (a USB HID device, a BLE HID service), `ReportMap::parse()` +works out where every field sits. Input fields (`fields()`) feed the decoders +(`GamepadDecoder`, `KeyboardDecoder`, ...). Output fields (`output_fields()`, +host to device: rumble, LEDs) are mapped too, each with its unit. + +## Rumble + +`hid-rp-rumble.hpp` handles rumble in both directions of a controller bridge: + +- **To a controller:** `RumbleEncoder::from_report_map()` finds a Physical + Interface Device style output report in the controller's own report map (DC + Enable Actuators, one Magnitude per actuator, Duration, Start Delay, Loop + Count, as the Xbox Wireless controller declares over Bluetooth LE). Any + controller that declares one can be driven, whatever its VID/PID: + + ```cpp + auto map = espp::hid_rp::ReportMap::parse(report_descriptor); + auto rumble = map ? espp::hid_rp::RumbleEncoder::from_report_map(*map) : std::nullopt; + if (rumble) { + // strong (left) motor full, weak (right) motor half, for 200 ms + auto payload = rumble->encode({.strong = 255, .weak = 128}, 200); + write_output_report(rumble->report_id(), payload); // e.g. a BLE HID output report + } + ``` + + The descriptor gives each field's position and range. Which Magnitude drives + which motor follows the Xbox convention (left trigger, right trigger, strong, + weak with four actuators; strong, weak with two), and `set_motor()` overrides it. + An effect plays once, for its duration: re-send it while the rumble lasts, so a + lost stop report cannot leave the motors running. +- **From a Switch host:** `decode_switch_rumble_report()` reads the two motor + levels (HD rumble, both bands) from the output reports `0x01` and `0x10` a + Switch sends a Pro Controller. `espp::SwitchPro` delivers them through + `Config::on_rumble`. + ## Example This example shows how to use the diff --git a/components/hid-rp/include/hid-rp-report-map.hpp b/components/hid-rp/include/hid-rp-report-map.hpp index 6f0b38c717..e302807773 100644 --- a/components/hid-rp/include/hid-rp-report-map.hpp +++ b/components/hid-rp/include/hid-rp-report-map.hpp @@ -23,11 +23,14 @@ #include "hid/rdf/descriptor_view.hpp" #include "hid/rdf/exception.hpp" #include "hid/rdf/parser.hpp" +#include "hid/rdf/unit.hpp" namespace espp { namespace hid_rp { -/// One Input data field of a device's report(s), as laid out in the report. +/// One data field of a device's report(s), as laid out in the report: an +/// Input field (ReportMap::fields()) or an Output field +/// (ReportMap::output_fields()). struct ReportField { uint8_t report_id{0}; ///< 0 when the device does not use report IDs uint32_t bit_offset{0}; ///< bit position within the report (after the ID byte, if any) @@ -37,16 +40,20 @@ struct ReportField { uint16_t usage_max{0}; ///< array fields: usage maximum (variable: unused) int32_t logical_min{0}; int32_t logical_max{0}; - bool array{false}; ///< array item: the value selects a usage (usage + value - logical_min) - bool relative{false}; ///< relative (mouse motion) rather than absolute + bool array{false}; ///< array item: the value selects a usage (usage + value - logical_min) + bool relative{false}; ///< relative (mouse motion) rather than absolute + uint32_t unit{0}; ///< the global Unit item (0 = none), as declared + int8_t unit_exponent{0}; ///< the global Unit Exponent: the value is in unit * 10^exponent }; /// The Input fields of a report descriptor, parsed at runtime. class ReportMap { public: /// Parse a report descriptor. Returns nullopt for a descriptor the parser - /// rejects (malformed items, unmatched push/pop). Only Input items are - /// mapped; Output/Feature items are skipped (they live in other reports). + /// rejects (malformed items, unmatched push/pop) or that has no Input + /// fields. Input items are mapped into fields(), Output items into + /// output_fields() (each with its own report layout, as a device's input and + /// output reports are separate); Feature items are skipped. static std::optional parse(std::span descriptor) { ReportMap map; // hid-rp reports malformed descriptors through HID_RDF_ASSERT, which @@ -76,6 +83,10 @@ class ReportMap { /// Every Input field, in descriptor order. const std::vector &fields() const { return fields_; } + /// Every Output field (host -> device: rumble, LEDs...), in descriptor order. + /// Constant (padding) items are not listed; they only move the next field's + /// bit_offset. + const std::vector &output_fields() const { return output_fields_; } /// Whether the device's reports start with a report ID byte. bool uses_report_ids() const { return uses_report_ids_; } /// Size in bytes of the Input report with the given ID (0 = no report IDs), @@ -84,6 +95,12 @@ class ReportMap { auto it = bit_cursor_.find(report_id); return it == bit_cursor_.end() ? 0 : (it->second + 7) / 8; } + /// Size in bytes of the Output report with the given ID (0 = no report IDs), + /// without the ID byte; 0 if the device declares no such output report. + size_t output_report_bytes(uint8_t report_id) const { + auto it = out_bit_cursor_.find(report_id); + return it == out_bit_cursor_.end() ? 0 : (it->second + 7) / 8; + } /// Extract a field's value from a report (`report` excludes the ID byte; /// use split() first). Fields with a negative logical minimum are @@ -155,9 +172,15 @@ class ReportMap { const items_view_type &main_section, unsigned /*tlc_number*/) override { namespace rdf = ::hid::rdf; - if (main_item.main_tag() != rdf::main::tag::INPUT) { + // Input and Output items are laid out in separate reports (an Input + // report and an Output report of the same ID are different reports), so + // each kind keeps its own fields and bit cursors. Feature items are not + // mapped. + const bool is_input = main_item.main_tag() == rdf::main::tag::INPUT; + if (!is_input && main_item.main_tag() != rdf::main::tag::OUTPUT) { return control::CONTINUE; } + auto &fields = is_input ? map_.fields_ : map_.output_fields_; const uint32_t flags = main_item.value_unsigned(); const bool constant = flags & 0x1; const bool variable = flags & 0x2; @@ -176,13 +199,19 @@ class ReportMap { const uint16_t usage_page = static_cast(global_u(rdf::global::tag::USAGE_PAGE, 0)); const int32_t logical_min = global_s(rdf::global::tag::LOGICAL_MINIMUM, 0); const int32_t logical_max = global_s(rdf::global::tag::LOGICAL_MAXIMUM, 0); + const uint32_t unit = global_u(rdf::global::tag::UNIT, 0); + const auto *exponent_item = global_state.get_item(rdf::global::tag::UNIT_EXPONENT); + const int8_t unit_exponent = + exponent_item ? static_cast(rdf::unit::get_exponent(*exponent_item)) : 0; if (report_size == 0 || report_count == 0) { return control::CONTINUE; // a field without bits: nothing in the report to map } - if (report_id != 0) { + if (report_id != 0 && is_input) { + // (input reports only: split() strips the ID from input reports, and an + // output report's ID is carried by whoever builds it) map_.uses_report_ids_ = true; } - uint32_t &cursor = map_.bit_cursor_[report_id]; + uint32_t &cursor = (is_input ? map_.bit_cursor_ : map_.out_bit_cursor_)[report_id]; // local items of this main section: a usage list and/or a usage range std::vector usages; // full usage (page << 16 | id) @@ -233,6 +262,8 @@ class ReportMap { f.logical_min = logical_min; f.logical_max = logical_max; f.relative = relative; + f.unit = unit; + f.unit_exponent = unit_exponent; if (variable) { uint32_t u = 0; if (have_range) { @@ -274,7 +305,7 @@ class ReportMap { f.usage_max = static_cast(hi & 0xFFFF); } cursor += report_size; - map_.fields_.push_back(f); + fields.push_back(f); } return control::CONTINUE; } @@ -291,7 +322,9 @@ class ReportMap { }; std::vector fields_; - std::map bit_cursor_; ///< input bit position per report ID + std::vector output_fields_; + std::map bit_cursor_; ///< input bit position per report ID + std::map out_bit_cursor_; ///< output bit position per report ID bool uses_report_ids_{false}; }; @@ -306,6 +339,7 @@ constexpr uint16_t PAGE_SIMULATION = 0x02; constexpr uint16_t PAGE_KEYBOARD = 0x07; constexpr uint16_t PAGE_BUTTON = 0x09; constexpr uint16_t PAGE_CONSUMER = 0x0C; +constexpr uint16_t PAGE_PHYSICAL_INPUT_DEVICE = 0x0F; ///< PID: force feedback / rumble constexpr uint16_t GD_X = 0x30, GD_Y = 0x31, GD_Z = 0x32, GD_RX = 0x33, GD_RY = 0x34, GD_RZ = 0x35; constexpr uint16_t GD_WHEEL = 0x38, GD_HAT = 0x39; constexpr uint16_t SIM_ACCELERATOR = 0xC4, SIM_BRAKE = 0xC5; @@ -314,6 +348,9 @@ constexpr uint16_t GD_DPAD_UP = 0x90, GD_DPAD_DOWN = 0x91, GD_DPAD_RIGHT = 0x92, constexpr uint16_t CONSUMER_MENU = 0x0040, CONSUMER_RECORD = 0x00B2, CONSUMER_AC_EXIT = 0x0204, CONSUMER_AC_PROPERTIES = 0x0209, CONSUMER_AC_HOME = 0x0223, CONSUMER_AC_BACK = 0x0224; +// Physical Interface Device (force feedback) usages used for rumble +constexpr uint16_t PID_SET_EFFECT_REPORT = 0x21, PID_DURATION = 0x50, PID_MAGNITUDE = 0x70, + PID_LOOP_COUNT = 0x7C, PID_DC_ENABLE_ACTUATORS = 0x97, PID_START_DELAY = 0xA7; } // namespace usage /// A gamepad report decoded into positions rather than button numbers. diff --git a/components/hid-rp/include/hid-rp-rumble.hpp b/components/hid-rp/include/hid-rp-rumble.hpp new file mode 100644 index 0000000000..93649305cf --- /dev/null +++ b/components/hid-rp/include/hid-rp-rumble.hpp @@ -0,0 +1,294 @@ +#pragma once + +// Rumble, both directions of a controller bridge: +// +// - RumbleEncoder builds a controller's rumble OUTPUT report from its report +// descriptor at runtime (descriptor-driven, like GamepadDecoder for inputs): +// a device whose report map declares a Physical Interface Device (PID) +// "Set Effect" style output report - DC Enable Actuators, one Magnitude per +// actuator, Duration, Start Delay, Loop Count, as the Xbox Wireless +// controller does over Bluetooth LE - can be driven without knowing its +// VID/PID. +// - decode_switch_rumble() reads the two motor levels a Nintendo Switch host +// sends a Pro Controller / Joy-Con (HD rumble, in output reports 0x01 and +// 0x10). +// +// Levels are 0 (off) .. 255 (full) throughout. Header-only, no ESP-IDF headers. + +#include +#include +#include +#include +#include +#include +#include + +#include "hid-rp-report-map.hpp" + +namespace espp { +namespace hid_rp { + +/// How strongly to drive each of a controller's rumble motors, 0 (off) .. 255. +struct RumbleLevels { + uint8_t strong{0}; ///< the large, low-frequency motor (left grip) + uint8_t weak{0}; ///< the small, high-frequency motor (right grip) + uint8_t left_trigger{0}; ///< impulse-trigger motor behind the left trigger + uint8_t right_trigger{0}; ///< impulse-trigger motor behind the right trigger + + /// Whether any motor is on. + constexpr bool any() const { return strong || weak || left_trigger || right_trigger; } + constexpr bool operator==(const RumbleLevels &) const = default; +}; + +/// Builds a controller's rumble output report from its report descriptor. +/// +/// from_report_map() looks for an output report whose fields use the Physical +/// Interface Device page (0x0F) and include at least one Magnitude (0x70): one +/// Magnitude field per actuator, plus, when present, DC Enable Actuators +/// (0x97), Duration (0x50), Start Delay (0xA7) and Loop Count (0x7C). The +/// descriptor gives each field's position, size and range; what it does not +/// give is which Magnitude drives which motor, so that follows a convention: +/// - 4 or more actuators: left trigger, right trigger, strong, weak (the +/// Xbox Wireless controller's order, as Linux's hid-microsoft driver uses +/// it); further actuators are left off; +/// - 2 or 3 actuators: strong, weak (a third is left off); +/// - 1 actuator: the stronger of strong / weak. +/// set_motor() overrides that per actuator for a device that differs. +/// +/// The enable field, when it has a bit per actuator, gets a bitmask in which +/// bit i enables actuator (count - 1 - i): the Xbox controller's bit 0 is its +/// weak motor and bit 1 its strong motor. A narrower enable field is a single +/// on / off flag. Duration is scaled by the field's unit (seconds with an +/// exponent: the Xbox controller's is 10 ms) and taken as milliseconds when the +/// field declares no time unit. Start Delay and Loop Count are 0: an effect +/// plays once, for its duration, starting at once. +class RumbleEncoder { +public: + /// What an actuator is driven from. + enum class Motor : uint8_t { Strong, Weak, LeftTrigger, RightTrigger, None }; + static constexpr size_t MAX_ACTUATORS = 8; ///< Magnitude fields beyond this are left at 0 + + /// The encoder for a device's rumble report, or nullopt when its report map + /// declares no PID-style output report with a Magnitude field. + static std::optional from_report_map(const ReportMap &map) { + namespace u = usage; + const auto &outs = map.output_fields(); + for (const auto &first : outs) { + if (first.usage_page != u::PAGE_PHYSICAL_INPUT_DEVICE || first.usage != u::PID_MAGNITUDE) { + continue; + } + // the first report that carries a Magnitude: gather its PID fields + RumbleEncoder e; + e.report_id_ = first.report_id; + e.report_size_ = map.output_report_bytes(first.report_id); + for (const auto &f : outs) { + if (f.report_id != e.report_id_ || f.usage_page != u::PAGE_PHYSICAL_INPUT_DEVICE) { + continue; + } + switch (f.usage) { + case u::PID_MAGNITUDE: + if (e.actuator_count_ < MAX_ACTUATORS) { + e.magnitudes_[e.actuator_count_++] = f; + } + break; + case u::PID_DC_ENABLE_ACTUATORS: + if (!e.enable_) + e.enable_ = f; + break; + case u::PID_DURATION: + if (!e.duration_) + e.duration_ = f; + break; + default: // Start Delay, Loop Count and anything else: left at 0 + break; + } + } + e.set_default_motors(); + return e; + } + return std::nullopt; + } + + /// The report ID to send the report with (0: the device uses no report IDs). + uint8_t report_id() const { return report_id_; } + /// The report's size in bytes, without the report ID byte. + size_t report_size() const { return report_size_; } + /// How many actuators (Magnitude fields) the report drives. + size_t actuator_count() const { return actuator_count_; } + /// What actuator @p slot (in descriptor order) is driven from. + Motor motor(size_t slot) const { return slot < actuator_count_ ? motors_[slot] : Motor::None; } + /// Drive actuator @p slot from @p m instead of the default (see the class notes). + void set_motor(size_t slot, Motor m) { + if (slot < actuator_count_) + motors_[slot] = m; + } + /// The longest effect the Duration field can express, in milliseconds (0 + /// when the report has no Duration field). + uint32_t max_duration_ms() const { + if (!duration_) + return 0; + return static_cast(std::lround(field_max(*duration_) * unit_ms(*duration_))); + } + + /// The report payload (without the report ID byte) that drives the motors at + /// @p levels for @p duration_ms (clamped to what the Duration field can say; + /// ignored when the report has none). All-zero levels make the stop report. + std::vector encode(const RumbleLevels &levels, uint32_t duration_ms) const { + std::vector out(report_size_, 0); + uint32_t enable_mask = 0; + bool any = false; + for (size_t i = 0; i < actuator_count_; i++) { + const uint8_t level = level_for(motors_[i], levels); + if (level) { + any = true; + // bit i enables actuator (count - 1 - i): see the class notes + const size_t bit = actuator_count_ - 1 - i; + if (bit < 32) + enable_mask |= 1u << bit; + } + const auto &f = magnitudes_[i]; + const int64_t lo = f.logical_min, hi = field_max(f); + put(out, f, static_cast(lo + (level * (hi - lo) + 127) / 255)); + } + if (enable_) { + const bool bitmask = enable_->bit_size >= actuator_count_; + put(out, *enable_, bitmask ? enable_mask : (any ? 1u : 0u)); + } + if (duration_) { + const double units = duration_ms / unit_ms(*duration_); + const int64_t hi = field_max(*duration_); + const int64_t v = std::clamp(std::llround(units), duration_->logical_min, hi); + put(out, *duration_, any ? static_cast(v) : 0u); + } + return out; + } + + /// The report that stops every motor. + std::vector encode_stop() const { return encode(RumbleLevels{}, 0); } + +private: + RumbleEncoder() = default; + + void set_default_motors() { + motors_.fill(Motor::None); + if (actuator_count_ >= 4) { + motors_[0] = Motor::LeftTrigger; + motors_[1] = Motor::RightTrigger; + motors_[2] = Motor::Strong; + motors_[3] = Motor::Weak; + } else if (actuator_count_ >= 2) { + motors_[0] = Motor::Strong; + motors_[1] = Motor::Weak; + } else if (actuator_count_ == 1) { + motors_[0] = Motor::Strong; // driven by max(strong, weak), see level_for() + } + } + + uint8_t level_for(Motor m, const RumbleLevels &l) const { + switch (m) { + case Motor::Strong: + return actuator_count_ == 1 ? std::max(l.strong, l.weak) : l.strong; + case Motor::Weak: + return l.weak; + case Motor::LeftTrigger: + return l.left_trigger; + case Motor::RightTrigger: + return l.right_trigger; + default: + return 0; + } + } + + // The field's top value: its logical maximum, or, when the descriptor leaves + // that at 0, the largest value its bits hold. + static int64_t field_max(const ReportField &f) { + if (f.logical_max > f.logical_min) + return f.logical_max; + return f.bit_size >= 32 ? 0xFFFFFFFFll : (1ll << f.bit_size) - 1; + } + + // Milliseconds per unit of a Duration field: a time unit (seconds, SI linear + // or rotation system) scaled by its exponent, else milliseconds. + static double unit_ms(const ReportField &f) { + const uint32_t system = f.unit & 0xF, time = (f.unit >> 12) & 0xF; + const bool seconds = + (system == 1 || system == 2) && time == 1 && (f.unit & 0x0FF0) == 0 && (f.unit >> 16) == 0; + return seconds ? std::pow(10.0, f.unit_exponent + 3) : 1.0; + } + + // Write @p value into the field's bits (little-endian, as HID reports are). + static void put(std::vector &out, const ReportField &f, uint32_t value) { + for (unsigned i = 0; i < f.bit_size && i < 32; i++) { + const uint32_t bit = f.bit_offset + i; + if ((bit >> 3) >= out.size()) + return; + const uint8_t mask = static_cast(1u << (bit & 7)); + if ((value >> i) & 1u) + out[bit >> 3] |= mask; + else + out[bit >> 3] &= static_cast(~mask); + } + } + + uint8_t report_id_{0}; + size_t report_size_{0}; + size_t actuator_count_{0}; + std::array magnitudes_{}; + std::array motors_{}; + std::optional enable_; + std::optional duration_; +}; + +/// The two motor levels of a Nintendo Switch host's rumble packet. +struct SwitchRumble { + uint8_t left{0}; ///< the left Joy-Con / grip motor, 0..255 + uint8_t right{0}; ///< the right Joy-Con / grip motor, 0..255 + constexpr bool operator==(const SwitchRumble &) const = default; +}; + +namespace detail { +// HD rumble amplitude code (0..100, the 7-bit step the host encodes) to an +// amplitude in 0..~1: the inverse of the encoding in dekuNukem's +// Nintendo_Switch_Reverse_Engineering rumble_data_table (log2 segments above +// codes 16 and 32; linear below, where the table's steps are tiny). +inline float switch_rumble_amplitude(int code) { + if (code <= 0) + return 0.0f; + code = std::min(code, 100); + if (code >= 32) + return std::exp2(code / 32.0f) / 8.7f; + if (code >= 16) + return std::exp2(code / 16.0f) / 17.0f; + return code * (2.0f / 17.0f) / 16.0f; +} +// One motor's 4 bytes: [0] HF frequency (low byte), [1] bit 0 HF frequency +// MSB, bits 1-7 HF amplitude code; [2] bits 0-6 LF frequency, bit 7 LF +// amplitude LSB; [3] LF amplitude code / 2 + 0x40. The motor level is the +// stronger of the two bands. +inline uint8_t switch_rumble_motor(std::span m) { + const int hf_code = m[1] >> 1; + const int lf_code = m[3] >= 0x40 ? ((m[3] - 0x40) << 1) | (m[2] >> 7) : 0; + const float amp = std::max(switch_rumble_amplitude(hf_code), switch_rumble_amplitude(lf_code)); + return static_cast(std::lround(std::clamp(amp, 0.0f, 1.0f) * 255.0f)); +} +} // namespace detail + +/// 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) { + return {detail::switch_rumble_motor(data.subspan<0, 4>()), + detail::switch_rumble_motor(data.subspan<4, 4>())}; +} + +/// The motor levels a Switch host's OUTPUT report carries, or nullopt when it +/// carries none. @p report starts with the report ID: 0x01 (rumble + +/// subcommand) and 0x10 (rumble only) both lay out [id][packet number][8 +/// rumble bytes]... +inline std::optional decode_switch_rumble_report(std::span report) { + if (report.size() < 10 || (report[0] != 0x01 && report[0] != 0x10)) + return std::nullopt; + return decode_switch_rumble(report.subspan<2, 8>()); +} + +} // namespace hid_rp +} // namespace espp diff --git a/components/hid-rp/test/hid_rp_rumble_host_test.cpp b/components/hid-rp/test/hid_rp_rumble_host_test.cpp new file mode 100644 index 0000000000..f9f9164cac --- /dev/null +++ b/components/hid-rp/test/hid_rp_rumble_host_test.cpp @@ -0,0 +1,232 @@ +// Host-buildable unit tests for the rumble helpers (hid-rp-rumble.hpp) and the +// Output-field side of the runtime report map. Build & run: +// +// c++ -std=c++23 -Wall -Wextra -Werror -Wno-comment \ +// -isystem components/hid-rp/include \ +// -isystem components/hid-rp/detail/hid-rp/hid-rp \ +// -isystem components/format/include \ +// -isystem components/format/detail/fmt/include \ +// components/hid-rp/test/hid_rp_rumble_host_test.cpp \ +// -o /tmp/hid_rp_rumble_host_test \ +// && /tmp/hid_rp_rumble_host_test +// +// No ESP-IDF headers required. + +#include +#include +#include + +#include "hid-rp-report-map.hpp" +#include "hid-rp-rumble.hpp" +#include "hid-rp-switch-pro.hpp" +#include "hid-rp-xbox.hpp" + +static int failures = 0; +#define CHECK(cond) \ + do { \ + if (!(cond)) { \ + std::printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \ + failures++; \ + } \ + } while (0) + +using namespace espp::hid_rp; +namespace u = espp::hid_rp::usage; + +template static std::vector bytes_of(const D &d) { + return std::vector(d.begin(), d.end()); +} + +static const ReportField *find_output(const ReportMap &m, uint8_t id, uint16_t usage, int nth = 0) { + for (const auto &f : m.output_fields()) { + if (f.report_id == id && f.usage_page == u::PAGE_PHYSICAL_INPUT_DEVICE && f.usage == usage && + nth-- == 0) + return &f; + } + return nullptr; +} + +// --- the Xbox Wireless controller's report map ------------------------------ +static void test_xbox_output_fields() { + const auto desc = bytes_of(espp::xbox_descriptor()); + const auto map = ReportMap::parse(desc); + CHECK(map.has_value()); + if (!map) + return; + // the rumble output report (id 3): 8 bytes, PID usages at the xpadneo offsets + CHECK(map->output_report_bytes(3) == 8); + const auto *enable = find_output(*map, 3, u::PID_DC_ENABLE_ACTUATORS); + CHECK(enable && enable->bit_offset == 0 && enable->bit_size == 4); + for (int i = 0; i < 4; i++) { + const auto *m = find_output(*map, 3, u::PID_MAGNITUDE, i); + CHECK(m && m->bit_offset == 8u + 8u * i && m->bit_size == 8 && m->logical_max == 100); + } + const auto *duration = find_output(*map, 3, u::PID_DURATION); + CHECK(duration && duration->bit_offset == 40 && duration->unit == 0x1001 && + duration->unit_exponent == -2); + const auto *delay = find_output(*map, 3, u::PID_START_DELAY); + CHECK(delay && delay->bit_offset == 48); + const auto *loop = find_output(*map, 3, u::PID_LOOP_COUNT); + CHECK(loop && loop->bit_offset == 56 && loop->unit == 0); + // outputs leave the input side alone: no input field from report 3 + for (const auto &f : map->fields()) + CHECK(f.report_id != 3); + CHECK(map->uses_report_ids()); +} + +static void test_xbox_encoder() { + const auto desc = bytes_of(espp::xbox_descriptor()); + const auto map = ReportMap::parse(desc); + const auto enc = map ? RumbleEncoder::from_report_map(*map) : std::nullopt; + CHECK(enc.has_value()); + if (!enc) + return; + CHECK(enc->report_id() == 3); + CHECK(enc->report_size() == 8); + CHECK(enc->actuator_count() == 4); + using M = RumbleEncoder::Motor; + CHECK(enc->motor(0) == M::LeftTrigger && enc->motor(1) == M::RightTrigger && + enc->motor(2) == M::Strong && enc->motor(3) == M::Weak); + CHECK(enc->max_duration_ms() == 2550); // 255 x 10 ms + + // strong full, weak half, for 250 ms + const auto b = enc->encode({.strong = 255, .weak = 128}, 250); + const std::vector want = {0x03, 0, 0, 100, 50, 25, 0, 0}; + CHECK(b == want); + // byte for byte what espp's hand-written Xbox rumble report produces + espp::XboxRumbleOutputReport<> r; + r.set_enabled(0x03); // weak (bit 0) + strong (bit 1) + r.set_magnitude(2, uint8_t{100}); + r.set_magnitude(3, uint8_t{50}); + r.set_duration(uint8_t{25}); + r.set_start_delay(uint8_t{0}); + r.set_loop_count(uint8_t{0}); + const auto ref = r.get_report(); + CHECK(std::vector(ref.begin(), ref.end()) == b); + + // trigger motors: slot 0 (left trigger) is enable bit 3, slot 1 bit 2 + const auto t = enc->encode({.left_trigger = 255, .right_trigger = 255}, 100); + CHECK(t.size() == 8 && t[0] == 0x0C && t[1] == 100 && t[2] == 100 && t[3] == 0 && t[4] == 0 && + t[5] == 10); + // durations beyond the field clamp to it + CHECK(enc->encode({.weak = 255}, 10'000)[5] == 255); + // the stop report is all zero + CHECK(enc->encode_stop() == std::vector(8, 0)); + CHECK(enc->encode({}, 500) == std::vector(8, 0)); + + // a remapped actuator follows its new motor + auto e2 = *enc; + e2.set_motor(2, M::Weak); + e2.set_motor(3, M::Strong); + const auto s = e2.encode({.strong = 255, .weak = 0}, 0); + CHECK(s[3] == 0 && s[4] == 100 && s[0] == 0x01); // weak slot (3) is bit 0 +} + +// --- a synthetic 2-motor PID layout ----------------------------------------- +// Input: report 1, 8 buttons. Output: report 5, a 1-bit DC Enable flag + 7 bits +// of padding, two 16-bit magnitudes 0..10000, a 16-bit Duration with no unit +// (milliseconds). +static const uint8_t TWO_MOTOR_DESC[] = { + 0x05, 0x01, 0x09, 0x05, 0xA1, 0x01, // GD / Gamepad / Application + 0x85, 0x01, // Report ID 1 + 0x05, 0x09, 0x19, 0x01, 0x29, 0x08, 0x15, 0x00, 0x25, 0x01, // buttons 1..8 + 0x75, 0x01, 0x95, 0x08, 0x81, 0x02, // Input (Data, Var) + 0x85, 0x05, // Report ID 5 + 0x05, 0x0F, // PID page + 0x09, 0x97, 0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x01, // DC Enable Actuators, 1 bit + 0x91, 0x02, // Output (Data, Var) + 0x75, 0x07, 0x95, 0x01, 0x91, 0x03, // 7 bits padding (Cnst) + 0x09, 0x70, 0x15, 0x00, 0x26, 0x10, 0x27, // Magnitude 0..10000 + 0x75, 0x10, 0x95, 0x02, 0x91, 0x02, // x2, 16 bit + 0x09, 0x50, 0x15, 0x00, 0x26, 0xFF, 0x7F, // Duration 0..32767 (no unit) + 0x75, 0x10, 0x95, 0x01, 0x91, 0x02, // 16 bit + 0xC0}; + +static void test_two_motor_encoder() { + const auto map = ReportMap::parse(TWO_MOTOR_DESC); + CHECK(map.has_value()); + if (!map) + return; + CHECK(map->report_bytes(1) == 1); // the input side is unchanged by the outputs + CHECK(map->output_report_bytes(5) == 7); // 1 + 7 + 32 + 16 bits + const auto enc = RumbleEncoder::from_report_map(*map); + CHECK(enc.has_value()); + if (!enc) + return; + CHECK(enc->report_id() == 5 && enc->report_size() == 7 && enc->actuator_count() == 2); + CHECK(enc->motor(0) == RumbleEncoder::Motor::Strong && + enc->motor(1) == RumbleEncoder::Motor::Weak); + CHECK(enc->max_duration_ms() == 32767); + const auto b = enc->encode({.strong = 255, .weak = 51}, 300); + // enable flag (1 bit, narrower than the 2 actuators: a single on/off flag), + // 10000 = 0x2710, 2000 = 0x07D0, 300 ms = 0x012C + const std::vector want = {0x01, 0x10, 0x27, 0xD0, 0x07, 0x2C, 0x01}; + CHECK(b == want); + CHECK(enc->encode_stop() == std::vector(7, 0)); +} + +// --- a device without a PID rumble report ----------------------------------- +static void test_no_rumble_report() { + // the Switch Pro descriptor has output reports (0x01, 0x10, 0x80, 0x82), but + // each is 63 constant vendor bytes: walked (their size is known) yet no data + // field, and nothing on the PID page + const auto desc = bytes_of(espp::switch_pro_descriptor()); + const auto map = ReportMap::parse(desc); + CHECK(map.has_value()); + if (map) { + CHECK(map->output_report_bytes(0x01) == 63 && map->output_report_bytes(0x10) == 63); + CHECK(map->output_fields().empty()); + CHECK(!RumbleEncoder::from_report_map(*map).has_value()); + } +} + +// --- Switch host rumble decoding -------------------------------------------- +static void test_switch_rumble() { + // neutral packet: 00 01 40 40 per motor + const uint8_t neutral[8] = {0x00, 0x01, 0x40, 0x40, 0x00, 0x01, 0x40, 0x40}; + CHECK(decode_switch_rumble(neutral) == SwitchRumble{}); + // left: HF amplitude at its maximum code (100); right: LF amplitude at its + // maximum (0x72 with the half-step bit in byte 2) + const uint8_t full[8] = {0x00, 0xC9, 0x40, 0x40, 0x00, 0x01, 0xC0, 0x72}; + const auto f = decode_switch_rumble(full); + CHECK(f.left == 255 && f.right == 255); + // HF code 64: 2^(64/32) / 8.7 = 0.46 -> 117 + const uint8_t mid[8] = {0x00, 0x80, 0x40, 0x40, 0x00, 0x01, 0x40, 0x40}; + CHECK(decode_switch_rumble(mid) == (SwitchRumble{117, 0})); + // the level grows with the code across the segment boundaries (16, 32) + int last = -1; + for (int code = 0; code <= 100; code++) { + const uint8_t p[8] = {0x00, static_cast(code << 1), 0x40, 0x40, 0x00, 0x01, 0x40, + 0x40}; + const int level = decode_switch_rumble(p).left; + CHECK(level >= last); + last = level; + } + CHECK(last == 255); + + // whole reports: the rumble data follows the report id AND the packet number + // (a 0xC9 packet number must not read as a full HF amplitude) + const uint8_t r10[10] = {0x10, 0xC9, 0x00, 0x01, 0x40, 0x40, 0x00, 0x80, 0x40, 0x40}; + const auto a = decode_switch_rumble_report(r10); + CHECK(a.has_value() && a->left == 0 && a->right == 117); + const uint8_t r01[12] = {0x01, 0x05, 0x00, 0x80, 0x40, 0x40, 0x00, 0x01, 0x40, 0x40, 0x48, 0x01}; + const auto b = decode_switch_rumble_report(r01); + CHECK(b.has_value() && b->left == 117 && b->right == 0); + const uint8_t init[10] = {0x80, 0x02, 0, 0, 0, 0, 0, 0, 0, 0}; // a USB init command + CHECK(!decode_switch_rumble_report(init).has_value()); + const uint8_t short_report[9] = {0x10, 0x00, 0x00, 0x01, 0x40, 0x40, 0x00, 0x01, 0x40}; + CHECK(!decode_switch_rumble_report(short_report).has_value()); +} + +int main() { + test_xbox_output_fields(); + test_xbox_encoder(); + test_two_motor_encoder(); + test_no_rumble_report(); + test_switch_rumble(); + if (failures == 0) + std::printf("ALL HID-RP RUMBLE TESTS PASSED\n"); + else + std::printf("%d FAILURE(S)\n", failures); + return failures == 0 ? 0 : 1; +} diff --git a/components/switch_pro/README.md b/components/switch_pro/README.md index 16bdb3275c..05b8c94e2f 100644 --- a/components/switch_pro/README.md +++ b/components/switch_pro/README.md @@ -65,6 +65,10 @@ Key class: `espp::SwitchPro` (`switch_pro.hpp`) - `on_attach()` → `optional` — the initial report to send on mount. - `on_hid_report(report_id, data, len)` → `optional` — handle a host OUTPUT report; returns the INPUT report to send back (`{report_id, bytes}`). +- `Config::on_rumble` — called with the two motor levels (`hid_rp::SwitchRumble`, + 0..255 each) of every host report that carries rumble data (`0x01`, `0x10`), + neutral packets included; runs on the caller of `on_hid_report()`, so it must + not block. - `get_input_report()` — the current standard (`0x30`) input report bytes. - `update_input_report(fn)` — thread-safely set buttons / sticks via the `hid-rp` report setters. diff --git a/components/switch_pro/include/switch_pro.hpp b/components/switch_pro/include/switch_pro.hpp index 9b6396e19c..6d4d6f0923 100644 --- a/components/switch_pro/include/switch_pro.hpp +++ b/components/switch_pro/include/switch_pro.hpp @@ -14,6 +14,7 @@ #include #include "base_component.hpp" +#include "hid-rp-rumble.hpp" #include "hid-rp-switch-pro.hpp" #include "high_resolution_timer.hpp" @@ -53,6 +54,12 @@ class SwitchPro : public espp::BaseComponent { /// @brief Configuration for the SwitchPro engine. struct Config { + /// Called with the motor levels of every host OUTPUT report that carries + /// rumble data (0x01 rumble + subcommand, 0x10 rumble only), neutral (0 / + /// 0) packets included: the host sends rumble continuously, so dedupe or + /// rate-limit downstream as needed. Runs on the caller of on_hid_report() + /// (usually the TinyUSB task), so it must not block. Optional. + std::function on_rumble{nullptr}; espp::Logger::Verbosity log_level{espp::Logger::Verbosity::WARN}; ///< Logger verbosity. }; @@ -92,6 +99,7 @@ class SwitchPro : public espp::BaseComponent { /// /// Feed every OUTPUT report the host sends (report ids 0x80 init, 0x01 output / /// subcommand, 0x10 rumble) here; byte 0 of @p data must be the report id. + /// The rumble data in 0x01 / 0x10 reports goes to Config::on_rumble. /// Returns the INPUT report to send back (report id + bytes), or std::nullopt if /// no reply is warranted. /// @param report_id The HID report id (ignored; the type is read from data[0]). @@ -175,6 +183,7 @@ class SwitchPro : public espp::BaseComponent { // streamed 0x30 report with them), so they are atomic. std::atomic vibrator_report_{0}; // randomly selected from sp::vibrator_bytes std::atomic imu_enabled_{false}; + std::function on_rumble_; // Config::on_rumble uint8_t input_report_id_ = 0x21; sp::TriggerTimes trigger_times_{}; diff --git a/components/switch_pro/src/switch_pro.cpp b/components/switch_pro/src/switch_pro.cpp index fe2ef28fb2..4ad0cce1e0 100644 --- a/components/switch_pro/src/switch_pro.cpp +++ b/components/switch_pro/src/switch_pro.cpp @@ -5,7 +5,8 @@ using namespace espp; SwitchPro::SwitchPro(const Config &config) - : BaseComponent("SwitchPro", config.log_level) { + : BaseComponent("SwitchPro", config.log_level) + , on_rumble_(config.on_rumble) { // start the input-report counter timer counter_timer_.periodic(counter_period_us); @@ -117,6 +118,14 @@ std::optional SwitchPro::on_hid_report(uint8_t report_id, using namespace sp; + // 0x01 (rumble + subcommand) and 0x10 (rumble only) both carry the rumble + // data at bytes 2..9 (after the report id and the packet number) + if (on_rumble_ && (data[0] == HOST_OUTPUT_REPORT || data[0] == HOST_RUMBLE_REPORT)) { + if (const auto rumble = hid_rp::decode_switch_rumble_report({data, len})) { + on_rumble_(*rumble); + } + } + switch (data[0]) { case HOST_INIT_REPORT: { if (len < 2) @@ -155,7 +164,7 @@ std::optional SwitchPro::on_hid_report(uint8_t report_id, case HOST_OUTPUT_REPORT: return process_command(data, len); case HOST_RUMBLE_REPORT: - // TODO: process the rumble packet (no reply required) + // rumble only: delivered to on_rumble above; no reply return std::nullopt; default: logger_.debug("Unhandled host report type: 0x{:02x}", data[0]); diff --git a/components/usb_device/README.md b/components/usb_device/README.md index 1facc80744..1724286501 100644 --- a/components/usb_device/README.md +++ b/components/usb_device/README.md @@ -232,7 +232,9 @@ X-Input interface (class 0xFF / subclass 0x5D / protocol 0x01), so it coexists with the built-in CDC, HID and vendor drivers when those are enabled. Set `Config::xinput`, send gamepad state with `update_xinput_state(GamepadState)`, -and receive rumble/LED reports via `XInputFunction::on_rumble`. The interface uses +and receive rumble/LED reports via `XInputFunction::on_rumble` +(`xinput::decode_rumble()` reads the two motor levels out of a rumble report and +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 diff --git a/components/usb_device/include/xinput.hpp b/components/usb_device/include/xinput.hpp index 6c0a8437ce..0b76956eca 100644 --- a/components/usb_device/include/xinput.hpp +++ b/components/usb_device/include/xinput.hpp @@ -19,6 +19,8 @@ #include #include #include +#include +#include #include namespace espp { @@ -112,6 +114,24 @@ struct GamepadState { } }; +/// 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 + uint8_t right{0}; ///< the small, high-frequency motor (right grip), 0..255 + constexpr bool operator==(const Rumble &) const = default; +}; + +/// The motor levels in a report the host sent on the X-Input OUT endpoint +/// (UsbDevice::XInputFunction::on_rumble), or nullopt for a report that is not +/// a rumble report. The host sends two kinds of 8-byte reports there: +/// - rumble: `00 08 00 00 00 00` +/// - LED ring: `01 03 ` (not rumble: nullopt) +inline std::optional decode_rumble(std::span report) { + if (report.size() < 5 || report[0] != 0x00) + return std::nullopt; + return Rumble{report[3], report[4]}; +} + /// 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/usb_device/test/xinput_host_test.cpp b/components/usb_device/test/xinput_host_test.cpp index 7a4b409bba..db7aefc0c9 100644 --- a/components/usb_device/test/xinput_host_test.cpp +++ b/components/usb_device/test/xinput_host_test.cpp @@ -67,6 +67,19 @@ int main() { // OUT endpoint CHECK(d[33] == 0x07 && d[34] == 0x05 && d[35] == 0x03 && d[36] == 0x03 && d[37] == kEpSize); + // --- rumble reports from the host --- + { + const uint8_t rumble[8] = {0x00, 0x08, 0x00, 0xC8, 0x40, 0x00, 0x00, 0x00}; + const auto r = decode_rumble(rumble); + CHECK(r.has_value() && r->left == 0xC8 && r->right == 0x40); + const uint8_t stop[8] = {0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + CHECK(decode_rumble(stop) == Rumble{}); + const uint8_t led[3] = {0x01, 0x03, 0x06}; // LED ring: not rumble + CHECK(!decode_rumble(led).has_value()); + const uint8_t short_report[4] = {0x00, 0x08, 0x00, 0xFF}; + CHECK(!decode_rumble(short_report).has_value()); + } + if (g_failures == 0) std::printf("all xinput host tests passed\n"); else diff --git a/doc/Doxyfile b/doc/Doxyfile index 8bea173fb0..d89b49a4b6 100755 --- a/doc/Doxyfile +++ b/doc/Doxyfile @@ -360,6 +360,7 @@ INPUT = \ $(PROJECT_PATH)/components/gamepad_map/include/gamepad_profiles.hpp \ $(PROJECT_PATH)/components/gamepad_map/include/gamepad_state.hpp \ $(PROJECT_PATH)/components/gamepad_map/include/gamepad_state_hid_rp.hpp \ + $(PROJECT_PATH)/components/gamepad_map/include/rumble_state.hpp \ $(PROJECT_PATH)/components/gfps_service/include/gfps.hpp \ $(PROJECT_PATH)/components/gfps_service/include/gfps_characteristic_callbacks.hpp \ $(PROJECT_PATH)/components/gfps_service/include/gfps_service.hpp \ @@ -373,6 +374,7 @@ INPUT = \ $(PROJECT_PATH)/components/hid-rp/include/hid-rp-gamepad.hpp \ $(PROJECT_PATH)/components/hid-rp/include/hid-rp-playstation.hpp \ $(PROJECT_PATH)/components/hid-rp/include/hid-rp-ps4.hpp \ + $(PROJECT_PATH)/components/hid-rp/include/hid-rp-rumble.hpp \ $(PROJECT_PATH)/components/hid-rp/include/hid-rp-switch-pro.hpp \ $(PROJECT_PATH)/components/hid-rp/include/hid-rp-xbox.hpp \ $(PROJECT_PATH)/components/hid_service/include/hid_service.hpp \ diff --git a/doc/en/hid/hid-rp.rst b/doc/en/hid/hid-rp.rst index c89c96fac6..7a064d21b1 100644 --- a/doc/en/hid/hid-rp.rst +++ b/doc/en/hid/hid-rp.rst @@ -8,6 +8,13 @@ implementation of a configurable HID Gamepad using hid-rp. It also implements Playstation DualSense, Playstation DualShock 4, Nintendo Switch Pro, Xbox gamepad, and 3Dconnexion SpaceMouse reports. +At runtime, ``ReportMap`` maps a device's report descriptor (its Input and Output +fields), and ``RumbleEncoder`` builds a controller's rumble report from it: any +controller that declares a Physical Interface Device style rumble report (as the +Xbox Wireless controller does over Bluetooth LE) can be driven without knowing its +VID/PID. ``decode_switch_rumble_report()`` reads the motor levels a Nintendo Switch +host sends a Pro Controller. + .. ------------------------------- Example ------------------------------------- .. toctree:: @@ -26,5 +33,6 @@ API Reference .. include-build-file:: inc/hid-rp-gamepad.inc .. include-build-file:: inc/hid-rp-playstation.inc .. include-build-file:: inc/hid-rp-ps4.inc +.. include-build-file:: inc/hid-rp-rumble.inc .. include-build-file:: inc/hid-rp-switch-pro.inc .. include-build-file:: inc/hid-rp-xbox.inc diff --git a/doc/en/input/gamepad_map.rst b/doc/en/input/gamepad_map.rst index bff4323bac..79b4366a7b 100644 --- a/doc/en/input/gamepad_map.rst +++ b/doc/en/input/gamepad_map.rst @@ -40,3 +40,4 @@ API Reference .. include-build-file:: inc/gamepad_map_service.inc .. include-build-file:: inc/gamepad_profiles.inc .. include-build-file:: inc/gamepad_state_hid_rp.inc +.. include-build-file:: inc/rumble_state.inc diff --git a/lib/include/espp.hpp b/lib/include/espp.hpp index 3e57c34fce..e59773507d 100644 --- a/lib/include/espp.hpp +++ b/lib/include/espp.hpp @@ -33,6 +33,7 @@ extern "C" { #include "gamepad_state.hpp" #include "gamepad_state_formatters.hpp" #include "gaussian.hpp" +#include "rumble_state.hpp" // TODO: these are not working // #include "hid-rp.hpp" // #include "hid-rp-gamepad.hpp" From a0e0ea6baf689275fb5a2bfe0a8580eba036b52f Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Mon, 23 Nov 2026 15:29:19 -0700 Subject: [PATCH 2/3] feat(usb_device): suspend / resume callbacks UsbDevice::set_suspend_callback() / set_resume_callback() forward esp_tinyusb's TINYUSB_EVENT_SUSPENDED / RESUMED, which the event callback used to drop. On suspend the device stays powered and configured, so an app can stop what the host was driving: a controller bridge stops the controller's rumble when a PC goes to sleep without sending a stop. Same pattern as the mount / unmount callbacks (run in the TinyUSB task, cb_mutex_-guarded). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU --- components/usb_device/README.md | 3 ++ components/usb_device/include/usb_device.hpp | 15 +++++++++ components/usb_device/src/usb_device.cpp | 34 ++++++++++++++++++++ 3 files changed, 52 insertions(+) diff --git a/components/usb_device/README.md b/components/usb_device/README.md index 1724286501..56825a9fd7 100644 --- a/components/usb_device/README.md +++ b/components/usb_device/README.md @@ -156,6 +156,9 @@ Key methods: would be a duplicate symbol). On unmount the component first clears the vendor + CDC TX FIFOs — so a departed host's queued backlog is not delivered to the next host that mounts — then invokes your callback. +- `void set_suspend_callback(...)` / `void set_resume_callback(...)` — the host + suspended / resumed the bus (a PC going to sleep). The device stays powered and + configured, so stop whatever the host was driving (rumble, say) on suspend. - `size_t vendor_write_available() const` / `size_t cdc_write_available() const` and `void vendor_write_clear()` / `void cdc_write_clear()` — TX-FIFO free space and flush helpers (skip/defer or drop a streaming frame when the host stops diff --git a/components/usb_device/include/usb_device.hpp b/components/usb_device/include/usb_device.hpp index 6409e47d5a..d3185c967f 100644 --- a/components/usb_device/include/usb_device.hpp +++ b/components/usb_device/include/usb_device.hpp @@ -672,6 +672,17 @@ class UsbDevice : public BaseComponent { /// (esp_tinyusb already defines it). void set_unmount_callback(const event_callback_fn &cb); + /// @brief Register a callback invoked when the host suspends the bus (a PC + /// going to sleep, a selective suspend). The device stays powered (in + /// the bus's suspend current budget) and configured; outputs the host + /// was driving, such as rumble, should stop. Runs in the TinyUSB + /// device-task context; nullptr detaches. + void set_suspend_callback(const event_callback_fn &cb); + + /// @brief Register a callback invoked when the host resumes the bus after a + /// suspend. Runs in the TinyUSB device-task context; nullptr detaches. + void set_resume_callback(const event_callback_fn &cb); + /// @brief Whether initialize() has completed successfully. bool is_initialized() const; @@ -808,6 +819,8 @@ class UsbDevice : public BaseComponent { /// (clears the TX FIFOs on unmount, then invokes the app callback). void handle_usb_mount(); void handle_usb_unmount(); + void handle_usb_suspend(); + void handle_usb_resume(); struct Impl; // holds TinyUSB descriptors, kept alive for driver lifetime std::unique_ptr impl_; @@ -826,6 +839,8 @@ class UsbDevice : public BaseComponent { receive_callback_fn on_hid_receive_; event_callback_fn on_mount_; event_callback_fn on_unmount_; + event_callback_fn on_suspend_; + event_callback_fn on_resume_; msc_event_callback_fn on_msc_event_; // Preallocated RX scratch buffers (sized in initialize()) so the TinyUSB-task diff --git a/components/usb_device/src/usb_device.cpp b/components/usb_device/src/usb_device.cpp index 9dfd457ff4..e21822c323 100644 --- a/components/usb_device/src/usb_device.cpp +++ b/components/usb_device/src/usb_device.cpp @@ -745,6 +745,10 @@ extern "C" void espp_usb_device_event_cb(tinyusb_event_t *event, void *arg) { dev->handle_usb_mount(); else if (event->id == TINYUSB_EVENT_DETACHED) dev->handle_usb_unmount(); + else if (event->id == TINYUSB_EVENT_SUSPENDED) + dev->handle_usb_suspend(); + else if (event->id == TINYUSB_EVENT_RESUMED) + dev->handle_usb_resume(); } #if (CFG_TUD_HID > 0) @@ -1854,6 +1858,36 @@ void UsbDevice::set_unmount_callback(const event_callback_fn &cb) { on_unmount_ = cb; } +void UsbDevice::set_suspend_callback(const event_callback_fn &cb) { + std::scoped_lock lk(cb_mutex_); + on_suspend_ = cb; +} + +void UsbDevice::set_resume_callback(const event_callback_fn &cb) { + std::scoped_lock lk(cb_mutex_); + on_resume_ = cb; +} + +void UsbDevice::handle_usb_suspend() { + event_callback_fn cb; + { + std::scoped_lock lk(cb_mutex_); + cb = on_suspend_; + } + if (cb) + cb(); // runs in the TinyUSB task context +} + +void UsbDevice::handle_usb_resume() { + event_callback_fn cb; + { + std::scoped_lock lk(cb_mutex_); + cb = on_resume_; + } + if (cb) + cb(); // runs in the TinyUSB task context +} + void UsbDevice::handle_usb_mount() { event_callback_fn cb; { From a87401bd2da2515d9a62a320c30a53ce79a3a43b Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Mon, 23 Nov 2026 16:06:00 -0700 Subject: [PATCH 3/3] fix: cppcheck style findings (shadowed names, find_if) - hid-rp ReportMap::Parser: the local field list was named `fields`, which shadowed ReportMap::fields(). It is now `dest_fields`. - xinput host test: the decoded rumble no longer shadows the outer report `r`. - hid-rp rumble test: find_output() uses std::find_if instead of a raw loop. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU --- components/hid-rp/include/hid-rp-report-map.hpp | 4 ++-- components/hid-rp/test/hid_rp_rumble_host_test.cpp | 13 +++++++------ components/usb_device/test/xinput_host_test.cpp | 4 ++-- 3 files changed, 11 insertions(+), 10 deletions(-) diff --git a/components/hid-rp/include/hid-rp-report-map.hpp b/components/hid-rp/include/hid-rp-report-map.hpp index e302807773..9887c27dd3 100644 --- a/components/hid-rp/include/hid-rp-report-map.hpp +++ b/components/hid-rp/include/hid-rp-report-map.hpp @@ -180,7 +180,7 @@ class ReportMap { if (!is_input && main_item.main_tag() != rdf::main::tag::OUTPUT) { return control::CONTINUE; } - auto &fields = is_input ? map_.fields_ : map_.output_fields_; + auto &dest_fields = is_input ? map_.fields_ : map_.output_fields_; const uint32_t flags = main_item.value_unsigned(); const bool constant = flags & 0x1; const bool variable = flags & 0x2; @@ -305,7 +305,7 @@ class ReportMap { f.usage_max = static_cast(hi & 0xFFFF); } cursor += report_size; - fields.push_back(f); + dest_fields.push_back(f); } return control::CONTINUE; } 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 f9f9164cac..aa73aec9b9 100644 --- a/components/hid-rp/test/hid_rp_rumble_host_test.cpp +++ b/components/hid-rp/test/hid_rp_rumble_host_test.cpp @@ -12,6 +12,7 @@ // // No ESP-IDF headers required. +#include #include #include #include @@ -38,12 +39,12 @@ template static std::vector bytes_of(const D &d) { } static const ReportField *find_output(const ReportMap &m, uint8_t id, uint16_t usage, int nth = 0) { - for (const auto &f : m.output_fields()) { - if (f.report_id == id && f.usage_page == u::PAGE_PHYSICAL_INPUT_DEVICE && f.usage == usage && - nth-- == 0) - return &f; - } - return nullptr; + const auto &outs = m.output_fields(); + const auto it = std::find_if(outs.begin(), outs.end(), [&](const ReportField &f) { + return f.report_id == id && f.usage_page == u::PAGE_PHYSICAL_INPUT_DEVICE && f.usage == usage && + nth-- == 0; + }); + return it == outs.end() ? nullptr : &*it; } // --- the Xbox Wireless controller's report map ------------------------------ diff --git a/components/usb_device/test/xinput_host_test.cpp b/components/usb_device/test/xinput_host_test.cpp index db7aefc0c9..bc2dde2127 100644 --- a/components/usb_device/test/xinput_host_test.cpp +++ b/components/usb_device/test/xinput_host_test.cpp @@ -70,8 +70,8 @@ int main() { // --- rumble reports from the host --- { const uint8_t rumble[8] = {0x00, 0x08, 0x00, 0xC8, 0x40, 0x00, 0x00, 0x00}; - const auto r = decode_rumble(rumble); - CHECK(r.has_value() && r->left == 0xC8 && r->right == 0x40); + const auto decoded = decode_rumble(rumble); + CHECK(decoded.has_value() && decoded->left == 0xC8 && decoded->right == 0x40); const uint8_t stop[8] = {0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; CHECK(decode_rumble(stop) == Rumble{}); const uint8_t led[3] = {0x01, 0x03, 0x06}; // LED ring: not rumble