Compare commits

...

37 commits
main ... main

Author SHA1 Message Date
9838c4ee64
feat: implement XInput mode (#27)
Reviewed-on: NaxdyOrg/NaxGCC-FW#27
2024-10-29 19:53:18 +00:00
6475e844a9
chore: improve flake & ci (#28)
Reviewed-on: NaxdyOrg/NaxGCC-FW#28
2024-10-27 20:49:20 +00:00
8f8d47704d
feat: implement "Pro-Controller" mode (#26)
Based on the pro-controller code from https://github.com/HandHeldLegend/HOJA-LIB-RP2040

Author has given their consent for this to be GPL'd:

![image](/attachments/c2551d3a-9b35-4c67-ad28-3778f9e04e29)

Reviewed-on: NaxdyOrg/NaxGCC-FW#26
2024-10-14 19:55:54 +00:00
4e1af50ebd
ci: adapt to new format 2024-09-01 17:21:38 +02:00
5cdd3348f4 implement filter for angled ftilts (#23)
Reviewed-on: NaxdyOrg/NaxGCC-FW#23
Reviewed-by: Naxdy <naxdy@naxdy.org>
Co-authored-by: Marcel Romagnuolo <marcello.r@gmx.net>
Co-committed-by: Marcel Romagnuolo <marcello.r@gmx.net>
2024-06-29 12:58:01 +00:00
b6b5bb25a7
feat: don't inline time-critical functions 2024-04-30 13:59:52 +02:00
a09d21b4fd
chore: fix changelog symlink 2024-04-25 11:26:24 +02:00
6545b0219a
feat: bump to v1.1.1 / improve opt-level 2024-04-25 10:50:31 +02:00
1c398652ad
chore: bump version to 1.1.0 2024-04-25 10:40:44 +02:00
fef0475abf
chore: add v1.1.0 changelog 2024-04-25 10:37:51 +02:00
c8a31df648
feat: benchmark new best opt-level 2024-04-25 10:31:38 +02:00
417c4a677a
feat(config): improve ticker during notch adjustment 2024-04-20 11:40:21 +02:00
974aa6b7af
feat(hid): add msos descriptor 2024-04-20 11:06:33 +02:00
2a01cd732a
feat(hid): distinguish "OG" from "PC" mode 2024-04-19 17:14:20 +02:00
818e0abf76
feat(hid): streamline timing between consistency and superhack 2024-04-19 17:07:26 +02:00
d661abc882
chore(input): use AnyPin for button state func 2024-04-18 18:00:53 +02:00
6f1d49b164
chore(config): improve naming & comments 2024-04-16 00:04:27 +02:00
c89938d23a
chore(ci): add github action for PR's 2024-04-16 00:01:55 +02:00
6b53472817
chore: add CONTRIBUTING.md 2024-04-12 21:46:04 +02:00
93ab0ffb3d
chore: remove unused dependency 2024-04-12 21:45:28 +02:00
569ae9784f
change(hid): set poll interval to 1ms by default 2024-04-12 21:25:32 +02:00
d39451dc2e
perf: improve opt-level 2024-04-12 19:49:08 +02:00
839638d528
chore(readme): add matrix link 2024-04-11 12:17:30 +02:00
1d67284516
chore: amend readme 2024-04-09 19:30:52 +02:00
43708a9365
fix(config): display rumble strength to user 2024-04-09 19:27:24 +02:00
f100f81842
feat(config): add ability to skip stick measurements (#11)
Reviewed-on: NaxdyOrg/NaxGCC-FW#11
2024-04-09 17:14:43 +00:00
88b6a22182
feat(superhack): give the console time to initialize 2024-04-09 19:14:16 +02:00
a785fb69eb
chore: bump version to 1.0.0 2024-04-08 23:41:44 +02:00
8a0760a620
chore: clippy concurrency (#10)
Reviewed-on: NaxdyOrg/NaxGCC-FW#10
2024-04-08 21:25:02 +00:00
fd9f9b533f
chore: add v1.0.0 changelog 2024-04-08 23:04:56 +02:00
ba7164dd9c
feat(ci): add workflow for stable releases 2024-04-08 22:55:23 +02:00
702cbe5eb0
add mode to further improve input latency while maintaining accuracy (#8)
This feels even hackier than consistency mode... we hold off on writing USB reports until the button state actually changes. Passes the input integrity benchmark with ~99.6%, but that doesn't mean much since the challenge is preserving input integrity for inputs less than 8.33ms apart.

Current rate limiter looks good from initial measurements, so will probably merge this at some point and leave it up to users to try the mode out or not. For now, I'd still recommend regular consistency mode, it's still hacky, but way less than this.

Also, not breaking because the new enum for input consistency mode is backward compatible with the bool.

Reviewed-on: NaxdyOrg/NaxGCC-FW#8
2024-04-08 20:53:23 +00:00
c2e4066125
chore: cancel previous clippy runs if need be 2024-04-08 22:40:38 +02:00
d49c72d9c0
feat(config): add ability to display current stick calibration values 2024-04-06 21:05:22 +02:00
c43e66f91d
chore: clarify nightly 2024-04-05 23:46:05 +02:00
71aaf07b29
chore(readme): clarify default behavior 2024-04-05 23:40:07 +02:00
0249f69b91
chore: amend readme & add license 2024-04-05 23:37:35 +02:00
28 changed files with 3511 additions and 908 deletions

13
.changelogs/v1.0.0.md Normal file
View file

@ -0,0 +1,13 @@
This marks the very first release of the NaxGCC firmware!
Compared to the PhobGCC firmware, the NaxGCC firmware has the following changes:
- fully rewritten in Rust, using the [embassy-rs](https://github.com/embassy-rs/embassy) framework for asynchronous operations
- directly connects to the console via USB, pretending to be a GCC adapter with 1 controller (itself) connected
- features a special "input consistency mode" that even further improves input consistency, beyond what is delivered by any other controller / adapter
- features an experimental "input latency mode" that reduces input latency even further, at a slight cost to input consistency compared to "consistency" mode
- improves button scan rate to ~50us (microseconds) compared to 1ms for the PhobGCC
- a few calibration button combos have changed (consult our documentation for details)
- pressing `A+X+Y` while plugging in the controller to your PC will enter bootloader mode, allowing you to flash a new firmware image
Huge thank you to the developers of the PhobGCC for providing a solid foundation to build upon!

7
.changelogs/v1.1.0.md Normal file
View file

@ -0,0 +1,7 @@
This is mainly a QoL and performance update for the NaxGCC. The following changes have been made:
- Added a MSOS descriptor to the USB device, allowing the NaxGCC to be immediately recognized on Windows, without the need for a custom driver. This should make it plug-and-play for Dolphin on Windows.
- Improved the "rate limiting" of SuperHack mode, which should make it more consistent and less likely to drop inputs compared to "Consistency" mode.
- Added a new "PC" mode which polls at 1000Hz, for use on PC or other consoles that don't have any issues with 1000Hz polling. The "OG" mode now polls at 125Hz always, regardless of which device it is connected to.
To update your firmware, plug in your controller while keeping the `A+X+Y` buttons held. Then drag & drop the `.uf2` file (found below, under Downloads) onto the storage device that appears.

1
.changelogs/v1.1.1.md Symbolic link
View file

@ -0,0 +1 @@
v1.1.0.md

12
.changelogs/v1.2.0.md Normal file
View file

@ -0,0 +1,12 @@
This release introduces a major new feature to combat a regression introduced in Switch firmware 19.0.0. For those unaware, Switch firmware 19.0.0 breaks compatibility with GCC adapters, including NaxGCC, which advertises itself as a GCC adapter.
Starting with this version, you will be able to connect NaxGCC in "Pro-Controller Mode" by pressing and holding `Start` while plugging it in. This will cause the NaxGCC to advertise itself as a Nintendo Switch Pro Controller, and therefore be unaffected by the bug in the latest Switch firmware. All input consistency modes remain fully functional while in this mode, and your settings (including calibration) carry over as well.
While in Pro-Controller Mode, pressing `Z+Start` will act like the home button on a regular Pro Controller. Additionally, pressing `L` will press both `L` and `ZL` at the same time (since the GCC only has one left shoulder button). This is useful if you want to map things like jump (short-hop macro) or shield (prevent rolling) to it.
> [!NOTE]
> As of this version, rumble will _not_ work while in Pro Controller Mode.
---
To update your firmware, plug in your controller to your computer while keeping the `A+X+Y` buttons held. Then drag & drop the `.uf2` file (found below, under Downloads) onto the storage device that appears.

10
.changelogs/v1.3.0.md Normal file
View file

@ -0,0 +1,10 @@
This release introduces XInput mode for the NaxGCC. This mode is mostly useful for playing games on PC, as it offers the best out-of-the-box compatiblity experience with most titles. Similar to Pro-Controller Mode, this is not a permanent configuration that you set, but a mode that is activated by pressing a button while plugging your controller in.
To enter XInput Mode, press and hold the `X` button while plugging in your controller. While in XInput mode, your NaxGCC will _always_ poll at 1ms intervals, regardless of your chosen input consistency mode setting. Once you go back to GCC or Pro-Controller Mode, your desired input consistency setting will be restored.
> [!NOTE]
> As of this version, rumble will _not_ work while in XInput mode.
---
To update your firmware, plug in your controller to your computer while keeping the `A+X+Y` buttons held. Then drag & drop the `.uf2` file (found below, under Downloads) onto the storage device that appears.

View file

@ -2,18 +2,25 @@ name: Code quality
on: pull_request
concurrency:
group: ${{ env.GITHUB_HEAD_REF }}
cancel-in-progress: true
jobs:
check:
runs-on: nix-flakes
steps:
- name: Set up packages
run: |
echo "extra-substituters = https://builder.naxdy.org/attic" >> /etc/nix/nix.conf
echo "extra-trusted-public-keys = attic:05LdE8Nav5Qd1E+KOJqSwdr+WE1z8AUmSb3oKL7s8dk=" >> /etc/nix/nix.conf
nix profile install nixpkgs#nodejs "github:zhaofengli/attic?ref=6eabc3f02fae3683bffab483e614bebfcd476b21"
echo "PATH=/nix/var/nix/profiles/per-user/root/profile/bin:$PATH" >> "$GITHUB_ENV"
- uses: actions/checkout@v4
- name: Set up attic binary cache
uses: https://git.naxdy.org/NaxdyOrg/attic-action@v0.3
with:
endpoint: "${{ vars.BINARY_CACHE_URL }}"
token: ""
cache: "${{ vars.PUBLIC_BINARY_CACHE_NAME }}"
skip-push: true
- name: Run Clippy
run: |
nix develop . --command cargo clippy -- -Dwarnings
nix flake check . --print-build-logs -j auto

View file

@ -13,24 +13,22 @@ jobs:
runs-on: nix-flakes
steps:
- name: Set up packages
run: |
echo "extra-substituters = https://builder.naxdy.org/attic" >> /etc/nix/nix.conf
echo "extra-trusted-public-keys = attic:05LdE8Nav5Qd1E+KOJqSwdr+WE1z8AUmSb3oKL7s8dk=" >> /etc/nix/nix.conf
nix profile install nixpkgs#nodejs "github:zhaofengli/attic?ref=6eabc3f02fae3683bffab483e614bebfcd476b21"
echo "PATH=/nix/var/nix/profiles/per-user/root/profile/bin:$PATH" >> "$GITHUB_ENV"
- name: Set up attic binary cache
run: |
attic login "${{ vars.PUBLIC_BINARY_CACHE_NAME }}" "${{ vars.BINARY_CACHE_URL }}" "${{ secrets.PUBLIC_BINARY_CACHE_AUTH_KEY }}"
attic use "${{ vars.PUBLIC_BINARY_CACHE_NAME }}"
uses: https://git.naxdy.org/NaxdyOrg/attic-action@v0.3
with:
endpoint: "${{ vars.BINARY_CACHE_URL }}"
token: "${{ secrets.PUBLIC_BINARY_CACHE_AUTH_KEY }}"
cache: "${{ vars.PUBLIC_BINARY_CACHE_NAME }}"
- uses: actions/checkout@v4
- name: Run flake checks
run: |
nix flake check . --print-build-logs -j auto
- name: Build firmware image
run: |
nix build .# -o dist --print-build-logs
- name: Push derivations to binary cache
run: |
cd /nix/store
attic push "${{ vars.PUBLIC_BINARY_CACHE_NAME }}" $(ls /nix/store --ignore='*.drv' --ignore='*fake_nixpkgs*')
- name: (Re-)generate tag
run: |
git config --global user.email "noreply@naxdy.org"
@ -40,6 +38,7 @@ jobs:
git tag nightly -m "Nightly Release"
git checkout nightly
git push --set-upstream origin nightly --force
- name: Publish nightly release
uses: https://gitea.com/actions/gitea-release-action@v1.3.0
with:
@ -48,7 +47,7 @@ jobs:
prerelease: true
name: "Nightly Release"
body: >
This is an automatically generated nightly release.
This is an automatically generated nightly release, based on the current state of the `main` branch.
**WARNING:** This release may contain untested changes and could potentially break your configuration. Use at your own risk. **Do not report issues you encounter with nightly releases.**
files: |

View file

@ -0,0 +1,31 @@
name: Publish stable release
on:
push:
tags:
- 'v[0-9]+.[0-9]+.[0-9]+'
jobs:
build:
runs-on: nix-flakes
steps:
- name: Set up attic binary cache
uses: https://git.naxdy.org/NaxdyOrg/attic-action@v0.3
with:
endpoint: "${{ vars.BINARY_CACHE_URL }}"
token: "${{ secrets.PUBLIC_BINARY_CACHE_AUTH_KEY }}"
cache: "${{ vars.PUBLIC_BINARY_CACHE_NAME }}"
- uses: actions/checkout@v4
- name: Build firmware image
run: |
nix build .# -o dist --print-build-logs
- name: Publish stable release
uses: https://gitea.com/actions/gitea-release-action@v1.3.0
with:
token: "${{ github.token }}"
tag_name: "${{ env.GITHUB_REF_NAME }}"
name: "NaxGCC ${{ env.GITHUB_REF_NAME }}"
body_path: .changelogs/${{ env.GITHUB_REF_NAME }}.md
files: |
dist/bin/*

21
.github/workflows/no-pr.yml vendored Normal file
View file

@ -0,0 +1,21 @@
name: Close pull request
on:
pull_request_target:
types:
- opened
jobs:
close-pr:
permissions:
pull-requests: write
runs-on: ubuntu-latest
steps:
- run: gh pr close "$NUMBER" --comment "$COMMENT"
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
NUMBER: ${{ github.event.number }}
COMMENT: >
Thank you for submitting your pull request.
Please note that the main repository is located at https://git.naxdy.org/NaxdyOrg/NaxGCC-FW - please submit your pull request there if you would like it to be considered for merging.

53
CONTRIBUTING.md Normal file
View file

@ -0,0 +1,53 @@
# Contributing
If you'd like to contribute to the development of the NaxGCC firmware, you're in the right place! This document will guide you through the process of setting up your development environment, building the firmware, testing it on your controller, and submitting your changes for review.
## Getting Started
The firmware is built using [nix](https://nixos.org/), a package manager that provides a consistent development environment across different systems. The easiest way for you to get going is to install nix on your system, [enable flakes](https://nixos.wiki/wiki/Flakes), and then run the following command:
```sh
nix develop .
```
This will begin downloading all the necessary development tools, such as Rust and the ARM toolchain, and will drop you into a shell where you can immediately run `cargo build` to build the firmware, without any additional setup. From this shell, you can also run your favorite text editor, and it will also have access to all the necessary tools.
If you want to take this a step further, you can install [direnv](https://direnv.net/), which will automatically drop you into a development shell whenever you enter the project directory. It also has a corresponding [VSCode extension](https://marketplace.visualstudio.com/items?itemName=mkhl.direnv) that will automatically set up your environment when you open the project in VSCode/VSCodium.
### Building the firmware
To build the firmware, simply run:
```sh
cargo build
```
for a development build, and
```sh
nix build .#
```
for a release build. Release builds will be placed in `./result/bin/` and can be flashed to your controller by simply dragging & dropping the `.uf2` file onto the controller while it's in bootloader mode (press `A+X+Y` while plugging it in).
### Debugging
The NaxGCC board exposes all the necessary pins to hook up a Pico debug probe. Running
```sh
cargo run
```
will automatically look for connected debug probes and use the first one it finds to flash the firmware to the controller.
## Submitting your changes
When you're ready to submit your changes, simply push your branch to the repository and open a pull request. The CI will automatically run tests on your changes, and a maintainer will review your code. If everything looks good, your changes will be merged into the main branch.
### Things not to submit
We strive to keep the NaxGCC firmware as clean and minimal as possible. As such, we have a few guidelines for contributions:
- **No Melee-specific features**: The primary focus of the NaxGCC firmware is Smash Ultimate and other Nintendo Switch games. As such, features that are solely beneficial for emulated Melee gameplay (e.g. analog trigger functionality) will probably be rejected. Keep in mind that you cannot use a NaxGCC on an actual GameCube/Wii anyway!
- **No time-based macros or other automation**: The NaxGCC firmware is designed to be tournament-legal, and as such, we do not allow any form of automation or macros that could give players an unfair advantage. Input filters and other simple "if-then" logic is acceptable (see [input_filter.rs](https://git.naxdy.org/NaxdyOrg/NaxGCC-FW/src/branch/main/src/input_filter.rs) for examples), but anything more complex will be rejected. The rule of thumb is: If it can be reasonably implemented as a hardware mod, it's probably fine.
- **No feature bloat**: We aim to keep the firmware as minimal as possible, to reduce the risk of bugs and to keep the codebase maintainable. As such, we will reject any features that are not deemed essential for the core functionality of the controller. This is especially important since the RP2040 executes the majority of code from flash, thus binary size matters. Performance improvements are always welcome, though.

170
Cargo.lock generated
View file

@ -2,6 +2,18 @@
# It is not intended for manual editing.
version = 3
[[package]]
name = "ahash"
version = "0.8.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e89da841a80418a9b391ebaea17f5c112ffaaa96f621d2c285b5174da76b9011"
dependencies = [
"cfg-if",
"once_cell",
"version_check",
"zerocopy",
]
[[package]]
name = "aho-corasick"
version = "1.1.2"
@ -77,6 +89,12 @@ version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46afbd2983a5d5a7bd740ccb198caf5b82f45c40c09c0eed36052d91cb92e719"
[[package]]
name = "bitfield"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d7e60934ceec538daadb9d8432424ed043a904d8e0243f3c6446bce549a46ac"
[[package]]
name = "bitflags"
version = "1.3.2"
@ -109,9 +127,9 @@ checksum = "a2ef034f05691a48569bd920a96c81b9d91bbad1ab5ac7c4616c1f6ef36cb79f"
[[package]]
name = "byteorder"
version = "1.4.3"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610"
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
[[package]]
name = "cfg-if"
@ -136,7 +154,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ec610d8f49840a5b376c69663b6369e71f4b34484b9b2eb29fb918d92516cb9"
dependencies = [
"bare-metal",
"bitfield",
"bitfield 0.13.2",
"embedded-hal 0.2.7",
"volatile-register",
]
@ -309,7 +327,8 @@ checksum = "11157ac094ffbdde99aa67b23417ebdd801842852b500e395a45a9c0aac03e4a"
[[package]]
name = "embassy-embedded-hal"
version = "0.1.0"
version = "0.2.0"
source = "git+https://git.naxdy.org/NaxdyOrg/embassy.git?branch=naxgcc-fw#16151cce0271573a66206aa6e85932c20bbf0c70"
dependencies = [
"defmt",
"embassy-futures",
@ -325,7 +344,8 @@ dependencies = [
[[package]]
name = "embassy-executor"
version = "0.5.0"
version = "0.6.0"
source = "git+https://git.naxdy.org/NaxdyOrg/embassy.git?branch=naxgcc-fw#16151cce0271573a66206aa6e85932c20bbf0c70"
dependencies = [
"cortex-m",
"critical-section",
@ -338,7 +358,8 @@ dependencies = [
[[package]]
name = "embassy-executor-macros"
version = "0.4.0"
version = "0.5.0"
source = "git+https://git.naxdy.org/NaxdyOrg/embassy.git?branch=naxgcc-fw#16151cce0271573a66206aa6e85932c20bbf0c70"
dependencies = [
"darling",
"proc-macro2",
@ -349,13 +370,15 @@ dependencies = [
[[package]]
name = "embassy-futures"
version = "0.1.1"
source = "git+https://git.naxdy.org/NaxdyOrg/embassy.git?branch=naxgcc-fw#16151cce0271573a66206aa6e85932c20bbf0c70"
dependencies = [
"defmt",
]
[[package]]
name = "embassy-hal-internal"
version = "0.1.0"
version = "0.2.0"
source = "git+https://git.naxdy.org/NaxdyOrg/embassy.git?branch=naxgcc-fw#16151cce0271573a66206aa6e85932c20bbf0c70"
dependencies = [
"cortex-m",
"critical-section",
@ -366,10 +389,12 @@ dependencies = [
[[package]]
name = "embassy-net-driver"
version = "0.2.0"
source = "git+https://git.naxdy.org/NaxdyOrg/embassy.git?branch=naxgcc-fw#16151cce0271573a66206aa6e85932c20bbf0c70"
[[package]]
name = "embassy-net-driver-channel"
version = "0.2.0"
version = "0.3.0"
source = "git+https://git.naxdy.org/NaxdyOrg/embassy.git?branch=naxgcc-fw#16151cce0271573a66206aa6e85932c20bbf0c70"
dependencies = [
"embassy-futures",
"embassy-net-driver",
@ -378,7 +403,8 @@ dependencies = [
[[package]]
name = "embassy-rp"
version = "0.1.0"
version = "0.2.0"
source = "git+https://git.naxdy.org/NaxdyOrg/embassy.git?branch=naxgcc-fw#16151cce0271573a66206aa6e85932c20bbf0c70"
dependencies = [
"atomic-polyfill",
"cfg-if",
@ -403,7 +429,6 @@ dependencies = [
"embedded-storage",
"embedded-storage-async",
"fixed",
"futures",
"nb 1.1.0",
"pio",
"pio-proc",
@ -414,7 +439,8 @@ dependencies = [
[[package]]
name = "embassy-sync"
version = "0.5.0"
version = "0.6.0"
source = "git+https://git.naxdy.org/NaxdyOrg/embassy.git?branch=naxgcc-fw#16151cce0271573a66206aa6e85932c20bbf0c70"
dependencies = [
"cfg-if",
"critical-section",
@ -426,7 +452,8 @@ dependencies = [
[[package]]
name = "embassy-time"
version = "0.3.0"
version = "0.3.2"
source = "git+https://git.naxdy.org/NaxdyOrg/embassy.git?branch=naxgcc-fw#16151cce0271573a66206aa6e85932c20bbf0c70"
dependencies = [
"cfg-if",
"critical-section",
@ -444,6 +471,7 @@ dependencies = [
[[package]]
name = "embassy-time-driver"
version = "0.1.0"
source = "git+https://git.naxdy.org/NaxdyOrg/embassy.git?branch=naxgcc-fw#16151cce0271573a66206aa6e85932c20bbf0c70"
dependencies = [
"document-features",
]
@ -451,10 +479,12 @@ dependencies = [
[[package]]
name = "embassy-time-queue-driver"
version = "0.1.0"
source = "git+https://git.naxdy.org/NaxdyOrg/embassy.git?branch=naxgcc-fw#16151cce0271573a66206aa6e85932c20bbf0c70"
[[package]]
name = "embassy-usb"
version = "0.1.0"
version = "0.3.0"
source = "git+https://git.naxdy.org/NaxdyOrg/embassy.git?branch=naxgcc-fw#16151cce0271573a66206aa6e85932c20bbf0c70"
dependencies = [
"defmt",
"embassy-futures",
@ -469,6 +499,7 @@ dependencies = [
[[package]]
name = "embassy-usb-driver"
version = "0.1.0"
source = "git+https://git.naxdy.org/NaxdyOrg/embassy.git?branch=naxgcc-fw#16151cce0271573a66206aa6e85932c20bbf0c70"
dependencies = [
"defmt",
]
@ -630,59 +661,12 @@ version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c"
[[package]]
name = "futures"
version = "0.3.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "645c6916888f6cb6350d2550b80fb63e734897a8498abe35cfb732b6487804b0"
dependencies = [
"futures-channel",
"futures-core",
"futures-io",
"futures-sink",
"futures-task",
"futures-util",
]
[[package]]
name = "futures-channel"
version = "0.3.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eac8f7d7865dcb88bd4373ab671c8cf4508703796caa2b1985a9ca867b3fcb78"
dependencies = [
"futures-core",
"futures-sink",
]
[[package]]
name = "futures-core"
version = "0.3.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dfc6580bb841c5a68e9ef15c77ccc837b40a7504914d52e47b8b0e9bbda25a1d"
[[package]]
name = "futures-io"
version = "0.3.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a44623e20b9681a318efdd71c299b6b222ed6f231972bfe2f224ebad6311f0c1"
[[package]]
name = "futures-macro"
version = "0.3.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.52",
]
[[package]]
name = "futures-sink"
version = "0.3.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9fb8e00e87438d937621c1c6269e53f536c14d3fbd6a042bb24879e57d474fb5"
[[package]]
name = "futures-task"
version = "0.3.30"
@ -696,8 +680,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d6401deb83407ab3da39eba7e33987a73c3df0c82b4bb5813ee871c19c41d48"
dependencies = [
"futures-core",
"futures-macro",
"futures-sink",
"futures-task",
"pin-project-lite",
"pin-utils",
@ -733,6 +715,15 @@ dependencies = [
"byteorder",
]
[[package]]
name = "hashbrown"
version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "43a3c133739dddd0d2990f9a4bdf8eb4b21ef50e4851ca85ab661199821d510e"
dependencies = [
"ahash",
]
[[package]]
name = "hashbrown"
version = "0.14.3"
@ -768,7 +759,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b0b929d511467233429c45a44ac1dcaa21ba0f5ba11e4879e6ed28ddb4f9df4"
dependencies = [
"equivalent",
"hashbrown",
"hashbrown 0.14.3",
]
[[package]]
@ -875,7 +866,7 @@ checksum = "523dc4f511e55ab87b694dc30d0f820d60906ef06413f93d4d7a1385599cc149"
[[package]]
name = "naxgcc-fw"
version = "0.1.0"
version = "1.3.0"
dependencies = [
"cortex-m",
"cortex-m-rt",
@ -897,7 +888,6 @@ dependencies = [
"portable-atomic",
"rand",
"static_cell",
"tiny_sort",
]
[[package]]
@ -1428,12 +1418,6 @@ dependencies = [
"crunchy",
]
[[package]]
name = "tiny_sort"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3bbd7912d5028a8f218a772a794fee0104b46ea1f6e747ff0a4fdbb5dc024a6"
[[package]]
name = "typenum"
version = "1.17.0"
@ -1460,15 +1444,19 @@ checksum = "f962df74c8c05a667b5ee8bcf162993134c104e96440b663c8daa176dc772d8c"
[[package]]
name = "usb-device"
version = "0.2.9"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f6cc3adc849b5292b4075fc0d5fdcf2f24866e88e336dd27a8943090a520508"
checksum = "98816b1accafbb09085168b90f27e93d790b4bfa19d883466b5e53315b5f06a6"
dependencies = [
"heapless",
"portable-atomic",
]
[[package]]
name = "usbd-hid"
version = "0.6.1"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "975bd411f4a939986751ea09992a24fa47c4d25c6ed108d04b4c2999a4fd0132"
checksum = "e6f291ab53d428685cc780f08a2eb9d5d6ff58622db2b36e239a4f715f1e184c"
dependencies = [
"serde",
"ssmarshal",
@ -1478,20 +1466,22 @@ dependencies = [
[[package]]
name = "usbd-hid-descriptors"
version = "0.1.2"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dcbee8c6735e90894fba04770bc41e11fd3c5256018856e15dc4dd1e6c8a3dd1"
checksum = "0eee54712c5d778d2fb2da43b1ce5a7b5060886ef7b09891baeb4bf36910a3ed"
dependencies = [
"bitfield",
"bitfield 0.14.0",
]
[[package]]
name = "usbd-hid-macros"
version = "0.6.0"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "261079a9ada015fa1acac7cc73c98559f3a92585e15f508034beccf6a2ab75a2"
checksum = "bb573c76e7884035ac5e1ab4a81234c187a82b6100140af0ab45757650ccda38"
dependencies = [
"byteorder",
"hashbrown 0.13.2",
"log",
"proc-macro2",
"quote",
"serde",
@ -1694,3 +1684,23 @@ checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed"
dependencies = [
"tap",
]
[[package]]
name = "zerocopy"
version = "0.7.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.7.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.52",
]

View file

@ -1,6 +1,6 @@
[package]
name = "naxgcc-fw"
version = "0.1.0"
version = "1.3.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@ -9,33 +9,33 @@ edition = "2021"
embassy-time = { version = "0.3.0", features = [
"defmt",
"defmt-timestamp-uptime",
], path = "lib/embassy-rs/embassy-time" }
embassy-embedded-hal = { version = "0.1.0", features = [
], git = "https://git.naxdy.org/NaxdyOrg/embassy.git", branch = "naxgcc-fw" }
embassy-embedded-hal = { version = "0.2.0", features = [
"defmt",
], path = "lib/embassy-rs/embassy-embedded-hal" }
embassy-sync = { version = "0.5.0", features = [
], git = "https://git.naxdy.org/NaxdyOrg/embassy.git", branch = "naxgcc-fw" }
embassy-sync = { version = "0.6.0", features = [
"defmt",
], path = "lib/embassy-rs/embassy-sync" }
embassy-executor = { version = "0.5.0", features = [
], git = "https://git.naxdy.org/NaxdyOrg/embassy.git", branch = "naxgcc-fw" }
embassy-executor = { version = "0.6.0", features = [
"task-arena-size-32768",
"arch-cortex-m",
"executor-thread",
"executor-interrupt",
"defmt",
"integrated-timers",
], path = "lib/embassy-rs/embassy-executor" }
embassy-rp = { version = "0.1.0", features = [
], git = "https://git.naxdy.org/NaxdyOrg/embassy.git", branch = "naxgcc-fw" }
embassy-rp = { version = "0.2.0", features = [
"defmt",
"unstable-pac",
"time-driver",
"critical-section-impl",
], path = "lib/embassy-rs/embassy-rp" }
embassy-usb = { version = "0.1.0", features = [
], git = "https://git.naxdy.org/NaxdyOrg/embassy.git", branch = "naxgcc-fw" }
embassy-usb = { version = "0.3.0", features = [
"defmt",
], path = "lib/embassy-rs/embassy-usb" }
], git = "https://git.naxdy.org/NaxdyOrg/embassy.git", branch = "naxgcc-fw" }
embassy-futures = { version = "0.1.0", features = [
"defmt",
], path = "lib/embassy-rs/embassy-futures" }
], git = "https://git.naxdy.org/NaxdyOrg/embassy.git", branch = "naxgcc-fw" }
defmt = "0.3"
defmt-rtt = "0.4"
fixed = "1.23.1"
@ -48,12 +48,9 @@ libm = { version = "0.2.8" }
cortex-m = { version = "0.7.6", features = ["inline-asm"] }
cortex-m-rt = "0.7.0"
panic-probe = { version = "0.3", features = ["print-defmt"] }
packed_struct = { version = "0.10.1", default_features = false }
packed_struct = { version = "0.10.1", default-features = false }
format_no_std = "1.0.2"
rand = { version = "0.8.5", default-features = false }
tiny_sort = { version = "1.0.5", default-features = false, features = [
"unstable",
] }
# cargo build/run
[profile.dev]
@ -61,7 +58,7 @@ codegen-units = 1
debug = 2
debug-assertions = true
incremental = false
opt-level = 1
opt-level = 3
lto = "fat"
overflow-checks = true
@ -74,7 +71,7 @@ incremental = false
lto = 'fat'
# opt level needs to be benchmarked after every major feature
# due to the changes in binary size and alignment
opt-level = 2
opt-level = 3
overflow-checks = false
# do not optimize proc-macro crates = faster builds from scratch
@ -82,14 +79,14 @@ overflow-checks = false
codegen-units = 8
debug = false
debug-assertions = false
opt-level = 0
opt-level = 3
overflow-checks = false
[profile.release.build-override]
codegen-units = 8
debug = false
debug-assertions = false
opt-level = 0
opt-level = 3
overflow-checks = false
# cargo test
@ -109,12 +106,3 @@ debug-assertions = false
incremental = false
lto = 'fat'
opt-level = 3
# [patch.crates-io]
# embassy-rp = { path = "lib/embassy-rs/embassy-rp" }
# embassy-time = { path = "lib/embassy-rs/embassy-time" }
# embassy-embedded-hal = { path = "lib/embassy-rs/embassy-embedded-hal" }
# embassy-usb = { path = "lib/embassy-rs/embassy-usb" }
# embassy-sync = { path = "lib/embassy-rs/embassy-sync" }
# embassy-executor = { path = "lib/embassy-rs/embassy-executor" }
# embassy-futures = { path = "lib/embassy-rs/embassy-futures" }

674
LICENSE Normal file
View file

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View file

@ -1,8 +1,20 @@
# NaxGCC
The main repository is located at [git.naxdy.org](https://git.naxdy.org/NaxdyOrg/NaxGCC-FW). The GitHub mirror exists solely for the sake of discoverability and redundancy.
> **Please do not submit issues or pull requests on GitHub.**
Find the latest releases here: https://git.naxdy.org/NaxdyOrg/NaxGCC-FW/releases
Full documentation is available at [gcc.naxdy.org](https://gcc.naxdy.org/).
Join the NaxGCC matrix chat at [#naxgcc:naxdy.org](https://matrix.to/#/#naxgcc:naxdy.org) to discuss development or ask for help.
---
This repo houses the firmware for the NaxGCC, a GameCube-style controller built on the [PhobGCC](https://github.com/PhobGCC/PhobGCC-SW). The firmware can also be used as an optional firmware for the PhobGCC, though the PhobGCC will then have to be connected to the console directly via USB.
Like the PhobGCC, the NaxGCC uses hall effect sensors instead of potentiometers for stick input. Additionally, it connects directly to the console via USB, by pretending to be a GCC adapter with 1 controller (itself) connected. This eliminates one additional layer of polling, and thus reduces perceived latency and improves input consistency. The NaxGCC firmware makes use of the [embassy-rs](https://github.com/embassy-rs/embassy) framework for asynchronous operations. Mainly, this means that the firmware is capable of polling the sticks and buttons at different frequencies, further improving input consistency and latency for button inputs.
Like the PhobGCC, the NaxGCC uses hall effect sensors instead of potentiometers for stick input. Additionally, it connects directly to the console via USB, by pretending to be a GCC adapter with 1 controller (itself) connected. This eliminates one additional layer of polling, and thus reduces perceived latency and improves input consistency. The NaxGCC also features a special "input consistency mode" that even further improves input consistency, beyond what is delivered by any other controller / adapter. The NaxGCC firmware makes use of the [embassy-rs](https://github.com/embassy-rs/embassy) framework for asynchronous operations. Mainly, this means that the firmware is capable of polling the sticks and buttons at different frequencies, further improving input consistency and latency for button inputs.
### Key Aspects
@ -16,7 +28,7 @@ Furthermore, large parts of its firmware have also been taken from PhobGCC's fir
</details>
<details><summary>Firmware is written in Rust, using the <a href="#">embassy-rs</a> framework for asynchronous operations.</summary>
<details><summary>Firmware is written in Rust, using the <a href="https://github.com/embassy-rs/embassy">embassy-rs</a> framework for asynchronous operations.</summary>
The firmware being written in Rust allows for writing much cleaner code than one would normally be used to when writing firmware in C, because Rust allows for many zero and low cost abstractions in order to enhance code readability and maintainability. Adding embassy-rs for asynchronous operations on top of that provides 2 main benefits:
@ -27,11 +39,11 @@ The firmware being written in Rust allows for writing much cleaner code than one
<details><summary>Provides both the lowest latency of any Switch controller, as well as the best input integrity.</summary>
Because the NaxGCC connects directly to the console via USB, it already outperforms any controller that has to go through an adapter in terms of input latency (including PhobGCC + Lossless Adapter).
Because the NaxGCC connects directly to the console via USB, it already outperforms any controller that has to go through an adapter in terms of input latency.
Further, the NaxGCC has a special "input consistency" mode (enabled by default), which ensures a $\gt 98\%$ input accuracy, compared to $\lt 75\%$ for any other controller (worse if there is an adapter in the mix, with the exception of the Lossless Adapter).
Further, the NaxGCC has a special "input consistency" mode (enabled by default), which ensures a $\gt 98\%$ input accuracy, compared to $\lt 76\%$ for any other controller (worse if there is an adapter in the mix, with the exception of the Lossless Adapter).
For details on how it works, have a look at our wiki.
For details on how it works, have a look at our [documentation](https://gcc.naxdy.org/).
</details>
@ -43,10 +55,10 @@ The NaxGCC firmware is compatible with regular Phob 2.0 boards (those using an R
## Contributing
The NaxGCC firmware is built using [nix](), which also provides a ready-to-go development environment, complete with all the tooling and libraries you need to get going. Simply install nix, [enable flakes]() and run
The NaxGCC firmware is built using [nix](https://nixos.org/download/), which also provides a ready-to-go development environment, complete with all the tooling and libraries you need to get going. Simply install nix, [enable flakes](https://nixos.wiki/wiki/Flakes) and run
```bash
nix develop .
```
and you're ready to work on the project. Submit your pull requests [here](https://git.naxdy.org/NaxdyOrg/NaxGCC-FW/pulls).
and you're ready to work on the project. Submit your pull requests [here](https://git.naxdy.org/NaxdyOrg/NaxGCC-FW/pulls). Also be sure to have a look at our [CONTRIBUTING.md](./CONTRIBUTING.md) for more information on how to contribute.

View file

@ -1,22 +1,5 @@
{
"nodes": {
"embassy-rs-patched": {
"flake": false,
"locked": {
"lastModified": 1710754402,
"narHash": "sha256-HyTw5VQXlSqz9UOq0Dc6G/NWNzQOPXf3PNWffMkfLC4=",
"ref": "naxgcc-fw",
"rev": "2ee4657727b9679998d941de00b43e1754f570bf",
"revCount": 6754,
"type": "git",
"url": "https://gitea@git.naxdy.org/NaxdyOrg/embassy"
},
"original": {
"ref": "naxgcc-fw",
"type": "git",
"url": "https://gitea@git.naxdy.org/NaxdyOrg/embassy"
}
},
"flake-utils": {
"inputs": {
"systems": "systems"
@ -35,24 +18,6 @@
"type": "github"
}
},
"flake-utils_2": {
"inputs": {
"systems": "systems_2"
},
"locked": {
"lastModified": 1705309234,
"narHash": "sha256-uNRRNRKmJyCRC/8y1RqBkqWBLM034y4qN7EprSdmgyA=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "1ef2e671c3b0c19053962c07dbda38332dcebf26",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"naersk": {
"inputs": {
"nixpkgs": [
@ -75,27 +40,27 @@
},
"nixpkgs": {
"locked": {
"lastModified": 1710283656,
"narHash": "sha256-nI+AOy4uK6jLGBi9nsbHjL1EdSIzoo8oa+9oeVhbyFc=",
"lastModified": 1728740863,
"narHash": "sha256-u+rxA79a0lyhG+u+oPBRtTDtzz8kvkc9a6SWSt9ekVc=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "51063ed4f2343a59fdeebb279bb81d87d453942b",
"rev": "a3f9ad65a0bf298ed5847629a57808b97e6e8077",
"type": "github"
},
"original": {
"owner": "nixos",
"ref": "nixos-23.11",
"ref": "nixos-24.05",
"repo": "nixpkgs",
"type": "github"
}
},
"nixpkgs_2": {
"locked": {
"lastModified": 1706487304,
"narHash": "sha256-LE8lVX28MV2jWJsidW13D2qrHU/RUUONendL2Q/WlJg=",
"lastModified": 1718428119,
"narHash": "sha256-WdWDpNaq6u1IPtxtYHHWpl5BmabtpmLnMAx0RdJ/vo8=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "90f456026d284c22b3e3497be980b2e47d0b28ac",
"rev": "e6cea36f83499eb4e9cd184c8a8e823296b50ad5",
"type": "github"
},
"original": {
@ -107,7 +72,6 @@
},
"root": {
"inputs": {
"embassy-rs-patched": "embassy-rs-patched",
"flake-utils": "flake-utils",
"naersk": "naersk",
"nixpkgs": "nixpkgs",
@ -116,15 +80,14 @@
},
"rust-overlay": {
"inputs": {
"flake-utils": "flake-utils_2",
"nixpkgs": "nixpkgs_2"
},
"locked": {
"lastModified": 1710382258,
"narHash": "sha256-2FW1q+o34VBweYQiEkRaSEkNMq3ecrn83VzETeGiVbY=",
"lastModified": 1728700003,
"narHash": "sha256-Ox1pvEHxLK6lAdaKQW21Zvk65SPDag+cD8YA444R/og=",
"owner": "oxalica",
"repo": "rust-overlay",
"rev": "8ce81e71ab04a7e906fae62da086d6ee5d6cfc21",
"rev": "fc1e58ebabe0cef4442eedea07556ff0c9eafcfe",
"type": "github"
},
"original": {
@ -147,21 +110,6 @@
"repo": "default",
"type": "github"
}
},
"systems_2": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
}
},
"root": "root",

View file

@ -2,17 +2,12 @@
description = "Firmware for the NaxGCC";
inputs = {
nixpkgs.url = "github:nixos/nixpkgs?ref=nixos-23.11";
nixpkgs.url = "github:nixos/nixpkgs?ref=nixos-24.05";
rust-overlay.url = "github:oxalica/rust-overlay";
flake-utils.url = "github:numtide/flake-utils";
embassy-rs-patched = {
url = "git+https://gitea@git.naxdy.org/NaxdyOrg/embassy?ref=naxgcc-fw";
flake = false;
};
naersk = {
url = "github:nmattia/naersk";
inputs.nixpkgs.follows = "nixpkgs";
@ -25,7 +20,6 @@
, rust-overlay
, flake-utils
, naersk
, embassy-rs-patched
}: (flake-utils.lib.eachDefaultSystem (system:
let
pkgs = import nixpkgs {
@ -51,35 +45,39 @@
};
CARGO_BUILD_TARGET = "thumbv6m-none-eabi";
prepCmd = ''
mkdir -p lib
rm lib/embassy-rs || true
ln -s "${embassy-rs-patched}" lib/embassy-rs
'';
in
{
packages.default = self.packages.${system}.naxgcc-fw-uf2;
packages = {
default = self.packages.${system}.naxgcc-fw-uf2;
packages.naxgcc-fw-uf2 = pkgs.runCommandLocal "${self.packages.${system}.naxgcc-fw.pname}-uf2-${self.packages.${system}.naxgcc-fw.version}" { } ''
mkdir -p $out/bin
${pkgs.elf2uf2-rs}/bin/elf2uf2-rs ${self.packages.${system}.naxgcc-fw}/bin/${self.packages.${system}.naxgcc-fw.pname} $out/bin/${self.packages.${system}.naxgcc-fw.pname}.uf2
'';
naxgcc-fw-uf2 = pkgs.runCommandLocal "${self.packages.${system}.naxgcc-fw.pname}-uf2-${self.packages.${system}.naxgcc-fw.version}" { } ''
mkdir -p $out/bin
${pkgs.elf2uf2-rs}/bin/elf2uf2-rs ${self.packages.${system}.naxgcc-fw}/bin/${self.packages.${system}.naxgcc-fw.pname} $out/bin/${self.packages.${system}.naxgcc-fw.pname}.uf2
'';
packages.naxgcc-fw = naersk_lib.buildPackage {
pname = (builtins.fromTOML (builtins.readFile ./Cargo.toml)).package.name;
version = (builtins.fromTOML (builtins.readFile ./Cargo.toml)).package.version;
naxgcc-fw = pkgs.callPackage
({ mode ? "build" }: naersk_lib.buildPackage {
pname = (builtins.fromTOML (builtins.readFile ./Cargo.toml)).package.name;
version = (builtins.fromTOML (builtins.readFile ./Cargo.toml)).package.version;
prePatch = prepCmd;
inherit mode;
src = self;
src = self;
cargoBuildOptions = _orig: _orig ++ [
"--target=${CARGO_BUILD_TARGET}"
];
cargoBuildOptions = _orig: _orig ++ [
"--target=${CARGO_BUILD_TARGET}"
];
# if a tree falls in the forest and no one is around to hear it, does it make a sound?
DEFMT_LOG = "off";
# if a tree falls in the forest and no one is around to hear it, does it make a sound?
DEFMT_LOG = "off";
})
{ };
};
checks = {
clippy = self.packages.${system}.naxgcc-fw.override {
mode = "clippy";
};
};
devShells.default = pkgs.mkShell {
@ -92,8 +90,6 @@
DEFMT_LOG = "debug";
inherit CARGO_BUILD_TARGET;
shellHook = prepCmd;
};
}));
}

View file

@ -10,13 +10,14 @@ use embassy_rp::{
flash::{Async, Flash, ERASE_SIZE},
peripherals::FLASH,
};
use packed_struct::{derive::PackedStruct, PackedStruct};
use packed_struct::{
derive::{PackedStruct, PrimitiveEnum_u8},
PackedStruct,
};
use crate::{
gcc_hid::{
Buttons1, Buttons2, SIGNAL_CHANGE_RUMBLE_STRENGTH, SIGNAL_INPUT_CONSISTENCY_MODE_STATUS,
},
helpers::{PackedFloat, ToPackedFloatArray, ToRegularArray, XyValuePair},
hid::gcc::{GcButtons1, GcButtons2, GcState},
input::{
read_ext_adc, Stick, StickAxis, FLOAT_ORIGIN, SPI_ACS_SHARED, SPI_CCS_SHARED, SPI_SHARED,
},
@ -25,6 +26,7 @@ use crate::{
LinearizedCalibration, NotchCalibration, NotchStatus, CALIBRATION_ORDER,
NOTCH_ADJUSTMENT_ORDER, NO_OF_ADJ_NOTCHES, NO_OF_CALIBRATION_POINTS, NO_OF_NOTCHES,
},
usb_comms::{MUTEX_INPUT_CONSISTENCY_MODE, SIGNAL_CHANGE_RUMBLE_STRENGTH},
ADDR_OFFSET, FLASH_SIZE,
};
@ -33,9 +35,9 @@ use embassy_sync::{
pubsub::Subscriber,
signal::Signal,
};
use embassy_time::{Duration, Ticker, Timer};
use embassy_time::Timer;
use crate::{gcc_hid::GcReport, input::CHANNEL_GCC_STATE};
use crate::input::CHANNEL_GCC_STATE;
/// Whether we are currently calibrating the sticks. Updates are dispatched when the status changes.
/// Initial status is assumed to be false.
@ -77,7 +79,7 @@ const MAX_ANALOG_SCALER: u8 = 125;
/// a certain mode.
#[derive(Default, Debug, Clone, Format)]
pub struct OverrideGcReportInstruction {
pub report: GcReport,
pub report: GcState,
pub duration_ms: u64,
}
@ -347,6 +349,27 @@ const INPUT_CONSISTENCY_TOGGLE_COMBO: [AwaitableButtons; 4] = [
AwaitableButtons::Wildcard,
];
const DISPLAY_WAVESHAPING_COMBO: [AwaitableButtons; 4] = [
AwaitableButtons::L,
AwaitableButtons::Start,
AwaitableButtons::Wildcard,
AwaitableButtons::Wildcard,
];
const DISPLAY_SMOOTHING_COMBO: [AwaitableButtons; 4] = [
AwaitableButtons::R,
AwaitableButtons::Start,
AwaitableButtons::Wildcard,
AwaitableButtons::Wildcard,
];
const DISPLAY_SNAPBACK_COMBO: [AwaitableButtons; 4] = [
AwaitableButtons::Up,
AwaitableButtons::Start,
AwaitableButtons::Wildcard,
AwaitableButtons::Wildcard,
];
const EXIT_CONFIG_MODE_COMBO: [AwaitableButtons; 4] = [
AwaitableButtons::A,
AwaitableButtons::X,
@ -443,8 +466,10 @@ pub struct OverrideStickState {
pub which_stick: Stick,
}
/// Enum button representation mainly used in the calibration process,
/// in conjunction with `is_awaitable_button_pressed`
#[allow(dead_code)]
#[derive(Clone, Copy, Debug, Format)]
#[derive(Clone, Copy, Debug, Format, PartialEq, Eq)]
pub enum AwaitableButtons {
A,
B,
@ -458,11 +483,11 @@ pub enum AwaitableButtons {
L,
R,
Z,
// special, because Z is used for cstick calibration
/// Special, because Z is used for cstick calibration.
NotZ,
/// Used for padding arrays to the correct length.
/// Can be used for padding arrays to a fixed length.
Wildcard,
/// Used for disabling certain button combinations.\
/// Can be used for disabling certain button combinations.
Impossible,
}
@ -523,6 +548,33 @@ impl Default for StickConfig {
}
}
#[derive(Debug, Clone, Copy, Format, PrimitiveEnum_u8, PartialEq, Eq)]
pub enum InputConsistencyMode {
/// Transmit inputs every 8ms, same as the original GCC adapter (and any other).
Original = 0,
/// Forcibly delay transmissions to be 8.33ms apart, to better align with the game's frame rate.
ConsistencyHack = 1,
/// Transmit inputs _at most_ every 8.33ms, but don't transmit anything at all if the controller state doesn't change.
/// This has the potential to drastically improve latency in certain situations, such as when you are waiting to react
/// to something your opponent does.
/// The name is not meant to imply that this is a hack that is super, but rather that this is super hacky.
SuperHack = 2,
/// Transmit inputs every 1 ms, for use on PC or other devices that are not garbage.
/// This is not recommended for use on the Switch!
PC = 3,
}
/// Not saved, but set upon plugging in the controller.
#[derive(Debug, Clone, Copy, Format, PrimitiveEnum_u8, PartialEq, Eq)]
pub enum ControllerMode {
/// Advertise itself as a GCC adapter with 1 controller (itself) connected.
GcAdapter = 0,
/// Pretend to be a Nintendo Switch Pro Controller connected via USB.
Procon = 1,
/// Act as an XInput device, and also advertise itself with 1000Hz polling capability.
XInput = 2,
}
#[derive(Debug, Clone, Format, PackedStruct)]
#[packed_struct(endian = "msb")]
pub struct ControllerConfig {
@ -532,8 +584,8 @@ pub struct ControllerConfig {
/// will trick the Switch into updating the state every 8.33ms
/// instead of every 8ms. The tradeoff is a slight increase in
/// input lag.
#[packed_field(size_bits = "8")]
pub input_consistency_mode: bool,
#[packed_field(size_bits = "8", ty = "enum")]
pub input_consistency_mode: InputConsistencyMode,
#[packed_field(size_bits = "8")]
pub rumble_strength: u8,
#[packed_field(size_bytes = "328")]
@ -546,7 +598,7 @@ impl Default for ControllerConfig {
fn default() -> Self {
Self {
config_revision: CONTROLLER_CONFIG_REVISION,
input_consistency_mode: true,
input_consistency_mode: InputConsistencyMode::ConsistencyHack,
astick_config: StickConfig::default(),
rumble_strength: 9,
cstick_config: StickConfig::default(),
@ -560,12 +612,7 @@ impl ControllerConfig {
) -> Result<Self, embassy_rp::flash::Error> {
let mut controller_config_packed: <ControllerConfig as packed_struct::PackedStruct>::ByteArray = ControllerConfig::default().pack().unwrap();
let r = flash.blocking_read(ADDR_OFFSET, &mut controller_config_packed);
if r.is_err() {
warn!("Controller config not found in flash, using default.");
controller_config_packed = [0u8; 659];
}
flash.blocking_read(ADDR_OFFSET, &mut controller_config_packed)?;
match ControllerConfig::unpack(&controller_config_packed) {
Ok(cfg) => match cfg {
@ -599,40 +646,45 @@ impl ControllerConfig {
}
}
trait WaitForButtonPress {
/// Trait for providing button presses, used in the calibration process.
trait ButtonPressProvider {
/// Wait for a single button press.
// TODO: remove allow once this is used somewhere
#[allow(dead_code)]
async fn wait_for_button_press(&mut self, button_to_wait_for: &AwaitableButtons);
/// Wait for a single button release.
async fn wait_for_button_release(&mut self, button_to_wait_for: &AwaitableButtons);
/// Wait for multiple buttons to be pressed simultaneously.
/// Wait for multiple buttons to be pressed simultaneously. Non-exclusive.
async fn wait_for_simultaneous_button_presses<const N: usize>(
&mut self,
buttons_to_wait_for: &[AwaitableButtons; N],
);
/// Wait for a single button press of specified buttons, and return the button that was pressed.
/// Wait for a single button press of specified buttons, and return the button that was pressed. Non-exclusive.
async fn wait_and_filter_button_press<const N: usize>(
&mut self,
buttons_to_wait_for: &[AwaitableButtons; N],
) -> AwaitableButtons;
/// See if one of the buttons in buttons_to_look_out_for is pressed, and return the pressed button, otherwise None.
/// See if one of the buttons in buttons_to_look_out_for is pressed, and return the pressed button, otherwise None. Non-exclusive.
fn filter_button_press_if_present<const N: usize>(
&mut self,
buttons_to_look_out_for: &[AwaitableButtons; N],
) -> Option<AwaitableButtons>;
/// Wait for multiple possible button combinations to be pressed simultaneously, and return the index of the combination that was pressed.
///
/// Note that this is done non-exclusively, so if the pressed buttons match multiple combinations, the first matching index in the array will be returned.
async fn wait_and_filter_simultaneous_button_presses<const N: usize, const M: usize>(
&mut self,
buttons_to_wait_for: &[[AwaitableButtons; N]; M],
) -> usize;
}
impl<'a, T: RawMutex, const I: usize, const J: usize, const K: usize> WaitForButtonPress
for Subscriber<'a, T, GcReport, I, J, K>
impl<'a, T: RawMutex, const I: usize, const J: usize, const K: usize> ButtonPressProvider
for Subscriber<'a, T, GcState, I, J, K>
{
async fn wait_for_button_press(&mut self, button_to_wait_for: &AwaitableButtons) {
loop {
@ -732,7 +784,7 @@ impl<'a, T: RawMutex, const I: usize, const J: usize, const K: usize> WaitForBut
}
pub fn is_awaitable_button_pressed(
report: &GcReport,
report: &GcState,
button_to_wait_for: &AwaitableButtons,
) -> bool {
match button_to_wait_for {
@ -846,6 +898,28 @@ impl<'a> StickCalibrationProcess<'a> {
}
}
fn calibration_skip_measurement(&mut self) {
self.calibration_step = NO_OF_CALIBRATION_POINTS as u8;
let stick_config = match self.which_stick {
Stick::ControlStick => &mut self.gcc_config.astick_config,
Stick::CStick => &mut self.gcc_config.cstick_config,
};
for i in 0..NO_OF_CALIBRATION_POINTS {
self.cal_points[i] = XyValuePair {
x: *stick_config.cal_points_x[i],
y: *stick_config.cal_points_y[i],
};
}
self.applied_calibration = AppliedCalibration::from_points(
stick_config.cal_points_x.to_regular_array(),
stick_config.cal_points_y.to_regular_array(),
stick_config,
);
}
async fn calibration_advance(&mut self) -> bool {
info!(
"Running calibration advance on stick {} at step {}",
@ -952,7 +1026,9 @@ impl<'a> StickCalibrationProcess<'a> {
let mut gcc_subscriber = CHANNEL_GCC_STATE.subscriber().unwrap();
SIGNAL_IS_CALIBRATING.signal(true);
while {
let mut done = false;
while !done {
if self.calibration_step < NO_OF_CALIBRATION_POINTS as u8 {
// Calibration phase
@ -978,9 +1054,14 @@ impl<'a> StickCalibrationProcess<'a> {
// Prevent accidental double presses
Timer::after_millis(100).await;
gcc_subscriber
.wait_for_button_press(&AwaitableButtons::A)
let btn_result = gcc_subscriber
.wait_and_filter_button_press(&[AwaitableButtons::A, AwaitableButtons::Start])
.await;
if btn_result == AwaitableButtons::Start {
self.calibration_skip_measurement();
continue;
}
} else {
// Notch adjustment phase
@ -990,8 +1071,6 @@ impl<'a> StickCalibrationProcess<'a> {
Timer::after_millis(100).await;
let mut ticker = Ticker::every(Duration::from_millis(20));
let notch_idx = NOTCH_ADJUSTMENT_ORDER
[self.calibration_step as usize - NO_OF_CALIBRATION_POINTS];
@ -1033,13 +1112,13 @@ impl<'a> StickCalibrationProcess<'a> {
None => self.adjust_notch(NotchAdjustmentType::None),
};
ticker.next().await;
Timer::after_millis(1).await;
yield_now().await;
}
};
!self.calibration_advance().await
} {}
done = self.calibration_advance().await;
}
SIGNAL_IS_CALIBRATING.signal(false);
SIGNAL_OVERRIDE_STICK_STATE.signal(None);
@ -1071,7 +1150,7 @@ async fn configuration_main_loop<
>(
current_config: &ControllerConfig,
flash: &mut Flash<'static, FLASH, Async, FLASH_SIZE>,
gcc_subscriber: &mut Subscriber<'a, M, GcReport, C, S, P>,
gcc_subscriber: &mut Subscriber<'a, M, GcState, C, S, P>,
) -> ControllerConfig {
let mut final_config = current_config.clone();
let config_options = [
@ -1116,6 +1195,9 @@ async fn configuration_main_loop<
RUMBLE_STRENGTH_INCREASE_COMBO,
RUMBLE_STRENGTH_DECREASE_COMBO,
INPUT_CONSISTENCY_TOGGLE_COMBO,
DISPLAY_WAVESHAPING_COMBO,
DISPLAY_SMOOTHING_COMBO,
DISPLAY_SNAPBACK_COMBO,
];
'main: loop {
@ -1126,15 +1208,15 @@ async fn configuration_main_loop<
// exit
0 => {
override_gcc_state_and_wait(&OverrideGcReportInstruction {
report: GcReport {
report: GcState {
trigger_r: 255,
trigger_l: 255,
buttons_2: Buttons2 {
buttons_2: GcButtons2 {
button_r: true,
button_l: true,
..Default::default()
},
buttons_1: Buttons1 {
buttons_1: GcButtons1 {
button_x: true,
button_y: true,
button_a: true,
@ -1154,15 +1236,15 @@ async fn configuration_main_loop<
// calibrate lstick
1 => {
override_gcc_state_and_wait(&OverrideGcReportInstruction {
report: GcReport {
report: GcState {
trigger_r: 255,
trigger_l: 255,
buttons_2: Buttons2 {
buttons_2: GcButtons2 {
button_r: true,
button_l: true,
..Default::default()
},
buttons_1: Buttons1 {
buttons_1: GcButtons1 {
button_x: true,
button_y: true,
button_a: true,
@ -1183,15 +1265,15 @@ async fn configuration_main_loop<
// calibrate rstick
2 => {
override_gcc_state_and_wait(&OverrideGcReportInstruction {
report: GcReport {
report: GcState {
trigger_r: 255,
trigger_l: 255,
buttons_2: Buttons2 {
buttons_2: GcButtons2 {
button_r: true,
button_l: true,
..Default::default()
},
buttons_1: Buttons1 {
buttons_1: GcButtons1 {
button_x: true,
button_y: true,
button_a: true,
@ -1242,15 +1324,15 @@ async fn configuration_main_loop<
.clamp(-ABS_MAX_SNAPBACK, ABS_MAX_SNAPBACK);
override_gcc_state_and_wait(&OverrideGcReportInstruction {
report: GcReport {
report: GcState {
trigger_r: 255,
trigger_l: 255,
buttons_2: Buttons2 {
buttons_2: GcButtons2 {
button_r: true,
button_l: true,
..Default::default()
},
buttons_1: Buttons1 {
buttons_1: GcButtons1 {
button_x: true,
button_y: true,
button_a: true,
@ -1328,15 +1410,15 @@ async fn configuration_main_loop<
.clamp(0, MAX_WAVESHAPING) as u8;
override_gcc_state_and_wait(&OverrideGcReportInstruction {
report: GcReport {
report: GcState {
trigger_r: 255,
trigger_l: 255,
buttons_2: Buttons2 {
buttons_2: GcButtons2 {
button_r: true,
button_l: true,
..Default::default()
},
buttons_1: Buttons1 {
buttons_1: GcButtons1 {
button_x: true,
button_y: true,
button_a: true,
@ -1414,15 +1496,15 @@ async fn configuration_main_loop<
.clamp(0, MAX_SMOOTHING) as u8;
override_gcc_state_and_wait(&OverrideGcReportInstruction {
report: GcReport {
report: GcState {
trigger_r: 255,
trigger_l: 255,
buttons_2: Buttons2 {
buttons_2: GcButtons2 {
button_r: true,
button_l: true,
..Default::default()
},
buttons_1: Buttons1 {
buttons_1: GcButtons1 {
button_x: true,
button_y: true,
button_a: true,
@ -1489,15 +1571,15 @@ async fn configuration_main_loop<
.clamp(-1, MAX_CARDINAL_SNAP);
override_gcc_state_and_wait(&OverrideGcReportInstruction {
report: GcReport {
report: GcState {
trigger_r: 255,
trigger_l: 255,
buttons_2: Buttons2 {
buttons_2: GcButtons2 {
button_r: true,
button_l: true,
..Default::default()
},
buttons_1: Buttons1 {
buttons_1: GcButtons1 {
button_x: true,
button_y: true,
button_a: true,
@ -1545,15 +1627,15 @@ async fn configuration_main_loop<
as u8;
override_gcc_state_and_wait(&OverrideGcReportInstruction {
report: GcReport {
report: GcState {
trigger_r: 255,
trigger_l: 255,
buttons_2: Buttons2 {
buttons_2: GcButtons2 {
button_r: true,
button_l: true,
..Default::default()
},
buttons_1: Buttons1 {
buttons_1: GcButtons1 {
button_x: true,
button_y: true,
button_a: true,
@ -1593,23 +1675,23 @@ async fn configuration_main_loop<
SIGNAL_CHANGE_RUMBLE_STRENGTH.signal(*to_adjust);
override_gcc_state_and_wait(&OverrideGcReportInstruction {
report: GcReport {
report: GcState {
trigger_r: 255,
trigger_l: 255,
buttons_2: Buttons2 {
buttons_2: GcButtons2 {
button_r: true,
button_l: true,
button_z: true,
..Default::default()
},
buttons_1: Buttons1 {
buttons_1: GcButtons1 {
button_x: true,
button_y: true,
button_a: true,
..Default::default()
},
stick_x: 127,
stick_y: 127,
stick_y: 127 + *to_adjust,
cstick_x: 127,
cstick_y: 127,
},
@ -1621,18 +1703,23 @@ async fn configuration_main_loop<
}
// input consistency toggle
37 => {
final_config.input_consistency_mode = !final_config.input_consistency_mode;
final_config.input_consistency_mode = match final_config.input_consistency_mode {
InputConsistencyMode::Original => InputConsistencyMode::PC,
InputConsistencyMode::PC => InputConsistencyMode::ConsistencyHack,
InputConsistencyMode::ConsistencyHack => InputConsistencyMode::SuperHack,
InputConsistencyMode::SuperHack => InputConsistencyMode::Original,
};
override_gcc_state_and_wait(&OverrideGcReportInstruction {
report: GcReport {
report: GcState {
trigger_r: 255,
trigger_l: 255,
buttons_2: Buttons2 {
buttons_2: GcButtons2 {
button_r: true,
button_l: true,
..Default::default()
},
buttons_1: Buttons1 {
buttons_1: GcButtons1 {
button_x: true,
button_y: true,
button_a: true,
@ -1641,8 +1728,10 @@ async fn configuration_main_loop<
stick_x: 127,
stick_y: (127_i8
+ match final_config.input_consistency_mode {
true => 69,
false => -69,
InputConsistencyMode::Original => -69,
InputConsistencyMode::PC => -42,
InputConsistencyMode::ConsistencyHack => 42,
InputConsistencyMode::SuperHack => 69,
}) as u8,
cstick_x: 127,
cstick_y: 127,
@ -1653,6 +1742,84 @@ async fn configuration_main_loop<
SIGNAL_CONFIG_CHANGE.signal(final_config.clone());
}
// display waveshaping values on both sticks
38 => {
override_gcc_state_and_wait(&OverrideGcReportInstruction {
report: GcState {
trigger_r: 255,
trigger_l: 255,
buttons_2: GcButtons2 {
button_r: true,
button_l: true,
..Default::default()
},
buttons_1: GcButtons1 {
button_x: true,
button_y: true,
button_a: true,
..Default::default()
},
stick_x: 127 + final_config.astick_config.x_waveshaping,
stick_y: 127 + final_config.astick_config.y_waveshaping,
cstick_x: 127 + final_config.cstick_config.x_waveshaping,
cstick_y: 127 + final_config.cstick_config.y_waveshaping,
},
duration_ms: 1000,
})
.await;
}
// display stick smoothing values on both sticks
39 => {
override_gcc_state_and_wait(&OverrideGcReportInstruction {
report: GcState {
trigger_r: 255,
trigger_l: 255,
buttons_2: GcButtons2 {
button_r: true,
button_l: true,
..Default::default()
},
buttons_1: GcButtons1 {
button_x: true,
button_y: true,
button_a: true,
..Default::default()
},
stick_x: 127 + final_config.astick_config.x_smoothing,
stick_y: 127 + final_config.astick_config.y_smoothing,
cstick_x: 127 + final_config.cstick_config.x_smoothing,
cstick_y: 127 + final_config.cstick_config.y_smoothing,
},
duration_ms: 1000,
})
.await;
}
// display snapback values on both sticks
40 => {
override_gcc_state_and_wait(&OverrideGcReportInstruction {
report: GcState {
trigger_r: 255,
trigger_l: 255,
buttons_2: GcButtons2 {
button_r: true,
button_l: true,
..Default::default()
},
buttons_1: GcButtons1 {
button_x: true,
button_y: true,
button_a: true,
..Default::default()
},
stick_x: (127 + final_config.astick_config.x_snapback) as u8,
stick_y: (127 + final_config.astick_config.y_snapback) as u8,
cstick_x: (127 + final_config.cstick_config.x_snapback) as u8,
cstick_y: (127 + final_config.cstick_config.y_snapback) as u8,
},
duration_ms: 1000,
})
.await;
}
s => {
error!("Invalid selection in config loop: {}", s);
continue;
@ -1682,7 +1849,11 @@ pub async fn config_task(mut flash: Flash<'static, FLASH, Async, FLASH_SIZE>) {
let mut current_config = ControllerConfig::from_flash_memory(&mut flash).unwrap();
SIGNAL_INPUT_CONSISTENCY_MODE_STATUS.signal(current_config.input_consistency_mode);
{
let mut m_input_consistency = MUTEX_INPUT_CONSISTENCY_MODE.lock().await;
*m_input_consistency = Some(current_config.input_consistency_mode);
}
SIGNAL_CHANGE_RUMBLE_STRENGTH.signal(current_config.rumble_strength);
SIGNAL_CONFIG_CHANGE.signal(current_config.clone());
@ -1697,15 +1868,15 @@ pub async fn config_task(mut flash: Flash<'static, FLASH, Async, FLASH_SIZE>) {
info!("Entering config mode.");
override_gcc_state_and_wait(&OverrideGcReportInstruction {
report: GcReport {
report: GcState {
trigger_r: 255,
trigger_l: 255,
buttons_2: Buttons2 {
buttons_2: GcButtons2 {
button_l: true,
button_r: true,
..Default::default()
},
buttons_1: Buttons1 {
buttons_1: GcButtons1 {
button_x: true,
button_y: true,
button_a: true,

View file

@ -179,7 +179,7 @@ pub struct KalmanState {
}
impl KalmanState {
// runs kalman filter
#[inline(never)]
#[link_section = ".time_critical.run_kalman"]
pub fn run_kalman(
&mut self,
@ -292,6 +292,7 @@ impl KalmanState {
/// output at the rim longer when released.
///
/// Output is a tuple of the x and y positions.
#[inline(never)]
#[link_section = ".time_critical.run_waveshaping"]
pub fn run_waveshaping(
x_pos: f32,

View file

@ -1,478 +0,0 @@
/**
* Communication with the console / PC over USB HID.
* Includes the HID report descriptor, and the GcReport struct.
*/
use core::default::Default;
use defmt::{debug, info, trace, warn, Format};
use embassy_futures::join::join;
use embassy_rp::{
peripherals::{PIN_25, PIN_29, PWM_CH4, PWM_CH6, USB},
pwm::Pwm,
usb::Driver,
};
use embassy_sync::{blocking_mutex::raw::CriticalSectionRawMutex, signal::Signal};
use embassy_time::{Duration, Instant, Ticker};
use embassy_usb::{
class::hid::{HidReaderWriter, ReportId, RequestHandler, State},
control::OutResponse,
Builder, Handler,
};
use libm::powf;
use packed_struct::{derive::PackedStruct, PackedStruct};
use crate::input::CHANNEL_GCC_STATE;
static SIGNAL_RUMBLE: Signal<CriticalSectionRawMutex, bool> = Signal::new();
/// We could turn the config change signal into a PubSubChannel instead, but that
/// would just transmit unnecessary amounts of data.
pub static SIGNAL_CHANGE_RUMBLE_STRENGTH: Signal<CriticalSectionRawMutex, u8> = Signal::new();
/// Only dispatched ONCE after powerup, to determine how to advertise itself via USB.
pub static SIGNAL_INPUT_CONSISTENCY_MODE_STATUS: Signal<CriticalSectionRawMutex, bool> =
Signal::new();
#[rustfmt::skip]
pub const GCC_REPORT_DESCRIPTOR: &[u8] = &[
0x05, 0x01, // Usage Page (Generic Desktop Ctrls)
0x09, 0x05, // Usage (Game Pad)
0xA1, 0x01, // Collection (Application)
0xA1, 0x03, // Collection (Report)
0x85, 0x11, // Report ID (17)
0x19, 0x00, // Usage Minimum (Undefined)
0x2A, 0xFF, 0x00, // Usage Maximum (0xFF)
0x15, 0x00, // Logical Minimum (0)
0x26, 0xFF, 0x00, // Logical Maximum (255)
0x75, 0x08, // Report Size (8)
0x95, 0x05, // Report Count (5)
0x91, 0x00, // Output (Data,Array,Abs,No Wrap,Linear,Preferred State,No Null Position,Non-volatile)
0xC0, // End Collection
0xA1, 0x03, // Collection (Report)
0x85, 0x21, // Report ID (33)
0x05, 0x00, // Usage Page (Undefined)
0x15, 0x00, // Logical Minimum (0)
0x25, 0xFF, // Logical Maximum (-1)
0x75, 0x08, // Report Size (8)
0x95, 0x01, // Report Count (1)
0x81, 0x02, // Input (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position)
0x05, 0x09, // Usage Page (Button)
0x19, 0x01, // Usage Minimum (0x01)
0x29, 0x08, // Usage Maximum (0x08)
0x15, 0x00, // Logical Minimum (0)
0x25, 0x01, // Logical Maximum (1)
0x75, 0x08, // Report Size (8)
0x95, 0x02, // Report Count (2)
0x81, 0x02, // Input (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position)
0x05, 0x01, // Usage Page (Generic Desktop Ctrls)
0x09, 0x30, // Usage (X)
0x09, 0x31, // Usage (Y)
0x09, 0x32, // Usage (Z)
0x09, 0x33, // Usage (Rx)
0x09, 0x34, // Usage (Ry)
0x09, 0x35, // Usage (Rz)
0x15, 0x81, // Logical Minimum (-127)
0x25, 0x7F, // Logical Maximum (127)
0x75, 0x08, // Report Size (8)
0x95, 0x06, // Report Count (6)
0x81, 0x02, // Input (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position)
0xC0, // End Collection
0xA1, 0x03, // Collection (Report)
0x85, 0x13, // Report ID (19)
0x19, 0x00, // Usage Minimum (Undefined)
0x2A, 0xFF, 0x00, // Usage Maximum (0xFF)
0x15, 0x00, // Logical Minimum (0)
0x26, 0xFF, 0x00, // Logical Maximum (255)
0x75, 0x08, // Report Size (8)
0x95, 0x01, // Report Count (1)
0x91, 0x00, // Output (Data,Array,Abs,No Wrap,Linear,Preferred State,No Null Position,Non-volatile)
0xC0, // End Collection
0xC0, // End Collection
];
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, PackedStruct, Format)]
#[packed_struct(bit_numbering = "lsb0", size_bytes = "1")]
pub struct Buttons1 {
#[packed_field(bits = "0")]
pub button_a: bool,
#[packed_field(bits = "1")]
pub button_b: bool,
#[packed_field(bits = "2")]
pub button_x: bool,
#[packed_field(bits = "3")]
pub button_y: bool,
#[packed_field(bits = "4")]
pub dpad_left: bool,
#[packed_field(bits = "5")]
pub dpad_right: bool,
#[packed_field(bits = "6")]
pub dpad_down: bool,
#[packed_field(bits = "7")]
pub dpad_up: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, PackedStruct, Format)]
#[packed_struct(bit_numbering = "lsb0", size_bytes = "1")]
pub struct Buttons2 {
#[packed_field(bits = "0")]
pub button_start: bool,
#[packed_field(bits = "1")]
pub button_z: bool,
#[packed_field(bits = "2")]
pub button_r: bool,
#[packed_field(bits = "3")]
pub button_l: bool,
#[packed_field(bits = "4..=7")]
pub blank1: u8,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PackedStruct, Format)]
#[packed_struct(bit_numbering = "msb0", size_bytes = "8")]
pub struct GcReport {
#[packed_field(bits = "0..=7")]
pub buttons_1: Buttons1,
#[packed_field(bits = "8..=15")]
pub buttons_2: Buttons2,
#[packed_field(bits = "16..=23")]
pub stick_x: u8,
#[packed_field(bits = "24..=31")]
pub stick_y: u8,
#[packed_field(bits = "32..=39")]
pub cstick_x: u8,
#[packed_field(bits = "40..=47")]
pub cstick_y: u8,
#[packed_field(bits = "48..=55")]
pub trigger_l: u8,
#[packed_field(bits = "56..=63")]
pub trigger_r: u8,
}
impl Default for GcReport {
fn default() -> Self {
Self {
buttons_1: Buttons1::default(),
buttons_2: Buttons2::default(),
stick_x: 127,
stick_y: 127,
cstick_x: 127,
cstick_y: 127,
trigger_l: 0,
trigger_r: 0,
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[repr(C, align(8))]
pub struct RawConsoleReport {
pub packet: [u8; 64],
}
impl Default for RawConsoleReport {
fn default() -> Self {
Self { packet: [0u8; 64] }
}
}
struct GccRequestHandler {}
impl RequestHandler for GccRequestHandler {
fn get_report(&self, id: ReportId, _buf: &mut [u8]) -> Option<usize> {
info!("Get report for {:?}", id);
None
}
fn set_report(&self, id: ReportId, data: &[u8]) -> OutResponse {
info!("Set report for {:?}: {=[u8]}", id, data);
OutResponse::Accepted
}
fn set_idle_ms(&self, id: Option<ReportId>, dur: u32) {
info!("Set idle rate for {:?} to {:?}", id, dur);
}
fn get_idle_ms(&self, id: Option<ReportId>) -> Option<u32> {
info!("Get idle rate for {:?}", id);
None
}
}
fn get_gcinput_hid_report(input_state: &GcReport) -> [u8; 37] {
static mut GC_FIRST: bool = false;
let mut buffer = [0u8; 37];
buffer[0] = 0x21;
buffer[1] |= 0x14;
let data = input_state.pack().expect("Failed to pack GC input data");
if unsafe { !GC_FIRST } {
buffer[1] |= 0x04;
buffer[10] |= 0x04;
buffer[19] |= 0x04;
buffer[28] |= 0x04;
unsafe { GC_FIRST = true };
} else {
// controller in "port 1"
buffer[2..=9].copy_from_slice(&data[0..=7]);
}
buffer
}
struct MyDeviceHandler {
configured: bool,
}
impl MyDeviceHandler {
fn new() -> Self {
MyDeviceHandler { configured: false }
}
}
impl Handler for MyDeviceHandler {
fn enabled(&mut self, enabled: bool) {
self.configured = true;
if enabled {
info!("Device enabled");
} else {
info!("Device disabled");
}
}
fn reset(&mut self) {
self.configured = false;
info!("Bus reset, the Vbus current limit is 100mA");
}
fn addressed(&mut self, addr: u8) {
self.configured = false;
info!("USB address set to: {}", addr);
}
fn configured(&mut self, configured: bool) {
self.configured = configured;
if configured {
info!(
"Device configured, it may now draw up to the configured current limit from Vbus."
)
} else {
info!("Device is no longer configured, the Vbus current limit is 100mA.");
}
}
}
#[embassy_executor::task]
pub async fn usb_transfer_task(raw_serial: [u8; 8], driver: Driver<'static, USB>) {
let input_consistency_mode = SIGNAL_INPUT_CONSISTENCY_MODE_STATUS.wait().await;
let mut serial_buffer = [0u8; 64];
let serial = format_no_std::show(
&mut serial_buffer,
format_args!(
"{:02X}{:02X}{:02X}{:02X}{:02X}{:02X}{:02X}{:02X}",
raw_serial[0],
raw_serial[1],
raw_serial[2],
raw_serial[3],
raw_serial[4],
raw_serial[5],
raw_serial[6],
raw_serial[7]
),
)
.unwrap();
info!("Detected flash with unique serial number {}", serial);
trace!("Start of config");
let mut usb_config = embassy_usb::Config::new(0x057e, 0x0337);
usb_config.manufacturer = Some("Naxdy");
usb_config.product = Some(if input_consistency_mode {
"NaxGCC (Consistency Mode)"
} else {
"NaxGCC (OG Mode)"
});
usb_config.serial_number = Some(serial);
usb_config.max_power = 200;
usb_config.max_packet_size_0 = 64;
usb_config.device_class = 0;
usb_config.device_protocol = 0;
usb_config.self_powered = false;
usb_config.device_sub_class = 0;
usb_config.supports_remote_wakeup = true;
let mut device_descriptor = [0; 256];
let mut config_descriptor = [0; 256];
let mut bos_descriptor = [0; 256];
let mut msos_descriptor = [0; 256];
let mut control_buf = [0; 64];
let request_handler = GccRequestHandler {};
let mut device_handler = MyDeviceHandler::new();
let mut state = State::new();
let mut builder = Builder::new(
driver,
usb_config,
&mut device_descriptor,
&mut config_descriptor,
&mut bos_descriptor,
&mut msos_descriptor,
&mut control_buf,
);
builder.handler(&mut device_handler);
let hid_config = embassy_usb::class::hid::Config {
report_descriptor: GCC_REPORT_DESCRIPTOR,
request_handler: Some(&request_handler),
poll_ms: if input_consistency_mode { 4 } else { 8 },
max_packet_size_in: 37,
max_packet_size_out: 5,
};
let hid = HidReaderWriter::<_, 5, 37>::new(&mut builder, &mut state, hid_config);
let mut usb = builder.build();
let usb_fut = async {
loop {
usb.run_until_suspend().await;
debug!("Suspended");
usb.wait_resume().await;
debug!("RESUMED!");
}
};
let (mut reader, mut writer) = hid.split();
let mut lasttime = Instant::now();
let in_fut = async {
let mut gcc_subscriber = CHANNEL_GCC_STATE.subscriber().unwrap();
let mut ticker = Ticker::every(Duration::from_micros(8333));
loop {
if input_consistency_mode {
// This is what we like to call a "hack".
// It forces reports to be sent every 8.33ms instead of every 8ms.
// 8.33ms is a multiple of the game's frame interval (16.66ms), so if we
// send a report every 8.33ms, it should (in theory) ensure (close to)
// 100% input accuracy.
//
// From the console's perspective, we are basically a laggy adapter, taking
// a minimum of 333 extra us to send a report every time it's polled, but it
// works to our advantage.
ticker.next().await;
}
match writer
.write(&{
let state = gcc_subscriber.next_message_pure().await;
let report = get_gcinput_hid_report(&state);
trace!("Report Written: {:08b}", report);
report
})
.await
{
Ok(()) => {
let currtime = Instant::now();
let polltime = currtime.duration_since(lasttime);
let micros = polltime.as_micros();
trace!("Report written in {}us", micros);
// If we're sending reports too fast, reset the ticker.
// This might happen right after plug-in, or after suspend.
if micros < 8150 {
ticker.reset();
}
lasttime = currtime;
}
Err(e) => warn!("Failed to send report: {:?}", e),
}
}
};
let out_fut = async {
loop {
trace!("Readery loop");
let mut buf = [0u8; 5];
match reader.read(&mut buf).await {
Ok(_e) => {
debug!("READ SOMETHIN: {:08b}", buf);
SIGNAL_RUMBLE.signal((buf[1] & 0x01) != 0);
}
Err(e) => {
warn!("Failed to read: {:?}", e);
}
}
}
};
let usb_fut_wrapped = async {
usb_fut.await;
debug!("USB FUT DED");
};
join(usb_fut_wrapped, join(in_fut, out_fut)).await;
}
fn calc_rumble_power(strength: u8) -> u16 {
if strength > 0 {
powf(2.0, 7.0 + ((strength as f32 - 3.0) / 8.0)) as u16
} else {
0
}
}
#[embassy_executor::task]
pub async fn rumble_task(
pin_rumble: PIN_25,
pin_brake: PIN_29,
pwm_ch_rumble: PWM_CH4,
pwm_ch_brake: PWM_CH6,
) {
let mut rumble_config: embassy_rp::pwm::Config = Default::default();
rumble_config.top = 255;
rumble_config.enable = true;
rumble_config.compare_b = 0;
let mut brake_config = rumble_config.clone();
brake_config.compare_b = 255;
let mut pwm_rumble = Pwm::new_output_b(pwm_ch_rumble, pin_rumble, rumble_config.clone());
let mut pwm_brake = Pwm::new_output_b(pwm_ch_brake, pin_brake, brake_config.clone());
let mut rumble_power = {
let strength = SIGNAL_CHANGE_RUMBLE_STRENGTH.wait().await;
calc_rumble_power(strength)
};
loop {
let new_rumble_status = SIGNAL_RUMBLE.wait().await;
debug!("Received rumble signal: {}", new_rumble_status);
if let Some(new_strength) = SIGNAL_CHANGE_RUMBLE_STRENGTH.try_take() {
rumble_power = calc_rumble_power(new_strength);
}
if new_rumble_status {
rumble_config.compare_b = rumble_power;
brake_config.compare_b = 0;
pwm_rumble.set_config(&rumble_config);
pwm_brake.set_config(&brake_config);
} else {
rumble_config.compare_b = 0;
brake_config.compare_b = 255;
pwm_rumble.set_config(&rumble_config);
pwm_brake.set_config(&brake_config);
}
}
}

198
src/hid/gcc.rs Normal file
View file

@ -0,0 +1,198 @@
use defmt::{info, trace, Format};
use embassy_usb::{
class::hid::{ReportId, RequestHandler},
control::OutResponse,
};
use crate::usb_comms::{HidReportBuilder, SIGNAL_RUMBLE};
use packed_struct::{derive::PackedStruct, PackedStruct};
#[rustfmt::skip]
pub const GCC_REPORT_DESCRIPTOR: &[u8] = &[
0x05, 0x01, // Usage Page (Generic Desktop Ctrls)
0x09, 0x05, // Usage (Game Pad)
0xA1, 0x01, // Collection (Application)
0xA1, 0x03, // Collection (Report)
0x85, 0x11, // Report ID (17)
0x19, 0x00, // Usage Minimum (Undefined)
0x2A, 0xFF, 0x00, // Usage Maximum (0xFF)
0x15, 0x00, // Logical Minimum (0)
0x26, 0xFF, 0x00, // Logical Maximum (255)
0x75, 0x08, // Report Size (8)
0x95, 0x05, // Report Count (5)
0x91, 0x00, // Output (Data,Array,Abs,No Wrap,Linear,Preferred State,No Null Position,Non-volatile)
0xC0, // End Collection
0xA1, 0x03, // Collection (Report)
0x85, 0x21, // Report ID (33)
0x05, 0x00, // Usage Page (Undefined)
0x15, 0x00, // Logical Minimum (0)
0x25, 0xFF, // Logical Maximum (-1)
0x75, 0x08, // Report Size (8)
0x95, 0x01, // Report Count (1)
0x81, 0x02, // Input (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position)
0x05, 0x09, // Usage Page (Button)
0x19, 0x01, // Usage Minimum (0x01)
0x29, 0x08, // Usage Maximum (0x08)
0x15, 0x00, // Logical Minimum (0)
0x25, 0x01, // Logical Maximum (1)
0x75, 0x08, // Report Size (8)
0x95, 0x02, // Report Count (2)
0x81, 0x02, // Input (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position)
0x05, 0x01, // Usage Page (Generic Desktop Ctrls)
0x09, 0x30, // Usage (X)
0x09, 0x31, // Usage (Y)
0x09, 0x32, // Usage (Z)
0x09, 0x33, // Usage (Rx)
0x09, 0x34, // Usage (Ry)
0x09, 0x35, // Usage (Rz)
0x15, 0x81, // Logical Minimum (-127)
0x25, 0x7F, // Logical Maximum (127)
0x75, 0x08, // Report Size (8)
0x95, 0x06, // Report Count (6)
0x81, 0x02, // Input (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position)
0xC0, // End Collection
0xA1, 0x03, // Collection (Report)
0x85, 0x13, // Report ID (19)
0x19, 0x00, // Usage Minimum (Undefined)
0x2A, 0xFF, 0x00, // Usage Maximum (0xFF)
0x15, 0x00, // Logical Minimum (0)
0x26, 0xFF, 0x00, // Logical Maximum (255)
0x75, 0x08, // Report Size (8)
0x95, 0x01, // Report Count (1)
0x91, 0x00, // Output (Data,Array,Abs,No Wrap,Linear,Preferred State,No Null Position,Non-volatile)
0xC0, // End Collection
0xC0, // End Collection
];
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, PackedStruct, Format)]
#[packed_struct(bit_numbering = "lsb0", size_bytes = "1")]
pub struct GcButtons1 {
#[packed_field(bits = "0")]
pub button_a: bool,
#[packed_field(bits = "1")]
pub button_b: bool,
#[packed_field(bits = "2")]
pub button_x: bool,
#[packed_field(bits = "3")]
pub button_y: bool,
#[packed_field(bits = "4")]
pub dpad_left: bool,
#[packed_field(bits = "5")]
pub dpad_right: bool,
#[packed_field(bits = "6")]
pub dpad_down: bool,
#[packed_field(bits = "7")]
pub dpad_up: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, PackedStruct, Format)]
#[packed_struct(bit_numbering = "lsb0", size_bytes = "1")]
pub struct GcButtons2 {
#[packed_field(bits = "0")]
pub button_start: bool,
#[packed_field(bits = "1")]
pub button_z: bool,
#[packed_field(bits = "2")]
pub button_r: bool,
#[packed_field(bits = "3")]
pub button_l: bool,
#[packed_field(bits = "4..=7")]
pub blank1: u8,
}
///
/// Struct representing the controller state. Used for HID communications in
/// GCC adapter mode, as well as for the internal representation of the controller.
///
#[derive(Clone, Copy, Debug, PartialEq, Eq, PackedStruct, Format)]
#[packed_struct(bit_numbering = "msb0", size_bytes = "8")]
pub struct GcState {
#[packed_field(bits = "0..=7")]
pub buttons_1: GcButtons1,
#[packed_field(bits = "8..=15")]
pub buttons_2: GcButtons2,
#[packed_field(bits = "16..=23")]
pub stick_x: u8,
#[packed_field(bits = "24..=31")]
pub stick_y: u8,
#[packed_field(bits = "32..=39")]
pub cstick_x: u8,
#[packed_field(bits = "40..=47")]
pub cstick_y: u8,
#[packed_field(bits = "48..=55")]
pub trigger_l: u8,
#[packed_field(bits = "56..=63")]
pub trigger_r: u8,
}
impl Default for GcState {
fn default() -> Self {
Self {
buttons_1: GcButtons1::default(),
buttons_2: GcButtons2::default(),
stick_x: 127,
stick_y: 127,
cstick_x: 127,
cstick_y: 127,
trigger_l: 0,
trigger_r: 0,
}
}
}
#[derive(Default)]
pub struct GcReportBuilder {
gc_first: bool,
}
impl HidReportBuilder<37> for GcReportBuilder {
async fn get_hid_report(&mut self, state: &GcState) -> [u8; 37] {
let mut buffer = [0u8; 37];
buffer[0] = 0x21;
buffer[1] |= 0x14;
let data = state.pack().expect("Failed to pack GC input data");
if !self.gc_first {
buffer[1] |= 0x04;
buffer[10] |= 0x04;
buffer[19] |= 0x04;
buffer[28] |= 0x04;
self.gc_first = true;
} else {
// controller in "port 1"
buffer[2..=9].copy_from_slice(&data);
}
buffer
}
}
pub struct GccRequestHandler;
impl RequestHandler for GccRequestHandler {
fn get_report(&mut self, id: ReportId, _buf: &mut [u8]) -> Option<usize> {
info!("Get report for {:?}", id);
None
}
fn set_report(&mut self, id: ReportId, data: &[u8]) -> OutResponse {
trace!("Set report for {:?}: {:x}", id, data);
if data.len() > 1 {
SIGNAL_RUMBLE.signal((data[1] & 0x01) != 0);
}
OutResponse::Accepted
}
fn set_idle_ms(&mut self, id: Option<ReportId>, dur: u32) {
info!("Set idle rate for {:?} to {:?}", id, dur);
}
fn get_idle_ms(&mut self, id: Option<ReportId>) -> Option<u32> {
info!("Get idle rate for {:?}", id);
None
}
}

70
src/hid/mod.rs Normal file
View file

@ -0,0 +1,70 @@
use embassy_usb::{
class::hid::{HidReader, HidReaderWriter, HidWriter, ReadError, RequestHandler},
driver::{Driver, EndpointError},
};
pub mod gcc;
pub mod procon;
pub mod xinput;
/// Custom trait to unify the API between embassy's HID writer, and our XInput reader/writer (and any
/// custom writers we may create in the future)
pub trait HidReaderWriterSplit<'d, D: Driver<'d>, const READ_N: usize, const WRITE_N: usize> {
fn split(
self,
) -> (
impl UsbReader<'d, D, READ_N>,
impl UsbWriter<'d, D, WRITE_N>,
);
}
/// Custom trait to unify the API between embassy's HID writer, and our XInput reader (and any
/// custom writers we may create in the future)
pub trait UsbReader<'d, D: Driver<'d>, const READ_N: usize> {
async fn run<T: RequestHandler>(self, use_report_ids: bool, handler: &mut T) -> !;
async fn read(&mut self, buf: &mut [u8]) -> Result<usize, ReadError>;
}
/// Custom trait to unify the API between embassy's HID writer, and our XInput writer (and any
/// custom writers we may create in the future)
pub trait UsbWriter<'d, D: Driver<'d>, const WRITE_N: usize> {
async fn ready(&mut self);
async fn write(&mut self, report: &[u8]) -> Result<(), EndpointError>;
}
impl<'d, D: Driver<'d>, const READ_N: usize, const WRITE_N: usize>
HidReaderWriterSplit<'d, D, READ_N, WRITE_N> for HidReaderWriter<'d, D, READ_N, WRITE_N>
{
fn split(
self,
) -> (
impl UsbReader<'d, D, READ_N>,
impl UsbWriter<'d, D, WRITE_N>,
) {
self.split()
}
}
impl<'d, D: Driver<'d>, const READ_N: usize> UsbReader<'d, D, READ_N> for HidReader<'d, D, READ_N> {
async fn run<T: RequestHandler>(self, use_report_ids: bool, handler: &mut T) -> ! {
self.run(use_report_ids, handler).await
}
async fn read(&mut self, buf: &mut [u8]) -> Result<usize, ReadError> {
self.read(buf).await
}
}
impl<'d, D: Driver<'d>, const WRITE_N: usize> UsbWriter<'d, D, WRITE_N>
for HidWriter<'d, D, WRITE_N>
{
async fn ready(&mut self) {
self.ready().await
}
async fn write(&mut self, report: &[u8]) -> Result<(), EndpointError> {
self.write(report).await
}
}

762
src/hid/procon.rs Normal file
View file

@ -0,0 +1,762 @@
///
/// The majority of the logic in this file is derived from HOJA-LIB-RP2040
/// https://github.com/HandHeldLegend/HOJA-LIB-RP2040
///
/// The original author gave their consent for this to be included in the NaxGCC firmware,
/// and for this file to be distributed under the GPLv3, see https://git.naxdy.org/NaxdyOrg/NaxGCC-FW/pulls/26
///
use core::ops::{Deref, DerefMut};
use defmt::{info, trace, Format};
use embassy_rp::clocks::RoscRng;
use embassy_sync::{blocking_mutex::raw::CriticalSectionRawMutex, signal::Signal};
use embassy_time::Instant;
use embassy_usb::{
class::hid::{ReportId, RequestHandler},
control::OutResponse,
};
use packed_struct::{derive::PackedStruct, PackedStruct};
use rand::RngCore;
use crate::usb_comms::HidReportBuilder;
use super::gcc::GcState;
const SW_INFO_SET_MAC: u8 = 0x01;
const SW_CMD_SET_INPUT_MODE: u8 = 0x03;
const SW_CMD_GET_DEVINFO: u8 = 0x02;
const SW_CMD_SET_SHIPMODE: u8 = 0x08;
const SW_CMD_GET_SPI: u8 = 0x10;
const SW_CMD_SET_PAIRING: u8 = 0x01;
const SW_CMD_GET_TRIGGERET: u8 = 0x04;
const ACK_GET_DEVINFO: u8 = 0x82;
const ACK_GET_SPI: u8 = 0x90;
const ACK_SET_PAIRING: u8 = 0x81;
const ACK_GET_TRIGERET: u8 = 0x83;
const ACK_GENERIC: u8 = 0x80;
const RM_SEND_STATE: u8 = 0x30;
const PRO_CONTROLLER_STRING: [u8; 24] = [
0x00, 0x25, 0x08, 0x50, 0x72, 0x6F, 0x20, 0x43, 0x6F, 0x6E, 0x74, 0x72, 0x6F, 0x6C, 0x6C, 0x65,
0x72, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68,
];
#[derive(Debug, Format, Clone, Copy)]
struct ProconRequestInfo {
report_id: ProconRequestId,
response_id: ProconResponseId,
command_id: u8,
raw_data: [u8; 64],
}
#[derive(Debug, Format, Clone, Copy)]
enum ProconRequestId {
GetInfo = 0x80,
Command = 0x01,
Rumble = 0x10,
}
#[derive(Debug, Format, Clone, Copy)]
enum ProconResponseId {
GetInfo = 0x81,
GetState = 0x30,
Command = 0x21,
}
static SIGNAL_PROCON_REQUEST: Signal<CriticalSectionRawMutex, ProconRequestInfo> = Signal::new();
#[rustfmt::skip]
pub const PROCON_REPORT_DESCRIPTOR: &[u8] = &[
0x05, 0x01, // Usage Page (Generic Desktop Ctrls)
0x15, 0x00, // Logical Minimum (0)
0x09, 0x04, // Usage (Joystick)
0xA1, 0x01, // Collection (Application)
0x85, 0x30, // Report ID (48)
0x05, 0x01, // Usage Page (Generic Desktop Ctrls)
0x05, 0x09, // Usage Page (Button)
0x19, 0x01, // Usage Minimum (0x01)
0x29, 0x0A, // Usage Maximum (0x0A)
0x15, 0x00, // Logical Minimum (0)
0x25, 0x01, // Logical Maximum (1)
0x75, 0x01, // Report Size (1)
0x95, 0x0A, // Report Count (10)
0x55, 0x00, // Unit Exponent (0)
0x65, 0x00, // Unit (None)
0x81, 0x02, // Input (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position)
0x05, 0x09, // Usage Page (Button)
0x19, 0x0B, // Usage Minimum (0x0B)
0x29, 0x0E, // Usage Maximum (0x0E)
0x15, 0x00, // Logical Minimum (0)
0x25, 0x01, // Logical Maximum (1)
0x75, 0x01, // Report Size (1)
0x95, 0x04, // Report Count (4)
0x81, 0x02, // Input (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position)
0x75, 0x01, // Report Size (1)
0x95, 0x02, // Report Count (2)
0x81, 0x03, // Input (Const,Var,Abs,No Wrap,Linear,Preferred State,No Null Position)
0x0B, 0x01, 0x00, 0x01, 0x00, // Usage (0x010001)
0xA1, 0x00, // Collection (Physical)
0x0B, 0x30, 0x00, 0x01, 0x00, // Usage (0x010030)
0x0B, 0x31, 0x00, 0x01, 0x00, // Usage (0x010031)
0x0B, 0x32, 0x00, 0x01, 0x00, // Usage (0x010032)
0x0B, 0x35, 0x00, 0x01, 0x00, // Usage (0x010035)
0x15, 0x00, // Logical Minimum (0)
0x27, 0xFF, 0xFF, 0x00, 0x00, // Logical Maximum (65534)
0x75, 0x10, // Report Size (16)
0x95, 0x04, // Report Count (4)
0x81, 0x02, // Input (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position)
0xC0, // End Collection
0x0B, 0x39, 0x00, 0x01, 0x00, // Usage (0x010039)
0x15, 0x00, // Logical Minimum (0)
0x25, 0x07, // Logical Maximum (7)
0x35, 0x00, // Physical Minimum (0)
0x46, 0x3B, 0x01, // Physical Maximum (315)
0x65, 0x14, // Unit (System: English Rotation, Length: Centimeter)
0x75, 0x04, // Report Size (4)
0x95, 0x01, // Report Count (1)
0x81, 0x02, // Input (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position)
0x05, 0x09, // Usage Page (Button)
0x19, 0x0F, // Usage Minimum (0x0F)
0x29, 0x12, // Usage Maximum (0x12)
0x15, 0x00, // Logical Minimum (0)
0x25, 0x01, // Logical Maximum (1)
0x75, 0x01, // Report Size (1)
0x95, 0x04, // Report Count (4)
0x81, 0x02, // Input (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position)
0x75, 0x08, // Report Size (8)
0x95, 0x34, // Report Count (52)
0x81, 0x03, // Input (Const,Var,Abs,No Wrap,Linear,Preferred State,No Null Position)
0x06, 0x00, 0xFF, // Usage Page (Vendor Defined 0xFF00)
0x85, 0x21, // Report ID (33)
0x09, 0x01, // Usage (0x01)
0x75, 0x08, // Report Size (8)
0x95, 0x3F, // Report Count (63)
0x81, 0x03, // Input (Const,Var,Abs,No Wrap,Linear,Preferred State,No Null Position)
0x85, 0x81, // Report ID (-127)
0x09, 0x02, // Usage (0x02)
0x75, 0x08, // Report Size (8)
0x95, 0x3F, // Report Count (63)
0x81, 0x03, // Input (Const,Var,Abs,No Wrap,Linear,Preferred State,No Null Position)
0x85, 0x01, // Report ID (1)
0x09, 0x03, // Usage (0x03)
0x75, 0x08, // Report Size (8)
0x95, 0x3F, // Report Count (63)
0x91, 0x83, // Output (Const,Var,Abs,No Wrap,Linear,Preferred State,No Null Position,Volatile)
0x85, 0x10, // Report ID (16)
0x09, 0x04, // Usage (0x04)
0x75, 0x08, // Report Size (8)
0x95, 0x3F, // Report Count (63)
0x91, 0x83, // Output (Const,Var,Abs,No Wrap,Linear,Preferred State,No Null Position,Volatile)
0x85, 0x80, // Report ID (-128)
0x09, 0x05, // Usage (0x05)
0x75, 0x08, // Report Size (8)
0x95, 0x3F, // Report Count (63)
0x91, 0x83, // Output (Const,Var,Abs,No Wrap,Linear,Preferred State,No Null Position,Volatile)
0x85, 0x82, // Report ID (-126)
0x09, 0x06, // Usage (0x06)
0x75, 0x08, // Report Size (8)
0x95, 0x3F, // Report Count (63)
0x91, 0x83, // Output (Const,Var,Abs,No Wrap,Linear,Preferred State,No Null Position,Volatile)
0xC0, // End Collection
// 203 bytes
];
#[derive(Clone, Copy, Debug, Format)]
struct ProconByteReport([u8; 64]);
impl Deref for ProconByteReport {
type Target = [u8; 64];
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for ProconByteReport {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl ProconByteReport {
fn set_report_id(&mut self, id: u8) {
self[0] = id;
}
fn set_battery_status(&mut self) {
self[2] = BatteryStatus::default()
.pack()
.expect("Failed to pack fake procon battery status")[0];
}
fn set_timer(&mut self) {
self[1] = Instant::now().as_millis() as u8;
}
fn set_ack(&mut self, ack: u8) {
self[13] = ack;
}
fn set_subcommand(&mut self, cmd: u8) {
self[14] = cmd;
}
fn set_devinfo(&mut self) {
self[15] = 0x04; // NS Firmware primary (4.x)
self[16] = 0x33; // NS Firmware secondary (x.21)
self[17] = 0x03; // Controller ID primary (Pro Controller)
self[18] = 0x02; // Controller ID secondary
self[25] = 0x01;
self[26] = 0x02;
}
fn sw_spi_readfromaddress(
&mut self,
offset_address: u8,
address: u8,
length: u8,
switch_host_address: &[u8],
) {
let read_info = [address, offset_address, 0x00, 0x00, length];
self[15..(15 + read_info.len())].copy_from_slice(&read_info);
let mut output_spi_data = [0u8; 30];
output_spi_data.iter_mut().enumerate().for_each(|(i, e)| {
*e = sw_spi_getaddressdata(offset_address, address + i as u8, switch_host_address)
});
self[20..(20 + length as usize)].copy_from_slice(&output_spi_data[..(length as usize)]);
}
fn set_trigerret(&mut self, time_10_ms: u16) {
let [upper_ms, lower_ms] = time_10_ms.to_be_bytes();
for i in 0..14 {
self[15 + i] = upper_ms;
self[16 + i] = lower_ms;
}
}
}
fn sw_spi_getaddressdata(offset_address: u8, address: u8, switch_host_address: &[u8]) -> u8 {
match offset_address {
0x00 => 0x00,
0x20..=0x40 => match address {
0x26 | 0x00 => 0x95,
// Size of pairing data
0x27 | 0x01 => 0x22,
// Checksum
0x28 | 0x29 | 0x02 | 0x03 => 0x00,
// Host BT address (Big-endian)
0x2A..=0x2F => switch_host_address[(address - 0x2a) as usize],
0x04..=0x09 => switch_host_address[(address - 4) as usize],
// Bluetooth LTK (Little-endian) NOT IMPLEMENTED YET
0x30..=0x3F => 0x00,
0x0A..=0x19 => 0x00,
// Host capability 0x68 is Nintendo Switch. 0x08 is PC
0x4A | 0x24 => 0x68,
0x4B | 0x25 => 0,
_ => 0x00,
},
0x50 => 0x00,
0x60 => match address {
0x00..0x0f => 0xff,
0x12 => 0x03,
0x13 => 0x02,
0x1b => 0x01,
0x20 => 35,
0x21 => 0,
0x22 => 185,
0x23 => 255,
0x24 => 26,
0x25 => 1,
0x26 => 0,
0x27 => 64,
0x28 => 0,
0x29 => 64,
0x2A => 0,
0x2B => 64,
0x2C => 1,
0x2D => 0,
0x2E => 1,
0x2F => 0,
0x30 => 1,
0x31 => 0,
0x32 => 0x3B,
0x33 => 0x34,
0x34 => 0x3B,
0x35 => 0x34,
0x36 => 0x3B,
0x37 => 0x34,
0x3d..=0x45 => mk_switch_analog_calibration_data()[(address - 0x3d) as usize],
0x46..=0x4e => mk_switch_analog_calibration_data()[(address - 0x3d) as usize],
0x4F => 0xFF,
0x50 => 26,
0x51 => 26,
0x52 => 26,
0x53..=0x55 => 94,
0x56 => 255,
0x57 => 255,
0x58 => 255,
0x59..=0x5B => 255,
0x5C => 0x01,
0x80 => 80,
0x81 => 253,
0x82 => 0,
0x83 => 0,
0x84 => 198,
0x85 => 15,
0x98 | 0x86 => 15,
0x99 | 0x87 => 48,
0x9A | 0x88 => 97,
0x9B | 0x89 => 174,
0x9C | 0x8A => 144,
0x9D | 0x8B => 217,
0x9E | 0x8C => 212,
0x9F | 0x8D => 20,
0xA0 | 0x8E => 84,
0xA1 | 0x8F => 65,
0xA2 | 0x90 => 21,
0xA3 | 0x91 => 84,
0xA4 | 0x92 => 199,
0xA5 | 0x93 => 121,
0xA6 | 0x94 => 156,
0xA7 | 0x95 => 51,
0xA8 | 0x96 => 54,
0xA9 | 0x97 => 99,
_ => 0,
},
0x80 => match address {
0x10..=0x1a => 0xff,
0x1b..=0x25 => 0xff,
0x26..=0x3f => 0xff,
_ => 0xff,
},
_ => 0xff,
}
}
fn mk_switch_analog_calibration_data() -> [u8; 18] {
fn switch_analog_encode(in_lower: u16, in_upper: u16) -> [u8; 3] {
let mut out = [0u8; 3];
[out[0], out[1]] = in_lower.to_le_bytes();
out[1] |= ((in_upper & 0xf) << 4) as u8;
out[2] = ((in_upper & 0xff0) >> 4) as u8;
out
}
const MIN: u16 = 128 << 4;
const MAXX: u16 = 128 << 4;
const CENTER: u16 = 128 << 4;
let mut out = [0u8; 18];
out[0..3].copy_from_slice(&switch_analog_encode(MAXX, MAXX));
out[3..6].copy_from_slice(&switch_analog_encode(CENTER, CENTER));
out[6..9].copy_from_slice(&switch_analog_encode(MIN, MIN));
out[9..12].copy_from_slice(&switch_analog_encode(CENTER, CENTER));
out[12..15].copy_from_slice(&switch_analog_encode(MIN, MIN));
out[15..18].copy_from_slice(&switch_analog_encode(MAXX, MAXX));
info!("Returning switch data: {:x}", out);
out
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, PackedStruct, Format)]
#[packed_struct(bit_numbering = "lsb0", size_bytes = "1")]
pub struct ProconButtonsRight {
#[packed_field(bits = "0")]
pub button_y: bool,
#[packed_field(bits = "1")]
pub button_x: bool,
#[packed_field(bits = "2")]
pub button_b: bool,
#[packed_field(bits = "3")]
pub button_a: bool,
#[packed_field(bits = "4")]
pub trigger_r_sr: bool,
#[packed_field(bits = "5")]
pub trigger_r_sl: bool,
#[packed_field(bits = "6")]
pub trigger_r: bool,
#[packed_field(bits = "7")]
pub trigger_zr: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, PackedStruct, Format)]
#[packed_struct(bit_numbering = "lsb0", size_bytes = "1")]
pub struct ProconButtonsShared {
#[packed_field(bits = "0")]
pub button_minus: bool,
#[packed_field(bits = "1")]
pub button_plus: bool,
#[packed_field(bits = "2")]
pub button_sb_right: bool,
#[packed_field(bits = "3")]
pub button_sb_left: bool,
#[packed_field(bits = "4")]
pub button_home: bool,
#[packed_field(bits = "5")]
pub button_capture: bool,
#[packed_field(bits = "6")]
pub none: bool,
#[packed_field(bits = "7")]
pub change_grip_active: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, PackedStruct, Format)]
#[packed_struct(bit_numbering = "lsb0", size_bytes = "1")]
pub struct ProconButtonsLeft {
#[packed_field(bits = "0")]
pub dpad_down: bool,
#[packed_field(bits = "1")]
pub dpad_up: bool,
#[packed_field(bits = "2")]
pub dpad_right: bool,
#[packed_field(bits = "3")]
pub dped_left: bool,
#[packed_field(bits = "4")]
pub trigger_l_sr: bool,
#[packed_field(bits = "5")]
pub trigger_l_sl: bool,
#[packed_field(bits = "6")]
pub trigger_l: bool,
#[packed_field(bits = "7")]
pub trigger_zl: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, PackedStruct, Format)]
#[packed_struct(bit_numbering = "msb0", endian = "lsb", size_bytes = "9")]
pub struct ProconState {
#[packed_field(bits = "0..=7")]
pub buttons_right: ProconButtonsRight,
#[packed_field(bits = "8..=15")]
pub buttons_shared: ProconButtonsShared,
#[packed_field(bits = "16..=23")]
pub buttons_left: ProconButtonsLeft,
#[packed_field(bits = "24..=39")]
pub lstick_x: u16,
#[packed_field(bits = "40..=47")]
pub lstick_y: u8,
#[packed_field(bits = "48..=63")]
pub rstick_x: u16,
#[packed_field(bits = "64..=71")]
pub rstick_y: u8,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PackedStruct, Format)]
#[packed_struct(bit_numbering = "lsb0", endian = "msb", size_bytes = "1")]
struct BatteryStatus {
#[packed_field(bits = "0..=3")]
connection: u8,
#[packed_field(bits = "4..=7")]
battery_level: u8,
}
impl Default for BatteryStatus {
fn default() -> Self {
Self {
connection: 1,
battery_level: 8,
}
}
}
impl From<&GcState> for ProconState {
fn from(value: &GcState) -> Self {
Self {
buttons_left: ProconButtonsLeft {
dpad_down: value.buttons_1.dpad_down,
dpad_right: value.buttons_1.dpad_right,
dpad_up: value.buttons_1.dpad_up,
dped_left: value.buttons_1.dpad_left,
trigger_l: value.buttons_2.button_l,
trigger_zl: value.buttons_2.button_l,
..Default::default()
},
buttons_right: ProconButtonsRight {
button_a: value.buttons_1.button_a,
button_b: value.buttons_1.button_b,
button_x: value.buttons_1.button_x,
button_y: value.buttons_1.button_y,
trigger_r: value.buttons_2.button_z,
trigger_zr: value.buttons_2.button_r,
..Default::default()
},
buttons_shared: ProconButtonsShared {
button_plus: value.buttons_2.button_start && !value.buttons_2.button_z,
button_home: value.buttons_2.button_start && value.buttons_2.button_z,
..Default::default()
},
lstick_x: value.stick_x as u16 * 16,
lstick_y: value.stick_y,
rstick_x: value.cstick_x as u16 * 16,
rstick_y: value.cstick_y,
}
}
}
pub struct ProconReportBuilder {
switch_reporting_mode: u8,
switch_mac_address: [u8; 6],
switch_host_address: [u8; 6],
switch_ltk: [u8; 16],
}
impl Default for ProconReportBuilder {
fn default() -> Self {
Self {
switch_reporting_mode: 0,
switch_mac_address: gen_switch_mac_address(),
switch_host_address: [0u8; 6],
switch_ltk: gen_switch_ltk(),
}
}
}
fn gen_switch_mac_address() -> [u8; 6] {
let mut mac_addr = [0u8; 6];
mac_addr.iter_mut().for_each(|e| {
*e = RoscRng.next_u64() as u8;
});
mac_addr[0] &= 0xfe;
mac_addr[5] = 0x9b;
mac_addr
}
fn gen_switch_ltk() -> [u8; 16] {
let mut switch_ltk = [0u8; 16];
switch_ltk.iter_mut().for_each(|e| {
*e = RoscRng.next_u64() as u8;
});
switch_ltk
}
impl ProconReportBuilder {
fn get_info_report(&self, current_report_info: &ProconRequestInfo) -> [u8; 64] {
let mut report = ProconByteReport([0u8; 64]);
report.set_report_id(ProconResponseId::GetInfo as u8);
if current_report_info.command_id == SW_INFO_SET_MAC {
report[1] = SW_INFO_SET_MAC;
report[3] = 0x03;
self.switch_mac_address
.iter()
.rev()
.enumerate()
.for_each(|(i, e)| {
report[4 + i] = *e;
});
} else {
report[1] = current_report_info.command_id;
}
*report
}
fn get_state_report(&self, state: &ProconState) -> [u8; 64] {
static mut UNKNOWN: u8 = 0xA;
unsafe {
UNKNOWN = match UNKNOWN {
0xA => 0xB,
0xB => 0xC,
_ => 0xA,
};
}
let mut report = ProconByteReport([0u8; 64]);
let data = state
.pack()
.expect("Failed to pack pro controller input data");
report.set_report_id(ProconResponseId::GetState as u8);
report.set_timer();
report.set_battery_status();
report[3..=11].copy_from_slice(&data);
report[12] = unsafe { UNKNOWN };
*report
}
fn get_command_report(&mut self, current_report_info: &ProconRequestInfo) -> [u8; 64] {
let mut report = ProconByteReport([0u8; 64]);
report.set_report_id(ProconResponseId::Command as u8);
report.set_timer();
report.set_battery_status();
report.set_subcommand(current_report_info.command_id);
match current_report_info.command_id {
SW_CMD_SET_INPUT_MODE => {
report.set_ack(ACK_GENERIC);
self.switch_reporting_mode = current_report_info.raw_data[11];
info!(
"Switch reporting mode is now {:x}",
self.switch_reporting_mode
);
}
SW_CMD_GET_DEVINFO => {
report.set_ack(ACK_GET_DEVINFO);
report.set_devinfo();
}
SW_CMD_GET_SPI => {
report.set_ack(ACK_GET_SPI);
report.sw_spi_readfromaddress(
current_report_info.raw_data[12],
current_report_info.raw_data[11],
current_report_info.raw_data[15],
&self.switch_host_address,
);
}
SW_CMD_SET_SHIPMODE => {
report.set_ack(ACK_GENERIC);
}
SW_CMD_SET_PAIRING => {
report.set_ack(ACK_SET_PAIRING);
self.perform_pairing(&mut report, current_report_info);
}
SW_CMD_GET_TRIGGERET => {
report.set_ack(ACK_GET_TRIGERET);
report.set_trigerret(100);
}
_ => {
report.set_ack(ACK_GENERIC);
}
}
*report
}
fn perform_pairing(
&mut self,
report: &mut ProconByteReport,
current_report_info: &ProconRequestInfo,
) {
let pairing_phase = current_report_info.raw_data[11];
let host_address = &current_report_info.raw_data[12..];
match pairing_phase {
1 => {
self.switch_host_address
.iter_mut()
.enumerate()
.for_each(|(i, e)| *e = host_address[5 - i]);
report[16..=21].copy_from_slice(&self.switch_mac_address);
report[22..(22 + PRO_CONTROLLER_STRING.len())]
.copy_from_slice(&PRO_CONTROLLER_STRING);
}
2 => {
report[15] = 2;
report[16..(16 + self.switch_ltk.len())].copy_from_slice(&self.switch_ltk);
}
3 => {
report[15] = 3;
}
_ => {}
}
}
}
impl HidReportBuilder<64> for ProconReportBuilder {
async fn get_hid_report(&mut self, state: &GcState) -> [u8; 64] {
let current_report_info = if self.switch_reporting_mode == RM_SEND_STATE {
SIGNAL_PROCON_REQUEST.try_take()
} else {
Some(SIGNAL_PROCON_REQUEST.wait().await)
};
if let Some(current_report_info) = current_report_info {
match current_report_info.report_id {
ProconRequestId::GetInfo => self.get_info_report(&current_report_info),
ProconRequestId::Command => self.get_command_report(&current_report_info),
ProconRequestId::Rumble => self.get_state_report(&ProconState::from(state)),
}
} else {
self.get_state_report(&ProconState::from(state))
}
}
}
pub struct ProconRequestHandler;
impl RequestHandler for ProconRequestHandler {
fn get_report(&mut self, id: ReportId, _buf: &mut [u8]) -> Option<usize> {
info!("Get report for {:?}", id);
None
}
fn set_report(&mut self, id: ReportId, data: &[u8]) -> OutResponse {
trace!("Set report for {:?}: {:x}", id, data);
let mut buf = [0u8; 64];
let len_to_copy = buf.len().min(data.len());
buf[..len_to_copy].copy_from_slice(&data[..len_to_copy]);
if let ReportId::Out(id) = id {
if id == ProconRequestId::GetInfo as u8 {
SIGNAL_PROCON_REQUEST.signal(ProconRequestInfo {
command_id: buf[1],
report_id: ProconRequestId::GetInfo,
response_id: ProconResponseId::GetInfo,
raw_data: buf,
});
} else if id == ProconRequestId::Command as u8 {
SIGNAL_PROCON_REQUEST.signal(ProconRequestInfo {
command_id: buf[10],
report_id: ProconRequestId::Command,
response_id: ProconResponseId::Command,
raw_data: buf,
});
} else if id == ProconRequestId::Rumble as u8 {
// TODO: handle rumble
}
}
OutResponse::Accepted
}
fn set_idle_ms(&mut self, id: Option<ReportId>, dur: u32) {
info!("Set idle rate for {:?} to {:?}", id, dur);
}
fn get_idle_ms(&mut self, id: Option<ReportId>) -> Option<u32> {
info!("Get idle rate for {:?}", id);
None
}
}

544
src/hid/xinput.rs Normal file
View file

@ -0,0 +1,544 @@
///
/// # XInput Protocol Implementation
///
/// The implementations for `XInputReader` and `XInputWriter` and the logic surrounding them is
/// mostly taken from embassy.
///
/// Unfortunately, the embassy hid classes don't allow us to specify a custom interface protocol,
/// hence the little bit of code duplication.
///
use core::{
mem::MaybeUninit,
sync::atomic::{AtomicUsize, Ordering},
};
use defmt::{info, trace, warn, Format};
use embassy_usb::{
class::hid::{Config, ReadError, ReportId, RequestHandler},
control::{InResponse, OutResponse, Recipient, Request, RequestType},
driver::{Driver, Endpoint, EndpointError, EndpointIn, EndpointOut},
types::InterfaceNumber,
Builder, Handler,
};
use packed_struct::{derive::PackedStruct, PackedStruct};
use crate::usb_comms::HidReportBuilder;
use super::{gcc::GcState, HidReaderWriterSplit, UsbReader, UsbWriter};
/// lol
pub const XINPUT_REPORT_DESCRIPTOR: &[u8] = &[];
const HID_DESC_DESCTYPE_HID: u8 = 0x21;
const HID_DESC_DESCTYPE_HID_REPORT: u8 = 0x22;
const HID_REQ_SET_IDLE: u8 = 0x0a;
const HID_REQ_GET_IDLE: u8 = 0x02;
const HID_REQ_GET_REPORT: u8 = 0x01;
const HID_REQ_SET_REPORT: u8 = 0x09;
const HID_REQ_GET_PROTOCOL: u8 = 0x03;
const HID_REQ_SET_PROTOCOL: u8 = 0x0b;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, PackedStruct, Format)]
#[packed_struct(bit_numbering = "lsb0", size_bytes = "1")]
pub struct XInputButtons1 {
#[packed_field(bits = "0")]
pub dpad_up: bool,
#[packed_field(bits = "1")]
pub dpad_down: bool,
#[packed_field(bits = "2")]
pub dpad_left: bool,
#[packed_field(bits = "3")]
pub dpad_right: bool,
#[packed_field(bits = "4")]
pub button_menu: bool,
#[packed_field(bits = "5")]
pub button_back: bool,
#[packed_field(bits = "6")]
pub button_stick_l: bool,
#[packed_field(bits = "7")]
pub button_stick_r: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, PackedStruct, Format)]
#[packed_struct(bit_numbering = "lsb0", size_bytes = "1")]
pub struct XInputButtons2 {
#[packed_field(bits = "0")]
pub bumper_l: bool,
#[packed_field(bits = "1")]
pub bumper_r: bool,
#[packed_field(bits = "2")]
pub button_guide: bool,
#[packed_field(bits = "3")]
pub blank_1: bool,
#[packed_field(bits = "4")]
pub button_a: bool,
#[packed_field(bits = "5")]
pub button_b: bool,
#[packed_field(bits = "6")]
pub button_x: bool,
#[packed_field(bits = "7")]
pub button_y: bool,
}
///
/// HID report that is sent back to the host.
///
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, PackedStruct, Format)]
#[packed_struct(bit_numbering = "msb0", endian = "lsb", size_bytes = "32")]
pub struct XInputReport {
#[packed_field(bits = "0..=7")]
pub report_id: u8,
#[packed_field(bits = "8..=15")]
pub report_size: u8,
#[packed_field(bits = "16..=23")]
pub buttons_1: XInputButtons1,
#[packed_field(bits = "24..=31")]
pub buttons_2: XInputButtons2,
#[packed_field(bits = "32..=39")]
pub analog_trigger_l: u8,
#[packed_field(bits = "40..=47")]
pub analog_trigger_r: u8,
#[packed_field(bits = "48..=63")]
pub stick_left_x: i16,
#[packed_field(bits = "64..=79")]
pub stick_left_y: i16,
#[packed_field(bits = "80..=95")]
pub stick_right_x: i16,
#[packed_field(bits = "96..=111")]
pub stick_right_y: i16,
#[packed_field(bits = "112..=255")]
pub reserved: [u8; 18],
}
impl From<&GcState> for XInputReport {
fn from(value: &GcState) -> Self {
Self {
report_id: 0,
report_size: 20,
buttons_1: XInputButtons1 {
dpad_up: value.buttons_1.dpad_up,
dpad_down: value.buttons_1.dpad_down,
dpad_right: value.buttons_1.dpad_right,
dpad_left: value.buttons_1.dpad_left,
button_menu: value.buttons_2.button_start,
button_back: false,
button_stick_l: false,
button_stick_r: false,
},
buttons_2: XInputButtons2 {
blank_1: false,
bumper_l: false,
bumper_r: value.buttons_2.button_z,
button_a: value.buttons_1.button_a,
button_b: value.buttons_1.button_b,
button_x: value.buttons_1.button_x,
button_y: value.buttons_1.button_y,
button_guide: false,
},
analog_trigger_l: value.trigger_l,
analog_trigger_r: value.trigger_r,
stick_left_x: (value.stick_x as i16 - 127).clamp(-127, 127) * 257,
stick_left_y: (value.stick_y as i16 - 127).clamp(-127, 127) * 257,
stick_right_x: (value.cstick_x as i16 - 127).clamp(-127, 127) * 257,
stick_right_y: (value.cstick_y as i16 - 127).clamp(-127, 127) * 257,
reserved: [0u8; 18],
}
}
}
///
/// Takes in a GcState, converts it to an `XInputReport` and returns its packed version.
///
pub struct XInputReportBuilder;
impl HidReportBuilder<32> for XInputReportBuilder {
async fn get_hid_report(&mut self, state: &super::gcc::GcState) -> [u8; 32] {
XInputReport::from(state)
.pack()
.expect("Failed to pack XInput State")
}
}
///
/// Handles packets sent from the host.
///
pub struct XInputRequestHandler;
impl RequestHandler for XInputRequestHandler {
fn get_report(
&mut self,
id: embassy_usb::class::hid::ReportId,
buf: &mut [u8],
) -> Option<usize> {
let _ = (id, buf);
None
}
fn set_report(
&mut self,
id: embassy_usb::class::hid::ReportId,
data: &[u8],
) -> embassy_usb::control::OutResponse {
let _ = (id, data);
info!("Set report for {:?}: {:x}", id, data);
embassy_usb::control::OutResponse::Accepted
}
fn get_idle_ms(&mut self, id: Option<embassy_usb::class::hid::ReportId>) -> Option<u32> {
let _ = id;
None
}
fn set_idle_ms(&mut self, id: Option<embassy_usb::class::hid::ReportId>, duration_ms: u32) {
let _ = (id, duration_ms);
}
}
/// Taken from embassy.
pub struct XInputWriter<'d, D: Driver<'d>, const N: usize> {
ep_in: D::EndpointIn,
}
impl<'d, D: Driver<'d>, const N: usize> UsbWriter<'d, D, N> for XInputWriter<'d, D, N> {
/// Waits for the interrupt in endpoint to be enabled.
async fn ready(&mut self) {
self.ep_in.wait_enabled().await;
}
/// Writes `report` to its interrupt endpoint.
async fn write(&mut self, report: &[u8]) -> Result<(), EndpointError> {
assert!(report.len() <= N);
let max_packet_size = usize::from(self.ep_in.info().max_packet_size);
let zlp_needed = report.len() < N && (report.len() % max_packet_size == 0);
for chunk in report.chunks(max_packet_size) {
self.ep_in.write(chunk).await?;
}
if zlp_needed {
self.ep_in.write(&[]).await?;
}
Ok(())
}
}
/// Taken from embassy.
pub struct XInputReader<'d, D: Driver<'d>, const N: usize> {
ep_out: D::EndpointOut,
offset: &'d AtomicUsize,
}
impl<'d, D: Driver<'d>, const N: usize> UsbReader<'d, D, N> for XInputReader<'d, D, N> {
async fn run<T: RequestHandler>(mut self, use_report_ids: bool, handler: &mut T) -> ! {
let offset = self.offset.load(Ordering::Acquire);
assert!(offset == 0);
let mut buf = [0; N];
loop {
match self.read(&mut buf).await {
Ok(len) => {
let id = if use_report_ids { buf[0] } else { 0 };
handler.set_report(ReportId::Out(id), &buf[..len]);
}
Err(ReadError::BufferOverflow) => warn!(
"Host ent output report larger than the configured maximum output report length ({})",
N
),
Err(ReadError::Disabled) => self.ep_out.wait_enabled().await,
Err(ReadError::Sync(_)) => unreachable!(),
}
}
}
async fn read(&mut self, buf: &mut [u8]) -> Result<usize, ReadError> {
assert!(N != 0);
assert!(buf.len() >= N);
// Read packets from the endpoint
let max_packet_size = usize::from(self.ep_out.info().max_packet_size);
let starting_offset = self.offset.load(Ordering::Acquire);
let mut total = starting_offset;
loop {
for chunk in buf[starting_offset..N].chunks_mut(max_packet_size) {
match self.ep_out.read(chunk).await {
Ok(size) => {
total += size;
if size < max_packet_size || total == N {
self.offset.store(0, Ordering::Release);
break;
}
self.offset.store(total, Ordering::Release);
}
Err(err) => {
self.offset.store(0, Ordering::Release);
return Err(err.into());
}
}
}
// Some hosts may send ZLPs even when not required by the HID spec, so we'll loop as long as total == 0.
if total > 0 {
break;
}
}
if starting_offset > 0 {
Err(ReadError::Sync(starting_offset..total))
} else {
Ok(total)
}
}
}
/// Taken from embassy, with a few modifications to the descriptor.
pub struct XInputReaderWriter<'d, D: Driver<'d>, const READ_N: usize, const WRITE_N: usize> {
reader: XInputReader<'d, D, READ_N>,
writer: XInputWriter<'d, D, WRITE_N>,
}
impl<'d, D: Driver<'d>, const READ_N: usize, const WRITE_N: usize>
XInputReaderWriter<'d, D, READ_N, WRITE_N>
{
pub fn new(
builder: &mut Builder<'d, D>,
state: &'d mut XInputState<'d>,
config: Config<'d>,
) -> Self {
let mut func = builder.function(0xff, 0x5d, 0x01);
let mut iface = func.interface();
let if_num = iface.interface_number();
let mut alt = iface.alt_setting(0xff, 0x5d, 0x01, None);
#[rustfmt::skip]
alt.descriptor(0x21, &[
0x10, 0x01, // bcdHID 1.10
0x01, // bCountryCode
0x24, // bNumDescriptors
0x81, // bDescriptorType[0] (Unknown 0x81)
0x14, 0x03, // wDescriptorLength[0] 788
0x00, // bDescriptorType[1] (Unknown 0x00)
0x03, 0x13, // wDescriptorLength[1] 4867
0x02, // bDescriptorType[2] (Unknown 0x02)
0x00, 0x03, // wDescriptorLength[2] 768
0x00, // bDescriptorType[3] (Unknown 0x00)
]);
let ep_in = alt.endpoint_interrupt_in(config.max_packet_size_in, config.poll_ms);
let ep_out = alt.endpoint_interrupt_out(config.max_packet_size_out, config.poll_ms);
drop(func);
let control = state.control.write(XInputControl::new(
if_num,
config.report_descriptor,
config.request_handler,
&state.out_report_offset,
));
builder.handler(control);
Self {
reader: XInputReader {
ep_out,
offset: &state.out_report_offset,
},
writer: XInputWriter { ep_in },
}
}
}
impl<'d, D: Driver<'d>, const READ_N: usize, const WRITE_N: usize>
HidReaderWriterSplit<'d, D, READ_N, WRITE_N> for XInputReaderWriter<'d, D, READ_N, WRITE_N>
{
fn split(
self,
) -> (
impl UsbReader<'d, D, READ_N>,
impl UsbWriter<'d, D, WRITE_N>,
) {
(self.reader, self.writer)
}
}
pub struct XInputState<'d> {
control: MaybeUninit<XInputControl<'d>>,
out_report_offset: AtomicUsize,
}
impl<'d> Default for XInputState<'d> {
fn default() -> Self {
Self::new()
}
}
impl<'d> XInputState<'d> {
pub const fn new() -> Self {
XInputState {
control: MaybeUninit::uninit(),
out_report_offset: AtomicUsize::new(0),
}
}
}
/// Taken from embassy.
struct XInputControl<'d> {
if_num: InterfaceNumber,
report_descriptor: &'d [u8],
request_handler: Option<&'d mut dyn RequestHandler>,
out_report_offset: &'d AtomicUsize,
hid_descriptor: [u8; 16],
}
impl<'d> XInputControl<'d> {
fn new(
if_num: InterfaceNumber,
report_descriptor: &'d [u8],
request_handler: Option<&'d mut dyn RequestHandler>,
out_report_offset: &'d AtomicUsize,
) -> Self {
XInputControl {
if_num,
report_descriptor,
request_handler,
out_report_offset,
#[rustfmt::skip]
hid_descriptor: [
0x10, // bLength
0x21, // bDescriptorType (HID)
0x10, 0x01, // bcdHID 1.10
0x01, // bCountryCode
0x24, // bNumDescriptors
0x81, // bDescriptorType[0] (Unknown 0x81)
0x14, 0x03, // wDescriptorLength[0] 788
0x00, // bDescriptorType[1] (Unknown 0x00)
0x03, 0x13, // wDescriptorLength[1] 4867
0x02, // bDescriptorType[2] (Unknown 0x02)
0x00, 0x03, // wDescriptorLength[2] 768
0x00, // bDescriptorType[3] (Unknown 0x00)
],
}
}
}
/// Helper function, since the function in `ReportId` is private.
const fn try_u16_to_report_id(value: u16) -> Result<ReportId, ()> {
match value >> 8 {
1 => Ok(ReportId::In(value as u8)),
2 => Ok(ReportId::Out(value as u8)),
3 => Ok(ReportId::Feature(value as u8)),
_ => Err(()),
}
}
impl<'d> Handler for XInputControl<'d> {
fn reset(&mut self) {
self.out_report_offset.store(0, Ordering::Release);
}
fn control_out(&mut self, req: Request, data: &[u8]) -> Option<OutResponse> {
if (req.request_type, req.recipient, req.index)
!= (
RequestType::Class,
Recipient::Interface,
self.if_num.0 as u16,
)
{
return None;
}
trace!("HID control_out {:?} {=[u8]:x}", req, data);
match req.request {
HID_REQ_SET_IDLE => {
if let Some(handler) = self.request_handler.as_mut() {
let id = req.value as u8;
let id = (id != 0).then_some(ReportId::In(id));
let dur = u32::from(req.value >> 8);
let dur = if dur == 0 { u32::MAX } else { 4 * dur };
handler.set_idle_ms(id, dur);
}
Some(OutResponse::Accepted)
}
HID_REQ_SET_REPORT => {
match (
try_u16_to_report_id(req.value),
self.request_handler.as_mut(),
) {
(Ok(id), Some(handler)) => Some(handler.set_report(id, data)),
_ => Some(OutResponse::Rejected),
}
}
HID_REQ_SET_PROTOCOL => {
if req.value == 1 {
Some(OutResponse::Accepted)
} else {
warn!("HID Boot Protocol is unsupported.");
Some(OutResponse::Rejected) // UNSUPPORTED: Boot Protocol
}
}
_ => Some(OutResponse::Rejected),
}
}
fn control_in<'a>(&'a mut self, req: Request, buf: &'a mut [u8]) -> Option<InResponse<'a>> {
if req.index != self.if_num.0 as u16 {
return None;
}
match (req.request_type, req.recipient) {
(RequestType::Standard, Recipient::Interface) => match req.request {
Request::GET_DESCRIPTOR => match (req.value >> 8) as u8 {
HID_DESC_DESCTYPE_HID_REPORT => {
Some(InResponse::Accepted(self.report_descriptor))
}
HID_DESC_DESCTYPE_HID => Some(InResponse::Accepted(&self.hid_descriptor)),
_ => Some(InResponse::Rejected),
},
_ => Some(InResponse::Rejected),
},
(RequestType::Class, Recipient::Interface) => {
trace!("HID control_in {:?}", req);
match req.request {
HID_REQ_GET_REPORT => {
let size = match try_u16_to_report_id(req.value) {
Ok(id) => self
.request_handler
.as_mut()
.and_then(|x| x.get_report(id, buf)),
Err(_) => None,
};
if let Some(size) = size {
Some(InResponse::Accepted(&buf[0..size]))
} else {
Some(InResponse::Rejected)
}
}
HID_REQ_GET_IDLE => {
if let Some(handler) = self.request_handler.as_mut() {
let id = req.value as u8;
let id = (id != 0).then_some(ReportId::In(id));
if let Some(dur) = handler.get_idle_ms(id) {
let dur = u8::try_from(dur / 4).unwrap_or(0);
buf[0] = dur;
Some(InResponse::Accepted(&buf[0..1]))
} else {
Some(InResponse::Rejected)
}
} else {
Some(InResponse::Rejected)
}
}
HID_REQ_GET_PROTOCOL => {
// UNSUPPORTED: Boot Protocol
buf[0] = 1;
Some(InResponse::Accepted(&buf[0..1]))
}
_ => Some(InResponse::Rejected),
}
}
_ => None,
}
}
}

View file

@ -1,7 +1,7 @@
use defmt::{debug, info, trace, Format};
use embassy_futures::yield_now;
use embassy_rp::{
gpio::{AnyPin, Input, Output, Pin},
gpio::{Input, Output},
peripherals::SPI0,
spi::{Blocking, Spi},
};
@ -16,18 +16,20 @@ use libm::{fmaxf, fminf};
use crate::{
config::{
ControllerConfig, OverrideGcReportInstruction, OverrideStickState, SIGNAL_CONFIG_CHANGE,
SIGNAL_IS_CALIBRATING, SIGNAL_OVERRIDE_GCC_STATE, SIGNAL_OVERRIDE_STICK_STATE,
ControllerConfig, ControllerMode, InputConsistencyMode, OverrideGcReportInstruction,
OverrideStickState, SIGNAL_CONFIG_CHANGE, SIGNAL_IS_CALIBRATING, SIGNAL_OVERRIDE_GCC_STATE,
SIGNAL_OVERRIDE_STICK_STATE,
},
filter::{run_waveshaping, FilterGains, KalmanState, WaveshapingValues, FILTER_GAINS},
gcc_hid::GcReport,
helpers::XyValuePair,
hid::gcc::GcState,
input_filter::{DummyFilter, InputFilter},
stick::{linearize, notch_remap, StickParams},
usb_comms::{MUTEX_CONTROLLER_MODE, MUTEX_INPUT_CONSISTENCY_MODE},
};
/// Used to send the button state to the usb task and the calibration task
pub static CHANNEL_GCC_STATE: PubSubChannel<CriticalSectionRawMutex, GcReport, 1, 4, 1> =
pub static CHANNEL_GCC_STATE: PubSubChannel<CriticalSectionRawMutex, GcState, 1, 4, 1> =
PubSubChannel::new();
/// Used to send the stick state from the stick task to the main input task
@ -35,10 +37,8 @@ static SIGNAL_STICK_STATE: Signal<CriticalSectionRawMutex, StickState> = Signal:
pub static SPI_SHARED: Mutex<ThreadModeRawMutex, Option<Spi<'static, SPI0, Blocking>>> =
Mutex::new(None);
pub static SPI_ACS_SHARED: Mutex<ThreadModeRawMutex, Option<Output<'static, AnyPin>>> =
Mutex::new(None);
pub static SPI_CCS_SHARED: Mutex<ThreadModeRawMutex, Option<Output<'static, AnyPin>>> =
Mutex::new(None);
pub static SPI_ACS_SHARED: Mutex<ThreadModeRawMutex, Option<Output<'static>>> = Mutex::new(None);
pub static SPI_CCS_SHARED: Mutex<ThreadModeRawMutex, Option<Output<'static>>> = Mutex::new(None);
const STICK_HYST_VAL: f32 = 0.3;
pub const FLOAT_ORIGIN: f32 = 127.5;
@ -81,19 +81,14 @@ pub enum StickAxis {
YAxis,
}
#[inline(never)]
#[link_section = ".time_critical.read_ext_adc"]
pub fn read_ext_adc<
'a,
Acs: Pin,
Ccs: Pin,
I: embassy_rp::spi::Instance,
M: embassy_rp::spi::Mode,
>(
pub fn read_ext_adc<'a, I: embassy_rp::spi::Instance, M: embassy_rp::spi::Mode>(
which_stick: Stick,
which_axis: StickAxis,
spi: &mut Spi<'a, I, M>,
spi_acs: &mut Output<'a, Acs>,
spi_ccs: &mut Output<'a, Ccs>,
spi_acs: &mut Output<'a>,
spi_ccs: &mut Output<'a>,
) -> u16 {
let mut buf = [0b11010000; 3];
@ -124,6 +119,7 @@ pub fn read_ext_adc<
/// Gets the average stick state over a 1ms interval in a non-blocking fashion.
/// Will wait until end_time is reached before continuing after reading the ADCs.
#[allow(clippy::too_many_arguments)]
#[inline(never)]
#[link_section = ".time_critical.update_stick_states"]
async fn update_stick_states(
current_stick_state: &StickState,
@ -154,8 +150,9 @@ async fn update_stick_states(
let spi_acs = spi_acs_unlocked.as_mut().unwrap();
let spi_ccs = spi_ccs_unlocked.as_mut().unwrap();
// "do-while at home"
while {
let mut done = false;
while !done {
let loop_start = Instant::now();
adc_count += 1;
@ -165,8 +162,9 @@ async fn update_stick_states(
cy_sum += read_ext_adc(Stick::CStick, StickAxis::YAxis, spi, spi_acs, spi_ccs) as u32;
let loop_end = Instant::now();
loop_end < end_time - (loop_end - loop_start)
} {}
done = loop_end >= end_time - (loop_end - loop_start);
}
trace!("ADC Count: {}", adc_count);
@ -346,33 +344,20 @@ async fn update_stick_states(
}
#[allow(clippy::too_many_arguments)]
fn update_button_states<
A: Pin,
B: Pin,
X: Pin,
Y: Pin,
Start: Pin,
L: Pin,
R: Pin,
Z: Pin,
DLeft: Pin,
DRight: Pin,
DUp: Pin,
DDown: Pin,
>(
gcc_state: &mut GcReport,
btn_a: &Input<'_, A>,
btn_b: &Input<'_, B>,
btn_x: &Input<'_, X>,
btn_y: &Input<'_, Y>,
btn_start: &Input<'_, Start>,
btn_l: &Input<'_, L>,
btn_r: &Input<'_, R>,
btn_z: &Input<'_, Z>,
btn_dleft: &Input<'_, DLeft>,
btn_dright: &Input<'_, DRight>,
btn_dup: &Input<'_, DUp>,
btn_ddown: &Input<'_, DDown>,
fn update_button_states(
gcc_state: &mut GcState,
btn_a: &Input<'_>,
btn_b: &Input<'_>,
btn_x: &Input<'_>,
btn_y: &Input<'_>,
btn_start: &Input<'_>,
btn_l: &Input<'_>,
btn_r: &Input<'_>,
btn_z: &Input<'_>,
btn_dleft: &Input<'_>,
btn_dright: &Input<'_>,
btn_dup: &Input<'_>,
btn_ddown: &Input<'_>,
) {
gcc_state.buttons_1.button_a = btn_a.is_low();
gcc_state.buttons_1.button_b = btn_b.is_low();
@ -401,7 +386,7 @@ pub async fn input_integrity_benchmark() {
loop {
SIGNAL_OVERRIDE_GCC_STATE.signal(OverrideGcReportInstruction {
report: {
let mut report = GcReport::default();
let mut report = GcState::default();
report.buttons_1.dpad_up = true;
report
},
@ -417,18 +402,18 @@ pub async fn input_integrity_benchmark() {
#[allow(clippy::too_many_arguments)]
#[embassy_executor::task]
pub async fn update_button_state_task(
btn_z: Input<'static, AnyPin>,
btn_a: Input<'static, AnyPin>,
btn_b: Input<'static, AnyPin>,
btn_dright: Input<'static, AnyPin>,
btn_dup: Input<'static, AnyPin>,
btn_ddown: Input<'static, AnyPin>,
btn_dleft: Input<'static, AnyPin>,
btn_l: Input<'static, AnyPin>,
btn_r: Input<'static, AnyPin>,
btn_x: Input<'static, AnyPin>,
btn_y: Input<'static, AnyPin>,
btn_start: Input<'static, AnyPin>,
btn_z: Input<'static>,
btn_a: Input<'static>,
btn_b: Input<'static>,
btn_dright: Input<'static>,
btn_dup: Input<'static>,
btn_ddown: Input<'static>,
btn_dleft: Input<'static>,
btn_l: Input<'static>,
btn_r: Input<'static>,
btn_x: Input<'static>,
btn_y: Input<'static>,
btn_start: Input<'static>,
) {
// upon loop entry, we check for the reset combo once
if btn_a.is_low() && btn_x.is_low() && btn_y.is_low() {
@ -439,7 +424,27 @@ pub async fn update_button_state_task(
loop {}
}
let mut gcc_state = GcReport::default();
{
let mut m = MUTEX_CONTROLLER_MODE.lock().await;
*m = if btn_start.is_low() {
Some(ControllerMode::Procon)
} else if btn_x.is_low() {
Some(ControllerMode::XInput)
} else {
Some(ControllerMode::GcAdapter)
};
}
let input_consistency_mode = {
while MUTEX_INPUT_CONSISTENCY_MODE.lock().await.is_none() {
Timer::after(Duration::from_millis(100)).await;
}
MUTEX_INPUT_CONSISTENCY_MODE.lock().await.unwrap()
};
let mut previous_state = GcState::default();
let mut gcc_state = GcState::default();
let gcc_publisher = CHANNEL_GCC_STATE.publisher().unwrap();
@ -448,6 +453,10 @@ pub async fn update_button_state_task(
// replace this with the input filter of your choice, if you so desire.
let mut input_filter = DummyFilter;
let mut initializing = true;
let init_time = Instant::now();
loop {
update_button_states(
&mut gcc_state,
@ -483,7 +492,15 @@ pub async fn update_button_state_task(
trace!("Overridden gcc state: {:?}", override_gcc_state.report);
let end_time = Instant::now() + Duration::from_millis(override_gcc_state.duration_ms);
while Instant::now() < end_time {
gcc_publisher.publish_immediate(override_gcc_state.report);
if input_consistency_mode == InputConsistencyMode::SuperHack {
if override_gcc_state.report != previous_state {
gcc_publisher.publish_immediate(override_gcc_state.report);
previous_state = override_gcc_state.report;
}
} else {
gcc_publisher.publish_immediate(override_gcc_state.report);
}
yield_now().await;
}
};
@ -503,7 +520,20 @@ pub async fn update_button_state_task(
gcc_publisher.publish_immediate(overriden_gcc_state);
} else {
input_filter.apply_filter(&mut gcc_state);
gcc_publisher.publish_immediate(gcc_state);
if input_consistency_mode == InputConsistencyMode::SuperHack {
// transmit state always for the first 5 seconds to give the console time to initialize the controller
if initializing && Instant::now().duration_since(init_time) > Duration::from_secs(5)
{
initializing = false;
}
if gcc_state != previous_state || initializing {
gcc_publisher.publish_immediate(gcc_state);
previous_state = gcc_state;
}
} else {
gcc_publisher.publish_immediate(gcc_state);
}
}
// give other tasks a chance to do something
@ -516,13 +546,17 @@ pub async fn update_button_state_task(
///
/// Has to run on core0 because it makes use of SPI0.
#[embassy_executor::task]
#[inline(never)]
#[link_section = ".time_critical.update_stick_states_task"]
pub async fn update_stick_states_task(
spi: Spi<'static, SPI0, embassy_rp::spi::Blocking>,
spi_acs: Output<'static, AnyPin>,
spi_ccs: Output<'static, AnyPin>,
spi_acs: Output<'static>,
spi_ccs: Output<'static>,
) {
Timer::after_secs(1).await;
// let some time pass before accepting stick inputs
// to ensure sticks are properly zeroed
Timer::after_secs(2).await;
*SPI_SHARED.lock().await = Some(spi);
*SPI_ACS_SHARED.lock().await = Some(spi_acs);
*SPI_CCS_SHARED.lock().await = Some(spi_ccs);
@ -581,7 +615,7 @@ pub async fn update_stick_states_task(
let n = Instant::now();
match (n - last_loop_time).as_micros() {
a if a > 1666 => debug!("Loop took {} us", a),
a if a > 800 => debug!("Loop took {} us", a),
_ => {}
};
last_loop_time = n;

View file

@ -2,15 +2,19 @@ use defmt::warn;
use crate::{
config::{is_awaitable_button_pressed, AwaitableButtons},
gcc_hid::GcReport,
hid::gcc::GcState,
};
/**
* Houses functionality for modifying GCC state before it is sent to the console.
*
* General info for implementing filters on the sticks:
* X and Y values of a stick go each from 0 to 255.
* 127.5 is the middle value and when both X and Y are 127.5 the stick is in neutral position.
*/
pub trait InputFilter: Sized {
fn apply_filter(&mut self, gcc_state: &mut GcReport);
fn apply_filter(&mut self, gcc_state: &mut GcState);
}
/// Presses a single button if another button is pressed.
@ -22,7 +26,7 @@ pub struct SingleButtonMacroFilter {
}
impl InputFilter for SingleButtonMacroFilter {
fn apply_filter(&mut self, gcc_state: &mut GcReport) {
fn apply_filter(&mut self, gcc_state: &mut GcState) {
if is_awaitable_button_pressed(gcc_state, &self.btn_instigator) {
match self.btn_to_press {
AwaitableButtons::A => {
@ -79,7 +83,7 @@ impl InputFilter for SingleButtonMacroFilter {
pub struct CStickUpTiltFilter;
impl InputFilter for CStickUpTiltFilter {
fn apply_filter(&mut self, gcc_state: &mut GcReport) {
fn apply_filter(&mut self, gcc_state: &mut GcState) {
if gcc_state.cstick_y > 157 {
if (137..=201).contains(&gcc_state.cstick_x) {
gcc_state.cstick_x = 201;
@ -100,10 +104,37 @@ impl InputFilter for CStickUpTiltFilter {
}
}
/// Improves hitting up/down angled forward tilt at the cost
/// of making it impossible to hit turnaround up & down tilt
/// and making it slightly harder to hit regular forward tilt.
pub struct CStickAngledFTiltFilter;
impl InputFilter for CStickAngledFTiltFilter {
fn apply_filter(&mut self, gcc_state: &mut GcState) {
if gcc_state.cstick_y > 147 {
if (147..=225).contains(&gcc_state.cstick_x) {
gcc_state.cstick_x = 205;
gcc_state.cstick_y = 205;
} else if (30..=107).contains(&gcc_state.cstick_x) {
gcc_state.cstick_x = 50;
gcc_state.cstick_y = 205;
}
} else if gcc_state.cstick_y < 107 {
if (147..=225).contains(&gcc_state.cstick_x) {
gcc_state.cstick_x = 205;
gcc_state.cstick_y = 50;
} else if (30..=107).contains(&gcc_state.cstick_x) {
gcc_state.cstick_x = 50;
gcc_state.cstick_y = 50;
}
}
}
}
/// Does nothing.
#[derive(Default)]
pub struct DummyFilter;
impl InputFilter for DummyFilter {
fn apply_filter(&mut self, _gcc_state: &mut GcReport) {}
fn apply_filter(&mut self, _gcc_state: &mut GcState) {}
}

View file

@ -1,19 +1,18 @@
//! This example test the RP Pico on board LED.
//!
//! It does not work with the RP Pico W board. See wifi_blinky.rs.
#![no_std]
#![no_main]
mod config;
mod filter;
mod gcc_hid;
mod helpers;
mod hid;
mod input;
mod input_filter;
mod stick;
mod usb_comms;
use core::ptr::addr_of_mut;
use config::config_task;
use defmt::{debug, info};
use defmt::info;
use embassy_executor::Executor;
use embassy_rp::{
bind_interrupts,
@ -24,14 +23,14 @@ use embassy_rp::{
spi::{self, Spi},
usb::{Driver, InterruptHandler},
};
use gcc_hid::usb_transfer_task;
use gpio::{Level, Output};
use usb_comms::usb_transfer_task;
use input::{update_button_state_task, update_stick_states_task};
use static_cell::StaticCell;
use crate::config::enter_config_mode_task;
use crate::gcc_hid::rumble_task;
use crate::usb_comms::rumble_task;
use {defmt_rtt as _, panic_probe as _};
@ -75,49 +74,37 @@ fn main() -> ! {
let spi_acs = Output::new(AnyPin::from(p_acs), Level::High); // active low
let spi_ccs = Output::new(AnyPin::from(p_ccs), Level::High); // active low
spawn_core1(p.CORE1, unsafe { &mut CORE1_STACK }, move || {
let executor1 = EXECUTOR1.init(Executor::new());
debug!("Mana");
executor1.run(|spawner| {
spawner.spawn(usb_transfer_task(uid, driver)).unwrap();
spawner.spawn(enter_config_mode_task()).unwrap();
spawner
.spawn(rumble_task(p.PIN_25, p.PIN_29, p.PWM_CH4, p.PWM_CH6))
.unwrap();
// spawner.spawn(input_integrity_benchmark()).unwrap();
spawner
.spawn(update_button_state_task(
Input::new(AnyPin::from(p.PIN_20), gpio::Pull::Up),
Input::new(AnyPin::from(p.PIN_17), gpio::Pull::Up),
Input::new(AnyPin::from(p.PIN_16), gpio::Pull::Up),
Input::new(AnyPin::from(p.PIN_11), gpio::Pull::Up),
Input::new(AnyPin::from(p.PIN_9), gpio::Pull::Up),
Input::new(AnyPin::from(p.PIN_10), gpio::Pull::Up),
Input::new(AnyPin::from(p.PIN_8), gpio::Pull::Up),
Input::new(AnyPin::from(p.PIN_22), gpio::Pull::Up),
Input::new(AnyPin::from(p.PIN_21), gpio::Pull::Up),
Input::new(AnyPin::from(p.PIN_18), gpio::Pull::Up),
Input::new(AnyPin::from(p.PIN_19), gpio::Pull::Up),
Input::new(AnyPin::from(p.PIN_5), gpio::Pull::Up),
))
.unwrap()
});
});
// Stick loop has to run on core0 because it makes use of SPI0.
// Perhaps in the future we can rewire the board to have it make use of SPI1 instead.
// This way it could be the sole task running on core1, and everything else could happen on core0.
// Also, it needs to run on a higher prio executor to ensure consistent polling.
// interrupt::SWI_IRQ_1.set_priority(interrupt::Priority::P0);
// let spawner_high = EXECUTOR_HIGH.start(interrupt::SWI_IRQ_1);
// spawner_high
// .spawn(update_stick_states_task(
// spi,
// spi_acs,
// spi_ccs,
// controller_config.clone(),
// ))
// .unwrap();
spawn_core1(
p.CORE1,
unsafe { addr_of_mut!(CORE1_STACK).as_mut().unwrap() },
move || {
let executor1 = EXECUTOR1.init(Executor::new());
executor1.run(|spawner| {
spawner.spawn(usb_transfer_task(uid, driver)).unwrap();
spawner.spawn(enter_config_mode_task()).unwrap();
spawner
.spawn(rumble_task(p.PIN_25, p.PIN_29, p.PWM_SLICE4, p.PWM_SLICE6))
.unwrap();
// spawner.spawn(input_integrity_benchmark()).unwrap();
spawner
.spawn(update_button_state_task(
Input::new(AnyPin::from(p.PIN_20), gpio::Pull::Up),
Input::new(AnyPin::from(p.PIN_17), gpio::Pull::Up),
Input::new(AnyPin::from(p.PIN_16), gpio::Pull::Up),
Input::new(AnyPin::from(p.PIN_11), gpio::Pull::Up),
Input::new(AnyPin::from(p.PIN_9), gpio::Pull::Up),
Input::new(AnyPin::from(p.PIN_10), gpio::Pull::Up),
Input::new(AnyPin::from(p.PIN_8), gpio::Pull::Up),
Input::new(AnyPin::from(p.PIN_22), gpio::Pull::Up),
Input::new(AnyPin::from(p.PIN_21), gpio::Pull::Up),
Input::new(AnyPin::from(p.PIN_18), gpio::Pull::Up),
Input::new(AnyPin::from(p.PIN_19), gpio::Pull::Up),
Input::new(AnyPin::from(p.PIN_5), gpio::Pull::Up),
))
.unwrap()
});
},
);
let executor0 = EXECUTOR0.init(Executor::new());
info!("Initialized.");

View file

@ -882,6 +882,7 @@ pub fn calc_stick_values(angle: f32) -> (f32, f32) {
(x, y)
}
#[inline(never)]
#[link_section = ".time_critical.linearize"]
pub fn linearize(point: f32, coefficients: &[f32; NUM_COEFFS]) -> f32 {
coefficients[0] * (point * point * point)
@ -890,6 +891,7 @@ pub fn linearize(point: f32, coefficients: &[f32; NUM_COEFFS]) -> f32 {
+ coefficients[3]
}
#[inline(never)]
#[link_section = ".time_critical.notch_remap"]
pub fn notch_remap(
x_in: f32,

499
src/usb_comms.rs Normal file
View file

@ -0,0 +1,499 @@
/**
* Communication with the console / PC over USB HID.
* Includes the HID report descriptor, and the GcReport struct.
*/
use core::{default::Default, future::Future};
use defmt::{debug, info, trace, warn};
use embassy_futures::join::join;
use embassy_rp::{
peripherals::{PIN_25, PIN_29, PWM_SLICE4, PWM_SLICE6, USB},
pwm::Pwm,
usb::Driver as EmbassyDriver,
};
use embassy_sync::{blocking_mutex::raw::CriticalSectionRawMutex, mutex::Mutex, signal::Signal};
use embassy_time::{Duration, Instant, Timer};
use embassy_usb::{
class::hid::{HidReaderWriter, RequestHandler, State},
driver::Driver,
msos::{self, windows_version},
Builder, Handler, UsbDevice,
};
use libm::powf;
use crate::{
config::{ControllerMode, InputConsistencyMode},
hid::{
gcc::{GcReportBuilder, GcState, GccRequestHandler, GCC_REPORT_DESCRIPTOR},
procon::{ProconReportBuilder, ProconRequestHandler, PROCON_REPORT_DESCRIPTOR},
xinput::{
XInputReaderWriter, XInputReportBuilder, XInputRequestHandler, XInputState,
XINPUT_REPORT_DESCRIPTOR,
},
HidReaderWriterSplit, UsbReader, UsbWriter,
},
input::CHANNEL_GCC_STATE,
};
pub static SIGNAL_RUMBLE: Signal<CriticalSectionRawMutex, bool> = Signal::new();
/// We could turn the config change signal into a PubSubChannel instead, but that
/// would just transmit unnecessary amounts of data.
pub static SIGNAL_CHANGE_RUMBLE_STRENGTH: Signal<CriticalSectionRawMutex, u8> = Signal::new();
/// Only dispatched ONCE after powerup, to determine how to advertise itself via USB.
pub static MUTEX_INPUT_CONSISTENCY_MODE: Mutex<
CriticalSectionRawMutex,
Option<InputConsistencyMode>,
> = Mutex::new(None);
/// Only dispatched ONCE after powerup, to determine how to advertise itself via USB.
pub static MUTEX_CONTROLLER_MODE: Mutex<CriticalSectionRawMutex, Option<ControllerMode>> =
Mutex::new(None);
/// Vendor-defined property data
const DEVICE_INTERFACE_GUID: &str = "{ecceff35-146c-4ff3-acd9-8f992d09acdd}";
pub trait HidReportBuilder<const LEN: usize> {
async fn get_hid_report(&mut self, state: &GcState) -> [u8; LEN];
}
struct UsbConfig {
vid: u16,
pid: u16,
report_descriptor: &'static [u8],
}
impl From<ControllerMode> for UsbConfig {
fn from(value: ControllerMode) -> Self {
match value {
ControllerMode::GcAdapter => Self {
vid: 0x057e,
pid: 0x0337,
report_descriptor: GCC_REPORT_DESCRIPTOR,
},
ControllerMode::Procon => Self {
vid: 0x57e,
pid: 0x2009,
report_descriptor: PROCON_REPORT_DESCRIPTOR,
},
ControllerMode::XInput => Self {
vid: 0x045e,
pid: 0x028e,
report_descriptor: XINPUT_REPORT_DESCRIPTOR,
},
}
}
}
struct MyDeviceHandler {
configured: bool,
}
impl MyDeviceHandler {
fn new() -> Self {
MyDeviceHandler { configured: false }
}
}
impl Handler for MyDeviceHandler {
fn enabled(&mut self, enabled: bool) {
self.configured = true;
// reason: in production, info! compiles to nothing
#[allow(clippy::if_same_then_else)]
if enabled {
info!("Device enabled");
} else {
info!("Device disabled");
}
}
fn reset(&mut self) {
self.configured = false;
info!("Bus reset, the Vbus current limit is 100mA");
}
fn addressed(&mut self, addr: u8) {
self.configured = false;
info!("USB address set to: {}", addr);
}
fn configured(&mut self, configured: bool) {
self.configured = configured;
if configured {
info!(
"Device configured, it may now draw up to the configured current limit from Vbus."
)
} else {
info!("Device is no longer configured, the Vbus current limit is 100mA.");
}
}
}
fn mk_hid_reader_writer<'d, S, D, T, F, const R: usize, const W: usize>(
input_consistency_mode: InputConsistencyMode,
controller_mode: ControllerMode,
report_descriptor: &'d [u8],
mut builder: Builder<'d, D>,
state: &'d mut S,
mut init_func: F,
) -> (
UsbDevice<'d, D>,
impl UsbReader<'d, D, R>,
impl UsbWriter<'d, D, W>,
)
where
D: Driver<'d>,
T: HidReaderWriterSplit<'d, D, R, W> + 'd,
F: FnMut(&mut Builder<'d, D>, &'d mut S, embassy_usb::class::hid::Config<'d>) -> T + 'd,
{
let hid_config = embassy_usb::class::hid::Config {
report_descriptor,
request_handler: None,
poll_ms: if let ControllerMode::XInput = controller_mode {
1
} else {
match input_consistency_mode {
InputConsistencyMode::Original => 8,
InputConsistencyMode::ConsistencyHack
| InputConsistencyMode::SuperHack
| InputConsistencyMode::PC => 1,
}
},
max_packet_size_in: W as u16,
max_packet_size_out: R as u16,
};
let hid = init_func(&mut builder, state, hid_config);
let usb = builder.build();
let (reader, writer) = hid.split();
(usb, reader, writer)
}
#[allow(clippy::too_many_arguments)]
fn mk_usb_transfer_futures<'d, S, D, H, F, Rq, T, const R: usize, const W: usize>(
input_consistency_mode: InputConsistencyMode,
controller_mode: ControllerMode,
usb_config: &UsbConfig,
request_handler: &'d mut Rq,
builder: Builder<'d, D>,
mut hid_report_builder: H,
state: &'d mut S,
init_func: F,
) -> (
impl Future<Output = ()> + 'd,
impl Future<Output = ()> + 'd,
impl Future<Output = ()> + 'd,
)
where
D: Driver<'d> + 'd,
H: HidReportBuilder<W> + 'd,
Rq: RequestHandler,
T: HidReaderWriterSplit<'d, D, R, W> + 'd,
F: FnMut(&mut Builder<'d, D>, &'d mut S, embassy_usb::class::hid::Config<'d>) -> T + 'd,
{
let (mut usb, reader, mut writer) = mk_hid_reader_writer(
input_consistency_mode,
controller_mode,
usb_config.report_descriptor,
builder,
state,
init_func,
);
let usb_fut = async move {
loop {
usb.run_until_suspend().await;
debug!("Suspended");
usb.wait_resume().await;
debug!("RESUMED!");
}
};
let in_fut = async move {
let mut gcc_subscriber = CHANNEL_GCC_STATE.subscriber().unwrap();
let mut last_report_time = Instant::now();
let mut rate_limit_end_time = Instant::now();
loop {
// This is what we like to call a "hack".
// It forces reports to be sent at least every 8.33ms instead of every 8ms.
// 8.33ms is a multiple of the game's frame interval (16.66ms), so if we
// send a report every 8.33ms, it should (in theory) ensure (close to)
// 100% input accuracy.
//
// From the console's perspective, we are basically a laggy adapter, taking
// a minimum of 333 extra us to send a report every time it's polled, but it
// works to our advantage.
if controller_mode != ControllerMode::XInput {
match input_consistency_mode {
InputConsistencyMode::SuperHack | InputConsistencyMode::ConsistencyHack => {
// "Ticker at home", so we can use this for both consistency and SuperHack mode
Timer::at(rate_limit_end_time).await;
}
InputConsistencyMode::Original | InputConsistencyMode::PC => {}
}
}
writer.ready().await;
let state = gcc_subscriber.next_message_pure().await;
let report = hid_report_builder.get_hid_report(&state).await;
trace!("Writing report: {:08b}", report);
match writer.write(&report).await {
Ok(()) => {
let currtime = Instant::now();
let polltime = currtime.duration_since(last_report_time);
let micros = polltime.as_micros();
debug!("Report written in {}us", micros);
if input_consistency_mode != InputConsistencyMode::Original
&& input_consistency_mode != InputConsistencyMode::PC
&& controller_mode != ControllerMode::XInput
{
while rate_limit_end_time < currtime {
rate_limit_end_time += Duration::from_micros(8333);
}
}
last_report_time = currtime;
}
Err(e) => warn!("Failed to send report: {:?}", e),
}
}
};
let out_fut = async move {
trace!("Readery loop");
reader.run(true, request_handler).await;
};
let usb_fut_wrapped = async {
usb_fut.await;
debug!("USB FUT DED");
};
(usb_fut_wrapped, in_fut, out_fut)
}
#[embassy_executor::task]
pub async fn usb_transfer_task(raw_serial: [u8; 8], driver: EmbassyDriver<'static, USB>) {
let input_consistency_mode = {
while MUTEX_INPUT_CONSISTENCY_MODE.lock().await.is_none() {
Timer::after(Duration::from_millis(100)).await;
}
MUTEX_INPUT_CONSISTENCY_MODE.lock().await.unwrap()
};
let controller_mode = {
while MUTEX_CONTROLLER_MODE.lock().await.is_none() {
Timer::after(Duration::from_millis(100)).await;
}
MUTEX_CONTROLLER_MODE.lock().await.unwrap()
};
let config = UsbConfig::from(controller_mode);
let mut serial_buffer = [0u8; 64];
let serial = format_no_std::show(
&mut serial_buffer,
format_args!(
"{:02X}{:02X}{:02X}{:02X}{:02X}{:02X}{:02X}{:02X}",
raw_serial[0],
raw_serial[1],
raw_serial[2],
raw_serial[3],
raw_serial[4],
raw_serial[5],
raw_serial[6],
raw_serial[7]
),
)
.unwrap();
info!("Detected flash with unique serial number {}", serial);
trace!("Start of config");
let mut usb_config = embassy_usb::Config::new(config.vid, config.pid);
usb_config.manufacturer = Some("Naxdy");
usb_config.product = Some(if controller_mode == ControllerMode::XInput {
"NaxGCC (XInput Mode)"
} else {
match input_consistency_mode {
InputConsistencyMode::Original => "NaxGCC (OG Mode)",
InputConsistencyMode::ConsistencyHack => "NaxGCC (Consistency Mode)",
InputConsistencyMode::SuperHack => "NaxGCC (SuperHack Mode)",
InputConsistencyMode::PC => "NaxGCC (PC Mode)",
}
});
usb_config.serial_number = Some(serial);
usb_config.max_power = 200;
usb_config.max_packet_size_0 = 64;
usb_config.device_class = if controller_mode == ControllerMode::XInput {
0xff
} else {
0
};
usb_config.device_protocol = 0;
usb_config.self_powered = false;
usb_config.device_sub_class = if controller_mode == ControllerMode::XInput {
0xff
} else {
0
};
usb_config.supports_remote_wakeup = true;
usb_config.device_release = if controller_mode == ControllerMode::XInput {
0x0572
} else {
0x0010
};
let mut config_descriptor = [0; 256];
let mut bos_descriptor = [0; 256];
let mut msos_descriptor = [0; 256];
let mut control_buf = [0; 64];
let mut device_handler = MyDeviceHandler::new();
let mut builder = Builder::new(
driver,
usb_config,
&mut config_descriptor,
&mut bos_descriptor,
&mut msos_descriptor,
&mut control_buf,
);
builder.msos_descriptor(windows_version::WIN8_1, 2);
let msos_writer = builder.msos_writer();
msos_writer.device_feature(msos::CompatibleIdFeatureDescriptor::new("WINUSB", ""));
msos_writer.device_feature(msos::RegistryPropertyFeatureDescriptor::new(
"DeviceInterfaceGUID",
msos::PropertyData::Sz(DEVICE_INTERFACE_GUID),
));
builder.handler(&mut device_handler);
match controller_mode {
ControllerMode::GcAdapter => {
let mut state = State::new();
let mut request_handler = GccRequestHandler;
let (usb_fut_wrapped, in_fut, out_fut) = mk_usb_transfer_futures(
input_consistency_mode,
controller_mode,
&config,
&mut request_handler,
builder,
GcReportBuilder::default(),
&mut state,
HidReaderWriter::<_, 5, 37>::new,
);
join(usb_fut_wrapped, join(in_fut, out_fut)).await;
}
ControllerMode::Procon => {
let mut state = State::new();
let mut request_handler = ProconRequestHandler;
let (usb_fut_wrapped, in_fut, out_fut) = mk_usb_transfer_futures(
input_consistency_mode,
controller_mode,
&config,
&mut request_handler,
builder,
ProconReportBuilder::default(),
&mut state,
HidReaderWriter::<_, 64, 64>::new,
);
join(usb_fut_wrapped, join(in_fut, out_fut)).await;
}
ControllerMode::XInput => {
let mut state = XInputState::new();
let mut request_handler = XInputRequestHandler;
let (usb_fut_wrapped, in_fut, out_fut) = mk_usb_transfer_futures(
input_consistency_mode,
controller_mode,
&config,
&mut request_handler,
builder,
XInputReportBuilder,
&mut state,
XInputReaderWriter::<_, 32, 32>::new,
);
join(usb_fut_wrapped, join(in_fut, out_fut)).await;
}
};
}
fn calc_rumble_power(strength: u8) -> u16 {
if strength > 0 {
powf(2.0, 7.0 + ((strength as f32 - 3.0) / 8.0)) as u16
} else {
0
}
}
#[embassy_executor::task]
pub async fn rumble_task(
pin_rumble: PIN_25,
pin_brake: PIN_29,
pwm_ch_rumble: PWM_SLICE4,
pwm_ch_brake: PWM_SLICE6,
) {
let mut rumble_config: embassy_rp::pwm::Config = Default::default();
rumble_config.top = 255;
rumble_config.enable = true;
rumble_config.compare_b = 0;
let mut brake_config = rumble_config.clone();
brake_config.compare_b = 255;
let mut pwm_rumble = Pwm::new_output_b(pwm_ch_rumble, pin_rumble, rumble_config.clone());
let mut pwm_brake = Pwm::new_output_b(pwm_ch_brake, pin_brake, brake_config.clone());
let mut rumble_power = {
let strength = SIGNAL_CHANGE_RUMBLE_STRENGTH.wait().await;
calc_rumble_power(strength)
};
loop {
let new_rumble_status = SIGNAL_RUMBLE.wait().await;
debug!("Received rumble signal: {}", new_rumble_status);
if let Some(new_strength) = SIGNAL_CHANGE_RUMBLE_STRENGTH.try_take() {
rumble_power = calc_rumble_power(new_strength);
}
if new_rumble_status {
rumble_config.compare_b = rumble_power;
brake_config.compare_b = 0;
pwm_rumble.set_config(&rumble_config);
pwm_brake.set_config(&brake_config);
} else {
rumble_config.compare_b = 0;
brake_config.compare_b = 255;
pwm_rumble.set_config(&rumble_config);
pwm_brake.set_config(&brake_config);
}
}
}