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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions components/gamepad_map/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
31 changes: 31 additions & 0 deletions components/gamepad_map/include/gamepad_state_hid_rp.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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 {

Expand Down Expand Up @@ -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
58 changes: 58 additions & 0 deletions components/gamepad_map/include/rumble_state.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
#pragma once

#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdint>

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<size_t>(Motor::Count);
static constexpr uint8_t LEVEL_MAX = 255; ///< full strength

std::array<uint8_t, MOTOR_COUNT> 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<uint8_t>(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<uint8_t>(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
22 changes: 22 additions & 0 deletions components/gamepad_map/test/gamepad_map_host_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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) \
Expand Down Expand Up @@ -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();
Expand All @@ -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");
Expand Down
38 changes: 38 additions & 0 deletions components/hid-rp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
57 changes: 47 additions & 10 deletions components/hid-rp/include/hid-rp-report-map.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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<ReportMap> parse(std::span<const uint8_t> descriptor) {
ReportMap map;
// hid-rp reports malformed descriptors through HID_RDF_ASSERT, which
Expand Down Expand Up @@ -76,6 +83,10 @@ class ReportMap {

/// Every Input field, in descriptor order.
const std::vector<ReportField> &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<ReportField> &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),
Expand All @@ -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
Expand Down Expand Up @@ -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 &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;
Expand All @@ -176,13 +199,19 @@ class ReportMap {
const uint16_t usage_page = static_cast<uint16_t>(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<int8_t>(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<uint32_t> usages; // full usage (page << 16 | id)
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -274,7 +305,7 @@ class ReportMap {
f.usage_max = static_cast<uint16_t>(hi & 0xFFFF);
}
cursor += report_size;
map_.fields_.push_back(f);
dest_fields.push_back(f);
}
return control::CONTINUE;
}
Expand All @@ -291,7 +322,9 @@ class ReportMap {
};

std::vector<ReportField> fields_;
std::map<uint8_t, uint32_t> bit_cursor_; ///< input bit position per report ID
std::vector<ReportField> output_fields_;
std::map<uint8_t, uint32_t> bit_cursor_; ///< input bit position per report ID
std::map<uint8_t, uint32_t> out_bit_cursor_; ///< output bit position per report ID
bool uses_report_ids_{false};
};

Expand All @@ -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;
Expand All @@ -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.
Expand Down
Loading
Loading