commit 21f54f1b9293a792d3f259ab9bdcfcc4354c0454 Author: dark98 Date: Sat Oct 17 18:26:50 2026 +0100 Initial commit: MimiCon v1.0.0 - Universal Gamepad Mimic & Console Bridge - Dual-Core Architecture: Dedicated 1000Hz USB gaming pipeline on Core 1 and BLE/Wi-Fi/Web telemetry on Core 0. - Multi-Input BLE Host: Parsers for Xbox Wireless, Google Stadia, 8BitDo (Ultimate/Pro2/SN30), and Generic HOGP gamepads. - Multi-Console USB Emulation: Nintendo Switch, PC DirectInput, PS3, PS4, Xbox 360 (libxsm3 cryptographic challenge-response), Original Xbox, and Couch Mouse/Keyboard. - Onboard Web Portal & Captive Portal: Real-time SVG gamepad visualizer, stick deadzone calibration, button combo remapping, and Wi-Fi manager. - Low-Latency Radio Management: Interactive SoftAP toggle to drop to 0-latency gaming mode. - Dual OTA Firmware Flashing: Browser-based wireless firmware updater and automated Python OTA script. - Strict Build Quality: Clean build under -Wall -Wextra with zero warnings or errors. - Versioning & Licensing: Semantic Versioning v1.0.0 and GNU GPLv3 with Commercial Restrictions. diff --git a/.clangd b/.clangd new file mode 100644 index 0000000..437f255 --- /dev/null +++ b/.clangd @@ -0,0 +1,2 @@ +CompileFlags: + Remove: [-f*, -m*] diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..e29f4ac --- /dev/null +++ b/.editorconfig @@ -0,0 +1,18 @@ +# EditorConfig helps maintain consistent coding styles across IDEs and contributors +# https://editorconfig.org + +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true +indent_style = space +indent_size = 4 + +[*.{json,yml,yaml,md,html,css,js}] +indent_size = 2 + +[Makefile] +indent_style = tab diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6b0fb66 --- /dev/null +++ b/.gitignore @@ -0,0 +1,23 @@ +# ESP-IDF build artifacts +build/ +sdkconfig +sdkconfig.old + +# Component manager +managed_components/ +dependencies.lock + +# Python cache & virtual environments +__pycache__/ +*.py[cod] +*$py.class +.venv/ +venv/ + +# Editor & tooling cache +.cache/ +.vscode/ + +# OS metadata +.DS_Store +Thumbs.db diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..29d5261 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,9 @@ +cmake_minimum_required(VERSION 3.16) + +# Read version from version.txt for reproducible SemVer across build artifacts +if(EXISTS "${CMAKE_CURRENT_LIST_DIR}/version.txt") + file(STRINGS "${CMAKE_CURRENT_LIST_DIR}/version.txt" PROJECT_VER) +endif() + +include($ENV{IDF_PATH}/tools/cmake/project.cmake) +project(mimicon) diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..cd113e4 --- /dev/null +++ b/LICENSE @@ -0,0 +1,357 @@ +GNU GENERAL PUBLIC LICENSE +Version 3, 29 June 2007 (with Non-Commercial Exclusivity Rider) + +Copyright (C) 2026 dark98 + +============================================================================== +COMMERCIAL RESTRICTION & NON-COMMERCIAL EXCLUSIVITY CLAUSE +============================================================================== + +Notwithstanding any provision in the GNU General Public License below, +permission to use, copy, modify, and distribute this software is strictly +conditioned upon compliance with the following additional terms: + +1. COPYLEFT & MANDATORY OPEN SOURCE: + All modifications, forks, enhancements, and derivative works of this + software or firmware MUST remain 100% free and open-source under these + exact license terms. Any individual or entity that distributes a fork or + derivative work must make the full, complete corresponding source code + publicly and freely available. + +2. COMMERCIAL RESTRICTIONS: + NO INDIVIDUAL, ENTITY, OR ORGANIZATION (OTHER THAN THE ORIGINAL COPYRIGHT + HOLDER, dark98) IS PERMITTED TO SELL, LICENSE, RESELL, OR COMMERCIALLY + EXPLOIT THIS SOFTWARE, ITS SOURCE CODE, OR ITS BINARIES IN ANY FORM. + This restriction explicitly includes: + - Selling copies or modified versions of the software or firmware binaries. + - Selling physical hardware devices or pre-flashed microcontrollers bundled + with this software or any derivative version thereof for profit. + - Charging fees, subscriptions, or paywalls for access to, or flashing of, + this firmware. + +3. EXCLUSIVE COMMERCIAL RIGHTS: + The copyright holder (dark98) exclusively reserves all rights to sell, + monetize, commercially license, or distribute the software or pre-flashed + hardware for commercial purposes. Any commercial use or commercial + distribution by third parties requires prior written authorization from + dark98. + +============================================================================== + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + 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 manner 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. + + Subject to the Commercial Restriction clause above, you may not charge +any fee for the copies. + + 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. + + 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. + + 7. Additional Terms. + + The Commercial Restriction & Non-Commercial Exclusivity Clause above +constitutes an additional permission restriction under which this work is +licensed. Any modified or derivative works conveyed must retain these terms. + + 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. + + 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. + + 11. Patents. + + 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. +Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims. + + 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. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users interacting +with it remotely through a computer network an opportunity to receive the +Corresponding Source of your version. + + 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. + + 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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..1a967d1 --- /dev/null +++ b/README.md @@ -0,0 +1,163 @@ +# 🎮 MimiCon: The Shape-Shifting Gamepad Bridge + +> **Any Controller. Any Console. Pure Mimicry.** + +A high-performance controller bridge running on the ultra-compact **Waveshare ESP32-S3-Zero**. **MimiCon** seamlessly translates **Wireless Bluetooth Gamepads** (Xbox Series/One, Google Stadia, 8BitDo, generic BLE HOGP) and **Web Touch Remote Controllers** into native USB wired controller signals for target consoles (**Nintendo Switch**, **Xbox 360**, **Original Xbox**, **PlayStation 3**, **PlayStation 4**, **PC DirectInput**, and **Couch Mouse & Keyboard**). + +--- + +## Architecture Overview + +MimiCon harnesses the dual-core Xtensa LX7 processor of the ESP32-S3: +- **Core 0 (Networking & RF Stack):** Dedicated entirely to Bluetooth LE Central (NimBLE), Wi-Fi Station & SoftAP, LwIP TCP/IP, HTTP Server, WebSocket telemetry, and mDNS. +- **Core 1 (Realtime Gaming Engine):** Dedicated 1000 Hz USB gaming loop, handling packet dispatch, input calibration, cryptographic challenges (Xbox 360 XSM3, OG Xbox security handshake), hotkey combo detection, and status LED animations with zero radio interference. + +``` +┌──────────────────────────────────────────────┐ +│ Wireless Input Sources │ +│ - Xbox Wireless (Series X/S, One S) │ +│ - Google Stadia Gamepad (BLE Mode) │ +│ - 8BitDo Controllers (Switch & D-Input) │ +│ - Generic Mobile / PC BLE Gamepads │ +│ - Web Touch Controller (Phone / Browser) │ +└──────────────────────â”Ŧ───────────────────────┘ + │ BLE GATT / WebSocket + â–ŧ +┌──────────────────────────────────────────────┐ +│ Core 0: RF & Input Parser │ +│ - Auto-scans & fast-reconnects to bonded │ +│ - Parser Pipeline: xbox, stadia, 8bitdo │ +│ - WebSocket state streaming (/ws/state) │ +└──────────────────────â”Ŧ───────────────────────┘ + │ controller_state_t + â–ŧ +┌──────────────────────────────────────────────┐ +│ Core 1: Gaming Engine (1000 Hz) │ +│ - Deadzone & axis calibration engine │ +│ - Hotkey profile manager (START + Face) │ +│ - Cryptographic security (XSM3 & OGX) │ +│ - Real-time USB re-enumeration │ +└──────────────────────â”Ŧ───────────────────────┘ + │ Native USB (GPIO 19 / 20) + â–ŧ +┌──────────────────────────────────────────────┐ +│ Target Host Console │ +│ Switch | X360 | OG Xbox | PS3 | PS4 | PC/Mac │ +└──────────────────────────────────────────────┘ +``` + +--- + +## Supported Input Controllers + +| Controller | Connection Type | Parser | Features Supported | +| :--- | :--- | :--- | :--- | +| **Xbox Wireless Controller** (Series X/S & One S) | Bluetooth Low Energy | `parser_xbox_ble` | Full 16-byte report, dual sticks, analog triggers, D-Pad, face buttons, View, Menu, Share, bi-directional rumble. | +| **Google Stadia Controller** (Bluetooth Mode) | Bluetooth Low Energy | `parser_stadia` | Dual sticks, analog triggers, D-Pad, face buttons, Options, Menu, Stadia Home, Assistant, Capture, rumble. | +| **8BitDo Controllers** (Pro 2, Ultimate, SN30 Pro, etc.) | Bluetooth Low Energy | `parser_8bitdo` | Switch Mode (0x3F/0x30 reports), D-Input, X-Input, dual rumble motor schemes, Home & Star buttons. | +| **Generic Mobile / PC BLE Gamepads** | Bluetooth Low Energy | `parser_generic_hogp` | Standard HID Over GATT Profile (HOGP) 8-bit axis and digital button mapping. | +| **Phone / Web Virtual Touch Gamepad** | Wi-Fi WebSocket | Built-in Web Portal | Fullscreen landscape remote with dual analog thumbsticks, L3/R3, face buttons, D-pad, and haptic feedback. | + +--- + +## Output Console Modes & On-The-Fly Switching + +You can switch the target console output profile **at any time** while playing using **`START + [Face Button]`** (held for ~1.5 seconds) or clicking the onboard **`BOOT`** button: + +| Button Combo (Hold ~1.5s) | Default Profile | Web Panel Configurable | Onboard RGB LED Color | Description | +| :--- | :--- | :--- | :--- | :--- | +| **`START + B`** (Circle / East) | **Nintendo Switch** | Yes (Any mode or Disabled) | **Solid Cyan** | Emulates a HORI Pokken Tournament DX Pro Pad (VID `0x0F0D`, PID `0x0092`). Plug & play without popups. | +| **`START + A`** (Cross / South) | **PC DirectInput** | Yes (Any mode or Disabled) | **Solid Blue** | Standard 18-button, 6-axis generic USB gamepad. | +| **`START + X`** (Square / West) | **PlayStation 3** | Yes (Any mode or Disabled) | **Solid Red** | Sony PS3 gamepad emulation (VID `0x054C`, PID `0x0268`). | +| **`START + Y`** (Triangle / North) | **Xbox 360** | Yes (Any mode or Disabled) | **Solid Emerald Green** | Authentic wired Xbox 360 controller emulation (VID `0x045E`, PID `0x028E`) with full **XSM3** cryptographic challenge/response for retail consoles. | +| *Configurable / BOOT Button* | **Original Xbox** | Yes (Assign to any combo) | **Solid Amber / Orange** | Native Xbox Input Device (XID) Controller S emulation (VID `0x045E`, PID `0x0289`). Connects to original Xbox consoles (via USB breakout) or Xemu. | +| *Configurable / BOOT Button* | **PlayStation 4** | Yes (Assign to any combo) | **Solid Royal Blue / Indigo** | Native Sony DualShock 4 emulation (VID `0x054C`, PID `0x05C4`). 64-byte reports, touchpad click, bi-directional rumble, and in-game Lightbar RGB color sync to the onboard WS2812 LED! | +| *Configurable / BOOT Button* | **Couch Mouse & Keys** | Yes (Assign to any combo) | **Solid Teal** | Left stick moves the mouse cursor, triggers act as left/right click, face buttons act as media keys (Volume, Play/Pause, Enter, Esc). | + +> **Web Customization & Persistence:** Each combo (`START + A/B/X/Y`) can be freely assigned to any console mode in the Web Portal. All mappings, active mode, and LED brightness are persistently stored in non-volatile flash (NVS). + +--- + +## Web Configuration Portal (AP + Home Wi-Fi & mDNS) + +MimiCon boots directly into **Zero-Latency Gaming Mode** with Wi-Fi disabled by default for maximum radio isolation. You can activate the configuration web server whenever needed: + +- **Controller Shortcut:** Hold **`SELECT + START + D-PAD UP`** (or `SELECT + START + GUIDE`) for **1.5 seconds**. +- **Hardware Button:** Hold the onboard **`BOOT`** button (GPIO0) on the ESP32 for **2 seconds**. + +### Accessing the Portal +- **Via Home Wi-Fi (Recommended):** Navigate to **`http://mimicon.local/`** (or `http://esp32-hid.local/`). +- **Via SoftAP Hotspot:** Connect to Wi-Fi **`MimiCon-Setup`** (open network, no password) and go to **`http://192.168.4.1/`**. + +### Portal Features +- **Live Controller Visualizer:** High-speed WebSocket streaming (`/ws/state`) renders analog stick positions, trigger bars, D-pad, and face buttons in real time. Clicking **L3** or **R3** illuminates the thumbsticks with a vibrant neon cyan glow. +- **Interactive SoftAP Toggle:** Click the **"CONFIG AP ACTIVE"** badge at any time to turn off the open `MimiCon-Setup` hotspot (switching to pure Station mode), freeing radio airtime for Bluetooth gaming while keeping the portal accessible over home Wi-Fi. +- **Fullscreen Virtual Gamepad:** Tap the Phone Remote button to launch a fullscreen touch controller with dual spring-loaded thumbsticks, L3/R3 buttons, and haptic feedback. +- **Stick Deadzones & Remapping:** Adjust radial inner deadzones (0% to 40%), trigger cutoffs, swap A/B or X/Y buttons, swap bumpers with triggers, and invert stick Y-axes. +- **Bluetooth Multi-Bond Memory:** Automatically stores pairings for up to 8 gamepads. The portal lists all remembered controllers with individual **Forget** buttons and a 1-click **Test Rumble đŸ“ŗ** tool. +- **Over-The-Air (OTA) Updates:** Upload compiled firmware binaries wirelessly from the browser or via the automated Python script with automated dual-slot validation. + +--- + +## Hardware Pinout Reference (ESP32-S3-Zero) + +| Pin | Function | Description | +| :--- | :--- | :--- | +| `GPIO19` | Native USB D- | Connected to USB-C port (Console output) | +| `GPIO20` | Native USB D+ | Connected to USB-C port (Console output) | +| `GPIO21` | WS2812 RGB LED | Onboard status indicator (profiles, pairing, lightbar sync) | +| `GPIO0` | BOOT Button | Short press: cycle console profiles. Hold 2s: toggle Wi-Fi Portal | +| `GPIO43` | UART0 TX | Debug serial logs (115200 baud) | +| `GPIO44` | UART0 RX | Debug serial input | + +--- + +## Building and Flashing + +### 1. Sourcing ESP-IDF Environment +In PowerShell: +```powershell +. 'C:\Espressif\tools\Microsoft.v6.1.PowerShell_profile.ps1' +``` + +### 2. Compiling Firmware +```powershell +idf.py build +``` +This generates the binary at `build/mimicon.bin`. + +### 3. Initial Flash (USB-C) +Connect the ESP32-S3-Zero to your computer and run: +```powershell +idf.py flash +``` +*(If needed: hold **BOOT**, press and release **RESET**, then release **BOOT**).* + +### 4. Wireless OTA Updates +Once initially flashed, all subsequent updates can be flashed wirelessly without touching the board: + +**Option A — Automated Python Tool (Recommended):** +```powershell +python ota_flash.py +``` +*(Optionally specify target host: `python ota_flash.py build/mimicon.bin http://mimicon.local`)* + +**Option B — Web Browser Portal:** +Navigate to `http://mimicon.local/`, choose `build/mimicon.bin` in the Firmware card, and click **⚡ Flash Firmware**. + +### 5. Versioning & Releases +MimiCon follows [Semantic Versioning (SemVer)](https://semver.org/): +- **`version.txt`**: Canonical plain-text version string (e.g. `1.0.0`), automatically ingested by CMake to embed into the ESP-IDF binary descriptor (`esp_app_desc_t`). +- **`main/version.h`**: Firmware C macros (`MIMICON_VERSION_MAJOR`, `MIMICON_VERSION_MINOR`, `MIMICON_VERSION_PATCH`, `MIMICON_VERSION_STRING`, `MIMICON_BUILD_NAME`). +- **Runtime Telemetry**: The version is reported via `/api/status`, displayed live in the web portal header and OTA card, and output on boot. +- **Git Tags**: Official firmware releases can be tagged via: + ```powershell + git tag -a v1.0.0 -m "Release v1.0.0" + ``` + +--- + +## License +Licensed under the **GNU General Public License v3.0 (GPLv3) with Commercial Restrictions**: +- **Strong Copyleft:** All forks, modifications, and derivative works must remain 100% free and open-source under these identical terms with complete source code made available. +- **Non-Commercial Exclusivity:** Commercial use, selling, or distributing this software, firmware binaries, or pre-flashed devices for profit is strictly prohibited. Exclusive commercial rights are reserved by the author (`dark98`). diff --git a/main/CMakeLists.txt b/main/CMakeLists.txt new file mode 100644 index 0000000..9781b6d --- /dev/null +++ b/main/CMakeLists.txt @@ -0,0 +1,47 @@ +idf_component_register( + SRCS + "main.c" + "status_led.c" + "profile_manager.c" + "input_calibration.c" + "ble_hid_host.c" + "dns_server.c" + "config_server.c" + "parsers/parser_xbox_ble.c" + "parsers/parser_stadia.c" + "parsers/parser_8bitdo.c" + "parsers/parser_generic_hogp.c" + "console_output/usb_gamepad.c" + "console_output/xinput_device.c" + "libxsm3/xsm3.c" + "libxsm3/usbdsec.c" + "libxsm3/excrypt_des.c" + "libxsm3/excrypt_parve.c" + "libxsm3/excrypt_sha.c" + INCLUDE_DIRS + "." + "parsers" + "console_output" + "libxsm3" + REQUIRES + log + esp_system + esp_timer + freertos + spi_flash + esp_psram + heap + driver + nvs_flash + bt + esp_wifi + esp_netif + esp_http_server + lwip + esp_event + app_update + espressif__esp_tinyusb + espressif__led_strip + ) + +target_compile_options(${COMPONENT_LIB} PRIVATE -Wall -Wextra) diff --git a/main/ble_hid_host.c b/main/ble_hid_host.c new file mode 100644 index 0000000..fdfdd12 --- /dev/null +++ b/main/ble_hid_host.c @@ -0,0 +1,936 @@ +#include "ble_hid_host.h" +#include "controller_parser.h" +#include "parsers/parser_xbox_ble.h" +#include "parsers/parser_stadia.h" +#include "parsers/parser_8bitdo.h" +#include "parsers/parser_generic_hogp.h" +#include "status_led.h" +#include "profile_manager.h" + +#include "nimble/nimble_port.h" +#include "nimble/nimble_port_freertos.h" +#include "host/ble_hs.h" +#include "host/ble_store.h" +#include "host/util/util.h" +#include "services/gap/ble_svc_gap.h" +#include "esp_log.h" +#include "nvs_flash.h" +#include "nvs.h" +#include +#include + +extern void ble_store_config_init(void); + +static const char *TAG = "BLE_HID_HOST"; + +static ble_report_cb_t s_report_cb = NULL; +static bool s_is_connected = false; +static uint16_t s_conn_handle = BLE_HS_CONN_HANDLE_NONE; +static ble_addr_t s_connected_addr; +static bool s_has_connected_addr = false; +static char s_device_name[64] = "Unknown Gamepad"; +static controller_type_t s_active_controller_type = CONTROLLER_TYPE_GENERIC_HOGP; + +/* Output Report (Rumble) state */ +#define MAX_OUTPUT_CHRS 4 +static uint16_t s_output_handles[MAX_OUTPUT_CHRS]; +static uint8_t s_output_props[MAX_OUTPUT_CHRS]; +static int s_output_handle_count = 0; +static uint16_t s_output_report_handle = 0; +static uint8_t s_output_report_prop = 0; +static uint8_t s_last_strong = 0; +static uint8_t s_last_weak = 0; +static uint32_t s_last_rumble_send_ticks = 0; + +/* Helper functions for peer device persistence */ +static void mac_to_str(const uint8_t *val, char *out, size_t out_len) +{ + snprintf(out, out_len, "%02x:%02x:%02x:%02x:%02x:%02x", + val[5], val[4], val[3], val[2], val[1], val[0]); +} + +static void mac_to_key(const uint8_t *val, char *out, size_t out_len) +{ + snprintf(out, out_len, "%02x%02x%02x%02x%02x%02x", + val[5], val[4], val[3], val[2], val[1], val[0]); +} + +static bool str_to_mac(const char *str, uint8_t *val) +{ + unsigned int m[6]; + if (sscanf(str, "%02x:%02x:%02x:%02x:%02x:%02x", + &m[5], &m[4], &m[3], &m[2], &m[1], &m[0]) == 6) { + for (int i = 0; i < 6; i++) val[i] = (uint8_t)m[i]; + return true; + } + return false; +} + +typedef struct __attribute__((packed)) { + char name[32]; + uint8_t type; +} peer_nvs_meta_t; + +static void save_peer_meta(const uint8_t *mac_val, const char *name, uint8_t type) +{ + nvs_handle_t h; + if (nvs_open("ble_peers", NVS_READWRITE, &h) == ESP_OK) { + char key[16]; + mac_to_key(mac_val, key, sizeof(key)); + peer_nvs_meta_t meta = {0}; + strncpy(meta.name, name, sizeof(meta.name) - 1); + meta.type = type; + nvs_set_blob(h, key, &meta, sizeof(meta)); + nvs_commit(h); + nvs_close(h); + } +} + +static bool load_peer_meta(const uint8_t *mac_val, char *out_name, size_t max_name, uint8_t *out_type) +{ + nvs_handle_t h; + if (nvs_open("ble_peers", NVS_READONLY, &h) == ESP_OK) { + char key[16]; + mac_to_key(mac_val, key, sizeof(key)); + peer_nvs_meta_t meta; + size_t sz = sizeof(meta); + if (nvs_get_blob(h, key, &meta, &sz) == ESP_OK) { + strncpy(out_name, meta.name, max_name - 1); + out_name[max_name - 1] = '\0'; + if (out_type) *out_type = meta.type; + nvs_close(h); + return true; + } + nvs_close(h); + } + return false; +} + +static void erase_peer_meta(const uint8_t *mac_val) +{ + nvs_handle_t h; + if (nvs_open("ble_peers", NVS_READWRITE, &h) == ESP_OK) { + char key[16]; + mac_to_key(mac_val, key, sizeof(key)); + nvs_erase_key(h, key); + nvs_commit(h); + nvs_close(h); + } +} + +/* Xbox Wireless Controller BLE Force Feedback Report (Report ID 0x03) */ +typedef struct __attribute__((packed)) { + uint8_t report_id; /* 0x03 */ + uint8_t enable; /* 0x0C (Bit 2: Strong, Bit 3: Weak) */ + uint8_t magnitude_lt; /* 0-100 */ + uint8_t magnitude_rt; /* 0-100 */ + uint8_t magnitude_strong; /* 0-100 (Left heavy motor) */ + uint8_t magnitude_weak; /* 0-100 (Right light motor) */ + uint8_t duration_10ms; /* 0xFF = ~2.55s sustain */ + uint8_t start_delay_10ms; /* 0x00 */ + uint8_t loop_count; /* 0x00 */ +} xbox_ble_ff_report_t; + +/* Standard UUIDs */ +static const ble_uuid16_t s_hid_svc_uuid = BLE_UUID16_INIT(0x1812); /* Human Interface Device */ +static const ble_uuid16_t s_hid_report_uuid = BLE_UUID16_INIT(0x2A4D); /* HID Report */ +static const ble_uuid16_t s_bas_svc_uuid = BLE_UUID16_INIT(0x180F); /* Battery Service */ +static const ble_uuid16_t s_bas_level_uuid = BLE_UUID16_INIT(0x2A19); /* Battery Level */ +static const ble_uuid16_t s_cccd_uuid = BLE_UUID16_INIT(0x2902); /* Client Characteristic Configuration */ + +static uint16_t s_bas_val_handle = 0; +static uint16_t s_bas_cccd_handle = 0; +static int8_t s_battery_level = -1; + +static int ble_gap_event(struct ble_gap_event *event, void *arg); +static void ble_scan_start(void); +static int on_disc_bas_svc(uint16_t conn_handle, const struct ble_gatt_error *error, + const struct ble_gatt_svc *svc, void *arg); + +bool ble_hid_host_is_connected(void) +{ + return s_is_connected; +} + +const char *ble_hid_host_get_device_name(void) +{ + return s_device_name; +} + +static void parse_and_dispatch_report(const uint8_t *data, size_t len) +{ + controller_state_t state; + bool parsed = false; + + if (s_active_controller_type == CONTROLLER_TYPE_XBOX_BLE) { + parsed = parser_xbox_ble_parse(data, len, &state); + } else if (s_active_controller_type == CONTROLLER_TYPE_STADIA) { + parsed = parser_stadia_parse(data, len, &state); + } else if (s_active_controller_type == CONTROLLER_TYPE_8BITDO) { + parsed = parser_8bitdo_parse(data, len, &state); + } else { + /* Auto-probe: 8BitDo -> Stadia -> Xbox -> Generic */ + parsed = parser_8bitdo_parse(data, len, &state); + if (!parsed) { + parsed = parser_stadia_parse(data, len, &state); + } + if (!parsed) { + parsed = parser_xbox_ble_parse(data, len, &state); + } + if (!parsed) { + parsed = parser_generic_hogp_parse(data, len, &state); + } + } + + if (parsed) { + /* Monitor button combos for profile switching */ + profile_manager_process_state(&state); + + /* Dispatch to USB output */ + if (s_report_cb) { + s_report_cb(&state); + } + } +} + +#define MAX_REPORT_CHRS 8 +typedef struct { + uint16_t val_handle; + uint16_t end_handle; + uint16_t cccd_handle; +} report_chr_t; + +static report_chr_t s_report_chrs[MAX_REPORT_CHRS]; +static int s_report_chr_count = 0; +static int s_sub_idx = 0; + +static void subscribe_next_report_cccd(uint16_t conn_handle); + +static int on_cccd_write_done(uint16_t conn_handle, const struct ble_gatt_error *error, + struct ble_gatt_attr *attr, void *arg) +{ + if (error->status == 0) { + ESP_LOGI(TAG, "Subscribed successfully to report %d/%d (handle=%d)", + s_sub_idx + 1, s_report_chr_count, s_report_chrs[s_sub_idx].val_handle); + } else { + ESP_LOGW(TAG, "Failed to write CCCD at idx %d, status=%d", s_sub_idx, error->status); + } + s_sub_idx++; + subscribe_next_report_cccd(conn_handle); + return 0; +} + +/* GATT Characteristic Descriptor Discovery (Enabling CCCD Notifications) */ +static int on_disc_dscs(uint16_t conn_handle, const struct ble_gatt_error *error, + uint16_t chr_val_handle, const struct ble_gatt_dsc *dsc, void *arg) +{ + if (error->status == 0 && dsc != NULL) { + if (ble_uuid_cmp(&dsc->uuid.u, &s_cccd_uuid.u) == 0) { + ESP_LOGI(TAG, "Found CCCD at handle %d for chr val_handle %d", dsc->handle, chr_val_handle); + if (s_sub_idx < s_report_chr_count) { + s_report_chrs[s_sub_idx].cccd_handle = dsc->handle; + } + } + return 0; + } + + /* Descriptor discovery finished for this characteristic */ + if (s_sub_idx < s_report_chr_count && s_report_chrs[s_sub_idx].cccd_handle != 0) { + uint16_t cccd = s_report_chrs[s_sub_idx].cccd_handle; + ESP_LOGI(TAG, "Writing CCCD at handle %d to enable notifications...", cccd); + uint8_t value[2] = {0x01, 0x00}; /* Enable Notifications */ + ble_gattc_write_flat(conn_handle, cccd, value, sizeof(value), on_cccd_write_done, NULL); + } else { + /* No CCCD found for this characteristic, advance to next */ + s_sub_idx++; + subscribe_next_report_cccd(conn_handle); + } + return 0; +} + +static void subscribe_next_report_cccd(uint16_t conn_handle) +{ + if (s_sub_idx >= s_report_chr_count) { + ESP_LOGI(TAG, "All %d HID Report characteristics subscribed! Discovering Battery Service...", s_report_chr_count); + ble_gattc_disc_svc_by_uuid(conn_handle, &s_bas_svc_uuid.u, on_disc_bas_svc, NULL); + return; + } + + uint16_t start = s_report_chrs[s_sub_idx].val_handle; + uint16_t end = s_report_chrs[s_sub_idx].end_handle; + if (end < start) end = start + 4; + + ESP_LOGI(TAG, "Discovering descriptors for chr %d/%d (val_handle=%d, end_handle=%d)...", + s_sub_idx + 1, s_report_chr_count, start, end); + ble_gattc_disc_all_dscs(conn_handle, start, end, on_disc_dscs, NULL); +} + +/* GATT Characteristic Discovery */ +static int on_disc_chars(uint16_t conn_handle, const struct ble_gatt_error *error, + const struct ble_gatt_chr *chr, void *arg) +{ + if (error->status == 0 && chr != NULL) { + if (ble_uuid_cmp(&chr->uuid.u, &s_hid_report_uuid.u) == 0) { + ESP_LOGI(TAG, "Discovered HID Report characteristic (val_handle=%d, def_handle=%d, props=0x%02x)", + chr->val_handle, chr->def_handle, chr->properties); + + /* If characteristic has WRITE or WRITE_NO_RSP, save as Rumble Output Report handle */ + if (chr->properties & (BLE_GATT_CHR_PROP_WRITE | BLE_GATT_CHR_PROP_WRITE_NO_RSP)) { + if (s_output_handle_count < MAX_OUTPUT_CHRS) { + s_output_handles[s_output_handle_count] = chr->val_handle; + s_output_props[s_output_handle_count] = chr->properties; + s_output_handle_count++; + } + s_output_report_handle = chr->val_handle; + s_output_report_prop = chr->properties; + ESP_LOGI(TAG, "==> Identified Rumble Output Report characteristic #%d (val_handle=%d, props=0x%02x)", + s_output_handle_count, chr->val_handle, chr->properties); + } + + /* If characteristic has NOTIFY, save for CCCD subscription */ + if (chr->properties & BLE_GATT_CHR_PROP_NOTIFY) { + if (s_report_chr_count < MAX_REPORT_CHRS) { + s_report_chrs[s_report_chr_count].val_handle = chr->val_handle; + s_report_chrs[s_report_chr_count].end_handle = chr->val_handle + 4; + s_report_chrs[s_report_chr_count].cccd_handle = 0; + s_report_chr_count++; + } + } + } + return 0; + } + + /* Characteristic discovery complete for this service */ + ESP_LOGI(TAG, "Characteristic discovery finished. Subscribing to %d report characteristics (found %d output handles)...", + s_report_chr_count, s_output_handle_count); + s_sub_idx = 0; + subscribe_next_report_cccd(conn_handle); + return 0; +} + +/* GATT Service Discovery */ +static int on_disc_svc(uint16_t conn_handle, const struct ble_gatt_error *error, + const struct ble_gatt_svc *svc, void *arg) +{ + if (error->status == 0 && svc != NULL) { + ESP_LOGI(TAG, "Discovered HID Service: start=%d, end=%d", svc->start_handle, svc->end_handle); + s_report_chr_count = 0; + s_sub_idx = 0; + s_output_handle_count = 0; + s_output_report_handle = 0; + s_output_report_prop = 0; + ble_gattc_disc_all_chrs(conn_handle, svc->start_handle, svc->end_handle, on_disc_chars, NULL); + } + return 0; +} + +/* -------------------------------------------------------------------------- */ +/* Battery Service (0x180F) & Battery Level (0x2A19) Telemetry */ +/* -------------------------------------------------------------------------- */ + +static int on_bas_read(uint16_t conn_handle, const struct ble_gatt_error *error, + struct ble_gatt_attr *attr, void *arg) +{ + if (error->status == 0 && attr != NULL && attr->om != NULL) { + uint8_t level = 0; + os_mbuf_copydata(attr->om, 0, 1, &level); + if (level <= 100) { + s_battery_level = (int8_t)level; + ESP_LOGI(TAG, "Controller Battery Level: %d%%", s_battery_level); + } + } + return 0; +} + +static int on_bas_cccd_write_done(uint16_t conn_handle, const struct ble_gatt_error *error, + struct ble_gatt_attr *attr, void *arg) +{ + if (error->status == 0) { + ESP_LOGI(TAG, "Subscribed to Battery Level notifications (CCCD handle=%d)", s_bas_cccd_handle); + } + if (s_bas_val_handle != 0) { + ble_gattc_read(conn_handle, s_bas_val_handle, on_bas_read, NULL); + } + return 0; +} + +static int on_disc_bas_dscs(uint16_t conn_handle, const struct ble_gatt_error *error, + uint16_t chr_val_handle, const struct ble_gatt_dsc *dsc, void *arg) +{ + if (error->status == 0 && dsc != NULL) { + if (ble_uuid_cmp(&dsc->uuid.u, &s_cccd_uuid.u) == 0) { + s_bas_cccd_handle = dsc->handle; + ESP_LOGI(TAG, "Found Battery CCCD at handle %d", dsc->handle); + } + return 0; + } + + if (s_bas_cccd_handle != 0) { + uint8_t value[2] = {0x01, 0x00}; + ble_gattc_write_flat(conn_handle, s_bas_cccd_handle, value, sizeof(value), on_bas_cccd_write_done, NULL); + } else if (s_bas_val_handle != 0) { + ble_gattc_read(conn_handle, s_bas_val_handle, on_bas_read, NULL); + } + return 0; +} + +static int on_disc_bas_chars(uint16_t conn_handle, const struct ble_gatt_error *error, + const struct ble_gatt_chr *chr, void *arg) +{ + if (error->status == 0 && chr != NULL) { + if (ble_uuid_cmp(&chr->uuid.u, &s_bas_level_uuid.u) == 0) { + s_bas_val_handle = chr->val_handle; + ESP_LOGI(TAG, "Discovered Battery Level characteristic (val_handle=%d, props=0x%02x)", + chr->val_handle, chr->properties); + if (chr->properties & BLE_GATT_CHR_PROP_NOTIFY) { + ble_gattc_disc_all_dscs(conn_handle, chr->val_handle, chr->val_handle + 2, on_disc_bas_dscs, NULL); + } else { + ble_gattc_read(conn_handle, s_bas_val_handle, on_bas_read, NULL); + } + } + return 0; + } + return 0; +} + +static int on_disc_bas_svc(uint16_t conn_handle, const struct ble_gatt_error *error, + const struct ble_gatt_svc *svc, void *arg) +{ + if (error->status == 0 && svc != NULL) { + ESP_LOGI(TAG, "Discovered Battery Service: start=%d, end=%d", svc->start_handle, svc->end_handle); + s_bas_val_handle = 0; + s_bas_cccd_handle = 0; + ble_gattc_disc_all_chrs(conn_handle, svc->start_handle, svc->end_handle, on_disc_bas_chars, NULL); + } + return 0; +} + +static void ble_scan_start(void) +{ + struct ble_gap_disc_params disc_params = { + .filter_duplicates = 1, + .passive = 0, + .itvl = BLE_GAP_SCAN_FAST_INTERVAL_MIN, + .window = BLE_GAP_SCAN_FAST_WINDOW, + .filter_policy = 0, + .limited = 0, + }; + + status_led_set_mode(LED_STATE_SCANNING); + ESP_LOGI(TAG, "Scanning for BLE gamepads (Xbox, 8BitDo, HID controllers)..."); + ble_gap_disc(BLE_OWN_ADDR_PUBLIC, BLE_HS_FOREVER, &disc_params, ble_gap_event, NULL); +} + +static int ble_gap_event(struct ble_gap_event *event, void *arg) +{ + switch (event->type) { + case BLE_GAP_EVENT_DISC: { + struct ble_hs_adv_fields fields; + if (ble_hs_adv_parse_fields(&fields, event->disc.data, event->disc.length_data) == 0) { + char name[32] = {0}; + if (fields.name != NULL && fields.name_len > 0) { + int len = (fields.name_len < sizeof(name) - 1) ? fields.name_len : sizeof(name) - 1; + memcpy(name, fields.name, len); + name[len] = '\0'; + } + + /* 1. Fast reconnect check: Is this advertising peer already bonded in NVS? */ + ble_addr_t bonded[BLE_MAX_PEERS]; + int num_bonded = 0; + ble_store_util_bonded_peers(bonded, &num_bonded, BLE_MAX_PEERS); + for (int b = 0; b < num_bonded; b++) { + if (memcmp(bonded[b].val, event->disc.addr.val, 6) == 0) { + char cached_name[32] = {0}; + uint8_t cached_type = 0; + if (load_peer_meta(event->disc.addr.val, cached_name, sizeof(cached_name), &cached_type)) { + strncpy(s_device_name, cached_name, sizeof(s_device_name) - 1); + s_active_controller_type = (controller_type_t)cached_type; + } else if (name[0] != '\0') { + strncpy(s_device_name, name, sizeof(s_device_name) - 1); + } else { + strncpy(s_device_name, "Paired Controller", sizeof(s_device_name) - 1); + } + ESP_LOGI(TAG, "Recognized bonded controller '%s'. Reconnecting instantly...", s_device_name); + ble_gap_disc_cancel(); + uint8_t own_addr_type; + ble_hs_id_infer_auto(0, &own_addr_type); + ble_gap_connect(own_addr_type, &event->disc.addr, 30000, NULL, ble_gap_event, NULL); + return 0; + } + } + + bool match = false; + /* Check if name contains controller keywords */ + if (strstr(name, "Xbox") || strstr(name, "Controller") || + strstr(name, "Gamepad") || strstr(name, "8BitDo") || + strstr(name, "Stadia")) { + match = true; + } + + /* Check advertised 16-bit UUIDs for HID Service (0x1812) */ + if (!match && fields.uuids16 != NULL) { + for (int i = 0; i < fields.num_uuids16; i++) { + if (ble_uuid_u16(&fields.uuids16[i].u) == 0x1812) { + match = true; + break; + } + } + } + + if (match) { + ESP_LOGI(TAG, "Found target controller: '%s' (RSSI: %d). Connecting...", name, event->disc.rssi); + ble_gap_disc_cancel(); + + strncpy(s_device_name, (name[0] != '\0') ? name : "BLE Gamepad", sizeof(s_device_name) - 1); + if (strstr(s_device_name, "Xbox")) { + s_active_controller_type = CONTROLLER_TYPE_XBOX_BLE; + } else if (strstr(s_device_name, "Stadia")) { + s_active_controller_type = CONTROLLER_TYPE_STADIA; + } else if (strstr(s_device_name, "8BitDo") || strstr(s_device_name, "8bitdo") || + strstr(s_device_name, "SN30") || strstr(s_device_name, "Pro 2") || + strstr(s_device_name, "Lite") || strstr(s_device_name, "M30") || + strstr(s_device_name, "Zero") || strstr(s_device_name, "Micro")) { + s_active_controller_type = CONTROLLER_TYPE_8BITDO; + } else { + s_active_controller_type = CONTROLLER_TYPE_GENERIC_HOGP; + } + + uint8_t own_addr_type; + ble_hs_id_infer_auto(0, &own_addr_type); + ble_gap_connect(own_addr_type, &event->disc.addr, 30000, NULL, ble_gap_event, NULL); + } + } + return 0; + } + + case BLE_GAP_EVENT_CONNECT: + if (event->connect.status == 0) { + s_is_connected = true; + s_conn_handle = event->connect.conn_handle; + ESP_LOGI(TAG, "Connected to '%s'! Initiating service discovery & pairing...", s_device_name); + + struct ble_gap_conn_desc desc; + if (ble_gap_conn_find(event->connect.conn_handle, &desc) == 0) { + s_connected_addr = desc.peer_id_addr; + s_has_connected_addr = true; + save_peer_meta(s_connected_addr.val, s_device_name, (uint8_t)s_active_controller_type); + } + + /* Initiate security / encryption (required for Xbox controllers) */ + ble_gap_security_initiate(s_conn_handle); + + /* Discover HID services (Battery Service discovery will follow sequentially) */ + ble_gattc_disc_svc_by_uuid(s_conn_handle, &s_hid_svc_uuid.u, on_disc_svc, NULL); + + /* Update LED to current profile mode */ + profile_manager_refresh_led(); + } else { + ESP_LOGW(TAG, "Connection failed, status=%d. Resuming scan...", event->connect.status); + s_is_connected = false; + s_has_connected_addr = false; + ble_scan_start(); + } + return 0; + + case BLE_GAP_EVENT_DISCONNECT: + ESP_LOGI(TAG, "Controller disconnected (reason=%d). Resuming scan...", event->disconnect.reason); + s_is_connected = false; + s_has_connected_addr = false; + s_conn_handle = BLE_HS_CONN_HANDLE_NONE; + s_output_handle_count = 0; + s_output_report_handle = 0; + s_output_report_prop = 0; + s_last_strong = 0; + s_last_weak = 0; + s_battery_level = -1; + s_bas_val_handle = 0; + s_bas_cccd_handle = 0; + controller_state_t zero_state = {0}; + profile_manager_process_state(&zero_state); + ble_scan_start(); + return 0; + + case BLE_GAP_EVENT_NOTIFY_RX: { + struct os_mbuf *om = event->notify_rx.om; + uint16_t len = OS_MBUF_PKTLEN(om); + uint8_t buf[64]; + if (len <= sizeof(buf)) { + os_mbuf_copydata(om, 0, len, buf); + if (event->notify_rx.attr_handle == s_bas_val_handle && len >= 1) { + if (buf[0] <= 100) { + s_battery_level = (int8_t)buf[0]; + ESP_LOGI(TAG, "Battery level notification: %d%%", s_battery_level); + } + } else { + ESP_LOGD(TAG, "NOTIFY handle=%d len=%d", event->notify_rx.attr_handle, len); + parse_and_dispatch_report(buf, len); + } + } + return 0; + } + + case BLE_GAP_EVENT_ENC_CHANGE: + ESP_LOGI(TAG, "Encryption changed, status=%d", event->enc_change.status); + return 0; + + default: + return 0; + } +} + +static void ble_on_sync(void) +{ + ESP_LOGI(TAG, "NimBLE Host synchronized."); + ble_scan_start(); +} + +static void ble_on_reset(int reason) +{ + ESP_LOGE(TAG, "NimBLE Host reset, reason=%d", reason); +} + +static void ble_host_task(void *param) +{ + ESP_LOGI(TAG, "BLE Host Task running."); + nimble_port_run(); + nimble_port_freertos_deinit(); +} + +esp_err_t ble_hid_host_init(ble_report_cb_t callback) +{ + s_report_cb = callback; + + esp_err_t err = nimble_port_init(); + if (err != ESP_OK) { + ESP_LOGE(TAG, "Failed to init NimBLE port: %s", esp_err_to_name(err)); + return err; + } + + /* Configure Security Manager for pairing with BLE controllers */ + ble_hs_cfg.sm_io_cap = BLE_SM_IO_CAP_NO_IO; + ble_hs_cfg.sm_bonding = 1; + ble_hs_cfg.sm_mitm = 0; + ble_hs_cfg.sm_sc = 1; + ble_hs_cfg.sm_our_key_dist = BLE_SM_PAIR_KEY_DIST_ENC | BLE_SM_PAIR_KEY_DIST_ID; + ble_hs_cfg.sm_their_key_dist = BLE_SM_PAIR_KEY_DIST_ENC | BLE_SM_PAIR_KEY_DIST_ID; + + ble_hs_cfg.sync_cb = ble_on_sync; + ble_hs_cfg.reset_cb = ble_on_reset; + + /* Initialize persistent bonding storage */ + ble_store_config_init(); + + nimble_port_freertos_init(ble_host_task); + + ESP_LOGI(TAG, "BLE HID Central Host initialized."); + return ESP_OK; +} + +void ble_hid_host_disconnect(void) +{ + if (s_is_connected && s_conn_handle != BLE_HS_CONN_HANDLE_NONE) { + ESP_LOGI(TAG, "Disconnecting BLE controller (conn_handle=%d)...", s_conn_handle); + ble_gap_terminate(s_conn_handle, BLE_ERR_REM_USER_CONN_TERM); + } +} + +void ble_hid_host_clear_bonds(void) +{ + ESP_LOGI(TAG, "Clearing all BLE bonding store entries..."); + if (s_is_connected && s_conn_handle != BLE_HS_CONN_HANDLE_NONE) { + ble_gap_terminate(s_conn_handle, BLE_ERR_REM_USER_CONN_TERM); + } + ble_store_clear(); + nvs_handle_t h; + if (nvs_open("ble_peers", NVS_READWRITE, &h) == ESP_OK) { + nvs_erase_all(h); + nvs_commit(h); + nvs_close(h); + } + ble_scan_start(); +} + +int ble_hid_host_get_peers(ble_peer_info_t *out_peers, int max_peers) +{ + if (!out_peers || max_peers <= 0) return 0; + + ble_addr_t bonded[BLE_MAX_PEERS]; + int num_bonded = 0; + ble_store_util_bonded_peers(bonded, &num_bonded, max_peers); + + int count = 0; + bool found_connected = false; + + for (int i = 0; i < num_bonded && count < max_peers; i++) { + mac_to_str(bonded[i].val, out_peers[count].mac_str, sizeof(out_peers[count].mac_str)); + memcpy(out_peers[count].addr_val, bonded[i].val, 6); + out_peers[count].addr_type = bonded[i].type; + + bool is_curr = (s_is_connected && s_has_connected_addr && memcmp(s_connected_addr.val, bonded[i].val, 6) == 0); + out_peers[count].is_connected = is_curr; + + if (is_curr) { + found_connected = true; + strncpy(out_peers[count].name, s_device_name, sizeof(out_peers[count].name) - 1); + out_peers[count].controller_type = (uint8_t)s_active_controller_type; + out_peers[count].battery = s_battery_level; + } else { + char cname[32] = {0}; + uint8_t ctype = 0; + if (load_peer_meta(bonded[i].val, cname, sizeof(cname), &ctype)) { + strncpy(out_peers[count].name, cname, sizeof(out_peers[count].name) - 1); + out_peers[count].controller_type = ctype; + } else { + strncpy(out_peers[count].name, "Paired Controller", sizeof(out_peers[count].name) - 1); + out_peers[count].controller_type = 0; + } + out_peers[count].battery = -1; + } + count++; + } + + if (s_is_connected && s_has_connected_addr && !found_connected && count < max_peers) { + mac_to_str(s_connected_addr.val, out_peers[count].mac_str, sizeof(out_peers[count].mac_str)); + memcpy(out_peers[count].addr_val, s_connected_addr.val, 6); + out_peers[count].addr_type = s_connected_addr.type; + out_peers[count].is_connected = true; + strncpy(out_peers[count].name, s_device_name, sizeof(out_peers[count].name) - 1); + out_peers[count].controller_type = (uint8_t)s_active_controller_type; + out_peers[count].battery = s_battery_level; + count++; + } + + return count; +} + +esp_err_t ble_hid_host_unpair_device(const char *mac_str) +{ + if (!mac_str) return ESP_ERR_INVALID_ARG; + uint8_t mac_val[6]; + if (!str_to_mac(mac_str, mac_val)) return ESP_ERR_INVALID_ARG; + + ESP_LOGI(TAG, "Unpairing controller: %s", mac_str); + + if (s_is_connected && s_has_connected_addr && memcmp(s_connected_addr.val, mac_val, 6) == 0) { + ESP_LOGI(TAG, "Disconnecting unpairing controller..."); + ble_gap_terminate(s_conn_handle, BLE_ERR_REM_USER_CONN_TERM); + } + + ble_addr_t addr; + memcpy(addr.val, mac_val, 6); + addr.type = BLE_ADDR_PUBLIC; + ble_gap_unpair(&addr); + addr.type = BLE_ADDR_RANDOM; + ble_gap_unpair(&addr); + + erase_peer_meta(mac_val); + + return ESP_OK; +} + +void ble_hid_host_send_rumble(uint8_t strong, uint8_t weak) +{ + if (!s_is_connected || s_conn_handle == BLE_HS_CONN_HANDLE_NONE || s_output_report_handle == 0) { + return; + } + + uint32_t now = (uint32_t)(xTaskGetTickCount() * portTICK_PERIOD_MS); + if (strong == s_last_strong && weak == s_last_weak) { + return; + } + + /* Rate limit to prevent saturating the BLE connection interval */ + if ((strong != 0 || weak != 0) && (now - s_last_rumble_send_ticks < 20)) { + return; + } + + s_last_strong = strong; + s_last_weak = weak; + s_last_rumble_send_ticks = now; + + /* Feature 5: Dynamic Haptic LED Lightshow (Visual Rumble) */ + if (strong > 0 || weak > 0) { + uint8_t r = (uint8_t)(((uint32_t)strong * 255) / 255); + uint8_t g = (uint8_t)(((uint32_t)weak * 80) / 255); + uint8_t b = (uint8_t)(((uint32_t)weak * 220) / 255); + status_led_flash_color(r, g, b, 120); + } else { + profile_manager_refresh_led(); + } + + if (s_active_controller_type == CONTROLLER_TYPE_XBOX_BLE) { + /* Authentic Xbox Wireless Controller Force Feedback Output Report */ + xbox_ble_ff_report_t pkt = {0}; + pkt.report_id = 0x03; + if (strong == 0 && weak == 0) { + pkt.enable = 0x0F; /* All 4 motors */ + pkt.magnitude_lt = 0; + pkt.magnitude_rt = 0; + pkt.magnitude_strong = 0; + pkt.magnitude_weak = 0; + pkt.duration_10ms = 0x00; /* Instant stop */ + pkt.start_delay_10ms = 0x00; + pkt.loop_count = 0x00; + } else { + pkt.enable = 0x0C; /* Enable Strong (left, bit 2) and Weak (right, bit 3) motors */ + pkt.magnitude_lt = 0; + pkt.magnitude_rt = 0; + pkt.magnitude_strong = (uint8_t)(((uint32_t)strong * 100) / 255); + pkt.magnitude_weak = (uint8_t)(((uint32_t)weak * 100) / 255); + pkt.duration_10ms = 0x14; /* 200ms sustain safeguard */ + pkt.start_delay_10ms = 0x00; + pkt.loop_count = 0x00; + } + + if (s_output_report_prop & BLE_GATT_CHR_PROP_WRITE_NO_RSP) { + ble_gattc_write_no_rsp_flat(s_conn_handle, s_output_report_handle, &pkt, sizeof(pkt)); + } else { + ble_gattc_write_flat(s_conn_handle, s_output_report_handle, &pkt, sizeof(pkt), NULL, NULL); + } + } else if (s_active_controller_type == CONTROLLER_TYPE_STADIA) { + /* Google Stadia Controller Output Report: Report ID 0x05, 16-bit Strong, 16-bit Weak */ + uint16_t s16 = (uint16_t)(((uint32_t)strong * 65535) / 255); + uint16_t w16 = (uint16_t)(((uint32_t)weak * 65535) / 255); + + /* 5-byte payload with Report ID 0x05 prefix (Standard USB & SDL hidapi layout) */ + uint8_t pkt5[5] = { + 0x05, + (uint8_t)(s16 & 0xFF), + (uint8_t)((s16 >> 8) & 0xFF), + (uint8_t)(w16 & 0xFF), + (uint8_t)((w16 >> 8) & 0xFF) + }; + + /* 4-byte payload without Report ID prefix (Raw HOGP Characteristic Value layout) */ + uint8_t pkt4[4] = { + (uint8_t)(s16 & 0xFF), + (uint8_t)((s16 >> 8) & 0xFF), + (uint8_t)(w16 & 0xFF), + (uint8_t)((w16 >> 8) & 0xFF) + }; + + int handles_to_try = s_output_handle_count > 0 ? s_output_handle_count : 1; + for (int i = 0; i < handles_to_try; i++) { + uint16_t h = (s_output_handle_count > 0) ? s_output_handles[i] : s_output_report_handle; + uint8_t prop = (s_output_handle_count > 0) ? s_output_props[i] : s_output_report_prop; + if (h == 0) continue; + + if (prop & BLE_GATT_CHR_PROP_WRITE_NO_RSP) { + ble_gattc_write_no_rsp_flat(s_conn_handle, h, pkt5, sizeof(pkt5)); + ble_gattc_write_no_rsp_flat(s_conn_handle, h, pkt4, sizeof(pkt4)); + } + if (prop & BLE_GATT_CHR_PROP_WRITE) { + ble_gattc_write_flat(s_conn_handle, h, pkt5, sizeof(pkt5), NULL, NULL); + ble_gattc_write_flat(s_conn_handle, h, pkt4, sizeof(pkt4), NULL, NULL); + } + } + } else if (s_active_controller_type == CONTROLLER_TYPE_8BITDO) { + /* 8BitDo controllers: Send standard generic HOGP and 5-byte force feedback report */ + uint8_t pkt[4] = { 0x01, weak, strong, 0x00 }; + uint8_t pkt5[5] = { 0x05, strong, 0x00, weak, 0x00 }; + + int handles_to_try = s_output_handle_count > 0 ? s_output_handle_count : 1; + for (int i = 0; i < handles_to_try; i++) { + uint16_t h = (s_output_handle_count > 0) ? s_output_handles[i] : s_output_report_handle; + uint8_t prop = (s_output_handle_count > 0) ? s_output_props[i] : s_output_report_prop; + if (h == 0) continue; + + if (prop & BLE_GATT_CHR_PROP_WRITE_NO_RSP) { + ble_gattc_write_no_rsp_flat(s_conn_handle, h, pkt, sizeof(pkt)); + ble_gattc_write_no_rsp_flat(s_conn_handle, h, pkt5, sizeof(pkt5)); + } + if (prop & BLE_GATT_CHR_PROP_WRITE) { + ble_gattc_write_flat(s_conn_handle, h, pkt, sizeof(pkt), NULL, NULL); + ble_gattc_write_flat(s_conn_handle, h, pkt5, sizeof(pkt5), NULL, NULL); + } + } + } else { + /* Standard generic HOGP force feedback packet */ + uint8_t pkt[4]; + pkt[0] = 0x01; + pkt[1] = weak; + pkt[2] = strong; + pkt[3] = 0x00; + + if (s_output_report_prop & BLE_GATT_CHR_PROP_WRITE_NO_RSP) { + ble_gattc_write_no_rsp_flat(s_conn_handle, s_output_report_handle, pkt, sizeof(pkt)); + } else { + ble_gattc_write_flat(s_conn_handle, s_output_report_handle, pkt, sizeof(pkt), NULL, NULL); + } + } +} + +typedef struct { + uint8_t strong; + uint8_t weak; + uint16_t duration_ms; +} rumble_pulse_t; + +static void rumble_pulse_task(void *param) +{ + rumble_pulse_t *p = (rumble_pulse_t *)param; + uint8_t strong = p->strong; + uint8_t weak = p->weak; + uint16_t dur = p->duration_ms > 0 ? p->duration_ms : 60; + free(p); + + ble_hid_host_send_rumble(strong, weak); + vTaskDelay(pdMS_TO_TICKS(dur)); + s_last_strong = 0xFF; + s_last_weak = 0xFF; + ble_hid_host_send_rumble(0, 0); + vTaskDelay(pdMS_TO_TICKS(20)); + s_last_strong = 0xFF; + s_last_weak = 0xFF; + ble_hid_host_send_rumble(0, 0); + vTaskDelete(NULL); +} + +void ble_hid_host_pulse_rumble(uint8_t strong_magnitude, uint8_t weak_magnitude, uint16_t duration_ms) +{ + rumble_pulse_t *p = malloc(sizeof(rumble_pulse_t)); + if (p) { + p->strong = strong_magnitude; + p->weak = weak_magnitude; + /* Pin rumble dispatch task to Core 0 (alongside NimBLE radio stack) */ + xTaskCreatePinnedToCore(rumble_pulse_task, "rumble_pulse", 2048, p, 4, NULL, 0); + } +} + +void ble_hid_host_test_rumble(uint16_t duration_ms) +{ + if (duration_ms == 0) duration_ms = 100; + ble_hid_host_pulse_rumble(150, 150, duration_ms); +} + +int8_t ble_hid_host_get_battery_level(void) +{ + if (!s_is_connected) { + return -1; + } + return s_battery_level; +} + +void ble_hid_host_refresh_battery(void) +{ + static uint32_t last_read_ticks = 0; + uint32_t now = xTaskGetTickCount(); + if (!s_is_connected || s_conn_handle == BLE_HS_CONN_HANDLE_NONE) { + return; + } + + if (s_bas_val_handle == 0) { + if ((now - last_read_ticks > pdMS_TO_TICKS(5000)) || last_read_ticks == 0) { + last_read_ticks = now; + ESP_LOGI(TAG, "Discovering Battery Service on demand..."); + ble_gattc_disc_svc_by_uuid(s_conn_handle, &s_bas_svc_uuid.u, on_disc_bas_svc, NULL); + } + return; + } + + if ((now - last_read_ticks > pdMS_TO_TICKS(10000)) || last_read_ticks == 0) { + last_read_ticks = now; + ble_gattc_read(s_conn_handle, s_bas_val_handle, on_bas_read, NULL); + } +} + diff --git a/main/ble_hid_host.h b/main/ble_hid_host.h new file mode 100644 index 0000000..af1e892 --- /dev/null +++ b/main/ble_hid_host.h @@ -0,0 +1,100 @@ +#pragma once + +#include +#include +#include "esp_err.h" +#include "controller_state.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void (*ble_report_cb_t)(const controller_state_t *state); + +/** + * @brief Initialize BLE Central stack and start scanning for wireless gamepads. + */ +esp_err_t ble_hid_host_init(ble_report_cb_t callback); + +/** + * @brief Check if a BLE gamepad is currently connected. + */ +bool ble_hid_host_is_connected(void); + +/** + * @brief Get the connected device name. + */ +const char *ble_hid_host_get_device_name(void); + +/** + * @brief Disconnect currently connected BLE gamepad. + */ +void ble_hid_host_disconnect(void); + +/** + * @brief Clear all stored BLE bonds/pairings and restart scan. + */ +void ble_hid_host_clear_bonds(void); + +/** + * @brief Send force-feedback / rumble commands to the connected wireless controller. + * @param strong_magnitude Heavy / low-frequency motor intensity (0 - 255). + * @param weak_magnitude Light / high-frequency motor intensity (0 - 255). + */ +void ble_hid_host_send_rumble(uint8_t strong_magnitude, uint8_t weak_magnitude); + +/** + * @brief Trigger a short test rumble vibration on the connected controller. + * @param duration_ms Duration in milliseconds (e.g. 500ms). + */ +void ble_hid_host_test_rumble(uint16_t duration_ms); + +/** + * @brief Pulse rumble with custom strength and duration (ideal for quick haptic clicks/confirmation). + * @param strong_magnitude Heavy motor intensity (0 - 255). + * @param weak_magnitude Light motor intensity (0 - 255). + * @param duration_ms Pulse duration in milliseconds. + */ +void ble_hid_host_pulse_rumble(uint8_t strong_magnitude, uint8_t weak_magnitude, uint16_t duration_ms); + +/** + * @brief Get the battery level of the connected wireless controller. + * @return Battery percentage (0 - 100), or -1 if unknown / disconnected. + */ +int8_t ble_hid_host_get_battery_level(void); + +/** + * @brief Refresh battery level from device if connected. + */ +void ble_hid_host_refresh_battery(void); + +#define BLE_MAX_PEERS 8 + +typedef struct { + char name[32]; + char mac_str[18]; /* "aa:bb:cc:dd:ee:ff" */ + uint8_t addr_val[6]; + uint8_t addr_type; + uint8_t controller_type; /* 0: Generic, 1: Xbox, 2: Stadia */ + bool is_connected; + int8_t battery; +} ble_peer_info_t; + +/** + * @brief Get list of bonded / remembered BLE controllers. + * @param out_peers Array of ble_peer_info_t. + * @param max_peers Max elements to write into out_peers. + * @return Number of peers written. + */ +int ble_hid_host_get_peers(ble_peer_info_t *out_peers, int max_peers); + +/** + * @brief Forget / unpair a specific controller by MAC address string. + * @param mac_str "aa:bb:cc:dd:ee:ff" + * @return ESP_OK on success, ESP_ERR_NOT_FOUND if not found. + */ +esp_err_t ble_hid_host_unpair_device(const char *mac_str); + +#ifdef __cplusplus +} +#endif diff --git a/main/board_esp32_s3_zero.h b/main/board_esp32_s3_zero.h new file mode 100644 index 0000000..ba022a0 --- /dev/null +++ b/main/board_esp32_s3_zero.h @@ -0,0 +1,28 @@ +#pragma once + +#include "soc/gpio_num.h" + +/** + * @file board_esp32_s3_zero.h + * @brief Pinout and hardware definitions for Waveshare ESP32-S3-Zero + */ + +#ifdef __cplusplus +extern "C" { +#endif + +/* Onboard Hardware Pins */ +#define BOARD_RGB_LED_GPIO GPIO_NUM_21 /* On-board WS2812 addressable RGB LED */ +#define BOARD_BOOT_BUTTON_GPIO GPIO_NUM_0 /* On-board BOOT button (active LOW) */ + +/* Native USB Pins */ +#define BOARD_USB_DM_GPIO GPIO_NUM_19 /* USB D- */ +#define BOARD_USB_DP_GPIO GPIO_NUM_20 /* USB D+ */ + +/* Default UART0 Pins */ +#define BOARD_UART0_TX_GPIO GPIO_NUM_43 /* UART0 TX pin */ +#define BOARD_UART0_RX_GPIO GPIO_NUM_44 /* UART0 RX pin */ + +#ifdef __cplusplus +} +#endif diff --git a/main/config_server.c b/main/config_server.c new file mode 100644 index 0000000..0e2734e --- /dev/null +++ b/main/config_server.c @@ -0,0 +1,1328 @@ +#include "config_server.h" +#include "web_assets.h" +#include "dns_server.h" +#include "profile_manager.h" +#include "input_calibration.h" +#include "ble_hid_host.h" +#include "status_led.h" +#include "console_output/usb_gamepad.h" + +#include "esp_wifi.h" +#include "esp_event.h" +#include "esp_netif.h" +#include "esp_http_server.h" +#include "esp_log.h" +#include "nvs_flash.h" +#include "nvs.h" +#include "mdns.h" +#include "esp_ota_ops.h" +#include "esp_app_desc.h" +#include "esp_timer.h" +#include +#include +#include +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "freertos/semphr.h" +#include +#include + +static const char *TAG = "CONFIG_SRV"; + +static esp_err_t httpd_open_fn(httpd_handle_t hd, int sockfd) +{ + int enable = 1; + setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, &enable, sizeof(enable)); + return ESP_OK; +} + +#define CONFIG_AP_SSID "MimiCon-Setup" +#define CONFIG_AP_CHANNEL 1 +#define CONFIG_AP_MAX_CONN 4 + +static bool s_wifi_inited = false; +static bool s_mdns_inited = false; +static esp_netif_t *s_ap_netif = NULL; +static esp_netif_t *s_sta_netif = NULL; +static httpd_handle_t s_http_server = NULL; + +static volatile bool s_is_active = false; + +/* Wi-Fi STA State */ +static bool s_sta_configured = false; +static bool s_sta_connected = false; +static char s_sta_ssid[33] = {0}; +static char s_sta_ip[16] = {0}; + +static controller_state_t s_latest_state = {0}; +static SemaphoreHandle_t s_state_mutex = NULL; + +static TaskHandle_t s_config_task_handle = NULL; +typedef enum { + CONFIG_CMD_NONE, + CONFIG_CMD_START, + CONFIG_CMD_STOP, + CONFIG_CMD_TOGGLE, +} config_cmd_t; +static volatile config_cmd_t s_pending_cmd = CONFIG_CMD_NONE; + +/* -------------------------------------------------------------------------- */ +/* NVS and Helper Functions */ +/* -------------------------------------------------------------------------- */ + +static bool json_get_string(const char *json, const char *key, char *dest, size_t max_len) +{ + if (!json || !key || !dest || max_len == 0) return false; + dest[0] = '\0'; + + char search_key[64]; + snprintf(search_key, sizeof(search_key), "\"%s\"", key); + const char *p = strstr(json, search_key); + if (!p) return false; + + p += strlen(search_key); + while (*p && (*p == ' ' || *p == ':' || *p == '\t' || *p == '\r' || *p == '\n')) { + p++; + } + if (*p != '\"') return false; + p++; /* skip opening quote */ + + size_t i = 0; + while (*p && *p != '\"' && i + 1 < max_len) { + if (*p == '\\' && *(p + 1)) { + p++; + } + dest[i++] = *p++; + } + dest[i] = '\0'; + return true; +} + +static bool json_get_int(const char *json, const char *key, int *val) +{ + if (!json || !key || !val) return false; + char search_key[64]; + snprintf(search_key, sizeof(search_key), "\"%s\"", key); + const char *p = strstr(json, search_key); + if (!p) return false; + + p += strlen(search_key); + while (*p && (*p == ' ' || *p == ':' || *p == '\t')) p++; + *val = atoi(p); + return true; +} + +static bool json_get_bool(const char *json, const char *key, bool *val) +{ + if (!json || !key || !val) return false; + char search_key[64]; + snprintf(search_key, sizeof(search_key), "\"%s\"", key); + const char *p = strstr(json, search_key); + if (!p) return false; + + p += strlen(search_key); + while (*p && (*p == ' ' || *p == ':' || *p == '\t')) p++; + if (strncmp(p, "true", 4) == 0 || *p == '1') { + *val = true; + return true; + } else if (strncmp(p, "false", 5) == 0 || *p == '0') { + *val = false; + return true; + } + return false; +} + +static bool read_saved_wifi_creds(char *ssid, size_t ssid_len, char *pass, size_t pass_len) +{ + nvs_handle_t nvs_h; + if (nvs_open("wifi_cfg", NVS_READONLY, &nvs_h) != ESP_OK) { + return false; + } + esp_err_t err_s = nvs_get_str(nvs_h, "sta_ssid", ssid, &ssid_len); + nvs_get_str(nvs_h, "sta_pass", pass, &pass_len); + nvs_close(nvs_h); + return (err_s == ESP_OK && strlen(ssid) > 0); +} + +static esp_err_t save_wifi_creds(const char *ssid, const char *pass) +{ + nvs_handle_t nvs_h; + esp_err_t err = nvs_open("wifi_cfg", NVS_READWRITE, &nvs_h); + if (err != ESP_OK) return err; + + nvs_set_str(nvs_h, "sta_ssid", ssid); + nvs_set_str(nvs_h, "sta_pass", pass ? pass : ""); + err = nvs_commit(nvs_h); + nvs_close(nvs_h); + return err; +} + +static esp_err_t clear_wifi_creds(void) +{ + nvs_handle_t nvs_h; + esp_err_t err = nvs_open("wifi_cfg", NVS_READWRITE, &nvs_h); + if (err != ESP_OK) return err; + + nvs_erase_key(nvs_h, "sta_ssid"); + nvs_erase_key(nvs_h, "sta_pass"); + err = nvs_commit(nvs_h); + nvs_close(nvs_h); + return err; +} + +static void wifi_event_handler(void *arg, esp_event_base_t event_base, + int32_t event_id, void *event_data) +{ + if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) { + if (s_sta_configured) { + ESP_LOGI(TAG, "STA interface started, connecting to %s...", s_sta_ssid); + esp_wifi_connect(); + } + } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) { + s_sta_connected = false; + s_sta_ip[0] = '\0'; + ESP_LOGI(TAG, "Wi-Fi Station disconnected"); + } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) { + ip_event_got_ip_t *event = (ip_event_got_ip_t *)event_data; + esp_ip4addr_ntoa(&event->ip_info.ip, s_sta_ip, sizeof(s_sta_ip)); + s_sta_connected = true; + ESP_LOGI(TAG, "====================================================="); + ESP_LOGI(TAG, " Wi-Fi Station Connected! "); + ESP_LOGI(TAG, " SSID: %s ", s_sta_ssid); + ESP_LOGI(TAG, " IP: %s ", s_sta_ip); + ESP_LOGI(TAG, " mDNS: http://mimicon.local/ (or http://esp32-hid.local/)"); + ESP_LOGI(TAG, "====================================================="); + } +} + +/* -------------------------------------------------------------------------- */ +/* HTTP URI Handlers */ +/* -------------------------------------------------------------------------- */ + +static esp_err_t index_get_handler(httpd_req_t *req) +{ + httpd_resp_set_type(req, "text/html; charset=utf-8"); + return httpd_resp_send(req, INDEX_HTML, strlen(INDEX_HTML)); +} + +static esp_err_t captive_portal_handler(httpd_req_t *req) +{ + httpd_resp_set_status(req, "302 Found"); + httpd_resp_set_hdr(req, "Location", "http://192.168.4.1/"); + return httpd_resp_send(req, NULL, 0); +} + +static esp_err_t api_status_handler(httpd_req_t *req) +{ + char json[768]; + console_mode_t mode = profile_manager_get_mode(); + combo_config_t combos; + profile_manager_get_combos(&combos); + + const esp_app_desc_t *app_desc = esp_app_get_description(); + const esp_partition_t *running_part = esp_ota_get_running_partition(); + const esp_partition_t *next_part = esp_ota_get_next_update_partition(NULL); + + ble_hid_host_refresh_battery(); + int8_t battery = ble_hid_host_get_battery_level(); + + wifi_mode_t cur_mode = WIFI_MODE_NULL; + esp_wifi_get_mode(&cur_mode); + bool ap_active = (cur_mode == WIFI_MODE_AP || cur_mode == WIFI_MODE_APSTA); + + snprintf(json, sizeof(json), + "{\"mode\":%d,\"mode_name\":\"%s\"," + "\"ble_connected\":%s,\"ble_device\":\"%s\"," + "\"battery\":%d," + "\"led_brightness\":%d," + "\"ap_active\":%s," + "\"sta_connected\":%s,\"sta_ssid\":\"%s\",\"sta_ip\":\"%s\"," + "\"mdns_url\":\"http://mimicon.local\"," + "\"combos\":{\"a\":%d,\"b\":%d,\"x\":%d,\"y\":%d}," + "\"app_version\":\"%s\"," + "\"compile_time\":\"%s %s\"," + "\"running_part\":\"%s\"," + "\"next_part\":\"%s\"}", + (int)mode, + profile_manager_mode_name(mode), + ble_hid_host_is_connected() ? "true" : "false", + ble_hid_host_get_device_name(), + (int)battery, + (int)status_led_get_brightness(), + ap_active ? "true" : "false", + s_sta_connected ? "true" : "false", + s_sta_ssid, + s_sta_ip, + (int)combos.combo_a, + (int)combos.combo_b, + (int)combos.combo_x, + (int)combos.combo_y, + app_desc ? app_desc->version : "1.0.0", + app_desc ? app_desc->date : "", + app_desc ? app_desc->time : "", + running_part ? running_part->label : "factory", + next_part ? next_part->label : "ota_0"); + + httpd_resp_set_type(req, "application/json"); + httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); + return httpd_resp_send(req, json, strlen(json)); +} + +static void format_state_json(char *buf, size_t buf_len) +{ + if (s_state_mutex) { + xSemaphoreTake(s_state_mutex, portMAX_DELAY); + } + + snprintf(buf, buf_len, + "{\"a\":%d,\"b\":%d,\"x\":%d,\"y\":%d,\"lb\":%d,\"rb\":%d," + "\"select\":%d,\"start\":%d,\"home\":%d,\"l3\":%d,\"r3\":%d," + "\"dup\":%d,\"ddown\":%d,\"dleft\":%d,\"dright\":%d," + "\"lx\":%d,\"ly\":%d,\"rx\":%d,\"ry\":%d," + "\"lt\":%d,\"rt\":%d}", + s_latest_state.btn_a ? 1 : 0, + s_latest_state.btn_b ? 1 : 0, + s_latest_state.btn_x ? 1 : 0, + s_latest_state.btn_y ? 1 : 0, + s_latest_state.btn_lb ? 1 : 0, + s_latest_state.btn_rb ? 1 : 0, + s_latest_state.btn_select ? 1 : 0, + s_latest_state.btn_start ? 1 : 0, + s_latest_state.btn_system ? 1 : 0, + s_latest_state.btn_l3 ? 1 : 0, + s_latest_state.btn_r3 ? 1 : 0, + s_latest_state.dpad_up ? 1 : 0, + s_latest_state.dpad_down ? 1 : 0, + s_latest_state.dpad_left ? 1 : 0, + s_latest_state.dpad_right ? 1 : 0, + (int)s_latest_state.lx, + (int)s_latest_state.ly, + (int)s_latest_state.rx, + (int)s_latest_state.ry, + (int)s_latest_state.lt, + (int)s_latest_state.rt); + + if (s_state_mutex) { + xSemaphoreGive(s_state_mutex); + } +} + +static esp_err_t api_state_handler(httpd_req_t *req) +{ + char json[320]; + format_state_json(json, sizeof(json)); + + httpd_resp_set_type(req, "application/json"); + httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); + return httpd_resp_send(req, json, strlen(json)); +} + +#if CONFIG_HTTPD_WS_SUPPORT +static esp_err_t ws_state_handler(httpd_req_t *req) +{ + if (req->method == HTTP_GET) { + ESP_LOGI(TAG, "WebSocket visualizer client connected"); + return ESP_OK; + } + + httpd_ws_frame_t ws_pkt; + uint8_t buf[256]; + memset(&ws_pkt, 0, sizeof(httpd_ws_frame_t)); + ws_pkt.payload = buf; + ws_pkt.type = HTTPD_WS_TYPE_TEXT; + esp_err_t ret = httpd_ws_recv_frame(req, &ws_pkt, sizeof(buf) - 1); + if (ret != ESP_OK) { + return ret; + } + buf[ws_pkt.len] = '\0'; + + if (strstr((char *)buf, "\"b\":") || strstr((char *)buf, "\"b\" :")) { + int buttons = 0, lx = 0, ly = 0, rx = 0, ry = 0, lt = 0, rt = 0; + json_get_int((char *)buf, "b", &buttons); + json_get_int((char *)buf, "lx", &lx); + json_get_int((char *)buf, "ly", &ly); + json_get_int((char *)buf, "rx", &rx); + json_get_int((char *)buf, "ry", &ry); + json_get_int((char *)buf, "lt", <); + json_get_int((char *)buf, "rt", &rt); + + controller_state_t st = {0}; + st.btn_a = (buttons & (1 << 0)) != 0; + st.btn_b = (buttons & (1 << 1)) != 0; + st.btn_x = (buttons & (1 << 2)) != 0; + st.btn_y = (buttons & (1 << 3)) != 0; + st.btn_lb = (buttons & (1 << 4)) != 0; + st.btn_rb = (buttons & (1 << 5)) != 0; + st.btn_select = (buttons & (1 << 8)) != 0; + st.btn_start = (buttons & (1 << 9)) != 0; + st.btn_system = (buttons & (1 << 10)) != 0; + st.btn_l3 = (buttons & (1 << 11)) != 0; + st.btn_r3 = (buttons & (1 << 12)) != 0; + st.dpad_up = (buttons & (1 << 13)) != 0; + st.dpad_down = (buttons & (1 << 14)) != 0; + st.dpad_left = (buttons & (1 << 15)) != 0; + st.dpad_right = (buttons & (1 << 16)) != 0; + st.lx = (int16_t)lx; + st.ly = (int16_t)ly; + st.rx = (int16_t)rx; + st.ry = (int16_t)ry; + st.lt = (uint8_t)(lt > 255 ? 255 : (lt < 0 ? 0 : lt)); + st.rt = (uint8_t)(rt > 255 ? 255 : (rt < 0 ? 0 : rt)); + + controller_state_t calibrated; + input_calibration_apply(&st, &calibrated); + usb_gamepad_send_state(&calibrated); + config_server_set_latest_state(&calibrated); + return ESP_OK; + } + + char json[320]; + format_state_json(json, sizeof(json)); + + memset(&ws_pkt, 0, sizeof(httpd_ws_frame_t)); + ws_pkt.payload = (uint8_t *)json; + ws_pkt.len = strlen(json); + ws_pkt.type = HTTPD_WS_TYPE_TEXT; + return httpd_ws_send_frame(req, &ws_pkt); +} +#endif + +static esp_err_t api_mode_handler(httpd_req_t *req) +{ + char buf[128]; + int ret = httpd_req_recv(req, buf, sizeof(buf) - 1); + if (ret <= 0) { + httpd_resp_send_500(req); + return ESP_FAIL; + } + buf[ret] = '\0'; + + char *p = strstr(buf, "\"mode\":"); + if (!p) p = strstr(buf, "\"mode\" :"); + if (p) { + int mode_val = atoi(p + 7); + if (mode_val >= 0 && mode_val < CONSOLE_MODE_MAX) { + ESP_LOGI(TAG, "Web client requested console mode %d", mode_val); + profile_manager_set_mode((console_mode_t)mode_val); + } + } + + httpd_resp_set_type(req, "application/json"); + return httpd_resp_send(req, "{\"status\":\"ok\"}", 15); +} + +static esp_err_t api_led_handler(httpd_req_t *req) +{ + char buf[128]; + int ret = httpd_req_recv(req, buf, sizeof(buf) - 1); + if (ret <= 0) { + httpd_resp_send_500(req); + return ESP_FAIL; + } + buf[ret] = '\0'; + + char *p = strstr(buf, "\"brightness\":"); + if (!p) p = strstr(buf, "\"brightness\" :"); + if (p) { + int br = atoi(p + 13); + if (br >= 0 && br <= 100) { + profile_manager_set_led_brightness((uint8_t)br); + } + } + + httpd_resp_set_type(req, "application/json"); + return httpd_resp_send(req, "{\"status\":\"ok\"}", 15); +} + +static esp_err_t api_combos_get_handler(httpd_req_t *req) +{ + combo_config_t combos; + profile_manager_get_combos(&combos); + + char json[128]; + snprintf(json, sizeof(json), "{\"combo_a\":%d,\"combo_b\":%d,\"combo_x\":%d,\"combo_y\":%d}", + combos.combo_a, combos.combo_b, combos.combo_x, combos.combo_y); + + httpd_resp_set_type(req, "application/json"); + httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); + return httpd_resp_send(req, json, strlen(json)); +} + +static esp_err_t api_combos_post_handler(httpd_req_t *req) +{ + char buf[160]; + int ret = httpd_req_recv(req, buf, sizeof(buf) - 1); + if (ret <= 0) { + httpd_resp_send_500(req); + return ESP_FAIL; + } + buf[ret] = '\0'; + + combo_config_t combos; + profile_manager_get_combos(&combos); + + int val = -1; + if (json_get_int(buf, "combo_a", &val)) combos.combo_a = (int8_t)val; + if (json_get_int(buf, "combo_b", &val)) combos.combo_b = (int8_t)val; + if (json_get_int(buf, "combo_x", &val)) combos.combo_x = (int8_t)val; + if (json_get_int(buf, "combo_y", &val)) combos.combo_y = (int8_t)val; + + profile_manager_set_combos(&combos); + + httpd_resp_set_type(req, "application/json"); + return httpd_resp_send(req, "{\"status\":\"ok\"}", 15); +} + +static esp_err_t api_ble_disconnect_handler(httpd_req_t *req) +{ + ble_hid_host_disconnect(); + httpd_resp_set_type(req, "application/json"); + return httpd_resp_send(req, "{\"status\":\"ok\"}", 15); +} + +static esp_err_t api_ble_clear_bonds_handler(httpd_req_t *req) +{ + ble_hid_host_clear_bonds(); + httpd_resp_set_type(req, "application/json"); + return httpd_resp_send(req, "{\"status\":\"ok\"}", 15); +} + +static esp_err_t api_ble_rumble_handler(httpd_req_t *req) +{ + ESP_LOGI(TAG, "Triggering BLE controller test rumble..."); + ble_hid_host_test_rumble(150); + httpd_resp_set_type(req, "application/json"); + return httpd_resp_send(req, "{\"status\":\"ok\"}", 15); +} + +static esp_err_t api_ble_peers_get_handler(httpd_req_t *req) +{ + ble_peer_info_t peers[BLE_MAX_PEERS]; + int count = ble_hid_host_get_peers(peers, BLE_MAX_PEERS); + + char *json = malloc(1024); + if (!json) { + httpd_resp_send_500(req); + return ESP_FAIL; + } + + size_t len = 0; + len += snprintf(json + len, 1024 - len, "["); + for (int i = 0; i < count; i++) { + char clean_name[32] = {0}; + int c_idx = 0; + for (int s = 0; s < strlen(peers[i].name) && c_idx < 31; s++) { + char ch = peers[i].name[s]; + if (ch == '\"' || ch == '\\') clean_name[c_idx++] = ' '; + else if (ch >= 32 && ch <= 126) clean_name[c_idx++] = ch; + } + + len += snprintf(json + len, 1024 - len, + "%s{\"name\":\"%s\",\"mac\":\"%s\",\"type\":%d,\"connected\":%s,\"battery\":%d}", + (i > 0) ? "," : "", + clean_name, + peers[i].mac_str, + (int)peers[i].controller_type, + peers[i].is_connected ? "true" : "false", + (int)peers[i].battery); + if (len + 64 >= 1024) break; + } + len += snprintf(json + len, 1024 - len, "]"); + + httpd_resp_set_type(req, "application/json"); + httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); + esp_err_t res = httpd_resp_send(req, json, len); + free(json); + return res; +} + +static esp_err_t api_ble_unpair_handler(httpd_req_t *req) +{ + char buf[128]; + int ret = httpd_req_recv(req, buf, sizeof(buf) - 1); + if (ret <= 0) { + httpd_resp_send_500(req); + return ESP_FAIL; + } + buf[ret] = '\0'; + + char mac[20] = {0}; + if (json_get_string(buf, "mac", mac, sizeof(mac))) { + ble_hid_host_unpair_device(mac); + } + + httpd_resp_set_type(req, "application/json"); + return httpd_resp_send(req, "{\"status\":\"ok\"}", 15); +} + +static esp_err_t api_remote_input_handler(httpd_req_t *req) +{ + char buf[256]; + int ret = httpd_req_recv(req, buf, sizeof(buf) - 1); + if (ret <= 0) { + httpd_resp_send_500(req); + return ESP_FAIL; + } + buf[ret] = '\0'; + + int buttons = 0, lx = 0, ly = 0, rx = 0, ry = 0, lt = 0, rt = 0; + json_get_int(buf, "b", &buttons); + json_get_int(buf, "lx", &lx); + json_get_int(buf, "ly", &ly); + json_get_int(buf, "rx", &rx); + json_get_int(buf, "ry", &ry); + json_get_int(buf, "lt", <); + json_get_int(buf, "rt", &rt); + + controller_state_t st = {0}; + st.btn_a = (buttons & (1 << 0)) != 0; + st.btn_b = (buttons & (1 << 1)) != 0; + st.btn_x = (buttons & (1 << 2)) != 0; + st.btn_y = (buttons & (1 << 3)) != 0; + st.btn_lb = (buttons & (1 << 4)) != 0; + st.btn_rb = (buttons & (1 << 5)) != 0; + st.btn_lt = (buttons & (1 << 6)) != 0; + st.btn_rt = (buttons & (1 << 7)) != 0; + st.btn_select = (buttons & (1 << 8)) != 0; + st.btn_start = (buttons & (1 << 9)) != 0; + st.btn_system = (buttons & (1 << 10)) != 0; + st.btn_l3 = (buttons & (1 << 11)) != 0; + st.btn_r3 = (buttons & (1 << 12)) != 0; + st.dpad_up = (buttons & (1 << 13)) != 0; + st.dpad_down = (buttons & (1 << 14)) != 0; + st.dpad_left = (buttons & (1 << 15)) != 0; + st.dpad_right = (buttons & (1 << 16)) != 0; + + st.lx = (int16_t)lx; + st.ly = (int16_t)ly; + st.rx = (int16_t)rx; + st.ry = (int16_t)ry; + st.lt = (uint8_t)(lt > 255 ? 255 : (lt < 0 ? 0 : lt)); + st.rt = (uint8_t)(rt > 255 ? 255 : (rt < 0 ? 0 : rt)); + + controller_state_t calibrated; + input_calibration_apply(&st, &calibrated); + usb_gamepad_send_state(&calibrated); + config_server_set_latest_state(&calibrated); + + httpd_resp_set_type(req, "application/json"); + httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); + return httpd_resp_send(req, "{\"status\":\"ok\"}", 15); +} + +static esp_err_t api_calibration_get_handler(httpd_req_t *req) +{ + input_calibration_cfg_t cfg; + input_calibration_get_config(&cfg); + + char json[256]; + snprintf(json, sizeof(json), + "{\"left_deadzone\":%d,\"right_deadzone\":%d,\"trigger_deadzone\":%d," + "\"swap_ab\":%s,\"swap_xy\":%s,\"swap_bumpers_triggers\":%s," + "\"invert_lx\":%s,\"invert_ly\":%s,\"invert_rx\":%s,\"invert_ry\":%s}", + cfg.left_deadzone, cfg.right_deadzone, cfg.trigger_deadzone, + cfg.swap_ab ? "true" : "false", + cfg.swap_xy ? "true" : "false", + cfg.swap_bumpers_triggers ? "true" : "false", + cfg.invert_lx ? "true" : "false", + cfg.invert_ly ? "true" : "false", + cfg.invert_rx ? "true" : "false", + cfg.invert_ry ? "true" : "false"); + + httpd_resp_set_type(req, "application/json"); + httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); + return httpd_resp_send(req, json, strlen(json)); +} + +static esp_err_t api_calibration_post_handler(httpd_req_t *req) +{ + char buf[320]; + int ret = httpd_req_recv(req, buf, sizeof(buf) - 1); + if (ret <= 0) { + httpd_resp_send_500(req); + return ESP_FAIL; + } + buf[ret] = '\0'; + + input_calibration_cfg_t cfg; + input_calibration_get_config(&cfg); + + int val = 0; + if (json_get_int(buf, "left_deadzone", &val)) cfg.left_deadzone = (uint8_t)val; + if (json_get_int(buf, "right_deadzone", &val)) cfg.right_deadzone = (uint8_t)val; + if (json_get_int(buf, "trigger_deadzone", &val)) cfg.trigger_deadzone = (uint8_t)val; + + bool b = false; + if (json_get_bool(buf, "swap_ab", &b)) cfg.swap_ab = b; + if (json_get_bool(buf, "swap_xy", &b)) cfg.swap_xy = b; + if (json_get_bool(buf, "swap_bumpers_triggers", &b)) cfg.swap_bumpers_triggers = b; + if (json_get_bool(buf, "invert_lx", &b)) cfg.invert_lx = b; + if (json_get_bool(buf, "invert_ly", &b)) cfg.invert_ly = b; + if (json_get_bool(buf, "invert_rx", &b)) cfg.invert_rx = b; + if (json_get_bool(buf, "invert_ry", &b)) cfg.invert_ry = b; + + input_calibration_set_config(&cfg); + + httpd_resp_set_type(req, "application/json"); + return httpd_resp_send(req, "{\"status\":\"ok\"}", 15); +} + +static esp_err_t api_calibration_reset_handler(httpd_req_t *req) +{ + input_calibration_reset_defaults(); + httpd_resp_set_type(req, "application/json"); + return httpd_resp_send(req, "{\"status\":\"ok\"}", 15); +} + +static esp_err_t api_exit_handler(httpd_req_t *req) +{ + ESP_LOGI(TAG, "Client requested exit from Config Mode"); + config_server_request_stop(); + httpd_resp_set_type(req, "application/json"); + return httpd_resp_send(req, "{\"status\":\"exiting\"}", 20); +} + +static esp_err_t api_wifi_scan_handler(httpd_req_t *req) +{ + ESP_LOGI(TAG, "Starting Wi-Fi scan..."); + wifi_scan_config_t scan_cfg = { + .ssid = NULL, + .bssid = NULL, + .channel = 0, + .show_hidden = false, + .scan_type = WIFI_SCAN_TYPE_ACTIVE, + }; + + esp_err_t err = esp_wifi_scan_start(&scan_cfg, true); + if (err != ESP_OK) { + ESP_LOGE(TAG, "Wi-Fi scan failed: %s", esp_err_to_name(err)); + httpd_resp_set_type(req, "application/json"); + return httpd_resp_send(req, "[]", 2); + } + + uint16_t ap_count = 0; + esp_wifi_scan_get_ap_num(&ap_count); + if (ap_count > 20) ap_count = 20; + + wifi_ap_record_t *ap_records = NULL; + if (ap_count > 0) { + ap_records = malloc(sizeof(wifi_ap_record_t) * ap_count); + if (ap_records) { + esp_wifi_scan_get_ap_records(&ap_count, ap_records); + } + } + + size_t json_cap = 2048; + char *json = malloc(json_cap); + if (!json) { + if (ap_records) free(ap_records); + httpd_resp_send_500(req); + return ESP_FAIL; + } + + size_t len = 0; + len += snprintf(json + len, json_cap - len, "["); + + int written = 0; + if (ap_records) { + for (int i = 0; i < ap_count; i++) { + if (ap_records[i].ssid[0] == '\0') continue; + + bool dup = false; + for (int j = 0; j < i; j++) { + if (strcmp((char *)ap_records[i].ssid, (char *)ap_records[j].ssid) == 0) { + dup = true; + break; + } + } + if (dup) continue; + + if (written > 0 && len + 2 < json_cap) { + len += snprintf(json + len, json_cap - len, ","); + } + + char clean_ssid[33] = {0}; + size_t c_idx = 0; + for (size_t s = 0; s < strlen((char *)ap_records[i].ssid) && c_idx + 1 < sizeof(clean_ssid); s++) { + char ch = ap_records[i].ssid[s]; + if (ch == '\"' || ch == '\\') clean_ssid[c_idx++] = ' '; + else if (ch >= 32 && ch <= 126) clean_ssid[c_idx++] = ch; + } + + len += snprintf(json + len, json_cap - len, + "{\"ssid\":\"%s\",\"rssi\":%d,\"auth\":%d}", + clean_ssid, + (int)ap_records[i].rssi, + (int)ap_records[i].authmode); + written++; + if (len + 64 >= json_cap) break; + } + free(ap_records); + } + + if (len + 2 < json_cap) { + len += snprintf(json + len, json_cap - len, "]"); + } + + httpd_resp_set_type(req, "application/json"); + httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); + esp_err_t res = httpd_resp_send(req, json, len); + free(json); + return res; +} + +static esp_err_t api_wifi_connect_handler(httpd_req_t *req) +{ + char buf[256]; + int ret = httpd_req_recv(req, buf, sizeof(buf) - 1); + if (ret <= 0) { + httpd_resp_send_500(req); + return ESP_FAIL; + } + buf[ret] = '\0'; + + char ssid[33] = {0}; + char pass[65] = {0}; + + json_get_string(buf, "ssid", ssid, sizeof(ssid)); + json_get_string(buf, "password", pass, sizeof(pass)); + + if (strlen(ssid) == 0) { + httpd_resp_set_type(req, "application/json"); + return httpd_resp_send(req, "{\"status\":\"error\",\"message\":\"Empty SSID\"}", HTTPD_RESP_USE_STRLEN); + } + + ESP_LOGI(TAG, "Saving Wi-Fi credentials for SSID: '%s'", ssid); + save_wifi_creds(ssid, pass); + + strncpy(s_sta_ssid, ssid, sizeof(s_sta_ssid) - 1); + s_sta_configured = true; + s_sta_connected = false; + s_sta_ip[0] = '\0'; + + wifi_config_t wifi_sta_cfg = {0}; + strncpy((char *)wifi_sta_cfg.sta.ssid, ssid, sizeof(wifi_sta_cfg.sta.ssid) - 1); + strncpy((char *)wifi_sta_cfg.sta.password, pass, sizeof(wifi_sta_cfg.sta.password) - 1); + + esp_wifi_set_config(WIFI_IF_STA, &wifi_sta_cfg); + esp_wifi_disconnect(); + esp_wifi_connect(); + + httpd_resp_set_type(req, "application/json"); + return httpd_resp_send(req, "{\"status\":\"connecting\"}", HTTPD_RESP_USE_STRLEN); +} + +static esp_err_t api_wifi_forget_handler(httpd_req_t *req) +{ + ESP_LOGI(TAG, "Clearing saved Wi-Fi credentials..."); + clear_wifi_creds(); + s_sta_configured = false; + s_sta_connected = false; + s_sta_ssid[0] = '\0'; + s_sta_ip[0] = '\0'; + + wifi_config_t empty_cfg = {0}; + esp_wifi_set_config(WIFI_IF_STA, &empty_cfg); + esp_wifi_disconnect(); + + httpd_resp_set_type(req, "application/json"); + return httpd_resp_send(req, "{\"status\":\"ok\"}", HTTPD_RESP_USE_STRLEN); +} + +static void delayed_restart_timer_callback(void *arg) +{ + ESP_LOGI(TAG, "Restarting ESP32-S3 into new firmware now..."); + esp_restart(); +} + +static esp_err_t api_ota_upload_handler(httpd_req_t *req) +{ + ESP_LOGI(TAG, "Starting OTA firmware upload, total size: %d bytes", req->content_len); + + if (req->content_len <= 0) { + httpd_resp_set_status(req, "400 Bad Request"); + httpd_resp_set_type(req, "application/json"); + return httpd_resp_send(req, "{\"status\":\"error\",\"message\":\"Empty payload\"}", HTTPD_RESP_USE_STRLEN); + } + + const esp_partition_t *update_partition = esp_ota_get_next_update_partition(NULL); + if (!update_partition) { + ESP_LOGE(TAG, "No OTA partition found"); + httpd_resp_set_status(req, "500 Internal Server Error"); + httpd_resp_set_type(req, "application/json"); + return httpd_resp_send(req, "{\"status\":\"error\",\"message\":\"No OTA partition found\"}", HTTPD_RESP_USE_STRLEN); + } + + ESP_LOGI(TAG, "Target OTA partition: %s (address: 0x%08lx, max size: 0x%08lx)", + update_partition->label, + (unsigned long)update_partition->address, + (unsigned long)update_partition->size); + + if (req->content_len > update_partition->size) { + ESP_LOGE(TAG, "Binary size (%d) exceeds partition capacity (%lu)", + req->content_len, (unsigned long)update_partition->size); + httpd_resp_set_status(req, "400 Bad Request"); + httpd_resp_set_type(req, "application/json"); + return httpd_resp_send(req, "{\"status\":\"error\",\"message\":\"Binary size exceeds partition size\"}", HTTPD_RESP_USE_STRLEN); + } + + esp_ota_handle_t ota_handle = 0; + esp_err_t err = esp_ota_begin(update_partition, OTA_WITH_SEQUENTIAL_WRITES, &ota_handle); + if (err != ESP_OK) { + ESP_LOGE(TAG, "esp_ota_begin failed: %s", esp_err_to_name(err)); + httpd_resp_set_status(req, "500 Internal Server Error"); + httpd_resp_set_type(req, "application/json"); + return httpd_resp_send(req, "{\"status\":\"error\",\"message\":\"Failed to begin OTA flash session\"}", HTTPD_RESP_USE_STRLEN); + } + + char *buf = malloc(2048); + if (!buf) { + esp_ota_abort(ota_handle); + httpd_resp_send_500(req); + return ESP_FAIL; + } + + int remaining = req->content_len; + while (remaining > 0) { + int to_read = remaining > 2048 ? 2048 : remaining; + int recv_len = httpd_req_recv(req, buf, to_read); + if (recv_len <= 0) { + if (recv_len == HTTPD_SOCK_ERR_TIMEOUT) { + continue; + } + ESP_LOGE(TAG, "OTA receive interrupted (%d)", recv_len); + esp_ota_abort(ota_handle); + free(buf); + httpd_resp_set_status(req, "500 Internal Server Error"); + httpd_resp_set_type(req, "application/json"); + return httpd_resp_send(req, "{\"status\":\"error\",\"message\":\"Connection lost during upload\"}", HTTPD_RESP_USE_STRLEN); + } + + err = esp_ota_write(ota_handle, (const void *)buf, recv_len); + if (err != ESP_OK) { + ESP_LOGE(TAG, "esp_ota_write failed: %s", esp_err_to_name(err)); + esp_ota_abort(ota_handle); + free(buf); + httpd_resp_set_status(req, "500 Internal Server Error"); + httpd_resp_set_type(req, "application/json"); + return httpd_resp_send(req, "{\"status\":\"error\",\"message\":\"Flash write error\"}", HTTPD_RESP_USE_STRLEN); + } + + remaining -= recv_len; + } + + free(buf); + + err = esp_ota_end(ota_handle); + if (err != ESP_OK) { + ESP_LOGE(TAG, "esp_ota_end validation failed: %s", esp_err_to_name(err)); + httpd_resp_set_status(req, "500 Internal Server Error"); + httpd_resp_set_type(req, "application/json"); + return httpd_resp_send(req, "{\"status\":\"error\",\"message\":\"Firmware verification failed\"}", HTTPD_RESP_USE_STRLEN); + } + + err = esp_ota_set_boot_partition(update_partition); + if (err != ESP_OK) { + ESP_LOGE(TAG, "esp_ota_set_boot_partition failed: %s", esp_err_to_name(err)); + httpd_resp_set_status(req, "500 Internal Server Error"); + httpd_resp_set_type(req, "application/json"); + return httpd_resp_send(req, "{\"status\":\"error\",\"message\":\"Failed to set boot partition\"}", HTTPD_RESP_USE_STRLEN); + } + + ESP_LOGI(TAG, "OTA update complete! New boot partition: %s. Scheduling reboot...", update_partition->label); + + httpd_resp_set_type(req, "application/json"); + httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); + httpd_resp_send(req, "{\"status\":\"ok\",\"message\":\"Update successful, rebooting...\"}", HTTPD_RESP_USE_STRLEN); + + const esp_timer_create_args_t restart_timer_args = { + .callback = &delayed_restart_timer_callback, + .name = "ota_reboot" + }; + esp_timer_handle_t restart_timer; + if (esp_timer_create(&restart_timer_args, &restart_timer) == ESP_OK) { + esp_timer_start_once(restart_timer, 1500000); /* 1.5 seconds */ + } else { + esp_restart(); + } + + return ESP_OK; +} + +static esp_err_t api_ap_toggle_handler(httpd_req_t *req) +{ + wifi_mode_t current_mode = WIFI_MODE_NULL; + esp_wifi_get_mode(¤t_mode); + + bool ap_now_active = false; + + if (current_mode == WIFI_MODE_APSTA || current_mode == WIFI_MODE_AP) { + /* User wants to turn OFF SoftAP */ + if (s_sta_connected) { + esp_wifi_set_mode(WIFI_MODE_STA); + dns_server_stop(); + ap_now_active = false; + ESP_LOGI(TAG, "SoftAP hotspot turned OFF (Station mode remains active)"); + } else { + /* If no Station connection, turning off AP shuts down server */ + ESP_LOGI(TAG, "SoftAP hotspot turned OFF with no STA -> requesting server stop"); + char resp[64]; + snprintf(resp, sizeof(resp), "{\"status\":\"ok\",\"ap_active\":false,\"stopped\":true}"); + httpd_resp_set_type(req, "application/json"); + httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); + httpd_resp_send(req, resp, strlen(resp)); + config_server_request_stop(); + return ESP_OK; + } + } else { + /* User wants to turn ON SoftAP */ + esp_wifi_set_mode(s_sta_configured ? WIFI_MODE_APSTA : WIFI_MODE_AP); + dns_server_start(); + ap_now_active = true; + ESP_LOGI(TAG, "SoftAP hotspot turned ON: %s", CONFIG_AP_SSID); + } + + char resp[64]; + snprintf(resp, sizeof(resp), "{\"status\":\"ok\",\"ap_active\":%s}", ap_now_active ? "true" : "false"); + httpd_resp_set_type(req, "application/json"); + httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); + return httpd_resp_send(req, resp, strlen(resp)); +} + +/* -------------------------------------------------------------------------- */ +/* Internal Server Start / Stop (Executed safely in dedicated task) */ +/* -------------------------------------------------------------------------- */ + +static esp_err_t config_server_start_internal(void) +{ + if (s_is_active) { + return ESP_OK; + } + + ESP_LOGI(TAG, "Starting Config Server (AP+STA mode and mDNS)..."); + + /* 1. Initialize TCP/IP and Wi-Fi stack once */ + if (!s_wifi_inited) { + esp_netif_init(); + esp_event_loop_create_default(); + s_ap_netif = esp_netif_create_default_wifi_ap(); + s_sta_netif = esp_netif_create_default_wifi_sta(); + + wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); + esp_wifi_init(&cfg); + esp_wifi_set_storage(WIFI_STORAGE_RAM); + + esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &wifi_event_handler, NULL, NULL); + esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &wifi_event_handler, NULL, NULL); + + s_wifi_inited = true; + } + + /* 2. Configure and start SoftAP + Station */ + wifi_config_t wifi_ap_config = { + .ap = { + .ssid = CONFIG_AP_SSID, + .ssid_len = strlen(CONFIG_AP_SSID), + .channel = CONFIG_AP_CHANNEL, + .password = "", + .max_connection = CONFIG_AP_MAX_CONN, + .authmode = WIFI_AUTH_OPEN, + }, + }; + + esp_err_t err = esp_wifi_set_mode(WIFI_MODE_APSTA); + if (err == ESP_OK) err = esp_wifi_set_config(WIFI_IF_AP, &wifi_ap_config); + + char saved_pass[65] = {0}; + if (read_saved_wifi_creds(s_sta_ssid, sizeof(s_sta_ssid), saved_pass, sizeof(saved_pass))) { + s_sta_configured = true; + wifi_config_t wifi_sta_config = {0}; + strncpy((char *)wifi_sta_config.sta.ssid, s_sta_ssid, sizeof(wifi_sta_config.sta.ssid) - 1); + strncpy((char *)wifi_sta_config.sta.password, saved_pass, sizeof(wifi_sta_config.sta.password) - 1); + esp_wifi_set_config(WIFI_IF_STA, &wifi_sta_config); + ESP_LOGI(TAG, "Loaded saved Wi-Fi STA SSID: %s", s_sta_ssid); + } else { + s_sta_configured = false; + s_sta_ssid[0] = '\0'; + } + + if (err == ESP_OK) err = esp_wifi_start(); + + if (err != ESP_OK) { + ESP_LOGE(TAG, "Failed to start Wi-Fi: %s", esp_err_to_name(err)); + return err; + } + + if (s_sta_configured) { + esp_wifi_connect(); + } + + ESP_LOGI(TAG, "====================================================="); + ESP_LOGI(TAG, " Config Wi-Fi SoftAP Started! "); + ESP_LOGI(TAG, " SoftAP SSID: %s (Open) ", CONFIG_AP_SSID); + ESP_LOGI(TAG, " SoftAP URL: http://192.168.4.1/ "); + ESP_LOGI(TAG, " mDNS URL: http://mimicon.local/ "); + ESP_LOGI(TAG, "====================================================="); + + /* 3. Start mDNS Responder */ + if (!s_mdns_inited) { + esp_err_t m_err = mdns_init(); + if (m_err == ESP_OK) { + mdns_hostname_set("mimicon"); + mdns_instance_name_set("MimiCon Gamepad Mimic"); + mdns_service_add("MimiCon-Web", "_http", "_tcp", 80, NULL, 0); + s_mdns_inited = true; + ESP_LOGI(TAG, "mDNS responder active: http://mimicon.local/"); + } else { + ESP_LOGW(TAG, "Failed to initialize mDNS: %s", esp_err_to_name(m_err)); + } + } + + /* 4. Start DNS Captive Portal server */ + dns_server_start(); + + /* 5. Start HTTP Web Server */ + httpd_config_t config = HTTPD_DEFAULT_CONFIG(); + config.stack_size = 8192; + config.max_uri_handlers = 32; + config.uri_match_fn = httpd_uri_match_wildcard; + config.core_id = 0; + config.open_fn = httpd_open_fn; + + err = httpd_start(&s_http_server, &config); + if (err == ESP_OK) { + httpd_uri_t uri_root = { .uri = "/", .method = HTTP_GET, .handler = index_get_handler }; + httpd_register_uri_handler(s_http_server, &uri_root); + + httpd_uri_t uri_idx = { .uri = "/index.html", .method = HTTP_GET, .handler = index_get_handler }; + httpd_register_uri_handler(s_http_server, &uri_idx); + + httpd_uri_t uri_gen204 = { .uri = "/generate_204", .method = HTTP_GET, .handler = captive_portal_handler }; + httpd_register_uri_handler(s_http_server, &uri_gen204); + + httpd_uri_t uri_hotspot = { .uri = "/hotspot-detect.html", .method = HTTP_GET, .handler = captive_portal_handler }; + httpd_register_uri_handler(s_http_server, &uri_hotspot); + + httpd_uri_t uri_ncsi = { .uri = "/ncsi.txt", .method = HTTP_GET, .handler = captive_portal_handler }; + httpd_register_uri_handler(s_http_server, &uri_ncsi); + + httpd_uri_t uri_conn = { .uri = "/connecttest.txt", .method = HTTP_GET, .handler = captive_portal_handler }; + httpd_register_uri_handler(s_http_server, &uri_conn); + + httpd_uri_t uri_status = { .uri = "/api/status", .method = HTTP_GET, .handler = api_status_handler }; + httpd_register_uri_handler(s_http_server, &uri_status); + + httpd_uri_t uri_state = { .uri = "/api/state", .method = HTTP_GET, .handler = api_state_handler }; + httpd_register_uri_handler(s_http_server, &uri_state); + +#if CONFIG_HTTPD_WS_SUPPORT + httpd_uri_t uri_ws_state = { + .uri = "/ws/state", + .method = HTTP_GET, + .handler = ws_state_handler, + .user_ctx = NULL, + .is_websocket = true + }; + httpd_register_uri_handler(s_http_server, &uri_ws_state); +#endif + + httpd_uri_t uri_mode = { .uri = "/api/mode", .method = HTTP_POST, .handler = api_mode_handler }; + httpd_register_uri_handler(s_http_server, &uri_mode); + + httpd_uri_t uri_combos_get = { .uri = "/api/combos", .method = HTTP_GET, .handler = api_combos_get_handler }; + httpd_register_uri_handler(s_http_server, &uri_combos_get); + + httpd_uri_t uri_combos_post = { .uri = "/api/combos", .method = HTTP_POST, .handler = api_combos_post_handler }; + httpd_register_uri_handler(s_http_server, &uri_combos_post); + + httpd_uri_t uri_led = { .uri = "/api/led", .method = HTTP_POST, .handler = api_led_handler }; + httpd_register_uri_handler(s_http_server, &uri_led); + + httpd_uri_t uri_disc = { .uri = "/api/ble/disconnect", .method = HTTP_POST, .handler = api_ble_disconnect_handler }; + httpd_register_uri_handler(s_http_server, &uri_disc); + + httpd_uri_t uri_clear = { .uri = "/api/ble/clear_bonds", .method = HTTP_POST, .handler = api_ble_clear_bonds_handler }; + httpd_register_uri_handler(s_http_server, &uri_clear); + + httpd_uri_t uri_rumble = { .uri = "/api/ble/rumble", .method = HTTP_POST, .handler = api_ble_rumble_handler }; + httpd_register_uri_handler(s_http_server, &uri_rumble); + + httpd_uri_t uri_peers = { .uri = "/api/ble/peers", .method = HTTP_GET, .handler = api_ble_peers_get_handler }; + httpd_register_uri_handler(s_http_server, &uri_peers); + + httpd_uri_t uri_unpair = { .uri = "/api/ble/unpair", .method = HTTP_POST, .handler = api_ble_unpair_handler }; + httpd_register_uri_handler(s_http_server, &uri_unpair); + + httpd_uri_t uri_remote = { .uri = "/api/remote/input", .method = HTTP_POST, .handler = api_remote_input_handler }; + httpd_register_uri_handler(s_http_server, &uri_remote); + + httpd_uri_t uri_calib_get = { .uri = "/api/calibration", .method = HTTP_GET, .handler = api_calibration_get_handler }; + httpd_register_uri_handler(s_http_server, &uri_calib_get); + + httpd_uri_t uri_calib_post = { .uri = "/api/calibration", .method = HTTP_POST, .handler = api_calibration_post_handler }; + httpd_register_uri_handler(s_http_server, &uri_calib_post); + + httpd_uri_t uri_calib_rst = { .uri = "/api/calibration/reset", .method = HTTP_POST, .handler = api_calibration_reset_handler }; + httpd_register_uri_handler(s_http_server, &uri_calib_rst); + + httpd_uri_t uri_scan = { .uri = "/api/wifi/scan", .method = HTTP_GET, .handler = api_wifi_scan_handler }; + httpd_register_uri_handler(s_http_server, &uri_scan); + + httpd_uri_t uri_wifi_conn = { .uri = "/api/wifi/connect", .method = HTTP_POST, .handler = api_wifi_connect_handler }; + httpd_register_uri_handler(s_http_server, &uri_wifi_conn); + + httpd_uri_t uri_wifi_forget = { .uri = "/api/wifi/forget", .method = HTTP_POST, .handler = api_wifi_forget_handler }; + httpd_register_uri_handler(s_http_server, &uri_wifi_forget); + + httpd_uri_t uri_exit = { .uri = "/api/exit", .method = HTTP_POST, .handler = api_exit_handler }; + httpd_register_uri_handler(s_http_server, &uri_exit); + + httpd_uri_t uri_ap_toggle = { .uri = "/api/ap/toggle", .method = HTTP_POST, .handler = api_ap_toggle_handler }; + httpd_register_uri_handler(s_http_server, &uri_ap_toggle); + + httpd_uri_t uri_ota_upload = { .uri = "/api/ota/upload", .method = HTTP_POST, .handler = api_ota_upload_handler }; + httpd_register_uri_handler(s_http_server, &uri_ota_upload); + } else { + ESP_LOGE(TAG, "Failed to start HTTP server: %s", esp_err_to_name(err)); + } + + s_is_active = true; + status_led_set_mode(LED_STATE_CONFIG_PORTAL); + + return ESP_OK; +} + +static esp_err_t config_server_stop_internal(void) +{ + if (!s_is_active) { + return ESP_OK; + } + + ESP_LOGI(TAG, "Stopping Config Server and Wi-Fi..."); + + if (s_mdns_inited) { + mdns_free(); + s_mdns_inited = false; + } + + if (s_http_server) { + httpd_stop(s_http_server); + s_http_server = NULL; + } + + dns_server_stop(); + esp_wifi_stop(); + + s_is_active = false; + s_sta_connected = false; + s_sta_ip[0] = '\0'; + + ESP_LOGI(TAG, "Wi-Fi radio stopped. Radio fully dedicated to BLE gaming with 0 latency!"); + profile_manager_refresh_led(); + + return ESP_OK; +} + +/* -------------------------------------------------------------------------- */ +/* Dedicated Config Task (Stack: 6144 bytes) */ +/* -------------------------------------------------------------------------- */ + +static void config_mgr_task(void *pvParameters) +{ + ESP_LOGI(TAG, "Config Manager Task running."); + + while (1) { + /* Sleep until command notification is received */ + ulTaskNotifyTake(pdTRUE, portMAX_DELAY); + + if (s_pending_cmd != CONFIG_CMD_NONE) { + config_cmd_t cmd = s_pending_cmd; + s_pending_cmd = CONFIG_CMD_NONE; + + if (cmd == CONFIG_CMD_TOGGLE) { + if (s_is_active) { + config_server_stop_internal(); + } else { + config_server_start_internal(); + } + } else if (cmd == CONFIG_CMD_START) { + if (!s_is_active) { + config_server_start_internal(); + } + } else if (cmd == CONFIG_CMD_STOP) { + if (s_is_active) { + config_server_stop_internal(); + } + } + } + } +} + +/* -------------------------------------------------------------------------- */ +/* Public API */ +/* -------------------------------------------------------------------------- */ + +esp_err_t config_server_init(void) +{ + if (!s_state_mutex) { + s_state_mutex = xSemaphoreCreateMutex(); + } + if (!s_config_task_handle) { + BaseType_t ret = xTaskCreatePinnedToCore(config_mgr_task, "cfg_mgr_task", 6144, NULL, 5, &s_config_task_handle, 0); + if (ret != pdPASS) { + ESP_LOGE(TAG, "Failed to create config manager task"); + return ESP_FAIL; + } + } + return ESP_OK; +} + +void config_server_request_toggle(void) +{ + s_pending_cmd = CONFIG_CMD_TOGGLE; + if (s_config_task_handle) { + xTaskNotifyGive(s_config_task_handle); + } +} + +void config_server_request_start(void) +{ + s_pending_cmd = CONFIG_CMD_START; + if (s_config_task_handle) { + xTaskNotifyGive(s_config_task_handle); + } +} + +void config_server_request_stop(void) +{ + s_pending_cmd = CONFIG_CMD_STOP; + if (s_config_task_handle) { + xTaskNotifyGive(s_config_task_handle); + } +} + +void config_server_toggle(void) +{ + config_server_request_toggle(); +} + +bool config_server_is_active(void) +{ + return s_is_active; +} + +void config_server_set_latest_state(const controller_state_t *state) +{ + if (!state || !s_state_mutex) return; + if (xSemaphoreTake(s_state_mutex, 0) == pdTRUE) { + s_latest_state = *state; + xSemaphoreGive(s_state_mutex); + } +} + +bool config_server_has_saved_wifi(void) +{ + char ssid[33] = {0}; + char pass[65] = {0}; + return read_saved_wifi_creds(ssid, sizeof(ssid), pass, sizeof(pass)); +} diff --git a/main/config_server.h b/main/config_server.h new file mode 100644 index 0000000..fee62bc --- /dev/null +++ b/main/config_server.h @@ -0,0 +1,55 @@ +#pragma once + +#include +#include +#include "esp_err.h" +#include "controller_state.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Initialize config server manager task (must be called once at boot in app_main). + */ +esp_err_t config_server_init(void); + +/** + * @brief Asynchronously request toggling the Config AP and Web Server on/off. + * Safe to call from any FreeRTOS task or interrupt context. + */ +void config_server_request_toggle(void); + +/** + * @brief Asynchronously request starting the Config AP and Web Server. + */ +void config_server_request_start(void); + +/** + * @brief Asynchronously request stopping the Config AP and Web Server. + */ +void config_server_request_stop(void); + +/** + * @brief Synchronous toggle alias for compatibility. + */ +void config_server_toggle(void); + +/** + * @brief Check if Config AP & Web Server are currently active. + */ +bool config_server_is_active(void); + +/** + * @brief Update latest controller state for web visualizer polling. + */ +void config_server_set_latest_state(const controller_state_t *state); + +/** + * @brief Check if Wi-Fi Station credentials are saved in NVS. + */ +bool config_server_has_saved_wifi(void); + +#ifdef __cplusplus +} +#endif diff --git a/main/console_output/dinput_descriptors.h b/main/console_output/dinput_descriptors.h new file mode 100644 index 0000000..64fe0ae --- /dev/null +++ b/main/console_output/dinput_descriptors.h @@ -0,0 +1,65 @@ +#pragma once + +#include +#include "tusb.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define DINPUT_VID 0x1234 +#define DINPUT_PID 0x1000 + +typedef struct __attribute__((packed)) { + uint8_t lx; /* Left Stick X: 0..255 (128 center) -> Usage X (0x30) */ + uint8_t ly; /* Left Stick Y: 0..255 (128 center) -> Usage Y (0x31) */ + uint8_t rx; /* Right Stick X: 0..255 (128 center) -> Usage Z (0x32) */ + uint8_t ry; /* Right Stick Y: 0..255 (128 center) -> Usage Rx (0x33) */ + uint8_t lt; /* Left Trigger: 0..255 (0 released) -> Usage Ry (0x34) */ + uint8_t rt; /* Right Trigger: 0..255 (0 released) -> Usage Rz (0x35) */ + uint8_t hat; /* Hat Switch: 0..7 directions, 8 centered */ + uint32_t buttons; /* 32 buttons bitmask (D-pad 12-15, System 16, Share 17) */ +} dinput_report_t; + +/* Standard 32-button, 6-axis, Hat Switch DirectInput Gamepad Report Descriptor */ +static const uint8_t dinput_hid_report_descriptor[] = { + 0x05, 0x01, // Usage Page (Generic Desktop Ctrls) + 0x09, 0x05, // Usage (Game Pad) + 0xA1, 0x01, // Collection (Application) + 0x15, 0x00, // Logical Minimum (0) + 0x26, 0xFF, 0x00, // Logical Maximum (255) + 0x75, 0x08, // Report Size (8) + 0x95, 0x06, // Report Count (6 axes) + 0x09, 0x30, // Usage (X) - Left Stick X + 0x09, 0x31, // Usage (Y) - Left Stick Y + 0x09, 0x32, // Usage (Z) - Right Stick X + 0x09, 0x33, // Usage (Rx) - Right Stick Y + 0x09, 0x34, // Usage (Ry) - Left Trigger + 0x09, 0x35, // Usage (Rz) - Right Trigger + 0x81, 0x02, // Input (Data,Var,Abs) + 0x05, 0x01, // Usage Page (Generic Desktop Ctrls) + 0x25, 0x07, // Logical Maximum (7) + 0x46, 0x3B, 0x01, // Physical Maximum (315) + 0x65, 0x14, // Unit (System: English Rotation, Degrees) + 0x75, 0x04, // Report Size (4) + 0x95, 0x01, // Report Count (1) + 0x09, 0x39, // Usage (Hat switch) + 0x81, 0x42, // Input (Data,Var,Abs,Null State) + 0x65, 0x00, // Unit (None) + 0x75, 0x04, // Report Size (4) + 0x95, 0x01, // Report Count (1) - padding + 0x81, 0x01, // Input (Const,Array,Abs) + 0x15, 0x00, // Logical Minimum (0) + 0x25, 0x01, // Logical Maximum (1) + 0x75, 0x01, // Report Size (1) + 0x95, 0x20, // Report Count (32 buttons) + 0x05, 0x09, // Usage Page (Button) + 0x19, 0x01, // Usage Minimum (0x01) + 0x29, 0x20, // Usage Maximum (0x20) + 0x81, 0x02, // Input (Data,Var,Abs) + 0xC0 // End Collection +}; + +#ifdef __cplusplus +} +#endif diff --git a/main/console_output/mouse_kb_descriptors.h b/main/console_output/mouse_kb_descriptors.h new file mode 100644 index 0000000..212336f --- /dev/null +++ b/main/console_output/mouse_kb_descriptors.h @@ -0,0 +1,101 @@ +#pragma once + +#include + +/* Standard USB HID Composite Report Descriptor: Mouse (ID 1), Keyboard (ID 2), Media (ID 3) */ +static const uint8_t mouse_kb_hid_report_descriptor[] = { + /* --- MOUSE (Report ID 1) --- */ + 0x05, 0x01, /* Usage Page (Generic Desktop) */ + 0x09, 0x02, /* Usage (Mouse) */ + 0xA1, 0x01, /* Collection (Application) */ + 0x85, 0x01, /* Report ID (1) */ + 0x09, 0x01, /* Usage (Pointer) */ + 0xA1, 0x00, /* Collection (Physical) */ + /* 5 Buttons: Left, Right, Middle, Back, Forward */ + 0x05, 0x09, /* Usage Page (Button) */ + 0x19, 0x01, /* Usage Minimum (Button 1) */ + 0x29, 0x05, /* Usage Maximum (Button 5) */ + 0x15, 0x00, /* Logical Minimum (0) */ + 0x25, 0x01, /* Logical Maximum (1) */ + 0x95, 0x05, /* Report Count (5) */ + 0x75, 0x01, /* Report Size (1) */ + 0x81, 0x02, /* Input (Data, Variable, Absolute) */ + /* Padding (3 bits) */ + 0x95, 0x01, /* Report Count (1) */ + 0x75, 0x03, /* Report Size (3) */ + 0x81, 0x03, /* Input (Constant, Variable, Absolute) */ + /* X, Y Movement (-127 to 127) */ + 0x05, 0x01, /* Usage Page (Generic Desktop) */ + 0x09, 0x30, /* Usage (X) */ + 0x09, 0x31, /* Usage (Y) */ + 0x15, 0x81, /* Logical Minimum (-127) */ + 0x25, 0x7F, /* Logical Maximum (127) */ + 0x75, 0x08, /* Report Size (8) */ + 0x95, 0x02, /* Report Count (2) */ + 0x81, 0x06, /* Input (Data, Variable, Relative) */ + /* Wheel (-127 to 127) */ + 0x09, 0x38, /* Usage (Wheel) */ + 0x15, 0x81, /* Logical Minimum (-127) */ + 0x25, 0x7F, /* Logical Maximum (127) */ + 0x75, 0x08, /* Report Size (8) */ + 0x95, 0x01, /* Report Count (1) */ + 0x81, 0x06, /* Input (Data, Variable, Relative) */ + 0xC0, /* End Collection */ + 0xC0, /* End Collection */ + + /* --- KEYBOARD (Report ID 2) --- */ + 0x05, 0x01, /* Usage Page (Generic Desktop) */ + 0x09, 0x06, /* Usage (Keyboard) */ + 0xA1, 0x01, /* Collection (Application) */ + 0x85, 0x02, /* Report ID (2) */ + /* Modifiers (8 bits: Ctrl, Shift, Alt, GUI) */ + 0x05, 0x07, /* Usage Page (Key Codes) */ + 0x19, 0xE0, /* Usage Minimum (224) */ + 0x29, 0xE7, /* Usage Maximum (231) */ + 0x15, 0x00, /* Logical Minimum (0) */ + 0x25, 0x01, /* Logical Maximum (1) */ + 0x75, 0x01, /* Report Size (1) */ + 0x95, 0x08, /* Report Count (8) */ + 0x81, 0x02, /* Input (Data, Variable, Absolute) */ + /* Reserved byte */ + 0x95, 0x01, /* Report Count (1) */ + 0x75, 0x08, /* Report Size (8) */ + 0x81, 0x03, /* Input (Constant) */ + /* Key array (6 keys) */ + 0x95, 0x06, /* Report Count (6) */ + 0x75, 0x08, /* Report Size (8) */ + 0x15, 0x00, /* Logical Minimum (0) */ + 0x25, 0xFF, /* Logical Maximum (255) */ + 0x05, 0x07, /* Usage Page (Key Codes) */ + 0x19, 0x00, /* Usage Minimum (0) */ + 0x29, 0xFF, /* Usage Maximum (255) */ + 0x81, 0x00, /* Input (Data, Array) */ + 0xC0, /* End Collection */ + + /* --- CONSUMER CONTROL / MEDIA (Report ID 3) --- */ + 0x05, 0x0C, /* Usage Page (Consumer) */ + 0x09, 0x01, /* Usage (Consumer Control) */ + 0xA1, 0x01, /* Collection (Application) */ + 0x85, 0x03, /* Report ID (3) */ + 0x15, 0x00, /* Logical Minimum (0) */ + 0x26, 0xFF, 0x03, /* Logical Maximum (0x03FF) */ + 0x19, 0x00, /* Usage Minimum (0) */ + 0x2A, 0xFF, 0x03, /* Usage Maximum (0x03FF) */ + 0x75, 0x10, /* Report Size (16) */ + 0x95, 0x01, /* Report Count (1) */ + 0x81, 0x00, /* Input (Data, Array) */ + 0xC0 /* End Collection */ +}; + +typedef struct __attribute__((packed)) { + uint8_t buttons; /* bit 0: Left, bit 1: Right, bit 2: Middle, bit 3: Back, bit 4: Forward */ + int8_t x; /* Relative X displacement */ + int8_t y; /* Relative Y displacement */ + int8_t wheel; /* Relative wheel roll */ +} mouse_report_payload_t; + +typedef struct __attribute__((packed)) { + uint8_t modifier; + uint8_t reserved; + uint8_t keycodes[6]; +} keyboard_report_payload_t; diff --git a/main/console_output/ogx_descriptors.h b/main/console_output/ogx_descriptors.h new file mode 100644 index 0000000..e3b2a91 --- /dev/null +++ b/main/console_output/ogx_descriptors.h @@ -0,0 +1,137 @@ +#pragma once + +#include +#include +#include "controller_state.h" +#include "tusb.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define OGX_VID 0x045E /* Microsoft Corp. */ +#define OGX_PID 0x0289 /* Xbox Controller S */ + +/* Digital Buttons (Byte 2 of report) */ +#define OGX_BTN_DPAD_UP (1U << 0) +#define OGX_BTN_DPAD_DOWN (1U << 1) +#define OGX_BTN_DPAD_LEFT (1U << 2) +#define OGX_BTN_DPAD_RIGHT (1U << 3) +#define OGX_BTN_START (1U << 4) +#define OGX_BTN_BACK (1U << 5) +#define OGX_BTN_L3 (1U << 6) +#define OGX_BTN_R3 (1U << 7) + +/** + * @brief Original Xbox (OG Xbox) 20-byte controller input report. + * Matches authentic XID specification and Linux xpad.c driver. + */ +typedef struct __attribute__((packed)) { + uint8_t start_byte; /* 0x00 */ + uint8_t bLength; /* 0x14 (20 bytes) */ + uint8_t dpad_digital; /* Bit 0: D-Up, 1: D-Down, 2: D-Left, 3: D-Right, 4: Start, 5: Back, 6: L3, 7: R3 */ + uint8_t reserved; /* 0x00 */ + uint8_t a; /* A button pressure: 0 or 255 */ + uint8_t b; /* B button pressure: 0 or 255 */ + uint8_t x; /* X button pressure: 0 or 255 */ + uint8_t y; /* Y button pressure: 0 or 255 */ + uint8_t black; /* Black button pressure: 0 or 255 (mapped from RB) */ + uint8_t white; /* White button pressure: 0 or 255 (mapped from LB) */ + uint8_t lt; /* Left trigger analog: 0 - 255 */ + uint8_t rt; /* Right trigger analog: 0 - 255 */ + int16_t lx; /* Left stick X (-32768 to 32767) */ + int16_t ly; /* Left stick Y (-32768 to 32767, up is positive) */ + int16_t rx; /* Right stick X (-32768 to 32767) */ + int16_t ry; /* Right stick Y (-32768 to 32767, up is positive) */ +} ogx_report_t; + +/* Device Descriptor */ +static const tusb_desc_device_t ogx_device_desc __attribute__((unused)) = { + .bLength = sizeof(tusb_desc_device_t), + .bDescriptorType = TUSB_DESC_DEVICE, + .bcdUSB = 0x0110, /* USB 1.10 */ + .bDeviceClass = 0x00, + .bDeviceSubClass = 0x00, + .bDeviceProtocol = 0x00, + .bMaxPacketSize0 = 64, + .idVendor = OGX_VID, + .idProduct = OGX_PID, + .bcdDevice = 0x0121, + .iManufacturer = 0x01, + .iProduct = 0x02, + .iSerialNumber = 0x03, + .bNumConfigurations = 0x01 +}; + +/* Configuration Descriptor (32 bytes) */ +static const uint8_t ogx_config_desc[32] __attribute__((unused)) = { + /* Configuration Descriptor (9 bytes) */ + 0x09, TUSB_DESC_CONFIGURATION, 32, 0x00, 1, 1, 0, 0x80, 50, + + /* Interface Descriptor (9 bytes): Class 0x58 (Xbox), SubClass 0x42 (Controller), Protocol 0x00 */ + 0x09, TUSB_DESC_INTERFACE, 0x00, 0x00, 0x02, 0x58, 0x42, 0x00, 0x00, + + /* Endpoint 1 IN Descriptor (7 bytes): EP 0x81, Interrupt, Max Packet 32, Interval 4ms */ + 0x07, TUSB_DESC_ENDPOINT, 0x81, 0x03, 0x20, 0x00, 0x04, + + /* Endpoint 2 OUT Descriptor (7 bytes): EP 0x02, Interrupt, Max Packet 32, Interval 4ms */ + 0x07, TUSB_DESC_ENDPOINT, 0x02, 0x03, 0x20, 0x00, 0x04, +}; + +/* 16-byte XID Descriptor returned on GET_DESCRIPTOR with wValue=0x4200 */ +static const uint8_t ogx_xid_descriptor[16] __attribute__((unused)) = { + 0x10, /* bLength = 16 bytes */ + 0x42, /* bDescriptorType = XID */ + 0x00, 0x01, /* bcdXid = 0x0100 (v1.00) */ + 0x01, /* bType = 0x01 (Game Controller) */ + 0x02, /* bSubType = 0x02 (Controller S) */ + 0x14, /* bMaxInputReportSize = 20 bytes (0x14) */ + 0x06, /* bMaxOutputReportSize = 6 bytes (0x06) */ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF /* wAlternateProductIds[4] */ +}; + +/* String Descriptors */ +static const char *ogx_string_desc[4] __attribute__((unused)) = { + (char[]){0x09, 0x04}, + "Microsoft Corporation", + "Xbox Controller S", + "000000000004" +}; + +/** + * @brief Build 20-byte OG Xbox report from normalized controller state. + */ +static inline void ogx_build_report(const controller_state_t *state, ogx_report_t *rep) +{ + memset(rep, 0, sizeof(ogx_report_t)); + rep->start_byte = 0x00; + rep->bLength = sizeof(ogx_report_t); /* 0x14 */ + + if (state->dpad_up) rep->dpad_digital |= OGX_BTN_DPAD_UP; + if (state->dpad_down) rep->dpad_digital |= OGX_BTN_DPAD_DOWN; + if (state->dpad_left) rep->dpad_digital |= OGX_BTN_DPAD_LEFT; + if (state->dpad_right) rep->dpad_digital |= OGX_BTN_DPAD_RIGHT; + if (state->btn_start) rep->dpad_digital |= OGX_BTN_START; + if (state->btn_select) rep->dpad_digital |= OGX_BTN_BACK; + if (state->btn_l3) rep->dpad_digital |= OGX_BTN_L3; + if (state->btn_r3) rep->dpad_digital |= OGX_BTN_R3; + + rep->a = state->btn_a ? 0xFF : 0x00; + rep->b = state->btn_b ? 0xFF : 0x00; + rep->x = state->btn_x ? 0xFF : 0x00; + rep->y = state->btn_y ? 0xFF : 0x00; + rep->black = state->btn_rb ? 0xFF : 0x00; /* RB -> Black button */ + rep->white = state->btn_lb ? 0xFF : 0x00; /* LB -> White button */ + + rep->lt = state->lt; + rep->rt = state->rt; + + rep->lx = state->lx; + rep->ly = state->ly; + rep->rx = state->rx; + rep->ry = state->ry; +} + +#ifdef __cplusplus +} +#endif diff --git a/main/console_output/ps4_descriptors.h b/main/console_output/ps4_descriptors.h new file mode 100644 index 0000000..f5aa971 --- /dev/null +++ b/main/console_output/ps4_descriptors.h @@ -0,0 +1,117 @@ +#pragma once + +#include + +#define PS4_VID 0x054C /* Sony Interactive Entertainment */ +#define PS4_PID 0x05C4 /* DualShock 4 Wireless Controller (USB) */ + +/* DualShock 4 Buttons Bitmask */ +#define PS4_BTN_SQUARE (1 << 4) +#define PS4_BTN_CROSS (1 << 5) +#define PS4_BTN_CIRCLE (1 << 6) +#define PS4_BTN_TRIANGLE (1 << 7) + +#define PS4_BTN_L1 (1 << 0) +#define PS4_BTN_R1 (1 << 1) +#define PS4_BTN_L2 (1 << 2) +#define PS4_BTN_R2 (1 << 3) +#define PS4_BTN_SHARE (1 << 4) +#define PS4_BTN_OPTIONS (1 << 5) +#define PS4_BTN_L3 (1 << 6) +#define PS4_BTN_R3 (1 << 7) + +#define PS4_BTN_PS (1 << 0) +#define PS4_BTN_TOUCHPAD (1 << 1) + +/* D-Pad Hat Switch (Bits 0..3) */ +#define PS4_HAT_UP 0x00 +#define PS4_HAT_UP_RIGHT 0x01 +#define PS4_HAT_RIGHT 0x02 +#define PS4_HAT_DOWN_RIGHT 0x03 +#define PS4_HAT_DOWN 0x04 +#define PS4_HAT_DOWN_LEFT 0x05 +#define PS4_HAT_LEFT 0x06 +#define PS4_HAT_UP_LEFT 0x07 +#define PS4_HAT_CENTER 0x08 + +/* DualShock 4 USB Input Report (Report ID 0x01, exactly 64 bytes) */ +typedef struct __attribute__((packed)) { + uint8_t report_id; /* 0x01 */ + uint8_t lx; /* 0..255, 128 center */ + uint8_t ly; /* 0..255, 128 center */ + uint8_t rx; /* 0..255, 128 center */ + uint8_t ry; /* 0..255, 128 center */ + uint8_t dpad_and_buttons1; /* Bits 0..3: Hat switch (0..7, 8 neutral); Bits 4..7: Square, Cross, Circle, Triangle */ + uint8_t buttons2; /* L1, R1, L2, R2, Share, Options, L3, R3 */ + uint8_t buttons3; /* Bit 0: PS Button, Bit 1: Touchpad Click, Bits 2..7: Packet counter */ + uint8_t lt; /* 0..255 Left Trigger analog */ + uint8_t rt; /* 0..255 Right Trigger analog */ + uint16_t timestamp; /* 188.43 kHz timer tick */ + uint8_t battery; /* Battery status (0x0B = 100% full, 0x1B = charging) */ + int16_t gyro_x; + int16_t gyro_y; + int16_t gyro_z; + int16_t accel_x; + int16_t accel_y; + int16_t accel_z; + uint8_t reserved[39]; +} ps4_report_t; + +/* Official DualShock 4 USB HID Report Descriptor */ +static const uint8_t ps4_hid_report_descriptor[] = { + 0x05, 0x01, // Usage Page (Generic Desktop Ctrls) + 0x09, 0x05, // Usage (Game Pad) + 0xA1, 0x01, // Collection (Application) + 0x85, 0x01, // Report ID (1) + 0x09, 0x30, // Usage (X) + 0x09, 0x31, // Usage (Y) + 0x09, 0x32, // Usage (Z) + 0x09, 0x35, // Usage (Rz) + 0x15, 0x00, // Logical Minimum (0) + 0x26, 0xFF, 0x00, // Logical Maximum (255) + 0x75, 0x08, // Report Size (8) + 0x95, 0x04, // Report Count (4) + 0x81, 0x02, // Input (Data,Var,Abs) + 0x09, 0x39, // Usage (Hat switch) + 0x15, 0x00, // Logical Minimum (0) + 0x25, 0x07, // Logical Maximum (7) + 0x35, 0x00, // Physical Minimum (0) + 0x46, 0x3B, 0x01, // Physical Maximum (315) + 0x65, 0x14, // Unit (Eng Rot:Degree) + 0x75, 0x04, // Report Size (4) + 0x95, 0x01, // Report Count (1) + 0x81, 0x42, // Input (Data,Var,Abs,Null State) + 0x65, 0x00, // Unit (None) + 0x05, 0x09, // Usage Page (Button) + 0x19, 0x01, // Usage Minimum (0x01) + 0x29, 0x0E, // Usage Maximum (0x0E) + 0x15, 0x00, // Logical Minimum (0) + 0x25, 0x01, // Logical Maximum (1) + 0x75, 0x01, // Report Size (1) + 0x95, 0x0E, // Report Count (14) + 0x81, 0x02, // Input (Data,Var,Abs) + 0x06, 0x00, 0xFF, // Usage Page (Vendor Defined 0xFF00) + 0x09, 0x20, // Usage (0x20) + 0x75, 0x06, // Report Size (6) + 0x95, 0x01, // Report Count (1) + 0x81, 0x02, // Input (Data,Var,Abs) + 0x05, 0x01, // Usage Page (Generic Desktop Ctrls) + 0x09, 0x33, // Usage (Rx) + 0x09, 0x34, // Usage (Ry) + 0x15, 0x00, // Logical Minimum (0) + 0x26, 0xFF, 0x00, // Logical Maximum (255) + 0x75, 0x08, // Report Size (8) + 0x95, 0x02, // Report Count (2) + 0x81, 0x02, // Input (Data,Var,Abs) + 0x06, 0x00, 0xFF, // Usage Page (Vendor Defined 0xFF00) + 0x09, 0x21, // Usage (0x21) + 0x75, 0x08, // Report Size (8) + 0x95, 0x36, // Report Count (54) + 0x81, 0x02, // Input (Data,Var,Abs) + 0x85, 0x05, // Report ID (5) + 0x09, 0x22, // Usage (0x22) + 0x75, 0x08, // Report Size (8) + 0x95, 0x1F, // Report Count (31) + 0x91, 0x02, // Output (Data,Var,Abs) + 0xC0 // End Collection +}; diff --git a/main/console_output/switch_descriptors.h b/main/console_output/switch_descriptors.h new file mode 100644 index 0000000..86fe273 --- /dev/null +++ b/main/console_output/switch_descriptors.h @@ -0,0 +1,96 @@ +#pragma once + +#include +#include "tusb.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define SWITCH_VID 0x0F0D /* HORI Co., Ltd. */ +#define SWITCH_PID 0x0092 /* POKKEN TOURNAMENT DX Pro Pad (Plug & Play on Switch/PC/PS3) */ + +/* Button Bitmasks for Switch */ +#define SWITCH_BTN_Y (1 << 0) +#define SWITCH_BTN_B (1 << 1) +#define SWITCH_BTN_A (1 << 2) +#define SWITCH_BTN_X (1 << 3) +#define SWITCH_BTN_L (1 << 4) +#define SWITCH_BTN_R (1 << 5) +#define SWITCH_BTN_ZL (1 << 6) +#define SWITCH_BTN_ZR (1 << 7) +#define SWITCH_BTN_MINUS (1 << 8) +#define SWITCH_BTN_PLUS (1 << 9) +#define SWITCH_BTN_LCLICK (1 << 10) +#define SWITCH_BTN_RCLICK (1 << 11) +#define SWITCH_BTN_HOME (1 << 12) +#define SWITCH_BTN_CAPTURE (1 << 13) + +#define SWITCH_HAT_UP 0 +#define SWITCH_HAT_UP_RIGHT 1 +#define SWITCH_HAT_RIGHT 2 +#define SWITCH_HAT_DOWN_RIGHT 3 +#define SWITCH_HAT_DOWN 4 +#define SWITCH_HAT_DOWN_LEFT 5 +#define SWITCH_HAT_LEFT 6 +#define SWITCH_HAT_UP_LEFT 7 +#define SWITCH_HAT_CENTER 8 + +typedef struct __attribute__((packed)) { + uint16_t buttons; + uint8_t hat; + uint8_t lx; + uint8_t ly; + uint8_t rx; + uint8_t ry; + uint8_t vendor; +} switch_report_t; + +/* Standard Switch Pokken Pad HID Report Descriptor */ +static const uint8_t switch_hid_report_descriptor[] = { + 0x05, 0x01, // Usage Page (Generic Desktop Ctrls) + 0x09, 0x05, // Usage (Game Pad) + 0xA1, 0x01, // Collection (Application) + 0x15, 0x00, // Logical Minimum (0) + 0x25, 0x01, // Logical Maximum (1) + 0x35, 0x00, // Physical Minimum (0) + 0x45, 0x01, // Physical Maximum (1) + 0x75, 0x01, // Report Size (1) + 0x95, 0x10, // Report Count (16) + 0x05, 0x09, // Usage Page (Button) + 0x19, 0x01, // Usage Minimum (0x01) + 0x29, 0x10, // Usage Maximum (0x10) + 0x81, 0x02, // Input (Data,Var,Abs) + 0x05, 0x01, // Usage Page (Generic Desktop Ctrls) + 0x25, 0x07, // Logical Maximum (7) + 0x46, 0x3B, 0x01, // Physical Maximum (315) + 0x75, 0x04, // Report Size (4) + 0x95, 0x01, // Report Count (1) + 0x65, 0x14, // Unit (System: English Rotation) + 0x09, 0x39, // Usage (Hat switch) + 0x81, 0x42, // Input (Data,Var,Abs,Null State) + 0x65, 0x00, // Unit (None) + 0x95, 0x01, // Report Count (1) + 0x81, 0x01, // Input (Const,Array,Abs) + 0x26, 0xFF, 0x00, // Logical Maximum (255) + 0x46, 0xFF, 0x00, // Physical Maximum (255) + 0x09, 0x30, // Usage (X) + 0x09, 0x31, // Usage (Y) + 0x09, 0x32, // Usage (Z) + 0x09, 0x35, // Usage (Rz) + 0x75, 0x08, // Report Size (8) + 0x95, 0x04, // Report Count (4) + 0x81, 0x02, // Input (Data,Var,Abs) + 0x06, 0x00, 0xFF, // Usage Page (Vendor Defined 0xFF00) + 0x09, 0x20, // Usage (0x20) + 0x95, 0x01, // Report Count (1) + 0x81, 0x02, // Input (Data,Var,Abs) + 0x0A, 0x21, 0x26, // Usage (0x2621) + 0x95, 0x08, // Report Count (8) + 0x91, 0x02, // Output (Data,Var,Abs) + 0xC0 // End Collection +}; + +#ifdef __cplusplus +} +#endif diff --git a/main/console_output/usb_gamepad.c b/main/console_output/usb_gamepad.c new file mode 100644 index 0000000..ffe1121 --- /dev/null +++ b/main/console_output/usb_gamepad.c @@ -0,0 +1,569 @@ +#include "usb_gamepad.h" +#include "switch_descriptors.h" +#include "dinput_descriptors.h" +#include "ogx_descriptors.h" +#include "ps4_descriptors.h" +#include "mouse_kb_descriptors.h" +#include "xinput_device.h" +#include "ble_hid_host.h" +#include "status_led.h" +#include "tinyusb.h" +#include "tusb.h" +#include "esp_log.h" +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include + +static const char *TAG = "USB_GAMEPAD"; +static console_mode_t s_active_mode = CONSOLE_MODE_SWITCH; +static bool s_driver_installed = false; + +static controller_state_t s_last_state; +static portMUX_TYPE s_state_mutex = portMUX_INITIALIZER_UNLOCKED; + +void usb_gamepad_get_last_state(controller_state_t *st) +{ + if (!st) return; + portENTER_CRITICAL(&s_state_mutex); + memcpy(st, &s_last_state, sizeof(controller_state_t)); + portEXIT_CRITICAL(&s_state_mutex); +} + +/* Device Descriptors */ +static tusb_desc_device_t s_device_desc = { + .bLength = sizeof(tusb_desc_device_t), + .bDescriptorType = TUSB_DESC_DEVICE, + .bcdUSB = 0x0200, + .bDeviceClass = 0x00, + .bDeviceSubClass = 0x00, + .bDeviceProtocol = 0x00, + .bMaxPacketSize0 = 64, + .idVendor = SWITCH_VID, + .idProduct = SWITCH_PID, + .bcdDevice = 0x0100, + .iManufacturer = 0x01, + .iProduct = 0x02, + .iSerialNumber = 0x03, + .bNumConfigurations = 0x01 +}; + +/* String Descriptors */ +static const char *s_string_desc_switch[] = { + (char[]){0x09, 0x04}, /* Supported language: English (0x0409) */ + "HORI CO.,LTD.", /* Manufacturer */ + "POKKEN TOURNAMENT DX Pro Pad", /* Product */ + "000000000001" /* Serial */ +}; + +static const char *s_string_desc_pc[] = { + (char[]){0x09, 0x04}, + "Generic USB", + "PC Game Controller", + "000000000002" +}; + +static const char *s_string_desc_ps3[] = { + (char[]){0x09, 0x04}, + "Sony Computer Entertainment", + "PS3 Game Controller", + "000000000003" +}; + +static const char *s_string_desc_ps4[] = { + (char[]){0x09, 0x04}, + "Sony Interactive Entertainment", + "Wireless Controller", + "000000000004" +}; + +/* Full Speed Configuration Descriptors (34 / 41 bytes) */ +static uint8_t s_config_desc_switch[34] = { + /* Configuration Descriptor (9 bytes) */ + 0x09, TUSB_DESC_CONFIGURATION, 34, 0x00, 1, 1, 0, 0x80, 50, + /* Interface Descriptor (9 bytes) */ + 0x09, TUSB_DESC_INTERFACE, 0, 0, 1, TUSB_CLASS_HID, 0, 0, 0, + /* HID Descriptor (9 bytes) */ + 0x09, 0x21, 0x11, 0x01, 0, 1, 0x22, (sizeof(switch_hid_report_descriptor) & 0xFF), ((sizeof(switch_hid_report_descriptor) >> 8) & 0xFF), + /* Endpoint IN Descriptor (7 bytes) */ + 0x07, TUSB_DESC_ENDPOINT, 0x81, 0x03, 64, 0x00, 8 +}; + +static uint8_t s_config_desc_pc[34] = { + 0x09, TUSB_DESC_CONFIGURATION, 34, 0x00, 1, 1, 0, 0x80, 50, + 0x09, TUSB_DESC_INTERFACE, 0, 0, 1, TUSB_CLASS_HID, 0, 0, 0, + 0x09, 0x21, 0x11, 0x01, 0, 1, 0x22, (sizeof(dinput_hid_report_descriptor) & 0xFF), ((sizeof(dinput_hid_report_descriptor) >> 8) & 0xFF), + 0x07, TUSB_DESC_ENDPOINT, 0x81, 0x03, 64, 0x00, 8 +}; + +static uint8_t s_config_desc_ps4[41] = { + /* Configuration Descriptor (9 bytes) */ + 0x09, TUSB_DESC_CONFIGURATION, 41, 0x00, 1, 1, 0, 0xC0, 250, + /* Interface Descriptor (9 bytes) */ + 0x09, TUSB_DESC_INTERFACE, 0, 0, 2, TUSB_CLASS_HID, 0, 0, 0, + /* HID Descriptor (9 bytes) */ + 0x09, 0x21, 0x11, 0x01, 0, 1, 0x22, (sizeof(ps4_hid_report_descriptor) & 0xFF), ((sizeof(ps4_hid_report_descriptor) >> 8) & 0xFF), + /* Endpoint IN Descriptor (7 bytes) */ + 0x07, TUSB_DESC_ENDPOINT, 0x81, 0x03, 64, 0x00, 4, + /* Endpoint OUT Descriptor (7 bytes) */ + 0x07, TUSB_DESC_ENDPOINT, 0x01, 0x03, 64, 0x00, 4 +}; + +static uint8_t s_config_desc_mouse_kb[34] = { + 0x09, TUSB_DESC_CONFIGURATION, 34, 0x00, 1, 1, 0, 0xA0, 50, + 0x09, TUSB_DESC_INTERFACE, 0, 0, 1, TUSB_CLASS_HID, 0, 0, 0, + 0x09, 0x21, 0x11, 0x01, 0, 1, 0x22, (sizeof(mouse_kb_hid_report_descriptor) & 0xFF), ((sizeof(mouse_kb_hid_report_descriptor) >> 8) & 0xFF), + 0x07, TUSB_DESC_ENDPOINT, 0x81, 0x03, 16, 0x00, 8 +}; + +static char const *s_string_desc_mouse_kb[] = { + (const char[]){ 0x09, 0x04 }, /* 0: Language English */ + "Antigravity", /* 1: Manufacturer */ + "Couch Mouse & Keyboard", /* 2: Product */ + "1.0.0", /* 3: Serial */ +}; + +/* --- TinyUSB Application Callbacks --- */ + +uint8_t const * tud_hid_descriptor_report_cb(uint8_t instance) +{ + (void)instance; + if (s_active_mode == CONSOLE_MODE_SWITCH) { + return switch_hid_report_descriptor; + } else if (s_active_mode == CONSOLE_MODE_PS4) { + return ps4_hid_report_descriptor; + } else if (s_active_mode == CONSOLE_MODE_MOUSE_KB) { + return mouse_kb_hid_report_descriptor; + } else if (s_active_mode == CONSOLE_MODE_XBOX360 || s_active_mode == CONSOLE_MODE_XBOXOG) { + return NULL; + } else { + return dinput_hid_report_descriptor; + } +} + +static void build_switch_report(const controller_state_t *state, switch_report_t *rep) +{ + memset(rep, 0, sizeof(switch_report_t)); + + /* Buttons */ + if (state->btn_y) rep->buttons |= SWITCH_BTN_Y; + if (state->btn_b) rep->buttons |= SWITCH_BTN_B; + if (state->btn_a) rep->buttons |= SWITCH_BTN_A; + if (state->btn_x) rep->buttons |= SWITCH_BTN_X; + if (state->btn_lb) rep->buttons |= SWITCH_BTN_L; + if (state->btn_rb) rep->buttons |= SWITCH_BTN_R; + if (state->btn_lt) rep->buttons |= SWITCH_BTN_ZL; + if (state->btn_rt) rep->buttons |= SWITCH_BTN_ZR; + if (state->btn_select) rep->buttons |= SWITCH_BTN_MINUS; + if (state->btn_start) rep->buttons |= SWITCH_BTN_PLUS; + if (state->btn_l3) rep->buttons |= SWITCH_BTN_LCLICK; + if (state->btn_r3) rep->buttons |= SWITCH_BTN_RCLICK; + if (state->btn_system) rep->buttons |= SWITCH_BTN_HOME; + if (state->btn_share) rep->buttons |= SWITCH_BTN_CAPTURE; + + /* Hat Switch (D-Pad) */ + if (state->dpad_up && state->dpad_right) rep->hat = SWITCH_HAT_UP_RIGHT; + else if (state->dpad_down && state->dpad_right) rep->hat = SWITCH_HAT_DOWN_RIGHT; + else if (state->dpad_down && state->dpad_left) rep->hat = SWITCH_HAT_DOWN_LEFT; + else if (state->dpad_up && state->dpad_left) rep->hat = SWITCH_HAT_UP_LEFT; + else if (state->dpad_up) rep->hat = SWITCH_HAT_UP; + else if (state->dpad_right) rep->hat = SWITCH_HAT_RIGHT; + else if (state->dpad_down) rep->hat = SWITCH_HAT_DOWN; + else if (state->dpad_left) rep->hat = SWITCH_HAT_LEFT; + else rep->hat = SWITCH_HAT_CENTER; + + /* Sticks: 0..255, 128 center, Y axis inverted: 0 is top */ + rep->lx = (uint8_t)(((int32_t)state->lx + 32768) >> 8); + rep->ly = (uint8_t)(((int32_t)32767 - state->ly) >> 8); + rep->rx = (uint8_t)(((int32_t)state->rx + 32768) >> 8); + rep->ry = (uint8_t)(((int32_t)32767 - state->ry) >> 8); + rep->vendor = 0x00; +} + +static void build_dinput_report(const controller_state_t *state, dinput_report_t *rep) +{ + memset(rep, 0, sizeof(dinput_report_t)); + + /* Sticks: X (lx), Y (ly), Rx (rx), Ry (ry) */ + rep->lx = (uint8_t)(((int32_t)state->lx + 32768) >> 8); + rep->ly = (uint8_t)(((int32_t)32767 - state->ly) >> 8); + rep->rx = (uint8_t)(((int32_t)state->rx + 32768) >> 8); + rep->ry = (uint8_t)(((int32_t)32767 - state->ry) >> 8); + + /* Triggers: Z (lt), Rz (rt) */ + rep->lt = state->lt; + rep->rt = state->rt; + + /* Hat: 0..7 directions, 8 neutral */ + if (state->dpad_up && state->dpad_right) rep->hat = 1; + else if (state->dpad_right && state->dpad_down) rep->hat = 3; + else if (state->dpad_down && state->dpad_left) rep->hat = 5; + else if (state->dpad_left && state->dpad_up) rep->hat = 7; + else if (state->dpad_up) rep->hat = 0; + else if (state->dpad_right) rep->hat = 2; + else if (state->dpad_down) rep->hat = 4; + else if (state->dpad_left) rep->hat = 6; + else rep->hat = 8; + + /* Buttons bitmask: Standard Gamepad API ordering */ + if (state->btn_a) rep->buttons |= (1UL << 0); + if (state->btn_b) rep->buttons |= (1UL << 1); + if (state->btn_x) rep->buttons |= (1UL << 2); + if (state->btn_y) rep->buttons |= (1UL << 3); + if (state->btn_lb) rep->buttons |= (1UL << 4); + if (state->btn_rb) rep->buttons |= (1UL << 5); + if (state->btn_lt) rep->buttons |= (1UL << 6); + if (state->btn_rt) rep->buttons |= (1UL << 7); + if (state->btn_select) rep->buttons |= (1UL << 8); + if (state->btn_start) rep->buttons |= (1UL << 9); + if (state->btn_l3) rep->buttons |= (1UL << 10); + if (state->btn_r3) rep->buttons |= (1UL << 11); + /* Buttons 12-15: Standard D-Pad buttons */ + if (state->dpad_up) rep->buttons |= (1UL << 12); + if (state->dpad_down) rep->buttons |= (1UL << 13); + if (state->dpad_left) rep->buttons |= (1UL << 14); + if (state->dpad_right) rep->buttons |= (1UL << 15); + /* Buttons 16-17: System / Guide / Home and Share / Capture */ + if (state->btn_system) rep->buttons |= (1UL << 16); + if (state->btn_share) rep->buttons |= (1UL << 17); +} + +static void build_ps4_report(const controller_state_t *state, ps4_report_t *rep) +{ + static uint16_t timer_tick = 0; + static uint8_t packet_counter = 0; + + memset(rep, 0, sizeof(ps4_report_t)); + rep->report_id = 0x01; + + /* Sticks: 0..255, 128 center, Y axis: 0 is top */ + rep->lx = (uint8_t)(((int32_t)state->lx + 32768) >> 8); + rep->ly = (uint8_t)(((int32_t)32767 - state->ly) >> 8); + rep->rx = (uint8_t)(((int32_t)state->rx + 32768) >> 8); + rep->ry = (uint8_t)(((int32_t)32767 - state->ry) >> 8); + + /* Hat Switch (D-Pad) */ + uint8_t hat = PS4_HAT_CENTER; + if (state->dpad_up && state->dpad_right) hat = PS4_HAT_UP_RIGHT; + else if (state->dpad_down && state->dpad_right) hat = PS4_HAT_DOWN_RIGHT; + else if (state->dpad_down && state->dpad_left) hat = PS4_HAT_DOWN_LEFT; + else if (state->dpad_up && state->dpad_left) hat = PS4_HAT_UP_LEFT; + else if (state->dpad_up) hat = PS4_HAT_UP; + else if (state->dpad_right) hat = PS4_HAT_RIGHT; + else if (state->dpad_down) hat = PS4_HAT_DOWN; + else if (state->dpad_left) hat = PS4_HAT_LEFT; + + rep->dpad_and_buttons1 = hat & 0x0F; + + /* Face buttons (Square, Cross, Circle, Triangle) */ + if (state->btn_x) rep->dpad_and_buttons1 |= PS4_BTN_SQUARE; + if (state->btn_a) rep->dpad_and_buttons1 |= PS4_BTN_CROSS; + if (state->btn_b) rep->dpad_and_buttons1 |= PS4_BTN_CIRCLE; + if (state->btn_y) rep->dpad_and_buttons1 |= PS4_BTN_TRIANGLE; + + /* Shoulder buttons & Menu */ + if (state->btn_lb) rep->buttons2 |= PS4_BTN_L1; + if (state->btn_rb) rep->buttons2 |= PS4_BTN_R1; + if (state->btn_lt) rep->buttons2 |= PS4_BTN_L2; + if (state->btn_rt) rep->buttons2 |= PS4_BTN_R2; + if (state->btn_select) rep->buttons2 |= PS4_BTN_SHARE; + if (state->btn_start) rep->buttons2 |= PS4_BTN_OPTIONS; + if (state->btn_l3) rep->buttons2 |= PS4_BTN_L3; + if (state->btn_r3) rep->buttons2 |= PS4_BTN_R3; + + /* System & Touchpad buttons */ + if (state->btn_system) rep->buttons3 |= PS4_BTN_PS; + /* Map Share / Capture button to Touchpad Click */ + if (state->btn_share) rep->buttons3 |= PS4_BTN_TOUCHPAD; + + /* Rolling packet counter */ + rep->buttons3 |= ((packet_counter++ & 0x3F) << 2); + + /* Analog triggers (0..255) */ + rep->lt = state->lt; + rep->rt = state->rt; + + /* Timestamp and battery */ + rep->timestamp = timer_tick++; + rep->battery = 0x0B; /* 100% full, cable connected */ + + /* Touchpad packet (finger not touching: bit 7 = 1) */ + rep->reserved[10] = 0x01; + rep->reserved[11] = 0x80; + rep->reserved[15] = 0x80; +} + +uint16_t tud_hid_get_report_cb(uint8_t instance, uint8_t report_id, hid_report_type_t report_type, uint8_t* buffer, uint16_t reqlen) +{ + (void)instance; + (void)report_id; + (void)report_type; + + controller_state_t current; + portENTER_CRITICAL(&s_state_mutex); + memcpy(¤t, &s_last_state, sizeof(controller_state_t)); + portEXIT_CRITICAL(&s_state_mutex); + + if (s_active_mode == CONSOLE_MODE_SWITCH) { + switch_report_t rep; + build_switch_report(¤t, &rep); + uint16_t copy_len = (reqlen < sizeof(rep)) ? reqlen : sizeof(rep); + memcpy(buffer, &rep, copy_len); + return copy_len; + } else if (s_active_mode == CONSOLE_MODE_PS4) { + ps4_report_t rep; + build_ps4_report(¤t, &rep); + uint16_t copy_len = (reqlen < sizeof(rep)) ? reqlen : sizeof(rep); + memcpy(buffer, &rep, copy_len); + return copy_len; + } else { + dinput_report_t rep; + build_dinput_report(¤t, &rep); + uint16_t copy_len = (reqlen < sizeof(rep)) ? reqlen : sizeof(rep); + memcpy(buffer, &rep, copy_len); + return copy_len; + } +} + +void tud_hid_set_report_cb(uint8_t instance, uint8_t report_id, hid_report_type_t report_type, uint8_t const* buffer, uint16_t bufsize) +{ + (void)instance; + (void)report_id; + if (report_type == HID_REPORT_TYPE_OUTPUT && buffer && bufsize > 0) { + if (s_active_mode == CONSOLE_MODE_PS3) { + /* PS3 DualShock 3 Output Report: + * Byte 2 = Right small motor (0 or 1 on/off) + * Byte 4 = Left large motor (0-255) + */ + if (bufsize >= 5) { + uint8_t light = buffer[2] ? 255 : 0; + uint8_t heavy = buffer[4]; + ble_hid_host_send_rumble(heavy, light); + } + } else if (s_active_mode == CONSOLE_MODE_PC_DINPUT) { + /* PC Generic Output Report: [heavy, light] */ + if (bufsize >= 2) { + ble_hid_host_send_rumble(buffer[0], buffer[1]); + } + } else if (s_active_mode == CONSOLE_MODE_PS4) { + /* PS4 DualShock 4 Output Report (Report ID 0x05): + * If buffer[0] == 0x05: + * buffer[4] = Light / small motor (0-255) + * buffer[5] = Heavy / large motor (0-255) + * buffer[6] = Lightbar Red (0-255) + * buffer[7] = Lightbar Green (0-255) + * buffer[8] = Lightbar Blue (0-255) + */ + size_t off = (buffer[0] == 0x05) ? 1 : 0; + if (bufsize >= off + 8) { + uint8_t light = buffer[off + 3]; + uint8_t heavy = buffer[off + 4]; + ble_hid_host_send_rumble(heavy, light); + + uint8_t r = buffer[off + 5]; + uint8_t g = buffer[off + 6]; + uint8_t b = buffer[off + 7]; + if (r > 0 || g > 0 || b > 0) { + status_led_flash_color(r, g, b, 2000); + } + } + } + } +} + +/* Background task ensuring reports are constantly streamed to prevent uninitialized host reads */ +static void usb_stream_task(void *pvParameters) +{ + while (1) { + if (tud_mounted()) { + controller_state_t current; + portENTER_CRITICAL(&s_state_mutex); + memcpy(¤t, &s_last_state, sizeof(controller_state_t)); + portEXIT_CRITICAL(&s_state_mutex); + + if (s_active_mode == CONSOLE_MODE_XBOX360) { + xinput_in_report_t rep; + xinput_device_build_report(¤t, &rep); + xinput_device_send_report(&rep); + } else if (s_active_mode == CONSOLE_MODE_XBOXOG) { + ogx_report_t rep; + ogx_build_report(¤t, &rep); + ogx_device_send_report(&rep, sizeof(rep)); + } else if (tud_hid_ready()) { + if (s_active_mode == CONSOLE_MODE_SWITCH) { + switch_report_t rep; + build_switch_report(¤t, &rep); + tud_hid_report(0, &rep, sizeof(rep)); + } else if (s_active_mode == CONSOLE_MODE_PS4) { + ps4_report_t rep; + build_ps4_report(¤t, &rep); + tud_hid_report(0, &rep, sizeof(rep)); + } else if (s_active_mode == CONSOLE_MODE_MOUSE_KB) { + /* Mouse movement calculation */ + int16_t lx = current.lx; + int16_t ly = current.ly; + int8_t dx = 0, dy = 0; + if (abs(lx) > 3000) { + int val = (lx > 0 ? (lx - 3000) : (lx + 3000)) / 2200; + if (val > 120) val = 120; + if (val < -120) val = -120; + dx = (int8_t)val; + } + if (abs(ly) > 3000) { + int val = -(ly > 0 ? (ly - 3000) : (ly + 3000)) / 2200; + if (val > 120) val = 120; + if (val < -120) val = -120; + dy = (int8_t)val; + } + + int8_t wheel = 0; + int16_t ry = current.ry; + if (abs(ry) > 6000) { + wheel = (ry > 0 ? 1 : -1) * (abs(ry) > 18000 ? 2 : 1); + } + + uint8_t btns = 0; + if (current.btn_a || current.btn_lt || current.btn_lb) btns |= 0x01; /* Left Click */ + if (current.btn_b || current.btn_rt || current.btn_rb) btns |= 0x02; /* Right Click */ + if (current.btn_l3 || current.btn_x) btns |= 0x04; /* Middle Click */ + + mouse_report_payload_t m_rep = { + .buttons = btns, + .x = dx, + .y = dy, + .wheel = wheel + }; + tud_hid_report(1, &m_rep, sizeof(m_rep)); + + /* Keyboard / Navigation keys */ + keyboard_report_payload_t k_rep = {0}; + uint8_t k_idx = 0; + if (current.dpad_up && k_idx < 6) k_rep.keycodes[k_idx++] = 0x52; /* Up Arrow */ + if (current.dpad_down && k_idx < 6) k_rep.keycodes[k_idx++] = 0x51; /* Down Arrow */ + if (current.dpad_left && k_idx < 6) k_rep.keycodes[k_idx++] = 0x50; /* Left Arrow */ + if (current.dpad_right && k_idx < 6) k_rep.keycodes[k_idx++] = 0x4F; /* Right Arrow */ + if (current.btn_y && k_idx < 6) k_rep.keycodes[k_idx++] = 0x28; /* Enter */ + if (current.btn_select && k_idx < 6) k_rep.keycodes[k_idx++] = 0x2C; /* Space */ + if (current.btn_start && k_idx < 6) k_rep.keycodes[k_idx++] = 0x29; /* Escape */ + + static uint8_t s_last_k_keys[6] = {0}; + if (memcmp(s_last_k_keys, k_rep.keycodes, 6) != 0) { + memcpy(s_last_k_keys, k_rep.keycodes, 6); + tud_hid_report(2, &k_rep, sizeof(k_rep)); + } + } else { + dinput_report_t rep; + build_dinput_report(¤t, &rep); + tud_hid_report(0, &rep, sizeof(rep)); + } + } + } + vTaskDelay(pdMS_TO_TICKS(10)); + } +} + +/* --- Public API --- */ + +esp_err_t usb_gamepad_init(console_mode_t initial_mode) +{ + s_active_mode = initial_mode; + + /* Initialize last state to neutral */ + portENTER_CRITICAL(&s_state_mutex); + controller_state_reset(&s_last_state); + portEXIT_CRITICAL(&s_state_mutex); + + tinyusb_config_t tusb_cfg = { + .device_descriptor = &s_device_desc, + .string_descriptor = s_string_desc_pc, + .string_descriptor_count = 4, + .external_phy = false, + .configuration_descriptor = s_config_desc_pc, + }; + + if (s_active_mode == CONSOLE_MODE_SWITCH) { + s_device_desc.idVendor = SWITCH_VID; + s_device_desc.idProduct = SWITCH_PID; + tusb_cfg.string_descriptor = s_string_desc_switch; + tusb_cfg.configuration_descriptor = s_config_desc_switch; + } else if (s_active_mode == CONSOLE_MODE_PS4) { + s_device_desc.idVendor = PS4_VID; + s_device_desc.idProduct = PS4_PID; + tusb_cfg.string_descriptor = s_string_desc_ps4; + tusb_cfg.configuration_descriptor = s_config_desc_ps4; + } else if (s_active_mode == CONSOLE_MODE_MOUSE_KB) { + s_device_desc.idVendor = 0x046D; /* Logitech */ + s_device_desc.idProduct = 0xC52B; /* Wireless Receiver */ + tusb_cfg.string_descriptor = s_string_desc_mouse_kb; + tusb_cfg.configuration_descriptor = s_config_desc_mouse_kb; + } else if (s_active_mode == CONSOLE_MODE_PS3) { + s_device_desc.idVendor = 0x054C; /* Sony PS3 */ + s_device_desc.idProduct = 0x0268; + tusb_cfg.string_descriptor = s_string_desc_ps3; + tusb_cfg.configuration_descriptor = s_config_desc_pc; + } else if (s_active_mode == CONSOLE_MODE_XBOX360) { + xinput_device_init(); + tusb_cfg.device_descriptor = &xinput_device_desc; + tusb_cfg.configuration_descriptor = xinput_config_desc; + tusb_cfg.string_descriptor = xinput_string_desc; + tusb_cfg.string_descriptor_count = 5; + } else if (s_active_mode == CONSOLE_MODE_XBOXOG) { + ogx_device_init(); + tusb_cfg.device_descriptor = &ogx_device_desc; + tusb_cfg.configuration_descriptor = ogx_config_desc; + tusb_cfg.string_descriptor = ogx_string_desc; + tusb_cfg.string_descriptor_count = 4; + } else { + s_device_desc.idVendor = DINPUT_VID; + s_device_desc.idProduct = DINPUT_PID; + tusb_cfg.string_descriptor = s_string_desc_pc; + tusb_cfg.configuration_descriptor = s_config_desc_pc; + } + + esp_err_t err = tinyusb_driver_install(&tusb_cfg); + if (err != ESP_OK) { + ESP_LOGE(TAG, "TinyUSB install failed: %s", esp_err_to_name(err)); + return err; + } + + s_driver_installed = true; + ESP_LOGI(TAG, "USB Gamepad initialized in mode: %s (VID:0x%04X PID:0x%04X)", + profile_manager_mode_name(s_active_mode), + tusb_cfg.device_descriptor->idVendor, + tusb_cfg.device_descriptor->idProduct); + + static bool task_created = false; + if (!task_created) { + /* Pin real-time USB transmission to Core 1 (APP CPU) with high priority */ + xTaskCreatePinnedToCore(usb_stream_task, "usb_stream_task", 4096, NULL, 6, NULL, 1); + task_created = true; + } + + return ESP_OK; +} + +esp_err_t usb_gamepad_change_mode(console_mode_t new_mode) +{ + if (s_driver_installed) { + ESP_LOGI(TAG, "Re-enumerating USB for new console profile..."); + tinyusb_driver_uninstall(); + s_driver_installed = false; + vTaskDelay(pdMS_TO_TICKS(200)); + } + return usb_gamepad_init(new_mode); +} + +bool usb_gamepad_is_mounted(void) +{ + return tud_mounted(); +} + +esp_err_t usb_gamepad_send_state(const controller_state_t *state) +{ + if (!state) return ESP_ERR_INVALID_ARG; + + portENTER_CRITICAL(&s_state_mutex); + memcpy(&s_last_state, state, sizeof(controller_state_t)); + portEXIT_CRITICAL(&s_state_mutex); + + return ESP_OK; +} diff --git a/main/console_output/usb_gamepad.h b/main/console_output/usb_gamepad.h new file mode 100644 index 0000000..a4706d5 --- /dev/null +++ b/main/console_output/usb_gamepad.h @@ -0,0 +1,35 @@ +#pragma once + +#include +#include +#include "esp_err.h" +#include "controller_state.h" +#include "profile_manager.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Initialize USB Gamepad emulation with the specified console mode. + */ +esp_err_t usb_gamepad_init(console_mode_t initial_mode); + +/** + * @brief Reconfigure USB descriptors and re-enumerate for a new console mode. + */ +esp_err_t usb_gamepad_change_mode(console_mode_t new_mode); + +/** + * @brief Translate and send normalized controller state to the host console. + */ +esp_err_t usb_gamepad_send_state(const controller_state_t *state); + +/** + * @brief Check if USB device is mounted and ready to transmit reports. + */ +bool usb_gamepad_is_mounted(void); + +#ifdef __cplusplus +} +#endif diff --git a/main/console_output/xinput_device.c b/main/console_output/xinput_device.c new file mode 100644 index 0000000..258780d --- /dev/null +++ b/main/console_output/xinput_device.c @@ -0,0 +1,497 @@ +#include "xinput_device.h" +#include "ogx_descriptors.h" +#include "xsm3.h" +#include "profile_manager.h" +#include "ble_hid_host.h" +#include "esp_log.h" +#include "esp_mac.h" +#include "device/usbd_pvt.h" +#include +#include + +extern void usb_gamepad_get_last_state(controller_state_t *st); + +static const char *TAG = "XINPUT_DEV"; + +#define XINPUT_ENDPOINT_SIZE 32 +#define DESC_TYPE_VENDOR 0x21 +#define DESC_TYPE_SEC 0x41 + +/* Device Descriptor */ +const tusb_desc_device_t xinput_device_desc = { + .bLength = sizeof(tusb_desc_device_t), + .bDescriptorType = TUSB_DESC_DEVICE, + .bcdUSB = 0x0200, + .bDeviceClass = 0xFF, + .bDeviceSubClass = 0xFF, + .bDeviceProtocol = 0xFF, + .bMaxPacketSize0 = 64, + .idVendor = XINPUT_VID, /* 0x045E */ + .idProduct = XINPUT_PID, /* 0x028E */ + .bcdDevice = 0x0114, + .iManufacturer = 0x01, + .iProduct = 0x02, + .iSerialNumber = 0x03, + .bNumConfigurations = 0x01 +}; + +/* Configuration Descriptor (153 bytes) - Authentic Xbox 360 Wired Controller */ +const uint8_t xinput_config_desc[153] = { + // Configuration descriptor (9 bytes) + 0x09, 0x02, 0x99, 0x00, 0x04, 0x01, 0x00, 0xA0, 0xFA, + + // ---- Interface 0: Gamepad (SubClass 0x5D, Protocol 0x01) ---- + 0x09, 0x04, 0x00, 0x00, 0x02, 0xFF, 0x5D, 0x01, 0x00, + 0x11, 0x21, 0x00, 0x01, 0x01, 0x25, 0x81, 0x14, + 0x00, 0x00, 0x00, 0x00, 0x13, 0x02, 0x08, 0x00, 0x00, + 0x07, 0x05, 0x81, 0x03, 0x20, 0x00, 0x04, + 0x07, 0x05, 0x02, 0x03, 0x20, 0x00, 0x08, + + // ---- Interface 1: Audio (SubClass 0x5D, Protocol 0x03) ---- + 0x09, 0x04, 0x01, 0x00, 0x04, 0xFF, 0x5D, 0x03, 0x00, + 0x1B, 0x21, 0x00, 0x01, 0x01, 0x01, 0x83, 0x40, + 0x01, 0x04, 0x20, 0x16, 0x85, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x16, 0x06, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, + 0x07, 0x05, 0x83, 0x03, 0x20, 0x00, 0x02, + 0x07, 0x05, 0x04, 0x03, 0x20, 0x00, 0x04, + 0x07, 0x05, 0x85, 0x03, 0x20, 0x00, 0x40, + 0x07, 0x05, 0x06, 0x03, 0x20, 0x00, 0x10, + + // ---- Interface 2: Plugin Module (SubClass 0x5D, Protocol 0x02) ---- + 0x09, 0x04, 0x02, 0x00, 0x01, 0xFF, 0x5D, 0x02, 0x00, + 0x09, 0x21, 0x00, 0x01, 0x01, 0x22, 0x86, 0x03, 0x00, + 0x07, 0x05, 0x86, 0x03, 0x20, 0x00, 0x10, + + // ---- Interface 3: Security (SubClass 0xFD, Protocol 0x13), iInterface=4 ---- + 0x09, 0x04, 0x03, 0x00, 0x00, 0xFF, 0xFD, 0x13, 0x04, + 0x06, 0x41, 0x00, 0x01, 0x01, 0x03, +}; + +static char s_usb_serial[13] = "000000000000"; + +const char *xinput_string_desc[5] = { + (char[]){0x09, 0x04}, + "\xa9Microsoft Corporation", + "Xbox 360 Controller", + s_usb_serial, + "Xbox Security Method 3, Version 1.00, \xa9 2005 Microsoft Corporation. All rights reserved." +}; + +/* State and Buffers */ +static uint8_t s_endpoint_in = 0xFF; +static uint8_t s_endpoint_out = 0xFF; +static uint8_t s_ep_in_buffer[XINPUT_ENDPOINT_SIZE]; +static uint8_t s_ep_out_buffer[XINPUT_ENDPOINT_SIZE]; + +typedef enum { + XSM3_AUTH_STATE_IDLE = 0, + XSM3_AUTH_STATE_RESPONDED = 2, + XSM3_AUTH_STATE_AUTHENTICATED = 4, +} xsm3_auth_state_t; + +static volatile xsm3_auth_state_t s_xsm3_auth_state = XSM3_AUTH_STATE_IDLE; +static uint8_t s_xsm3_identification[0x1D]; +static uint8_t s_xsm3_buf_82[0x22]; +static uint8_t s_xsm3_buf_87[0x16]; +static uint8_t s_xsm3_state_buf[2] = { 0x01, 0x00 }; +static bool s_identity_initialized = false; + +static void init_xsm3_identity(void) +{ + if (s_identity_initialized) return; + + xsm3_initialise_state(); + + uint8_t mac[6]; + esp_efuse_mac_get_default(mac); + snprintf(s_usb_serial, sizeof(s_usb_serial), "%02X%02X%02X%02X%02X%02X", + mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); + + memcpy(s_xsm3_identification, xsm3_id_data_ms_controller, sizeof(s_xsm3_identification)); + memcpy(&s_xsm3_identification[0x05], s_usb_serial, 12); + + /* Calculate XOR checksum of packet starting at offset 5 */ + uint8_t packet_end = s_xsm3_identification[4] + 5; + uint8_t checksum = 0; + for (uint8_t i = 5; i < packet_end; ++i) { + checksum ^= s_xsm3_identification[i]; + } + s_xsm3_identification[0x1C] = checksum; + + xsm3_set_identification_data(s_xsm3_identification); + s_identity_initialized = true; + + ESP_LOGI(TAG, "XSM3 Identity ready: Serial=%s Checksum=0x%02X", s_usb_serial, checksum); +} + +void xinput_device_init(void) +{ + s_endpoint_in = 0xFF; + s_endpoint_out = 0xFF; + s_xsm3_auth_state = XSM3_AUTH_STATE_IDLE; + memset(s_ep_in_buffer, 0, sizeof(s_ep_in_buffer)); + memset(s_ep_out_buffer, 0, sizeof(s_ep_out_buffer)); + + init_xsm3_identity(); +} + +static bool xinput_deinit(void) +{ + s_endpoint_in = 0xFF; + s_endpoint_out = 0xFF; + return true; +} + +static void xinput_reset(uint8_t rhport) +{ + (void)rhport; + s_endpoint_in = 0xFF; + s_endpoint_out = 0xFF; + s_xsm3_auth_state = XSM3_AUTH_STATE_IDLE; +} + +static uint16_t xinput_open(uint8_t rhport, tusb_desc_interface_t const *itf_desc, uint16_t max_len) +{ + /* Claim vendor-class interfaces: Xbox 360 (0xFF) and Original Xbox (0x58) */ + if (itf_desc->bInterfaceClass != 0xFF && itf_desc->bInterfaceClass != 0x58) { + return 0; + } + + uint16_t drv_len = sizeof(tusb_desc_interface_t); + uint8_t const *p_desc = tu_desc_next((uint8_t const*)itf_desc); + + /* Original Xbox: Interface Class 0x58, SubClass 0x42 */ + if (itf_desc->bInterfaceClass == 0x58 && itf_desc->bInterfaceSubClass == 0x42) { + for (uint8_t i = 0; i < itf_desc->bNumEndpoints; i++) { + tusb_desc_endpoint_t const *ep_desc = (tusb_desc_endpoint_t const *)p_desc; + if (TUSB_DESC_ENDPOINT != tu_desc_type(ep_desc)) break; + TU_VERIFY(usbd_edpt_open(rhport, ep_desc), 0); + if (tu_edpt_dir(ep_desc->bEndpointAddress) == TUSB_DIR_IN) { + s_endpoint_in = ep_desc->bEndpointAddress; + } else { + s_endpoint_out = ep_desc->bEndpointAddress; + } + drv_len += sizeof(tusb_desc_endpoint_t); + p_desc = tu_desc_next(p_desc); + } + if (s_endpoint_out != 0xFF) { + usbd_edpt_xfer(rhport, s_endpoint_out, s_ep_out_buffer, XINPUT_ENDPOINT_SIZE, false); + } + TU_VERIFY(max_len >= drv_len, 0); + return drv_len; + } + + /* Interface 0: Gamepad (0x5D/0x01) — open EP 0x81 (IN) & EP 0x02 (OUT) */ + if (itf_desc->bInterfaceSubClass == 0x5D && itf_desc->bInterfaceProtocol == 0x01) { + if (p_desc[1] == DESC_TYPE_VENDOR) { + drv_len += tu_desc_len(p_desc); + p_desc = tu_desc_next(p_desc); + } + for (uint8_t i = 0; i < itf_desc->bNumEndpoints; i++) { + tusb_desc_endpoint_t const *ep_desc = (tusb_desc_endpoint_t const *)p_desc; + if (TUSB_DESC_ENDPOINT != tu_desc_type(ep_desc)) break; + TU_VERIFY(usbd_edpt_open(rhport, ep_desc), 0); + if (tu_edpt_dir(ep_desc->bEndpointAddress) == TUSB_DIR_IN) { + s_endpoint_in = ep_desc->bEndpointAddress; + } else { + s_endpoint_out = ep_desc->bEndpointAddress; + } + drv_len += sizeof(tusb_desc_endpoint_t); + p_desc = tu_desc_next(p_desc); + } + if (s_endpoint_out != 0xFF) { + usbd_edpt_xfer(rhport, s_endpoint_out, s_ep_out_buffer, XINPUT_ENDPOINT_SIZE, false); + } + TU_VERIFY(max_len >= drv_len, 0); + return drv_len; + } + + /* Interface 1: Audio (0x5D/0x03) — skip endpoints (stub) */ + if (itf_desc->bInterfaceSubClass == 0x5D && itf_desc->bInterfaceProtocol == 0x03) { + if (p_desc[1] == DESC_TYPE_VENDOR) { + drv_len += tu_desc_len(p_desc); + p_desc = tu_desc_next(p_desc); + } + for (uint8_t i = 0; i < itf_desc->bNumEndpoints; i++) { + drv_len += sizeof(tusb_desc_endpoint_t); + p_desc = tu_desc_next(p_desc); + } + TU_VERIFY(max_len >= drv_len, 0); + return drv_len; + } + + /* Interface 2: Plugin (0x5D/0x02) — skip endpoints (stub) */ + if (itf_desc->bInterfaceSubClass == 0x5D && itf_desc->bInterfaceProtocol == 0x02) { + if (p_desc[1] == DESC_TYPE_VENDOR) { + drv_len += tu_desc_len(p_desc); + p_desc = tu_desc_next(p_desc); + } + for (uint8_t i = 0; i < itf_desc->bNumEndpoints; i++) { + drv_len += sizeof(tusb_desc_endpoint_t); + p_desc = tu_desc_next(p_desc); + } + TU_VERIFY(max_len >= drv_len, 0); + return drv_len; + } + + /* Interface 3: Security (0xFD/0x13) — skip 0x41 descriptor, no EPs */ + if (itf_desc->bInterfaceSubClass == 0xFD && itf_desc->bInterfaceProtocol == 0x13) { + if (p_desc[1] == DESC_TYPE_SEC) { + drv_len += tu_desc_len(p_desc); + } + TU_VERIFY(max_len >= drv_len, 0); + return drv_len; + } + + return 0; +} + +static bool xinput_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) +{ + (void)result; + (void)xferred_bytes; + if (ep_addr == s_endpoint_out) { + console_mode_t current_mode = profile_manager_get_mode(); + if (current_mode == CONSOLE_MODE_XBOX360) { + /* Xbox 360 Rumble Report: s_ep_out_buffer[0] == 0x00, s_ep_out_buffer[1] == 0x08 */ + if (s_ep_out_buffer[0] == 0x00 && s_ep_out_buffer[1] == 0x08) { + uint8_t heavy = s_ep_out_buffer[3]; + uint8_t light = s_ep_out_buffer[4]; + ble_hid_host_send_rumble(heavy, light); + } + } else if (current_mode == CONSOLE_MODE_XBOXOG) { + /* Original Xbox Rumble Report: s_ep_out_buffer[0] == 0x00, s_ep_out_buffer[1] == 0x06 */ + if (s_ep_out_buffer[0] == 0x00 && s_ep_out_buffer[1] == 0x06) { + uint8_t heavy = s_ep_out_buffer[3]; + uint8_t light = s_ep_out_buffer[5]; + ble_hid_host_send_rumble(heavy, light); + } + } + /* Re-prime OUT endpoint to receive rumble / LED packets */ + usbd_edpt_xfer(rhport, s_endpoint_out, s_ep_out_buffer, XINPUT_ENDPOINT_SIZE, false); + } + return true; +} + +static bool xinput_control_handler(uint8_t rhport, uint8_t stage, tusb_control_request_t const *request) +{ + console_mode_t current_mode = profile_manager_get_mode(); + + /* Original Xbox XID control request handling */ + if (current_mode == CONSOLE_MODE_XBOXOG) { + /* XID Descriptor Request: bRequest == 0x06 (GET_DESCRIPTOR) and wValue == 0x4200 */ + if (request->bRequest == 0x06 && request->wValue == 0x4200) { + if (stage == CONTROL_STAGE_SETUP) { + uint16_t len = (request->wLength < sizeof(ogx_xid_descriptor)) ? request->wLength : sizeof(ogx_xid_descriptor); + return tud_control_xfer(rhport, request, (void *)ogx_xid_descriptor, len); + } + return true; + } + /* GET_REPORT on control endpoint (bRequest == 0x01) */ + if (request->bRequest == 0x01 && (request->bmRequestType & 0x80)) { + if (stage == CONTROL_STAGE_SETUP) { + controller_state_t st; + ogx_report_t rep; + usb_gamepad_get_last_state(&st); + ogx_build_report(&st, &rep); + uint16_t len = (request->wLength < sizeof(rep)) ? request->wLength : sizeof(rep); + return tud_control_xfer(rhport, request, &rep, len); + } + return true; + } + /* SET_REPORT on control endpoint (bRequest == 0x09) */ + if (request->bRequest == 0x09 && !(request->bmRequestType & 0x80)) { + return tud_control_status(rhport, request); + } + return false; + } + + if (current_mode != CONSOLE_MODE_XBOX360) { + return false; + } + + uint8_t type_bits = request->bmRequestType & 0x60; + if (type_bits != 0x40 && type_bits != 0x20) { + return false; + } + + switch (request->bRequest) { + case 0x81: /* GET Identification */ + if (stage == CONTROL_STAGE_SETUP) { + ESP_LOGI(TAG, "XSM3: 0x81 GET_SERIAL (wLength=%d)", request->wLength); + if (request->wLength >= 0x1D) { + return tud_control_xfer(rhport, request, s_xsm3_identification, 0x1D); + } + } + return true; + + case 0x82: /* OUT Challenge Init */ + if (stage == CONTROL_STAGE_SETUP && request->wLength >= 0x22) { + return tud_control_xfer(rhport, request, s_xsm3_buf_82, 0x22); + } + if (stage == CONTROL_STAGE_DATA) { + ESP_LOGI(TAG, "XSM3: 0x82 challenge init received, executing crypt..."); + xsm3_do_challenge_init(s_xsm3_buf_82); + s_xsm3_auth_state = XSM3_AUTH_STATE_RESPONDED; + } + return true; + + case 0x83: /* GET Challenge Response */ + if (stage == CONTROL_STAGE_SETUP) { + if (s_xsm3_auth_state == XSM3_AUTH_STATE_RESPONDED) { + ESP_LOGI(TAG, "XSM3: 0x83 sending init response (46 bytes)"); + uint16_t len = (request->wLength < 46) ? request->wLength : 46; + bool ok = tud_control_xfer(rhport, request, xsm3_challenge_response, len); + if (ok) s_xsm3_auth_state = XSM3_AUTH_STATE_IDLE; + return ok; + } + if (s_xsm3_auth_state == XSM3_AUTH_STATE_AUTHENTICATED) { + ESP_LOGI(TAG, "XSM3: 0x83 sending verify response (22 bytes)"); + uint16_t len = (request->wLength < 22) ? request->wLength : 22; + bool ok = tud_control_xfer(rhport, request, xsm3_challenge_response, len); + if (ok) s_xsm3_auth_state = XSM3_AUTH_STATE_IDLE; + return ok; + } + return false; + } + return true; + + case 0x84: /* GET Keepalive */ + if (stage == CONTROL_STAGE_SETUP) { + return tud_control_xfer(rhport, request, NULL, 0); + } + return true; + + case 0x86: /* GET State */ + if (stage == CONTROL_STAGE_SETUP && request->wLength >= 2) { + uint8_t state_val = (s_xsm3_auth_state == XSM3_AUTH_STATE_RESPONDED || + s_xsm3_auth_state == XSM3_AUTH_STATE_AUTHENTICATED) + ? 2 /* Ready */ : 1 /* Processing */; + s_xsm3_state_buf[0] = state_val; + s_xsm3_state_buf[1] = 0x00; + return tud_control_xfer(rhport, request, s_xsm3_state_buf, 2); + } + return true; + + case 0x87: /* OUT Challenge Verify */ + if (stage == CONTROL_STAGE_SETUP && request->wLength >= 0x16) { + return tud_control_xfer(rhport, request, s_xsm3_buf_87, 0x16); + } + if (stage == CONTROL_STAGE_DATA) { + ESP_LOGI(TAG, "XSM3: 0x87 verify received, authenticating..."); + xsm3_do_challenge_verify(s_xsm3_buf_87); + s_xsm3_auth_state = XSM3_AUTH_STATE_AUTHENTICATED; + ESP_LOGI(TAG, "XSM3: Controller authenticated successfully!"); + } + return true; + + default: + return false; + } +} + +static bool xinput_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_request_t const *request) +{ + return xinput_control_handler(rhport, stage, request); +} + +/* Intercept vendor-specific control requests dispatched directly from usbd.c */ +bool tud_vendor_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_request_t const *request) +{ + return xinput_control_handler(rhport, stage, request); +} + +static const usbd_class_driver_t s_xinput_class_driver = { +#if CFG_TUSB_DEBUG >= 2 + .name = "XINPUT", +#else + .name = NULL, +#endif + .init = xinput_device_init, + .deinit = xinput_deinit, + .reset = xinput_reset, + .open = xinput_open, + .control_xfer_cb = xinput_control_xfer_cb, + .xfer_cb = xinput_xfer_cb, + .xfer_isr = NULL, + .sof = NULL +}; + +/* Application class driver registration for TinyUSB */ +usbd_class_driver_t const* usbd_app_driver_get_cb(uint8_t* driver_count) +{ + *driver_count = 1; + return &s_xinput_class_driver; +} + +void xinput_device_build_report(const controller_state_t *state, xinput_in_report_t *rep) +{ + memset(rep, 0, sizeof(xinput_in_report_t)); + rep->report_id = 0x00; + rep->report_size = sizeof(xinput_in_report_t); + + /* Buttons 0: D-Pad, Start, Back, L3, R3 */ + if (state->dpad_up) rep->buttons0 |= XINPUT_BTN_DPAD_UP; + if (state->dpad_down) rep->buttons0 |= XINPUT_BTN_DPAD_DOWN; + if (state->dpad_left) rep->buttons0 |= XINPUT_BTN_DPAD_LEFT; + if (state->dpad_right) rep->buttons0 |= XINPUT_BTN_DPAD_RIGHT; + if (state->btn_start) rep->buttons0 |= XINPUT_BTN_START; + if (state->btn_select) rep->buttons0 |= XINPUT_BTN_BACK; + if (state->btn_l3) rep->buttons0 |= XINPUT_BTN_L3; + if (state->btn_r3) rep->buttons0 |= XINPUT_BTN_R3; + + /* Buttons 1: LB, RB, Guide, A, B, X, Y */ + if (state->btn_lb) rep->buttons1 |= XINPUT_BTN_LB; + if (state->btn_rb) rep->buttons1 |= XINPUT_BTN_RB; + if (state->btn_system) rep->buttons1 |= XINPUT_BTN_GUIDE; + if (state->btn_a) rep->buttons1 |= XINPUT_BTN_A; + if (state->btn_b) rep->buttons1 |= XINPUT_BTN_B; + if (state->btn_x) rep->buttons1 |= XINPUT_BTN_X; + if (state->btn_y) rep->buttons1 |= XINPUT_BTN_Y; + + /* Triggers: 0..255 */ + rep->trigger_l = state->lt; + rep->trigger_r = state->rt; + + /* Joysticks: int16_t (-32768..32767). + controller_state_t: Up is positive. + XInput specification: Up is positive. + */ + rep->joystick_lx = state->lx; + rep->joystick_ly = state->ly; + rep->joystick_rx = state->rx; + rep->joystick_ry = state->ry; +} + +bool xinput_device_send_report(const xinput_in_report_t *rep) +{ + if (!tud_mounted() || s_endpoint_in == 0xFF) return false; + if (usbd_edpt_busy(0, s_endpoint_in)) return false; + + memcpy(s_ep_in_buffer, rep, sizeof(xinput_in_report_t)); + usbd_edpt_claim(0, s_endpoint_in); + usbd_edpt_xfer(0, s_endpoint_in, s_ep_in_buffer, sizeof(xinput_in_report_t), false); + usbd_edpt_release(0, s_endpoint_in); + return true; +} + +void ogx_device_init(void) +{ + s_endpoint_in = 0xFF; + s_endpoint_out = 0xFF; + memset(s_ep_in_buffer, 0, sizeof(s_ep_in_buffer)); + memset(s_ep_out_buffer, 0, sizeof(s_ep_out_buffer)); +} + +bool ogx_device_send_report(const void *rep, uint16_t len) +{ + if (!tud_mounted() || s_endpoint_in == 0xFF) return false; + if (usbd_edpt_busy(0, s_endpoint_in)) return false; + + memcpy(s_ep_in_buffer, rep, len); + usbd_edpt_claim(0, s_endpoint_in); + usbd_edpt_xfer(0, s_endpoint_in, s_ep_in_buffer, len, false); + usbd_edpt_release(0, s_endpoint_in); + return true; +} diff --git a/main/console_output/xinput_device.h b/main/console_output/xinput_device.h new file mode 100644 index 0000000..07587f9 --- /dev/null +++ b/main/console_output/xinput_device.h @@ -0,0 +1,74 @@ +#pragma once + +#include +#include +#include "controller_state.h" +#include "tusb.h" +#include "device/usbd_pvt.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define XINPUT_VID 0x045E /* Microsoft Corp. */ +#define XINPUT_PID 0x028E /* Xbox 360 Controller */ + +/* Buttons 0 Bitmask */ +#define XINPUT_BTN_DPAD_UP (1U << 0) +#define XINPUT_BTN_DPAD_DOWN (1U << 1) +#define XINPUT_BTN_DPAD_LEFT (1U << 2) +#define XINPUT_BTN_DPAD_RIGHT (1U << 3) +#define XINPUT_BTN_START (1U << 4) +#define XINPUT_BTN_BACK (1U << 5) +#define XINPUT_BTN_L3 (1U << 6) +#define XINPUT_BTN_R3 (1U << 7) + +/* Buttons 1 Bitmask */ +#define XINPUT_BTN_LB (1U << 0) +#define XINPUT_BTN_RB (1U << 1) +#define XINPUT_BTN_GUIDE (1U << 2) +#define XINPUT_BTN_A (1U << 4) +#define XINPUT_BTN_B (1U << 5) +#define XINPUT_BTN_X (1U << 6) +#define XINPUT_BTN_Y (1U << 7) + +typedef struct __attribute__((packed)) { + uint8_t report_id; /* Always 0x00 */ + uint8_t report_size; /* Always 0x14 (20 bytes) */ + uint8_t buttons0; /* D-pad, Start, Back, L3, R3 */ + uint8_t buttons1; /* LB, RB, Guide, A, B, X, Y */ + uint8_t trigger_l; /* 0..255 */ + uint8_t trigger_r; /* 0..255 */ + int16_t joystick_lx; /* -32768..32767 */ + int16_t joystick_ly; /* -32768..32767 (Up is positive) */ + int16_t joystick_rx; /* -32768..32767 */ + int16_t joystick_ry; /* -32768..32767 (Up is positive) */ + uint8_t reserved[6]; +} xinput_in_report_t; + +typedef struct __attribute__((packed)) { + uint8_t report_id; /* 0x00 = Rumble, 0x01 = LED */ + uint8_t report_size; /* 0x08 */ + uint8_t led; + uint8_t rumble_l; /* Heavy motor */ + uint8_t rumble_r; /* Light motor */ + uint8_t reserved[3]; +} xinput_out_report_t; + +extern const tusb_desc_device_t xinput_device_desc; +extern const uint8_t xinput_config_desc[153]; +extern const char *xinput_string_desc[5]; + +void xinput_device_init(void); +void xinput_device_build_report(const controller_state_t *state, xinput_in_report_t *rep); +bool xinput_device_send_report(const xinput_in_report_t *rep); + +void ogx_device_init(void); +bool ogx_device_send_report(const void *rep, uint16_t len); + +/* TinyUSB Application Class Driver for XInput & XSM3 Security Handshake */ +usbd_class_driver_t const *xinput_device_get_class_driver(void); + +#ifdef __cplusplus +} +#endif diff --git a/main/controller_state.h b/main/controller_state.h new file mode 100644 index 0000000..9ccc6e7 --- /dev/null +++ b/main/controller_state.h @@ -0,0 +1,67 @@ +#pragma once + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Unified, normalized controller state representing any gamepad. + * + * Analog sticks are scaled to -32768 to 32767 (0 is neutral centered). + * Triggers are normalized from 0 to 255 (0 is released, 255 is fully depressed). + */ +typedef struct { + /* Analog Axes */ + int16_t lx; /* Left Stick X (-32768 to 32767) */ + int16_t ly; /* Left Stick Y (-32768 to 32767, up is positive) */ + int16_t rx; /* Right Stick X (-32768 to 32767) */ + int16_t ry; /* Right Stick Y (-32768 to 32767, up is positive) */ + + /* Analog Triggers */ + uint8_t lt; /* Left Trigger (0 to 255) */ + uint8_t rt; /* Right Trigger (0 to 255) */ + + /* D-Pad Buttons */ + uint8_t dpad_up : 1; + uint8_t dpad_down : 1; + uint8_t dpad_left : 1; + uint8_t dpad_right : 1; + + /* Face Buttons */ + uint8_t btn_a : 1; /* South (Xbox A, Switch B, PS Cross) */ + uint8_t btn_b : 1; /* East (Xbox B, Switch A, PS Circle) */ + uint8_t btn_x : 1; /* West (Xbox X, Switch Y, PS Square) */ + uint8_t btn_y : 1; /* North (Xbox Y, Switch X, PS Triangle) */ + + /* Shoulder & Trigger Digital Buttons */ + uint8_t btn_lb : 1; /* Left Bumper / L1 / L */ + uint8_t btn_rb : 1; /* Right Bumper / R1 / R */ + uint8_t btn_lt : 1; /* Left Trigger digital click / ZL */ + uint8_t btn_rt : 1; /* Right Trigger digital click / ZR */ + + /* Special & Navigation Buttons */ + uint8_t btn_select : 1; /* Back / View / Minus / Select */ + uint8_t btn_start : 1; /* Start / Menu / Plus */ + uint8_t btn_l3 : 1; /* Left Thumbstick Click */ + uint8_t btn_r3 : 1; /* Right Thumbstick Click */ + uint8_t btn_system : 1; /* Xbox Guide / PS / Switch Home */ + uint8_t btn_share : 1; /* Share / Capture */ +} controller_state_t; + +/** + * @brief Reset controller state to neutral rest position. + */ +static inline void controller_state_reset(controller_state_t *state) +{ + if (state) { + memset(state, 0, sizeof(controller_state_t)); + } +} + +#ifdef __cplusplus +} +#endif diff --git a/main/dns_server.c b/main/dns_server.c new file mode 100644 index 0000000..876f848 --- /dev/null +++ b/main/dns_server.c @@ -0,0 +1,151 @@ +#include "dns_server.h" +#include +#include +#include +#include +#include "esp_log.h" +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" + +static const char *TAG = "DNS_SERVER"; + +#define DNS_PORT 53 +#define DNS_MAX_LEN 512 + +static int s_dns_sock = -1; +static TaskHandle_t s_dns_task_handle = NULL; +static volatile bool s_dns_running = false; + +static void dns_server_task(void *pvParameters) +{ + uint8_t rx_buffer[DNS_MAX_LEN]; + uint8_t tx_buffer[DNS_MAX_LEN]; + struct sockaddr_in client_addr; + socklen_t client_addr_len = sizeof(client_addr); + + ESP_LOGI(TAG, "DNS Captive Portal Server listening on UDP port %d", DNS_PORT); + + while (s_dns_running && s_dns_sock >= 0) { + int len = recvfrom(s_dns_sock, rx_buffer, sizeof(rx_buffer), 0, + (struct sockaddr *)&client_addr, &client_addr_len); + if (len < 12) { + continue; + } + + /* Check if it's a standard query (QR=0, Opcode=0) */ + uint16_t flags = (rx_buffer[2] << 8) | rx_buffer[3]; + if ((flags & 0x8000) != 0) { + continue; /* Not a query */ + } + + /* Construct response */ + memcpy(tx_buffer, rx_buffer, len); + + /* Set flags: Response, Authoritative, Recursion Available */ + tx_buffer[2] = 0x81; + tx_buffer[3] = 0x80; + + /* Answers count = 1 */ + tx_buffer[6] = 0x00; + tx_buffer[7] = 0x01; + /* Authority RRs = 0, Additional RRs = 0 */ + tx_buffer[8] = 0x00; + tx_buffer[9] = 0x00; + tx_buffer[10] = 0x00; + tx_buffer[11] = 0x00; + + /* Append Answer record right after the query section */ + int resp_len = len; + if (resp_len + 16 <= DNS_MAX_LEN) { + /* Name pointer to offset 12 (first label) */ + tx_buffer[resp_len++] = 0xC0; + tx_buffer[resp_len++] = 0x0C; + /* Type A (0x0001) */ + tx_buffer[resp_len++] = 0x00; + tx_buffer[resp_len++] = 0x01; + /* Class IN (0x0001) */ + tx_buffer[resp_len++] = 0x00; + tx_buffer[resp_len++] = 0x01; + /* TTL: 60 seconds (0x0000003C) */ + tx_buffer[resp_len++] = 0x00; + tx_buffer[resp_len++] = 0x00; + tx_buffer[resp_len++] = 0x00; + tx_buffer[resp_len++] = 0x3C; + /* Data length: 4 */ + tx_buffer[resp_len++] = 0x00; + tx_buffer[resp_len++] = 0x04; + /* IP: 192.168.4.1 */ + tx_buffer[resp_len++] = 192; + tx_buffer[resp_len++] = 168; + tx_buffer[resp_len++] = 4; + tx_buffer[resp_len++] = 1; + + sendto(s_dns_sock, tx_buffer, resp_len, 0, + (struct sockaddr *)&client_addr, client_addr_len); + } + } + + if (s_dns_sock >= 0) { + close(s_dns_sock); + s_dns_sock = -1; + } + s_dns_task_handle = NULL; + vTaskDelete(NULL); +} + +esp_err_t dns_server_start(void) +{ + if (s_dns_running) { + return ESP_OK; + } + + struct sockaddr_in serv_addr; + memset(&serv_addr, 0, sizeof(serv_addr)); + serv_addr.sin_family = AF_INET; + serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); + serv_addr.sin_port = htons(DNS_PORT); + + s_dns_sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP); + if (s_dns_sock < 0) { + ESP_LOGE(TAG, "Unable to create DNS socket: errno %d", errno); + return ESP_FAIL; + } + + /* Set socket receive timeout so task can exit cleanly */ + struct timeval timeout = { + .tv_sec = 1, + .tv_usec = 0, + }; + setsockopt(s_dns_sock, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)); + + int err = bind(s_dns_sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)); + if (err < 0) { + ESP_LOGE(TAG, "DNS socket unable to bind: errno %d", errno); + close(s_dns_sock); + s_dns_sock = -1; + return ESP_FAIL; + } + + /* Pin captive portal DNS responder to Core 0 (alongside network stack) */ + BaseType_t ret = xTaskCreatePinnedToCore(dns_server_task, "dns_server_task", 3072, NULL, 5, &s_dns_task_handle, 0); + if (ret != pdPASS) { + ESP_LOGE(TAG, "Failed to create DNS task"); + close(s_dns_sock); + s_dns_sock = -1; + s_dns_running = false; + return ESP_FAIL; + } + + return ESP_OK; +} + +void dns_server_stop(void) +{ + if (!s_dns_running) { + return; + } + + ESP_LOGI(TAG, "Stopping DNS Captive Portal server..."); + s_dns_running = false; + /* Socket timeout will trigger task to exit and close socket */ +} diff --git a/main/dns_server.h b/main/dns_server.h new file mode 100644 index 0000000..3af464e --- /dev/null +++ b/main/dns_server.h @@ -0,0 +1,21 @@ +#pragma once + +#include "esp_err.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Start lightweight DNS server answering all A-record queries with AP IP (Captive Portal) + */ +esp_err_t dns_server_start(void); + +/** + * @brief Stop DNS server + */ +void dns_server_stop(void); + +#ifdef __cplusplus +} +#endif diff --git a/main/idf_component.yml b/main/idf_component.yml new file mode 100644 index 0000000..9660e38 --- /dev/null +++ b/main/idf_component.yml @@ -0,0 +1,4 @@ +dependencies: + espressif/esp_tinyusb: "^1.5.0" + espressif/led_strip: "^3.0.0" + espressif/mdns: "^1.4.0" diff --git a/main/input_calibration.c b/main/input_calibration.c new file mode 100644 index 0000000..535f0a7 --- /dev/null +++ b/main/input_calibration.c @@ -0,0 +1,203 @@ +#include "input_calibration.h" +#include "nvs_flash.h" +#include "nvs.h" +#include "esp_log.h" +#include "freertos/FreeRTOS.h" +#include "freertos/portmacro.h" +#include +#include + +static const char *TAG = "INPUT_CALIB"; +static const char *NVS_NAMESPACE = "calib_cfg"; + +static input_calibration_cfg_t s_cfg = { + .left_deadzone = 5, + .right_deadzone = 5, + .trigger_deadzone = 0, + .swap_ab = false, + .swap_xy = false, + .swap_bumpers_triggers = false, + .invert_lx = false, + .invert_ly = false, + .invert_rx = false, + .invert_ry = false, +}; + +static portMUX_TYPE s_calib_mutex = portMUX_INITIALIZER_UNLOCKED; + +static void load_from_nvs(void) +{ + nvs_handle_t nvs_h; + if (nvs_open(NVS_NAMESPACE, NVS_READONLY, &nvs_h) != ESP_OK) { + return; + } + + uint8_t u8_val = 0; + if (nvs_get_u8(nvs_h, "ldz", &u8_val) == ESP_OK && u8_val <= 40) s_cfg.left_deadzone = u8_val; + if (nvs_get_u8(nvs_h, "rdz", &u8_val) == ESP_OK && u8_val <= 40) s_cfg.right_deadzone = u8_val; + if (nvs_get_u8(nvs_h, "tdz", &u8_val) == ESP_OK && u8_val <= 50) s_cfg.trigger_deadzone = u8_val; + + if (nvs_get_u8(nvs_h, "sab", &u8_val) == ESP_OK) s_cfg.swap_ab = (u8_val != 0); + if (nvs_get_u8(nvs_h, "sxy", &u8_val) == ESP_OK) s_cfg.swap_xy = (u8_val != 0); + if (nvs_get_u8(nvs_h, "sbt", &u8_val) == ESP_OK) s_cfg.swap_bumpers_triggers = (u8_val != 0); + if (nvs_get_u8(nvs_h, "ilx", &u8_val) == ESP_OK) s_cfg.invert_lx = (u8_val != 0); + if (nvs_get_u8(nvs_h, "ily", &u8_val) == ESP_OK) s_cfg.invert_ly = (u8_val != 0); + if (nvs_get_u8(nvs_h, "irx", &u8_val) == ESP_OK) s_cfg.invert_rx = (u8_val != 0); + if (nvs_get_u8(nvs_h, "iry", &u8_val) == ESP_OK) s_cfg.invert_ry = (u8_val != 0); + + nvs_close(nvs_h); +} + +static esp_err_t save_to_nvs(const input_calibration_cfg_t *cfg) +{ + nvs_handle_t nvs_h; + esp_err_t err = nvs_open(NVS_NAMESPACE, NVS_READWRITE, &nvs_h); + if (err != ESP_OK) return err; + + nvs_set_u8(nvs_h, "ldz", cfg->left_deadzone); + nvs_set_u8(nvs_h, "rdz", cfg->right_deadzone); + nvs_set_u8(nvs_h, "tdz", cfg->trigger_deadzone); + nvs_set_u8(nvs_h, "sab", cfg->swap_ab ? 1 : 0); + nvs_set_u8(nvs_h, "sxy", cfg->swap_xy ? 1 : 0); + nvs_set_u8(nvs_h, "sbt", cfg->swap_bumpers_triggers ? 1 : 0); + nvs_set_u8(nvs_h, "ilx", cfg->invert_lx ? 1 : 0); + nvs_set_u8(nvs_h, "ily", cfg->invert_ly ? 1 : 0); + nvs_set_u8(nvs_h, "irx", cfg->invert_rx ? 1 : 0); + nvs_set_u8(nvs_h, "iry", cfg->invert_ry ? 1 : 0); + + err = nvs_commit(nvs_h); + nvs_close(nvs_h); + return err; +} + +esp_err_t input_calibration_init(void) +{ + load_from_nvs(); + ESP_LOGI(TAG, "Input calibration loaded: L-DZ=%d%%, R-DZ=%d%%, SwapAB=%d, SwapXY=%d", + s_cfg.left_deadzone, s_cfg.right_deadzone, s_cfg.swap_ab, s_cfg.swap_xy); + return ESP_OK; +} + +void input_calibration_get_config(input_calibration_cfg_t *cfg) +{ + if (!cfg) return; + portENTER_CRITICAL(&s_calib_mutex); + *cfg = s_cfg; + portEXIT_CRITICAL(&s_calib_mutex); +} + +esp_err_t input_calibration_set_config(const input_calibration_cfg_t *cfg) +{ + if (!cfg) return ESP_ERR_INVALID_ARG; + + input_calibration_cfg_t validated = *cfg; + if (validated.left_deadzone > 40) validated.left_deadzone = 40; + if (validated.right_deadzone > 40) validated.right_deadzone = 40; + if (validated.trigger_deadzone > 50) validated.trigger_deadzone = 50; + + portENTER_CRITICAL(&s_calib_mutex); + s_cfg = validated; + portEXIT_CRITICAL(&s_calib_mutex); + + save_to_nvs(&validated); + ESP_LOGI(TAG, "Updated calibration: L-DZ=%d%%, R-DZ=%d%%, TrgDZ=%d", + validated.left_deadzone, validated.right_deadzone, validated.trigger_deadzone); + return ESP_OK; +} + +esp_err_t input_calibration_reset_defaults(void) +{ + input_calibration_cfg_t def = { + .left_deadzone = 5, + .right_deadzone = 5, + .trigger_deadzone = 0, + .swap_ab = false, + .swap_xy = false, + .swap_bumpers_triggers = false, + .invert_lx = false, + .invert_ly = false, + .invert_rx = false, + .invert_ry = false, + }; + return input_calibration_set_config(&def); +} + +static void apply_stick_deadzone(int16_t *x, int16_t *y, uint8_t deadzone_pct) +{ + if (deadzone_pct == 0) return; + + float fx = (float)*x; + float fy = (float)*y; + float mag = sqrtf(fx * fx + fy * fy); + float dz = (float)deadzone_pct * (32767.0f / 100.0f); + + if (mag <= dz) { + *x = 0; + *y = 0; + } else { + float norm = (mag - dz) / (32767.0f - dz); + if (norm > 1.0f) norm = 1.0f; + *x = (int16_t)((fx / mag) * norm * 32767.0f); + *y = (int16_t)((fy / mag) * norm * 32767.0f); + } +} + +void input_calibration_apply(const controller_state_t *in_raw, controller_state_t *out_calibrated) +{ + if (!in_raw || !out_calibrated) return; + + input_calibration_cfg_t cfg; + portENTER_CRITICAL(&s_calib_mutex); + cfg = s_cfg; + portEXIT_CRITICAL(&s_calib_mutex); + + /* Copy raw state base */ + *out_calibrated = *in_raw; + + /* 1. Apply Radial Analog Deadzones */ + apply_stick_deadzone(&out_calibrated->lx, &out_calibrated->ly, cfg.left_deadzone); + apply_stick_deadzone(&out_calibrated->rx, &out_calibrated->ry, cfg.right_deadzone); + + /* 2. Apply Stick Inversions */ + if (cfg.invert_lx) out_calibrated->lx = -out_calibrated->lx; + if (cfg.invert_ly) out_calibrated->ly = -out_calibrated->ly; + if (cfg.invert_rx) out_calibrated->rx = -out_calibrated->rx; + if (cfg.invert_ry) out_calibrated->ry = -out_calibrated->ry; + + /* 3. Apply Trigger Deadzone */ + if (cfg.trigger_deadzone > 0) { + if (out_calibrated->lt < cfg.trigger_deadzone) { + out_calibrated->lt = 0; + out_calibrated->btn_lt = 0; + } + if (out_calibrated->rt < cfg.trigger_deadzone) { + out_calibrated->rt = 0; + out_calibrated->btn_rt = 0; + } + } + + /* 4. Apply Button Remapping / Swaps */ + if (cfg.swap_ab) { + uint8_t tmp = out_calibrated->btn_a; + out_calibrated->btn_a = out_calibrated->btn_b; + out_calibrated->btn_b = tmp; + } + if (cfg.swap_xy) { + uint8_t tmp = out_calibrated->btn_x; + out_calibrated->btn_x = out_calibrated->btn_y; + out_calibrated->btn_y = tmp; + } + if (cfg.swap_bumpers_triggers) { + uint8_t tmp_lb = out_calibrated->btn_lb; + uint8_t tmp_rb = out_calibrated->btn_rb; + uint8_t tmp_lt = out_calibrated->lt; + uint8_t tmp_rt = out_calibrated->rt; + + out_calibrated->btn_lb = (tmp_lt > 100) ? 1 : 0; + out_calibrated->btn_rb = (tmp_rt > 100) ? 1 : 0; + out_calibrated->lt = tmp_lb ? 255 : 0; + out_calibrated->rt = tmp_rb ? 255 : 0; + out_calibrated->btn_lt = (out_calibrated->lt > 0); + out_calibrated->btn_rt = (out_calibrated->rt > 0); + } +} diff --git a/main/input_calibration.h b/main/input_calibration.h new file mode 100644 index 0000000..ebb3459 --- /dev/null +++ b/main/input_calibration.h @@ -0,0 +1,54 @@ +#pragma once + +#include +#include +#include "controller_state.h" +#include "esp_err.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct { + uint8_t left_deadzone; /* Inner deadzone percentage: 0 to 40% (default: 5%) */ + uint8_t right_deadzone; /* Inner deadzone percentage: 0 to 40% (default: 5%) */ + uint8_t trigger_deadzone; /* Trigger minimum deadzone: 0 to 50 (default: 0) */ + bool swap_ab; /* Swap South (A) and East (B) */ + bool swap_xy; /* Swap West (X) and North (Y) */ + bool swap_bumpers_triggers; /* Swap Bumpers (LB/RB) with Triggers (LT/RT) */ + bool invert_lx; /* Invert Left Stick X */ + bool invert_ly; /* Invert Left Stick Y */ + bool invert_rx; /* Invert Right Stick X */ + bool invert_ry; /* Invert Right Stick Y */ +} input_calibration_cfg_t; + +/** + * @brief Initialize input calibration module and load settings from NVS. + */ +esp_err_t input_calibration_init(void); + +/** + * @brief Get the current input calibration configuration. + */ +void input_calibration_get_config(input_calibration_cfg_t *cfg); + +/** + * @brief Save new input calibration configuration to NVS and apply immediately. + */ +esp_err_t input_calibration_set_config(const input_calibration_cfg_t *cfg); + +/** + * @brief Reset input calibration configuration to default values. + */ +esp_err_t input_calibration_reset_defaults(void); + +/** + * @brief Apply deadzones, axis inversions, and button remapping to raw state. + * @param in_raw Raw input controller state. + * @param out_calibrated Output calibrated and remapped controller state. + */ +void input_calibration_apply(const controller_state_t *in_raw, controller_state_t *out_calibrated); + +#ifdef __cplusplus +} +#endif diff --git a/main/libxsm3/excrypt.h b/main/libxsm3/excrypt.h new file mode 100644 index 0000000..102583b --- /dev/null +++ b/main/libxsm3/excrypt.h @@ -0,0 +1,39 @@ +#ifndef EXCRYPT_H_ +#define EXCRYPT_H_ + +#ifdef __cplusplus +extern "C" { +#endif +#include + +#if(__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) +#define SWAP16(i) (i) +#define SWAP32(i) (i) +#define SWAP64(i) (i) +#else +#define SWAP16(i) (__builtin_bswap16((uint16_t)(i))) +#define SWAP32(i) (__builtin_bswap32((uint32_t)(i))) +#define SWAP64(i) (__builtin_bswap64((uint64_t)(i))) +#endif + +#define U8V(data) ((uint8_t)(data) & 0xFF) +#define ROTL8(data, bits) (U8V((data) << (bits)) | ((data) >> (8 - (bits)))) + +#define U16V(data) ((uint16_t)(data) & 0xFFFF) +#define ROTL16(data, bits) (U16V((data) << (bits)) | ((data) >> (16 - (bits)))) + +#define U32V(data) ((uint32_t)(data) & 0xFFFFFFFF) +#define ROTL32(data, bits) (U32V((data) << (bits)) | ((data) >> (32 - (bits)))) + +#define ROTL64(data, bits) (((data) << (bits)) | ((data) >> (64 - (bits)))) + +typedef int BOOL; + +#include "excrypt_des.h" +#include "excrypt_sha.h" +#include "excrypt_parve.h" +#ifdef __cplusplus +} +#endif + +#endif // EXCRYPT_H_ \ No newline at end of file diff --git a/main/libxsm3/excrypt_des.c b/main/libxsm3/excrypt_des.c new file mode 100644 index 0000000..a8c2759 --- /dev/null +++ b/main/libxsm3/excrypt_des.c @@ -0,0 +1,198 @@ +#include "excrypt.h" +#include "excrypt_des_data.h" +#include + +#define LODWORD(_qw) ((uint32_t)(_qw)) +#define HIDWORD(_qw) ((uint32_t)(((_qw) >> 32) & 0xffffffff)) + +// DES code based on https://github.com/fffaraz/cppDES + +void ExCryptDesParity(const uint8_t* input, uint32_t input_size, uint8_t* output) +{ + for (uint32_t i = 0; i < input_size; i++) + { + uint8_t parity = input[i]; + + parity ^= parity >> 4; + parity ^= parity >> 2; + parity ^= parity >> 1; + + output[i] = (input[i] & 0xFE) | (~parity & 1); + } +} + +void ExCryptDesKey(EXCRYPT_DES_STATE* state, const uint8_t* key) +{ + uint64_t qkey = SWAP64(*(const uint64_t*)key); + + // initial key schedule calculation + uint64_t permuted_choice_1 = 0; // 56 bits + for (int i = 0; i < 56; i++) + { + permuted_choice_1 <<= 1; + permuted_choice_1 |= (qkey >> (64 - PC1[i])) & LB64_MASK; + } + + // 28 bits + uint32_t C = (uint32_t)((permuted_choice_1 >> 28) & 0x000000000fffffff); + uint32_t D = (uint32_t)(permuted_choice_1 & 0x000000000fffffff); + + // Calculation of the 16 keys + for (int i = 0; i < 16; i++) + { + // key schedule, shifting Ci and Di + for (int j = 0; j < ITERATION_SHIFT[i]; j++) + { + C = (0x0fffffff & (C << 1)) | (0x00000001 & (C >> 27)); + D = (0x0fffffff & (D << 1)) | (0x00000001 & (D >> 27)); + } + + uint64_t permuted_choice_2 = (((uint64_t)C) << 28) | (uint64_t)D; + + uint64_t sub_key = 0; // 48 bits (2*24) + for (int j = 0; j < 48; j++) + { + sub_key <<= 1; + sub_key |= (permuted_choice_2 >> (56 - PC2[j])) & LB64_MASK; + } + state->keytab[i] = sub_key; + } +} + +uint32_t f(uint32_t R, uint64_t k) +{ + // applying expansion permutation and returning 48-bit data + uint64_t s_input = 0; + for (int i = 0; i < 48; i++) + { + s_input <<= 1; + s_input |= (uint64_t)((R >> (32 - EXPANSION[i])) & LB32_MASK); + } + + // XORing expanded Ri with Ki, the round key + s_input = s_input ^ k; + + // applying S-Boxes function and returning 32-bit data + uint32_t s_output = 0; + for (int i = 0; i < 8; i++) + { + // Outer bits + char row = (char)((s_input & (0x0000840000000000 >> 6 * i)) >> (42 - 6 * i)); + row = (row >> 4) | (row & 0x01); + + // Middle 4 bits of input + char column = (char)((s_input & (0x0000780000000000 >> 6 * i)) >> (43 - 6 * i)); + + s_output <<= 4; + s_output |= (uint32_t)(SBOX[i][16 * row + column] & 0x0f); + } + + // applying the round permutation + uint32_t f_result = 0; + for (int i = 0; i < 32; i++) + { + f_result <<= 1; + f_result |= (s_output >> (32 - PBOX[i])) & LB32_MASK; + } + + return f_result; +} + +void feistel(uint32_t* L, uint32_t* R, uint32_t F) +{ + uint32_t temp = *R; + *R = *L ^ F; + *L = temp; +} + +void ExCryptDesEcb(const EXCRYPT_DES_STATE* state, const uint8_t* input, uint8_t* output, uint8_t encrypt) +{ + uint64_t block; + memcpy(&block, input, sizeof(uint64_t)); + block = SWAP64(block); + //uint64_t block = SWAP64(*(uint64_t*)input) + + + // initial permutation + uint64_t result = 0; + for (int i = 0; i < 64; i++) + { + result <<= 1; + result |= (block >> (64 - IP[i])) & LB64_MASK; + } + + // dividing T' into two 32-bit parts + uint32_t L = HIDWORD(result); + uint32_t R = LODWORD(result); + + // 16 rounds + for (int i = 0; i < 16; i++) + { + uint32_t F = !encrypt ? f(R, state->keytab[15 - i]) : f(R, state->keytab[i]); + feistel(&L, &R, F); + } + + // swapping the two parts + block = (((uint64_t)R) << 32) | (uint64_t)L; + + // inverse initial permutation + result = 0; + for (int i = 0; i < 64; i++) + { + result <<= 1; + result |= (block >> (64 - FP[i])) & LB64_MASK; + } + result = SWAP64(result); + memcpy(output, &result, sizeof(result)); +} + +void ExCryptDes3Key(EXCRYPT_DES3_STATE* state, const uint64_t* keys) +{ + ExCryptDesKey(&state->des_state[0], (const uint8_t*)& keys[0]); + ExCryptDesKey(&state->des_state[1], (const uint8_t*)& keys[1]); + ExCryptDesKey(&state->des_state[2], (const uint8_t*)& keys[2]); +} + +void ExCryptDes3Ecb(const EXCRYPT_DES3_STATE* state, const uint8_t* input, uint8_t* output, uint8_t encrypt) +{ + if (encrypt) + { + ExCryptDesEcb(&state->des_state[0], input, output, encrypt); + ExCryptDesEcb(&state->des_state[1], output, output, !encrypt); + ExCryptDesEcb(&state->des_state[2], output, output, encrypt); + } + else + { + ExCryptDesEcb(&state->des_state[2], input, output, encrypt); + ExCryptDesEcb(&state->des_state[1], output, output, !encrypt); + ExCryptDesEcb(&state->des_state[0], output, output, encrypt); + } +} + +void ExCryptDes3Cbc(const EXCRYPT_DES3_STATE* state, const uint8_t* input, uint32_t input_size, uint8_t* output, uint8_t* feed, uint8_t encrypt) +{ + uint64_t last_block = *(uint64_t*)feed; + for (uint32_t i = 0; i < input_size / 8; i++) + { + if (encrypt) { + uint64_t temp; + memcpy(&temp, input, sizeof(temp)); + temp = temp ^ last_block; + memcpy(output, &temp, sizeof(temp)); + ExCryptDes3Ecb(state, output, output, encrypt); + memcpy(&last_block, output, sizeof(last_block)); + } + else + { + ExCryptDes3Ecb(state, input, output, encrypt); + uint64_t temp; + memcpy(&temp, output, sizeof(temp)); + temp = temp ^ last_block; + memcpy(output, &temp, sizeof(temp)); + memcpy(&last_block, input, sizeof(last_block)); + } + input += 8; + output += 8; + } + *(uint64_t*)feed = last_block; +} diff --git a/main/libxsm3/excrypt_des.h b/main/libxsm3/excrypt_des.h new file mode 100644 index 0000000..f4b3ee1 --- /dev/null +++ b/main/libxsm3/excrypt_des.h @@ -0,0 +1,24 @@ +#ifndef EXCRYPT_DES_H_ +#define EXCRYPT_DES_H_ +// DES & 3DES functions + +typedef struct _EXCRYPT_DES_STATE +{ + uint64_t keytab[16]; +} EXCRYPT_DES_STATE; + +void ExCryptDesParity(const uint8_t* input, uint32_t input_size, uint8_t* output); + +void ExCryptDesKey(EXCRYPT_DES_STATE* state, const uint8_t* key); +void ExCryptDesEcb(const EXCRYPT_DES_STATE* state, const uint8_t* input, uint8_t* output, uint8_t encrypt); + +typedef struct _EXCRYPT_DES3_STATE +{ + EXCRYPT_DES_STATE des_state[3]; +} EXCRYPT_DES3_STATE; + +void ExCryptDes3Key(EXCRYPT_DES3_STATE* state, const uint64_t* keys); +void ExCryptDes3Ecb(const EXCRYPT_DES3_STATE* state, const uint8_t* input, uint8_t* output, uint8_t encrypt); +void ExCryptDes3Cbc(const EXCRYPT_DES3_STATE* state, const uint8_t* input, uint32_t input_size, uint8_t* output, uint8_t* feed, uint8_t encrypt); + +#endif // EXCRYPT_DES_H_ \ No newline at end of file diff --git a/main/libxsm3/excrypt_des_data.h b/main/libxsm3/excrypt_des_data.h new file mode 100644 index 0000000..d585e87 --- /dev/null +++ b/main/libxsm3/excrypt_des_data.h @@ -0,0 +1,157 @@ +#ifndef EXCRYPT_DES_DATA_H_ +#define EXCRYPT_DES_DATA_H_ +// Data needed by DES/3DES functions +// (only included by excrypt_des.c - no headers should include this!) + +#define LB32_MASK 0x00000001 +#define LB64_MASK 0x0000000000000001 +#define L64_MASK 0x00000000ffffffff + +// Initial Permutation Table [8*8] +static const char IP[] = +{ + 58, 50, 42, 34, 26, 18, 10, 2, + 60, 52, 44, 36, 28, 20, 12, 4, + 62, 54, 46, 38, 30, 22, 14, 6, + 64, 56, 48, 40, 32, 24, 16, 8, + 57, 49, 41, 33, 25, 17, 9, 1, + 59, 51, 43, 35, 27, 19, 11, 3, + 61, 53, 45, 37, 29, 21, 13, 5, + 63, 55, 47, 39, 31, 23, 15, 7 +}; + +// Inverse Initial Permutation Table [8*8] +static const char FP[] = +{ + 40, 8, 48, 16, 56, 24, 64, 32, + 39, 7, 47, 15, 55, 23, 63, 31, + 38, 6, 46, 14, 54, 22, 62, 30, + 37, 5, 45, 13, 53, 21, 61, 29, + 36, 4, 44, 12, 52, 20, 60, 28, + 35, 3, 43, 11, 51, 19, 59, 27, + 34, 2, 42, 10, 50, 18, 58, 26, + 33, 1, 41, 9, 49, 17, 57, 25 +}; + +// Expansion table [6*8] +static const char EXPANSION[] = +{ + 32, 1, 2, 3, 4, 5, + 4, 5, 6, 7, 8, 9, + 8, 9, 10, 11, 12, 13, + 12, 13, 14, 15, 16, 17, + 16, 17, 18, 19, 20, 21, + 20, 21, 22, 23, 24, 25, + 24, 25, 26, 27, 28, 29, + 28, 29, 30, 31, 32, 1 +}; + +// The S-Box tables [8*16*4] +static const char SBOX[8][64] = +{ + { + // S1 + 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7, + 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8, + 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0, + 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13 +}, +{ + // S2 + 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10, + 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5, + 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15, + 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9 +}, +{ + // S3 + 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8, + 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1, + 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7, + 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12 +}, +{ + // S4 + 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15, + 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9, + 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4, + 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14 +}, +{ + // S5 + 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9, + 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6, + 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14, + 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3 +}, +{ + // S6 + 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11, + 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8, + 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6, + 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13 +}, +{ + // S7 + 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1, + 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6, + 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2, + 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12 +}, +{ + // S8 + 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7, + 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2, + 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8, + 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11 +} +}; + +// Post S-Box permutation [4*8] +static const char PBOX[] = +{ + 16, 7, 20, 21, + 29, 12, 28, 17, + 1, 15, 23, 26, + 5, 18, 31, 10, + 2, 8, 24, 14, + 32, 27, 3, 9, + 19, 13, 30, 6, + 22, 11, 4, 25 +}; + +// Permuted Choice 1 Table [7*8] +static const char PC1[] = +{ + 57, 49, 41, 33, 25, 17, 9, + 1, 58, 50, 42, 34, 26, 18, + 10, 2, 59, 51, 43, 35, 27, + 19, 11, 3, 60, 52, 44, 36, + + 63, 55, 47, 39, 31, 23, 15, + 7, 62, 54, 46, 38, 30, 22, + 14, 6, 61, 53, 45, 37, 29, + 21, 13, 5, 28, 20, 12, 4 +}; + +// Permuted Choice 2 Table [6*8] +static const char PC2[] = +{ + 14, 17, 11, 24, 1, 5, + 3, 28, 15, 6, 21, 10, + 23, 19, 12, 4, 26, 8, + 16, 7, 27, 20, 13, 2, + 41, 52, 31, 37, 47, 55, + 30, 40, 51, 45, 33, 48, + 44, 49, 39, 56, 34, 53, + 46, 42, 50, 36, 29, 32 +}; + +// Iteration Shift Array +static const char ITERATION_SHIFT[] = +{ + // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 + 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 +}; + +#endif // EXCRYPT_DES_DATA_H_ \ No newline at end of file diff --git a/main/libxsm3/excrypt_parve.c b/main/libxsm3/excrypt_parve.c new file mode 100644 index 0000000..bebb023 --- /dev/null +++ b/main/libxsm3/excrypt_parve.c @@ -0,0 +1,78 @@ +#include +#include + +#include "excrypt.h" + +void ExCryptParveEcb(const uint8_t* key, const uint8_t* sbox, const uint8_t* input, uint8_t* output) +{ + uint8_t block[9]; + + memcpy(block, input, 8); + block[8] = block[0]; + + for (int i = 8; i > 0; i--) + { + for (int j = 0; j < 8; j++) + { + uint8_t x = key[j] + block[j] + i; + uint8_t y = sbox[x] + block[j + 1]; + block[j + 1] = ROTL8(y, 1); + } + + block[0] = block[8]; + } + + memcpy(output, block, 8); +} + +void ExCryptParveCbcMac(const uint8_t* key, const uint8_t* sbox, const uint8_t* iv, const uint8_t* input, uint32_t input_size, uint8_t* output) +{ + uint64_t block; + uint64_t temp; + memcpy(&block, iv, 8); + + if (input_size >= 8) + { + for (uint32_t i = 0; i < input_size / 8; i++) + { + memcpy(&temp, input + (i * 8), sizeof(temp)); + block ^= temp; + ExCryptParveEcb(key, sbox, (uint8_t*)&block, (uint8_t*)&block); + } + } + + memcpy(output, &block, 8); +} + +void ExCryptChainAndSumMac(const uint32_t* cd, const uint32_t* ab, const uint32_t* input, uint32_t input_dwords, uint32_t* output) +{ + uint64_t out0 = 0; + uint64_t out1 = 0; + + uint32_t ab0 = SWAP32(ab[0]) % 0x7FFFFFFF; + uint32_t ab1 = SWAP32(ab[1]) % 0x7FFFFFFF; + uint32_t cd0 = SWAP32(cd[0]) % 0x7FFFFFFF; + uint32_t cd1 = SWAP32(cd[1]) % 0x7FFFFFFF; + + for (uint32_t i = 0; i < input_dwords / 2; i++) + { + out0 += (uint64_t)SWAP32(input[0]) * 0xE79A9C1; + out0 = (out0 % 0x7FFFFFFF) * ab0; + out0 += ab1; + out0 = out0 % 0x7FFFFFFF; + + out1 += out0; + + out0 = (uint64_t)(SWAP32(input[1]) + out0) * cd0; + out0 = (out0 % 0x7FFFFFFF) + cd1; + out0 = out0 % 0x7FFFFFFF; + + out1 += out0; + + input += 2; + } + out0 = SWAP32((out0 + ab1) % 0x7FFFFFFF); + out1 = SWAP32((out1 + cd1) % 0x7FFFFFFF); + memcpy(output, &out0, sizeof(uint32_t)); + memcpy(output+1, &out1, sizeof(uint32_t)); +} diff --git a/main/libxsm3/excrypt_parve.h b/main/libxsm3/excrypt_parve.h new file mode 100644 index 0000000..b7082df --- /dev/null +++ b/main/libxsm3/excrypt_parve.h @@ -0,0 +1,9 @@ +#ifndef EXCRYPT_PARVE_H_ +#define EXCRYPT_PARVE_H_ +// "Parve" functions, seem to be used during controller auth + +void ExCryptParveEcb(const uint8_t* key, const uint8_t* sbox, const uint8_t* input, uint8_t* output); +void ExCryptParveCbcMac(const uint8_t* key, const uint8_t* sbox, const uint8_t* iv, const uint8_t* input, uint32_t input_size, uint8_t* output); +void ExCryptChainAndSumMac(const uint32_t* cd, const uint32_t* ab, const uint32_t* input, uint32_t input_dwords, uint32_t* output); + +#endif // EXCRYPT_PARVE_H_ \ No newline at end of file diff --git a/main/libxsm3/excrypt_sha.c b/main/libxsm3/excrypt_sha.c new file mode 100644 index 0000000..a68e346 --- /dev/null +++ b/main/libxsm3/excrypt_sha.c @@ -0,0 +1,155 @@ +#include +#include + +#include "excrypt.h" + +// SHA1 code based on https://github.com/mohaps/TinySHA1 + +void sha1_process_block(EXCRYPT_SHA_STATE* state) +{ + uint32_t w[80]; + for (size_t i = 0; i < 16; i++) { + w[i] = ((uint32_t)state->buffer[i * 4 + 0] << 24); + w[i] |= ((uint32_t)state->buffer[i * 4 + 1] << 16); + w[i] |= ((uint32_t)state->buffer[i * 4 + 2] << 8); + w[i] |= ((uint32_t)state->buffer[i * 4 + 3]); + } + for (size_t i = 16; i < 80; i++) { + w[i] = ROTL32((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]), 1); + } + + uint32_t a = state->state[0]; + uint32_t b = state->state[1]; + uint32_t c = state->state[2]; + uint32_t d = state->state[3]; + uint32_t e = state->state[4]; + + for (int i = 0; i < 80; ++i) { + uint32_t f = 0; + uint32_t k = 0; + + if (i < 20) { + f = (b & c) | (~b & d); + k = 0x5A827999; + } + else if (i < 40) { + f = b ^ c ^ d; + k = 0x6ED9EBA1; + } + else if (i < 60) { + f = (b & c) | (b & d) | (c & d); + k = 0x8F1BBCDC; + } + else { + f = b ^ c ^ d; + k = 0xCA62C1D6; + } + uint32_t temp = ROTL32(a, 5) + f + e + k + w[i]; + e = d; + d = c; + c = ROTL32(b, 30); + b = a; + a = temp; + } + + state->state[0] += a; + state->state[1] += b; + state->state[2] += c; + state->state[3] += d; + state->state[4] += e; +} + +void sha1_process_byte(EXCRYPT_SHA_STATE* state, uint8_t octet) +{ + uint32_t offset = state->count++ & 0x3F; + state->buffer[offset] = octet; + if ((state->count & 0x3F) == 0) + { + sha1_process_block(state); + } +} + +void ExCryptShaInit(EXCRYPT_SHA_STATE* state) +{ + state->count = 0; + state->state[0] = 0x67452301; + state->state[1] = 0xEFCDAB89; + state->state[2] = 0x98BADCFE; + state->state[3] = 0x10325476; + state->state[4] = 0xC3D2E1F0; +} + +void ExCryptShaUpdate(EXCRYPT_SHA_STATE* state, const uint8_t* input, uint32_t input_size) +{ + for (uint32_t i = 0; i < input_size; i++) + { + sha1_process_byte(state, input[i]); + } +} + +void ExCryptShaFinal(EXCRYPT_SHA_STATE* state, uint8_t* output, uint32_t output_size) +{ + uint64_t bit_count = (uint64_t)state->count * 8; + + sha1_process_byte(state, 0x80); + + if ((state->count & 0x3F) > 56) + { + while ((state->count & 0x3F) != 0) + { + sha1_process_byte(state, 0); + } + while ((state->count & 0x3F) < 56) + { + sha1_process_byte(state, 0); + } + } + else + { + while ((state->count & 0x3F) < 56) + { + sha1_process_byte(state, 0); + } + } + + sha1_process_byte(state, 0); + sha1_process_byte(state, 0); + sha1_process_byte(state, 0); + sha1_process_byte(state, 0); + + sha1_process_byte(state, (uint8_t)((bit_count >> 24) & 0xFF)); + sha1_process_byte(state, (uint8_t)((bit_count >> 16) & 0xFF)); + sha1_process_byte(state, (uint8_t)((bit_count >> 8) & 0xFF)); + sha1_process_byte(state, (uint8_t)((bit_count) & 0xFF)); + + //sha1_process_block(state); + uint32_t result[5]; + result[0] = SWAP32(state->state[0]); + result[1] = SWAP32(state->state[1]); + result[2] = SWAP32(state->state[2]); + result[3] = SWAP32(state->state[3]); + result[4] = SWAP32(state->state[4]); + memcpy(output, result, 0x14); +} + +void ExCryptSha(const uint8_t* input1, uint32_t input1_size, const uint8_t* input2, uint32_t input2_size, + const uint8_t* input3, uint32_t input3_size, uint8_t* output, uint32_t output_size) +{ + EXCRYPT_SHA_STATE state[1]; + ExCryptShaInit(state); + + if (input1 && input1_size) + { + ExCryptShaUpdate(state, input1, input1_size); + } + if (input2 && input2_size) + { + ExCryptShaUpdate(state, input2, input2_size); + } + if (input3 && input3_size) + { + ExCryptShaUpdate(state, input3, input3_size); + } + + ExCryptShaFinal(state, output, output_size); +} \ No newline at end of file diff --git a/main/libxsm3/excrypt_sha.h b/main/libxsm3/excrypt_sha.h new file mode 100644 index 0000000..80024d8 --- /dev/null +++ b/main/libxsm3/excrypt_sha.h @@ -0,0 +1,18 @@ +#ifndef EXCRYPT_SHA_H_ +#define EXCRYPT_SHA_H_ +// SHA1 hash & HMAC algorithm + +typedef struct _EXCRYPT_SHA_STATE +{ + uint32_t count; + uint32_t state[5]; + uint8_t buffer[64]; +} EXCRYPT_SHA_STATE; + +void ExCryptShaInit(EXCRYPT_SHA_STATE* state); +void ExCryptShaUpdate(EXCRYPT_SHA_STATE* state, const uint8_t* input, uint32_t input_size); +void ExCryptShaFinal(EXCRYPT_SHA_STATE* state, uint8_t* output, uint32_t output_size); +void ExCryptSha(const uint8_t* input1, uint32_t input1_size, const uint8_t* input2, uint32_t input2_size, + const uint8_t* input3, uint32_t input3_size, uint8_t* output, uint32_t output_size); + +#endif // EXCRYPT_SHA_H_ \ No newline at end of file diff --git a/main/libxsm3/usbdsec.c b/main/libxsm3/usbdsec.c new file mode 100644 index 0000000..d5ab64e --- /dev/null +++ b/main/libxsm3/usbdsec.c @@ -0,0 +1,153 @@ +/* + usbdsec.c - part of libxsm3 + Copyright (C) 2013 oct0xor + Copyright (C) 2022 InvoxiPlayGames + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include +#include +#include "excrypt.h" + +static uint8_t UsbdSecSboxData[256] __attribute__ ((aligned(4))) = { + 0xB0, 0x3D, 0x9B, 0x70, 0xF3, 0xC7, 0x80, 0x60, + 0x73, 0x9F, 0x6C, 0xC0, 0xF1, 0x3D, 0xBB, 0x40, + 0xB3, 0xC8, 0x37, 0x14, 0xDF, 0x49, 0xDA, 0xD4, + 0x48, 0x22, 0x78, 0x80, 0x6E, 0xCD, 0xE7, 0x00, + 0x81, 0x86, 0x68, 0xE1, 0x5D, 0x7C, 0x54, 0x2C, + 0x55, 0x7B, 0xEF, 0x48, 0x42, 0x7B, 0x3B, 0x68, + 0xE3, 0xDB, 0xAA, 0xC0, 0x0F, 0xA9, 0x96, 0x20, + 0x95, 0x05, 0x93, 0x94, 0x9A, 0xF6, 0xA3, 0x64, + 0x5D, 0xCC, 0x76, 0x00, 0xE5, 0x08, 0x19, 0xE8, + 0x8D, 0x29, 0xD7, 0x4C, 0x21, 0x91, 0x17, 0xF4, + 0xBC, 0x6A, 0xB3, 0x80, 0x83, 0xC6, 0xD4, 0x90, + 0x9B, 0xAE, 0x0E, 0xFE, 0x2E, 0x4A, 0xF2, 0x00, + 0x73, 0x88, 0xD9, 0x40, 0x66, 0xC5, 0xD4, 0x08, + 0x57, 0xB1, 0x89, 0x48, 0xDC, 0x54, 0xFC, 0x43, + 0x6A, 0x26, 0x87, 0xB8, 0x09, 0x5F, 0xCE, 0x80, + 0xE4, 0x0B, 0x05, 0x9C, 0x24, 0xF3, 0xDE, 0xE2, + 0x3E, 0xEC, 0x38, 0x8A, 0xA2, 0x55, 0xA4, 0x50, + 0x4E, 0x4B, 0xE9, 0x58, 0x7F, 0x9F, 0x7D, 0x80, + 0x23, 0x0C, 0x4D, 0x80, 0x05, 0x44, 0x26, 0xB8, + 0xE9, 0xD8, 0xBC, 0xE6, 0x76, 0x3A, 0x6E, 0xA4, + 0x19, 0xDE, 0xC2, 0xD0, 0xC4, 0xBC, 0xC3, 0x5C, + 0x59, 0xDF, 0x16, 0x46, 0x39, 0x70, 0xF4, 0xEE, + 0x2D, 0x58, 0x5A, 0xA8, 0x17, 0x86, 0x6B, 0x60, + 0x29, 0x58, 0x4D, 0xD2, 0x5F, 0x28, 0x7A, 0xD8, + 0x8E, 0x79, 0xEA, 0x82, 0x94, 0x33, 0x31, 0x81, + 0xD9, 0x22, 0xD5, 0x10, 0xDA, 0x92, 0xA0, 0x7D, + 0x3D, 0xDA, 0xAC, 0x1C, 0xA2, 0x53, 0x31, 0xB8, + 0x3C, 0x96, 0x52, 0x00, 0x82, 0x6B, 0x56, 0xA0, + 0xD3, 0xC2, 0x40, 0xC7, 0x1B, 0x7F, 0xDC, 0x01, + 0x72, 0x70, 0xB1, 0x8C, 0x01, 0x09, 0x09, 0x36, + 0xFC, 0x97, 0xEA, 0xDE, 0xE3, 0x0D, 0xAE, 0x7E, + 0xE3, 0x0D, 0xAE, 0x7E, 0x33, 0x69, 0x80, 0x40 +}; + +static uint8_t UsbdSecPlainTextData[128] __attribute__ ((aligned(4))) = { + 0xD1, 0xD2, 0xF2, 0x80, 0x6E, 0xBA, 0x0C, 0xC0, + 0xB6, 0xC4, 0xC9, 0xD8, 0x61, 0x75, 0x1D, 0x1A, + 0x3F, 0x95, 0x58, 0xBE, 0xD8, 0x0D, 0xE2, 0xC0, + 0xD0, 0x21, 0x79, 0x20, 0x65, 0x2D, 0x99, 0x40, + 0x3C, 0x96, 0x52, 0x00, 0x1B, 0x7F, 0xDC, 0x01, + 0x82, 0x1C, 0x13, 0xD8, 0x33, 0x69, 0x80, 0x40, + 0xFC, 0x97, 0xEA, 0xDE, 0x08, 0xEA, 0x14, 0xDC, + 0xEB, 0x0F, 0x6A, 0x18, 0x6F, 0x78, 0x2C, 0xB0, + 0xD3, 0xC2, 0x40, 0xC7, 0x82, 0x6B, 0x56, 0xA0, + 0x19, 0x09, 0x36, 0xE0, 0x72, 0x70, 0xB1, 0x8C, + 0xE3, 0x0D, 0xAE, 0x7E, 0x50, 0xA5, 0x2B, 0xE2, + 0xC9, 0xAF, 0xC7, 0x70, 0x1C, 0x29, 0x80, 0x56, + 0x24, 0xF0, 0x66, 0xFA, 0x02, 0x2B, 0x58, 0x98, + 0x8F, 0xE4, 0xD1, 0x3C, 0x6E, 0x38, 0x2A, 0xFF, + 0xB8, 0xFA, 0x35, 0xB0, 0x52, 0x49, 0xC5, 0xB4, + 0x66, 0xFA, 0x47, 0x55, 0x6C, 0x8D, 0x40, 0x08 +}; + +void UsbdSecXSM3AuthenticationCrypt(const uint8_t *key, const uint8_t *input, size_t length, uint8_t *output, uint8_t encrypt) { + EXCRYPT_DES3_STATE des; + uint64_t sk[3]; + uint8_t iv[8]; + + // clear local variables + memset(iv, 0, sizeof(iv)); + // run parity on the key + ExCryptDesParity(key, 0x10, (uint8_t *)sk); + sk[2] = sk[0]; + // set the key in the state and run triple-des cbc en/decryption on it + ExCryptDes3Key(&des, sk); + ExCryptDes3Cbc(&des, input, length, output, iv, encrypt); +} + +void UsbdSecXSM3AuthenticationMac(const uint8_t *key, uint8_t *salt, uint8_t *input, size_t length, uint8_t *output) { + EXCRYPT_DES3_STATE des3; + EXCRYPT_DES_STATE des; + uint64_t sk[3]; + uint8_t iv[8]; + uint8_t temp[8]; + uint64_t input_temp; + int i; + + // clear iv + temp value of stack junk + memset(iv, 0, sizeof(iv)); + memset(temp, 0, sizeof(temp)); + // run parity on the key + ExCryptDesParity(key, 0x10, (uint8_t *)sk); + sk[2] = sk[0]; + // set the key in our initial des state + ExCryptDesKey(&des, (uint8_t *)&sk[0]); + // if we have a salt, encrypt it into the temp value + if (salt) { + memcpy(&input_temp, salt, sizeof(input_temp)); + input_temp = SWAP64(SWAP64(input_temp) + 1); + memcpy(salt, &input_temp, sizeof(input_temp)); // no idea what this does + ExCryptDesEcb(&des, salt, temp, 1); + } + // for every 8 byte input block, xor the temp value with it and encrypt over itself + for (i = 0; i < length; i += 8) { + memcpy(&input_temp, input+i, sizeof(input_temp)); + *(uint64_t *)temp ^= input_temp; + ExCryptDesEcb(&des, temp, temp, 1); + } + // xor the highest bit of the temp value + temp[0] ^= 0x80; + // set the key and perform the final triple-des encryption + ExCryptDes3Key(&des3, sk); + ExCryptDes3Cbc(&des3, temp, 8, output, iv, 1); + // real kernel does the following, but the above works: + // XeCryptDesEcb(des_state_1, temp, temp, 1); + // XeCryptDesEcb(des_state_2, temp, temp, 0); + // XeCryptDesEcb(des_state_1, temp, output, 1); +} + +void UsbdSecXSMAuthenticationAcr(const uint8_t *console_id, const uint8_t *input, const uint8_t *key, uint8_t *output) { + uint8_t block[8]; + uint8_t iv[8]; + uint8_t ab[8]; + uint8_t cd[8]; + + // fill in the input block with the first 4 bytes of input data and the first 4 bytes of the console ID + memcpy(block, input, 4); + memcpy(block+4, console_id, 4); + // run custom "parve" crypto algorithms. idk whar they do + ExCryptParveEcb(key, UsbdSecSboxData, input + 0x10, iv); + ExCryptParveEcb(key, UsbdSecSboxData, block, cd); + ExCryptParveCbcMac(key, UsbdSecSboxData, iv, UsbdSecPlainTextData, 0x80, ab); + ExCryptChainAndSumMac((uint32_t *)cd, (uint32_t *)ab, (uint32_t *)UsbdSecPlainTextData, 0x20, (uint32_t *)output); + uint64_t current; + memcpy(¤t, output, sizeof(current)); + current ^= *(uint64_t *)ab; + memcpy(output, ¤t, sizeof(current)); +} \ No newline at end of file diff --git a/main/libxsm3/usbdsec.h b/main/libxsm3/usbdsec.h new file mode 100644 index 0000000..c36bf8a --- /dev/null +++ b/main/libxsm3/usbdsec.h @@ -0,0 +1,30 @@ +/* + usbdsec.h - part of libxsm3 + Copyright (C) 2022 InvoxiPlayGames + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef USBDSEC_H_ +#define USBDSEC_H_ + +#include +#include + +void UsbdSecXSM3AuthenticationCrypt(const uint8_t *key, const uint8_t *input, size_t length, uint8_t *output, uint8_t encrypt); +void UsbdSecXSM3AuthenticationMac(const uint8_t *key, const uint8_t *salt, uint8_t *input, size_t length, uint8_t *output); +void UsbdSecXSMAuthenticationAcr(const uint8_t *console_id, const uint8_t *input, const uint8_t *key, uint8_t *output); + +#endif // USBDSEC_H_ \ No newline at end of file diff --git a/main/libxsm3/xsm3.c b/main/libxsm3/xsm3.c new file mode 100644 index 0000000..97825e8 --- /dev/null +++ b/main/libxsm3/xsm3.c @@ -0,0 +1,292 @@ +/* + xsm3.c - part of libxsm3 + Copyright (C) 2022-2023 InvoxiPlayGames + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include +#include +#include +#include +#include +#if !defined(XSM3_EMBEDDED) +#include +#endif +#include "xsm3.h" +#include "esp_random.h" +#include "excrypt.h" +#include "usbdsec.h" + +// disable debugging by specifying XSM3_NO_DEBUGGING at compile time +#ifndef XSM3_NO_DEBUGGING +#define XSM3_printf printf +#else +#define XSM3_printf +#endif // XSM3_NO_DEBUGGING + +// constant variables +const uint8_t xsm3_id_data_ms_controller[0x1D] = { + 0x49, 0x4B, 0x00, 0x00, 0x17, 0x41, 0x41, 0x41, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x00, 0x00, 0x80, 0x02, 0x5E, 0x04, 0x8E, 0x02, + 0x03, 0x00, 0x01, 0x01, 0x16 +}; + +// static global keys from the keyvault (shared across every retail system) +static const uint8_t xsm3_key_0x1D[0x10] = { + 0xE3, 0x5B, 0xFB, 0x1C, 0xCD, 0xAD, 0x32, 0x5B, + 0xF7, 0x0E, 0x07, 0xFD, 0x62, 0x3D, 0xA7, 0xC4 +}; +static const uint8_t xsm3_key_0x1E[0x10] = { + 0x8F, 0x29, 0x08, 0x38, 0x0B, 0x5B, 0xFE, 0x68, + 0x7C, 0x26, 0x46, 0x2A, 0x51, 0xF2, 0xBC, 0x19 +}; + +// retail keys for generating 0x23/0x24 keys from console ID +static const uint8_t xsm3_root_key_0x23[0x10] = { + 0x82, 0x80, 0x78, 0x68, 0x3A, 0x52, 0x3A, 0x98, + 0x10, 0xF4, 0x0C, 0x12, 0x70, 0x66, 0xDC, 0xBA +}; +static const uint8_t xsm3_root_key_0x24[0x10] = { + 0x66, 0x62, 0x1A, 0x78, 0xF8, 0x60, 0x9C, 0x8A, + 0x26, 0x9A, 0x04, 0xAE, 0xD8, 0x5C, 0x1E, 0xC8 +}; + +/* +global device keys from devkit keyvaults +static const uint8_t xsm3_key_0x1D[0x10] = { + 0xC2, 0x15, 0xE5, 0x5E, 0xE5, 0x51, 0x94, 0x2A, + 0xEC, 0x3D, 0x45, 0xEC, 0xB6, 0xE6, 0xF2, 0x16 +}; +static const uint8_t xsm3_key_0x1E[0x10] = { + 0xC7, 0x45, 0xAD, 0x1F, 0x08, 0x0B, 0xD9, 0xE9, + 0x9B, 0x1C, 0x34, 0xE3, 0xA4, 0x6D, 0xC8, 0xC4 +}; +*/ + +// devkit recovery keys for generating 0x23/0x24 keys from console ID +// static const uint8_t xsm3_root_key_0x23[0x10] = { +// 0xB9, 0xE0, 0x9E, 0x68, 0x04, 0x83, 0x91, 0xB3, +// 0x32, 0x45, 0x7A, 0xDA, 0x43, 0x6B, 0x80, 0xAD +// }; +// static const uint8_t xsm3_root_key_0x24[0x10] = { +// 0x92, 0x5D, 0x29, 0x6E, 0xB0, 0x61, 0x0B, 0xF1, +// 0xD6, 0x29, 0x3B, 0xC8, 0xC7, 0xD9, 0x32, 0xBC +// }; + +// response to give to the given challenge command +uint8_t xsm3_challenge_response[0x30]; +// console id fetched from challenge init packet +uint8_t xsm3_console_id[0x8]; + +// buffer to store the first key fetched from the KV (0x23) +static uint8_t xsm3_kv_2des_key_1[0x10]; +// buffer to store the second key fetched from the KV (0x24) +static uint8_t xsm3_kv_2des_key_2[0x10]; +// have we been given a KV key yet? +static bool xsm3_has_kv_keys = false; + +// temporary buffer for decrypting packets +static uint8_t xsm3_decryption_buffer[0x30]; +// identification data for the current device +static uint8_t xsm3_identification_data[0x20]; +// random data sent from the console during the challenge init stage +static uint8_t xsm3_random_console_data[0x10]; +static uint8_t xsm3_random_console_data_enc[0x10]; +static uint8_t xsm3_random_console_data_swap[0x10]; +static uint8_t xsm3_random_console_data_swap_enc[0x10]; +// random data set by the controller during the challenge init stage +static uint8_t xsm3_random_controller_data[0x10]; +// hash of the decrypted data sent by the controller during challenge init +static uint8_t xsm3_challenge_init_hash[0x14]; + +void xsm3_initialise_state() { + // set all variables to all zeroes + memset(xsm3_challenge_response, 0, sizeof(xsm3_challenge_response)); + memset(xsm3_console_id, 0, sizeof(xsm3_console_id)); + memset(xsm3_kv_2des_key_1, 0, sizeof(xsm3_kv_2des_key_1)); + memset(xsm3_kv_2des_key_2, 0, sizeof(xsm3_kv_2des_key_2)); + memset(xsm3_decryption_buffer, 0, sizeof(xsm3_decryption_buffer)); + memset(xsm3_identification_data, 0, sizeof(xsm3_identification_data)); + memset(xsm3_random_console_data, 0, sizeof(xsm3_random_console_data)); + memset(xsm3_random_console_data_enc, 0, sizeof(xsm3_random_console_data_enc)); + memset(xsm3_random_console_data_swap, 0, sizeof(xsm3_random_console_data_swap)); + memset(xsm3_random_console_data_swap_enc, 0, sizeof(xsm3_random_console_data_swap_enc)); + memset(xsm3_random_controller_data, 0, sizeof(xsm3_random_controller_data)); + memset(xsm3_challenge_init_hash, 0, sizeof(xsm3_challenge_init_hash)); +} + +static uint8_t xsm3_calculate_checksum(const uint8_t * packet) { + // packet length in header doesn't include the header itself + uint8_t packet_length = packet[0x4] + 0x5; + uint8_t checksum = 0x00; + int i = 0; + // checksum is just a XOR over all packet bytes + for(i = 0x5; i < packet_length; i++) { + checksum ^= packet[i]; + } + // last byte of the packet is the checksum + return checksum; +} + +static bool xsm3_verify_checksum(const uint8_t * packet) { + // packet length in header doesn't include the header itself + uint8_t packet_length = packet[0x4] + 0x5; + // last byte of the packet is the checksum + return (xsm3_calculate_checksum(packet) == packet[packet_length]); +} + +void xsm3_set_identification_data(const uint8_t id_data[0x1D]) { + // validate the checksum + if (!xsm3_verify_checksum(id_data)) { + XSM3_printf("[ Checksum failed when setting identification data! ]\n"); + } + + // skip over the packet header + id_data += 0x5; + + // prepare the xsm3_identification_data buffer + + // contains serial number (len: 0xC), unknown (len: 0x2) and the "category node" to use (len: 0x1) + memcpy(xsm3_identification_data, id_data, 0xF); + // vendor ID + memcpy(xsm3_identification_data + 0x10, id_data + 0xF, sizeof(unsigned short)); + // product ID + memcpy(xsm3_identification_data + 0x12, id_data + 0x11, sizeof(unsigned short)); + // unknown + memcpy(xsm3_identification_data + 0x14, id_data + 0x13, sizeof(unsigned char)); + // unknown + memcpy(xsm3_identification_data + 0x15, id_data + 0x16, sizeof(unsigned char)); + // unknown + memcpy(xsm3_identification_data + 0x16, id_data + 0x14, sizeof(unsigned short)); +} + +void xsm3_import_kv_keys(const uint8_t key1[0x10], const uint8_t key2[0x10]) { + xsm3_has_kv_keys = true; + // copy the provided keys into our buffers + memcpy(xsm3_kv_2des_key_1, key1, sizeof(xsm3_kv_2des_key_1)); + memcpy(xsm3_kv_2des_key_2, key2, sizeof(xsm3_kv_2des_key_2)); +} + +void xsm3_generate_kv_keys(const uint8_t console_id[0x8]) { + xsm3_has_kv_keys = true; + // make a sha-1 hash of the console id + uint8_t console_id_hash[0x14]; + ExCryptSha(console_id, 0x8, NULL, 0, NULL, 0, console_id_hash, 0x14); + // encrypt it with the root keys for 1st party controllers + UsbdSecXSM3AuthenticationCrypt(xsm3_root_key_0x23, console_id_hash, 0x10, xsm3_kv_2des_key_1, 1); + UsbdSecXSM3AuthenticationCrypt(xsm3_root_key_0x24, console_id_hash + 0x4, 0x10, xsm3_kv_2des_key_2, 1); +} + +void xsm3_do_challenge_init(uint8_t challenge_packet[0x22]) { + uint8_t incoming_packet_mac[0x8]; + uint8_t response_packet_mac[0x8]; + int i = 0; + + // validate the checksum + if (!xsm3_verify_checksum(challenge_packet)) { + XSM3_printf("[ Checksum failed when validating challenge init! ]\n"); + } + + // decrypt the packet content using the static key from the keyvault + UsbdSecXSM3AuthenticationCrypt(xsm3_key_0x1D, challenge_packet + 0x5, 0x18, xsm3_decryption_buffer, 0); + // first 0x10 bytes are random data + memcpy(xsm3_random_console_data, xsm3_decryption_buffer, 0x10); + // next 0x8 bytes are from the console certificate + memcpy(xsm3_console_id, xsm3_decryption_buffer + 0x10, 0x8); + // last 4 bytes of the packet are the last 4 bytes of the MAC + UsbdSecXSM3AuthenticationMac(xsm3_key_0x1E, NULL, challenge_packet + 5, 0x18, incoming_packet_mac); + // validate the MAC + if (memcmp(incoming_packet_mac + 4, challenge_packet + 0x5 + 0x18, 0x4) != 0) { + XSM3_printf("[ MAC failed when validating challenge init! ]\n"); + } + + // if we haven't got our KV keys yet, generate it + if (!xsm3_has_kv_keys) xsm3_generate_kv_keys(xsm3_console_id); + + // the random value is swapped at an 8 byte boundary + memcpy(xsm3_random_console_data_swap, xsm3_random_console_data + 0x8, 0x8); + memcpy(xsm3_random_console_data_swap + 0x8, xsm3_random_console_data, 0x8); + // and then encrypted - the regular value encrypted with key 1, the swapped value encrypted with key 2 + UsbdSecXSM3AuthenticationCrypt(xsm3_kv_2des_key_1, xsm3_random_console_data, 0x10, xsm3_random_console_data_enc, 1); + UsbdSecXSM3AuthenticationCrypt(xsm3_kv_2des_key_2, xsm3_random_console_data_swap, 0x10, xsm3_random_console_data_swap_enc, 1); + + // generate random data + for (i = 0; i < 0x10; i++) { + xsm3_random_controller_data[i] = (uint8_t)(esp_random() & 0xFF); + } + + // clear response buffers + memset(xsm3_challenge_response, 0, sizeof(xsm3_challenge_response)); + memset(xsm3_decryption_buffer, 0, sizeof(xsm3_decryption_buffer)); + // set header and packet length of challenge response + xsm3_challenge_response[0] = 0x49; // packet magic + xsm3_challenge_response[1] = 0x4C; + xsm3_challenge_response[4] = 0x28; // packet length + // copy random controller, random console data to the encryption buffer + memcpy(xsm3_decryption_buffer, xsm3_random_controller_data, 0x10); + memcpy(xsm3_decryption_buffer + 0x10, xsm3_random_console_data, 0x10); + // save the sha1 hash of the decrypted contents for later + ExCryptSha(xsm3_decryption_buffer, 0x20, NULL, 0, NULL, 0, xsm3_challenge_init_hash, 0x14); + + // encrypt challenge response packet using the encrypted random key + UsbdSecXSM3AuthenticationCrypt(xsm3_random_console_data_enc, xsm3_decryption_buffer, 0x20, xsm3_challenge_response + 0x5, 1); + // calculate MAC using the encrypted swapped random key and use it to calculate ACR + UsbdSecXSM3AuthenticationMac(xsm3_random_console_data_swap_enc, NULL, xsm3_challenge_response + 0x5, 0x20, response_packet_mac); + // calculate ACR and append to the end of the xsm3_challenge_response + UsbdSecXSMAuthenticationAcr(xsm3_console_id, xsm3_identification_data, response_packet_mac, xsm3_challenge_response + 0x5 + 0x20); + // calculate the checksum for the response packet + xsm3_challenge_response[0x5 + 0x28] = xsm3_calculate_checksum(xsm3_challenge_response); + + // the console random value changes slightly after this point + memcpy(xsm3_random_console_data, xsm3_random_controller_data + 0xC, 0x4); + memcpy(xsm3_random_console_data + 0x4, xsm3_random_console_data + 0xC, 0x4); +} + +void xsm3_do_challenge_verify(uint8_t challenge_packet[0x16]) { + uint8_t incoming_packet_mac[0x8]; + + // validate the checksum + if (!xsm3_verify_checksum(challenge_packet)) { + XSM3_printf("[ Checksum failed when validating challenge verify! ]\n"); + } + + // decrypt the packet using the controller generated random value + UsbdSecXSM3AuthenticationCrypt(xsm3_random_controller_data, challenge_packet + 0x5, 0x8, xsm3_decryption_buffer, 0); + // replace part of our random encryption value with the decrypted buffer + memcpy(xsm3_random_console_data + 0x8, xsm3_decryption_buffer, 0x8); + + // calculate the MAC of the incoming packet + UsbdSecXSM3AuthenticationMac(xsm3_challenge_init_hash, xsm3_random_console_data, challenge_packet + 0x5, 0x8, incoming_packet_mac); + // validate the MAC + if (memcmp(incoming_packet_mac, challenge_packet + 0x5 + 0x8, 0x8) != 0) { + XSM3_printf("[ MAC failed when validating challenge verify! ]\n"); + } + // clear response buffers + memset(xsm3_challenge_response, 0, sizeof(xsm3_challenge_response)); + memset(xsm3_decryption_buffer, 0, sizeof(xsm3_decryption_buffer)); + // set header and packet length of challenge response + xsm3_challenge_response[0] = 0x49; // packet magic + xsm3_challenge_response[1] = 0x4C; + xsm3_challenge_response[4] = 0x10; // packet length + // calculate the ACR value and encrypt it into the outgoing packet using the encrypted random + UsbdSecXSMAuthenticationAcr(xsm3_console_id, xsm3_identification_data, xsm3_random_console_data + 0x8, xsm3_decryption_buffer); + UsbdSecXSM3AuthenticationCrypt(xsm3_random_console_data_enc, xsm3_decryption_buffer, 0x8, xsm3_challenge_response + 0x5, 1); + // calculate the MAC of the encrypted packet and append it to the end + UsbdSecXSM3AuthenticationMac(xsm3_random_console_data_swap_enc, xsm3_random_console_data, xsm3_challenge_response + 0x5, 0x8, xsm3_challenge_response + 0x5 + 0x8); + // calculate the checksum for the response packet + xsm3_challenge_response[0x5 + 0x10] = xsm3_calculate_checksum(xsm3_challenge_response); +} diff --git a/main/libxsm3/xsm3.h b/main/libxsm3/xsm3.h new file mode 100644 index 0000000..93e985b --- /dev/null +++ b/main/libxsm3/xsm3.h @@ -0,0 +1,51 @@ +/* + xsm3.h - part of libxsm3 + Copyright (C) 2022 InvoxiPlayGames + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef XSM3_H_ +#define XSM3_H_ + +#include +#include +#include + +// Identification data taken from an official wired controller. (Serial number is static.) +extern const uint8_t xsm3_id_data_ms_controller[0x1D]; + +// The response data from the previously completed challenge. +extern uint8_t xsm3_challenge_response[0x30]; + +// The console ID fetched from the console after request 0x82. +extern uint8_t xsm3_console_id[0x8]; + +// Clears the state of the XSM3 internal variables. +void xsm3_initialise_state(); + +// Sets the identification data to use. +void xsm3_set_identification_data(const uint8_t id_data[0x1D]); + +// Imports the console-specific keys (GetKey index 0x23 and 0x24 for wired controllers) into the current state. +void xsm3_import_kv_keys(const uint8_t key1[0x10], const uint8_t key2[0x10]); + +// Initialises the XSM3 state using information from the challenge init packet (0x82) and places a response in xsm3_challenge_response. +void xsm3_do_challenge_init(uint8_t challenge_packet[0x22]); + +// Completes a verify challenge passed from request 0x87 and places the response data in xsm3_challenge_response. +void xsm3_do_challenge_verify(uint8_t challenge_packet[0x16]); + +#endif // XSM3_H_ \ No newline at end of file diff --git a/main/main.c b/main/main.c new file mode 100644 index 0000000..f8ebd3a --- /dev/null +++ b/main/main.c @@ -0,0 +1,99 @@ +#include +#include +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "esp_system.h" +#include "esp_log.h" + +#include "board_esp32_s3_zero.h" +#include "controller_state.h" +#include "status_led.h" +#include "profile_manager.h" +#include "input_calibration.h" +#include "console_output/usb_gamepad.h" +#include "ble_hid_host.h" +#include "config_server.h" +#include "version.h" + +static const char *TAG = "APP_MAIN"; + +/* Callback invoked whenever the user switches console emulation profile */ +static void on_profile_changed(console_mode_t new_mode) +{ + ESP_LOGI(TAG, "Profile changed event: Reconfiguring USB for [%s]", profile_manager_mode_name(new_mode)); + usb_gamepad_change_mode(new_mode); +} + +/* Callback invoked whenever a wireless BLE controller sends an input report */ +static void on_controller_report(const controller_state_t *state) +{ + /* Apply user deadzones, axis inversions, and button swaps */ + controller_state_t calibrated; + input_calibration_apply(state, &calibrated); + + /* Forward translated report to host console via USB */ + usb_gamepad_send_state(&calibrated); + + /* Update live visualizer state if Config AP is active */ + if (config_server_is_active()) { + config_server_set_latest_state(&calibrated); + } +} + +void app_main(void) +{ + ESP_LOGI(TAG, "====================================================="); + ESP_LOGI(TAG, " ESP32-S3-Zero HID Translation Layer Initializing "); + ESP_LOGI(TAG, " Wireless BLE Input -> USB Console Gamepad Output "); + ESP_LOGI(TAG, "====================================================="); + + /* 1. Initialize Onboard WS2812 RGB LED (GPIO21) */ + ESP_ERROR_CHECK(status_led_init()); + + /* 2. Initialize Profile Manager (NVS + BOOT Button on GPIO0) */ + ESP_ERROR_CHECK(profile_manager_init(on_profile_changed)); + console_mode_t initial_mode = profile_manager_get_mode(); + + /* 3. Initialize Input Calibration & Button Remapping */ + ESP_ERROR_CHECK(input_calibration_init()); + + /* 3. Initialize USB Gamepad Device via TinyUSB (Native USB GPIO19/20) */ + ESP_ERROR_CHECK(usb_gamepad_init(initial_mode)); + + /* 4. Initialize BLE Central Host (NimBLE Scanner & Pairing) */ + ESP_ERROR_CHECK(ble_hid_host_init(on_controller_report)); + + /* 5. Initialize Config Server Manager Task */ + ESP_ERROR_CHECK(config_server_init()); + + /* 6. Auto-connect to home Wi-Fi and enable mDNS / OTA if credentials exist */ + if (config_server_has_saved_wifi()) { + ESP_LOGI(TAG, "Saved Wi-Fi credentials found: Auto-starting Station & mDNS for remote OTA access"); + config_server_request_start(); + } + + ESP_LOGI(TAG, "====================================================="); + ESP_LOGI(TAG, " __ __ _ _ _____ "); + ESP_LOGI(TAG, " | \\/ (_) (_)/ ____| "); + ESP_LOGI(TAG, " | \\ / |_ _ __ ___ _| | ___ _ __ "); + ESP_LOGI(TAG, " | |\\/| | | '_ ` _ \\| | | / _ \\| '_ \\ "); + ESP_LOGI(TAG, " | | | | | | | | | | | |___| (_) | | | |"); + ESP_LOGI(TAG, " |_| |_|_|_| |_| |_|_|\\_____\\___/|_| |_|"); + ESP_LOGI(TAG, " Universal Gamepad Bridge v%s (%s)", MIMICON_VERSION_STRING, MIMICON_BUILD_NAME); + ESP_LOGI(TAG, "====================================================="); + ESP_LOGI(TAG, "Target Console Mode: %s", profile_manager_mode_name(initial_mode)); + ESP_LOGI(TAG, "How to launch Config Web Server:"); + ESP_LOGI(TAG, " - Hold [SELECT + START + D-PAD UP] on controller for 1.5s"); + ESP_LOGI(TAG, " - Or hold BOOT button (GPIO0) on the ESP32 for 2s"); + ESP_LOGI(TAG, " - Connect to Wi-Fi [MimiCon-Setup] -> http://192.168.4.1/"); + ESP_LOGI(TAG, " - Or via Home Network: http://mimicon.local/ (or http://esp32-hid.local/)"); + ESP_LOGI(TAG, "How to switch console profiles instantly:"); + ESP_LOGI(TAG, " - Hold [START + Face Button] for 1.5s (Configurable in Web Portal)"); + ESP_LOGI(TAG, " - Supported: Switch, PC, PS3, PS4, Xbox 360, Original Xbox, Mouse/Keys"); + ESP_LOGI(TAG, " - Or press physical BOOT button (GPIO0) to cycle modes"); + ESP_LOGI(TAG, "====================================================="); + + while (1) { + vTaskDelay(pdMS_TO_TICKS(1000)); + } +} diff --git a/main/parsers/controller_parser.h b/main/parsers/controller_parser.h new file mode 100644 index 0000000..0510ec1 --- /dev/null +++ b/main/parsers/controller_parser.h @@ -0,0 +1,60 @@ +#pragma once + +#include +#include +#include +#include "controller_state.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + CONTROLLER_TYPE_UNKNOWN = 0, + CONTROLLER_TYPE_XBOX_BLE, + CONTROLLER_TYPE_GENERIC_HOGP, + CONTROLLER_TYPE_8BITDO, + CONTROLLER_TYPE_STADIA, +} controller_type_t; + +/** + * @brief Scale an 8-bit analog stick axis (0..255, 128 centered) to signed 16-bit (-32768..32767) + * with overflow protection. + */ +static inline int16_t scale_axis_8bit(uint8_t raw, bool invert) +{ + int32_t val = invert ? ((int32_t)128 - raw) * 256 : ((int32_t)raw - 128) * 256; + if (val > 32767) val = 32767; + if (val < -32768) val = -32768; + return (int16_t)val; +} + +/** + * @brief Parse a standard 0-indexed 8-way Hat Switch (D-Pad). + * 0=Up, 1=Up-Right, 2=Right, 3=Down-Right, 4=Down, 5=Down-Left, 6=Left, 7=Up-Left, 8=Centered + */ +static inline void parse_hat_switch_8way(uint8_t hat, controller_state_t *out_state) +{ + hat &= 0x0F; + if (hat < 8) { + out_state->dpad_up = (hat == 0 || hat == 1 || hat == 7) ? 1 : 0; + out_state->dpad_right = (hat == 1 || hat == 2 || hat == 3) ? 1 : 0; + out_state->dpad_down = (hat == 3 || hat == 4 || hat == 5) ? 1 : 0; + out_state->dpad_left = (hat == 5 || hat == 6 || hat == 7) ? 1 : 0; + } +} + +/** + * @brief Base parser function prototype + */ +typedef bool (*controller_parse_fn_t)(const uint8_t *report, size_t len, controller_state_t *out_state); + +typedef struct { + const char *name; + controller_type_t type; + controller_parse_fn_t parse; +} controller_driver_t; + +#ifdef __cplusplus +} +#endif diff --git a/main/parsers/parser_8bitdo.c b/main/parsers/parser_8bitdo.c new file mode 100644 index 0000000..daa1c72 --- /dev/null +++ b/main/parsers/parser_8bitdo.c @@ -0,0 +1,196 @@ +#include "parser_8bitdo.h" +#include "parser_xbox_ble.h" +#include + +static bool parse_8bitdo_switch_simple(const uint8_t *data, size_t len, controller_state_t *out_state) +{ + if (len < 8) return false; + + controller_state_reset(out_state); + + /* Byte 1: Buttons Low */ + uint8_t b1 = data[1]; + /* Standard Switch layout: Y (West), B (South), A (East), X (North) */ + out_state->btn_y = (b1 & 0x01) ? 1 : 0; + out_state->btn_b = (b1 & 0x02) ? 1 : 0; + out_state->btn_a = (b1 & 0x04) ? 1 : 0; + out_state->btn_x = (b1 & 0x08) ? 1 : 0; + out_state->btn_lb = (b1 & 0x10) ? 1 : 0; /* L1 */ + out_state->btn_rb = (b1 & 0x20) ? 1 : 0; /* R1 */ + out_state->btn_lt = (b1 & 0x40) ? 1 : 0; /* ZL / L2 */ + out_state->btn_rt = (b1 & 0x80) ? 1 : 0; /* ZR / R2 */ + + /* Byte 2: Buttons High */ + uint8_t b2 = data[2]; + out_state->btn_select = (b2 & 0x01) ? 1 : 0; /* Minus */ + out_state->btn_start = (b2 & 0x02) ? 1 : 0; /* Plus */ + out_state->btn_l3 = (b2 & 0x04) ? 1 : 0; + out_state->btn_r3 = (b2 & 0x08) ? 1 : 0; + out_state->btn_system = (b2 & 0x10) ? 1 : 0; /* Home */ + out_state->btn_share = (b2 & 0x20) ? 1 : 0; /* Capture / Star */ + + /* Byte 3: Hat Switch (D-Pad) */ + parse_hat_switch_8way(data[3], out_state); + + /* Bytes 4..7: Analog Sticks (0..255, 128 centered) */ + uint8_t raw_lx = data[4]; + uint8_t raw_ly = data[5]; + uint8_t raw_rx = data[6]; + uint8_t raw_ry = data[7]; + + out_state->lx = scale_axis_8bit(raw_lx, false); + out_state->ly = scale_axis_8bit(raw_ly, true); + out_state->rx = scale_axis_8bit(raw_rx, false); + out_state->ry = scale_axis_8bit(raw_ry, true); + + /* Analog Triggers */ + if (len >= 10) { + out_state->lt = data[8]; + out_state->rt = data[9]; + if (out_state->lt > 30) out_state->btn_lt = 1; + if (out_state->rt > 30) out_state->btn_rt = 1; + } else { + out_state->lt = out_state->btn_lt ? 255 : 0; + out_state->rt = out_state->btn_rt ? 255 : 0; + } + + return true; +} + +static bool parse_8bitdo_switch_full(const uint8_t *data, size_t len, controller_state_t *out_state) +{ + if (len < 12) return false; + + controller_state_reset(out_state); + + /* Byte 3: Buttons 1 */ + uint8_t b3 = data[3]; + out_state->btn_y = (b3 & 0x01) ? 1 : 0; + out_state->btn_x = (b3 & 0x02) ? 1 : 0; + out_state->btn_b = (b3 & 0x04) ? 1 : 0; + out_state->btn_a = (b3 & 0x08) ? 1 : 0; + out_state->btn_rb = (b3 & 0x40) ? 1 : 0; /* R */ + out_state->btn_rt = (b3 & 0x80) ? 1 : 0; /* ZR */ + + /* Byte 4: Buttons 2 */ + uint8_t b4 = data[4]; + out_state->btn_select = (b4 & 0x01) ? 1 : 0; /* Minus */ + out_state->btn_start = (b4 & 0x02) ? 1 : 0; /* Plus */ + out_state->btn_r3 = (b4 & 0x04) ? 1 : 0; + out_state->btn_l3 = (b4 & 0x08) ? 1 : 0; + out_state->btn_system = (b4 & 0x10) ? 1 : 0; /* Home */ + out_state->btn_share = (b4 & 0x20) ? 1 : 0; /* Capture */ + + /* Byte 5: D-Pad & Left shoulders */ + uint8_t b5 = data[5]; + out_state->dpad_down = (b5 & 0x01) ? 1 : 0; + out_state->dpad_up = (b5 & 0x02) ? 1 : 0; + out_state->dpad_right = (b5 & 0x04) ? 1 : 0; + out_state->dpad_left = (b5 & 0x08) ? 1 : 0; + out_state->btn_lb = (b5 & 0x40) ? 1 : 0; /* L */ + out_state->btn_lt = (b5 & 0x80) ? 1 : 0; /* ZL */ + + /* Analog Sticks: 12-bit packed values (0..4095, center ~2048) */ + uint16_t lx_12 = (uint16_t)(data[6] | ((data[7] & 0x0F) << 8)); + uint16_t ly_12 = (uint16_t)((data[7] >> 4) | (data[8] << 4)); + uint16_t rx_12 = (uint16_t)(data[9] | ((data[10] & 0x0F) << 8)); + uint16_t ry_12 = (uint16_t)((data[10] >> 4) | (data[11] << 4)); + + out_state->lx = (int16_t)(((int32_t)lx_12 - 2048) * 16); + out_state->ly = (int16_t)(((int32_t)2048 - ly_12) * 16); /* Inverted Y */ + out_state->rx = (int16_t)(((int32_t)rx_12 - 2048) * 16); + out_state->ry = (int16_t)(((int32_t)2048 - ry_12) * 16); + + out_state->lt = out_state->btn_lt ? 255 : 0; + out_state->rt = out_state->btn_rt ? 255 : 0; + + return true; +} + +static bool parse_8bitdo_dinput(const uint8_t *data, size_t len, controller_state_t *out_state) +{ + if (len < 6) return false; + + controller_state_reset(out_state); + + /* Byte 0..3: LX, LY, RX, RY (0..255, 128 centered) */ + uint8_t raw_lx = data[0]; + uint8_t raw_ly = data[1]; + uint8_t raw_rx = (len > 2) ? data[2] : 128; + uint8_t raw_ry = (len > 3) ? data[3] : 128; + + out_state->lx = scale_axis_8bit(raw_lx, false); + out_state->ly = scale_axis_8bit(raw_ly, true); + out_state->rx = scale_axis_8bit(raw_rx, false); + out_state->ry = scale_axis_8bit(raw_ry, true); + + /* Byte 4: Hat Switch & Buttons */ + parse_hat_switch_8way(data[4], out_state); + + uint8_t b1 = (data[4] >> 4) | ((data[5] & 0x0F) << 4); + out_state->btn_a = (b1 & (1 << 0)) ? 1 : 0; + out_state->btn_b = (b1 & (1 << 1)) ? 1 : 0; + out_state->btn_x = (b1 & (1 << 2)) ? 1 : 0; + out_state->btn_y = (b1 & (1 << 3)) ? 1 : 0; + out_state->btn_lb = (b1 & (1 << 4)) ? 1 : 0; + out_state->btn_rb = (b1 & (1 << 5)) ? 1 : 0; + out_state->btn_lt = (b1 & (1 << 6)) ? 1 : 0; + out_state->btn_rt = (b1 & (1 << 7)) ? 1 : 0; + + if (len >= 7) { + uint8_t b2 = data[6]; + out_state->btn_select = (b2 & (1 << 0)) ? 1 : 0; + out_state->btn_start = (b2 & (1 << 1)) ? 1 : 0; + out_state->btn_l3 = (b2 & (1 << 2)) ? 1 : 0; + out_state->btn_r3 = (b2 & (1 << 3)) ? 1 : 0; + out_state->btn_system = (b2 & (1 << 4)) ? 1 : 0; /* Home */ + out_state->btn_share = (b2 & (1 << 5)) ? 1 : 0; /* Star / Capture */ + } + + /* Analog Triggers (Pro 2 / Ultimate in D-input mode) */ + if (len >= 9) { + out_state->lt = data[7]; + out_state->rt = data[8]; + if (out_state->lt > 30) out_state->btn_lt = 1; + if (out_state->rt > 30) out_state->btn_rt = 1; + } else { + out_state->lt = out_state->btn_lt ? 255 : 0; + out_state->rt = out_state->btn_rt ? 255 : 0; + } + + return true; +} + +bool parser_8bitdo_parse(const uint8_t *report, size_t len, controller_state_t *out_state) +{ + if (!report || !out_state || len < 6) { + return false; + } + + /* 1. Check for 8BitDo Switch Simple Mode (Report ID 0x3F) */ + if (report[0] == 0x3F && len >= 8) { + return parse_8bitdo_switch_simple(report, len, out_state); + } + + /* 2. Check for 8BitDo Switch Full Mode (Report ID 0x30 or 0x21) */ + if ((report[0] == 0x30 || report[0] == 0x21) && len >= 12) { + return parse_8bitdo_switch_full(report, len, out_state); + } + + /* 3. Check for 8BitDo X-Input Mode (Standard 16-byte Xbox packet) */ + if ((len >= 15 && report[12] <= 8) || (report[0] == 0x01 && len >= 16)) { + if (parser_xbox_ble_parse(report, len, out_state)) { + return true; + } + } + + /* 4. Fallback to 8BitDo D-Input / Android Mode */ + const uint8_t *data = report; + size_t dlen = len; + if (dlen > 6 && data[0] <= 0x05) { + data++; + dlen--; + } + + return parse_8bitdo_dinput(data, dlen, out_state); +} diff --git a/main/parsers/parser_8bitdo.h b/main/parsers/parser_8bitdo.h new file mode 100644 index 0000000..82a83b3 --- /dev/null +++ b/main/parsers/parser_8bitdo.h @@ -0,0 +1,28 @@ +#pragma once + +#include "controller_parser.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Parse HID input report from 8BitDo Bluetooth Gamepads + * (Pro 2, Ultimate, SN30 Pro, Lite 2, M30, Zero 2, Micro) + * + * Supports: + * - Switch / Pro simple mode (Report ID 0x3F) + * - Switch / Pro standard mode (Report ID 0x30 / 0x21) + * - D-Input / Android mode (Report ID 0x01 or raw 8-10 byte reports) + * - X-Input mode (delegated to Xbox parser) + * + * @param report Raw report buffer received from BLE characteristic + * @param len Length of the report buffer + * @param out_state Pointer to controller_state_t to populate + * @return true if successfully parsed, false otherwise + */ +bool parser_8bitdo_parse(const uint8_t *report, size_t len, controller_state_t *out_state); + +#ifdef __cplusplus +} +#endif diff --git a/main/parsers/parser_generic_hogp.c b/main/parsers/parser_generic_hogp.c new file mode 100644 index 0000000..f6d80dc --- /dev/null +++ b/main/parsers/parser_generic_hogp.c @@ -0,0 +1,54 @@ +#include "parser_generic_hogp.h" + +bool parser_generic_hogp_parse(const uint8_t *report, size_t len, controller_state_t *out_state) +{ + if (!report || !out_state || len < 6) { + return false; + } + + controller_state_reset(out_state); + + const uint8_t *data = report; + /* If first byte is Report ID, skip it */ + if (len > 6 && (data[0] <= 0x05)) { + data++; + len--; + } + + /* Standard 8-bit axis mapping (0..255, 128 center) */ + uint8_t raw_lx = data[0]; + uint8_t raw_ly = data[1]; + uint8_t raw_rx = (len > 2) ? data[2] : 128; + uint8_t raw_ry = (len > 3) ? data[3] : 128; + + out_state->lx = scale_axis_8bit(raw_lx, false); + out_state->ly = scale_axis_8bit(raw_ly, true); + out_state->rx = scale_axis_8bit(raw_rx, false); + out_state->ry = scale_axis_8bit(raw_ry, true); + + /* Hat switch & buttons */ + if (len >= 6) { + parse_hat_switch_8way(data[4], out_state); + + uint8_t btn1 = (data[4] >> 4) | ((data[5] & 0x0F) << 4); + out_state->btn_a = (btn1 & (1 << 0)) ? 1 : 0; + out_state->btn_b = (btn1 & (1 << 1)) ? 1 : 0; + out_state->btn_x = (btn1 & (1 << 2)) ? 1 : 0; + out_state->btn_y = (btn1 & (1 << 3)) ? 1 : 0; + out_state->btn_lb = (btn1 & (1 << 4)) ? 1 : 0; + out_state->btn_rb = (btn1 & (1 << 5)) ? 1 : 0; + out_state->btn_lt = (btn1 & (1 << 6)) ? 1 : 0; + out_state->btn_rt = (btn1 & (1 << 7)) ? 1 : 0; + + if (len >= 7) { + uint8_t btn2 = data[6]; + out_state->btn_select = (btn2 & (1 << 0)) ? 1 : 0; + out_state->btn_start = (btn2 & (1 << 1)) ? 1 : 0; + out_state->btn_l3 = (btn2 & (1 << 2)) ? 1 : 0; + out_state->btn_r3 = (btn2 & (1 << 3)) ? 1 : 0; + out_state->btn_system = (btn2 & (1 << 4)) ? 1 : 0; + } + } + + return true; +} diff --git a/main/parsers/parser_generic_hogp.h b/main/parsers/parser_generic_hogp.h new file mode 100644 index 0000000..a7ba01b --- /dev/null +++ b/main/parsers/parser_generic_hogp.h @@ -0,0 +1,16 @@ +#pragma once + +#include "controller_parser.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Parse generic BLE HOGP Gamepad report into normalized state. + */ +bool parser_generic_hogp_parse(const uint8_t *report, size_t len, controller_state_t *out_state); + +#ifdef __cplusplus +} +#endif diff --git a/main/parsers/parser_stadia.c b/main/parsers/parser_stadia.c new file mode 100644 index 0000000..30c375a --- /dev/null +++ b/main/parsers/parser_stadia.c @@ -0,0 +1,115 @@ +#include "parser_stadia.h" + +bool parser_stadia_parse(const uint8_t *report, size_t len, controller_state_t *out_state) +{ + if (!report || !out_state || len < 7) { + return false; + } + + const uint8_t *data = report; + + /* + * Stadia BLE reports over GATT notification are 10 bytes and do NOT include + * a Report ID: + * Byte 0 is the D-PAD hat switch (0x00=Up, 0x01=Up-Right, 0x02=Right, + * 0x03=Down-Right, 0x04=Down, 0x05=Down-Left, 0x06=Left, 0x07=Up-Left, 0x08=Neutral). + * + * Note: 0x03 is Down+Right! We must never assume data[0] == 0x03 is a Report ID + * on standard BLE reports (len == 10). Only transports like USB HID that prepend + * Report ID 0x03 produce len >= 11 where data[1] is the Hat switch and data[4] is LX. + */ + if (len >= 11 && data[0] == 0x03 && (data[1] & 0x0F) <= 8 && data[4] >= 40 && data[4] <= 215) { + data++; + len--; + } + + if (len < 7) { + return false; + } + + controller_state_reset(out_state); + + /* + * Verified Google Stadia Controller HID Report Layout: + * Byte 0: D-PAD (Hat switch) + * 0x00=Up, 0x01=Up+Right, 0x02=Right, 0x03=Down+Right, + * 0x04=Down, 0x05=Down+Left, 0x06=Left, 0x07=Up+Left, + * 0x08=Neutral / Centered + * Byte 1: Buttons Low + * 0x01: Capture / Screenshot + * 0x02: Google Assistant + * 0x04: L2 digital trigger + * 0x08: R2 digital trigger + * 0x10: Stadia Logo (System / Home) + * 0x20: Menu (Start / Hamburger) + * 0x40: Options (Select / ...) + * 0x80: R3 (Right Stick Click) + * Byte 2: Buttons High + * 0x01: L3 (Left Stick Click) + * 0x02: R1 (Right Bumper) + * 0x04: L1 (Left Bumper) + * 0x08: Y + * 0x10: X + * 0x20: B + * 0x40: A + * Byte 3: Left Stick X (0..255, 128 center) + * Byte 4: Left Stick Y (0..255, 128 center) + * Byte 5: Right Stick X (0..255, 128 center) + * Byte 6: Right Stick Y (0..255, 128 center) + * Byte 7: Left Trigger Analog (0..255) (if present) + * Byte 8: Right Trigger Analog (0..255) (if present) + */ + + /* --- 1. D-Pad / Hat Switch (Byte 0) --- */ + parse_hat_switch_8way(data[0], out_state); + + /* --- 2. Buttons Byte 1 (data[1]) --- */ + uint8_t b1 = data[1]; + out_state->btn_share = (b1 & 0x01) ? 1 : 0; /* Capture */ + if (b1 & 0x02) out_state->btn_share = 1; /* Assistant -> map to Share */ + out_state->btn_lt = (b1 & 0x04) ? 1 : 0; /* L2 Digital */ + out_state->btn_rt = (b1 & 0x08) ? 1 : 0; /* R2 Digital */ + out_state->btn_system = (b1 & 0x10) ? 1 : 0; /* Stadia Logo */ + out_state->btn_start = (b1 & 0x20) ? 1 : 0; /* Menu */ + out_state->btn_select = (b1 & 0x40) ? 1 : 0; /* Options */ + out_state->btn_r3 = (b1 & 0x80) ? 1 : 0; /* R3 */ + + /* --- 3. Buttons Byte 2 (data[2]) --- */ + uint8_t b2 = data[2]; + out_state->btn_l3 = (b2 & 0x01) ? 1 : 0; /* L3 */ + out_state->btn_rb = (b2 & 0x02) ? 1 : 0; /* R1 */ + out_state->btn_lb = (b2 & 0x04) ? 1 : 0; /* L1 */ + out_state->btn_y = (b2 & 0x08) ? 1 : 0; /* Y */ + out_state->btn_x = (b2 & 0x10) ? 1 : 0; /* X */ + out_state->btn_b = (b2 & 0x20) ? 1 : 0; /* B */ + out_state->btn_a = (b2 & 0x40) ? 1 : 0; /* A */ + + /* --- 4. Analog Sticks (data[3..6]) --- */ + uint8_t raw_lx = data[3]; + uint8_t raw_ly = data[4]; + uint8_t raw_rx = data[5]; + uint8_t raw_ry = data[6]; + + /* Convert 0..255 (128 centered) to normalized -32768..32767 with overflow protection */ + out_state->lx = scale_axis_8bit(raw_lx, false); + out_state->ly = scale_axis_8bit(raw_ly, true); + out_state->rx = scale_axis_8bit(raw_rx, false); + out_state->ry = scale_axis_8bit(raw_ry, true); + + /* --- 5. Analog Triggers (data[7..8]) --- */ + if (len >= 8) { + out_state->lt = data[7]; + if (out_state->lt > 30) out_state->btn_lt = 1; + } else { + out_state->lt = out_state->btn_lt ? 255 : 0; + } + + if (len >= 9) { + out_state->rt = data[8]; + if (out_state->rt > 30) out_state->btn_rt = 1; + } else { + out_state->rt = out_state->btn_rt ? 255 : 0; + } + + return true; +} diff --git a/main/parsers/parser_stadia.h b/main/parsers/parser_stadia.h new file mode 100644 index 0000000..ce8c429 --- /dev/null +++ b/main/parsers/parser_stadia.h @@ -0,0 +1,16 @@ +#pragma once + +#include "controller_parser.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Parse Google Stadia Controller (Bluetooth mode) input report into normalized state. + */ +bool parser_stadia_parse(const uint8_t *report, size_t len, controller_state_t *out_state); + +#ifdef __cplusplus +} +#endif diff --git a/main/parsers/parser_xbox_ble.c b/main/parsers/parser_xbox_ble.c new file mode 100644 index 0000000..8f52a34 --- /dev/null +++ b/main/parsers/parser_xbox_ble.c @@ -0,0 +1,74 @@ +#include "parser_xbox_ble.h" + +bool parser_xbox_ble_parse(const uint8_t *report, size_t len, controller_state_t *out_state) +{ + if (!report || !out_state || len < 15) { + return false; + } + + const uint8_t *data = report; + /* If first byte is Report ID 0x01, advance pointer */ + if (data[0] == 0x01 && len >= 16) { + data++; + len--; + } + + if (len < 15) { + return false; + } + + /* Clear state */ + controller_state_reset(out_state); + + /* Analog Sticks (16-bit little-endian) */ + uint16_t lx_raw = (uint16_t)(data[0] | (data[1] << 8)); + uint16_t ly_raw = (uint16_t)(data[2] | (data[3] << 8)); + uint16_t rx_raw = (uint16_t)(data[4] | (data[5] << 8)); + uint16_t ry_raw = (uint16_t)(data[6] | (data[7] << 8)); + + out_state->lx = (int16_t)(lx_raw - 32768); + out_state->ly = (int16_t)(32767 - ly_raw); // Inverted Y so positive is UP + out_state->rx = (int16_t)(rx_raw - 32768); + out_state->ry = (int16_t)(32767 - ry_raw); + + /* Analog Triggers (10-bit little endian: 0 to 1023) */ + uint16_t lt_raw = (uint16_t)(data[8] | (data[9] << 8)); + uint16_t rt_raw = (uint16_t)(data[10] | (data[11] << 8)); + out_state->lt = (uint8_t)(lt_raw >> 2); + out_state->rt = (uint8_t)(rt_raw >> 2); + + /* Digital Triggers (thresholded) */ + out_state->btn_lt = (out_state->lt > 30) ? 1 : 0; + out_state->btn_rt = (out_state->rt > 30) ? 1 : 0; + + /* D-Pad Hat Switch (1 = N, 2 = NE, 3 = E, 4 = SE, 5 = S, 6 = SW, 7 = W, 8 = NW, 0 = neutral) */ + uint8_t hat = data[12]; + out_state->dpad_up = (hat == 1 || hat == 2 || hat == 8) ? 1 : 0; + out_state->dpad_right = (hat == 2 || hat == 3 || hat == 4) ? 1 : 0; + out_state->dpad_down = (hat == 4 || hat == 5 || hat == 6) ? 1 : 0; + out_state->dpad_left = (hat == 6 || hat == 7 || hat == 8) ? 1 : 0; + + /* Buttons byte 1 */ + uint8_t b1 = data[13]; + out_state->btn_a = (b1 & (1 << 0)) ? 1 : 0; + out_state->btn_b = (b1 & (1 << 1)) ? 1 : 0; + out_state->btn_x = (b1 & (1 << 3)) ? 1 : 0; + out_state->btn_y = (b1 & (1 << 4)) ? 1 : 0; + out_state->btn_lb = (b1 & (1 << 6)) ? 1 : 0; + out_state->btn_rb = (b1 & (1 << 7)) ? 1 : 0; + + /* Buttons byte 2 */ + uint8_t b2 = data[14]; + out_state->btn_select = (b2 & (1 << 2)) ? 1 : 0; /* View / Back */ + out_state->btn_start = (b2 & (1 << 3)) ? 1 : 0; /* Menu / Start */ + out_state->btn_system = (b2 & (1 << 4)) ? 1 : 0; /* Xbox Guide */ + out_state->btn_l3 = (b2 & (1 << 5)) ? 1 : 0; + out_state->btn_r3 = (b2 & (1 << 6)) ? 1 : 0; + + /* Share button (on newer Series controllers) */ + if (len >= 16) { + out_state->btn_share = (data[15] & (1 << 0)) ? 1 : 0; + } + + return true; +} diff --git a/main/parsers/parser_xbox_ble.h b/main/parsers/parser_xbox_ble.h new file mode 100644 index 0000000..1991306 --- /dev/null +++ b/main/parsers/parser_xbox_ble.h @@ -0,0 +1,16 @@ +#pragma once + +#include "controller_parser.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Parse Xbox Wireless Controller (BLE) input report into normalized state. + */ +bool parser_xbox_ble_parse(const uint8_t *report, size_t len, controller_state_t *out_state); + +#ifdef __cplusplus +} +#endif diff --git a/main/profile_manager.c b/main/profile_manager.c new file mode 100644 index 0000000..ba5aa80 --- /dev/null +++ b/main/profile_manager.c @@ -0,0 +1,331 @@ +#include "profile_manager.h" +#include "board_esp32_s3_zero.h" +#include "status_led.h" +#include "config_server.h" +#include "nvs_flash.h" +#include "nvs.h" +#include "esp_log.h" +#include "driver/gpio.h" +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "ble_hid_host.h" + +static const char *TAG = "PROFILE_MGR"; +static const char *NVS_NAMESPACE = "gamepad_cfg"; +static const char *NVS_KEY_MODE = "mode"; +static const char *NVS_KEY_BRIGHTNESS = "brightness"; +static const char *NVS_KEY_COMBO_A = "combo_a"; +static const char *NVS_KEY_COMBO_B = "combo_b"; +static const char *NVS_KEY_COMBO_X = "combo_x"; +static const char *NVS_KEY_COMBO_Y = "combo_y"; + +static console_mode_t s_current_mode = CONSOLE_MODE_SWITCH; +static uint8_t s_led_brightness = 100; +static profile_change_cb_t s_change_cb = NULL; + +static combo_config_t s_combos = { + .combo_a = CONSOLE_MODE_PC_DINPUT, /* START + A -> PC DirectInput */ + .combo_b = CONSOLE_MODE_SWITCH, /* START + B -> Nintendo Switch */ + .combo_x = CONSOLE_MODE_PS3, /* START + X -> PlayStation 3 */ + .combo_y = CONSOLE_MODE_XBOX360, /* START + Y -> Xbox 360 */ +}; + +static portMUX_TYPE s_state_lock = portMUX_INITIALIZER_UNLOCKED; +static controller_state_t s_latest_state = {0}; +static uint32_t s_combo_hold_ms = 0; +static console_mode_t s_pending_mode = CONSOLE_MODE_SWITCH; +static bool s_combo_handled = false; + +static uint32_t s_config_toggle_hold_ms = 0; +static bool s_config_toggle_handled = false; + +const char *profile_manager_mode_name(console_mode_t mode) +{ + switch (mode) { + case CONSOLE_MODE_SWITCH: return "Nintendo Switch (HORI Pokken Pad)"; + case CONSOLE_MODE_PC_DINPUT: return "PC DirectInput Gamepad"; + case CONSOLE_MODE_PS3: return "PlayStation 3 Gamepad"; + case CONSOLE_MODE_XBOX360: return "Xbox 360 (XInput + XSM3)"; + case CONSOLE_MODE_XBOXOG: return "Original Xbox (Controller S)"; + case CONSOLE_MODE_PS4: return "PlayStation 4 (DualShock 4)"; + case CONSOLE_MODE_MOUSE_KB: return "Couch Mouse & Keyboard"; + default: return "Unknown Mode"; + } +} + +static void update_led_for_mode(console_mode_t mode) +{ + /* If Config AP is active, keep LED indicating Config Portal */ + if (config_server_is_active()) { + status_led_set_mode(LED_STATE_CONFIG_PORTAL); + return; + } + + switch (mode) { + case CONSOLE_MODE_SWITCH: + status_led_set_mode(LED_STATE_SWITCH_MODE); + break; + case CONSOLE_MODE_PC_DINPUT: + status_led_set_mode(LED_STATE_PC_MODE); + break; + case CONSOLE_MODE_PS3: + status_led_set_mode(LED_STATE_PS3_MODE); + break; + case CONSOLE_MODE_XBOX360: + status_led_set_mode(LED_STATE_XBOX360_MODE); + break; + case CONSOLE_MODE_XBOXOG: + status_led_set_mode(LED_STATE_XBOXOG_MODE); + break; + case CONSOLE_MODE_PS4: + status_led_set_mode(LED_STATE_PS4_MODE); + break; + case CONSOLE_MODE_MOUSE_KB: + status_led_set_mode(LED_STATE_MOUSE_KB_MODE); + break; + default: + break; + } +} + +void profile_manager_refresh_led(void) +{ + update_led_for_mode(s_current_mode); +} + +static void boot_button_task(void *pvParameters) +{ + gpio_config_t io_conf = { + .pin_bit_mask = (1ULL << BOARD_BOOT_BUTTON_GPIO), + .mode = GPIO_MODE_INPUT, + .pull_up_en = GPIO_PULLUP_ENABLE, + .pull_down_en = GPIO_PULLDOWN_DISABLE, + .intr_type = GPIO_INTR_DISABLE, + }; + gpio_config(&io_conf); + + uint32_t press_duration_ms = 0; + bool long_press_handled = false; + + while (1) { + /* Physical BOOT button (GPIO0) handling */ + bool pressed = (gpio_get_level(BOARD_BOOT_BUTTON_GPIO) == 0); + if (pressed) { + press_duration_ms += 50; + if (press_duration_ms == 50) { + ESP_LOGI(TAG, "BOOT button pressed"); + } + if (press_duration_ms >= 1500 && !long_press_handled) { + ESP_LOGI(TAG, "BOOT button held >= 1.5s: Toggling Config AP Portal..."); + long_press_handled = true; + status_led_flash_color(40, 40, 40, 200); + config_server_request_toggle(); + } + } else { + if (press_duration_ms > 50 && !long_press_handled) { + ESP_LOGI(TAG, "BOOT button short click (%ld ms): Cycling profile mode...", press_duration_ms); + profile_manager_cycle_mode(); + } + press_duration_ms = 0; + long_press_handled = false; + } + + /* Periodic controller button combo checks (independent of BLE packet frequency) */ + controller_state_t st; + portENTER_CRITICAL(&s_state_lock); + st = s_latest_state; + portEXIT_CRITICAL(&s_state_lock); + + /* 1. Config Portal Combo: SELECT + START + (D-PAD UP or SYSTEM/GUIDE) held 1.5s */ + if (st.btn_select && st.btn_start && (st.dpad_up || st.btn_system)) { + s_config_toggle_hold_ms += 50; + if (s_config_toggle_hold_ms >= 1500 && !s_config_toggle_handled) { + ESP_LOGI(TAG, "Controller combo detected: Toggling Web Config Portal!"); + s_config_toggle_handled = true; + status_led_flash_color(40, 40, 40, 200); + config_server_request_toggle(); + } + } else { + s_config_toggle_hold_ms = 0; + s_config_toggle_handled = false; + } + + /* 2. Console Profile Combos: START + [Single Face Button] held 1.2s */ + int face_count = (st.btn_a ? 1 : 0) + (st.btn_b ? 1 : 0) + + (st.btn_x ? 1 : 0) + (st.btn_y ? 1 : 0); + + bool combo_match = false; + console_mode_t target_mode = s_current_mode; + + if (st.btn_start && !st.btn_select && face_count == 1) { + int8_t mapped_mode = -1; + if (st.btn_a) mapped_mode = s_combos.combo_a; + else if (st.btn_b) mapped_mode = s_combos.combo_b; + else if (st.btn_x) mapped_mode = s_combos.combo_x; + else if (st.btn_y) mapped_mode = s_combos.combo_y; + + if (mapped_mode >= 0 && mapped_mode < CONSOLE_MODE_MAX) { + target_mode = (console_mode_t)mapped_mode; + combo_match = true; + } + } + + if (combo_match && target_mode != s_current_mode) { + if (s_pending_mode != target_mode) { + s_pending_mode = target_mode; + s_combo_hold_ms = 0; + s_combo_handled = false; + } else { + s_combo_hold_ms += 50; + if (s_combo_hold_ms >= 3000 && !s_combo_handled) { + ESP_LOGI(TAG, "Button combo (START + face button) held >= 3.0s! Switching mode to %d (%s)...", + target_mode, profile_manager_mode_name(target_mode)); + s_combo_handled = true; + status_led_set_mode(LED_STATE_MODE_SWITCHING); + profile_manager_set_mode(target_mode); + ble_hid_host_pulse_rumble(255, 220, 70); /* Punchy, heavy 70ms haptic confirmation kick */ + } + } + } else { + s_combo_hold_ms = 0; + s_combo_handled = false; + } + + vTaskDelay(pdMS_TO_TICKS(50)); + } +} + +esp_err_t profile_manager_init(profile_change_cb_t callback) +{ + s_change_cb = callback; + + /* Initialize NVS */ + esp_err_t err = nvs_flash_init(); + if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) { + nvs_flash_erase(); + err = nvs_flash_init(); + } + + /* Read saved settings */ + nvs_handle_t nvs_h; + if (nvs_open(NVS_NAMESPACE, NVS_READONLY, &nvs_h) == ESP_OK) { + uint8_t saved_mode = 0; + if (nvs_get_u8(nvs_h, NVS_KEY_MODE, &saved_mode) == ESP_OK) { + if (saved_mode < CONSOLE_MODE_MAX) { + s_current_mode = (console_mode_t)saved_mode; + } + } + uint8_t saved_brightness = 100; + if (nvs_get_u8(nvs_h, NVS_KEY_BRIGHTNESS, &saved_brightness) == ESP_OK) { + if (saved_brightness <= 100) { + s_led_brightness = saved_brightness; + status_led_set_brightness(s_led_brightness); + } + } + int8_t saved_combo = -1; + if (nvs_get_i8(nvs_h, NVS_KEY_COMBO_A, &saved_combo) == ESP_OK) s_combos.combo_a = saved_combo; + if (nvs_get_i8(nvs_h, NVS_KEY_COMBO_B, &saved_combo) == ESP_OK) s_combos.combo_b = saved_combo; + if (nvs_get_i8(nvs_h, NVS_KEY_COMBO_X, &saved_combo) == ESP_OK) s_combos.combo_x = saved_combo; + if (nvs_get_i8(nvs_h, NVS_KEY_COMBO_Y, &saved_combo) == ESP_OK) s_combos.combo_y = saved_combo; + nvs_close(nvs_h); + } + + ESP_LOGI(TAG, "Active Profile: [%d] %s", s_current_mode, profile_manager_mode_name(s_current_mode)); + update_led_for_mode(s_current_mode); + + /* Monitor physical BOOT button (GPIO0) and profile button combos on Core 1 */ + xTaskCreatePinnedToCore(boot_button_task, "boot_btn_task", 3072, NULL, 4, NULL, 1); + + return ESP_OK; +} + +console_mode_t profile_manager_get_mode(void) +{ + return s_current_mode; +} + +esp_err_t profile_manager_set_mode(console_mode_t mode) +{ + if (mode >= CONSOLE_MODE_MAX) { + return ESP_ERR_INVALID_ARG; + } + + s_current_mode = mode; + ESP_LOGI(TAG, "Switched Profile to: [%d] %s", mode, profile_manager_mode_name(mode)); + + /* Save to NVS */ + nvs_handle_t nvs_h; + if (nvs_open(NVS_NAMESPACE, NVS_READWRITE, &nvs_h) == ESP_OK) { + nvs_set_u8(nvs_h, NVS_KEY_MODE, (uint8_t)mode); + nvs_commit(nvs_h); + nvs_close(nvs_h); + } + + update_led_for_mode(mode); + + if (s_change_cb) { + s_change_cb(mode); + } + + return ESP_OK; +} + +void profile_manager_cycle_mode(void) +{ + console_mode_t next_mode = (console_mode_t)((s_current_mode + 1) % CONSOLE_MODE_MAX); + profile_manager_set_mode(next_mode); +} + +esp_err_t profile_manager_set_led_brightness(uint8_t percent) +{ + if (percent > 100) percent = 100; + s_led_brightness = percent; + status_led_set_brightness(percent); + + nvs_handle_t nvs_h; + if (nvs_open(NVS_NAMESPACE, NVS_READWRITE, &nvs_h) == ESP_OK) { + nvs_set_u8(nvs_h, NVS_KEY_BRIGHTNESS, percent); + nvs_commit(nvs_h); + nvs_close(nvs_h); + } + return ESP_OK; +} + +uint8_t profile_manager_get_led_brightness(void) +{ + return s_led_brightness; +} + +void profile_manager_get_combos(combo_config_t *combos) +{ + if (combos) { + *combos = s_combos; + } +} + +esp_err_t profile_manager_set_combos(const combo_config_t *combos) +{ + if (!combos) return ESP_ERR_INVALID_ARG; + s_combos = *combos; + + nvs_handle_t nvs_h; + if (nvs_open(NVS_NAMESPACE, NVS_READWRITE, &nvs_h) == ESP_OK) { + nvs_set_i8(nvs_h, NVS_KEY_COMBO_A, s_combos.combo_a); + nvs_set_i8(nvs_h, NVS_KEY_COMBO_B, s_combos.combo_b); + nvs_set_i8(nvs_h, NVS_KEY_COMBO_X, s_combos.combo_x); + nvs_set_i8(nvs_h, NVS_KEY_COMBO_Y, s_combos.combo_y); + nvs_commit(nvs_h); + nvs_close(nvs_h); + } + ESP_LOGI(TAG, "Saved button combos: A=%d, B=%d, X=%d, Y=%d", + s_combos.combo_a, s_combos.combo_b, s_combos.combo_x, s_combos.combo_y); + return ESP_OK; +} + +void profile_manager_process_state(const controller_state_t *state) +{ + if (!state) return; + portENTER_CRITICAL(&s_state_lock); + s_latest_state = *state; + portEXIT_CRITICAL(&s_state_lock); +} diff --git a/main/profile_manager.h b/main/profile_manager.h new file mode 100644 index 0000000..eb88b74 --- /dev/null +++ b/main/profile_manager.h @@ -0,0 +1,89 @@ +#pragma once + +#include +#include +#include "controller_state.h" +#include "esp_err.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + CONSOLE_MODE_SWITCH = 0, /* Nintendo Switch (HORI Pokken Pad) */ + CONSOLE_MODE_PC_DINPUT = 1, /* PC DirectInput / Generic Gamepad */ + CONSOLE_MODE_PS3 = 2, /* PS3 Controller */ + CONSOLE_MODE_XBOX360 = 3, /* Xbox 360 Controller (XInput + XSM3) */ + CONSOLE_MODE_XBOXOG = 4, /* Original Xbox (Controller S / XID) */ + CONSOLE_MODE_PS4 = 5, /* PlayStation 4 (DualShock 4 / DS4) */ + CONSOLE_MODE_MOUSE_KB = 6, /* Couch Mouse & Keyboard (Media + Cursor) */ + CONSOLE_MODE_MAX +} console_mode_t; + +typedef void (*profile_change_cb_t)(console_mode_t new_mode); + +/** + * @brief Initialize profile manager (loads saved mode from NVS, sets up BOOT button). + */ +esp_err_t profile_manager_init(profile_change_cb_t callback); + +/** + * @brief Get the currently active console mode. + */ +console_mode_t profile_manager_get_mode(void); + +/** + * @brief Set the active console mode and save to NVS. + */ +esp_err_t profile_manager_set_mode(console_mode_t mode); + +/** + * @brief Cycle to the next console mode. + */ +void profile_manager_cycle_mode(void); + +/** + * @brief Process controller state to detect button combos for mode switching. + */ +void profile_manager_process_state(const controller_state_t *state); + +/** + * @brief Get string name of the mode. + */ +const char *profile_manager_mode_name(console_mode_t mode); + +/** + * @brief Set LED brightness (0 - 100%) and persist to NVS. + */ +esp_err_t profile_manager_set_led_brightness(uint8_t percent); + +/** + * @brief Get saved LED brightness. + */ +uint8_t profile_manager_get_led_brightness(void); + +/** + * @brief Refresh LED color for active profile (e.g. after exiting config portal). + */ +void profile_manager_refresh_led(void); + +typedef struct { + int8_t combo_a; /* Target console_mode_t for START + A (South / Cross), or -1 for disabled */ + int8_t combo_b; /* Target console_mode_t for START + B (East / Circle), or -1 for disabled */ + int8_t combo_x; /* Target console_mode_t for START + X (West / Square), or -1 for disabled */ + int8_t combo_y; /* Target console_mode_t for START + Y (North / Triangle), or -1 for disabled */ +} combo_config_t; + +/** + * @brief Get current button combo configuration. + */ +void profile_manager_get_combos(combo_config_t *combos); + +/** + * @brief Set button combo configuration and persist to NVS. + */ +esp_err_t profile_manager_set_combos(const combo_config_t *combos); + +#ifdef __cplusplus +} +#endif diff --git a/main/status_led.c b/main/status_led.c new file mode 100644 index 0000000..a69212f --- /dev/null +++ b/main/status_led.c @@ -0,0 +1,173 @@ +#include "status_led.h" +#include "board_esp32_s3_zero.h" +#include "led_strip.h" +#include "esp_log.h" +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" + +static const char *TAG = "STATUS_LED"; +static led_strip_handle_t s_led_strip = NULL; +static volatile led_status_mode_t s_current_mode = LED_STATE_SCANNING; +static volatile uint8_t s_brightness = 100; /* Percentage 0-100 */ + +static void set_scaled_pixel(uint8_t r, uint8_t g, uint8_t b) +{ + if (!s_led_strip) return; + uint32_t br = s_brightness; + uint8_t sr = (uint8_t)((r * br) / 100); + uint8_t sg = (uint8_t)((g * br) / 100); + uint8_t sb = (uint8_t)((b * br) / 100); + led_strip_set_pixel(s_led_strip, 0, sr, sg, sb); +} + +static void status_led_task(void *pvParameters) +{ + uint32_t step = 0; + while (1) { + if (!s_led_strip) { + vTaskDelay(pdMS_TO_TICKS(100)); + continue; + } + + switch (s_current_mode) { + case LED_STATE_SCANNING: + /* Yellow flash: 200ms on, 200ms off */ + if ((step % 2) == 0) { + set_scaled_pixel(30, 25, 0); // Dim yellow + } else { + led_strip_clear(s_led_strip); + } + led_strip_refresh(s_led_strip); + vTaskDelay(pdMS_TO_TICKS(200)); + break; + + case LED_STATE_CONFIG_PORTAL: + /* Config Mode: Pulsating Magenta / Violet (250ms cadence) */ + if ((step % 2) == 0) { + set_scaled_pixel(35, 0, 35); + } else { + set_scaled_pixel(6, 0, 6); + } + led_strip_refresh(s_led_strip); + vTaskDelay(pdMS_TO_TICKS(250)); + break; + + case LED_STATE_SWITCH_MODE: + /* Nintendo Switch: Solid Cyan / Joy-Con Teal */ + set_scaled_pixel(0, 25, 25); + led_strip_refresh(s_led_strip); + vTaskDelay(pdMS_TO_TICKS(500)); + break; + + case LED_STATE_PC_MODE: + /* PC DirectInput: Solid Blue */ + set_scaled_pixel(0, 0, 30); + led_strip_refresh(s_led_strip); + vTaskDelay(pdMS_TO_TICKS(500)); + break; + + case LED_STATE_PS3_MODE: + /* PS3: Solid Red */ + set_scaled_pixel(30, 0, 0); + led_strip_refresh(s_led_strip); + vTaskDelay(pdMS_TO_TICKS(500)); + break; + + case LED_STATE_XBOX360_MODE: + /* Xbox 360: Solid Emerald Green */ + set_scaled_pixel(0, 35, 0); + led_strip_refresh(s_led_strip); + vTaskDelay(pdMS_TO_TICKS(500)); + break; + + case LED_STATE_XBOXOG_MODE: + /* Original Xbox: Solid Amber / Warm Orange */ + set_scaled_pixel(35, 12, 0); + led_strip_refresh(s_led_strip); + vTaskDelay(pdMS_TO_TICKS(500)); + break; + + case LED_STATE_PS4_MODE: + /* PlayStation 4: Solid DualShock 4 Royal Blue */ + set_scaled_pixel(0, 10, 45); + led_strip_refresh(s_led_strip); + vTaskDelay(pdMS_TO_TICKS(500)); + break; + + case LED_STATE_MOUSE_KB_MODE: + /* Couch Mouse & Keyboard: Solid Turquoise / Teal */ + set_scaled_pixel(0, 35, 30); + led_strip_refresh(s_led_strip); + vTaskDelay(pdMS_TO_TICKS(500)); + break; + + case LED_STATE_MODE_SWITCHING: + /* White fast flash */ + set_scaled_pixel(40, 40, 40); + led_strip_refresh(s_led_strip); + vTaskDelay(pdMS_TO_TICKS(100)); + led_strip_clear(s_led_strip); + led_strip_refresh(s_led_strip); + vTaskDelay(pdMS_TO_TICKS(100)); + break; + + case LED_STATE_OFF: + default: + led_strip_clear(s_led_strip); + led_strip_refresh(s_led_strip); + vTaskDelay(pdMS_TO_TICKS(500)); + break; + } + step++; + } +} + +esp_err_t status_led_init(void) +{ + led_strip_config_t strip_config = { + .strip_gpio_num = BOARD_RGB_LED_GPIO, + .max_leds = 1, + }; + led_strip_rmt_config_t rmt_config = { + .resolution_hz = 10 * 1000 * 1000, /* 10MHz */ + .flags.with_dma = false, + }; + + esp_err_t err = led_strip_new_rmt_device(&strip_config, &rmt_config, &s_led_strip); + if (err != ESP_OK) { + ESP_LOGE(TAG, "Failed to initialize WS2812 on GPIO%d: %s", BOARD_RGB_LED_GPIO, esp_err_to_name(err)); + return err; + } + + led_strip_clear(s_led_strip); + led_strip_refresh(s_led_strip); + + /* Pin WS2812 RMT animation engine to Core 1 */ + xTaskCreatePinnedToCore(status_led_task, "status_led_task", 2048, NULL, 3, NULL, 1); + ESP_LOGI(TAG, "WS2812 RGB LED initialized on GPIO%d", BOARD_RGB_LED_GPIO); + return ESP_OK; +} + +void status_led_set_mode(led_status_mode_t mode) +{ + s_current_mode = mode; +} + +void status_led_set_brightness(uint8_t percent) +{ + if (percent > 100) percent = 100; + s_brightness = percent; +} + +uint8_t status_led_get_brightness(void) +{ + return s_brightness; +} + +void status_led_flash_color(uint8_t r, uint8_t g, uint8_t b, uint32_t duration_ms) +{ + if (!s_led_strip) return; + set_scaled_pixel(r, g, b); + led_strip_refresh(s_led_strip); + vTaskDelay(pdMS_TO_TICKS(duration_ms)); +} diff --git a/main/status_led.h b/main/status_led.h new file mode 100644 index 0000000..c692ec5 --- /dev/null +++ b/main/status_led.h @@ -0,0 +1,52 @@ +#pragma once + +#include +#include +#include "esp_err.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + LED_STATE_OFF, + LED_STATE_SCANNING, /* Yellow flashing */ + LED_STATE_MODE_SWITCHING, /* Quick white pulses */ + LED_STATE_CONFIG_PORTAL, /* Pulsating Magenta/Purple for Wi-Fi AP Config Mode */ + LED_STATE_SWITCH_MODE, /* Solid / pulsating Green */ + LED_STATE_PC_MODE, /* Solid / pulsating Blue */ + LED_STATE_PS3_MODE, /* Solid / pulsating Red */ + LED_STATE_XBOX360_MODE, /* Solid Emerald / Lime Green */ + LED_STATE_XBOXOG_MODE, /* Solid Amber / Orange */ + LED_STATE_PS4_MODE, /* Solid Royal Blue / Indigo */ + LED_STATE_MOUSE_KB_MODE, /* Solid Turquoise / Teal */ +} led_status_mode_t; + +/** + * @brief Initialize the onboard WS2812 RGB LED (GPIO21). + */ +esp_err_t status_led_init(void); + +/** + * @brief Set current LED status mode. + */ +void status_led_set_mode(led_status_mode_t mode); + +/** + * @brief Set LED brightness (0 - 100%). + */ +void status_led_set_brightness(uint8_t percent); + +/** + * @brief Get current LED brightness (0 - 100%). + */ +uint8_t status_led_get_brightness(void); + +/** + * @brief Flash a specific RGB color for a given duration (in ms). + */ +void status_led_flash_color(uint8_t r, uint8_t g, uint8_t b, uint32_t duration_ms); + +#ifdef __cplusplus +} +#endif diff --git a/main/version.h b/main/version.h new file mode 100644 index 0000000..8864139 --- /dev/null +++ b/main/version.h @@ -0,0 +1,7 @@ +#pragma once + +#define MIMICON_VERSION_MAJOR 1 +#define MIMICON_VERSION_MINOR 0 +#define MIMICON_VERSION_PATCH 0 +#define MIMICON_VERSION_STRING "1.0.0" +#define MIMICON_BUILD_NAME "MimiCon Genesis" diff --git a/main/web_assets.h b/main/web_assets.h new file mode 100644 index 0000000..6901101 --- /dev/null +++ b/main/web_assets.h @@ -0,0 +1,1630 @@ +#pragma once + +static const char INDEX_HTML[] = +"\n" +"\n" +"\n" +"\n" +"\n" +"MimiCon - Universal Gamepad Bridge\n" +"\n" +"\n" +"\n" +"
\n" +"
\n" +"
\n" +"
🎮
\n" +"
\n" +"

MimiCon v1.0.0

\n" +"
Universal Gamepad Mimic & Console Bridge
\n" +"
\n" +"
\n" +"
\n" +" \n" +" CONFIG AP ACTIVE\n" +"
\n" +"
\n" +"\n" +" \n" +"
\n" +"
\n" +"
Web Server Active
\n" +"
Wi-Fi is on (no auto-timeout). Click to turn off for 0-latency gaming.
\n" +"
\n" +" \n" +"
\n" +"\n" +" \n" +"
\n" +"
\n" +"
Target Console Mode
\n" +"
Nintendo Switch
\n" +"
\n" +"
\n" +" \n" +" \n" +" \n" +" \n" +" \n" +" \n" +" \n" +"
\n" +"
\n" +"\n" +" \n" +"
\n" +"
\n" +"
Button Combos (Hold 3s to Switch)
\n" +"
\n" +"
\n" +"
\n" +" Hold START + [Face Button] for 3s on your controller to switch console profiles instantly:\n" +"
\n" +"
\n" +"
\n" +"
\n" +" ● START + A (Cross ✕)\n" +"
\n" +" \n" +"
\n" +"
\n" +"
\n" +" ● START + B (Circle ○)\n" +"
\n" +" \n" +"
\n" +"
\n" +"
\n" +" ● START + X (Square □)\n" +"
\n" +" \n" +"
\n" +"
\n" +"
\n" +" ● START + Y (Triangle â–ŗ)\n" +"
\n" +" \n" +"
\n" +"
\n" +"
\n" +"\n" +" \n" +"
\n" +"
\n" +"
Live Controller Visualizer
\n" +"
Scanning for Gamepad...
\n" +"
\n" +"
\n" +" \n" +" \n" +" \n" +" \n" +" \n" +" \n" +" \n" +" \n" +" \n" +" \n" +" \n" +" \n" +"\n" +" \n" +" \n" +" \n" +"\n" +" \n" +" \n" +" \n" +"\n" +" \n" +" \n" +" Y\n" +"\n" +" \n" +" X\n" +"\n" +" \n" +" B\n" +"\n" +" \n" +" A\n" +"\n" +" \n" +" \n" +" LB\n" +" \n" +" RB\n" +"\n" +" \n" +" \n" +" \n" +" \n" +" \n" +"\n" +"
\n" +"
\n" +"
Left Trigger (LT)0%
\n" +"
\n" +"
\n" +"
\n" +"
Right Trigger (RT)0%
\n" +"
\n" +"
\n" +"
\n" +"\n" +"
\n" +"
Left Stick: X: 0, Y: 0
\n" +"
Right Stick: X: 0, Y: 0
\n" +"
\n" +"
\n" +"
\n" +"\n" +" \n" +"
\n" +"
\n" +"
Stick Deadzones & Remapping
\n" +"
\n" +"
\n" +"
\n" +"
\n" +"
\n" +" đŸ•šī¸ Left Stick Radial Deadzone\n" +" 5%\n" +"
\n" +" \n" +"
\n" +"
\n" +"
\n" +" đŸ•šī¸ Right Stick Radial Deadzone\n" +" 5%\n" +"
\n" +" \n" +"
\n" +"
\n" +"
\n" +" đŸŽ¯ Analog Triggers Minimum Cutoff\n" +" 0\n" +"
\n" +" \n" +"
\n" +"
\n" +" \n" +" \n" +" \n" +" \n" +" \n" +"
\n" +"
\n" +" \n" +"
\n" +"
\n" +"
\n" +"\n" +" \n" +"
\n" +"
\n" +"
📱 Phone / Web Virtual Controller
\n" +"
\n" +" \n" +" \n" +"
\n" +"
\n" +"
\n" +" Control games directly from your smartphone touchscreen over Wi-Fi with dual analog thumbsticks:\n" +"
\n" +"
\n" +"
\n" +"
\n" +" \n" +" \n" +"
\n" +"
\n" +" \n" +" \n" +" \n" +" \n" +"
\n" +"
\n" +" \n" +" \n" +"
\n" +"
\n" +"
\n" +"
\n" +"
\n" +"
\n" +" \n" +"
\n" +" \n" +"
\n" +" \n" +"
\n" +" \n" +"
\n" +"
\n" +"
\n" +"
\n" +"
\n" +"
\n" +" \n" +"
\n" +"
\n" +"
\n" +"
\n" +"
\n" +"
\n" +"
\n" +" \n" +"
\n" +"
\n" +"
\n" +" \n" +"
\n" +" \n" +"
\n" +" \n" +"
\n" +" \n" +"
\n" +"
\n" +"
\n" +"
\n" +"
\n" +"
\n" +"\n" +" \n" +"
\n" +"
\n" +"
Bluetooth Controller
\n" +"
\n" +"
\n" +"
\n" +"
\n" +"
\n" +"
Scanning...
\n" +" 100%\n" +"
\n" +"
Auto-pairing with nearby gamepads
\n" +"
\n" +"
\n" +"
\n" +"
\n" +"
\n" +" \n" +" \n" +" \n" +"
\n" +"
\n" +"
\n" +"
\n" +"
Stored Paired Controllers (0)
\n" +"
NVS Multi-Bond Memory
\n" +"
\n" +"
\n" +"
Loading paired controllers...
\n" +"
\n" +"
\n" +"
\n" +"\n" +" \n" +"
\n" +"
\n" +"
Wi-Fi Station & mDNS
\n" +"
Checking status...
\n" +"
\n" +"
\n" +"
\n" +"
\n" +" 🌐 mDNS Hostname: http://mimicon.local/\n" +"
\n" +"
Connect to home Wi-Fi to access this portal from any phone, PC, or tablet on your network!
\n" +"
\n" +"
\n" +"
\n" +"
\n" +" \n" +" \n" +"
\n" +"
\n" +" \n" +" \n" +"
\n" +"
\n" +"
\n" +"
\n" +" \n" +" \n" +"
\n" +"
\n" +"
\n" +"
\n" +"\n" +" \n" +"
\n" +"
\n" +"
Onboard WS2812 RGB LED (GPIO21)
\n" +"
100%
\n" +"
\n" +"
\n" +" 🌑 Off\n" +" \n" +" 💡 100%\n" +"
\n" +"
\n" +"\n" +" \n" +"
\n" +"
\n" +"
Firmware & Over-The-Air (OTA) Update
\n" +"
Dual OTA Scheme
\n" +"
\n" +"
\n" +"
\n" +"
Running Firmware:
\n" +"
Loading...
\n" +"
\n" +"
\n" +"
Build Timestamp:
\n" +"
...
\n" +"
\n" +"
\n" +"
Active Slot:
\n" +"
...
\n" +"
\n" +"
\n" +"
Next Boot Slot:
\n" +"
...
\n" +"
\n" +"
\n" +"
\n" +"
\n" +" \n" +"
No .bin file selected
\n" +" \n" +"
\n" +"
\n" +"
\n" +"
\n" +"
\n" +"
Select a compiled .bin file (e.g. build/mimicon.bin) to flash wirelessly.
\n" +"
0%
\n" +"
\n" +"
\n" +"
\n" +"
\n" +"\n" +"\n" +"\n" +"\n"; diff --git a/ota_flash.py b/ota_flash.py new file mode 100644 index 0000000..d97e69d --- /dev/null +++ b/ota_flash.py @@ -0,0 +1,145 @@ +#!/usr/bin/env python3 +""" +MimiCon Wireless Over-The-Air (OTA) Automated Flash Tool +Usage: + python ota_flash.py [binary_path] [host_url] + +Examples: + python ota_flash.py + python ota_flash.py build/mimicon.bin http://mimicon.local +""" + +import sys +import os +import time +import json +import urllib.request +import urllib.error + +DEFAULT_HOST = "http://mimicon.local" +ALT_HOST = "http://esp32-hid.local" + +DEFAULT_BIN = os.path.join(os.path.dirname(__file__), "build", "mimicon.bin") +ALT_BIN = os.path.join(os.path.dirname(__file__), "build", "esp32_s3_zero_skeleton.bin") + +def get_status(host, timeout=5): + url = f"{host.rstrip('/')}/api/status" + req = urllib.request.Request(url, headers={"User-Agent": "MimiCon-OTA-Tool"}) + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + if resp.status == 200: + return json.loads(resp.read().decode("utf-8")) + except Exception: + return None + return None + +def flash_firmware(bin_path, host): + if not os.path.isfile(bin_path): + if bin_path == DEFAULT_BIN and os.path.isfile(ALT_BIN): + bin_path = ALT_BIN + else: + print(f"[-] Error: Firmware binary not found at '{bin_path}'") + return False + + file_size = os.path.getsize(bin_path) + print("=" * 60) + print(" MimiCon Wireless Over-The-Air (OTA) Flasher ") + print("=" * 60) + print(f"[*] Target Host: {host}") + print(f"[*] Firmware Binary: {bin_path} ({file_size:,} bytes / {file_size / 1024:.1f} KB)") + + print("[*] Contacting device via mDNS...") + initial_status = get_status(host, timeout=6) + if not initial_status and host == DEFAULT_HOST: + print(f"[*] Trying fallback host '{ALT_HOST}'...") + initial_status = get_status(ALT_HOST, timeout=6) + if initial_status: + host = ALT_HOST + if not initial_status: + # Try fallback to IP if needed or print error + print(f"[-] Could not reach device at '{host}'.") + print(" Ensure the ESP32-S3 is powered on, Wi-Fi is active, and your PC is on the same network.") + return False + + app_version = initial_status.get("app_version", "unknown") + running_part = initial_status.get("running_part", "unknown") + next_part = initial_status.get("next_part", "unknown") + compile_time = initial_status.get("compile_time", "unknown") + mode_name = initial_status.get("mode_name", "unknown") + sta_ssid = initial_status.get("sta_ssid", "unknown") + sta_ip = initial_status.get("sta_ip", "unknown") + + print(f"[+] Device Connected!") + print(f" - Firmware: MimiCon v{app_version} (Built: {compile_time})") + print(f" - Network: {sta_ssid} (IP: {sta_ip})") + print(f" - Console Mode: {mode_name}") + print(f" - Current Slot: {running_part} -> Target Slot: {next_part}") + print() + + upload_url = f"{host.rstrip('/')}/api/ota/upload" + print(f"[*] Uploading binary to {upload_url}...") + + with open(bin_path, "rb") as f: + bin_data = f.read() + + req = urllib.request.Request( + upload_url, + data=bin_data, + headers={ + "Content-Type": "application/octet-stream", + "Content-Length": str(len(bin_data)), + "User-Agent": "ESP32-OTA-Tool" + }, + method="POST" + ) + + start_time = time.time() + try: + with urllib.request.urlopen(req, timeout=120) as resp: + resp_body = resp.read().decode("utf-8") + elapsed = time.time() - start_time + speed = (file_size / 1024) / elapsed if elapsed > 0 else 0 + print(f"[+] Upload complete in {elapsed:.2f}s ({speed:.1f} KB/s)!") + print(f"[+] Device response: {resp_body}") + except urllib.error.HTTPError as e: + print(f"[-] HTTP Error {e.code}: {e.read().decode('utf-8')}") + return False + except Exception as e: + print(f"[-] Upload failed: {e}") + return False + + print("\n[*] Waiting for ESP32-S3 reboot and reconnection (approx. 5-8 seconds)...") + time.sleep(3) + + reconnected = False + for attempt in range(15): + time.sleep(1) + st = get_status(host, timeout=2) + if st: + new_running = st.get("running_part", "unknown") + new_compile = st.get("compile_time", "unknown") + print(f"\n[+] ESP32-S3 is back online!") + print(f" - Active Slot: {new_running}") + print(f" - Build Time: {new_compile}") + print(f" - Console Mode: {st.get('mode_name', 'unknown')}") + if new_running == next_part: + print(f"[SUCCESS] Successfully updated from {running_part} -> {new_running}!") + else: + print(f"[+] Partition status: {new_running}") + reconnected = True + break + else: + print(".", end="", flush=True) + + if not reconnected: + print("\n[!] Device rebooted but took longer than 15s to reconnect to mDNS.") + print(" Check the serial monitor or web portal to verify.") + return True + + return True + +if __name__ == "__main__": + target_bin = sys.argv[1] if len(sys.argv) > 1 else DEFAULT_BIN + target_host = sys.argv[2] if len(sys.argv) > 2 else DEFAULT_HOST + success = flash_firmware(target_bin, target_host) + sys.exit(0 if success else 1) diff --git a/partitions.csv b/partitions.csv new file mode 100644 index 0000000..a87dc38 --- /dev/null +++ b/partitions.csv @@ -0,0 +1,7 @@ +# ESP-IDF Partition Table +# Name, Type, SubType, Offset, Size, Flags +nvs, data, nvs, 0x9000, 0x4000, +otadata, data, ota, 0xd000, 0x2000, +phy_init, data, phy, 0xf000, 0x1000, +ota_0, app, ota_0, 0x10000, 0x1F0000, +ota_1, app, ota_1, 0x200000,0x1F0000, diff --git a/sdkconfig.defaults b/sdkconfig.defaults new file mode 100644 index 0000000..99411e5 --- /dev/null +++ b/sdkconfig.defaults @@ -0,0 +1,52 @@ +CONFIG_IDF_TARGET="esp32s3" + +# Flash & PSRAM configuration (ESP32-S3FH4R2) +CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y +CONFIG_ESPTOOLPY_FLASHFREQ_80M=y +CONFIG_ESPTOOLPY_FLASHMODE_DIO=y + +CONFIG_SPIRAM=y +CONFIG_SPIRAM_MODE_QUAD=y +CONFIG_SPIRAM_SPEED_80M=y + +# Custom Partition Table (2.25MB App Partition) +CONFIG_PARTITION_TABLE_CUSTOM=y +CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv" +CONFIG_PARTITION_TABLE_FILENAME="partitions.csv" + +# Console via UART0 (Pins 43/44) +# When TinyUSB is acting as a USB Gamepad device on native USB (GPIO19/20), +# console output is sent via UART0 to avoid USB peripheral resource collision. +CONFIG_ESP_CONSOLE_UART_DEFAULT=y +CONFIG_ESP_CONSOLE_SECONDARY_NONE=y + +# Bluetooth LE (NimBLE Host Stack as BLE Central) +CONFIG_BT_ENABLED=y +CONFIG_BT_NIMBLE_ENABLED=y +CONFIG_BT_CONTROLLER_ENABLED=y +CONFIG_BT_NIMBLE_ROLE_CENTRAL=y +CONFIG_BT_NIMBLE_ROLE_OBSERVER=y +CONFIG_BT_NIMBLE_ROLE_PERIPHERAL=n +CONFIG_BT_NIMBLE_ROLE_BROADCASTER=n +CONFIG_BT_NIMBLE_MAX_CONNECTIONS=1 +CONFIG_BT_NIMBLE_SM_LEGACY=y +CONFIG_BT_NIMBLE_SM_SC=y + +# Wi-Fi & Software Coexistence +CONFIG_ESP_WIFI_ENABLED=y +CONFIG_ESP_WIFI_SOFTAP_SUPPORT=y +CONFIG_ESP_COEX_SW_COEXIST_ENABLE=y +CONFIG_LWIP_IPV4=y + +# HTTP Web Server +CONFIG_HTTPD_MAX_REQ_HDR_LEN=1024 +CONFIG_HTTPD_MAX_URI_LEN=512 +CONFIG_HTTPD_WS_SUPPORT=y + +# TinyUSB HID Device Emulation +CONFIG_TINYUSB_HID_COUNT=1 + +# System & FreeRTOS +CONFIG_FREERTOS_HZ=1000 +CONFIG_LOG_DEFAULT_LEVEL_INFO=y +CONFIG_LOG_COLORS=y diff --git a/version.txt b/version.txt new file mode 100644 index 0000000..3eefcb9 --- /dev/null +++ b/version.txt @@ -0,0 +1 @@ +1.0.0