Gamepad Map APIs#

Gamepad Map#

The gamepad_map component remaps a gamepad’s buttons and axes: button to button, analog to digital (a stick direction or trigger past a threshold), digital to analog (a button driving an axis) and analog to analog (swap, invert, scale), plus radial stick dead zones. GamepadState names buttons by position (south / east / west / north) so a map means the same thing for Xbox, Nintendo and PlayStation controllers. GamepadProfiles keeps a default map and one map per controller type (vendor / product ID) in a file, stored with PersistentData. to_gamepad_state() converts the runtime HID decoder’s hid_rp::GamepadReport.

GamepadMapService serves a GamepadProfiles store over any framed byte stream (dispatcher module 11, protocol espp.gamepad_map v1), so the hosted Gamepad Map Console web app can edit the maps over WebUSB / Web Serial and show the controller’s input before and after mapping, live.

Code examples for the Gamepad Map API are provided in the gamepad_map example (decode, map, profiles) and webapp_example (the service over USB with the web console) folders.

API Reference#

Header File#

Header File#

Header File#

Classes#

class GamepadMapService : public espp::BaseComponent#

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).

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).

GamepadMapService Example#

  // One GamepadMapService per transport, both serving the one profile store.
  // When the console changes the map the connected controller uses, the
  // service hands it over: swap the map the input path applies.
  auto on_map_changed = [&](const espp::GamepadMap &map) {
    std::lock_guard<std::mutex> lock(map_mutex);
    active_map = map;
    logger.info("Map changed from the console: {} rule(s)", map.rules.size());
  };
  espp::GamepadMapService vendor_map({.send = vendor_send,
                                      .profiles = &profiles,
                                      .on_active_map_changed = on_map_changed,
                                      .task_config = {.name = "gpmap_v", .stack_size_bytes = 4096},
                                      .log_level = espp::Logger::Verbosity::INFO});
  espp::GamepadMapService cdc_map({.send = cdc_send,
                                   .profiles = &profiles,
                                   .on_active_map_changed = on_map_changed,
                                   .task_config = {.name = "gpmap_c", .stack_size_bytes = 4096},
                                   .log_level = espp::Logger::Verbosity::INFO});

  // A controller connected: tell every service, and start from its map (under
  // the same mutex as on_map_changed, which may run on a dispatcher thread).
  {
    std::lock_guard<std::mutex> lock(map_mutex);
    active_map = vendor_map.set_controller(demo_vid, demo_pid, demo_name);
    cdc_map.set_controller(demo_vid, demo_pid, demo_name);
  }

Public Types

using send_fn = std::function<void(std::span<const uint8_t> frame)>#

Transmits one encoded frame to the host.

using map_changed_fn = std::function<void(const GamepadMap &map)>#

Called with the connected controller’s new map after a host changed it.

Public Functions

inline explicit GamepadMapService(const Config &config)#

Construct the service.

inline uint8_t module_id() const#

The dispatcher module id this service answers on (Config::module).

inline Dispatcher::ModuleInfo module_info() const#

Discovery metadata for registering this service on a Dispatcher.

inline GamepadMap set_controller(uint16_t vid, uint16_t pid, const std::string &name)#

A controller connected (or the connected one changed).

Returns:

The map to apply to it (its profile’s, else the default map).

inline void clear_controller()#

The controller disconnected (INPUT then reports no controller).

inline GamepadMap active_map() const#

The map the connected controller should use now (default map when none is connected).

inline void publish_input(const GamepadState &raw, const GamepadState &mapped)#

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.

inline bool streaming() const#

Whether INPUT events are being sent.

inline void stop_stream()#

Stop streaming (also done by the destructor, SET_STREAM 0 and the lease).

inline void handle(const espp::stream_frame::Frame &frame)#

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)`.

inline void feed(std::span<const uint8_t> data)#

Feed received transport bytes (standalone use, without a Dispatcher).

inline void reset_parser()#

Discard any partially-buffered frame bytes (standalone feed() use).

inline bool handle_frame(uint8_t type, std::span<const uint8_t> payload, std::optional<uint16_t> correlation = std::nullopt)#

Handle one already-parsed request frame.

Parameters:

correlation – The request frame’s correlation id, if it carried one; every reply echoes it (streamed events carry none).

Returns:

true if the type belongs to the gamepad map protocol (a reply was sent), false if it was ignored.

inline const std::string &get_name() const#

Get the name of the component

Note

This is the tag of the logger

Returns:

A const reference to the name of the component

template<typename T = void>
inline void set_log_tag(const std::string_view&)#

Not available: the tag is fixed at construction (pass it to the constructor). Enable CONFIG_ESPP_LOGGER_MUTABLE_TAG (menuconfig: ESPP Logger -> Mutable tag) to change it afterwards.

inline espp::Logger::Verbosity get_log_level() const#

Get the log level for the logger

Returns:

The verbosity level of the logger

inline void set_log_level(espp::Logger::Verbosity level)#

Set the log level for the logger

Parameters:

level – The verbosity level to use for the logger

inline void set_log_verbosity(espp::Logger::Verbosity level)#

Set the log verbosity for the logger

See also

set_log_level

Note

This is a convenience method that calls set_log_level

Parameters:

level – The verbosity level to use for the logger

inline espp::Logger::Verbosity get_log_verbosity() const#

Get the log verbosity for the logger

See also

get_log_level

Note

This is a convenience method that calls get_log_level

Returns:

The verbosity level of the logger

inline void set_log_rate_limit(std::chrono::duration<float> rate_limit)#

Set the rate limit for the logger

Note

Only calls to the logger that have _rate_limit suffix will be rate limited

Parameters:

rate_limit – The rate limit to use for the logger

Public Static Attributes

static uint8_t kModule = espp::detail::gamepad_map_protocol::kModule#

Default dispatcher module id (11). A routing key only: Config::module serves on any id, and hosts find it through discovery (by kProtocol).

static const char *kProtocol = espp::detail::gamepad_map_protocol::kProtocol#

Stable protocol identifier + version advertised through discovery.

struct Config#

Configuration for the GamepadMapService.

Public Members

send_fn send = {nullptr}#

Transmits an encoded frame (required).

GamepadProfiles *profiles = {nullptr}#

The store served (required; must outlive the service).

map_changed_fn on_active_map_changed = {nullptr}#

Called (without the service’s locks held) when a host’s change gives the connected controller a new map.

uint8_t module = {kModule}#

Dispatcher module id this instance answers on (and stamps on every frame it sends). A routing key only (0x00..0xEF).

std::chrono::milliseconds min_stream_period = {20}#

Shortest INPUT period a host may request (SET_STREAM is clamped to it).

std::chrono::milliseconds max_stream_period = {1000}#

Longest INPUT period a host may request (SET_STREAM is clamped to it).

std::chrono::milliseconds stream_lease = {10000}#

The stream stops when no SET_STREAM enable renews it for this long.

Task::BaseConfig task_config   = {.name = "gamepad_map_stream", .stack_size_bytes = 4 * 1024}

The streaming task (started on the first SET_STREAM enable).

espp::Logger::Verbosity log_level = {espp::Logger::Verbosity::WARN}#

Logger verbosity.

Header File#

Classes#

class GamepadProfiles : public espp::BaseComponent#

Per-controller-type gamepad maps, stored in a file with PersistentData.

Holds a default map plus one GamepadProfile per controller type, and saves every change atomically (see PersistentData) to a file on a mounted filesystem (LittleFS, SPIFFS, SD). Look a controller up when it connects (map_for()) and keep the returned map for its reports; the lookup copies the map and is not meant for every report.

Every map that comes in is checked with GamepadMap::valid(). 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 `<file>.unreadable` and the store starts from the defaults, so the next change does not overwrite what may still be recoverable (see load_error()).

Thread-safe.

Gamepad Profiles Example#

    // The default map is used for controllers without a profile; the file is
    // written on the first change.
    espp::GamepadMap default_map;
    default_map.invert(A::LeftY).invert(A::RightY); // up-positive sticks for this host
    espp::GamepadProfiles profiles({
        .file_path = path,
        .default_map = default_map,
        .log_level = espp::Logger::Verbosity::INFO,
    });

    // A profile for one controller type (vendor / product ID; from the BLE
    // Device Information PnP ID, or the USB device descriptor).
    espp::GamepadMap bsp_d8 = default_map;
    bsp_d8.swap(B::South, B::East);
    if (!profiles.set_profile({.vid = 0x1949, .pid = 0x0402, .name = "BSP-D8", .map = bsp_d8}, ec))
      logger.error("Could not save the profile: {}", ec.message());

    // When a controller connects, look its map up once and keep it.
    const espp::GamepadMap active = profiles.map_for(0x1949, 0x0402, "BSP-D8");
    logger.info("BSP-D8 map: {} rule(s); default map: {} rule(s)", active.rules.size(),
                profiles.default_map().rules.size());

Public Functions

inline explicit GamepadProfiles(const Config &config)#

Load the profiles (or start from `config.default_map` when there is no file yet; the file is written on the first change).

Parameters:

config – The configuration.

inline std::error_code load_error() const#

Why the file could not be loaded (it was set aside as `<file>.unreadable`); clear if it loaded or did not exist.

inline GamepadMap map_for(uint16_t vid, uint16_t pid, const std::string &name = {}) const#

The map for a controller: its profile’s, else the default map.

inline std::optional<GamepadProfile> profile(uint16_t vid, uint16_t pid, const std::string &name = {}) const#

The profile for a controller, if it has one.

inline bool has_profile(uint16_t vid, uint16_t pid, const std::string &name = {}) const#

Whether a controller has a profile of its own.

inline std::vector<GamepadProfile> profiles() const#

Every profile.

inline size_t profile_count() const#

How many profiles are stored.

inline GamepadMap default_map() const#

The map for controllers without a profile.

inline Data data() const#

Everything, as stored.

inline size_t max_profiles() const#

The most profiles the store accepts.

inline std::mutex &change_mutex() const#

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.

inline bool set_default_map(const GamepadMap &map, std::error_code &ec)#

Replace the default map and save.

Parameters:
  • map – The map (must be valid()).

  • ec – Set on failure: std::errc::invalid_argument for an invalid map, else the save error.

Returns:

true if saved.

inline bool set_profile(const GamepadProfile &entry, std::error_code &ec)#

Add a profile, or replace the one for the same controller, and save.

Parameters:
  • 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).

  • 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.

Returns:

true if saved.

inline bool erase_profile(uint16_t vid, uint16_t pid, const std::string &name, std::error_code &ec)#

Remove a controller’s profile (it then uses the default map) and save.

Returns:

true if saved; false with `ec` clear if there was no such profile.

inline bool reset(std::error_code &ec)#

Forget every profile and reset the default map to identity, and save.

Returns:

true if saved.

inline const std::string &get_name() const#

Get the name of the component

Note

This is the tag of the logger

Returns:

A const reference to the name of the component

template<typename T = void>
inline void set_log_tag(const std::string_view&)#

Not available: the tag is fixed at construction (pass it to the constructor). Enable CONFIG_ESPP_LOGGER_MUTABLE_TAG (menuconfig: ESPP Logger -> Mutable tag) to change it afterwards.

inline espp::Logger::Verbosity get_log_level() const#

Get the log level for the logger

Returns:

The verbosity level of the logger

inline void set_log_level(espp::Logger::Verbosity level)#

Set the log level for the logger

Parameters:

level – The verbosity level to use for the logger

inline void set_log_verbosity(espp::Logger::Verbosity level)#

Set the log verbosity for the logger

See also

set_log_level

Note

This is a convenience method that calls set_log_level

Parameters:

level – The verbosity level to use for the logger

inline espp::Logger::Verbosity get_log_verbosity() const#

Get the log verbosity for the logger

See also

get_log_level

Note

This is a convenience method that calls get_log_level

Returns:

The verbosity level of the logger

inline void set_log_rate_limit(std::chrono::duration<float> rate_limit)#

Set the rate limit for the logger

Note

Only calls to the logger that have _rate_limit suffix will be rate limited

Parameters:

rate_limit – The rate limit to use for the logger

struct Config#

Configuration for the GamepadProfiles.

Public Members

std::filesystem::path file_path#

file the profiles live in

GamepadMap default_map = {}#

default map when the file does not exist yet

size_t max_profiles = {16}#

profiles the store accepts

Logger::Verbosity log_level = {Logger::Verbosity::WARN}#

Verbosity of the logger.

Header File#