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
4 changes: 4 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,8 @@ jobs:
target: esp32c6
- path: 'components/switch_pro/example'
target: esp32s3
- path: 'components/switch_pro/host_example'
target: esp32s3
- path: 'components/sx126x/example'
target: esp32s3
- path: 'components/system/example'
Expand Down Expand Up @@ -428,6 +430,8 @@ jobs:
target: esp32s3
- path: 'components/ws-s3-touch/example'
target: esp32s3
- path: 'components/xbox_host/example'
target: esp32s3
- path: 'components/xiao-esp32s3-sense/example'
target: esp32s3

Expand Down
2 changes: 2 additions & 0 deletions .github/workflows/upload_components.yml
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,9 @@ jobs:
components/ws-s3-geek
components/ws-s3-lcd-1-47
components/ws-s3-touch
components/xbox_host
components/xiao-esp32s3-sense
components/xinput
namespace: "espp"
# use old version if this isn't a release for testing
version: ${{ github.event.release && github.event.release.tag_name || 'v0.20.2' }}
Expand Down
1 change: 1 addition & 0 deletions components/bldc_haptics/example/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ set(EXTRA_COMPONENT_DIRS
"../../../components/task"
"../../../components/timer"
"../../../components/usb_device"
"../../../components/xinput"
)

# With the component manager disabled (IDF_COMPONENT_MANAGER=0, e.g. in CI so the
Expand Down
1 change: 1 addition & 0 deletions components/canopen/can_bridge_example/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ set(EXTRA_COMPONENT_DIRS
"../../../components/task"
"../../../components/twai"
"../../../components/usb_device"
"../../../components/xinput"
)

# With the component manager disabled (IDF_COMPONENT_MANAGER=0, e.g. in CI so the
Expand Down
13 changes: 13 additions & 0 deletions components/canopen/can_bridge_example/main/idf_component.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
## IDF Component Manager Manifest File - example project overrides.
##
## This file only affects THIS example build, not any published component.
dependencies:
# espp/xinput (the X-Input wire format, which usb_device and xbox_host use) is
# published with the next espp release (it is in
# .github/workflows/upload_components.yml now); until then this example, which
# runs the component manager, would fail to resolve it from the registry.
# Point at the in-repo source, and delete this file once it is on the
# registry.
espp/xinput:
version: "*"
override_path: "../../../xinput"
1 change: 1 addition & 0 deletions components/coredump/example/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ set(EXTRA_COMPONENT_DIRS
"../../../components/system"
"../../../components/task"
"../../../components/usb_device"
"../../../components/xinput"
)

# With the component manager disabled (IDF_COMPONENT_MANAGER=0, e.g. in CI so the
Expand Down
1 change: 1 addition & 0 deletions components/desktop/example/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ set(EXTRA_COMPONENT_DIRS
"../../../components/system"
"../../../components/task"
"../../../components/usb_device"
"../../../components/xinput"
"../../../components/wifi"
)

Expand Down
1 change: 1 addition & 0 deletions components/gamepad_map/webapp_example/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ set(EXTRA_COMPONENT_DIRS
"../../../components/system"
"../../../components/task"
"../../../components/usb_device"
"../../../components/xinput"
)

# With the component manager disabled (IDF_COMPONENT_MANAGER=0, e.g. in CI so the
Expand Down
29 changes: 29 additions & 0 deletions components/hid-rp/include/hid-rp-rumble.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,35 @@ inline uint8_t switch_rumble_motor(std::span<const uint8_t, 4> m) {
}
} // namespace detail

namespace detail {
// One motor's 4 bytes for a level (0..255): the amplitude code whose
// amplitude (switch_rumble_amplitude) is closest, in both bands, at the
// frequencies of the neutral packet (high band 320 Hz, low band 160 Hz). Level
// 0 is the neutral 00 01 40 40.
inline std::array<uint8_t, 4> switch_rumble_motor_bytes(uint8_t level) {
const float target = level / 255.0f;
int code = 0;
float best = target; // code 0: amplitude 0
for (int c = 1; c <= 100; c++) {
const float err = std::fabs(switch_rumble_amplitude(c) - target);
if (err < best) {
best = err;
code = c;
}
}
return {0x00, static_cast<uint8_t>((code << 1) | 0x01),
static_cast<uint8_t>(0x40 | ((code & 1) << 7)), static_cast<uint8_t>(0x40 + (code >> 1))};
}
} // namespace detail

/// The 8-byte rumble packet a host sends a Switch controller for two motor
/// levels (the inverse of decode_switch_rumble(), to within a level's rounding).
inline std::array<uint8_t, 8> encode_switch_rumble(const SwitchRumble &rumble) {
const auto l = detail::switch_rumble_motor_bytes(rumble.left);
const auto r = detail::switch_rumble_motor_bytes(rumble.right);
return {l[0], l[1], l[2], l[3], r[0], r[1], r[2], r[3]};
}

/// The motor levels in an 8-byte Switch rumble packet (left motor's 4 bytes,
/// then the right's). The neutral packet (00 01 40 40 per motor) is 0 / 0.
inline SwitchRumble decode_switch_rumble(std::span<const uint8_t, 8> data) {
Expand Down
20 changes: 20 additions & 0 deletions components/hid-rp/test/hid_rp_rumble_host_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <vector>

#include <doctest/doctest.h>
Expand Down Expand Up @@ -204,3 +205,22 @@ TEST_CASE("switch rumble") {
const uint8_t short_report[9] = {0x10, 0x00, 0x00, 0x01, 0x40, 0x40, 0x00, 0x01, 0x40};
CHECK(!decode_switch_rumble_report(short_report).has_value());
}

TEST_CASE("a host's Switch rumble packets decode back to their levels") {
using espp::hid_rp::SwitchRumble;
// off is the neutral packet
CHECK(espp::hid_rp::encode_switch_rumble(SwitchRumble{}) ==
std::array<uint8_t, 8>{0x00, 0x01, 0x40, 0x40, 0x00, 0x01, 0x40, 0x40});
// every level comes back within the encoding's step
for (int left = 0; left <= 255; left += 5) {
const SwitchRumble r{static_cast<uint8_t>(left), static_cast<uint8_t>(255 - left)};
const auto packet = espp::hid_rp::encode_switch_rumble(r);
const auto back = espp::hid_rp::decode_switch_rumble(packet);
CHECK(std::abs(back.left - r.left) <= 12);
CHECK(std::abs(back.right - r.right) <= 12);
}
// full strength stays at (not beyond) the table's top code, 100
const auto full = espp::hid_rp::encode_switch_rumble(SwitchRumble{255, 255});
CHECK((full[1] >> 1) <= 100);
CHECK(espp::hid_rp::decode_switch_rumble(full) == SwitchRumble{255, 255});
}
1 change: 1 addition & 0 deletions components/mcp266/webapp_example/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ set(EXTRA_COMPONENT_DIRS
"../../../components/task"
"../../../components/twai"
"../../../components/usb_device"
"../../../components/xinput"
)

# With the component manager disabled (IDF_COMPONENT_MANAGER=0, e.g. in CI so the
Expand Down
1 change: 1 addition & 0 deletions components/odrive_native/usb_example/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ set(EXTRA_COMPONENT_DIRS
"../../../components/odrive_ascii"
"../../../components/odrive_native"
"../../../components/usb_device"
"../../../components/xinput"
)

set(
Expand Down
13 changes: 13 additions & 0 deletions components/odrive_native/usb_example/main/idf_component.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
## IDF Component Manager Manifest File - example project overrides.
##
## This file only affects THIS example build, not any published component.
dependencies:
# espp/xinput (the X-Input wire format, which usb_device and xbox_host use) is
# published with the next espp release (it is in
# .github/workflows/upload_components.yml now); until then this example, which
# runs the component manager, would fail to resolve it from the registry.
# Point at the in-repo source, and delete this file once it is on the
# registry.
espp/xinput:
version: "*"
override_path: "../../../xinput"
1 change: 1 addition & 0 deletions components/ota/example/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ set(EXTRA_COMPONENT_DIRS
"../../../components/system"
"../../../components/task"
"../../../components/usb_device"
"../../../components/xinput"
"../../../components/wifi"
)

Expand Down
3 changes: 2 additions & 1 deletion components/switch_pro/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ idf_component_register(
# esp_hw_support (esp_mac.h / esp_random.h) and esp_timer (esp_timer.h) are
# included by the PUBLIC switch_pro.hpp, so downstream consumers of that header
# need their include paths -> public REQUIRES, not PRIV_REQUIRES.
REQUIRES base_component hid-rp timer esp_hw_support esp_timer)
# gamepad_map: GamepadState / RumbleState (switch_pro_host.hpp)
REQUIRES base_component gamepad_map hid-rp timer esp_hw_support esp_timer)
49 changes: 49 additions & 0 deletions components/switch_pro/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,56 @@ The example's `sdkconfig.defaults` enables the TinyUSB HID class
keeps the console on UART0 (the native USB port is taken by the HID interface;
see the `usb_device` docs on the shared ESP32-S3 USB PHY).

## Host side: `espp::SwitchProHost`

`espp::SwitchProHost` (`switch_pro_host.hpp`) is the other end of the cable: it
reads a real Pro controller plugged into a USB **host** port. Over USB the Pro
controller is a HID device, but a generic HID gamepad decoder cannot read it: it
reports nothing useful until a host runs its handshake, and its full input
report (`0x30`) is vendor-defined. `SwitchProHost` runs that handshake and
decodes the reports into gamepad_map's `espp::GamepadState`:

1. init commands (OUTPUT report `0x80`): device info, handshake, baud rate,
handshake, USB only (no Bluetooth timeout);
2. subcommands (OUTPUT report `0x01`): the full input report mode (`0x30`), the
stick calibration from the controller's SPI flash (factory at `0x603D`, then
the user calibration at `0x8010` when it has one), vibration on, and the
player lights;
3. then every `0x30` report is decoded with that calibration, and
`set_rumble()` (gamepad_map's `espp::RumbleState`) / `set_player()` drive the
motors and the lights.

It is transport-light too: give it a function that sends an OUTPUT report
(`espp::UsbHost::HidDevice::send_output_report()` takes the same arguments),
feed it every INPUT report (`on_input_report()`, byte 0 the report ID), and call
`update()` every 10..50 ms while it starts: it resends a step whose reply is late
and skips one that is never answered (with typical values for a calibration it
could not read), so a controller that only partly follows the protocol still
ends up streaming input. A calibration that covers the whole 12-bit range, as
some third-party controllers that present themselves as a Pro controller store,
is also replaced by typical values, so their sticks still reach full deflection.

```cpp
std::shared_ptr<espp::UsbHost::HidDevice> device = ...; // VID/PID 057E:2009
espp::SwitchProHost pro({
.send_report = [device](uint8_t id, std::span<const uint8_t> payload) {
std::error_code ec;
return device->send_output_report(id, payload, ec);
},
.on_state = [](const espp::GamepadState &state) { /* ... */ },
.player = 1,
});
device->set_input_callback([&](std::span<const uint8_t> report) { pro.on_input_report(report); });
pro.start();
// ... and pro.update() from a timer every ~20 ms
```

The [host example](./host_example) does this with `espp::UsbHost` on an
ESP32-S3: it logs the controller's state and rumbles it with ZL / ZR.

## Requirements

- An ESP with the native USB-OTG peripheral (ESP32-S3 / S2 / P4).
- espp `usb_device` (or another USB HID transport), `hid-rp`, `timer`.
- For the host side: espp `usb_host` (or another HID host transport) and
`gamepad_map` (`GamepadState` / `RumbleState`).
6 changes: 6 additions & 0 deletions components/switch_pro/example/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,18 @@ include($ENV{IDF_PATH}/tools/cmake/project.cmake)
# add only the component directories that we want to use
set(EXTRA_COMPONENT_DIRS
"../../../components/base_component"
"../../../components/dispatcher"
"../../../components/format"
"../../../components/gamepad_map"
"../../../components/persistent_data"
"../../../components/serialization"
"../../../components/stream_frame"
"../../../components/logger"
"../../../components/task"
"../../../components/timer"
"../../../components/hid-rp"
"../../../components/usb_device"
"../../../components/xinput"
"../../../components/switch_pro"
)

Expand Down
13 changes: 13 additions & 0 deletions components/switch_pro/example/main/idf_component.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
## IDF Component Manager Manifest File - example project overrides.
##
## This file only affects THIS example build, not any published component.
dependencies:
# espp/xinput (the X-Input wire format, which usb_device and xbox_host use) is
# published with the next espp release (it is in
# .github/workflows/upload_components.yml now); until then this example, which
# runs the component manager, would fail to resolve it from the registry.
# Point at the in-repo source, and delete this file once it is on the
# registry.
espp/xinput:
version: "*"
override_path: "../../../xinput"
34 changes: 34 additions & 0 deletions components/switch_pro/host_example/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# 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)

include($ENV{IDF_PATH}/tools/cmake/project.cmake)

# espp's components, from this repository; the USB Host Library (`usb`) and
# the HID class driver espp::UsbHost uses come from the ESP Component Registry
set(EXTRA_COMPONENT_DIRS
"../../../components/base_component"
"../../../components/dispatcher"
"../../../components/format"
"../../../components/gamepad_map"
"../../../components/hid-rp"
"../../../components/logger"
"../../../components/persistent_data"
"../../../components/serialization"
"../../../components/stream_frame"
"../../../components/switch_pro"
"../../../components/task"
"../../../components/timer"
"../../../components/usb_host"
)

set(
COMPONENTS
"main esptool_py switch_pro usb_host"
CACHE STRING
"List of components to include"
)

project(switch_pro_host_example)

set(CMAKE_CXX_STANDARD 23)
35 changes: 35 additions & 0 deletions components/switch_pro/host_example/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Switch Pro Controller Host Example

This example reads a Nintendo Switch Pro controller (NS1) plugged into the
ESP32-S3's native USB port in host mode. `espp::UsbHost` opens it as a HID
device, and `espp::SwitchProHost` runs the USB handshake that starts it, reads
its stick calibration, lights the player 1 LED, and decodes its input reports
into `espp::GamepadState`, which the example logs. The triggers rumble the
controller (ZL: the left grip, ZR: the right).

## How to use the example

### Hardware Required

An ESP32-S3 (or -S2 / -P4) board whose native USB port can **source VBUS** to
the controller (a USB-A host port, or an OTG adapter with power), and a
Nintendo Switch Pro controller with a USB-C cable. On the ESP32-S3 the console
runs on UART0 (the native USB port is the host), so monitor it with a UART
adapter.

### Build and Flash

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

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

## Example Output

```
I (1234) Switch Pro Host: Starting the Switch Pro controller host example
I (2345) Switch Pro Host: Pro controller connected: 'Pro Controller'
I (2600) Switch Pro Host: Pro controller running
I (2700) Switch Pro Host: GamepadState{buttons: [east], left_x: 0, ...}
```
5 changes: 5 additions & 0 deletions components/switch_pro/host_example/main/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
idf_component_register(
SRC_DIRS "."
INCLUDE_DIRS "."
REQUIRES gamepad_map switch_pro timer usb_host
)
Loading
Loading