Skip to content

Comments

Swerve and PathPlanner#7

Open
JosephTLockwood wants to merge 3 commits intomainfrom
1-Swerve
Open

Swerve and PathPlanner#7
JosephTLockwood wants to merge 3 commits intomainfrom
1-Swerve

Conversation

@JosephTLockwood
Copy link
Collaborator

@JosephTLockwood JosephTLockwood commented Oct 14, 2025

Summary by CodeRabbit

  • New Features

    • Field‑centric swerve drive with controller bindings and a dashboard autonomous chooser.
    • New telemetry visuals and logging for drive pose and module/module-state monitoring.
  • Additions

    • Path planner assets: nav grid, default settings, example path, and vendored pathplanner manifest.
    • Multiple simulation joystick/device profiles.
  • Improvements

    • Safe idle behavior when disabled and automatic path‑planner warmup on startup.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link

coderabbitai bot commented Oct 14, 2025

Walkthrough

Adds PathPlanner assets and vendored manifest, a command-based swerve drivetrain with AutoBuilder, simulation fast-periodic loop and vision hooks, RobotContainer bindings and auto chooser, telemetry publishing, and several static JSON configuration files (navgrid, example path, settings, sim GUI, PathplannerLib manifest).

Changes

Cohort / File(s) Summary
Command-based drivetrain & telemetry
src/main/java/frc/robot/subsystems/CommandSwerveDrivetrain.java, src/main/java/frc/robot/Telemetry.java
Adds CommandSwerveDrivetrain class (multiple constructors, simulation fast-periodic update, AutoBuilder integration, applyRequest command, vision-measurement overrides) and a Telemetry utility that publishes pose/module state to NetworkTables and logs signals.
Robot wiring & controls
src/main/java/frc/robot/RobotContainer.java
Adds public CommandSwerveDrivetrain field, Xbox controller bindings for field-centric velocity control, idle/disabled behavior, PathPlanner auto chooser wired to SmartDashboard, and PathPlanner warmup scheduling.
PathPlanner deployment assets
src/main/deploy/pathplanner/settings.json, src/main/deploy/pathplanner/navgrid.json, src/main/deploy/pathplanner/paths/Example Path.path
Adds planner settings (robot physical/kinematic parameters), a boolean navigation grid layout, and an example path file with waypoints and motion constraints.
Simulation GUI mappings
simgui-ds.json
Adds a SIM GUI device profile with five keyboard/joystick mappings (axis mappings, buttons, optional POV configs).
Vendored dependency manifest
vendordeps/PathplannerLib-2025.2.7.json
Adds PathplannerLib vendored manifest describing Java/C++ dependency versions, metadata, and supported binary platforms.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Driver
  participant Xbox as CommandXboxController
  participant RC as RobotContainer
  participant DT as CommandSwerveDrivetrain
  participant HW as SwerveHardware

  Note over RC,DT: Teleop — field-centric velocity control
  Driver->>Xbox: move sticks / press buttons
  Xbox-->>RC: axis/button inputs
  RC->>DT: applyRequest(Supplier<SwerveRequest>)
  DT->>DT: compute wheel states & feedforwards
  DT->>HW: set module speeds/angles
  HW-->>DT: odometry updates
  DT-->>RC: periodic pose/state (telemetry)
Loading
sequenceDiagram
  autonumber
  participant SD as SmartDashboard
  participant RC as RobotContainer
  participant PP as PathPlanner (AutoBuilder)
  participant DT as CommandSwerveDrivetrain

  Note over RC,PP: Autonomous flow
  RC->>PP: configureAutoBuilder(RobotConfig, controllers, flipByAlliance)
  SD-->>RC: selected auto path
  RC->>PP: request full auto command
  PP->>DT: execute trajectory commands (pose targets, wheel setpoints)
  DT->>DT: apply controls & update odometry
  DT-->>PP: pose feedback
Loading
sequenceDiagram
  autonumber
  participant WPISim as WPILib Simulation
  participant DT as CommandSwerveDrivetrain
  participant Notif as Sim Notifier

  Note over DT: Simulation fast-periodic loop
  WPISim->>DT: init (isSimulation)
  DT->>Notif: start fastPeriodic(Δt)
  loop each tick
    Notif->>DT: fastPeriodic(Δt, batteryVoltage)
    DT-->>DT: update simulated state & odometry
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

  • Focus review on:
    • CommandSwerveDrivetrain.java: constructor correctness, simulation notifier lifecycle, AutoBuilder wiring and alliance flipping, feedforward application, and vision timestamp/std-dev handling.
    • RobotContainer.java: input-to-request supplier mapping, deadbands/scaling, and auto chooser integration.
    • Telemetry.java: NetworkTables keys/array shapes and Mechanism2d usage performance.
    • JSON assets: units, grid orientation, and path constraint values.
    • vendordeps/PathplannerLib-2025.2.7.json: platform entries and artifact specification.

Poem

Hop hop — new paths to tread,
Wheels whirl where waypoints spread.
I tune the grid, I nudge the code,
In sim and field I bound and bode.
Carrot-sprung, I map the road 🥕

Pre-merge checks and finishing touches

❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 57.14% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Title check ❓ Inconclusive The title 'Swerve and PathPlanner' is vague and generic, using broad terms without specifying the nature of the changes (additions, fixes, refactoring, configuration, etc.). Consider a more descriptive title like 'Add swerve drivetrain and PathPlanner integration' or 'Implement CommandSwerveDrivetrain with PathPlanner support' to clearly convey the main changes.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 1-Swerve

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6fa6716 and ceb63da.

📒 Files selected for processing (1)
  • src/main/java/frc/robot/RobotContainer.java (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/java/frc/robot/RobotContainer.java

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (4)
src/main/java/frc/robot/RobotContainer.java (1)

22-26: Style: constants should be final and lowerCamelCase.

Make these fields final and rename to lowerCamelCase for Java style.

Apply this diff:

-  private double MaxSpeed =
+  private final double maxSpeed =
       TunerConstants.kSpeedAt12Volts.in(MetersPerSecond); // kSpeedAt12Volts desired top speed
-  private double MaxAngularRate =
+  private final double maxAngularRate =
       RotationsPerSecond.of(0.75)
           .in(RadiansPerSecond); // 3/4 of a rotation per second max angular velocity

And update usages accordingly.

src/main/deploy/pathplanner/settings.json (1)

7-11: Align speed parameters across code and PathPlanner.

Teleop uses kSpeedAt12Volts = 4.54 m/s, while settings.json has maxDriveSpeed 5.45 m/s (defaultMaxVel 3.0). This mismatch can skew controller scaling and auto tuning.

Pick a single, measured max drive speed and reflect it in:

  • TunerConstants.kSpeedAt12Volts
  • settings.json maxDriveSpeed/defaultMaxVel

Also applies to: 17-18

src/main/java/frc/robot/subsystems/CommandSwerveDrivetrain.java (2)

118-146: Include exception message in error report for easier diagnosis.

Currently only the stack trace is reported. Append ex.getMessage().

Apply this diff:

-    } catch (Exception ex) {
-      DriverStation.reportError(
-          "Failed to load PathPlanner config and configure AutoBuilder", ex.getStackTrace());
-    }
+    } catch (Exception ex) {
+      DriverStation.reportError(
+          "Failed to load PathPlanner config and configure AutoBuilder: " + ex.getMessage(),
+          ex.getStackTrace());
+    }

180-195: Optional: clean up Notifier on shutdown in sim.

Minor: consider stopping/closing m_simNotifier when the program shuts down or when leaving sim to avoid stray threads in long-running sim sessions.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4c08c64 and 06fe017.

⛔ Files ignored due to path filters (1)
  • src/main/java/frc/robot/generated/TunerConstants.java is excluded by !**/generated/**
📒 Files selected for processing (7)
  • simgui-ds.json (1 hunks)
  • src/main/deploy/pathplanner/navgrid.json (1 hunks)
  • src/main/deploy/pathplanner/paths/Example Path.path (1 hunks)
  • src/main/deploy/pathplanner/settings.json (1 hunks)
  • src/main/java/frc/robot/RobotContainer.java (1 hunks)
  • src/main/java/frc/robot/subsystems/CommandSwerveDrivetrain.java (1 hunks)
  • vendordeps/PathplannerLib-2025.2.7.json (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
src/main/java/frc/robot/RobotContainer.java (2)
src/main/java/frc/robot/generated/TunerConstants.java (1)
  • TunerConstants (19-314)
src/main/java/frc/robot/subsystems/CommandSwerveDrivetrain.java (1)
  • CommandSwerveDrivetrain (29-230)
src/main/java/frc/robot/subsystems/CommandSwerveDrivetrain.java (1)
src/main/java/frc/robot/generated/TunerConstants.java (2)
  • TunerConstants (19-314)
  • TunerSwerveDrivetrain (243-313)
🔇 Additional comments (5)
src/main/deploy/pathplanner/navgrid.json (1)

1-1: Nav grid looks fine; please verify field selection/dimensions.

Confirm field_size and nodeSizeMeters match your PathPlanner field in GUI to avoid misaligned planning.

vendordeps/PathplannerLib-2025.2.7.json (1)

1-38: Vendordep manifest LGTM.

Version, URLs, and platforms look correct.

If Gradle fails to resolve, run WPILib “Manage Vendor Libraries” to reimport and regenerate the lockfile.

simgui-ds.json (1)

1-92: Sim DS mappings look good.

Profiles cover common inputs; nothing blocking.

src/main/deploy/pathplanner/paths/Example Path.path (1)

1-54: Example path is valid.

Good starter path; add events when needed.

src/main/java/frc/robot/RobotContainer.java (1)

44-46: Remove null-safety suggestion; Robot.autonomousInit already skips scheduling when getAutonomousCommand() returns null, and there’s no no-arg buildAutoChooser overload to replace.

Likely an incorrect or invalid review comment.

… already, removed by us for simplification purposes)
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (8)
src/main/java/frc/robot/RobotContainer.java (2)

22-26: Consider making speed constants final.

MaxSpeed and MaxAngularRate are computed once from constants and never reassigned. Making them final communicates intent and prevents accidental modification.

-  private double MaxSpeed =
+  private final double MaxSpeed =
       TunerConstants.kSpeedAt12Volts.in(MetersPerSecond); // kSpeedAt12Volts desired top speed
-  private double MaxAngularRate =
+  private final double MaxAngularRate =
       RotationsPerSecond.of(0.75)
           .in(RadiansPerSecond); // 3/4 of a rotation per second max angular velocity

81-84: getSelected() may return null.

If no auto path is selected in the chooser, autoChooser.getSelected() returns null. WPILib's command scheduler handles this gracefully, but you may want to provide a fallback (e.g., Commands.none()) for clarity.

   public Command getAutonomousCommand() {
     /* Run the path selected from the auto chooser */
-    return autoChooser.getSelected();
+    Command selected = autoChooser.getSelected();
+    return selected != null ? selected : Commands.none();
   }
src/main/java/frc/robot/Telemetry.java (3)

30-33: SignalLogger.start() in constructor may conflict with external control.

Starting the SignalLogger unconditionally in the constructor could cause issues if other code expects to control when logging starts/stops, or if multiple Telemetry instances are created. Consider making this configurable or managing the logger lifecycle externally.


60-96: Consider extracting magic numbers as named constants.

The values 0.5 (root position, initial speed length) and 0.1 (direction length) are used repeatedly. Extracting them as named constants would improve readability and maintainability.


134-140: SmartDashboard.putData called repeatedly in loop.

SmartDashboard.putData is called every telemetry cycle for each module. While idempotent, this is slightly inefficient. Consider moving the putData calls to the constructor or an initialization method, since the Mechanism2d objects themselves don't change.

src/main/java/frc/robot/subsystems/CommandSwerveDrivetrain.java (3)

55-117: Constructor initialization is duplicated across all three overloads.

The startSimThread() and configureAutoBuilder() calls are repeated in all three constructors. Consider using constructor chaining or a private initialization method to reduce duplication and ensure consistency.

   public CommandSwerveDrivetrain(
       SwerveDrivetrainConstants drivetrainConstants, SwerveModuleConstants<?, ?, ?>... modules) {
     super(drivetrainConstants, modules);
+    initialize();
+  }
+
+  // ... other constructors call initialize() similarly
+
+  private void initialize() {
     if (Utils.isSimulation()) {
       startSimThread();
     }
     configureAutoBuilder();
   }

133-137: PID constants are hardcoded magic numbers.

The translation PID (10, 0, 0) and rotation PID (7, 0, 0) constants would benefit from being extracted to named constants or documented, making tuning easier to identify and adjust.

+  private static final PIDConstants TRANSLATION_PID = new PIDConstants(10, 0, 0);
+  private static final PIDConstants ROTATION_PID = new PIDConstants(7, 0, 0);
+
   // In configureAutoBuilder:
           new PPHolonomicDriveController(
-              // PID constants for translation
-              new PIDConstants(10, 0, 0),
-              // PID constants for rotation
-              new PIDConstants(7, 0, 0)),
+              TRANSLATION_PID,
+              ROTATION_PID),

181-196: Simulation notifier resource is not explicitly managed.

The m_simNotifier is created but never closed. While typically acceptable in FRC (robot runs until power-off), consider implementing close() from AutoCloseable if this subsystem might be recreated during testing.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 06fe017 and 6fa6716.

📒 Files selected for processing (3)
  • src/main/java/frc/robot/RobotContainer.java (1 hunks)
  • src/main/java/frc/robot/Telemetry.java (1 hunks)
  • src/main/java/frc/robot/subsystems/CommandSwerveDrivetrain.java (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
src/main/java/frc/robot/RobotContainer.java (2)
src/main/java/frc/robot/generated/TunerConstants.java (1)
  • TunerConstants (19-314)
src/main/java/frc/robot/subsystems/CommandSwerveDrivetrain.java (1)
  • CommandSwerveDrivetrain (30-231)
src/main/java/frc/robot/subsystems/CommandSwerveDrivetrain.java (1)
src/main/java/frc/robot/generated/TunerConstants.java (2)
  • TunerConstants (19-314)
  • TunerSwerveDrivetrain (243-313)
🔇 Additional comments (6)
src/main/java/frc/robot/RobotContainer.java (2)

45-53: LGTM! Constructor setup is well-structured.

The auto chooser initialization with SmartDashboard integration and PathPlanner warmup command scheduling are appropriate. The warmup helps avoid Java JIT pauses during autonomous.


55-79: LGTM! Drive bindings follow WPILib conventions correctly.

The axis negations for joystick input follow WPILib's coordinate system convention. The idle state with ignoringDisable(true) ensures neutral mode is applied to drive motors while disabled, which is good practice for safety.

src/main/java/frc/robot/Telemetry.java (1)

35-58: LGTM! NetworkTable publishers are well-organized.

Using struct publishers for WPILib types is efficient and provides proper serialization. The separation between DriveState and Pose tables is clear.

src/main/java/frc/robot/subsystems/CommandSwerveDrivetrain.java (3)

155-157: LGTM! Clean command factory pattern.

The applyRequest method provides a clean interface for applying swerve requests as commands, properly binding to this subsystem.


159-179: LGTM! Operator perspective handling is well-designed.

The logic correctly handles applying operator perspective on first run or when disabled, allowing mid-match corrections without affecting driving behavior during enabled states. The ifPresent pattern safely handles the case when alliance info isn't yet available.


205-230: LGTM! Vision measurement overrides correctly handle timestamp conversion.

The Utils.fpgaToCurrentTime() conversion ensures proper timestamp handling for the Kalman filter. Both overloads are well-documented and properly delegate to the parent class.

Comment on lines +143 to +146
} catch (Exception ex) {
DriverStation.reportError(
"Failed to load PathPlanner config and configure AutoBuilder", ex.getStackTrace());
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Silent failure if PathPlanner config fails to load.

If RobotConfig.fromGUISettings() throws, the error is logged but AutoBuilder remains unconfigured. Autonomous commands will fail silently. Consider adding a state flag or more prominent warning (e.g., in periodic()) to alert operators.

🤖 Prompt for AI Agents
In src/main/java/frc/robot/subsystems/CommandSwerveDrivetrain.java around lines
143-146, the catch for RobotConfig.fromGUISettings() only logs the exception
causing AutoBuilder to remain unconfigured and leading to silent autonomous
failures; add a boolean field (e.g., autoBuilderConfigured) initialized to true,
set it to false inside the catch, and ensure any code that uses AutoBuilder
checks this flag before scheduling autonomous routines; also surface the problem
to operators by reporting a persistent warning (DriverStation.reportWarning or
SmartDashboard putBoolean/putString) in periodic() when autoBuilderConfigured is
false so the issue is obvious on the driver station.

driveModuleTargets.set(state.ModuleTargets);
driveModulePositions.set(state.ModulePositions);
driveTimestamp.set(state.Timestamp);
driveOdometryFrequency.set(1.0 / state.OdometryPeriod);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Potential division by zero if OdometryPeriod is zero.

If state.OdometryPeriod is zero (e.g., during initialization or error conditions), this will result in infinity or NaN being published.

-    driveOdometryFrequency.set(1.0 / state.OdometryPeriod);
+    driveOdometryFrequency.set(state.OdometryPeriod > 0 ? 1.0 / state.OdometryPeriod : 0);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
driveOdometryFrequency.set(1.0 / state.OdometryPeriod);
driveOdometryFrequency.set(state.OdometryPeriod > 0 ? 1.0 / state.OdometryPeriod : 0);
🤖 Prompt for AI Agents
In src/main/java/frc/robot/Telemetry.java around line 111, the code divides by
state.OdometryPeriod which can be zero; change to guard against zero/negative by
checking OdometryPeriod first (use an epsilon like 1e-9), and only compute 1.0 /
OdometryPeriod when it is > epsilon; otherwise set driveOdometryFrequency to a
safe default (e.g., 0.0) or skip publishing and optionally log a warning so you
never publish Infinity/NaN.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants