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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,8 @@ jobs:
target: esp32
- path: 'components/ft5x06/example'
target: esp32s3
- path: 'components/gamepad_map/example'
target: esp32s3
- path: 'components/gfps_service/example'
target: esp32s3
- path: 'components/gps/example'
Expand Down
75 changes: 75 additions & 0 deletions .github/workflows/gamepad_map_tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
name: Gamepad map host test

# Builds and runs, on the host with g++ -std=c++23:
# - components/gamepad_map/test/gamepad_map_host_test.cpp (GamepadState,
# GamepadMap rules + validation, the hid-rp conversion, GamepadProfiles'
# file round trip)
# - components/hid-rp/test/hid_rp_report_map_host_test.cpp (the runtime
# report map + Gamepad / Keyboard / Mouse decoders the map is fed from)
# Runs whenever either component, or what they store / log with, changes.

# Minimal token scope: build + run tests, never writes.
permissions:
contents: read

on:
pull_request:
paths:
- "components/gamepad_map/**"
- "components/hid-rp/**"
- "components/persistent_data/**"
- "components/serialization/**"
- "components/logger/**"
- "components/format/**"
- "components/base_component/**"
- ".github/workflows/gamepad_map_tests.yml"
push:
branches:
- main
paths:
- "components/gamepad_map/**"
- "components/hid-rp/**"
- "components/persistent_data/**"
- "components/serialization/**"
- "components/logger/**"
- "components/format/**"
- "components/base_component/**"
- ".github/workflows/gamepad_map_tests.yml"
workflow_dispatch:

concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true

jobs:
host-test:
name: C++ host tests (gamepad map, hid-rp report map)
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v7
with:
submodules: recursive
- name: Build and run hid_rp_report_map_host_test
run: |
g++ --version | head -1
g++ -std=c++23 -Wall -Wextra -Werror -Wno-comment \
-isystem components/hid-rp/include \
-isystem components/hid-rp/detail/hid-rp/hid-rp \
-isystem components/format/include \
-isystem components/format/detail/fmt/include \
components/hid-rp/test/hid_rp_report_map_host_test.cpp -o hid_rp_report_map_host_test
./hid_rp_report_map_host_test
- name: Build and run gamepad_map_host_test
run: |
g++ -std=c++23 -Wall -Wextra -Werror -Wno-comment \
-I components/gamepad_map/include -I components/persistent_data/include \
-I components/serialization/include -I components/base_component/include \
-I components/logger/include -I components/format/include \
-isystem components/serialization/detail/alpaca/include \
-isystem components/format/detail/fmt/include \
-isystem components/hid-rp/include \
-isystem components/hid-rp/detail/hid-rp/hid-rp \
components/gamepad_map/test/gamepad_map_host_test.cpp components/logger/src/logger.cpp \
-o gamepad_map_host_test
./gamepad_map_host_test
1 change: 1 addition & 0 deletions .github/workflows/upload_components.yml
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ jobs:
components/format
components/ft5x06
components/ftp
components/gamepad_map
components/gfps_service
components/gps
components/gt911
Expand Down
4 changes: 4 additions & 0 deletions components/gamepad_map/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
idf_component_register(
INCLUDE_DIRS "include"
REQUIRES base_component format hid-rp persistent_data
)
136 changes: 136 additions & 0 deletions components/gamepad_map/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
# Gamepad Map Component

[![Badge](https://components.espressif.com/components/espp/gamepad_map/badge.svg)](https://components.espressif.com/components/espp/gamepad_map)

The `gamepad_map` component remaps a gamepad's buttons and axes: button to
button, analog to digital, digital to analog and analog to analog, plus stick
dead zones. Maps are stored per controller type in a file with
[persistent_data](../persistent_data). The component is meant to sit between
whatever reads a controller (a BLE or USB HID gamepad, GPIO buttons) and
whatever comes next (an emulated USB controller, an emulator's input).

<!-- markdown-toc start - Don't edit this section. Run M-x markdown-toc-refresh-toc -->
**Table of Contents**

- [Gamepad Map Component](#gamepad-map-component)
- [Overview](#overview)
- [Gamepad state](#gamepad-state)
- [Rules](#rules)
- [Profiles](#profiles)
- [From a HID gamepad](#from-a-hid-gamepad)
- [Host test](#host-test)
- [Example](#example)

<!-- markdown-toc end -->

## Overview

| Type | What it is |
|------|------------|
| `espp::GamepadState` | Buttons by position plus six axes: the common format inputs are decoded into |
| `espp::GamepadMapRule` | One remap: where one control's input goes |
| `espp::GamepadMap` | Stick dead zones plus a list of rules; `apply()` maps one state to another |
| `espp::GamepadProfiles` | A default map plus one map per controller type, saved in a file |
| `espp::to_gamepad_state()` | A state from a `hid_rp::GamepadReport` (`gamepad_state_hid_rp.hpp`) |

Everything except `GamepadProfiles` is header-only plain data with no
allocation in `apply()`, so it can run on every report.

## Gamepad state

`espp::GamepadState` names face buttons by **position** (south / east / west /
north), not label, because the labels disagree between controller families:

| Position | Xbox | Nintendo | PlayStation |
|----------|------|----------|-------------|
| south | A | B | Cross |
| east | B | A | Circle |
| west | X | Y | Square |
| north | Y | X | Triangle |

Besides the face buttons there are L1/R1, L2/R2 (the triggers as buttons),
L3/R3, Select, Start, Home, Capture, the d-pad and four paddles. The axes are
the two sticks (-32767..32767, X right, Y **down**, as in HID) and the two
triggers (0..32767).

## Rules

| Kind | Effect | `param` |
|------|--------|---------|
| button → button | the source presses the target | - |
| axis → button | the target is pressed while the axis is past the threshold | threshold: positive = at or above, negative = at or below |
| button → axis | while pressed, the value is added to the target axis | value |
| axis → axis | the scaled source is added to the target axis | scale in percent, -400..400 (negative inverts) |

A control that is the source of a rule is **moved**: it no longer reaches its
own position unless the rule has `KEEP_SOURCE`. A rule with target `NONE`
removes its source. Several rules can feed one target: buttons are OR-ed and
axis contributions are summed, then clamped to the axis' range. Every control
that no rule takes as a source passes through unchanged, so an empty map is the
identity.

```cpp
espp::GamepadMap map;
map.swap(B::South, B::East) // Nintendo-style A / B
.left_stick_to_dpad() // the stick also drives the d-pad
.triggers_to_buttons() // analog triggers also press ZL / ZR
.add(espp::GamepadMapRule::button(B::Paddle1, B::South)); // a paddle as A
map.left_deadzone_percent = 8;

espp::GamepadState out = map.apply(in);
```

Check a map that came from outside (a file, a web page) with `valid()`.
`apply()` skips rules whose indices are out of range, so a bad map can never
read or write outside the state.

## Profiles

`espp::GamepadProfiles` keeps a default map and one `GamepadProfile` per
controller type, keyed by vendor and product ID. For BLE these come from the
Device Information service's PnP ID; for USB, from the device descriptor. A
controller that reports neither is matched by name. Every change is validated
and saved atomically. Look the map up when a controller connects, not on every
report:

```cpp
espp::GamepadProfiles profiles({.file_path = fs.get_root_path() / "gamepad_profiles.bin",
.default_map = legacy_settings_as_a_map});
espp::GamepadMap active = profiles.map_for(vid, pid, name);
```

The file is written on the first change. Until then the configured
`default_map` is used, which is how an application can migrate its older
settings into a map.

## From a HID gamepad

The runtime `hid_rp::GamepadDecoder` (`hid-rp-report-map.hpp`) decodes any HID
gamepad from its report descriptor. For a pass-through, turn off its emulator
conveniences (stick as d-pad, triggers as L2/R2, Capture as Home) so the map
decides those:

```cpp
auto report_map = espp::hid_rp::ReportMap::parse(descriptor);
if (!report_map || !espp::hid_rp::GamepadDecoder::looks_like_gamepad(*report_map))
return; // not a gamepad (or a malformed descriptor)
espp::hid_rp::GamepadDecoder decoder(std::move(*report_map));
decoder.set_combine_controls(false);

espp::hid_rp::GamepadReport report;
if (decoder.update(report_id, payload, report)) // BLE: the ID comes out of band
send(map.apply(espp::to_gamepad_state(report)));
```

## Host test

`test/gamepad_map_host_test.cpp` covers the rule semantics, validation, the
hid-rp conversion (with a real BLE gamepad's descriptor) and the profile store's
file round trip. The build command is at the top of the file, and CI runs it in
`.github/workflows/gamepad_map_tests.yml` together with the hid-rp report-map
test.

## Example

The [example](./example) decodes a BLE gamepad report, remaps it, and stores
per-controller profiles on a LittleFS partition.
22 changes: 22 additions & 0 deletions components/gamepad_map/example/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# The following lines of boilerplate have to be in your project's CMakeLists
# in this exact order for cmake to work correctly
cmake_minimum_required(VERSION 3.20)

set(ENV{IDF_COMPONENT_MANAGER} "0")
include($ENV{IDF_PATH}/tools/cmake/project.cmake)

# add the component directories that we want to use
set(EXTRA_COMPONENT_DIRS
"../../../components/"
)

set(
COMPONENTS
"main esptool_py logger file_system gamepad_map"
CACHE STRING
"List of components to include"
)

project(gamepad_map_example)

set(CMAKE_CXX_STANDARD 23)
61 changes: 61 additions & 0 deletions components/gamepad_map/example/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# Gamepad Map Example

This example shows the `gamepad_map` component between a gamepad and whatever
comes next:

1. A BLE gamepad's HID report map (a ShanWan BSP-D8 in its Android mode) is
parsed with `hid_rp::ReportMap` and decoded with `hid_rp::GamepadDecoder`,
with the decoder's emulator conveniences turned off.
2. Each decoded report becomes an `espp::GamepadState`, which an
`espp::GamepadMap` remaps. The map here swaps A/B to the Nintendo layout,
puts the left stick on the d-pad as well, makes the analog triggers press
ZL/ZR too, and adds a left-stick dead zone.
3. `espp::GamepadProfiles` stores a default map and a per-controller-type
profile in a file on a [littlefs](https://github.com/littlefs-project/littlefs)
partition, and reloads them.

It ends with a pass / fail summary.

## How to use example

### Hardware Required

Any ESP32 with a `littlefs` partition (see `partitions.csv`). The partition
label is configured through `menuconfig`
(`CONFIG_ESPP_FILE_SYSTEM_PARTITION_LABEL`).

### Build and Flash

Build the project and flash it to the board, then run the monitor tool to view
serial output:

```
idf.py -p PORT flash monitor
```

(Replace PORT with the name of the serial port to use.)

(To exit the serial monitor, type ``Ctrl-]``.)

See the Getting Started Guide for full steps to configure and use ESP-IDF to build projects.

## Expected Output

```
I (…) gamepad map example: Starting gamepad map example!
I (…) gamepad map example: Decode a BLE gamepad report, then remap it
I (…) gamepad map example: controller: {buttons: [south], lx: -32767, ly: 128, rx: 128, ry: 128, lt: 0, rt: 32767}
I (…) gamepad map example: mapped: {buttons: [east, r2, left], lx: -32767, ly: 128, rx: 128, ry: 128, lt: 0, rt: 32767}
[PASS] south is mapped to east
[PASS] the left stick also presses d-pad left
[PASS] the stick is kept
[PASS] the right trigger also presses R2
I (…) gamepad map example: Per-controller profiles in a file
I (…) gamepad map example: BSP-D8 map: 4 rule(s); default map: 2 rule(s)
[PASS] the profile is used for its controller
[PASS] other controllers get the default map
[PASS] profiles survive a reload
[PASS] erase a profile
I (…) gamepad map example: 8 passed, 0 failed
I (…) gamepad map example: Gamepad map example complete!
```
2 changes: 2 additions & 0 deletions components/gamepad_map/example/main/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
idf_component_register(SRC_DIRS "."
INCLUDE_DIRS ".")
Loading
Loading