diff --git a/source/docs/software/commandbased/commands-v3/advanced-topics.rst b/source/docs/software/commandbased/commands-v3/advanced-topics.rst new file mode 100644 index 0000000000..2131c44cd9 --- /dev/null +++ b/source/docs/software/commandbased/commands-v3/advanced-topics.rst @@ -0,0 +1,55 @@ +# Advanced Topics + +.. todo:: + This article covers advanced patterns, optimizations, and edge cases in Commands v3. This content is for experienced teams who have mastered the basics and want to push v3 to its limits or handle unusual requirements. + +## Custom Command Base Classes + +.. todo:: + Explain how and when to create custom base classes for commands. Cover: + - When custom base classes are useful vs. unnecessary abstraction + - Creating abstract command base classes with common functionality + - Decorator pattern for command functionality + - Wrapping commands to add cross-cutting concerns + - Best practices for base class design + - Examples of useful base class patterns (describe scenarios, not full implementations) + +## Performance Optimization + +.. todo:: + Provide guidance on optimizing v3 command performance. Cover: + - Understanding scheduler overhead + - Minimizing allocations in command execution + - Efficient trigger condition evaluation + - Optimizing periodic operations + - Profiling v3 command code + - Trade-offs between readability and performance + - When optimization matters vs. premature optimization + - Benchmarking techniques + +## Advanced Async Patterns + +.. todo:: + Showcase advanced patterns using async/await and coroutines. Cover: + - Command pipelines and streaming patterns + - State machines implemented with async/await + - Error handling and recovery with async commands + - Cancellation and timeout patterns + - Coordinating multiple mechanisms with complex dependencies + - Real-time responsive commands with background processing + - Describe complex scenarios and how to implement them with v3 features + +## Edge Cases and Gotchas + +.. todo:: + Document edge cases, limitations, and common pitfalls. Cover: + - Commands that never yield (infinite loops without yield) + - Forked commands and lifecycle management + - Nested trigger scopes and cleanup + - Priority conflicts + - Requirements conflicts with complex command compositions + - Thread safety considerations (if any) + - Limitations of the coroutine model + - Breaking scheduler assumptions + - Common mistakes and how to avoid them + - What NOT to do in v3 commands diff --git a/source/docs/software/commandbased/commands-v3/async-await-patterns.rst b/source/docs/software/commandbased/commands-v3/async-await-patterns.rst new file mode 100644 index 0000000000..fc2352d6df --- /dev/null +++ b/source/docs/software/commandbased/commands-v3/async-await-patterns.rst @@ -0,0 +1,78 @@ +# Async/Await Patterns + +.. todo:: + This article explains the async/await helper functions that enable advanced command orchestration in v3. These functions allow commands to launch other commands and wait for them to complete, enabling powerful composition patterns. Teams should understand basic command creation before reading this article. + +## Introduction to Async/Await + +.. todo:: + Provide an overview of async/await in Commands v3. Cover: + - What async/await means in the context of v3 (not OS-level async) + - Why async/await is useful for command orchestration + - How async/await differs from composition groups + - When to use async/await vs. other patterns + - High-level mental model for how it works with the scheduler + - Relationship to coroutines and yield() + +## fork() + +.. todo:: + Explain the fork() function in detail. Cover: + - What fork(command) does: launch a command without waiting for it + - "Fire and forget" semantics + - Lifecycle of forked commands relative to parent + - Requirements and priority considerations + - Common use cases (background operations, side effects, etc.) + - Potential pitfalls and how to avoid them + - Examples of fork() patterns (describe what examples should show) + +## await() + +.. todo:: + Explain the await() function in detail. Cover: + - What await(command) does: schedule a command and wait for it to complete + - Easier to explain as a blocking version of fork() + - How await() blocks the calling command until the child completes + - Requirements and priority handling with awaited commands + - What happens if the awaited command is interrupted + - What happens if the parent command is interrupted + - Return values and status from awaited commands + - When to use fork() vs. await() + - Examples of await() patterns (describe what examples should show) + +## awaitAll() + +.. todo:: + Explain the awaitAll() function in detail. Cover: + - What awaitAll(commands) does: wait for multiple commands in parallel + - How awaitAll() differs from await() in a loop + - When all commands must complete vs. early termination scenarios + - Requirements management across multiple parallel commands + - Error and interruption handling + - Performance implications of parallel execution + - Examples of awaitAll() patterns (describe what examples should show) + +## awaitAny() + +.. todo:: + Explain the awaitAny() function in detail. Cover: + - What awaitAny(commands) does: wait until any command completes + - Race condition semantics: which command "wins" + - **Important**: awaitAny() cancels all other still-running commands when one completes + - Both await functions are blocking + - Use cases for awaitAny() (timeouts, alternative paths, etc.) + - How interruption is handled + - Differences from race groups in composition + - Examples of awaitAny() patterns (describe what examples should show) + +## Practical Patterns + +.. todo:: + Showcase common practical patterns combining async/await functions. Cover: + - Timeout patterns: use awaitAny() with a timeout command alongside the main command - first to complete wins + - Sequential operations with conditional logic + - Parallel operations with synchronization points + - Launching background tasks with fork() + - Complex state machines using async/await + - Error recovery and fallback patterns + - Describe several real-world scenarios and which async/await functions to combine diff --git a/source/docs/software/commandbased/commands-v3/binding-commands-to-triggers.rst b/source/docs/software/commandbased/commands-v3/binding-commands-to-triggers.rst new file mode 100644 index 0000000000..761bfc0640 --- /dev/null +++ b/source/docs/software/commandbased/commands-v3/binding-commands-to-triggers.rst @@ -0,0 +1,80 @@ +# Binding Commands to Triggers + +.. todo:: + This article explains how to connect commands to button inputs and other events using the trigger system. Triggers are how robot code responds to driver input and sensor events. This is essential knowledge for any team using Commands v3. + +## Triggers Overview + +.. todo:: + Provide an overview of the trigger system in v3. Cover: + - What triggers are and their role in the command framework + - How triggers differ from directly calling command.schedule() + - When trigger bindings are evaluated by the scheduler + - Available trigger sources (buttons, joysticks, sensors, custom) + - High-level syntax for creating and binding triggers + +## Button Bindings + +.. todo:: + Explain how to bind commands to physical buttons. Cover: + - CommandHID classes vs. regular HID classes (CommandXboxController vs. XboxController, etc.) + - When to use each type of controller class + - Accessing button triggers from controllers/joysticks + - Available binding methods: onTrue(), onFalse(), whileTrue(), whileFalse(), toggleOnTrue(), etc. + - When each binding type activates and deactivates commands + - Multiple bindings on the same button + - Button composition (modifier keys, button combinations) + - Best practices for organizing button bindings in RobotContainer + - Examples of common button binding patterns (describe what examples should show) + +## Creating Custom Triggers + +.. todo:: + Explain how to create custom triggers beyond simple buttons. Cover: + - Creating triggers from boolean supplier functions + - Sensor-based triggers (limit switches, photoelectric sensors, etc.) + - State-based triggers (robot state, game piece detection, etc.) + - Time-based triggers + - Network table triggers + - Performance considerations for trigger condition functions + - Best practices for custom trigger implementation + - Examples of custom trigger patterns (describe what examples should show) + +## Trigger Composition + +.. todo:: + Explain how to compose triggers using logical operations. Cover: + - Available composition operations: and(), or(), negate() + - Creating complex trigger conditions from simple ones + - Debouncing triggers + - Edge detection (rising/falling edges) + - Trigger filtering and transformation + - When composition is evaluated + - Note: This section may need updates if https://github.com/wpilibsuite/allwpilib/pull/8366 is merged + - Examples of trigger composition patterns (describe what examples should show) + +## Inner Trigger Scopes + +.. todo:: + Explain inner trigger scopes for command-local bindings. Cover: + - What inner trigger scopes are and when to use them + - How to create an inner scope within a command + - Lifecycle of inner scope bindings (when they're active) + - Use cases: responding to events during command execution + - How inner scopes interact with command interruption + - Cleanup of inner scope bindings + - Differences from global trigger bindings + - Examples of inner scope patterns (describe what examples should show) + +## Practical Patterns + +.. todo:: + Showcase common practical patterns for trigger usage. Cover: + - Organizing bindings in RobotContainer + - Driver control schemes (tank drive, arcade drive, split stick, etc.) + - Operator control panels and button boxes + - Mode switching and control profiles + - Cancellation buttons and emergency stops + - Trigger-based autonomous selection + - Testing and debugging trigger bindings + - Describe several real-world scenarios and recommended trigger patterns diff --git a/source/docs/software/commandbased/commands-v3/command-compositions.rst b/source/docs/software/commandbased/commands-v3/command-compositions.rst new file mode 100644 index 0000000000..5a13d30b35 --- /dev/null +++ b/source/docs/software/commandbased/commands-v3/command-compositions.rst @@ -0,0 +1,89 @@ +# Command Compositions + +.. todo:: + This article covers the traditional command composition groups that allow combining multiple commands into more complex behaviors. While v3 emphasizes async/await patterns, composition groups are still important and useful in many scenarios. This article should help teams understand when to use compositions vs. async/await. + +## Composition Overview + +.. todo:: + Provide an overview of command composition in v3. Cover: + - What command compositions are and why they exist + - How compositions differ from async/await patterns + - When to use compositions vs. async/await + - Available composition types in v3 + - General syntax and usage patterns + +## Sequence Groups + +.. todo:: + Explain sequence command groups in detail. Cover: + - What sequence groups do: run commands one after another + - How to create a sequence group + - When commands transition in the sequence + - What happens if a command in the sequence is interrupted + - Requirements aggregation across sequence members + - Common use cases for sequences + - Comparison to using await() in a coroutine + - Examples of sequence group patterns (describe what examples should show) + +## Parallel Groups + +.. todo:: + Explain parallel command groups in detail. Cover: + - What parallel groups do: run multiple commands simultaneously + - How to create a parallel group + - Note: All composition groups (parallel, race, deadline) are implemented as parallel groups with different configurations: Parallel groups have _n_ required commands and _m_ optional commands. The group exits once all _n_ required commands have exited. "Traditional" parallel groups: _m_ = 0 (every command is required). Race groups: _n_ = 0 (every command is optional, exits when any finishes). Deadline groups: both _n_ and _m_ are nonzero (mix of required and optional). Note: v2 deadlines were special case where _n_ = 1 and _m_ ≥ 1; v3 deadlines are generalized. + - Requirements handling with overlapping requirements + - What happens if one command is interrupted + - Common use cases for parallel groups + - Comparison to using awaitAll() in a coroutine + - Examples of parallel group patterns (describe what examples should show) + +## Race Groups + +.. todo:: + Explain race command groups in detail. Cover: + - What race groups do: run commands in parallel until one finishes + - How to create a race group + - When the race group completes (first command finishes) + - What happens to other commands when one finishes + - Common use cases for race groups (timeouts, alternatives) + - Comparison to using awaitAny() in a coroutine + - Examples of race group patterns (describe what examples should show) + +## Deadline Groups + +.. todo:: + Explain deadline command groups in detail. Cover: + - What deadline groups do: run commands with one as a "deadline" + - How to create a deadline group and specify the deadline command + - When the deadline group completes + - Differences between deadline command and other commands + - Common use cases for deadline groups + - How to achieve similar behavior with async/await + - Examples of deadline group patterns (describe what examples should show) + +## Repeating and Looping + +.. todo:: + Explain repeating and looping command patterns. Cover: + - Available repeat/loop composition functions + - Infinite repeats vs. counted repeats + - When the loop terminates + - How interruption affects repeated commands + - Performance implications of repeated compositions + - Common use cases for repeating commands + - Comparison to using yield() loops in coroutines + - Examples of repeat patterns (describe what examples should show) + +## Conditional Groups + +.. todo:: + Explain conditional command execution patterns. Cover: + - Available conditional composition functions (if/else-style branching) + - How conditions are evaluated + - When condition evaluation happens (command creation vs. execution) + - Proxy commands and deferred command selection + - Common use cases for conditional groups + - Comparison to using if/else in coroutines + - Examples of conditional patterns (describe what examples should show) diff --git a/source/docs/software/commandbased/commands-v3/commands-and-coroutines.rst b/source/docs/software/commandbased/commands-v3/commands-and-coroutines.rst new file mode 100644 index 0000000000..68a322357d --- /dev/null +++ b/source/docs/software/commandbased/commands-v3/commands-and-coroutines.rst @@ -0,0 +1,83 @@ +# Commands and Coroutines + +.. todo:: + This article covers the core of Commands v3: creating commands using the coroutine API. It explains the fundamental building blocks of command creation, the coroutine control flow primitives, and how command lifecycle works. This should be one of the first articles teams read when learning v3. + +## Command Creation Patterns + +.. todo:: + Describe the different ways to create commands in v3. Cover: + - Basic command creation using coroutine functions + - Inline vs. named command functions + - Commands as methods on Mechanism classes (factories) + - Commands as standalone functions in command files + - Lambda/anonymous command functions + - When to use each pattern + - Code examples showing syntax for each approach (structure only, not full implementations) + +## The Coroutine API + +.. todo:: + Provide an overview of what coroutines are and how v3 uses them. Cover: + - High-level explanation of coroutines for teams unfamiliar with the concept + - How coroutines enable sequential command logic without state machines + - The yield paradigm + - How the scheduler executes coroutine commands + - Benefits of the coroutine approach + +## yield() + +.. todo:: + Explain the yield() primitive in detail. Cover: + - What yield() does: pause execution and resume next cycle + - When to use yield() vs. other control flow primitives + - How yield() relates to the scheduler loop timing + - Common patterns using yield() (e.g., running for multiple cycles) + - Note: The compiler plugin checks for `yield` in while-loops (this check does not apply to other loop types) + - Performance implications + - Examples of yield() usage patterns (describe what examples should show) + +## park() + +.. todo:: + Explain the park() primitive in detail. Cover: + - What park() does: pause indefinitely until command is interrupted + - When to use park() (e.g., commands that should run until interrupted) + - How park() differs from yield() in a loop + - Note: The compiler plugin checks for unreachable code after a `park()` call + - Interaction with command interruption and priorities + - Common use cases for park() + - Examples of park() usage patterns (describe what examples should show) + +## wait()/waitUntil() + +.. todo:: + Explain the wait() and waitUntil() primitives. Cover: + - wait(duration): pause for a specific time period + - waitUntil(condition): pause until a condition becomes true + - How these differ from yield() loops + - Timeout behavior and edge cases + - Best practices for conditions in waitUntil() + - Performance and timing accuracy considerations + - Examples of wait/waitUntil patterns (describe what examples should show) + +## Command Lifecycle + +.. todo:: + Describe the lifecycle of a command from creation to completion. Cover: + - When a command is created vs. when it starts executing + - The execution cycle: initialization, periodic execution, ending + - How coroutines map to the lifecycle phases + - What happens when a command completes normally + - What happens when a command is interrupted + - Cleanup and resource management + +## Command Properties + +.. todo:: + Explain the various properties that can be set on commands. Cover: + - Available properties: name, priority, interruptible, runsWhenDisabled, etc. + - How to set command properties (method chaining, decorators, etc.) + - When properties are evaluated vs. applied + - How properties affect scheduler behavior + - Best practices for setting properties diff --git a/source/docs/software/commandbased/commands-v3/getting-started.rst b/source/docs/software/commandbased/commands-v3/getting-started.rst new file mode 100644 index 0000000000..d3fd4879b3 --- /dev/null +++ b/source/docs/software/commandbased/commands-v3/getting-started.rst @@ -0,0 +1,121 @@ +# Getting Started with Commands v3 + +.. todo:: This article provides a hands-on tutorial for writing your first Commands v3 robot program. + +## Prerequisites + +.. todo:: + - WPILib 2027+ installation + - Basic Java knowledge (variables, methods, loops) + - No prior command-based experience required (but helpful) + +## Project Setup + +.. todo:: + **Creating a New Project:** + - Use WPILib VS Code project creator + - Select "Command Robot (v3)" template + - Project structure overview (Robot.java, RobotContainer.java, etc.) + + **Migrating Existing Project:** + - Point to migration guide for v2 → v3 + - Package imports change: ``org.wpilib.commands3`` not ``commands2`` + - Cannot mix v2 and v3 in same project + +## Setting Up the Scheduler + +.. todo:: + **Robot.java Configuration:** + - Import ``org.wpilib.commands3.Scheduler`` + - Call ``Scheduler.getDefault().run()`` in ``robotPeriodic()`` + - Why this must run every 20ms + - Single-threaded requirement warning + + **Example RLI:** + - Complete Robot.java from a wpilibjExamples project + - Show minimal setup with scheduler call + +## Creating Your First Mechanism + +.. todo:: + **What is a Mechanism:** + - Hardware grouping (motors, sensors, actuators that work together) + - Acts as exclusive resource for commands + - Replaces v2's Subsystem concept + + **Drivetrain Example:** + - Extend ``Mechanism`` base class + - Constructor: initialize hardware + - Private methods for hardware control (``tank()``, ``arcade()``, ``stop()``) + - Public methods for sensor reading (``getDistance()``, ``getHeading()``) + - Setting a default command for idle behavior + + **Example RLI:** + - Simple Drivetrain mechanism from wpilibjExamples + - Show hardware encapsulation pattern + - Default command for stopping motors when idle + +## Writing Your First Command + +.. todo:: + **What is a Command:** + - A command represents an action the robot can perform + - Commands run on the scheduler and can be scheduled, interrupted, or composed + - Commands can require Mechanisms (exclusive access to hardware) + - Commands have a lifecycle: scheduled → running → completed/interrupted + + **Drive For Distance Example:** + - Use ``mechanism.run()`` factory method + - Command body receives ``Coroutine`` parameter + - Sequential steps: reset encoders → loop until target → stop + - **Critical:** ``coroutine.yield()`` inside the loop + - Naming the command with ``.named()`` + + **Understanding yield():** + - Pauses command execution + - Allows scheduler to run other commands + - Command resumes on next cycle + - What happens if you forget it (robot freeze) + + **Example RLI:** + - Drive for distance command + - Drive for time command + - Turn to angle command + +## Scheduling Commands + +.. todo:: + **Manual Scheduling:** + - ``Scheduler.schedule(command)`` + - When to use manual scheduling (autonomous, testing) + + **Button Bindings:** + - Quick preview (detailed in triggers article) + - ``CommandXboxController`` usage + - ``button.onTrue(command)`` pattern + + **Example RLI:** + - RobotContainer with button bindings + - Autonomous command scheduling + +## Testing Your First Command + +.. todo:: + **Using Driver Station:** + - Enable teleop mode + - Trigger command with button + - Observe robot behavior + - Check console output for command status + + **Dashboard Monitoring:** + - Glass/Shuffleboard command widgets + - Viewing running commands + - Command status indicators + +## Next Steps + +.. todo:: + - Link to Mechanisms article for deeper dive + - Link to Commands and Coroutines for full API reference + - Link to Async/Await Patterns for advanced orchestration + - Link to Binding Commands to Triggers for full control setup diff --git a/source/docs/software/commandbased/commands-v3/index.rst b/source/docs/software/commandbased/commands-v3/index.rst new file mode 100644 index 0000000000..e7675b428a --- /dev/null +++ b/source/docs/software/commandbased/commands-v3/index.rst @@ -0,0 +1,111 @@ +# Commands v3 Programming + +.. note:: Commands v3 is currently in development for the 2027 season. This documentation is a work in progress. + +This section serves as an introduction to and reference for the WPILib Commands v3 framework. + +Commands v3 is the next-generation command-based framework for Java that introduces imperative-style command writing using coroutines. Instead of building complex chains of lambda expressions and decorators, you can write command logic as straightforward sequential code with loops, conditionals, and explicit control flow. + +**Java teams are encouraged to alpha test Commands v3 and provide feedback.** Commands v3 is actively being developed with new features including improved telemetry, enhanced trigger functionality, and priority-based interruption. + +.. warning:: + Commands v3 is **Java-only** and does not support C++ or Python. + +.. note:: + **Single-Threaded Requirement**: The Commands v3 scheduler must run on a single thread. Call ``Scheduler.getDefault().run()`` from ``robotPeriodic()`` as usual, but do not use the scheduler from virtual threads or other threads. + +## Should You Use Commands v3? + +**Use Commands v3 if:** + +- You're a Java team +- You want improved telemetry, enhanced triggers, and priority-based interruption +- You prefer imperative control flow (loops, if-statements) over declarative composition +- You're starting fresh or ready to migrate for the 2027 season + +**Stick with Commands v2 if:** + +- You need C++ or Python support +- Your team isn't ready to migrate yet +- You have significant existing v2 code that works well + +.. note:: + Commands v2 will continue to be maintained, but new features and improvements are focused on v3. + +See :ref:`docs/software/commandbased/commands-v2/index:Commands v2 Programming` for the v2 documentation. + +## Documentation Contents + +.. toctree:: + :maxdepth: 1 + + what-is-commands-v3 + getting-started + mechanisms + commands-and-coroutines + async-await-patterns + command-compositions + binding-commands-to-triggers + priorities-and-interrupts + structuring-v3-project + testing-and-simulation + telemetry-and-debugging + troubleshooting + migration-from-v2 + advanced-topics + +## Quick Example + +Here's a simple "drive for distance" command written in Commands v3 style: + +.. code-block:: java + + Command driveTenFeet = drivetrain + .run(coroutine -> { + drivetrain.resetEncoders(); + while (drivetrain.getDistanceMeters() < 3.048) { + drivetrain.tank(0.5, 0.5); + coroutine.yield(); // Let scheduler run other commands + } + drivetrain.stop(); + }) + .named("Drive 10 ft"); + +Compare this to the equivalent v2 style which requires chaining multiple decorators and command groups to achieve the same sequential logic. + +## What's New in v3? + +- **Imperative command bodies**: Write commands as sequential code using ``Coroutine`` objects +- **Mechanisms replace Subsystems**: Similar concept with refined API and naming +- **Command priorities**: Fine-grained interrupt control beyond simple "interrupt or reject" +- **Async/await helpers**: ``await()``, ``awaitAll()``, ``awaitAny()``, ``fork()`` for orchestrating multiple commands +- **Explicit naming**: Commands require names for better debugging and dashboard visibility +- **Cooperative yielding**: Use ``coroutine.yield()`` to pause and let the scheduler run other commands +- **Enhanced telemetry**: Per-instance command tracking with performance metrics + +## Core Concepts + +### Mechanisms + +Mechanisms (like v2 Subsystems) represent robot hardware groupings and act as exclusive resources. Only one command can require a mechanism at a time. See :ref:`docs/software/commandbased/commands-v3/mechanisms:Mechanisms` for details. + +### Coroutines + +Coroutines enable cooperative multitasking. When you write a command body, you receive a ``Coroutine`` object that provides: + +- ``yield()``: Pause and let the scheduler run other commands +- ``await(command)``: Schedule another command and wait for it to finish +- ``wait(time)`` and ``waitUntil(condition)``: Delay or block on conditions +- ``park()``: Pause forever until canceled or interrupted + +See :ref:`docs/software/commandbased/commands-v3/commands-and-coroutines:Commands and Coroutines` for a deep dive. + +### Priorities + +Commands have priority levels. When a new command conflicts with a running command, it only starts if it has equal or higher priority. This provides more control than v2's simple "interrupt or reject" model. See :ref:`docs/software/commandbased/commands-v3/priorities-and-interrupts:Priorities and Interrupts`. + +## Getting Started + +Start with :ref:`docs/software/commandbased/commands-v3/getting-started:Getting Started with Commands v3` for a hands-on introduction. + +If you're migrating from Commands v2, see :ref:`docs/software/commandbased/commands-v3/migration-from-v2:Migrating from Commands v2 to v3`. diff --git a/source/docs/software/commandbased/commands-v3/mechanisms.rst b/source/docs/software/commandbased/commands-v3/mechanisms.rst new file mode 100644 index 0000000000..5170ced83d --- /dev/null +++ b/source/docs/software/commandbased/commands-v3/mechanisms.rst @@ -0,0 +1,72 @@ +# Mechanisms + +.. todo:: + This article provides a comprehensive guide to Mechanisms, the v3 replacement for Subsystems. It explains the philosophy behind Mechanisms, how to create them, best practices for encapsulation, and how they interact with the command system. The focus should be on teaching teams how to properly structure robot hardware abstractions in v3. + +## Creating Mechanisms + +.. todo:: + Describe how to create a Mechanism class. Cover: + - Basic Mechanism class structure and constructor + - When to create a Mechanism vs. other organizational patterns + - Example of something that doesn't need a Mechanism (e.g., a vision system that provides data but doesn't need exclusive access) + - Naming conventions for Mechanism classes + - Where Mechanism classes should live in the project structure + - Note: Mechanisms are automatically registered with the scheduler in the base class constructor + +## Encapsulation Best Practices + +.. todo:: + Explain encapsulation principles for Mechanisms. Cover: + - What hardware and state should be encapsulated within a Mechanism + - Public API design: what methods should be exposed vs. kept private + - How to avoid leaking implementation details + - Sensor data processing and filtering within Mechanisms + - State management and validation + - Examples of good vs. bad encapsulation patterns + +## Default Commands + +.. todo:: + Explain how default commands work with Mechanisms. Cover: + - What default commands are and when to use them + - How to set a default command for a Mechanism + - Lifecycle of default commands (when they start/stop) + - Common use cases (idle states, teleoperated control, etc.) + - How default commands interact with other commands requiring the same Mechanism + - Best practices for implementing default command behavior + +## Periodic Updates + +.. todo:: + Describe periodic update patterns in Mechanisms. Cover: + - Mechanisms don't have a built-in periodic() method + - Manual periodic functions can be plumbed if needed using `Scheduler.addPeriodic()` + - Alternatively, call periodic functions manually in `robotPeriodic()` + - Example patterns for sensor refresh methods + - When to use periodic updates vs. command-based updates + - Performance considerations for periodic operations + - Common patterns like updating telemetry, processing sensor data, safety checks + +## Command Factories + +.. todo:: + Explain the command factory pattern for Mechanisms. Cover: + - What command factories are and why they're useful + - How to create factory methods on Mechanism classes + - Naming conventions for factory methods + - Benefits: encapsulation, reusability, readability + - How factories interact with requirements management + - Examples of simple and complex command factories + - When to use factories vs. standalone command classes + +## Requirements Management + +.. todo:: + Describe how Mechanisms interact with the requirements system. Cover: + - How commands declare they require a Mechanism + - What happens when multiple commands require the same Mechanism + - How the scheduler resolves requirement conflicts + - Relationship between requirements and the priority system + - Best practices for designing Mechanism APIs to work well with requirements + - Common pitfalls and how to avoid them diff --git a/source/docs/software/commandbased/commands-v3/migration-from-v2.rst b/source/docs/software/commandbased/commands-v3/migration-from-v2.rst new file mode 100644 index 0000000000..6cc4103c6c --- /dev/null +++ b/source/docs/software/commandbased/commands-v3/migration-from-v2.rst @@ -0,0 +1,112 @@ +# Migrating from Commands v2 to v3 + +.. todo:: + This article guides teams through migrating an existing Commands v2 codebase to v3. This article should help teams plan their migration strategy, understand the key differences, and avoid common pitfalls. This is a critical resource for established teams. + +## Migration Strategy + +.. todo:: + Provide high-level guidance on planning a v2-to-v3 migration. Cover: + - Should teams migrate? (pros/cons, when to migrate vs. stay on v2) + - Migration approach: full rewrite recommended + - What to migrate first (start with simple mechanisms/commands) + - Testing strategy during migration + - Timeline considerations (offseason vs. competition season) + - Team training and learning curve + - Recommended migration phases + +## Package Changes + +.. todo:: + Document package and import changes between v2 and v3. Cover: + - New v3 package names and locations + - Renamed classes and methods + - Deprecated v2 APIs and their v3 equivalents + - How to install the v3 vendordep + - Version compatibility and requirements + - Note: Vendor library compatibility with v3 is up to individual vendors + +## History: Evolution of Command-Based Programming + +.. todo:: + Provide context on how the command-based framework has evolved. Cover: + - Brief history: v1 (original command-based) → v2 (functional composition) → v3 (coroutines) + - Why each version was created and what problems it solved + - How v3 addresses the learning curve issues with v2's declarative composition + +## Concept Mapping + +.. todo:: + Map v2 concepts to their v3 equivalents. Cover: + - Subsystem → Mechanism (concepts and naming) + - Command classes → Coroutine functions + - CommandBase methods (initialize, execute, end, isFinished) → Coroutine flow + - Command groups → Composition functions and async/await + - Sequential/Parallel/Race groups → v3 equivalents + - Trigger bindings (changes in API) + - Requirements → v3 requirements system + - Default commands → v3 default commands + - Subsystem periodic() → Scheduler.addPeriodic() or manual calls in robotPeriodic() + - What's new in v3 that has no v2 equivalent (priorities, fork, etc.) + - Binary interrupt behavior in v2 → Priority levels in v3 + +## Common Migration Patterns + +.. todo:: + Provide concrete patterns for migrating common v2 code. Cover: + - Converting a simple Subsystem to a Mechanism + - Converting a simple Command to a coroutine command + - Converting a command group to a sequence/composition + - Converting a command group to async/await + - Converting trigger bindings + - Converting autonomous command groups + - Migrating default commands + - Handling periodic() methods from v2 Subsystems + - For each pattern, describe the v2 code structure and the equivalent v3 structure + +## API Differences Reference + +.. todo:: + Provide a quick reference of v2 vs. v3 API differences. Cover: + - Side-by-side comparison of common operations + - Method name changes + - Parameter changes + - Behavior changes (same API, different semantics) + - Removed v2 features and why + - Added v3 features not in v2 + - Present in table or comparison format for quick lookup + +## Telemetry and Debugging Changes + +.. todo:: + Document changes in telemetry and debugging between v2 and v3. Cover: + - New telemetry features in v3 (scheduler events, command lifecycle events) + - Changes in how command state is exposed + - Migration of existing telemetry code + - New debugging capabilities unique to v3 + +## Testing and Simulation Changes + +.. todo:: + Document changes in testing approach between v2 and v3. Cover: + - Differences in unit testing commands + - Mechanisms can accept a Scheduler parameter in constructor to avoid shared state + - Simulation approach differences + - Migration of existing test code + +## Migration Checklist + +.. todo:: + Provide a checklist for teams migrating to v3. Cover: + - Pre-migration: backup code, ensure v2 works, review v3 docs + - Update dependencies and build files + - Convert Subsystems to Mechanisms + - Convert Commands to coroutines + - Update trigger bindings + - Update autonomous routines + - Update RobotContainer + - Update Robot.java + - Test incrementally + - Update telemetry/logging + - Post-migration: cleanup, refactor to use v3 patterns, document changes + - Present as a sequential checklist teams can follow diff --git a/source/docs/software/commandbased/commands-v3/priorities-and-interrupts.rst b/source/docs/software/commandbased/commands-v3/priorities-and-interrupts.rst new file mode 100644 index 0000000000..ef20af9b34 --- /dev/null +++ b/source/docs/software/commandbased/commands-v3/priorities-and-interrupts.rst @@ -0,0 +1,74 @@ +# Priorities and Interrupts + +.. todo:: + This article explains v3's priority system, one of the major new features compared to v2. The priority system provides fine-grained control over when commands can interrupt each other, enabling more sophisticated robot behaviors. Understanding priorities is crucial for teams using v3 effectively. + +## Priority Levels Explained + +.. todo:: + Introduce the concept of command priorities in v3. Cover: + - What priorities are and why they were added in v3 + - Available priority levels (numeric values, named constants) + - Default priority level for commands + - How priorities solve common v2 pain points + - High-level mental model: priorities as "importance" levels + - Relationship to requirements and the scheduler + +## How Priorities Work + +.. todo:: + Explain the mechanics of the priority system. Cover: + - How the scheduler uses priorities to resolve conflicts + - What happens when commands with different priorities require the same Mechanism + - Rules for when a higher-priority command can interrupt a lower-priority one + - What happens when priorities are equal + - The interruptible flag and its interaction with priorities + - How priorities propagate through command compositions and async/await + - Timing: when priority checks occur + +## Setting Command Priorities + +.. todo:: + Explain how to set priorities on commands. Cover: + - Syntax for setting command priority (method chaining, decorators, etc.) + - Where to set priorities: factory methods, binding sites, composition creation + - How to choose appropriate priority levels for different commands + - Making commands non-interruptible regardless of priority + - Dynamic priority adjustment (if supported) + - Best practices for consistent priority assignment across a codebase + +## Common Priority Patterns + +.. todo:: + Showcase common patterns for using priorities effectively. Cover: + - Default/teleoperated commands at low priority + - Autonomous routines at medium priority + - Safety/override commands at high priority + - Emergency stops at maximum priority + - Layered control systems with multiple priority tiers + - Mode-based priority schemes + - Describe several real-world scenarios and recommended priority levels + +## Interruption Behavior + +.. todo:: + Explain what happens when commands are interrupted. Cover: + - Command lifecycle during interruption + - Cleanup and resource release + - How coroutine commands handle interruption (exceptions, early exit) + - Interruption of composed commands (what happens to child commands) + - Interruption of awaited commands (how it propagates to parent) + - Forked commands and interruption + - Best practices for writing interruption-safe commands + +## Debugging Priority Issues + +.. todo:: + Provide guidance on troubleshooting priority-related problems. Cover: + - Common symptoms of priority misconfiguration + - How to diagnose why a command didn't interrupt another + - Tools and techniques for visualizing priority conflicts + - Dashboard/telemetry for monitoring command priorities + - Logging priority-related events + - Common mistakes and how to fix them + - Testing priority behavior diff --git a/source/docs/software/commandbased/commands-v3/structuring-v3-project.rst b/source/docs/software/commandbased/commands-v3/structuring-v3-project.rst new file mode 100644 index 0000000000..783e5b70a0 --- /dev/null +++ b/source/docs/software/commandbased/commands-v3/structuring-v3-project.rst @@ -0,0 +1,65 @@ +# Structuring a Commands v3 Project + +.. todo:: + This article provides guidance on how to organize a robot code project using Commands v3. Good project structure makes code easier to understand, maintain, and test. This article should help teams establish clean patterns early in their v3 adoption. + +## Project Structure Overview + +.. todo:: + Describe the recommended file and package organization for v3 projects. Cover: + - Top-level package structure + - Where Mechanisms should live (mechanisms/ directory with subdirectories per mechanism) + - Where command functions/classes should be organized + - Organization of constants and configuration + - Separation of concerns between different code areas + - Example directory tree: Autos.java, ControllerBindings.java, Main.java, Robot.java, mechanisms/ (with subdirectories per mechanism like drive/ containing DriveConstants.java and Drive.java, elevator/ containing ElevatorConstants.java and Elevator.java) + +## Robot.java and Controller Bindings + +.. todo:: + Explain the organization of Robot.java and controller bindings. Cover: + - Robot.java is the main organization point (not using RobotContainer pattern) + - Mechanism instantiation and initialization in Robot.java + - ControllerBindings.java for organizing button bindings + - Autos.java for autonomous routine organization + - Controller/joystick setup + - Patterns for clean organization without RobotContainer + +## Robot.java Setup + +.. todo:: + Explain the Robot.java class and v3-specific setup. Cover: + - Required v3 initialization in robotInit() + - Periodic methods and what should go in them + - How v3 uses the scheduler in periodic loops + - Autonomous vs. teleop initialization + - Test mode setup for v3 + - What should NOT go in Robot.java (antipatterns) + - Example Robot.java structure for v3 + +## Command Organization Strategies + +.. todo:: + Describe different approaches to organizing command code. Cover: + - Commands as factory methods on Mechanisms + - Commands as standalone functions in command files + - Commands organized by robot function (intake, shooter, etc.) + - Commands organized by autonomous routine + - Reusable command utilities and helpers + - Trade-offs of different organizational approaches + - Recommendations for small vs. large codebases + - Examples of each organizational strategy + +## Constants and Configuration + +.. todo:: + Explain how to organize constants, configuration, and tuning values. Cover: + - Where constants should live (Constants.java, separate config classes, etc.) + - Organizing constants by Mechanism vs. by type + - Physical constants vs. tuning parameters + - Using preferences/network tables for live tuning + - Version control and constants + - Robot-specific vs. shared constants (multiple robots) + - Type safety and units for constants + - Example constants organization patterns + diff --git a/source/docs/software/commandbased/commands-v3/telemetry-and-debugging.rst b/source/docs/software/commandbased/commands-v3/telemetry-and-debugging.rst new file mode 100644 index 0000000000..1cd6867c8f --- /dev/null +++ b/source/docs/software/commandbased/commands-v3/telemetry-and-debugging.rst @@ -0,0 +1,56 @@ +# Telemetry and Debugging + +.. todo:: + This article covers using v3's telemetry features and debugging tools to understand and troubleshoot robot behavior. Good telemetry is essential for rapid iteration during competition. + +## Telemetry Features + +.. todo:: + Overview of telemetry features in v3. Cover: + - Telemetry API and Epilogue compatibility (protobuf serialization) + - Mechanism state visibility + - Scheduler events: Detail the subtypes of `SchedulerEvent` and when they are emitted. Add event listeners to listen for them. + - Command lifecycle events + - Priority and interruption logging + - How telemetry integrates with the scheduler + +## Data Logging and Analysis + +.. todo:: + Explain how v3 telemetry works with data logging and analysis tools. Cover: + - Protobuf serialization for telemetry data + - Integration with AdvantageScope for post-match analysis + - Tracking command lifetimes and triggering events + - Live or post-match analysis workflows + - Publishing Mechanism state to Network Tables + - Best practices for data logging + +## Debugging Techniques + +.. todo:: + Provide techniques for debugging v3 command-based code. Cover: + - Using telemetry data to diagnose issues + - Logging command lifecycle events + - Tracing command execution flow + - Debugging priority conflicts + - Debugging requirement conflicts + - Debugging trigger bindings that don't fire + - Debugging commands that don't end/interrupt properly + - Using simulation for debugging + - Breakpoint debugging in IDEs (only in simulation or unit tests, not on running robots) + - Common debugging patterns and workflows + +## Logging Best Practices + +.. todo:: + Explain best practices for logging in v3 projects. Cover: + - What to log and when to log it + - Logging levels and appropriate usage + - WPILib DataLog integration + - Logging command execution and state transitions + - Logging Mechanism state and sensor readings + - Logging errors and exceptions + - Performance impact of logging + - Log analysis tools and workflows + - Competition-ready logging strategies (what to enable/disable) + - Example logging patterns for commands and mechanisms diff --git a/source/docs/software/commandbased/commands-v3/testing-and-simulation.rst b/source/docs/software/commandbased/commands-v3/testing-and-simulation.rst new file mode 100644 index 0000000000..ef4a92776a --- /dev/null +++ b/source/docs/software/commandbased/commands-v3/testing-and-simulation.rst @@ -0,0 +1,80 @@ +# Testing and Simulation + +.. todo:: + This article covers testing commands and mechanisms using both unit tests and simulation. Testing is crucial for reliable robot code, and v3's design facilitates testing. This article should encourage teams to adopt testing practices and show them how. + +## Why Test Commands + +.. todo:: + Make the case for testing command-based code. Cover: + - Benefits of testing: catch bugs early, enable refactoring, document behavior + - What aspects of command code can/should be tested + - Testing pyramid: unit tests, integration tests, simulation tests + - When to write tests (TDD, after implementation, before competition) + - Realistic expectations for FRC teams regarding testing + +## Unit Testing Commands + +.. todo:: + Explain how to write unit tests for individual commands. Cover: + - Setting up the test environment (scheduler, mocks, etc.) + - How to simulate scheduler cycles in tests + - Testing command initialization and execution logic + - Testing command completion conditions + - Testing interruption behavior + - Mocking Mechanisms and their methods + - Verifying command requirements + - Testing command properties (priority, interruptibility, etc.) + - Example test structure for a simple command (describe test cases, not full code) + +## Integration Testing + +.. todo:: + Explain how to write integration tests for command interactions. Cover: + - What integration tests cover that unit tests don't + - Testing command compositions + - Testing async/await patterns (await, awaitAll, fork, etc.) + - Testing trigger bindings + - Testing priority and interruption behavior between commands + - Testing Mechanism interactions with multiple commands + - Testing default commands + - Example integration test scenarios (describe test cases) + +## Simulation Integration + +.. todo:: + Explain how to use WPILib simulation tools with v3. Cover: + - Overview of WPILib simulation framework + - Setting up simulation for v3 projects + - Simulating Mechanisms and their hardware + - Running commands in simulation + - Using the simulation GUI to test robot behavior + - Physics simulation for mechanisms (drivetrains, arms, elevators, etc.) + - Advantages of simulation testing vs. pure unit tests + - Example simulation test workflow + +## Common Testing Patterns + +.. todo:: + Showcase common patterns and utilities for testing v3 code. Cover: + - Test fixture setup for commands and mechanisms + - Helper functions for advancing the scheduler + - Mock Mechanism base classes or utilities + - Testing commands with time-based logic + - Testing commands with sensor conditions + - Testing error handling and edge cases + - Snapshot testing for complex command sequences + - Performance testing (cycle time, memory usage) + - Describe useful testing utilities teams should build + +## Test Project Structure + +.. todo:: + Describe how to structure test code for v3 projects. Cover: + - Where test files should live relative to main code + - Unit test organization (per-Mechanism, per-command, etc.) + - Integration test organization + - Test utilities and fixtures + - **Mechanism testing**: Mechanisms can accept a `Scheduler` parameter in their constructor to avoid shared state in tests + - CI/CD integration considerations + - Example test directory structure diff --git a/source/docs/software/commandbased/commands-v3/troubleshooting.rst b/source/docs/software/commandbased/commands-v3/troubleshooting.rst new file mode 100644 index 0000000000..06b848c573 --- /dev/null +++ b/source/docs/software/commandbased/commands-v3/troubleshooting.rst @@ -0,0 +1,32 @@ +# Troubleshooting Commands v3 + +.. todo:: + This article covers common mistakes and their fixes when working with Commands v3. This serves as a quick reference for debugging common issues. + +## Common Mistakes and Fixes + +.. todo:: + **Forgetting yield():** + - Symptom: robot freezes, becomes unresponsive + - Fix: add ``coroutine.yield()`` in every loop + + **Using v2 and v3 together:** + - Symptom: import errors, scheduler conflicts + - Fix: choose one framework per project + + **Calling yield() in synchronized blocks:** + - Symptom: exceptions, deadlocks + - Fix: restructure code to avoid locks or use different synchronization + + **Wrong package imports:** + - Symptom: cannot find Mechanism, Coroutine classes + - Fix: use ``org.wpilib.commands3`` not ``commands2`` + +## Debugging Tips + +.. todo:: + Provide general debugging guidance. Cover: + - Using telemetry to track command lifecycle + - Print debugging for command flow + - Common error messages and their meaning + - Using simulation for debugging diff --git a/source/docs/software/commandbased/commands-v3/what-is-commands-v3.rst b/source/docs/software/commandbased/commands-v3/what-is-commands-v3.rst new file mode 100644 index 0000000000..425d996a00 --- /dev/null +++ b/source/docs/software/commandbased/commands-v3/what-is-commands-v3.rst @@ -0,0 +1,96 @@ +# What is Commands v3? + +.. todo:: This article introduces the conceptual foundation of Commands v3, explaining what problem it solves and its core concepts. + +## Introduction + +.. todo:: + - Recap the command-based pattern (commands + mechanisms for resource management) + - Explain the imperative programming style + - How v3 enables writing robot code that looks like simple sequential programs + +## Learning Curve and On-Ramp + +.. todo:: + **Imperative On-Ramp:** + - Commands v3 allows teams to transition from basic imperative code to the command framework + - Simple sequential code can be lifted into commands with minimal changes + - Example: A basic drive-in-a-square routine can be wrapped in command functions + - Changing `Thread.sleep()` to `coroutine.wait()` and direct calls to `coroutine.await()` + - This provides a gentle learning curve for teams new to command-based programming + + **Code Readability:** + - Write robot actions as sequential steps + - Use familiar control flow: loops, if-statements, and function calls + - Easy to add delays, loops, and conditions within command logic + +## Core Concepts + +### Commands as Imperative Functions + +.. todo:: + - Commands in v3 are written as normal sequential functions + - Use loops, if-statements, and control flow naturally + - The ``Coroutine`` object provides pause points via ``yield()`` + - Example: Simple command that reads like pseudocode + +### Coroutines and Cooperative Multitasking + +.. todo:: + - What are coroutines (functions that can pause and resume) + - Cooperative vs preemptive multitasking + - Commands must voluntarily yield control + - The scheduler cannot forcibly suspend commands + +### Mechanisms as Exclusive Resources + +.. todo:: + - Mechanisms represent hardware groupings + - Only one command can require a mechanism at a time + - Automatic resource conflict detection and resolution + +### Command Priorities + +.. todo:: + - Priority levels for controlling command interruption + - Higher priority commands can interrupt lower priority ones + - Enables nuanced control (e.g., LED priority ladder for different robot states) + - Default priorities and when to override them + +## Additional Features + +### Mandatory Command Naming + +.. todo:: + - All commands must have descriptive names + - Improves telemetry and debugging + - Automatic naming for compositions (e.g., "Step 1 -> Step 2 -> Step 3") + +### Enhanced Telemetry + +.. todo:: + - Per-instance command tracking (each execution has unique ID) + - Clear command hierarchy visualization + - Better dashboard integration + +### Inner Trigger Scopes + +.. todo:: + - Triggers defined inside command bodies are scoped to that command's lifetime + - Cleaner code organization + - Example: Temporary button binding during a specific command + +## What v3 Doesn't Do (Non-Goals) + +.. todo:: + - **Not preemptive multitasking**: Commands must yield voluntarily + - **Not multi-threaded**: Single-threaded execution only + - **No unrestricted coroutine usage**: Coroutines only work within command context + - **Cannot replace periodic loops**: Still need periodic methods for continuous updates + +## Next Steps + +.. todo:: + - Link to Getting Started guide + - Link to Migration guide for v2 users + - Link to Mechanisms article for understanding hardware organization diff --git a/source/docs/software/commandbased/index.rst b/source/docs/software/commandbased/index.rst index 97aa5a5ea2..34ebc77bc8 100644 --- a/source/docs/software/commandbased/index.rst +++ b/source/docs/software/commandbased/index.rst @@ -6,5 +6,7 @@ For a collection of example projects using the command-based framework, see :ref .. toctree:: :maxdepth: 1 + :caption: Command-Based Frameworks commands-v2/index + commands-v3/index