diff --git a/.github/workflows/cpp-ci-python-bindings.yml b/.github/workflows/cpp-ci-python-bindings.yml new file mode 100644 index 0000000000..c8fa4f9ade --- /dev/null +++ b/.github/workflows/cpp-ci-python-bindings.yml @@ -0,0 +1,50 @@ +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-26.04 + + steps: + - name: Checkout Arduino-Source + uses: actions/checkout@v7 + with: + 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 + mkdir bin + cd bin + 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 + run: | + cd Arduino-Source/SerialPrograms/Source/PythonBindings + /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 diff --git a/SerialPrograms/CMakeLists.txt b/SerialPrograms/CMakeLists.txt index c36d2f86f5..5cd6b77cdd 100644 --- a/SerialPrograms/CMakeLists.txt +++ b/SerialPrograms/CMakeLists.txt @@ -63,6 +63,30 @@ 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) + +# 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. @@ -84,6 +108,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() @@ -283,13 +310,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") @@ -871,3 +891,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/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 2e2ccf5b2b..a7ae477274 100644 --- a/SerialPrograms/Source/Integrations/PybindSwitchController.cpp +++ b/SerialPrograms/Source/Integrations/PybindSwitchController.cpp @@ -30,15 +30,25 @@ 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); + 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_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; @@ -85,9 +95,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; } @@ -116,9 +125,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{ @@ -127,7 +136,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; @@ -145,71 +154,72 @@ 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){ +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, uint64_t hold, uint64_t release, uint32_t 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, - 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(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, - 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(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), - Milliseconds(hold), - Milliseconds(release), - {x, y} + Milliseconds(delay_ms), + Milliseconds(hold_ms), + Milliseconds(release_ms), + JoystickPosition(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(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), - Milliseconds(hold), - Milliseconds(release), - {x, y} + Milliseconds(delay_ms), + Milliseconds(hold_ms), + Milliseconds(release_ms), + JoystickPosition(x, y) ); } 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 45a7d6e128..cd1bae8c72 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,96 +71,71 @@ 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 - // ready, and block only if the device's command queue is full. - // - // `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. - void wait(uint64_t duration); - - // 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 - // `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`. - // - // `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); - // 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). - // - // `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); - // 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. + // Commands. These line up with the pbf functions in + // SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h + + // 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. // - // `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, uint64_t hold, uint64_t release, 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, uint64_t hold, uint64_t release, 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. + // These throw InvalidConnectionStateException if the controller is not + // ready, and block only if the device's command queue is full. + + // 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); + + // 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); + + // 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); + + // 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); + + // 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); + + // 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. + // 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, in milliseconds. void 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 ); 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/.gitignore b/SerialPrograms/Source/PythonBindings/.gitignore new file mode 100644 index 0000000000..40d42af36c --- /dev/null +++ b/SerialPrograms/Source/PythonBindings/.gitignore @@ -0,0 +1,9 @@ +# Built extension module (copied in by CMake after building _pa_core) +pokemon_automation/_pa_core*.so +pokemon_automation/_pa_core*.pyd + +# Python +__pycache__/ +*.pyc +*.egg-info/ +.pytest_cache/ diff --git a/SerialPrograms/Source/PythonBindings/PythonBindings.cmake b/SerialPrograms/Source/PythonBindings/PythonBindings.cmake new file mode 100644 index 0000000000..26261dea69 --- /dev/null +++ b/SerialPrograms/Source/PythonBindings/PythonBindings.cmake @@ -0,0 +1,63 @@ +# 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: 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) # 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 + 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(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`)." + ) +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..5d67921d06 --- /dev/null +++ b/SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp @@ -0,0 +1,271 @@ +/* _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_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.", + py::call_guard()) + .def("push_button", &PybindSwitchProController::push_button, + 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("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("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 (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("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 (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"), + py::arg("left_x"), py::arg("left_y"), py::arg("right_x"), py::arg("right_y"), + 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 new file mode 100644 index 0000000000..4951da9112 --- /dev/null +++ b/SerialPrograms/Source/PythonBindings/README.md @@ -0,0 +1,174 @@ +# 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` — `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. + - `fake.py` — `FakeController`: the same backend interface without hardware, + for unit tests. + - `devices.py` — `list_serial_ports()`. + - `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). + +## 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 fails with +installation instructions — it is not downloaded automatically. + +Run the following commands: + +```sh +# 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 +``` + +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, 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 +`SerialPrograms/Source/PythonBindings/pokemon_automation/`. + +To install it for a project: + +```sh +# starting from the root Arduino-Source +pip install -e SerialPrograms/Source/PythonBindings +``` + +## Example usage: Switch Connection test + +`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). + +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 +# 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. 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. + +## Running the unit tests + +Pytest must be installed: `pip install pytest` + +```sh +# starting from the root Arduino-Source +cd SerialPrograms/Source/PythonBindings +python -m pytest +``` + +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. + +## Controller Commands +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: + +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. + +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. + +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(..., hold_ms=10000) +push_left_joystick(..., hold_ms=10000) +push_left_joystick(..., hold_ms=10000) +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(..., 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() +``` + +## Other 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/__init__.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py new file mode 100644 index 0000000000..cd147a11f3 --- /dev/null +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/__init__.py @@ -0,0 +1,54 @@ +"""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 (the module is + SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp, wrapping + 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 + bitfields. `fake.FakeController` implements the same backend interface for + testing without hardware. + +Quick start: + from pokemon_automation import SwitchProController, list_serial_ports + + print(list_serial_ports()) + 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) + sw.wait_for_all_requests() +""" + +from .buttons import ( + BUTTON_BITS, + DPAD_NONE, + DPAD_POSITIONS, + ParsedButtons, + check_against_core, + parse_buttons, + parse_stick, + parse_stick_pair, +) +from .controller import SwitchProController +from .devices import list_serial_ports +from .fake import FakeController + +__all__ = [ + "BUTTON_BITS", + "DPAD_NONE", + "DPAD_POSITIONS", + "FakeController", + "ParsedButtons", + "SwitchProController", + "check_against_core", + "list_serial_ports", + "parse_buttons", + "parse_stick", + "parse_stick_pair", +] + +__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..de1660b7b0 --- /dev/null +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/_core.py @@ -0,0 +1,64 @@ +"""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. + +C++ reference: `_pa_core` is built from +SerialPrograms/Source/PythonBindings/PythonBindings_Module.cpp and wraps +`NintendoSwitch::PybindSwitchProController` +(SerialPrograms/Source/Integrations/PybindSwitchController.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. +""" + +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..9cd2c397dc --- /dev/null +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/buttons.py @@ -0,0 +1,240 @@ +"""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", "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"). +- Joystick positions: an (x, y) pair in [-1, 1] with +x = right and +y = up. + 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 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 +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 + +import math +from collections.abc import Sequence +from dataclasses import dataclass + +# Bit positions, mirroring the C++ `enum Button` in +# SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerButtons.h. +# 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 +# - 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, + "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, +} + +# 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, + "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 +""" +ButtonsArg +- can be either Button or D-pad inputs (see above for the exact strings). +- validated by `parse_buttons()` +""" + +StickArg = str | Sequence[float] | None +""" +StickArg (currently unused) +- Accepts a direction name ("up", "down_left", "neutral") or an (x, y) pair. +- validated by `parse_stick()` +""" + + +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): + return [part for part in buttons.strip().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"). + """ + 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 = _normalize_name(name) + if key in BUTTON_BITS: # parse as button + buttonstate_bitfield |= BUTTON_BITS[key] + continue + if key in _DIRECTION_VECTORS: # parse as dpad + vx, vy = _DIRECTION_VECTORS[key] # vectors of current DPAD being parsed + 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]}") + 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( + f"Unknown button {name!r}. Valid buttons: {', '.join(BUTTON_BITS)}, " + f"d-pad: {', '.join(DPAD_POSITIONS)}." + ) + dpad = DPAD_NONE + if dpad_x or dpad_y: + for direction, (vx, vy) in _DIRECTION_VECTORS.items(): + if (vx, vy) == (dpad_x, dpad_y): + dpad = DPAD_POSITIONS[direction] + return ParsedButtons(buttonstate_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): # parse as string + 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) # normalize to [-1, 1] + # else parse as (x, y) pair + return parse_stick_pair(position) + + +def parse_stick_pair(position: tuple[float, float]) -> tuple[float, float]: + """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 + of `controller_state()`. 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]) + 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`: + 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: + 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..6f39de6780 --- /dev/null +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/controller.py @@ -0,0 +1,310 @@ +"""High-level Nintendo Switch controller API on top of `_pa_core.Controller`. + +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 SwitchProController + + 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 + 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) # left stick up, hold B, hold Dpad up + sw.wait_for_all_requests() +""" + +from __future__ import annotations + +import threading +from typing import Protocol + +from . import _core, buttons as btn + +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): + # 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 + It, in turn, is a 1:1 binding of `NintendoSwitch::PybindSwitchProController` + (SerialPrograms/Source/Integrations/PybindSwitchController.h), which wraps the + device-side command queue of `AbstractController` + (SerialPrograms/Source/Controllers/Controller.h). + """ + + 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_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, 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, + duration_ms: int, + ) -> 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 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, + "/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 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() + 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()}") + + # ---- 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 current_status(self) -> str: + """The connection status text: device name and firmware version, or the + 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() + + 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 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`: 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 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()` + (SerialPrograms/Source/Controllers/Controller.h), via + `PybindSwitchProController::push_button()` + (SerialPrograms/Source/Integrations/PybindSwitchController.h). + """ + _check_nonnegative(hold_ms=hold_ms, release_ms=release_ms) + self._require_open() + parsed = btn.parse_buttons(buttons) + 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.") + 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, + release_ms: int = DEFAULT_RELEASE_MS) -> None: + """Tap a d-pad direction. + + `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()` + (SerialPrograms/Source/Controllers/Controller.h), via + `PybindSwitchProController::push_dpad()` + (SerialPrograms/Source/Integrations/PybindSwitchController.h). + """ + _check_nonnegative(hold_ms=hold_ms, release_ms=release_ms) + self._require_open() + parsed = btn.parse_buttons(dpad) + if parsed.has_buttons: + raise ValueError( + 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: + 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, *, + 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`: 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. + """ + _check_nonnegative(duration_ms=duration_ms) + self._require_open() + 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._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, + duration_ms + ) + + 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. + + 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) + + 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. + + 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) + + 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) + 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: + """Queue a pause of `duration_ms` with nothing pressed.""" + _check_nonnegative(duration_ms=duration_ms) + self._require_open() + if duration_ms > 0: + 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. + + C++: `PybindSwitchProController::wait_for_all_requests()` -> + `AbstractController::wait_for_all()` (SerialPrograms/Source/Controllers/Controller.h). + """ + self._require_open() + self._backend.wait_for_all_requests() + + def cancel_all_and_wait(self, timeout_ms: int = 500) -> bool: + """Cancel every queued command and return the controller to the neutral state. + + 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). + + C++: `PybindSwitchProController::cancel_all_and_wait(timeout_ms)` + (SerialPrograms/Source/Integrations/PybindSwitchController.h) -> + `AbstractController::cancel_all_and_wait()` (SerialPrograms/Source/Controllers/Controller.h). + """ + self._require_open() + return self._backend.cancel_all_and_wait(int(timeout_ms)) + + # ---- lifecycle ------------------------------------------------------------- + + def close(self) -> None: + """Stop the device (cancelling queued commands and waiting briefly for the + 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 + 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 + pass + + def __enter__(self) -> SwitchProController: + 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..27de41491b --- /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)] # 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 diff --git a/SerialPrograms/Source/PythonBindings/pokemon_automation/fake.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/fake.py new file mode 100644 index 0000000000..a28a4c21aa --- /dev/null +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/fake.py @@ -0,0 +1,98 @@ +"""A fake controller for testing without hardware. + +`FakeController` implements the same interface as `_pa_core.Controller` and +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 +`NintendoSwitch::PybindSwitchProController` +(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. +""" + +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 + # 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 -------------------------------------- + + 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_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: + self.log.append((name, args)) + + def wait(self, duration_ms: int) -> None: + self._record("wait", duration_ms) + + 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, 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, 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, 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, + 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", button_bitfield, dpad_position, left_x, left_y, right_x, right_y, duration_ms) + + # -- 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/switch_connection_test.py b/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py new file mode 100644 index 0000000000..c866b8aad9 --- /dev/null +++ b/SerialPrograms/Source/PythonBindings/pokemon_automation/switch_connection_test.py @@ -0,0 +1,71 @@ +"""Switch connection test: connect to the Switch via PABotBase2 and send a few simple commands. + + 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 some buttons and d-pad +steps, moves the right stick, waits for the device to confirm, and cancels with +confirmation. +""" + +from __future__ import annotations + +import argparse +import sys + +from . import _core, devices +from .controller import SwitchProController + + +def try_port(port: str) -> bool: + try: + 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)'}") + 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(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() + 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 + print(f" {port}: {e}") + return False + + +def main(argv: list[str] | None = None) -> int: + 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) + + 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..ed8730875e --- /dev/null +++ b/SerialPrograms/Source/PythonBindings/tests/test_buttons.py @@ -0,0 +1,69 @@ +import math + +import pytest + +from pokemon_automation import buttons as btn + + +def test_single_and_combined_buttons(): + """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"] + assert not both.has_dpad + assert btn.parse_buttons(["zl", "a"]).bitfield == btn.BUTTON_BITS["ZL"] | btn.BUTTON_BITS["A"] + + +def test_plus_minus_no_longer_buttons(): + """tests parse_buttons(): + "+" 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 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(): + """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"] + 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(): + """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"): + btn.parse_buttons("up+down") + assert not btn.parse_buttons(None).has_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") + 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") + diff --git a/SerialPrograms/Source/PythonBindings/tests/test_core.py b/SerialPrograms/Source/PythonBindings/tests/test_core.py new file mode 100644 index 0000000000..1285379719 --- /dev/null +++ b/SerialPrograms/Source/PythonBindings/tests/test_core.py @@ -0,0 +1,104 @@ +# 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/PybindSwitchController.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") + + +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. + 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 + 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(): + """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, + } + + +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): + core.set_log_file("/nonexistent directory/pa_core.log") + core.set_log_file("") + + +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: + 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(): + """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() + 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(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 + + +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 new file mode 100644 index 0000000000..434d8f9260 --- /dev/null +++ b/SerialPrograms/Source/PythonBindings/tests/test_fake_controller.py @@ -0,0 +1,254 @@ +# 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/PybindSwitchController.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, SwitchProController + + +def make(): + """Create a SwitchProController on a fresh FakeController and return both, so tests can inspect the recorded commands.""" + fake = FakeController() + sw = SwitchProController(backend=fake) + return sw, fake + + +def test_requires_port_or_backend(): + """Constructing a SwitchProController without a port or backend raises ValueError.""" + with pytest.raises(ValueError): + SwitchProController() + + +def test_empty_port_rejected(): + """An empty port string is rejected like no port at all.""" + with pytest.raises(ValueError, match="non-empty"): + 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"): + SwitchProController(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"] + (bitfield, delay, hold, release), = fake.arguments("push_button") + assert bitfield == BUTTON_BITS["A"] + assert delay == hold + release and hold == 80 and release == 80 + + +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) + (bitfield, delay, hold, release), = fake.arguments("push_button") + assert bitfield == BUTTON_BITS["L"] | BUTTON_BITS["R"] + assert (delay, hold, release) == (250, 200, 50) + + +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) + (position, delay, hold, release), = fake.arguments("push_dpad") + assert position == DPAD_POSITIONS["UP"] and hold == 100 and delay == 100 + release + + +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") + with pytest.raises(ValueError, match="push_dpad"): + sw.push_button("up") + assert fake.commands() == [] + + +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") + with pytest.raises(ValueError, match="push_button"): + sw.push_dpad("ZL") + assert fake.commands() == [] + + +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) + assert fake.commands() == [] + + +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) + 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_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 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) + assert fake.commands() == ["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"] + assert (left_x, left_y, right_x, right_y) == (0.0, 0.0, 0.0, 0.0) + + +def test_push_left_joystick(): + """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) + (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(): + """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) + (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(): + """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_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"] + 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(): + """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,)] + sw.wait(0) # a zero-length wait is a no-op + assert fake.arguments("wait") == [(1000,)] + + +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) + with pytest.raises(ValueError): + sw.push_button("Q") + with pytest.raises(ValueError): + sw.push_dpad("up+down") + assert fake.commands() == [] + + +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 + 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(): + """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 + with pytest.raises(RuntimeError, match="closed"): + sw.push_button("A") + with pytest.raises(RuntimeError, match="closed"): + sw.wait_for_all_requests() + sw.close() # idempotent + 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 = SwitchProController(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() + with SwitchProController(backend=fake) as sw: + sw.push_button("A") + with pytest.raises(RuntimeError, match="closed"): + sw.push_button("A")