From 19136079f7c49d6702e05f34b66098d4fda25299 Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Tue, 24 Nov 2026 16:42:43 -0700 Subject: [PATCH 1/3] feat(gamepad_map): per-controller rumble options (off / strength / swap motors) espp::RumbleOptions (rumble_options.hpp, beside rumble_state.hpp so both can move into a rumble component later): {flags: RUMBLE_OFF | SWAP_MOTORS, strength_percent 0..200, default 100}. apply(request) is pure / constexpr / allocation-free: off -> all motors 0; otherwise Strong / Weak swapped when asked (trigger motors never), every motor min(255, (level * pct + 50) / 100). 100 % is the exact identity and a 0 level stays 0 for every option, so a stop is always a stop. The application applies it once, at send time, to the host's raw request; espp never applies it by itself. GamepadProfiles (file schema v2): - every GamepadProfile has `rumble`, and the store has default_rumble (also Config::default_rumble for a store without a file); - rumble_for(), default_rumble(), set_default_rumble(), set_defaults() (map + rumble in one save), set_profile_map() (keeps a profile's rumble; a new one starts from the default's); set_profile() replaces the whole profile; - V1 is frozen (GamepadProfileV1; its layout fingerprint 0x4ed1a13b is pinned and a V1 file written by the previous release is loaded in the host test). A V1 file loads with neutral options and stays V1 until the first change (save_after_migration = false), so a rollback before any edit keeps maps; - loaded options are sanitized (unknown flag bits cleared, strength clamped), invalid ones are refused on every write. Wire protocol: still espp.gamepad_map v1 (a released console hides a module advertised at another version). INFO flags bit1 = the device stores rumble options; MAP flags bit1 + a [flags][strength] block; SET_MAP takes an optional trailing block, and without it the stored options are kept, so an older console can never reset them. A SET_MAP with anything but 0 or 2 bytes after the map is malformed. GamepadMapService: active_rumble(), Config::on_active_rumble_changed. change() now decides its notifications after the save, with a controller generation counter: a controller that connected while a change was saved used to keep the stale map; now it gets the map and rumble callbacks. Console: a Rumble row in the map editor (on / strength slider / 100 % / swap, with notes), saved in the same SET_MAP as the map; disabled with a note on firmware without rumble options. The codec block mirrors the C++ (decoded objects gain fields only when the device sent them; unknown flag bits are kept and echoed). Tests: host test (the apply parity table, exhaustive identity / stop / monotonic checks, the store API, sanitizing, the V1 golden file + both pinned fingerprints, the downgrade error), protocol test (rumble goldens), a new GamepadMapService host test (wire, keep-when-absent, callbacks, the connect-during-save race) added to CI, codec test (21 groups). Examples updated (the example gains 3 checks); README / rst / Doxyfile documented. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU --- .github/workflows/gamepad_map_tests.yml | 25 +- components/gamepad_map/README.md | 156 +++++++++- components/gamepad_map/example/README.md | 13 +- .../example/main/gamepad_map_example.cpp | 53 ++++ .../include/detail/gamepad_map_protocol.hpp | 128 ++++++-- .../gamepad_map/include/gamepad_map.hpp | 5 +- .../include/gamepad_map_service.hpp | 116 +++++-- .../gamepad_map/include/gamepad_profiles.hpp | 290 ++++++++++++++---- .../gamepad_map/include/rumble_options.hpp | 113 +++++++ .../test/gamepad_map_host_test.cpp | 277 ++++++++++++++++- .../test/gamepad_map_protocol_host_test.cpp | 85 ++++- .../test/gamepad_map_service_host_test.cpp | 255 +++++++++++++++ .../gamepad_map/web/gamepad_map_console.html | 191 ++++++++++-- .../web/test/gamepad_map_codec_test.js | 171 ++++++++++- .../gamepad_map/webapp_example/README.md | 21 +- .../main/gamepad_map_webapp_example.cpp | 29 +- doc/Doxyfile | 1 + doc/en/input/gamepad_map.rst | 18 +- doc/en/web_apps.rst | 5 +- lib/include/espp.hpp | 1 + 20 files changed, 1783 insertions(+), 170 deletions(-) create mode 100644 components/gamepad_map/include/rumble_options.hpp create mode 100644 components/gamepad_map/test/gamepad_map_service_host_test.cpp diff --git a/.github/workflows/gamepad_map_tests.yml b/.github/workflows/gamepad_map_tests.yml index 01b6b76a2a..fe747f0ced 100644 --- a/.github/workflows/gamepad_map_tests.yml +++ b/.github/workflows/gamepad_map_tests.yml @@ -2,12 +2,15 @@ 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) +# GamepadMap rules + validation, the hid-rp conversion, RumbleOptions, +# GamepadProfiles' file round trip and its version 1 -> 2 migration) # - 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/test/gamepad_map_service_host_test.cpp +# (GamepadMapService against a real store: rumble options on the wire, the +# change callbacks) # - 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. @@ -27,6 +30,8 @@ on: - "components/format/**" - "components/base_component/**" - "components/stream_frame/**" + - "components/task/**" + - "components/dispatcher/**" - ".github/workflows/gamepad_map_tests.yml" push: branches: @@ -40,6 +45,8 @@ on: - "components/format/**" - "components/base_component/**" - "components/stream_frame/**" + - "components/task/**" + - "components/dispatcher/**" - ".github/workflows/gamepad_map_tests.yml" workflow_dispatch: @@ -86,6 +93,20 @@ jobs: components/gamepad_map/test/gamepad_map_protocol_host_test.cpp \ -o gamepad_map_protocol_host_test ./gamepad_map_protocol_host_test + - name: Build and run gamepad_map_service_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 \ + -I components/task/include -I components/dispatcher/include \ + -I components/stream_frame/include \ + -isystem components/serialization/detail/alpaca/include \ + -isystem components/format/detail/fmt/include \ + components/gamepad_map/test/gamepad_map_service_host_test.cpp \ + components/logger/src/logger.cpp components/task/src/task.cpp -lpthread \ + -o gamepad_map_service_host_test + ./gamepad_map_service_host_test - name: Run the web console codec test run: | node --version diff --git a/components/gamepad_map/README.md b/components/gamepad_map/README.md index 0075a821b7..f3167ca255 100644 --- a/components/gamepad_map/README.md +++ b/components/gamepad_map/README.md @@ -5,9 +5,11 @@ 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). +[persistent_data](../persistent_data), together with how each controller type +plays a host's rumble (off, strength, strong / weak motors swapped). 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** @@ -17,7 +19,10 @@ whatever comes next (an emulated USB controller, an emulator's input). - [Gamepad state](#gamepad-state) - [Rules](#rules) - [Profiles](#profiles) + - [Upgrading](#upgrading) - [From a HID gamepad](#from-a-hid-gamepad) + - [Rumble](#rumble) + - [Rumble options](#rumble-options) - [Web console](#web-console) - [Host test](#host-test) - [Examples](#examples) @@ -31,7 +36,8 @@ whatever comes next (an emulated USB controller, an emulator's input). | `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::GamepadProfiles` | A default map plus one map per controller type, each with its rumble options, saved in a file | +| `espp::RumbleOptions` | off / strength 0..200 % / swap strong-weak for a host's rumble; stored per profile; `apply()` once before encoding | | `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) | @@ -92,18 +98,51 @@ read or write outside the state. 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: +and saved atomically. Look the map and the [rumble options](#rumble-options) 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); +espp::RumbleOptions rumble = profiles.rumble_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. +`default_map` and `default_rumble` are used, which is how an application can +migrate its older settings into a map. + +Every profile stores its controller type's rumble options next to its map, and +the default map has its own (`default_rumble()`) for every controller without a +profile. `rumble_for()` returns the profile's options, or the default's when +there is no profile. There are two ways to save a profile: + +- `set_profile()` replaces the whole profile, rumble options included: a + `{.vid, .pid, .name, .map}` without `.rumble` resets them to neutral. +- `set_profile_map()` changes only the map (and the stored name). An existing + profile keeps its rumble options; a new one starts with the default's. The + console saves a new profile the same way: its editor starts from the default + map's rules and rumble options. + +For the default, `set_default_map()` keeps the default rumble options, +`set_default_rumble()` changes only them, and `set_defaults()` saves both in +one write. `erase_profile()` removes the profile's rumble options with it (the +controller then uses the default's), and `reset()` sets the default rumble +options back to neutral too. Invalid options (see `RumbleOptions::valid()`) are +refused with `invalid_argument`, so nothing invalid is ever saved. Options read +from the file are checked as well: unknown flag bits are cleared and a strength +above 200 % is clamped to 200 %, each with a warning. + +### Upgrading + +Rumble options came with version 2 of the file's schema. A version 1 file +(written by firmware without rumble options) loads with neutral rumble options +everywhere, even when `Config::default_rumble` is set, and stays version 1 on +flash until the first change, which writes it as version 2. Older firmware +cannot read a version 2 file: it sets it aside as `.unreadable` and starts +from its defaults. So rolling back to older firmware after a map or rumble +option was edited on the new one loses the profiles; rolling back before any +edit keeps them. ## From a HID gamepad @@ -139,6 +178,57 @@ auto state = espp::to_rumble_state(switch_rumble); auto payload = encoder.encode(espp::to_rumble_levels(state), 200); ``` +### Rumble options + +`espp::RumbleOptions` (`rumble_options.hpp`) says how one controller type plays +a host's rumble. It is two bytes of plain data, stored per profile: + +| Field | Values | Effect | +|-------|--------|--------| +| `flags` bit0, `RUMBLE_OFF` | set / clear | off: every request plays as a stop (all motors 0) | +| `flags` bit1, `SWAP_MOTORS` | set / clear | the strong motor plays the weak motor's level and the weak motor the strong one's; the trigger motors are never swapped | +| `strength_percent` | 0..200, default 100 | every motor's level is scaled by this percentage | + +`RumbleOptions{}` (on, 100 %, not swapped) is neutral: `apply()` returns the +request unchanged. `apply(request)` computes the levels to play: + +- **Off** gives all four motors 0, whatever the strength or swap. The stored + strength is kept, so turning rumble back on restores it. +- **Strength** sets each motor to `min(255, (level * strength_percent + 50) / 100)` + (rounded half up). 0 % is silent, like off. Above 100 % each motor saturates + at 255 on its own, so strong effects lose their differences: at 200 %, a + level of 127 plays as 254 and anything from 128 up as 255. A level of 0 stays + 0 at every strength, so a stop is always a stop. +- **Swap** is for a controller whose motors come out the wrong way round. It + commutes with the scaling. A controller with a single motor feels no + difference, since `hid_rp::RumbleEncoder` drives it from the larger of strong + and weak. +- Unknown flag bits are ignored, and a strength above 200 acts as 200. + +The library never applies the options by itself. Apply them **once**, at send +time, to the host's raw request: + +- Keep the host's latest request raw, and keep the options next to it, under + the same lock. +- Each time the rumble sender decides what to send (a new request, an options + change, a keep-alive repeat, a test pulse), compute `options.apply(raw)`. + Deduplicate and repeat on that result. +- Send an all-zero result as a stop, including its repeats. Off means "send + stops", not "send nothing", so turning rumble off mid-effect stops the motors. + +```cpp +// each time the rumble sender sends: the host's raw request, shaped once +auto payload = encoder.encode(espp::to_rumble_levels(options.apply(host_request)), 200); +``` + +Never apply the options to an already-applied state: the scaling compounds and +a second swap undoes the first. Do not apply them where the host's request is +decoded either: a strength change would then wait for the host's next request, +and off would not stop a rumble the host is holding on. Look the options up +(`rumble_for()`, `GamepadMapService::active_rumble()`) at connect and in change +callbacks, not on every rumble update: the lookup takes the store's lock and may +allocate. + ## Web console `espp::GamepadMapService` serves a `GamepadProfiles` store over any framed byte @@ -146,9 +236,9 @@ 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: +uses it to edit the maps and their rumble options 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, @@ -156,32 +246,64 @@ espp::GamepadMapService service({.send = send_to_host, .on_active_map_changed = [&](const espp::GamepadMap &m) { std::lock_guard lock(map_mutex); active_map = m; // the console changed this controller's map + }, + .on_active_rumble_changed = [&](const espp::RumbleOptions &r) { + std::lock_guard lock(map_mutex); + active_rumble = r; // ... or its rumble options: hand them + // to the rumble sender }}); dispatcher.register_module(service); { - std::lock_guard lock(map_mutex); // the callback above may run on another thread + std::lock_guard lock(map_mutex); // the callbacks above may run on another thread active_map = service.set_controller(vid, pid, name); // on connect; clear_controller() on disconnect + active_rumble = service.active_rumble(); // right after, under the same lock } // for every report: service.publish_input(raw, mapped); // a 32-byte copy under a lock; never sends ``` +Each callback fires only when a change from the console gives the connected +controller a different value (or when the controller changed while the change +was being saved), and never while no controller is connected. The callbacks +run on the thread that handles the request; they must not call back into the +service or change the store. + 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. +Rumble options were added to the protocol without changing its version (still +`espp.gamepad_map` v1), so consoles and firmware from before them keep working +with newer ones. A console learns that a device has them from capability bits: + +- INFO flags bit1: the device stores rumble options per map. +- MAP flags bit1: a 2-byte rumble block follows the map: + `[flags u8][strength_percent u8]`, `RumbleOptions` field for field (neutral + is `00 64`). +- SET_MAP takes the same block, optionally, after the map. With it, the map and + the rumble options are saved together in one write. Without it (what a + console from before rumble options sends), only the map is saved: the stored + rumble options are kept, and a new profile gets the default's. Options with + reserved flag bits or a strength above 200 are refused with an ERROR, and + nothing is saved. + ## 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. `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 +hid-rp conversion (with a real BLE gamepad's descriptor), the rumble options' +math, and the profile store: its file round trip, the rumble options it keeps +per profile, and loading a version 1 file. `test/gamepad_map_protocol_host_test.cpp` +checks the wire protocol against golden encodings. +`test/gamepad_map_service_host_test.cpp` drives `GamepadMapService` with request +frames: replies, what each kind of SET_MAP saves, and which change callbacks +fire. Each file's build command is at its top, and CI runs them in `.github/workflows/gamepad_map_tests.yml` together with the hid-rp report-map test. ## Examples -- [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, stores + per-controller profiles on a LittleFS partition, and applies a profile's + rumble options to a host's rumble request. - [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/example/README.md b/components/gamepad_map/example/README.md index 71d24d6a59..cd3ceee10b 100644 --- a/components/gamepad_map/example/README.md +++ b/components/gamepad_map/example/README.md @@ -13,6 +13,12 @@ comes next: 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. +4. The same store keeps each controller type's rumble options. A profile saved + with its strong and weak motors swapped and a strength of 150 % is looked up + with `rumble_for()`, and `espp::RumbleOptions::apply()` turns a host's rumble + request (strong 100, weak 200) into the levels the controller plays (strong + 255, saturated, and weak 150). Other controllers keep the default's neutral + options, and the profile's options survive a reload. It ends with a pass / fail summary. @@ -56,6 +62,11 @@ I (…) gamepad map example: BSP-D8 map: 4 rule(s); default map: 2 rule(s) [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: Rumble options per controller type +I (…) gamepad map example: host asks for strong 100 weak 200; the controller plays strong 255 weak 150 + [PASS] the options swap and scale the motors + [PASS] other controllers play the host's rumble as asked + [PASS] rumble options survive a reload +I (…) gamepad map example: 11 passed, 0 failed I (…) gamepad map example: Gamepad map example complete! ``` diff --git a/components/gamepad_map/example/main/gamepad_map_example.cpp b/components/gamepad_map/example/main/gamepad_map_example.cpp index 42c8f39471..5de13859be 100644 --- a/components/gamepad_map/example/main/gamepad_map_example.cpp +++ b/components/gamepad_map/example/main/gamepad_map_example.cpp @@ -9,6 +9,8 @@ #include "gamepad_state_formatters.hpp" #include "gamepad_state_hid_rp.hpp" #include "logger.hpp" +#include "rumble_options.hpp" +#include "rumble_state.hpp" using namespace std::chrono_literals; @@ -122,6 +124,57 @@ extern "C" void app_main(void) { reloaded.map_for(0x1949, 0x0402) == default_map); } + { + logger.info("Rumble options per controller type"); + auto &fs = espp::FileSystem::get(); + const std::filesystem::path path = fs.get_root_path() / "gamepad_profiles.bin"; + std::error_code ec; + using M = espp::RumbleState::Motor; + //! [rumble options example] + espp::GamepadProfiles profiles({.file_path = path}); + + // This controller type's motors come out the wrong way round and feel weak: + // swap the strong and weak motors and play every motor at 150 % of what the + // host asks. set_profile() replaces the whole profile, rumble included; + // set_profile_map() would change only the map and keep the stored options. + const espp::RumbleOptions bsp_d8_rumble{.flags = espp::RumbleOptions::SWAP_MOTORS, + .strength_percent = 150}; + if (!profiles.set_profile({.vid = 0x1949, + .pid = 0x0402, + .name = "BSP-D8", + .map = profiles.default_map(), + .rumble = bsp_d8_rumble}, + ec)) + logger.error("Could not save the profile: {}", ec.message()); + + // When a controller connects, look its rumble options up once (next to + // map_for()) and keep them with the host's raw rumble request. + const espp::RumbleOptions options = profiles.rumble_for(0x1949, 0x0402, "BSP-D8"); + + // Each time the rumble is sent: apply the options once to the host's raw + // request. Here the host asks for strong 100, weak 200. + espp::RumbleState host_request; + host_request.set(M::Strong, 100); + host_request.set(M::Weak, 200); + const espp::RumbleState played = options.apply(host_request); + logger.info("host asks for strong {} weak {}; the controller plays strong {} weak {}", + host_request.level(M::Strong), host_request.level(M::Weak), played.level(M::Strong), + played.level(M::Weak)); + // `played` then goes to the controller, e.g. through a hid_rp::RumbleEncoder: + // encoder.encode(espp::to_rumble_levels(played), 200). An all-zero result + // (rumble off, or the host's stop) is sent too: it is a stop. + //! [rumble options example] + // weak 200 x 150 % = 300 saturates at 255 and plays on the strong motor; + // strong 100 x 150 % = 150 plays on the weak motor + check("the options swap and scale the motors", + played.level(M::Strong) == 255 && played.level(M::Weak) == 150); + check("other controllers play the host's rumble as asked", + profiles.rumble_for(0x045e, 0x0b13).is_neutral() && + profiles.default_rumble().is_neutral()); + espp::GamepadProfiles reloaded({.file_path = path}); + check("rumble options survive a reload", reloaded.rumble_for(0x1949, 0x0402) == bsp_d8_rumble); + } + logger.info("{} passed, {} failed", passed, failed); logger.info("Gamepad map example complete!"); while (true) { diff --git a/components/gamepad_map/include/detail/gamepad_map_protocol.hpp b/components/gamepad_map/include/detail/gamepad_map_protocol.hpp index 80fff7953e..79cc141bc7 100644 --- a/components/gamepad_map/include/detail/gamepad_map_protocol.hpp +++ b/components/gamepad_map/include/detail/gamepad_map_protocol.hpp @@ -6,10 +6,10 @@ // 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 +// This header is deliberately host-buildable (stream_frame.hpp, gamepad_map.hpp, +// rumble_options.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: @@ -22,13 +22,23 @@ // (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) +// rumble [flags u8][strength_percent u8] (2 bytes; RumbleOptions field for field) +// flags bit0 = RUMBLE_OFF, bit1 = SWAP_MOTORS, bits 2-7 reserved; +// strength 0..200; neutral = 00 64 // // 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 +// 0x03 SET_MAP [target][map] or [target][map][rumble] +// validated, then saved; a profile target adds or +// replaces that profile. Exactly 0 or 2 bytes may follow +// the map (anything else is malformed). With the rumble +// block, the map and the options are saved together; +// without it the stored options are kept (a new profile +// starts from the default rumble options) // 0x04 ERASE_PROFILE [vid u16][pid u16][name str] +// the profile's rumble options go with it (the controller +// falls back to the default rumble options) // 0x05 LIST_PROFILES (no payload) // 0x06 SET_STREAM [enable u8][period_ms u16] // INPUT events every period while enabled; the device @@ -36,12 +46,15 @@ // 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 +// 0x07 RESET_ALL (no payload) every profile erased, default = identity, +// default rumble options = neutral // 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] +// flags bit1 = the device stores rumble options per map (MAP +// carries them and SET_MAP accepts them); adds no bytes // Answers GET_INFO, and is also sent unsolicited (no // correlation id) when the INPUT stream starts and when the // connected controller changes while it is on. @@ -51,6 +64,9 @@ // profile that does not exist answers // with the map its controller uses // today, the default map, exists 0) +// then [rumble] when flags bit1 is set: the profile's rumble +// options, else the default ones (what the controller uses +// today). A host fails a MAP whose bit1 block is short. // 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 @@ -66,6 +82,16 @@ // listed with no payload must have none), 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. +// +// Revision: rumble options (still v1). The rumble additions (INFO flags bit1, +// MAP flags bit1 + its block, SET_MAP's optional block) keep the protocol at +// version 1 and are found through capability bits instead, because a released +// console hides a module advertised at another version. Every addition is +// compatible both ways: an older host tests only bit0 and ignores the bytes +// after the map, and its SET_MAP (no block) keeps the stored rumble options; a +// newer host sees INFO bit1 clear on older firmware and sends SET_MAP without +// the block, byte-identical to before. Firmware that does not know the block +// rejects a SET_MAP that carries one as malformed (nothing is saved). #include #include @@ -76,6 +102,7 @@ #include "gamepad_map.hpp" #include "gamepad_state.hpp" +#include "rumble_options.hpp" #include "stream_frame.hpp" namespace espp::detail::gamepad_map_protocol { @@ -111,11 +138,17 @@ inline constexpr uint8_t kFlagConnected = 0x01; 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; +/// INFO flag: the device stores rumble options per map (MAP carries them, SET_MAP accepts them). +inline constexpr uint8_t kFlagRumbleOptions = 0x02; +/// MAP flag: a rumble block follows the map. +inline constexpr uint8_t kFlagRumble = 0x02; /// Bytes of an encoded GamepadState. inline constexpr size_t kStateSize = 16; /// Bytes of one encoded GamepadMapRule. inline constexpr size_t kRuleSize = 6; +/// Bytes of an encoded RumbleOptions. +inline constexpr size_t kRumbleSize = 2; /// Which map a GET_MAP / SET_MAP addresses. struct Target { @@ -142,6 +175,7 @@ struct Info { uint8_t max_rules{0}; uint8_t max_profiles{0}; uint8_t profile_count{0}; + bool rumble_options{false}; ///< flags bit1: the device stores rumble options per map std::optional controller{}; bool operator==(const Info &) const = default; }; @@ -227,6 +261,8 @@ class Reader { return true; } bool done() const { return ok_ && pos_ == data_.size(); } + /// Bytes not read yet (0 once a read has failed). + size_t remaining() const { return ok_ ? data_.size() - pos_ : 0; } /// 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_; } @@ -319,6 +355,18 @@ inline bool read_map(Reader &r, GamepadMap &m) { return true; } +/// Encode rumble options: [flags u8][strength_percent u8]. +inline void put_rumble(std::vector &out, const RumbleOptions &o) { + put_u8(out, o.flags); + put_u8(out, o.strength_percent); +} +/// Decode rumble options. Only the layout is checked here; check the result +/// with RumbleOptions::valid() before using it. +inline bool read_rumble(Reader &r, RumbleOptions &o) { + o = {}; + return r.u8(o.flags) && r.u8(o.strength_percent); +} + inline void put_state(std::vector &out, const GamepadState &s) { put_u32(out, s.buttons); for (const int16_t a : s.axes) @@ -348,20 +396,43 @@ inline std::optional decode_get_map(std::span payload) { return t; } -inline std::vector encode_set_map(const Target &t, const GamepadMap &m) { +/// Decoded SET_MAP. +struct SetMapRequest { + Target target{}; + GamepadMap map{}; + /// The rumble block, if the request carried one (absent: keep the stored options). + std::optional rumble{}; + bool operator==(const SetMapRequest &) const = default; +}; + +/// Encode SET_MAP; without `rumble` the request is the original v1 form (the +/// device keeps the stored rumble options). +inline std::vector +encode_set_map(const Target &t, const GamepadMap &m, + const std::optional &rumble = std::nullopt) { std::vector p; put_target(p, t); put_map(p, m); + if (rumble) + put_rumble(p, *rumble); return p; } -inline std::optional> -decode_set_map(std::span payload) { +/// Decode SET_MAP: exactly 0 (no rumble) or kRumbleSize (a rumble block) bytes +/// may follow the map. Only the layout is checked (see read_map / read_rumble). +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()) + SetMapRequest req; + if (!read_target(r, req.target) || !read_map(r, req.map)) + return std::nullopt; + if (r.remaining() == kRumbleSize) { + RumbleOptions o; + if (!read_rumble(r, o)) + return std::nullopt; + req.rumble = o; + } + if (!r.done()) return std::nullopt; - return std::make_pair(std::move(t), std::move(m)); + return req; } inline std::vector encode_erase_profile(uint16_t vid, uint16_t pid, @@ -406,7 +477,8 @@ inline std::vector encode_info(const Info &info) { 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); + put_u8(p, static_cast((info.controller ? kFlagConnected : 0) | + (info.rumble_options ? kFlagRumbleOptions : 0))); if (info.controller) { put_u16(p, info.controller->vid); put_u16(p, info.controller->pid); @@ -422,6 +494,7 @@ inline std::optional decode_info(std::span payload) { 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; + info.rumble_options = flags & kFlagRumbleOptions; if (flags & kFlagConnected) { Controller c; uint8_t has = 0; @@ -440,23 +513,40 @@ struct MapReply { Target target{}; bool exists{false}; GamepadMap map{}; + /// The rumble block (flags bit1), if the device sent one. + std::optional rumble{}; }; -inline std::vector encode_map_reply(const Target &t, bool exists, const GamepadMap &m) { +/// Encode MAP; with `rumble`, flags bit1 is set and the block follows the map. +inline std::vector +encode_map_reply(const Target &t, bool exists, const GamepadMap &m, + const std::optional &rumble = std::nullopt) { std::vector p; put_target(p, t); - put_u8(p, exists ? kFlagExists : 0); + put_u8(p, static_cast((exists ? kFlagExists : 0) | (rumble ? kFlagRumble : 0))); put_map(p, m); + if (rumble) + put_rumble(p, *rumble); return p; } +/// Decode MAP. Flags bit1 with a missing or short rumble block fails; bytes +/// after the known fields are ignored (without bit1 there is no rumble block, +/// whatever follows the map). 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()) + if (!read_target(r, reply.target) || !r.u8(flags) || !read_map(r, reply.map)) return std::nullopt; reply.exists = flags & kFlagExists; + if (flags & kFlagRumble) { + RumbleOptions o; + if (!read_rumble(r, o)) + return std::nullopt; + reply.rumble = o; + } + if (!r.known_fields_read()) + return std::nullopt; return reply; } diff --git a/components/gamepad_map/include/gamepad_map.hpp b/components/gamepad_map/include/gamepad_map.hpp index e42d6a960e..ca32de8374 100644 --- a/components/gamepad_map/include/gamepad_map.hpp +++ b/components/gamepad_map/include/gamepad_map.hpp @@ -46,6 +46,8 @@ namespace espp { * * The struct is plain data (it is stored with PersistentData and * sent over the wire as is); build rules with the static helpers. + * Stored as is inside GamepadProfiles' file: a layout change needs a + * new schema version (see GamepadProfileV1). */ struct GamepadMapRule { using Button = GamepadState::Button; @@ -162,7 +164,8 @@ struct GamepadMapRule { * * 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. + * page) before using it. Stored as is inside GamepadProfiles' file: a + * layout change needs a new schema version (see GamepadProfileV1). * * \section gamepad_map_ex1 Gamepad Map Example * \snippet gamepad_map_example.cpp gamepad map example diff --git a/components/gamepad_map/include/gamepad_map_service.hpp b/components/gamepad_map/include/gamepad_map_service.hpp index 1ef3279a0e..db07ed7e06 100644 --- a/components/gamepad_map/include/gamepad_map_service.hpp +++ b/components/gamepad_map/include/gamepad_map_service.hpp @@ -60,22 +60,27 @@ namespace espp { * 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() only copies the state - * under a lock (no I/O), so it can be called for every report. + * swaps the map it applies. Likewise, when a change gives the + * connected controller different rumble options (see RumbleOptions), + * the service calls Config::on_active_rumble_changed with them: the + * application applies the new options to the rumble it forwards. + * publish_input() only copies the state under a lock (no I/O), 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. * Their changes and notifications are serialized on the store's * change_mutex(), so the last notification always carries the map - * the store holds. + * (and rumble options) the store holds. * * **Threading**: an internal mutex covers the parser, the controller state and * the stream task; every outbound frame is serialized on a send mutex held * across `send`, so frames never interleave. set_controller(), * clear_controller() and publish_input() never send (an INFO for a controller * change goes out from the stream task), so they are safe to call from a - * radio / host task. `send` and `on_active_map_changed` must not re-enter this - * object (nor change the store). + * radio / host task. `send`, `on_active_map_changed` and + * `on_active_rumble_changed` must not re-enter this object (nor change the + * store). * * \section gamepad_map_service_ex1 GamepadMapService Example * \snippet gamepad_map_webapp_example.cpp gamepad_map_webapp_example @@ -96,6 +101,8 @@ class GamepadMapService : public BaseComponent { 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; + /// Called with the connected controller's new rumble options after a host changed them. + using rumble_changed_fn = std::function; /// Configuration for the GamepadMapService. struct Config { @@ -104,6 +111,10 @@ class GamepadMapService : public BaseComponent { /// 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}; + /// Called (without the service's locks held, under the store's + /// change_mutex()) when a host's change gives the connected controller + /// different rumble options. + rumble_changed_fn on_active_rumble_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}; @@ -135,7 +146,8 @@ class GamepadMapService : public BaseComponent { Dispatcher::ModuleInfo module_info() const { return {.name = "Gamepad map", .app = "gamepad_map_console.html", - .description = "Gamepad button / axis mapping and per-controller profiles", + .description = + "Gamepad button / axis mapping, rumble options and per-controller profiles", .protocol = kProtocol, .protocol_version = kProtocolVersion}; } @@ -144,6 +156,9 @@ class GamepadMapService : public BaseComponent { /** * @brief A controller connected (or the connected one changed). + * @details Call active_rumble() right after for its rumble options, under the + * same lock your change callbacks take, so a host's change cannot + * slip in between. * @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) { @@ -153,6 +168,8 @@ class GamepadMapService : public BaseComponent { const Controller c{vid, pid, name}; changed = !controller_ || !(*controller_ == c); controller_ = c; + if (changed) + ++controller_generation_; // a change() in flight notifies for this controller } if (changed) { reset_input(); // nothing from the previous controller carries over @@ -168,6 +185,8 @@ class GamepadMapService : public BaseComponent { std::lock_guard lock(mutex_); changed = controller_.has_value(); controller_.reset(); + if (changed) + ++controller_generation_; } if (changed) { reset_input(); @@ -183,6 +202,17 @@ class GamepadMapService : public BaseComponent { return c ? config_.profiles->map_for(c->vid, c->pid, c->name) : config_.profiles->default_map(); } + /// @brief The rumble options the connected controller should use now (the + /// default ones when none is connected). Apply them once, where the + /// host's raw rumble becomes the controller's motor command. + RumbleOptions active_rumble() const { + if (!config_.profiles) + return {}; + const auto c = controller(); + return c ? config_.profiles->rumble_for(c->vid, c->pid, c->name) + : config_.profiles->default_rumble(); + } + /** * @brief Report one input: what the controller sent and what it was mapped * to. Copies 32 bytes under a lock (always, so a stream that starts @@ -290,19 +320,25 @@ class GamepadMapService : public BaseComponent { } proto::Target resolved = *target; GamepadMap map; + RumbleOptions rumble; bool exists = true; if (target->profile) { if (const auto p = profiles.profile(target->vid, target->pid, target->name)) { map = p->map; + rumble = p->rumble; resolved.name = p->name; // as stored } else { - exists = false; // no such profile: the controller uses the default map today + // no such profile: the controller uses the default map and rumble today + exists = false; map = profiles.default_map(); + rumble = profiles.default_rumble(); } } else { map = profiles.default_map(); + rumble = profiles.default_rumble(); } - send_frame(proto::build_frame(Type::Map, proto::encode_map_reply(resolved, exists, map), + send_frame(proto::build_frame(Type::Map, + proto::encode_map_reply(resolved, exists, map, rumble), module_id(), correlation)); break; } @@ -312,19 +348,33 @@ class GamepadMapService : public BaseComponent { send_error(type, std::errc::invalid_argument, "malformed SET_MAP", correlation); break; } - const auto &[target, map] = *req; + const auto &target = req->target; + const auto &map = req->map; + const auto &rumble = req->rumble; std::string why; if (!map.valid(&why)) { send_error(type, std::errc::invalid_argument, "invalid map: " + why, correlation); break; } + if (rumble && !rumble->valid(&why)) { + send_error(type, std::errc::invalid_argument, "invalid rumble options: " + why, + correlation); + break; + } std::error_code ec; + // with a rumble block, the map and the options are saved together; without + // one (an older host) the stored options are kept const bool saved = change([&] { - return target.profile - ? profiles.set_profile( - {.vid = target.vid, .pid = target.pid, .name = target.name, .map = map}, - ec) - : profiles.set_default_map(map, ec); + if (target.profile) { + return rumble ? profiles.set_profile({.vid = target.vid, + .pid = target.pid, + .name = target.name, + .map = map, + .rumble = *rumble}, + ec) + : profiles.set_profile_map(target.vid, target.pid, target.name, map, ec); + } + return rumble ? profiles.set_defaults(map, *rumble, ec) : profiles.set_default_map(map, ec); }); if (!saved) { send_error(type, std::errc::io_error, @@ -432,7 +482,8 @@ class GamepadMapService : public BaseComponent { .max_profiles = static_cast(std::min(config_.profiles->max_profiles(), 255)), .profile_count = - static_cast(std::min(config_.profiles->profile_count(), 255))}; + static_cast(std::min(config_.profiles->profile_count(), 255)), + .rumble_options = true}; if (const auto c = controller()) { info.controller = proto::Controller{.vid = c->vid, @@ -444,20 +495,32 @@ class GamepadMapService : public BaseComponent { } /// Apply one change to the store (`save` returns whether it was saved) and, - /// when it gives the connected controller a different map, tell the - /// application -- all under the store's change mutex, so services sharing a - /// store change and notify one at a time and the last notification carries - /// the map the store holds. + /// when it gives the connected controller a different map or different + /// rumble options, tell the application -- all under the store's change + /// mutex, so services sharing a store change and notify one at a time and + /// the last notification carries what the store holds. Whether to notify is + /// decided after the save: a controller that connected while it ran (its + /// map looked up before the save landed) is told too. template bool change(Save save) { std::lock_guard lock(config_.profiles->change_mutex()); - const bool notify = config_.on_active_map_changed && controller().has_value(); - const GamepadMap before = notify ? active_map() : GamepadMap{}; + const uint32_t generation = controller_generation_.load(); + const GamepadMap map_before = config_.on_active_map_changed ? active_map() : GamepadMap{}; + const RumbleOptions rumble_before = + config_.on_active_rumble_changed ? active_rumble() : RumbleOptions{}; if (!save()) return false; - if (notify) { - const GamepadMap now = active_map(); - if (now != before) - config_.on_active_map_changed(now); + if (controller().has_value()) { + const bool reconnected = controller_generation_.load() != generation; + if (config_.on_active_map_changed) { + const GamepadMap now = active_map(); + if (reconnected || now != map_before) + config_.on_active_map_changed(now); + } + if (config_.on_active_rumble_changed) { + const RumbleOptions now = active_rumble(); + if (reconnected || now != rumble_before) + config_.on_active_rumble_changed(now); + } } return true; } @@ -575,6 +638,9 @@ class GamepadMapService : public BaseComponent { std::mutex input_mutex_; ///< guards the latest input Stream parser_; std::optional controller_{}; + /// Bumped whenever the connected controller changes (under mutex_), so + /// change() can tell that one connected while it saved. + std::atomic controller_generation_{0}; std::unique_ptr task_; std::atomic streaming_{false}; bool task_active_{false}; ///< task_ is running (guarded by mutex_) diff --git a/components/gamepad_map/include/gamepad_profiles.hpp b/components/gamepad_map/include/gamepad_profiles.hpp index f5afb6ba06..41440e91a5 100644 --- a/components/gamepad_map/include/gamepad_profiles.hpp +++ b/components/gamepad_map/include/gamepad_profiles.hpp @@ -12,11 +12,12 @@ #include "base_component.hpp" #include "gamepad_map.hpp" #include "persistent_data.hpp" +#include "rumble_options.hpp" namespace espp { /** - * @brief The map for one type of controller. + * @brief The map and rumble options 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 @@ -27,10 +28,11 @@ struct GamepadProfile { /// Longest name stored; longer names are cut to it (and compared cut). static constexpr size_t MAX_NAME_LENGTH = 64; - 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 + 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 + RumbleOptions rumble{}; ///< how this controller type plays a host's rumble /// @brief A name as stored (cut to MAX_NAME_LENGTH bytes). static std::string clip_name(const std::string &n) { return n.substr(0, MAX_NAME_LENGTH); } @@ -47,31 +49,77 @@ struct GamepadProfile { bool operator==(const GamepadProfile &) const = default; }; -/// @brief The data a GamepadProfiles store keeps (schema version 1). +/** + * @brief One profile as schema version 1 stored it. + * + * @details FROZEN: its layout is the V1 file format. Never edit it, nor + * GamepadMap / GamepadMapRule while V1 is supported (a GamepadMap + * layout change must freeze a GamepadMapV1 for V1 and V2 and add a + * V3). + */ +struct GamepadProfileV1 { + 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 Schema version 1 of the data a GamepadProfiles store keeps (FROZEN; +/// same layout fingerprint as before rumble options were added). struct GamepadProfilesV1 { static constexpr uint32_t VERSION = 1; + GamepadMap default_map{}; ///< for a controller without a profile + std::vector profiles{}; ///< per controller type +}; + +/// @brief The data a GamepadProfiles store keeps (schema version 2: rumble options). +struct GamepadProfilesV2 { + static constexpr uint32_t VERSION = 2; GamepadMap default_map{}; ///< for a controller without a profile + RumbleOptions default_rumble{}; ///< for a controller without a profile std::vector profiles{}; ///< per controller type + + /// @brief V1 -> V2: maps and keys copied; every rumble option neutral + /// (default_rumble included). + static GamepadProfilesV2 migrate(const GamepadProfilesV1 &v1) { + GamepadProfilesV2 v2{.default_map = v1.default_map, .default_rumble = {}}; + v2.profiles.reserve(v1.profiles.size()); + for (const auto &p : v1.profiles) + v2.profiles.push_back( + {.vid = p.vid, .pid = p.pid, .name = p.name, .map = p.map, .rumble = {}}); + return v2; + } }; /** - * @brief Per-controller-type gamepad maps, stored in a file with - * PersistentData. + * @brief Per-controller-type gamepad maps and rumble options, 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. + * @details Holds a default map and default RumbleOptions plus one + * GamepadProfile (map and rumble options) 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(), rumble_for()) and keep what is + * returned for its reports / rumble; the lookups copy and are not + * meant for every report. * - * Every map that comes in is checked with GamepadMap::valid(). From a - * file, an invalid rule is dropped (the rest of its map kept), and a - * profile no controller can match, a duplicate or one over the limit - * is dropped, each with a warning. A file that cannot be read (corrupt, - * or written by a newer firmware) is renamed to `.unreadable` - * and the store starts from the defaults, so the next change does not - * overwrite what may still be recoverable (see load_error()). + * Every map that comes in is checked with GamepadMap::valid(), and + * every RumbleOptions with RumbleOptions::valid(), so nothing invalid + * is ever saved. From a file, an invalid rule is dropped (the rest of + * its map kept), unknown rumble flag bits are cleared and a rumble + * strength over 200 % is clamped, and a profile no controller can + * match, a duplicate or one over the limit is dropped, each with a + * warning. A file that cannot be read (corrupt, or written by a newer + * firmware) is renamed to `.unreadable` and the store starts + * from the defaults, so the next change does not overwrite what may + * still be recoverable (see load_error()). + * + * The file is schema version 2 (rumble options). A version 1 file + * (maps only) loads, migrated in memory with neutral rumble options + * everywhere (Config::default_rumble does not apply to it), and stays + * version 1 on flash until the first change writes version 2. After + * that, older firmware cannot read the file: it sets it aside as + * `.unreadable` and starts from its defaults. * * Thread-safe. * @@ -80,8 +128,8 @@ struct GamepadProfilesV1 { */ class GamepadProfiles : public BaseComponent { public: - using Data = GamepadProfilesV1; - using Storage = PersistentData; + using Data = GamepadProfilesV2; + using Storage = PersistentData; /** * @brief Configuration for the GamepadProfiles. @@ -89,13 +137,19 @@ class GamepadProfiles : public BaseComponent { 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 + /// Default rumble options when the file does not exist yet (invalid ones + /// are replaced by neutral options). + RumbleOptions default_rumble{}; + 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). + * @brief Load the profiles (or start from `config.default_map` and + * `config.default_rumble` when there is no file yet; the file is + * written on the first change). + * @details An older (version 1) file is migrated in memory only: it is + * rewritten as the current version on the first change. * @param config The configuration. */ explicit GamepadProfiles(const Config &config) @@ -103,17 +157,24 @@ class GamepadProfiles : public BaseComponent { , max_profiles_(config.max_profiles) , storage_({.file_path = config.file_path, .auto_load = false, + .save_after_migration = false, .max_file_size = max_file_size(config.max_profiles), .log_level = config.log_level}) { std::error_code ec; if (storage_.load(ec)) { data_ = sanitize(storage_.get()); + if (storage_.was_migrated()) + logger_.info("Loaded gamepad profiles v{}; rumble options start neutral; the file is " + "rewritten as v2 on the first change", + storage_.loaded_version()); } else { if (ec != make_error_code(PersistentDataErrc::file_not_found)) { load_error_ = ec; keep_unreadable(config.file_path, ec); } data_.default_map = config.default_map.valid() ? config.default_map : GamepadMap{}; + data_.default_rumble = + config.default_rumble.valid() ? config.default_rumble : RumbleOptions{}; } // only data_ is used from here on: do not keep a second copy in storage_ storage_.set(Data{}); @@ -130,6 +191,15 @@ class GamepadProfiles : public BaseComponent { return p ? p->map : data_.default_map; } + /// @brief The rumble options for a controller: its profile's, else the default + /// rumble options. Apply them once, where the host's raw request + /// becomes the controller's motor command (see RumbleOptions). + RumbleOptions rumble_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->rumble : data_.default_rumble; + } + /// @brief The profile for a controller, if it has one. std::optional profile(uint16_t vid, uint16_t pid, const std::string &name = {}) const { @@ -162,6 +232,12 @@ class GamepadProfiles : public BaseComponent { return data_.default_map; } + /// @brief The rumble options for controllers without a profile. + RumbleOptions default_rumble() const { + std::lock_guard lock(mutex_); + return data_.default_rumble; + } + /// @brief Everything, as stored. Data data() const { std::lock_guard lock(mutex_); @@ -178,7 +254,7 @@ class GamepadProfiles : public BaseComponent { std::mutex &change_mutex() const { return change_mutex_; } /** - * @brief Replace the default map and save. + * @brief Replace the default map and save (the default rumble options are kept). * @param map The map (must be valid()). * @param ec Set on failure: std::errc::invalid_argument for an invalid map, * else the save error. @@ -194,42 +270,80 @@ class GamepadProfiles : public BaseComponent { } /** - * @brief Add a profile, or replace the one for the same controller, and save. - * @param entry The profile (its map must be valid(); with VID and PID 0 it - * needs a name; a name is stored cut to MAX_NAME_LENGTH). - * @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. + * @brief Replace the default rumble options and save (the default map is kept). + * @param rumble The options (must be valid()). + * @param ec Set on failure: std::errc::invalid_argument for invalid options, + * else the save error. * @return true if saved. */ - bool set_profile(const GamepadProfile &entry, std::error_code &ec) { - if (!check(entry.map, ec)) + bool set_default_rumble(const RumbleOptions &rumble, std::error_code &ec) { + if (!check(rumble, ec)) return false; - if (entry.vid == 0 && entry.pid == 0 && entry.name.empty()) { - ec = std::make_error_code(std::errc::invalid_argument); - return false; - } - GamepadProfile stored = entry; - stored.name = GamepadProfile::clip_name(entry.name); 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(stored.vid, stored.pid, stored.name); - }); - if (it != next.profiles.end()) { - *it = std::move(stored); - } else if (next.profiles.size() >= max_profiles_) { - ec = std::make_error_code(std::errc::no_buffer_space); + next.default_rumble = rumble; + return commit(std::move(next), ec); + } + + /** + * @brief Replace the default map and the default rumble options, and save + * both in one commit. + * @param map The map (must be valid()). + * @param rumble The rumble options (must be valid()). + * @param ec Set on failure: std::errc::invalid_argument when either is + * invalid (nothing is saved), else the save error. + * @return true if saved. + */ + bool set_defaults(const GamepadMap &map, const RumbleOptions &rumble, std::error_code &ec) { + if (!check(map, ec) || !check(rumble, ec)) return false; - } else { - next.profiles.push_back(std::move(stored)); - } + std::lock_guard lock(mutex_); + Data next = data_; + next.default_map = map; + next.default_rumble = rumble; return commit(std::move(next), ec); } /** - * @brief Remove a controller's profile (it then uses the default map) and save. + * @brief Add a profile, or replace the one for the same controller, and save. + * @details Replaces the whole profile, rumble included: `{.vid, .pid, .name, + * .map}` resets its rumble to neutral; use set_profile_map() to + * change only the map. + * @param entry The profile (its map and rumble options must be valid(); with + * VID and PID 0 it needs a name; a name is stored cut to + * MAX_NAME_LENGTH). + * @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 &entry, std::error_code &ec) { + return upsert(entry, /*map_only=*/false, ec); + } + + /** + * @brief Set a controller's map, keeping its rumble options, and save. + * @details Replaces only the map (and the stored name, as set_profile() + * does) of the controller's profile. A controller without a profile + * gets a new one with this map and the default rumble options. + * @param vid The controller's vendor ID. + * @param pid The controller's product ID. + * @param name The controller's name (needed with VID and PID 0; stored cut + * to MAX_NAME_LENGTH). + * @param map The map (must be valid()). + * @param ec Set on failure: std::errc::invalid_argument for an invalid map + * or a missing key, std::errc::no_buffer_space when the store is + * full, else the save error. + * @return true if saved. + */ + bool set_profile_map(uint16_t vid, uint16_t pid, const std::string &name, const GamepadMap &map, + std::error_code &ec) { + return upsert({.vid = vid, .pid = pid, .name = name, .map = map}, /*map_only=*/true, ec); + } + + /** + * @brief Remove a controller's profile (it then uses the default map and the + * default rumble options) 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) { @@ -245,7 +359,8 @@ class GamepadProfiles : public BaseComponent { } /** - * @brief Forget every profile and reset the default map to identity, and save. + * @brief Forget every profile, reset the default map to identity and the + * default rumble options to neutral, and save. * @return true if saved. */ bool reset(std::error_code &ec) { @@ -259,8 +374,11 @@ class GamepadProfiles : public BaseComponent { // overhead), so whatever save() writes, load() accepts. static size_t max_file_size(size_t max_profiles) { constexpr size_t map_bytes = 32 + GamepadMap::MAX_RULES * 16; - constexpr size_t profile_bytes = map_bytes + GamepadProfile::MAX_NAME_LENGTH + 32; - return std::max(64 * 1024, 1024 + map_bytes + max_profiles * profile_bytes); + constexpr size_t rumble_bytes = 8; + constexpr size_t profile_bytes = + map_bytes + rumble_bytes + GamepadProfile::MAX_NAME_LENGTH + 32; + return std::max(64 * 1024, + 1024 + map_bytes + rumble_bytes + max_profiles * profile_bytes); } void keep_unreadable(const std::filesystem::path &file, const std::error_code &why) { @@ -292,6 +410,49 @@ class GamepadProfiles : public BaseComponent { return true; } + static bool check(const RumbleOptions &rumble, std::error_code &ec) { + ec.clear(); + if (!rumble.valid()) { + ec = std::make_error_code(std::errc::invalid_argument); + return false; + } + return true; + } + + // set_profile() / set_profile_map(): add the profile, or replace the one for + // the same controller. With `map_only`, entry.rumble is not used: a stored + // profile keeps its rumble options and a new one starts from default_rumble. + bool upsert(GamepadProfile entry, bool map_only, std::error_code &ec) { + if (!check(entry.map, ec)) + return false; + if (!map_only && !check(entry.rumble, ec)) + return false; + if (entry.vid == 0 && entry.pid == 0 && entry.name.empty()) { + ec = std::make_error_code(std::errc::invalid_argument); + return false; + } + entry.name = GamepadProfile::clip_name(entry.name); + 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(entry.vid, entry.pid, entry.name); + }); + if (it != next.profiles.end()) { + if (map_only) + entry.rumble = it->rumble; + *it = std::move(entry); + } else if (next.profiles.size() >= max_profiles_) { + ec = std::make_error_code(std::errc::no_buffer_space); + return false; + } else { + if (map_only) + entry.rumble = next.default_rumble; + next.profiles.push_back(std::move(entry)); + } + return commit(std::move(next), ec); + } + // save first, then take it: memory never holds what the file does not bool commit(Data next, std::error_code &ec) { ec.clear(); @@ -321,8 +482,24 @@ class GamepadProfiles : public BaseComponent { return m; } + // Keep what can be kept of rumble options from the file: flag bits this + // firmware does not know are cleared, a strength over the maximum clamped. + RumbleOptions sanitize_rumble(RumbleOptions r, const char *what) const { + const auto unknown = static_cast(r.flags & ~RumbleOptions::KNOWN_FLAGS); + if (unknown) { + logger_.warn("{}: unknown rumble flags 0x{:02x} cleared", what, unknown); + r.flags = static_cast(r.flags & RumbleOptions::KNOWN_FLAGS); + } + if (r.strength_percent > RumbleOptions::MAX_STRENGTH_PERCENT) { + logger_.warn("{}: rumble strength out of range; clamped", what); + r.strength_percent = RumbleOptions::MAX_STRENGTH_PERCENT; + } + return r; + } + Data sanitize(Data d) const { d.default_map = sanitize_map(std::move(d.default_map), "stored default map"); + d.default_rumble = sanitize_rumble(d.default_rumble, "stored default rumble"); std::vector kept; for (auto &p : d.profiles) { p.name = GamepadProfile::clip_name(p.name); @@ -339,6 +516,7 @@ class GamepadProfiles : public BaseComponent { continue; } p.map = sanitize_map(std::move(p.map), "a stored profile"); + p.rumble = sanitize_rumble(p.rumble, "a stored profile"); kept.push_back(std::move(p)); } d.profiles = std::move(kept); diff --git a/components/gamepad_map/include/rumble_options.hpp b/components/gamepad_map/include/rumble_options.hpp new file mode 100644 index 0000000000..786d025d8d --- /dev/null +++ b/components/gamepad_map/include/rumble_options.hpp @@ -0,0 +1,113 @@ +#pragma once + +#include +#include +#include +#include + +#include "rumble_state.hpp" + +namespace espp { + +/** + * @brief How to play a host's rumble on one controller type: off, a strength + * (0..200 %), and whether the strong and weak motors trade places. + * + * @details Plain data. GamepadProfiles stores one per profile plus one for + * controllers without a profile, and GamepadMapService sends it field + * for field ([flags u8][strength_percent u8]). RumbleOptions{} is + * neutral: apply() returns its input. + * + * Apply it exactly ONCE, where the host's request becomes the + * controller's motor command. Re-apply it to the stored raw request + * whenever the request or the options change, never to an + * already-applied state: scaling compounds and a swap undoes itself. + * An all-zero result is a stop to SEND. "Off" means "send stops", + * not "send nothing". + * + * apply() scales every motor's level by strength_percent / 100, + * rounding half up, and saturates each motor on its own at + * RumbleState::LEVEL_MAX (so above 100 % strong effects play at full + * strength). SWAP_MOTORS trades the Strong and Weak levels; the + * trigger motors are scaled but never swapped. A level of 0 stays 0 + * for every option value, so apply() never turns on a motor the host + * left off. It is pure, constexpr and does not allocate. + * + * A new flag bit is a compatible addition (no schema bump) only if a + * clear bit means today's behaviour. Firmware that does not know a bit + * ignores it in apply(), rejects it in valid(), and clears it when it + * loads a stored file. A console must learn from a capability bit + * that a device honours a new flag. + * + * \section rumble_options_ex1 Rumble Options Example + * \snippet gamepad_map_example.cpp rumble options example + */ +struct RumbleOptions { + static constexpr uint8_t RUMBLE_OFF = 0x01; ///< flag: every request plays as a stop + static constexpr uint8_t SWAP_MOTORS = 0x02; ///< flag: Strong plays Weak's level and vice versa + static constexpr uint8_t KNOWN_FLAGS = + RUMBLE_OFF | SWAP_MOTORS; ///< every flag this firmware knows + static constexpr uint8_t DEFAULT_STRENGTH_PERCENT = 100; ///< as the host asks + static constexpr uint8_t MAX_STRENGTH_PERCENT = 200; ///< largest valid strength + + uint8_t flags{0}; ///< RUMBLE_OFF | SWAP_MOTORS + uint8_t strength_percent{DEFAULT_STRENGTH_PERCENT}; ///< 0..200: every motor's level x this / 100 + + /// @brief Whether every request plays as a stop (RUMBLE_OFF). + constexpr bool is_off() const { return flags & RUMBLE_OFF; } + /// @brief Whether the Strong and Weak motors trade places (SWAP_MOTORS). + constexpr bool swaps_motors() const { return flags & SWAP_MOTORS; } + /// @brief Whether apply() changes nothing (unknown flag bits are ignored). + constexpr bool is_neutral() const { + return (flags & KNOWN_FLAGS) == 0 && strength_percent == DEFAULT_STRENGTH_PERCENT; + } + + /// @brief Whether the options are in range; `why` (if given) says what is wrong: + /// "unknown rumble flags" / "strength out of range (0..200 %)". + bool valid(std::string *why = nullptr) const { + auto fail = [why](const char *reason) { + if (why) + *why = reason; + return false; + }; + if (flags & ~KNOWN_FLAGS) + return fail("unknown rumble flags"); + if (strength_percent > MAX_STRENGTH_PERCENT) + return fail("strength out of range (0..200 %)"); + return true; + } + + /** + * @brief The levels to play for a host's request (see the class notes). + * @param request The host's request, as it asked for it (never an + * already-applied state). + * @return All zero when off; otherwise every motor scaled by the strength + * (clamped to MAX_STRENGTH_PERCENT), Strong and Weak swapped when + * SWAP_MOTORS is set. Unknown flag bits are ignored. + */ + constexpr RumbleState apply(const RumbleState &request) const { + using Motor = RumbleState::Motor; + if (is_off()) + return RumbleState{}; + const uint8_t pct = std::min(strength_percent, MAX_STRENGTH_PERCENT); + const bool swap = swaps_motors(); + RumbleState out; + out.set(Motor::Strong, scale(request.level(swap ? Motor::Weak : Motor::Strong), pct)); + out.set(Motor::Weak, scale(request.level(swap ? Motor::Strong : Motor::Weak), pct)); + out.set(Motor::LeftTrigger, scale(request.level(Motor::LeftTrigger), pct)); + out.set(Motor::RightTrigger, scale(request.level(Motor::RightTrigger), pct)); + return out; + } + + constexpr bool operator==(const RumbleOptions &) const = default; + +private: + static constexpr uint8_t scale(uint8_t level, uint8_t percent) { + const uint32_t v = (uint32_t{level} * percent + 50) / 100; // round half up + return static_cast(std::min(v, RumbleState::LEVEL_MAX)); + } +}; + +static_assert(std::is_aggregate_v && std::is_trivially_copyable_v); + +} // 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 d5a8ce48bf..e1ecd309f5 100644 --- a/components/gamepad_map/test/gamepad_map_host_test.cpp +++ b/components/gamepad_map/test/gamepad_map_host_test.cpp @@ -1,5 +1,6 @@ // Host-buildable unit tests for the gamepad_map component (GamepadState, -// GamepadMap, the hid-rp conversion and GamepadProfiles). Build & run from the +// GamepadMap, the hid-rp conversion, RumbleOptions and GamepadProfiles, +// including the version 1 -> 2 file migration). Build & run from the // repository root (third-party headers are -isystem so their own warnings do // not fail the build): // @@ -20,6 +21,7 @@ #include #include #include +#include #include #include @@ -27,6 +29,7 @@ #include "gamepad_profiles.hpp" #include "gamepad_state_formatters.hpp" #include "gamepad_state_hid_rp.hpp" +#include "rumble_options.hpp" #include "rumble_state.hpp" static int failures = 0; @@ -381,6 +384,275 @@ static void test_rumble_state() { CHECK(!r.any() && r == RumbleState{}); } +static void test_rumble_options() { + using espp::RumbleOptions; + using espp::RumbleState; + using M = RumbleState::Motor; + constexpr auto make = [](uint8_t strong, uint8_t weak, uint8_t lt, uint8_t rt) { + RumbleState r; + r.set(M::Strong, strong); + r.set(M::Weak, weak); + r.set(M::LeftTrigger, lt); + r.set(M::RightTrigger, rt); + return r; + }; + constexpr RumbleState sample = make(200, 10, 5, 7); + static_assert(RumbleOptions{}.apply(sample) == sample); // neutral, at compile time + + // 100 % with no flags is the exact identity for every level on every motor + bool identity = true; + for (int level = 0; level <= 255; ++level) { + const auto l = static_cast(level); + identity = identity && RumbleOptions{}.apply(make(l, l, l, l)) == make(l, l, l, l); + } + CHECK(identity); + + // the parity table (the console's applyRumble() is tested against the same rows) + struct Row { + RumbleOptions o; + RumbleState in, out; + }; + constexpr uint8_t OFF = RumbleOptions::RUMBLE_OFF; + constexpr uint8_t SWAP = RumbleOptions::SWAP_MOTORS; + const Row rows[] = { + {{0, 100}, make(200, 10, 5, 7), make(200, 10, 5, 7)}, + {{OFF, 100}, make(200, 10, 5, 7), make(0, 0, 0, 0)}, + {{0, 0}, make(200, 10, 5, 7), make(0, 0, 0, 0)}, + {{0, 50}, make(255, 1, 3, 0), make(128, 1, 2, 0)}, + {{0, 1}, make(255, 1, 0, 0), make(3, 0, 0, 0)}, + {{0, 49}, make(1, 0, 0, 0), make(0, 0, 0, 0)}, + {{0, 150}, make(100, 200, 128, 0), make(150, 255, 192, 0)}, + {{0, 200}, make(127, 128, 255, 100), make(254, 255, 255, 200)}, + {{SWAP, 100}, make(200, 10, 5, 7), make(10, 200, 5, 7)}, + {{SWAP, 50}, make(200, 10, 5, 7), make(5, 100, 3, 4)}, + {{0xFC, 100}, make(200, 10, 5, 7), make(200, 10, 5, 7)}, // unknown bits only + {{0, 250}, make(100, 0, 0, 0), make(200, 0, 0, 0)}, // invalid: behaves as 200 + }; + for (const auto &row : rows) { + if (row.o.apply(row.in) != row.out) { + std::printf("FAIL rumble parity row {0x%02x, %u}\n", row.o.flags, row.o.strength_percent); + failures++; + } + } + + // a stop stays a stop for every option value + bool stop_safe = true; + for (uint8_t flags = 0; flags <= 3; ++flags) + for (int pct = 0; pct <= 200; ++pct) + stop_safe = stop_safe && RumbleOptions{flags, static_cast(pct)}.apply( + RumbleState{}) == RumbleState{}; + CHECK(stop_safe); + + // monotonic in the level and in the strength + bool monotonic = true; + for (int pct = 0; pct <= 200; ++pct) { + const RumbleOptions o{0, static_cast(pct)}; + for (int level = 1; level <= 255; ++level) + monotonic = + monotonic && o.apply(make(static_cast(level), 0, 0, 0)).level(M::Strong) >= + o.apply(make(static_cast(level - 1), 0, 0, 0)).level(M::Strong); + } + for (int level = 0; level <= 255; ++level) + for (int pct = 1; pct <= 200; ++pct) + monotonic = monotonic && RumbleOptions{0, static_cast(pct)} + .apply(make(static_cast(level), 0, 0, 0)) + .level(M::Strong) >= + RumbleOptions{0, static_cast(pct - 1)} + .apply(make(static_cast(level), 0, 0, 0)) + .level(M::Strong); + CHECK(monotonic); + + // swap twice at 100 % is the identity; swap and scaling commute + const RumbleOptions swap{SWAP, 100}; + CHECK(swap.apply(swap.apply(sample)) == sample); + CHECK((RumbleOptions{SWAP, 150}.apply(sample)) == + swap.apply(RumbleOptions{0, 150}.apply(sample))); + // off keeps the stored strength (turning it back on restores it) + const RumbleOptions off{OFF, 150}; + CHECK(off.is_off() && off.strength_percent == 150); + + // validation + std::string why; + CHECK((RumbleOptions{0x03, 200}.valid())); + CHECK(!(RumbleOptions{0x04, 100}.valid(&why)) && why == "unknown rumble flags"); + CHECK(!(RumbleOptions{0, 201}.valid(&why)) && why == "strength out of range (0..200 %)"); + // neutral: unknown bits ignored + CHECK(RumbleOptions{}.is_neutral() && (RumbleOptions{0xFC, 100}.is_neutral())); + CHECK(!(RumbleOptions{SWAP, 100}.is_neutral()) && !(RumbleOptions{0, 99}.is_neutral())); +} + +static std::vector read_file(const std::filesystem::path &path) { + std::ifstream in(path, std::ios::binary); + return {std::istreambuf_iterator(in), std::istreambuf_iterator()}; +} + +static uint32_t file_version(const std::filesystem::path &path) { + const auto bytes = read_file(path); + return bytes.size() < 8 ? 0 + : static_cast(bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | + (bytes[7] << 24)); +} + +static void test_profiles_rumble() { + namespace fs = std::filesystem; + using espp::RumbleOptions; + const fs::path dir = fs::temp_directory_path() / "gamepad_map_host_test_rumble"; + fs::remove_all(dir); + fs::create_directories(dir); + const fs::path file = dir / "profiles.bin"; + std::error_code ec; + const RumbleOptions swap150{.flags = RumbleOptions::SWAP_MOTORS, .strength_percent = 150}; + const RumbleOptions off{.flags = RumbleOptions::RUMBLE_OFF, .strength_percent = 100}; + const RumbleOptions half{.flags = 0, .strength_percent = 50}; + GamepadMap bsp; + bsp.swap(B::South, B::East); + { + // Config::default_rumble applies with no file, and nothing is written + espp::GamepadProfiles profiles({.file_path = file, .default_rumble = half}); + CHECK(profiles.default_rumble() == half && !fs::exists(file)); + CHECK(profiles.rumble_for(1, 2) == half); + } + { + // an invalid configured default becomes neutral + espp::GamepadProfiles profiles({.file_path = file, .default_rumble = {0, 250}}); + CHECK(profiles.default_rumble() == RumbleOptions{}); + } + { + espp::GamepadProfiles profiles({.file_path = file}); + CHECK(profiles.set_profile( + {.vid = 0x1949, .pid = 0x0402, .name = "BSP-D8", .map = bsp, .rumble = swap150}, ec)); + CHECK(profiles.rumble_for(0x1949, 0x0402) == swap150); + CHECK(profiles.rumble_for(0x045e, 0x0b13) == profiles.default_rumble()); + CHECK(profiles.set_default_rumble(half, ec) && profiles.default_rumble() == half); + GamepadMap inverted; + inverted.invert(A::LeftY); + CHECK(profiles.set_defaults(inverted, off, ec)); + CHECK(profiles.default_map() == inverted && profiles.default_rumble() == off); + CHECK(profiles.set_default_map(GamepadMap{}, ec) && profiles.default_rumble() == off); + } + { + // reloaded: everything persisted + espp::GamepadProfiles profiles({.file_path = file}); + CHECK(!profiles.load_error()); + CHECK(profiles.rumble_for(0x1949, 0x0402) == swap150); + CHECK(profiles.default_rumble() == off && profiles.default_map().is_identity()); + + // set_profile_map keeps a stored profile's rumble, changes its map + GamepadMap other; + other.left_deadzone_percent = 7; + CHECK(profiles.set_profile_map(0x1949, 0x0402, "BSP-D8", other, ec)); + CHECK(profiles.map_for(0x1949, 0x0402) == other && + profiles.rumble_for(0x1949, 0x0402) == swap150); + // ... and a new profile starts from the default rumble + CHECK(profiles.set_profile_map(0x0001, 0x0002, "new", other, ec)); + CHECK(profiles.rumble_for(0x0001, 0x0002) == off); + CHECK(!profiles.set_profile_map(0, 0, "", other, ec) && ec == std::errc::invalid_argument); + + // set_profile replaces the whole profile, rumble included + CHECK(profiles.set_profile({.vid = 0x0001, .pid = 0x0002, .name = "new", .map = other}, ec)); + CHECK(profiles.rumble_for(0x0001, 0x0002) == RumbleOptions{}); + + // invalid options are refused and nothing is written + const auto before = read_file(file); + CHECK(!profiles.set_profile({.vid = 3, .pid = 4, .name = "x", .map = {}, .rumble = {0x04, 100}}, + ec) && + ec == std::errc::invalid_argument); + CHECK(!profiles.set_default_rumble({0, 201}, ec) && ec == std::errc::invalid_argument); + CHECK(!profiles.set_defaults(GamepadMap{}, {0, 201}, ec) && ec == std::errc::invalid_argument); + CHECK(read_file(file) == before); + + // erase: the controller falls back to the default; reset: default neutral + CHECK(profiles.erase_profile(0x1949, 0x0402, "", ec)); + CHECK(profiles.rumble_for(0x1949, 0x0402) == off); + CHECK(profiles.reset(ec) && profiles.default_rumble() == RumbleOptions{}); + } + { + // full store: set_profile_map reports no_buffer_space + espp::GamepadProfiles profiles({.file_path = file, .max_profiles = 1}); + CHECK(profiles.set_profile_map(1, 1, "a", GamepadMap{}, ec)); + CHECK(!profiles.set_profile_map(2, 2, "b", GamepadMap{}, ec) && + ec == std::errc::no_buffer_space); + } + { + // stored options are sanitized: unknown bits cleared, strength clamped, the profile kept + espp::GamepadProfiles::Data d; + d.default_rumble = {0xFC, 250}; + d.profiles.push_back({.vid = 1, .pid = 2, .name = "ok", .map = {}, .rumble = {0x06, 255}}); + espp::GamepadProfiles::Storage raw({.file_path = file, .auto_load = false}); + CHECK(raw.save(d, ec)); + espp::GamepadProfiles profiles({.file_path = file}); + CHECK(!profiles.load_error()); + CHECK((profiles.default_rumble() == RumbleOptions{0x00, 200})); + CHECK(profiles.profile_count() == 1 && (profiles.rumble_for(1, 2) == RumbleOptions{0x02, 200})); + } + fs::remove_all(dir); +} + +static void test_profiles_v1_migration() { + namespace fs = std::filesystem; + using espp::RumbleOptions; + // A version 1 file as espp before rumble options wrote it (default map + // invert(LeftY); 1949:0402 "BSP-D8" swap(South, East); 0:0 "NoPnP" with a + // 12 % left dead zone), from GamepadProfiles::Storage::encode(). + static const uint8_t kV1File[] = { + 0x45, 0x53, 0x50, 0x44, 0x01, 0x00, 0x00, 0x00, 0x3b, 0xa1, 0xd1, 0x4e, 0x43, 0x00, 0x00, + 0x00, 0x4a, 0x32, 0xe8, 0x17, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x03, 0x01, 0x01, 0x00, + 0x9c, 0xff, 0x02, 0x00, 0x00, 0x00, 0x49, 0x19, 0x02, 0x04, 0x06, 0x00, 0x00, 0x00, 0x42, + 0x53, 0x50, 0x2d, 0x44, 0x38, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, + 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, + 0x00, 0x4e, 0x6f, 0x50, 0x6e, 0x50, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, + }; + // changing this means V1 files no longer load: GamepadProfileV1 / + // GamepadProfilesV1 (and GamepadMap / GamepadMapRule) are frozen + CHECK(espp::persistent_data::layout::fingerprint() == 0x4ed1a13b); + // a change to the V2 layout needs a V3 + CHECK(espp::GamepadProfiles::Storage::layout_fingerprint() == 0x64dff6d1); + CHECK(espp::GamepadProfiles::Storage::CURRENT_VERSION == 2); + + const fs::path dir = fs::temp_directory_path() / "gamepad_map_host_test_v1"; + fs::remove_all(dir); + fs::create_directories(dir); + const fs::path file = dir / "profiles.bin"; + { + std::ofstream out(file, std::ios::binary | std::ios::trunc); + out.write(reinterpret_cast(kV1File), sizeof(kV1File)); + } + std::error_code ec; + GamepadMap legacy; + legacy.invert(A::LeftY); + GamepadMap bsp; + bsp.swap(B::South, B::East); + GamepadMap named; + named.left_deadzone_percent = 12; + espp::GamepadProfiles::Data loaded; + { + // the configured default rumble does not apply to a migrated file + espp::GamepadProfiles profiles({.file_path = file, .default_rumble = {0, 50}}); + CHECK(!profiles.load_error()); + CHECK(profiles.default_map() == legacy); + CHECK(profiles.map_for(0x1949, 0x0402) == bsp && profiles.map_for(0, 0, "NoPnP") == named); + CHECK(profiles.default_rumble() == RumbleOptions{}); + CHECK(profiles.rumble_for(0x1949, 0x0402) == RumbleOptions{} && + profiles.rumble_for(0, 0, "NoPnP") == RumbleOptions{}); + CHECK(file_version(file) == 1); // not rewritten on load + CHECK(profiles.set_default_rumble(RumbleOptions{}, ec)); + CHECK(file_version(file) == 2); // the first change writes version 2 + loaded = profiles.data(); + } + { + espp::GamepadProfiles profiles({.file_path = file}); + const auto again = profiles.data(); + CHECK(!profiles.load_error() && again.default_map == loaded.default_map && + again.default_rumble == loaded.default_rumble && again.profiles == loaded.profiles); + } + { + // older firmware (V1 only) cannot read a version 2 file + espp::PersistentData old({.file_path = file, .auto_load = false}); + CHECK(!old.load(ec) && ec == espp::PersistentDataErrc::unknown_version); + } + fs::remove_all(dir); +} + int main() { test_state(); test_identity(); @@ -394,7 +666,10 @@ int main() { test_aliasing(); test_hid_rp_bridge(); test_rumble_state(); + test_rumble_options(); test_profiles(); + test_profiles_rumble(); + test_profiles_v1_migration(); if (failures == 0) { std::printf("gamepad_map_host_test: all checks passed\n"); return 0; diff --git a/components/gamepad_map/test/gamepad_map_protocol_host_test.cpp b/components/gamepad_map/test/gamepad_map_protocol_host_test.cpp index 4e1b8d5216..f580832899 100644 --- a/components/gamepad_map/test/gamepad_map_protocol_host_test.cpp +++ b/components/gamepad_map/test/gamepad_map_protocol_host_test.cpp @@ -21,6 +21,7 @@ namespace proto = espp::detail::gamepad_map_protocol; using espp::GamepadMap; using espp::GamepadMapRule; using espp::GamepadState; +using espp::RumbleOptions; using B = GamepadState::Button; using A = GamepadState::Axis; @@ -53,8 +54,9 @@ static void test_map_encoding() { const auto back = proto::decode_set_map(p); CHECK(back.has_value()); if (back) { - CHECK(back->first == t); - CHECK(back->second == m); + CHECK(back->target == t); + CHECK(back->map == m); + CHECK(!back->rumble); // the v1 form: the device keeps the stored rumble options } // the default target is one byte const Bytes def = proto::encode_get_map({}); @@ -72,7 +74,7 @@ static void test_map_encoding() { // 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()); + CHECK(invalid.has_value() && !invalid->map.valid()); // MAP: the target, the exists flag, the map; a host ignores appended fields Bytes reply = proto::encode_map_reply(t, false, m); @@ -87,6 +89,64 @@ static void test_map_encoding() { CHECK(decoded.has_value() && decoded->exists && !decoded->target.profile); } +// Rumble options (still protocol v1): SET_MAP's optional trailing block, MAP's +// flags bit1 + block, INFO's capability bit. +static void test_rumble_wire() { + 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 v1 = proto::encode_set_map(t, m); + + // SET_MAP: the v1 form is unchanged; with a block, [flags][strength] follows + const RumbleOptions off80{.flags = RumbleOptions::RUMBLE_OFF, .strength_percent = 80}; + Bytes with = proto::encode_set_map(t, m, off80); + Bytes expected = v1; + expected.insert(expected.end(), {0x01, 0x50}); + CHECK(with == expected); + auto back = proto::decode_set_map(with); + CHECK(back.has_value() && back->target == t && back->map == m && back->rumble == off80); + // default target, empty map, neutral options + CHECK(proto::encode_set_map({}, GamepadMap{}, RumbleOptions{}) == + (Bytes{0x00, 0x00, 0x00, 0x00, 0x00, 0x64})); + // exactly 0 or 2 bytes may follow the map + Bytes one = v1; + one.push_back(0x01); + CHECK(!proto::decode_set_map(one)); + Bytes three = with; + three.push_back(0x00); + CHECK(!proto::decode_set_map(three)); + // the layout decodes even when the options are invalid: valid() is the service's job + Bytes bad = v1; + bad.insert(bad.end(), {0xFF, 250}); + back = proto::decode_set_map(bad); + CHECK(back.has_value() && back->rumble.has_value() && !back->rumble->valid()); + + // MAP: flags bit1 + the block after the map + const RumbleOptions swap150{.flags = RumbleOptions::SWAP_MOTORS, .strength_percent = 150}; + Bytes reply = proto::encode_map_reply({}, true, GamepadMap{}, swap150); + CHECK(reply == (Bytes{0x00, 0x03, 0x00, 0x00, 0x00, 0x02, 0x96})); + auto decoded = proto::decode_map_reply(reply); + CHECK(decoded.has_value() && decoded->exists && decoded->rumble == swap150); + // bytes after the block are ignored (a later field) + Bytes longer = reply; + longer.push_back(0xAA); + decoded = proto::decode_map_reply(longer); + CHECK(decoded.has_value() && decoded->rumble == swap150); + // bit1 with no block, or a 1-byte block, is truncated + CHECK(!proto::decode_map_reply(Bytes{0x00, 0x03, 0x00, 0x00, 0x00})); + CHECK(!proto::decode_map_reply(Bytes{0x00, 0x03, 0x00, 0x00, 0x00, 0x02})); + // without bit1 there is no rumble, whatever follows the map + decoded = proto::decode_map_reply(Bytes{0x00, 0x01, 0x00, 0x00, 0x00, 0xAA, 0xBB}); + CHECK(decoded.has_value() && !decoded->rumble); + // a missing profile: exists 0 plus the default options + reply = proto::encode_map_reply(t, false, GamepadMap{}, RumbleOptions{}); + CHECK(reply.size() == 9 + 1 + 3 + 2 && reply[9] == 0x02 && reply[13] == 0x00 && + reply[14] == 0x64); +} + static void test_info() { proto::Info info{ .button_count = 22, .axis_count = 6, .max_rules = 64, .max_profiles = 16, .profile_count = 1}; @@ -101,11 +161,29 @@ static void test_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); + CHECK(!back->rumble_options); // flags bit1 clear: an older device 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)); + + // flags bit1: the device stores rumble options per map (adds no bytes) + proto::Info rumble_info{.button_count = 22, + .axis_count = 6, + .max_rules = 64, + .max_profiles = 16, + .profile_count = 1, + .rumble_options = true}; + p = proto::encode_info(rumble_info); + CHECK(p == (Bytes{22, 6, 64, 16, 1, 0x02})); + back = proto::decode_info(p); + CHECK(back.has_value() && *back == rumble_info); + rumble_info.controller = info.controller; + p = proto::encode_info(rumble_info); + CHECK(p == (Bytes{22, 6, 64, 16, 1, 0x03, 0x5e, 0x04, 0x13, 0x0b, 4, 'X', 'b', 'o', 'x', 1})); + back = proto::decode_info(p); + CHECK(back.has_value() && *back == rumble_info); } static void test_profiles() { @@ -177,6 +255,7 @@ static void test_erase_error_frame() { int main() { test_map_encoding(); + test_rumble_wire(); test_info(); test_profiles(); test_input_and_stream(); diff --git a/components/gamepad_map/test/gamepad_map_service_host_test.cpp b/components/gamepad_map/test/gamepad_map_service_host_test.cpp new file mode 100644 index 0000000000..bcab27357d --- /dev/null +++ b/components/gamepad_map/test/gamepad_map_service_host_test.cpp @@ -0,0 +1,255 @@ +// Host-buildable unit tests for GamepadMapService: requests go in through +// handle_frame(), replies are captured from `send` and parsed back; the store is +// a GamepadProfiles file in a temp directory. Covers the rumble options on the +// wire (INFO / MAP / SET_MAP, with and without the rumble block), the change +// callbacks, and a controller connecting while a change is being saved. 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 \ +// -I components/task/include -I components/dispatcher/include \ +// -I components/stream_frame/include \ +// -isystem components/serialization/detail/alpaca/include \ +// -isystem components/format/detail/fmt/include \ +// components/gamepad_map/test/gamepad_map_service_host_test.cpp \ +// components/logger/src/logger.cpp components/task/src/task.cpp -lpthread \ +// -o gamepad_map_service_host_test +// ./gamepad_map_service_host_test +// +// No ESP-IDF headers required. + +#include +#include +#include +#include +#include +#include + +#include "gamepad_map_service.hpp" + +namespace proto = espp::detail::gamepad_map_protocol; +using espp::GamepadMap; +using espp::GamepadMapService; +using espp::GamepadProfiles; +using espp::RumbleOptions; +using B = espp::GamepadState::Button; +using Type = proto::Type; +using Bytes = std::vector; + +static int failures = 0; +#define CHECK(cond) \ + do { \ + if (!(cond)) { \ + std::printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \ + failures++; \ + } \ + } while (0) + +// change() is protected: reach it to run a save that a controller connects during +class TestService : public GamepadMapService { +public: + using GamepadMapService::GamepadMapService; + template bool run_change(Save save) { return change(save); } +}; + +// Captures what the service sends and what the application is told. +struct Harness { + espp::stream_frame::StreamParser parser; + std::vector frames; + int map_calls{0}; + int rumble_calls{0}; + GamepadMap last_map{}; + RumbleOptions last_rumble{}; + + GamepadMapService::Config config(GamepadProfiles *profiles) { + return {.send = + [this](std::span f) { + auto parsed = parser.feed(f); + frames.insert(frames.end(), parsed.begin(), parsed.end()); + }, + .profiles = profiles, + .on_active_map_changed = + [this](const GamepadMap &m) { + ++map_calls; + last_map = m; + }, + .on_active_rumble_changed = + [this](const RumbleOptions &r) { + ++rumble_calls; + last_rumble = r; + }}; + } + void reset_calls() { map_calls = rumble_calls = 0; } + + // Send one request; return the (single) reply. + std::optional request(GamepadMapService &service, Type type, + const Bytes &payload = {}) { + frames.clear(); + service.handle_frame(static_cast(type), payload); + // (the service's `send` fills `frames` from inside handle_frame()) + // cppcheck-suppress knownConditionTrueFalse + if (frames.size() != 1) + return std::nullopt; + return frames.front(); + } +}; + +static bool is_ok(const std::optional &f) { + return f && f->type == static_cast(Type::Ok); +} + +// ERROR: [request type u8][code u32][message] +static bool is_error(const std::optional &f, uint32_t code, + const std::string &message_prefix) { + if (!f || f->type != static_cast(Type::Error) || f->payload.size() < 5) + return false; + const auto &p = f->payload; + const uint32_t got = static_cast(p[1] | (p[2] << 8) | (p[3] << 16) | (p[4] << 24)); + const std::string message(p.begin() + 5, p.end()); + return got == code && message.rfind(message_prefix, 0) == 0; +} + +static std::optional get_map(Harness &h, GamepadMapService &s, + const proto::Target &t) { + const auto f = h.request(s, Type::GetMap, proto::encode_get_map(t)); + if (!f || f->type != static_cast(Type::Map)) + return std::nullopt; + return proto::decode_map_reply(f->payload); +} + +int main() { + namespace fs = std::filesystem; + const fs::path dir = fs::temp_directory_path() / "gamepad_map_service_host_test"; + fs::remove_all(dir); + fs::create_directories(dir); + std::error_code ec; + + const proto::Target def{}; + const proto::Target x{.profile = true, .vid = 0x1949, .pid = 0x0402, .name = "BSP-D8"}; + const proto::Target y{.profile = true, .vid = 0x045e, .pid = 0x0b13, .name = "Xbox"}; + const RumbleOptions off100{.flags = RumbleOptions::RUMBLE_OFF, .strength_percent = 100}; + const RumbleOptions swap150{.flags = RumbleOptions::SWAP_MOTORS, .strength_percent = 150}; + const RumbleOptions p150{.flags = 0, .strength_percent = 150}; + GamepadMap swapped; + swapped.swap(B::South, B::East); + + GamepadProfiles profiles({.file_path = dir / "profiles.bin"}); + Harness h; + TestService service(h.config(&profiles)); + + // 1. INFO advertises rumble options (flags bit1) + { + const auto f = h.request(service, Type::GetInfo); + CHECK(f && f->type == static_cast(Type::Info)); + if (f) { + const auto info = proto::decode_info(f->payload); + CHECK(info && info->rumble_options); + } + } + + // 2. MAP always carries the rumble block + { + auto m = get_map(h, service, def); + CHECK(m && m->exists && m->rumble == RumbleOptions{}); // default target: neutral + CHECK(profiles.set_default_rumble(p150, ec)); + m = get_map(h, service, x); + CHECK(m && !m->exists && m->rumble == p150); // missing profile: the default options + CHECK( + profiles.set_profile({.vid = x.vid, .pid = x.pid, .name = x.name, .rumble = swap150}, ec)); + m = get_map(h, service, x); + CHECK(m && m->exists && m->rumble == swap150); // the profile's own + } + + // 3. SET_MAP with a block saves map + rumble together + { + CHECK(is_ok(h.request(service, Type::SetMap, proto::encode_set_map(x, swapped, off100)))); + const auto m = get_map(h, service, x); + CHECK(m && m->map == swapped && m->rumble == off100); + } + + // 4. SET_MAP without a block (an older host) keeps the stored options + { + CHECK(is_ok(h.request(service, Type::SetMap, proto::encode_set_map(x, GamepadMap{})))); + CHECK(profiles.map_for(x.vid, x.pid).is_identity() && + profiles.rumble_for(x.vid, x.pid) == off100); + // a new profile starts from the default options (150 %) + CHECK(is_ok(h.request(service, Type::SetMap, proto::encode_set_map(y, swapped)))); + CHECK(profiles.rumble_for(y.vid, y.pid) == p150); + // the default target keeps the default options + CHECK(is_ok(h.request(service, Type::SetMap, proto::encode_set_map(def, swapped)))); + CHECK(profiles.default_map() == swapped && profiles.default_rumble() == p150); + } + + // 5. invalid options are refused, nothing saved; a short block is malformed + { + const auto before = profiles.rumble_for(x.vid, x.pid); + CHECK(is_error(h.request(service, Type::SetMap, + proto::encode_set_map(x, GamepadMap{}, RumbleOptions{0, 201})), + 22, "invalid rumble options")); + CHECK(is_error(h.request(service, Type::SetMap, + proto::encode_set_map(x, GamepadMap{}, RumbleOptions{0x04, 100})), + 22, "invalid rumble options")); + Bytes one = proto::encode_set_map(x, GamepadMap{}); + one.push_back(0x01); + CHECK(is_error(h.request(service, Type::SetMap, one), 22, "malformed SET_MAP")); + CHECK(profiles.rumble_for(x.vid, x.pid) == before); + } + + // 6. callbacks fire only for the connected controller's own changes + { + h.reset_calls(); + // nothing connected: nothing fires + CHECK(is_ok(h.request(service, Type::SetMap, proto::encode_set_map(x, swapped, swap150)))); + CHECK(h.map_calls == 0 && h.rumble_calls == 0); + + service.set_controller(x.vid, x.pid, x.name); + CHECK(service.active_rumble() == swap150); + h.reset_calls(); + // X's rumble only + CHECK(is_ok(h.request(service, Type::SetMap, proto::encode_set_map(x, swapped, off100)))); + CHECK(h.rumble_calls == 1 && h.last_rumble == off100 && h.map_calls == 0); + h.reset_calls(); + // X's map only (the v1 form keeps the rumble) + CHECK(is_ok(h.request(service, Type::SetMap, proto::encode_set_map(x, GamepadMap{})))); + CHECK(h.map_calls == 1 && h.last_map.is_identity() && h.rumble_calls == 0); + h.reset_calls(); + // another profile: nothing + CHECK(is_ok(h.request(service, Type::SetMap, proto::encode_set_map(y, swapped, swap150)))); + CHECK(h.map_calls == 0 && h.rumble_calls == 0); + // erasing X's profile: X falls back to the default options (150 %) + CHECK(is_ok( + h.request(service, Type::EraseProfile, proto::encode_erase_profile(x.vid, x.pid, x.name)))); + CHECK(h.rumble_calls == 1 && h.last_rumble == p150); + h.reset_calls(); + // reset: neutral + CHECK(is_ok(h.request(service, Type::ResetAll))); + CHECK(h.rumble_calls == 1 && h.last_rumble == RumbleOptions{}); + service.clear_controller(); + } + + // 7. a controller that connects while a change is saved is told about it + { + h.reset_calls(); + GamepadMap m2; + m2.left_deadzone_percent = 9; + CHECK(service.run_change([&] { + service.set_controller(x.vid, x.pid, x.name); // looks up the map before the save lands + return profiles.set_profile( + {.vid = x.vid, .pid = x.pid, .name = x.name, .map = m2, .rumble = swap150}, ec); + })); + CHECK(h.map_calls == 1 && h.last_map == m2); + CHECK(h.rumble_calls == 1 && h.last_rumble == swap150); + service.clear_controller(); + } + + fs::remove_all(dir); + if (failures == 0) { + std::printf("gamepad_map_service_host_test: all checks passed\n"); + return 0; + } + std::printf("gamepad_map_service_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 index 56979327c2..0e70e9c01a 100644 --- a/components/gamepad_map/web/gamepad_map_console.html +++ b/components/gamepad_map/web/gamepad_map_console.html @@ -4,7 +4,7 @@ espp Gamepad Map Console (WebUSB / Web Serial) - + @@ -16,9 +16,10 @@ game controller, remaps its buttons / axes with an espp::GamepadMap and sends the result on. The map for each controller type (by USB / Bluetooth VID:PID, or by name) and a default map live on the device in an - espp::GamepadProfiles store; this page views and edits them and shows the - controller's input before and after mapping, over EITHER WebUSB (vendor - 0xFF interface) OR Web Serial. + espp::GamepadProfiles store, each with its per-controller rumble options + (off / strength / swap motors) for the host's rumble the device forwards; + this page views and edits them and shows the controller's input before and + after mapping, over EITHER WebUSB (vendor 0xFF interface) OR Web Serial. Framed with the espp stream_frame v2 codec, routed on module id 11 by default (a routing key; the id actually used is discovered from the device, @@ -28,7 +29,11 @@ SET_STREAM, RESET_ALL), replies / events 0x81..0x86 (INFO, MAP, OK, ERROR, PROFILES, INPUT). The input stream is a lease: the page renews it every few seconds while "Live input" is on and the device stops by itself when a - closed page stops renewing it. + closed page stops renewing it. Rumble options leave the protocol at v1: + firmware that stores them sets INFO / MAP flags bit1 and appends them to + MAP; the Rumble row saves them in the same SET_MAP as the map, and stays + disabled for firmware without them (whose SET_MAP then goes out in the + form it always had). -->