From dd374bce7ff9811b9369b85d3193322016fa8cdf Mon Sep 17 00:00:00 2001 From: PA Dev Bot <344001113+pa-devbot@users.noreply.github.com> Date: Sun, 18 Oct 2026 18:01:01 +0000 Subject: [PATCH 01/58] Python: basic pybind11 interface to the microcontroller Adds _pa_core, a pybind11 module (new PA_PYTHON_BINDINGS cmake option, OFF by default) that wraps the existing CoreLib class NintendoSwitch::PybindSwitchProController so Python can act as a Nintendo Switch controller through a PABotBase2 serial device: status, queued button / d-pad / stick commands, flush and cancel, button/d-pad constants, and log-to-stderr/file controls. C++ exceptions surface as RuntimeError; blocking calls release the GIL. The pokemon_automation Python package sits on top of it: SwitchController (button names instead of bitfields), button parsing, list_serial_ports(), a hardware-free FakeController, a hardware self-test, and a pytest suite. See SerialPrograms/Source/PythonBindings/README.md. A new CI workflow builds the GUI-free core plus the module on Ubuntu and runs the pytest suite. PR #1519 is used as a reference. --- SerialPrograms/CMakeLists.txt | 13 + .../Source/PythonBindings/.gitignore | 8 + .../PythonBindings/PythonBindings.cmake | 64 +++++ .../PythonBindings/PythonBindings_Module.cpp | 258 ++++++++++++++++++ .../Source/PythonBindings/README.md | 91 ++++++ .../Source/PythonBindings/conftest.py | 6 + .../pokemon_automation.egg-info/PKG-INFO | 102 +++++++ .../pokemon_automation.egg-info/SOURCES.txt | 18 ++ .../dependency_links.txt | 1 + .../pokemon_automation.egg-info/requires.txt | 6 + .../pokemon_automation.egg-info/top_level.txt | 1 + .../pokemon_automation/__init__.py | 52 ++++ .../pokemon_automation/_core.py | 58 ++++ .../pokemon_automation/buttons.py | 208 ++++++++++++++ .../pokemon_automation/controller.py | 200 ++++++++++++++ .../pokemon_automation/devices.py | 36 +++ .../PythonBindings/pokemon_automation/fake.py | 86 ++++++ .../pokemon_automation/selftest.py | 61 +++++ .../Source/PythonBindings/pyproject.toml | 29 ++ .../PythonBindings/tests/test_buttons.py | 56 ++++ .../PythonBindings/tests/test_controller.py | 133 +++++++++ .../Source/PythonBindings/tests/test_core.py | 60 ++++ 22 files changed, 1547 insertions(+) create mode 100644 SerialPrograms/Source/PythonBindings/.gitignore create mode 100644 SerialPrograms/Source/PythonBindings/PythonBindings.cmake create mode 100644 SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp create mode 100644 SerialPrograms/Source/PythonBindings/README.md create mode 100644 SerialPrograms/Source/PythonBindings/conftest.py create mode 100644 SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/PKG-INFO create mode 100644 SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/SOURCES.txt create mode 100644 SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/dependency_links.txt create mode 100644 SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/requires.txt create mode 100644 SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/top_level.txt create mode 100644 SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py create mode 100644 SerialPrograms/Source/PythonBindings/pokemon_automation/_core.py create mode 100644 SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py create mode 100644 SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py create mode 100644 SerialPrograms/Source/PythonBindings/pokemon_automation/devices.py create mode 100644 SerialPrograms/Source/PythonBindings/pokemon_automation/fake.py create mode 100644 SerialPrograms/Source/PythonBindings/pokemon_automation/selftest.py create mode 100644 SerialPrograms/Source/PythonBindings/pyproject.toml create mode 100644 SerialPrograms/Source/PythonBindings/tests/test_buttons.py create mode 100644 SerialPrograms/Source/PythonBindings/tests/test_controller.py create mode 100644 SerialPrograms/Source/PythonBindings/tests/test_core.py diff --git a/SerialPrograms/CMakeLists.txt b/SerialPrograms/CMakeLists.txt index c36d2f86f5..95954a2256 100644 --- a/SerialPrograms/CMakeLists.txt +++ b/SerialPrograms/CMakeLists.txt @@ -63,6 +63,11 @@ find_package(Threads REQUIRED) # Define a toggle option (ON by default) option(COMMAND_LINE_EXE "Build the optional executable" ON) +# Build the _pa_core Python (pybind11) module; see Source/PythonBindings/README.md. +# OFF by default because it needs a Python interpreter with development headers +# and pybind11 (a system package or `pip install pybind11`). +option(PA_PYTHON_BINDINGS "Build the _pa_core Python module (Switch controller)" OFF) + # Build only the GUI-free core: CoreLib and SerialProgramsCommandLine. This needs # no Qt, OpenCV, ONNX Runtime, Tesseract, DPP or Discord SDK, so none of them are # searched for. @@ -84,6 +89,9 @@ if(PA_CORE_ONLY) if(COMMAND_LINE_EXE) include(Source/CommandLine/CommandLineExecutable.cmake) endif() + if(PA_PYTHON_BINDINGS) + include(Source/PythonBindings/PythonBindings.cmake) + endif() return() endif() @@ -871,3 +879,8 @@ if(COMMAND_LINE_EXE) # Add command-line executable (GUI-free) from subdirectory include(Source/CommandLine/CommandLineExecutable.cmake) endif() + +if(PA_PYTHON_BINDINGS) + # Python bindings (GUI-free) from subdirectory + include(Source/PythonBindings/PythonBindings.cmake) +endif() diff --git a/SerialPrograms/Source/PythonBindings/.gitignore b/SerialPrograms/Source/PythonBindings/.gitignore new file mode 100644 index 0000000000..2def3a1d08 --- /dev/null +++ b/SerialPrograms/Source/PythonBindings/.gitignore @@ -0,0 +1,8 @@ +# Built extension module (copied in by CMake after building _pa_core) +pokemon_automation/_pa_core*.so +pokemon_automation/_pa_core*.pyd + +# Python +__pycache__/ +*.pyc +.pytest_cache/ diff --git a/SerialPrograms/Source/PythonBindings/PythonBindings.cmake b/SerialPrograms/Source/PythonBindings/PythonBindings.cmake new file mode 100644 index 0000000000..9a9d93f599 --- /dev/null +++ b/SerialPrograms/Source/PythonBindings/PythonBindings.cmake @@ -0,0 +1,64 @@ +# Python bindings: the `_pa_core` module. +# +# This file is included by CMakeLists.txt when PA_PYTHON_BINDINGS is ON, for both +# the full build and the core-only build (-DPA_CORE_ONLY=ON). +# +# It builds `_pa_core`, a pybind11 extension module that lets Python act as a +# Nintendo Switch controller through a PABotBase2 serial device. It links only +# CoreLib (this codebase, GUI-free); it needs no Qt, OpenCV, ONNX Runtime or +# Tesseract. See Source/PythonBindings/README.md for usage. +# +# Configure with, for example: +# cmake .. -DPA_PYTHON_BINDINGS=ON [-DPython_EXECUTABLE=$(which python3)] +# and build with: +# cmake --build . --target _pa_core +# +# After each build the module is copied into the `pokemon_automation` package +# (Source/PythonBindings/pokemon_automation/), so the package can be used +# straight from the source tree (or with `pip install -e Source/PythonBindings`). + +# The extension module is a shared library, so everything linked into it must be +# position-independent. +set_target_properties(CoreLib PROPERTIES POSITION_INDEPENDENT_CODE ON) + +# pybind11: prefer an installed copy (a system package or `pip install pybind11`), +# and download a pinned release only as a fallback. +set(PYBIND11_FINDPYTHON ON) +find_package(Python 3.10 REQUIRED COMPONENTS Interpreter Development.Module) +find_package(pybind11 CONFIG QUIET) +if (NOT pybind11_FOUND) + execute_process( + COMMAND "${Python_EXECUTABLE}" -m pybind11 --cmakedir + OUTPUT_VARIABLE PYBIND11_PIP_CMAKE_DIR + OUTPUT_STRIP_TRAILING_WHITESPACE + ERROR_QUIET + ) + if (PYBIND11_PIP_CMAKE_DIR) + find_package(pybind11 CONFIG QUIET PATHS "${PYBIND11_PIP_CMAKE_DIR}" NO_DEFAULT_PATH) + endif() +endif() +if (NOT pybind11_FOUND) + message(STATUS "Python bindings: pybind11 not found, downloading it") + include(FetchContent) + FetchContent_Declare( + pybind11 + GIT_REPOSITORY https://github.com/pybind/pybind11.git + GIT_TAG v3.0.1 + ) + FetchContent_MakeAvailable(pybind11) +endif() +message(STATUS "Python bindings: building _pa_core for ${Python_EXECUTABLE} (${Python_VERSION})") + +# The controller class the module wraps (Source/Integrations/PybindSwitchController.*) +# is part of CoreLib, so only the module file is compiled here. +pybind11_add_module(_pa_core Source/PythonBindings/PythonBindings_Module.cpp) +pa_apply_gui_free_target_properties(_pa_core) +target_link_libraries(_pa_core PRIVATE CoreLib) + +# Copy the built module into the package next to the Python sources. +add_custom_command( + TARGET _pa_core POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy $ + ${CMAKE_CURRENT_SOURCE_DIR}/Source/PythonBindings/pokemon_automation/ + COMMENT "Copying _pa_core into the pokemon_automation Python package" +) diff --git a/SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp b/SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp new file mode 100644 index 0000000000..956ef33ee2 --- /dev/null +++ b/SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp @@ -0,0 +1,258 @@ +/* _pa_core: Pokemon Automation's Python module + * + * From: https://github.com/PokemonAutomation/ + * + * pybind11 module that lets Python act as a Nintendo Switch controller through a + * PABotBase2 serial device. It wraps `NintendoSwitch::PybindSwitchProController` + * (Source/Integrations/), which is part of CoreLib, so it links CoreLib only: no + * Qt, OpenCV, ONNX Runtime or Tesseract. + * + * The `pokemon_automation` Python package next to this file is built on top of + * this module (see Source/PythonBindings/README.md). + * + * Conventions: + * - All durations are milliseconds. + * - Commands are queued on the device: the push_*() / controller_state() calls + * return as soon as the command is scheduled, not when it executes. Call + * wait_for_all_requests() to block until everything queued has executed. + * - Every call that can block releases the Python GIL, so other Python threads + * (e.g. an emergency stop) keep running. + * - C++ `PokemonAutomation::Exception`s become Python `RuntimeError`s. + * - Nothing is written to stdout. Internal log lines can be routed to stderr + * and/or a log file with set_log_stderr() / set_log_file(). + */ + +#include +#include +#include +#include +#include +#include + +#include "Common/Cpp/Concurrency/Mutex.h" +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Logging/GlobalLogger.h" +#include "Common/Cpp/Logging/MultiOutputLogger.h" +#include "Common/Cpp/Time.h" +#include "Integrations/PybindSwitchController.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ControllerButtons.h" + +namespace py = pybind11; + +// CoreLib references this in every executable that links it. The module has no Qt UI. +namespace PokemonAutomation{ + bool USE_QT_UI = false; +} + + +namespace{ + +// Receives every line written to the global logger and forwards it to stderr +// and/or a log file, while keeping the most recent lines in memory for +// `recent_logs()`. +class PythonLogSink final : public PokemonAutomation::Logger{ +public: + static PythonLogSink& instance(){ + static PythonLogSink sink; + return sink; + } + + void set_stderr(bool enabled){ + PokemonAutomation::LockGuard lg(m_lock); + m_stderr = enabled; + } + + // Append log lines to `path`. An empty path stops file logging. + // Throws FileException if the file can't be opened. + void set_file(const std::string& path){ + PokemonAutomation::LockGuard lg(m_lock); + m_file.close(); + if (!path.empty()){ + m_file.open(path, std::ios::app); + if (!m_file){ + throw PokemonAutomation::FileException( + nullptr, + PA_CURRENT_FUNCTION, + "Unable to open log file.", + path + ); + } + } + } + + // Up to `count` of the most recent log lines, oldest first. + std::vector recent(size_t count) const{ + PokemonAutomation::LockGuard lg(m_lock); + count = std::min(count, m_recent.size()); + return std::vector(m_recent.end() - count, m_recent.end()); + } + + virtual void log(const std::string& msg, PokemonAutomation::Color color = PokemonAutomation::Color()) override{ + PokemonAutomation::LockGuard lg(m_lock); + if (m_stderr){ + std::cerr << msg << std::endl; + } + if (m_file.is_open()){ + m_file << msg << std::endl; + m_file.flush(); + } + m_recent.emplace_back(msg); + if (m_recent.size() > kMaxRecentLines){ + m_recent.pop_front(); + } + } + +private: + PythonLogSink(){ + PokemonAutomation::global_multi_logger().add_listener(*this); + } + + static constexpr size_t kMaxRecentLines = 1000; + + mutable PokemonAutomation::Mutex m_lock; + bool m_stderr = true; + std::ofstream m_file; + std::deque m_recent; +}; + +} + + +using namespace PokemonAutomation; +using NintendoSwitch::PybindSwitchProController; + + +PYBIND11_MODULE(_pa_core, m){ + m.doc() = "Pokemon Automation: act as a Nintendo Switch controller through a PABotBase2 serial device."; + + // C++ exceptions -> Python exceptions. + py::register_exception_translator([](std::exception_ptr p){ + try{ + if (p){ + std::rethrow_exception(p); + } + }catch (const PokemonAutomation::Exception& e){ + PyErr_SetString(PyExc_RuntimeError, e.to_str().c_str()); + } + }); + + // Attach the log sink before anything logs. + PythonLogSink::instance(); + + + // Logging. + + m.def( + "set_log_stderr", + [](bool enabled){ PythonLogSink::instance().set_stderr(enabled); }, + py::arg("enabled"), + "Echo internal log lines to stderr (enabled by default)." + ); + m.def( + "set_log_file", + [](const std::string& path){ PythonLogSink::instance().set_file(path); }, + py::arg("path"), + "Append internal log lines to this file. Pass an empty string to stop." + ); + m.def( + "log", + [](const std::string& message){ + global_logger_raw().log(current_time_to_str() + " - " + message); + }, + py::arg("message"), + "Write a line to the internal log, so Python events appear alongside the C++ ones." + ); + m.def( + "recent_logs", + [](size_t count){ return PythonLogSink::instance().recent(count); }, + py::arg("count") = 50, + "Return up to `count` of the most recent internal log lines, oldest first." + ); + + + // Input constants, so Python code never hard-codes bit positions or d-pad + // numbers. Keys are the C++ names without the "BUTTON_" / "DPAD_" prefix. + + py::dict buttons; + for (size_t bit = 0; bit < NintendoSwitch::TOTAL_BUTTONS; bit++){ + NintendoSwitch::Button button = (NintendoSwitch::Button)((uint32_t)1 << bit); + std::string name = NintendoSwitch::button_to_code_string(button); + if (name.starts_with("BUTTON_")){ + name = name.substr(7); + } + buttons[py::str(name)] = (uint32_t)button; + } + m.attr("BUTTONS") = buttons; + + py::dict dpad_positions; + for (size_t position = 0; position <= (size_t)NintendoSwitch::DpadPosition::DPAD_NONE; position++){ + std::string name = NintendoSwitch::dpad_to_code_string((NintendoSwitch::DpadPosition)position); + if (name.starts_with("DPAD_")){ + name = name.substr(5); + } + dpad_positions[py::str(name)] = (uint32_t)position; + } + m.attr("DPAD_POSITIONS") = dpad_positions; + + + // Controller. + + py::class_(m, "Controller", + "A Switch controller on a PABotBase2 device. Commands are queued on the device " + "and return as soon as they are scheduled; call wait_for_all_requests() to block " + "until they have executed.") + .def(py::init(), py::arg("port_name")) + .def("wait_for_ready", &PybindSwitchProController::wait_for_ready, + py::arg("timeout_ms") = 10000, + "Block until the device handshake finishes and a Switch controller is " + "available, or `timeout_ms` passes. Returns True if ready.", + py::call_guard()) + .def("is_ready", &PybindSwitchProController::is_ready, + "True if the device is connected and a Switch controller is available.") + .def("current_status", &PybindSwitchProController::current_status, + "The connection status text: device name and firmware version, or the " + "error message if the connection failed.") + .def("controller_name", &PybindSwitchProController::controller_name, + "Name of the active controller implementation, e.g. " + "\"Nintendo Switch: Pro Controller\". Empty if not ready.") + .def("wait_for_all_requests", &PybindSwitchProController::wait_for_all_requests, + "Block until every command queued so far has been executed by the device.", + py::call_guard()) + .def("cancel_all_commands", &PybindSwitchProController::cancel_all_commands, + "Cancel every command that has not executed yet, clearing the device's " + "command queue and returning the controller to the neutral state. " + "Asynchronous: does not wait for the device to reach the neutral state.") + .def("wait", &PybindSwitchProController::wait, + py::arg("duration_ms"), + "Queue a pause of `duration_ms` with nothing pressed.", + py::call_guard()) + .def("push_button", &PybindSwitchProController::push_button, + py::arg("delay_ms"), py::arg("hold_ms"), py::arg("release_ms"), py::arg("bitfield"), + "Queue a press of every button in `bitfield` (see `BUTTONS`). `delay_ms` is " + "how long to wait before the press may start, `hold_ms` how long the buttons " + "stay down, `release_ms` how long they stay up before the same button can be " + "pressed again. D-pad directions are not part of `bitfield`; use push_dpad().", + py::call_guard()) + .def("push_dpad", &PybindSwitchProController::push_dpad, + py::arg("delay_ms"), py::arg("hold_ms"), py::arg("release_ms"), py::arg("position"), + "Queue a d-pad press in direction `position` (see `DPAD_POSITIONS`). " + "`delay_ms` / `hold_ms` / `release_ms` have the same meaning as in push_button().", + py::call_guard()) + .def("push_left_joystick", &PybindSwitchProController::push_left_joystick, + py::arg("delay_ms"), py::arg("hold_ms"), py::arg("release_ms"), py::arg("x"), py::arg("y"), + "Queue the left stick being held at (x, y), in [-1.0, 1.0] with +x = right " + "and +y = up. `delay_ms` / `hold_ms` / `release_ms` have the same meaning as in push_button().", + py::call_guard()) + .def("push_right_joystick", &PybindSwitchProController::push_right_joystick, + py::arg("delay_ms"), py::arg("hold_ms"), py::arg("release_ms"), py::arg("x"), py::arg("y"), + "Queue the right stick being held at (x, y), in [-1.0, 1.0] with +x = right " + "and +y = up. `delay_ms` / `hold_ms` / `release_ms` have the same meaning as in push_button().", + py::call_guard()) + .def("controller_state", &PybindSwitchProController::controller_state, + py::arg("duration_ms"), py::arg("buttons"), py::arg("dpad"), + py::arg("left_x"), py::arg("left_y"), py::arg("right_x"), py::arg("right_y"), + "Queue the entire controller state (buttons, d-pad, both sticks) being held " + "for `duration_ms`; everything not specified is released. This is the most " + "direct way to hold arbitrary combinations, e.g. B while moving the left stick.", + py::call_guard()); +} diff --git a/SerialPrograms/Source/PythonBindings/README.md b/SerialPrograms/Source/PythonBindings/README.md new file mode 100644 index 0000000000..ffb8029fb1 --- /dev/null +++ b/SerialPrograms/Source/PythonBindings/README.md @@ -0,0 +1,91 @@ +# Python Bindings + +A basic Python interface for the microcontroller, built with [pybind11](https://github.com/pybind/pybind11). +It lets Python act as a Nintendo Switch controller through a PABotBase2 serial +device, using the `NintendoSwitch::PybindSwitchProController` class from CoreLib +(`Source/Integrations/PybindSwitchController.h`). + +## Layout + +- `PythonBindings_Module.cpp` — the `_pa_core` pybind11 module: a thin 1:1 + binding of `PybindSwitchProController` plus logging controls and the + `BUTTONS` / `DPAD_POSITIONS` constants. +- `PythonBindings.cmake` — builds the module (linked against CoreLib only: no + Qt, OpenCV, ONNX Runtime or Tesseract). +- `pokemon_automation/` — the Python package on top of it: + - `controller.py` — `SwitchController`: the user-facing API, with button names + instead of bitfields (`press("L+R")`, `stick("left", "up")`, ...). + - `buttons.py` — parsing of button / d-pad / stick names into bitfields. + - `fake.py` — `FakeController`: the same backend interface without hardware, + for unit tests. + - `devices.py` — `list_serial_ports()`. + - `selftest.py` — `python -m pokemon_automation.selftest [port]`: connect to + a real device and send a few commands. +- `tests/` — pytest suite (pure-Python parts always run; compiled-module tests + skip when `_pa_core` is not built). + +## Building the module + +Requires a Python 3.10+ with development headers and pybind11 (a system package +or `pip install pybind11`). If neither is found, CMake downloads a pinned +pybind11 release. + +```sh +cd SerialPrograms +mkdir bin && cd bin +cmake .. -DPA_PYTHON_BINDINGS=ON [-DPA_CORE_ONLY=ON] [-DPython_EXECUTABLE=$(which python3)] +cmake --build . --target _pa_core +``` + +`-DPA_CORE_ONLY=ON` builds only the GUI-free core (CoreLib, +SerialProgramsCommandLine and the module) — the fast path; without it the +module is built alongside the full GUI program. + +After the build, `_pa_core` is copied into `pokemon_automation/`, so the +package works straight from the source tree. To install it for a project: + +```sh +pip install -e SerialPrograms/Source/PythonBindings +``` + +## Usage + +```python +from pokemon_automation import SwitchController, list_serial_ports + +print(list_serial_ports()) +with SwitchController("/dev/ttyACM0") as sw: + print(sw.status()) # device name and firmware version + sw.press("A") # tap A (80 ms hold, 80 ms release) + sw.press("L+R", hold_ms=200) # press L and R together + sw.press("up", repeat=2) # d-pad up twice + sw.stick("left", "up", duration_ms=1500) # walk forward + sw.hold("B", left="up", duration_ms=2000) # run forward + sw.wait(300) + sw.flush() # block until the device executed everything +``` + +Commands are queued on the microcontroller and return as soon as they are +scheduled, mirroring the `pbf_*()` functions of the main program. Call +`flush()` to wait for execution, and `cancel_all_commands()` (thread-safe) to +drop the queue and release all inputs — e.g. from an emergency-stop thread. + +Run the tests: + +```sh +cd SerialPrograms/Source/PythonBindings +python -m pytest +``` + +## Notes + +- All durations are milliseconds. +- C++ `PokemonAutomation::Exception`s surface as Python `RuntimeError`s. +- Internal log lines (the "Pybind"-tagged connection logs) are not written to + stdout. `_pa_core.set_log_stderr(True/False)` and + `_pa_core.set_log_file(path)` route them to stderr and/or a file, and + `_pa_core.recent_logs(50)` returns the most recent lines. +- The device must be configured as a Pro Controller (or a wired controller) + with the main program; the device remembers the setting. +- PR #1519 ("Agent mcp server", draft) extends this interface with a full + `pokemon_automation` package (MCP server, video, OCR). diff --git a/SerialPrograms/Source/PythonBindings/conftest.py b/SerialPrograms/Source/PythonBindings/conftest.py new file mode 100644 index 0000000000..c4ab58fb73 --- /dev/null +++ b/SerialPrograms/Source/PythonBindings/conftest.py @@ -0,0 +1,6 @@ +# Make `import pokemon_automation` work when running pytest from the +# PythonBindings directory without installing the package. +import os +import sys + +sys.path.insert(0, os.path.dirname(__file__)) diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/PKG-INFO b/SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/PKG-INFO new file mode 100644 index 0000000000..f5f93fde62 --- /dev/null +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/PKG-INFO @@ -0,0 +1,102 @@ +Metadata-Version: 2.4 +Name: pokemon-automation +Version: 0.1.0 +Summary: Send Nintendo Switch controller input from Python with Pokemon Automation hardware. +Requires-Python: >=3.10 +Description-Content-Type: text/markdown +Provides-Extra: serial +Requires-Dist: pyserial>=3.5; extra == "serial" +Provides-Extra: test +Requires-Dist: pytest>=7; extra == "test" + +# Python Bindings + +A basic Python interface for the microcontroller, built with [pybind11](https://github.com/pybind/pybind11). +It lets Python act as a Nintendo Switch controller through a PABotBase2 serial +device, using the `NintendoSwitch::PybindSwitchProController` class from CoreLib +(`Source/Integrations/PybindSwitchController.h`). + +## Layout + +- `PythonBindings_Module.cpp` — the `_pa_core` pybind11 module: a thin 1:1 + binding of `PybindSwitchProController` plus logging controls and the + `BUTTONS` / `DPAD_POSITIONS` constants. +- `PythonBindings.cmake` — builds the module (linked against CoreLib only: no + Qt, OpenCV, ONNX Runtime or Tesseract). +- `pokemon_automation/` — the Python package on top of it: + - `controller.py` — `SwitchController`: the user-facing API, with button names + instead of bitfields (`press("L+R")`, `stick("left", "up")`, ...). + - `buttons.py` — parsing of button / d-pad / stick names into bitfields. + - `fake.py` — `FakeController`: the same backend interface without hardware, + for unit tests. + - `devices.py` — `list_serial_ports()`. + - `selftest.py` — `python -m pokemon_automation.selftest [port]`: connect to + a real device and send a few commands. +- `tests/` — pytest suite (pure-Python parts always run; compiled-module tests + skip when `_pa_core` is not built). + +## Building the module + +Requires a Python 3.10+ with development headers and pybind11 (a system package +or `pip install pybind11`). If neither is found, CMake downloads a pinned +pybind11 release. + +```sh +cd SerialPrograms +mkdir bin && cd bin +cmake .. -DPA_PYTHON_BINDINGS=ON [-DPA_CORE_ONLY=ON] [-DPython_EXECUTABLE=$(which python3)] +cmake --build . --target _pa_core +``` + +`-DPA_CORE_ONLY=ON` builds only the GUI-free core (CoreLib, +SerialProgramsCommandLine and the module) — the fast path; without it the +module is built alongside the full GUI program. + +After the build, `_pa_core` is copied into `pokemon_automation/`, so the +package works straight from the source tree. To install it for a project: + +```sh +pip install -e SerialPrograms/Source/PythonBindings +``` + +## Usage + +```python +from pokemon_automation import SwitchController, list_serial_ports + +print(list_serial_ports()) +with SwitchController("/dev/ttyACM0") as sw: + print(sw.status()) # device name and firmware version + sw.press("A") # tap A (80 ms hold, 80 ms release) + sw.press("L+R", hold_ms=200) # press L and R together + sw.press("up", repeat=2) # d-pad up twice + sw.stick("left", "up", duration_ms=1500) # walk forward + sw.hold("B", left="up", duration_ms=2000) # run forward + sw.wait(300) + sw.flush() # block until the device executed everything +``` + +Commands are queued on the microcontroller and return as soon as they are +scheduled, mirroring the `pbf_*()` functions of the main program. Call +`flush()` to wait for execution, and `cancel_all_commands()` (thread-safe) to +drop the queue and release all inputs — e.g. from an emergency-stop thread. + +Run the tests: + +```sh +cd SerialPrograms/Source/PythonBindings +python -m pytest +``` + +## Notes + +- All durations are milliseconds. +- C++ `PokemonAutomation::Exception`s surface as Python `RuntimeError`s. +- Internal log lines (the "Pybind"-tagged connection logs) are not written to + stdout. `_pa_core.set_log_stderr(True/False)` and + `_pa_core.set_log_file(path)` route them to stderr and/or a file, and + `_pa_core.recent_logs(50)` returns the most recent lines. +- The device must be configured as a Pro Controller (or a wired controller) + with the main program; the device remembers the setting. +- PR #1519 ("Agent mcp server", draft) extends this interface with a full + `pokemon_automation` package (MCP server, video, OCR). diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/SOURCES.txt b/SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/SOURCES.txt new file mode 100644 index 0000000000..f8378c1acd --- /dev/null +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/SOURCES.txt @@ -0,0 +1,18 @@ +README.md +pyproject.toml +pokemon_automation/__init__.py +pokemon_automation/_core.py +pokemon_automation/_pa_core.cpython-314-aarch64-linux-gnu.so +pokemon_automation/buttons.py +pokemon_automation/controller.py +pokemon_automation/devices.py +pokemon_automation/fake.py +pokemon_automation/selftest.py +pokemon_automation.egg-info/PKG-INFO +pokemon_automation.egg-info/SOURCES.txt +pokemon_automation.egg-info/dependency_links.txt +pokemon_automation.egg-info/requires.txt +pokemon_automation.egg-info/top_level.txt +tests/test_buttons.py +tests/test_controller.py +tests/test_core.py \ No newline at end of file diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/dependency_links.txt b/SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/dependency_links.txt new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/dependency_links.txt @@ -0,0 +1 @@ + diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/requires.txt b/SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/requires.txt new file mode 100644 index 0000000000..838faf46e4 --- /dev/null +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/requires.txt @@ -0,0 +1,6 @@ + +[serial] +pyserial>=3.5 + +[test] +pytest>=7 diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/top_level.txt b/SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/top_level.txt new file mode 100644 index 0000000000..a49f7f3514 --- /dev/null +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/top_level.txt @@ -0,0 +1 @@ +pokemon_automation diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py new file mode 100644 index 0000000000..c3d1586fb4 --- /dev/null +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py @@ -0,0 +1,52 @@ +"""Pokemon Automation: send Nintendo Switch controller input from Python. + +Layers (each built on the one below): + +- `_pa_core` (C++, pybind11): acts as a Switch controller through a PABotBase2 + serial device, built only from this codebase's CoreLib. Build it from + SerialPrograms with `-DPA_PYTHON_BINDINGS=ON` (see the README next to this + package). +- `SwitchController`: the Python API on top of it, with button names instead of + bitfields. `fake.FakeController` implements the same backend interface for + testing without hardware. + +Quick start: + from pokemon_automation import SwitchController, list_serial_ports + + print(list_serial_ports()) + with SwitchController("/dev/cu.usbserial-0001") as sw: + sw.press("A") + sw.press("up+right") + sw.stick("left", "up", duration_ms=1500) + sw.flush() +""" + +from .buttons import ( + BUTTON_ALIASES, + BUTTON_BITS, + DPAD_NONE, + DPAD_POSITIONS, + ParsedButtons, + check_against_core, + parse_buttons, + parse_stick, +) +from .controller import SwitchController +from .devices import list_serial_ports +from .fake import FakeController + +__all__ = [ + "BUTTON_ALIASES", + "BUTTON_BITS", + "DPAD_NONE", + "DPAD_POSITIONS", + "FakeController", + "ParsedButtons", + "SwitchController", + "check_against_core", + "list_serial_ports", + "parse_buttons", + "parse_stick", +] + +__version__ = "0.1.0" diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/_core.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/_core.py new file mode 100644 index 0000000000..1b14da832b --- /dev/null +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/_core.py @@ -0,0 +1,58 @@ +"""Locate and import the compiled `_pa_core` extension module. + +The module is built by CMake (`-DPA_PYTHON_BINDINGS=ON`, target `_pa_core`) and +copied next to this file after every build. Set the environment variable +`PA_CORE_PATH` to a folder containing `_pa_core*.so` / `_pa_core*.pyd` to load +it from somewhere else. + +Importing is deferred until first use, so the pure-Python parts of the package +(button parsing, `fake.FakeController`) work without the compiled module. +""" + +from __future__ import annotations + +import importlib +import os +import sys +from types import ModuleType + +_module: ModuleType | None = None + +BUILD_HINT = ( + "The compiled module pokemon_automation._pa_core was not found. Build it with:\n" + " cmake -DPA_PYTHON_BINDINGS=ON -DPython_EXECUTABLE=" + sys.executable + "\n" + " cmake --build . --target _pa_core\n" + "or set PA_CORE_PATH to the folder containing the built module." +) + + +def core() -> ModuleType: + """Return the `_pa_core` module, importing it on first call. + + Raises ImportError with build instructions if the module can't be found. + """ + global _module + if _module is not None: + return _module + override = os.environ.get("PA_CORE_PATH") + if override: + sys.path.insert(0, override) + try: + _module = importlib.import_module("_pa_core") + finally: + sys.path.remove(override) + return _module + try: + from . import _pa_core # type: ignore[attr-defined] + except ImportError as e: + raise ImportError(BUILD_HINT) from e + _module = _pa_core + return _module + + +def core_available() -> bool: + try: + core() + return True + except ImportError: + return False diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py new file mode 100644 index 0000000000..b1323ea78d --- /dev/null +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py @@ -0,0 +1,208 @@ +"""Button and d-pad names shared by the Python API. + +Everything a caller types to describe an input is parsed here: + +- Buttons: "A", "B", "X", "Y", "L", "R", "ZL", "ZR", "PLUS" ("+", "START"), + "MINUS" ("-", "SELECT"), "HOME", "CAPTURE", "LCLICK" ("L3", "LS"), + "RCLICK" ("R3", "RS"). Case-insensitive. +- D-pad: "UP", "DOWN", "LEFT", "RIGHT" and diagonals such as "UP_RIGHT" (also + "UP-RIGHT", "UPRIGHT"). Listing "UP" and "RIGHT" together also means up-right. +- Combinations: a list (["L", "R"]) or a "+"-joined string ("L+R", "ZL+A"). +- Joystick positions: a direction name ("up", "down_left", ...) or an (x, y) pair + in [-1, 1] with +x = right and +y = up. "neutral"/"center" means (0, 0). + +The button bit values match `NintendoSwitch::Button` in +Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerButtons.h. When the +compiled module is available, `check_against_core()` verifies that they still agree. +""" + +from __future__ import annotations + +import math +from collections.abc import Sequence +from dataclasses import dataclass + +# Bit positions from NintendoSwitch_ControllerButtons.h. +BUTTON_BITS: dict[str, int] = { + "Y": 1 << 0, + "B": 1 << 1, + "A": 1 << 2, + "X": 1 << 3, + "L": 1 << 4, + "R": 1 << 5, + "ZL": 1 << 6, + "ZR": 1 << 7, + "MINUS": 1 << 8, + "PLUS": 1 << 9, + "LCLICK": 1 << 10, + "RCLICK": 1 << 11, + "HOME": 1 << 12, + "CAPTURE": 1 << 13, +} + +BUTTON_ALIASES: dict[str, str] = { + "+": "PLUS", + "START": "PLUS", + "-": "MINUS", + "SELECT": "MINUS", + "L3": "LCLICK", + "LS": "LCLICK", + "R3": "RCLICK", + "RS": "RCLICK", +} + +# D-pad positions from `NintendoSwitch::DpadPosition`: 0 = up, clockwise, 8 = none. +DPAD_POSITIONS: dict[str, int] = { + "UP": 0, + "UP_RIGHT": 1, + "RIGHT": 2, + "DOWN_RIGHT": 3, + "DOWN": 4, + "DOWN_LEFT": 5, + "LEFT": 6, + "UP_LEFT": 7, +} +DPAD_NONE = 8 + +# Unit vectors for the 8 directions, used for both the d-pad and the joysticks. +_DIRECTION_VECTORS: dict[str, tuple[int, int]] = { + "UP": (0, 1), + "UP_RIGHT": (1, 1), + "RIGHT": (1, 0), + "DOWN_RIGHT": (1, -1), + "DOWN": (0, -1), + "DOWN_LEFT": (-1, -1), + "LEFT": (-1, 0), + "UP_LEFT": (-1, 1), +} + +ButtonsArg = str | Sequence[str] | None +StickArg = str | Sequence[float] | None + + +def _normalize_name(name: str) -> str: + name = name.strip().upper().replace("-", "_").replace(" ", "_") + if name.startswith("DPAD_"): + name = name[5:] + for vertical in ("UP", "DOWN"): + for horizontal in ("LEFT", "RIGHT"): + if name in (vertical + horizontal, horizontal + vertical, horizontal + "_" + vertical): + return vertical + "_" + horizontal + return name + + +def _split(buttons: ButtonsArg) -> list[str]: + if buttons is None: + return [] + if isinstance(buttons, str): + text = buttons.strip() + # A lone "+" or "-" is the PLUS/MINUS button, not a separator. + if text in ("+", "-"): + return [text] + return [part for part in text.replace(",", "+").split("+") if part.strip()] + ret: list[str] = [] + for item in buttons: + ret.extend(_split(item)) + return ret + + +@dataclass(frozen=True) +class ParsedButtons: + """The result of parsing a button combination.""" + + bitfield: int + dpad: int # DPAD_NONE if no d-pad direction was given + + @property + def has_buttons(self) -> bool: + return self.bitfield != 0 + + @property + def has_dpad(self) -> bool: + return self.dpad != DPAD_NONE + + +def parse_buttons(buttons: ButtonsArg) -> ParsedButtons: + """Parse a button combination into a bitfield plus a d-pad position. + + Examples: + parse_buttons("A") -> bitfield A, no d-pad + parse_buttons("L+R") -> bitfield L|R + parse_buttons(["ZL", "up"]) -> bitfield ZL, d-pad up + parse_buttons("up+right") -> d-pad up-right + + Raises ValueError for unknown names or contradictory d-pad directions + (e.g. "up+down"). + """ + bitfield = 0 + dx = dy = 0 + seen_dpad: list[str] = [] + for raw in _split(buttons): + name = raw.strip() + key = name.upper() if name in ("+", "-") else _normalize_name(name) + key = BUTTON_ALIASES.get(key, key) + if key in BUTTON_BITS: + bitfield |= BUTTON_BITS[key] + continue + if key in _DIRECTION_VECTORS: + vx, vy = _DIRECTION_VECTORS[key] + if (vx and dx and vx != dx) or (vy and dy and vy != dy): + raise ValueError(f"Contradictory d-pad directions: {seen_dpad + [name]}") + dx = vx or dx + dy = vy or dy + seen_dpad.append(name) + continue + raise ValueError( + f"Unknown button {name!r}. Valid buttons: {', '.join(BUTTON_BITS)}, " + f"d-pad: {', '.join(DPAD_POSITIONS)}." + ) + dpad = DPAD_NONE + if dx or dy: + for direction, (vx, vy) in _DIRECTION_VECTORS.items(): + if (vx, vy) == (dx, dy): + dpad = DPAD_POSITIONS[direction] + return ParsedButtons(bitfield, dpad) + + +def parse_stick(position: StickArg) -> tuple[float, float]: + """Parse a joystick position into (x, y) in [-1, 1], +y = up. + + Accepts a direction name ("up", "down_left", "neutral") or an (x, y) pair. + Diagonal names are normalized to length 1 so they tilt the stick fully. + Raises ValueError for unknown names or out-of-range coordinates. + """ + if position is None: + return (0.0, 0.0) + if isinstance(position, str): + key = _normalize_name(position) + if key in ("NEUTRAL", "CENTER", "NONE"): + return (0.0, 0.0) + if key not in _DIRECTION_VECTORS: + raise ValueError( + f"Unknown stick direction {position!r}. Use one of " + f"{', '.join(d.lower() for d in _DIRECTION_VECTORS)}, or an [x, y] pair." + ) + vx, vy = _DIRECTION_VECTORS[key] + length = math.hypot(vx, vy) + return (vx / length, vy / length) + values = list(position) + if len(values) != 2: + raise ValueError(f"A stick position needs exactly two numbers [x, y], got {position!r}.") + x, y = float(values[0]), float(values[1]) + if not (-1.0 <= x <= 1.0 and -1.0 <= y <= 1.0): + raise ValueError(f"Stick coordinates must be within [-1, 1], got ({x}, {y}).") + return (x, y) + + +def check_against_core(core_buttons: dict[str, int], core_dpad: dict[str, int]) -> None: + """Raise AssertionError if `BUTTON_BITS` / `DPAD_POSITIONS` disagree with the C++ enums. + + `core_buttons` / `core_dpad` are `_pa_core.BUTTONS` / `_pa_core.DPAD_POSITIONS`, + generated from `NintendoSwitch::Button` / `DpadPosition`. + """ + for name, bit in BUTTON_BITS.items(): + if core_buttons.get(name) != bit: + raise AssertionError(f"Button {name} is {bit:#x} in buttons.py but {core_buttons.get(name)!r} in _pa_core.") + for name, position in DPAD_POSITIONS.items(): + if core_dpad.get(name) != position: + raise AssertionError(f"D-pad {name} is {position} in buttons.py but {core_dpad.get(name)!r} in _pa_core.") diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py new file mode 100644 index 0000000000..935b0b4924 --- /dev/null +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py @@ -0,0 +1,200 @@ +"""High-level Nintendo Switch controller API on top of `_pa_core.Controller`. + +Commands are queued on the microcontroller and return immediately, like the +`pbf_*()` functions in the main C++ program. Call `flush()` to wait until +everything queued so far has executed, and `cancel_all_commands()` to drop +anything still queued and release all inputs. + +Example: + from pokemon_automation import SwitchController + + with SwitchController("/dev/cu.usbserial-0001") as sw: + sw.press("A") # tap A + sw.press("L+R", hold_ms=200) # press L and R together + sw.press("up", repeat=2) # d-pad up twice + sw.stick("left", "up", duration_ms=1500) # walk forward + sw.hold("B", left="up", duration_ms=2000) # run forward + sw.flush() +""" + +from __future__ import annotations + +import threading +from typing import Protocol + +from . import _core, buttons as btn + +DEFAULT_HOLD_MS = 80 +DEFAULT_RELEASE_MS = 80 + + +class ControllerBackend(Protocol): + """The `_pa_core.Controller` methods used here. `fake.FakeController` implements it too.""" + + def wait_for_ready(self, timeout_ms: int = ...) -> bool: ... + def is_ready(self) -> bool: ... + def current_status(self) -> str: ... + def controller_name(self) -> str: ... + def wait_for_all_requests(self) -> None: ... + def cancel_all_commands(self) -> None: ... + def wait(self, duration_ms: int) -> None: ... + def push_button(self, delay_ms: int, hold_ms: int, release_ms: int, bitfield: int) -> None: ... + def push_dpad(self, delay_ms: int, hold_ms: int, release_ms: int, position: int) -> None: ... + def push_left_joystick(self, delay_ms: int, hold_ms: int, release_ms: int, x: float, y: float) -> None: ... + def push_right_joystick(self, delay_ms: int, hold_ms: int, release_ms: int, x: float, y: float) -> None: ... + def controller_state( + self, duration_ms: int, buttons: int, dpad: int, + left_x: float, left_y: float, right_x: float, right_y: float, + ) -> None: ... + + +def _check_nonnegative(**kwargs: int) -> None: + for name, value in kwargs.items(): + if value < 0: + raise ValueError(f"{name} must not be negative, got {value}.") + + +class SwitchController: + """A Switch controller on a PABotBase2 device (ESP32/Pico running PA firmware). + + `port` is the serial port, e.g. "/dev/cu.usbserial-0001" on macOS, + "/dev/ttyACM0" on Linux or "COM3" on Windows. See `devices.list_serial_ports()`. + + Pass `backend` to wrap an existing `_pa_core.Controller` or a + `fake.FakeController` instead of opening a port. + + Raises RuntimeError if the device isn't ready within `timeout_s` seconds. + """ + + def __init__(self, port: str | None = None, *, timeout_s: float = 10.0, + backend: ControllerBackend | None = None): + if backend is None: + if port is None: + raise ValueError("Either port or backend is required.") + backend = _core.core().Controller(port) + self._backend = backend + self._lock = threading.Lock() + self._closed = False + self.port = port + if not self._backend.wait_for_ready(int(timeout_s * 1000)): + raise RuntimeError(f"Controller on {port} is not ready: {self._backend.current_status()}") + + # ---- status ------------------------------------------------------------- + + @property + def backend(self) -> ControllerBackend: + """The wrapped `_pa_core.Controller` (or `fake.FakeController`).""" + return self._backend + + def is_ready(self) -> bool: + self._require_open() + return self._backend.is_ready() + + def status(self) -> str: + """The connection status text: device name and firmware version, or the + error message if the connection failed.""" + self._require_open() + return self._backend.current_status() + + def name(self) -> str: + """Name of the active controller implementation, e.g. "Nintendo Switch: Pro Controller".""" + self._require_open() + return self._backend.controller_name() + + # ---- commands ------------------------------------------------------------- + + def press(self, buttons: btn.ButtonsArg, hold_ms: int = DEFAULT_HOLD_MS, + release_ms: int = DEFAULT_RELEASE_MS, repeat: int = 1) -> None: + """Tap a button combination (and/or one d-pad direction) `repeat` times. + + `buttons`: "A", "L+R", ["ZL", "up"], ... (see `pokemon_automation.buttons`). + """ + if repeat < 1: + raise ValueError(f"repeat must be at least 1, got {repeat}.") + _check_nonnegative(hold_ms=hold_ms, release_ms=release_ms) + self._require_open() + parsed = btn.parse_buttons(buttons) + if not parsed.has_buttons and not parsed.has_dpad: + raise ValueError("press() needs at least one button or d-pad direction.") + b = self._backend + delay = hold_ms + release_ms + with self._lock: + for _ in range(repeat): + if parsed.has_buttons and not parsed.has_dpad: + b.push_button(delay, hold_ms, release_ms, parsed.bitfield) + elif parsed.has_dpad and not parsed.has_buttons: + b.push_dpad(delay, hold_ms, release_ms, parsed.dpad) + else: + # Buttons and d-pad held together: one full state, then release. + b.controller_state(hold_ms, parsed.bitfield, parsed.dpad, 0.0, 0.0, 0.0, 0.0) + b.wait(release_ms) + + def hold(self, buttons: btn.ButtonsArg = None, duration_ms: int = 500, *, + left: btn.StickArg = None, right: btn.StickArg = None) -> None: + """Hold any combination of buttons, d-pad and sticks for `duration_ms`. + + Everything not specified is released for the whole hold. + """ + _check_nonnegative(duration_ms=duration_ms) + self._require_open() + parsed = btn.parse_buttons(buttons) + left_x, left_y = btn.parse_stick(left) if left is not None else (0.0, 0.0) + right_x, right_y = btn.parse_stick(right) if right is not None else (0.0, 0.0) + with self._lock: + self._backend.controller_state( + duration_ms, parsed.bitfield, parsed.dpad, + left_x, left_y, right_x, right_y + ) + + def stick(self, side: str, position: btn.StickArg, duration_ms: int = 500, + release_ms: int = 0) -> None: + """Tilt the "left" or "right" stick to `position` for `duration_ms`.""" + _check_nonnegative(duration_ms=duration_ms, release_ms=release_ms) + if side not in ("left", "right"): + raise ValueError('side must be "left" or "right", got ' + repr(side)) + self._require_open() + x, y = btn.parse_stick(position) + with self._lock: + if side == "left": + self._backend.push_left_joystick(duration_ms + release_ms, duration_ms, release_ms, x, y) + else: + self._backend.push_right_joystick(duration_ms + release_ms, duration_ms, release_ms, x, y) + + def wait(self, duration_ms: int) -> None: + """Queue a pause of `duration_ms` with nothing pressed.""" + _check_nonnegative(duration_ms=duration_ms) + self._require_open() + if duration_ms > 0: + self._backend.wait(duration_ms) + + def flush(self) -> None: + """Block until every queued command has executed on the device.""" + self._require_open() + self._backend.wait_for_all_requests() + + def cancel_all_commands(self) -> None: + """Drop every queued command and return the controller to the neutral state. + + Asynchronous: the device is told to cancel, but this does not wait for it + to confirm the neutral state. Thread-safe: may be called from another + thread while commands are being sent (emergency stop). + """ + self._require_open() + self._backend.cancel_all_commands() + + # ---- lifecycle ------------------------------------------------------------- + + def close(self) -> None: + """Drop the connection. Queued commands may still complete on the device; + call `cancel_all_commands()` first to stop it.""" + self._closed = True + + def __enter__(self) -> SwitchController: + return self + + def __exit__(self, *exc: object) -> None: + self.close() + + def _require_open(self) -> None: + if self._closed: + raise RuntimeError("This controller has been closed.") diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/devices.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/devices.py new file mode 100644 index 0000000000..b695bca1e3 --- /dev/null +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/devices.py @@ -0,0 +1,36 @@ +"""Discover serial ports that may be a PABotBase2 controller device.""" + +from __future__ import annotations + +import glob +import sys + +# Serial devices that are never a PABotBase2 controller. +_IGNORED_PORT_WORDS = ("bluetooth", "debug-console", "wlan", "headphones", "airpods") + + +def list_serial_ports() -> list[str]: + """Return candidate serial ports for the controller device, most likely first. + + Uses pyserial if it is installed (`pip install pyserial`); otherwise scans + /dev (macOS and Linux) or enumerates COM ports by name (Windows). On macOS + only the "cu." (call-out) nodes are listed, which are the ones to open; the + matching "tty." nodes block on open. + """ + ports: list[str] = [] + try: + from serial.tools import list_ports # type: ignore[import-not-found] + ports = [p.device for p in list_ports.comports()] + except ImportError: + if sys.platform == "darwin": + ports = glob.glob("/dev/cu.*") + elif sys.platform.startswith("linux"): + ports = glob.glob("/dev/ttyUSB*") + glob.glob("/dev/ttyACM*") + glob.glob("/dev/ttyS[0-9]*") + else: + ports = [f"COM{i}" for i in range(1, 64)] + if sys.platform == "darwin": + ports = [p for p in ports if not p.startswith("/dev/tty.")] + ports = [p for p in ports if not any(w in p.lower() for w in _IGNORED_PORT_WORDS)] + # USB-serial adapters first. + ports.sort(key=lambda p: (not any(w in p.lower() for w in ("usb", "uart", "acm", "com")), p)) + return ports diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/fake.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/fake.py new file mode 100644 index 0000000000..8d5982ffb1 --- /dev/null +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/fake.py @@ -0,0 +1,86 @@ +"""A fake controller for testing without hardware. + +`FakeController` implements the same interface as `_pa_core.Controller` and +records every command it receives, so `SwitchController` and friends can be +exercised in unit tests. It needs no compiled module. +""" + +from __future__ import annotations + +import threading +from typing import Any + + +class FakeController: + """Records every command it receives. `log` holds (name, args) tuples, oldest first.""" + + def __init__(self, port_name: str = "fake", ready: bool = True): + self.port_name = port_name + self.ready = ready + self.log: list[tuple[str, tuple[Any, ...]]] = [] + self.cancel_count = 0 + self._lock = threading.Lock() + + # -- _pa_core.Controller interface -------------------------------------- + + def wait_for_ready(self, timeout_ms: int = 10000) -> bool: + return self.ready + + def is_ready(self) -> bool: + return self.ready + + def current_status(self) -> str: + return "Fake controller (no hardware)" + + def controller_name(self) -> str: + return "Fake Controller" + + def wait_for_all_requests(self) -> None: + pass + + def cancel_all_commands(self) -> None: + with self._lock: + self.cancel_count += 1 + + def _record(self, name: str, *args: Any) -> None: + with self._lock: + self.log.append((name, args)) + + def wait(self, duration_ms: int) -> None: + self._record("wait", duration_ms) + + def push_button(self, delay_ms: int, hold_ms: int, release_ms: int, bitfield: int) -> None: + self._record("push_button", delay_ms, hold_ms, release_ms, bitfield) + + def push_dpad(self, delay_ms: int, hold_ms: int, release_ms: int, position: int) -> None: + self._record("push_dpad", delay_ms, hold_ms, release_ms, position) + + def push_left_joystick(self, delay_ms: int, hold_ms: int, release_ms: int, x: float, y: float) -> None: + self._record("push_left_joystick", delay_ms, hold_ms, release_ms, x, y) + + def push_right_joystick(self, delay_ms: int, hold_ms: int, release_ms: int, x: float, y: float) -> None: + self._record("push_right_joystick", delay_ms, hold_ms, release_ms, x, y) + + def controller_state( + self, + duration_ms: int, + buttons: int, + dpad: int, + left_x: float, + left_y: float, + right_x: float, + right_y: float, + ) -> None: + self._record("controller_state", duration_ms, buttons, dpad, left_x, left_y, right_x, right_y) + + # -- test helpers --------------------------------------------------------- + + def commands(self) -> list[str]: + """Names of recorded commands, excluding waits.""" + with self._lock: + return [name for name, _ in self.log if name != "wait"] + + def arguments(self, name: str) -> list[tuple[Any, ...]]: + """Recorded argument tuples of every command called `name`.""" + with self._lock: + return [args for n, args in self.log if n == name] diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/selftest.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/selftest.py new file mode 100644 index 0000000000..e07f4f0e4f --- /dev/null +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/selftest.py @@ -0,0 +1,61 @@ +"""Hardware self-test: connect to a PABotBase2 and send a few simple commands. + + python -m pokemon_automation.selftest [port] + +If `port` is omitted, every port from `list_serial_ports()` is tried in turn. +The test connects, prints the device status, presses HOME and a d-pad step, +waits for the device to confirm, and cancels. It only presses HOME and the d-pad. +""" + +from __future__ import annotations + +import argparse +import sys + +from . import _core, devices +from .controller import SwitchController + + +def try_port(port: str) -> bool: + try: + with SwitchController(port, timeout_s=5.0) as sw: + print(f"Connected to {port}") + print(f" status: {sw.status()}") + print(f" name: {sw.name() or '(unknown)'}") + sw.press("HOME") + sw.press("right", hold_ms=100) + sw.wait(500) + sw.flush() + sw.cancel_all_commands() + print("Self-test OK.") + return True + except Exception as e: # noqa: BLE001 - a self-test reports, it does not crash + print(f" {port}: {e}") + return False + + +def main(argv: list[str] | None = None) -> int: + p = argparse.ArgumentParser(prog="python -m pokemon_automation.selftest", description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + p.add_argument("port", nargs="?", help="Controller serial port. Omit to try every candidate port.") + args = p.parse_args(argv) + + if not _core.core_available(): + print(_core.BUILD_HINT, file=sys.stderr) + return 2 + + ports = [args.port] if args.port else devices.list_serial_ports() + if not ports: + print("No candidate serial ports found; pass one as an argument.") + return 1 + + print(f"Candidate ports: {ports}") + for port in ports: + if try_port(port): + return 0 + print("Could not connect to any port.") + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/SerialPrograms/Source/PythonBindings/pyproject.toml b/SerialPrograms/Source/PythonBindings/pyproject.toml new file mode 100644 index 0000000000..116d69bf5f --- /dev/null +++ b/SerialPrograms/Source/PythonBindings/pyproject.toml @@ -0,0 +1,29 @@ +[build-system] +requires = ["setuptools>=68"] +build-backend = "setuptools.build_meta" + +# The compiled `_pa_core` module (acts as a Switch controller) is built by CMake +# (see README.md) and copied into pokemon_automation/. This file packages the +# Python side for `pip install -e .` from this directory. + +[project] +name = "pokemon-automation" +version = "0.1.0" +description = "Send Nintendo Switch controller input from Python with Pokemon Automation hardware." +readme = "README.md" +requires-python = ">=3.10" +dependencies = [] + +[project.optional-dependencies] +# Better serial port discovery on every platform. +serial = ["pyserial>=3.5"] +test = ["pytest>=7"] + +[tool.setuptools] +packages = ["pokemon_automation"] + +[tool.setuptools.package-data] +pokemon_automation = ["_pa_core*.so", "_pa_core*.pyd"] + +[tool.pytest.ini_options] +testpaths = ["tests"] diff --git a/SerialPrograms/Source/PythonBindings/tests/test_buttons.py b/SerialPrograms/Source/PythonBindings/tests/test_buttons.py new file mode 100644 index 0000000000..b14924f646 --- /dev/null +++ b/SerialPrograms/Source/PythonBindings/tests/test_buttons.py @@ -0,0 +1,56 @@ +import math + +import pytest + +from pokemon_automation import buttons as btn + + +def test_single_and_combined_buttons(): + assert btn.parse_buttons("A").bitfield == btn.BUTTON_BITS["A"] + both = btn.parse_buttons("L+R") + assert both.bitfield == btn.BUTTON_BITS["L"] | btn.BUTTON_BITS["R"] + assert not both.has_dpad + assert btn.parse_buttons(["zl", "a"]).bitfield == btn.BUTTON_BITS["ZL"] | btn.BUTTON_BITS["A"] + + +def test_aliases_and_plus_minus(): + assert btn.parse_buttons("+").bitfield == btn.BUTTON_BITS["PLUS"] + assert btn.parse_buttons("-").bitfield == btn.BUTTON_BITS["MINUS"] + assert btn.parse_buttons("start").bitfield == btn.BUTTON_BITS["PLUS"] + assert btn.parse_buttons("L3").bitfield == btn.BUTTON_BITS["LCLICK"] + assert btn.parse_buttons(["A", "+"]).bitfield == btn.BUTTON_BITS["A"] | btn.BUTTON_BITS["PLUS"] + + +def test_dpad(): + assert btn.parse_buttons("up").dpad == btn.DPAD_POSITIONS["UP"] + assert btn.parse_buttons("up+right").dpad == btn.DPAD_POSITIONS["UP_RIGHT"] + assert btn.parse_buttons("down-left").dpad == btn.DPAD_POSITIONS["DOWN_LEFT"] + assert btn.parse_buttons("UPLEFT").dpad == btn.DPAD_POSITIONS["UP_LEFT"] + mixed = btn.parse_buttons("ZL+DOWN") + assert mixed.bitfield == btn.BUTTON_BITS["ZL"] and mixed.dpad == btn.DPAD_POSITIONS["DOWN"] + assert btn.parse_buttons(None).dpad == btn.DPAD_NONE + + +def test_invalid_buttons(): + with pytest.raises(ValueError, match="Unknown button"): + btn.parse_buttons("Q") + with pytest.raises(ValueError, match="Contradictory"): + btn.parse_buttons("up+down") + assert not btn.parse_buttons(None).has_buttons + + +def test_sticks(): + assert btn.parse_stick("up") == (0.0, 1.0) + assert btn.parse_stick("neutral") == (0.0, 0.0) + x, y = btn.parse_stick("down_right") + assert math.isclose(math.hypot(x, y), 1.0) and x > 0 and y < 0 + assert btn.parse_stick([0.5, -0.25]) == (0.5, -0.25) + with pytest.raises(ValueError): + btn.parse_stick([2, 0]) + with pytest.raises(ValueError): + btn.parse_stick("sideways") + + +def test_matches_cpp_enum(): + core = pytest.importorskip("pokemon_automation._pa_core") + btn.check_against_core(dict(core.BUTTONS), dict(core.DPAD_POSITIONS)) diff --git a/SerialPrograms/Source/PythonBindings/tests/test_controller.py b/SerialPrograms/Source/PythonBindings/tests/test_controller.py new file mode 100644 index 0000000000..be49708475 --- /dev/null +++ b/SerialPrograms/Source/PythonBindings/tests/test_controller.py @@ -0,0 +1,133 @@ +import pytest + +from pokemon_automation import BUTTON_BITS, DPAD_NONE, DPAD_POSITIONS, FakeController, SwitchController + + +def make(): + fake = FakeController() + sw = SwitchController(backend=fake) + return sw, fake + + +def test_requires_port_or_backend(): + with pytest.raises(ValueError): + SwitchController() + + +def test_not_ready_raises(): + fake = FakeController(ready=False) + with pytest.raises(RuntimeError, match="not ready"): + SwitchController(backend=fake, timeout_s=0.1) + + +def test_press_single_button(): + sw, fake = make() + sw.press("A") + assert fake.commands() == ["push_button"] + (delay, hold, release, bitfield), = fake.arguments("push_button") + assert bitfield == BUTTON_BITS["A"] + assert delay == hold + release and hold == 80 and release == 80 + + +def test_press_combined_and_custom_durations(): + sw, fake = make() + sw.press("L+R", hold_ms=200, release_ms=50) + (delay, hold, release, bitfield), = fake.arguments("push_button") + assert bitfield == BUTTON_BITS["L"] | BUTTON_BITS["R"] + assert (delay, hold, release) == (250, 200, 50) + + +def test_press_repeat_dpad(): + sw, fake = make() + sw.press("up", repeat=3, hold_ms=100) + args = fake.arguments("push_dpad") + assert len(args) == 3 + for delay, hold, release, position in args: + assert position == DPAD_POSITIONS["UP"] and hold == 100 + + +def test_press_mixed_uses_controller_state(): + sw, fake = make() + sw.press("ZL+up", hold_ms=60, release_ms=30) + assert fake.commands() == ["controller_state"] + (duration, buttons, dpad, left_x, left_y, right_x, right_y), = fake.arguments("controller_state") + assert duration == 60 + assert buttons == BUTTON_BITS["ZL"] + assert dpad == DPAD_POSITIONS["UP"] + assert (left_x, left_y, right_x, right_y) == (0.0, 0.0, 0.0, 0.0) + assert fake.arguments("wait") == [(30,)] + + +def test_press_needs_something(): + sw, fake = make() + with pytest.raises(ValueError): + sw.press(None) + assert fake.commands() == [] + + +def test_stick(): + sw, fake = make() + sw.stick("left", "up", duration_ms=1500) + (delay, hold, release, x, y), = fake.arguments("push_left_joystick") + assert (x, y) == (0.0, 1.0) and hold == 1500 and delay == 1500 + release + sw.stick("right", [0.5, -0.5], duration_ms=300, release_ms=100) + (delay, hold, release, x, y), = fake.arguments("push_right_joystick") + assert (x, y) == (0.5, -0.5) and delay == 400 + with pytest.raises(ValueError): + sw.stick("middle", "up") + + +def test_hold_combination(): + sw, fake = make() + sw.hold("B", left="up", right=[1.0, 0.0], duration_ms=2000) + (duration, buttons, dpad, left_x, left_y, right_x, right_y), = fake.arguments("controller_state") + assert duration == 2000 + assert buttons == BUTTON_BITS["B"] + assert dpad == DPAD_NONE + assert (left_x, left_y) == (0.0, 1.0) + assert (right_x, right_y) == (1.0, 0.0) + + +def test_wait(): + sw, fake = make() + sw.wait(1000) + assert fake.arguments("wait") == [(1000,)] + sw.wait(0) # a zero-length wait is a no-op + assert fake.arguments("wait") == [(1000,)] + + +def test_validation(): + sw, fake = make() + with pytest.raises(ValueError): + sw.press("A", hold_ms=-1) + with pytest.raises(ValueError): + sw.press("A", repeat=0) + with pytest.raises(ValueError): + sw.press("Q") + with pytest.raises(ValueError): + sw.press("up+down") + assert fake.commands() == [] + + +def test_flush_and_cancel(): + sw, fake = make() + sw.flush() + sw.cancel_all_commands() + assert fake.cancel_count == 1 + + +def test_close(): + sw, fake = make() + sw.close() + with pytest.raises(RuntimeError, match="closed"): + sw.press("A") + with pytest.raises(RuntimeError, match="closed"): + sw.flush() + + +def test_context_manager(): + fake = FakeController() + with SwitchController(backend=fake) as sw: + sw.press("A") + with pytest.raises(RuntimeError, match="closed"): + sw.press("A") diff --git a/SerialPrograms/Source/PythonBindings/tests/test_core.py b/SerialPrograms/Source/PythonBindings/tests/test_core.py new file mode 100644 index 0000000000..053a7b17a7 --- /dev/null +++ b/SerialPrograms/Source/PythonBindings/tests/test_core.py @@ -0,0 +1,60 @@ +# Tests for the compiled `_pa_core` module. They are skipped when the module +# has not been built (it is built with -DPA_PYTHON_BINDINGS=ON). +import pytest + +core = pytest.importorskip("pokemon_automation._pa_core") + + +def test_buttons_dict(): + # A sample of the C++ `NintendoSwitch::Button` enum, straight from the module. + assert core.BUTTONS["A"] == 1 << 2 + assert core.BUTTONS["PLUS"] == 1 << 9 + assert core.BUTTONS["HOME"] == 1 << 12 + # Third-party controller and d-pad bits exist too. + for name in ("GR", "GL", "C", "UP", "LEFT"): + assert name in core.BUTTONS + + +def test_dpad_positions_dict(): + assert core.DPAD_POSITIONS == { + "UP": 0, "UP_RIGHT": 1, "RIGHT": 2, "DOWN_RIGHT": 3, + "DOWN": 4, "DOWN_LEFT": 5, "LEFT": 6, "UP_LEFT": 7, "NONE": 8, + } + + +def test_python_constants_match_cpp(): + from pokemon_automation import buttons as btn + btn.check_against_core(dict(core.BUTTONS), dict(core.DPAD_POSITIONS)) + + +def test_log_functions(): + core.log("hello from python") + assert any("hello from python" in line for line in core.recent_logs(10)) + with pytest.raises(RuntimeError): + core.set_log_file("/nonexistent directory/pa_core.log") + core.set_log_file("") + + +def test_log_file(tmp_path): + log_file = tmp_path / "pa_core.log" + core.set_log_file(str(log_file)) + try: + core.log("line in file") + finally: + core.set_log_file("") + text = log_file.read_text() + assert "line in file" in text + + +def test_unreachable_port(): + c = core.Controller("nonexistent-port-xyz") + assert not c.wait_for_ready(500) + assert not c.is_ready() + assert c.current_status() # an error message, not empty + assert c.controller_name() == "" + # Commands on a not-ready controller raise RuntimeError, they do not crash. + with pytest.raises(RuntimeError): + c.push_button(0, 10, 10, core.BUTTONS["A"]) + # These are safe no-ops when not ready. + c.wait_for_all_requests() + c.cancel_all_commands() From 871232d742dedadda551e465494e5d714e1877e2 Mon Sep 17 00:00:00 2001 From: PA Dev Bot <344001113+pa-devbot@users.noreply.github.com> Date: Sun, 18 Oct 2026 18:02:17 +0000 Subject: [PATCH 02/58] Python: stop committing pip egg-info leftovers --- .../Source/PythonBindings/.gitignore | 1 + .../pokemon_automation.egg-info/PKG-INFO | 102 ------------------ .../pokemon_automation.egg-info/SOURCES.txt | 18 ---- .../dependency_links.txt | 1 - .../pokemon_automation.egg-info/requires.txt | 6 -- .../pokemon_automation.egg-info/top_level.txt | 1 - 6 files changed, 1 insertion(+), 128 deletions(-) delete mode 100644 SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/PKG-INFO delete mode 100644 SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/SOURCES.txt delete mode 100644 SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/dependency_links.txt delete mode 100644 SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/requires.txt delete mode 100644 SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/top_level.txt diff --git a/SerialPrograms/Source/PythonBindings/.gitignore b/SerialPrograms/Source/PythonBindings/.gitignore index 2def3a1d08..40d42af36c 100644 --- a/SerialPrograms/Source/PythonBindings/.gitignore +++ b/SerialPrograms/Source/PythonBindings/.gitignore @@ -5,4 +5,5 @@ pokemon_automation/_pa_core*.pyd # Python __pycache__/ *.pyc +*.egg-info/ .pytest_cache/ diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/PKG-INFO b/SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/PKG-INFO deleted file mode 100644 index f5f93fde62..0000000000 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/PKG-INFO +++ /dev/null @@ -1,102 +0,0 @@ -Metadata-Version: 2.4 -Name: pokemon-automation -Version: 0.1.0 -Summary: Send Nintendo Switch controller input from Python with Pokemon Automation hardware. -Requires-Python: >=3.10 -Description-Content-Type: text/markdown -Provides-Extra: serial -Requires-Dist: pyserial>=3.5; extra == "serial" -Provides-Extra: test -Requires-Dist: pytest>=7; extra == "test" - -# Python Bindings - -A basic Python interface for the microcontroller, built with [pybind11](https://github.com/pybind/pybind11). -It lets Python act as a Nintendo Switch controller through a PABotBase2 serial -device, using the `NintendoSwitch::PybindSwitchProController` class from CoreLib -(`Source/Integrations/PybindSwitchController.h`). - -## Layout - -- `PythonBindings_Module.cpp` — the `_pa_core` pybind11 module: a thin 1:1 - binding of `PybindSwitchProController` plus logging controls and the - `BUTTONS` / `DPAD_POSITIONS` constants. -- `PythonBindings.cmake` — builds the module (linked against CoreLib only: no - Qt, OpenCV, ONNX Runtime or Tesseract). -- `pokemon_automation/` — the Python package on top of it: - - `controller.py` — `SwitchController`: the user-facing API, with button names - instead of bitfields (`press("L+R")`, `stick("left", "up")`, ...). - - `buttons.py` — parsing of button / d-pad / stick names into bitfields. - - `fake.py` — `FakeController`: the same backend interface without hardware, - for unit tests. - - `devices.py` — `list_serial_ports()`. - - `selftest.py` — `python -m pokemon_automation.selftest [port]`: connect to - a real device and send a few commands. -- `tests/` — pytest suite (pure-Python parts always run; compiled-module tests - skip when `_pa_core` is not built). - -## Building the module - -Requires a Python 3.10+ with development headers and pybind11 (a system package -or `pip install pybind11`). If neither is found, CMake downloads a pinned -pybind11 release. - -```sh -cd SerialPrograms -mkdir bin && cd bin -cmake .. -DPA_PYTHON_BINDINGS=ON [-DPA_CORE_ONLY=ON] [-DPython_EXECUTABLE=$(which python3)] -cmake --build . --target _pa_core -``` - -`-DPA_CORE_ONLY=ON` builds only the GUI-free core (CoreLib, -SerialProgramsCommandLine and the module) — the fast path; without it the -module is built alongside the full GUI program. - -After the build, `_pa_core` is copied into `pokemon_automation/`, so the -package works straight from the source tree. To install it for a project: - -```sh -pip install -e SerialPrograms/Source/PythonBindings -``` - -## Usage - -```python -from pokemon_automation import SwitchController, list_serial_ports - -print(list_serial_ports()) -with SwitchController("/dev/ttyACM0") as sw: - print(sw.status()) # device name and firmware version - sw.press("A") # tap A (80 ms hold, 80 ms release) - sw.press("L+R", hold_ms=200) # press L and R together - sw.press("up", repeat=2) # d-pad up twice - sw.stick("left", "up", duration_ms=1500) # walk forward - sw.hold("B", left="up", duration_ms=2000) # run forward - sw.wait(300) - sw.flush() # block until the device executed everything -``` - -Commands are queued on the microcontroller and return as soon as they are -scheduled, mirroring the `pbf_*()` functions of the main program. Call -`flush()` to wait for execution, and `cancel_all_commands()` (thread-safe) to -drop the queue and release all inputs — e.g. from an emergency-stop thread. - -Run the tests: - -```sh -cd SerialPrograms/Source/PythonBindings -python -m pytest -``` - -## Notes - -- All durations are milliseconds. -- C++ `PokemonAutomation::Exception`s surface as Python `RuntimeError`s. -- Internal log lines (the "Pybind"-tagged connection logs) are not written to - stdout. `_pa_core.set_log_stderr(True/False)` and - `_pa_core.set_log_file(path)` route them to stderr and/or a file, and - `_pa_core.recent_logs(50)` returns the most recent lines. -- The device must be configured as a Pro Controller (or a wired controller) - with the main program; the device remembers the setting. -- PR #1519 ("Agent mcp server", draft) extends this interface with a full - `pokemon_automation` package (MCP server, video, OCR). diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/SOURCES.txt b/SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/SOURCES.txt deleted file mode 100644 index f8378c1acd..0000000000 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/SOURCES.txt +++ /dev/null @@ -1,18 +0,0 @@ -README.md -pyproject.toml -pokemon_automation/__init__.py -pokemon_automation/_core.py -pokemon_automation/_pa_core.cpython-314-aarch64-linux-gnu.so -pokemon_automation/buttons.py -pokemon_automation/controller.py -pokemon_automation/devices.py -pokemon_automation/fake.py -pokemon_automation/selftest.py -pokemon_automation.egg-info/PKG-INFO -pokemon_automation.egg-info/SOURCES.txt -pokemon_automation.egg-info/dependency_links.txt -pokemon_automation.egg-info/requires.txt -pokemon_automation.egg-info/top_level.txt -tests/test_buttons.py -tests/test_controller.py -tests/test_core.py \ No newline at end of file diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/dependency_links.txt b/SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/dependency_links.txt deleted file mode 100644 index 8b13789179..0000000000 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/dependency_links.txt +++ /dev/null @@ -1 +0,0 @@ - diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/requires.txt b/SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/requires.txt deleted file mode 100644 index 838faf46e4..0000000000 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/requires.txt +++ /dev/null @@ -1,6 +0,0 @@ - -[serial] -pyserial>=3.5 - -[test] -pytest>=7 diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/top_level.txt b/SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/top_level.txt deleted file mode 100644 index a49f7f3514..0000000000 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation.egg-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -pokemon_automation From 0f9c150330bbae5d6e46b228e706e821a22c41f0 Mon Sep 17 00:00:00 2001 From: PA Dev Bot <344001113+pa-devbot@users.noreply.github.com> Date: Mon, 19 Oct 2026 06:09:12 +0000 Subject: [PATCH 03/58] Python: switch to cancel_all_and_wait(); stop miniz.c warnings breaking CoreLib The rebased branch picked up AbstractController::cancel_all_and_wait() (cancel + wait for the device to acknowledge the neutral state, returns a bool), which replaced the old fire-and-forget cancel_all_commands(). Update the _pa_core binding, the pokemon_automation API (cancel_all_and_wait() now returns whether the device confirmed; close() uses it to guarantee a neutral state), the fake controller, the tests, and the docs. Also compile the third-party 3rdParty-Core/miniz-3.1.1/miniz.c with warnings off (/W0 on MSVC, -w on GCC/Clang): it is compiled straight into CoreLib, and newer compilers emit warnings in it that -Werror / /WX turn into build errors. It includes miniz.h from its own directory, so a SYSTEM include directory cannot shield it; suppressing the file itself is the portable fix. --- .../PythonBindings/PythonBindings_Module.cpp | 13 +++++--- .../Source/PythonBindings/README.md | 6 ++-- .../pokemon_automation/controller.py | 30 ++++++++++++------- .../PythonBindings/pokemon_automation/fake.py | 7 ++++- .../pokemon_automation/selftest.py | 5 ++-- .../PythonBindings/tests/test_controller.py | 8 ++++- .../Source/PythonBindings/tests/test_core.py | 2 +- SerialPrograms/cmake/CoreLib.cmake | 14 +++++++++ 8 files changed, 63 insertions(+), 22 deletions(-) diff --git a/SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp b/SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp index 956ef33ee2..7a4785720f 100644 --- a/SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp +++ b/SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp @@ -218,10 +218,15 @@ PYBIND11_MODULE(_pa_core, m){ .def("wait_for_all_requests", &PybindSwitchProController::wait_for_all_requests, "Block until every command queued so far has been executed by the device.", py::call_guard()) - .def("cancel_all_commands", &PybindSwitchProController::cancel_all_commands, - "Cancel every command that has not executed yet, clearing the device's " - "command queue and returning the controller to the neutral state. " - "Asynchronous: does not wait for the device to reach the neutral state.") + .def("cancel_all_and_wait", &PybindSwitchProController::cancel_all_and_wait, + py::arg("timeout_ms") = 500, + "Cancel every command that has not executed yet, clear the device's command " + "queue, return the controller to the neutral state (no buttons pressed, " + "sticks centered), and wait up to `timeout_ms` for the device to " + "acknowledge. Returns True if acknowledged, False on timeout or if the " + "controller is not ready. Thread-safe: may be called from another thread, " + "e.g. as an emergency stop.", + py::call_guard()) .def("wait", &PybindSwitchProController::wait, py::arg("duration_ms"), "Queue a pause of `duration_ms` with nothing pressed.", diff --git a/SerialPrograms/Source/PythonBindings/README.md b/SerialPrograms/Source/PythonBindings/README.md index ffb8029fb1..d0609235bb 100644 --- a/SerialPrograms/Source/PythonBindings/README.md +++ b/SerialPrograms/Source/PythonBindings/README.md @@ -67,8 +67,10 @@ with SwitchController("/dev/ttyACM0") as sw: Commands are queued on the microcontroller and return as soon as they are scheduled, mirroring the `pbf_*()` functions of the main program. Call -`flush()` to wait for execution, and `cancel_all_commands()` (thread-safe) to -drop the queue and release all inputs — e.g. from an emergency-stop thread. +`flush()` to wait for execution, and `cancel_all_and_wait()` (thread-safe) to +drop the queue, release all inputs and wait for the device to confirm the +neutral state — e.g. from an emergency-stop thread. `close()` does this for +you before dropping the connection. Run the tests: diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py index 935b0b4924..c9157fe4ff 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py @@ -2,8 +2,9 @@ Commands are queued on the microcontroller and return immediately, like the `pbf_*()` functions in the main C++ program. Call `flush()` to wait until -everything queued so far has executed, and `cancel_all_commands()` to drop -anything still queued and release all inputs. +everything queued so far has executed, and `cancel_all_and_wait()` to drop +anything still queued and release all inputs (waiting for the device to confirm +the neutral state). Example: from pokemon_automation import SwitchController @@ -36,7 +37,7 @@ def is_ready(self) -> bool: ... def current_status(self) -> str: ... def controller_name(self) -> str: ... def wait_for_all_requests(self) -> None: ... - def cancel_all_commands(self) -> None: ... + def cancel_all_and_wait(self, timeout_ms: int = ...) -> bool: ... def wait(self, duration_ms: int) -> None: ... def push_button(self, delay_ms: int, hold_ms: int, release_ms: int, bitfield: int) -> None: ... def push_dpad(self, delay_ms: int, hold_ms: int, release_ms: int, position: int) -> None: ... @@ -172,22 +173,29 @@ def flush(self) -> None: self._require_open() self._backend.wait_for_all_requests() - def cancel_all_commands(self) -> None: - """Drop every queued command and return the controller to the neutral state. + def cancel_all_and_wait(self, timeout_ms: int = 500) -> bool: + """Cancel every queued command and return the controller to the neutral state. - Asynchronous: the device is told to cancel, but this does not wait for it - to confirm the neutral state. Thread-safe: may be called from another - thread while commands are being sent (emergency stop). + Waits up to `timeout_ms` for the device to acknowledge the cancel. Returns + True if acknowledged, False on timeout (or if the controller is not ready). + Thread-safe: may be called from another thread while commands are being sent + (emergency stop). """ self._require_open() - self._backend.cancel_all_commands() + return self._backend.cancel_all_and_wait(int(timeout_ms)) # ---- lifecycle ------------------------------------------------------------- def close(self) -> None: - """Drop the connection. Queued commands may still complete on the device; - call `cancel_all_commands()` first to stop it.""" + """Stop the device (cancelling queued commands and waiting briefly for the + neutral state) and drop the connection.""" + if self._closed: + return self._closed = True + try: + self._backend.cancel_all_and_wait(500) + except Exception: # noqa: BLE001 - best effort: the connection is dropped anyway + pass def __enter__(self) -> SwitchController: return self diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/fake.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/fake.py index 8d5982ffb1..9a99b46dfb 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/fake.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/fake.py @@ -19,6 +19,8 @@ def __init__(self, port_name: str = "fake", ready: bool = True): self.ready = ready self.log: list[tuple[str, tuple[Any, ...]]] = [] self.cancel_count = 0 + # Tests can set this to False to simulate a device that does not acknowledge in time. + self.confirm_cancel = True self._lock = threading.Lock() # -- _pa_core.Controller interface -------------------------------------- @@ -38,9 +40,12 @@ def controller_name(self) -> str: def wait_for_all_requests(self) -> None: pass - def cancel_all_commands(self) -> None: + def cancel_all_and_wait(self, timeout_ms: int = 500) -> bool: + """Counts the call in `cancel_count`. Returns `confirm_cancel`, which tests can + set to False to simulate a device that does not acknowledge in time.""" with self._lock: self.cancel_count += 1 + return self.confirm_cancel def _record(self, name: str, *args: Any) -> None: with self._lock: diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/selftest.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/selftest.py index e07f4f0e4f..b55339896f 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/selftest.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/selftest.py @@ -4,7 +4,8 @@ If `port` is omitted, every port from `list_serial_ports()` is tried in turn. The test connects, prints the device status, presses HOME and a d-pad step, -waits for the device to confirm, and cancels. It only presses HOME and the d-pad. +waits for the device to confirm, and cancels with confirmation. It only +presses HOME and the d-pad. """ from __future__ import annotations @@ -26,7 +27,7 @@ def try_port(port: str) -> bool: sw.press("right", hold_ms=100) sw.wait(500) sw.flush() - sw.cancel_all_commands() + print(" cancel confirmed:", sw.cancel_all_and_wait(500)) print("Self-test OK.") return True except Exception as e: # noqa: BLE001 - a self-test reports, it does not crash diff --git a/SerialPrograms/Source/PythonBindings/tests/test_controller.py b/SerialPrograms/Source/PythonBindings/tests/test_controller.py index be49708475..cd3fda1da8 100644 --- a/SerialPrograms/Source/PythonBindings/tests/test_controller.py +++ b/SerialPrograms/Source/PythonBindings/tests/test_controller.py @@ -112,17 +112,23 @@ def test_validation(): def test_flush_and_cancel(): sw, fake = make() sw.flush() - sw.cancel_all_commands() + assert sw.cancel_all_and_wait() is True assert fake.cancel_count == 1 + fake.confirm_cancel = False + assert sw.cancel_all_and_wait() is False + assert fake.cancel_count == 2 def test_close(): sw, fake = make() sw.close() + assert fake.cancel_count == 1 # close() stops the device first with pytest.raises(RuntimeError, match="closed"): sw.press("A") with pytest.raises(RuntimeError, match="closed"): sw.flush() + sw.close() # idempotent + assert fake.cancel_count == 1 def test_context_manager(): diff --git a/SerialPrograms/Source/PythonBindings/tests/test_core.py b/SerialPrograms/Source/PythonBindings/tests/test_core.py index 053a7b17a7..451d4bbd02 100644 --- a/SerialPrograms/Source/PythonBindings/tests/test_core.py +++ b/SerialPrograms/Source/PythonBindings/tests/test_core.py @@ -57,4 +57,4 @@ def test_unreachable_port(): c.push_button(0, 10, 10, core.BUTTONS["A"]) # These are safe no-ops when not ready. c.wait_for_all_requests() - c.cancel_all_commands() + assert c.cancel_all_and_wait(100) is False diff --git a/SerialPrograms/cmake/CoreLib.cmake b/SerialPrograms/cmake/CoreLib.cmake index e076d91edb..5f48624f83 100644 --- a/SerialPrograms/cmake/CoreLib.cmake +++ b/SerialPrograms/cmake/CoreLib.cmake @@ -91,3 +91,17 @@ else() # macOS and Linux target_compile_options(CoreLib PRIVATE -march=nehalem) endif() endif() + +# miniz is a third-party library: compile it with warnings off so that its own +# code (and its header, which it includes from its own directory, so no SYSTEM +# include directory can shield it) can never trip -Werror / /WX, regardless of +# which compiler or compiler version is used. +if (WIN32) + set(MINIZ_WARNING_FLAGS "/W0") +else() + set(MINIZ_WARNING_FLAGS "-w") +endif() +set_source_files_properties( + ../3rdParty-Core/miniz-3.1.1/miniz.c + PROPERTIES COMPILE_OPTIONS "${MINIZ_WARNING_FLAGS}" +) From d34e550106cf949a6caa6fd7d015a837903cdb10 Mon Sep 17 00:00:00 2001 From: PA Dev Bot <344001113+pa-devbot@users.noreply.github.com> Date: Mon, 19 Oct 2026 06:33:39 +0000 Subject: [PATCH 04/58] Move the miniz.c warning suppression into pa_apply_base_target_properties() The old copy in CMakeLists.txt only runs in the full build: with PA_CORE_ONLY the configure returns before reaching it, so miniz.c was still compiled with -Werror / /WX in core-only builds. Setting the source property from pa_apply_base_target_properties() (cmake/CoreLib.cmake) covers both build modes and every target that uses it; the two now-redundant copies are removed. Use if(MSVC) instead of if(WIN32) - the flag choice follows the compiler's command-line dialect (true for cl and for clang-cl), and COMPILE_OPTIONS instead of the deprecated COMPILE_FLAGS. --- SerialPrograms/CMakeLists.txt | 7 ------- SerialPrograms/cmake/CoreLib.cmake | 31 ++++++++++++++++-------------- 2 files changed, 17 insertions(+), 21 deletions(-) diff --git a/SerialPrograms/CMakeLists.txt b/SerialPrograms/CMakeLists.txt index 95954a2256..65cb95b181 100644 --- a/SerialPrograms/CMakeLists.txt +++ b/SerialPrograms/CMakeLists.txt @@ -291,13 +291,6 @@ endfunction() apply_common_target_properties(SerialProgramsLib) apply_common_target_properties(SerialPrograms) -if(MSVC) - set_source_files_properties("../3rdParty-Core/miniz-3.1.1/miniz.c" PROPERTIES COMPILE_FLAGS "/W0") -else() - # For GCC/Clang - set_source_files_properties("../3rdParty-Core/miniz-3.1.1/miniz.c" PROPERTIES COMPILE_FLAGS "-w") -endif() - # REPO_ROOT_DIR: the root folder of the git repository, "Arduino-Source/" set(PACKAGES_DIR "${REPO_ROOT_DIR}/Packages") set(FIRMWARE_DIR "${PACKAGES_DIR}/Firmware") diff --git a/SerialPrograms/cmake/CoreLib.cmake b/SerialPrograms/cmake/CoreLib.cmake index 5f48624f83..c58570aad9 100644 --- a/SerialPrograms/cmake/CoreLib.cmake +++ b/SerialPrograms/cmake/CoreLib.cmake @@ -42,6 +42,23 @@ function(pa_apply_base_target_properties target_name) ${PA_SERIAL_PROGRAMS_DIR}/../../Internal/ ${PA_SERIAL_PROGRAMS_DIR}/Source/ ) + + # miniz is a third-party library compiled into CoreLib: build it with + # warnings off so its own code (and its header, which it includes from its + # own directory, so no SYSTEM include directory can shield it) can never + # trip -Werror / /WX, regardless of compiler or compiler version. Source + # properties are global, so setting this once is enough for every target. + if (MSVC) + set_source_files_properties( + ../3rdParty-Core/miniz-3.1.1/miniz.c + PROPERTIES COMPILE_OPTIONS "/W0" + ) + else() + set_source_files_properties( + ../3rdParty-Core/miniz-3.1.1/miniz.c + PROPERTIES COMPILE_OPTIONS "-w" + ) + endif() endfunction() # Base properties for a target that must not depend on Qt or any other GUI library. @@ -91,17 +108,3 @@ else() # macOS and Linux target_compile_options(CoreLib PRIVATE -march=nehalem) endif() endif() - -# miniz is a third-party library: compile it with warnings off so that its own -# code (and its header, which it includes from its own directory, so no SYSTEM -# include directory can shield it) can never trip -Werror / /WX, regardless of -# which compiler or compiler version is used. -if (WIN32) - set(MINIZ_WARNING_FLAGS "/W0") -else() - set(MINIZ_WARNING_FLAGS "-w") -endif() -set_source_files_properties( - ../3rdParty-Core/miniz-3.1.1/miniz.c - PROPERTIES COMPILE_OPTIONS "${MINIZ_WARNING_FLAGS}" -) From 7b07de21cd40f0ab7da2ceca8a2cbeea41020383 Mon Sep 17 00:00:00 2001 From: PA Dev Bot <344001113+pa-devbot@users.noreply.github.com> Date: Mon, 19 Oct 2026 07:11:39 +0000 Subject: [PATCH 05/58] Put the miniz.c warning suppression in the base CMakeLists.txt, before PA_CORE_ONLY miniz.c is compiled into every target that uses CORE_LIBRARY_SOURCES - CoreLib in both build modes, and SerialProgramsLib in the full build (which compiles its own copy of the core sources), so the fix belongs in the base CMakeLists.txt, not CoreLib.cmake. It must also run before the PA_CORE_ONLY early return, which is where the old copy at the bottom of the file (from #1098) was, and why core-only builds still failed. Source properties are global, so one set_source_files_properties() covers all targets; verified that in a full build both CoreLib's and SerialProgramsLib's miniz.c compile lines carry the suppression. --- SerialPrograms/CMakeLists.txt | 19 +++++++++++++++++++ SerialPrograms/cmake/CoreLib.cmake | 17 ----------------- 2 files changed, 19 insertions(+), 17 deletions(-) diff --git a/SerialPrograms/CMakeLists.txt b/SerialPrograms/CMakeLists.txt index 65cb95b181..5cd6b77cdd 100644 --- a/SerialPrograms/CMakeLists.txt +++ b/SerialPrograms/CMakeLists.txt @@ -68,6 +68,25 @@ option(COMMAND_LINE_EXE "Build the optional executable" ON) # and pybind11 (a system package or `pip install pybind11`). option(PA_PYTHON_BINDINGS "Build the _pa_core Python module (Switch controller)" OFF) +# miniz is a third-party library compiled into every target that uses +# CORE_LIBRARY_SOURCES (CoreLib in both build modes, SerialProgramsLib in the +# full build): compile it with warnings off so its own code (and its header, +# which it includes from its own directory, so no SYSTEM include directory can +# shield it) can never trip -Werror / /WX, regardless of compiler or compiler +# version. Must run before the PA_CORE_ONLY early return below; source +# properties are global, so setting it once covers every target. +if (MSVC) + set_source_files_properties( + ../3rdParty-Core/miniz-3.1.1/miniz.c + PROPERTIES COMPILE_OPTIONS "/W0" + ) +else() + set_source_files_properties( + ../3rdParty-Core/miniz-3.1.1/miniz.c + PROPERTIES COMPILE_OPTIONS "-w" + ) +endif() + # Build only the GUI-free core: CoreLib and SerialProgramsCommandLine. This needs # no Qt, OpenCV, ONNX Runtime, Tesseract, DPP or Discord SDK, so none of them are # searched for. diff --git a/SerialPrograms/cmake/CoreLib.cmake b/SerialPrograms/cmake/CoreLib.cmake index c58570aad9..e076d91edb 100644 --- a/SerialPrograms/cmake/CoreLib.cmake +++ b/SerialPrograms/cmake/CoreLib.cmake @@ -42,23 +42,6 @@ function(pa_apply_base_target_properties target_name) ${PA_SERIAL_PROGRAMS_DIR}/../../Internal/ ${PA_SERIAL_PROGRAMS_DIR}/Source/ ) - - # miniz is a third-party library compiled into CoreLib: build it with - # warnings off so its own code (and its header, which it includes from its - # own directory, so no SYSTEM include directory can shield it) can never - # trip -Werror / /WX, regardless of compiler or compiler version. Source - # properties are global, so setting this once is enough for every target. - if (MSVC) - set_source_files_properties( - ../3rdParty-Core/miniz-3.1.1/miniz.c - PROPERTIES COMPILE_OPTIONS "/W0" - ) - else() - set_source_files_properties( - ../3rdParty-Core/miniz-3.1.1/miniz.c - PROPERTIES COMPILE_OPTIONS "-w" - ) - endif() endfunction() # Base properties for a target that must not depend on Qt or any other GUI library. From 6de7657334b1fafdcac97c30056672f4e501533a Mon Sep 17 00:00:00 2001 From: jw098 Date: Mon, 19 Oct 2026 12:20:42 -0700 Subject: [PATCH 06/58] update pybind README --- .../Source/PythonBindings/README.md | 68 +++++++++++++------ 1 file changed, 47 insertions(+), 21 deletions(-) diff --git a/SerialPrograms/Source/PythonBindings/README.md b/SerialPrograms/Source/PythonBindings/README.md index d0609235bb..f2a7aa4c31 100644 --- a/SerialPrograms/Source/PythonBindings/README.md +++ b/SerialPrograms/Source/PythonBindings/README.md @@ -24,37 +24,63 @@ device, using the `NintendoSwitch::PybindSwitchProController` class from CoreLib - `tests/` — pytest suite (pure-Python parts always run; compiled-module tests skip when `_pa_core` is not built). -## Building the module +## Building the pybind module Requires a Python 3.10+ with development headers and pybind11 (a system package -or `pip install pybind11`). If neither is found, CMake downloads a pinned +or `pip install pybind11`). If pybind11 is not found, CMake downloads a pinned pybind11 release. +Run the following commands: + ```sh -cd SerialPrograms +cd SerialPrograms # starting from the root Arduino-Source mkdir bin && cd bin -cmake .. -DPA_PYTHON_BINDINGS=ON [-DPA_CORE_ONLY=ON] [-DPython_EXECUTABLE=$(which python3)] +cmake .. -DPA_PYTHON_BINDINGS=ON -DPA_CORE_ONLY=ON cmake --build . --target _pa_core ``` +Note: If cmake has issues with finding python, you can use the command: + +`cmake .. -DPA_PYTHON_BINDINGS=ON -DPA_CORE_ONLY=ON -DPython_EXECUTABLE=$(which python3)` + +However, note that the `$(which ...)` command does not work in Windows. + `-DPA_CORE_ONLY=ON` builds only the GUI-free core (CoreLib, -SerialProgramsCommandLine and the module) — the fast path; without it the -module is built alongside the full GUI program. +SerialProgramsCommandLine and the module) — the fast path; without it, the +module is built alongside the full GUI program, meaning that you would have +to configure your build to include Qt and other libraries. + +## Installing the pybind module -After the build, `_pa_core` is copied into `pokemon_automation/`, so the -package works straight from the source tree. To install it for a project: +After the build, `_pa_core` is copied into +`SerialPrograms/Source/PythonBindings/pokemon_automation/`. + +To install it for a project: ```sh -pip install -e SerialPrograms/Source/PythonBindings +pip install -e SerialPrograms/Source/PythonBindings # starting from the root Arduino-Source ``` -## Usage +## Running the test file + +`selftest.py` will connect to the Switch via PABotBase2 and send a few simple commands. + +Run the following commands: + +```sh +cd SerialPrograms/Source/PythonBindings # starting from the root Arduino-Source +python -m pokemon_automation.selftest [port] +``` + +If `port` is omitted, every port from `list_serial_ports()` is tried in turn. + +## More example usage ```python from pokemon_automation import SwitchController, list_serial_ports print(list_serial_ports()) -with SwitchController("/dev/ttyACM0") as sw: +with SwitchController("/dev/ttyACM0") as sw: # connects to the Switch via port /dev/ttyACM0 print(sw.status()) # device name and firmware version sw.press("A") # tap A (80 ms hold, 80 ms release) sw.press("L+R", hold_ms=200) # press L and R together @@ -66,18 +92,18 @@ with SwitchController("/dev/ttyACM0") as sw: ``` Commands are queued on the microcontroller and return as soon as they are -scheduled, mirroring the `pbf_*()` functions of the main program. Call -`flush()` to wait for execution, and `cancel_all_and_wait()` (thread-safe) to -drop the queue, release all inputs and wait for the device to confirm the -neutral state — e.g. from an emergency-stop thread. `close()` does this for -you before dropping the connection. +scheduled, mirroring the `pbf_*()` functions of the main program. -Run the tests: +- `flush()`: to wait for all queued commands to execute. +- `cancel_all_and_wait()`: (thread-safe) to +drop the queue, release all inputs and wait for the device to confirm the +neutral state — e.g. from an emergency-stop thread. +- `close()`: runs `cancel_all_and_wait()`, then drops the connection. +- `press()`: presses the buttons on the Switch +- `stick()`: moves the left or right stick on the Switch +- `hold()`: simulatenously holds/presses any combination of buttons, d-pad and sticks. -```sh -cd SerialPrograms/Source/PythonBindings -python -m pytest -``` +See `controller.py` for more details. ## Notes From d4da6466105cf61046e2eedf189d5678d04d9b9e Mon Sep 17 00:00:00 2001 From: PA Dev Bot <344001113+pa-devbot@users.noreply.github.com> Date: Mon, 19 Oct 2026 19:31:16 +0000 Subject: [PATCH 07/58] Python bindings README: small fixes - 'simulatenously' -> 'simultaneously' - selftest code block: [port] is not shell syntax; show the optional argument as a real example instead - rename 'Running the test file' to 'Hardware self-test' (the pytest suite lives in tests/) and add the missing 'Running the unit tests' section, which the Layout section advertises but nothing in the file explained - add wait() to the method list (it is used in the example) - drop trailing whitespace --- .../Source/PythonBindings/README.md | 25 +++++++++++++------ 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/SerialPrograms/Source/PythonBindings/README.md b/SerialPrograms/Source/PythonBindings/README.md index f2a7aa4c31..eb9d83634e 100644 --- a/SerialPrograms/Source/PythonBindings/README.md +++ b/SerialPrograms/Source/PythonBindings/README.md @@ -52,7 +52,7 @@ to configure your build to include Qt and other libraries. ## Installing the pybind module -After the build, `_pa_core` is copied into +After the build, `_pa_core` is copied into `SerialPrograms/Source/PythonBindings/pokemon_automation/`. To install it for a project: @@ -61,7 +61,7 @@ To install it for a project: pip install -e SerialPrograms/Source/PythonBindings # starting from the root Arduino-Source ``` -## Running the test file +## Hardware self-test `selftest.py` will connect to the Switch via PABotBase2 and send a few simple commands. @@ -69,11 +69,21 @@ Run the following commands: ```sh cd SerialPrograms/Source/PythonBindings # starting from the root Arduino-Source -python -m pokemon_automation.selftest [port] +python -m pokemon_automation.selftest # try every candidate port in turn +python -m pokemon_automation.selftest /dev/ttyACM0 # or pass a specific port ``` If `port` is omitted, every port from `list_serial_ports()` is tried in turn. +## Running the unit tests + +```sh +cd SerialPrograms/Source/PythonBindings # starting from the root Arduino-Source +python -m pytest +``` + +The tests that need the compiled module are skipped when `_pa_core` has not been built. + ## More example usage ```python @@ -92,16 +102,17 @@ with SwitchController("/dev/ttyACM0") as sw: # connects to the Switch via port ``` Commands are queued on the microcontroller and return as soon as they are -scheduled, mirroring the `pbf_*()` functions of the main program. +scheduled, mirroring the `pbf_*()` functions of the main program. -- `flush()`: to wait for all queued commands to execute. +- `flush()`: to wait for all queued commands to execute. - `cancel_all_and_wait()`: (thread-safe) to drop the queue, release all inputs and wait for the device to confirm the -neutral state — e.g. from an emergency-stop thread. +neutral state — e.g. from an emergency-stop thread. - `close()`: runs `cancel_all_and_wait()`, then drops the connection. - `press()`: presses the buttons on the Switch - `stick()`: moves the left or right stick on the Switch -- `hold()`: simulatenously holds/presses any combination of buttons, d-pad and sticks. +- `hold()`: simultaneously holds/presses any combination of buttons, d-pad and sticks. +- `wait()`: queues a pause with nothing pressed. See `controller.py` for more details. From 7b583081f6d4db1fa0136014063cbb1cc08c03eb Mon Sep 17 00:00:00 2001 From: jw098 Date: Mon, 19 Oct 2026 12:41:37 -0700 Subject: [PATCH 08/58] more README updates --- SerialPrograms/Source/PythonBindings/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/SerialPrograms/Source/PythonBindings/README.md b/SerialPrograms/Source/PythonBindings/README.md index eb9d83634e..fa05ce4884 100644 --- a/SerialPrograms/Source/PythonBindings/README.md +++ b/SerialPrograms/Source/PythonBindings/README.md @@ -77,6 +77,8 @@ If `port` is omitted, every port from `list_serial_ports()` is tried in turn. ## Running the unit tests +Pytest must be installed: `pip install pytest` + ```sh cd SerialPrograms/Source/PythonBindings # starting from the root Arduino-Source python -m pytest From babadf93d29fd6562dc217da4cf23f4a778fd9e0 Mon Sep 17 00:00:00 2001 From: jw098 Date: Mon, 19 Oct 2026 12:59:10 -0700 Subject: [PATCH 09/58] pybind CI --- .github/workflows/cpp-ci-python-bindings.yml | 40 ++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 .github/workflows/cpp-ci-python-bindings.yml diff --git a/.github/workflows/cpp-ci-python-bindings.yml b/.github/workflows/cpp-ci-python-bindings.yml new file mode 100644 index 0000000000..e97b775c2c --- /dev/null +++ b/.github/workflows/cpp-ci-python-bindings.yml @@ -0,0 +1,40 @@ +name: C++ CI Python Bindings +on: + push: + branches: [main] + workflow_dispatch: + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +# Builds the GUI-free core plus the _pa_core pybind11 module +# (Source/PythonBindings/README.md) and runs the package's pytest suite. +# This needs no Qt, OpenCV, ONNX Runtime, Tesseract, DPP or Discord SDK. + +jobs: + build: + # if: github.event_name != 'pull_request' || github.event.pull_request.draft == false + runs-on: ubuntu-latest + steps: + - name: Checkout Arduino-Source + uses: actions/checkout@v7 + with: + path: 'Arduino-Source' + submodules: 'recursive' + - name: Generate binaries + run: | + cd Arduino-Source/SerialPrograms + mkdir bin + cd bin + cmake .. -DPA_CORE_ONLY=ON -DPA_PYTHON_BINDINGS=ON + cmake --build . --config RelWithDebInfo --parallel 10 + - name: Run the Python tests + run: | + python3 -m venv /tmp/pa-pytest-venv/tmp/pa-pytest-venv/bin/pip install pytest + cd Arduino-Source/SerialPrograms/Source/PythonBindings/tmp/pa-pytest-venv/bin/python -m pytest -q + +# Note: the venv avoids PEP 668 issues with system-pip on newer runners. +# The runner's system Python needs dev headers (python3-dev is preinstalled on the images). \ No newline at end of file From 5b3eaa0c63f326fd39e5dace1359e45472c6cf2c Mon Sep 17 00:00:00 2001 From: jw098 Date: Mon, 19 Oct 2026 13:28:55 -0700 Subject: [PATCH 10/58] update CI --- .github/workflows/cpp-ci-python-bindings.yml | 41 +++++++++++--------- 1 file changed, 23 insertions(+), 18 deletions(-) diff --git a/.github/workflows/cpp-ci-python-bindings.yml b/.github/workflows/cpp-ci-python-bindings.yml index e97b775c2c..58eede1634 100644 --- a/.github/workflows/cpp-ci-python-bindings.yml +++ b/.github/workflows/cpp-ci-python-bindings.yml @@ -17,24 +17,29 @@ concurrency: jobs: build: # if: github.event_name != 'pull_request' || github.event.pull_request.draft == false - runs-on: ubuntu-latest - steps: - - name: Checkout Arduino-Source - uses: actions/checkout@v7 - with: - path: 'Arduino-Source' - submodules: 'recursive' - - name: Generate binaries - run: | - cd Arduino-Source/SerialPrograms - mkdir bin - cd bin - cmake .. -DPA_CORE_ONLY=ON -DPA_PYTHON_BINDINGS=ON - cmake --build . --config RelWithDebInfo --parallel 10 - - name: Run the Python tests - run: | - python3 -m venv /tmp/pa-pytest-venv/tmp/pa-pytest-venv/bin/pip install pytest - cd Arduino-Source/SerialPrograms/Source/PythonBindings/tmp/pa-pytest-venv/bin/python -m pytest -q + runs-on: ubuntu-26.04 + + steps: + - name: Checkout Arduino-Source + uses: actions/checkout@v7 + with: + path: 'Arduino-Source' + submodules: 'recursive' + + - name: Generate binaries + run: | + cd Arduino-Source/SerialPrograms + mkdir bin + cd bin + cmake .. -DPA_CORE_ONLY=ON -DPA_PYTHON_BINDINGS=ON + cmake --build . --config RelWithDebInfo --parallel 10 + + - name: Run the Python tests + run: | + python3 -m venv /tmp/pa-pytest-venv + /tmp/pa-pytest-venv/bin/pip install pytest + cd Arduino-Source/SerialPrograms/Source/PythonBindings + /tmp/pa-pytest-venv/bin/python -m pytest -q # Note: the venv avoids PEP 668 issues with system-pip on newer runners. # The runner's system Python needs dev headers (python3-dev is preinstalled on the images). \ No newline at end of file From 903085e7fbc6ad9b2e25b4e8f30792b6abdd7a3c Mon Sep 17 00:00:00 2001 From: jw098 Date: Mon, 19 Oct 2026 16:22:59 -0700 Subject: [PATCH 11/58] rename selftest to controller_test --- SerialPrograms/Source/PythonBindings/README.md | 18 ++++++++++++------ .../{selftest.py => controller_test.py} | 6 +++--- 2 files changed, 15 insertions(+), 9 deletions(-) rename SerialPrograms/Source/PythonBindings/pokemon_automation/{selftest.py => controller_test.py} (90%) diff --git a/SerialPrograms/Source/PythonBindings/README.md b/SerialPrograms/Source/PythonBindings/README.md index fa05ce4884..43531973f0 100644 --- a/SerialPrograms/Source/PythonBindings/README.md +++ b/SerialPrograms/Source/PythonBindings/README.md @@ -19,7 +19,7 @@ device, using the `NintendoSwitch::PybindSwitchProController` class from CoreLib - `fake.py` — `FakeController`: the same backend interface without hardware, for unit tests. - `devices.py` — `list_serial_ports()`. - - `selftest.py` — `python -m pokemon_automation.selftest [port]`: connect to + - `controller_test.py` — `python -m pokemon_automation.controller_test [port]`: connect to a real device and send a few commands. - `tests/` — pytest suite (pure-Python parts always run; compiled-module tests skip when `_pa_core` is not built). @@ -61,19 +61,25 @@ To install it for a project: pip install -e SerialPrograms/Source/PythonBindings # starting from the root Arduino-Source ``` -## Hardware self-test +## Controller test -`selftest.py` will connect to the Switch via PABotBase2 and send a few simple commands. +`controller_test.py` will connect to the Switch via PABotBase2 and send a few simple commands. + +Ensure your microcontroller is connected to your computer, and has the correct firmware flashed onto it, and is ready to connect to the Switch (e.g. Switch in the Change Grip/controller menu for the Pico W and ESP32, or that the USB cable is connecting the microcontroller to the Switch dock for the ESP32-S3). + +The easiest way to do a proper setup is to establish the connection to the Switch in the Computer Control program first, while noting the port used. Follow the [setup guide](https://pokemonautomation.github.io/SetupGuide/index.html) if you're not familiar with the Computer Control setup. Then, disconnect the microcontroller by either shutting down the Computer Control program, or by setting the port to "none". Note: in order for the microcontroller to connect to the Switch via this python module, the microcontroller must NOT be connected to the Computer Control program. Run the following commands: ```sh cd SerialPrograms/Source/PythonBindings # starting from the root Arduino-Source -python -m pokemon_automation.selftest # try every candidate port in turn -python -m pokemon_automation.selftest /dev/ttyACM0 # or pass a specific port +python -m pokemon_automation.controller_test # try every candidate port in turn +python -m pokemon_automation.controller_test /dev/ttyACM0 # or pass a specific port ``` -If `port` is omitted, every port from `list_serial_ports()` is tried in turn. +If `port` is omitted, every port from `list_serial_ports()` is tried in turn. + +`port` examples: "/dev/cu.usbserial-0001" on macOS, "/dev/ttyACM0" on Linux, or "COM3" on Windows. ## Running the unit tests diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/selftest.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller_test.py similarity index 90% rename from SerialPrograms/Source/PythonBindings/pokemon_automation/selftest.py rename to SerialPrograms/Source/PythonBindings/pokemon_automation/controller_test.py index b55339896f..cf263bb2e2 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/selftest.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller_test.py @@ -1,6 +1,6 @@ -"""Hardware self-test: connect to a PABotBase2 and send a few simple commands. +"""Controller test: connect to the Switch via PABotBase2 and send a few simple commands. - python -m pokemon_automation.selftest [port] + python -m pokemon_automation.controller_test [port] If `port` is omitted, every port from `list_serial_ports()` is tried in turn. The test connects, prints the device status, presses HOME and a d-pad step, @@ -36,7 +36,7 @@ def try_port(port: str) -> bool: def main(argv: list[str] | None = None) -> int: - p = argparse.ArgumentParser(prog="python -m pokemon_automation.selftest", description=__doc__, + p = argparse.ArgumentParser(prog="python -m pokemon_automation.controller_test", description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument("port", nargs="?", help="Controller serial port. Omit to try every candidate port.") args = p.parse_args(argv) From 253fa4ff38275ab017f1fad1772e07a46ac857b0 Mon Sep 17 00:00:00 2001 From: jw098 Date: Mon, 19 Oct 2026 17:06:37 -0700 Subject: [PATCH 12/58] rename files --- SerialPrograms/Source/PythonBindings/README.md | 10 +++++----- .../{controller_test.py => switch_connection_test.py} | 6 +++--- .../{test_controller.py => test_fake_controller.py} | 0 3 files changed, 8 insertions(+), 8 deletions(-) rename SerialPrograms/Source/PythonBindings/pokemon_automation/{controller_test.py => switch_connection_test.py} (89%) rename SerialPrograms/Source/PythonBindings/tests/{test_controller.py => test_fake_controller.py} (100%) diff --git a/SerialPrograms/Source/PythonBindings/README.md b/SerialPrograms/Source/PythonBindings/README.md index 43531973f0..2237691e78 100644 --- a/SerialPrograms/Source/PythonBindings/README.md +++ b/SerialPrograms/Source/PythonBindings/README.md @@ -19,7 +19,7 @@ device, using the `NintendoSwitch::PybindSwitchProController` class from CoreLib - `fake.py` — `FakeController`: the same backend interface without hardware, for unit tests. - `devices.py` — `list_serial_ports()`. - - `controller_test.py` — `python -m pokemon_automation.controller_test [port]`: connect to + - `switch_connection_test.py` — `python -m pokemon_automation.switch_connection_test [port]`: connect to a real device and send a few commands. - `tests/` — pytest suite (pure-Python parts always run; compiled-module tests skip when `_pa_core` is not built). @@ -61,9 +61,9 @@ To install it for a project: pip install -e SerialPrograms/Source/PythonBindings # starting from the root Arduino-Source ``` -## Controller test +## Switch Connection test -`controller_test.py` will connect to the Switch via PABotBase2 and send a few simple commands. +`switch_connection_test.py` will connect to the Switch via PABotBase2 and send a few simple commands. Ensure your microcontroller is connected to your computer, and has the correct firmware flashed onto it, and is ready to connect to the Switch (e.g. Switch in the Change Grip/controller menu for the Pico W and ESP32, or that the USB cable is connecting the microcontroller to the Switch dock for the ESP32-S3). @@ -73,8 +73,8 @@ Run the following commands: ```sh cd SerialPrograms/Source/PythonBindings # starting from the root Arduino-Source -python -m pokemon_automation.controller_test # try every candidate port in turn -python -m pokemon_automation.controller_test /dev/ttyACM0 # or pass a specific port +python -m pokemon_automation.switch_connection_test # try every candidate port in turn +python -m pokemon_automation.switch_connection_test /dev/ttyACM0 # or pass a specific port ``` If `port` is omitted, every port from `list_serial_ports()` is tried in turn. diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller_test.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py similarity index 89% rename from SerialPrograms/Source/PythonBindings/pokemon_automation/controller_test.py rename to SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py index cf263bb2e2..0d28c6490b 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller_test.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py @@ -1,6 +1,6 @@ -"""Controller test: connect to the Switch via PABotBase2 and send a few simple commands. +"""Switch connection test: connect to the Switch via PABotBase2 and send a few simple commands. - python -m pokemon_automation.controller_test [port] + python -m pokemon_automation.switch_connection_test [port] If `port` is omitted, every port from `list_serial_ports()` is tried in turn. The test connects, prints the device status, presses HOME and a d-pad step, @@ -36,7 +36,7 @@ def try_port(port: str) -> bool: def main(argv: list[str] | None = None) -> int: - p = argparse.ArgumentParser(prog="python -m pokemon_automation.controller_test", description=__doc__, + p = argparse.ArgumentParser(prog="python -m pokemon_automation.switch_connection_test", description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument("port", nargs="?", help="Controller serial port. Omit to try every candidate port.") args = p.parse_args(argv) diff --git a/SerialPrograms/Source/PythonBindings/tests/test_controller.py b/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py similarity index 100% rename from SerialPrograms/Source/PythonBindings/tests/test_controller.py rename to SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py From e582f3729aff426764145c28d5f19a420ecb91b6 Mon Sep 17 00:00:00 2001 From: PA Dev Bot <344001113+pa-devbot@users.noreply.github.com> Date: Tue, 20 Oct 2026 00:19:12 +0000 Subject: [PATCH 13/58] Python: label where the Python code references the C++ code Add comments naming the C++ source each Python definition mirrors or depends on (repo-relative paths): the BUTTON_BITS/DPAD_POSITIONS constants and check_against_core() vs the enums in NintendoSwitch_ControllerButtons.h; the ControllerBackend protocol, status/flush/cancel_all_and_wait and press() vs PybindSwitchProController / AbstractController; the fake and the _core loader vs the module source and the wrapped class; and the test headers. Also note that DEFAULT_HOLD_MS/DEFAULT_RELEASE_MS are Python-side defaults (the C++ issue_buttons() takes explicit durations). --- .../pokemon_automation/__init__.py | 8 +++-- .../pokemon_automation/_core.py | 6 ++++ .../pokemon_automation/buttons.py | 23 +++++++++---- .../pokemon_automation/controller.py | 34 +++++++++++++++++-- .../PythonBindings/pokemon_automation/fake.py | 7 ++++ .../PythonBindings/tests/test_buttons.py | 3 ++ .../Source/PythonBindings/tests/test_core.py | 7 ++++ .../tests/test_fake_controller.py | 5 +++ 8 files changed, 80 insertions(+), 13 deletions(-) diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py index c3d1586fb4..8d46ed6b7c 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py @@ -3,9 +3,11 @@ Layers (each built on the one below): - `_pa_core` (C++, pybind11): acts as a Switch controller through a PABotBase2 - serial device, built only from this codebase's CoreLib. Build it from - SerialPrograms with `-DPA_PYTHON_BINDINGS=ON` (see the README next to this - package). + serial device, built only from this codebase's CoreLib (the module is + SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp, wrapping + SerialPrograms/Source/Integrations/PybindSwitchProController.h). Build it + from SerialPrograms with `-DPA_PYTHON_BINDINGS=ON` (see the README next to + this package). - `SwitchController`: the Python API on top of it, with button names instead of bitfields. `fake.FakeController` implements the same backend interface for testing without hardware. diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/_core.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/_core.py index 1b14da832b..96027b2fa3 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/_core.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/_core.py @@ -5,6 +5,12 @@ `PA_CORE_PATH` to a folder containing `_pa_core*.so` / `_pa_core*.pyd` to load it from somewhere else. +C++ reference: `_pa_core` is built from +SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp and wraps +`NintendoSwitch::PybindSwitchProController` +(SerialPrograms/Source/Integrations/PybindSwitchProController.h/.cpp), which +lives in CoreLib. + Importing is deferred until first use, so the pure-Python parts of the package (button parsing, `fake.FakeController`) work without the compiled module. """ diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py index b1323ea78d..5daf542631 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py @@ -11,9 +11,12 @@ - Joystick positions: a direction name ("up", "down_left", ...) or an (x, y) pair in [-1, 1] with +x = right and +y = up. "neutral"/"center" means (0, 0). -The button bit values match `NintendoSwitch::Button` in -Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerButtons.h. When the -compiled module is available, `check_against_core()` verifies that they still agree. +The button bit values match `NintendoSwitch::Button` and the d-pad values +match `NintendoSwitch::DpadPosition` in +SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerButtons.h. +When the compiled module is available, `check_against_core()` verifies that +they still agree (the module exposes both enums, built by +SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp). """ from __future__ import annotations @@ -22,7 +25,9 @@ from collections.abc import Sequence from dataclasses import dataclass -# Bit positions from NintendoSwitch_ControllerButtons.h. +# Bit positions, mirroring the C++ `enum Button` in +# SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerButtons.h. +# Do not edit by hand; tests/test_buttons.py checks these against the C++ enum. BUTTON_BITS: dict[str, int] = { "Y": 1 << 0, "B": 1 << 1, @@ -51,7 +56,9 @@ "RS": "RCLICK", } -# D-pad positions from `NintendoSwitch::DpadPosition`: 0 = up, clockwise, 8 = none. +# D-pad positions, mirroring the C++ `enum DpadPosition` in +# SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerButtons.h: +# 0 = up, clockwise, 8 = none. DPAD_POSITIONS: dict[str, int] = { "UP": 0, "UP_RIGHT": 1, @@ -197,8 +204,10 @@ def parse_stick(position: StickArg) -> tuple[float, float]: def check_against_core(core_buttons: dict[str, int], core_dpad: dict[str, int]) -> None: """Raise AssertionError if `BUTTON_BITS` / `DPAD_POSITIONS` disagree with the C++ enums. - `core_buttons` / `core_dpad` are `_pa_core.BUTTONS` / `_pa_core.DPAD_POSITIONS`, - generated from `NintendoSwitch::Button` / `DpadPosition`. + `core_buttons` / `core_dpad` are `_pa_core.BUTTONS` / `_pa_core.DPAD_POSITIONS`: + the module (SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp) + generates them from the C++ enums in + SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerButtons.h. """ for name, bit in BUTTON_BITS.items(): if core_buttons.get(name) != bit: diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py index c9157fe4ff..c70e34fdae 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py @@ -27,10 +27,20 @@ DEFAULT_HOLD_MS = 80 DEFAULT_RELEASE_MS = 80 +# Python-side defaults for a quick tap; there is no C++ constant behind them +# (the C++ issue_buttons()/issue_dpad() take explicit durations). class ControllerBackend(Protocol): - """The `_pa_core.Controller` methods used here. `fake.FakeController` implements it too.""" + """The `_pa_core.Controller` methods used here. `fake.FakeController` implements it too. + + C++ reference: `_pa_core.Controller` is a 1:1 binding of + `NintendoSwitch::PybindSwitchProController` + (SerialPrograms/Source/Integrations/PybindSwitchProController.h), which wraps the + device-side command queue of `AbstractController` + (SerialPrograms/Source/Controllers/Controller.h). The binding itself is in + SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp. + """ def wait_for_ready(self, timeout_ms: int = ...) -> bool: ... def is_ready(self) -> bool: ... @@ -93,7 +103,11 @@ def is_ready(self) -> bool: def status(self) -> str: """The connection status text: device name and firmware version, or the - error message if the connection failed.""" + error message if the connection failed. + + C++: `PybindSwitchProController::current_status()` -> `ControllerConnection::status_text()` + (SerialPrograms/Source/Controllers/ControllerConnection.h). + """ self._require_open() return self._backend.current_status() @@ -109,6 +123,12 @@ def press(self, buttons: btn.ButtonsArg, hold_ms: int = DEFAULT_HOLD_MS, """Tap a button combination (and/or one d-pad direction) `repeat` times. `buttons`: "A", "L+R", ["ZL", "up"], ... (see `pokemon_automation.buttons`). + + C++: maps to `issue_buttons()` / `issue_dpad()` / `issue_full_controller_state()` + on `AbstractController` (SerialPrograms/Source/Controllers/Controller.h), via + `PybindSwitchProController` (SerialPrograms/Source/Integrations/PybindSwitchProController.h). + `delay = hold + release` runs commands back to back, the same convention as the + C++ class docs. """ if repeat < 1: raise ValueError(f"repeat must be at least 1, got {repeat}.") @@ -169,7 +189,11 @@ def wait(self, duration_ms: int) -> None: self._backend.wait(duration_ms) def flush(self) -> None: - """Block until every queued command has executed on the device.""" + """Block until every queued command has executed on the device. + + C++: `PybindSwitchProController::wait_for_all_requests()` -> + `AbstractController::wait_for_all()` (SerialPrograms/Source/Controllers/Controller.h). + """ self._require_open() self._backend.wait_for_all_requests() @@ -180,6 +204,10 @@ def cancel_all_and_wait(self, timeout_ms: int = 500) -> bool: True if acknowledged, False on timeout (or if the controller is not ready). Thread-safe: may be called from another thread while commands are being sent (emergency stop). + + C++: `PybindSwitchProController::cancel_all_and_wait(timeout_millis)` + (SerialPrograms/Source/Integrations/PybindSwitchProController.h) -> + `AbstractController::cancel_all_and_wait()` (SerialPrograms/Source/Controllers/Controller.h). """ self._require_open() return self._backend.cancel_all_and_wait(int(timeout_ms)) diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/fake.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/fake.py index 9a99b46dfb..3e40719538 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/fake.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/fake.py @@ -3,6 +3,13 @@ `FakeController` implements the same interface as `_pa_core.Controller` and records every command it receives, so `SwitchController` and friends can be exercised in unit tests. It needs no compiled module. + +C++ reference: the interface it mirrors is the binding of +`NintendoSwitch::PybindSwitchProController` +(SerialPrograms/Source/Integrations/PybindSwitchProController.h) in +SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp; method names +and arguments match that C++ class, so the fake is also a check that the +Python API stays in step with the C++ interface. """ from __future__ import annotations diff --git a/SerialPrograms/Source/PythonBindings/tests/test_buttons.py b/SerialPrograms/Source/PythonBindings/tests/test_buttons.py index b14924f646..a6fc06041e 100644 --- a/SerialPrograms/Source/PythonBindings/tests/test_buttons.py +++ b/SerialPrograms/Source/PythonBindings/tests/test_buttons.py @@ -52,5 +52,8 @@ def test_sticks(): def test_matches_cpp_enum(): + # C++ side: `enum Button` / `enum DpadPosition` in + # SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerButtons.h, + # exposed by the module (SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp). core = pytest.importorskip("pokemon_automation._pa_core") btn.check_against_core(dict(core.BUTTONS), dict(core.DPAD_POSITIONS)) diff --git a/SerialPrograms/Source/PythonBindings/tests/test_core.py b/SerialPrograms/Source/PythonBindings/tests/test_core.py index 451d4bbd02..7b39ef9894 100644 --- a/SerialPrograms/Source/PythonBindings/tests/test_core.py +++ b/SerialPrograms/Source/PythonBindings/tests/test_core.py @@ -1,5 +1,12 @@ # Tests for the compiled `_pa_core` module. They are skipped when the module # has not been built (it is built with -DPA_PYTHON_BINDINGS=ON). +# +# C++ reference: `_pa_core` is built from +# SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp and wraps +# `NintendoSwitch::PybindSwitchProController` +# (SerialPrograms/Source/Integrations/PybindSwitchProController.h); the +# BUTTONS / DPAD_POSITIONS dicts it exposes are generated from the enums in +# SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerButtons.h. import pytest core = pytest.importorskip("pokemon_automation._pa_core") diff --git a/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py b/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py index cd3fda1da8..de9733382e 100644 --- a/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py +++ b/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py @@ -1,3 +1,8 @@ +# SwitchController on top of a FakeController (no hardware, no compiled module). +# The assertions check the exact backend calls, which mirror the C++ interface of +# `NintendoSwitch::PybindSwitchProController` +# (SerialPrograms/Source/Integrations/PybindSwitchProController.h), bound by +# SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp. import pytest from pokemon_automation import BUTTON_BITS, DPAD_NONE, DPAD_POSITIONS, FakeController, SwitchController From 6c9ff5f45b7718d79fdaa8edb87e053fd105ca99 Mon Sep 17 00:00:00 2001 From: jw098 Date: Mon, 19 Oct 2026 22:22:14 -0700 Subject: [PATCH 14/58] minor update to switch_connection_test.py --- .../pokemon_automation/switch_connection_test.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py index 0d28c6490b..a4a40823c8 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py @@ -23,8 +23,12 @@ def try_port(port: str) -> bool: print(f"Connected to {port}") print(f" status: {sw.status()}") print(f" name: {sw.name() or '(unknown)'}") - sw.press("HOME") + sw.press("A") # initial button press to wake up the connection + sw.press("HOME", hold_ms=200, release_ms=1000) sw.press("right", hold_ms=100) + sw.press("right", hold_ms=100) + sw.press("left", hold_ms=100) + sw.press("left", hold_ms=100) sw.wait(500) sw.flush() print(" cancel confirmed:", sw.cancel_all_and_wait(500)) From 7370e4e7dcf09d945db7c369812cf3253c1f627e Mon Sep 17 00:00:00 2001 From: jw098 Date: Mon, 19 Oct 2026 23:12:06 -0700 Subject: [PATCH 15/58] add comments --- .../Source/PythonBindings/pokemon_automation/buttons.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py index 5daf542631..b712731dd3 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py @@ -83,7 +83,7 @@ "UP_LEFT": (-1, 1), } -ButtonsArg = str | Sequence[str] | None +ButtonsArg = str | Sequence[str] | None # both Buttons and D-pad inputs allowed. see the keys for BUTTON_BITS, BUTTON_ALIASES, _DIRECTION_VECTORS above for valid strings StickArg = str | Sequence[float] | None @@ -142,7 +142,7 @@ def parse_buttons(buttons: ButtonsArg) -> ParsedButtons: (e.g. "up+down"). """ bitfield = 0 - dx = dy = 0 + dx = dy = 0 # dx, dy represents the current overall DPAD position. starts neutral seen_dpad: list[str] = [] for raw in _split(buttons): name = raw.strip() @@ -152,7 +152,7 @@ def parse_buttons(buttons: ButtonsArg) -> ParsedButtons: bitfield |= BUTTON_BITS[key] continue if key in _DIRECTION_VECTORS: - vx, vy = _DIRECTION_VECTORS[key] + vx, vy = _DIRECTION_VECTORS[key] # vectors of current DPAD being parsed if (vx and dx and vx != dx) or (vy and dy and vy != dy): raise ValueError(f"Contradictory d-pad directions: {seen_dpad + [name]}") dx = vx or dx From 9e7b6b58ff0e4095e6d816f4087215698e308706 Mon Sep 17 00:00:00 2001 From: jw098 Date: Mon, 19 Oct 2026 23:20:27 -0700 Subject: [PATCH 16/58] minor update to switch_connection_test.py --- .../PythonBindings/pokemon_automation/switch_connection_test.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py index a4a40823c8..f6fee72761 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py @@ -29,6 +29,8 @@ def try_port(port: str) -> bool: sw.press("right", hold_ms=100) sw.press("left", hold_ms=100) sw.press("left", hold_ms=100) + sw.stick("right", [1, 0], duration_ms=2000) + sw.stick("right", [-1, 0], duration_ms=2000) sw.wait(500) sw.flush() print(" cancel confirmed:", sw.cancel_all_and_wait(500)) From 31533d9ce3df528483f3b2f647c9bf0172fcaf42 Mon Sep 17 00:00:00 2001 From: jw098 Date: Mon, 19 Oct 2026 23:33:24 -0700 Subject: [PATCH 17/58] add comments --- .../Source/PythonBindings/pokemon_automation/controller.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py index c70e34fdae..27c737147a 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py @@ -34,12 +34,11 @@ class ControllerBackend(Protocol): """The `_pa_core.Controller` methods used here. `fake.FakeController` implements it too. - C++ reference: `_pa_core.Controller` is a 1:1 binding of - `NintendoSwitch::PybindSwitchProController` + C++ reference: `_pa_core.Controller` is a pybind defined in PythonBindings_Module.cpp + It, in turn, is a 1:1 binding of `NintendoSwitch::PybindSwitchProController` (SerialPrograms/Source/Integrations/PybindSwitchProController.h), which wraps the device-side command queue of `AbstractController` - (SerialPrograms/Source/Controllers/Controller.h). The binding itself is in - SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp. + (SerialPrograms/Source/Controllers/Controller.h). """ def wait_for_ready(self, timeout_ms: int = ...) -> bool: ... From 26bfca3138f26624740493fc05a486c80096d5ba Mon Sep 17 00:00:00 2001 From: PA Dev Bot <344001113+pa-devbot@users.noreply.github.com> Date: Tue, 20 Oct 2026 06:58:28 +0000 Subject: [PATCH 18/58] Python: name SwitchController commands after the backend methods The command methods of SwitchController now match the names of the _p a_core.Controller methods they wrap (and thus the C++ PybindSwitchProController methods): - press() -> push_button() / push_dpad() (mixed combos now go to controller_state(); each method rejects the other kind with a pointer to the right method) - hold() -> controller_state() (duration_ms first, like the C++ signature; no implicit release wait) - stick(side) -> push_left_joystick() / push_right_joystick() - flush() -> wait_for_all_requests() - status() -> current_status() - name() -> controller_name() - wait(), cancel_all_and_wait(), is_ready() and close() already matched. Button-name parsing is unchanged; _pa_core and FakeController are untouched. Updated examples in the package docstrings, README, switch_connection_test.py and the tests (31 tests now, including rejection of mixed inputs in push_button()/push_dpad()). --- .../Source/PythonBindings/README.md | 36 +++-- .../pokemon_automation/__init__.py | 8 +- .../pokemon_automation/controller.py | 152 ++++++++++++------ .../switch_connection_test.py | 28 ++-- .../tests/test_fake_controller.py | 100 ++++++++---- 5 files changed, 209 insertions(+), 115 deletions(-) diff --git a/SerialPrograms/Source/PythonBindings/README.md b/SerialPrograms/Source/PythonBindings/README.md index 2237691e78..13d2c56216 100644 --- a/SerialPrograms/Source/PythonBindings/README.md +++ b/SerialPrograms/Source/PythonBindings/README.md @@ -14,7 +14,8 @@ device, using the `NintendoSwitch::PybindSwitchProController` class from CoreLib Qt, OpenCV, ONNX Runtime or Tesseract). - `pokemon_automation/` — the Python package on top of it: - `controller.py` — `SwitchController`: the user-facing API, with button names - instead of bitfields (`press("L+R")`, `stick("left", "up")`, ...). + instead of bitfields (`push_button("L+R")`, `push_dpad("up")`, ...). Its + command methods match the names of `_pa_core.Controller`. - `buttons.py` — parsing of button / d-pad / stick names into bitfields. - `fake.py` — `FakeController`: the same backend interface without hardware, for unit tests. @@ -99,28 +100,33 @@ from pokemon_automation import SwitchController, list_serial_ports print(list_serial_ports()) with SwitchController("/dev/ttyACM0") as sw: # connects to the Switch via port /dev/ttyACM0 - print(sw.status()) # device name and firmware version - sw.press("A") # tap A (80 ms hold, 80 ms release) - sw.press("L+R", hold_ms=200) # press L and R together - sw.press("up", repeat=2) # d-pad up twice - sw.stick("left", "up", duration_ms=1500) # walk forward - sw.hold("B", left="up", duration_ms=2000) # run forward + print(sw.current_status()) # device name and firmware version + sw.push_button("A") # tap A (80 ms hold, 80 ms release) + sw.push_button("L+R", hold_ms=200) # press L and R together + sw.push_dpad("up", repeat=2) # d-pad up twice + sw.push_left_joystick("up", duration_ms=1500) # walk forward + sw.controller_state(2000, buttons="B", left="up") # run forward sw.wait(300) - sw.flush() # block until the device executed everything + sw.wait_for_all_requests() # block until the device executed everything ``` Commands are queued on the microcontroller and return as soon as they are -scheduled, mirroring the `pbf_*()` functions of the main program. - -- `flush()`: to wait for all queued commands to execute. +scheduled, mirroring the `pbf_*()` functions of the main program. The command +methods of `SwitchController` match the names of the backend they wrap +(`_pa_core.Controller`, and with it the C++ +`PybindSwitchProController` methods): + +- `push_button()`: taps buttons on the Switch. +- `push_dpad()`: taps a d-pad direction. +- `push_left_joystick()` / `push_right_joystick()`: moves a stick. +- `controller_state()`: simultaneously holds/presses any combination of buttons, + d-pad and sticks. +- `wait()`: queues a pause with nothing pressed. +- `wait_for_all_requests()`: to wait for all queued commands to execute. - `cancel_all_and_wait()`: (thread-safe) to drop the queue, release all inputs and wait for the device to confirm the neutral state — e.g. from an emergency-stop thread. - `close()`: runs `cancel_all_and_wait()`, then drops the connection. -- `press()`: presses the buttons on the Switch -- `stick()`: moves the left or right stick on the Switch -- `hold()`: simultaneously holds/presses any combination of buttons, d-pad and sticks. -- `wait()`: queues a pause with nothing pressed. See `controller.py` for more details. diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py index 8d46ed6b7c..5a0bfc805a 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py @@ -17,10 +17,10 @@ print(list_serial_ports()) with SwitchController("/dev/cu.usbserial-0001") as sw: - sw.press("A") - sw.press("up+right") - sw.stick("left", "up", duration_ms=1500) - sw.flush() + sw.push_button("A") + sw.push_dpad("up+right") + sw.push_left_joystick("up", duration_ms=1500) + sw.wait_for_all_requests() """ from .buttons import ( diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py index 27c737147a..e8de13978a 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py @@ -1,21 +1,23 @@ """High-level Nintendo Switch controller API on top of `_pa_core.Controller`. -Commands are queued on the microcontroller and return immediately, like the -`pbf_*()` functions in the main C++ program. Call `flush()` to wait until -everything queued so far has executed, and `cancel_all_and_wait()` to drop -anything still queued and release all inputs (waiting for the device to confirm -the neutral state). +The command methods carry the same names as the backend they wrap +(`_pa_core.Controller`, a 1:1 binding of `NintendoSwitch::PybindSwitchProController`), +but take button names instead of bitfields. Commands are queued on the +microcontroller and return immediately, like the `pbf_*()` functions in the main +C++ program. Call `wait_for_all_requests()` to wait until everything queued so +far has executed, and `cancel_all_and_wait()` to drop anything still queued and +release all inputs (waiting for the device to confirm the neutral state). Example: from pokemon_automation import SwitchController with SwitchController("/dev/cu.usbserial-0001") as sw: - sw.press("A") # tap A - sw.press("L+R", hold_ms=200) # press L and R together - sw.press("up", repeat=2) # d-pad up twice - sw.stick("left", "up", duration_ms=1500) # walk forward - sw.hold("B", left="up", duration_ms=2000) # run forward - sw.flush() + sw.push_button("A") # tap A + sw.push_button("L+R", hold_ms=200) # press L and R together + sw.push_dpad("up", repeat=2) # d-pad up twice + sw.push_left_joystick("up", duration_ms=1500) # walk forward + sw.controller_state(2000, buttons="B", left="up") # run forward + sw.wait_for_all_requests() """ from __future__ import annotations @@ -100,7 +102,7 @@ def is_ready(self) -> bool: self._require_open() return self._backend.is_ready() - def status(self) -> str: + def current_status(self) -> str: """The connection status text: device name and firmware version, or the error message if the connection failed. @@ -110,22 +112,25 @@ def status(self) -> str: self._require_open() return self._backend.current_status() - def name(self) -> str: + def controller_name(self) -> str: """Name of the active controller implementation, e.g. "Nintendo Switch: Pro Controller".""" self._require_open() return self._backend.controller_name() # ---- commands ------------------------------------------------------------- - def press(self, buttons: btn.ButtonsArg, hold_ms: int = DEFAULT_HOLD_MS, - release_ms: int = DEFAULT_RELEASE_MS, repeat: int = 1) -> None: - """Tap a button combination (and/or one d-pad direction) `repeat` times. + def push_button(self, buttons: btn.ButtonsArg, hold_ms: int = DEFAULT_HOLD_MS, + release_ms: int = DEFAULT_RELEASE_MS, repeat: int = 1) -> None: + """Tap a button combination (d-pad directions not accepted) `repeat` times. - `buttons`: "A", "L+R", ["ZL", "up"], ... (see `pokemon_automation.buttons`). + `buttons`: "A", "L+R", ["ZL", "B"], ... (see `pokemon_automation.buttons`). + For d-pad input use `push_dpad()`; to hold buttons and d-pad together use + `controller_state()`. - C++: maps to `issue_buttons()` / `issue_dpad()` / `issue_full_controller_state()` - on `AbstractController` (SerialPrograms/Source/Controllers/Controller.h), via - `PybindSwitchProController` (SerialPrograms/Source/Integrations/PybindSwitchProController.h). + C++: `AbstractController::issue_buttons()` + (SerialPrograms/Source/Controllers/Controller.h), via + `PybindSwitchProController::push_button()` + (SerialPrograms/Source/Integrations/PybindSwitchProController.h). `delay = hold + release` runs commands back to back, the same convention as the C++ class docs. """ @@ -134,26 +139,57 @@ def press(self, buttons: btn.ButtonsArg, hold_ms: int = DEFAULT_HOLD_MS, _check_nonnegative(hold_ms=hold_ms, release_ms=release_ms) self._require_open() parsed = btn.parse_buttons(buttons) - if not parsed.has_buttons and not parsed.has_dpad: - raise ValueError("press() needs at least one button or d-pad direction.") - b = self._backend - delay = hold_ms + release_ms - with self._lock: - for _ in range(repeat): - if parsed.has_buttons and not parsed.has_dpad: - b.push_button(delay, hold_ms, release_ms, parsed.bitfield) - elif parsed.has_dpad and not parsed.has_buttons: - b.push_dpad(delay, hold_ms, release_ms, parsed.dpad) - else: - # Buttons and d-pad held together: one full state, then release. - b.controller_state(hold_ms, parsed.bitfield, parsed.dpad, 0.0, 0.0, 0.0, 0.0) - b.wait(release_ms) - - def hold(self, buttons: btn.ButtonsArg = None, duration_ms: int = 500, *, - left: btn.StickArg = None, right: btn.StickArg = None) -> None: + if parsed.has_dpad: + raise ValueError( + f"push_button() only accepts buttons, but {buttons!r} includes a d-pad direction. " + "Use push_dpad() for d-pad input or controller_state() to combine them." + ) + if not parsed.has_buttons: + raise ValueError("push_button() needs at least one button.") + self._repeat_commands(hold_ms, release_ms, repeat, + lambda delay, hold, release: self._backend.push_button( + delay, hold, release, parsed.bitfield)) + + def push_dpad(self, position: btn.ButtonsArg, hold_ms: int = DEFAULT_HOLD_MS, + release_ms: int = DEFAULT_RELEASE_MS, repeat: int = 1) -> None: + """Tap a d-pad direction `repeat` times. + + `position`: "up", "up+right" (or "UP_RIGHT"), ["up", "right"], ... + For buttons use `push_button()`; to hold buttons and d-pad together use + `controller_state()`. + + C++: `AbstractController::issue_dpad()` + (SerialPrograms/Source/Controllers/Controller.h), via + `PybindSwitchProController::push_dpad()` + (SerialPrograms/Source/Integrations/PybindSwitchProController.h). + """ + if repeat < 1: + raise ValueError(f"repeat must be at least 1, got {repeat}.") + _check_nonnegative(hold_ms=hold_ms, release_ms=release_ms) + self._require_open() + parsed = btn.parse_buttons(position) + if parsed.has_buttons: + raise ValueError( + f"push_dpad() only accepts d-pad directions, but {position!r} includes buttons. " + "Use push_button() for buttons or controller_state() to combine them." + ) + if not parsed.has_dpad: + raise ValueError("push_dpad() needs at least one d-pad direction.") + self._repeat_commands(hold_ms, release_ms, repeat, + lambda delay, hold, release: self._backend.push_dpad( + delay, hold, release, parsed.dpad)) + + def controller_state(self, duration_ms: int = 500, buttons: btn.ButtonsArg = None, *, + left: btn.StickArg = None, right: btn.StickArg = None) -> None: """Hold any combination of buttons, d-pad and sticks for `duration_ms`. - Everything not specified is released for the whole hold. + `buttons` may mix buttons and d-pad directions ("ZL+up"). Everything not + specified is released for the whole hold. The state is released when the + next queued command executes; queue a `wait()` afterwards for a gap. + + C++: `AbstractController::issue_full_controller_state()` + (SerialPrograms/Source/Controllers/Controller.h), via + `PybindSwitchProController::controller_state()`. """ _check_nonnegative(duration_ms=duration_ms) self._require_open() @@ -166,19 +202,39 @@ def hold(self, buttons: btn.ButtonsArg = None, duration_ms: int = 500, *, left_x, left_y, right_x, right_y ) - def stick(self, side: str, position: btn.StickArg, duration_ms: int = 500, - release_ms: int = 0) -> None: - """Tilt the "left" or "right" stick to `position` for `duration_ms`.""" + def push_left_joystick(self, position: btn.StickArg, duration_ms: int = 500, + release_ms: int = 0) -> None: + """Tilt the left stick to `position` for `duration_ms`. + + C++: `AbstractController::issue_left_joystick()` + (SerialPrograms/Source/Controllers/Controller.h), via + `PybindSwitchProController::push_left_joystick()`. + """ + self._push_joystick(self._backend.push_left_joystick, position, duration_ms, release_ms) + + def push_right_joystick(self, position: btn.StickArg, duration_ms: int = 500, + release_ms: int = 0) -> None: + """Tilt the right stick to `position` for `duration_ms`. + + C++: `AbstractController::issue_right_joystick()` + (SerialPrograms/Source/Controllers/Controller.h), via + `PybindSwitchProController::push_right_joystick()`. + """ + self._push_joystick(self._backend.push_right_joystick, position, duration_ms, release_ms) + + def _push_joystick(self, send, position: btn.StickArg, duration_ms: int, release_ms: int) -> None: _check_nonnegative(duration_ms=duration_ms, release_ms=release_ms) - if side not in ("left", "right"): - raise ValueError('side must be "left" or "right", got ' + repr(side)) self._require_open() x, y = btn.parse_stick(position) with self._lock: - if side == "left": - self._backend.push_left_joystick(duration_ms + release_ms, duration_ms, release_ms, x, y) - else: - self._backend.push_right_joystick(duration_ms + release_ms, duration_ms, release_ms, x, y) + send(duration_ms + release_ms, duration_ms, release_ms, x, y) + + def _repeat_commands(self, hold_ms: int, release_ms: int, repeat: int, send) -> None: + """Queue `send(delay, hold, release)` `repeat` times, back to back.""" + delay = hold_ms + release_ms + with self._lock: + for _ in range(repeat): + send(delay, hold_ms, release_ms) def wait(self, duration_ms: int) -> None: """Queue a pause of `duration_ms` with nothing pressed.""" @@ -187,7 +243,7 @@ def wait(self, duration_ms: int) -> None: if duration_ms > 0: self._backend.wait(duration_ms) - def flush(self) -> None: + def wait_for_all_requests(self) -> None: """Block until every queued command has executed on the device. C++: `PybindSwitchProController::wait_for_all_requests()` -> diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py index f6fee72761..bc5183b7ff 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py @@ -3,9 +3,9 @@ python -m pokemon_automation.switch_connection_test [port] If `port` is omitted, every port from `list_serial_ports()` is tried in turn. -The test connects, prints the device status, presses HOME and a d-pad step, -waits for the device to confirm, and cancels with confirmation. It only -presses HOME and the d-pad. +The test connects, prints the device status, presses some buttons and d-pad +steps, moves the right stick, waits for the device to confirm, and cancels with +confirmation. """ from __future__ import annotations @@ -21,18 +21,18 @@ def try_port(port: str) -> bool: try: with SwitchController(port, timeout_s=5.0) as sw: print(f"Connected to {port}") - print(f" status: {sw.status()}") - print(f" name: {sw.name() or '(unknown)'}") - sw.press("A") # initial button press to wake up the connection - sw.press("HOME", hold_ms=200, release_ms=1000) - sw.press("right", hold_ms=100) - sw.press("right", hold_ms=100) - sw.press("left", hold_ms=100) - sw.press("left", hold_ms=100) - sw.stick("right", [1, 0], duration_ms=2000) - sw.stick("right", [-1, 0], duration_ms=2000) + print(f" status: {sw.current_status()}") + print(f" name: {sw.controller_name() or '(unknown)'}") + sw.push_button("A") # initial button press to wake up the connection + sw.push_button("HOME", hold_ms=200, release_ms=1000) + sw.push_dpad("right", hold_ms=100) + sw.push_dpad("right", hold_ms=100) + sw.push_dpad("left", hold_ms=100) + sw.push_dpad("left", hold_ms=100) + sw.push_right_joystick([1, 0], duration_ms=2000) + sw.push_right_joystick([-1, 0], duration_ms=2000) sw.wait(500) - sw.flush() + sw.wait_for_all_requests() print(" cancel confirmed:", sw.cancel_all_and_wait(500)) print("Self-test OK.") return True diff --git a/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py b/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py index de9733382e..afb51633ac 100644 --- a/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py +++ b/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py @@ -1,6 +1,6 @@ # SwitchController on top of a FakeController (no hardware, no compiled module). -# The assertions check the exact backend calls, which mirror the C++ interface of -# `NintendoSwitch::PybindSwitchProController` +# The command names match the backend (`_pa_core.Controller`), which mirrors the +# C++ interface of `NintendoSwitch::PybindSwitchProController` # (SerialPrograms/Source/Integrations/PybindSwitchProController.h), bound by # SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp. import pytest @@ -25,66 +25,98 @@ def test_not_ready_raises(): SwitchController(backend=fake, timeout_s=0.1) -def test_press_single_button(): +def test_status_and_name_match_backend(): sw, fake = make() - sw.press("A") + assert sw.current_status() == fake.current_status() + assert sw.controller_name() == fake.controller_name() + + +def test_push_button_single_button(): + sw, fake = make() + sw.push_button("A") assert fake.commands() == ["push_button"] (delay, hold, release, bitfield), = fake.arguments("push_button") assert bitfield == BUTTON_BITS["A"] assert delay == hold + release and hold == 80 and release == 80 -def test_press_combined_and_custom_durations(): +def test_push_button_combined_and_custom_durations(): sw, fake = make() - sw.press("L+R", hold_ms=200, release_ms=50) + sw.push_button("L+R", hold_ms=200, release_ms=50) (delay, hold, release, bitfield), = fake.arguments("push_button") assert bitfield == BUTTON_BITS["L"] | BUTTON_BITS["R"] assert (delay, hold, release) == (250, 200, 50) -def test_press_repeat_dpad(): +def test_push_dpad_repeat(): sw, fake = make() - sw.press("up", repeat=3, hold_ms=100) + sw.push_dpad("up", repeat=3, hold_ms=100) args = fake.arguments("push_dpad") assert len(args) == 3 for delay, hold, release, position in args: assert position == DPAD_POSITIONS["UP"] and hold == 100 -def test_press_mixed_uses_controller_state(): +def test_push_button_rejects_dpad(): + sw, fake = make() + with pytest.raises(ValueError, match="push_dpad"): + sw.push_button("ZL+up") + with pytest.raises(ValueError, match="push_dpad"): + sw.push_button("up") + assert fake.commands() == [] + + +def test_push_dpad_rejects_buttons(): + sw, fake = make() + with pytest.raises(ValueError, match="push_button"): + sw.push_dpad("ZL+up") + with pytest.raises(ValueError, match="push_button"): + sw.push_dpad("ZL") + assert fake.commands() == [] + + +def test_push_button_needs_something(): + sw, fake = make() + with pytest.raises(ValueError): + sw.push_button(None) + assert fake.commands() == [] + + +def test_push_dpad_needs_something(): + sw, fake = make() + with pytest.raises(ValueError): + sw.push_dpad(None) + assert fake.commands() == [] + + +def test_controller_state_mixed_combination(): sw, fake = make() - sw.press("ZL+up", hold_ms=60, release_ms=30) + sw.controller_state(60, buttons="ZL+up") assert fake.commands() == ["controller_state"] (duration, buttons, dpad, left_x, left_y, right_x, right_y), = fake.arguments("controller_state") assert duration == 60 assert buttons == BUTTON_BITS["ZL"] assert dpad == DPAD_POSITIONS["UP"] assert (left_x, left_y, right_x, right_y) == (0.0, 0.0, 0.0, 0.0) - assert fake.arguments("wait") == [(30,)] -def test_press_needs_something(): +def test_push_left_joystick(): sw, fake = make() - with pytest.raises(ValueError): - sw.press(None) - assert fake.commands() == [] + sw.push_left_joystick("up", duration_ms=1500) + (delay, hold, release, x, y), = fake.arguments("push_left_joystick") + assert (x, y) == (0.0, 1.0) and hold == 1500 and delay == 1500 + release -def test_stick(): +def test_push_right_joystick(): sw, fake = make() - sw.stick("left", "up", duration_ms=1500) - (delay, hold, release, x, y), = fake.arguments("push_left_joystick") - assert (x, y) == (0.0, 1.0) and hold == 1500 and delay == 1500 + release - sw.stick("right", [0.5, -0.5], duration_ms=300, release_ms=100) + sw.push_right_joystick([0.5, -0.5], duration_ms=300, release_ms=100) (delay, hold, release, x, y), = fake.arguments("push_right_joystick") assert (x, y) == (0.5, -0.5) and delay == 400 - with pytest.raises(ValueError): - sw.stick("middle", "up") -def test_hold_combination(): +def test_controller_state_combination(): sw, fake = make() - sw.hold("B", left="up", right=[1.0, 0.0], duration_ms=2000) + sw.controller_state(2000, buttons="B", left="up", right=[1.0, 0.0]) (duration, buttons, dpad, left_x, left_y, right_x, right_y), = fake.arguments("controller_state") assert duration == 2000 assert buttons == BUTTON_BITS["B"] @@ -104,19 +136,19 @@ def test_wait(): def test_validation(): sw, fake = make() with pytest.raises(ValueError): - sw.press("A", hold_ms=-1) + sw.push_button("A", hold_ms=-1) with pytest.raises(ValueError): - sw.press("A", repeat=0) + sw.push_button("A", repeat=0) with pytest.raises(ValueError): - sw.press("Q") + sw.push_button("Q") with pytest.raises(ValueError): - sw.press("up+down") + sw.push_dpad("up+down") assert fake.commands() == [] -def test_flush_and_cancel(): +def test_wait_for_all_requests_and_cancel(): sw, fake = make() - sw.flush() + sw.wait_for_all_requests() assert sw.cancel_all_and_wait() is True assert fake.cancel_count == 1 fake.confirm_cancel = False @@ -129,9 +161,9 @@ def test_close(): sw.close() assert fake.cancel_count == 1 # close() stops the device first with pytest.raises(RuntimeError, match="closed"): - sw.press("A") + sw.push_button("A") with pytest.raises(RuntimeError, match="closed"): - sw.flush() + sw.wait_for_all_requests() sw.close() # idempotent assert fake.cancel_count == 1 @@ -139,6 +171,6 @@ def test_close(): def test_context_manager(): fake = FakeController() with SwitchController(backend=fake) as sw: - sw.press("A") + sw.push_button("A") with pytest.raises(RuntimeError, match="closed"): - sw.press("A") + sw.push_button("A") From 3409e3ebe239bcb45216f4ff079f75fed2fbe86b Mon Sep 17 00:00:00 2001 From: PA Dev Bot <344001113+pa-devbot@users.noreply.github.com> Date: Tue, 20 Oct 2026 16:24:58 +0000 Subject: [PATCH 19/58] Python: drop the repeat option from push_button()/push_dpad() Each call now queues exactly one tap, matching the single-command semantics of the C++ layer; repeated presses are just repeated calls (or a controller_state() with a longer hold). --- .../Source/PythonBindings/README.md | 2 +- .../pokemon_automation/controller.py | 31 ++++++------------- .../tests/test_fake_controller.py | 12 +++---- 3 files changed, 14 insertions(+), 31 deletions(-) diff --git a/SerialPrograms/Source/PythonBindings/README.md b/SerialPrograms/Source/PythonBindings/README.md index 13d2c56216..173d757c8f 100644 --- a/SerialPrograms/Source/PythonBindings/README.md +++ b/SerialPrograms/Source/PythonBindings/README.md @@ -103,7 +103,7 @@ with SwitchController("/dev/ttyACM0") as sw: # connects to the Switch via port print(sw.current_status()) # device name and firmware version sw.push_button("A") # tap A (80 ms hold, 80 ms release) sw.push_button("L+R", hold_ms=200) # press L and R together - sw.push_dpad("up", repeat=2) # d-pad up twice + sw.push_dpad("up") # d-pad up sw.push_left_joystick("up", duration_ms=1500) # walk forward sw.controller_state(2000, buttons="B", left="up") # run forward sw.wait(300) diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py index e8de13978a..b829c54e34 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py @@ -14,7 +14,7 @@ with SwitchController("/dev/cu.usbserial-0001") as sw: sw.push_button("A") # tap A sw.push_button("L+R", hold_ms=200) # press L and R together - sw.push_dpad("up", repeat=2) # d-pad up twice + sw.push_dpad("up") # d-pad up sw.push_left_joystick("up", duration_ms=1500) # walk forward sw.controller_state(2000, buttons="B", left="up") # run forward sw.wait_for_all_requests() @@ -120,8 +120,8 @@ def controller_name(self) -> str: # ---- commands ------------------------------------------------------------- def push_button(self, buttons: btn.ButtonsArg, hold_ms: int = DEFAULT_HOLD_MS, - release_ms: int = DEFAULT_RELEASE_MS, repeat: int = 1) -> None: - """Tap a button combination (d-pad directions not accepted) `repeat` times. + release_ms: int = DEFAULT_RELEASE_MS) -> None: + """Tap a button combination (d-pad directions not accepted). `buttons`: "A", "L+R", ["ZL", "B"], ... (see `pokemon_automation.buttons`). For d-pad input use `push_dpad()`; to hold buttons and d-pad together use @@ -134,8 +134,6 @@ def push_button(self, buttons: btn.ButtonsArg, hold_ms: int = DEFAULT_HOLD_MS, `delay = hold + release` runs commands back to back, the same convention as the C++ class docs. """ - if repeat < 1: - raise ValueError(f"repeat must be at least 1, got {repeat}.") _check_nonnegative(hold_ms=hold_ms, release_ms=release_ms) self._require_open() parsed = btn.parse_buttons(buttons) @@ -146,13 +144,12 @@ def push_button(self, buttons: btn.ButtonsArg, hold_ms: int = DEFAULT_HOLD_MS, ) if not parsed.has_buttons: raise ValueError("push_button() needs at least one button.") - self._repeat_commands(hold_ms, release_ms, repeat, - lambda delay, hold, release: self._backend.push_button( - delay, hold, release, parsed.bitfield)) + with self._lock: + self._backend.push_button(hold_ms + release_ms, hold_ms, release_ms, parsed.bitfield) def push_dpad(self, position: btn.ButtonsArg, hold_ms: int = DEFAULT_HOLD_MS, - release_ms: int = DEFAULT_RELEASE_MS, repeat: int = 1) -> None: - """Tap a d-pad direction `repeat` times. + release_ms: int = DEFAULT_RELEASE_MS) -> None: + """Tap a d-pad direction. `position`: "up", "up+right" (or "UP_RIGHT"), ["up", "right"], ... For buttons use `push_button()`; to hold buttons and d-pad together use @@ -163,8 +160,6 @@ def push_dpad(self, position: btn.ButtonsArg, hold_ms: int = DEFAULT_HOLD_MS, `PybindSwitchProController::push_dpad()` (SerialPrograms/Source/Integrations/PybindSwitchProController.h). """ - if repeat < 1: - raise ValueError(f"repeat must be at least 1, got {repeat}.") _check_nonnegative(hold_ms=hold_ms, release_ms=release_ms) self._require_open() parsed = btn.parse_buttons(position) @@ -175,9 +170,8 @@ def push_dpad(self, position: btn.ButtonsArg, hold_ms: int = DEFAULT_HOLD_MS, ) if not parsed.has_dpad: raise ValueError("push_dpad() needs at least one d-pad direction.") - self._repeat_commands(hold_ms, release_ms, repeat, - lambda delay, hold, release: self._backend.push_dpad( - delay, hold, release, parsed.dpad)) + with self._lock: + self._backend.push_dpad(hold_ms + release_ms, hold_ms, release_ms, parsed.dpad) def controller_state(self, duration_ms: int = 500, buttons: btn.ButtonsArg = None, *, left: btn.StickArg = None, right: btn.StickArg = None) -> None: @@ -229,13 +223,6 @@ def _push_joystick(self, send, position: btn.StickArg, duration_ms: int, release with self._lock: send(duration_ms + release_ms, duration_ms, release_ms, x, y) - def _repeat_commands(self, hold_ms: int, release_ms: int, repeat: int, send) -> None: - """Queue `send(delay, hold, release)` `repeat` times, back to back.""" - delay = hold_ms + release_ms - with self._lock: - for _ in range(repeat): - send(delay, hold_ms, release_ms) - def wait(self, duration_ms: int) -> None: """Queue a pause of `duration_ms` with nothing pressed.""" _check_nonnegative(duration_ms=duration_ms) diff --git a/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py b/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py index afb51633ac..d5b6ecd986 100644 --- a/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py +++ b/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py @@ -48,13 +48,11 @@ def test_push_button_combined_and_custom_durations(): assert (delay, hold, release) == (250, 200, 50) -def test_push_dpad_repeat(): +def test_push_dpad(): sw, fake = make() - sw.push_dpad("up", repeat=3, hold_ms=100) - args = fake.arguments("push_dpad") - assert len(args) == 3 - for delay, hold, release, position in args: - assert position == DPAD_POSITIONS["UP"] and hold == 100 + sw.push_dpad("up", hold_ms=100) + (delay, hold, release, position), = fake.arguments("push_dpad") + assert position == DPAD_POSITIONS["UP"] and hold == 100 and delay == 100 + release def test_push_button_rejects_dpad(): @@ -137,8 +135,6 @@ def test_validation(): sw, fake = make() with pytest.raises(ValueError): sw.push_button("A", hold_ms=-1) - with pytest.raises(ValueError): - sw.push_button("A", repeat=0) with pytest.raises(ValueError): sw.push_button("Q") with pytest.raises(ValueError): From c0dadd75928925501859aab27690519003fd584e Mon Sep 17 00:00:00 2001 From: jw098 Date: Tue, 20 Oct 2026 13:15:47 -0700 Subject: [PATCH 20/58] add comments --- .../pokemon_automation/buttons.py | 40 ++++++++++++------- .../pokemon_automation/controller.py | 3 +- .../PythonBindings/tests/test_buttons.py | 3 +- 3 files changed, 30 insertions(+), 16 deletions(-) diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py index b712731dd3..a80025ef30 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py @@ -83,8 +83,19 @@ "UP_LEFT": (-1, 1), } -ButtonsArg = str | Sequence[str] | None # both Buttons and D-pad inputs allowed. see the keys for BUTTON_BITS, BUTTON_ALIASES, _DIRECTION_VECTORS above for valid strings +ButtonsArg = str | Sequence[str] | None +""" +ButtonsArg +- accepts both Buttons and D-pad inputs (see above for the exact strings). +- validated by `parse_buttons()` +""" + StickArg = str | Sequence[float] | None +""" +StickArg +- Accepts a direction name ("up", "down_left", "neutral") or an (x, y) pair. +- validated by `parse_stick()` +""" def _normalize_name(name: str) -> str: @@ -141,22 +152,22 @@ def parse_buttons(buttons: ButtonsArg) -> ParsedButtons: Raises ValueError for unknown names or contradictory d-pad directions (e.g. "up+down"). """ - bitfield = 0 - dx = dy = 0 # dx, dy represents the current overall DPAD position. starts neutral + buttonstate_bitfield = 0 + dpad_x = dpad_y = 0 # dpad_x, dpad_y represents the current overall DPAD position. starts neutral seen_dpad: list[str] = [] for raw in _split(buttons): name = raw.strip() key = name.upper() if name in ("+", "-") else _normalize_name(name) key = BUTTON_ALIASES.get(key, key) - if key in BUTTON_BITS: - bitfield |= BUTTON_BITS[key] + if key in BUTTON_BITS: # parse as button + buttonstate_bitfield |= BUTTON_BITS[key] continue - if key in _DIRECTION_VECTORS: + if key in _DIRECTION_VECTORS: # parse as dpad vx, vy = _DIRECTION_VECTORS[key] # vectors of current DPAD being parsed - if (vx and dx and vx != dx) or (vy and dy and vy != dy): + if (vx and dpad_x and vx != dpad_x) or (vy and dpad_y and vy != dpad_y): # check for contradictory dpad directions raise ValueError(f"Contradictory d-pad directions: {seen_dpad + [name]}") - dx = vx or dx - dy = vy or dy + dpad_x = vx or dpad_x # update dpad_x with vx, unless it's 0 + dpad_y = vy or dpad_y # update dpad_y with vy, unless it's 0 seen_dpad.append(name) continue raise ValueError( @@ -164,11 +175,11 @@ def parse_buttons(buttons: ButtonsArg) -> ParsedButtons: f"d-pad: {', '.join(DPAD_POSITIONS)}." ) dpad = DPAD_NONE - if dx or dy: + if dpad_x or dpad_y: for direction, (vx, vy) in _DIRECTION_VECTORS.items(): - if (vx, vy) == (dx, dy): + if (vx, vy) == (dpad_x, dpad_y): dpad = DPAD_POSITIONS[direction] - return ParsedButtons(bitfield, dpad) + return ParsedButtons(buttonstate_bitfield, dpad) def parse_stick(position: StickArg) -> tuple[float, float]: @@ -180,7 +191,7 @@ def parse_stick(position: StickArg) -> tuple[float, float]: """ if position is None: return (0.0, 0.0) - if isinstance(position, str): + if isinstance(position, str): # parse as string key = _normalize_name(position) if key in ("NEUTRAL", "CENTER", "NONE"): return (0.0, 0.0) @@ -191,7 +202,8 @@ def parse_stick(position: StickArg) -> tuple[float, float]: ) vx, vy = _DIRECTION_VECTORS[key] length = math.hypot(vx, vy) - return (vx / length, vy / length) + return (vx / length, vy / length) # normalize to [-1, 1] + # else parse as (x, y) pair values = list(position) if len(values) != 2: raise ValueError(f"A stick position needs exactly two numbers [x, y], got {position!r}.") diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py index b829c54e34..7cd51720c1 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py @@ -33,7 +33,8 @@ # (the C++ issue_buttons()/issue_dpad() take explicit durations). -class ControllerBackend(Protocol): +class ControllerBackend(Protocol): + # Note: This is a Protocol. So, it does't affect runtime at all, it's just to provide type hints """The `_pa_core.Controller` methods used here. `fake.FakeController` implements it too. C++ reference: `_pa_core.Controller` is a pybind defined in PythonBindings_Module.cpp diff --git a/SerialPrograms/Source/PythonBindings/tests/test_buttons.py b/SerialPrograms/Source/PythonBindings/tests/test_buttons.py index a6fc06041e..fcc2984d92 100644 --- a/SerialPrograms/Source/PythonBindings/tests/test_buttons.py +++ b/SerialPrograms/Source/PythonBindings/tests/test_buttons.py @@ -52,7 +52,8 @@ def test_sticks(): def test_matches_cpp_enum(): - # C++ side: `enum Button` / `enum DpadPosition` in + # C++ side: core.BUTTONS and core.DPAD_POSITIONS defined in PythongBindings_Module.cpp + # which are based on `enum Button` / `enum DpadPosition` in # SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerButtons.h, # exposed by the module (SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp). core = pytest.importorskip("pokemon_automation._pa_core") From 8b669080fc683cde59e2167f7ade2b1fa2a3bd81 Mon Sep 17 00:00:00 2001 From: PA Dev Bot <344001113+pa-devbot@users.noreply.github.com> Date: Wed, 21 Oct 2026 15:56:38 +0000 Subject: [PATCH 21/58] Python tests: add a short docstring to every test function --- .../PythonBindings/tests/test_buttons.py | 6 ++++++ .../Source/PythonBindings/tests/test_core.py | 6 ++++++ .../tests/test_fake_controller.py | 20 +++++++++++++++++++ 3 files changed, 32 insertions(+) diff --git a/SerialPrograms/Source/PythonBindings/tests/test_buttons.py b/SerialPrograms/Source/PythonBindings/tests/test_buttons.py index a6fc06041e..493c981e2c 100644 --- a/SerialPrograms/Source/PythonBindings/tests/test_buttons.py +++ b/SerialPrograms/Source/PythonBindings/tests/test_buttons.py @@ -6,6 +6,7 @@ def test_single_and_combined_buttons(): + """Single button names, "+"-joined strings and lists all parse to the right bitfield, with no d-pad set.""" assert btn.parse_buttons("A").bitfield == btn.BUTTON_BITS["A"] both = btn.parse_buttons("L+R") assert both.bitfield == btn.BUTTON_BITS["L"] | btn.BUTTON_BITS["R"] @@ -14,6 +15,7 @@ def test_single_and_combined_buttons(): def test_aliases_and_plus_minus(): + """Aliases (START/SELECT, L3, ...) resolve to their buttons, and a lone "+" or "-" is the PLUS/MINUS button, not a separator.""" assert btn.parse_buttons("+").bitfield == btn.BUTTON_BITS["PLUS"] assert btn.parse_buttons("-").bitfield == btn.BUTTON_BITS["MINUS"] assert btn.parse_buttons("start").bitfield == btn.BUTTON_BITS["PLUS"] @@ -22,6 +24,7 @@ def test_aliases_and_plus_minus(): def test_dpad(): + """D-pad direction names (including diagonals and mixed spellings) map to the right DpadPosition, can be combined with buttons, and None means no d-pad.""" assert btn.parse_buttons("up").dpad == btn.DPAD_POSITIONS["UP"] assert btn.parse_buttons("up+right").dpad == btn.DPAD_POSITIONS["UP_RIGHT"] assert btn.parse_buttons("down-left").dpad == btn.DPAD_POSITIONS["DOWN_LEFT"] @@ -32,6 +35,7 @@ def test_dpad(): def test_invalid_buttons(): + """Unknown button names and contradictory d-pad directions raise ValueError; None parses as no input at all.""" with pytest.raises(ValueError, match="Unknown button"): btn.parse_buttons("Q") with pytest.raises(ValueError, match="Contradictory"): @@ -40,6 +44,7 @@ def test_invalid_buttons(): def test_sticks(): + """parse_stick() maps direction names to unit vectors (diagonals normalized to length 1), passes raw [x, y] pairs through, and rejects out-of-range or unknown values.""" assert btn.parse_stick("up") == (0.0, 1.0) assert btn.parse_stick("neutral") == (0.0, 0.0) x, y = btn.parse_stick("down_right") @@ -52,6 +57,7 @@ def test_sticks(): def test_matches_cpp_enum(): + """The constants in buttons.py still agree with the C++ enums as exposed by the compiled module (skips when it is not built).""" # C++ side: `enum Button` / `enum DpadPosition` in # SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerButtons.h, # exposed by the module (SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp). diff --git a/SerialPrograms/Source/PythonBindings/tests/test_core.py b/SerialPrograms/Source/PythonBindings/tests/test_core.py index 7b39ef9894..0d4856b718 100644 --- a/SerialPrograms/Source/PythonBindings/tests/test_core.py +++ b/SerialPrograms/Source/PythonBindings/tests/test_core.py @@ -13,6 +13,7 @@ def test_buttons_dict(): + """The module's BUTTONS dict matches the C++ Button enum bit positions for a sample of buttons, including third-party controller bits.""" # A sample of the C++ `NintendoSwitch::Button` enum, straight from the module. assert core.BUTTONS["A"] == 1 << 2 assert core.BUTTONS["PLUS"] == 1 << 9 @@ -23,6 +24,7 @@ def test_buttons_dict(): def test_dpad_positions_dict(): + """The module's DPAD_POSITIONS dict matches the C++ DpadPosition enum order (0 = up, clockwise, 8 = none).""" assert core.DPAD_POSITIONS == { "UP": 0, "UP_RIGHT": 1, "RIGHT": 2, "DOWN_RIGHT": 3, "DOWN": 4, "DOWN_LEFT": 5, "LEFT": 6, "UP_LEFT": 7, "NONE": 8, @@ -30,11 +32,13 @@ def test_dpad_positions_dict(): def test_python_constants_match_cpp(): + """The pure-Python constants in buttons.py agree with the C++-generated values in the module.""" from pokemon_automation import buttons as btn btn.check_against_core(dict(core.BUTTONS), dict(core.DPAD_POSITIONS)) def test_log_functions(): + """log() lines are retrievable through recent_logs(), and set_log_file() raises RuntimeError for a path that cannot be opened.""" core.log("hello from python") assert any("hello from python" in line for line in core.recent_logs(10)) with pytest.raises(RuntimeError): @@ -43,6 +47,7 @@ def test_log_functions(): def test_log_file(tmp_path): + """set_log_file() routes log lines to a file on disk (and "" disables it again).""" log_file = tmp_path / "pa_core.log" core.set_log_file(str(log_file)) try: @@ -54,6 +59,7 @@ def test_log_file(tmp_path): def test_unreachable_port(): + """The not-ready path of the C++ Controller: an unreachable port never becomes ready, the status reports the error, commands raise RuntimeError instead of crashing, and wait_for_all_requests()/cancel_all_and_wait() are safe no-ops.""" c = core.Controller("nonexistent-port-xyz") assert not c.wait_for_ready(500) assert not c.is_ready() diff --git a/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py b/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py index d5b6ecd986..9ac2e0b095 100644 --- a/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py +++ b/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py @@ -9,29 +9,34 @@ def make(): + """Create a SwitchController on a fresh FakeController and return both, so tests can inspect the recorded commands.""" fake = FakeController() sw = SwitchController(backend=fake) return sw, fake def test_requires_port_or_backend(): + """Constructing a SwitchController without a port or backend raises ValueError.""" with pytest.raises(ValueError): SwitchController() def test_not_ready_raises(): + """The constructor raises RuntimeError when the backend is not ready within the timeout.""" fake = FakeController(ready=False) with pytest.raises(RuntimeError, match="not ready"): SwitchController(backend=fake, timeout_s=0.1) def test_status_and_name_match_backend(): + """current_status() and controller_name() pass the backend's values through unchanged.""" sw, fake = make() assert sw.current_status() == fake.current_status() assert sw.controller_name() == fake.controller_name() def test_push_button_single_button(): + """Tapping one button issues a backend push_button with the right bitfield and the default 80/80 ms timing.""" sw, fake = make() sw.push_button("A") assert fake.commands() == ["push_button"] @@ -41,6 +46,7 @@ def test_push_button_single_button(): def test_push_button_combined_and_custom_durations(): + """A combination is OR-ed into one bitfield and custom hold/release durations are forwarded, with delay = hold + release.""" sw, fake = make() sw.push_button("L+R", hold_ms=200, release_ms=50) (delay, hold, release, bitfield), = fake.arguments("push_button") @@ -49,6 +55,7 @@ def test_push_button_combined_and_custom_durations(): def test_push_dpad(): + """A d-pad direction is forwarded as push_dpad with the C++ DpadPosition value and the requested timing.""" sw, fake = make() sw.push_dpad("up", hold_ms=100) (delay, hold, release, position), = fake.arguments("push_dpad") @@ -56,6 +63,7 @@ def test_push_dpad(): def test_push_button_rejects_dpad(): + """push_button() rejects d-pad input with a ValueError pointing to push_dpad(), and queues nothing.""" sw, fake = make() with pytest.raises(ValueError, match="push_dpad"): sw.push_button("ZL+up") @@ -65,6 +73,7 @@ def test_push_button_rejects_dpad(): def test_push_dpad_rejects_buttons(): + """push_dpad() rejects button names with a ValueError pointing to push_button(), and queues nothing.""" sw, fake = make() with pytest.raises(ValueError, match="push_button"): sw.push_dpad("ZL+up") @@ -74,6 +83,7 @@ def test_push_dpad_rejects_buttons(): def test_push_button_needs_something(): + """push_button(None) raises ValueError and queues no command.""" sw, fake = make() with pytest.raises(ValueError): sw.push_button(None) @@ -81,6 +91,7 @@ def test_push_button_needs_something(): def test_push_dpad_needs_something(): + """push_dpad(None) raises ValueError and queues no command.""" sw, fake = make() with pytest.raises(ValueError): sw.push_dpad(None) @@ -88,6 +99,7 @@ def test_push_dpad_needs_something(): def test_controller_state_mixed_combination(): + """Buttons and d-pad held together go out as a single controller_state with the right bitfield, d-pad position and neutral sticks.""" sw, fake = make() sw.controller_state(60, buttons="ZL+up") assert fake.commands() == ["controller_state"] @@ -99,6 +111,7 @@ def test_controller_state_mixed_combination(): def test_push_left_joystick(): + """A stick direction name becomes an (x, y) pair, forwarded to push_left_joystick with delay = duration + release.""" sw, fake = make() sw.push_left_joystick("up", duration_ms=1500) (delay, hold, release, x, y), = fake.arguments("push_left_joystick") @@ -106,6 +119,7 @@ def test_push_left_joystick(): def test_push_right_joystick(): + """A raw [x, y] stick position is forwarded to push_right_joystick with the requested duration and release.""" sw, fake = make() sw.push_right_joystick([0.5, -0.5], duration_ms=300, release_ms=100) (delay, hold, release, x, y), = fake.arguments("push_right_joystick") @@ -113,6 +127,7 @@ def test_push_right_joystick(): def test_controller_state_combination(): + """Buttons and both sticks can be held at once via controller_state, with everything not specified left neutral.""" sw, fake = make() sw.controller_state(2000, buttons="B", left="up", right=[1.0, 0.0]) (duration, buttons, dpad, left_x, left_y, right_x, right_y), = fake.arguments("controller_state") @@ -124,6 +139,7 @@ def test_controller_state_combination(): def test_wait(): + """wait() queues a backend wait of the requested length; a zero-length wait is a no-op.""" sw, fake = make() sw.wait(1000) assert fake.arguments("wait") == [(1000,)] @@ -132,6 +148,7 @@ def test_wait(): def test_validation(): + """Negative durations, unknown buttons and contradictory d-pad directions all raise ValueError without queueing anything.""" sw, fake = make() with pytest.raises(ValueError): sw.push_button("A", hold_ms=-1) @@ -143,6 +160,7 @@ def test_validation(): def test_wait_for_all_requests_and_cancel(): + """wait_for_all_requests() forwards to the backend, and cancel_all_and_wait() reports the device's acknowledgement (True, then False when the fake stops confirming) on each call.""" sw, fake = make() sw.wait_for_all_requests() assert sw.cancel_all_and_wait() is True @@ -153,6 +171,7 @@ def test_wait_for_all_requests_and_cancel(): def test_close(): + """close() cancels the queued commands, makes subsequent commands raise, and is idempotent.""" sw, fake = make() sw.close() assert fake.cancel_count == 1 # close() stops the device first @@ -165,6 +184,7 @@ def test_close(): def test_context_manager(): + """The context manager closes the controller on exit; commands after that raise.""" fake = FakeController() with SwitchController(backend=fake) as sw: sw.push_button("A") From c0ccd7457da12a759bf848014cbe1a01f52cba4a Mon Sep 17 00:00:00 2001 From: jw098 Date: Wed, 21 Oct 2026 09:03:10 -0700 Subject: [PATCH 22/58] add comments --- .../Source/PythonBindings/pokemon_automation/devices.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/devices.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/devices.py index b695bca1e3..27de41491b 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/devices.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/devices.py @@ -30,7 +30,7 @@ def list_serial_ports() -> list[str]: ports = [f"COM{i}" for i in range(1, 64)] if sys.platform == "darwin": ports = [p for p in ports if not p.startswith("/dev/tty.")] - ports = [p for p in ports if not any(w in p.lower() for w in _IGNORED_PORT_WORDS)] + ports = [p for p in ports if not any(w in p.lower() for w in _IGNORED_PORT_WORDS)] # filter out devices contained within _IGNORED_PORT_WORDS # USB-serial adapters first. ports.sort(key=lambda p: (not any(w in p.lower() for w in ("usb", "uart", "acm", "com")), p)) return ports From 8f6d5150c8b86b26dfaddd875fe7eae97905bdb8 Mon Sep 17 00:00:00 2001 From: jw098 Date: Wed, 21 Oct 2026 09:27:30 -0700 Subject: [PATCH 23/58] update comments --- .../Source/PythonBindings/tests/test_buttons.py | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/SerialPrograms/Source/PythonBindings/tests/test_buttons.py b/SerialPrograms/Source/PythonBindings/tests/test_buttons.py index e594e57b41..c8e24a59a2 100644 --- a/SerialPrograms/Source/PythonBindings/tests/test_buttons.py +++ b/SerialPrograms/Source/PythonBindings/tests/test_buttons.py @@ -6,7 +6,9 @@ def test_single_and_combined_buttons(): - """Single button names, "+"-joined strings and lists all parse to the right bitfield, with no d-pad set.""" + """tests parse_buttons(): + Ensures that single button names, "+"-joined strings and lists all parse to the right bitfield, with no d-pad set. + """ assert btn.parse_buttons("A").bitfield == btn.BUTTON_BITS["A"] both = btn.parse_buttons("L+R") assert both.bitfield == btn.BUTTON_BITS["L"] | btn.BUTTON_BITS["R"] @@ -15,7 +17,9 @@ def test_single_and_combined_buttons(): def test_aliases_and_plus_minus(): - """Aliases (START/SELECT, L3, ...) resolve to their buttons, and a lone "+" or "-" is the PLUS/MINUS button, not a separator.""" + """tests parse_buttons(): + Aliases (START/SELECT, L3, ...) resolve to their buttons, and a lone "+" or "-" is the PLUS/MINUS button, not a separator. + """ assert btn.parse_buttons("+").bitfield == btn.BUTTON_BITS["PLUS"] assert btn.parse_buttons("-").bitfield == btn.BUTTON_BITS["MINUS"] assert btn.parse_buttons("start").bitfield == btn.BUTTON_BITS["PLUS"] @@ -24,7 +28,9 @@ def test_aliases_and_plus_minus(): def test_dpad(): - """D-pad direction names (including diagonals and mixed spellings) map to the right DpadPosition, can be combined with buttons, and None means no d-pad.""" + """tests parse_buttons(): + D-pad direction names (including diagonals and mixed spellings) map to the right DpadPosition, can be combined with buttons, and None means no d-pad. + """ assert btn.parse_buttons("up").dpad == btn.DPAD_POSITIONS["UP"] assert btn.parse_buttons("up+right").dpad == btn.DPAD_POSITIONS["UP_RIGHT"] assert btn.parse_buttons("down-left").dpad == btn.DPAD_POSITIONS["DOWN_LEFT"] @@ -35,7 +41,9 @@ def test_dpad(): def test_invalid_buttons(): - """Unknown button names and contradictory d-pad directions raise ValueError; None parses as no input at all.""" + """tests parse_buttons(): + Unknown button names and contradictory d-pad directions raise ValueError; None parses as no input at all. + """ with pytest.raises(ValueError, match="Unknown button"): btn.parse_buttons("Q") with pytest.raises(ValueError, match="Contradictory"): From 74385b8ba48c618e468f9912903079dd6b7dd8a1 Mon Sep 17 00:00:00 2001 From: PA Dev Bot <344001113+pa-devbot@users.noreply.github.com> Date: Wed, 21 Oct 2026 16:29:39 +0000 Subject: [PATCH 24/58] Python tests: drop test_matches_cpp_enum, duplicate of test_python_constants_match_cpp Both tests just call buttons.check_against_core() with the module's BUTTONS/DPAD_POSITIONS dicts. Keep the one in test_core.py (the compiled-module file, skipped wholesale when _pa_core is not built). --- .../Source/PythonBindings/tests/test_buttons.py | 9 --------- 1 file changed, 9 deletions(-) diff --git a/SerialPrograms/Source/PythonBindings/tests/test_buttons.py b/SerialPrograms/Source/PythonBindings/tests/test_buttons.py index c8e24a59a2..74dea5c833 100644 --- a/SerialPrograms/Source/PythonBindings/tests/test_buttons.py +++ b/SerialPrograms/Source/PythonBindings/tests/test_buttons.py @@ -63,12 +63,3 @@ def test_sticks(): with pytest.raises(ValueError): btn.parse_stick("sideways") - -def test_matches_cpp_enum(): - """The constants in buttons.py still agree with the C++ enums as exposed by the compiled module (skips when it is not built).""" - # C++ side: core.BUTTONS and core.DPAD_POSITIONS defined in PythongBindings_Module.cpp - # which are based on `enum Button` / `enum DpadPosition` in - # SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerButtons.h, - # exposed by the module (SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp). - core = pytest.importorskip("pokemon_automation._pa_core") - btn.check_against_core(dict(core.BUTTONS), dict(core.DPAD_POSITIONS)) From 48841174acd8dd80c7bee2eb069e8ecd9b96c087 Mon Sep 17 00:00:00 2001 From: jw098 Date: Wed, 21 Oct 2026 10:08:57 -0700 Subject: [PATCH 25/58] add comments --- SerialPrograms/Source/PythonBindings/tests/test_core.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/SerialPrograms/Source/PythonBindings/tests/test_core.py b/SerialPrograms/Source/PythonBindings/tests/test_core.py index 0d4856b718..9e0ea06c45 100644 --- a/SerialPrograms/Source/PythonBindings/tests/test_core.py +++ b/SerialPrograms/Source/PythonBindings/tests/test_core.py @@ -13,7 +13,9 @@ def test_buttons_dict(): - """The module's BUTTONS dict matches the C++ Button enum bit positions for a sample of buttons, including third-party controller bits.""" + """The module's BUTTONS dict matches the C++ Button enum bit positions for a sample of buttons, including third-party controller bits. + It checks the module against hardcoded protocol values (e.g. A == 1<<2, PLUS == 1<<9) + """ # A sample of the C++ `NintendoSwitch::Button` enum, straight from the module. assert core.BUTTONS["A"] == 1 << 2 assert core.BUTTONS["PLUS"] == 1 << 9 @@ -24,7 +26,9 @@ def test_buttons_dict(): def test_dpad_positions_dict(): - """The module's DPAD_POSITIONS dict matches the C++ DpadPosition enum order (0 = up, clockwise, 8 = none).""" + """The module's DPAD_POSITIONS dict matches the C++ DpadPosition enum order (0 = up, clockwise, 8 = none). + It checks the module against hardcoded protocol values. + """ assert core.DPAD_POSITIONS == { "UP": 0, "UP_RIGHT": 1, "RIGHT": 2, "DOWN_RIGHT": 3, "DOWN": 4, "DOWN_LEFT": 5, "LEFT": 6, "UP_LEFT": 7, "NONE": 8, From d23186563bef32bb3d4172acbb9f8cefd70a80a7 Mon Sep 17 00:00:00 2001 From: jw098 Date: Wed, 21 Oct 2026 13:00:18 -0700 Subject: [PATCH 26/58] rename variables --- .../Integrations/PybindSwitchController.cpp | 48 +++++++++---------- .../Integrations/PybindSwitchController.h | 26 +++++----- .../PythonBindings/PythonBindings_Module.cpp | 12 ++--- .../pokemon_automation/controller.py | 26 +++++----- .../switch_connection_test.py | 5 +- .../tests/test_fake_controller.py | 4 +- 6 files changed, 61 insertions(+), 60 deletions(-) diff --git a/SerialPrograms/Source/Integrations/PybindSwitchController.cpp b/SerialPrograms/Source/Integrations/PybindSwitchController.cpp index 2e2ccf5b2b..174cc2c524 100644 --- a/SerialPrograms/Source/Integrations/PybindSwitchController.cpp +++ b/SerialPrograms/Source/Integrations/PybindSwitchController.cpp @@ -36,9 +36,9 @@ class PybindSwitchProControllerInternal final : public ControllerConnection::Sta m_connection->remove_status_listener(*this); } - bool wait_for_ready(uint64_t timeout_millis){ + bool wait_for_ready(uint64_t timeout_ms){ std::unique_lock lg(m_lock); - m_cv.wait_for(lg, Milliseconds(timeout_millis), [this]{ + m_cv.wait_for(lg, Milliseconds(timeout_ms), [this]{ return m_connected; }); return controller_if_ready() != nullptr; @@ -116,9 +116,9 @@ PybindSwitchProController::~PybindSwitchProController(){ delete (PybindSwitchProControllerInternal*)m_internals; } -bool PybindSwitchProController::wait_for_ready(uint64_t timeout_millis){ +bool PybindSwitchProController::wait_for_ready(uint64_t timeout_ms){ PybindSwitchProControllerInternal* internal = (PybindSwitchProControllerInternal*)m_internals; - return internal->wait_for_ready(timeout_millis); + return internal->wait_for_ready(timeout_ms); } bool PybindSwitchProController::is_ready() const{ @@ -145,56 +145,56 @@ void PybindSwitchProController::wait_for_all_requests(){ } controller->wait_for_all(nullptr); } -bool PybindSwitchProController::cancel_all_and_wait(uint64_t timeout_millis){ +bool PybindSwitchProController::cancel_all_and_wait(uint64_t timeout_ms){ PybindSwitchProControllerInternal* internal = (PybindSwitchProControllerInternal*)m_internals; ProController* controller = internal->controller_if_ready(); if (controller == nullptr){ internal->m_logger.log("Controller is not ready.", COLOR_RED); return false; } - return controller->cancel_all_and_wait(Milliseconds(timeout_millis)); + return controller->cancel_all_and_wait(Milliseconds(timeout_ms)); } void PybindSwitchProController::wait(uint64_t duration){ PybindSwitchProControllerInternal* internal = (PybindSwitchProControllerInternal*)m_internals; internal->controller().issue_nop(nullptr, Milliseconds(duration)); } -void PybindSwitchProController::push_button(uint64_t delay, uint64_t hold, uint64_t release, uint32_t bitfield){ +void PybindSwitchProController::push_button(uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms, uint32_t button_bitfield){ PybindSwitchProControllerInternal* internal = (PybindSwitchProControllerInternal*)m_internals; internal->controller().issue_buttons( nullptr, - Milliseconds(delay), - Milliseconds(hold), - Milliseconds(release), - (Button)bitfield + Milliseconds(delay_ms), + Milliseconds(hold_ms), + Milliseconds(release_ms), + (Button)button_bitfield ); } -void PybindSwitchProController::push_dpad(uint64_t delay, uint64_t hold, uint64_t release, uint8_t position){ +void PybindSwitchProController::push_dpad(uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms, uint8_t dpad_position){ PybindSwitchProControllerInternal* internal = (PybindSwitchProControllerInternal*)m_internals; internal->controller().issue_dpad( nullptr, - Milliseconds(delay), - Milliseconds(hold), - Milliseconds(release), - (DpadPosition)position + Milliseconds(delay_ms), + Milliseconds(hold_ms), + Milliseconds(release_ms), + (DpadPosition)dpad_position ); } -void PybindSwitchProController::push_left_joystick(uint64_t delay, uint64_t hold, uint64_t release, double x, double y){ +void PybindSwitchProController::push_left_joystick(uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms, double x, double y){ PybindSwitchProControllerInternal* internal = (PybindSwitchProControllerInternal*)m_internals; internal->controller().issue_left_joystick( nullptr, - Milliseconds(delay), - Milliseconds(hold), - Milliseconds(release), + Milliseconds(delay_ms), + Milliseconds(hold_ms), + Milliseconds(release_ms), {x, y} ); } -void PybindSwitchProController::push_right_joystick(uint64_t delay, uint64_t hold, uint64_t release, double x, double y){ +void PybindSwitchProController::push_right_joystick(uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms, double x, double y){ PybindSwitchProControllerInternal* internal = (PybindSwitchProControllerInternal*)m_internals; internal->controller().issue_right_joystick( nullptr, - Milliseconds(delay), - Milliseconds(hold), - Milliseconds(release), + Milliseconds(delay_ms), + Milliseconds(hold_ms), + Milliseconds(release_ms), {x, y} ); } diff --git a/SerialPrograms/Source/Integrations/PybindSwitchController.h b/SerialPrograms/Source/Integrations/PybindSwitchController.h index 45a7d6e128..04ae2230ef 100644 --- a/SerialPrograms/Source/Integrations/PybindSwitchController.h +++ b/SerialPrograms/Source/Integrations/PybindSwitchController.h @@ -52,9 +52,9 @@ class PybindSwitchProController{ ~PybindSwitchProController(); // Block until the device handshake finishes and a Switch controller has been - // created, or `timeout_millis` passes. + // created, or `timeout_ms` passes. // Returns true if the controller is ready to receive commands. - bool wait_for_ready(uint64_t timeout_millis); + bool wait_for_ready(uint64_t timeout_ms); bool is_ready() const; @@ -71,13 +71,13 @@ class PybindSwitchProController{ void wait_for_all_requests(); // Drop every queued command that has not executed yet, return to the neutral - // state (no buttons pressed, sticks centered), and wait at most `timeout_millis` + // state (no buttons pressed, sticks centered), and wait at most `timeout_ms` // for the device to acknowledge that it received the cancel. // // Returns true if acknowledged, false on timeout or if the controller is not ready. // Commands pushed from other threads while this is running may land after the // cancel and are not cancelled. - bool cancel_all_and_wait(uint64_t timeout_millis); + bool cancel_all_and_wait(uint64_t timeout_ms); public: // Commands. These throw InvalidConnectionStateException if the controller is not @@ -93,35 +93,35 @@ class PybindSwitchProController{ // duration: wait duration, milliseconds. // If the controller is not ready, it throws InvalidConnectionStateException. // The function will block only if the device's command queue is full. - void wait(uint64_t duration); + void wait(uint64_t duration_ms); // Send a button press command to the controller. It will press all buttons in - // `bitfield` simultaneously. D-pad buttons are excluded and should be called via + // `button_bitfield` simultaneously. D-pad buttons are excluded and should be called via // `push_dpad()`. // delay: how long to wait before the next command may start. // hold: how long the button press is held, milliseconds. // release: how long the buttons stay released before the same button can be used again, // milliseconds. - // bitfield: values from `NintendoSwitch::Button`. + // button_bitfield: values from `NintendoSwitch::Button`. // // `delay = hold + release` runs commands back to back like `pbf_press_button()`; // `delay < hold` overlaps commands, e.g. to hold a button while moving a stick. // If the controller is not ready, it throws InvalidConnectionStateException. // The function will block only if the device's command queue is full. - void push_button(uint64_t delay, uint64_t hold, uint64_t release, uint32_t bitfield); + void push_button(uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms, uint32_t button_bitfield); // Send a D-pad press command to the controller. It will press one or two D-pad buttons to // indicate a direction to the game. // delay: how long to wait before the next command may start. // hold: how long the button press is held, milliseconds. // release: how long the buttons stay released before the same button can be used again, // milliseconds. - // position: `NintendoSwitch::DpadPosition` values (0 = up, clockwise to 7 = up-left, 8 = none). + // dpad_position: `NintendoSwitch::DpadPosition` values (0 = up, clockwise to 7 = up-left, 8 = none). // // `delay = hold + release` runs commands back to back like `pbf_press_button()`; // `delay < hold` overlaps commands, e.g. to hold a button while moving a stick. // If the controller is not ready, it throws InvalidConnectionStateException. // The function will block only if the device's command queue is full. - void push_dpad(uint64_t delay, uint64_t hold, uint64_t release, uint8_t position); + void push_dpad(uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms, uint8_t dpad_position); // Send a left joystick push command to the controller. // delay: how long to wait before the next command may start. // hold: how long the joystick is pushed, milliseconds. @@ -133,7 +133,7 @@ class PybindSwitchProController{ // `delay < hold` overlaps commands, e.g. to hold a button while moving a stick. // If the controller is not ready, it throws InvalidConnectionStateException. // The function will block only if the device's command queue is full. - void push_left_joystick(uint64_t delay, uint64_t hold, uint64_t release, double x, double y); + void push_left_joystick(uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms, double x, double y); // Send a right joystick push command to the controller. // delay: how long to wait before the next command may start. // hold: how long the joystick is pushed, milliseconds. @@ -145,7 +145,7 @@ class PybindSwitchProController{ // `delay < hold` overlaps commands, e.g. to hold a button while moving a stick. // If the controller is not ready, it throws InvalidConnectionStateException. // The function will block only if the device's command queue is full. - void push_right_joystick(uint64_t delay, uint64_t hold, uint64_t release, double x, double y); + void push_right_joystick(uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms, double x, double y); // Set the entire controller state at once and hold it for `duration`. // Everything not specified is released. This is the most direct way to hold @@ -156,7 +156,7 @@ class PybindSwitchProController{ // left_x, left_y: in [-1.0, 1.0] with +x = right and +y = up. // right_x, right_y: in [-1.0, 1.0] with +x = right and +y = up. void controller_state( - uint64_t duration, + uint64_t duration_ms, uint32_t button_bitfield, uint8_t dpad_position, double left_x, double left_y, diff --git a/SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp b/SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp index 7a4785720f..347d14620b 100644 --- a/SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp +++ b/SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp @@ -232,15 +232,15 @@ PYBIND11_MODULE(_pa_core, m){ "Queue a pause of `duration_ms` with nothing pressed.", py::call_guard()) .def("push_button", &PybindSwitchProController::push_button, - py::arg("delay_ms"), py::arg("hold_ms"), py::arg("release_ms"), py::arg("bitfield"), - "Queue a press of every button in `bitfield` (see `BUTTONS`). `delay_ms` is " + py::arg("delay_ms"), py::arg("hold_ms"), py::arg("release_ms"), py::arg("button_bitfield"), + "Queue a press of every button in `button_bitfield` (see `BUTTONS`). `delay_ms` is " "how long to wait before the press may start, `hold_ms` how long the buttons " "stay down, `release_ms` how long they stay up before the same button can be " - "pressed again. D-pad directions are not part of `bitfield`; use push_dpad().", + "pressed again. D-pad directions are not part of `button_bitfield`; use push_dpad().", py::call_guard()) .def("push_dpad", &PybindSwitchProController::push_dpad, - py::arg("delay_ms"), py::arg("hold_ms"), py::arg("release_ms"), py::arg("position"), - "Queue a d-pad press in direction `position` (see `DPAD_POSITIONS`). " + py::arg("delay_ms"), py::arg("hold_ms"), py::arg("release_ms"), py::arg("dpad_position"), + "Queue a d-pad press in direction `dpad_position` (see `DPAD_POSITIONS`). " "`delay_ms` / `hold_ms` / `release_ms` have the same meaning as in push_button().", py::call_guard()) .def("push_left_joystick", &PybindSwitchProController::push_left_joystick, @@ -254,7 +254,7 @@ PYBIND11_MODULE(_pa_core, m){ "and +y = up. `delay_ms` / `hold_ms` / `release_ms` have the same meaning as in push_button().", py::call_guard()) .def("controller_state", &PybindSwitchProController::controller_state, - py::arg("duration_ms"), py::arg("buttons"), py::arg("dpad"), + py::arg("duration_ms"), py::arg("button_bitfield"), py::arg("dpad_position"), py::arg("left_x"), py::arg("left_y"), py::arg("right_x"), py::arg("right_y"), "Queue the entire controller state (buttons, d-pad, both sticks) being held " "for `duration_ms`; everything not specified is released. This is the most " diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py index 7cd51720c1..46d51ff0f3 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py @@ -15,7 +15,7 @@ sw.push_button("A") # tap A sw.push_button("L+R", hold_ms=200) # press L and R together sw.push_dpad("up") # d-pad up - sw.push_left_joystick("up", duration_ms=1500) # walk forward + sw.push_left_joystick("up", hold_ms=1500) # walk forward sw.controller_state(2000, buttons="B", left="up") # run forward sw.wait_for_all_requests() """ @@ -51,12 +51,12 @@ def controller_name(self) -> str: ... def wait_for_all_requests(self) -> None: ... def cancel_all_and_wait(self, timeout_ms: int = ...) -> bool: ... def wait(self, duration_ms: int) -> None: ... - def push_button(self, delay_ms: int, hold_ms: int, release_ms: int, bitfield: int) -> None: ... - def push_dpad(self, delay_ms: int, hold_ms: int, release_ms: int, position: int) -> None: ... + def push_button(self, delay_ms: int, hold_ms: int, release_ms: int, button_bitfield: int) -> None: ... + def push_dpad(self, delay_ms: int, hold_ms: int, release_ms: int, dpad_position: int) -> None: ... def push_left_joystick(self, delay_ms: int, hold_ms: int, release_ms: int, x: float, y: float) -> None: ... def push_right_joystick(self, delay_ms: int, hold_ms: int, release_ms: int, x: float, y: float) -> None: ... def controller_state( - self, duration_ms: int, buttons: int, dpad: int, + self, duration_ms: int, button_bitfield: int, dpad_position: int, left_x: float, left_y: float, right_x: float, right_y: float, ) -> None: ... @@ -197,32 +197,32 @@ def controller_state(self, duration_ms: int = 500, buttons: btn.ButtonsArg = Non left_x, left_y, right_x, right_y ) - def push_left_joystick(self, position: btn.StickArg, duration_ms: int = 500, + def push_left_joystick(self, position: btn.StickArg, hold_ms: int = 500, release_ms: int = 0) -> None: - """Tilt the left stick to `position` for `duration_ms`. + """Tilt the left stick to `position` for `hold_ms`. C++: `AbstractController::issue_left_joystick()` (SerialPrograms/Source/Controllers/Controller.h), via `PybindSwitchProController::push_left_joystick()`. """ - self._push_joystick(self._backend.push_left_joystick, position, duration_ms, release_ms) + self._push_joystick(self._backend.push_left_joystick, position, hold_ms, release_ms) - def push_right_joystick(self, position: btn.StickArg, duration_ms: int = 500, + def push_right_joystick(self, position: btn.StickArg, hold_ms: int = 500, release_ms: int = 0) -> None: - """Tilt the right stick to `position` for `duration_ms`. + """Tilt the right stick to `position` for `hold_ms`. C++: `AbstractController::issue_right_joystick()` (SerialPrograms/Source/Controllers/Controller.h), via `PybindSwitchProController::push_right_joystick()`. """ - self._push_joystick(self._backend.push_right_joystick, position, duration_ms, release_ms) + self._push_joystick(self._backend.push_right_joystick, position, hold_ms, release_ms) - def _push_joystick(self, send, position: btn.StickArg, duration_ms: int, release_ms: int) -> None: - _check_nonnegative(duration_ms=duration_ms, release_ms=release_ms) + def _push_joystick(self, send, position: btn.StickArg, hold_ms: int, release_ms: int) -> None: + _check_nonnegative(hold_ms=hold_ms, release_ms=release_ms) self._require_open() x, y = btn.parse_stick(position) with self._lock: - send(duration_ms + release_ms, duration_ms, release_ms, x, y) + send(hold_ms + release_ms, hold_ms, release_ms, x, y) def wait(self, duration_ms: int) -> None: """Queue a pause of `duration_ms` with nothing pressed.""" diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py index bc5183b7ff..43c6a79be0 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py @@ -29,8 +29,9 @@ def try_port(port: str) -> bool: sw.push_dpad("right", hold_ms=100) sw.push_dpad("left", hold_ms=100) sw.push_dpad("left", hold_ms=100) - sw.push_right_joystick([1, 0], duration_ms=2000) - sw.push_right_joystick([-1, 0], duration_ms=2000) + sw.push_right_joystick([1, 0], hold_ms=2000) # hold the right joystick to the right + sw.push_right_joystick([-1, 0], hold_ms=2000) # hold the right joystick to the left + sw.controller_state(duration_ms=2000, buttons="B", left="up") # hold B, while pushing up the left joystick sw.wait(500) sw.wait_for_all_requests() print(" cancel confirmed:", sw.cancel_all_and_wait(500)) diff --git a/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py b/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py index 9ac2e0b095..6123cae584 100644 --- a/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py +++ b/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py @@ -113,7 +113,7 @@ def test_controller_state_mixed_combination(): def test_push_left_joystick(): """A stick direction name becomes an (x, y) pair, forwarded to push_left_joystick with delay = duration + release.""" sw, fake = make() - sw.push_left_joystick("up", duration_ms=1500) + sw.push_left_joystick("up", hold_ms=1500) (delay, hold, release, x, y), = fake.arguments("push_left_joystick") assert (x, y) == (0.0, 1.0) and hold == 1500 and delay == 1500 + release @@ -121,7 +121,7 @@ def test_push_left_joystick(): def test_push_right_joystick(): """A raw [x, y] stick position is forwarded to push_right_joystick with the requested duration and release.""" sw, fake = make() - sw.push_right_joystick([0.5, -0.5], duration_ms=300, release_ms=100) + sw.push_right_joystick([0.5, -0.5], hold_ms=300, release_ms=100) (delay, hold, release, x, y), = fake.arguments("push_right_joystick") assert (x, y) == (0.5, -0.5) and delay == 400 From d8913a312acf70e203b16d1dbf1e19a85a6a7f85 Mon Sep 17 00:00:00 2001 From: PA Dev Bot <344001113+pa-devbot@users.noreply.github.com> Date: Wed, 21 Oct 2026 20:32:09 +0000 Subject: [PATCH 27/58] Python: follow the duration_ms/hold_ms/bitfield renames through all call sites Two call sites still used the old push_left_joystick(duration_ms=...) keyword, which now raises TypeError: - the quick start in pokemon_automation/__init__.py - the example in the README Also rename the FakeController parameters to the new backend names (button_bitfield, dpad_position) so it matches the ControllerBackend protocol, and fix two stale 'delay = duration + release' docstrings in test_fake_controller.py. --- SerialPrograms/Source/PythonBindings/README.md | 2 +- .../PythonBindings/pokemon_automation/__init__.py | 2 +- .../PythonBindings/pokemon_automation/fake.py | 14 +++++++------- .../PythonBindings/tests/test_fake_controller.py | 4 ++-- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/SerialPrograms/Source/PythonBindings/README.md b/SerialPrograms/Source/PythonBindings/README.md index 173d757c8f..b53dbb24c4 100644 --- a/SerialPrograms/Source/PythonBindings/README.md +++ b/SerialPrograms/Source/PythonBindings/README.md @@ -104,7 +104,7 @@ with SwitchController("/dev/ttyACM0") as sw: # connects to the Switch via port sw.push_button("A") # tap A (80 ms hold, 80 ms release) sw.push_button("L+R", hold_ms=200) # press L and R together sw.push_dpad("up") # d-pad up - sw.push_left_joystick("up", duration_ms=1500) # walk forward + sw.push_left_joystick("up", hold_ms=1500) # walk forward sw.controller_state(2000, buttons="B", left="up") # run forward sw.wait(300) sw.wait_for_all_requests() # block until the device executed everything diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py index 5a0bfc805a..2f6371c256 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py @@ -19,7 +19,7 @@ with SwitchController("/dev/cu.usbserial-0001") as sw: sw.push_button("A") sw.push_dpad("up+right") - sw.push_left_joystick("up", duration_ms=1500) + sw.push_left_joystick("up", hold_ms=1500) sw.wait_for_all_requests() """ diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/fake.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/fake.py index 3e40719538..e261af9b03 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/fake.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/fake.py @@ -61,11 +61,11 @@ def _record(self, name: str, *args: Any) -> None: def wait(self, duration_ms: int) -> None: self._record("wait", duration_ms) - def push_button(self, delay_ms: int, hold_ms: int, release_ms: int, bitfield: int) -> None: - self._record("push_button", delay_ms, hold_ms, release_ms, bitfield) + def push_button(self, delay_ms: int, hold_ms: int, release_ms: int, button_bitfield: int) -> None: + self._record("push_button", delay_ms, hold_ms, release_ms, button_bitfield) - def push_dpad(self, delay_ms: int, hold_ms: int, release_ms: int, position: int) -> None: - self._record("push_dpad", delay_ms, hold_ms, release_ms, position) + def push_dpad(self, delay_ms: int, hold_ms: int, release_ms: int, dpad_position: int) -> None: + self._record("push_dpad", delay_ms, hold_ms, release_ms, dpad_position) def push_left_joystick(self, delay_ms: int, hold_ms: int, release_ms: int, x: float, y: float) -> None: self._record("push_left_joystick", delay_ms, hold_ms, release_ms, x, y) @@ -76,14 +76,14 @@ def push_right_joystick(self, delay_ms: int, hold_ms: int, release_ms: int, x: f def controller_state( self, duration_ms: int, - buttons: int, - dpad: int, + button_bitfield: int, + dpad_position: int, left_x: float, left_y: float, right_x: float, right_y: float, ) -> None: - self._record("controller_state", duration_ms, buttons, dpad, left_x, left_y, right_x, right_y) + self._record("controller_state", duration_ms, button_bitfield, dpad_position, left_x, left_y, right_x, right_y) # -- test helpers --------------------------------------------------------- diff --git a/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py b/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py index 6123cae584..343f9f0b30 100644 --- a/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py +++ b/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py @@ -111,7 +111,7 @@ def test_controller_state_mixed_combination(): def test_push_left_joystick(): - """A stick direction name becomes an (x, y) pair, forwarded to push_left_joystick with delay = duration + release.""" + """A stick direction name becomes an (x, y) pair, forwarded to push_left_joystick with delay = hold + release.""" sw, fake = make() sw.push_left_joystick("up", hold_ms=1500) (delay, hold, release, x, y), = fake.arguments("push_left_joystick") @@ -119,7 +119,7 @@ def test_push_left_joystick(): def test_push_right_joystick(): - """A raw [x, y] stick position is forwarded to push_right_joystick with the requested duration and release.""" + """A raw [x, y] stick position is forwarded to push_right_joystick with the requested hold and release.""" sw, fake = make() sw.push_right_joystick([0.5, -0.5], hold_ms=300, release_ms=100) (delay, hold, release, x, y), = fake.arguments("push_right_joystick") From f7d16c441cd4c7782b7909c89f42cbba8bc9ff56 Mon Sep 17 00:00:00 2001 From: PA Dev Bot <344001113+pa-devbot@users.noreply.github.com> Date: Wed, 21 Oct 2026 21:41:49 +0000 Subject: [PATCH 28/58] Align pybind/Python controller API with the PBF API Argument order now matches NintendoSwitch_Commands_PushButtons.h (input first, then timing, no context parameter): - push_button(button_bitfield, delay_ms, hold_ms, release_ms) - push_dpad(dpad_position, delay_ms, hold_ms, release_ms) - push_left_joystick(joystick_position, delay_ms, hold_ms, release_ms) - push_right_joystick(joystick_position, delay_ms, hold_ms, release_ms) - controller_state(button_bitfield, dpad_position, left_x, left_y, right_x, right_y, duration_ms) (duration last, like pbf_controller_state) The pybind controller keeps delay_ms (pbf_*() always uses delay = hold + release; that combination is what the Python layer queues). The joysticks take a single (x, y) joystick_position tuple instead of separate x/y arguments, and the Python push_left_joystick()/push_right_joystick() only accept coordinates (parse_stick_position(), no direction-name strings); parse_stick() keeps string support for controller_state()'s left/right. --- .../Source/CommandLine/CommandLine_Main.cpp | 2 +- .../Integrations/PybindSwitchController.cpp | 29 ++-- .../Integrations/PybindSwitchController.h | 147 +++++++++--------- .../DevPrograms/TestProgramComputer.cpp | 2 +- .../DevPrograms/TestProgramSwitch.cpp | 2 +- .../PythonBindings/PythonBindings_Module.cpp | 46 +++--- .../Source/PythonBindings/README.md | 4 +- .../pokemon_automation/__init__.py | 4 +- .../pokemon_automation/buttons.py | 39 ++++- .../pokemon_automation/controller.py | 66 ++++---- .../PythonBindings/pokemon_automation/fake.py | 20 +-- .../Source/PythonBindings/tests/test_core.py | 2 +- .../tests/test_fake_controller.py | 38 +++-- 13 files changed, 233 insertions(+), 168 deletions(-) diff --git a/SerialPrograms/Source/CommandLine/CommandLine_Main.cpp b/SerialPrograms/Source/CommandLine/CommandLine_Main.cpp index b94f5ecc39..9a576e21c1 100644 --- a/SerialPrograms/Source/CommandLine/CommandLine_Main.cpp +++ b/SerialPrograms/Source/CommandLine/CommandLine_Main.cpp @@ -87,7 +87,7 @@ int main(int argc, char* argv[]){ for (int i = 0; i < 30; i++){ // Push A button: delay=0ms, hold=50ms, release=50ms, button=BUTTON_A - controller.push_button(0, 50, 50, static_cast(BUTTON_A)); + controller.push_button(static_cast(BUTTON_A), 0, 50, 50); } // Wait for all button commands to complete diff --git a/SerialPrograms/Source/Integrations/PybindSwitchController.cpp b/SerialPrograms/Source/Integrations/PybindSwitchController.cpp index 174cc2c524..b3d2ea87ff 100644 --- a/SerialPrograms/Source/Integrations/PybindSwitchController.cpp +++ b/SerialPrograms/Source/Integrations/PybindSwitchController.cpp @@ -154,11 +154,11 @@ bool PybindSwitchProController::cancel_all_and_wait(uint64_t timeout_ms){ } return controller->cancel_all_and_wait(Milliseconds(timeout_ms)); } -void PybindSwitchProController::wait(uint64_t duration){ +void PybindSwitchProController::wait(uint64_t duration_ms){ PybindSwitchProControllerInternal* internal = (PybindSwitchProControllerInternal*)m_internals; - internal->controller().issue_nop(nullptr, Milliseconds(duration)); + internal->controller().issue_nop(nullptr, Milliseconds(duration_ms)); } -void PybindSwitchProController::push_button(uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms, uint32_t button_bitfield){ +void PybindSwitchProController::push_button(uint32_t button_bitfield, uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms){ PybindSwitchProControllerInternal* internal = (PybindSwitchProControllerInternal*)m_internals; internal->controller().issue_buttons( nullptr, @@ -168,7 +168,7 @@ void PybindSwitchProController::push_button(uint64_t delay_ms, uint64_t hold_ms, (Button)button_bitfield ); } -void PybindSwitchProController::push_dpad(uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms, uint8_t dpad_position){ +void PybindSwitchProController::push_dpad(uint8_t dpad_position, uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms){ PybindSwitchProControllerInternal* internal = (PybindSwitchProControllerInternal*)m_internals; internal->controller().issue_dpad( nullptr, @@ -178,38 +178,45 @@ void PybindSwitchProController::push_dpad(uint64_t delay_ms, uint64_t hold_ms, u (DpadPosition)dpad_position ); } -void PybindSwitchProController::push_left_joystick(uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms, double x, double y){ +void PybindSwitchProController::push_left_joystick( + const std::tuple& joystick_position, + uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms +){ PybindSwitchProControllerInternal* internal = (PybindSwitchProControllerInternal*)m_internals; internal->controller().issue_left_joystick( nullptr, Milliseconds(delay_ms), Milliseconds(hold_ms), Milliseconds(release_ms), - {x, y} + JoystickPosition(std::get<0>(joystick_position), std::get<1>(joystick_position)) ); } -void PybindSwitchProController::push_right_joystick(uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms, double x, double y){ +void PybindSwitchProController::push_right_joystick( + const std::tuple& joystick_position, + uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms +){ PybindSwitchProControllerInternal* internal = (PybindSwitchProControllerInternal*)m_internals; internal->controller().issue_right_joystick( nullptr, Milliseconds(delay_ms), Milliseconds(hold_ms), Milliseconds(release_ms), - {x, y} + JoystickPosition(std::get<0>(joystick_position), std::get<1>(joystick_position)) ); } void PybindSwitchProController::controller_state( - uint64_t duration, uint32_t button_bitfield, uint8_t dpad_position, double left_x, double left_y, - double right_x, double right_y + double right_x, double right_y, + uint64_t duration_ms ){ PybindSwitchProControllerInternal* internal = (PybindSwitchProControllerInternal*)m_internals; + // Same as pbf_controller_state(). internal->controller().issue_full_controller_state( nullptr, true, - Milliseconds(duration), + Milliseconds(duration_ms), (Button)button_bitfield, (DpadPosition)dpad_position, {left_x, left_y}, diff --git a/SerialPrograms/Source/Integrations/PybindSwitchController.h b/SerialPrograms/Source/Integrations/PybindSwitchController.h index 04ae2230ef..153cf67373 100644 --- a/SerialPrograms/Source/Integrations/PybindSwitchController.h +++ b/SerialPrograms/Source/Integrations/PybindSwitchController.h @@ -9,6 +9,7 @@ #include #include +#include namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -80,87 +81,85 @@ class PybindSwitchProController{ bool cancel_all_and_wait(uint64_t timeout_ms); public: - // Commands. These throw InvalidConnectionStateException if the controller is not - // ready, and block only if the device's command queue is full. + // Commands. These line up with the PBF API (`pbf_*()`) in + // SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h + // (input first, then the timing), without the `context` parameter (Python + // does not need it). The `push_*()` commands additionally take a `delay_ms` + // that `pbf_*()` does not expose; `pbf_*()` always uses delay = hold + release + // (back to back), which is what `delay_ms = hold_ms + release_ms` gives here. + // + // `delay_ms` is how long to wait before the next command may start, `hold_ms` + // how long the input is held, and `release_ms` how long it stays released + // before the same input can be used again. `duration_ms` is the total hold + // time. // - // `delay` is how long to wait before the next command may start, `hold` how long - // the input is held, and `release` how long it must stay released before the same - // button can be used again. `delay = hold + release` runs commands back to back - // like `pbf_press_button()`; `delay < hold` overlaps them, e.g. to hold a button - // while moving a stick. - - // Send a wait command to the controller. Nothing is pressed during the wait time. - // duration: wait duration, milliseconds. - // If the controller is not ready, it throws InvalidConnectionStateException. - // The function will block only if the device's command queue is full. + // These throw InvalidConnectionStateException if the controller is not + // ready, and block only if the device's command queue is full. + + // Equivalent to `pbf_wait()`: send a wait command to the controller. Nothing is + // pressed during the wait time. + // duration_ms: wait duration, milliseconds. void wait(uint64_t duration_ms); - // Send a button press command to the controller. It will press all buttons in - // `button_bitfield` simultaneously. D-pad buttons are excluded and should be called via - // `push_dpad()`. - // delay: how long to wait before the next command may start. - // hold: how long the button press is held, milliseconds. - // release: how long the buttons stay released before the same button can be used again, - // milliseconds. - // button_bitfield: values from `NintendoSwitch::Button`. - // - // `delay = hold + release` runs commands back to back like `pbf_press_button()`; - // `delay < hold` overlaps commands, e.g. to hold a button while moving a stick. - // If the controller is not ready, it throws InvalidConnectionStateException. - // The function will block only if the device's command queue is full. - void push_button(uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms, uint32_t button_bitfield); - // Send a D-pad press command to the controller. It will press one or two D-pad buttons to - // indicate a direction to the game. - // delay: how long to wait before the next command may start. - // hold: how long the button press is held, milliseconds. - // release: how long the buttons stay released before the same button can be used again, - // milliseconds. - // dpad_position: `NintendoSwitch::DpadPosition` values (0 = up, clockwise to 7 = up-left, 8 = none). - // - // `delay = hold + release` runs commands back to back like `pbf_press_button()`; - // `delay < hold` overlaps commands, e.g. to hold a button while moving a stick. - // If the controller is not ready, it throws InvalidConnectionStateException. - // The function will block only if the device's command queue is full. - void push_dpad(uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms, uint8_t dpad_position); - // Send a left joystick push command to the controller. - // delay: how long to wait before the next command may start. - // hold: how long the joystick is pushed, milliseconds. - // release: how long the joystick stay released before the same the joystick can be used again, - // milliseconds. - // x, y: in [-1.0, 1.0] with +x = right and +y = up. - // - // `delay = hold + release` runs commands back to back like `pbf_press_button()`; - // `delay < hold` overlaps commands, e.g. to hold a button while moving a stick. - // If the controller is not ready, it throws InvalidConnectionStateException. - // The function will block only if the device's command queue is full. - void push_left_joystick(uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms, double x, double y); - // Send a right joystick push command to the controller. - // delay: how long to wait before the next command may start. - // hold: how long the joystick is pushed, milliseconds. - // release: how long the joystick stay released before the same the joystick can be used again, - // milliseconds. - // x, y: in [-1.0, 1.0] with +x = right and +y = up. - // - // `delay = hold + release` runs commands back to back like `pbf_press_button()`; - // `delay < hold` overlaps commands, e.g. to hold a button while moving a stick. - // If the controller is not ready, it throws InvalidConnectionStateException. - // The function will block only if the device's command queue is full. - void push_right_joystick(uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms, double x, double y); - - // Set the entire controller state at once and hold it for `duration`. - // Everything not specified is released. This is the most direct way to hold - // arbitrary combinations, e.g. running (B + left stick) while turning the camera. - // duration: how long to hold the buttons/joysticks, milliseconds. - // button_bitfield: one or more non-D-pad buttons, values from `NintendoSwitch::Button`. - // dpad_position: `NintendoSwitch::DpadPosition` values (0 = up, clockwise to 7 = up-left, 8 = none). - // left_x, left_y: in [-1.0, 1.0] with +x = right and +y = up. - // right_x, right_y: in [-1.0, 1.0] with +x = right and +y = up. + // Equivalent to `pbf_press_button()`: send a button press command to the + // controller. It will press all buttons in `button_bitfield` simultaneously. + // D-pad buttons are excluded and should be called via `push_dpad()`. + // button_bitfield: values from `NintendoSwitch::Button`. + // delay_ms: how long to wait before the next command may start, milliseconds. + // hold_ms: how long the button press is held, milliseconds. + // release_ms: how long the buttons stay released before the same button can be + // used again, milliseconds. + void push_button(uint32_t button_bitfield, uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms); + + // Equivalent to `pbf_press_dpad()`: send a D-pad press command to the + // controller. It will press one or two D-pad buttons to indicate a direction + // to the game. + // dpad_position: `NintendoSwitch::DpadPosition` values (0 = up, clockwise to 7 = up-left, 8 = none). + // delay_ms: how long to wait before the next command may start, milliseconds. + // hold_ms: how long the button press is held, milliseconds. + // release_ms: how long the buttons stay released before the same button can be + // used again, milliseconds. + void push_dpad(uint8_t dpad_position, uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms); + + // Equivalent to `pbf_move_left_joystick()`: move the left joystick towards a + // 2D direction. + // joystick_position: (x, y) in [-1.0, 1.0] with +x = right and +y = up. + // delay_ms: how long to wait before the next command may start, milliseconds. + // hold_ms: how long the joystick is pushed, milliseconds. + // release_ms: how long the joystick stays released before the same joystick can + // be used again, milliseconds. + void push_left_joystick( + const std::tuple& joystick_position, + uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms + ); + + // Equivalent to `pbf_move_right_joystick()`: move the right joystick towards a + // 2D direction. + // joystick_position: (x, y) in [-1.0, 1.0] with +x = right and +y = up. + // delay_ms: how long to wait before the next command may start, milliseconds. + // hold_ms: how long the joystick is pushed, milliseconds. + // release_ms: how long the joystick stays released before the same joystick can + // be used again, milliseconds. + void push_right_joystick( + const std::tuple& joystick_position, + uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms + ); + + // Equivalent to `pbf_controller_state()`: set the entire controller state at + // once and hold it for `duration_ms`. Everything not specified is released. + // This is the most direct way to hold arbitrary combinations, e.g. running + // (B + left stick) while turning the camera. + // button_bitfield: one or more non-D-pad buttons, values from `NintendoSwitch::Button`. + // dpad_position: `NintendoSwitch::DpadPosition` values (0 = up, clockwise to 7 = up-left, 8 = none). + // left_x, left_y: in [-1.0, 1.0] with +x = right and +y = up. + // right_x, right_y: in [-1.0, 1.0] with +x = right and +y = up. + // duration_ms: how long to hold the buttons/d-pad/joysticks, milliseconds. void controller_state( - uint64_t duration_ms, uint32_t button_bitfield, uint8_t dpad_position, double left_x, double left_y, - double right_x, double right_y + double right_x, double right_y, + uint64_t duration_ms ); private: diff --git a/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestProgramComputer.cpp b/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestProgramComputer.cpp index 55438a1e22..fb173e0cfa 100644 --- a/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestProgramComputer.cpp +++ b/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestProgramComputer.cpp @@ -738,7 +738,7 @@ void TestProgramComputer::program(ProgramEnvironment& env, CancellableScope& sco #if 0 PybindSwitchProController controller("COM3"); controller.wait_for_ready(5000); - controller.push_button(1000, 200, 800, BUTTON_X); + controller.push_button(BUTTON_X, 1000, 200, 800); controller.wait_for_all_requests(); #endif diff --git a/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestProgramSwitch.cpp b/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestProgramSwitch.cpp index 038294cd2f..bfabc7c96e 100644 --- a/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestProgramSwitch.cpp +++ b/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestProgramSwitch.cpp @@ -896,7 +896,7 @@ void TestProgram::program(MultiSwitchProgramEnvironment& env, CancellableScope& #if 0 { PybindSwitchProController controller("COM12"); - controller.push_button(1000, 200, 800, BUTTON_B); + controller.push_button(BUTTON_B, 1000, 200, 800); controller.wait_for_all_requests(); } #endif diff --git a/SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp b/SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp index 347d14620b..fb6c398e15 100644 --- a/SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp +++ b/SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp @@ -232,32 +232,42 @@ PYBIND11_MODULE(_pa_core, m){ "Queue a pause of `duration_ms` with nothing pressed.", py::call_guard()) .def("push_button", &PybindSwitchProController::push_button, - py::arg("delay_ms"), py::arg("hold_ms"), py::arg("release_ms"), py::arg("button_bitfield"), - "Queue a press of every button in `button_bitfield` (see `BUTTONS`). `delay_ms` is " - "how long to wait before the press may start, `hold_ms` how long the buttons " - "stay down, `release_ms` how long they stay up before the same button can be " - "pressed again. D-pad directions are not part of `button_bitfield`; use push_dpad().", + py::arg("button_bitfield"), py::arg("delay_ms"), py::arg("hold_ms"), py::arg("release_ms"), + "Like pbf_press_button(), with an extra `delay_ms`: queue a press of every " + "button in `button_bitfield` (see `BUTTONS`). `delay_ms` is how long to wait " + "before the next command may start, `hold_ms` how long the buttons stay down, " + "`release_ms` how long they stay up before the same button can be used again. " + "`delay_ms = hold_ms + release_ms` runs commands back to back, like " + "pbf_press_button(). D-pad directions are not part of `button_bitfield`; use " + "push_dpad().", py::call_guard()) .def("push_dpad", &PybindSwitchProController::push_dpad, - py::arg("delay_ms"), py::arg("hold_ms"), py::arg("release_ms"), py::arg("dpad_position"), - "Queue a d-pad press in direction `dpad_position` (see `DPAD_POSITIONS`). " - "`delay_ms` / `hold_ms` / `release_ms` have the same meaning as in push_button().", + py::arg("dpad_position"), py::arg("delay_ms"), py::arg("hold_ms"), py::arg("release_ms"), + "Like pbf_press_dpad(), with an extra `delay_ms`: queue a d-pad press in " + "direction `dpad_position` (see `DPAD_POSITIONS`). `delay_ms` / `hold_ms` / " + "`release_ms` have the same meaning as in push_button().", py::call_guard()) .def("push_left_joystick", &PybindSwitchProController::push_left_joystick, - py::arg("delay_ms"), py::arg("hold_ms"), py::arg("release_ms"), py::arg("x"), py::arg("y"), - "Queue the left stick being held at (x, y), in [-1.0, 1.0] with +x = right " - "and +y = up. `delay_ms` / `hold_ms` / `release_ms` have the same meaning as in push_button().", + py::arg("joystick_position"), py::arg("delay_ms"), py::arg("hold_ms"), py::arg("release_ms"), + "Like pbf_move_left_joystick(), with an extra `delay_ms`: queue the left stick " + "being held at `joystick_position` (an (x, y) tuple in [-1.0, 1.0] with +x = " + "right and +y = up). `delay_ms` / `hold_ms` / `release_ms` have the same " + "meaning as in push_button().", py::call_guard()) .def("push_right_joystick", &PybindSwitchProController::push_right_joystick, - py::arg("delay_ms"), py::arg("hold_ms"), py::arg("release_ms"), py::arg("x"), py::arg("y"), - "Queue the right stick being held at (x, y), in [-1.0, 1.0] with +x = right " - "and +y = up. `delay_ms` / `hold_ms` / `release_ms` have the same meaning as in push_button().", + py::arg("joystick_position"), py::arg("delay_ms"), py::arg("hold_ms"), py::arg("release_ms"), + "Like pbf_move_right_joystick(), with an extra `delay_ms`: queue the right " + "stick being held at `joystick_position` (an (x, y) tuple in [-1.0, 1.0] with " + "+x = right and +y = up). `delay_ms` / `hold_ms` / `release_ms` have the same " + "meaning as in push_button().", py::call_guard()) .def("controller_state", &PybindSwitchProController::controller_state, - py::arg("duration_ms"), py::arg("button_bitfield"), py::arg("dpad_position"), + py::arg("button_bitfield"), py::arg("dpad_position"), py::arg("left_x"), py::arg("left_y"), py::arg("right_x"), py::arg("right_y"), - "Queue the entire controller state (buttons, d-pad, both sticks) being held " - "for `duration_ms`; everything not specified is released. This is the most " - "direct way to hold arbitrary combinations, e.g. B while moving the left stick.", + py::arg("duration_ms"), + "Like pbf_controller_state(): queue the entire controller state (buttons, " + "d-pad, both sticks) being held for `duration_ms`; everything not specified " + "is released. This is the most direct way to hold arbitrary combinations, " + "e.g. B while moving the left stick.", py::call_guard()); } diff --git a/SerialPrograms/Source/PythonBindings/README.md b/SerialPrograms/Source/PythonBindings/README.md index b53dbb24c4..17f2912972 100644 --- a/SerialPrograms/Source/PythonBindings/README.md +++ b/SerialPrograms/Source/PythonBindings/README.md @@ -104,8 +104,8 @@ with SwitchController("/dev/ttyACM0") as sw: # connects to the Switch via port sw.push_button("A") # tap A (80 ms hold, 80 ms release) sw.push_button("L+R", hold_ms=200) # press L and R together sw.push_dpad("up") # d-pad up - sw.push_left_joystick("up", hold_ms=1500) # walk forward - sw.controller_state(2000, buttons="B", left="up") # run forward + sw.push_left_joystick((0.0, 1.0), hold_ms=1500) # walk forward + sw.controller_state("B", left="up", duration_ms=2000) # run forward sw.wait(300) sw.wait_for_all_requests() # block until the device executed everything ``` diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py index 2f6371c256..51c1a7514e 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py @@ -19,7 +19,7 @@ with SwitchController("/dev/cu.usbserial-0001") as sw: sw.push_button("A") sw.push_dpad("up+right") - sw.push_left_joystick("up", hold_ms=1500) + sw.push_left_joystick((0.0, 1.0), hold_ms=1500) sw.wait_for_all_requests() """ @@ -32,6 +32,7 @@ check_against_core, parse_buttons, parse_stick, + parse_stick_position, ) from .controller import SwitchController from .devices import list_serial_ports @@ -49,6 +50,7 @@ "list_serial_ports", "parse_buttons", "parse_stick", + "parse_stick_position", ] __version__ = "0.1.0" diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py index a80025ef30..fb7eb872c5 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py @@ -8,8 +8,10 @@ - D-pad: "UP", "DOWN", "LEFT", "RIGHT" and diagonals such as "UP_RIGHT" (also "UP-RIGHT", "UPRIGHT"). Listing "UP" and "RIGHT" together also means up-right. - Combinations: a list (["L", "R"]) or a "+"-joined string ("L+R", "ZL+A"). -- Joystick positions: a direction name ("up", "down_left", ...) or an (x, y) pair - in [-1, 1] with +x = right and +y = up. "neutral"/"center" means (0, 0). +- Joystick positions: an (x, y) pair in [-1, 1] with +x = right and +y = up. + `parse_stick()` additionally accepts a direction name ("up", "down_left", ...) and + "neutral"/"center" for convenience; `parse_stick_position()` (used by + push_left_joystick() / push_right_joystick()) accepts only the (x, y) pair. The button bit values match `NintendoSwitch::Button` and the d-pad values match `NintendoSwitch::DpadPosition` in @@ -97,6 +99,13 @@ - validated by `parse_stick()` """ +StickCoords = Sequence[float] +""" +StickCoords +- A strict (x, y) pair in [-1, 1], no direction names. +- validated by `parse_stick_position()` (used by push_left_joystick() / push_right_joystick()) +""" + def _normalize_name(name: str) -> str: name = name.strip().upper().replace("-", "_").replace(" ", "_") @@ -204,15 +213,37 @@ def parse_stick(position: StickArg) -> tuple[float, float]: length = math.hypot(vx, vy) return (vx / length, vy / length) # normalize to [-1, 1] # else parse as (x, y) pair - values = list(position) + return _parse_stick_pair(position) + + +def _parse_stick_pair(values: StickCoords) -> tuple[float, float]: + """Parse an (x, y) pair into floats in [-1, 1]. Raises ValueError otherwise.""" + values = list(values) if len(values) != 2: - raise ValueError(f"A stick position needs exactly two numbers [x, y], got {position!r}.") + raise ValueError(f"A stick position needs exactly two numbers [x, y], got {values!r}.") x, y = float(values[0]), float(values[1]) if not (-1.0 <= x <= 1.0 and -1.0 <= y <= 1.0): raise ValueError(f"Stick coordinates must be within [-1, 1], got ({x}, {y}).") return (x, y) +def parse_stick_position(position: StickCoords) -> tuple[float, float]: + """Parse a strict (x, y) joystick position, as used by push_left_joystick() / + push_right_joystick(). + + Unlike `parse_stick()`, direction names (and None) are not allowed: pass an + (x, y) pair in [-1, 1] with +x = right and +y = up. + """ + if position is None: + raise ValueError("joystick_position must be an (x, y) pair, got None.") + if isinstance(position, str): + raise ValueError( + f"joystick_position must be an (x, y) pair, not a string (got {position!r}). " + "Direction names are not accepted here." + ) + return _parse_stick_pair(position) + + def check_against_core(core_buttons: dict[str, int], core_dpad: dict[str, int]) -> None: """Raise AssertionError if `BUTTON_BITS` / `DPAD_POSITIONS` disagree with the C++ enums. diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py index 46d51ff0f3..50d70fdf36 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py @@ -15,8 +15,8 @@ sw.push_button("A") # tap A sw.push_button("L+R", hold_ms=200) # press L and R together sw.push_dpad("up") # d-pad up - sw.push_left_joystick("up", hold_ms=1500) # walk forward - sw.controller_state(2000, buttons="B", left="up") # run forward + sw.push_left_joystick((0.0, 1.0), hold_ms=1500) # walk forward + sw.controller_state("B", left="up", duration_ms=2000) # run forward sw.wait_for_all_requests() """ @@ -51,13 +51,14 @@ def controller_name(self) -> str: ... def wait_for_all_requests(self) -> None: ... def cancel_all_and_wait(self, timeout_ms: int = ...) -> bool: ... def wait(self, duration_ms: int) -> None: ... - def push_button(self, delay_ms: int, hold_ms: int, release_ms: int, button_bitfield: int) -> None: ... - def push_dpad(self, delay_ms: int, hold_ms: int, release_ms: int, dpad_position: int) -> None: ... - def push_left_joystick(self, delay_ms: int, hold_ms: int, release_ms: int, x: float, y: float) -> None: ... - def push_right_joystick(self, delay_ms: int, hold_ms: int, release_ms: int, x: float, y: float) -> None: ... + def push_button(self, button_bitfield: int, delay_ms: int, hold_ms: int, release_ms: int) -> None: ... + def push_dpad(self, dpad_position: int, delay_ms: int, hold_ms: int, release_ms: int) -> None: ... + def push_left_joystick(self, joystick_position: tuple[float, float], delay_ms: int, hold_ms: int, release_ms: int) -> None: ... + def push_right_joystick(self, joystick_position: tuple[float, float], delay_ms: int, hold_ms: int, release_ms: int) -> None: ... def controller_state( - self, duration_ms: int, button_bitfield: int, dpad_position: int, + self, button_bitfield: int, dpad_position: int, left_x: float, left_y: float, right_x: float, right_y: float, + duration_ms: int, ) -> None: ... @@ -132,8 +133,9 @@ def push_button(self, buttons: btn.ButtonsArg, hold_ms: int = DEFAULT_HOLD_MS, (SerialPrograms/Source/Controllers/Controller.h), via `PybindSwitchProController::push_button()` (SerialPrograms/Source/Integrations/PybindSwitchProController.h). - `delay = hold + release` runs commands back to back, the same convention as the - C++ class docs. + Queued back to back, the same timing `pbf_press_button()` uses + (delay = hold + release); the backend's `delay_ms` is available by + calling the `_pa_core.Controller` directly. """ _check_nonnegative(hold_ms=hold_ms, release_ms=release_ms) self._require_open() @@ -146,7 +148,7 @@ def push_button(self, buttons: btn.ButtonsArg, hold_ms: int = DEFAULT_HOLD_MS, if not parsed.has_buttons: raise ValueError("push_button() needs at least one button.") with self._lock: - self._backend.push_button(hold_ms + release_ms, hold_ms, release_ms, parsed.bitfield) + self._backend.push_button(parsed.bitfield, hold_ms + release_ms, hold_ms, release_ms) def push_dpad(self, position: btn.ButtonsArg, hold_ms: int = DEFAULT_HOLD_MS, release_ms: int = DEFAULT_RELEASE_MS) -> None: @@ -172,19 +174,16 @@ def push_dpad(self, position: btn.ButtonsArg, hold_ms: int = DEFAULT_HOLD_MS, if not parsed.has_dpad: raise ValueError("push_dpad() needs at least one d-pad direction.") with self._lock: - self._backend.push_dpad(hold_ms + release_ms, hold_ms, release_ms, parsed.dpad) + self._backend.push_dpad(parsed.dpad, hold_ms + release_ms, hold_ms, release_ms) - def controller_state(self, duration_ms: int = 500, buttons: btn.ButtonsArg = None, *, - left: btn.StickArg = None, right: btn.StickArg = None) -> None: + def controller_state(self, buttons: btn.ButtonsArg = None, *, + left: btn.StickArg = None, right: btn.StickArg = None, + duration_ms: int = 500) -> None: """Hold any combination of buttons, d-pad and sticks for `duration_ms`. `buttons` may mix buttons and d-pad directions ("ZL+up"). Everything not - specified is released for the whole hold. The state is released when the - next queued command executes; queue a `wait()` afterwards for a gap. - - C++: `AbstractController::issue_full_controller_state()` - (SerialPrograms/Source/Controllers/Controller.h), via - `PybindSwitchProController::controller_state()`. + specified is released for the whole hold. The argument order matches + `pbf_controller_state()`: buttons/d-pad first, sticks, then duration. """ _check_nonnegative(duration_ms=duration_ms) self._require_open() @@ -193,36 +192,43 @@ def controller_state(self, duration_ms: int = 500, buttons: btn.ButtonsArg = Non right_x, right_y = btn.parse_stick(right) if right is not None else (0.0, 0.0) with self._lock: self._backend.controller_state( - duration_ms, parsed.bitfield, parsed.dpad, - left_x, left_y, right_x, right_y + parsed.bitfield, parsed.dpad, + left_x, left_y, right_x, right_y, + duration_ms ) - def push_left_joystick(self, position: btn.StickArg, hold_ms: int = 500, + def push_left_joystick(self, joystick_position: btn.StickCoords, hold_ms: int = 500, release_ms: int = 0) -> None: - """Tilt the left stick to `position` for `hold_ms`. + """Tilt the left stick to `joystick_position`, an (x, y) pair in [-1, 1] + with +x = right and +y = up, for `hold_ms`. + + Direction-name strings are not accepted: pass coordinates, e.g. (0.0, 1.0). C++: `AbstractController::issue_left_joystick()` (SerialPrograms/Source/Controllers/Controller.h), via `PybindSwitchProController::push_left_joystick()`. """ - self._push_joystick(self._backend.push_left_joystick, position, hold_ms, release_ms) + self._push_joystick(self._backend.push_left_joystick, joystick_position, hold_ms, release_ms) - def push_right_joystick(self, position: btn.StickArg, hold_ms: int = 500, + def push_right_joystick(self, joystick_position: btn.StickCoords, hold_ms: int = 500, release_ms: int = 0) -> None: - """Tilt the right stick to `position` for `hold_ms`. + """Tilt the right stick to `joystick_position`, an (x, y) pair in [-1, 1] + with +x = right and +y = up, for `hold_ms`. + + Direction-name strings are not accepted: pass coordinates, e.g. (0.0, 1.0). C++: `AbstractController::issue_right_joystick()` (SerialPrograms/Source/Controllers/Controller.h), via `PybindSwitchProController::push_right_joystick()`. """ - self._push_joystick(self._backend.push_right_joystick, position, hold_ms, release_ms) + self._push_joystick(self._backend.push_right_joystick, joystick_position, hold_ms, release_ms) - def _push_joystick(self, send, position: btn.StickArg, hold_ms: int, release_ms: int) -> None: + def _push_joystick(self, send, joystick_position: btn.StickCoords, hold_ms: int, release_ms: int) -> None: _check_nonnegative(hold_ms=hold_ms, release_ms=release_ms) self._require_open() - x, y = btn.parse_stick(position) + x, y = btn.parse_stick_position(joystick_position) with self._lock: - send(hold_ms + release_ms, hold_ms, release_ms, x, y) + send((x, y), hold_ms + release_ms, hold_ms, release_ms) def wait(self, duration_ms: int) -> None: """Queue a pause of `duration_ms` with nothing pressed.""" diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/fake.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/fake.py index e261af9b03..b4f326d9b5 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/fake.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/fake.py @@ -61,29 +61,29 @@ def _record(self, name: str, *args: Any) -> None: def wait(self, duration_ms: int) -> None: self._record("wait", duration_ms) - def push_button(self, delay_ms: int, hold_ms: int, release_ms: int, button_bitfield: int) -> None: - self._record("push_button", delay_ms, hold_ms, release_ms, button_bitfield) + def push_button(self, button_bitfield: int, delay_ms: int, hold_ms: int, release_ms: int) -> None: + self._record("push_button", button_bitfield, delay_ms, hold_ms, release_ms) - def push_dpad(self, delay_ms: int, hold_ms: int, release_ms: int, dpad_position: int) -> None: - self._record("push_dpad", delay_ms, hold_ms, release_ms, dpad_position) + def push_dpad(self, dpad_position: int, delay_ms: int, hold_ms: int, release_ms: int) -> None: + self._record("push_dpad", dpad_position, delay_ms, hold_ms, release_ms) - def push_left_joystick(self, delay_ms: int, hold_ms: int, release_ms: int, x: float, y: float) -> None: - self._record("push_left_joystick", delay_ms, hold_ms, release_ms, x, y) + def push_left_joystick(self, joystick_position: tuple[float, float], delay_ms: int, hold_ms: int, release_ms: int) -> None: + self._record("push_left_joystick", joystick_position, delay_ms, hold_ms, release_ms) - def push_right_joystick(self, delay_ms: int, hold_ms: int, release_ms: int, x: float, y: float) -> None: - self._record("push_right_joystick", delay_ms, hold_ms, release_ms, x, y) + def push_right_joystick(self, joystick_position: tuple[float, float], delay_ms: int, hold_ms: int, release_ms: int) -> None: + self._record("push_right_joystick", joystick_position, delay_ms, hold_ms, release_ms) def controller_state( self, - duration_ms: int, button_bitfield: int, dpad_position: int, left_x: float, left_y: float, right_x: float, right_y: float, + duration_ms: int, ) -> None: - self._record("controller_state", duration_ms, button_bitfield, dpad_position, left_x, left_y, right_x, right_y) + self._record("controller_state", button_bitfield, dpad_position, left_x, left_y, right_x, right_y, duration_ms) # -- test helpers --------------------------------------------------------- diff --git a/SerialPrograms/Source/PythonBindings/tests/test_core.py b/SerialPrograms/Source/PythonBindings/tests/test_core.py index 9e0ea06c45..cebe5bf4f2 100644 --- a/SerialPrograms/Source/PythonBindings/tests/test_core.py +++ b/SerialPrograms/Source/PythonBindings/tests/test_core.py @@ -71,7 +71,7 @@ def test_unreachable_port(): assert c.controller_name() == "" # Commands on a not-ready controller raise RuntimeError, they do not crash. with pytest.raises(RuntimeError): - c.push_button(0, 10, 10, core.BUTTONS["A"]) + c.push_button(core.BUTTONS["A"], 0, 10, 10) # These are safe no-ops when not ready. c.wait_for_all_requests() assert c.cancel_all_and_wait(100) is False diff --git a/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py b/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py index 343f9f0b30..5cd6d5fdcf 100644 --- a/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py +++ b/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py @@ -40,7 +40,7 @@ def test_push_button_single_button(): sw, fake = make() sw.push_button("A") assert fake.commands() == ["push_button"] - (delay, hold, release, bitfield), = fake.arguments("push_button") + (bitfield, delay, hold, release), = fake.arguments("push_button") assert bitfield == BUTTON_BITS["A"] assert delay == hold + release and hold == 80 and release == 80 @@ -49,7 +49,7 @@ def test_push_button_combined_and_custom_durations(): """A combination is OR-ed into one bitfield and custom hold/release durations are forwarded, with delay = hold + release.""" sw, fake = make() sw.push_button("L+R", hold_ms=200, release_ms=50) - (delay, hold, release, bitfield), = fake.arguments("push_button") + (bitfield, delay, hold, release), = fake.arguments("push_button") assert bitfield == BUTTON_BITS["L"] | BUTTON_BITS["R"] assert (delay, hold, release) == (250, 200, 50) @@ -58,7 +58,7 @@ def test_push_dpad(): """A d-pad direction is forwarded as push_dpad with the C++ DpadPosition value and the requested timing.""" sw, fake = make() sw.push_dpad("up", hold_ms=100) - (delay, hold, release, position), = fake.arguments("push_dpad") + (position, delay, hold, release), = fake.arguments("push_dpad") assert position == DPAD_POSITIONS["UP"] and hold == 100 and delay == 100 + release @@ -99,11 +99,11 @@ def test_push_dpad_needs_something(): def test_controller_state_mixed_combination(): - """Buttons and d-pad held together go out as a single controller_state with the right bitfield, d-pad position and neutral sticks.""" + """Buttons and d-pad held together go out as a single controller_state with the right bitfield, d-pad position, neutral sticks and duration last.""" sw, fake = make() - sw.controller_state(60, buttons="ZL+up") + sw.controller_state("ZL+up", duration_ms=60) assert fake.commands() == ["controller_state"] - (duration, buttons, dpad, left_x, left_y, right_x, right_y), = fake.arguments("controller_state") + (buttons, dpad, left_x, left_y, right_x, right_y, duration), = fake.arguments("controller_state") assert duration == 60 assert buttons == BUTTON_BITS["ZL"] assert dpad == DPAD_POSITIONS["UP"] @@ -111,26 +111,36 @@ def test_controller_state_mixed_combination(): def test_push_left_joystick(): - """A stick direction name becomes an (x, y) pair, forwarded to push_left_joystick with delay = hold + release.""" + """A stick (x, y) pair is forwarded to push_left_joystick as a single joystick_position tuple with delay = hold + release.""" sw, fake = make() - sw.push_left_joystick("up", hold_ms=1500) - (delay, hold, release, x, y), = fake.arguments("push_left_joystick") - assert (x, y) == (0.0, 1.0) and hold == 1500 and delay == 1500 + release + sw.push_left_joystick((0.0, 1.0), hold_ms=1500) + (joystick_position, delay, hold, release), = fake.arguments("push_left_joystick") + assert joystick_position == (0.0, 1.0) and hold == 1500 and delay == 1500 + release + + +def test_push_left_joystick_rejects_string(): + """push_left_joystick() does not accept direction-name strings, only (x, y) coordinates.""" + sw, fake = make() + with pytest.raises(ValueError, match="joystick_position"): + sw.push_left_joystick("up") + with pytest.raises(ValueError): + sw.push_left_joystick(None) + assert fake.commands() == [] def test_push_right_joystick(): """A raw [x, y] stick position is forwarded to push_right_joystick with the requested hold and release.""" sw, fake = make() sw.push_right_joystick([0.5, -0.5], hold_ms=300, release_ms=100) - (delay, hold, release, x, y), = fake.arguments("push_right_joystick") - assert (x, y) == (0.5, -0.5) and delay == 400 + (joystick_position, delay, hold, release), = fake.arguments("push_right_joystick") + assert joystick_position == (0.5, -0.5) and hold == 300 and release == 100 and delay == 400 def test_controller_state_combination(): """Buttons and both sticks can be held at once via controller_state, with everything not specified left neutral.""" sw, fake = make() - sw.controller_state(2000, buttons="B", left="up", right=[1.0, 0.0]) - (duration, buttons, dpad, left_x, left_y, right_x, right_y), = fake.arguments("controller_state") + sw.controller_state("B", left="up", right=[1.0, 0.0], duration_ms=2000) + (buttons, dpad, left_x, left_y, right_x, right_y, duration), = fake.arguments("controller_state") assert duration == 2000 assert buttons == BUTTON_BITS["B"] assert dpad == DPAD_NONE From b594981e634b8ec279655da0fe7d3c67de431531 Mon Sep 17 00:00:00 2001 From: PA Dev Bot <344001113+pa-devbot@users.noreply.github.com> Date: Wed, 21 Oct 2026 22:39:03 +0000 Subject: [PATCH 29/58] push_*_joystick(): back to separate x, y arguments On request, the joysticks take separate x, y arguments again instead of a single (x, y) joystick_position tuple: - C++: push_left_joystick(x, y, delay_ms, hold_ms, release_ms) - module: py::arg("x"), py::arg("y"), ... - Python: sw.push_left_joystick(0.0, 1.0, hold_ms=1500) No parsing step is needed anymore (x, y are plain numbers; the C++ binding enforces numeric types), so parse_stick_position() was removed and parse_stick() keeps its (x, y)-pair helper for controller_state()'s left/right. --- .../Integrations/PybindSwitchController.cpp | 14 +++----- .../Integrations/PybindSwitchController.h | 15 +++------ .../PythonBindings/PythonBindings_Module.cpp | 14 ++++---- .../Source/PythonBindings/README.md | 2 +- .../pokemon_automation/__init__.py | 4 +-- .../pokemon_automation/buttons.py | 32 +++---------------- .../pokemon_automation/controller.py | 29 ++++++++--------- .../PythonBindings/pokemon_automation/fake.py | 8 ++--- .../switch_connection_test.py | 4 +-- .../Source/PythonBindings/tests/test_core.py | 7 ++++ .../tests/test_fake_controller.py | 26 +++++---------- 11 files changed, 54 insertions(+), 101 deletions(-) diff --git a/SerialPrograms/Source/Integrations/PybindSwitchController.cpp b/SerialPrograms/Source/Integrations/PybindSwitchController.cpp index b3d2ea87ff..f0e780b025 100644 --- a/SerialPrograms/Source/Integrations/PybindSwitchController.cpp +++ b/SerialPrograms/Source/Integrations/PybindSwitchController.cpp @@ -178,30 +178,24 @@ void PybindSwitchProController::push_dpad(uint8_t dpad_position, uint64_t delay_ (DpadPosition)dpad_position ); } -void PybindSwitchProController::push_left_joystick( - const std::tuple& joystick_position, - uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms -){ +void PybindSwitchProController::push_left_joystick(double x, double y, uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms){ PybindSwitchProControllerInternal* internal = (PybindSwitchProControllerInternal*)m_internals; internal->controller().issue_left_joystick( nullptr, Milliseconds(delay_ms), Milliseconds(hold_ms), Milliseconds(release_ms), - JoystickPosition(std::get<0>(joystick_position), std::get<1>(joystick_position)) + JoystickPosition(x, y) ); } -void PybindSwitchProController::push_right_joystick( - const std::tuple& joystick_position, - uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms -){ +void PybindSwitchProController::push_right_joystick(double x, double y, uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms){ PybindSwitchProControllerInternal* internal = (PybindSwitchProControllerInternal*)m_internals; internal->controller().issue_right_joystick( nullptr, Milliseconds(delay_ms), Milliseconds(hold_ms), Milliseconds(release_ms), - JoystickPosition(std::get<0>(joystick_position), std::get<1>(joystick_position)) + JoystickPosition(x, y) ); } void PybindSwitchProController::controller_state( diff --git a/SerialPrograms/Source/Integrations/PybindSwitchController.h b/SerialPrograms/Source/Integrations/PybindSwitchController.h index 153cf67373..e3fed77a06 100644 --- a/SerialPrograms/Source/Integrations/PybindSwitchController.h +++ b/SerialPrograms/Source/Integrations/PybindSwitchController.h @@ -9,7 +9,6 @@ #include #include -#include namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -123,27 +122,21 @@ class PybindSwitchProController{ // Equivalent to `pbf_move_left_joystick()`: move the left joystick towards a // 2D direction. - // joystick_position: (x, y) in [-1.0, 1.0] with +x = right and +y = up. + // x, y: in [-1.0, 1.0] with +x = right and +y = up. // delay_ms: how long to wait before the next command may start, milliseconds. // hold_ms: how long the joystick is pushed, milliseconds. // release_ms: how long the joystick stays released before the same joystick can // be used again, milliseconds. - void push_left_joystick( - const std::tuple& joystick_position, - uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms - ); + void push_left_joystick(double x, double y, uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms); // Equivalent to `pbf_move_right_joystick()`: move the right joystick towards a // 2D direction. - // joystick_position: (x, y) in [-1.0, 1.0] with +x = right and +y = up. + // x, y: in [-1.0, 1.0] with +x = right and +y = up. // delay_ms: how long to wait before the next command may start, milliseconds. // hold_ms: how long the joystick is pushed, milliseconds. // release_ms: how long the joystick stays released before the same joystick can // be used again, milliseconds. - void push_right_joystick( - const std::tuple& joystick_position, - uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms - ); + void push_right_joystick(double x, double y, uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms); // Equivalent to `pbf_controller_state()`: set the entire controller state at // once and hold it for `duration_ms`. Everything not specified is released. diff --git a/SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp b/SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp index fb6c398e15..5d67921d06 100644 --- a/SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp +++ b/SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp @@ -248,18 +248,16 @@ PYBIND11_MODULE(_pa_core, m){ "`release_ms` have the same meaning as in push_button().", py::call_guard()) .def("push_left_joystick", &PybindSwitchProController::push_left_joystick, - py::arg("joystick_position"), py::arg("delay_ms"), py::arg("hold_ms"), py::arg("release_ms"), + py::arg("x"), py::arg("y"), py::arg("delay_ms"), py::arg("hold_ms"), py::arg("release_ms"), "Like pbf_move_left_joystick(), with an extra `delay_ms`: queue the left stick " - "being held at `joystick_position` (an (x, y) tuple in [-1.0, 1.0] with +x = " - "right and +y = up). `delay_ms` / `hold_ms` / `release_ms` have the same " - "meaning as in push_button().", + "being held at (x, y), in [-1.0, 1.0] with +x = right and +y = up. `delay_ms` / " + "`hold_ms` / `release_ms` have the same meaning as in push_button().", py::call_guard()) .def("push_right_joystick", &PybindSwitchProController::push_right_joystick, - py::arg("joystick_position"), py::arg("delay_ms"), py::arg("hold_ms"), py::arg("release_ms"), + py::arg("x"), py::arg("y"), py::arg("delay_ms"), py::arg("hold_ms"), py::arg("release_ms"), "Like pbf_move_right_joystick(), with an extra `delay_ms`: queue the right " - "stick being held at `joystick_position` (an (x, y) tuple in [-1.0, 1.0] with " - "+x = right and +y = up). `delay_ms` / `hold_ms` / `release_ms` have the same " - "meaning as in push_button().", + "stick being held at (x, y), in [-1.0, 1.0] with +x = right and +y = up. " + "`delay_ms` / `hold_ms` / `release_ms` have the same meaning as in push_button().", py::call_guard()) .def("controller_state", &PybindSwitchProController::controller_state, py::arg("button_bitfield"), py::arg("dpad_position"), diff --git a/SerialPrograms/Source/PythonBindings/README.md b/SerialPrograms/Source/PythonBindings/README.md index 17f2912972..2c0c5fc557 100644 --- a/SerialPrograms/Source/PythonBindings/README.md +++ b/SerialPrograms/Source/PythonBindings/README.md @@ -104,7 +104,7 @@ with SwitchController("/dev/ttyACM0") as sw: # connects to the Switch via port sw.push_button("A") # tap A (80 ms hold, 80 ms release) sw.push_button("L+R", hold_ms=200) # press L and R together sw.push_dpad("up") # d-pad up - sw.push_left_joystick((0.0, 1.0), hold_ms=1500) # walk forward + sw.push_left_joystick(0.0, 1.0, hold_ms=1500) # walk forward sw.controller_state("B", left="up", duration_ms=2000) # run forward sw.wait(300) sw.wait_for_all_requests() # block until the device executed everything diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py index 51c1a7514e..1fe126471d 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py @@ -19,7 +19,7 @@ with SwitchController("/dev/cu.usbserial-0001") as sw: sw.push_button("A") sw.push_dpad("up+right") - sw.push_left_joystick((0.0, 1.0), hold_ms=1500) + sw.push_left_joystick(0.0, 1.0, hold_ms=1500) sw.wait_for_all_requests() """ @@ -32,7 +32,6 @@ check_against_core, parse_buttons, parse_stick, - parse_stick_position, ) from .controller import SwitchController from .devices import list_serial_ports @@ -50,7 +49,6 @@ "list_serial_ports", "parse_buttons", "parse_stick", - "parse_stick_position", ] __version__ = "0.1.0" diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py index fb7eb872c5..6db727d711 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py @@ -9,9 +9,9 @@ "UP-RIGHT", "UPRIGHT"). Listing "UP" and "RIGHT" together also means up-right. - Combinations: a list (["L", "R"]) or a "+"-joined string ("L+R", "ZL+A"). - Joystick positions: an (x, y) pair in [-1, 1] with +x = right and +y = up. - `parse_stick()` additionally accepts a direction name ("up", "down_left", ...) and - "neutral"/"center" for convenience; `parse_stick_position()` (used by - push_left_joystick() / push_right_joystick()) accepts only the (x, y) pair. + push_left_joystick() / push_right_joystick() take the x and y numbers directly; + `parse_stick()` (used for `controller_state()`'s left/right) additionally accepts + a direction name ("up", "down_left", ...) and "neutral"/"center" for convenience. The button bit values match `NintendoSwitch::Button` and the d-pad values match `NintendoSwitch::DpadPosition` in @@ -99,13 +99,6 @@ - validated by `parse_stick()` """ -StickCoords = Sequence[float] -""" -StickCoords -- A strict (x, y) pair in [-1, 1], no direction names. -- validated by `parse_stick_position()` (used by push_left_joystick() / push_right_joystick()) -""" - def _normalize_name(name: str) -> str: name = name.strip().upper().replace("-", "_").replace(" ", "_") @@ -216,7 +209,7 @@ def parse_stick(position: StickArg) -> tuple[float, float]: return _parse_stick_pair(position) -def _parse_stick_pair(values: StickCoords) -> tuple[float, float]: +def _parse_stick_pair(values: Sequence[float]) -> tuple[float, float]: """Parse an (x, y) pair into floats in [-1, 1]. Raises ValueError otherwise.""" values = list(values) if len(values) != 2: @@ -227,23 +220,6 @@ def _parse_stick_pair(values: StickCoords) -> tuple[float, float]: return (x, y) -def parse_stick_position(position: StickCoords) -> tuple[float, float]: - """Parse a strict (x, y) joystick position, as used by push_left_joystick() / - push_right_joystick(). - - Unlike `parse_stick()`, direction names (and None) are not allowed: pass an - (x, y) pair in [-1, 1] with +x = right and +y = up. - """ - if position is None: - raise ValueError("joystick_position must be an (x, y) pair, got None.") - if isinstance(position, str): - raise ValueError( - f"joystick_position must be an (x, y) pair, not a string (got {position!r}). " - "Direction names are not accepted here." - ) - return _parse_stick_pair(position) - - def check_against_core(core_buttons: dict[str, int], core_dpad: dict[str, int]) -> None: """Raise AssertionError if `BUTTON_BITS` / `DPAD_POSITIONS` disagree with the C++ enums. diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py index 50d70fdf36..accf55f780 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py @@ -15,7 +15,7 @@ sw.push_button("A") # tap A sw.push_button("L+R", hold_ms=200) # press L and R together sw.push_dpad("up") # d-pad up - sw.push_left_joystick((0.0, 1.0), hold_ms=1500) # walk forward + sw.push_left_joystick(0.0, 1.0, hold_ms=1500) # walk forward sw.controller_state("B", left="up", duration_ms=2000) # run forward sw.wait_for_all_requests() """ @@ -53,8 +53,8 @@ def cancel_all_and_wait(self, timeout_ms: int = ...) -> bool: ... def wait(self, duration_ms: int) -> None: ... def push_button(self, button_bitfield: int, delay_ms: int, hold_ms: int, release_ms: int) -> None: ... def push_dpad(self, dpad_position: int, delay_ms: int, hold_ms: int, release_ms: int) -> None: ... - def push_left_joystick(self, joystick_position: tuple[float, float], delay_ms: int, hold_ms: int, release_ms: int) -> None: ... - def push_right_joystick(self, joystick_position: tuple[float, float], delay_ms: int, hold_ms: int, release_ms: int) -> None: ... + def push_left_joystick(self, x: float, y: float, delay_ms: int, hold_ms: int, release_ms: int) -> None: ... + def push_right_joystick(self, x: float, y: float, delay_ms: int, hold_ms: int, release_ms: int) -> None: ... def controller_state( self, button_bitfield: int, dpad_position: int, left_x: float, left_y: float, right_x: float, right_y: float, @@ -197,38 +197,35 @@ def controller_state(self, buttons: btn.ButtonsArg = None, *, duration_ms ) - def push_left_joystick(self, joystick_position: btn.StickCoords, hold_ms: int = 500, + def push_left_joystick(self, x: float, y: float, hold_ms: int = 500, release_ms: int = 0) -> None: - """Tilt the left stick to `joystick_position`, an (x, y) pair in [-1, 1] - with +x = right and +y = up, for `hold_ms`. + """Tilt the left stick to (x, y) for `hold_ms`. - Direction-name strings are not accepted: pass coordinates, e.g. (0.0, 1.0). + `x`, `y`: in [-1, 1] with +x = right and +y = up; e.g. (0.0, 1.0) is up. C++: `AbstractController::issue_left_joystick()` (SerialPrograms/Source/Controllers/Controller.h), via `PybindSwitchProController::push_left_joystick()`. """ - self._push_joystick(self._backend.push_left_joystick, joystick_position, hold_ms, release_ms) + self._push_joystick(self._backend.push_left_joystick, x, y, hold_ms, release_ms) - def push_right_joystick(self, joystick_position: btn.StickCoords, hold_ms: int = 500, + def push_right_joystick(self, x: float, y: float, hold_ms: int = 500, release_ms: int = 0) -> None: - """Tilt the right stick to `joystick_position`, an (x, y) pair in [-1, 1] - with +x = right and +y = up, for `hold_ms`. + """Tilt the right stick to (x, y) for `hold_ms`. - Direction-name strings are not accepted: pass coordinates, e.g. (0.0, 1.0). + `x`, `y`: in [-1, 1] with +x = right and +y = up; e.g. (0.0, 1.0) is up. C++: `AbstractController::issue_right_joystick()` (SerialPrograms/Source/Controllers/Controller.h), via `PybindSwitchProController::push_right_joystick()`. """ - self._push_joystick(self._backend.push_right_joystick, joystick_position, hold_ms, release_ms) + self._push_joystick(self._backend.push_right_joystick, x, y, hold_ms, release_ms) - def _push_joystick(self, send, joystick_position: btn.StickCoords, hold_ms: int, release_ms: int) -> None: + def _push_joystick(self, send, x: float, y: float, hold_ms: int, release_ms: int) -> None: _check_nonnegative(hold_ms=hold_ms, release_ms=release_ms) self._require_open() - x, y = btn.parse_stick_position(joystick_position) with self._lock: - send((x, y), hold_ms + release_ms, hold_ms, release_ms) + send(x, y, hold_ms + release_ms, hold_ms, release_ms) def wait(self, duration_ms: int) -> None: """Queue a pause of `duration_ms` with nothing pressed.""" diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/fake.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/fake.py index b4f326d9b5..c87bad4026 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/fake.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/fake.py @@ -67,11 +67,11 @@ def push_button(self, button_bitfield: int, delay_ms: int, hold_ms: int, release def push_dpad(self, dpad_position: int, delay_ms: int, hold_ms: int, release_ms: int) -> None: self._record("push_dpad", dpad_position, delay_ms, hold_ms, release_ms) - def push_left_joystick(self, joystick_position: tuple[float, float], delay_ms: int, hold_ms: int, release_ms: int) -> None: - self._record("push_left_joystick", joystick_position, delay_ms, hold_ms, release_ms) + def push_left_joystick(self, x: float, y: float, delay_ms: int, hold_ms: int, release_ms: int) -> None: + self._record("push_left_joystick", x, y, delay_ms, hold_ms, release_ms) - def push_right_joystick(self, joystick_position: tuple[float, float], delay_ms: int, hold_ms: int, release_ms: int) -> None: - self._record("push_right_joystick", joystick_position, delay_ms, hold_ms, release_ms) + def push_right_joystick(self, x: float, y: float, delay_ms: int, hold_ms: int, release_ms: int) -> None: + self._record("push_right_joystick", x, y, delay_ms, hold_ms, release_ms) def controller_state( self, diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py index 43c6a79be0..7ab46a62d9 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py @@ -29,8 +29,8 @@ def try_port(port: str) -> bool: sw.push_dpad("right", hold_ms=100) sw.push_dpad("left", hold_ms=100) sw.push_dpad("left", hold_ms=100) - sw.push_right_joystick([1, 0], hold_ms=2000) # hold the right joystick to the right - sw.push_right_joystick([-1, 0], hold_ms=2000) # hold the right joystick to the left + sw.push_right_joystick(1.0, 0.0, hold_ms=2000) # hold the right joystick to the right + sw.push_right_joystick(-1.0, 0.0, hold_ms=2000) # hold the right joystick to the left sw.controller_state(duration_ms=2000, buttons="B", left="up") # hold B, while pushing up the left joystick sw.wait(500) sw.wait_for_all_requests() diff --git a/SerialPrograms/Source/PythonBindings/tests/test_core.py b/SerialPrograms/Source/PythonBindings/tests/test_core.py index cebe5bf4f2..021025fc08 100644 --- a/SerialPrograms/Source/PythonBindings/tests/test_core.py +++ b/SerialPrograms/Source/PythonBindings/tests/test_core.py @@ -72,6 +72,13 @@ def test_unreachable_port(): # Commands on a not-ready controller raise RuntimeError, they do not crash. with pytest.raises(RuntimeError): c.push_button(core.BUTTONS["A"], 0, 10, 10) + + +def test_push_joystick_rejects_string(): + """The module's x/y arguments are numbers: a direction-name string is rejected with TypeError.""" + c = core.Controller("nonexistent-port-xyz") + with pytest.raises(TypeError): + c.push_left_joystick("up", 0.0, 0, 10, 0) # These are safe no-ops when not ready. c.wait_for_all_requests() assert c.cancel_all_and_wait(100) is False diff --git a/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py b/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py index 5cd6d5fdcf..978740b3be 100644 --- a/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py +++ b/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py @@ -111,29 +111,19 @@ def test_controller_state_mixed_combination(): def test_push_left_joystick(): - """A stick (x, y) pair is forwarded to push_left_joystick as a single joystick_position tuple with delay = hold + release.""" + """Separate x, y arguments are forwarded to push_left_joystick with delay = hold + release.""" sw, fake = make() - sw.push_left_joystick((0.0, 1.0), hold_ms=1500) - (joystick_position, delay, hold, release), = fake.arguments("push_left_joystick") - assert joystick_position == (0.0, 1.0) and hold == 1500 and delay == 1500 + release - - -def test_push_left_joystick_rejects_string(): - """push_left_joystick() does not accept direction-name strings, only (x, y) coordinates.""" - sw, fake = make() - with pytest.raises(ValueError, match="joystick_position"): - sw.push_left_joystick("up") - with pytest.raises(ValueError): - sw.push_left_joystick(None) - assert fake.commands() == [] + sw.push_left_joystick(0.0, 1.0, hold_ms=1500) + (x, y, delay, hold, release), = fake.arguments("push_left_joystick") + assert (x, y) == (0.0, 1.0) and hold == 1500 and delay == 1500 + release def test_push_right_joystick(): - """A raw [x, y] stick position is forwarded to push_right_joystick with the requested hold and release.""" + """x, y are forwarded to push_right_joystick with the requested hold and release.""" sw, fake = make() - sw.push_right_joystick([0.5, -0.5], hold_ms=300, release_ms=100) - (joystick_position, delay, hold, release), = fake.arguments("push_right_joystick") - assert joystick_position == (0.5, -0.5) and hold == 300 and release == 100 and delay == 400 + sw.push_right_joystick(0.5, -0.5, hold_ms=300, release_ms=100) + (x, y, delay, hold, release), = fake.arguments("push_right_joystick") + assert (x, y) == (0.5, -0.5) and hold == 300 and release == 100 and delay == 400 def test_controller_state_combination(): From 0a7eb70c587a74bcc9d761bddc6bc7a9491fcd7c Mon Sep 17 00:00:00 2001 From: PA Dev Bot <344001113+pa-devbot@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:09:03 +0000 Subject: [PATCH 30/58] Python push_*_joystick(): accept an (x, y) joystick_position tuple The Python layer now takes the stick position as a single (x, y) tuple/list argument, joystick_position, for both push_left_joystick() and push_right_joystick(). The pair is unpacked at the ControllerBackend boundary, so _pa_core (and FakeController) keep the C++-shaped separate x, y arguments: sw.push_left_joystick(joystick_position=(0.0, 1.0), hold_ms=1500) The pair validator is promoted from _parse_stick_pair to a public parse_stick_pair() (two numbers, in [-1, 1], no strings/None), reused by parse_stick() and exported from the package. --- .../Source/PythonBindings/README.md | 2 +- .../pokemon_automation/__init__.py | 4 ++- .../pokemon_automation/buttons.py | 26 ++++++++++++++----- .../pokemon_automation/controller.py | 26 ++++++++++++------- .../switch_connection_test.py | 4 +-- .../tests/test_fake_controller.py | 18 ++++++++++--- 6 files changed, 55 insertions(+), 25 deletions(-) diff --git a/SerialPrograms/Source/PythonBindings/README.md b/SerialPrograms/Source/PythonBindings/README.md index 2c0c5fc557..17f2912972 100644 --- a/SerialPrograms/Source/PythonBindings/README.md +++ b/SerialPrograms/Source/PythonBindings/README.md @@ -104,7 +104,7 @@ with SwitchController("/dev/ttyACM0") as sw: # connects to the Switch via port sw.push_button("A") # tap A (80 ms hold, 80 ms release) sw.push_button("L+R", hold_ms=200) # press L and R together sw.push_dpad("up") # d-pad up - sw.push_left_joystick(0.0, 1.0, hold_ms=1500) # walk forward + sw.push_left_joystick((0.0, 1.0), hold_ms=1500) # walk forward sw.controller_state("B", left="up", duration_ms=2000) # run forward sw.wait(300) sw.wait_for_all_requests() # block until the device executed everything diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py index 1fe126471d..ae6802a836 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py @@ -19,7 +19,7 @@ with SwitchController("/dev/cu.usbserial-0001") as sw: sw.push_button("A") sw.push_dpad("up+right") - sw.push_left_joystick(0.0, 1.0, hold_ms=1500) + sw.push_left_joystick((0.0, 1.0), hold_ms=1500) sw.wait_for_all_requests() """ @@ -32,6 +32,7 @@ check_against_core, parse_buttons, parse_stick, + parse_stick_pair, ) from .controller import SwitchController from .devices import list_serial_ports @@ -49,6 +50,7 @@ "list_serial_ports", "parse_buttons", "parse_stick", + "parse_stick_pair", ] __version__ = "0.1.0" diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py index 6db727d711..03006cdf4c 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py @@ -9,9 +9,10 @@ "UP-RIGHT", "UPRIGHT"). Listing "UP" and "RIGHT" together also means up-right. - Combinations: a list (["L", "R"]) or a "+"-joined string ("L+R", "ZL+A"). - Joystick positions: an (x, y) pair in [-1, 1] with +x = right and +y = up. - push_left_joystick() / push_right_joystick() take the x and y numbers directly; - `parse_stick()` (used for `controller_state()`'s left/right) additionally accepts - a direction name ("up", "down_left", ...) and "neutral"/"center" for convenience. + push_left_joystick() / push_right_joystick() take the pair as a single + argument (validated by `parse_stick_pair()`); `parse_stick()` additionally + accepts a direction name ("up", "down_left", ...) and "neutral"/"center" + for the left/right arguments of controller_state(). The button bit values match `NintendoSwitch::Button` and the d-pad values match `NintendoSwitch::DpadPosition` in @@ -206,12 +207,23 @@ def parse_stick(position: StickArg) -> tuple[float, float]: length = math.hypot(vx, vy) return (vx / length, vy / length) # normalize to [-1, 1] # else parse as (x, y) pair - return _parse_stick_pair(position) + return parse_stick_pair(position) -def _parse_stick_pair(values: Sequence[float]) -> tuple[float, float]: - """Parse an (x, y) pair into floats in [-1, 1]. Raises ValueError otherwise.""" - values = list(values) +def parse_stick_pair(position: Sequence[float]) -> tuple[float, float]: + """Parse an (x, y) stick position into (float, float) in [-1, 1], +y = up. + + Used by `parse_stick()` (for pairs) and by `push_left_joystick()` / + `push_right_joystick()`. Direction-name strings (and None) are not + accepted here: pass exactly two numbers. + """ + if position is None: + raise ValueError("A stick position must be an (x, y) pair, got None.") + if isinstance(position, str): + raise ValueError( + f"A stick position must be an (x, y) pair, not a string (got {position!r})." + ) + values = list(position) if len(values) != 2: raise ValueError(f"A stick position needs exactly two numbers [x, y], got {values!r}.") x, y = float(values[0]), float(values[1]) diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py index accf55f780..1e656db32b 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py @@ -15,7 +15,7 @@ sw.push_button("A") # tap A sw.push_button("L+R", hold_ms=200) # press L and R together sw.push_dpad("up") # d-pad up - sw.push_left_joystick(0.0, 1.0, hold_ms=1500) # walk forward + sw.push_left_joystick((0.0, 1.0), hold_ms=1500) # walk forward sw.controller_state("B", left="up", duration_ms=2000) # run forward sw.wait_for_all_requests() """ @@ -23,6 +23,7 @@ from __future__ import annotations import threading +from collections.abc import Sequence from typing import Protocol from . import _core, buttons as btn @@ -197,33 +198,38 @@ def controller_state(self, buttons: btn.ButtonsArg = None, *, duration_ms ) - def push_left_joystick(self, x: float, y: float, hold_ms: int = 500, + def push_left_joystick(self, joystick_position: Sequence[float], hold_ms: int = 500, release_ms: int = 0) -> None: - """Tilt the left stick to (x, y) for `hold_ms`. + """Tilt the left stick to `joystick_position`, an (x, y) tuple in [-1, 1] + with +x = right and +y = up, for `hold_ms`; e.g. (0.0, 1.0) is up. - `x`, `y`: in [-1, 1] with +x = right and +y = up; e.g. (0.0, 1.0) is up. + The pair is unpacked and passed to the backend as separate x, y + arguments (`_pa_core` keeps the C++ signature). C++: `AbstractController::issue_left_joystick()` (SerialPrograms/Source/Controllers/Controller.h), via `PybindSwitchProController::push_left_joystick()`. """ - self._push_joystick(self._backend.push_left_joystick, x, y, hold_ms, release_ms) + self._push_joystick(self._backend.push_left_joystick, joystick_position, hold_ms, release_ms) - def push_right_joystick(self, x: float, y: float, hold_ms: int = 500, + def push_right_joystick(self, joystick_position: Sequence[float], hold_ms: int = 500, release_ms: int = 0) -> None: - """Tilt the right stick to (x, y) for `hold_ms`. + """Tilt the right stick to `joystick_position`, an (x, y) tuple in [-1, 1] + with +x = right and +y = up, for `hold_ms`; e.g. (0.0, 1.0) is up. - `x`, `y`: in [-1, 1] with +x = right and +y = up; e.g. (0.0, 1.0) is up. + The pair is unpacked and passed to the backend as separate x, y + arguments (`_pa_core` keeps the C++ signature). C++: `AbstractController::issue_right_joystick()` (SerialPrograms/Source/Controllers/Controller.h), via `PybindSwitchProController::push_right_joystick()`. """ - self._push_joystick(self._backend.push_right_joystick, x, y, hold_ms, release_ms) + self._push_joystick(self._backend.push_right_joystick, joystick_position, hold_ms, release_ms) - def _push_joystick(self, send, x: float, y: float, hold_ms: int, release_ms: int) -> None: + def _push_joystick(self, send, joystick_position: Sequence[float], hold_ms: int, release_ms: int) -> None: _check_nonnegative(hold_ms=hold_ms, release_ms=release_ms) self._require_open() + x, y = btn.parse_stick_pair(joystick_position) with self._lock: send(x, y, hold_ms + release_ms, hold_ms, release_ms) diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py index 7ab46a62d9..8b7734bb26 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py @@ -29,8 +29,8 @@ def try_port(port: str) -> bool: sw.push_dpad("right", hold_ms=100) sw.push_dpad("left", hold_ms=100) sw.push_dpad("left", hold_ms=100) - sw.push_right_joystick(1.0, 0.0, hold_ms=2000) # hold the right joystick to the right - sw.push_right_joystick(-1.0, 0.0, hold_ms=2000) # hold the right joystick to the left + sw.push_right_joystick((1.0, 0.0), hold_ms=2000) # hold the right joystick to the right + sw.push_right_joystick((-1.0, 0.0), hold_ms=2000) # hold the right joystick to the left sw.controller_state(duration_ms=2000, buttons="B", left="up") # hold B, while pushing up the left joystick sw.wait(500) sw.wait_for_all_requests() diff --git a/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py b/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py index 978740b3be..af41bd1e84 100644 --- a/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py +++ b/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py @@ -111,17 +111,27 @@ def test_controller_state_mixed_combination(): def test_push_left_joystick(): - """Separate x, y arguments are forwarded to push_left_joystick with delay = hold + release.""" + """An (x, y) tuple is forwarded to the backend as separate x, y arguments, with delay = hold + release.""" sw, fake = make() - sw.push_left_joystick(0.0, 1.0, hold_ms=1500) + sw.push_left_joystick((0.0, 1.0), hold_ms=1500) (x, y, delay, hold, release), = fake.arguments("push_left_joystick") assert (x, y) == (0.0, 1.0) and hold == 1500 and delay == 1500 + release +def test_push_left_joystick_rejects_string(): + """push_left_joystick() wants an (x, y) tuple, not a direction-name string.""" + sw, fake = make() + with pytest.raises(ValueError, match="not a string"): + sw.push_left_joystick("up") + with pytest.raises(ValueError): + sw.push_left_joystick(None) + assert fake.commands() == [] + + def test_push_right_joystick(): - """x, y are forwarded to push_right_joystick with the requested hold and release.""" + """A [x, y] list is accepted too, forwarded with the requested hold and release.""" sw, fake = make() - sw.push_right_joystick(0.5, -0.5, hold_ms=300, release_ms=100) + sw.push_right_joystick([0.5, -0.5], hold_ms=300, release_ms=100) (x, y, delay, hold, release), = fake.arguments("push_right_joystick") assert (x, y) == (0.5, -0.5) and hold == 300 and release == 100 and delay == 400 From 6ab581a81d0ffd90b7ee3bbae8a2ddfefb100d0f Mon Sep 17 00:00:00 2001 From: jw098 Date: Wed, 21 Oct 2026 16:22:46 -0700 Subject: [PATCH 31/58] update comments. add kwargs --- .../PythonBindings/pokemon_automation/controller.py | 8 ++++---- .../pokemon_automation/switch_connection_test.py | 4 ++-- .../Source/PythonBindings/tests/test_fake_controller.py | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py index 1e656db32b..9f594ef253 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py @@ -200,8 +200,8 @@ def controller_state(self, buttons: btn.ButtonsArg = None, *, def push_left_joystick(self, joystick_position: Sequence[float], hold_ms: int = 500, release_ms: int = 0) -> None: - """Tilt the left stick to `joystick_position`, an (x, y) tuple in [-1, 1] - with +x = right and +y = up, for `hold_ms`; e.g. (0.0, 1.0) is up. + """Tilt the left stick to `joystick_position`, an (x, y) tuple in [-1, 1] for `hold_ms` + -x=left, x=0=neutral, +x=right. -y=down, y=0=neutral, +y=up. e.g. (0.0, 1.0) is up. The pair is unpacked and passed to the backend as separate x, y arguments (`_pa_core` keeps the C++ signature). @@ -214,8 +214,8 @@ def push_left_joystick(self, joystick_position: Sequence[float], hold_ms: int = def push_right_joystick(self, joystick_position: Sequence[float], hold_ms: int = 500, release_ms: int = 0) -> None: - """Tilt the right stick to `joystick_position`, an (x, y) tuple in [-1, 1] - with +x = right and +y = up, for `hold_ms`; e.g. (0.0, 1.0) is up. + """Tilt the right stick to `joystick_position`, an (x, y) tuple in [-1, 1] for `hold_ms` + -x=left, x=0=neutral, +x=right. -y=down, y=0=neutral, +y=up. e.g. (0.0, 1.0) is up. The pair is unpacked and passed to the backend as separate x, y arguments (`_pa_core` keeps the C++ signature). diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py index 8b7734bb26..dbb041e8e9 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py @@ -29,8 +29,8 @@ def try_port(port: str) -> bool: sw.push_dpad("right", hold_ms=100) sw.push_dpad("left", hold_ms=100) sw.push_dpad("left", hold_ms=100) - sw.push_right_joystick((1.0, 0.0), hold_ms=2000) # hold the right joystick to the right - sw.push_right_joystick((-1.0, 0.0), hold_ms=2000) # hold the right joystick to the left + sw.push_right_joystick(joystick_position=(1.0, 0.0), hold_ms=2000) # hold the right joystick to the right + sw.push_right_joystick(joystick_position=(-1.0, 0.0), hold_ms=2000) # hold the right joystick to the left sw.controller_state(duration_ms=2000, buttons="B", left="up") # hold B, while pushing up the left joystick sw.wait(500) sw.wait_for_all_requests() diff --git a/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py b/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py index af41bd1e84..bd03ab01a8 100644 --- a/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py +++ b/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py @@ -131,7 +131,7 @@ def test_push_left_joystick_rejects_string(): def test_push_right_joystick(): """A [x, y] list is accepted too, forwarded with the requested hold and release.""" sw, fake = make() - sw.push_right_joystick([0.5, -0.5], hold_ms=300, release_ms=100) + sw.push_right_joystick(joystick_position=(0.5, -0.5), hold_ms=300, release_ms=100) (x, y, delay, hold, release), = fake.arguments("push_right_joystick") assert (x, y) == (0.5, -0.5) and hold == 300 and release == 100 and delay == 400 From 9c9a0081a09b9ce12c0115491fa287f27fecc3a8 Mon Sep 17 00:00:00 2001 From: PA Dev Bot <344001113+pa-devbot@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:30:19 +0000 Subject: [PATCH 32/58] Python controller_state(): left_joystick/right_joystick as (x, y) tuples controller_state() now takes the sticks as (x, y) tuples, renamed from left=/right= to left_joystick=/right_joystick= to match push_*_joystick(). None (the default) releases the stick; direction-name strings are no longer accepted there (parse_stick_pair() validates, so the same error messages as joystick_position apply). The pairs are unpacked at the ControllerBackend boundary, so _pa_core keeps the C++-shaped separate left_x/left_y/right_x/right_y arguments. Also tighten the joystick_position annotations from Sequence[float] to tuple[float, float] (lists still work at runtime; the annotation now says exactly what is expected). --- .../Source/PythonBindings/README.md | 2 +- .../pokemon_automation/buttons.py | 12 ++++---- .../pokemon_automation/controller.py | 28 +++++++++++-------- .../switch_connection_test.py | 2 +- .../tests/test_fake_controller.py | 10 ++++++- 5 files changed, 35 insertions(+), 19 deletions(-) diff --git a/SerialPrograms/Source/PythonBindings/README.md b/SerialPrograms/Source/PythonBindings/README.md index 17f2912972..f6a9574c2c 100644 --- a/SerialPrograms/Source/PythonBindings/README.md +++ b/SerialPrograms/Source/PythonBindings/README.md @@ -105,7 +105,7 @@ with SwitchController("/dev/ttyACM0") as sw: # connects to the Switch via port sw.push_button("L+R", hold_ms=200) # press L and R together sw.push_dpad("up") # d-pad up sw.push_left_joystick((0.0, 1.0), hold_ms=1500) # walk forward - sw.controller_state("B", left="up", duration_ms=2000) # run forward + sw.controller_state("B", left_joystick=(0.0, 1.0), duration_ms=2000) # run forward sw.wait(300) sw.wait_for_all_requests() # block until the device executed everything ``` diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py index 03006cdf4c..1fc4873c13 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py @@ -9,10 +9,11 @@ "UP-RIGHT", "UPRIGHT"). Listing "UP" and "RIGHT" together also means up-right. - Combinations: a list (["L", "R"]) or a "+"-joined string ("L+R", "ZL+A"). - Joystick positions: an (x, y) pair in [-1, 1] with +x = right and +y = up. - push_left_joystick() / push_right_joystick() take the pair as a single + push_left_joystick() / push_right_joystick() and the left_joystick / + right_joystick arguments of controller_state() take the pair as a single argument (validated by `parse_stick_pair()`); `parse_stick()` additionally - accepts a direction name ("up", "down_left", ...) and "neutral"/"center" - for the left/right arguments of controller_state(). + accepts a direction name ("up", "down_left", ...) and "neutral"/"center", + for use when a direction name is more readable than coordinates. The button bit values match `NintendoSwitch::Button` and the d-pad values match `NintendoSwitch::DpadPosition` in @@ -210,11 +211,12 @@ def parse_stick(position: StickArg) -> tuple[float, float]: return parse_stick_pair(position) -def parse_stick_pair(position: Sequence[float]) -> tuple[float, float]: +def parse_stick_pair(position: tuple[float, float]) -> tuple[float, float]: """Parse an (x, y) stick position into (float, float) in [-1, 1], +y = up. Used by `parse_stick()` (for pairs) and by `push_left_joystick()` / - `push_right_joystick()`. Direction-name strings (and None) are not + `push_right_joystick()` and the left_joystick / right_joystick arguments + of `controller_state()`. Direction-name strings (and None) are not accepted here: pass exactly two numbers. """ if position is None: diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py index 9f594ef253..dcbcb7496d 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py @@ -16,14 +16,13 @@ sw.push_button("L+R", hold_ms=200) # press L and R together sw.push_dpad("up") # d-pad up sw.push_left_joystick((0.0, 1.0), hold_ms=1500) # walk forward - sw.controller_state("B", left="up", duration_ms=2000) # run forward + sw.controller_state("B", left_joystick=(0.0, 1.0), duration_ms=2000) # run forward sw.wait_for_all_requests() """ from __future__ import annotations import threading -from collections.abc import Sequence from typing import Protocol from . import _core, buttons as btn @@ -178,19 +177,26 @@ def push_dpad(self, position: btn.ButtonsArg, hold_ms: int = DEFAULT_HOLD_MS, self._backend.push_dpad(parsed.dpad, hold_ms + release_ms, hold_ms, release_ms) def controller_state(self, buttons: btn.ButtonsArg = None, *, - left: btn.StickArg = None, right: btn.StickArg = None, + left_joystick: tuple[float, float] | None = None, + right_joystick: tuple[float, float] | None = None, duration_ms: int = 500) -> None: """Hold any combination of buttons, d-pad and sticks for `duration_ms`. - `buttons` may mix buttons and d-pad directions ("ZL+up"). Everything not - specified is released for the whole hold. The argument order matches - `pbf_controller_state()`: buttons/d-pad first, sticks, then duration. + `buttons` may mix buttons and d-pad directions ("ZL+up"). + `left_joystick` / `right_joystick` are (x, y) tuples in [-1, 1]. + -x=left, x=0=neutral, +x=right. -y=down, y=0=neutral, +y=up. + e.g. (0.0, 1.0) is up. None (the default) releases that stick. The + argument order matches `pbf_controller_state()`: buttons/d-pad first, + sticks, then duration. + + The stick tuples are unpacked and passed to the backend as separate + x, y arguments (`_pa_core` keeps the C++ signature). """ _check_nonnegative(duration_ms=duration_ms) self._require_open() parsed = btn.parse_buttons(buttons) - left_x, left_y = btn.parse_stick(left) if left is not None else (0.0, 0.0) - right_x, right_y = btn.parse_stick(right) if right is not None else (0.0, 0.0) + left_x, left_y = btn.parse_stick_pair(left_joystick) if left_joystick is not None else (0.0, 0.0) + right_x, right_y = btn.parse_stick_pair(right_joystick) if right_joystick is not None else (0.0, 0.0) with self._lock: self._backend.controller_state( parsed.bitfield, parsed.dpad, @@ -198,7 +204,7 @@ def controller_state(self, buttons: btn.ButtonsArg = None, *, duration_ms ) - def push_left_joystick(self, joystick_position: Sequence[float], hold_ms: int = 500, + def push_left_joystick(self, joystick_position: tuple[float, float], hold_ms: int = 500, release_ms: int = 0) -> None: """Tilt the left stick to `joystick_position`, an (x, y) tuple in [-1, 1] for `hold_ms` -x=left, x=0=neutral, +x=right. -y=down, y=0=neutral, +y=up. e.g. (0.0, 1.0) is up. @@ -212,7 +218,7 @@ def push_left_joystick(self, joystick_position: Sequence[float], hold_ms: int = """ self._push_joystick(self._backend.push_left_joystick, joystick_position, hold_ms, release_ms) - def push_right_joystick(self, joystick_position: Sequence[float], hold_ms: int = 500, + def push_right_joystick(self, joystick_position: tuple[float, float], hold_ms: int = 500, release_ms: int = 0) -> None: """Tilt the right stick to `joystick_position`, an (x, y) tuple in [-1, 1] for `hold_ms` -x=left, x=0=neutral, +x=right. -y=down, y=0=neutral, +y=up. e.g. (0.0, 1.0) is up. @@ -226,7 +232,7 @@ def push_right_joystick(self, joystick_position: Sequence[float], hold_ms: int = """ self._push_joystick(self._backend.push_right_joystick, joystick_position, hold_ms, release_ms) - def _push_joystick(self, send, joystick_position: Sequence[float], hold_ms: int, release_ms: int) -> None: + def _push_joystick(self, send, joystick_position: tuple[float, float], hold_ms: int, release_ms: int) -> None: _check_nonnegative(hold_ms=hold_ms, release_ms=release_ms) self._require_open() x, y = btn.parse_stick_pair(joystick_position) diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py index dbb041e8e9..278cdc220a 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py @@ -31,7 +31,7 @@ def try_port(port: str) -> bool: sw.push_dpad("left", hold_ms=100) sw.push_right_joystick(joystick_position=(1.0, 0.0), hold_ms=2000) # hold the right joystick to the right sw.push_right_joystick(joystick_position=(-1.0, 0.0), hold_ms=2000) # hold the right joystick to the left - sw.controller_state(duration_ms=2000, buttons="B", left="up") # hold B, while pushing up the left joystick + sw.controller_state(duration_ms=2000, buttons="B", left_joystick=(0.0, 1.0)) # hold B, while pushing up the left joystick sw.wait(500) sw.wait_for_all_requests() print(" cancel confirmed:", sw.cancel_all_and_wait(500)) diff --git a/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py b/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py index bd03ab01a8..b152be5e1c 100644 --- a/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py +++ b/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py @@ -98,6 +98,14 @@ def test_push_dpad_needs_something(): assert fake.commands() == [] +def test_controller_state_rejects_string_stick(): + """controller_state() takes (x, y) tuples for its sticks, not direction-name strings.""" + sw, fake = make() + with pytest.raises(ValueError, match="not a string"): + sw.controller_state("B", left_joystick="up", duration_ms=2000) + assert fake.commands() == [] + + def test_controller_state_mixed_combination(): """Buttons and d-pad held together go out as a single controller_state with the right bitfield, d-pad position, neutral sticks and duration last.""" sw, fake = make() @@ -139,7 +147,7 @@ def test_push_right_joystick(): def test_controller_state_combination(): """Buttons and both sticks can be held at once via controller_state, with everything not specified left neutral.""" sw, fake = make() - sw.controller_state("B", left="up", right=[1.0, 0.0], duration_ms=2000) + sw.controller_state("B", left_joystick=(0.0, 1.0), right_joystick=(1.0, 0.0), duration_ms=2000) (buttons, dpad, left_x, left_y, right_x, right_y, duration), = fake.arguments("controller_state") assert duration == 2000 assert buttons == BUTTON_BITS["B"] From 04884c5cbb4f5e6be662e3316861c8ec3d01a1e3 Mon Sep 17 00:00:00 2001 From: PA Dev Bot <344001113+pa-devbot@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:58:26 +0000 Subject: [PATCH 33/58] Python controller_state(): split buttons and dpad; push_dpad arg -> dpad controller_state() now takes buttons and dpad as separate arguments, matching pbf_controller_state() and the C++ backend (button_bitfield, dpad_position, ...): sw.controller_state("B", "up", left_joystick=(0.0, 1.0), duration_ms=2000) The buttons argument rejects d-pad directions (and the dpad argument rejects buttons) with an error pointing at the other argument - the same rules push_button()/push_dpad() already enforce. The one-string mixed form ("ZL+up") is no longer accepted. push_dpad()'s argument is renamed position -> dpad. _pa_core / FakeController are unchanged (the backend already has them separate). --- .../Source/PythonBindings/README.md | 2 +- .../pokemon_automation/controller.py | 37 +++++++++++++------ .../tests/test_fake_controller.py | 14 ++++++- 3 files changed, 38 insertions(+), 15 deletions(-) diff --git a/SerialPrograms/Source/PythonBindings/README.md b/SerialPrograms/Source/PythonBindings/README.md index f6a9574c2c..cee6d2faf8 100644 --- a/SerialPrograms/Source/PythonBindings/README.md +++ b/SerialPrograms/Source/PythonBindings/README.md @@ -105,7 +105,7 @@ with SwitchController("/dev/ttyACM0") as sw: # connects to the Switch via port sw.push_button("L+R", hold_ms=200) # press L and R together sw.push_dpad("up") # d-pad up sw.push_left_joystick((0.0, 1.0), hold_ms=1500) # walk forward - sw.controller_state("B", left_joystick=(0.0, 1.0), duration_ms=2000) # run forward + sw.controller_state("B", "up", left_joystick=(0.0, 1.0), duration_ms=2000) # run forward sw.wait(300) sw.wait_for_all_requests() # block until the device executed everything ``` diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py index dcbcb7496d..eade6511b2 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py @@ -16,7 +16,7 @@ sw.push_button("L+R", hold_ms=200) # press L and R together sw.push_dpad("up") # d-pad up sw.push_left_joystick((0.0, 1.0), hold_ms=1500) # walk forward - sw.controller_state("B", left_joystick=(0.0, 1.0), duration_ms=2000) # run forward + sw.controller_state("B", "up", left_joystick=(0.0, 1.0), duration_ms=2000) # run forward sw.wait_for_all_requests() """ @@ -150,11 +150,11 @@ def push_button(self, buttons: btn.ButtonsArg, hold_ms: int = DEFAULT_HOLD_MS, with self._lock: self._backend.push_button(parsed.bitfield, hold_ms + release_ms, hold_ms, release_ms) - def push_dpad(self, position: btn.ButtonsArg, hold_ms: int = DEFAULT_HOLD_MS, + def push_dpad(self, dpad: btn.ButtonsArg, hold_ms: int = DEFAULT_HOLD_MS, release_ms: int = DEFAULT_RELEASE_MS) -> None: """Tap a d-pad direction. - `position`: "up", "up+right" (or "UP_RIGHT"), ["up", "right"], ... + `dpad`: "up", "up+right" (or "UP_RIGHT"), ["up", "right"], ... For buttons use `push_button()`; to hold buttons and d-pad together use `controller_state()`. @@ -165,10 +165,10 @@ def push_dpad(self, position: btn.ButtonsArg, hold_ms: int = DEFAULT_HOLD_MS, """ _check_nonnegative(hold_ms=hold_ms, release_ms=release_ms) self._require_open() - parsed = btn.parse_buttons(position) + parsed = btn.parse_buttons(dpad) if parsed.has_buttons: raise ValueError( - f"push_dpad() only accepts d-pad directions, but {position!r} includes buttons. " + f"push_dpad() only accepts d-pad directions, but {dpad!r} includes buttons. " "Use push_button() for buttons or controller_state() to combine them." ) if not parsed.has_dpad: @@ -176,30 +176,43 @@ def push_dpad(self, position: btn.ButtonsArg, hold_ms: int = DEFAULT_HOLD_MS, with self._lock: self._backend.push_dpad(parsed.dpad, hold_ms + release_ms, hold_ms, release_ms) - def controller_state(self, buttons: btn.ButtonsArg = None, *, + def controller_state(self, buttons: btn.ButtonsArg = None, dpad: btn.ButtonsArg = None, *, left_joystick: tuple[float, float] | None = None, right_joystick: tuple[float, float] | None = None, duration_ms: int = 500) -> None: """Hold any combination of buttons, d-pad and sticks for `duration_ms`. - `buttons` may mix buttons and d-pad directions ("ZL+up"). + `buttons`: button names only ("A", "L+R"), or None to release all buttons. + `dpad`: d-pad directions only ("up", "up+right", ["up", "right"]), or None + to release the d-pad. The argument order matches `pbf_controller_state()` + and the C++ backend: buttons, d-pad, sticks, then duration. + `left_joystick` / `right_joystick` are (x, y) tuples in [-1, 1]. -x=left, x=0=neutral, +x=right. -y=down, y=0=neutral, +y=up. - e.g. (0.0, 1.0) is up. None (the default) releases that stick. The - argument order matches `pbf_controller_state()`: buttons/d-pad first, - sticks, then duration. + e.g. (0.0, 1.0) is up. None (the default) releases that stick. The stick tuples are unpacked and passed to the backend as separate x, y arguments (`_pa_core` keeps the C++ signature). """ _check_nonnegative(duration_ms=duration_ms) self._require_open() - parsed = btn.parse_buttons(buttons) + parsed_buttons = btn.parse_buttons(buttons) + if parsed_buttons.has_dpad: + raise ValueError( + f"controller_state(): the buttons argument must not include d-pad " + f"directions ({buttons!r}). Use the dpad argument instead." + ) + parsed_dpad = btn.parse_buttons(dpad) + if parsed_dpad.has_buttons: + raise ValueError( + f"controller_state(): the dpad argument must not include buttons " + f"({dpad!r}). Use the buttons argument instead." + ) left_x, left_y = btn.parse_stick_pair(left_joystick) if left_joystick is not None else (0.0, 0.0) right_x, right_y = btn.parse_stick_pair(right_joystick) if right_joystick is not None else (0.0, 0.0) with self._lock: self._backend.controller_state( - parsed.bitfield, parsed.dpad, + parsed_buttons.bitfield, parsed_dpad.dpad, left_x, left_y, right_x, right_y, duration_ms ) diff --git a/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py b/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py index b152be5e1c..203472dc0d 100644 --- a/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py +++ b/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py @@ -106,10 +106,20 @@ def test_controller_state_rejects_string_stick(): assert fake.commands() == [] +def test_controller_state_rejects_mixed_arguments(): + """The buttons argument rejects d-pad directions (and vice versa), pointing at the other argument.""" + sw, fake = make() + with pytest.raises(ValueError, match="dpad argument"): + sw.controller_state("ZL+up", duration_ms=60) + with pytest.raises(ValueError, match="buttons argument"): + sw.controller_state(None, "B", duration_ms=60) + assert fake.commands() == [] + + def test_controller_state_mixed_combination(): - """Buttons and d-pad held together go out as a single controller_state with the right bitfield, d-pad position, neutral sticks and duration last.""" + """Buttons and d-pad held via separate arguments go out as a single controller_state with the right bitfield, d-pad position, neutral sticks and duration last.""" sw, fake = make() - sw.controller_state("ZL+up", duration_ms=60) + sw.controller_state("ZL", "up", duration_ms=60) assert fake.commands() == ["controller_state"] (buttons, dpad, left_x, left_y, right_x, right_y, duration), = fake.arguments("controller_state") assert duration == 60 From c1425e843b0dfa37915c9fc31142c68ea42c681c Mon Sep 17 00:00:00 2001 From: jw098 Date: Wed, 21 Oct 2026 17:06:57 -0700 Subject: [PATCH 34/58] update comments --- .../Source/PythonBindings/pokemon_automation/buttons.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py index 1fc4873c13..bf8b403e1a 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py @@ -90,13 +90,13 @@ ButtonsArg = str | Sequence[str] | None """ ButtonsArg -- accepts both Buttons and D-pad inputs (see above for the exact strings). +- can be either Button or D-pad inputs (see above for the exact strings). - validated by `parse_buttons()` """ StickArg = str | Sequence[float] | None """ -StickArg +StickArg (currently unused) - Accepts a direction name ("up", "down_left", "neutral") or an (x, y) pair. - validated by `parse_stick()` """ @@ -212,7 +212,7 @@ def parse_stick(position: StickArg) -> tuple[float, float]: def parse_stick_pair(position: tuple[float, float]) -> tuple[float, float]: - """Parse an (x, y) stick position into (float, float) in [-1, 1], +y = up. + """Parse an (x, y) stick position into (float, float) in [-1, 1] Used by `parse_stick()` (for pairs) and by `push_left_joystick()` / `push_right_joystick()` and the left_joystick / right_joystick arguments From 42b9a44ccba73701805fde27ed8813e9288385f9 Mon Sep 17 00:00:00 2001 From: jw098 Date: Wed, 21 Oct 2026 17:22:08 -0700 Subject: [PATCH 35/58] minor fix --- .../PythonBindings/pokemon_automation/switch_connection_test.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py index 278cdc220a..efa614ad3f 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py @@ -31,7 +31,7 @@ def try_port(port: str) -> bool: sw.push_dpad("left", hold_ms=100) sw.push_right_joystick(joystick_position=(1.0, 0.0), hold_ms=2000) # hold the right joystick to the right sw.push_right_joystick(joystick_position=(-1.0, 0.0), hold_ms=2000) # hold the right joystick to the left - sw.controller_state(duration_ms=2000, buttons="B", left_joystick=(0.0, 1.0)) # hold B, while pushing up the left joystick + sw.controller_state(buttons="B", left_joystick=(0.0, 1.0), duration_ms=2000) # hold B, while pushing up the left joystick sw.wait(500) sw.wait_for_all_requests() print(" cancel confirmed:", sw.cancel_all_and_wait(500)) From f9a9070bd1873789cbfdd8db2259c61e9b5cb8ca Mon Sep 17 00:00:00 2001 From: jw098 Date: Wed, 21 Oct 2026 23:28:30 -0700 Subject: [PATCH 36/58] update switch_connection_test.py --- .../PythonBindings/pokemon_automation/switch_connection_test.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py index efa614ad3f..041decbaa0 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py @@ -31,6 +31,8 @@ def try_port(port: str) -> bool: sw.push_dpad("left", hold_ms=100) sw.push_right_joystick(joystick_position=(1.0, 0.0), hold_ms=2000) # hold the right joystick to the right sw.push_right_joystick(joystick_position=(-1.0, 0.0), hold_ms=2000) # hold the right joystick to the left + sw.push_left_joystick(joystick_position=(1.0, 0.0), hold_ms=2000) # hold the left joystick to the right + sw.push_left_joystick(joystick_position=(-1.0, 0.0), hold_ms=2000) # hold the left joystick to the left sw.controller_state(buttons="B", left_joystick=(0.0, 1.0), duration_ms=2000) # hold B, while pushing up the left joystick sw.wait(500) sw.wait_for_all_requests() From dc683a22ffbe5352f259eaadd0486be92c5506a3 Mon Sep 17 00:00:00 2001 From: jw098 Date: Wed, 21 Oct 2026 23:47:25 -0700 Subject: [PATCH 37/58] update comments --- .../pokemon_automation/controller.py | 39 +++++++------------ 1 file changed, 15 insertions(+), 24 deletions(-) diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py index eade6511b2..a40fb1cb2e 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py @@ -125,17 +125,18 @@ def push_button(self, buttons: btn.ButtonsArg, hold_ms: int = DEFAULT_HOLD_MS, release_ms: int = DEFAULT_RELEASE_MS) -> None: """Tap a button combination (d-pad directions not accepted). - `buttons`: "A", "L+R", ["ZL", "B"], ... (see `pokemon_automation.buttons`). - For d-pad input use `push_dpad()`; to hold buttons and d-pad together use + `buttons`: May be a single button, or multiple buttons. e.g. "A", "L+R", ["ZL", "B"], ... + For d-pad input use `push_dpad()`; to hold buttons and d-pad together, use `controller_state()`. + + This function does not allow for overlapping button presses. For that, use controller_state(). + However, the pybind backend does expose `delay_ms`. If this is set to less than `hold_ms`, one may + also overlap button presses, similar to the functions in NintendoSwitch_Commands_Superscalar.h C++: `AbstractController::issue_buttons()` (SerialPrograms/Source/Controllers/Controller.h), via `PybindSwitchProController::push_button()` (SerialPrograms/Source/Integrations/PybindSwitchProController.h). - Queued back to back, the same timing `pbf_press_button()` uses - (delay = hold + release); the backend's `delay_ms` is available by - calling the `_pa_core.Controller` directly. """ _check_nonnegative(hold_ms=hold_ms, release_ms=release_ms) self._require_open() @@ -154,8 +155,9 @@ def push_dpad(self, dpad: btn.ButtonsArg, hold_ms: int = DEFAULT_HOLD_MS, release_ms: int = DEFAULT_RELEASE_MS) -> None: """Tap a d-pad direction. - `dpad`: "up", "up+right" (or "UP_RIGHT"), ["up", "right"], ... - For buttons use `push_button()`; to hold buttons and d-pad together use + `dpad`: May be a single direction, or multiple directions as long as they are not contradictory. + e.g. "up", "up+right" (or "UP_RIGHT"), ["up", "right"], + For buttons use `push_button()`; to hold buttons and d-pad together, use `controller_state()`. C++: `AbstractController::issue_dpad()` @@ -182,17 +184,12 @@ def controller_state(self, buttons: btn.ButtonsArg = None, dpad: btn.ButtonsArg duration_ms: int = 500) -> None: """Hold any combination of buttons, d-pad and sticks for `duration_ms`. - `buttons`: button names only ("A", "L+R"), or None to release all buttons. - `dpad`: d-pad directions only ("up", "up+right", ["up", "right"]), or None - to release the d-pad. The argument order matches `pbf_controller_state()` - and the C++ backend: buttons, d-pad, sticks, then duration. - - `left_joystick` / `right_joystick` are (x, y) tuples in [-1, 1]. + * `buttons`: button names only ("A", "L+R"), or None to release all buttons. + * `dpad`: d-pad directions only (e.g. "up", "up+right", ["up", "right"]), or None + to release the d-pad. + * `left_joystick` / `right_joystick` are (x, y) tuples in [-1, 1]. -x=left, x=0=neutral, +x=right. -y=down, y=0=neutral, +y=up. e.g. (0.0, 1.0) is up. None (the default) releases that stick. - - The stick tuples are unpacked and passed to the backend as separate - x, y arguments (`_pa_core` keeps the C++ signature). """ _check_nonnegative(duration_ms=duration_ms) self._require_open() @@ -219,12 +216,9 @@ def controller_state(self, buttons: btn.ButtonsArg = None, dpad: btn.ButtonsArg def push_left_joystick(self, joystick_position: tuple[float, float], hold_ms: int = 500, release_ms: int = 0) -> None: - """Tilt the left stick to `joystick_position`, an (x, y) tuple in [-1, 1] for `hold_ms` + """Tilt the left stick to `joystick_position`, an (x, y) tuple in [-1, 1], for `hold_ms` -x=left, x=0=neutral, +x=right. -y=down, y=0=neutral, +y=up. e.g. (0.0, 1.0) is up. - The pair is unpacked and passed to the backend as separate x, y - arguments (`_pa_core` keeps the C++ signature). - C++: `AbstractController::issue_left_joystick()` (SerialPrograms/Source/Controllers/Controller.h), via `PybindSwitchProController::push_left_joystick()`. @@ -233,12 +227,9 @@ def push_left_joystick(self, joystick_position: tuple[float, float], hold_ms: in def push_right_joystick(self, joystick_position: tuple[float, float], hold_ms: int = 500, release_ms: int = 0) -> None: - """Tilt the right stick to `joystick_position`, an (x, y) tuple in [-1, 1] for `hold_ms` + """Tilt the right stick to `joystick_position`, an (x, y) tuple in [-1, 1], for `hold_ms` -x=left, x=0=neutral, +x=right. -y=down, y=0=neutral, +y=up. e.g. (0.0, 1.0) is up. - The pair is unpacked and passed to the backend as separate x, y - arguments (`_pa_core` keeps the C++ signature). - C++: `AbstractController::issue_right_joystick()` (SerialPrograms/Source/Controllers/Controller.h), via `PybindSwitchProController::push_right_joystick()`. From da174963e8a340d6135db41c4309df388f21a1a7 Mon Sep 17 00:00:00 2001 From: jw098 Date: Thu, 22 Oct 2026 00:27:58 -0700 Subject: [PATCH 38/58] update README --- .../Source/PythonBindings/README.md | 87 ++++++++++++------- 1 file changed, 54 insertions(+), 33 deletions(-) diff --git a/SerialPrograms/Source/PythonBindings/README.md b/SerialPrograms/Source/PythonBindings/README.md index cee6d2faf8..d1bd786e72 100644 --- a/SerialPrograms/Source/PythonBindings/README.md +++ b/SerialPrograms/Source/PythonBindings/README.md @@ -62,7 +62,7 @@ To install it for a project: pip install -e SerialPrograms/Source/PythonBindings # starting from the root Arduino-Source ``` -## Switch Connection test +## Example usage: Switch Connection test `switch_connection_test.py` will connect to the Switch via PABotBase2 and send a few simple commands. @@ -91,46 +91,67 @@ cd SerialPrograms/Source/PythonBindings # starting from the root Arduino-Source python -m pytest ``` +Running pytest, it will look insid `pyproject.toml`, then run the all tests +within the `tests` folder. The tests that need the compiled module are skipped when `_pa_core` has not been built. -## More example usage - -```python -from pokemon_automation import SwitchController, list_serial_ports - -print(list_serial_ports()) -with SwitchController("/dev/ttyACM0") as sw: # connects to the Switch via port /dev/ttyACM0 - print(sw.current_status()) # device name and firmware version - sw.push_button("A") # tap A (80 ms hold, 80 ms release) - sw.push_button("L+R", hold_ms=200) # press L and R together - sw.push_dpad("up") # d-pad up - sw.push_left_joystick((0.0, 1.0), hold_ms=1500) # walk forward - sw.controller_state("B", "up", left_joystick=(0.0, 1.0), duration_ms=2000) # run forward - sw.wait(300) - sw.wait_for_all_requests() # block until the device executed everything -``` - -Commands are queued on the microcontroller and return as soon as they are -scheduled, mirroring the `pbf_*()` functions of the main program. The command -methods of `SwitchController` match the names of the backend they wrap -(`_pa_core.Controller`, and with it the C++ -`PybindSwitchProController` methods): - -- `push_button()`: taps buttons on the Switch. -- `push_dpad()`: taps a d-pad direction. -- `push_left_joystick()` / `push_right_joystick()`: moves a stick. +## Controller Commands +The command methods of `SwitchController` match the names of the backend they wrap +(`_pa_core.Controller` from PythonBindings_Module.cpp, and with it the C++ +`PybindSwitchProController` methods). Here's a brief description of some of the +controller functions: + +Controller commands: queued on the microcontroller and return as soon as they are +scheduled. +- `push_button()`: presses button(s) on the Switch. +- `push_dpad()`: presses the d-pad. +- `push_left_joystick()` / `push_right_joystick()`: moves the joystick. - `controller_state()`: simultaneously holds/presses any combination of buttons, d-pad and sticks. -- `wait()`: queues a pause with nothing pressed. -- `wait_for_all_requests()`: to wait for all queued commands to execute. -- `cancel_all_and_wait()`: (thread-safe) to -drop the queue, release all inputs and wait for the device to confirm the -neutral state — e.g. from an emergency-stop thread. +- `wait()`: queues a pause, with nothing pressed. + +Other commands: +- `wait_for_all_requests()`: Blocks code execution until all the queued commands have been executed. +- `cancel_all_and_wait()`: Drops all commands queued on the microcontroller, release all inputs and +waits for the device to confirm the neutral state — e.g. from an emergency-stop thread. - `close()`: runs `cancel_all_and_wait()`, then drops the connection. See `controller.py` for more details. -## Notes +See `switch_connection_test.py` for example usage. + +## Notes on the command queue + +As mentioned above, commands are queued on the microcontroller and return as soon as they are +scheduled. i.e. the main program doesn't pause or wait for the physical button press to finish +before moving to the next line of code. It hands the command to the microcontroller and instantly moves on. +This mirrors the `pbf_*()` functions of the C++ program. + +Example 1: +```py +push_left_joystick(..., duration=10s) +push_left_joystick(..., duration=10s) +push_left_joystick(..., duration=10s) +do_something_else() +``` + +Suppose you have 3 calls to `push_left_joystick()`, where you push the joystick +for 10 seconds each. The above 3 commands will be queued onto the microcontroller, +then immediately move onto `do_something_else()`, even when the above 3 commands +have not yet finished executing on the microcontroller. If you want +`do_something_else()` to only start once the three commands have finished +executing on the microcontroller, you need to use `wait_for_all_requests()`. + +Example 2: +```py +push_left_joystick(..., duration=10s) +push_left_joystick(..., duration=10s) +push_left_joystick(..., duration=10s) +wait_for_all_requests() # waits for the above, then runs do_something_else() below +do_something_else() +``` + +## Other Notes - All durations are milliseconds. - C++ `PokemonAutomation::Exception`s surface as Python `RuntimeError`s. From 7f515b49122c5c62a056c422665aa33bc9d7563b Mon Sep 17 00:00:00 2001 From: jw098 Date: Thu, 22 Oct 2026 00:46:49 -0700 Subject: [PATCH 39/58] update comments --- .../Integrations/PybindSwitchController.h | 38 ++++++------------- 1 file changed, 11 insertions(+), 27 deletions(-) diff --git a/SerialPrograms/Source/Integrations/PybindSwitchController.h b/SerialPrograms/Source/Integrations/PybindSwitchController.h index e3fed77a06..c194108492 100644 --- a/SerialPrograms/Source/Integrations/PybindSwitchController.h +++ b/SerialPrograms/Source/Integrations/PybindSwitchController.h @@ -80,17 +80,17 @@ class PybindSwitchProController{ bool cancel_all_and_wait(uint64_t timeout_ms); public: - // Commands. These line up with the PBF API (`pbf_*()`) in + // Commands. These line up with the pbf functions in // SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h - // (input first, then the timing), without the `context` parameter (Python - // does not need it). The `push_*()` commands additionally take a `delay_ms` - // that `pbf_*()` does not expose; `pbf_*()` always uses delay = hold + release - // (back to back), which is what `delay_ms = hold_ms + release_ms` gives here. - // - // `delay_ms` is how long to wait before the next command may start, `hold_ms` - // how long the input is held, and `release_ms` how long it stays released - // before the same input can be used again. `duration_ms` is the total hold - // time. + + // All times are in milliseconds. + // `delay_ms`: how long to wait before the next command may start. + // `delay = hold + release` runs commands back to back + // like `pbf_press_button()`; `delay < hold` overlaps them, e.g. to hold a button + // while moving a stick. + // `hold_ms`: how long the input is held. + // `release_ms` how long it stays released before the same input can be used again. + // `duration_ms` is the total hold time. // // These throw InvalidConnectionStateException if the controller is not // ready, and block only if the device's command queue is full. @@ -104,38 +104,22 @@ class PybindSwitchProController{ // controller. It will press all buttons in `button_bitfield` simultaneously. // D-pad buttons are excluded and should be called via `push_dpad()`. // button_bitfield: values from `NintendoSwitch::Button`. - // delay_ms: how long to wait before the next command may start, milliseconds. - // hold_ms: how long the button press is held, milliseconds. - // release_ms: how long the buttons stay released before the same button can be - // used again, milliseconds. void push_button(uint32_t button_bitfield, uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms); // Equivalent to `pbf_press_dpad()`: send a D-pad press command to the // controller. It will press one or two D-pad buttons to indicate a direction // to the game. // dpad_position: `NintendoSwitch::DpadPosition` values (0 = up, clockwise to 7 = up-left, 8 = none). - // delay_ms: how long to wait before the next command may start, milliseconds. - // hold_ms: how long the button press is held, milliseconds. - // release_ms: how long the buttons stay released before the same button can be - // used again, milliseconds. void push_dpad(uint8_t dpad_position, uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms); // Equivalent to `pbf_move_left_joystick()`: move the left joystick towards a // 2D direction. // x, y: in [-1.0, 1.0] with +x = right and +y = up. - // delay_ms: how long to wait before the next command may start, milliseconds. - // hold_ms: how long the joystick is pushed, milliseconds. - // release_ms: how long the joystick stays released before the same joystick can - // be used again, milliseconds. void push_left_joystick(double x, double y, uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms); // Equivalent to `pbf_move_right_joystick()`: move the right joystick towards a // 2D direction. // x, y: in [-1.0, 1.0] with +x = right and +y = up. - // delay_ms: how long to wait before the next command may start, milliseconds. - // hold_ms: how long the joystick is pushed, milliseconds. - // release_ms: how long the joystick stays released before the same joystick can - // be used again, milliseconds. void push_right_joystick(double x, double y, uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms); // Equivalent to `pbf_controller_state()`: set the entire controller state at @@ -146,7 +130,7 @@ class PybindSwitchProController{ // dpad_position: `NintendoSwitch::DpadPosition` values (0 = up, clockwise to 7 = up-left, 8 = none). // left_x, left_y: in [-1.0, 1.0] with +x = right and +y = up. // right_x, right_y: in [-1.0, 1.0] with +x = right and +y = up. - // duration_ms: how long to hold the buttons/d-pad/joysticks, milliseconds. + // duration_ms: how long to hold the buttons/d-pad/joysticks, in milliseconds. void controller_state( uint32_t button_bitfield, uint8_t dpad_position, From 4bfcec827f6f150caef439ff53a0ffee4cc59229 Mon Sep 17 00:00:00 2001 From: jw098 Date: Thu, 22 Oct 2026 10:10:19 -0700 Subject: [PATCH 40/58] update comments --- .../Integrations/PybindSwitchController.h | 21 +++++++++---------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/SerialPrograms/Source/Integrations/PybindSwitchController.h b/SerialPrograms/Source/Integrations/PybindSwitchController.h index c194108492..cd1bae8c72 100644 --- a/SerialPrograms/Source/Integrations/PybindSwitchController.h +++ b/SerialPrograms/Source/Integrations/PybindSwitchController.h @@ -85,44 +85,43 @@ class PybindSwitchProController{ // All times are in milliseconds. // `delay_ms`: how long to wait before the next command may start. - // `delay = hold + release` runs commands back to back - // like `pbf_press_button()`; `delay < hold` overlaps them, e.g. to hold a button - // while moving a stick. + // `delay = hold + release` runs commands back to back like `pbf_press_button()`; + // `delay < hold` overlaps them, e.g. to hold a button while moving a stick. // `hold_ms`: how long the input is held. - // `release_ms` how long it stays released before the same input can be used again. - // `duration_ms` is the total hold time. + // `release_ms`: how long it stays released before the same input can be used again. + // `duration_ms`: is the total hold time. // // These throw InvalidConnectionStateException if the controller is not // ready, and block only if the device's command queue is full. - // Equivalent to `pbf_wait()`: send a wait command to the controller. Nothing is + // Similar to `pbf_wait()`: send a wait command to the controller. Nothing is // pressed during the wait time. // duration_ms: wait duration, milliseconds. void wait(uint64_t duration_ms); - // Equivalent to `pbf_press_button()`: send a button press command to the + // Similar to `pbf_press_button()`: send a button press command to the // controller. It will press all buttons in `button_bitfield` simultaneously. // D-pad buttons are excluded and should be called via `push_dpad()`. // button_bitfield: values from `NintendoSwitch::Button`. void push_button(uint32_t button_bitfield, uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms); - // Equivalent to `pbf_press_dpad()`: send a D-pad press command to the + // Similar to `pbf_press_dpad()`: send a D-pad press command to the // controller. It will press one or two D-pad buttons to indicate a direction // to the game. // dpad_position: `NintendoSwitch::DpadPosition` values (0 = up, clockwise to 7 = up-left, 8 = none). void push_dpad(uint8_t dpad_position, uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms); - // Equivalent to `pbf_move_left_joystick()`: move the left joystick towards a + // Similar to `pbf_move_left_joystick()`: move the left joystick towards a // 2D direction. // x, y: in [-1.0, 1.0] with +x = right and +y = up. void push_left_joystick(double x, double y, uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms); - // Equivalent to `pbf_move_right_joystick()`: move the right joystick towards a + // Similar to `pbf_move_right_joystick()`: move the right joystick towards a // 2D direction. // x, y: in [-1.0, 1.0] with +x = right and +y = up. void push_right_joystick(double x, double y, uint64_t delay_ms, uint64_t hold_ms, uint64_t release_ms); - // Equivalent to `pbf_controller_state()`: set the entire controller state at + // Similar to `pbf_controller_state()`: set the entire controller state at // once and hold it for `duration_ms`. Everything not specified is released. // This is the most direct way to hold arbitrary combinations, e.g. running // (B + left stick) while turning the camera. From 736d0eb101d4c90186a1b8bf63dd571d8edfc2ee Mon Sep 17 00:00:00 2001 From: jw098 Date: Thu, 22 Oct 2026 10:59:25 -0700 Subject: [PATCH 41/58] update pybind CI --- .github/workflows/cpp-ci-python-bindings.yml | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/.github/workflows/cpp-ci-python-bindings.yml b/.github/workflows/cpp-ci-python-bindings.yml index 58eede1634..57faa9867a 100644 --- a/.github/workflows/cpp-ci-python-bindings.yml +++ b/.github/workflows/cpp-ci-python-bindings.yml @@ -26,6 +26,13 @@ jobs: path: 'Arduino-Source' submodules: 'recursive' + # Step 1: Create a single environment for the entire job + - name: Set up Virtual Environment + run: | + python3 -m venv /tmp/pa-build-venv + /tmp/pa-build-venv/bin/pip install --upgrade pip + /tmp/pa-build-venv/bin/pip install pybind11 pytest + - name: Generate binaries run: | cd Arduino-Source/SerialPrograms @@ -36,10 +43,8 @@ jobs: - name: Run the Python tests run: | - python3 -m venv /tmp/pa-pytest-venv - /tmp/pa-pytest-venv/bin/pip install pytest cd Arduino-Source/SerialPrograms/Source/PythonBindings - /tmp/pa-pytest-venv/bin/python -m pytest -q + /tmp/pa-build-venv/bin/python -m pytest -q # Note: the venv avoids PEP 668 issues with system-pip on newer runners. # The runner's system Python needs dev headers (python3-dev is preinstalled on the images). \ No newline at end of file From f3a533f644da9facfc70cf132ef1339ba129a0ad Mon Sep 17 00:00:00 2001 From: PA Dev Bot <344001113+pa-devbot@users.noreply.github.com> Date: Thu, 22 Oct 2026 18:14:28 +0000 Subject: [PATCH 42/58] PythonBindings.cmake: do not download pybind11; error with install steps Drop the FetchContent fallback. If pybind11 is not found (system package or pip-installed for the target interpreter), configure now fails with a FATAL_ERROR that names the interpreter and gives the install commands, instead of silently git-cloning a pinned pybind11 release during configure. Builds no longer reach the network on their own. README updated to match. --- .../Source/PythonBindings/PythonBindings.cmake | 17 ++++++++--------- SerialPrograms/Source/PythonBindings/README.md | 4 ++-- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/SerialPrograms/Source/PythonBindings/PythonBindings.cmake b/SerialPrograms/Source/PythonBindings/PythonBindings.cmake index 9a9d93f599..ce1d022026 100644 --- a/SerialPrograms/Source/PythonBindings/PythonBindings.cmake +++ b/SerialPrograms/Source/PythonBindings/PythonBindings.cmake @@ -21,8 +21,9 @@ # position-independent. set_target_properties(CoreLib PROPERTIES POSITION_INDEPENDENT_CODE ON) -# pybind11: prefer an installed copy (a system package or `pip install pybind11`), -# and download a pinned release only as a fallback. +# pybind11: use an installed copy (a system package or `pip install pybind11`). +# It is deliberately NOT downloaded here: configure fails with instructions +# instead, so builds never reach out to the network on their own. set(PYBIND11_FINDPYTHON ON) find_package(Python 3.10 REQUIRED COMPONENTS Interpreter Development.Module) find_package(pybind11 CONFIG QUIET) @@ -38,14 +39,12 @@ if (NOT pybind11_FOUND) endif() endif() if (NOT pybind11_FOUND) - message(STATUS "Python bindings: pybind11 not found, downloading it") - include(FetchContent) - FetchContent_Declare( - pybind11 - GIT_REPOSITORY https://github.com/pybind/pybind11.git - GIT_TAG v3.0.1 + message(FATAL_ERROR + "Python bindings: pybind11 was not found for ${Python_EXECUTABLE} (${Python_VERSION}).\n" + "This build does not download pybind11 automatically. Install it and reconfigure, e.g.:\n" + " \"${Python_EXECUTABLE}\" -m pip install pybind11\n" + "or use a system package (Debian/Ubuntu: `sudo apt install pybind11-dev`, macOS: `brew install pybind11`)." ) - FetchContent_MakeAvailable(pybind11) endif() message(STATUS "Python bindings: building _pa_core for ${Python_EXECUTABLE} (${Python_VERSION})") diff --git a/SerialPrograms/Source/PythonBindings/README.md b/SerialPrograms/Source/PythonBindings/README.md index d1bd786e72..bf2cbe9d03 100644 --- a/SerialPrograms/Source/PythonBindings/README.md +++ b/SerialPrograms/Source/PythonBindings/README.md @@ -28,8 +28,8 @@ device, using the `NintendoSwitch::PybindSwitchProController` class from CoreLib ## Building the pybind module Requires a Python 3.10+ with development headers and pybind11 (a system package -or `pip install pybind11`). If pybind11 is not found, CMake downloads a pinned -pybind11 release. +or `pip install pybind11`). If pybind11 is not found, CMake fails with +installation instructions — it is not downloaded automatically. Run the following commands: From e014c4745f82fc3ac135f24dcda203b33dca8d74 Mon Sep 17 00:00:00 2001 From: jw098 Date: Thu, 22 Oct 2026 11:23:24 -0700 Subject: [PATCH 43/58] update pybind CI --- .github/workflows/cpp-ci-python-bindings.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/cpp-ci-python-bindings.yml b/.github/workflows/cpp-ci-python-bindings.yml index 57faa9867a..c8fa4f9ade 100644 --- a/.github/workflows/cpp-ci-python-bindings.yml +++ b/.github/workflows/cpp-ci-python-bindings.yml @@ -38,7 +38,7 @@ jobs: cd Arduino-Source/SerialPrograms mkdir bin cd bin - cmake .. -DPA_CORE_ONLY=ON -DPA_PYTHON_BINDINGS=ON + cmake .. -DPA_CORE_ONLY=ON -DPA_PYTHON_BINDINGS=ON -DPython_EXECUTABLE=/tmp/pa-build-venv/bin/python cmake --build . --config RelWithDebInfo --parallel 10 - name: Run the Python tests From ce5ebac9939e817a5418144448d5767c5b860a0c Mon Sep 17 00:00:00 2001 From: jw098 Date: Thu, 22 Oct 2026 11:42:00 -0700 Subject: [PATCH 44/58] update comments --- SerialPrograms/Source/PythonBindings/PythonBindings.cmake | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/SerialPrograms/Source/PythonBindings/PythonBindings.cmake b/SerialPrograms/Source/PythonBindings/PythonBindings.cmake index ce1d022026..26261dea69 100644 --- a/SerialPrograms/Source/PythonBindings/PythonBindings.cmake +++ b/SerialPrograms/Source/PythonBindings/PythonBindings.cmake @@ -26,8 +26,8 @@ set_target_properties(CoreLib PROPERTIES POSITION_INDEPENDENT_CODE ON) # instead, so builds never reach out to the network on their own. set(PYBIND11_FINDPYTHON ON) find_package(Python 3.10 REQUIRED COMPONENTS Interpreter Development.Module) -find_package(pybind11 CONFIG QUIET) -if (NOT pybind11_FOUND) +find_package(pybind11 CONFIG QUIET) # search standard system directories for pybind +if (NOT pybind11_FOUND) ## next, search pip folder for pybind execute_process( COMMAND "${Python_EXECUTABLE}" -m pybind11 --cmakedir OUTPUT_VARIABLE PYBIND11_PIP_CMAKE_DIR From 2590c3a8eaf2aa7844fb0999b47df33b306009e7 Mon Sep 17 00:00:00 2001 From: PA Dev Bot <344001113+pa-devbot@users.noreply.github.com> Date: Thu, 22 Oct 2026 20:56:45 +0000 Subject: [PATCH 45/58] Python bindings: fix doc typos and stale example kwargs - controller.py: cancel_all_and_wait() docstring cited the old C++\n parameter name (timeout_millis -> timeout_ms).\n- README: 'insid' -> 'inside', 'run the all tests' -> 'run all the tests',\n queue examples used a nonexistent duration kwarg (now hold_ms, which is\n what push_left_joystick() actually takes), and mkdir bin -> mkdir -p bin\n so the instructions work on a re-run.\n- test_push_right_joystick now actually passes a [x, y] list, matching its\n docstring (lists are accepted via parse_stick_pair). --- SerialPrograms/Source/PythonBindings/README.md | 16 ++++++++-------- .../pokemon_automation/controller.py | 2 +- .../PythonBindings/tests/test_fake_controller.py | 2 +- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/SerialPrograms/Source/PythonBindings/README.md b/SerialPrograms/Source/PythonBindings/README.md index bf2cbe9d03..162e5bd659 100644 --- a/SerialPrograms/Source/PythonBindings/README.md +++ b/SerialPrograms/Source/PythonBindings/README.md @@ -35,7 +35,7 @@ Run the following commands: ```sh cd SerialPrograms # starting from the root Arduino-Source -mkdir bin && cd bin +mkdir -p bin && cd bin cmake .. -DPA_PYTHON_BINDINGS=ON -DPA_CORE_ONLY=ON cmake --build . --target _pa_core ``` @@ -91,7 +91,7 @@ cd SerialPrograms/Source/PythonBindings # starting from the root Arduino-Source python -m pytest ``` -Running pytest, it will look insid `pyproject.toml`, then run the all tests +Running pytest, it will look inside `pyproject.toml`, then run all the tests within the `tests` folder. The tests that need the compiled module are skipped when `_pa_core` has not been built. @@ -129,9 +129,9 @@ This mirrors the `pbf_*()` functions of the C++ program. Example 1: ```py -push_left_joystick(..., duration=10s) -push_left_joystick(..., duration=10s) -push_left_joystick(..., duration=10s) +push_left_joystick(..., hold_ms=10000) +push_left_joystick(..., hold_ms=10000) +push_left_joystick(..., hold_ms=10000) do_something_else() ``` @@ -144,9 +144,9 @@ executing on the microcontroller, you need to use `wait_for_all_requests()`. Example 2: ```py -push_left_joystick(..., duration=10s) -push_left_joystick(..., duration=10s) -push_left_joystick(..., duration=10s) +push_left_joystick(..., hold_ms=10000) +push_left_joystick(..., hold_ms=10000) +push_left_joystick(..., hold_ms=10000) wait_for_all_requests() # waits for the above, then runs do_something_else() below do_something_else() ``` diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py index a40fb1cb2e..aef348958e 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py @@ -267,7 +267,7 @@ def cancel_all_and_wait(self, timeout_ms: int = 500) -> bool: Thread-safe: may be called from another thread while commands are being sent (emergency stop). - C++: `PybindSwitchProController::cancel_all_and_wait(timeout_millis)` + C++: `PybindSwitchProController::cancel_all_and_wait(timeout_ms)` (SerialPrograms/Source/Integrations/PybindSwitchProController.h) -> `AbstractController::cancel_all_and_wait()` (SerialPrograms/Source/Controllers/Controller.h). """ diff --git a/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py b/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py index 203472dc0d..2d2c426b12 100644 --- a/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py +++ b/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py @@ -149,7 +149,7 @@ def test_push_left_joystick_rejects_string(): def test_push_right_joystick(): """A [x, y] list is accepted too, forwarded with the requested hold and release.""" sw, fake = make() - sw.push_right_joystick(joystick_position=(0.5, -0.5), hold_ms=300, release_ms=100) + sw.push_right_joystick(joystick_position=[0.5, -0.5], hold_ms=300, release_ms=100) (x, y, delay, hold, release), = fake.arguments("push_right_joystick") assert (x, y) == (0.5, -0.5) and hold == 300 and release == 100 and delay == 400 From b1698ea135c7b01ab360b59406ce50c8173e1579 Mon Sep 17 00:00:00 2001 From: jw098 Date: Thu, 22 Oct 2026 15:02:40 -0700 Subject: [PATCH 46/58] Fix bug: close() serialization close() no longer lets a command slip in after the cancel: the closed flag is set under the command lock, and every command method re-checks it while holding the lock before sending, so commands starting while the cancel is in flight are rejected. --- .../pokemon_automation/controller.py | 26 ++++++++++---- .../Source/PythonBindings/tests/test_core.py | 20 +++++++++++ .../tests/test_fake_controller.py | 34 +++++++++++++++++++ 3 files changed, 73 insertions(+), 7 deletions(-) diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py index aef348958e..bc9c82bd4f 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py @@ -83,8 +83,8 @@ class SwitchController: def __init__(self, port: str | None = None, *, timeout_s: float = 10.0, backend: ControllerBackend | None = None): if backend is None: - if port is None: - raise ValueError("Either port or backend is required.") + if not port: + raise ValueError("Either a non-empty port or a backend is required.") backend = _core.core().Controller(port) self._backend = backend self._lock = threading.Lock() @@ -149,6 +149,7 @@ def push_button(self, buttons: btn.ButtonsArg, hold_ms: int = DEFAULT_HOLD_MS, if not parsed.has_buttons: raise ValueError("push_button() needs at least one button.") with self._lock: + self._require_open() # close() may have run while we were parsing self._backend.push_button(parsed.bitfield, hold_ms + release_ms, hold_ms, release_ms) def push_dpad(self, dpad: btn.ButtonsArg, hold_ms: int = DEFAULT_HOLD_MS, @@ -176,6 +177,7 @@ def push_dpad(self, dpad: btn.ButtonsArg, hold_ms: int = DEFAULT_HOLD_MS, if not parsed.has_dpad: raise ValueError("push_dpad() needs at least one d-pad direction.") with self._lock: + self._require_open() # close() may have run while we were parsing self._backend.push_dpad(parsed.dpad, hold_ms + release_ms, hold_ms, release_ms) def controller_state(self, buttons: btn.ButtonsArg = None, dpad: btn.ButtonsArg = None, *, @@ -208,6 +210,7 @@ def controller_state(self, buttons: btn.ButtonsArg = None, dpad: btn.ButtonsArg left_x, left_y = btn.parse_stick_pair(left_joystick) if left_joystick is not None else (0.0, 0.0) right_x, right_y = btn.parse_stick_pair(right_joystick) if right_joystick is not None else (0.0, 0.0) with self._lock: + self._require_open() # close() may have run while we were parsing self._backend.controller_state( parsed_buttons.bitfield, parsed_dpad.dpad, left_x, left_y, right_x, right_y, @@ -241,6 +244,7 @@ def _push_joystick(self, send, joystick_position: tuple[float, float], hold_ms: self._require_open() x, y = btn.parse_stick_pair(joystick_position) with self._lock: + self._require_open() # close() may have run while we were parsing send(x, y, hold_ms + release_ms, hold_ms, release_ms) def wait(self, duration_ms: int) -> None: @@ -248,7 +252,9 @@ def wait(self, duration_ms: int) -> None: _check_nonnegative(duration_ms=duration_ms) self._require_open() if duration_ms > 0: - self._backend.wait(duration_ms) + with self._lock: + self._require_open() # close() may have run while we were parsing + self._backend.wait(duration_ms) def wait_for_all_requests(self) -> None: """Block until every queued command has executed on the device. @@ -278,10 +284,16 @@ def cancel_all_and_wait(self, timeout_ms: int = 500) -> bool: def close(self) -> None: """Stop the device (cancelling queued commands and waiting briefly for the - neutral state) and drop the connection.""" - if self._closed: - return - self._closed = True + neutral state) and drop the connection. + + The closed flag is set under the command lock before the cancel starts, so + commands that start while the cancel is in flight are rejected instead of + being queued after it. + """ + with self._lock: + if self._closed: + return + self._closed = True try: self._backend.cancel_all_and_wait(500) except Exception: # noqa: BLE001 - best effort: the connection is dropped anyway diff --git a/SerialPrograms/Source/PythonBindings/tests/test_core.py b/SerialPrograms/Source/PythonBindings/tests/test_core.py index 021025fc08..d2ee0cbe0f 100644 --- a/SerialPrograms/Source/PythonBindings/tests/test_core.py +++ b/SerialPrograms/Source/PythonBindings/tests/test_core.py @@ -82,3 +82,23 @@ def test_push_joystick_rejects_string(): # These are safe no-ops when not ready. c.wait_for_all_requests() assert c.cancel_all_and_wait(100) is False + + +def test_empty_port(): + """An empty port name opens no connection: querying is safe, commands raise, and destruction is safe.""" + c = core.Controller("") + assert not c.wait_for_ready(200) + assert not c.is_ready() + assert c.current_status() + assert c.cancel_all_and_wait(100) is False + with pytest.raises(RuntimeError): + c.push_button(core.BUTTONS["A"], 0, 10, 10) + del c + + +def test_destroy_while_connecting(): + """Destroying the controller while its connection is still establishing is safe: the + connection thread is joined before the internals are destroyed.""" + for _ in range(5): + c = core.Controller("nonexistent-port-xyz") + del c diff --git a/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py b/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py index 2d2c426b12..e473f462a2 100644 --- a/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py +++ b/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py @@ -3,6 +3,9 @@ # C++ interface of `NintendoSwitch::PybindSwitchProController` # (SerialPrograms/Source/Integrations/PybindSwitchProController.h), bound by # SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp. +import threading +import time + import pytest from pokemon_automation import BUTTON_BITS, DPAD_NONE, DPAD_POSITIONS, FakeController, SwitchController @@ -21,6 +24,12 @@ def test_requires_port_or_backend(): SwitchController() +def test_empty_port_rejected(): + """An empty port string is rejected like no port at all.""" + with pytest.raises(ValueError, match="non-empty"): + SwitchController("") + + def test_not_ready_raises(): """The constructor raises RuntimeError when the backend is not ready within the timeout.""" fake = FakeController(ready=False) @@ -211,6 +220,31 @@ def test_close(): assert fake.cancel_count == 1 +def test_command_while_closing_is_rejected(): + """close() flags the controller before the cancel finishes, so a command that starts + while the cancel is in flight is rejected instead of being queued after it.""" + fake = FakeController() + sw = SwitchController(backend=fake) + cancelling = threading.Event() + cancel_calls = 0 + + def slow_cancel(timeout_ms: int = 500) -> bool: + nonlocal cancel_calls + cancel_calls += 1 + cancelling.set() + time.sleep(0.05) + return True + + fake.cancel_all_and_wait = slow_cancel + t = threading.Thread(target=sw.close) + t.start() + assert cancelling.wait(1.0) + with pytest.raises(RuntimeError, match="closed"): + sw.push_button("A") + t.join() + assert cancel_calls == 1 + + def test_context_manager(): """The context manager closes the controller on exit; commands after that raise.""" fake = FakeController() From 9bafba2ba273dacabbcf7f3e293df31dc8cb3bdf Mon Sep 17 00:00:00 2001 From: jw098 Date: Thu, 22 Oct 2026 15:26:33 -0700 Subject: [PATCH 47/58] fix Empty port name: SerialPABotBase2_Descriptor::open_connection() returns nullptr for an empty name, leaving m_connection null and crashing current_status(). The constructor, destructor, controller() and current_status() now tolerate a null connection ("No connection."), and SwitchController rejects an empty port up front with a ValueError. --- .../Source/Integrations/PybindSwitchController.cpp | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/SerialPrograms/Source/Integrations/PybindSwitchController.cpp b/SerialPrograms/Source/Integrations/PybindSwitchController.cpp index f0e780b025..ddb2f0d92e 100644 --- a/SerialPrograms/Source/Integrations/PybindSwitchController.cpp +++ b/SerialPrograms/Source/Integrations/PybindSwitchController.cpp @@ -30,7 +30,10 @@ class PybindSwitchProControllerInternal final : public ControllerConnection::Sta , m_descriptor(name) , m_connection(m_descriptor.open_connection(m_logger)) { - m_connection->add_status_listener(*this); + // open_connection() returns nullptr for an empty port name. + if (m_connection){ + m_connection->add_status_listener(*this); + } } ~PybindSwitchProControllerInternal(){ m_connection->remove_status_listener(*this); @@ -85,9 +88,8 @@ class PybindSwitchProControllerInternal final : public ControllerConnection::Sta ProController& controller(){ ProController* procon = controller_if_ready(); if (procon == nullptr){ - throw InvalidConnectionStateException( - "Controller is not ready: " + m_connection->status_text() - ); + std::string status = m_connection ? m_connection->status_text() : "No connection."; + throw InvalidConnectionStateException("Controller is not ready: " + status); } return *procon; } @@ -127,7 +129,7 @@ bool PybindSwitchProController::is_ready() const{ } std::string PybindSwitchProController::current_status() const{ PybindSwitchProControllerInternal* internal = (PybindSwitchProControllerInternal*)m_internals; - return internal->m_connection->raw_status_text(); + return internal->m_connection ? internal->m_connection->raw_status_text() : "No connection."; } std::string PybindSwitchProController::controller_name() const{ PybindSwitchProControllerInternal* internal = (PybindSwitchProControllerInternal*)m_internals; From 3d248db8aa587f503e1538f555b52054e339d3d2 Mon Sep 17 00:00:00 2001 From: jw098 Date: Thu, 22 Oct 2026 15:03:54 -0700 Subject: [PATCH 48/58] Fix review bugs: destruction race, empty port #1 Destruction race (PybindSwitchController.cpp): the connection thread is joined only when m_connection is destroyed, i.e. after m_controller, m_cv and m_lock already were. Destroying the controller while a connection is still establishing (e.g. SwitchController's timeout path) let the connect thread write to destroyed members. The destructor now resets m_connection first, so the thread is joined before any member is destroyed. #2 Empty port name: SerialPABotBase2_Descriptor::open_connection() returns nullptr for an empty name, leaving m_connection null and crashing current_status(). The constructor, destructor, controller() and current_status() now tolerate a null connection ("No connection."), and SwitchController rejects an empty port up front with a ValueError. --- .../Source/Integrations/PybindSwitchController.cpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/SerialPrograms/Source/Integrations/PybindSwitchController.cpp b/SerialPrograms/Source/Integrations/PybindSwitchController.cpp index ddb2f0d92e..a7ae477274 100644 --- a/SerialPrograms/Source/Integrations/PybindSwitchController.cpp +++ b/SerialPrograms/Source/Integrations/PybindSwitchController.cpp @@ -36,7 +36,14 @@ class PybindSwitchProControllerInternal final : public ControllerConnection::Sta } } ~PybindSwitchProControllerInternal(){ - m_connection->remove_status_listener(*this); + if (m_connection){ + m_connection->remove_status_listener(*this); + // The connection's destructor joins the connection thread, which may still be + // inside post_connection_ready() and touching our members (m_controller, + // m_procon, m_lock, m_cv, ...). Destroy the connection now, before any of + // our own members are destroyed. + m_connection.reset(); + } } bool wait_for_ready(uint64_t timeout_ms){ From 49d1cfaf9a60cc679b43cda75a5d00a351e1764d Mon Sep 17 00:00:00 2001 From: jw098 Date: Thu, 22 Oct 2026 16:23:42 -0700 Subject: [PATCH 49/58] update README --- SerialPrograms/Source/PythonBindings/README.md | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/SerialPrograms/Source/PythonBindings/README.md b/SerialPrograms/Source/PythonBindings/README.md index 162e5bd659..e56c8bdb47 100644 --- a/SerialPrograms/Source/PythonBindings/README.md +++ b/SerialPrograms/Source/PythonBindings/README.md @@ -34,8 +34,11 @@ installation instructions — it is not downloaded automatically. Run the following commands: ```sh -cd SerialPrograms # starting from the root Arduino-Source -mkdir -p bin && cd bin +# starting from the root Arduino-Source +cd SerialPrograms +# create the build folder and cd into it +mkdir -p bin +cd bin cmake .. -DPA_PYTHON_BINDINGS=ON -DPA_CORE_ONLY=ON cmake --build . --target _pa_core ``` @@ -59,7 +62,8 @@ After the build, `_pa_core` is copied into To install it for a project: ```sh -pip install -e SerialPrograms/Source/PythonBindings # starting from the root Arduino-Source +# starting from the root Arduino-Source +pip install -e SerialPrograms/Source/PythonBindings ``` ## Example usage: Switch Connection test @@ -87,7 +91,8 @@ If `port` is omitted, every port from `list_serial_ports()` is tried in turn. Pytest must be installed: `pip install pytest` ```sh -cd SerialPrograms/Source/PythonBindings # starting from the root Arduino-Source +# starting from the root Arduino-Source +cd SerialPrograms/Source/PythonBindings python -m pytest ``` From 4bc8307a54f89f02b08cc0da7884698d23935b64 Mon Sep 17 00:00:00 2001 From: jw098 Date: Thu, 22 Oct 2026 18:08:57 -0700 Subject: [PATCH 50/58] update README --- SerialPrograms/Source/PythonBindings/README.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/SerialPrograms/Source/PythonBindings/README.md b/SerialPrograms/Source/PythonBindings/README.md index e56c8bdb47..d085a0d0f0 100644 --- a/SerialPrograms/Source/PythonBindings/README.md +++ b/SerialPrograms/Source/PythonBindings/README.md @@ -77,9 +77,13 @@ The easiest way to do a proper setup is to establish the connection to the Switc Run the following commands: ```sh -cd SerialPrograms/Source/PythonBindings # starting from the root Arduino-Source -python -m pokemon_automation.switch_connection_test # try every candidate port in turn -python -m pokemon_automation.switch_connection_test /dev/ttyACM0 # or pass a specific port +# starting from the root Arduino-Source +cd SerialPrograms/Source/PythonBindings +# try every candidate port in turn +python -m pokemon_automation.switch_connection_test + +# OR pass a specific port +python -m pokemon_automation.switch_connection_test /dev/ttyACM0 ``` If `port` is omitted, every port from `list_serial_ports()` is tried in turn. From c100ca035d17ea066b33713248339f3a0258cdc9 Mon Sep 17 00:00:00 2001 From: PA Dev Bot <344001113+pa-devbot@users.noreply.github.com> Date: Sat, 24 Oct 2026 17:56:41 +0000 Subject: [PATCH 51/58] Rename SwitchController to SwitchProController Matches the C++ class it wraps (PybindSwitchProController) and the device's controller type (the Pro Controller / wired controller). No backwards-compat alias: the package is pre-release (0.1.0). --- .../Source/PythonBindings/README.md | 6 +++--- .../pokemon_automation/__init__.py | 10 +++++----- .../pokemon_automation/controller.py | 8 ++++---- .../PythonBindings/pokemon_automation/fake.py | 2 +- .../switch_connection_test.py | 4 ++-- .../tests/test_fake_controller.py | 20 +++++++++---------- 6 files changed, 25 insertions(+), 25 deletions(-) diff --git a/SerialPrograms/Source/PythonBindings/README.md b/SerialPrograms/Source/PythonBindings/README.md index d085a0d0f0..e8600e1b69 100644 --- a/SerialPrograms/Source/PythonBindings/README.md +++ b/SerialPrograms/Source/PythonBindings/README.md @@ -3,7 +3,7 @@ A basic Python interface for the microcontroller, built with [pybind11](https://github.com/pybind/pybind11). It lets Python act as a Nintendo Switch controller through a PABotBase2 serial device, using the `NintendoSwitch::PybindSwitchProController` class from CoreLib -(`Source/Integrations/PybindSwitchController.h`). +(`Source/Integrations/PybindSwitchProController.h`). ## Layout @@ -13,7 +13,7 @@ device, using the `NintendoSwitch::PybindSwitchProController` class from CoreLib - `PythonBindings.cmake` — builds the module (linked against CoreLib only: no Qt, OpenCV, ONNX Runtime or Tesseract). - `pokemon_automation/` — the Python package on top of it: - - `controller.py` — `SwitchController`: the user-facing API, with button names + - `controller.py` — `SwitchProController`: the user-facing API, with button names instead of bitfields (`push_button("L+R")`, `push_dpad("up")`, ...). Its command methods match the names of `_pa_core.Controller`. - `buttons.py` — parsing of button / d-pad / stick names into bitfields. @@ -105,7 +105,7 @@ within the `tests` folder. The tests that need the compiled module are skipped when `_pa_core` has not been built. ## Controller Commands -The command methods of `SwitchController` match the names of the backend they wrap +The command methods of `SwitchProController` match the names of the backend they wrap (`_pa_core.Controller` from PythonBindings_Module.cpp, and with it the C++ `PybindSwitchProController` methods). Here's a brief description of some of the controller functions: diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py index ae6802a836..c42c8bf6f8 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py @@ -8,15 +8,15 @@ SerialPrograms/Source/Integrations/PybindSwitchProController.h). Build it from SerialPrograms with `-DPA_PYTHON_BINDINGS=ON` (see the README next to this package). -- `SwitchController`: the Python API on top of it, with button names instead of +- `SwitchProController`: the Python API on top of it, with button names instead of bitfields. `fake.FakeController` implements the same backend interface for testing without hardware. Quick start: - from pokemon_automation import SwitchController, list_serial_ports + from pokemon_automation import SwitchProController, list_serial_ports print(list_serial_ports()) - with SwitchController("/dev/cu.usbserial-0001") as sw: + with SwitchProController("/dev/cu.usbserial-0001") as sw: sw.push_button("A") sw.push_dpad("up+right") sw.push_left_joystick((0.0, 1.0), hold_ms=1500) @@ -34,7 +34,7 @@ parse_stick, parse_stick_pair, ) -from .controller import SwitchController +from .controller import SwitchProController from .devices import list_serial_ports from .fake import FakeController @@ -45,7 +45,7 @@ "DPAD_POSITIONS", "FakeController", "ParsedButtons", - "SwitchController", + "SwitchProController", "check_against_core", "list_serial_ports", "parse_buttons", diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py index bc9c82bd4f..b9fbf3117d 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py @@ -9,9 +9,9 @@ release all inputs (waiting for the device to confirm the neutral state). Example: - from pokemon_automation import SwitchController + from pokemon_automation import SwitchProController - with SwitchController("/dev/cu.usbserial-0001") as sw: + with SwitchProController("/dev/cu.usbserial-0001") as sw: sw.push_button("A") # tap A sw.push_button("L+R", hold_ms=200) # press L and R together sw.push_dpad("up") # d-pad up @@ -68,7 +68,7 @@ def _check_nonnegative(**kwargs: int) -> None: raise ValueError(f"{name} must not be negative, got {value}.") -class SwitchController: +class SwitchProController: """A Switch controller on a PABotBase2 device (ESP32/Pico running PA firmware). `port` is the serial port, e.g. "/dev/cu.usbserial-0001" on macOS, @@ -299,7 +299,7 @@ def close(self) -> None: except Exception: # noqa: BLE001 - best effort: the connection is dropped anyway pass - def __enter__(self) -> SwitchController: + def __enter__(self) -> SwitchProController: return self def __exit__(self, *exc: object) -> None: diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/fake.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/fake.py index c87bad4026..14f7a5fe80 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/fake.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/fake.py @@ -1,7 +1,7 @@ """A fake controller for testing without hardware. `FakeController` implements the same interface as `_pa_core.Controller` and -records every command it receives, so `SwitchController` and friends can be +records every command it receives, so `SwitchProController` and friends can be exercised in unit tests. It needs no compiled module. C++ reference: the interface it mirrors is the binding of diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py index 041decbaa0..c866b8aad9 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py @@ -14,12 +14,12 @@ import sys from . import _core, devices -from .controller import SwitchController +from .controller import SwitchProController def try_port(port: str) -> bool: try: - with SwitchController(port, timeout_s=5.0) as sw: + with SwitchProController(port, timeout_s=5.0) as sw: print(f"Connected to {port}") print(f" status: {sw.current_status()}") print(f" name: {sw.controller_name() or '(unknown)'}") diff --git a/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py b/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py index e473f462a2..17e1a6d94a 100644 --- a/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py +++ b/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py @@ -1,4 +1,4 @@ -# SwitchController on top of a FakeController (no hardware, no compiled module). +# SwitchProController on top of a FakeController (no hardware, no compiled module). # The command names match the backend (`_pa_core.Controller`), which mirrors the # C++ interface of `NintendoSwitch::PybindSwitchProController` # (SerialPrograms/Source/Integrations/PybindSwitchProController.h), bound by @@ -8,33 +8,33 @@ import pytest -from pokemon_automation import BUTTON_BITS, DPAD_NONE, DPAD_POSITIONS, FakeController, SwitchController +from pokemon_automation import BUTTON_BITS, DPAD_NONE, DPAD_POSITIONS, FakeController, SwitchProController def make(): - """Create a SwitchController on a fresh FakeController and return both, so tests can inspect the recorded commands.""" + """Create a SwitchProController on a fresh FakeController and return both, so tests can inspect the recorded commands.""" fake = FakeController() - sw = SwitchController(backend=fake) + sw = SwitchProController(backend=fake) return sw, fake def test_requires_port_or_backend(): - """Constructing a SwitchController without a port or backend raises ValueError.""" + """Constructing a SwitchProController without a port or backend raises ValueError.""" with pytest.raises(ValueError): - SwitchController() + SwitchProController() def test_empty_port_rejected(): """An empty port string is rejected like no port at all.""" with pytest.raises(ValueError, match="non-empty"): - SwitchController("") + SwitchProController("") def test_not_ready_raises(): """The constructor raises RuntimeError when the backend is not ready within the timeout.""" fake = FakeController(ready=False) with pytest.raises(RuntimeError, match="not ready"): - SwitchController(backend=fake, timeout_s=0.1) + SwitchProController(backend=fake, timeout_s=0.1) def test_status_and_name_match_backend(): @@ -224,7 +224,7 @@ def test_command_while_closing_is_rejected(): """close() flags the controller before the cancel finishes, so a command that starts while the cancel is in flight is rejected instead of being queued after it.""" fake = FakeController() - sw = SwitchController(backend=fake) + sw = SwitchProController(backend=fake) cancelling = threading.Event() cancel_calls = 0 @@ -248,7 +248,7 @@ def slow_cancel(timeout_ms: int = 500) -> bool: def test_context_manager(): """The context manager closes the controller on exit; commands after that raise.""" fake = FakeController() - with SwitchController(backend=fake) as sw: + with SwitchProController(backend=fake) as sw: sw.push_button("A") with pytest.raises(RuntimeError, match="closed"): sw.push_button("A") From 54093a596c7d1e5697859712891fe04cffcf03ee Mon Sep 17 00:00:00 2001 From: jw098 Date: Sat, 24 Oct 2026 11:03:44 -0700 Subject: [PATCH 52/58] add comments --- .../Source/PythonBindings/pokemon_automation/buttons.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py index bf8b403e1a..0aaf892b5e 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py @@ -32,6 +32,12 @@ # Bit positions, mirroring the C++ `enum Button` in # SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerButtons.h. # Do not edit by hand; tests/test_buttons.py checks these against the C++ enum. +# +# Why we define these dictionaries in python instead of using the C++ enum directly: +# - allows this package to be usable without the compiled pybind module. e.g. running unit tests +# - enables IDE syntax highlighting, type checking, since IDEs can't look inside the +# compiled pybind binary +# - drift between the C++ and the dictionaries is prevented with tests/test_buttons.py checks BUTTON_BITS: dict[str, int] = { "Y": 1 << 0, "B": 1 << 1, From 92e6cdb657991f71b4ec4e8b096412dc0a16e7fb Mon Sep 17 00:00:00 2001 From: PA Dev Bot <344001113+pa-devbot@users.noreply.github.com> Date: Sat, 24 Oct 2026 19:30:14 +0000 Subject: [PATCH 53/58] buttons.py: remove the BUTTON_ALIASES table START/SELECT/L3/LS/R3/RS and the "+"/"-" spellings no longer map to PLUS/MINUS/LCLICK/RCLICK. "+" remains a separator (a lone "+" parses to no input), and "-" and the former alias names are now unknown buttons with the usual ValueError. Removed the now-dead "+"/"-" special cases in _split()/parse_buttons(), the __init__ export, and the docs; the alias test now pins the new behavior. --- .../pokemon_automation/__init__.py | 2 -- .../pokemon_automation/buttons.py | 25 +++---------------- .../PythonBindings/tests/test_buttons.py | 18 +++++++------ 3 files changed, 15 insertions(+), 30 deletions(-) diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py index c42c8bf6f8..e21303708f 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py @@ -24,7 +24,6 @@ """ from .buttons import ( - BUTTON_ALIASES, BUTTON_BITS, DPAD_NONE, DPAD_POSITIONS, @@ -39,7 +38,6 @@ from .fake import FakeController __all__ = [ - "BUTTON_ALIASES", "BUTTON_BITS", "DPAD_NONE", "DPAD_POSITIONS", diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py index 0aaf892b5e..b6d1ac1a26 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py @@ -2,9 +2,8 @@ Everything a caller types to describe an input is parsed here: -- Buttons: "A", "B", "X", "Y", "L", "R", "ZL", "ZR", "PLUS" ("+", "START"), - "MINUS" ("-", "SELECT"), "HOME", "CAPTURE", "LCLICK" ("L3", "LS"), - "RCLICK" ("R3", "RS"). Case-insensitive. +- Buttons: "A", "B", "X", "Y", "L", "R", "ZL", "ZR", "PLUS", "MINUS", + "HOME", "CAPTURE", "LCLICK", "RCLICK". Case-insensitive. - D-pad: "UP", "DOWN", "LEFT", "RIGHT" and diagonals such as "UP_RIGHT" (also "UP-RIGHT", "UPRIGHT"). Listing "UP" and "RIGHT" together also means up-right. - Combinations: a list (["L", "R"]) or a "+"-joined string ("L+R", "ZL+A"). @@ -55,17 +54,6 @@ "CAPTURE": 1 << 13, } -BUTTON_ALIASES: dict[str, str] = { - "+": "PLUS", - "START": "PLUS", - "-": "MINUS", - "SELECT": "MINUS", - "L3": "LCLICK", - "LS": "LCLICK", - "R3": "RCLICK", - "RS": "RCLICK", -} - # D-pad positions, mirroring the C++ `enum DpadPosition` in # SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerButtons.h: # 0 = up, clockwise, 8 = none. @@ -123,11 +111,7 @@ def _split(buttons: ButtonsArg) -> list[str]: if buttons is None: return [] if isinstance(buttons, str): - text = buttons.strip() - # A lone "+" or "-" is the PLUS/MINUS button, not a separator. - if text in ("+", "-"): - return [text] - return [part for part in text.replace(",", "+").split("+") if part.strip()] + return [part for part in buttons.strip().replace(",", "+").split("+") if part.strip()] ret: list[str] = [] for item in buttons: ret.extend(_split(item)) @@ -167,8 +151,7 @@ def parse_buttons(buttons: ButtonsArg) -> ParsedButtons: seen_dpad: list[str] = [] for raw in _split(buttons): name = raw.strip() - key = name.upper() if name in ("+", "-") else _normalize_name(name) - key = BUTTON_ALIASES.get(key, key) + key = _normalize_name(name) if key in BUTTON_BITS: # parse as button buttonstate_bitfield |= BUTTON_BITS[key] continue diff --git a/SerialPrograms/Source/PythonBindings/tests/test_buttons.py b/SerialPrograms/Source/PythonBindings/tests/test_buttons.py index 74dea5c833..ed8730875e 100644 --- a/SerialPrograms/Source/PythonBindings/tests/test_buttons.py +++ b/SerialPrograms/Source/PythonBindings/tests/test_buttons.py @@ -16,15 +16,19 @@ def test_single_and_combined_buttons(): assert btn.parse_buttons(["zl", "a"]).bitfield == btn.BUTTON_BITS["ZL"] | btn.BUTTON_BITS["A"] -def test_aliases_and_plus_minus(): +def test_plus_minus_no_longer_buttons(): """tests parse_buttons(): - Aliases (START/SELECT, L3, ...) resolve to their buttons, and a lone "+" or "-" is the PLUS/MINUS button, not a separator. + "+" and "-" no longer resolve to PLUS/MINUS: a lone "+" parses to no input + (it is a separator), while "-" and former alias names ("start", "L3") are unknown buttons. """ - assert btn.parse_buttons("+").bitfield == btn.BUTTON_BITS["PLUS"] - assert btn.parse_buttons("-").bitfield == btn.BUTTON_BITS["MINUS"] - assert btn.parse_buttons("start").bitfield == btn.BUTTON_BITS["PLUS"] - assert btn.parse_buttons("L3").bitfield == btn.BUTTON_BITS["LCLICK"] - assert btn.parse_buttons(["A", "+"]).bitfield == btn.BUTTON_BITS["A"] | btn.BUTTON_BITS["PLUS"] + assert not btn.parse_buttons("+").has_buttons + assert btn.parse_buttons("A+").bitfield == btn.BUTTON_BITS["A"] + with pytest.raises(ValueError, match="Unknown button"): + btn.parse_buttons("-") + with pytest.raises(ValueError, match="Unknown button"): + btn.parse_buttons("start") + with pytest.raises(ValueError, match="Unknown button"): + btn.parse_buttons("L3") def test_dpad(): From 8ec060792c7113e974fc1960ff08297d93763b66 Mon Sep 17 00:00:00 2001 From: jw098 Date: Fri, 6 Nov 2026 18:50:06 -0700 Subject: [PATCH 54/58] fix comment --- SerialPrograms/Source/PythonBindings/README.md | 2 +- .../Source/PythonBindings/pokemon_automation/__init__.py | 2 +- .../Source/PythonBindings/pokemon_automation/_core.py | 2 +- .../PythonBindings/pokemon_automation/controller.py | 8 ++++---- .../Source/PythonBindings/pokemon_automation/fake.py | 2 +- SerialPrograms/Source/PythonBindings/tests/test_core.py | 2 +- .../Source/PythonBindings/tests/test_fake_controller.py | 2 +- 7 files changed, 10 insertions(+), 10 deletions(-) diff --git a/SerialPrograms/Source/PythonBindings/README.md b/SerialPrograms/Source/PythonBindings/README.md index e8600e1b69..1bd58714e4 100644 --- a/SerialPrograms/Source/PythonBindings/README.md +++ b/SerialPrograms/Source/PythonBindings/README.md @@ -3,7 +3,7 @@ A basic Python interface for the microcontroller, built with [pybind11](https://github.com/pybind/pybind11). It lets Python act as a Nintendo Switch controller through a PABotBase2 serial device, using the `NintendoSwitch::PybindSwitchProController` class from CoreLib -(`Source/Integrations/PybindSwitchProController.h`). +(`Source/Integrations/PybindSwitchController.h`). ## Layout diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py index e21303708f..cd147a11f3 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py @@ -5,7 +5,7 @@ - `_pa_core` (C++, pybind11): acts as a Switch controller through a PABotBase2 serial device, built only from this codebase's CoreLib (the module is SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp, wrapping - SerialPrograms/Source/Integrations/PybindSwitchProController.h). Build it + SerialPrograms/Source/Integrations/PybindSwitchController.h). Build it from SerialPrograms with `-DPA_PYTHON_BINDINGS=ON` (see the README next to this package). - `SwitchProController`: the Python API on top of it, with button names instead of diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/_core.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/_core.py index 96027b2fa3..de1660b7b0 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/_core.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/_core.py @@ -8,7 +8,7 @@ C++ reference: `_pa_core` is built from SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp and wraps `NintendoSwitch::PybindSwitchProController` -(SerialPrograms/Source/Integrations/PybindSwitchProController.h/.cpp), which +(SerialPrograms/Source/Integrations/PybindSwitchController.h/.cpp), which lives in CoreLib. Importing is deferred until first use, so the pure-Python parts of the package diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py index b9fbf3117d..57c9f11829 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py @@ -39,7 +39,7 @@ class ControllerBackend(Protocol): C++ reference: `_pa_core.Controller` is a pybind defined in PythonBindings_Module.cpp It, in turn, is a 1:1 binding of `NintendoSwitch::PybindSwitchProController` - (SerialPrograms/Source/Integrations/PybindSwitchProController.h), which wraps the + (SerialPrograms/Source/Integrations/PybindSwitchController.h), which wraps the device-side command queue of `AbstractController` (SerialPrograms/Source/Controllers/Controller.h). """ @@ -136,7 +136,7 @@ def push_button(self, buttons: btn.ButtonsArg, hold_ms: int = DEFAULT_HOLD_MS, C++: `AbstractController::issue_buttons()` (SerialPrograms/Source/Controllers/Controller.h), via `PybindSwitchProController::push_button()` - (SerialPrograms/Source/Integrations/PybindSwitchProController.h). + (SerialPrograms/Source/Integrations/PybindSwitchController.h). """ _check_nonnegative(hold_ms=hold_ms, release_ms=release_ms) self._require_open() @@ -164,7 +164,7 @@ def push_dpad(self, dpad: btn.ButtonsArg, hold_ms: int = DEFAULT_HOLD_MS, C++: `AbstractController::issue_dpad()` (SerialPrograms/Source/Controllers/Controller.h), via `PybindSwitchProController::push_dpad()` - (SerialPrograms/Source/Integrations/PybindSwitchProController.h). + (SerialPrograms/Source/Integrations/PybindSwitchController.h). """ _check_nonnegative(hold_ms=hold_ms, release_ms=release_ms) self._require_open() @@ -274,7 +274,7 @@ def cancel_all_and_wait(self, timeout_ms: int = 500) -> bool: (emergency stop). C++: `PybindSwitchProController::cancel_all_and_wait(timeout_ms)` - (SerialPrograms/Source/Integrations/PybindSwitchProController.h) -> + (SerialPrograms/Source/Integrations/PybindSwitchController.h) -> `AbstractController::cancel_all_and_wait()` (SerialPrograms/Source/Controllers/Controller.h). """ self._require_open() diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/fake.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/fake.py index 14f7a5fe80..a28a4c21aa 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/fake.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/fake.py @@ -6,7 +6,7 @@ C++ reference: the interface it mirrors is the binding of `NintendoSwitch::PybindSwitchProController` -(SerialPrograms/Source/Integrations/PybindSwitchProController.h) in +(SerialPrograms/Source/Integrations/PybindSwitchController.h) in SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp; method names and arguments match that C++ class, so the fake is also a check that the Python API stays in step with the C++ interface. diff --git a/SerialPrograms/Source/PythonBindings/tests/test_core.py b/SerialPrograms/Source/PythonBindings/tests/test_core.py index d2ee0cbe0f..1285379719 100644 --- a/SerialPrograms/Source/PythonBindings/tests/test_core.py +++ b/SerialPrograms/Source/PythonBindings/tests/test_core.py @@ -4,7 +4,7 @@ # C++ reference: `_pa_core` is built from # SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp and wraps # `NintendoSwitch::PybindSwitchProController` -# (SerialPrograms/Source/Integrations/PybindSwitchProController.h); the +# (SerialPrograms/Source/Integrations/PybindSwitchController.h); the # BUTTONS / DPAD_POSITIONS dicts it exposes are generated from the enums in # SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerButtons.h. import pytest diff --git a/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py b/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py index 17e1a6d94a..434d8f9260 100644 --- a/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py +++ b/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py @@ -1,7 +1,7 @@ # SwitchProController on top of a FakeController (no hardware, no compiled module). # The command names match the backend (`_pa_core.Controller`), which mirrors the # C++ interface of `NintendoSwitch::PybindSwitchProController` -# (SerialPrograms/Source/Integrations/PybindSwitchProController.h), bound by +# (SerialPrograms/Source/Integrations/PybindSwitchController.h), bound by # SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp. import threading import time From 8dad4236b772f6fe8e75f31d3c4526e8fc9083ac Mon Sep 17 00:00:00 2001 From: jw098 Date: Fri, 6 Nov 2026 19:00:42 -0700 Subject: [PATCH 55/58] update comments --- .../Source/PythonBindings/pokemon_automation/buttons.py | 3 ++- .../Source/PythonBindings/pokemon_automation/controller.py | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py index b6d1ac1a26..9cd2c397dc 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py @@ -30,7 +30,8 @@ # Bit positions, mirroring the C++ `enum Button` in # SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerButtons.h. -# Do not edit by hand; tests/test_buttons.py checks these against the C++ enum. +# Do not edit by hand; tests/test_core.py::test_python_constants_match_cpp (via check_against_core()) +# checks these against the C++ enum. # # Why we define these dictionaries in python instead of using the C++ enum directly: # - allows this package to be usable without the compiled pybind module. e.g. running unit tests diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py index 57c9f11829..655dd3fca8 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py @@ -16,7 +16,7 @@ sw.push_button("L+R", hold_ms=200) # press L and R together sw.push_dpad("up") # d-pad up sw.push_left_joystick((0.0, 1.0), hold_ms=1500) # walk forward - sw.controller_state("B", "up", left_joystick=(0.0, 1.0), duration_ms=2000) # run forward + sw.controller_state("B", "up", left_joystick=(0.0, 1.0), duration_ms=2000) # left stick up, hold B, hold Dpad up sw.wait_for_all_requests() """ @@ -130,7 +130,7 @@ def push_button(self, buttons: btn.ButtonsArg, hold_ms: int = DEFAULT_HOLD_MS, `controller_state()`. This function does not allow for overlapping button presses. For that, use controller_state(). - However, the pybind backend does expose `delay_ms`. If this is set to less than `hold_ms`, one may + However, the raw `_pa_core` backend does expose `delay_ms`. If this is set to less than `hold_ms`, one may also overlap button presses, similar to the functions in NintendoSwitch_Commands_Superscalar.h C++: `AbstractController::issue_buttons()` From fa5597af9fe9380f81071d2e76e9a36569037248 Mon Sep 17 00:00:00 2001 From: jw098 Date: Fri, 6 Nov 2026 19:16:59 -0700 Subject: [PATCH 56/58] minor update to error message --- .../Source/PythonBindings/pokemon_automation/controller.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py index 655dd3fca8..1d595a7cec 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py @@ -91,7 +91,7 @@ def __init__(self, port: str | None = None, *, timeout_s: float = 10.0, self._closed = False self.port = port if not self._backend.wait_for_ready(int(timeout_s * 1000)): - raise RuntimeError(f"Controller on {port} is not ready: {self._backend.current_status()}") + raise RuntimeError(f"Controller is not ready (port: {port or 'not specified'}): {self._backend.current_status()}") # ---- status ------------------------------------------------------------- From 46581b7c286742e6c34290ac470f0256d9f7312a Mon Sep 17 00:00:00 2001 From: jw098 Date: Fri, 6 Nov 2026 19:35:03 -0700 Subject: [PATCH 57/58] update comments --- SerialPrograms/Source/PythonBindings/README.md | 2 +- .../Source/PythonBindings/pokemon_automation/controller.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/SerialPrograms/Source/PythonBindings/README.md b/SerialPrograms/Source/PythonBindings/README.md index 1bd58714e4..0026486c02 100644 --- a/SerialPrograms/Source/PythonBindings/README.md +++ b/SerialPrograms/Source/PythonBindings/README.md @@ -86,7 +86,7 @@ python -m pokemon_automation.switch_connection_test python -m pokemon_automation.switch_connection_test /dev/ttyACM0 ``` -If `port` is omitted, every port from `list_serial_ports()` is tried in turn. +If `port` is omitted, every port from `list_serial_ports()` is tried in turn. WARNING: In Windows, without pyserial, the script will try every port from COM1 to COM63, which can take several minutes. Consider installing pyserial with `pip install pyserial`. `port` examples: "/dev/cu.usbserial-0001" on macOS, "/dev/ttyACM0" on Linux, or "COM3" on Windows. diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py index 1d595a7cec..dff0dc49b1 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py @@ -284,7 +284,7 @@ def cancel_all_and_wait(self, timeout_ms: int = 500) -> bool: def close(self) -> None: """Stop the device (cancelling queued commands and waiting briefly for the - neutral state) and drop the connection. + neutral state). The closed flag is set under the command lock before the cancel starts, so commands that start while the cancel is in flight are rejected instead of From d927703c1f7f26e24df0ff7f45bd6515a41806ed Mon Sep 17 00:00:00 2001 From: jw098 Date: Fri, 6 Nov 2026 20:14:54 -0700 Subject: [PATCH 58/58] minor fixes --- SerialPrograms/Source/PythonBindings/README.md | 2 +- .../Source/PythonBindings/pokemon_automation/controller.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/SerialPrograms/Source/PythonBindings/README.md b/SerialPrograms/Source/PythonBindings/README.md index 0026486c02..4951da9112 100644 --- a/SerialPrograms/Source/PythonBindings/README.md +++ b/SerialPrograms/Source/PythonBindings/README.md @@ -86,7 +86,7 @@ python -m pokemon_automation.switch_connection_test python -m pokemon_automation.switch_connection_test /dev/ttyACM0 ``` -If `port` is omitted, every port from `list_serial_ports()` is tried in turn. WARNING: In Windows, without pyserial, the script will try every port from COM1 to COM63, which can take several minutes. Consider installing pyserial with `pip install pyserial`. +If `port` is omitted, every port from `list_serial_ports()` is tried in turn. WARNING: On Windows, without pyserial, the script will try every port from COM1 to COM63, which can take several minutes. Consider installing pyserial with `pip install pyserial`. `port` examples: "/dev/cu.usbserial-0001" on macOS, "/dev/ttyACM0" on Linux, or "COM3" on Windows. diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py index dff0dc49b1..6f39de6780 100644 --- a/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py @@ -91,7 +91,7 @@ def __init__(self, port: str | None = None, *, timeout_s: float = 10.0, self._closed = False self.port = port if not self._backend.wait_for_ready(int(timeout_s * 1000)): - raise RuntimeError(f"Controller is not ready (port: {port or 'not specified'}): {self._backend.current_status()}") + raise RuntimeError(f"Controller is not ready (port: {port or 'not specified'}): {self._backend.current_status()}") # ---- status -------------------------------------------------------------