diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index fce12b8f1b..a54a1b6819 100755 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -183,6 +183,9 @@ jobs: target: esp32s3 - path: 'components/gamepad_map/example' target: esp32s3 + - path: 'components/gamepad_map/webapp_example' + target: esp32s3 + command: 'IDF_COMPONENT_MANAGER=0 idf.py build' - path: 'components/gfps_service/example' target: esp32s3 - path: 'components/gps/example' diff --git a/.github/workflows/gamepad_map_tests.yml b/.github/workflows/gamepad_map_tests.yml index ac7219ea44..01b6b76a2a 100644 --- a/.github/workflows/gamepad_map_tests.yml +++ b/.github/workflows/gamepad_map_tests.yml @@ -6,6 +6,10 @@ name: Gamepad map host test # file round trip) # - components/hid-rp/test/hid_rp_report_map_host_test.cpp (the runtime # report map + Gamepad / Keyboard / Mouse decoders the map is fed from) +# - components/gamepad_map/test/gamepad_map_protocol_host_test.cpp (the +# GamepadMapService wire protocol codec) +# - components/gamepad_map/web/test/gamepad_map_codec_test.js (the web +# console's copy of that codec, with node) # Runs whenever either component, or what they store / log with, changes. # Minimal token scope: build + run tests, never writes. @@ -22,6 +26,7 @@ on: - "components/logger/**" - "components/format/**" - "components/base_component/**" + - "components/stream_frame/**" - ".github/workflows/gamepad_map_tests.yml" push: branches: @@ -34,6 +39,7 @@ on: - "components/logger/**" - "components/format/**" - "components/base_component/**" + - "components/stream_frame/**" - ".github/workflows/gamepad_map_tests.yml" workflow_dispatch: @@ -73,3 +79,14 @@ jobs: components/gamepad_map/test/gamepad_map_host_test.cpp components/logger/src/logger.cpp \ -o gamepad_map_host_test ./gamepad_map_host_test + - name: Build and run gamepad_map_protocol_host_test + run: | + g++ -std=c++23 -Wall -Wextra -Werror \ + -I components/gamepad_map/include -I components/stream_frame/include \ + components/gamepad_map/test/gamepad_map_protocol_host_test.cpp \ + -o gamepad_map_protocol_host_test + ./gamepad_map_protocol_host_test + - name: Run the web console codec test + run: | + node --version + node components/gamepad_map/web/test/gamepad_map_codec_test.js diff --git a/components/dispatcher/README.md b/components/dispatcher/README.md index 8463f2d455..e1ea2e88c7 100644 --- a/components/dispatcher/README.md +++ b/components/dispatcher/README.md @@ -32,6 +32,8 @@ protocols and examples use these ids by default: | 7 | System info / reboot (`espp::SystemService`) | `espp.system` v1 | | 8 | Heap / task monitor (`espp::MonitorService`) | `espp.monitor` v1 | | 9 | Windowed desktop (`espp::DesktopService`) | `espp.desktop` v2 | +| 10 | VL53L5CX ToF console (`espp::Vl53l5cxService`) | `espp.vl53l5cx` v1 | +| 11 | Gamepad map (`espp::GamepadMapService`) | `espp.gamepad_map` v1 | | 0xF0–0xFE | reserved (meta) | — | | 0xFF | capability discovery | — | diff --git a/components/dispatcher/web/test/apps_registry_test.js b/components/dispatcher/web/test/apps_registry_test.js index bbcd264485..0ceed597c7 100644 --- a/components/dispatcher/web/test/apps_registry_test.js +++ b/components/dispatcher/web/test/apps_registry_test.js @@ -61,7 +61,8 @@ for (const p of pages) { // constants are declared as `PROTOCOL = "id", PROTOCOL_VERSION = n` // with the same (possibly empty) prefix, e.g. OTA_PROTOCOL / OTA_PROTOCOL_VERSION // or the bare PROTOCOL / PROTOCOL_VERSION pair - for (const m of src.matchAll(/\b[A-Z0-9_]*PROTOCOL\s*=\s*"(espp\.[a-z0-9.-]+)"/g)) idsInScript.add(m[1]); + // (ids may contain `_`, e.g. espp.gamepad_map, as the generator's PROTOCOL_RE allows) + for (const m of src.matchAll(/\b[A-Z0-9_]*PROTOCOL\s*=\s*"(espp\.[a-z0-9._-]+)"/g)) idsInScript.add(m[1]); for (const id of idsInScript) assert.ok(protocols.some((p) => p.id === id), rel + ": script defines protocol " + id + " not declared in espp-protocols"); // and the version it implements: every declared protocol must have its pair for (const pr of protocols) { diff --git a/components/dispatcher/web/test/resolve_module_id_test.js b/components/dispatcher/web/test/resolve_module_id_test.js index 83b0b18185..a40de36e55 100644 --- a/components/dispatcher/web/test/resolve_module_id_test.js +++ b/components/dispatcher/web/test/resolve_module_id_test.js @@ -27,6 +27,7 @@ const consoles = [ "components/system/web/system_console.html", "components/desktop/web/desktop.html", "components/vl53l/web/vl53l5cx_console.html", + "components/gamepad_map/web/gamepad_map_console.html", ]; const hub = "components/dispatcher/web/dispatcher_hub.html"; diff --git a/components/gamepad_map/CMakeLists.txt b/components/gamepad_map/CMakeLists.txt index eddea4ac62..d54a52368b 100644 --- a/components/gamepad_map/CMakeLists.txt +++ b/components/gamepad_map/CMakeLists.txt @@ -1,4 +1,4 @@ idf_component_register( INCLUDE_DIRS "include" - REQUIRES base_component format hid-rp persistent_data + REQUIRES base_component dispatcher format hid-rp persistent_data stream_frame task ) diff --git a/components/gamepad_map/README.md b/components/gamepad_map/README.md index ae028bb0eb..aa0b9f1366 100644 --- a/components/gamepad_map/README.md +++ b/components/gamepad_map/README.md @@ -18,8 +18,9 @@ whatever comes next (an emulated USB controller, an emulator's input). - [Rules](#rules) - [Profiles](#profiles) - [From a HID gamepad](#from-a-hid-gamepad) + - [Web console](#web-console) - [Host test](#host-test) - - [Example](#example) + - [Examples](#examples) @@ -32,6 +33,7 @@ whatever comes next (an emulated USB controller, an emulator's input). | `espp::GamepadMap` | Stick dead zones plus a list of rules; `apply()` maps one state to another | | `espp::GamepadProfiles` | A default map plus one map per controller type, saved in a file | | `espp::to_gamepad_state()` | A state from a `hid_rp::GamepadReport` (`gamepad_state_hid_rp.hpp`) | +| `espp::GamepadMapService` | Serves a `GamepadProfiles` store to the web console (dispatcher module 11) | Everything except `GamepadProfiles` is header-only plain data with no allocation in `apply()`, so it can run on every report. @@ -122,15 +124,49 @@ if (decoder.update(report_id, payload, report)) // BLE: the ID comes out of ba send(map.apply(espp::to_gamepad_state(report))); ``` +## Web console + +`espp::GamepadMapService` serves a `GamepadProfiles` store over any framed byte +stream (WebUSB vendor, Web Serial CDC...) through an `espp::Dispatcher`. Its +protocol is `espp.gamepad_map` v1 on module 11 by default +(`include/detail/gamepad_map_protocol.hpp` is the wire spec). The hosted +[Gamepad Map Console](https://esp-cpp.github.io/espp/apps/gamepad_map_console.html) +uses it to edit the maps and to show the controller's input before and after +mapping, live. The application tells the service about the controller and feeds +it the input: + +```cpp +espp::GamepadMapService service({.send = send_to_host, + .profiles = &profiles, + .on_active_map_changed = [&](const espp::GamepadMap &m) { + std::lock_guard lock(map_mutex); + active_map = m; // the console changed this controller's map + }}); +dispatcher.register_module(service); + +{ + std::lock_guard lock(map_mutex); // the callback above may run on another thread + active_map = service.set_controller(vid, pid, name); // on connect; clear_controller() on disconnect +} +// for every report: +service.publish_input(raw, mapped); // a 32-byte copy under a lock; never sends +``` + +The INPUT stream ends by itself when the host stops renewing it +(`Config::stream_lease`), so a closed browser tab does not leave it running. + ## Host test `test/gamepad_map_host_test.cpp` covers the rule semantics, validation, the hid-rp conversion (with a real BLE gamepad's descriptor) and the profile store's -file round trip. The build command is at the top of the file, and CI runs it in +file round trip. `test/gamepad_map_protocol_host_test.cpp` checks the wire +protocol against golden encodings. The build command is at the top of the file, and CI runs it in `.github/workflows/gamepad_map_tests.yml` together with the hid-rp report-map test. -## Example +## Examples -The [example](./example) decodes a BLE gamepad report, remaps it, and stores -per-controller profiles on a LittleFS partition. +- [example](./example) decodes a BLE gamepad report, remaps it, and stores + per-controller profiles on a LittleFS partition. +- [webapp_example](./webapp_example) serves the profiles over USB (WebUSB / + Web Serial) to the Gamepad Map Console, with a demo controller. diff --git a/components/gamepad_map/idf_component.yml b/components/gamepad_map/idf_component.yml index 20efd4f705..c2b2045220 100644 --- a/components/gamepad_map/idf_component.yml +++ b/components/gamepad_map/idf_component.yml @@ -8,6 +8,7 @@ maintainers: documentation: "https://esp-cpp.github.io/espp/input/gamepad_map.html" examples: - path: example + - path: webapp_example tags: - cpp - Component @@ -18,7 +19,10 @@ dependencies: idf: version: '>=5.0' espp/base_component: '>=1.0' + espp/dispatcher: '>=1.0' espp/format: '>=1.0' # GamepadReport::lt / rt / capture and GamepadDecoder::set_combine_controls() espp/hid-rp: '>=1.4.6' espp/persistent_data: '>=1.0' + espp/stream_frame: '>=1.0' + espp/task: '>=1.0' diff --git a/components/gamepad_map/include/detail/gamepad_map_protocol.hpp b/components/gamepad_map/include/detail/gamepad_map_protocol.hpp new file mode 100644 index 0000000000..80fff7953e --- /dev/null +++ b/components/gamepad_map/include/detail/gamepad_map_protocol.hpp @@ -0,0 +1,533 @@ +#pragma once + +// Wire protocol of espp::GamepadMapService: view and edit the gamepad maps of +// an espp::GamepadProfiles store, and watch a controller's input before and +// after mapping, over the espp stream_frame codec. Routed by an +// espp::Dispatcher on module 11 by default (`espp.gamepad_map` v1 through +// discovery). +// +// This header is deliberately host-buildable (stream_frame.hpp, gamepad_map.hpp +// and the standard library only) so the codec is unit-tested on the host +// (components/gamepad_map/test/gamepad_map_protocol_host_test.cpp) and so host +// tools can reuse it. All multi-byte fields are little-endian; a `str` is +// [len u8][utf8 bytes]. +// +// Shared encodings: +// target [kind u8] 0 = the default map (nothing follows) +// [kind u8 = 1][vid u16][pid u16][name str] +// 1 = the profile for that controller type +// (VID and PID 0: matched by name) +// map [left_deadzone u8][right_deadzone u8][rule_count u8] +// {[kind u8][source u8][target u8][flags u8][param i16]} x rule_count +// (GamepadMapRule field for field; 6 bytes per rule) +// state [buttons u32][left_x i16][left_y i16][right_x i16][right_y i16] +// [left_trigger i16][right_trigger i16] (16 bytes) +// +// Requests (host -> device, reply flag clear): +// 0x01 GET_INFO (no payload) +// 0x02 GET_MAP [target] +// 0x03 SET_MAP [target][map] validated, then saved; a profile +// target adds or replaces that profile +// 0x04 ERASE_PROFILE [vid u16][pid u16][name str] +// 0x05 LIST_PROFILES (no payload) +// 0x06 SET_STREAM [enable u8][period_ms u16] +// INPUT events every period while enabled; the device +// clamps the period to its minimum and stops by itself +// when no SET_STREAM enable renews the stream within its +// lease (GamepadMapService::Config::stream_lease), so a +// closed page does not leave it streaming +// 0x07 RESET_ALL (no payload) every profile erased, default = identity +// Replies / events (device -> host, high bit set = frame reply flag): +// 0x81 INFO [button_count u8][axis_count u8][max_rules u8] +// [max_profiles u8][profile_count u8][flags u8] +// flags bit0 = a controller is connected, then: +// [vid u16][pid u16][name str][has_profile u8] +// Answers GET_INFO, and is also sent unsolicited (no +// correlation id) when the INPUT stream starts and when the +// connected controller changes while it is on. +// 0x82 MAP [target][flags u8][map] (GET_MAP; the target as requested, +// the profile's stored name if it +// exists; flags bit0 = it exists. A +// profile that does not exist answers +// with the map its controller uses +// today, the default map, exists 0) +// 0x83 OK [request_type u8] +// 0x84 ERROR [request_type u8][code u32][utf8 message] +// code = the POSIX errno value of the std::errc the service +// chose (informational; the message is authoritative) +// 0x85 PROFILES [count u8]{[vid u16][pid u16][name str][rule_count u8]} +// 0x86 INPUT [flags u8][raw state][mapped state] +// flags bit0 = a controller is connected, bit1 = the state +// changed since the previous INPUT event (streamed only) +// Replies echo the request frame's correlation id (if it carried one); +// streamed INPUT events and unsolicited INFO carry none. +// +// Compatibility: the device rejects trailing bytes in a request (a request +// 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. + +#include +#include +#include +#include +#include +#include + +#include "gamepad_map.hpp" +#include "gamepad_state.hpp" +#include "stream_frame.hpp" + +namespace espp::detail::gamepad_map_protocol { + +/// Default dispatcher module id (a routing key only; see GamepadMapService::Config::module). +inline constexpr uint8_t kModule = 11; +/// Stable protocol identifier + version advertised through discovery. +inline constexpr const char *kProtocol = "espp.gamepad_map"; +inline constexpr uint16_t kProtocolVersion = 1; + +/// Frame `type` values within the gamepad map module. +enum class Type : uint8_t { + // host -> device + GetInfo = 0x01, + GetMap = 0x02, + SetMap = 0x03, + EraseProfile = 0x04, + ListProfiles = 0x05, + SetStream = 0x06, + ResetAll = 0x07, + // device -> host (high bit set) + Info = 0x81, + Map = 0x82, + Ok = 0x83, + Error = 0x84, + Profiles = 0x85, + Input = 0x86, +}; + +/// INFO / INPUT flag: a controller is connected. +inline constexpr uint8_t kFlagConnected = 0x01; +/// INPUT flag: the state changed since the previous INPUT event. +inline constexpr uint8_t kFlagChanged = 0x02; +/// MAP flag: the requested map exists (a profile that does not answers with the default map). +inline constexpr uint8_t kFlagExists = 0x01; + +/// Bytes of an encoded GamepadState. +inline constexpr size_t kStateSize = 16; +/// Bytes of one encoded GamepadMapRule. +inline constexpr size_t kRuleSize = 6; + +/// Which map a GET_MAP / SET_MAP addresses. +struct Target { + bool profile{false}; ///< false = the default map + uint16_t vid{0}; + uint16_t pid{0}; + std::string name{}; + bool operator==(const Target &) const = default; +}; + +/// The connected controller, as carried in INFO. +struct Controller { + uint16_t vid{0}; + uint16_t pid{0}; + std::string name{}; + bool has_profile{false}; + bool operator==(const Controller &) const = default; +}; + +/// Decoded INFO. +struct Info { + uint8_t button_count{0}; + uint8_t axis_count{0}; + uint8_t max_rules{0}; + uint8_t max_profiles{0}; + uint8_t profile_count{0}; + std::optional controller{}; + bool operator==(const Info &) const = default; +}; + +/// One entry of PROFILES. +struct ProfileSummary { + uint16_t vid{0}; + uint16_t pid{0}; + std::string name{}; + uint8_t rule_count{0}; + bool operator==(const ProfileSummary &) const = default; +}; + +/// Decoded SET_STREAM. +struct StreamRequest { + bool enable{false}; + uint16_t period_ms{0}; +}; + +/// Decoded INPUT. +struct Input { + bool connected{false}; + bool changed{false}; + GamepadState raw{}; + GamepadState mapped{}; +}; + +/// Whether a type value is a device->host reply / event. +inline constexpr bool is_reply(Type type) { return (static_cast(type) & 0x80) != 0; } + +/// Build an encoded frame for a gamepad map message (device->host types map to +/// the frame reply flag). +inline std::vector build_frame(Type type, std::span payload = {}, + uint8_t module = kModule, + std::optional correlation = std::nullopt) { + return espp::stream_frame::build_frame(is_reply(type), module, static_cast(type), + payload, correlation); +} + +// ---- byte helpers ------------------------------------------------------------- + +/// Reads little-endian fields from a payload; every read fails (and keeps +/// failing) once the payload is exhausted. +class Reader { +public: + explicit Reader(std::span data) + : data_(data) {} + bool u8(uint8_t &v) { + if (!have(1)) + return false; + v = data_[pos_++]; + return true; + } + bool u16(uint16_t &v) { + if (!have(2)) + return false; + v = static_cast(data_[pos_] | (data_[pos_ + 1] << 8)); + pos_ += 2; + return true; + } + bool i16(int16_t &v) { + uint16_t u = 0; + if (!u16(u)) + return false; + v = static_cast(u); + return true; + } + bool u32(uint32_t &v) { + if (!have(4)) + return false; + v = static_cast(data_[pos_]) | (static_cast(data_[pos_ + 1]) << 8) | + (static_cast(data_[pos_ + 2]) << 16) | + (static_cast(data_[pos_ + 3]) << 24); + pos_ += 4; + return true; + } + bool str(std::string &s) { + uint8_t n = 0; + if (!u8(n) || !have(n)) + return false; + s.assign(reinterpret_cast(data_.data() + pos_), n); + pos_ += n; + return true; + } + bool done() const { return ok_ && pos_ == data_.size(); } + /// For device -> host messages: every known field was read (trailing bytes, + /// fields of a later protocol version, are ignored). + bool known_fields_read() const { return ok_; } + +private: + bool have(size_t n) { + if (!ok_ || data_.size() - pos_ < n) { + ok_ = false; + return false; + } + return true; + } + std::span data_; + size_t pos_{0}; + bool ok_{true}; +}; + +inline void put_u8(std::vector &out, uint8_t v) { out.push_back(v); } +inline void put_u16(std::vector &out, uint16_t v) { + out.push_back(static_cast(v & 0xFF)); + out.push_back(static_cast(v >> 8)); +} +inline void put_i16(std::vector &out, int16_t v) { + put_u16(out, static_cast(v)); +} +inline void put_u32(std::vector &out, uint32_t v) { + for (int i = 0; i < 4; i++) + out.push_back(static_cast((v >> (8 * i)) & 0xFF)); +} +/// Append a [len u8][bytes] string (truncated to 255 bytes). +inline void put_str(std::vector &out, std::string_view s) { + const size_t n = s.size() > 255 ? 255 : s.size(); + out.push_back(static_cast(n)); + out.insert(out.end(), s.begin(), s.begin() + static_cast(n)); +} + +// ---- shared encodings ----------------------------------------------------------- + +inline void put_target(std::vector &out, const Target &t) { + put_u8(out, t.profile ? 1 : 0); + if (!t.profile) + return; + put_u16(out, t.vid); + put_u16(out, t.pid); + put_str(out, t.name); +} +inline bool read_target(Reader &r, Target &t) { + uint8_t kind = 0; + if (!r.u8(kind) || kind > 1) + return false; + t = {}; + if (kind == 0) + return true; + t.profile = true; + return r.u16(t.vid) && r.u16(t.pid) && r.str(t.name); +} + +/// Encode a map. At most 255 rules are written (a valid map has far fewer). +inline void put_map(std::vector &out, const GamepadMap &m) { + const size_t n = m.rules.size() > 255 ? 255 : m.rules.size(); + put_u8(out, m.left_deadzone_percent); + put_u8(out, m.right_deadzone_percent); + put_u8(out, static_cast(n)); + for (size_t i = 0; i < n; i++) { + const auto &rule = m.rules[i]; + put_u8(out, static_cast(rule.kind)); + put_u8(out, rule.source); + put_u8(out, rule.target); + put_u8(out, rule.flags); + put_i16(out, rule.param); + } +} +/// Decode a map. Only the layout is checked here; check the result with +/// GamepadMap::valid() before using it. +inline bool read_map(Reader &r, GamepadMap &m) { + uint8_t count = 0; + m = {}; + if (!r.u8(m.left_deadzone_percent) || !r.u8(m.right_deadzone_percent) || !r.u8(count)) + return false; + m.rules.reserve(count); + for (uint8_t i = 0; i < count; i++) { + uint8_t kind = 0; + GamepadMapRule rule; + if (!r.u8(kind) || !r.u8(rule.source) || !r.u8(rule.target) || !r.u8(rule.flags) || + !r.i16(rule.param)) + return false; + rule.kind = static_cast(kind); + m.rules.push_back(rule); + } + return true; +} + +inline void put_state(std::vector &out, const GamepadState &s) { + put_u32(out, s.buttons); + for (const int16_t a : s.axes) + put_i16(out, a); +} +inline bool read_state(Reader &r, GamepadState &s) { + if (!r.u32(s.buttons)) + return false; + for (auto &a : s.axes) + if (!r.i16(a)) + return false; + return true; +} + +// ---- requests (host -> device) -------------------------------------------------- + +inline std::vector encode_get_map(const Target &t) { + std::vector p; + put_target(p, t); + return p; +} +inline std::optional decode_get_map(std::span payload) { + Reader r(payload); + Target t; + if (!read_target(r, t) || !r.done()) + return std::nullopt; + return t; +} + +inline std::vector encode_set_map(const Target &t, const GamepadMap &m) { + std::vector p; + put_target(p, t); + put_map(p, m); + return p; +} +inline std::optional> +decode_set_map(std::span payload) { + Reader r(payload); + Target t; + GamepadMap m; + if (!read_target(r, t) || !read_map(r, m) || !r.done()) + return std::nullopt; + return std::make_pair(std::move(t), std::move(m)); +} + +inline std::vector encode_erase_profile(uint16_t vid, uint16_t pid, + std::string_view name) { + std::vector p; + put_u16(p, vid); + put_u16(p, pid); + put_str(p, name); + return p; +} +inline std::optional decode_erase_profile(std::span payload) { + Reader r(payload); + Target t; + t.profile = true; + if (!r.u16(t.vid) || !r.u16(t.pid) || !r.str(t.name) || !r.done()) + return std::nullopt; + return t; +} + +inline std::vector encode_set_stream(bool enable, uint16_t period_ms) { + std::vector p; + put_u8(p, enable ? 1 : 0); + put_u16(p, period_ms); + return p; +} +inline std::optional decode_set_stream(std::span payload) { + Reader r(payload); + uint8_t enable = 0; + StreamRequest s; + if (!r.u8(enable) || enable > 1 || !r.u16(s.period_ms) || !r.done()) + return std::nullopt; + s.enable = enable != 0; + return s; +} + +// ---- replies / events (device -> host) ----------------------------------------- + +inline std::vector encode_info(const Info &info) { + std::vector p; + put_u8(p, info.button_count); + put_u8(p, info.axis_count); + put_u8(p, info.max_rules); + put_u8(p, info.max_profiles); + put_u8(p, info.profile_count); + put_u8(p, info.controller ? kFlagConnected : 0); + if (info.controller) { + put_u16(p, info.controller->vid); + put_u16(p, info.controller->pid); + put_str(p, info.controller->name); + put_u8(p, info.controller->has_profile ? 1 : 0); + } + return p; +} +inline std::optional decode_info(std::span payload) { + Reader r(payload); + Info info; + uint8_t flags = 0; + if (!r.u8(info.button_count) || !r.u8(info.axis_count) || !r.u8(info.max_rules) || + !r.u8(info.max_profiles) || !r.u8(info.profile_count) || !r.u8(flags)) + return std::nullopt; + if (flags & kFlagConnected) { + Controller c; + uint8_t has = 0; + if (!r.u16(c.vid) || !r.u16(c.pid) || !r.str(c.name) || !r.u8(has)) + return std::nullopt; + c.has_profile = has != 0; + info.controller = std::move(c); + } + if (!r.known_fields_read()) + return std::nullopt; + return info; +} + +/// Decoded MAP. +struct MapReply { + Target target{}; + bool exists{false}; + GamepadMap map{}; +}; + +inline std::vector encode_map_reply(const Target &t, bool exists, const GamepadMap &m) { + std::vector p; + put_target(p, t); + put_u8(p, exists ? kFlagExists : 0); + put_map(p, m); + return p; +} +inline std::optional decode_map_reply(std::span payload) { + Reader r(payload); + MapReply reply; + uint8_t flags = 0; + if (!read_target(r, reply.target) || !r.u8(flags) || !read_map(r, reply.map) || + !r.known_fields_read()) + return std::nullopt; + reply.exists = flags & kFlagExists; + return reply; +} + +inline std::vector encode_ok(uint8_t request_type) { return {request_type}; } + +inline std::vector encode_error(uint8_t request_type, uint32_t code, + std::string_view message) { + std::vector p; + put_u8(p, request_type); + put_u32(p, code); + p.insert(p.end(), message.begin(), message.end()); + return p; +} + +/// Encode PROFILES, keeping it within @p max_bytes: entries that would not fit +/// are dropped from the end (at most 255 entries). +/// @param[out] encoded_count Set to the number of entries encoded, if non-null. +inline std::vector encode_profiles(std::span profiles, + size_t max_bytes = espp::stream_frame::kMaxPayloadSize, + size_t *encoded_count = nullptr) { + std::vector p{0}; + size_t n = 0; + for (const auto &s : profiles) { + const size_t name_len = s.name.size() > 255 ? 255 : s.name.size(); + const size_t entry = 2 + 2 + 1 + name_len + 1; + if (n == 255 || p.size() + entry > max_bytes) + break; + put_u16(p, s.vid); + put_u16(p, s.pid); + put_str(p, s.name); + put_u8(p, s.rule_count); + n++; + } + p[0] = static_cast(n); + if (encoded_count) + *encoded_count = n; + return p; +} +inline std::optional> +decode_profiles(std::span payload) { + Reader r(payload); + uint8_t count = 0; + if (!r.u8(count)) + return std::nullopt; + std::vector out(count); + for (auto &s : out) + if (!r.u16(s.vid) || !r.u16(s.pid) || !r.str(s.name) || !r.u8(s.rule_count)) + return std::nullopt; + if (!r.known_fields_read()) + return std::nullopt; + return out; +} + +inline std::vector encode_input(const Input &in) { + std::vector p; + p.reserve(1 + 2 * kStateSize); + put_u8(p, static_cast((in.connected ? kFlagConnected : 0) | + (in.changed ? kFlagChanged : 0))); + put_state(p, in.raw); + put_state(p, in.mapped); + return p; +} +inline std::optional decode_input(std::span payload) { + Reader r(payload); + Input in; + uint8_t flags = 0; + if (!r.u8(flags) || !read_state(r, in.raw) || !read_state(r, in.mapped) || !r.known_fields_read()) + return std::nullopt; + in.connected = flags & kFlagConnected; + in.changed = flags & kFlagChanged; + return in; +} + +} // namespace espp::detail::gamepad_map_protocol diff --git a/components/gamepad_map/include/gamepad_map.hpp b/components/gamepad_map/include/gamepad_map.hpp index d88f137a6d..e42d6a960e 100644 --- a/components/gamepad_map/include/gamepad_map.hpp +++ b/components/gamepad_map/include/gamepad_map.hpp @@ -133,6 +133,11 @@ struct GamepadMapRule { return fail("target out of range"); if (kind == Kind::AxisToButton && param == 0) return fail("axis -> button needs a non-zero threshold"); + if (kind == Kind::AxisToButton && param < 0 && + GamepadState::is_trigger(static_cast(source))) + return fail("a trigger never goes below 0: its threshold must be positive"); + if (target == NONE && keeps_source()) + return fail("a rule that keeps its source needs a target"); if (kind == Kind::AxisToAxis && (param < -MAX_SCALE_PERCENT || param > MAX_SCALE_PERCENT)) return fail("axis -> axis scale out of range"); return true; diff --git a/components/gamepad_map/include/gamepad_map_service.hpp b/components/gamepad_map/include/gamepad_map_service.hpp new file mode 100644 index 0000000000..1ef3279a0e --- /dev/null +++ b/components/gamepad_map/include/gamepad_map_service.hpp @@ -0,0 +1,593 @@ +#pragma once + +// espp::GamepadMapService -- view and edit an espp::GamepadProfiles store and +// watch a controller's input before / after mapping, as a transport-agnostic +// dispatcher module (detail/gamepad_map_protocol.hpp is the wire spec). Same +// contract as the other espp services: requests are handled under an internal +// mutex, the `send` callback runs with that mutex released, frames for other +// modules / reply-flagged frames are ignored so the service shares a stream. +// +// Wiring (one line per transport): +// +// espp::GamepadMapService map_service({.send = [&](auto f) { usb.write_vendor(f); }, +// .profiles = &profiles}); +// dispatcher.register_module(map_service); // module 11 + discovery metadata + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "dispatcher.hpp" +#include "stream_frame.hpp" + +#include "base_component.hpp" +#include "detail/gamepad_map_protocol.hpp" +#include "gamepad_map.hpp" +#include "gamepad_profiles.hpp" +#include "gamepad_state.hpp" +#include "task.hpp" + +namespace espp { + +/** + * @brief Serves a GamepadProfiles store over any framed byte stream so a host + * (the hosted gamepad map web console) can view and edit the maps and + * watch a controller's input live (dispatcher module 11 by default; see + * Config::module). + * + * @details The application tells the service which controller is connected + * (set_controller() / clear_controller()) and hands it every input it + * maps (publish_input(), raw and mapped). The service answers GET_INFO + * / GET_MAP / LIST_PROFILES from the store, applies SET_MAP / + * ERASE_PROFILE / RESET_ALL to it (every map is validated, every + * change saved), and while a host has the stream on, sends the latest + * input as INPUT events every period. The stream stops by itself when + * the host does not renew it within Config::stream_lease, so a closed + * browser tab does not leave it running. + * + * When a change affects the map of the connected controller (its + * profile, or the default map it falls back to), the service calls + * Config::on_active_map_changed with the new map: the application + * swaps the map it applies. publish_input() 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. + * + * **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). + * + * \section gamepad_map_service_ex1 GamepadMapService Example + * \snippet gamepad_map_webapp_example.cpp gamepad_map_webapp_example + */ +class GamepadMapService : public BaseComponent { +public: + using Stream = espp::stream_frame::StreamParser; + using Type = espp::detail::gamepad_map_protocol::Type; + + /// Default dispatcher module id (11). A routing key only: Config::module serves + /// on any id, and hosts find it through discovery (by kProtocol). + static constexpr uint8_t kModule = espp::detail::gamepad_map_protocol::kModule; + /// Stable protocol identifier + version advertised through discovery. + static constexpr const char *kProtocol = espp::detail::gamepad_map_protocol::kProtocol; + static constexpr uint16_t kProtocolVersion = espp::detail::gamepad_map_protocol::kProtocolVersion; + + /// Transmits one encoded frame to the host. + using send_fn = std::function frame)>; + /// Called with the connected controller's new map after a host changed it. + using map_changed_fn = std::function; + + /// Configuration for the GamepadMapService. + struct Config { + send_fn send{nullptr}; ///< Transmits an encoded frame (required). + GamepadProfiles *profiles{nullptr}; ///< The store served (required; must outlive the service). + /// Called (without the service's locks held) when a host's change gives the + /// connected controller a new map. + map_changed_fn on_active_map_changed{nullptr}; + /// Dispatcher module id this instance answers on (and stamps on every + /// frame it sends). A routing key only (0x00..0xEF). + uint8_t module{kModule}; + /// Shortest INPUT period a host may request (SET_STREAM is clamped to it). + std::chrono::milliseconds min_stream_period{20}; + /// Longest INPUT period a host may request (SET_STREAM is clamped to it). + std::chrono::milliseconds max_stream_period{1000}; + /// The stream stops when no SET_STREAM enable renews it for this long. + std::chrono::milliseconds stream_lease{10000}; + /// The streaming task (started on the first SET_STREAM enable). + Task::BaseConfig task_config{.name = "gamepad_map_stream", .stack_size_bytes = 4 * 1024}; + espp::Logger::Verbosity log_level{espp::Logger::Verbosity::WARN}; ///< Logger verbosity. + }; + + /// @brief Construct the service. + explicit GamepadMapService(const Config &config) + : BaseComponent("GamepadMapService", config.log_level) + , config_(config) { + if (!config_.profiles) + logger_.error("no GamepadProfiles store configured: every request will fail"); + } + + ~GamepadMapService() { stop_stream(); } + + /// @brief The dispatcher module id this service answers on (Config::module). + uint8_t module_id() const { return config_.module; } + + /// @brief Discovery metadata for registering this service on a Dispatcher. + Dispatcher::ModuleInfo module_info() const { + return {.name = "Gamepad map", + .app = "gamepad_map_console.html", + .description = "Gamepad button / axis mapping and per-controller profiles", + .protocol = kProtocol, + .protocol_version = kProtocolVersion}; + } + + // --- application side --- + + /** + * @brief A controller connected (or the connected one changed). + * @return The map to apply to it (its profile's, else the default map). + */ + GamepadMap set_controller(uint16_t vid, uint16_t pid, const std::string &name) { + bool changed = false; + { + std::lock_guard lock(mutex_); + const Controller c{vid, pid, name}; + changed = !controller_ || !(*controller_ == c); + controller_ = c; + } + if (changed) { + reset_input(); // nothing from the previous controller carries over + info_pending_ = true; + } + return config_.profiles ? config_.profiles->map_for(vid, pid, name) : GamepadMap{}; + } + + /// @brief The controller disconnected (INPUT then reports no controller). + void clear_controller() { + bool changed = false; + { + std::lock_guard lock(mutex_); + changed = controller_.has_value(); + controller_.reset(); + } + if (changed) { + reset_input(); + info_pending_ = true; + } + } + + /// @brief The map the connected controller should use now (default map when none is connected). + GamepadMap active_map() const { + if (!config_.profiles) + return {}; + const auto c = controller(); + return c ? config_.profiles->map_for(c->vid, c->pid, c->name) : config_.profiles->default_map(); + } + + /** + * @brief Report one input: what the controller sent and what it was mapped + * to. Copies 32 bytes under a lock (always, so a stream that starts + * later begins from the real state); never sends. + */ + void publish_input(const GamepadState &raw, const GamepadState &mapped) { + std::lock_guard lock(input_mutex_); + if (raw != latest_raw_ || mapped != latest_mapped_) + input_changed_ = true; + latest_raw_ = raw; + latest_mapped_ = mapped; + } + + /// @brief Whether INPUT events are being sent. + bool streaming() const { return streaming_.load(); } + + /// @brief Stop streaming (also done by the destructor, SET_STREAM 0 and the lease). + void stop_stream() { + std::unique_ptr task; + { + std::lock_guard lock(mutex_); + streaming_.store(false); + task_active_ = false; + task = std::move(task_); + } + if (task) + task->stop(); + } + + // --- transport side --- + + /** + * @brief Dispatcher entry point: handle one routed frame. Frames for other + * modules and reply-flagged frames are ignored, so this can be + * registered directly: `dispatcher.register_module(service)`. + */ + void handle(const espp::stream_frame::Frame &frame) { + if (frame.module != module_id() || frame.is_reply()) + return; + handle_frame(frame.type, frame.payload, frame.correlation); + } + + /// @brief Feed received transport bytes (standalone use, without a Dispatcher). + void feed(std::span data) { + std::vector frames; + { + std::lock_guard lock(mutex_); + frames = parser_.feed(data); + } + for (const auto &frame : frames) + handle(frame); + } + + /// @brief Discard any partially-buffered frame bytes (standalone feed() use). + void reset_parser() { + std::lock_guard lock(mutex_); + parser_.reset(); + } + + /** + * @brief Handle one already-parsed request frame. + * @param correlation The request frame's correlation id, if it carried one; + * every reply echoes it (streamed events carry none). + * @return true if the type belongs to the gamepad map protocol (a reply was + * sent), false if it was ignored. + */ + bool handle_frame(uint8_t type, std::span payload, + std::optional correlation = std::nullopt) { + namespace proto = espp::detail::gamepad_map_protocol; + const auto request = static_cast(type); + switch (request) { + case Type::GetInfo: + case Type::GetMap: + case Type::SetMap: + case Type::EraseProfile: + case Type::ListProfiles: + case Type::SetStream: + case Type::ResetAll: + break; + default: + return false; // not a gamepad map request: ignore so the service can share a stream + } + if (!config_.profiles) { + send_error(type, std::errc::not_supported, "no profile store configured", correlation); + return true; + } + // requests without a payload take none: a longer one is a newer protocol's + // request this firmware does not understand (never act on it) + if ((request == Type::GetInfo || request == Type::ListProfiles || request == Type::ResetAll) && + !payload.empty()) { + send_error(type, std::errc::invalid_argument, "unexpected payload", correlation); + return true; + } + auto &profiles = *config_.profiles; + switch (request) { + case Type::GetInfo: + send_frame(proto::build_frame(Type::Info, proto::encode_info(build_info()), module_id(), + correlation)); + break; + case Type::GetMap: { + const auto target = proto::decode_get_map(payload); + if (!target) { + send_error(type, std::errc::invalid_argument, "malformed GET_MAP", correlation); + break; + } + proto::Target resolved = *target; + GamepadMap map; + bool exists = true; + if (target->profile) { + if (const auto p = profiles.profile(target->vid, target->pid, target->name)) { + map = p->map; + resolved.name = p->name; // as stored + } else { + exists = false; // no such profile: the controller uses the default map today + map = profiles.default_map(); + } + } else { + map = profiles.default_map(); + } + send_frame(proto::build_frame(Type::Map, proto::encode_map_reply(resolved, exists, map), + module_id(), correlation)); + break; + } + case Type::SetMap: { + const auto req = proto::decode_set_map(payload); + if (!req) { + send_error(type, std::errc::invalid_argument, "malformed SET_MAP", correlation); + break; + } + const auto &[target, map] = *req; + std::string why; + if (!map.valid(&why)) { + send_error(type, std::errc::invalid_argument, "invalid map: " + why, correlation); + break; + } + std::error_code ec; + 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 (!saved) { + send_error(type, std::errc::io_error, + "could not save the map: " + (ec ? ec.message() : std::string("unknown error")), + correlation, ec); + break; + } + ok(type, correlation); + break; + } + case Type::EraseProfile: { + const auto target = proto::decode_erase_profile(payload); + if (!target) { + send_error(type, std::errc::invalid_argument, "malformed ERASE_PROFILE", correlation); + break; + } + std::error_code ec; + if (!change( + [&] { return profiles.erase_profile(target->vid, target->pid, target->name, ec); })) { + if (ec) + send_error(type, std::errc::io_error, "could not save: " + ec.message(), correlation, ec); + else + send_error(type, std::errc::no_such_file_or_directory, "no such profile", correlation); + break; + } + ok(type, correlation); + break; + } + case Type::ListProfiles: { + const auto stored = profiles.profiles(); + std::vector list; + list.reserve(stored.size()); + std::transform( + stored.begin(), stored.end(), std::back_inserter(list), [](const GamepadProfile &p) { + return proto::ProfileSummary{ + .vid = p.vid, + .pid = p.pid, + .name = p.name, + .rule_count = static_cast(std::min(p.map.rules.size(), 255))}; + }); + size_t encoded = 0; + auto reply = proto::encode_profiles(list, max_payload(), &encoded); + if (encoded < list.size()) + logger_.warn("PROFILES payload full: listing {} of {} profiles", encoded, list.size()); + send_frame(proto::build_frame(Type::Profiles, reply, module_id(), correlation)); + break; + } + case Type::SetStream: { + const auto req = proto::decode_set_stream(payload); + if (!req) { + send_error(type, std::errc::invalid_argument, + "malformed SET_STREAM (expected u8 enable, u16 period_ms)", correlation); + break; + } + if (req->enable) + start_stream(std::chrono::milliseconds(req->period_ms)); + else + stop_stream(); + ok(type, correlation); + break; + } + case Type::ResetAll: { + std::error_code ec; + if (!change([&] { return profiles.reset(ec); })) { + send_error(type, std::errc::io_error, "could not save: " + ec.message(), correlation, ec); + break; + } + ok(type, correlation); + break; + } + default: + break; + } + return true; + } + +protected: + struct Controller { + uint16_t vid{0}; + uint16_t pid{0}; + std::string name{}; + bool operator==(const Controller &) const = default; + }; + + /// Forget the latest input (a controller changed): the next INPUT shows a + /// neutral state until the new controller reports. + void reset_input() { + std::lock_guard lock(input_mutex_); + latest_raw_ = {}; + latest_mapped_ = {}; + input_changed_ = true; + } + + std::optional controller() const { + std::lock_guard lock(mutex_); + return controller_; + } + + espp::detail::gamepad_map_protocol::Info build_info() const { + namespace proto = espp::detail::gamepad_map_protocol; + proto::Info info{ + .button_count = static_cast(GamepadState::BUTTON_COUNT), + .axis_count = static_cast(GamepadState::AXIS_COUNT), + .max_rules = static_cast(std::min(GamepadMap::MAX_RULES, 255)), + .max_profiles = + static_cast(std::min(config_.profiles->max_profiles(), 255)), + .profile_count = + static_cast(std::min(config_.profiles->profile_count(), 255))}; + if (const auto c = controller()) { + info.controller = + proto::Controller{.vid = c->vid, + .pid = c->pid, + .name = c->name, + .has_profile = config_.profiles->has_profile(c->vid, c->pid, c->name)}; + } + return info; + } + + /// 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. + 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{}; + if (!save()) + return false; + if (notify) { + const GamepadMap now = active_map(); + if (now != before) + config_.on_active_map_changed(now); + } + return true; + } + + void ok(uint8_t request_type, std::optional correlation) { + namespace proto = espp::detail::gamepad_map_protocol; + send_frame( + proto::build_frame(Type::Ok, proto::encode_ok(request_type), module_id(), correlation)); + } + + /// The payload cap: the stream_frame payload limit. + static constexpr size_t max_payload() { return espp::stream_frame::kMaxPayloadSize; } + + void start_stream(std::chrono::milliseconds period) { + std::unique_ptr finished; + { + std::lock_guard lock(mutex_); + period_ms_.store( + std::clamp(period, config_.min_stream_period, config_.max_stream_period).count()); + lease_until_.store(now_ms() + config_.stream_lease.count()); + if (!streaming_.load()) { + // the first event after (re)enabling is a full picture + std::lock_guard input_lock(input_mutex_); + input_changed_ = true; + info_pending_ = true; + } + streaming_.store(true); + if (task_ && task_active_) + return; // running: the new period and lease apply on its next wake + finished = std::move(task_); // ended itself (lease ran out): join it below + task_active_ = true; + task_ = std::make_unique( + Task::Config{.callback = [this](std::mutex &m, std::condition_variable &cv, + bool ¬ified) { return stream_step(m, cv, notified); }, + .task_config = config_.task_config}); + task_->start(); + } + if (finished) + finished->stop(); // it already returned: this only joins it + } + + /// One streaming period: send a pending INFO and the latest input (no + /// correlation id: events, not replies), then wait one period. When the + /// lease has run out (or the stream was stopped) the task ends itself; the + /// next SET_STREAM starts a new one. + bool stream_step(std::mutex &m, std::condition_variable &cv, bool ¬ified) { + namespace proto = espp::detail::gamepad_map_protocol; + if (!streaming_.load() || now_ms() > lease_until_.load()) { + // decided under mutex_, where start_stream() renews the lease, so a + // renewal that just landed is never undone + std::lock_guard lock(mutex_); + if (!streaming_.load() || now_ms() > lease_until_.load()) { + if (streaming_.load()) + logger_.info("INPUT stream lease expired; stopping the stream"); + streaming_.store(false); + task_active_ = false; + return true; // end this task + } + } + if (info_pending_.exchange(false)) + send_frame(proto::build_frame(Type::Info, proto::encode_info(build_info()), module_id())); + proto::Input in; + in.connected = controller().has_value(); + { + std::lock_guard lock(input_mutex_); + in.raw = latest_raw_; + in.mapped = latest_mapped_; + in.changed = input_changed_; + input_changed_ = false; + } + send_frame(proto::build_frame(Type::Input, proto::encode_input(in), module_id())); + std::unique_lock lock(m); + cv.wait_for(lock, std::chrono::milliseconds(period_ms_.load()), + [¬ified] { return notified; }); + notified = false; // consumed, under the mutex, per the Task contract + return false; + } + + static int64_t now_ms() { + using namespace std::chrono; + return duration_cast(steady_clock::now().time_since_epoch()).count(); + } + + /// Transmit a frame. Serialized on send_mutex_ (held across the callback) so + /// an event and a reply never interleave. Never called with mutex_ held. + void send_frame(const std::vector &frame) { + if (frame.empty()) + return; + std::lock_guard send_lock(send_mutex_); + if (!config_.send) { + logger_.warn_rate_limited("no send function configured; dropping a {}-byte frame", + frame.size()); + return; + } + config_.send(frame); + } + + void send_error(uint8_t request_type, std::errc errc, std::string_view message, + std::optional correlation = std::nullopt, std::error_code cause = {}) { + namespace proto = espp::detail::gamepad_map_protocol; + logger_.warn("{} (type 0x{:02x})", message, request_type); + // a generic-category cause is already a POSIX errno; anything else reports + // the std::errc the service chose + const uint32_t code = static_cast(cause && cause.category() == std::generic_category() + ? cause.value() + : std::make_error_code(errc).value()); + send_frame(proto::build_frame(Type::Error, proto::encode_error(request_type, code, message), + module_id(), correlation)); + } + +private: + Config config_; + mutable std::mutex mutex_; ///< guards the parser, controller_ and task_ + mutable std::mutex send_mutex_; ///< serializes every outbound frame across `send` + std::mutex input_mutex_; ///< guards the latest input + Stream parser_; + std::optional controller_{}; + std::unique_ptr task_; + std::atomic streaming_{false}; + bool task_active_{false}; ///< task_ is running (guarded by mutex_) + std::atomic info_pending_{false}; ///< send INFO on the next stream tick + std::atomic period_ms_{20}; + std::atomic lease_until_{0}; + GamepadState latest_raw_{}; + GamepadState latest_mapped_{}; + bool input_changed_{true}; +}; + +// Compile-time check that the service keeps satisfying the dispatcher's module +// contract (module_id() / module_info() / handle(frame)). +static_assert(DispatcherModuleConcept); + +} // namespace espp diff --git a/components/gamepad_map/include/gamepad_profiles.hpp b/components/gamepad_map/include/gamepad_profiles.hpp index 0ae9fa777a..f5afb6ba06 100644 --- a/components/gamepad_map/include/gamepad_profiles.hpp +++ b/components/gamepad_map/include/gamepad_profiles.hpp @@ -171,6 +171,12 @@ class GamepadProfiles : public BaseComponent { /// @brief The most profiles the store accepts. size_t max_profiles() const { return max_profiles_; } + /// @brief A mutex for the store's users to serialize "change the store and + /// act on the change" (GamepadMapService holds it across a change and + /// the notification it causes, so services sharing a store notify in + /// order). The store's own methods never take it. + std::mutex &change_mutex() const { return change_mutex_; } + /** * @brief Replace the default map and save. * @param map The map (must be valid()). @@ -342,6 +348,7 @@ class GamepadProfiles : public BaseComponent { size_t max_profiles_; Storage storage_; mutable std::mutex mutex_; + mutable std::mutex change_mutex_; Data data_{}; std::error_code load_error_{}; }; diff --git a/components/gamepad_map/test/gamepad_map_host_test.cpp b/components/gamepad_map/test/gamepad_map_host_test.cpp index 2af77a1a1c..8c4785ebf6 100644 --- a/components/gamepad_map/test/gamepad_map_host_test.cpp +++ b/components/gamepad_map/test/gamepad_map_host_test.cpp @@ -201,6 +201,13 @@ static void test_validation() { CHECK(!map.valid(&why)); map.rules = {{GamepadMapRule::Kind::ButtonToButton, 0, 1, 0x80, 0}}; CHECK(!map.valid(&why)); // unknown flag + map.rules = {GamepadMapRule::axis_to_button(A::LeftTrigger, -100, B::L2)}; + CHECK(!map.valid(&why)); // a trigger never goes below 0 + map.rules = {GamepadMapRule::axis_to_button(A::LeftTrigger, 100, B::L2)}; + CHECK(map.valid()); + map.rules = {{GamepadMapRule::Kind::ButtonToButton, 0, GamepadMapRule::NONE, + GamepadMapRule::KEEP_SOURCE, 0}}; + CHECK(!map.valid(&why)); // keeping the source of a rule with no target does nothing map.rules.assign(GamepadMap::MAX_RULES + 1, GamepadMapRule::button(B::South, B::East)); CHECK(!map.valid(&why) && why == "too many rules"); map.rules.clear(); diff --git a/components/gamepad_map/test/gamepad_map_protocol_host_test.cpp b/components/gamepad_map/test/gamepad_map_protocol_host_test.cpp new file mode 100644 index 0000000000..4e1b8d5216 --- /dev/null +++ b/components/gamepad_map/test/gamepad_map_protocol_host_test.cpp @@ -0,0 +1,190 @@ +// Host-buildable unit tests for the gamepad map wire protocol +// (include/detail/gamepad_map_protocol.hpp): golden encodings of every message +// plus decode round trips and rejection of malformed payloads. Build & run +// from the repository root: +// +// g++ -std=c++23 -Wall -Wextra -Werror +// -I components/gamepad_map/include -I components/stream_frame/include +// components/gamepad_map/test/gamepad_map_protocol_host_test.cpp +// -o gamepad_map_protocol_host_test +// ./gamepad_map_protocol_host_test +// +// No ESP-IDF headers required. + +#include +#include +#include + +#include "detail/gamepad_map_protocol.hpp" + +namespace proto = espp::detail::gamepad_map_protocol; +using espp::GamepadMap; +using espp::GamepadMapRule; +using espp::GamepadState; +using B = GamepadState::Button; +using A = GamepadState::Axis; + +static int failures = 0; +#define CHECK(cond) \ + do { \ + if (!(cond)) { \ + std::printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \ + failures++; \ + } \ + } while (0) + +using Bytes = std::vector; + +static void test_map_encoding() { + GamepadMap m; + m.left_deadzone_percent = 10; + m.right_deadzone_percent = 5; + m.add(GamepadMapRule::button(B::South, B::East)) + .add(GamepadMapRule::axis_to_button(A::LeftY, -16384, B::Up, true)); + const proto::Target t{.profile = true, .vid = 0x1949, .pid = 0x0402, .name = "BSP"}; + const Bytes p = proto::encode_set_map(t, m); + const Bytes golden{ + 0x01, 0x49, 0x19, 0x02, 0x04, 0x03, 'B', 'S', 'P', // target: profile 1949:0402 "BSP" + 10, 5, 2, // dead zones, 2 rules + 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, // south -> east + 0x01, 0x01, 0x0e, 0x01, 0x00, 0xc0, // left_y <= -16384 -> up, keep + }; + CHECK(p == golden); + const auto back = proto::decode_set_map(p); + CHECK(back.has_value()); + if (back) { + CHECK(back->first == t); + CHECK(back->second == m); + } + // the default target is one byte + const Bytes def = proto::encode_get_map({}); + CHECK(def == Bytes{0x00}); + CHECK(proto::decode_get_map(def).has_value() && !proto::decode_get_map(def)->profile); + // malformed: unknown target kind, truncated rule, trailing bytes + CHECK(!proto::decode_get_map(Bytes{0x02})); + Bytes truncated = golden; + truncated.pop_back(); + CHECK(!proto::decode_set_map(truncated)); + Bytes trailing = golden; + trailing.push_back(0); + CHECK(!proto::decode_set_map(trailing)); + // the layout decodes even when the content is invalid: valid() is the + // service's job + const Bytes bad_rule{0x00, 0, 0, 1, 0x07, 0x40, 0x00, 0x00, 0x00, 0x00}; + const auto invalid = proto::decode_set_map(bad_rule); + CHECK(invalid.has_value() && !invalid->second.valid()); + + // MAP: the target, the exists flag, the map; a host ignores appended fields + Bytes reply = proto::encode_map_reply(t, false, m); + CHECK(reply.size() == golden.size() + 1); + CHECK(reply[9] == 0x00); // after the 9-byte target: exists = 0 + auto decoded = proto::decode_map_reply(reply); + CHECK(decoded.has_value() && decoded->target == t && !decoded->exists && decoded->map == m); + reply = proto::encode_map_reply({}, true, GamepadMap{}); + CHECK(reply == (Bytes{0x00, 0x01, 0, 0, 0})); + reply.push_back(0xAA); // a later version's field + decoded = proto::decode_map_reply(reply); + CHECK(decoded.has_value() && decoded->exists && !decoded->target.profile); +} + +static void test_info() { + proto::Info info{ + .button_count = 22, .axis_count = 6, .max_rules = 64, .max_profiles = 16, .profile_count = 1}; + Bytes p = proto::encode_info(info); + CHECK(p == (Bytes{22, 6, 64, 16, 1, 0x00})); + auto back = proto::decode_info(p); + CHECK(back.has_value() && *back == info); + + info.controller = + proto::Controller{.vid = 0x045e, .pid = 0x0b13, .name = "Xbox", .has_profile = true}; + p = proto::encode_info(info); + CHECK(p == (Bytes{22, 6, 64, 16, 1, 0x01, 0x5e, 0x04, 0x13, 0x0b, 4, 'X', 'b', 'o', 'x', 1})); + back = proto::decode_info(p); + CHECK(back.has_value() && *back == info); + Bytes longer = p; + longer.push_back(0x55); // device -> host: appended fields are ignored + CHECK(proto::decode_info(longer).has_value() && *proto::decode_info(longer) == info); + p.pop_back(); + CHECK(!proto::decode_info(p)); +} + +static void test_profiles() { + const std::vector list{{0x1949, 0x0402, "BSP-D8", 4}, {0, 0, "NoPnP", 0}}; + const Bytes p = proto::encode_profiles(list); + const Bytes golden{2, 0x49, 0x19, 0x02, 0x04, 6, 'B', 'S', 'P', '-', 'D', '8', + 4, 0x00, 0x00, 0x00, 0x00, 5, 'N', 'o', 'P', 'n', 'P', 0}; + CHECK(p == golden); + const auto back = proto::decode_profiles(p); + CHECK(back.has_value() && *back == list); + // capped: only what fits + size_t encoded = 0; + const Bytes capped = proto::encode_profiles(list, 1 + 12, &encoded); + CHECK(encoded == 1 && capped.size() == 13 && capped[0] == 1); +} + +static void test_input_and_stream() { + proto::Input in; + in.connected = true; + in.changed = true; + in.raw.set(B::South, true); + in.raw.set(A::LeftX, -32767); + in.mapped.set(B::East, true); + in.mapped.set(A::RightTrigger, 32767); + const Bytes p = proto::encode_input(in); + CHECK(p.size() == 1 + 2 * proto::kStateSize); + CHECK(p[0] == 0x03); + CHECK(p[1] == 0x01 && p[2] == 0 && p[3] == 0 && p[4] == 0); // raw buttons: south + CHECK(p[5] == 0x01 && p[6] == 0x80); // raw left_x = -32767 + CHECK(p[17] == 0x02); // mapped buttons: east + CHECK(p[31] == 0xff && p[32] == 0x7f); // mapped right_trigger + const auto back = proto::decode_input(p); + CHECK(back.has_value()); + if (back) { + CHECK(back->connected && back->changed); + CHECK(back->raw == in.raw && back->mapped == in.mapped); + } + + const Bytes s = proto::encode_set_stream(true, 50); + CHECK(s == (Bytes{1, 50, 0})); + const auto req = proto::decode_set_stream(s); + CHECK(req.has_value() && req->enable && req->period_ms == 50); + CHECK(!proto::decode_set_stream(Bytes{2, 50, 0})); // enable must be 0 / 1 + CHECK(!proto::decode_set_stream(Bytes{1, 50})); +} + +static void test_erase_error_frame() { + const Bytes e = proto::encode_erase_profile(0x1949, 0x0402, "BSP"); + CHECK(e == (Bytes{0x49, 0x19, 0x02, 0x04, 3, 'B', 'S', 'P'})); + const auto t = proto::decode_erase_profile(e); + CHECK(t.has_value() && t->profile && t->vid == 0x1949 && t->name == "BSP"); + + const Bytes err = proto::encode_error(0x03, 22, "bad"); + CHECK(err == (Bytes{0x03, 22, 0, 0, 0, 'b', 'a', 'd'})); + + // replies carry the reply flag, requests do not; the frame decodes back + const auto frame = proto::build_frame(proto::Type::Ok, proto::encode_ok(0x03), proto::kModule, 7); + espp::stream_frame::StreamParser parser; + const auto frames = parser.feed(frame); + CHECK(frames.size() == 1); + if (frames.size() == 1) { + CHECK(frames[0].is_reply()); + CHECK(frames[0].module == 11); + CHECK(frames[0].type == 0x83); + CHECK(frames[0].correlation == std::optional(7)); + } + CHECK(!proto::is_reply(proto::Type::SetMap) && proto::is_reply(proto::Type::Input)); +} + +int main() { + test_map_encoding(); + test_info(); + test_profiles(); + test_input_and_stream(); + test_erase_error_frame(); + if (failures == 0) { + std::printf("gamepad_map_protocol_host_test: all checks passed\n"); + return 0; + } + std::printf("gamepad_map_protocol_host_test: %d failure(s)\n", failures); + return 1; +} diff --git a/components/gamepad_map/web/gamepad_map_console.html b/components/gamepad_map/web/gamepad_map_console.html new file mode 100644 index 0000000000..56979327c2 --- /dev/null +++ b/components/gamepad_map/web/gamepad_map_console.html @@ -0,0 +1,2009 @@ + + + + + + espp Gamepad Map Console (WebUSB / Web Serial) + + + + + + + + +
+
+

espp Gamepad Map Console (WebUSB / Web Serial)

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

Device

+
+ + + + + +
+ +
+

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

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

Live input

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

Raw (from the controller)

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

Mapped (what the device sends on)

+
+
No input yet.
+
+
+

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

+
+ + +
+

Map editor

+
+ Editing: nothing loaded + +
+ +
+

Pick a map on the right and Load it.

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

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

+

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

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

+
+
+ +
+ +
+

Map to edit

+ + +
+ +
+

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

+
+ + +
+

Profiles

+
Not connected.
+
+ + +
+

Reset

+

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

+ +
+
+
+ + +
+

Log

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