From af7fa01b1eb91e33859e23084ed541016d2775c0 Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Sat, 21 Nov 2026 15:25:53 -0700 Subject: [PATCH 1/5] feat(gamepad_map): gamepad button / axis remapping with per-controller profiles; hid-rp decoder for BLE HID gamepads hid-rp (hid-rp-report-map.hpp, GamepadDecoder): - Layout::Android (1 south, 2 east, 4 west, 5 north, 7/8 L1/R1, 9/10 L2/R2, 11 select, 12 start, 13 home, 14/15 L3/R3), picked when the descriptor reports Simulation-page Brake / Accelerator triggers: BLE HID gamepads, the Xbox Wireless controller over BLE, espp's own gamepad report. - Analog triggers (GamepadReport::lt / rt) from Brake / Accelerator, or Rx / Ry when Z / Rz are the right stick (DualShock); Rx no longer overwrites the right stick's X on such pads. Capture (consumer Record) is reported on its own (GamepadReport::capture). - decode(report_id, payload) for transports that carry the report ID out of band (BLE), and a stateful update() / reset() that decodes the latest report of every ID together, so a pad that splits its state over several reports does not reset half of it on every report. - set_combine_controls(false) turns off the emulator conveniences (left stick as d-pad, analog triggers as L2/R2, Capture as Home) for a pass-through; on by default, so existing users see no change. - Per-field roles are worked out once in the constructor; layout_name(). gamepad_map (new component): - GamepadState: buttons by position (south / east / west / north ...), sticks -32767..32767 (Y down) and triggers 0..32767. - GamepadMapRule / GamepadMap: radial stick dead zones plus button -> button, axis -> button (threshold), button -> axis (value) and axis -> axis (scale / invert) rules; sources are moved unless KEEP_SOURCE, unmapped controls pass through, apply() does not allocate. Presets for swaps, inversion, stick <-> d-pad and triggers <-> buttons; valid(). - GamepadProfiles: a default map plus one map per controller type (vendor / product ID, name when both are 0), validated and saved atomically with PersistentData. - to_gamepad_state() from hid_rp::GamepadReport, fmt formatter, example (esp32s3, LittleFS), docs, host test; CI workflow gamepad_map_tests.yml also runs the hid-rp report-map host test. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU --- .github/workflows/build.yml | 2 + .github/workflows/gamepad_map_tests.yml | 69 +++ .github/workflows/upload_components.yml | 1 + components/gamepad_map/CMakeLists.txt | 4 + components/gamepad_map/README.md | 134 +++++ components/gamepad_map/example/CMakeLists.txt | 22 + components/gamepad_map/example/README.md | 61 +++ .../gamepad_map/example/main/CMakeLists.txt | 2 + .../example/main/gamepad_map_example.cpp | 126 +++++ components/gamepad_map/example/partitions.csv | 5 + .../gamepad_map/example/sdkconfig.defaults | 12 + components/gamepad_map/idf_component.yml | 24 + .../gamepad_map/include/gamepad_map.hpp | 334 ++++++++++++ .../gamepad_map/include/gamepad_profiles.hpp | 273 ++++++++++ .../gamepad_map/include/gamepad_state.hpp | 125 +++++ .../include/gamepad_state_formatters.hpp | 26 + .../include/gamepad_state_hid_rp.hpp | 52 ++ .../test/gamepad_map_host_test.cpp | 316 +++++++++++ .../hid-rp/include/hid-rp-report-map.hpp | 501 ++++++++++++++---- .../test/hid_rp_report_map_host_test.cpp | 168 +++++- .../main/usb_host_tab5_example.cpp | 4 +- doc/Doxyfile | 5 + doc/en/input/gamepad_map.rst | 34 ++ doc/en/input/gamepad_map_example.md | 2 + doc/en/input/index.rst | 1 + lib/espp.cmake | 1 + lib/include/espp.hpp | 4 + 27 files changed, 2194 insertions(+), 114 deletions(-) create mode 100644 .github/workflows/gamepad_map_tests.yml create mode 100644 components/gamepad_map/CMakeLists.txt create mode 100644 components/gamepad_map/README.md create mode 100644 components/gamepad_map/example/CMakeLists.txt create mode 100644 components/gamepad_map/example/README.md create mode 100644 components/gamepad_map/example/main/CMakeLists.txt create mode 100644 components/gamepad_map/example/main/gamepad_map_example.cpp create mode 100644 components/gamepad_map/example/partitions.csv create mode 100644 components/gamepad_map/example/sdkconfig.defaults create mode 100644 components/gamepad_map/idf_component.yml create mode 100644 components/gamepad_map/include/gamepad_map.hpp create mode 100644 components/gamepad_map/include/gamepad_profiles.hpp create mode 100644 components/gamepad_map/include/gamepad_state.hpp create mode 100644 components/gamepad_map/include/gamepad_state_formatters.hpp create mode 100644 components/gamepad_map/include/gamepad_state_hid_rp.hpp create mode 100644 components/gamepad_map/test/gamepad_map_host_test.cpp create mode 100644 doc/en/input/gamepad_map.rst create mode 100644 doc/en/input/gamepad_map_example.md diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 58a5d8d306..fce12b8f1b 100755 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -181,6 +181,8 @@ jobs: target: esp32 - path: 'components/ft5x06/example' target: esp32s3 + - path: 'components/gamepad_map/example' + target: esp32s3 - path: 'components/gfps_service/example' target: esp32s3 - path: 'components/gps/example' diff --git a/.github/workflows/gamepad_map_tests.yml b/.github/workflows/gamepad_map_tests.yml new file mode 100644 index 0000000000..b51c02f1a9 --- /dev/null +++ b/.github/workflows/gamepad_map_tests.yml @@ -0,0 +1,69 @@ +name: Gamepad map host test + +# Builds and runs, on the host with g++ -std=c++23: +# - components/gamepad_map/test/gamepad_map_host_test.cpp (GamepadState, +# GamepadMap rules + validation, the hid-rp conversion, GamepadProfiles' +# file round trip) +# - components/hid-rp/test/hid_rp_report_map_host_test.cpp (the runtime +# report map + Gamepad / Keyboard / Mouse decoders the map is fed from) +# Runs whenever either component, or what they store / log with, changes. + +# Minimal token scope: build + run tests, never writes. +permissions: + contents: read + +on: + pull_request: + paths: + - "components/gamepad_map/**" + - "components/hid-rp/**" + - "components/persistent_data/**" + - "components/serialization/**" + - ".github/workflows/gamepad_map_tests.yml" + push: + branches: + - main + paths: + - "components/gamepad_map/**" + - "components/hid-rp/**" + - "components/persistent_data/**" + - "components/serialization/**" + - ".github/workflows/gamepad_map_tests.yml" + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + host-test: + name: C++ host tests (gamepad map, hid-rp report map) + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v7 + with: + submodules: recursive + - name: Build and run hid_rp_report_map_host_test + run: | + g++ --version | head -1 + g++ -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_report_map_host_test.cpp -o hid_rp_report_map_host_test + ./hid_rp_report_map_host_test + - name: Build and run gamepad_map_host_test + run: | + g++ -std=c++23 -Wall -Wextra -Werror -Wno-comment \ + -I components/gamepad_map/include -I components/persistent_data/include \ + -I components/serialization/include -I components/base_component/include \ + -I components/logger/include -I components/format/include \ + -isystem components/serialization/detail/alpaca/include \ + -isystem components/format/detail/fmt/include \ + -isystem components/hid-rp/include \ + -isystem components/hid-rp/detail/hid-rp/hid-rp \ + components/gamepad_map/test/gamepad_map_host_test.cpp components/logger/src/logger.cpp \ + -o gamepad_map_host_test + ./gamepad_map_host_test diff --git a/.github/workflows/upload_components.yml b/.github/workflows/upload_components.yml index d845826d2b..510bfd4969 100755 --- a/.github/workflows/upload_components.yml +++ b/.github/workflows/upload_components.yml @@ -119,6 +119,7 @@ jobs: components/format components/ft5x06 components/ftp + components/gamepad_map components/gfps_service components/gps components/gt911 diff --git a/components/gamepad_map/CMakeLists.txt b/components/gamepad_map/CMakeLists.txt new file mode 100644 index 0000000000..eddea4ac62 --- /dev/null +++ b/components/gamepad_map/CMakeLists.txt @@ -0,0 +1,4 @@ +idf_component_register( + INCLUDE_DIRS "include" + REQUIRES base_component format hid-rp persistent_data + ) diff --git a/components/gamepad_map/README.md b/components/gamepad_map/README.md new file mode 100644 index 0000000000..d3f7453d48 --- /dev/null +++ b/components/gamepad_map/README.md @@ -0,0 +1,134 @@ +# Gamepad Map Component + +[![Badge](https://components.espressif.com/components/espp/gamepad_map/badge.svg)](https://components.espressif.com/components/espp/gamepad_map) + +The `gamepad_map` component remaps a gamepad's buttons and axes: button to +button, analog to digital, digital to analog and analog to analog, plus stick +dead zones. Maps are stored per controller type in a file with +[persistent_data](../persistent_data). The component is meant to sit between +whatever reads a controller (a BLE or USB HID gamepad, GPIO buttons) and +whatever comes next (an emulated USB controller, an emulator's input). + + +**Table of Contents** + +- [Gamepad Map Component](#gamepad-map-component) + - [Overview](#overview) + - [Gamepad state](#gamepad-state) + - [Rules](#rules) + - [Profiles](#profiles) + - [From a HID gamepad](#from-a-hid-gamepad) + - [Host test](#host-test) + - [Example](#example) + + + +## Overview + +| Type | What it is | +|------|------------| +| `espp::GamepadState` | Buttons by position plus six axes: the common format inputs are decoded into | +| `espp::GamepadMapRule` | One remap: where one control's input goes | +| `espp::GamepadMap` | Stick dead zones plus a list of rules; `apply()` maps one state to another | +| `espp::GamepadProfiles` | A default map plus one map per controller type, saved in a file | +| `espp::to_gamepad_state()` | A state from a `hid_rp::GamepadReport` (`gamepad_state_hid_rp.hpp`) | + +Everything except `GamepadProfiles` is header-only plain data with no +allocation in `apply()`, so it can run on every report. + +## Gamepad state + +`espp::GamepadState` names face buttons by **position** (south / east / west / +north), not label, because the labels disagree between controller families: + +| Position | Xbox | Nintendo | PlayStation | +|----------|------|----------|-------------| +| south | A | B | Cross | +| east | B | A | Circle | +| west | X | Y | Square | +| north | Y | X | Triangle | + +Besides the face buttons there are L1/R1, L2/R2 (the triggers as buttons), +L3/R3, Select, Start, Home, Capture, the d-pad and four paddles. The axes are +the two sticks (-32767..32767, X right, Y **down**, as in HID) and the two +triggers (0..32767). + +## Rules + +| Kind | Effect | `param` | +|------|--------|---------| +| button → button | the source presses the target | - | +| axis → button | the target is pressed while the axis is past the threshold | threshold: positive = at or above, negative = at or below | +| button → axis | while pressed, the value is added to the target axis | value | +| axis → axis | the scaled source is added to the target axis | scale in percent, -400..400 (negative inverts) | + +A control that is the source of a rule is **moved**: it no longer reaches its +own position unless the rule has `KEEP_SOURCE`. A rule with target `NONE` +removes its source. Several rules can feed one target: buttons are OR-ed and +axis contributions are summed, then clamped to the axis' range. Every control +that no rule takes as a source passes through unchanged, so an empty map is the +identity. + +```cpp +espp::GamepadMap map; +map.swap(B::South, B::East) // Nintendo-style A / B + .left_stick_to_dpad() // the stick also drives the d-pad + .triggers_to_buttons() // analog triggers also press ZL / ZR + .add(espp::GamepadMapRule::button(B::Paddle1, B::South)); // a paddle as A +map.left_deadzone_percent = 8; + +espp::GamepadState out = map.apply(in); +``` + +Check a map that came from outside (a file, a web page) with `valid()`. +`apply()` skips rules whose indices are out of range, so a bad map can never +read or write outside the state. + +## Profiles + +`espp::GamepadProfiles` keeps a default map and one `GamepadProfile` per +controller type, keyed by vendor and product ID. For BLE these come from the +Device Information service's PnP ID; for USB, from the device descriptor. A +controller that reports neither is matched by name. Every change is validated +and saved atomically. Look the map up when a controller connects, not on every +report: + +```cpp +espp::GamepadProfiles profiles({.file_path = fs.get_root_path() / "gamepad_profiles.bin", + .default_map = legacy_settings_as_a_map}); +espp::GamepadMap active = profiles.map_for(vid, pid, name); +``` + +The file is written on the first change. Until then the configured +`default_map` is used, which is how an application can migrate its older +settings into a map. + +## From a HID gamepad + +The runtime `hid_rp::GamepadDecoder` (`hid-rp-report-map.hpp`) decodes any HID +gamepad from its report descriptor. For a pass-through, turn off its emulator +conveniences (stick as d-pad, triggers as L2/R2, Capture as Home) so the map +decides those: + +```cpp +auto report_map = espp::hid_rp::ReportMap::parse(descriptor); +espp::hid_rp::GamepadDecoder decoder(std::move(*report_map)); +decoder.set_combine_controls(false); + +espp::hid_rp::GamepadReport report; +if (decoder.update(report_id, payload, report)) // BLE: the ID comes out of band + send(map.apply(espp::to_gamepad_state(report))); +``` + +## Host test + +`test/gamepad_map_host_test.cpp` covers the rule semantics, validation, the +hid-rp conversion (with a real BLE gamepad's descriptor) and the profile store's +file round trip. The build command is at the top of the file, and CI runs it in +`.github/workflows/gamepad_map_tests.yml` together with the hid-rp report-map +test. + +## Example + +The [example](./example) decodes a BLE gamepad report, remaps it, and stores +per-controller profiles on a LittleFS partition. diff --git a/components/gamepad_map/example/CMakeLists.txt b/components/gamepad_map/example/CMakeLists.txt new file mode 100644 index 0000000000..096a698bcb --- /dev/null +++ b/components/gamepad_map/example/CMakeLists.txt @@ -0,0 +1,22 @@ +# 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) + +set(ENV{IDF_COMPONENT_MANAGER} "0") +include($ENV{IDF_PATH}/tools/cmake/project.cmake) + +# add the component directories that we want to use +set(EXTRA_COMPONENT_DIRS + "../../../components/" +) + +set( + COMPONENTS + "main esptool_py logger file_system gamepad_map" + CACHE STRING + "List of components to include" + ) + +project(gamepad_map_example) + +set(CMAKE_CXX_STANDARD 23) diff --git a/components/gamepad_map/example/README.md b/components/gamepad_map/example/README.md new file mode 100644 index 0000000000..07d49a8a04 --- /dev/null +++ b/components/gamepad_map/example/README.md @@ -0,0 +1,61 @@ +# Gamepad Map Example + +This example shows the `gamepad_map` component between a gamepad and whatever +comes next: + +1. A BLE gamepad's HID report map (a ShanWan BSP-D8 in its Android mode) is + parsed with `hid_rp::ReportMap` and decoded with `hid_rp::GamepadDecoder`, + with the decoder's emulator conveniences turned off. +2. Each decoded report becomes an `espp::GamepadState`, which an + `espp::GamepadMap` remaps. The map here swaps A/B to the Nintendo layout, + puts the left stick on the d-pad as well, makes the analog triggers press + ZL/ZR too, and adds a left-stick dead zone. +3. `espp::GamepadProfiles` stores a default map and a per-controller-type + profile in a file on a [littlefs](https://github.com/littlefs-project/littlefs) + partition, and reloads them. + +It ends with a pass / fail summary. + +## How to use example + +### Hardware Required + +Any ESP32 with a `littlefs` partition (see `partitions.csv`). The partition +label is configured through `menuconfig` +(`CONFIG_ESPP_FILE_SYSTEM_PARTITION_LABEL`). + +### Build and Flash + +Build the project and flash it to the board, then run the monitor tool to view +serial output: + +``` +idf.py -p PORT flash monitor +``` + +(Replace PORT with the name of the serial port to use.) + +(To exit the serial monitor, type ``Ctrl-]``.) + +See the Getting Started Guide for full steps to configure and use ESP-IDF to build projects. + +## Expected Output + +``` +I (…) gamepad map example: Starting gamepad map example! +I (…) gamepad map example: Decode a BLE gamepad report, then remap it +I (…) gamepad map example: controller: {buttons: [south], lx: -32767, ly: 257, rx: 257, ry: 257, lt: 0, rt: 32767} +I (…) gamepad map example: mapped: {buttons: [east, r2, left], lx: -32767, ly: 0, rx: 257, ry: 257, lt: 0, rt: 32767} + [PASS] south is mapped to east + [PASS] the left stick also presses d-pad left + [PASS] the stick is kept + [PASS] the right trigger also presses R2 +I (…) gamepad map example: Per-controller profiles in a file +I (…) gamepad map example: BSP-D8 map: 4 rule(s); default map: 2 rule(s) + [PASS] the profile is used for its controller + [PASS] other controllers get the default map + [PASS] profiles survive a reload + [PASS] erase a profile +I (…) gamepad map example: 8 passed, 0 failed +I (…) gamepad map example: Gamepad map example complete! +``` diff --git a/components/gamepad_map/example/main/CMakeLists.txt b/components/gamepad_map/example/main/CMakeLists.txt new file mode 100644 index 0000000000..a941e22ba7 --- /dev/null +++ b/components/gamepad_map/example/main/CMakeLists.txt @@ -0,0 +1,2 @@ +idf_component_register(SRC_DIRS "." + INCLUDE_DIRS ".") diff --git a/components/gamepad_map/example/main/gamepad_map_example.cpp b/components/gamepad_map/example/main/gamepad_map_example.cpp new file mode 100644 index 0000000000..62e7abfd34 --- /dev/null +++ b/components/gamepad_map/example/main/gamepad_map_example.cpp @@ -0,0 +1,126 @@ +#include +#include +#include +#include + +#include "file_system.hpp" +#include "gamepad_map.hpp" +#include "gamepad_profiles.hpp" +#include "gamepad_state_formatters.hpp" +#include "gamepad_state_hid_rp.hpp" +#include "logger.hpp" + +using namespace std::chrono_literals; + +// The HID report map of a BLE gamepad (a ShanWan BSP-D8 in its Android mode), +// as read from its Report Map characteristic: report 3 = consumer keys, +// report 4 = 8-bit X/Y/Z/Rz sticks, a hat, 16 buttons, Brake / Accelerator. +static const char *kReportMapHex = + "050c0901a1018503751095011501269c0219012a9c028100c005010905a10185040901a1000930093109320935" + "150026ff00750895048102c00939150025073500463b016514750495018142750495018101050919012910150025" + "017501951081020502150026ff0009c409c5950275088102750895018101c0"; + +static std::vector from_hex(const char *hex) { + std::vector out; + for (; hex[0] && hex[1]; hex += 2) + out.push_back(static_cast(std::stoi(std::string(hex, 2), nullptr, 16))); + return out; +} + +extern "C" void app_main(void) { + espp::Logger logger({.tag = "gamepad map example", .level = espp::Logger::Verbosity::INFO}); + logger.info("Starting gamepad map example!"); + + int passed = 0; + int failed = 0; + auto check = [&](const char *name, bool ok) { + fmt::print(" [{}] {}\n", ok ? "PASS" : "FAIL", name); + (ok ? passed : failed)++; + }; + + using B = espp::GamepadState::Button; + using A = espp::GamepadState::Axis; + + { + logger.info("Decode a BLE gamepad report, then remap it"); + //! [gamepad map example] + // At connect: parse the controller's report map once and keep a decoder. + // A bridge decodes every control as only itself and lets the map decide. + auto report_map = espp::hid_rp::ReportMap::parse(from_hex(kReportMapHex)); + espp::hid_rp::GamepadDecoder decoder(std::move(*report_map)); + decoder.set_combine_controls(false); + + // The map: Nintendo-style A/B (south <-> east), the left stick also on the + // d-pad, analog triggers also as ZL / ZR, a 10% left-stick dead zone. + espp::GamepadMap map; + map.swap(B::South, B::East).left_stick_to_dpad().triggers_to_buttons(); + map.left_deadzone_percent = 10; + std::string why; + if (!map.valid(&why)) + logger.error("Invalid map: {}", why); + + // For every report: decode (BLE delivers the report ID out of band), map, + // and hand the result on. Here: the south button (A), left stick fully + // left, right trigger fully pressed. + const std::vector payload{0x00, 0x80, 0x80, 0x80, 0x0f, 0x01, 0x00, 0xff, 0x00, 0x00}; + espp::hid_rp::GamepadReport report; + if (decoder.update(4, payload, report)) { + const espp::GamepadState in = espp::to_gamepad_state(report); + const espp::GamepadState out = map.apply(in); + logger.info("controller: {}", in); + logger.info("mapped: {}", out); + } + //! [gamepad map example] + espp::hid_rp::GamepadReport r; + decoder.update(4, payload, r); + const auto out = map.apply(espp::to_gamepad_state(r)); + check("south is mapped to east", out.pressed(B::East) && !out.pressed(B::South)); + check("the left stick also presses d-pad left", out.pressed(B::Left)); + check("the stick is kept", out.axis(A::LeftX) < -30000); + check("the right trigger also presses R2", out.pressed(B::R2)); + } + + { + logger.info("Per-controller profiles in a file"); + auto &fs = espp::FileSystem::get(); + const std::filesystem::path path = fs.get_root_path() / "gamepad_profiles.bin"; + std::error_code ec; + std::filesystem::remove(path, ec); // start clean for the checks below + //! [gamepad profiles example] + // The default map is used for controllers without a profile; the file is + // written on the first change. + espp::GamepadMap default_map; + default_map.invert(A::LeftY).invert(A::RightY); // up-positive sticks for this host + espp::GamepadProfiles profiles({ + .file_path = path, + .default_map = default_map, + .log_level = espp::Logger::Verbosity::INFO, + }); + + // A profile for one controller type (vendor / product ID; from the BLE + // Device Information PnP ID, or the USB device descriptor). + espp::GamepadMap bsp_d8 = default_map; + bsp_d8.swap(B::South, B::East); + if (!profiles.set_profile({.vid = 0x1949, .pid = 0x0402, .name = "BSP-D8", .map = bsp_d8}, ec)) + logger.error("Could not save the profile: {}", ec.message()); + + // When a controller connects, look its map up once and keep it. + const espp::GamepadMap active = profiles.map_for(0x1949, 0x0402, "BSP-D8"); + logger.info("BSP-D8 map: {} rule(s); default map: {} rule(s)", active.rules.size(), + profiles.default_map().rules.size()); + //! [gamepad profiles example] + check("the profile is used for its controller", active == bsp_d8); + check("other controllers get the default map", profiles.map_for(0x045e, 0x0b13) == default_map); + espp::GamepadProfiles reloaded({.file_path = path}); + check("profiles survive a reload", + reloaded.map_for(0x1949, 0x0402) == bsp_d8 && reloaded.default_map() == default_map); + check("erase a profile", reloaded.erase_profile(0x1949, 0x0402, "", ec) && !ec && + reloaded.map_for(0x1949, 0x0402) == default_map); + } + + logger.info("{} passed, {} failed", passed, failed); + logger.info("Gamepad map example complete!"); + while (true) { + std::this_thread::sleep_for(1s); + } +} diff --git a/components/gamepad_map/example/partitions.csv b/components/gamepad_map/example/partitions.csv new file mode 100644 index 0000000000..4196003405 --- /dev/null +++ b/components/gamepad_map/example/partitions.csv @@ -0,0 +1,5 @@ +# Name, Type, SubType, Offset, Size +nvs, data, nvs, 0x9000, 0x6000 +phy_init, data, phy, 0xf000, 0x1000 +factory, app, factory, 0x10000, 2M +littlefs, data, littlefs, , 1M diff --git a/components/gamepad_map/example/sdkconfig.defaults b/components/gamepad_map/example/sdkconfig.defaults new file mode 100644 index 0000000000..169de32462 --- /dev/null +++ b/components/gamepad_map/example/sdkconfig.defaults @@ -0,0 +1,12 @@ +# Common ESP-related +# +CONFIG_ESP_SYSTEM_EVENT_TASK_STACK_SIZE=4096 +CONFIG_ESP_MAIN_TASK_STACK_SIZE=8192 + +CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y + +# +# Partition Table +# +CONFIG_PARTITION_TABLE_CUSTOM=y +CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv" diff --git a/components/gamepad_map/idf_component.yml b/components/gamepad_map/idf_component.yml new file mode 100644 index 0000000000..20efd4f705 --- /dev/null +++ b/components/gamepad_map/idf_component.yml @@ -0,0 +1,24 @@ +## IDF Component Manager Manifest File +license: "MIT" +description: "Gamepad button / axis remapping with per-controller profiles for ESP-IDF" +url: "https://github.com/esp-cpp/espp/tree/main/components/gamepad_map" +repository: "git://github.com/esp-cpp/espp.git" +maintainers: + - William Emfinger +documentation: "https://esp-cpp.github.io/espp/input/gamepad_map.html" +examples: + - path: example +tags: + - cpp + - Component + - Input + - Gamepad + - HID +dependencies: + idf: + version: '>=5.0' + espp/base_component: '>=1.0' + espp/format: '>=1.0' + # GamepadReport::lt / rt / capture and GamepadDecoder::set_combine_controls() + espp/hid-rp: '>=1.4.6' + espp/persistent_data: '>=1.0' diff --git a/components/gamepad_map/include/gamepad_map.hpp b/components/gamepad_map/include/gamepad_map.hpp new file mode 100644 index 0000000000..0918054d13 --- /dev/null +++ b/components/gamepad_map/include/gamepad_map.hpp @@ -0,0 +1,334 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "gamepad_state.hpp" + +namespace espp { + +/** + * @brief One rule of a GamepadMap: where one control's input goes. + * + * @details Four kinds of rule cover the remaps controllers need: + * - **button -> button**: the source button presses the target + * (swap A/B, move a function to a paddle); + * - **axis -> button**: the target is pressed while the source axis + * is past a threshold (a stick direction as the d-pad, an analog + * trigger as ZL/ZR). A positive threshold presses at values >= it, + * a negative one at values <= it (stick up / left); + * - **button -> axis**: while the source button is pressed it adds a + * value to the target axis (the d-pad as the left stick, a button + * as a full trigger); + * - **axis -> axis**: the source axis, scaled by a percentage (a + * negative scale inverts), is added to the target (swap or invert + * sticks, a stick as a trigger). + * + * A control that is the source of a rule no longer reaches its own + * position (it is "moved", not copied) unless the rule sets + * KEEP_SOURCE; a rule whose target is NONE just removes its source. + * Several rules may feed one target: buttons are OR-ed, axis + * contributions are summed and clamped. + * + * The struct is plain data (it is stored with PersistentData and + * sent over the wire as is); build rules with the static helpers. + */ +struct GamepadMapRule { + using Button = GamepadState::Button; + using Axis = GamepadState::Axis; + + /// What the source and target are. + enum class Kind : uint8_t { + ButtonToButton, ///< param unused + AxisToButton, ///< param = threshold (sign = direction), never 0 + ButtonToAxis, ///< param = value added to the target while pressed + AxisToAxis, ///< param = scale in percent, -400..400 (negative inverts) + }; + + static constexpr uint8_t NONE = 0xFF; ///< target: remove the source, send it nowhere + static constexpr uint8_t KEEP_SOURCE = 0x01; ///< flag: the source also stays where it was + static constexpr int16_t MAX_SCALE_PERCENT = 400; + + Kind kind{Kind::ButtonToButton}; + uint8_t source{0}; ///< a Button or an Axis (by kind) + uint8_t target{NONE}; ///< a Button or an Axis (by kind), or NONE + uint8_t flags{0}; ///< KEEP_SOURCE + int16_t param{0}; ///< see Kind + + /// @brief Whether the source stays at its own position too. + constexpr bool keeps_source() const { return flags & KEEP_SOURCE; } + /// @brief Whether the source is an axis. + constexpr bool source_is_axis() const { + return kind == Kind::AxisToButton || kind == Kind::AxisToAxis; + } + /// @brief Whether the target is an axis. + constexpr bool target_is_axis() const { + return kind == Kind::ButtonToAxis || kind == Kind::AxisToAxis; + } + + /// @brief `from` presses `to`. + static constexpr GamepadMapRule button(Button from, Button to, bool keep_source = false) { + return {Kind::ButtonToButton, static_cast(from), static_cast(to), + keep_flag(keep_source), 0}; + } + /// @brief `to` is pressed while `from` is at or past `threshold` (a negative + /// threshold: at or below it). 16384 is half way. + static constexpr GamepadMapRule axis_to_button(Axis from, int16_t threshold, Button to, + bool keep_source = false) { + return {Kind::AxisToButton, static_cast(from), static_cast(to), + keep_flag(keep_source), threshold}; + } + /// @brief While `from` is pressed, `value` is added to `to` (e.g. 32767 for a + /// full trigger, -32767 for the left stick fully left). + static constexpr GamepadMapRule button_to_axis(Button from, Axis to, int16_t value, + bool keep_source = false) { + return {Kind::ButtonToAxis, static_cast(from), static_cast(to), + keep_flag(keep_source), value}; + } + /// @brief `from` scaled by `scale_percent` is added to `to` (-100 inverts). + static constexpr GamepadMapRule axis(Axis from, Axis to, int16_t scale_percent = 100, + bool keep_source = false) { + return {Kind::AxisToAxis, static_cast(from), static_cast(to), + keep_flag(keep_source), scale_percent}; + } + /// @brief Remove a button. + static constexpr GamepadMapRule disable(Button b) { + return {Kind::ButtonToButton, static_cast(b), NONE, 0, 0}; + } + /// @brief Remove an axis (it reads 0 / released). + static constexpr GamepadMapRule disable(Axis a) { + return {Kind::AxisToAxis, static_cast(a), NONE, 0, 100}; + } + + /// @brief Whether the rule is well formed; `why` (if given) says what is wrong. + bool valid(std::string *why = nullptr) const { + auto fail = [why](const char *reason) { + if (why) + *why = reason; + return false; + }; + if (kind > Kind::AxisToAxis) + return fail("unknown rule kind"); + if (flags & ~KEEP_SOURCE) + return fail("unknown flags"); + const size_t sources = source_is_axis() ? GamepadState::AXIS_COUNT : GamepadState::BUTTON_COUNT; + const size_t targets = target_is_axis() ? GamepadState::AXIS_COUNT : GamepadState::BUTTON_COUNT; + if (source >= sources) + return fail("source out of range"); + if (target != NONE && target >= targets) + return fail("target out of range"); + if (kind == Kind::AxisToButton && param == 0) + return fail("axis -> button needs a non-zero threshold"); + if (kind == Kind::AxisToAxis && (param < -MAX_SCALE_PERCENT || param > MAX_SCALE_PERCENT)) + return fail("axis -> axis scale out of range"); + return true; + } + + constexpr bool operator==(const GamepadMapRule &) const = default; + +private: + static constexpr uint8_t keep_flag(bool keep) { return keep ? KEEP_SOURCE : 0; } +}; + +/** + * @brief A button / axis mapping for a gamepad: radial stick dead zones plus a + * list of GamepadMapRule. + * + * @details apply() turns the state a controller reports into the state to + * send on: dead zones first (they belong to the physical sticks), + * then the rules; every control no rule takes as its source passes + * through unchanged, so an empty map is the identity. apply() does + * not allocate and touches each rule twice, so it is cheap enough to + * run on every report. + * + * A GamepadMap is plain data: copy it, store it (see GamepadProfiles), + * send it. Use valid() on one that came from outside (a file, a web + * page) before using it. + * + * \section gamepad_map_ex1 Gamepad Map Example + * \snippet gamepad_map_example.cpp gamepad map example + */ +struct GamepadMap { + using Button = GamepadState::Button; + using Axis = GamepadState::Axis; + using Rule = GamepadMapRule; + + static constexpr size_t MAX_RULES = 64; ///< rules a valid map may hold + static constexpr uint8_t MAX_DEADZONE_PERCENT = 90; ///< largest valid dead zone + + uint8_t left_deadzone_percent{0}; ///< radial dead zone of the left stick, 0..90 + uint8_t right_deadzone_percent{0}; ///< radial dead zone of the right stick, 0..90 + std::vector rules{}; + + /// @brief Whether the map is well formed; `why` (if given) says what is wrong. + bool valid(std::string *why = nullptr) const { + if (left_deadzone_percent > MAX_DEADZONE_PERCENT || + right_deadzone_percent > MAX_DEADZONE_PERCENT) { + if (why) + *why = "dead zone out of range"; + return false; + } + if (rules.size() > MAX_RULES) { + if (why) + *why = "too many rules"; + return false; + } + for (size_t i = 0; i < rules.size(); i++) { + std::string reason; + if (!rules[i].valid(&reason)) { + if (why) + *why = "rule " + std::to_string(i) + ": " + reason; + return false; + } + } + return true; + } + + /// @brief Whether the map changes nothing. + bool is_identity() const { + return left_deadzone_percent == 0 && right_deadzone_percent == 0 && rules.empty(); + } + + /// @brief Map `in` to `out` (they may be the same object). Rules that are + /// not valid() are skipped. + void apply(const GamepadState &in_state, GamepadState &out) const { + GamepadState in = in_state; // `out` may alias `in_state` + apply_deadzone(in, Axis::LeftX, Axis::LeftY, left_deadzone_percent); + apply_deadzone(in, Axis::RightX, Axis::RightY, right_deadzone_percent); + + // controls moved elsewhere do not pass through + uint32_t moved_buttons = 0; + uint32_t moved_axes = 0; + for (const auto &r : rules) { + if (r.keeps_source() || !usable(r)) + continue; + (r.source_is_axis() ? moved_axes : moved_buttons) |= 1u << r.source; + } + std::array sum{}; + for (size_t a = 0; a < GamepadState::AXIS_COUNT; a++) { + if (!(moved_axes & (1u << a))) + sum[a] = in.axes[a]; + } + uint32_t buttons = in.buttons & ~moved_buttons; + + for (const auto &r : rules) { + if (r.target == Rule::NONE || !usable(r)) + continue; + switch (r.kind) { + case Rule::Kind::ButtonToButton: + if ((in.buttons >> r.source) & 1u) + buttons |= 1u << r.target; + break; + case Rule::Kind::AxisToButton: { + const int16_t v = in.axes[r.source]; + if (r.param > 0 ? v >= r.param : v <= r.param) + buttons |= 1u << r.target; + break; + } + case Rule::Kind::ButtonToAxis: + if ((in.buttons >> r.source) & 1u) + sum[r.target] += r.param; + break; + case Rule::Kind::AxisToAxis: + sum[r.target] += static_cast(in.axes[r.source]) * r.param / 100; + break; + } + } + out.buttons = buttons; + for (size_t a = 0; a < GamepadState::AXIS_COUNT; a++) + out.axes[a] = GamepadState::clamp(static_cast(a), sum[a]); + } + + /// @brief The mapped copy of `in`. + GamepadState apply(const GamepadState &in) const { + GamepadState out; + apply(in, out); + return out; + } + + // --- building maps --- + + /// @brief Add a rule (no check: see valid()). Returns *this for chaining. + GamepadMap &add(const GamepadMapRule &rule) { + rules.push_back(rule); + return *this; + } + /// @brief Exchange two buttons (e.g. south/east for Nintendo A/B placement). + GamepadMap &swap(Button a, Button b) { return add(Rule::button(a, b)).add(Rule::button(b, a)); } + /// @brief Exchange two axes (e.g. the sticks, one axis at a time). + GamepadMap &swap(Axis a, Axis b) { return add(Rule::axis(a, b)).add(Rule::axis(b, a)); } + /// @brief Invert an axis (stick Y up-positive, say). + GamepadMap &invert(Axis a) { return add(Rule::axis(a, a, -100)); } + /// @brief Exchange the left and right sticks. + GamepadMap &swap_sticks() { + return swap(Axis::LeftX, Axis::RightX).swap(Axis::LeftY, Axis::RightY); + } + /// @brief The left stick also drives the d-pad past `threshold` (default 50%). + GamepadMap &left_stick_to_dpad(int16_t threshold = 16384, bool keep_stick = true) { + return add(Rule::axis_to_button(Axis::LeftX, static_cast(-threshold), Button::Left, + keep_stick)) + .add(Rule::axis_to_button(Axis::LeftX, threshold, Button::Right, keep_stick)) + .add(Rule::axis_to_button(Axis::LeftY, static_cast(-threshold), Button::Up, + keep_stick)) + .add(Rule::axis_to_button(Axis::LeftY, threshold, Button::Down, keep_stick)); + } + /// @brief The d-pad also drives the left stick to full deflection. + GamepadMap &dpad_to_left_stick(bool keep_dpad = true) { + return add(Rule::button_to_axis(Button::Left, Axis::LeftX, -GamepadState::AXIS_MAX, keep_dpad)) + .add(Rule::button_to_axis(Button::Right, Axis::LeftX, GamepadState::AXIS_MAX, keep_dpad)) + .add(Rule::button_to_axis(Button::Up, Axis::LeftY, -GamepadState::AXIS_MAX, keep_dpad)) + .add(Rule::button_to_axis(Button::Down, Axis::LeftY, GamepadState::AXIS_MAX, keep_dpad)); + } + /// @brief The analog triggers also press L2 / R2 past `threshold` (default 40%). + GamepadMap &triggers_to_buttons(int16_t threshold = 13107, bool keep_triggers = true) { + return add(Rule::axis_to_button(Axis::LeftTrigger, threshold, Button::L2, keep_triggers)) + .add(Rule::axis_to_button(Axis::RightTrigger, threshold, Button::R2, keep_triggers)); + } + /// @brief L2 / R2 also pull the analog triggers fully (for digital-trigger pads). + GamepadMap &buttons_to_triggers(bool keep_buttons = true) { + return add(Rule::button_to_axis(Button::L2, Axis::LeftTrigger, GamepadState::AXIS_MAX, + keep_buttons)) + .add(Rule::button_to_axis(Button::R2, Axis::RightTrigger, GamepadState::AXIS_MAX, + keep_buttons)); + } + + bool operator==(const GamepadMap &) const = default; + +private: + static bool usable(const GamepadMapRule &r) { + // the cheap part of valid(): indices in range, so apply() never reads or + // writes outside the state + const size_t sources = + r.source_is_axis() ? GamepadState::AXIS_COUNT : GamepadState::BUTTON_COUNT; + const size_t targets = + r.target_is_axis() ? GamepadState::AXIS_COUNT : GamepadState::BUTTON_COUNT; + return r.kind <= GamepadMapRule::Kind::AxisToAxis && r.source < sources && + (r.target == GamepadMapRule::NONE || r.target < targets) && + !(r.kind == GamepadMapRule::Kind::AxisToButton && r.param == 0); + } + + static void apply_deadzone(GamepadState &s, Axis x_axis, Axis y_axis, uint8_t percent) { + if (percent == 0 || percent > MAX_DEADZONE_PERCENT) + return; + const float x = s.axis(x_axis), y = s.axis(y_axis); + const float mag = std::sqrt(x * x + y * y); + const float dead = GamepadState::AXIS_MAX * (percent / 100.0f); + if (mag <= dead) { + s.set(x_axis, 0); + s.set(y_axis, 0); + return; + } + // rescale what is left so the edge of the dead zone reads 0 and full + // deflection still reads full + const float scale = std::min(1.0f, (mag - dead) / (GamepadState::AXIS_MAX - dead)) * + GamepadState::AXIS_MAX / mag; + s.set(x_axis, static_cast(std::lround(x * scale))); + s.set(y_axis, static_cast(std::lround(y * scale))); + } +}; + +} // namespace espp diff --git a/components/gamepad_map/include/gamepad_profiles.hpp b/components/gamepad_map/include/gamepad_profiles.hpp new file mode 100644 index 0000000000..aca9a07070 --- /dev/null +++ b/components/gamepad_map/include/gamepad_profiles.hpp @@ -0,0 +1,273 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "base_component.hpp" +#include "gamepad_map.hpp" +#include "persistent_data.hpp" + +namespace espp { + +/** + * @brief The map for one type of controller. + * + * @details A controller type is its USB / Bluetooth vendor and product ID + * (for BLE, from the Device Information service's PnP ID). A + * controller that reports neither (VID and PID 0) is matched by its + * name instead. + */ +struct GamepadProfile { + uint16_t vid{0}; ///< vendor ID (0 = unknown: match by name) + uint16_t pid{0}; ///< product ID (0 = unknown: match by name) + std::string name{}; ///< for display, and the key when VID and PID are 0 + GamepadMap map{}; ///< the mapping for this controller type + + /// @brief Whether this profile is for the controller with these IDs / name. + bool matches(uint16_t vid_, uint16_t pid_, const std::string &name_) const { + if (vid == 0 && pid == 0) + return vid_ == 0 && pid_ == 0 && !name.empty() && name == name_; + return vid == vid_ && pid == pid_; + } + + bool operator==(const GamepadProfile &) const = default; +}; + +/// @brief The data a GamepadProfiles store keeps (schema version 1). +struct GamepadProfilesV1 { + static constexpr uint32_t VERSION = 1; + GamepadMap default_map{}; ///< for a controller without a profile + std::vector profiles{}; ///< per controller type +}; + +/** + * @brief Per-controller-type gamepad maps, stored in a file with + * PersistentData. + * + * @details Holds a default map plus one GamepadProfile per controller type, + * and saves every change atomically (see PersistentData) to a file on + * a mounted filesystem (LittleFS, SPIFFS, SD). Look a controller up + * when it connects (map_for()) and keep the returned map for its + * reports; the lookup copies the map and is not meant for every + * report. + * + * Every map that comes in is checked with GamepadMap::valid(); one + * loaded from a file that is not (or is a duplicate) is dropped + * with a warning rather than used. + * + * Thread-safe. + * + * \section gamepad_profiles_ex1 Gamepad Profiles Example + * \snippet gamepad_map_example.cpp gamepad profiles example + */ +class GamepadProfiles : public BaseComponent { +public: + using Data = GamepadProfilesV1; + using Storage = PersistentData; + + /** + * @brief Configuration for the GamepadProfiles. + */ + struct Config { + std::filesystem::path file_path; ///< file the profiles live in + GamepadMap default_map{}; ///< default map when the file does not exist yet + size_t max_profiles{16}; ///< profiles the store accepts + Logger::Verbosity log_level{Logger::Verbosity::WARN}; ///< Verbosity of the logger + }; + + /** + * @brief Load the profiles (or start from `config.default_map` when there is + * no file yet; the file is written on the first change). + * @param config The configuration. + */ + explicit GamepadProfiles(const Config &config) + : BaseComponent("GamepadProfiles", config.log_level) + , max_profiles_(config.max_profiles) + , storage_( + {.file_path = config.file_path, .auto_load = false, .log_level = config.log_level}) { + std::error_code ec; + if (storage_.load(ec)) { + data_ = sanitize(storage_.get()); + } else { + if (ec != make_error_code(PersistentDataErrc::file_not_found)) + logger_.warn("Could not load {}: {}; starting from the defaults", config.file_path.string(), + ec.message()); + data_.default_map = config.default_map.valid() ? config.default_map : GamepadMap{}; + } + } + + /// @brief The map for a controller: its profile's, else the default map. + GamepadMap map_for(uint16_t vid, uint16_t pid, const std::string &name = {}) const { + std::lock_guard lock(mutex_); + const auto *p = find(vid, pid, name); + return p ? p->map : data_.default_map; + } + + /// @brief The profile for a controller, if it has one. + std::optional profile(uint16_t vid, uint16_t pid, + const std::string &name = {}) const { + std::lock_guard lock(mutex_); + const auto *p = find(vid, pid, name); + return p ? std::optional(*p) : std::nullopt; + } + + /// @brief Every profile. + std::vector profiles() const { + std::lock_guard lock(mutex_); + return data_.profiles; + } + + /// @brief The map for controllers without a profile. + GamepadMap default_map() const { + std::lock_guard lock(mutex_); + return data_.default_map; + } + + /// @brief Everything, as stored. + Data data() const { + std::lock_guard lock(mutex_); + return data_; + } + + /// @brief The most profiles the store accepts. + size_t max_profiles() const { return max_profiles_; } + + /** + * @brief Replace the default map and save. + * @param map The map (must be valid()). + * @param ec Set on failure: std::errc::invalid_argument for an invalid map, + * else the save error. + * @return true if saved. + */ + bool set_default_map(const GamepadMap &map, std::error_code &ec) { + if (!check(map, ec)) + return false; + std::lock_guard lock(mutex_); + Data next = data_; + next.default_map = map; + return commit(std::move(next), ec); + } + + /** + * @brief Add a profile, or replace the one for the same controller, and save. + * @param profile The profile (its map must be valid(); with VID and PID 0 it + * needs a name). + * @param ec Set on failure: std::errc::invalid_argument for an invalid + * profile, std::errc::no_buffer_space when the store is full, else + * the save error. + * @return true if saved. + */ + bool set_profile(const GamepadProfile &profile, std::error_code &ec) { + if (!check(profile.map, ec)) + return false; + if (profile.vid == 0 && profile.pid == 0 && profile.name.empty()) { + ec = std::make_error_code(std::errc::invalid_argument); + return false; + } + std::lock_guard lock(mutex_); + Data next = data_; + auto it = + std::find_if(next.profiles.begin(), next.profiles.end(), [&](const GamepadProfile &p) { + return p.matches(profile.vid, profile.pid, profile.name); + }); + if (it != next.profiles.end()) { + *it = profile; + } else if (next.profiles.size() >= max_profiles_) { + ec = std::make_error_code(std::errc::no_buffer_space); + return false; + } else { + next.profiles.push_back(profile); + } + return commit(std::move(next), ec); + } + + /** + * @brief Remove a controller's profile (it then uses the default map) and save. + * @return true if saved; false with `ec` clear if there was no such profile. + */ + bool erase_profile(uint16_t vid, uint16_t pid, const std::string &name, std::error_code &ec) { + ec.clear(); + std::lock_guard lock(mutex_); + Data next = data_; + const auto before = next.profiles.size(); + std::erase_if(next.profiles, + [&](const GamepadProfile &p) { return p.matches(vid, pid, name); }); + if (next.profiles.size() == before) + return false; + return commit(std::move(next), ec); + } + + /** + * @brief Forget every profile and reset the default map to identity, and save. + * @return true if saved. + */ + bool reset(std::error_code &ec) { + std::lock_guard lock(mutex_); + return commit(Data{}, ec); + } + +private: + const GamepadProfile *find(uint16_t vid, uint16_t pid, const std::string &name) const { + auto it = std::find_if(data_.profiles.begin(), data_.profiles.end(), + [&](const GamepadProfile &p) { return p.matches(vid, pid, name); }); + return it == data_.profiles.end() ? nullptr : &*it; + } + + static bool check(const GamepadMap &map, std::error_code &ec) { + ec.clear(); + if (!map.valid()) { + ec = std::make_error_code(std::errc::invalid_argument); + return false; + } + return true; + } + + // save first, then take it: memory never holds what the file does not + bool commit(Data next, std::error_code &ec) { + ec.clear(); + if (!storage_.save(next, ec)) + return false; + data_ = std::move(next); + return true; + } + + Data sanitize(Data d) const { + std::string why; + if (!d.default_map.valid(&why)) { + logger_.warn("Stored default map is invalid ({}); using identity", why); + d.default_map = {}; + } + std::vector kept; + for (auto &p : d.profiles) { + if (!p.map.valid(&why)) { + logger_.warn("Dropping the stored profile for {:04x}:{:04x} '{}': {}", p.vid, p.pid, p.name, + why); + continue; + } + const bool dup = std::any_of(kept.begin(), kept.end(), [&](const GamepadProfile &k) { + return k.matches(p.vid, p.pid, p.name); + }); + if (dup || kept.size() >= max_profiles_) { + logger_.warn("Dropping the stored profile for {:04x}:{:04x} '{}': {}", p.vid, p.pid, p.name, + dup ? "duplicate" : "over the profile limit"); + continue; + } + kept.push_back(std::move(p)); + } + d.profiles = std::move(kept); + return d; + } + + size_t max_profiles_; + Storage storage_; + mutable std::mutex mutex_; + Data data_{}; +}; + +} // namespace espp diff --git a/components/gamepad_map/include/gamepad_state.hpp b/components/gamepad_map/include/gamepad_state.hpp new file mode 100644 index 0000000000..52389d7816 --- /dev/null +++ b/components/gamepad_map/include/gamepad_state.hpp @@ -0,0 +1,125 @@ +#pragma once + +#include +#include +#include + +namespace espp { + +/** + * @brief The state of a gamepad, by control position. + * + * @details The common currency of the gamepad_map component: inputs are + * decoded into it (from a HID report, a USB/BLE controller, GPIO + * buttons...), a GamepadMap rewrites it, and the result is encoded + * into whatever comes next (a USB controller report, an emulator's + * input). + * + * Face buttons are named by **position**, not label, because the + * labels disagree between controller families: south is Xbox A / + * Nintendo B / PlayStation Cross, east is Xbox B / Nintendo A / + * PlayStation Circle, west is Xbox X / Nintendo Y / Square and north + * is Xbox Y / Nintendo X / Triangle. + * + * Sticks are -32767..32767 with X growing to the right and Y growing + * **downwards** (the HID convention); triggers are 0..32767. + */ +struct GamepadState { + /// A digital control. + enum class Button : uint8_t { + South, ///< Xbox A, Nintendo B, PlayStation Cross + East, ///< Xbox B, Nintendo A, PlayStation Circle + West, ///< Xbox X, Nintendo Y, PlayStation Square + North, ///< Xbox Y, Nintendo X, PlayStation Triangle + L1, ///< left bumper / L + R1, ///< right bumper / R + L2, ///< left trigger as a button / ZL + R2, ///< right trigger as a button / ZR + L3, ///< left stick click + R3, ///< right stick click + Select, ///< View / Back / Minus / Share + Start, ///< Menu / Plus / Options + Home, ///< Guide / Home / PS + Capture, ///< Share (Xbox Series) / Capture (Nintendo) + Up, ///< d-pad up + Down, ///< d-pad down + Left, ///< d-pad left + Right, ///< d-pad right + Paddle1, ///< extra / back buttons (paddles, SL/SR...) + Paddle2, + Paddle3, + Paddle4, + Count ///< number of buttons (not a button) + }; + + /// An analog control. + enum class Axis : uint8_t { + LeftX, ///< left stick X, -32767 (left) .. 32767 (right) + LeftY, ///< left stick Y, -32767 (up) .. 32767 (down) + RightX, ///< right stick X + RightY, ///< right stick Y + LeftTrigger, ///< 0 (released) .. 32767 (fully pressed) + RightTrigger, ///< 0 (released) .. 32767 (fully pressed) + Count ///< number of axes (not an axis) + }; + + static constexpr size_t BUTTON_COUNT = static_cast(Button::Count); + static constexpr size_t AXIS_COUNT = static_cast(Axis::Count); + static constexpr int16_t AXIS_MAX = 32767; ///< full deflection of a stick or trigger + + uint32_t buttons{0}; ///< bit n = Button n pressed + std::array axes{}; ///< indexed by Axis + + /// @brief Whether a button is pressed. + constexpr bool pressed(Button b) const { + return b < Button::Count && (buttons >> static_cast(b)) & 1u; + } + /// @brief Press or release a button. + constexpr void set(Button b, bool pressed) { + if (b >= Button::Count) + return; + const uint32_t bit = 1u << static_cast(b); + buttons = pressed ? (buttons | bit) : (buttons & ~bit); + } + /// @brief The value of an axis (0 for an invalid axis). + constexpr int16_t axis(Axis a) const { + return a < Axis::Count ? axes[static_cast(a)] : 0; + } + /// @brief Set an axis, clamped to its range (see is_trigger()). + constexpr void set(Axis a, int32_t value) { + if (a >= Axis::Count) + return; + axes[static_cast(a)] = clamp(a, value); + } + + /// @brief Whether an axis is a trigger (0..32767) rather than a stick axis. + static constexpr bool is_trigger(Axis a) { + return a == Axis::LeftTrigger || a == Axis::RightTrigger; + } + /// @brief Clamp a value to an axis' range. + static constexpr int16_t clamp(Axis a, int32_t value) { + const int32_t lo = is_trigger(a) ? 0 : -AXIS_MAX; + return static_cast(value < lo ? lo : value > AXIS_MAX ? AXIS_MAX : value); + } + + /// @brief Short, stable name of a button ("south", "l1", "up"...), for logs and UIs. + static constexpr const char *name(Button b) { + constexpr const char *names[] = {"south", "east", "west", "north", "l1", "r1", + "l2", "r2", "l3", "r3", "select", "start", + "home", "capture", "up", "down", "left", "right", + "paddle1", "paddle2", "paddle3", "paddle4"}; + static_assert(sizeof(names) / sizeof(names[0]) == BUTTON_COUNT); + return b < Button::Count ? names[static_cast(b)] : "?"; + } + /// @brief Short, stable name of an axis ("left_x", "right_trigger"...). + static constexpr const char *name(Axis a) { + constexpr const char *names[] = {"left_x", "left_y", "right_x", + "right_y", "left_trigger", "right_trigger"}; + static_assert(sizeof(names) / sizeof(names[0]) == AXIS_COUNT); + return a < Axis::Count ? names[static_cast(a)] : "?"; + } + + bool operator==(const GamepadState &) const = default; +}; + +} // namespace espp diff --git a/components/gamepad_map/include/gamepad_state_formatters.hpp b/components/gamepad_map/include/gamepad_state_formatters.hpp new file mode 100644 index 0000000000..0851386fc7 --- /dev/null +++ b/components/gamepad_map/include/gamepad_state_formatters.hpp @@ -0,0 +1,26 @@ +#pragma once + +#include "format.hpp" +#include "gamepad_state.hpp" + +/// Formats a GamepadState as the pressed buttons by name plus the axes, e.g. +/// `{buttons: [south, up], lx: 0, ly: -32767, rx: 0, ry: 0, lt: 0, rt: 32767}`. +template <> struct fmt::formatter : fmt::formatter { + template + auto format(const espp::GamepadState &s, FormatContext &ctx) const -> decltype(ctx.out()) { + using B = espp::GamepadState::Button; + using A = espp::GamepadState::Axis; + auto out = fmt::format_to(ctx.out(), "{{buttons: ["); + bool first = true; + for (size_t i = 0; i < espp::GamepadState::BUTTON_COUNT; i++) { + const auto b = static_cast(i); + if (!s.pressed(b)) + continue; + out = fmt::format_to(out, "{}{}", first ? "" : ", ", espp::GamepadState::name(b)); + first = false; + } + return fmt::format_to(out, "], lx: {}, ly: {}, rx: {}, ry: {}, lt: {}, rt: {}}}", + s.axis(A::LeftX), s.axis(A::LeftY), s.axis(A::RightX), s.axis(A::RightY), + s.axis(A::LeftTrigger), s.axis(A::RightTrigger)); + } +}; diff --git a/components/gamepad_map/include/gamepad_state_hid_rp.hpp b/components/gamepad_map/include/gamepad_state_hid_rp.hpp new file mode 100644 index 0000000000..1433829698 --- /dev/null +++ b/components/gamepad_map/include/gamepad_state_hid_rp.hpp @@ -0,0 +1,52 @@ +#pragma once + +#include "gamepad_state.hpp" +#include "hid-rp-report-map.hpp" + +namespace espp { + +/** + * @brief A GamepadState from a decoded HID gamepad report + * (hid_rp::GamepadDecoder). + * + * @details Both name buttons by position and share the stick convention + * (-32767..32767, Y down), so this is a field-by-field copy. For a + * pass-through (a controller bridge, a remapper) decode with + * `GamepadDecoder::set_combine_controls(false)`, so the d-pad, L2/R2 + * and Home are only what the controller reports for them and the map + * decides the rest. + * @param r The decoded report. + * @return The state. + */ +inline GamepadState to_gamepad_state(const hid_rp::GamepadReport &r) { + using B = GamepadState::Button; + using A = GamepadState::Axis; + GamepadState s; + s.set(B::South, r.south); + s.set(B::East, r.east); + s.set(B::West, r.west); + s.set(B::North, r.north); + s.set(B::L1, r.l1); + s.set(B::R1, r.r1); + s.set(B::L2, r.l2); + s.set(B::R2, r.r2); + s.set(B::L3, r.l3); + s.set(B::R3, r.r3); + s.set(B::Select, r.select); + s.set(B::Start, r.start); + s.set(B::Home, r.home); + s.set(B::Capture, r.capture); + s.set(B::Up, r.up); + s.set(B::Down, r.down); + s.set(B::Left, r.left); + s.set(B::Right, r.right); + s.set(A::LeftX, r.lx); + s.set(A::LeftY, r.ly); + s.set(A::RightX, r.rx); + s.set(A::RightY, r.ry); + s.set(A::LeftTrigger, r.lt); + s.set(A::RightTrigger, r.rt); + return s; +} + +} // namespace espp diff --git a/components/gamepad_map/test/gamepad_map_host_test.cpp b/components/gamepad_map/test/gamepad_map_host_test.cpp new file mode 100644 index 0000000000..c5d4d2fbfc --- /dev/null +++ b/components/gamepad_map/test/gamepad_map_host_test.cpp @@ -0,0 +1,316 @@ +// Host-buildable unit tests for the gamepad_map component (GamepadState, +// GamepadMap, the hid-rp conversion and GamepadProfiles). Build & run from the +// repository root (third-party headers are -isystem so their own warnings do +// not fail the build): +// +// g++ -std=c++23 -Wall -Wextra -Werror -Wno-comment +// -I components/gamepad_map/include -I components/persistent_data/include +// -I components/serialization/include -I components/base_component/include +// -I components/logger/include -I components/format/include +// -isystem components/serialization/detail/alpaca/include +// -isystem components/format/detail/fmt/include +// -isystem components/hid-rp/include -isystem components/hid-rp/detail/hid-rp/hid-rp +// components/gamepad_map/test/gamepad_map_host_test.cpp components/logger/src/logger.cpp +// -o gamepad_map_host_test +// ./gamepad_map_host_test +// +// No ESP-IDF headers required. + +#include +#include +#include +#include +#include + +#include "gamepad_map.hpp" +#include "gamepad_profiles.hpp" +#include "gamepad_state_formatters.hpp" +#include "gamepad_state_hid_rp.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 espp::GamepadMap; +using espp::GamepadMapRule; +using espp::GamepadState; +using B = GamepadState::Button; +using A = GamepadState::Axis; + +static GamepadState state(std::initializer_list pressed, std::array axes = {}) { + GamepadState s; + for (auto b : pressed) + s.set(b, true); + s.axes = axes; + return s; +} + +static void test_state() { + GamepadState s; + s.set(B::East, true); + s.set(B::Paddle4, true); + CHECK(s.pressed(B::East) && s.pressed(B::Paddle4) && !s.pressed(B::South)); + s.set(B::East, false); + CHECK(!s.pressed(B::East)); + s.set(B::Count, true); // ignored + CHECK(s.buttons == (1u << static_cast(B::Paddle4))); + s.set(A::LeftX, -40000); + CHECK(s.axis(A::LeftX) == -32767); + s.set(A::RightTrigger, -5); + CHECK(s.axis(A::RightTrigger) == 0); // triggers do not go negative + CHECK(std::string(GamepadState::name(B::South)) == "south"); + CHECK(std::string(GamepadState::name(A::RightTrigger)) == "right_trigger"); + GamepadState f; + f.set(B::South, true); + f.set(B::Up, true); + f.set(A::LeftY, -32767); + f.set(A::RightTrigger, 32767); + CHECK(fmt::format("{}", f) == + "{buttons: [south, up], lx: 0, ly: -32767, rx: 0, ry: 0, lt: 0, rt: 32767}"); +} + +static void test_identity() { + GamepadMap map; + CHECK(map.is_identity() && map.valid()); + const auto in = state({B::South, B::Up, B::Home}, {100, -200, 300, -400, 500, 600}); + CHECK(map.apply(in) == in); +} + +static void test_swap_and_disable() { + GamepadMap map; + map.swap(B::South, B::East).add(GamepadMapRule::disable(B::Capture)); + CHECK(map.valid()); + auto out = map.apply(state({B::South, B::Capture, B::Start})); + CHECK(out.pressed(B::East) && !out.pressed(B::South)); + CHECK(!out.pressed(B::Capture)); + CHECK(out.pressed(B::Start)); // untouched controls pass through + out = map.apply(state({B::East})); + CHECK(out.pressed(B::South) && !out.pressed(B::East)); + out = map.apply(state({B::South, B::East})); + CHECK(out.pressed(B::South) && out.pressed(B::East)); +} + +static void test_keep_source_and_or() { + GamepadMap map; + // a paddle presses south too, keeping itself; L1 also presses south (moved) + map.add(GamepadMapRule::button(B::Paddle1, B::South, true)) + .add(GamepadMapRule::button(B::L1, B::South)); + auto out = map.apply(state({B::Paddle1})); + CHECK(out.pressed(B::Paddle1) && out.pressed(B::South)); + out = map.apply(state({B::L1})); + CHECK(out.pressed(B::South) && !out.pressed(B::L1)); + out = map.apply(state({B::South})); + CHECK(out.pressed(B::South)); // south is a target, not a source: still passes +} + +static void test_axis_to_button() { + GamepadMap map; + map.left_stick_to_dpad(16384, /*keep_stick=*/false).triggers_to_buttons(13107, true); + CHECK(map.valid()); + auto out = map.apply(state({}, {-20000, 20000, 0, 0, 13107, 13106})); + CHECK(out.pressed(B::Left) && !out.pressed(B::Right)); + CHECK(out.pressed(B::Down) && !out.pressed(B::Up)); + CHECK(out.axis(A::LeftX) == 0 && out.axis(A::LeftY) == 0); // the stick was moved + CHECK(out.pressed(B::L2) && !out.pressed(B::R2)); // >= threshold presses + CHECK(out.axis(A::LeftTrigger) == 13107); // kept + out = map.apply(state({}, {16383, -16384, 0, 0, 0, 0})); + CHECK(!out.pressed(B::Right) && out.pressed(B::Up)); +} + +static void test_button_to_axis() { + GamepadMap map; + map.dpad_to_left_stick(/*keep_dpad=*/false).buttons_to_triggers(true); + auto out = map.apply(state({B::Left, B::Down, B::R2}, {1000, 0, 0, 0, 0, 0})); + // the d-pad adds to the stick, which still passes through, then clamps + CHECK(out.axis(A::LeftX) == -32767 + 1000); + CHECK(out.axis(A::LeftY) == 32767); + CHECK(!out.pressed(B::Left) && !out.pressed(B::Down)); + CHECK(out.axis(A::RightTrigger) == 32767 && out.pressed(B::R2)); + out = map.apply(state({B::Left, B::Right})); + CHECK(out.axis(A::LeftX) == 0); // opposite directions cancel +} + +static void test_axis_to_axis() { + GamepadMap map; + map.invert(A::LeftY).swap_sticks(); + // invert(LeftY) moves LeftY to itself inverted; swap_sticks then moves LeftY + // to RightY as well: both contribute to their targets + auto out = map.apply(state({}, {100, 200, 300, 400, 0, 0})); + CHECK(out.axis(A::LeftX) == 300 && out.axis(A::RightX) == 100); + CHECK(out.axis(A::RightY) == 200); + CHECK(out.axis(A::LeftY) == 400 - 200); + + GamepadMap trig; + trig.add(GamepadMapRule::axis(A::RightY, A::RightTrigger, -100)); // stick up = trigger + out = trig.apply(state({}, {0, 0, 0, -32767, 0, 0})); + CHECK(out.axis(A::RightTrigger) == 32767 && out.axis(A::RightY) == 0); + out = trig.apply(state({}, {0, 0, 0, 32767, 0, 0})); + CHECK(out.axis(A::RightTrigger) == 0); // clamped at released + + GamepadMap gone; + gone.add(GamepadMapRule::disable(A::LeftTrigger)); + CHECK(gone.apply(state({}, {0, 0, 0, 0, 9000, 9000})).axis(A::LeftTrigger) == 0); +} + +static void test_deadzone() { + GamepadMap map; + map.left_deadzone_percent = 10; + auto out = map.apply(state({}, {3000, -1000, 3000, 0, 0, 0})); + CHECK(out.axis(A::LeftX) == 0 && out.axis(A::LeftY) == 0); + CHECK(out.axis(A::RightX) == 3000); // only the left stick + out = map.apply(state({}, {32767, 0, 0, 0, 0, 0})); + CHECK(out.axis(A::LeftX) == 32767); // full deflection still full + out = map.apply(state({}, {-20000, 0, 0, 0, 0, 0})); + CHECK(out.axis(A::LeftX) < -18000 && out.axis(A::LeftX) > -20000); // rescaled +} + +static void test_validation() { + std::string why; + GamepadMap map; + map.add({GamepadMapRule::Kind::ButtonToButton, 40, 0, 0, 0}); + CHECK(!map.valid(&why) && why.find("source") != std::string::npos); + // an invalid rule is skipped by apply() instead of reading out of range + CHECK(map.apply(state({B::South})).pressed(B::South)); + map.rules = {GamepadMapRule::axis_to_button(A::LeftX, 0, B::Left)}; + CHECK(!map.valid(&why)); + map.rules = {GamepadMapRule::axis(A::LeftX, A::RightX, 401)}; + CHECK(!map.valid(&why)); + map.rules = {{GamepadMapRule::Kind::ButtonToAxis, 0, 6, 0, 0}}; // axis 6 does not exist + CHECK(!map.valid(&why)); + map.rules = {{GamepadMapRule::Kind::ButtonToButton, 0, 1, 0x80, 0}}; + CHECK(!map.valid(&why)); // unknown flag + map.rules.assign(GamepadMap::MAX_RULES + 1, GamepadMapRule::button(B::South, B::East)); + CHECK(!map.valid(&why) && why == "too many rules"); + map.rules.clear(); + map.right_deadzone_percent = 91; + CHECK(!map.valid(&why)); +} + +static void test_aliasing() { + GamepadMap map; + map.swap(B::South, B::East); + auto s = state({B::South}); + map.apply(s, s); + CHECK(s.pressed(B::East) && !s.pressed(B::South)); +} + +// BSP-D8 (ShanWan BM-769) in its Android mode, as reported over BLE: the +// decoder + the conversion give a usable state, and a map applies on top. +static void test_hid_rp_bridge() { + const char *hex = + "050c0901a1018503751095011501269c0219012a9c028100c005010905a10185040901a1000930093109320935" + "150026ff00750895048102c00939150025073500463b016514750495018142750495018101050919012910150025" + "017501951081020502150026ff0009c409c5950275088102750895018101c0"; + std::vector desc; + for (const char *p = hex; p[0] && p[1]; p += 2) + desc.push_back(static_cast(std::stoi(std::string(p, 2), nullptr, 16))); + auto map = espp::hid_rp::ReportMap::parse(desc); + CHECK(map.has_value()); + if (!map) + return; + espp::hid_rp::GamepadDecoder decoder(std::move(*map)); + decoder.set_combine_controls(false); + // A pressed, hat up, right trigger full, left stick full right + const std::vector pad{0xff, 0x80, 0x80, 0x80, 0x00, 0x01, 0x00, 0xff, 0x00, 0x00}; + espp::hid_rp::GamepadReport r; + CHECK(decoder.update(4, pad, r)); + auto s = espp::to_gamepad_state(r); + CHECK(s.pressed(B::South) && s.pressed(B::Up)); + CHECK(s.axis(A::RightTrigger) > 32000 && s.axis(A::LeftX) > 32000); + CHECK(!s.pressed(B::R2) && !s.pressed(B::Right)); // nothing combined + + // a Nintendo-style host: A is east + GamepadMap nintendo; + nintendo.swap(B::South, B::East).triggers_to_buttons(); + s = nintendo.apply(s); + CHECK(s.pressed(B::East) && !s.pressed(B::South) && s.pressed(B::R2)); +} + +static void test_profiles() { + namespace fs = std::filesystem; + const fs::path dir = fs::temp_directory_path() / "gamepad_map_host_test"; + fs::remove_all(dir); + fs::create_directories(dir); + const fs::path file = dir / "profiles.bin"; + std::error_code ec; + + GamepadMap legacy; // e.g. migrated from an application's old settings + legacy.invert(A::LeftY); + { + espp::GamepadProfiles profiles({.file_path = file, .default_map = legacy}); + CHECK(profiles.default_map() == legacy); // no file yet: the configured default + CHECK(!fs::exists(file)); // ... and nothing written until a change + CHECK(profiles.map_for(0x1949, 0x0402) == legacy); + + GamepadMap bsp; + bsp.swap(B::South, B::East); + CHECK(profiles.set_profile({.vid = 0x1949, .pid = 0x0402, .name = "BSP-D8", .map = bsp}, ec)); + CHECK(!ec && fs::exists(file)); + CHECK(profiles.map_for(0x1949, 0x0402) == bsp); + CHECK(profiles.map_for(0x045e, 0x0b13) == legacy); + + GamepadMap named; + named.left_deadzone_percent = 12; + CHECK(profiles.set_profile({.vid = 0, .pid = 0, .name = "NoPnP", .map = named}, ec)); + CHECK(profiles.map_for(0, 0, "NoPnP") == named); + CHECK(profiles.map_for(0, 0, "Other") == legacy); + CHECK(!profiles.set_profile({.vid = 0, .pid = 0, .name = "", .map = named}, ec)); + CHECK(ec == std::errc::invalid_argument); + + GamepadMap bad; + bad.right_deadzone_percent = 99; + CHECK(!profiles.set_profile({.vid = 1, .pid = 2, .name = "x", .map = bad}, ec)); + CHECK(ec == std::errc::invalid_argument); + CHECK(!profiles.set_default_map(bad, ec)); + + // replacing keeps one entry per controller + bsp.rules.clear(); + CHECK(profiles.set_profile({.vid = 0x1949, .pid = 0x0402, .name = "BSP-D8", .map = bsp}, ec)); + CHECK(profiles.profiles().size() == 2); + } + { + // reloaded from the file + espp::GamepadProfiles profiles({.file_path = file, .default_map = GamepadMap{}}); + CHECK(profiles.default_map() == legacy); // the stored default, not the configured one + CHECK(profiles.profiles().size() == 2); + CHECK(profiles.map_for(0x1949, 0x0402).rules.empty()); + CHECK(profiles.erase_profile(0x1949, 0x0402, "", ec) && !ec); + CHECK(!profiles.erase_profile(0x1949, 0x0402, "", ec) && !ec); // already gone + CHECK(profiles.map_for(0x1949, 0x0402) == legacy); + } + { + espp::GamepadProfiles profiles({.file_path = file, .max_profiles = 1}); + CHECK(profiles.profiles().size() == 1); // NoPnP + CHECK(!profiles.set_profile({.vid = 5, .pid = 6, .name = "full", .map = {}}, ec)); + CHECK(ec == std::errc::no_buffer_space); + CHECK(profiles.reset(ec) && profiles.profiles().empty() && + profiles.default_map().is_identity()); + } + fs::remove_all(dir); +} + +int main() { + test_state(); + test_identity(); + test_swap_and_disable(); + test_keep_source_and_or(); + test_axis_to_button(); + test_button_to_axis(); + test_axis_to_axis(); + test_deadzone(); + test_validation(); + test_aliasing(); + test_hid_rp_bridge(); + test_profiles(); + if (failures == 0) { + std::printf("gamepad_map_host_test: all checks passed\n"); + return 0; + } + std::printf("gamepad_map_host_test: %d failure(s)\n", failures); + return 1; +} diff --git a/components/hid-rp/include/hid-rp-report-map.hpp b/components/hid-rp/include/hid-rp-report-map.hpp index 7f0910a72b..d7ef769ad6 100644 --- a/components/hid-rp/include/hid-rp-report-map.hpp +++ b/components/hid-rp/include/hid-rp-report-map.hpp @@ -302,11 +302,13 @@ class ReportMap { /// HID usage pages / IDs the decoders look at. namespace usage { constexpr uint16_t PAGE_GENERIC_DESKTOP = 0x01; +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 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; constexpr uint16_t GD_DPAD_UP = 0x90, GD_DPAD_DOWN = 0x91, GD_DPAD_RIGHT = 0x92, GD_DPAD_LEFT = 0x93; constexpr uint16_t CONSUMER_MENU = 0x0040, CONSUMER_RECORD = 0x00B2, CONSUMER_AC_EXIT = 0x0204, @@ -326,20 +328,55 @@ struct GamepadReport { int32_t hat{-1}; ///< raw hat value (-1 when absent) uint64_t buttons{0}; ///< raw: bit n = button usage n pressed (usages 1..63) uint16_t consumer[4]{0, 0, 0, 0}; ///< raw consumer-page usages active + int16_t lt{0}, rt{0}; ///< analog triggers, 0..32767 (0 on a pad without them) + bool capture{false}; ///< Share / Capture (consumer Record) }; /// Decodes gamepad reports. Face-button numbering differs between controller /// families, so the decoder carries a layout: -/// - Xbox-style: 1 = south, 2 = east, 3 = west, 4 = north (default) -/// - DirectInput / DualShock: 1 = west, 2 = south, 3 = east, 4 = north -/// (picked when the descriptor has a hat switch and >= 13 buttons) -/// Always: 5/6 = L1/R1, 7/8 = L2/R2, 9 = select, 10 = start, 11/12 = L3/R3. -/// Consumer-page controls (Menu, AC Back/Home, Record, AC Properties/Exit as -/// sent by Xbox-style pads) map to start / select / home. Per-device quirks -/// are keyed on VID/PID (apply_quirks()). +/// - Xbox-style: 1 = south, 2 = east, 3 = west, 4 = north, 5/6 = L1/R1, +/// 7/8 = L2/R2, 9 = select, 10 = start, 11/12 = L3/R3 (default) +/// - DirectInput / DualShock: 1 = west, 2 = south, 3 = east, 4 = north, the +/// rest as Xbox-style (picked when the descriptor has a hat switch and >= 13 +/// buttons) +/// - Android: 1 = south, 2 = east, 4 = west, 5 = north, 7/8 = L1/R1, +/// 9/10 = L2/R2, 11 = select, 12 = start, 13 = home, 14/15 = L3/R3: the +/// layout of BLE HID gamepads (Xbox Wireless over BLE, and the Android modes +/// of 8BitDo / ShanWan pads), picked when the descriptor reports its triggers +/// on the Simulation page (Brake / Accelerator), as those pads do +/// The sticks come from X/Y (left) and Z/Rz (right) when the pad has both Z and +/// Rz, its Rx/Ry then being the analog triggers (DualShock); otherwise the +/// right stick is Rx/Ry (Z without Rz: Z is its X). Simulation-page Brake / +/// Accelerator are the left / right analog triggers. Consumer-page controls +/// (Menu, AC Back/Home, Record, AC Properties/Exit as sent by Xbox-style pads) +/// map to start / select / home. Per-device quirks are keyed on VID/PID +/// (apply_quirks()). +/// +/// By default related controls are combined the way an emulator wants: the +/// left stick also drives the d-pad and the analog triggers also press L2/R2 +/// (both past 40% of their travel), and Share / Capture (consumer Record) also +/// presses Home. A pass-through (a controller bridge, a remapper) turns that off +/// with set_combine_controls(false) so every control reports only itself. +/// +/// A device may spread its state over several input reports (a BLE pad sending +/// its gamepad in report 4 and its consumer keys in report 3, say): update() +/// keeps the latest report of each ID and decodes them together, so a report +/// that carries only some controls does not reset the others. class GamepadDecoder { public: - enum class Layout { Xbox, DirectInput }; + enum class Layout { Xbox, DirectInput, Android }; + /// Human-readable name of a layout (for logs). + static constexpr const char *layout_name(Layout layout) { + switch (layout) { + case Layout::Xbox: + return "Xbox-style"; + case Layout::DirectInput: + return "DirectInput"; + case Layout::Android: + return "Android"; + } + return "?"; + } struct Quirks { Layout layout{Layout::Xbox}; bool dpad_updown_swapped{false}; ///< usages 0x90/0x91 carry down/up @@ -352,16 +389,35 @@ class GamepadDecoder { explicit GamepadDecoder(ReportMap map) : map_(std::move(map)) { size_t buttons = 0; - bool hat = false; + bool hat = false, z = false, rz = false, rx = false, ry = false, sim_triggers = false; for (const auto &f : map_.fields()) { if (f.usage_page == usage::PAGE_BUTTON && !f.array) buttons++; - if (f.usage_page == usage::PAGE_GENERIC_DESKTOP && f.usage == usage::GD_HAT) - hat = true; + if (f.usage_page == usage::PAGE_SIMULATION && + (f.usage == usage::SIM_ACCELERATOR || f.usage == usage::SIM_BRAKE)) + sim_triggers = true; + if (f.usage_page != usage::PAGE_GENERIC_DESKTOP || f.relative) + continue; + hat |= f.usage == usage::GD_HAT; + z |= f.usage == usage::GD_Z; + rz |= f.usage == usage::GD_RZ; + rx |= f.usage == usage::GD_RX; + ry |= f.usage == usage::GD_RY; } - if (hat && buttons >= 13) { + if (sim_triggers) { + quirks_.layout = Layout::Android; + } else if (hat && buttons >= 13) { quirks_.layout = Layout::DirectInput; } + // What each field is, worked out once: decode() then only switches on it. + const bool z_rz_stick = z && rz; + roles_.reserve(map_.fields().size()); + for (const auto &f : map_.fields()) { + roles_.push_back(role_of(f, z_rz_stick, rx, ry, sim_triggers)); + if (std::find(report_ids_.begin(), report_ids_.end(), f.report_id) == report_ids_.end()) + report_ids_.push_back(f.report_id); + } + latest_.resize(report_ids_.size()); } /// Whether a map looks like a gamepad (buttons plus a direction source). @@ -405,108 +461,342 @@ class GamepadDecoder { Quirks &quirks() { return quirks_; } const ReportMap &map() const { return map_; } + /// Whether related controls are combined: the left stick also drives the + /// d-pad, the analog triggers also press L2/R2 and Capture also presses Home + /// (default true; see the class description). + void set_combine_controls(bool enabled) { combine_controls_ = enabled; } + bool combine_controls() const { return combine_controls_; } + /// Decode a raw report (with its ID byte, if the device uses IDs). Returns /// false when the report carries none of the mapped fields. bool decode(std::span raw, GamepadReport &out) const { const auto [id, report] = map_.split(raw); + return decode(id, report, out); + } + + /// Decode one report given its ID separately, `payload` excluding any ID + /// byte (how BLE HID delivers reports: the ID comes from the characteristic's + /// Report Reference). The ID is ignored for a device without report IDs. + /// Returns false when the report carries none of the mapped fields. + bool decode(uint8_t report_id, std::span payload, GamepadReport &out) const { + const uint8_t id = map_.uses_report_ids() ? report_id : 0; + return decode_impl( + [id, payload](uint8_t field_id) { + return field_id == id ? payload : std::span{}; + }, + out); + } + + /// Remember `payload` as the latest report `report_id` (no ID byte, as for + /// decode(report_id, payload, out)), then decode the latest report of every + /// ID together into `out`. Returns false, leaving `out` alone, when no mapped + /// field lives in that report. Not thread-safe: feed one decoder from one + /// task. A report of a size seen before is stored without allocating. + bool update(uint8_t report_id, std::span payload, GamepadReport &out) { + const uint8_t id = map_.uses_report_ids() ? report_id : 0; + const auto it = std::find(report_ids_.begin(), report_ids_.end(), id); + if (it == report_ids_.end()) + return false; + latest_[static_cast(it - report_ids_.begin())].assign(payload.begin(), payload.end()); + return decode_impl( + [this](uint8_t field_id) { + const auto at = std::find(report_ids_.begin(), report_ids_.end(), field_id); + return at == report_ids_.end() + ? std::span{} + : std::span( + latest_[static_cast(at - report_ids_.begin())]); + }, + out); + } + + /// Forget the reports update() remembered (e.g. when the device disconnects). + void reset() { + for (auto &r : latest_) + r.clear(); + } + +private: + enum class Role : uint8_t { + None, + Button, + Hat, + DpadUp, + DpadDown, + DpadRight, + DpadLeft, + LeftX, + LeftY, + RightX, + RightY, + LeftTrigger, + RightTrigger, + Consumer, + }; + + static Role role_of(const ReportField &f, bool z_rz_stick, bool has_rx, bool has_ry, + bool sim_triggers) { + if (f.usage_page == usage::PAGE_BUTTON) + return f.array ? Role::None : Role::Button; + if (f.usage_page == usage::PAGE_CONSUMER) + return Role::Consumer; + const bool axis = !f.relative && !f.array && f.logical_max > f.logical_min; + if (f.usage_page == usage::PAGE_SIMULATION && axis) { + if (f.usage == usage::SIM_BRAKE) + return Role::LeftTrigger; + if (f.usage == usage::SIM_ACCELERATOR) + return Role::RightTrigger; + return Role::None; + } + if (f.usage_page != usage::PAGE_GENERIC_DESKTOP) + return Role::None; + switch (f.usage) { + case usage::GD_HAT: + return Role::Hat; + case usage::GD_DPAD_UP: + return Role::DpadUp; + case usage::GD_DPAD_DOWN: + return Role::DpadDown; + case usage::GD_DPAD_RIGHT: + return Role::DpadRight; + case usage::GD_DPAD_LEFT: + return Role::DpadLeft; + default: + break; + } + if (!axis) + return Role::None; + switch (f.usage) { + case usage::GD_X: + return Role::LeftX; + case usage::GD_Y: + return Role::LeftY; + case usage::GD_Z: + // Z is the right stick's X with Rz as its Y, else when there is no Rx + return z_rz_stick || !has_rx ? Role::RightX : Role::None; + case usage::GD_RZ: + return z_rz_stick || !has_ry ? Role::RightY : Role::None; + case usage::GD_RX: + // with Z/Rz as the right stick, Rx/Ry are the triggers (DualShock) unless + // the triggers are on the Simulation page + if (z_rz_stick) + return sim_triggers ? Role::None : Role::LeftTrigger; + return Role::RightX; + case usage::GD_RY: + if (z_rz_stick) + return sim_triggers ? Role::None : Role::RightTrigger; + return Role::RightY; + default: + return Role::None; + } + } + + // Which position a Button-page usage is, for the current layout. + enum class Pos : uint8_t { + None, + South, + East, + West, + North, + L1, + R1, + L2, + R2, + L3, + R3, + Select, + Start, + Home + }; + static Pos position_of(Layout layout, uint16_t button) { + if (layout == Layout::Android) { + switch (button) { + case 1: + return Pos::South; + case 2: + return Pos::East; + case 4: + return Pos::West; + case 5: + return Pos::North; + case 7: + return Pos::L1; + case 8: + return Pos::R1; + case 9: + return Pos::L2; + case 10: + return Pos::R2; + case 11: + return Pos::Select; + case 12: + return Pos::Start; + case 13: + return Pos::Home; + case 14: + return Pos::L3; + case 15: + return Pos::R3; + default: + return Pos::None; + } + } + const bool xbox = layout == Layout::Xbox; + switch (button) { + case 1: + return xbox ? Pos::South : Pos::West; + case 2: + return xbox ? Pos::East : Pos::South; + case 3: + return xbox ? Pos::West : Pos::East; + case 4: + return Pos::North; + case 5: + return Pos::L1; + case 6: + return Pos::R1; + case 7: + return Pos::L2; + case 8: + return Pos::R2; + case 9: + return Pos::Select; + case 10: + return Pos::Start; + case 11: + return Pos::L3; + case 12: + return Pos::R3; + default: + return Pos::None; + } + } + + static int16_t stick_value(const ReportField &f, int32_t v) { + // 64-bit throughout: a full 32-bit logical range overflows int32_t + const int64_t range = static_cast(f.logical_max) - f.logical_min; + const int64_t centered = 2 * (static_cast(v) - f.logical_min) - range; + return static_cast(std::clamp(centered * 32767 / range, -32767, 32767)); + } + static int16_t trigger_value(const ReportField &f, int32_t v) { + const int64_t range = static_cast(f.logical_max) - f.logical_min; + const int64_t from_min = static_cast(v) - f.logical_min; + return static_cast(std::clamp(from_min * 32767 / range, 0, 32767)); + } + + // `payload_for(report_id)` gives the payload holding that ID's fields (empty + // when there is none to decode). + template + bool decode_impl(PayloadFor payload_for, GamepadReport &out) const { GamepadReport r{}; bool any = false; - const bool xbox = quirks_.layout == Layout::Xbox; - const uint16_t south = xbox ? 1 : 2, east = xbox ? 2 : 3, west = xbox ? 3 : 1, north = 4; size_t n_consumer = 0; - for (const auto &f : map_.fields()) { - const auto v = ReportMap::extract(f, id, report); + const auto &fields = map_.fields(); + for (size_t i = 0; i < fields.size(); i++) { + const auto &f = fields[i]; + const Role role = roles_[i]; + if (role == Role::None) + continue; + const auto payload = payload_for(f.report_id); + if (payload.empty()) + continue; + const auto v = ReportMap::extract(f, f.report_id, payload); if (!v) continue; any = true; - if (f.usage_page == usage::PAGE_BUTTON && !f.array) { + switch (role) { + case Role::Button: { const bool pressed = *v != 0; if (pressed && f.usage >= 1 && f.usage < 64) r.buttons |= uint64_t{1} << f.usage; - if (f.usage == south) + switch (position_of(quirks_.layout, f.usage)) { + case Pos::South: r.south |= pressed; - else if (f.usage == east) + break; + case Pos::East: r.east |= pressed; - else if (f.usage == west) + break; + case Pos::West: r.west |= pressed; - else if (f.usage == north) + break; + case Pos::North: r.north |= pressed; - else if (f.usage == 5) + break; + case Pos::L1: r.l1 |= pressed; - else if (f.usage == 6) + break; + case Pos::R1: r.r1 |= pressed; - else if (f.usage == 7) + break; + case Pos::L2: r.l2 |= pressed; - else if (f.usage == 8) + break; + case Pos::R2: r.r2 |= pressed; - else if (f.usage == 9) - r.select |= pressed; - else if (f.usage == 10) - r.start |= pressed; - else if (f.usage == 11) + break; + case Pos::L3: r.l3 |= pressed; - else if (f.usage == 12) + break; + case Pos::R3: r.r3 |= pressed; - } else if (f.usage_page == usage::PAGE_GENERIC_DESKTOP) { - if (f.usage == usage::GD_HAT) { - r.hat = *v; - const int32_t dir = - *v - f.logical_min; // 0 = up, clockwise; 8 (or out of range) = centered - if (*v >= f.logical_min && *v <= f.logical_max && dir >= 0 && dir < 8) { - r.up |= dir == 7 || dir == 0 || dir == 1; - r.right |= dir >= 1 && dir <= 3; - r.down |= dir >= 3 && dir <= 5; - r.left |= dir >= 5; - } - } else if (f.usage >= usage::GD_DPAD_UP && f.usage <= usage::GD_DPAD_LEFT) { - const bool pressed = *v != 0; - switch (f.usage) { - case usage::GD_DPAD_UP: - (quirks_.dpad_updown_swapped ? r.down : r.up) |= pressed; - break; - case usage::GD_DPAD_DOWN: - (quirks_.dpad_updown_swapped ? r.up : r.down) |= pressed; - break; - case usage::GD_DPAD_RIGHT: - r.right |= pressed; - break; - case usage::GD_DPAD_LEFT: - r.left |= pressed; - break; - default: - break; - } - } else if (f.usage >= usage::GD_X && f.usage <= usage::GD_RZ && !f.relative && - f.logical_max > f.logical_min) { - // 64-bit throughout: a full 32-bit logical range overflows int32_t - const int64_t range = static_cast(f.logical_max) - f.logical_min; - const int64_t centered = 2 * (static_cast(*v) - f.logical_min) - range; - int16_t n = - static_cast(std::clamp(centered * 32767 / range, -32767, 32767)); - const bool vertical = - f.usage == usage::GD_Y || f.usage == usage::GD_RZ || f.usage == usage::GD_RY; - if (vertical && quirks_.y_up_positive) - n = static_cast(-n); - switch (f.usage) { - case usage::GD_X: - r.lx = n; - break; - case usage::GD_Y: - r.ly = n; - break; - case usage::GD_Z: - case usage::GD_RX: - r.rx = n; - break; - case usage::GD_RZ: - case usage::GD_RY: - r.ry = n; - break; - default: - break; - } + break; + case Pos::Select: + r.select |= pressed; + break; + case Pos::Start: + r.start |= pressed; + break; + case Pos::Home: + r.home |= pressed; + break; + case Pos::None: + break; + } + break; + } + case Role::Hat: { + r.hat = *v; + const int32_t dir = *v - f.logical_min; // 0 = up, clockwise; 8 (or out of range) = centered + if (*v >= f.logical_min && *v <= f.logical_max && dir >= 0 && dir < 8) { + r.up |= dir == 7 || dir == 0 || dir == 1; + r.right |= dir >= 1 && dir <= 3; + r.down |= dir >= 3 && dir <= 5; + r.left |= dir >= 5; } - } else if (f.usage_page == usage::PAGE_CONSUMER) { + break; + } + case Role::DpadUp: + (quirks_.dpad_updown_swapped ? r.down : r.up) |= *v != 0; + break; + case Role::DpadDown: + (quirks_.dpad_updown_swapped ? r.up : r.down) |= *v != 0; + break; + case Role::DpadRight: + r.right |= *v != 0; + break; + case Role::DpadLeft: + r.left |= *v != 0; + break; + case Role::LeftX: + r.lx = stick_value(f, *v); + break; + case Role::LeftY: + r.ly = + quirks_.y_up_positive ? static_cast(-stick_value(f, *v)) : stick_value(f, *v); + break; + case Role::RightX: + r.rx = stick_value(f, *v); + break; + case Role::RightY: + r.ry = + quirks_.y_up_positive ? static_cast(-stick_value(f, *v)) : stick_value(f, *v); + break; + case Role::LeftTrigger: + r.lt = trigger_value(f, *v); + break; + case Role::RightTrigger: + r.rt = trigger_value(f, *v); + break; + case Role::Consumer: { uint16_t u = 0; if (f.array) { if (*v == f.logical_min && (f.usage != 0 || f.logical_min != 0)) @@ -531,29 +821,44 @@ class GamepadDecoder { r.select = true; break; case usage::CONSUMER_AC_HOME: - case usage::CONSUMER_RECORD: r.home = true; break; + case usage::CONSUMER_RECORD: + r.capture = true; + break; default: break; } + break; + } + case Role::None: + break; } } - // the left stick as a d-pad with a 40% dead zone - constexpr int16_t DEAD = 32767 * 2 / 5; - r.left |= r.lx < -DEAD; - r.right |= r.lx > DEAD; - r.up |= r.ly < -DEAD; - r.down |= r.ly > DEAD; if (!any) return false; + if (combine_controls_) { + // the left stick as a d-pad and the analog triggers as L2 / R2, with a + // 40% dead zone; Capture as Home + r.home |= r.capture; + constexpr int16_t DEAD = 32767 * 2 / 5; + r.left |= r.lx < -DEAD; + r.right |= r.lx > DEAD; + r.up |= r.ly < -DEAD; + r.down |= r.ly > DEAD; + r.l2 |= r.lt > DEAD; + r.r2 |= r.rt > DEAD; + } out = r; return true; } -private: ReportMap map_; Quirks quirks_{}; + bool combine_controls_{true}; + std::vector roles_; ///< per field of map_ + std::vector report_ids_; ///< the IDs the fields live in + std::vector> latest_; ///< update(): latest payload per report_ids_ entry }; /// A keyboard report: which usages (HID keyboard page, 0..255 incl. the diff --git a/components/hid-rp/test/hid_rp_report_map_host_test.cpp b/components/hid-rp/test/hid_rp_report_map_host_test.cpp index 7cbcbbdf17..f1847684e8 100644 --- a/components/hid-rp/test/hid_rp_report_map_host_test.cpp +++ b/components/hid-rp/test/hid_rp_report_map_host_test.cpp @@ -1,25 +1,27 @@ // Host-buildable unit tests for the runtime report map / decoders // (hid-rp-report-map.hpp). Build & run: // -// c++ -std=c++23 -Wall -Wextra -Werror \ -// -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_report_map_host_test.cpp \ -// -o /tmp/hid_rp_report_map_host_test \ +// c++ -std=c++23 -Wall -Wextra -Werror +// -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_report_map_host_test.cpp +// -o /tmp/hid_rp_report_map_host_test // && /tmp/hid_rp_report_map_host_test // // No ESP-IDF headers required. #include #include +#include #include #include #include "hid-rp-gamepad.hpp" #include "hid-rp-report-map.hpp" #include "hid-rp-switch-pro.hpp" +#include "hid-rp-xbox.hpp" static int failures = 0; #define CHECK(cond) \ @@ -64,11 +66,12 @@ static void test_generated_gamepad() { // Build a report with the generator, decode it with the mapper. Gamepad report; report.reset(); - report.set_button(2, true); // Xbox-style: 2 = east - report.set_button(10, true); // start + report.set_button(2, true); // Android numbering: 2 = east + report.set_button(12, true); // start report.set_hat(espp::gamepad::Hat::UP); report.set_left_joystick(-1.0f, 0.0f); report.set_right_joystick(0.0f, 1.0f); + report.set_accelerator(1.0f); auto bytes = report.get_report(); std::vector raw(bytes.begin(), bytes.end()); if (map->uses_report_ids()) { @@ -77,10 +80,9 @@ static void test_generated_gamepad() { espp::hid_rp::GamepadDecoder decoder(*map); CHECK(decoder.looks_like_gamepad()); - // a hat plus 16 buttons reads as a DualShock-style pad to the heuristic; - // pin the layout the assertions below assume - CHECK(decoder.quirks().layout == espp::hid_rp::GamepadDecoder::Layout::DirectInput); - decoder.quirks().layout = espp::hid_rp::GamepadDecoder::Layout::Xbox; + // Simulation-page triggers (Brake / Accelerator) read as an Android-layout + // pad: the numbering espp's own BLE gamepads (and the Xbox over BLE) use + CHECK(decoder.quirks().layout == espp::hid_rp::GamepadDecoder::Layout::Android); espp::hid_rp::GamepadReport g; CHECK(decoder.decode(raw, g)); CHECK(g.east); @@ -90,6 +92,143 @@ static void test_generated_gamepad() { CHECK(g.lx < -30000); CHECK(g.left); // full left stick deflection also reads as d-pad left CHECK(g.ry > 30000); + CHECK(g.rt > 32000 && g.lt == 0); + CHECK(g.r2 && !g.l2); // ... and the full trigger as R2 + + // a pass-through decoder reports every control only as itself + decoder.set_combine_controls(false); + CHECK(decoder.decode(raw, g)); + CHECK(!g.left && g.lx < -30000); + CHECK(!g.r2 && g.rt > 32000); + CHECK(g.up); // the hat itself still is the d-pad +} + +// BSP-D8 (ShanWan BM-769) in its Android mode, descriptor as the device +// reports it over BLE: report 3 = consumer keys, report 4 = gamepad with 8-bit +// X/Y/Z/Rz sticks, a 4-bit hat (null state), 16 buttons, 8-bit Simulation-page +// Accelerator / Brake triggers. +static std::vector hex_bytes(const char *hex) { + std::vector out; + auto nibble = [](char c) { + return static_cast(c <= '9' ? c - '0' : (c | 0x20) - 'a' + 10); + }; + for (; hex[0] && hex[1]; hex += 2) + out.push_back(static_cast(nibble(hex[0]) << 4 | nibble(hex[1]))); + return out; +} + +static void test_ble_android_pad() { + const auto desc = hex_bytes( + "050c0901a1018503751095011501269c0219012a9c028100c005010905a10185040901a1000930093109320935" + "150026ff00750895048102c00939150025073500463b016514750495018142750495018101050919012910150025" + "017501951081020502150026ff0009c409c5950275088102750895018101c0"); + auto map = espp::hid_rp::ReportMap::parse(desc); + CHECK(map.has_value()); + if (!map) + return; + CHECK(map->uses_report_ids()); + CHECK(map->report_bytes(4) == 10); + espp::hid_rp::GamepadDecoder decoder(std::move(*map)); + CHECK(decoder.looks_like_gamepad()); + CHECK(decoder.quirks().layout == espp::hid_rp::GamepadDecoder::Layout::Android); + decoder.set_combine_controls(false); + + // BLE delivers the payload without the ID byte; the ID comes from the Report + // Reference. Neutral: sticks at 0x80, hat null (15), nothing pressed. + std::vector pad{0x80, 0x80, 0x80, 0x80, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00}; + espp::hid_rp::GamepadReport g; + CHECK(decoder.decode(4, pad, g)); + CHECK(std::abs(g.lx) < 300 && std::abs(g.ly) < 300); + CHECK(std::abs(g.rx) < 300 && std::abs(g.ry) < 300); // the Xbox parse pegged these + CHECK(!g.up && !g.down && !g.left && !g.right); + CHECK(g.buttons == 0 && g.lt == 0 && g.rt == 0); + + // A (button 1), Y (button 5), R1 (button 8), Start (button 12), hat right, + // right stick full left / down, half left trigger, full right trigger + pad = {0x80, 0x80, 0x00, 0xff, 0x02, 0x91, 0x08, 0xff, 0x80, 0x00}; + CHECK(decoder.decode(4, pad, g)); + CHECK(g.south && g.north && !g.east && !g.west); + CHECK(g.r1 && !g.l1); + CHECK(g.start && !g.select); + CHECK(g.right && !g.up && !g.down && !g.left); + CHECK(g.rx < -32000 && g.ry > 32000); + CHECK(g.rt > 32000); // Accelerator (first) = right trigger + CHECK(g.lt > 16000 && g.lt < 16600); // Brake = left trigger, half way + + // the consumer report (3) alone carries no pad state: decode() of it alone + // reports only consumer keys, update() keeps the pad report it last saw + std::vector consumer{0x23, 0x02}; // AC Home + CHECK(decoder.update(4, pad, g)); + CHECK(g.south && g.rt > 32000); + CHECK(decoder.update(3, consumer, g)); + CHECK(g.home); + CHECK(g.south && g.rt > 32000); // still there + CHECK(!decoder.update(9, pad, g)); // not a report of this device + decoder.reset(); + CHECK(decoder.update(3, consumer, g)); + CHECK(g.home && !g.south); +} + +// espp's Xbox Wireless (BLE) report: X/Y/Z/Rz 16-bit sticks, Simulation +// triggers, Android button numbering (A = 1, B = 2, X = 4, Y = 5, ...). +static void test_xbox_ble() { + auto rdf = espp::xbox_descriptor(); + std::vector desc(rdf.begin(), rdf.end()); + auto map = espp::hid_rp::ReportMap::parse(desc); + CHECK(map.has_value()); + if (!map) + return; + espp::hid_rp::GamepadDecoder decoder(std::move(*map)); + CHECK(decoder.quirks().layout == espp::hid_rp::GamepadDecoder::Layout::Android); + decoder.set_combine_controls(false); + espp::XboxGamepadInputReport<> report; + report.reset(); + report.set_button_x(true); + report.set_button_l3(true); + report.set_button_menu(true); + report.set_left_joystick(0.0f, -1.0f); + report.set_brake(1.0f); + auto bytes = report.get_report(); + std::vector payload(bytes.begin(), bytes.end()); + espp::hid_rp::GamepadReport g; + CHECK(decoder.decode(espp::XboxGamepadInputReport<>::ID, payload, g)); + CHECK(g.west && !g.south && !g.north && !g.east); + CHECK(g.l3 && !g.r3); + CHECK(g.start); + CHECK(g.ly < -30000 && std::abs(g.lx) < 300); + CHECK(g.lt > 32000 && g.rt == 0); +} + +// A DualShock-style descriptor: X/Y/Z/Rz sticks, then Rx/Ry as the analog +// triggers (the pre-Android decoder read Rx over the right stick's X). +static void test_dualshock_axes() { + // usage page GD, gamepad, app collection, report id 1, X Y Z Rz 8-bit, + // hat, 14 buttons, padding, Rx Ry 8-bit + const std::vector desc{ + 0x05, 0x01, 0x09, 0x05, 0xa1, 0x01, 0x85, 0x01, // GD, gamepad, app, id 1 + 0x09, 0x30, 0x09, 0x31, 0x09, 0x32, 0x09, 0x35, // X Y Z Rz + 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x04, 0x81, 0x02, // 4 x u8 + 0x09, 0x39, 0x15, 0x00, 0x25, 0x07, 0x75, 0x04, 0x95, 0x01, 0x81, 0x42, // hat + 0x05, 0x09, 0x19, 0x01, 0x29, 0x0e, 0x15, 0x00, 0x25, 0x01, // buttons 1..14 + 0x75, 0x01, 0x95, 0x0e, 0x81, 0x02, // + 0x75, 0x06, 0x95, 0x01, 0x81, 0x01, // pad to a byte + 0x05, 0x01, 0x09, 0x33, 0x09, 0x34, 0x15, 0x00, 0x26, 0xff, 0x00, // Rx Ry + 0x75, 0x08, 0x95, 0x02, 0x81, 0x02, 0xc0}; + auto map = espp::hid_rp::ReportMap::parse(desc); + CHECK(map.has_value()); + if (!map) + return; + espp::hid_rp::GamepadDecoder decoder(std::move(*map)); + CHECK(decoder.quirks().layout == espp::hid_rp::GamepadDecoder::Layout::DirectInput); + // right stick full right, left trigger full, right trigger released + // byte 4 = hat (null, 8) in the low nibble + buttons 1..4 above it (2 = 0x20) + const std::vector raw{0x01, 0x80, 0x80, 0xff, 0x80, 0x28, 0x00, 0x00, 0xff, 0x00}; + espp::hid_rp::GamepadReport g; + CHECK(decoder.decode(raw, g)); + CHECK(g.rx > 32000); // Z, not overwritten by Rx + CHECK(std::abs(g.ry) < 300); + CHECK(g.lt > 32000 && g.rt == 0); + CHECK(g.south); // DirectInput: button 2 = south } // The classic boot-protocol keyboard descriptor (8-byte reports: modifier @@ -399,6 +538,9 @@ int main() { test_keyboard_array_logical_min(); test_edge_items(); test_generated_gamepad(); + test_ble_android_pad(); + test_xbox_ble(); + test_dualshock_axes(); test_keyboard(); test_mouse(); test_report_ids_consumer_dpad(); diff --git a/components/usb_host/tab5_example/main/usb_host_tab5_example.cpp b/components/usb_host/tab5_example/main/usb_host_tab5_example.cpp index 6f2b3e3972..b7d424f710 100644 --- a/components/usb_host/tab5_example/main/usb_host_tab5_example.cpp +++ b/components/usb_host/tab5_example/main/usb_host_tab5_example.cpp @@ -163,9 +163,7 @@ extern "C" void app_main(void) { } else if (GamepadDecoder::looks_like_gamepad(*map)) { GamepadDecoder pad(std::move(*map)); pad.apply_quirks(info.vid, info.pid); // per-device layout fixes, by VID:PID - logger.info("gamepad layout: {}", pad.quirks().layout == GamepadDecoder::Layout::Xbox - ? "Xbox-style" - : "DirectInput"); + logger.info("gamepad layout: {}", GamepadDecoder::layout_name(pad.quirks().layout)); iface.decoder = std::move(pad); iface.card.kind = Gui::Kind::Gamepad; } diff --git a/doc/Doxyfile b/doc/Doxyfile index fdc37ad5b4..2ee7bfe390 100755 --- a/doc/Doxyfile +++ b/doc/Doxyfile @@ -131,6 +131,7 @@ EXAMPLE_PATH = \ $(PROJECT_PATH)/components/filters/example/main/filters_example.cpp \ $(PROJECT_PATH)/components/ftp/example/main/ftp_example.cpp \ $(PROJECT_PATH)/components/ft5x06/example/main/ft5x06_example.cpp \ + $(PROJECT_PATH)/components/gamepad_map/example/main/gamepad_map_example.cpp \ $(PROJECT_PATH)/components/gfps_service/example/main/gfps_service_example.cpp \ $(PROJECT_PATH)/components/gps/example/main/gps_example.cpp \ $(PROJECT_PATH)/components/gt911/example/main/gt911_example.cpp \ @@ -353,6 +354,10 @@ INPUT = \ $(PROJECT_PATH)/components/ftp/include/ftp_server.hpp \ $(PROJECT_PATH)/components/ftp/include/ftp_client_session.hpp \ $(PROJECT_PATH)/components/ft5x06/include/ft5x06.hpp \ + $(PROJECT_PATH)/components/gamepad_map/include/gamepad_map.hpp \ + $(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/gfps_service/include/gfps.hpp \ $(PROJECT_PATH)/components/gfps_service/include/gfps_characteristic_callbacks.hpp \ $(PROJECT_PATH)/components/gfps_service/include/gfps_service.hpp \ diff --git a/doc/en/input/gamepad_map.rst b/doc/en/input/gamepad_map.rst new file mode 100644 index 0000000000..02e509473d --- /dev/null +++ b/doc/en/input/gamepad_map.rst @@ -0,0 +1,34 @@ +Gamepad Map APIs +**************** + +Gamepad Map +----------- + +The `gamepad_map` component remaps a gamepad's buttons and axes: button to +button, analog to digital (a stick direction or trigger past a threshold), +digital to analog (a button driving an axis) and analog to analog (swap, +invert, scale), plus radial stick dead zones. `GamepadState` names buttons by +position (south / east / west / north) so a map means the same thing for Xbox, +Nintendo and PlayStation controllers. `GamepadProfiles` keeps a default map and +one map per controller type (vendor / product ID) in a file, stored with +`PersistentData`. `to_gamepad_state()` converts the runtime HID decoder's +`hid_rp::GamepadReport`. + +Code examples for the Gamepad Map API are provided in the `gamepad_map` example +folder. + +.. ------------------------------- Example ------------------------------------- + +.. toctree:: + + gamepad_map_example + +.. ---------------------------- API Reference ---------------------------------- + +API Reference +------------- + +.. include-build-file:: inc/gamepad_state.inc +.. include-build-file:: inc/gamepad_map.inc +.. include-build-file:: inc/gamepad_profiles.inc +.. include-build-file:: inc/gamepad_state_hid_rp.inc diff --git a/doc/en/input/gamepad_map_example.md b/doc/en/input/gamepad_map_example.md new file mode 100644 index 0000000000..008f2ff5fa --- /dev/null +++ b/doc/en/input/gamepad_map_example.md @@ -0,0 +1,2 @@ +```{include} ../../../components/gamepad_map/example/README.md +``` diff --git a/doc/en/input/index.rst b/doc/en/input/index.rst index 6f9a5456ed..93e93dd323 100644 --- a/doc/en/input/index.rst +++ b/doc/en/input/index.rst @@ -12,6 +12,7 @@ Input devices button joystick controller + gamepad_map qwiicnes Touch & input drivers diff --git a/lib/espp.cmake b/lib/espp.cmake index 66547e79cb..bbbd7b2050 100644 --- a/lib/espp.cmake +++ b/lib/espp.cmake @@ -295,6 +295,7 @@ set(ESPP_INCLUDES ${ESPP_COMPONENTS}/filters/include ${ESPP_COMPONENTS}/ftp/include ${ESPP_COMPONENTS}/format/include + ${ESPP_COMPONENTS}/gamepad_map/include ${ESPP_COMPONENTS}/hid-rp/include ${ESPP_COMPONENTS}/joystick/include ${ESPP_COMPONENTS}/logger/include diff --git a/lib/include/espp.hpp b/lib/include/espp.hpp index 81e53b3efc..3e57c34fce 100644 --- a/lib/include/espp.hpp +++ b/lib/include/espp.hpp @@ -28,6 +28,10 @@ extern "C" { #include "file_system.hpp" #include "ftp_client_session.hpp" #include "ftp_server.hpp" +#include "gamepad_map.hpp" +#include "gamepad_profiles.hpp" +#include "gamepad_state.hpp" +#include "gamepad_state_formatters.hpp" #include "gaussian.hpp" // TODO: these are not working // #include "hid-rp.hpp" From b949d72e23967567ead295e8176a2343ed05b01c Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Sat, 21 Nov 2026 15:39:29 -0700 Subject: [PATCH 2/5] fix(gamepad_map): cppcheck findings (pass the test helper's axes by reference, parameters no longer shadow pressed() / profile()) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU --- .../gamepad_map/include/gamepad_profiles.hpp | 14 +++++++------- components/gamepad_map/include/gamepad_state.hpp | 4 ++-- .../gamepad_map/test/gamepad_map_host_test.cpp | 3 ++- 3 files changed, 11 insertions(+), 10 deletions(-) diff --git a/components/gamepad_map/include/gamepad_profiles.hpp b/components/gamepad_map/include/gamepad_profiles.hpp index aca9a07070..d487b77a1c 100644 --- a/components/gamepad_map/include/gamepad_profiles.hpp +++ b/components/gamepad_map/include/gamepad_profiles.hpp @@ -156,17 +156,17 @@ class GamepadProfiles : public BaseComponent { /** * @brief Add a profile, or replace the one for the same controller, and save. - * @param profile The profile (its map must be valid(); with VID and PID 0 it + * @param entry The profile (its map must be valid(); with VID and PID 0 it * needs a name). * @param ec Set on failure: std::errc::invalid_argument for an invalid * profile, std::errc::no_buffer_space when the store is full, else * the save error. * @return true if saved. */ - bool set_profile(const GamepadProfile &profile, std::error_code &ec) { - if (!check(profile.map, ec)) + bool set_profile(const GamepadProfile &entry, std::error_code &ec) { + if (!check(entry.map, ec)) return false; - if (profile.vid == 0 && profile.pid == 0 && profile.name.empty()) { + if (entry.vid == 0 && entry.pid == 0 && entry.name.empty()) { ec = std::make_error_code(std::errc::invalid_argument); return false; } @@ -174,15 +174,15 @@ class GamepadProfiles : public BaseComponent { Data next = data_; auto it = std::find_if(next.profiles.begin(), next.profiles.end(), [&](const GamepadProfile &p) { - return p.matches(profile.vid, profile.pid, profile.name); + return p.matches(entry.vid, entry.pid, entry.name); }); if (it != next.profiles.end()) { - *it = profile; + *it = entry; } else if (next.profiles.size() >= max_profiles_) { ec = std::make_error_code(std::errc::no_buffer_space); return false; } else { - next.profiles.push_back(profile); + next.profiles.push_back(entry); } return commit(std::move(next), ec); } diff --git a/components/gamepad_map/include/gamepad_state.hpp b/components/gamepad_map/include/gamepad_state.hpp index 52389d7816..2f42268e8d 100644 --- a/components/gamepad_map/include/gamepad_state.hpp +++ b/components/gamepad_map/include/gamepad_state.hpp @@ -75,11 +75,11 @@ struct GamepadState { return b < Button::Count && (buttons >> static_cast(b)) & 1u; } /// @brief Press or release a button. - constexpr void set(Button b, bool pressed) { + constexpr void set(Button b, bool down) { if (b >= Button::Count) return; const uint32_t bit = 1u << static_cast(b); - buttons = pressed ? (buttons | bit) : (buttons & ~bit); + buttons = down ? (buttons | bit) : (buttons & ~bit); } /// @brief The value of an axis (0 for an invalid axis). constexpr int16_t axis(Axis a) const { diff --git a/components/gamepad_map/test/gamepad_map_host_test.cpp b/components/gamepad_map/test/gamepad_map_host_test.cpp index c5d4d2fbfc..f43fd22cfb 100644 --- a/components/gamepad_map/test/gamepad_map_host_test.cpp +++ b/components/gamepad_map/test/gamepad_map_host_test.cpp @@ -42,7 +42,8 @@ using espp::GamepadState; using B = GamepadState::Button; using A = GamepadState::Axis; -static GamepadState state(std::initializer_list pressed, std::array axes = {}) { +static GamepadState state(std::initializer_list pressed, + const std::array &axes = {}) { GamepadState s; for (auto b : pressed) s.set(b, true); From 99c90cbd559c69cccf36cba711ff83507d306933 Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Sat, 21 Nov 2026 16:03:08 -0700 Subject: [PATCH 3/5] feat(gamepad_map): GamepadMapService + Gamepad Map Console web app - GamepadMapService (dispatcher module 11, protocol espp.gamepad_map v1, wire spec + host-buildable codec in include/detail/gamepad_map_protocol.hpp): GET_INFO (limits, connected controller, whether it has a profile), GET_MAP / SET_MAP (default map or a per-controller profile; validated, saved through GamepadProfiles), ERASE_PROFILE, LIST_PROFILES, RESET_ALL, and SET_STREAM: INPUT events (raw + mapped state) every period, ended by the device when the host stops renewing the lease, plus an unsolicited INFO when the controller changes while streaming. MAP says whether the requested profile exists. Host decoders ignore appended fields of device -> host messages, so the protocol can grow. - Application side: set_controller() / clear_controller() (returns the map to apply), publish_input() (an atomic load while nobody streams), Config::on_active_map_changed when a host changes the connected controller's map. - GamepadMapRule::valid() also rejects a negative threshold on a trigger and KEEP_SOURCE with no target (rules that could never do anything). - web/gamepad_map_console.html: live raw / mapped input (button grid, stick pads, axis bars), map picker (default / connected controller / stored profiles / new), rule editor with per-kind parameters, learn by pressing, presets, dead zones, local validation, save / revert / erase / reset with inline confirms; shared discovery / connection / navigation / hand-back blocks byte-identical to the other consoles. - webapp_example (esp32s3 / esp32p4, USB vendor + CDC, the standard system / monitor / OTA / core dump services, profiles on LittleFS, a demo controller with the BOOT button as South). - Tests: gamepad_map_protocol_host_test.cpp (golden encodings), the web codec test (node), both in gamepad_map_tests.yml; the console is in the dispatcher web tests' console list; apps_registry_test's undeclared- protocol check now matches protocol ids with '_'. - Docs: module 11 in the dispatcher module tables (and the missing module 10 row in the README), web_apps.rst, gamepad_map.rst + example page, Doxyfile; CI build entry for the example. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU --- .github/workflows/build.yml | 3 + .github/workflows/gamepad_map_tests.yml | 17 + components/dispatcher/README.md | 2 + .../dispatcher/web/test/apps_registry_test.js | 3 +- .../web/test/resolve_module_id_test.js | 1 + components/gamepad_map/CMakeLists.txt | 2 +- components/gamepad_map/README.md | 43 +- components/gamepad_map/idf_component.yml | 4 + .../include/detail/gamepad_map_protocol.hpp | 533 +++++ .../gamepad_map/include/gamepad_map.hpp | 5 + .../include/gamepad_map_service.hpp | 548 +++++ .../test/gamepad_map_host_test.cpp | 7 + .../test/gamepad_map_protocol_host_test.cpp | 190 ++ .../gamepad_map/web/gamepad_map_console.html | 2009 +++++++++++++++++ .../web/test/gamepad_map_codec_test.js | 322 +++ .../gamepad_map/webapp_example/CMakeLists.txt | 64 + .../gamepad_map/webapp_example/README.md | 68 + .../webapp_example/main/CMakeLists.txt | 4 + .../webapp_example/main/Kconfig.projbuild | 25 + .../main/gamepad_map_webapp_example.cpp | 269 +++ .../gamepad_map/webapp_example/partitions.csv | 11 + .../webapp_example/sdkconfig.defaults | 57 + doc/Doxyfile | 2 + doc/en/dispatcher/custom_modules.rst | 1 + doc/en/input/gamepad_map.rst | 12 +- doc/en/input/gamepad_map_webapp_example.md | 2 + doc/en/web_apps.rst | 5 + 27 files changed, 4200 insertions(+), 9 deletions(-) create mode 100644 components/gamepad_map/include/detail/gamepad_map_protocol.hpp create mode 100644 components/gamepad_map/include/gamepad_map_service.hpp create mode 100644 components/gamepad_map/test/gamepad_map_protocol_host_test.cpp create mode 100644 components/gamepad_map/web/gamepad_map_console.html create mode 100644 components/gamepad_map/web/test/gamepad_map_codec_test.js create mode 100644 components/gamepad_map/webapp_example/CMakeLists.txt create mode 100644 components/gamepad_map/webapp_example/README.md create mode 100644 components/gamepad_map/webapp_example/main/CMakeLists.txt create mode 100644 components/gamepad_map/webapp_example/main/Kconfig.projbuild create mode 100644 components/gamepad_map/webapp_example/main/gamepad_map_webapp_example.cpp create mode 100644 components/gamepad_map/webapp_example/partitions.csv create mode 100644 components/gamepad_map/webapp_example/sdkconfig.defaults create mode 100644 doc/en/input/gamepad_map_webapp_example.md diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index fce12b8f1b..a54a1b6819 100755 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -183,6 +183,9 @@ jobs: target: esp32s3 - path: 'components/gamepad_map/example' target: esp32s3 + - path: 'components/gamepad_map/webapp_example' + target: esp32s3 + command: 'IDF_COMPONENT_MANAGER=0 idf.py build' - path: 'components/gfps_service/example' target: esp32s3 - path: 'components/gps/example' diff --git a/.github/workflows/gamepad_map_tests.yml b/.github/workflows/gamepad_map_tests.yml index b51c02f1a9..c8f0bb63e5 100644 --- a/.github/workflows/gamepad_map_tests.yml +++ b/.github/workflows/gamepad_map_tests.yml @@ -6,6 +6,10 @@ name: Gamepad map host test # file round trip) # - components/hid-rp/test/hid_rp_report_map_host_test.cpp (the runtime # report map + Gamepad / Keyboard / Mouse decoders the map is fed from) +# - components/gamepad_map/test/gamepad_map_protocol_host_test.cpp (the +# GamepadMapService wire protocol codec) +# - components/gamepad_map/web/test/gamepad_map_codec_test.js (the web +# console's copy of that codec, with node) # Runs whenever either component, or what they store / log with, changes. # Minimal token scope: build + run tests, never writes. @@ -19,6 +23,7 @@ on: - "components/hid-rp/**" - "components/persistent_data/**" - "components/serialization/**" + - "components/stream_frame/**" - ".github/workflows/gamepad_map_tests.yml" push: branches: @@ -28,6 +33,7 @@ on: - "components/hid-rp/**" - "components/persistent_data/**" - "components/serialization/**" + - "components/stream_frame/**" - ".github/workflows/gamepad_map_tests.yml" workflow_dispatch: @@ -67,3 +73,14 @@ jobs: components/gamepad_map/test/gamepad_map_host_test.cpp components/logger/src/logger.cpp \ -o gamepad_map_host_test ./gamepad_map_host_test + - name: Build and run gamepad_map_protocol_host_test + run: | + g++ -std=c++23 -Wall -Wextra -Werror \ + -I components/gamepad_map/include -I components/stream_frame/include \ + components/gamepad_map/test/gamepad_map_protocol_host_test.cpp \ + -o gamepad_map_protocol_host_test + ./gamepad_map_protocol_host_test + - name: Run the web console codec test + run: | + node --version + node components/gamepad_map/web/test/gamepad_map_codec_test.js diff --git a/components/dispatcher/README.md b/components/dispatcher/README.md index 8463f2d455..e1ea2e88c7 100644 --- a/components/dispatcher/README.md +++ b/components/dispatcher/README.md @@ -32,6 +32,8 @@ protocols and examples use these ids by default: | 7 | System info / reboot (`espp::SystemService`) | `espp.system` v1 | | 8 | Heap / task monitor (`espp::MonitorService`) | `espp.monitor` v1 | | 9 | Windowed desktop (`espp::DesktopService`) | `espp.desktop` v2 | +| 10 | VL53L5CX ToF console (`espp::Vl53l5cxService`) | `espp.vl53l5cx` v1 | +| 11 | Gamepad map (`espp::GamepadMapService`) | `espp.gamepad_map` v1 | | 0xF0–0xFE | reserved (meta) | — | | 0xFF | capability discovery | — | diff --git a/components/dispatcher/web/test/apps_registry_test.js b/components/dispatcher/web/test/apps_registry_test.js index bbcd264485..0ceed597c7 100644 --- a/components/dispatcher/web/test/apps_registry_test.js +++ b/components/dispatcher/web/test/apps_registry_test.js @@ -61,7 +61,8 @@ for (const p of pages) { // constants are declared as `PROTOCOL = "id", PROTOCOL_VERSION = n` // with the same (possibly empty) prefix, e.g. OTA_PROTOCOL / OTA_PROTOCOL_VERSION // or the bare PROTOCOL / PROTOCOL_VERSION pair - for (const m of src.matchAll(/\b[A-Z0-9_]*PROTOCOL\s*=\s*"(espp\.[a-z0-9.-]+)"/g)) idsInScript.add(m[1]); + // (ids may contain `_`, e.g. espp.gamepad_map, as the generator's PROTOCOL_RE allows) + for (const m of src.matchAll(/\b[A-Z0-9_]*PROTOCOL\s*=\s*"(espp\.[a-z0-9._-]+)"/g)) idsInScript.add(m[1]); for (const id of idsInScript) assert.ok(protocols.some((p) => p.id === id), rel + ": script defines protocol " + id + " not declared in espp-protocols"); // and the version it implements: every declared protocol must have its pair for (const pr of protocols) { diff --git a/components/dispatcher/web/test/resolve_module_id_test.js b/components/dispatcher/web/test/resolve_module_id_test.js index 83b0b18185..a40de36e55 100644 --- a/components/dispatcher/web/test/resolve_module_id_test.js +++ b/components/dispatcher/web/test/resolve_module_id_test.js @@ -27,6 +27,7 @@ const consoles = [ "components/system/web/system_console.html", "components/desktop/web/desktop.html", "components/vl53l/web/vl53l5cx_console.html", + "components/gamepad_map/web/gamepad_map_console.html", ]; const hub = "components/dispatcher/web/dispatcher_hub.html"; diff --git a/components/gamepad_map/CMakeLists.txt b/components/gamepad_map/CMakeLists.txt index eddea4ac62..d54a52368b 100644 --- a/components/gamepad_map/CMakeLists.txt +++ b/components/gamepad_map/CMakeLists.txt @@ -1,4 +1,4 @@ idf_component_register( INCLUDE_DIRS "include" - REQUIRES base_component format hid-rp persistent_data + REQUIRES base_component dispatcher format hid-rp persistent_data stream_frame task ) diff --git a/components/gamepad_map/README.md b/components/gamepad_map/README.md index d3f7453d48..341bd91507 100644 --- a/components/gamepad_map/README.md +++ b/components/gamepad_map/README.md @@ -18,8 +18,9 @@ whatever comes next (an emulated USB controller, an emulator's input). - [Rules](#rules) - [Profiles](#profiles) - [From a HID gamepad](#from-a-hid-gamepad) + - [Web console](#web-console) - [Host test](#host-test) - - [Example](#example) + - [Examples](#examples) @@ -32,6 +33,7 @@ whatever comes next (an emulated USB controller, an emulator's input). | `espp::GamepadMap` | Stick dead zones plus a list of rules; `apply()` maps one state to another | | `espp::GamepadProfiles` | A default map plus one map per controller type, saved in a file | | `espp::to_gamepad_state()` | A state from a `hid_rp::GamepadReport` (`gamepad_state_hid_rp.hpp`) | +| `espp::GamepadMapService` | Serves a `GamepadProfiles` store to the web console (dispatcher module 11) | Everything except `GamepadProfiles` is header-only plain data with no allocation in `apply()`, so it can run on every report. @@ -120,15 +122,46 @@ if (decoder.update(report_id, payload, report)) // BLE: the ID comes out of ba send(map.apply(espp::to_gamepad_state(report))); ``` +## Web console + +`espp::GamepadMapService` serves a `GamepadProfiles` store over any framed byte +stream (WebUSB vendor, Web Serial CDC...) through an `espp::Dispatcher`. Its +protocol is `espp.gamepad_map` v1 on module 11 by default +(`include/detail/gamepad_map_protocol.hpp` is the wire spec). The hosted +[Gamepad Map Console](https://esp-cpp.github.io/espp/apps/gamepad_map_console.html) +uses it to edit the maps and to show the controller's input before and after +mapping, live. The application tells the service about the controller and feeds +it the input: + +```cpp +espp::GamepadMapService service({.send = send_to_host, + .profiles = &profiles, + .on_active_map_changed = [&](const espp::GamepadMap &m) { + std::lock_guard lock(map_mutex); + active_map = m; // the console changed this controller's map + }}); +dispatcher.register_module(service); + +active_map = service.set_controller(vid, pid, name); // on connect; clear_controller() on disconnect +// for every report: +service.publish_input(raw, mapped); // an atomic load while nobody is streaming +``` + +The INPUT stream ends by itself when the host stops renewing it +(`Config::stream_lease`), so a closed browser tab does not leave it running. + ## Host test `test/gamepad_map_host_test.cpp` covers the rule semantics, validation, the hid-rp conversion (with a real BLE gamepad's descriptor) and the profile store's -file round trip. The build command is at the top of the file, and CI runs it in +file round trip. `test/gamepad_map_protocol_host_test.cpp` checks the wire +protocol against golden encodings. The build command is at the top of the file, and CI runs it in `.github/workflows/gamepad_map_tests.yml` together with the hid-rp report-map test. -## Example +## Examples -The [example](./example) decodes a BLE gamepad report, remaps it, and stores -per-controller profiles on a LittleFS partition. +- [example](./example) decodes a BLE gamepad report, remaps it, and stores + per-controller profiles on a LittleFS partition. +- [webapp_example](./webapp_example) serves the profiles over USB (WebUSB / + Web Serial) to the Gamepad Map Console, with a demo controller. diff --git a/components/gamepad_map/idf_component.yml b/components/gamepad_map/idf_component.yml index 20efd4f705..c2b2045220 100644 --- a/components/gamepad_map/idf_component.yml +++ b/components/gamepad_map/idf_component.yml @@ -8,6 +8,7 @@ maintainers: documentation: "https://esp-cpp.github.io/espp/input/gamepad_map.html" examples: - path: example + - path: webapp_example tags: - cpp - Component @@ -18,7 +19,10 @@ dependencies: idf: version: '>=5.0' espp/base_component: '>=1.0' + espp/dispatcher: '>=1.0' espp/format: '>=1.0' # GamepadReport::lt / rt / capture and GamepadDecoder::set_combine_controls() espp/hid-rp: '>=1.4.6' espp/persistent_data: '>=1.0' + espp/stream_frame: '>=1.0' + espp/task: '>=1.0' diff --git a/components/gamepad_map/include/detail/gamepad_map_protocol.hpp b/components/gamepad_map/include/detail/gamepad_map_protocol.hpp new file mode 100644 index 0000000000..e4371e2753 --- /dev/null +++ b/components/gamepad_map/include/detail/gamepad_map_protocol.hpp @@ -0,0 +1,533 @@ +#pragma once + +// Wire protocol of espp::GamepadMapService: view and edit the gamepad maps of +// an espp::GamepadProfiles store, and watch a controller's input before and +// after mapping, over the espp stream_frame codec. Routed by an +// espp::Dispatcher on module 11 by default (`espp.gamepad_map` v1 through +// discovery). +// +// This header is deliberately host-buildable (stream_frame.hpp, gamepad_map.hpp +// and the standard library only) so the codec is unit-tested on the host +// (components/gamepad_map/test/gamepad_map_protocol_host_test.cpp) and so host +// tools can reuse it. All multi-byte fields are little-endian; a `str` is +// [len u8][utf8 bytes]. +// +// Shared encodings: +// target [kind u8] 0 = the default map (nothing follows) +// [kind u8 = 1][vid u16][pid u16][name str] +// 1 = the profile for that controller type +// (VID and PID 0: matched by name) +// map [left_deadzone u8][right_deadzone u8][rule_count u8] +// {[kind u8][source u8][target u8][flags u8][param i16]} x rule_count +// (GamepadMapRule field for field; 6 bytes per rule) +// state [buttons u32][left_x i16][left_y i16][right_x i16][right_y i16] +// [left_trigger i16][right_trigger i16] (16 bytes) +// +// Requests (host -> device, reply flag clear): +// 0x01 GET_INFO (no payload) +// 0x02 GET_MAP [target] +// 0x03 SET_MAP [target][map] validated, then saved; a profile +// target adds or replaces that profile +// 0x04 ERASE_PROFILE [vid u16][pid u16][name str] +// 0x05 LIST_PROFILES (no payload) +// 0x06 SET_STREAM [enable u8][period_ms u16] +// INPUT events every period while enabled; the device +// clamps the period to its minimum and stops by itself +// when no SET_STREAM enable renews the stream within its +// lease (GamepadMapService::Config::stream_lease), so a +// closed page does not leave it streaming +// 0x07 RESET_ALL (no payload) every profile erased, default = identity +// Replies / events (device -> host, high bit set = frame reply flag): +// 0x81 INFO [button_count u8][axis_count u8][max_rules u8] +// [max_profiles u8][profile_count u8][flags u8] +// flags bit0 = a controller is connected, then: +// [vid u16][pid u16][name str][has_profile u8] +// Answers GET_INFO, and is also sent unsolicited (no +// correlation id) when the connected controller changes while +// the INPUT stream is on. +// 0x82 MAP [target][flags u8][map] (GET_MAP; the target as requested, +// the profile's stored name if it +// exists; flags bit0 = it exists. A +// profile that does not exist answers +// with the map its controller uses +// today, the default map, exists 0) +// 0x83 OK [request_type u8] +// 0x84 ERROR [request_type u8][code u32][utf8 message] +// code = the POSIX errno value of the std::errc the service +// chose (informational; the message is authoritative) +// 0x85 PROFILES [count u8]{[vid u16][pid u16][name str][rule_count u8]} +// 0x86 INPUT [flags u8][raw state][mapped state] +// flags bit0 = a controller is connected, bit1 = the state +// changed since the previous INPUT event (streamed only) +// Replies echo the request frame's correlation id (if it carried one); +// streamed INPUT events and unsolicited INFO carry none. +// +// Compatibility: the device rejects trailing bytes in a request, but a host +// decodes device -> host messages leniently: bytes after the fields it knows +// are ignored, so a later version of the protocol may append fields to them. + +#include +#include +#include +#include +#include +#include + +#include "gamepad_map.hpp" +#include "gamepad_state.hpp" +#include "stream_frame.hpp" + +namespace espp::detail::gamepad_map_protocol { + +/// Default dispatcher module id (a routing key only; see GamepadMapService::Config::module). +inline constexpr uint8_t kModule = 11; +/// Stable protocol identifier + version advertised through discovery. +inline constexpr const char *kProtocol = "espp.gamepad_map"; +inline constexpr uint16_t kProtocolVersion = 1; + +/// Frame `type` values within the gamepad map module. +enum class Type : uint8_t { + // host -> device + GetInfo = 0x01, + GetMap = 0x02, + SetMap = 0x03, + EraseProfile = 0x04, + ListProfiles = 0x05, + SetStream = 0x06, + ResetAll = 0x07, + // device -> host (high bit set) + Info = 0x81, + Map = 0x82, + Ok = 0x83, + Error = 0x84, + Profiles = 0x85, + Input = 0x86, +}; + +/// INFO / INPUT flag: a controller is connected. +inline constexpr uint8_t kFlagConnected = 0x01; +/// INPUT flag: the state changed since the previous INPUT event. +inline constexpr uint8_t kFlagChanged = 0x02; +/// MAP flag: the requested map exists (a profile that does not answers with the default map). +inline constexpr uint8_t kFlagExists = 0x01; + +/// Bytes of an encoded GamepadState. +inline constexpr size_t kStateSize = 16; +/// Bytes of one encoded GamepadMapRule. +inline constexpr size_t kRuleSize = 6; + +/// Which map a GET_MAP / SET_MAP addresses. +struct Target { + bool profile{false}; ///< false = the default map + uint16_t vid{0}; + uint16_t pid{0}; + std::string name{}; + bool operator==(const Target &) const = default; +}; + +/// The connected controller, as carried in INFO. +struct Controller { + uint16_t vid{0}; + uint16_t pid{0}; + std::string name{}; + bool has_profile{false}; + bool operator==(const Controller &) const = default; +}; + +/// Decoded INFO. +struct Info { + uint8_t button_count{0}; + uint8_t axis_count{0}; + uint8_t max_rules{0}; + uint8_t max_profiles{0}; + uint8_t profile_count{0}; + std::optional controller{}; + bool operator==(const Info &) const = default; +}; + +/// One entry of PROFILES. +struct ProfileSummary { + uint16_t vid{0}; + uint16_t pid{0}; + std::string name{}; + uint8_t rule_count{0}; + bool operator==(const ProfileSummary &) const = default; +}; + +/// Decoded SET_STREAM. +struct StreamRequest { + bool enable{false}; + uint16_t period_ms{0}; +}; + +/// Decoded INPUT. +struct Input { + bool connected{false}; + bool changed{false}; + GamepadState raw{}; + GamepadState mapped{}; +}; + +/// Whether a type value is a device->host reply / event. +inline constexpr bool is_reply(Type type) { return (static_cast(type) & 0x80) != 0; } + +/// Build an encoded frame for a gamepad map message (device->host types map to +/// the frame reply flag). +inline std::vector build_frame(Type type, std::span payload = {}, + uint8_t module = kModule, + std::optional correlation = std::nullopt) { + return espp::stream_frame::build_frame(is_reply(type), module, static_cast(type), + payload, correlation); +} + +// ---- byte helpers ------------------------------------------------------------- + +/// Reads little-endian fields from a payload; every read fails (and keeps +/// failing) once the payload is exhausted. +class Reader { +public: + explicit Reader(std::span data) + : data_(data) {} + bool u8(uint8_t &v) { + if (!have(1)) + return false; + v = data_[pos_++]; + return true; + } + bool u16(uint16_t &v) { + if (!have(2)) + return false; + v = static_cast(data_[pos_] | (data_[pos_ + 1] << 8)); + pos_ += 2; + return true; + } + bool i16(int16_t &v) { + uint16_t u = 0; + if (!u16(u)) + return false; + v = static_cast(u); + return true; + } + bool u32(uint32_t &v) { + if (!have(4)) + return false; + v = static_cast(data_[pos_]) | (static_cast(data_[pos_ + 1]) << 8) | + (static_cast(data_[pos_ + 2]) << 16) | + (static_cast(data_[pos_ + 3]) << 24); + pos_ += 4; + return true; + } + bool str(std::string &s) { + uint8_t n = 0; + if (!u8(n) || !have(n)) + return false; + s.assign(reinterpret_cast(data_.data() + pos_), n); + pos_ += n; + return true; + } + bool done() const { return ok_ && pos_ == data_.size(); } + /// For device -> host messages: every known field was read (trailing bytes, + /// fields of a later protocol version, are ignored). + bool known_fields_read() const { return ok_; } + bool ok() const { return ok_; } + +private: + bool have(size_t n) { + if (!ok_ || data_.size() - pos_ < n) { + ok_ = false; + return false; + } + return true; + } + std::span data_; + size_t pos_{0}; + bool ok_{true}; +}; + +inline void put_u8(std::vector &out, uint8_t v) { out.push_back(v); } +inline void put_u16(std::vector &out, uint16_t v) { + out.push_back(static_cast(v & 0xFF)); + out.push_back(static_cast(v >> 8)); +} +inline void put_i16(std::vector &out, int16_t v) { + put_u16(out, static_cast(v)); +} +inline void put_u32(std::vector &out, uint32_t v) { + for (int i = 0; i < 4; i++) + out.push_back(static_cast((v >> (8 * i)) & 0xFF)); +} +/// Append a [len u8][bytes] string (truncated to 255 bytes). +inline void put_str(std::vector &out, std::string_view s) { + const size_t n = s.size() > 255 ? 255 : s.size(); + out.push_back(static_cast(n)); + out.insert(out.end(), s.begin(), s.begin() + static_cast(n)); +} + +// ---- shared encodings ----------------------------------------------------------- + +inline void put_target(std::vector &out, const Target &t) { + put_u8(out, t.profile ? 1 : 0); + if (!t.profile) + return; + put_u16(out, t.vid); + put_u16(out, t.pid); + put_str(out, t.name); +} +inline bool read_target(Reader &r, Target &t) { + uint8_t kind = 0; + if (!r.u8(kind) || kind > 1) + return false; + t = {}; + if (kind == 0) + return true; + t.profile = true; + return r.u16(t.vid) && r.u16(t.pid) && r.str(t.name); +} + +/// Encode a map. At most 255 rules are written (a valid map has far fewer). +inline void put_map(std::vector &out, const GamepadMap &m) { + const size_t n = m.rules.size() > 255 ? 255 : m.rules.size(); + put_u8(out, m.left_deadzone_percent); + put_u8(out, m.right_deadzone_percent); + put_u8(out, static_cast(n)); + for (size_t i = 0; i < n; i++) { + const auto &rule = m.rules[i]; + put_u8(out, static_cast(rule.kind)); + put_u8(out, rule.source); + put_u8(out, rule.target); + put_u8(out, rule.flags); + put_i16(out, rule.param); + } +} +/// Decode a map. Only the layout is checked here; check the result with +/// GamepadMap::valid() before using it. +inline bool read_map(Reader &r, GamepadMap &m) { + uint8_t count = 0; + m = {}; + if (!r.u8(m.left_deadzone_percent) || !r.u8(m.right_deadzone_percent) || !r.u8(count)) + return false; + m.rules.reserve(count); + for (uint8_t i = 0; i < count; i++) { + uint8_t kind = 0; + GamepadMapRule rule; + if (!r.u8(kind) || !r.u8(rule.source) || !r.u8(rule.target) || !r.u8(rule.flags) || + !r.i16(rule.param)) + return false; + rule.kind = static_cast(kind); + m.rules.push_back(rule); + } + return true; +} + +inline void put_state(std::vector &out, const GamepadState &s) { + put_u32(out, s.buttons); + for (const int16_t a : s.axes) + put_i16(out, a); +} +inline bool read_state(Reader &r, GamepadState &s) { + if (!r.u32(s.buttons)) + return false; + for (auto &a : s.axes) + if (!r.i16(a)) + return false; + return true; +} + +// ---- requests (host -> device) -------------------------------------------------- + +inline std::vector encode_get_map(const Target &t) { + std::vector p; + put_target(p, t); + return p; +} +inline std::optional decode_get_map(std::span payload) { + Reader r(payload); + Target t; + if (!read_target(r, t) || !r.done()) + return std::nullopt; + return t; +} + +inline std::vector encode_set_map(const Target &t, const GamepadMap &m) { + std::vector p; + put_target(p, t); + put_map(p, m); + return p; +} +inline std::optional> +decode_set_map(std::span payload) { + Reader r(payload); + Target t; + GamepadMap m; + if (!read_target(r, t) || !read_map(r, m) || !r.done()) + return std::nullopt; + return std::make_pair(std::move(t), std::move(m)); +} + +inline std::vector encode_erase_profile(uint16_t vid, uint16_t pid, + std::string_view name) { + std::vector p; + put_u16(p, vid); + put_u16(p, pid); + put_str(p, name); + return p; +} +inline std::optional decode_erase_profile(std::span payload) { + Reader r(payload); + Target t; + t.profile = true; + if (!r.u16(t.vid) || !r.u16(t.pid) || !r.str(t.name) || !r.done()) + return std::nullopt; + return t; +} + +inline std::vector encode_set_stream(bool enable, uint16_t period_ms) { + std::vector p; + put_u8(p, enable ? 1 : 0); + put_u16(p, period_ms); + return p; +} +inline std::optional decode_set_stream(std::span payload) { + Reader r(payload); + uint8_t enable = 0; + StreamRequest s; + if (!r.u8(enable) || enable > 1 || !r.u16(s.period_ms) || !r.done()) + return std::nullopt; + s.enable = enable != 0; + return s; +} + +// ---- replies / events (device -> host) ----------------------------------------- + +inline std::vector encode_info(const Info &info) { + std::vector p; + put_u8(p, info.button_count); + put_u8(p, info.axis_count); + put_u8(p, info.max_rules); + put_u8(p, info.max_profiles); + put_u8(p, info.profile_count); + put_u8(p, info.controller ? kFlagConnected : 0); + if (info.controller) { + put_u16(p, info.controller->vid); + put_u16(p, info.controller->pid); + put_str(p, info.controller->name); + put_u8(p, info.controller->has_profile ? 1 : 0); + } + return p; +} +inline std::optional decode_info(std::span payload) { + Reader r(payload); + Info info; + uint8_t flags = 0; + if (!r.u8(info.button_count) || !r.u8(info.axis_count) || !r.u8(info.max_rules) || + !r.u8(info.max_profiles) || !r.u8(info.profile_count) || !r.u8(flags)) + return std::nullopt; + if (flags & kFlagConnected) { + Controller c; + uint8_t has = 0; + if (!r.u16(c.vid) || !r.u16(c.pid) || !r.str(c.name) || !r.u8(has)) + return std::nullopt; + c.has_profile = has != 0; + info.controller = std::move(c); + } + if (!r.known_fields_read()) + return std::nullopt; + return info; +} + +/// Decoded MAP. +struct MapReply { + Target target{}; + bool exists{false}; + GamepadMap map{}; +}; + +inline std::vector encode_map_reply(const Target &t, bool exists, const GamepadMap &m) { + std::vector p; + put_target(p, t); + put_u8(p, exists ? kFlagExists : 0); + put_map(p, m); + return p; +} +inline std::optional decode_map_reply(std::span payload) { + Reader r(payload); + MapReply reply; + uint8_t flags = 0; + if (!read_target(r, reply.target) || !r.u8(flags) || !read_map(r, reply.map) || + !r.known_fields_read()) + return std::nullopt; + reply.exists = flags & kFlagExists; + return reply; +} + +inline std::vector encode_ok(uint8_t request_type) { return {request_type}; } + +inline std::vector encode_error(uint8_t request_type, uint32_t code, + std::string_view message) { + std::vector p; + put_u8(p, request_type); + put_u32(p, code); + p.insert(p.end(), message.begin(), message.end()); + return p; +} + +/// Encode PROFILES, keeping it within @p max_bytes: entries that would not fit +/// are dropped from the end (at most 255 entries). +/// @param[out] encoded_count Set to the number of entries encoded, if non-null. +inline std::vector encode_profiles(std::span profiles, + size_t max_bytes = espp::stream_frame::kMaxPayloadSize, + size_t *encoded_count = nullptr) { + std::vector p{0}; + size_t n = 0; + for (const auto &s : profiles) { + const size_t name_len = s.name.size() > 255 ? 255 : s.name.size(); + const size_t entry = 2 + 2 + 1 + name_len + 1; + if (n == 255 || p.size() + entry > max_bytes) + break; + put_u16(p, s.vid); + put_u16(p, s.pid); + put_str(p, s.name); + put_u8(p, s.rule_count); + n++; + } + p[0] = static_cast(n); + if (encoded_count) + *encoded_count = n; + return p; +} +inline std::optional> +decode_profiles(std::span payload) { + Reader r(payload); + uint8_t count = 0; + if (!r.u8(count)) + return std::nullopt; + std::vector out(count); + for (auto &s : out) + if (!r.u16(s.vid) || !r.u16(s.pid) || !r.str(s.name) || !r.u8(s.rule_count)) + return std::nullopt; + if (!r.known_fields_read()) + return std::nullopt; + return out; +} + +inline std::vector encode_input(const Input &in) { + std::vector p; + p.reserve(1 + 2 * kStateSize); + put_u8(p, static_cast((in.connected ? kFlagConnected : 0) | + (in.changed ? kFlagChanged : 0))); + put_state(p, in.raw); + put_state(p, in.mapped); + return p; +} +inline std::optional decode_input(std::span payload) { + Reader r(payload); + Input in; + uint8_t flags = 0; + if (!r.u8(flags) || !read_state(r, in.raw) || !read_state(r, in.mapped) || !r.known_fields_read()) + return std::nullopt; + in.connected = flags & kFlagConnected; + in.changed = flags & kFlagChanged; + return in; +} + +} // namespace espp::detail::gamepad_map_protocol diff --git a/components/gamepad_map/include/gamepad_map.hpp b/components/gamepad_map/include/gamepad_map.hpp index 0918054d13..8af58c5c07 100644 --- a/components/gamepad_map/include/gamepad_map.hpp +++ b/components/gamepad_map/include/gamepad_map.hpp @@ -123,6 +123,11 @@ struct GamepadMapRule { return fail("target out of range"); if (kind == Kind::AxisToButton && param == 0) return fail("axis -> button needs a non-zero threshold"); + if (kind == Kind::AxisToButton && param < 0 && + GamepadState::is_trigger(static_cast(source))) + return fail("a trigger never goes below 0: its threshold must be positive"); + if (target == NONE && keeps_source()) + return fail("a rule that keeps its source needs a target"); if (kind == Kind::AxisToAxis && (param < -MAX_SCALE_PERCENT || param > MAX_SCALE_PERCENT)) return fail("axis -> axis scale out of range"); return true; diff --git a/components/gamepad_map/include/gamepad_map_service.hpp b/components/gamepad_map/include/gamepad_map_service.hpp new file mode 100644 index 0000000000..afd8d130df --- /dev/null +++ b/components/gamepad_map/include/gamepad_map_service.hpp @@ -0,0 +1,548 @@ +#pragma once + +// espp::GamepadMapService -- view and edit an espp::GamepadProfiles store and +// watch a controller's input before / after mapping, as a transport-agnostic +// dispatcher module (detail/gamepad_map_protocol.hpp is the wire spec). Same +// contract as the other espp services: requests are handled under an internal +// mutex, the `send` callback runs with that mutex released, frames for other +// modules / reply-flagged frames are ignored so the service shares a stream. +// +// Wiring (one line per transport): +// +// espp::GamepadMapService map_service({.send = [&](auto f) { usb.write_vendor(f); }, +// .profiles = &profiles}); +// dispatcher.register_module(map_service); // module 11 + discovery metadata + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "dispatcher.hpp" +#include "stream_frame.hpp" + +#include "base_component.hpp" +#include "detail/gamepad_map_protocol.hpp" +#include "gamepad_map.hpp" +#include "gamepad_profiles.hpp" +#include "gamepad_state.hpp" +#include "task.hpp" + +namespace espp { + +/** + * @brief Serves a GamepadProfiles store over any framed byte stream so a host + * (the hosted gamepad map web console) can view and edit the maps and + * watch a controller's input live (dispatcher module 11 by default; see + * Config::module). + * + * @details The application tells the service which controller is connected + * (set_controller() / clear_controller()) and hands it every input it + * maps (publish_input(), raw and mapped). The service answers GET_INFO + * / GET_MAP / LIST_PROFILES from the store, applies SET_MAP / + * ERASE_PROFILE / RESET_ALL to it (every map is validated, every + * change saved), and while a host has the stream on, sends the latest + * input as INPUT events every period. The stream stops by itself when + * the host does not renew it within Config::stream_lease, so a closed + * browser tab does not leave it running. + * + * When a change affects the map of the connected controller (its + * profile, or the default map it falls back to), the service calls + * Config::on_active_map_changed with the new map: the application + * swaps the map it applies. publish_input() is cheap when nobody is + * streaming (an atomic load), so it can be called for every report. + * + * Several services (one per transport) may share one GamepadProfiles + * store; tell each about the controller and feed each the input. + * + * **Threading**: an internal mutex covers the parser and the controller state; + * every outbound frame is serialized on a send mutex held across `send`, so + * frames never interleave. `send` and `on_active_map_changed` must not + * re-enter this object. + * + * \section gamepad_map_service_ex1 GamepadMapService Example + * \snippet gamepad_map_webapp_example.cpp gamepad_map_webapp_example + */ +class GamepadMapService : public BaseComponent { +public: + using Stream = espp::stream_frame::StreamParser; + using Type = espp::detail::gamepad_map_protocol::Type; + + /// Default dispatcher module id (11). A routing key only: Config::module serves + /// on any id, and hosts find it through discovery (by kProtocol). + static constexpr uint8_t kModule = espp::detail::gamepad_map_protocol::kModule; + /// Stable protocol identifier + version advertised through discovery. + static constexpr const char *kProtocol = espp::detail::gamepad_map_protocol::kProtocol; + static constexpr uint16_t kProtocolVersion = espp::detail::gamepad_map_protocol::kProtocolVersion; + + /// Transmits one encoded frame to the host. + using send_fn = std::function frame)>; + /// Called with the connected controller's new map after a host changed it. + using map_changed_fn = std::function; + + /// Configuration for the GamepadMapService. + struct Config { + send_fn send{nullptr}; ///< Transmits an encoded frame (required). + GamepadProfiles *profiles{nullptr}; ///< The store served (required; must outlive the service). + /// Called (without the service's locks held) when a host's change gives the + /// connected controller a new map. + map_changed_fn on_active_map_changed{nullptr}; + /// Dispatcher module id this instance answers on (and stamps on every + /// frame it sends). A routing key only (0x00..0xEF). + uint8_t module{kModule}; + /// Shortest INPUT period a host may request (SET_STREAM is clamped to it). + std::chrono::milliseconds min_stream_period{20}; + /// The stream stops when no SET_STREAM enable renews it for this long. + std::chrono::milliseconds stream_lease{10000}; + /// The streaming task (started on the first SET_STREAM enable). + Task::BaseConfig task_config{.name = "gamepad_map_stream", .stack_size_bytes = 4 * 1024}; + espp::Logger::Verbosity log_level{espp::Logger::Verbosity::WARN}; ///< Logger verbosity. + }; + + /// @brief Construct the service. + explicit GamepadMapService(const Config &config) + : BaseComponent("GamepadMapService", config.log_level) + , config_(config) { + if (!config_.profiles) + logger_.error("no GamepadProfiles store configured: every request will fail"); + } + + ~GamepadMapService() { stop_stream(); } + + /// @brief The dispatcher module id this service answers on (Config::module). + uint8_t module_id() const { return config_.module; } + + /// @brief Discovery metadata for registering this service on a Dispatcher. + Dispatcher::ModuleInfo module_info() const { + return {.name = "Gamepad map", + .app = "gamepad_map_console.html", + .description = "Gamepad button / axis mapping and per-controller profiles", + .protocol = kProtocol, + .protocol_version = kProtocolVersion}; + } + + // --- application side --- + + /** + * @brief A controller connected (or the connected one changed). + * @return The map to apply to it (its profile's, else the default map). + */ + GamepadMap set_controller(uint16_t vid, uint16_t pid, const std::string &name) { + bool changed = false; + { + std::lock_guard lock(mutex_); + const Controller c{vid, pid, name}; + changed = !controller_ || !(*controller_ == c); + controller_ = c; + } + if (changed) + push_info(); + return config_.profiles ? config_.profiles->map_for(vid, pid, name) : GamepadMap{}; + } + + /// @brief The controller disconnected (INPUT then reports no controller). + void clear_controller() { + bool changed = false; + { + std::lock_guard lock(mutex_); + changed = controller_.has_value(); + controller_.reset(); + } + if (changed) + push_info(); + } + + /// @brief The map the connected controller should use now (default map when none is connected). + GamepadMap active_map() const { + if (!config_.profiles) + return {}; + const auto c = controller(); + return c ? config_.profiles->map_for(c->vid, c->pid, c->name) : config_.profiles->default_map(); + } + + /** + * @brief Report one input: what the controller sent and what it was mapped + * to. Cheap (an atomic load) while no host is streaming. + */ + void publish_input(const GamepadState &raw, const GamepadState &mapped) { + if (!streaming_.load(std::memory_order_relaxed)) + return; + std::lock_guard lock(input_mutex_); + if (raw != latest_raw_ || mapped != latest_mapped_) + input_changed_ = true; + latest_raw_ = raw; + latest_mapped_ = mapped; + } + + /// @brief Whether INPUT events are being sent. + bool streaming() const { return streaming_.load(); } + + /// @brief Stop streaming (also done by the destructor, SET_STREAM 0 and the lease). + void stop_stream() { + std::unique_ptr task; + { + std::lock_guard lock(mutex_); + streaming_.store(false); + task = std::move(task_); + } + if (task) + task->stop(); + } + + // --- transport side --- + + /** + * @brief Dispatcher entry point: handle one routed frame. Frames for other + * modules and reply-flagged frames are ignored, so this can be + * registered directly: `dispatcher.register_module(service)`. + */ + void handle(const espp::stream_frame::Frame &frame) { + if (frame.module != module_id() || frame.is_reply()) + return; + handle_frame(frame.type, frame.payload, frame.correlation); + } + + /// @brief Feed received transport bytes (standalone use, without a Dispatcher). + void feed(std::span data) { + std::vector frames; + { + std::lock_guard lock(mutex_); + frames = parser_.feed(data); + } + for (const auto &frame : frames) + handle(frame); + } + + /// @brief Discard any partially-buffered frame bytes (standalone feed() use). + void reset_parser() { + std::lock_guard lock(mutex_); + parser_.reset(); + } + + /** + * @brief Handle one already-parsed request frame. + * @param correlation The request frame's correlation id, if it carried one; + * every reply echoes it (streamed events carry none). + * @return true if the type belongs to the gamepad map protocol (a reply was + * sent), false if it was ignored. + */ + bool handle_frame(uint8_t type, std::span payload, + std::optional correlation = std::nullopt) { + namespace proto = espp::detail::gamepad_map_protocol; + const auto request = static_cast(type); + switch (request) { + case Type::GetInfo: + case Type::GetMap: + case Type::SetMap: + case Type::EraseProfile: + case Type::ListProfiles: + case Type::SetStream: + case Type::ResetAll: + break; + default: + return false; // not a gamepad map request: ignore so the service can share a stream + } + if (!config_.profiles) { + send_error(type, std::errc::not_supported, "no profile store configured", correlation); + return true; + } + auto &profiles = *config_.profiles; + switch (request) { + case Type::GetInfo: + send_frame(proto::build_frame(Type::Info, proto::encode_info(build_info()), module_id(), + correlation)); + break; + case Type::GetMap: { + const auto target = proto::decode_get_map(payload); + if (!target) { + send_error(type, std::errc::invalid_argument, "malformed GET_MAP", correlation); + break; + } + proto::Target resolved = *target; + GamepadMap map; + bool exists = true; + if (target->profile) { + if (const auto p = profiles.profile(target->vid, target->pid, target->name)) { + map = p->map; + resolved.name = p->name; // as stored + } else { + exists = false; // no such profile: the controller uses the default map today + map = profiles.default_map(); + } + } else { + map = profiles.default_map(); + } + send_frame(proto::build_frame(Type::Map, proto::encode_map_reply(resolved, exists, map), + module_id(), correlation)); + break; + } + case Type::SetMap: { + const auto req = proto::decode_set_map(payload); + if (!req) { + send_error(type, std::errc::invalid_argument, "malformed SET_MAP", correlation); + break; + } + const auto &[target, map] = *req; + std::string why; + if (!map.valid(&why)) { + send_error(type, std::errc::invalid_argument, "invalid map: " + why, correlation); + break; + } + const GamepadMap before = active_map(); + std::error_code ec; + const bool saved = + target.profile + ? profiles.set_profile( + {.vid = target.vid, .pid = target.pid, .name = target.name, .map = map}, ec) + : profiles.set_default_map(map, ec); + if (!saved) { + send_error(type, std::errc::io_error, + "could not save the map: " + (ec ? ec.message() : std::string("unknown error")), + correlation, ec); + break; + } + ok(type, correlation); + notify_if_changed(before); + break; + } + case Type::EraseProfile: { + const auto target = proto::decode_erase_profile(payload); + if (!target) { + send_error(type, std::errc::invalid_argument, "malformed ERASE_PROFILE", correlation); + break; + } + const GamepadMap before = active_map(); + std::error_code ec; + if (!profiles.erase_profile(target->vid, target->pid, target->name, ec)) { + if (ec) + send_error(type, std::errc::io_error, "could not save: " + ec.message(), correlation, ec); + else + send_error(type, std::errc::no_such_file_or_directory, "no such profile", correlation); + break; + } + ok(type, correlation); + notify_if_changed(before); + break; + } + case Type::ListProfiles: { + const auto stored = profiles.profiles(); + std::vector list; + list.reserve(stored.size()); + std::transform( + stored.begin(), stored.end(), std::back_inserter(list), [](const GamepadProfile &p) { + return proto::ProfileSummary{ + .vid = p.vid, + .pid = p.pid, + .name = p.name, + .rule_count = static_cast(std::min(p.map.rules.size(), 255))}; + }); + size_t encoded = 0; + auto reply = proto::encode_profiles(list, max_payload(), &encoded); + if (encoded < list.size()) + logger_.warn("PROFILES payload full: listing {} of {} profiles", encoded, list.size()); + send_frame(proto::build_frame(Type::Profiles, reply, module_id(), correlation)); + break; + } + case Type::SetStream: { + const auto req = proto::decode_set_stream(payload); + if (!req) { + send_error(type, std::errc::invalid_argument, + "malformed SET_STREAM (expected u8 enable, u16 period_ms)", correlation); + break; + } + if (req->enable) + start_stream(std::chrono::milliseconds(req->period_ms)); + else + stop_stream(); + ok(type, correlation); + break; + } + case Type::ResetAll: { + const GamepadMap before = active_map(); + std::error_code ec; + if (!profiles.reset(ec)) { + send_error(type, std::errc::io_error, "could not save: " + ec.message(), correlation, ec); + break; + } + ok(type, correlation); + notify_if_changed(before); + break; + } + default: + break; + } + return true; + } + +protected: + struct Controller { + uint16_t vid{0}; + uint16_t pid{0}; + std::string name{}; + bool operator==(const Controller &) const = default; + }; + + /// Tell a streaming host about a controller change right away (unsolicited + /// INFO, no correlation id); a host that is not streaming asks with GET_INFO. + void push_info() { + namespace proto = espp::detail::gamepad_map_protocol; + if (!config_.profiles || !streaming_.load()) + return; + send_frame(proto::build_frame(Type::Info, proto::encode_info(build_info()), module_id())); + } + + std::optional controller() const { + std::lock_guard lock(mutex_); + return controller_; + } + + espp::detail::gamepad_map_protocol::Info build_info() const { + namespace proto = espp::detail::gamepad_map_protocol; + proto::Info info{ + .button_count = static_cast(GamepadState::BUTTON_COUNT), + .axis_count = static_cast(GamepadState::AXIS_COUNT), + .max_rules = static_cast(std::min(GamepadMap::MAX_RULES, 255)), + .max_profiles = + static_cast(std::min(config_.profiles->max_profiles(), 255)), + .profile_count = + static_cast(std::min(config_.profiles->profiles().size(), 255))}; + if (const auto c = controller()) { + info.controller = proto::Controller{ + .vid = c->vid, + .pid = c->pid, + .name = c->name, + .has_profile = config_.profiles->profile(c->vid, c->pid, c->name).has_value()}; + } + return info; + } + + void notify_if_changed(const GamepadMap &before) { + if (!config_.on_active_map_changed || !controller()) + return; + const GamepadMap now = active_map(); + if (now != before) + config_.on_active_map_changed(now); + } + + void ok(uint8_t request_type, std::optional correlation) { + namespace proto = espp::detail::gamepad_map_protocol; + send_frame( + proto::build_frame(Type::Ok, proto::encode_ok(request_type), module_id(), correlation)); + } + + /// The payload cap: the stream_frame payload limit. + static constexpr size_t max_payload() { return espp::stream_frame::kMaxPayloadSize; } + + void start_stream(std::chrono::milliseconds period) { + std::lock_guard lock(mutex_); + period_ms_.store(std::max(period, config_.min_stream_period).count()); + lease_until_.store(now_ms() + config_.stream_lease.count()); + { + std::lock_guard input_lock(input_mutex_); + input_changed_ = true; // the first event after (re)enabling is always "changed" + } + streaming_.store(true); + if (task_) + return; // already running: the new period and lease apply on its next wake + task_ = std::make_unique( + Task::Config{.callback = [this](std::mutex &m, std::condition_variable &cv, + bool ¬ified) { return stream_step(m, cv, notified); }, + .task_config = config_.task_config}); + task_->start(); + } + + /// One streaming period: send the latest input (no correlation id: events, + /// not replies), end the stream when its lease ran out, then wait one period. + bool stream_step(std::mutex &m, std::condition_variable &cv, bool ¬ified) { + namespace proto = espp::detail::gamepad_map_protocol; + if (streaming_.load()) { + if (now_ms() > lease_until_.load()) { + logger_.info("INPUT stream lease expired; stopping the stream"); + streaming_.store(false); + } else { + proto::Input in; + in.connected = controller().has_value(); + { + std::lock_guard lock(input_mutex_); + in.raw = latest_raw_; + in.mapped = latest_mapped_; + in.changed = input_changed_; + input_changed_ = false; + } + send_frame(proto::build_frame(Type::Input, proto::encode_input(in), module_id())); + } + } + // A stopped stream (lease ran out) leaves the task idle at a slow tick until + // the next SET_STREAM, which takes effect on its next wake. + const auto wait = streaming_.load() ? std::chrono::milliseconds(period_ms_.load()) + : std::chrono::milliseconds(250); + std::unique_lock lock(m); + cv.wait_for(lock, wait, [¬ified] { return notified; }); + notified = false; // consumed, under the mutex, per the Task contract + return false; + } + + static int64_t now_ms() { + using namespace std::chrono; + return duration_cast(steady_clock::now().time_since_epoch()).count(); + } + + /// Transmit a frame. Serialized on send_mutex_ (held across the callback) so + /// an event and a reply never interleave. Never called with mutex_ held. + void send_frame(const std::vector &frame) { + if (frame.empty()) + return; + std::lock_guard send_lock(send_mutex_); + if (!config_.send) { + logger_.warn_rate_limited("no send function configured; dropping a {}-byte frame", + frame.size()); + return; + } + config_.send(frame); + } + + void send_error(uint8_t request_type, std::errc errc, std::string_view message, + std::optional correlation = std::nullopt, std::error_code cause = {}) { + namespace proto = espp::detail::gamepad_map_protocol; + logger_.warn("{} (type 0x{:02x})", message, request_type); + // a generic-category cause is already a POSIX errno; anything else reports + // the std::errc the service chose + const uint32_t code = static_cast(cause && cause.category() == std::generic_category() + ? cause.value() + : std::make_error_code(errc).value()); + send_frame(proto::build_frame(Type::Error, proto::encode_error(request_type, code, message), + module_id(), correlation)); + } + +private: + Config config_; + mutable std::mutex mutex_; ///< guards the parser, controller_ and task_ + mutable std::mutex send_mutex_; ///< serializes every outbound frame across `send` + std::mutex input_mutex_; ///< guards the latest input + Stream parser_; + std::optional controller_{}; + std::unique_ptr task_; + std::atomic streaming_{false}; + std::atomic period_ms_{20}; + std::atomic lease_until_{0}; + GamepadState latest_raw_{}; + GamepadState latest_mapped_{}; + bool input_changed_{true}; +}; + +// Compile-time check that the service keeps satisfying the dispatcher's module +// contract (module_id() / module_info() / handle(frame)). +static_assert(DispatcherModuleConcept); + +} // 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 f43fd22cfb..2ee0092512 100644 --- a/components/gamepad_map/test/gamepad_map_host_test.cpp +++ b/components/gamepad_map/test/gamepad_map_host_test.cpp @@ -185,6 +185,13 @@ static void test_validation() { CHECK(!map.valid(&why)); map.rules = {{GamepadMapRule::Kind::ButtonToButton, 0, 1, 0x80, 0}}; CHECK(!map.valid(&why)); // unknown flag + map.rules = {GamepadMapRule::axis_to_button(A::LeftTrigger, -100, B::L2)}; + CHECK(!map.valid(&why)); // a trigger never goes below 0 + map.rules = {GamepadMapRule::axis_to_button(A::LeftTrigger, 100, B::L2)}; + CHECK(map.valid()); + map.rules = {{GamepadMapRule::Kind::ButtonToButton, 0, GamepadMapRule::NONE, + GamepadMapRule::KEEP_SOURCE, 0}}; + CHECK(!map.valid(&why)); // keeping the source of a rule with no target does nothing map.rules.assign(GamepadMap::MAX_RULES + 1, GamepadMapRule::button(B::South, B::East)); CHECK(!map.valid(&why) && why == "too many rules"); map.rules.clear(); diff --git a/components/gamepad_map/test/gamepad_map_protocol_host_test.cpp b/components/gamepad_map/test/gamepad_map_protocol_host_test.cpp new file mode 100644 index 0000000000..4e1b8d5216 --- /dev/null +++ b/components/gamepad_map/test/gamepad_map_protocol_host_test.cpp @@ -0,0 +1,190 @@ +// Host-buildable unit tests for the gamepad map wire protocol +// (include/detail/gamepad_map_protocol.hpp): golden encodings of every message +// plus decode round trips and rejection of malformed payloads. Build & run +// from the repository root: +// +// g++ -std=c++23 -Wall -Wextra -Werror +// -I components/gamepad_map/include -I components/stream_frame/include +// components/gamepad_map/test/gamepad_map_protocol_host_test.cpp +// -o gamepad_map_protocol_host_test +// ./gamepad_map_protocol_host_test +// +// No ESP-IDF headers required. + +#include +#include +#include + +#include "detail/gamepad_map_protocol.hpp" + +namespace proto = espp::detail::gamepad_map_protocol; +using espp::GamepadMap; +using espp::GamepadMapRule; +using espp::GamepadState; +using B = GamepadState::Button; +using A = GamepadState::Axis; + +static int failures = 0; +#define CHECK(cond) \ + do { \ + if (!(cond)) { \ + std::printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \ + failures++; \ + } \ + } while (0) + +using Bytes = std::vector; + +static void test_map_encoding() { + GamepadMap m; + m.left_deadzone_percent = 10; + m.right_deadzone_percent = 5; + m.add(GamepadMapRule::button(B::South, B::East)) + .add(GamepadMapRule::axis_to_button(A::LeftY, -16384, B::Up, true)); + const proto::Target t{.profile = true, .vid = 0x1949, .pid = 0x0402, .name = "BSP"}; + const Bytes p = proto::encode_set_map(t, m); + const Bytes golden{ + 0x01, 0x49, 0x19, 0x02, 0x04, 0x03, 'B', 'S', 'P', // target: profile 1949:0402 "BSP" + 10, 5, 2, // dead zones, 2 rules + 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, // south -> east + 0x01, 0x01, 0x0e, 0x01, 0x00, 0xc0, // left_y <= -16384 -> up, keep + }; + CHECK(p == golden); + const auto back = proto::decode_set_map(p); + CHECK(back.has_value()); + if (back) { + CHECK(back->first == t); + CHECK(back->second == m); + } + // the default target is one byte + const Bytes def = proto::encode_get_map({}); + CHECK(def == Bytes{0x00}); + CHECK(proto::decode_get_map(def).has_value() && !proto::decode_get_map(def)->profile); + // malformed: unknown target kind, truncated rule, trailing bytes + CHECK(!proto::decode_get_map(Bytes{0x02})); + Bytes truncated = golden; + truncated.pop_back(); + CHECK(!proto::decode_set_map(truncated)); + Bytes trailing = golden; + trailing.push_back(0); + CHECK(!proto::decode_set_map(trailing)); + // the layout decodes even when the content is invalid: valid() is the + // service's job + const Bytes bad_rule{0x00, 0, 0, 1, 0x07, 0x40, 0x00, 0x00, 0x00, 0x00}; + const auto invalid = proto::decode_set_map(bad_rule); + CHECK(invalid.has_value() && !invalid->second.valid()); + + // MAP: the target, the exists flag, the map; a host ignores appended fields + Bytes reply = proto::encode_map_reply(t, false, m); + CHECK(reply.size() == golden.size() + 1); + CHECK(reply[9] == 0x00); // after the 9-byte target: exists = 0 + auto decoded = proto::decode_map_reply(reply); + CHECK(decoded.has_value() && decoded->target == t && !decoded->exists && decoded->map == m); + reply = proto::encode_map_reply({}, true, GamepadMap{}); + CHECK(reply == (Bytes{0x00, 0x01, 0, 0, 0})); + reply.push_back(0xAA); // a later version's field + decoded = proto::decode_map_reply(reply); + CHECK(decoded.has_value() && decoded->exists && !decoded->target.profile); +} + +static void test_info() { + proto::Info info{ + .button_count = 22, .axis_count = 6, .max_rules = 64, .max_profiles = 16, .profile_count = 1}; + Bytes p = proto::encode_info(info); + CHECK(p == (Bytes{22, 6, 64, 16, 1, 0x00})); + auto back = proto::decode_info(p); + CHECK(back.has_value() && *back == info); + + info.controller = + proto::Controller{.vid = 0x045e, .pid = 0x0b13, .name = "Xbox", .has_profile = true}; + p = proto::encode_info(info); + CHECK(p == (Bytes{22, 6, 64, 16, 1, 0x01, 0x5e, 0x04, 0x13, 0x0b, 4, 'X', 'b', 'o', 'x', 1})); + back = proto::decode_info(p); + CHECK(back.has_value() && *back == info); + Bytes longer = p; + longer.push_back(0x55); // device -> host: appended fields are ignored + CHECK(proto::decode_info(longer).has_value() && *proto::decode_info(longer) == info); + p.pop_back(); + CHECK(!proto::decode_info(p)); +} + +static void test_profiles() { + const std::vector list{{0x1949, 0x0402, "BSP-D8", 4}, {0, 0, "NoPnP", 0}}; + const Bytes p = proto::encode_profiles(list); + const Bytes golden{2, 0x49, 0x19, 0x02, 0x04, 6, 'B', 'S', 'P', '-', 'D', '8', + 4, 0x00, 0x00, 0x00, 0x00, 5, 'N', 'o', 'P', 'n', 'P', 0}; + CHECK(p == golden); + const auto back = proto::decode_profiles(p); + CHECK(back.has_value() && *back == list); + // capped: only what fits + size_t encoded = 0; + const Bytes capped = proto::encode_profiles(list, 1 + 12, &encoded); + CHECK(encoded == 1 && capped.size() == 13 && capped[0] == 1); +} + +static void test_input_and_stream() { + proto::Input in; + in.connected = true; + in.changed = true; + in.raw.set(B::South, true); + in.raw.set(A::LeftX, -32767); + in.mapped.set(B::East, true); + in.mapped.set(A::RightTrigger, 32767); + const Bytes p = proto::encode_input(in); + CHECK(p.size() == 1 + 2 * proto::kStateSize); + CHECK(p[0] == 0x03); + CHECK(p[1] == 0x01 && p[2] == 0 && p[3] == 0 && p[4] == 0); // raw buttons: south + CHECK(p[5] == 0x01 && p[6] == 0x80); // raw left_x = -32767 + CHECK(p[17] == 0x02); // mapped buttons: east + CHECK(p[31] == 0xff && p[32] == 0x7f); // mapped right_trigger + const auto back = proto::decode_input(p); + CHECK(back.has_value()); + if (back) { + CHECK(back->connected && back->changed); + CHECK(back->raw == in.raw && back->mapped == in.mapped); + } + + const Bytes s = proto::encode_set_stream(true, 50); + CHECK(s == (Bytes{1, 50, 0})); + const auto req = proto::decode_set_stream(s); + CHECK(req.has_value() && req->enable && req->period_ms == 50); + CHECK(!proto::decode_set_stream(Bytes{2, 50, 0})); // enable must be 0 / 1 + CHECK(!proto::decode_set_stream(Bytes{1, 50})); +} + +static void test_erase_error_frame() { + const Bytes e = proto::encode_erase_profile(0x1949, 0x0402, "BSP"); + CHECK(e == (Bytes{0x49, 0x19, 0x02, 0x04, 3, 'B', 'S', 'P'})); + const auto t = proto::decode_erase_profile(e); + CHECK(t.has_value() && t->profile && t->vid == 0x1949 && t->name == "BSP"); + + const Bytes err = proto::encode_error(0x03, 22, "bad"); + CHECK(err == (Bytes{0x03, 22, 0, 0, 0, 'b', 'a', 'd'})); + + // replies carry the reply flag, requests do not; the frame decodes back + const auto frame = proto::build_frame(proto::Type::Ok, proto::encode_ok(0x03), proto::kModule, 7); + espp::stream_frame::StreamParser parser; + const auto frames = parser.feed(frame); + CHECK(frames.size() == 1); + if (frames.size() == 1) { + CHECK(frames[0].is_reply()); + CHECK(frames[0].module == 11); + CHECK(frames[0].type == 0x83); + CHECK(frames[0].correlation == std::optional(7)); + } + CHECK(!proto::is_reply(proto::Type::SetMap) && proto::is_reply(proto::Type::Input)); +} + +int main() { + test_map_encoding(); + test_info(); + test_profiles(); + test_input_and_stream(); + test_erase_error_frame(); + if (failures == 0) { + std::printf("gamepad_map_protocol_host_test: all checks passed\n"); + return 0; + } + std::printf("gamepad_map_protocol_host_test: %d failure(s)\n", failures); + return 1; +} diff --git a/components/gamepad_map/web/gamepad_map_console.html b/components/gamepad_map/web/gamepad_map_console.html new file mode 100644 index 0000000000..56979327c2 --- /dev/null +++ b/components/gamepad_map/web/gamepad_map_console.html @@ -0,0 +1,2009 @@ + + + + + + espp Gamepad Map Console (WebUSB / Web Serial) + + + + + + + + +
+
+

espp Gamepad Map Console (WebUSB / Web Serial)

+ + Disconnected +
+ +
+ This browser supports neither WebUSB nor Web Serial. Use a Chromium-based browser + (Chrome / Edge / Opera) on a secure origin (https, localhost or file://). +
+ + +
+

Device

+
+ + + + + +
+ +
+

Not connected. Default WebUSB filter: VID 0x1209 / PID 0x0d32 (espp default).

+
+ Controller: - + Profile: - + Profiles stored: - + Rules per map: - + Controls: - +
+
+ +
+
+ +
+

Live input

+
+ + + Received: - +
+ - +
+ +
+
+

Raw (from the controller)

+
+
No input yet: connect and keep "Live input" on.
+
+
+

Mapped (what the device sends on)

+
+
No input yet.
+
+
+

Sticks are -100..100 % with Y growing down; triggers 0..100 %. The dashed circle on the raw sticks is the dead zone of the map in the editor.

+
+ + +
+

Map editor

+
+ Editing: nothing loaded + +
+ +
+

Pick a map on the right and Load it.

+
+ + +
+
+ + + +
#KindSourceTargetKeep sourceParameterDoes
+
+

No rules: every control passes through unchanged (after the dead zones).

+

A rule moves its source to the target (the source no longer reaches its own position) unless "keep source" is ticked; a target of "none" just removes the source. Controls no rule takes as a source pass through. Several rules may feed one target: buttons are OR-ed, axis contributions summed and clamped.

+
+ + 0 rules (the device takes at most 64) +
+
+ Presets (append rules): +
+ +
+ + +
+ +
+

+
+
+ +
+ +
+

Map to edit

+ + +
+ +
+

The default map applies to every controller without a profile. A profile belongs to one controller type (its USB / Bluetooth VID:PID; by name when both are 0). Loading a controller that has no profile yet starts from the default map; saving creates the profile.

+
+ + +
+

Profiles

+
Not connected.
+
+ + +
+

Reset

+

Erase every profile and set the default map back to the identity (no rules, no dead zones).

+ +
+
+
+ + +
+

Log

+
+
+ +
+ espp Gamepad Map Console · talks to espp::GamepadMapService + (components/gamepad_map), which remaps a controller with an + espp::GamepadMap and keeps the maps in an espp::GamepadProfiles store. + Single-file, offline, no dependencies. +
+
+ + + + diff --git a/components/gamepad_map/web/test/gamepad_map_codec_test.js b/components/gamepad_map/web/test/gamepad_map_codec_test.js new file mode 100644 index 0000000000..b8b1115091 --- /dev/null +++ b/components/gamepad_map/web/test/gamepad_map_codec_test.js @@ -0,0 +1,322 @@ +#!/usr/bin/env node +// Unit tests for the gamepad map console's pure logic: the block of +// gamepad_map_console.html between `// --- begin gamepad map codec` and +// `// --- end gamepad map codec ---` (the espp.gamepad_map v1 wire codec, +// local map validation, rule descriptions, presets and the learn detector). +// Device -> host decoders follow the protocol's compatibility rule: a +// truncated message fails, bytes after the known fields are ignored. +// The byte vectors are derived by hand from +// components/gamepad_map/include/detail/gamepad_map_protocol.hpp (layouts) and +// gamepad_map.hpp (GamepadMap's builder helpers). Dependency-free: +// +// node components/gamepad_map/web/test/gamepad_map_codec_test.js +"use strict"; +const fs = require("fs"); +const path = require("path"); +const assert = require("assert"); + +const html = fs.readFileSync(path.join(__dirname, "..", "gamepad_map_console.html"), "utf8"); +// (plain string search: the markers delimit the one codec block) +const begin = html.indexOf(" // --- begin gamepad map codec"); +const end = html.indexOf(" // --- end gamepad map codec ---"); +assert.ok(begin > 0 && end > begin, "codec block markers not found in gamepad_map_console.html"); +const block = html.slice(begin, end); +assert.ok(!/\b(document|window|els|navigator|location)\b/.test(block.replace(/\/\/.*$/gm, "")), "the codec block must not touch the DOM / page state"); +const G = new Function(block + ` + return { T_GET_INFO, T_GET_MAP, T_SET_MAP, T_ERASE_PROFILE, T_LIST_PROFILES, T_SET_STREAM, T_RESET_ALL, + T_INFO, T_MAP, T_OK, T_ERROR, T_PROFILES, T_INPUT, BUTTON_NAMES, AXIS_NAMES, BUTTON_COUNT, AXIS_COUNT, B, A, K, + RULE_NONE, KEEP_SOURCE, AXIS_MAX, STATE_SIZE, RULE_SIZE, PRESETS, + buttonLabel, axisLabel, percentToParam, paramToPercent, GmReader, GmWriter, readMap, readState, encodeState, + encodeGetMap, encodeSetMap, encodeEraseProfile, encodeSetStream, + decodeInfo, decodeMapReply, decodeProfiles, decodeInput, decodeOk, decodeError, + describeTarget, sameTarget, validateTarget, gmLimits, validateRule, validateMap, + ruleButton, ruleAxisToButton, ruleButtonToAxis, ruleAxis, changeRuleKind, describeRule, + learnBaseline, learnStep, applyLearnHit }; +`)(); + +// The whole inline script must parse (a syntax error anywhere breaks the page). +const scriptOpen = html.indexOf(""); +assert.ok(scriptOpen >= 0 && scriptClose > scriptOpen, "no inline