Skip to content
Merged
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
52 changes: 51 additions & 1 deletion .github/workflows/platformio.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,16 @@ name: ESP32-BLE-Gamepad platformio CI
- "master"
- "ci-builds-*"
pull_request:
# Ad-hoc builds with no local toolchain: fork the repo (or use this one if you
# have write access), open the Actions tab, pick this workflow, "Run workflow",
# optionally enter a ref to build, then download the test-firmware-<board>
# artifact from the finished run. See test/ci_build/README.md.
workflow_dispatch:
inputs:
ref:
description: "Branch, tag or SHA to build (blank = the branch you run this from; a PR is refs/pull/<number>/head)"
required: false
type: string

concurrency:
# https://docs.github.com/en/actions/examples/using-concurrency-expressions-and-a-test-matrix
Expand All @@ -31,10 +40,21 @@ jobs:
# espidf). Re-enable once that lands; see the commented-out
# [env:esp32c6] in test/ci_build/platformio.ini.
board: [esp32dev, esp32s3, esp32c3]
include:
# `chip` is the name esptool expects when flashing the artifact.
- board: esp32dev
chip: esp32
- board: esp32s3
chip: esp32s3
- board: esp32c3
chip: esp32c3

steps:
- name: Checkout code
uses: actions/checkout@v7
with:
# Empty for non-dispatch events, so checkout uses the triggering ref.
ref: ${{ inputs.ref }}

- name: Set up Python
uses: actions/setup-python@v7
Expand All @@ -46,8 +66,38 @@ jobs:
python -m pip install --upgrade pip
pip install platformio

- name: Build Test firmware for ${{ matrix.board }}
- name: Build test firmware for ${{ matrix.board }}
run: |
# pio run -d examples/TestAll/TestAll.ino -e ${{ matrix.board }} -D BLE_GAMEPAD_DEBUG=1 --verbose
cd test/ci_build
pio run -e ${{ matrix.board }}

- name: Collect firmware binaries
run: |
cd test/ci_build
build_dir=".pio/build/${{ matrix.board }}"
mkdir -p dist
cp "$build_dir/firmware.bin" "dist/test-firmware-${{ matrix.board }}.bin"
cp "$build_dir/firmware-factory.bin" "dist/test-firmware-${{ matrix.board }}-factory.bin"

- name: Upload firmware artifact
uses: actions/upload-artifact@v7
with:
name: test-firmware-${{ matrix.board }}
path: test/ci_build/dist/*.bin

- name: Flashing instructions
run: |
{
echo "### Test firmware — ${{ matrix.board }}"
echo
echo "Download the \`test-firmware-${{ matrix.board }}\` artifact, then either:"
echo
echo '- Flash `test-firmware-'"${{ matrix.board }}"'-factory.bin` at offset `0x0`:'
echo
echo ' ```'
echo ' esptool.py --chip ${{ matrix.chip }} write_flash 0x0 test-firmware-${{ matrix.board }}-factory.bin'
echo ' ```'
echo
echo '- Or drag that `-factory.bin` onto <https://espressif.github.io/esptool-js/> (flash address `0x0`).'
} >> "$GITHUB_STEP_SUMMARY"
19 changes: 19 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ jobs:
runs-on: ubuntu-latest
permissions:
contents: write
actions: read # download the test-firmware artifacts from the triggering run

steps:
- name: Checkout tag
Expand Down Expand Up @@ -73,6 +74,24 @@ jobs:
$prerelease_flag
fi

- name: Download test firmware artifacts
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
gh run download "${{ github.event.workflow_run.id }}" \
--repo "${{ github.repository }}" \
--pattern 'test-firmware-*' \
--dir firmware

- name: Attach test firmware to release
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
# Artifacts download into per-artifact subdirs; upload every .bin.
find firmware -type f -name '*.bin' -exec \
gh release upload "${{ steps.version.outputs.tag }}" {} \
--repo "${{ github.repository }}" --clobber ';'

- name: Set up Python
uses: actions/setup-python@v7
with:
Expand Down
2 changes: 1 addition & 1 deletion examples/Diagnostics/Diagnostics.ino
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ void setup()

bleGamepadConfig.setButtonCount(8); // covers BUTTON_1..BUTTON_8
//bleGamepadConfig.setHatSwitchCount(0);
// Need one HAT or else gaempad is not registered on Android. The hat is never used, so just leave it at 1.
// Need one HAT or else gamepad is not registered on AndroidTV. The hat is never used, so just leave it at 1.
bleGamepadConfig.setHatSwitchCount(1);
bleGamepadConfig.setWhichAxes(false, false, false, false, false, false, false, false);

Expand Down
102 changes: 102 additions & 0 deletions test/ci_build/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
# CI test firmware

A self-contained firmware that builds this library and exercises it at runtime,
with no wiring and no extra libraries. It exists so you can flash a known-good
device and confirm the library works before chasing a build- or wiring-specific
problem.

## What it does

`src/main.cpp` advertises as **`ESP32 BLE Gamepad Test`** and brings up the full
BLE profile the library offers:

- the **gamepad HID** service (24 buttons, the right thumbstick, one unused hat
switch; everything else left out to keep the HID descriptor small);
- every **Device Information Service** characteristic, set to an identifiable
value (model / serial number / firmware / hardware / software revision — the
Software Revision carries the build id);
- the **Nordic UART Service (NUS)** — on connect it sends a greeting, then a
status line every ~3 s, and answers `help` / `status` (anything else is echoed
back). Use nRF Connect or any BLE UART terminal.

Once a host connects it, on its own:

- presses one button at a time, cycling a range **well above `BUTTON_16`**
(`FIRST_TEST_BUTTON`..`LAST_TEST_BUTTON` in `src/main.cpp`). Buttons `1..16`
are skipped on purpose — Android maps them to named controls (A/B/X/Y,
shoulders/triggers, start/select, stick clicks), so auto-pressing them drives
UI navigation on the host. Buttons `17+` land on Android's generic
`KEYCODE_BUTTON_*` range that nothing acts on;
- sweeps the **right thumbstick** (Z / RZ) around a circle, kept under ~50%
deflection (right stick not left, small throw, so it doesn't move Android's
on-screen focus);
- ramps the battery level `100% -> 10% -> 100%` on a ~5 s tick, reporting
**discharging** while it falls and **charging** while it rises, with a
**critical** power level at or below 20%.

Progress is printed to serial at `115200` baud. The Software Revision
characteristic reports the exact build, e.g.
`ESP32-BLE-Gamepad 0.7.5-rc0+g05599be` (set by `inject_version.py` from
`library.properties` + git).

## Watching the serial log — no local tools

<https://www.serialmonitor.org> is a browser serial monitor. Click **Connect**,
pick the board's port, and set **baud `115200`**.

It uses the **Web Serial API**, so it needs a Chromium-based desktop browser —
Chrome, Edge or Opera — the same requirement as
<https://espressif.github.io/esptool-js>. Firefox and Safari don't implement Web
Serial.

| OS | Port looks like |
| --- | --- |
| macOS | `/dev/cu.usbserial-XXXX` (CH340/CP210x boards) or `/dev/cu.usbmodemXXXX` (native-USB S3/C3) |
| Linux | `/dev/ttyUSB0` (CH340/CP210x) or `/dev/ttyACM0` (native USB) |
| Windows | `COM3`, `COM4`, … (see Device Manager) |

With a toolchain, `pio device monitor -e esp32dev` or the Arduino IDE Serial
Monitor at `115200` do the same job. Close any other monitor before flashing —
only one program can hold the port.

## Building locally

```
cd test/ci_build
pio run -e esp32dev # or esp32s3, esp32c3
```

Each build produces, in `.pio/build/<env>/`:

- `firmware.bin` — application image (flash at the board's app offset), and
- `firmware-factory.bin` — bootloader + partitions + app merged into one image,
flashable at offset `0x0` (see `merge_firmware.py`).

## Getting a prebuilt binary (no toolchain)

`.github/workflows/platformio.yml` builds all three boards on every push/PR and
uploads a `test-firmware-<board>` artifact (both `.bin` variants). Tagged
releases also get the binaries attached (and release assets need no login).

**Build any branch/PR/tag on demand:**

1. Fork this repo (or use it directly if you have write access) and enable
Actions on the fork.
2. Actions tab → **ESP32-BLE-Gamepad platformio CI** → **Run workflow**.
3. Optionally set **ref** to the branch, tag or SHA to build (a PR is
`refs/pull/<number>/head`); leave blank to build the branch you launch from.
4. When the run finishes, download the `test-firmware-<board>` artifact from it.

Downloading Actions artifacts requires a (free) GitHub login; release assets do
not.

## Flashing it

Grab `test-firmware-<board>-factory.bin` and either:

```
esptool.py --chip <esp32|esp32s3|esp32c3> write_flash 0x0 test-firmware-<board>-factory.bin
```

or drag it onto <https://espressif.github.io/esptool-js/> with flash address
`0x0`.
46 changes: 46 additions & 0 deletions test/ci_build/inject_version.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# PlatformIO pre-build step. Exposes two macros:
# BLE_GAMEPAD_LIB_VERSION - "ESP32-BLE-Gamepad <version>+g<short-sha>" from
# ../../library.properties and git; main.cpp reports it as the Software
# Revision DIS characteristic so a GATT browser shows which build is flashed.
# BLE_GAMEPAD_BUILD_TIME - UTC timestamp of this build. It changes every run,
# which also forces main.cpp to recompile, so the value printed on boot is a
# reliable "did my upload actually land?" check.

import subprocess
import time
from pathlib import Path

Import("env") # noqa: F821 (injected by PlatformIO)

lib_root = Path(env["PROJECT_DIR"]).resolve().parent.parent

version = "unknown"
props = lib_root / "library.properties"
if props.is_file():
for line in props.read_text().splitlines():
if line.startswith("version="):
version = line.split("=", 1)[1].strip() or version
break

sha = ""
try:
sha = subprocess.check_output(
["git", "-C", str(lib_root), "rev-parse", "--short", "HEAD"],
text=True,
stderr=subprocess.DEVNULL,
).strip()
except Exception:
pass

identifier = "ESP32-BLE-Gamepad " + version
if sha:
identifier += "+g" + sha

build_time = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())

print("BLE_GAMEPAD_LIB_VERSION = %s" % identifier)
print("BLE_GAMEPAD_BUILD_TIME = %s" % build_time)
env.Append(CPPDEFINES=[
("BLE_GAMEPAD_LIB_VERSION", env.StringifyMacro(identifier)),
("BLE_GAMEPAD_BUILD_TIME", env.StringifyMacro(build_time)),
])
58 changes: 58 additions & 0 deletions test/ci_build/merge_firmware.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# PlatformIO post-build step: merge the bootloader, partition table, boot_app0
# and application into one image flashable at offset 0x0. This is what web
# flashers (https://espressif.github.io/esptool-js/) expect and it lets people
# flash the CI test firmware with a single command and no toolchain.
#
# Produces <PROGNAME>-factory.bin next to firmware.bin in $BUILD_DIR.

Import("env") # noqa: F821 (injected by PlatformIO)

board_config = env.BoardConfig()

chip = board_config.get("build.mcu", "esp32")
flash_size = board_config.get("upload.flash_size", "4MB")
flash_mode = board_config.get("build.flash_mode", env.subst("$BOARD_FLASH_MODE"))
flash_freq = str(board_config.get("build.f_flash", "40000000L"))
flash_freq = flash_freq.replace("000000L", "m").replace("L", "")
# The espressif32 builder exposes the app offset as $ESP32_APP_OFFSET; fall
# back to the board manifest and then the common default.
app_offset = (
env.subst("$ESP32_APP_OFFSET")
or board_config.get("upload.offset_address", "")
or "0x10000"
)


def merge_bin(source, target, env):
firmware_path = env.subst("$BUILD_DIR/${PROGNAME}.bin")
merged_path = env.subst("$BUILD_DIR/${PROGNAME}-factory.bin")

# FLASH_EXTRA_IMAGES holds (offset, path) pairs for the bootloader,
# partition table and boot_app0; the app itself goes at app_offset.
segments = []
for offset, image in env.get("FLASH_EXTRA_IMAGES", []):
segments += [offset, image]
segments += [app_offset, firmware_path]

cmd = [
'"$PYTHONEXE"',
'"$OBJCOPY"',
"--chip",
chip,
"merge_bin",
"-o",
'"%s"' % merged_path,
"--flash_mode",
flash_mode,
"--flash_freq",
flash_freq,
"--flash_size",
flash_size,
]
for item in segments:
cmd.append(item if item.startswith("0x") else '"%s"' % item)

env.Execute(env.VerboseAction(" ".join(cmd), "Merging %s" % merged_path))


env.AddPostAction("$BUILD_DIR/${PROGNAME}.bin", merge_bin)
41 changes: 14 additions & 27 deletions test/ci_build/platformio.ini
Original file line number Diff line number Diff line change
@@ -1,35 +1,30 @@
[env:esp32dev]
# Options shared by every environment below.
[env]
platform = espressif32
board = esp32dev
framework = arduino
lib_ldf_mode = deep+
lib_deps =
h2zero/NimBLE-Arduino
../../
build_flags =
-D BLE_GAMEPAD_DEBUG=1
-D BLE_GAMEPAD_DEBUG=0
# -D BLE_GAMEPAD_DEBUG=1

monitor_speed = 115200
extra_scripts =
# Sets BLE_GAMEPAD_LIB_VERSION from library.properties + git.
pre:inject_version.py
# Emits <PROGNAME>-factory.bin: a single image flashable at offset 0x0.
post:merge_firmware.py

[env:esp32dev]
board = esp32dev

[env:esp32c3]
platform = espressif32
board = esp32-c3-devkitc-02
framework = arduino
lib_ldf_mode = deep+
lib_deps =
h2zero/NimBLE-Arduino
../../
build_flags =
-D BLE_GAMEPAD_DEBUG=1

[env:esp32s3]
platform = espressif32
board = esp32-s3-devkitc-1
framework = arduino
lib_ldf_mode = deep+
lib_deps =
h2zero/NimBLE-Arduino
../../
build_flags =
-D BLE_GAMEPAD_DEBUG=1

# [env:esp32c6]
# Disabled for now: the official "espressif32" platform's
Expand All @@ -40,12 +35,4 @@ build_flags =
# but we're holding off on that until the official platform reaches
# GA support for C6 under Arduino. Re-enable in .github/workflows/platformio.yml
# once that lands.
# platform = espressif32
# board = esp32-c6-devkitc-1
# framework = arduino
# lib_ldf_mode = deep+
# lib_deps =
# h2zero/NimBLE-Arduino
# ../../
# build_flags =
# -D BLE_GAMEPAD_DEBUG=1
Loading
Loading